language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
C++ | wireshark/ui/qt/widgets/detachable_tabwidget.cpp | /* @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/detachable_tabwidget.h>
#include <QStackedWidget>
#include <QBoxLayout>
#include <QEvent>
#include <QCloseEvent>
#include <QMouseEvent>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QMimeData>
#include <QStringList>
#include <QApplication>
#include <QDrag>
#include <QPixmap>
#include <QPainter>
DetachableTabWidget::DetachableTabWidget(QWidget *parent) :
QTabWidget(parent)
{
DragDropTabBar * tabBar = new DragDropTabBar(this);
connect(tabBar, &DragDropTabBar::onDetachTab, this, &DetachableTabWidget::detachTab);
connect(tabBar, &DragDropTabBar::onMoveTab, this, &DetachableTabWidget::moveTab);
setMovable(false);
setTabBar(tabBar);
}
void DetachableTabWidget::setTabBasename(QString newName) {
_tabBasename = newName;
}
QString DetachableTabWidget::tabBasename() const {
return _tabBasename;
}
void DetachableTabWidget::moveTab(int from, int to)
{
QWidget * contentWidget = widget(from);
QString text = tabText(from);
removeTab(from);
insertTab(to, contentWidget, text);
setCurrentIndex(to);
}
void DetachableTabWidget::detachTab(int tabIdx, QPoint pos)
{
QString name = tabText(tabIdx);
QWidget * contentWidget = widget(tabIdx);
/* For the widget to properly show in the dialog, it has to be
* removed properly and unhidden. QTabWidget uses a QStackedWidget for
* all parents of widgets. So we remove it from it's own parent and then
* unhide it to show the widget in the dialog */
QStackedWidget * par = qobject_cast<QStackedWidget *>(contentWidget->parent());
if (!par)
return;
QRect contentWidgetRect = par->frameGeometry();
par->removeWidget(contentWidget);
contentWidget->setHidden(false);
ToolDialog * detachedTab = new ToolDialog(contentWidget, parentWidget());
detachedTab->setWindowModality(Qt::NonModal);
detachedTab->setWindowTitle(_tabBasename + ": " + name);
detachedTab->setObjectName(name);
detachedTab->setGeometry(contentWidgetRect);
connect(detachedTab, &ToolDialog::onCloseSignal, this, &DetachableTabWidget::attachTab);
detachedTab->move(pos);
detachedTab->show();
}
void DetachableTabWidget::attachTab(QWidget * content, QString name)
{
content->setParent(this);
int index = addTab(content, name);
if (index > -1)
setCurrentIndex(index);
}
ToolDialog::ToolDialog(QWidget *contentWidget, QWidget *parent, Qt::WindowFlags f) :
QDialog(parent, f)
{
_contentWidget = contentWidget;
_contentWidget->setParent(this);
QVBoxLayout * layout = new QVBoxLayout(this);
layout->addWidget(_contentWidget);
this->setLayout(layout);
}
bool ToolDialog::event(QEvent *event)
{
/**
* Capture a double click event on the dialog's window frame
*/
if (event->type() == QEvent::NonClientAreaMouseButtonDblClick) {
event->accept();
close();
}
return QDialog::event(event);
}
void ToolDialog::closeEvent(QCloseEvent * /*event*/)
{
emit onCloseSignal(_contentWidget, objectName());
}
DragDropTabBar::DragDropTabBar(QWidget *parent) :
QTabBar(parent)
{
setAcceptDrops(true);
setElideMode(Qt::ElideRight);
setSelectionBehaviorOnRemove(QTabBar::SelectLeftTab);
_dragStartPos = QPoint();
_dragDropPos = QPoint();
_mouseCursor = QCursor();
_dragInitiated = false;
}
void DragDropTabBar::mouseDoubleClickEvent(QMouseEvent *event)
{
event->accept();
emit onDetachTab(tabAt(event->pos()), _mouseCursor.pos());
}
void DragDropTabBar::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
_dragStartPos = event->pos();
_dragDropPos = QPoint(0, 0);
_dragInitiated = false;
QTabBar::mousePressEvent(event);
}
void DragDropTabBar::mouseMoveEvent(QMouseEvent *event)
{
if (!_dragStartPos.isNull() &&
((event->pos() - _dragStartPos).manhattanLength() > QApplication::startDragDistance()))
_dragInitiated = true;
if ((event->buttons() & Qt::LeftButton) && _dragInitiated) {
QMouseEvent * finishMouseMove = new QMouseEvent(QEvent::MouseMove, event->pos(), QCursor::pos(), Qt::NoButton, Qt::NoButton, Qt::NoModifier);
QTabBar::mouseMoveEvent(finishMouseMove);
QDrag * drag = new QDrag(this);
QMimeData * mimeData = new QMimeData();
mimeData->setData("action", "application/tab-detach");
drag->setMimeData(mimeData);
QWidget * original = parentWidget();
if (qobject_cast<DetachableTabWidget *>(original)) {
DetachableTabWidget * tabWidget = qobject_cast<DetachableTabWidget *>(original);
original = tabWidget->widget(tabWidget->currentIndex());
}
QPixmap pixmap = original->grab();
QPixmap targetPixmap = QPixmap(pixmap.size());
targetPixmap.fill(Qt::transparent);
QPainter painter(&targetPixmap);
painter.setOpacity(0.85);
painter.drawPixmap(0, 0, pixmap);
painter.end();
drag->setPixmap(targetPixmap);
Qt::DropAction dropAction = drag->exec(Qt::MoveAction | Qt::CopyAction);
if (dropAction == Qt::IgnoreAction) {
event->accept();
emit onDetachTab(tabAt(_dragStartPos), _mouseCursor.pos());
} if (dropAction == Qt::MoveAction) {
if (! _dragDropPos.isNull()) {
event->accept();
emit onMoveTab(tabAt(_dragStartPos), tabAt(_dragDropPos));
}
}
} else
QTabBar::mouseMoveEvent(event);
}
void DragDropTabBar::dragEnterEvent(QDragEnterEvent *event)
{
const QMimeData * mimeData = event->mimeData();
QStringList formats = mimeData->formats();
if (formats.contains("action") && mimeData->data("action") == "application/tab-detach")
event->acceptProposedAction();
}
void DragDropTabBar::dropEvent(QDropEvent *event)
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
_dragDropPos = event->position().toPoint();
#else
_dragDropPos = event->pos();
#endif
QTabBar::dropEvent(event);
} |
C/C++ | wireshark/ui/qt/widgets/detachable_tabwidget.h | /* @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef DETACHABLE_TABWIDGET_H
#define DETACHABLE_TABWIDGET_H
#include <wireshark.h>
#include <QTabWidget>
#include <QDialog>
#include <QEvent>
#include <QCloseEvent>
#include <QTabBar>
#include <QPoint>
#include <QCursor>
class DetachableTabWidget : public QTabWidget
{
Q_OBJECT
public:
DetachableTabWidget(QWidget * parent = nullptr);
QString tabBasename() const;
protected:
void setTabBasename(QString newName);
protected slots:
virtual void moveTab(int from, int to);
virtual void detachTab(int tabIdx, QPoint pos);
virtual void attachTab(QWidget * content, QString name);
private:
QString _tabBasename;
};
class ToolDialog : public QDialog
{
Q_OBJECT
public:
explicit ToolDialog(QWidget * _contentWidget, QWidget * parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags());
protected:
virtual bool event(QEvent *event);
virtual void closeEvent(QCloseEvent *event);
signals:
void onCloseSignal(QWidget * contentWidget, QString name);
private:
QWidget * _contentWidget;
};
class DragDropTabBar : public QTabBar
{
Q_OBJECT
public:
explicit DragDropTabBar(QWidget * parent);
signals:
void onDetachTab(int tabIdx, QPoint pos);
void onMoveTab(int oldIdx, int newIdx);
protected:
virtual void mouseDoubleClickEvent(QMouseEvent *event);
virtual void mousePressEvent(QMouseEvent *event);
virtual void mouseMoveEvent(QMouseEvent *event);
virtual void dragEnterEvent(QDragEnterEvent *event);
virtual void dropEvent(QDropEvent *event);
private:
QPoint _dragStartPos;
QPoint _dragDropPos;
QCursor _mouseCursor;
bool _dragInitiated;
};
#endif // DETACHABLE_TABWIDGET_H |
C++ | wireshark/ui/qt/widgets/display_filter_combo.cpp | /* display_filter_combo.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <stdio.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "ui/recent_utils.h"
#include "ui/recent.h"
#include <epan/prefs.h>
#include <QHelpEvent>
#include <QStyleOptionComboBox>
#include <QStandardItemModel>
#include <QDateTime>
#include <ui/qt/widgets/display_filter_edit.h>
#include <ui/qt/widgets/display_filter_combo.h>
#include <ui/qt/utils/color_utils.h>
#include "main_application.h"
// If we ever add support for multiple windows this will need to be replaced.
static DisplayFilterCombo *cur_display_filter_combo = NULL;
DisplayFilterCombo::DisplayFilterCombo(QWidget *parent) :
QComboBox(parent)
{
setEditable(true);
setLineEdit(new DisplayFilterEdit(this, DisplayFilterToApply));
// setLineEdit will create a new QCompleter that performs inline completion,
// be sure to disable that since our DisplayFilterEdit performs its own
// popup completion. As QLineEdit's completer is designed for full line
// completion, we cannot reuse it for word completion.
setCompleter(0);
// When the combobox menu is not entirely populated, pressing Enter would
// normally append entries to the end. However, before doing so it moves the
// cursor position to the end of the field which breaks the completer.
// Therefore disable this and rely on dfilter_combo_add_recent being called.
setInsertPolicy(QComboBox::NoInsert);
// Default is Preferred.
setSizePolicy(QSizePolicy::MinimumExpanding, sizePolicy().verticalPolicy());
setAccessibleName(tr("Display filter selector"));
cur_display_filter_combo = this;
updateStyleSheet();
setToolTip(tr("Select from previously used filters."));
QStandardItemModel *model = qobject_cast<QStandardItemModel*>(this->model());
model->setSortRole(Qt::UserRole);
connect(mainApp, &MainApplication::preferencesChanged, this, &DisplayFilterCombo::updateMaxCount);
// Ugly cast required (?)
// https://stackoverflow.com/questions/16794695/connecting-overloaded-signals-and-slots-in-qt-5
connect(this, static_cast<void (DisplayFilterCombo::*)(int)>(&DisplayFilterCombo::activated), this, &DisplayFilterCombo::onActivated);
}
extern "C" void dfilter_recent_combo_write_all(FILE *rf) {
if (!cur_display_filter_combo)
return;
cur_display_filter_combo->writeRecent(rf);
}
void DisplayFilterCombo::writeRecent(FILE *rf) {
int i;
for (i = 0; i < count(); i++) {
const QByteArray& filter = itemText(i).toUtf8();
if (!filter.isEmpty()) {
fprintf(rf, RECENT_KEY_DISPLAY_FILTER ": %s\n", filter.constData());
}
}
}
void DisplayFilterCombo::onActivated(int row)
{
/* Update the row timestamp and resort list. */
QStandardItemModel *m = qobject_cast<QStandardItemModel*>(this->model());
QModelIndex idx = m->index(row, 0);
m->setData(idx, QVariant(QDateTime::currentMSecsSinceEpoch()), Qt::UserRole);
m->sort(0, Qt::DescendingOrder);
}
bool DisplayFilterCombo::event(QEvent *event)
{
switch (event->type()) {
case QEvent::ToolTip:
{
// Only show a tooltip for the arrow.
QHelpEvent *he = (QHelpEvent *) event;
QStyleOptionComboBox opt;
initStyleOption(&opt);
QRect scr = style()->subControlRect(QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxArrow, this);
if (!scr.contains(he->pos())) {
return false;
}
break;
}
case QEvent::ApplicationPaletteChange:
updateStyleSheet();
break;
default:
break;
}
return QComboBox::event(event);
}
void DisplayFilterCombo::updateStyleSheet()
{
const char *display_mode = ColorUtils::themeIsDark() ? "dark" : "light";
QString ss = QString(
"QComboBox {"
#ifdef Q_OS_MAC
" border: 1px solid gray;"
#else
" border: 1px solid palette(shadow);"
#endif
" border-radius: 3px;"
" padding: 0px 0px 0px 0px;"
" margin-left: 0px;"
" min-width: 20em;"
" }"
"QComboBox::drop-down {"
" subcontrol-origin: padding;"
" subcontrol-position: top right;"
" width: 14px;"
" border-left-width: 0px;"
" }"
"QComboBox::down-arrow {"
" image: url(:/stock_icons/14x14/x-filter-dropdown.%1.png);"
" }"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */"
" top: 1px;"
" left: 1px;"
"}"
).arg(display_mode);
setStyleSheet(ss);
}
bool DisplayFilterCombo::checkDisplayFilter()
{
DisplayFilterEdit *df_edit = qobject_cast<DisplayFilterEdit *>(lineEdit());
bool state = false;
if (df_edit) state = df_edit->checkFilter();
return state;
}
void DisplayFilterCombo::applyDisplayFilter()
{
DisplayFilterEdit *df_edit = qobject_cast<DisplayFilterEdit *>(lineEdit());
if (df_edit) df_edit->applyDisplayFilter();
}
void DisplayFilterCombo::setDisplayFilter(QString filter)
{
lineEdit()->setText(filter);
lineEdit()->setFocus();
}
void DisplayFilterCombo::updateMaxCount()
{
setMaxCount(prefs.gui_recent_df_entries_max);
}
extern "C" gboolean dfilter_combo_add_recent(const gchar *filter) {
if (!cur_display_filter_combo)
return FALSE;
// Adding an item to a QComboBox also sets its lineEdit. In our case
// that means we might trigger a temporary status message so we block
// the lineEdit's signals.
// Another approach would be to update QComboBox->model directly.
bool block_state = cur_display_filter_combo->lineEdit()->blockSignals(true);
cur_display_filter_combo->addItem(filter, QVariant(QDateTime::currentMSecsSinceEpoch()));
cur_display_filter_combo->clearEditText();
cur_display_filter_combo->lineEdit()->blockSignals(block_state);
return TRUE;
} |
C/C++ | wireshark/ui/qt/widgets/display_filter_combo.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef DISPLAY_FILTER_COMBO_H
#define DISPLAY_FILTER_COMBO_H
#include <QComboBox>
#include <QList>
class DisplayFilterCombo : public QComboBox
{
Q_OBJECT
public:
explicit DisplayFilterCombo(QWidget *parent = 0);
bool addRecentCapture(const char *filter);
void writeRecent(FILE *rf);
protected:
virtual bool event(QEvent *event);
private:
void updateStyleSheet();
public slots:
bool checkDisplayFilter();
void applyDisplayFilter();
void setDisplayFilter(QString filter);
private slots:
void updateMaxCount();
void onActivated(int index);
};
#endif // DISPLAY_FILTER_COMBO_H |
C++ | wireshark/ui/qt/widgets/display_filter_edit.cpp | /* display_filter_edit.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <glib.h>
#include <epan/dfilter/dfilter.h>
#include <ui/recent.h>
#include <wsutil/utf8_entities.h>
#include "main_application.h"
#include <ui/qt/widgets/display_filter_edit.h>
#include "filter_dialog.h"
#include <ui/qt/widgets/stock_icon_tool_button.h>
#include <ui/qt/widgets/syntax_line_edit.h>
#include <ui/qt/utils/wireshark_mime_data.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/models/pref_models.h>
#include <ui/qt/filter_action.h>
#include <ui/qt/display_filter_expression_dialog.h>
#include <ui/qt/main_window.h>
#include <QAction>
#include <QAbstractItemView>
#include <QComboBox>
#include <QCompleter>
#include <QMenu>
#include <QMessageBox>
#include <QPainter>
#include <QStringListModel>
#include <QWidget>
#include <QObject>
#include <QDrag>
#include <QDropEvent>
#include <QMimeData>
#include <QJsonDocument>
#include <QJsonObject>
// To do:
// - Get rid of shortcuts and replace them with "n most recently applied filters"?
// - We need simplified (button- and dropdown-free) versions for use in dialogs and field-only checking.
// - Add a separator or otherwise distinguish between recent items and fields
// in the completion dropdown.
#ifdef __APPLE__
#define DEFAULT_MODIFIER UTF8_PLACE_OF_INTEREST_SIGN
#else
#define DEFAULT_MODIFIER "Ctrl-"
#endif
// proto.c:fld_abbrev_chars
static const QString fld_abbrev_chars_ = "-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
DisplayFilterEdit::DisplayFilterEdit(QWidget *parent, DisplayFilterEditType type) :
SyntaxLineEdit(parent),
type_(type),
save_action_(NULL),
remove_action_(NULL),
actions_(Q_NULLPTR),
bookmark_button_(NULL),
clear_button_(NULL),
apply_button_(NULL),
leftAlignActions_(false),
last_applied_(QString()),
filter_word_preamble_(QString()),
autocomplete_accepts_field_(true)
{
setAccessibleName(tr("Display filter entry"));
completion_model_ = new QStringListModel(this);
setCompleter(new QCompleter(completion_model_, this));
setCompletionTokenChars(fld_abbrev_chars_);
QString buttonStyle = QString(
"QToolButton {"
" border: none;"
" background: transparent;" // Disables platform style on Windows.
" padding: 0 0 0 0;"
"}"
"QToolButton::menu-indicator {"
" image: none;"
"}"
);
leftAlignActions_ = recent.gui_geometry_leftalign_actions;
if (type_ == DisplayFilterToApply) {
bookmark_button_ = new StockIconToolButton(this, "x-display-filter-bookmark");
bookmark_button_->setMenu(new QMenu(bookmark_button_));
bookmark_button_->setPopupMode(QToolButton::InstantPopup);
bookmark_button_->setToolTip(tr("Manage saved bookmarks."));
bookmark_button_->setIconSize(QSize(14, 14));
bookmark_button_->setStyleSheet(buttonStyle);
bookmark_button_->setVisible(false);
clear_button_ = new StockIconToolButton(this, "x-filter-clear");
clear_button_->setToolTip(tr("Clear display filter"));
clear_button_->setIconSize(QSize(14, 14));
clear_button_->setStyleSheet(buttonStyle);
clear_button_->setVisible(false);
apply_button_ = new StockIconToolButton(this, "x-filter-apply");
apply_button_->setEnabled(false);
apply_button_->setToolTip(tr("Apply display filter"));
apply_button_->setIconSize(QSize(24, 14));
apply_button_->setStyleSheet(buttonStyle);
apply_button_->setVisible(false);
connect(clear_button_, &StockIconToolButton::clicked, this, &DisplayFilterEdit::clearFilter);
connect(apply_button_, &StockIconToolButton::clicked, this, &DisplayFilterEdit::applyDisplayFilter);
connect(this, &DisplayFilterEdit::returnPressed, this, &DisplayFilterEdit::applyDisplayFilter);
}
connect(this, &DisplayFilterEdit::textChanged, this,
static_cast<void (DisplayFilterEdit::*)(const QString &)>(&DisplayFilterEdit::checkFilter));
connect(mainApp, &MainApplication::appInitialized, this, &DisplayFilterEdit::updateBookmarkMenu);
connect(mainApp, &MainApplication::displayFilterListChanged, this, &DisplayFilterEdit::updateBookmarkMenu);
connect(mainApp, &MainApplication::preferencesChanged, this, [=](){ checkFilter(); });
connect(mainApp, &MainApplication::appInitialized, this, &DisplayFilterEdit::connectToMainWindow);
}
void DisplayFilterEdit::connectToMainWindow()
{
connect(this, &DisplayFilterEdit::filterPackets, qobject_cast<MainWindow *>(mainApp->mainWindow()),
&MainWindow::filterPackets);
connect(this, &DisplayFilterEdit::showPreferencesDialog,
qobject_cast<MainWindow *>(mainApp->mainWindow()), &MainWindow::showPreferencesDialog);
connect(qobject_cast<MainWindow *>(mainApp->mainWindow()), &MainWindow::displayFilterSuccess,
this, &DisplayFilterEdit::displayFilterSuccess);
}
void DisplayFilterEdit::contextMenuEvent(QContextMenuEvent *event) {
QMenu *menu = this->createStandardContextMenu();
menu->setAttribute(Qt::WA_DeleteOnClose);
if (menu->actions().count() <= 0) {
menu->deleteLater();
return;
}
QAction * first = menu->actions().at(0);
QAction * na = new QAction(tr("Left align buttons"), this);
na->setCheckable(true);
na->setChecked(leftAlignActions_);
connect(na, &QAction::triggered, this, &DisplayFilterEdit::triggerAlignementAction);
menu->addSeparator();
menu->addAction(na);
na = new QAction(tr("Display Filter Expression…"), this);
connect(na, &QAction::triggered, this, &DisplayFilterEdit::displayFilterExpression);
menu->insertAction(first, na);
menu->insertSeparator(first);
menu->popup(event->globalPos());
}
void DisplayFilterEdit::triggerAlignementAction()
{
leftAlignActions_ = ! leftAlignActions_;
if (qobject_cast<QAction *>(sender()))
qobject_cast<QAction *>(sender())->setChecked(leftAlignActions_);
recent.gui_geometry_leftalign_actions = leftAlignActions_;
write_recent();
alignActionButtons();
}
void DisplayFilterEdit::alignActionButtons()
{
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
QSize bksz, cbsz, apsz;
bksz = apsz = cbsz = QSize(0, 0);
if (type_ == DisplayFilterToApply) {
bookmark_button_->setMinimumHeight(contentsRect().height());
bookmark_button_->setMaximumHeight(contentsRect().height());
bksz = bookmark_button_->sizeHint();
apsz = apply_button_->sizeHint();
apply_button_->setMinimumHeight(contentsRect().height());
apply_button_->setMaximumHeight(contentsRect().height());
if (clear_button_->isVisible())
{
cbsz = clear_button_->sizeHint();
clear_button_->setMinimumHeight(contentsRect().height());
clear_button_->setMaximumHeight(contentsRect().height());
}
}
int leftPadding = frameWidth + 1;
int leftMargin = bksz.width();
int rightMargin = cbsz.width() + apsz.width() + frameWidth + 2;
if (leftAlignActions_)
{
leftMargin = rightMargin + bksz.width() - 2;
rightMargin = 0;
}
setStyleSheet(QString(
"DisplayFilterEdit {"
" padding-left: %1px;"
" margin-left: %2px;"
" margin-right: %3px;"
"}"
)
.arg(leftPadding)
.arg(leftMargin)
.arg(rightMargin)
);
if (apply_button_) {
if (! leftAlignActions_)
{
apply_button_->move(contentsRect().right() - frameWidth - apsz.width(),
contentsRect().top());
} else {
apply_button_->move(contentsRect().left() + bookmark_button_->width(), contentsRect().top());
}
}
if (clear_button_ && apply_button_) {
if (! leftAlignActions_)
{
clear_button_->move(contentsRect().right() - frameWidth - cbsz.width() - apsz.width(),
contentsRect().top());
} else {
int width = bookmark_button_->width() + apply_button_->width();
clear_button_->move(contentsRect().left() + width, contentsRect().top());
}
}
update();
}
void DisplayFilterEdit::setDefaultPlaceholderText()
{
switch (type_) {
case DisplayFilterToApply:
placeholder_text_ = QString(tr("Apply a display filter %1 <%2/>")).arg(UTF8_HORIZONTAL_ELLIPSIS)
.arg(DEFAULT_MODIFIER);
break;
case DisplayFilterToEnter:
placeholder_text_ = QString(tr("Enter a display filter %1")).arg(UTF8_HORIZONTAL_ELLIPSIS);
break;
case ReadFilterToApply:
placeholder_text_ = QString(tr("Apply a read filter %1")).arg(UTF8_HORIZONTAL_ELLIPSIS);
break;
}
setPlaceholderText(placeholder_text_);
}
void DisplayFilterEdit::paintEvent(QPaintEvent *evt) {
SyntaxLineEdit::paintEvent(evt);
if (bookmark_button_ && isEnabled()) {
if (! bookmark_button_->isVisible())
{
bookmark_button_->setVisible(true);
apply_button_->setVisible(true);
setDefaultPlaceholderText();
alignActionButtons();
return;
}
// Draw the borders by hand. We could try to do this in the
// style sheet but it's a pain.
#ifdef Q_OS_MAC
QColor divider_color = Qt::gray;
#else
QColor divider_color = palette().shadow().color();
#endif
QPainter painter(this);
painter.setPen(divider_color);
QRect cr = contentsRect();
int left_xpos = 0;
int right_xpos = 0;
if (leftAlignActions_)
{
left_xpos = 1 + bookmark_button_->width();
if (clear_button_->isVisible())
left_xpos += clear_button_->width();
if (apply_button_->isVisible())
left_xpos += apply_button_->width();
right_xpos = cr.width() - 1;
}
else
{
left_xpos = bookmark_button_->width();
right_xpos = cr.width() - 4;
if (clear_button_->isVisible())
right_xpos -= clear_button_->width();
if (apply_button_->isVisible())
right_xpos -= apply_button_->width();
}
painter.drawLine(left_xpos, cr.top(), left_xpos, cr.bottom() + 1);
if (!text().isEmpty())
painter.drawLine(right_xpos, cr.top(), right_xpos, cr.bottom() + 1);
}
}
void DisplayFilterEdit::resizeEvent(QResizeEvent *)
{
alignActionButtons();
}
void DisplayFilterEdit::focusOutEvent(QFocusEvent *event)
{
if (syntaxState() == Valid) {
emit popFilterSyntaxStatus();
setToolTip(QString());
}
SyntaxLineEdit::focusOutEvent(event);
}
bool DisplayFilterEdit::checkFilter()
{
checkFilter(text());
return syntaxState() != Invalid;
}
void DisplayFilterEdit::checkFilter(const QString& filter_text)
{
if (text().length() == 0 && actions_ && actions_->checkedAction())
actions_->checkedAction()->setChecked(false);
if (clear_button_) {
if (filter_text.length() > 0)
clear_button_->setVisible(true);
else if (last_applied_.length() > 0)
setPlaceholderText(tr("Current filter: %1").arg(last_applied_));
else if (filter_text.length() <= 0 && last_applied_.length() <= 0)
clear_button_->setVisible(false);
alignActionButtons();
}
if ((filter_text.length() <= 0) && mainApp->mainWindow()->isActiveWindow())
mainApp->popStatus(MainApplication::FilterSyntax);
emit popFilterSyntaxStatus();
if (!checkDisplayFilter(filter_text))
return;
switch (syntaxState()) {
case Deprecated:
{
if (mainApp->mainWindow()->isActiveWindow())
mainApp->pushStatus(MainApplication::FilterSyntax, syntaxErrorMessage());
setToolTip(syntaxErrorMessage());
break;
}
case Invalid:
{
QString invalidMsg = tr("Invalid filter: ").append(syntaxErrorMessage());
if (mainApp->mainWindow()->isActiveWindow())
mainApp->pushStatus(MainApplication::FilterSyntax, syntaxErrorMessage());
setToolTip(invalidMsg);
break;
}
default:
setToolTip(QString());
break;
}
if (bookmark_button_) {
bookmark_button_->setStockIcon("x-display-filter-bookmark");
if (remove_action_ && save_action_)
{
remove_action_->setEnabled(false);
save_action_->setEnabled(false);
}
if (filter_text.length() > 0)
{
bool enable_save_action = false;
bool match = false;
FilterListModel model(FilterListModel::Display);
QModelIndex idx = model.findByExpression(filter_text);
if (idx.isValid()) {
match = true;
bookmark_button_->setStockIcon("x-filter-matching-bookmark");
if (remove_action_) {
remove_action_->setData(text());
remove_action_->setEnabled(true);
}
} else {
bookmark_button_->setStockIcon("x-display-filter-bookmark");
if (remove_action_) {
remove_action_->setEnabled(false);
}
}
if (!match && (syntaxState() == Valid || syntaxState() == Deprecated) && !filter_text.isEmpty()) {
enable_save_action = true;
}
if (save_action_) {
save_action_->setEnabled(enable_save_action);
}
}
apply_button_->setEnabled(syntaxState() != Invalid);
}
}
void DisplayFilterEdit::updateBookmarkMenu()
{
if (!bookmark_button_)
return;
QMenu *bb_menu = bookmark_button_->menu();
bb_menu->clear();
save_action_ = bb_menu->addAction(tr("Save this filter"));
connect(save_action_, &QAction::triggered, this, &DisplayFilterEdit::saveFilter);
remove_action_ = bb_menu->addAction(tr("Remove this filter"));
connect(remove_action_, &QAction::triggered, this, &DisplayFilterEdit::removeFilter);
QAction *manage_action = bb_menu->addAction(tr("Manage Display Filters"));
connect(manage_action, &QAction::triggered, this, &DisplayFilterEdit::showFilters);
QAction *expr_action = bb_menu->addAction(tr("Filter Button Preferences..."));
connect(expr_action, &QAction::triggered, this, &DisplayFilterEdit::showExpressionPrefs);
bb_menu->addSeparator();
FilterListModel model(FilterListModel::Display);
QModelIndex idx = model.findByExpression(text());
int one_em = bb_menu->fontMetrics().height();
if (! actions_)
actions_ = new QActionGroup(this);
for (int row = 0; row < model.rowCount(); row++)
{
QModelIndex nameIdx = model.index(row, FilterListModel::ColumnName);
QString name = nameIdx.data().toString();
QString expr = model.index(row, FilterListModel::ColumnExpression).data().toString();
QString prep_text = QString("%1: %2").arg(name).arg(expr);
prep_text = bb_menu->fontMetrics().elidedText(prep_text, Qt::ElideRight, one_em * 40);
QAction * prep_action = bb_menu->addAction(prep_text);
prep_action->setCheckable(true);
if (nameIdx == idx)
prep_action->setChecked(true);
prep_action->setProperty("display_filter", expr);
actions_->addAction(prep_action);
connect(prep_action, &QAction::triggered, this, &DisplayFilterEdit::applyOrPrepareFilter);
}
checkFilter();
}
// GTK+ behavior:
// - Operates on words (proto.c:fld_abbrev_chars).
// - Popup appears when you enter or remove text.
// Our behavior:
// - Operates on words (fld_abbrev_chars_).
// - Popup appears when you enter or remove text.
// - Popup appears when you move the cursor.
// - Popup does not appear when text is selected.
// - Recent and saved display filters in popup when editing first word.
// ui/gtk/filter_autocomplete.c:build_autocompletion_list
void DisplayFilterEdit::buildCompletionList(const QString &field_word, const QString &preamble)
{
// Push a hint about the current field.
if (syntaxState() == Valid) {
if (mainApp->mainWindow()->isActiveWindow())
mainApp->popStatus(MainApplication::FilterSyntax);
header_field_info *hfinfo = proto_registrar_get_byname(field_word.toUtf8().constData());
if (hfinfo) {
QString cursor_field_msg = QString("%1: %2")
.arg(hfinfo->name)
.arg(ftype_pretty_name(hfinfo->type));
if (mainApp->mainWindow()->isActiveWindow())
mainApp->pushStatus(MainApplication::FilterSyntax, cursor_field_msg);
}
}
if (field_word.length() < 1) {
completion_model_->setStringList(QStringList());
return;
}
// Grab matching display filters from our parent combo and from the
// saved display filters file. Skip ones that look like single fields
// and assume they will be added below.
QStringList complex_list;
QComboBox *df_combo = qobject_cast<QComboBox *>(parent());
if (df_combo) {
for (int i = 0; i < df_combo->count() ; i++) {
QString recent_filter = df_combo->itemText(i);
if (isComplexFilter(recent_filter)) {
complex_list << recent_filter;
}
}
}
FilterListModel model(FilterListModel::Display);
for (int row = 0; row < model.rowCount(); row++)
{
QString saved_filter = model.index(row, FilterListModel::ColumnExpression).data().toString();
if (isComplexFilter(saved_filter) && !complex_list.contains(saved_filter)) {
complex_list << saved_filter;
}
}
completion_model_->setStringList(complex_list);
completer()->setCompletionPrefix(field_word);
// Only add fields to completion if a field is valid at this position.
// Try to compile preamble and check error message.
if (preamble != filter_word_preamble_) {
df_error_t *df_err = NULL;
dfilter_t *test_df = NULL;
if (preamble.size() > 0) {
dfilter_compile_full(qUtf8Printable(preamble), &test_df, &df_err,
DF_EXPAND_MACROS, __func__);
}
if (test_df == NULL || (df_err != NULL && df_err->code == DF_ERROR_UNEXPECTED_END)) {
// Unexpected end of expression means "expected identifier (field) or literal".
autocomplete_accepts_field_ = true;
}
else {
autocomplete_accepts_field_ = false;
}
dfilter_free(test_df);
df_error_free(&df_err);
filter_word_preamble_ = preamble;
}
QStringList field_list;
if (autocomplete_accepts_field_) {
void *proto_cookie;
int field_dots = static_cast<int>(field_word.count('.')); // Some protocol names (_ws.expert) contain periods.
for (int proto_id = proto_get_first_protocol(&proto_cookie); proto_id != -1; proto_id = proto_get_next_protocol(&proto_cookie)) {
protocol_t *protocol = find_protocol_by_id(proto_id);
if (!proto_is_protocol_enabled(protocol)) continue;
const QString pfname = proto_get_protocol_filter_name(proto_id);
field_list << pfname;
// Add fields only if we're past the protocol name and only for the
// current protocol.
if (field_dots > pfname.count('.')) {
void *field_cookie;
const QByteArray fw_ba = field_word.toUtf8(); // or toLatin1 or toStdString?
const char *fw_utf8 = fw_ba.constData();
gsize fw_len = (gsize) strlen(fw_utf8);
for (header_field_info *hfinfo = proto_get_first_protocol_field(proto_id, &field_cookie); hfinfo; hfinfo = proto_get_next_protocol_field(proto_id, &field_cookie)) {
if (hfinfo->same_name_prev_id != -1) continue; // Ignore duplicate names.
if (!g_ascii_strncasecmp(fw_utf8, hfinfo->abbrev, fw_len)) {
if ((gsize) strlen(hfinfo->abbrev) != fw_len) field_list << hfinfo->abbrev;
}
}
}
}
field_list.sort();
}
completion_model_->setStringList(complex_list + field_list);
completer()->setCompletionPrefix(field_word);
}
void DisplayFilterEdit::clearFilter()
{
clear();
last_applied_ = QString();
updateClearButton();
emit filterPackets(QString(), true);
}
void DisplayFilterEdit::applyDisplayFilter()
{
if (syntaxState() == Invalid)
return;
if (text().length() > 0)
last_applied_ = text();
updateClearButton();
emit filterPackets(text(), true);
}
void DisplayFilterEdit::updateClearButton()
{
setDefaultPlaceholderText();
clear_button_->setVisible(!text().isEmpty());
alignActionButtons();
}
void DisplayFilterEdit::displayFilterSuccess(bool success)
{
if (apply_button_)
apply_button_->setEnabled(!success);
}
void DisplayFilterEdit::changeEvent(QEvent* event)
{
if (0 != event)
{
switch (event->type())
{
case QEvent::LanguageChange:
setDefaultPlaceholderText();
break;
default:
break;
}
}
SyntaxLineEdit::changeEvent(event);
}
void DisplayFilterEdit::saveFilter()
{
FilterDialog *display_filter_dlg = new FilterDialog(window(), FilterDialog::DisplayFilter, text());
display_filter_dlg->setWindowModality(Qt::ApplicationModal);
display_filter_dlg->setAttribute(Qt::WA_DeleteOnClose);
display_filter_dlg->show();
}
void DisplayFilterEdit::removeFilter()
{
if (! actions_ || ! actions_->checkedAction())
return;
QAction *ra = actions_->checkedAction();
if (ra->property("display_filter").toString().isEmpty())
return;
QString remove_filter = ra->property("display_filter").toString();
FilterListModel model(FilterListModel::Display);
QModelIndex idx = model.findByExpression(remove_filter);
if (idx.isValid())
{
model.removeFilter(idx);
model.saveList();
}
updateBookmarkMenu();
}
void DisplayFilterEdit::showFilters()
{
FilterDialog *display_filter_dlg = new FilterDialog(window(), FilterDialog::DisplayFilter);
display_filter_dlg->setWindowModality(Qt::ApplicationModal);
display_filter_dlg->setAttribute(Qt::WA_DeleteOnClose);
display_filter_dlg->show();
}
void DisplayFilterEdit::showExpressionPrefs()
{
emit showPreferencesDialog(PrefsModel::typeToString(PrefsModel::FilterButtons));
}
void DisplayFilterEdit::applyOrPrepareFilter()
{
QAction *pa = qobject_cast<QAction*>(sender());
if (! pa || pa->property("display_filter").toString().isEmpty())
return;
QString filterText = pa->property("display_filter").toString();
last_applied_ = filterText;
setText(filterText);
// Holding down the Shift key will only prepare filter.
if (!(QApplication::keyboardModifiers() & Qt::ShiftModifier)) {
applyDisplayFilter();
}
}
void DisplayFilterEdit::dragEnterEvent(QDragEnterEvent *event)
{
if (! event || ! event->mimeData())
return;
if (qobject_cast<const ToolbarEntryMimeData *>(event->mimeData()) ||
event->mimeData()->hasFormat(WiresharkMimeData::DisplayFilterMimeType)) {
if (event->source() != this)
{
event->setDropAction(Qt::CopyAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void DisplayFilterEdit::dragMoveEvent(QDragMoveEvent *event)
{
if (! event || ! event->mimeData())
return;
if (qobject_cast<const ToolbarEntryMimeData *>(event->mimeData()) ||
event->mimeData()->hasFormat(WiresharkMimeData::DisplayFilterMimeType)) {
if (event->source() != this)
{
event->setDropAction(Qt::CopyAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void DisplayFilterEdit::dropEvent(QDropEvent *event)
{
if (! event || ! event->mimeData())
return;
QString filterText = "";
if (event->mimeData()->hasFormat(WiresharkMimeData::DisplayFilterMimeType))
{
QByteArray jsonData = event->mimeData()->data(WiresharkMimeData::DisplayFilterMimeType);
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData);
if (! jsonDoc.isObject())
return;
QJsonObject data = jsonDoc.object();
if ((QApplication::keyboardModifiers() & Qt::AltModifier) && data.contains("field"))
filterText = data["field"].toString();
else if (data.contains("filter"))
filterText = data["filter"].toString();
}
else if (qobject_cast<const ToolbarEntryMimeData *>(event->mimeData()))
{
const ToolbarEntryMimeData * data = qobject_cast<const ToolbarEntryMimeData *>(event->mimeData());
filterText = data->filter();
}
/* Moving items around */
if (filterText.length() > 0) {
if (event->source() != this)
{
event->setDropAction(Qt::CopyAction);
event->accept();
bool prepare = QApplication::keyboardModifiers() & Qt::ShiftModifier;
if (text().length() > 0 || QApplication::keyboardModifiers() & Qt::MetaModifier)
{
createFilterTextDropMenu(event, prepare, filterText);
return;
}
last_applied_ = filterText;
setText(filterText);
// Holding down the Shift key will only prepare filter.
if (! prepare) {
applyDisplayFilter();
}
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void DisplayFilterEdit::createFilterTextDropMenu(QDropEvent *event, bool prepare, QString filterText)
{
if (filterText.isEmpty())
return;
FilterAction::Action filterAct = prepare ? FilterAction::ActionPrepare : FilterAction::ActionApply;
QMenu * applyMenu = FilterAction::createFilterMenu(filterAct, filterText, true, this);
applyMenu->setAttribute(Qt::WA_DeleteOnClose);
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
applyMenu->popup(this->mapToGlobal(event->position().toPoint()));
#else
applyMenu->popup(this->mapToGlobal(event->pos()));
#endif
}
void DisplayFilterEdit::displayFilterExpression()
{
DisplayFilterExpressionDialog *dfe_dialog = new DisplayFilterExpressionDialog(this);
connect(dfe_dialog, &DisplayFilterExpressionDialog::insertDisplayFilter,
this, &DisplayFilterEdit::insertFilter);
dfe_dialog->show();
} |
C/C++ | wireshark/ui/qt/widgets/display_filter_edit.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef DISPLAYFILTEREDIT_H
#define DISPLAYFILTEREDIT_H
#include <QDrag>
#include <QActionGroup>
#include <ui/qt/widgets/syntax_line_edit.h>
class QEvent;
class StockIconToolButton;
typedef enum {
DisplayFilterToApply,
DisplayFilterToEnter,
ReadFilterToApply
} DisplayFilterEditType;
class DisplayFilterEdit : public SyntaxLineEdit
{
Q_OBJECT
public:
explicit DisplayFilterEdit(QWidget *parent = 0, DisplayFilterEditType type = DisplayFilterToEnter);
protected:
void paintEvent(QPaintEvent *evt);
void resizeEvent(QResizeEvent *);
void keyPressEvent(QKeyEvent *event) { completionKeyPressEvent(event); }
void focusInEvent(QFocusEvent *event) { completionFocusInEvent(event); }
void focusOutEvent(QFocusEvent *event);
virtual void dragEnterEvent(QDragEnterEvent *event);
virtual void dragMoveEvent(QDragMoveEvent *event);
virtual void dropEvent(QDropEvent *event);
virtual void contextMenuEvent(QContextMenuEvent *menu);
public slots:
bool checkFilter();
void updateBookmarkMenu();
void applyDisplayFilter();
void displayFilterSuccess(bool success);
private slots:
void checkFilter(const QString &filter_text);
void clearFilter();
void changeEvent(QEvent* event);
void displayFilterExpression();
void saveFilter();
void removeFilter();
void showFilters();
void showExpressionPrefs();
void applyOrPrepareFilter();
void triggerAlignementAction();
void connectToMainWindow();
private:
DisplayFilterEditType type_;
QString placeholder_text_;
QAction *save_action_;
QAction *remove_action_;
QActionGroup * actions_;
StockIconToolButton *bookmark_button_;
StockIconToolButton *clear_button_;
StockIconToolButton *apply_button_;
bool leftAlignActions_;
QString last_applied_;
QString filter_word_preamble_;
bool autocomplete_accepts_field_;
void setDefaultPlaceholderText();
void buildCompletionList(const QString &field_word, const QString &preamble);
void createFilterTextDropMenu(QDropEvent *event, bool prepare, QString filterText = QString());
void alignActionButtons();
void updateClearButton();
signals:
void pushFilterSyntaxStatus(const QString&);
void popFilterSyntaxStatus();
void filterPackets(QString new_filter, bool force);
void showPreferencesDialog(QString pane_name);
};
#endif // DISPLAYFILTEREDIT_H |
C++ | wireshark/ui/qt/widgets/dissector_syntax_line_edit.cpp | /* dissector_syntax_line_edit.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <glib.h>
#include <epan/packet.h>
#include <wsutil/utf8_entities.h>
#include <ui/qt/widgets/dissector_syntax_line_edit.h>
#include <ui/qt/widgets/syntax_line_edit.h>
#include <QAction>
#include <QCompleter>
#include <QEvent>
#include <QStringListModel>
#include <wsutil/utf8_entities.h>
// Ordinary dissector names allow the same characters as display filter
// fields (heuristic dissectors don't allow upper-case.)
static const QString fld_abbrev_chars_ = "-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
DissectorSyntaxLineEdit::DissectorSyntaxLineEdit(QWidget *parent) :
SyntaxLineEdit(parent)
{
setAccessibleName(tr("Dissector entry"));
completion_model_ = new QStringListModel(this);
setCompleter(new QCompleter(completion_model_, this));
setCompletionTokenChars(fld_abbrev_chars_);
GList *dissector_names = get_dissector_names();
QStringList dissector_list;
for (GList* l = dissector_names; l != NULL; l = l->next) {
dissector_list << (const char*) l->data;
}
g_list_free(dissector_names);
dissector_list.sort();
completion_model_->setStringList(dissector_list);
setDefaultPlaceholderText();
connect(this, &DissectorSyntaxLineEdit::textChanged, this,
static_cast<void (DissectorSyntaxLineEdit::*)(const QString &)>(&DissectorSyntaxLineEdit::checkDissectorName));
}
void DissectorSyntaxLineEdit::setDefaultPlaceholderText()
{
placeholder_text_ = QString(tr("Enter a dissector %1")).arg(UTF8_HORIZONTAL_ELLIPSIS);
setPlaceholderText(placeholder_text_);
}
void DissectorSyntaxLineEdit::checkDissectorName(const QString &dissector)
{
if (dissector.isEmpty()) {
setSyntaxState(SyntaxLineEdit::Empty);
} else if (find_dissector(dissector.trimmed().toUtf8().constData())) {
setSyntaxState(SyntaxLineEdit::Valid);
} else {
setSyntaxState(SyntaxLineEdit::Invalid);
}
}
void DissectorSyntaxLineEdit::buildCompletionList(const QString &field_word, const QString &preamble _U_)
{
#if 0
// It would be nice to push a hint about the current dissector with
// the description, as we do with the status line in the main window
// with filters.
if (syntaxState() == Valid) {
dissector_handle_t handle = find_dissector(field_word.toUtf8().constData());
if (handle) {
QString cursor_field_msg = QString("%1: %2")
.arg(dissector_handle_get_dissector_name(handle))
.arg(dissector_handle_get_description(handle));
}
}
#endif
completer()->setCompletionPrefix(field_word);
}
void DissectorSyntaxLineEdit::changeEvent(QEvent* event)
{
if (0 != event)
{
switch (event->type())
{
case QEvent::LanguageChange:
setDefaultPlaceholderText();
break;
default:
break;
}
}
SyntaxLineEdit::changeEvent(event);
} |
C/C++ | wireshark/ui/qt/widgets/dissector_syntax_line_edit.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef DISSECTOR_SYNTAX_LINEEDIT_H
#define DISSECTOR_SYNTAX_LINEEDIT_H
#include <ui/qt/widgets/syntax_line_edit.h>
class QEvent;
class StockIconToolButton;
class DissectorSyntaxLineEdit : public SyntaxLineEdit
{
Q_OBJECT
public:
explicit DissectorSyntaxLineEdit(QWidget *parent = 0);
protected:
void keyPressEvent(QKeyEvent *event) { completionKeyPressEvent(event); }
void focusInEvent(QFocusEvent *event) { completionFocusInEvent(event); }
private slots:
void checkDissectorName(const QString &dissector);
void changeEvent(QEvent* event);
private:
QString placeholder_text_;
void setDefaultPlaceholderText();
void buildCompletionList(const QString &field_word, const QString &preamble);
};
#endif // DISSECTOR_SYNTAX_LINEEDIT_H |
C++ | wireshark/ui/qt/widgets/dissector_tables_view.cpp | /* dissector_tables_view.cpp
* Tree view of Dissector Table data.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "dissector_tables_view.h"
#include <ui/qt/models/dissector_tables_model.h>
DissectorTablesTreeView::DissectorTablesTreeView(QWidget *parent) : QTreeView(parent)
{
}
void DissectorTablesTreeView::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
if (current.isValid())
{
((DissectorTablesProxyModel*)model())->adjustHeader(current);
}
QTreeView::currentChanged(current, previous);
} |
C/C++ | wireshark/ui/qt/widgets/dissector_tables_view.h | /** @file
*
* Tree view of Dissector Table data.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef DISSECTOR_TABLES_VIEW_H
#define DISSECTOR_TABLES_VIEW_H
#include <config.h>
#include <QTreeView>
class DissectorTablesTreeView : public QTreeView
{
Q_OBJECT
public:
DissectorTablesTreeView(QWidget *parent = 0);
protected slots:
void currentChanged(const QModelIndex ¤t, const QModelIndex &previous);
};
#endif // DISSECTOR_TABLES_VIEW_H |
C++ | wireshark/ui/qt/widgets/drag_drop_toolbar.cpp | /* drag_drop_toolbar.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <wsutil/utf8_entities.h>
#include <ui/qt/widgets/drag_drop_toolbar.h>
#include <ui/qt/widgets/drag_label.h>
#include <ui/qt/utils/wireshark_mime_data.h>
#include <QAction>
#include <QApplication>
#include <QToolBar>
#include <QToolButton>
#include <QDrag>
#include <QLayout>
#include <QMimeData>
#include <QMouseEvent>
#include <QWindow>
#include <QJsonObject>
#include <QJsonDocument>
#define drag_drop_toolbar_action_ "drag_drop_toolbar_action_"
DragDropToolBar::DragDropToolBar(const QString &title, QWidget *parent) :
QToolBar(title, parent)
{
setupToolbar();
}
DragDropToolBar::DragDropToolBar(QWidget *parent) :
QToolBar(parent)
{
setupToolbar();
}
void DragDropToolBar::setupToolbar()
{
childCounter = 0;
setAcceptDrops(true);
// Each QToolBar has a QToolBarExtension button. Its icon looks
// terrible. We might want to create our own icon, but the double
// angle quote is a similar, nice-looking shape.
QToolButton *ext_button = findChild<QToolButton*>();
if (ext_button) {
ext_button->setIcon(QIcon());
ext_button->setText(UTF8_RIGHT_POINTING_DOUBLE_ANGLE_QUOTATION_MARK);
}
}
DragDropToolBar::~DragDropToolBar()
{
}
void DragDropToolBar::childEvent(QChildEvent * event)
{
/* New action has been added */
if (event->type() == QEvent::ChildAdded)
{
if (event->child()->isWidgetType())
{
/* Reset if it has moved underneath lower limit */
if (childCounter < 0)
childCounter = 0;
((QWidget *)event->child())->installEventFilter(this);
event->child()->setProperty(drag_drop_toolbar_action_, QVariant::fromValue(childCounter));
childCounter++;
}
}
else if (event->type() == QEvent::ChildRemoved)
{
childCounter--;
}
else if (event->type() == QEvent::ChildPolished)
{
/* Polish is called every time a child is added or removed. This is implemented by adding
* all childs again as hidden elements, and afterwards removing the existing ones. Therefore
* we have to reset child counter here, if a widget is being polished. If this is not being
* done, crashes will occur after an item has been removed and other items are moved afterwards */
if (event->child()->isWidgetType())
childCounter = 0;
}
}
void DragDropToolBar::clear()
{
QToolBar::clear();
childCounter = 0;
}
WiresharkMimeData * DragDropToolBar::createMimeData(QString name, int position)
{
return new ToolbarEntryMimeData(name, position);
}
bool DragDropToolBar::eventFilter(QObject * obj, QEvent * event)
{
if (! obj->isWidgetType())
return QToolBar::eventFilter(obj, event);
QWidget * elem = qobject_cast<QWidget *>(obj);
if (! elem || (event->type() != QEvent::MouseButtonPress && event->type() != QEvent::MouseMove) )
return QToolBar::eventFilter(obj, event);
QMouseEvent * ev = (QMouseEvent *)event;
if (event->type() == QEvent::MouseButtonPress)
{
if (ev->buttons() & Qt::LeftButton)
dragStartPosition = ev->pos();
}
else if (event->type() == QEvent::MouseMove)
{
if ((ev->buttons() & Qt::LeftButton) && (ev->pos() - dragStartPosition).manhattanLength()
> QApplication::startDragDistance())
{
if (! qobject_cast<QToolButton *>(elem) || ! elem->property(drag_drop_toolbar_action_).isValid())
return QToolBar::eventFilter(obj, event);
WiresharkMimeData * temd = createMimeData(((QToolButton *)elem)->text(), elem->property(drag_drop_toolbar_action_).toInt());
DragLabel * lbl = new DragLabel(temd->labelText(), this);
QDrag * drag = new QDrag(this);
drag->setMimeData(temd);
qreal dpr = window()->windowHandle()->devicePixelRatio();
QPixmap pixmap(lbl->size() * dpr);
pixmap.setDevicePixelRatio(dpr);
lbl->render(&pixmap);
drag->setPixmap(pixmap);
drag->exec(Qt::CopyAction | Qt::MoveAction);
return true;
}
}
return QToolBar::eventFilter(obj, event);
}
void DragDropToolBar::dragEnterEvent(QDragEnterEvent *event)
{
if (! event || ! event->mimeData())
return;
if (qobject_cast<const ToolbarEntryMimeData *>(event->mimeData()))
{
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else if (event->mimeData()->hasFormat(WiresharkMimeData::DisplayFilterMimeType)) {
if (event->source() != this)
{
event->setDropAction(Qt::CopyAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void DragDropToolBar::dragMoveEvent(QDragMoveEvent *event)
{
if (! event || ! event->mimeData())
return;
if (qobject_cast<const ToolbarEntryMimeData *>(event->mimeData()))
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
QAction * actionAtPos = actionAt(event->position().toPoint());
#else
QAction * actionAtPos = actionAt(event->pos());
#endif
if (actionAtPos)
{
QWidget * widget = widgetForAction(actionAtPos);
if (widget)
{
bool success = false;
widget->property(drag_drop_toolbar_action_).toInt(&success);
if (! success)
{
event->ignore();
return;
}
}
}
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else if (event->mimeData()->hasFormat(WiresharkMimeData::DisplayFilterMimeType)) {
if (event->source() != this)
{
event->setDropAction(Qt::CopyAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void DragDropToolBar::dropEvent(QDropEvent *event)
{
if (! event || ! event->mimeData())
return;
/* Moving items around */
if (qobject_cast<const ToolbarEntryMimeData *>(event->mimeData()))
{
const ToolbarEntryMimeData * data = qobject_cast<const ToolbarEntryMimeData *>(event->mimeData());
int oldPos = data->position();
int newPos = -1;
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
QAction * action = actionAt(event->position().toPoint());
#else
QAction * action = actionAt(event->pos());
#endif
if (action && actions().at(oldPos))
{
widgetForAction(action)->setStyleSheet("QWidget { border: none; };");
newPos = widgetForAction(action)->property(drag_drop_toolbar_action_).toInt();
moveToolbarItems(oldPos, newPos);
QAction * moveAction = actions().at(oldPos);
emit actionMoved(moveAction, oldPos, newPos);
}
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else if (event->mimeData()->hasFormat(WiresharkMimeData::DisplayFilterMimeType)) {
QByteArray jsonData = event->mimeData()->data(WiresharkMimeData::DisplayFilterMimeType);
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData);
if (jsonDoc.isObject())
{
QJsonObject data = jsonDoc.object();
if (event->source() != this && data.contains("description") && data.contains("filter"))
{
event->setDropAction(Qt::CopyAction);
event->accept();
emit newFilterDropped(data["description"].toString(), data["filter"].toString());
} else {
event->acceptProposedAction();
}
}
} else {
event->ignore();
}
}
void DragDropToolBar::moveToolbarItems(int fromPos, int newPos)
{
if (fromPos == newPos)
return;
setUpdatesEnabled(false);
QList<QAction *> storedActions = actions();
clear();
childCounter = 0;
storedActions.move(fromPos, newPos);
foreach (QAction * action, storedActions)
addAction(action);
setUpdatesEnabled(true);
} |
C/C++ | wireshark/ui/qt/widgets/drag_drop_toolbar.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef DRAG_DROP_TOOLBAR_H
#define DRAG_DROP_TOOLBAR_H
#include <QToolBar>
#include <QPoint>
class WiresharkMimeData;
class DragDropToolBar : public QToolBar
{
Q_OBJECT
public:
explicit DragDropToolBar(const QString &title, QWidget *parent = Q_NULLPTR);
explicit DragDropToolBar(QWidget *parent = Q_NULLPTR);
~DragDropToolBar();
virtual void clear();
signals:
void actionMoved(QAction * action, int oldPos, int newPos);
void newFilterDropped(QString description, QString filter);
protected:
virtual WiresharkMimeData * createMimeData(QString name, int position);
virtual void childEvent(QChildEvent * event);
virtual bool eventFilter(QObject * obj, QEvent * ev);
virtual void dragEnterEvent(QDragEnterEvent *event);
virtual void dragMoveEvent(QDragMoveEvent *event);
virtual void dropEvent(QDropEvent *event);
private:
QPoint dragStartPosition;
int childCounter;
void setupToolbar();
void moveToolbarItems(int fromPos, int toPos);
};
#endif // DRAG_DROP_TOOLBAR_H |
C++ | wireshark/ui/qt/widgets/drag_label.cpp | /* drag_label.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/drag_label.h>
#include <QLayout>
DragLabel::DragLabel(QString txt, QWidget * parent)
: QLabel(txt, parent)
{
setAutoFillBackground(true);
setFrameShape(QFrame::Panel);
setFrameShadow(QFrame::Raised);
setAttribute(Qt::WA_DeleteOnClose);
setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
adjustSize();
}
DragLabel::~DragLabel() {
// TODO Auto-generated destructor stub
} |
C/C++ | wireshark/ui/qt/widgets/drag_label.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef UI_QT_WIDGETS_DRAG_LABEL_H_
#define UI_QT_WIDGETS_DRAG_LABEL_H_
#include <QLabel>
#include <QDrag>
#include <QMimeData>
#include <QMouseEvent>
class DragLabel: public QLabel
{
Q_OBJECT
public:
explicit DragLabel(QString text, QWidget * parent = 0);
virtual ~DragLabel();
};
#endif /* UI_QT_WIDGETS_DRAG_LABEL_H_ */ |
C++ | wireshark/ui/qt/widgets/editor_file_dialog.cpp | /* editor_file_dialog.h
*
* File dialog that can be used as an "inline editor" in a table
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/editor_file_dialog.h>
#include <ui/qt/widgets/wireshark_file_dialog.h>
#include <QKeyEvent>
#include <QStyle>
#include "wsutil/utf8_entities.h"
EditorFileDialog::EditorFileDialog(const QModelIndex& index, enum FileMode mode, QWidget* parent, const QString& caption, const QString& directory, const QString& filter)
: QLineEdit(parent)
, file_dialog_button_(new QPushButton(this))
, index_(index)
, mode_(mode)
, caption_(caption)
, directory_(directory)
, filter_(filter)
, options_(QFileDialog::Options())
{
if (mode_ == Directory)
options_ = QFileDialog::ShowDirsOnly;
if (!directory.isEmpty())
setText(directory);
file_dialog_button_->setText(UTF8_HORIZONTAL_ELLIPSIS);
connect(file_dialog_button_, &QPushButton::clicked, this, &EditorFileDialog::applyFilename);
}
void EditorFileDialog::setOption(QFileDialog::Option option, bool on)
{
if (on)
{
options_ |= option;
}
else
{
options_ &= (~option);
}
}
// QAbstractItemView installs QAbstractItemDelegate's event filter after
// we've been created. We need to install our own event filter after that
// happens so that we can steal tab keypresses.
void EditorFileDialog::focusInEvent(QFocusEvent *event)
{
installEventFilter(this);
QLineEdit::focusInEvent(event);
}
void EditorFileDialog::focusOutEvent(QFocusEvent *event)
{
removeEventFilter(this);
QLineEdit::focusOutEvent(event);
}
bool EditorFileDialog::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent* key = static_cast<QKeyEvent*>(event);
if ((key->key() == Qt::Key_Tab) && !file_dialog_button_->hasFocus()) {
file_dialog_button_->setFocus();
return true;
}
}
return QLineEdit::eventFilter(obj, event);
}
void EditorFileDialog::resizeEvent(QResizeEvent *)
{
// Move the button to the end of the line edit and set its height.
QSize sz = file_dialog_button_->sizeHint();
int frame_width = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
file_dialog_button_->move(rect().right() - frame_width - sz.width(),
contentsRect().top());
file_dialog_button_->setMinimumHeight(contentsRect().height());
file_dialog_button_->setMaximumHeight(contentsRect().height());
}
void EditorFileDialog::applyFilename()
{
QString file;
if (mode_ == Directory)
{
file = WiresharkFileDialog::getExistingDirectory(this, caption_, directory_, options_);
}
else
{
file = WiresharkFileDialog::getOpenFileName(this, caption_, directory_, filter_, NULL, options_);
}
if (!file.isEmpty())
{
setText(file);
emit acceptEdit(index_);
}
} |
C/C++ | wireshark/ui/qt/widgets/editor_file_dialog.h | /** @file
*
* File dialog that can be used as an "inline editor" in a table
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef EDITOR_FILE_DIALOG_H_
#define EDITOR_FILE_DIALOG_H_
#include <QModelIndex>
#include <QLineEdit>
#include <QFileDialog>
#include <QPushButton>
class EditorFileDialog : public QLineEdit
{
Q_OBJECT
public:
enum FileMode { ExistingFile, Directory };
explicit EditorFileDialog(const QModelIndex& index, enum FileMode mode, QWidget* parent = 0, const QString & caption = QString(), const QString & directory = QString(), const QString & filter = QString());
void setOption(QFileDialog::Option option, bool on = true);
virtual void focusInEvent(QFocusEvent *event);
virtual void focusOutEvent(QFocusEvent *event);
virtual bool eventFilter(QObject *obj, QEvent *event);
signals:
void acceptEdit(const QModelIndex& index);
private slots:
void applyFilename();
protected:
void resizeEvent(QResizeEvent *);
QPushButton* file_dialog_button_;
const QModelIndex index_; //saved index of table cell
enum FileMode mode_;
QString caption_;
QString directory_;
QString filter_;
QFileDialog::Options options_;
};
#endif /* EDITOR_FILE_DIALOG_H_ */ |
C++ | wireshark/ui/qt/widgets/elided_label.cpp | /* elided_label.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/elided_label.h>
#include <ui/qt/utils/color_utils.h>
#include <QFontMetrics>
#include <QResizeEvent>
ElidedLabel::ElidedLabel(QWidget *parent) :
QLabel(parent),
small_text_(false)
{
QFontMetrics fm(font());
setMinimumWidth(fm.height() * 5); // em-widths
}
void ElidedLabel::setUrl(const QString &url)
{
url_ = url;
updateText();
}
bool ElidedLabel::event(QEvent *event)
{
switch (event->type()) {
case QEvent::ApplicationPaletteChange:
updateText();
break;
default:
break;
}
return QLabel::event(event);
}
void ElidedLabel::resizeEvent(QResizeEvent *)
{
updateText();
}
void ElidedLabel::updateText()
{
// XXX We should probably move text drawing to PaintEvent to match
// LabelStack.
int fudged_width = small_text_ ? width() * 1.2 : width();
QString elided_text = fontMetrics().elidedText(full_text_, Qt::ElideMiddle, fudged_width);
QString label_text = small_text_ ? "<small><i>" : "<i>";
if (url_.length() > 0) {
label_text.prepend(ColorUtils::themeLinkStyle());
label_text.append(QString("<a href=\"%1\">%2</a>").arg(url_, elided_text));
} else {
label_text += elided_text;
}
label_text += small_text_ ? "</i></small> " : "</i> ";
QLabel::setText(label_text);
}
void ElidedLabel::clear()
{
full_text_.clear();
url_.clear();
setToolTip("");
updateText();
}
void ElidedLabel::setText(const QString &text)
{
full_text_ = text.toHtmlEscaped();
updateText();
} |
C/C++ | wireshark/ui/qt/widgets/elided_label.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef ELIDED_LABEL_H
#define ELIDED_LABEL_H
#include <QLabel>
class ElidedLabel : public QLabel
{
Q_OBJECT
public:
explicit ElidedLabel(QWidget *parent = 0);
/**
* @brief setUrl Set the label's URL.
* @param url The URL to set.
*/
void setUrl(const QString &url);
/**
* @brief setSmallText Specifies a small or normal text size.
* @param small_text Show the text in a smaller font size if true, or a normal size otherwise.
*/
void setSmallText(bool small_text = true) { small_text_ = small_text; }
protected:
virtual bool event(QEvent *event);
virtual void resizeEvent(QResizeEvent *);
private:
bool small_text_;
QString full_text_;
QString url_;
void updateText();
signals:
public slots:
/**
* @brief clear Clear the label.
*/
void clear();
/**
* @brief setText Set the label's plain text.
* @param text The text to set. HTML will be escaped.
*/
void setText(const QString &text);
};
#endif // ELIDED_LABEL_H |
C++ | wireshark/ui/qt/widgets/expert_info_view.cpp | /* expert_info_view.cpp
* Tree view of Expert Info data.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "expert_info_view.h"
#include <ui/qt/models/expert_info_model.h>
#include <ui/qt/models/expert_info_proxy_model.h>
#include <QHeaderView>
ExpertInfoTreeView::ExpertInfoTreeView(QWidget *parent) : QTreeView(parent)
{
}
void ExpertInfoTreeView::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
if (current.isValid())
{
if (current.parent().isValid()) {
((ExpertInfoProxyModel*)model())->setSeverityMode(ExpertInfoProxyModel::Packet);
} else {
((ExpertInfoProxyModel*)model())->setSeverityMode(ExpertInfoProxyModel::Group);
}
QModelIndex model_index = ((ExpertInfoProxyModel*)model())->mapToSource(current);
if (model_index.parent().isValid()) {
ExpertPacketItem* currentItem = static_cast<ExpertPacketItem*>(model_index.internalPointer());
if (currentItem != NULL)
{
emit goToPacket(currentItem->packetNum(), currentItem->hfId());
}
}
}
QTreeView::currentChanged(current, previous);
} |
C/C++ | wireshark/ui/qt/widgets/expert_info_view.h | /** @file
*
* Tree view of Expert Info data.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef EXPERT_INFO_VIEW_H
#define EXPERT_INFO_VIEW_H
#include <config.h>
#include <QTreeView>
class ExpertInfoTreeView : public QTreeView
{
Q_OBJECT
public:
ExpertInfoTreeView(QWidget *parent = 0);
signals:
void goToPacket(int packet_num, int hf_id);
protected slots:
void currentChanged(const QModelIndex ¤t, const QModelIndex &previous);
};
#endif // EXPERT_INFO_VIEW_H |
C++ | wireshark/ui/qt/widgets/export_objects_view.cpp | /* export_objects_view.cpp
* Tree view of Export object data.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "export_objects_view.h"
#include <ui/qt/models/export_objects_model.h>
ExportObjectsTreeView::ExportObjectsTreeView(QWidget *parent) : QTreeView(parent)
{
}
void ExportObjectsTreeView::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
emit currentIndexChanged(current);
QTreeView::currentChanged(current, previous);
} |
C/C++ | wireshark/ui/qt/widgets/export_objects_view.h | /** @file
*
* Tree view of Export object data.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef EXPORT_OBJECTS_VIEW_H
#define EXPORT_OBJECTS_VIEW_H
#include <config.h>
#include <QTreeView>
class ExportObjectsTreeView : public QTreeView
{
Q_OBJECT
public:
ExportObjectsTreeView(QWidget *parent = 0);
signals:
void currentIndexChanged(const QModelIndex ¤t);
protected slots:
void currentChanged(const QModelIndex ¤t, const QModelIndex &previous);
};
#endif // EXPORT_OBJECTS_VIEW_H |
C++ | wireshark/ui/qt/widgets/field_filter_edit.cpp | /* field_filter_edit.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <glib.h>
#include <epan/dfilter/dfilter.h>
#include <wsutil/filter_files.h>
#include <wsutil/utf8_entities.h>
#include <ui/qt/widgets/field_filter_edit.h>
#include "filter_dialog.h"
#include <ui/qt/widgets/stock_icon_tool_button.h>
#include <ui/qt/widgets/syntax_line_edit.h>
#include <QAction>
#include <QCompleter>
#include <QEvent>
#include <QStringListModel>
#include <wsutil/utf8_entities.h>
// To do:
// - Get rid of shortcuts and replace them with "n most recently applied filters"?
// - We need simplified (button- and dropdown-free) versions for use in dialogs and field-only checking.
// - Add a separator or otherwise distinguish between recent items and fields
// in the completion dropdown.
#ifdef __APPLE__
#define DEFAULT_MODIFIER UTF8_PLACE_OF_INTEREST_SIGN
#else
#define DEFAULT_MODIFIER "Ctrl-"
#endif
// proto.c:fld_abbrev_chars
static const QString fld_abbrev_chars_ = "-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
FieldFilterEdit::FieldFilterEdit(QWidget *parent) :
SyntaxLineEdit(parent)
{
setAccessibleName(tr("Display filter entry"));
completion_model_ = new QStringListModel(this);
setCompleter(new QCompleter(completion_model_, this));
setCompletionTokenChars(fld_abbrev_chars_);
setDefaultPlaceholderText();
// DFCombo
// Bookmark
// DisplayFilterEdit
// Clear button
// Apply (right arrow)
// Combo drop-down
connect(this, &FieldFilterEdit::textChanged, this,
static_cast<void (FieldFilterEdit::*)(const QString &)>(&FieldFilterEdit::checkFilter));
// connect(this, &FieldFilterEdit::returnPressed, this, &FieldFilterEdit::applyDisplayFilter);
}
void FieldFilterEdit::setDefaultPlaceholderText()
{
placeholder_text_ = QString(tr("Enter a field %1")).arg(UTF8_HORIZONTAL_ELLIPSIS);
setPlaceholderText(placeholder_text_);
}
void FieldFilterEdit::focusOutEvent(QFocusEvent *event)
{
if (syntaxState() == Valid)
emit popFilterSyntaxStatus();
SyntaxLineEdit::focusOutEvent(event);
}
bool FieldFilterEdit::checkFilter()
{
checkFilter(text());
return syntaxState() != Invalid;
}
void FieldFilterEdit::checkFilter(const QString& filter_text)
{
popFilterSyntaxStatus();
if (!checkDisplayFilter(filter_text))
return;
switch (syntaxState()) {
case Deprecated:
{
emit pushFilterSyntaxWarning(syntaxErrorMessage());
break;
}
case Invalid:
{
QString invalidMsg(tr("Invalid filter: "));
invalidMsg.append(syntaxErrorMessage());
emit pushFilterSyntaxStatus(invalidMsg);
break;
}
default:
break;
}
}
// GTK+ behavior:
// - Operates on words (proto.c:fld_abbrev_chars).
// - Popup appears when you enter or remove text.
// Our behavior:
// - Operates on words (fld_abbrev_chars_).
// - Popup appears when you enter or remove text.
// - Popup appears when you move the cursor.
// - Popup does not appear when text is selected.
// - Recent and saved display filters in popup when editing first word.
// ui/gtk/filter_autocomplete.c:build_autocompletion_list
void FieldFilterEdit::buildCompletionList(const QString &field_word, const QString &preamble _U_)
{
// Push a hint about the current field.
if (syntaxState() == Valid) {
emit popFilterSyntaxStatus();
header_field_info *hfinfo = proto_registrar_get_byname(field_word.toUtf8().constData());
if (hfinfo) {
QString cursor_field_msg = QString("%1: %2")
.arg(hfinfo->name)
.arg(ftype_pretty_name(hfinfo->type));
emit pushFilterSyntaxStatus(cursor_field_msg);
}
}
if (field_word.length() < 1) {
completion_model_->setStringList(QStringList());
return;
}
void *proto_cookie;
QStringList field_list;
int field_dots = static_cast<int>(field_word.count('.')); // Some protocol names (_ws.expert) contain periods.
for (int proto_id = proto_get_first_protocol(&proto_cookie); proto_id != -1; proto_id = proto_get_next_protocol(&proto_cookie)) {
protocol_t *protocol = find_protocol_by_id(proto_id);
if (!proto_is_protocol_enabled(protocol)) continue;
const QString pfname = proto_get_protocol_filter_name(proto_id);
field_list << pfname;
// Add fields only if we're past the protocol name and only for the
// current protocol.
if (field_dots > pfname.count('.')) {
void *field_cookie;
const QByteArray fw_ba = field_word.toUtf8(); // or toLatin1 or toStdString?
const char *fw_utf8 = fw_ba.constData();
gsize fw_len = (gsize) strlen(fw_utf8);
for (header_field_info *hfinfo = proto_get_first_protocol_field(proto_id, &field_cookie); hfinfo; hfinfo = proto_get_next_protocol_field(proto_id, &field_cookie)) {
if (hfinfo->same_name_prev_id != -1) continue; // Ignore duplicate names.
if (!g_ascii_strncasecmp(fw_utf8, hfinfo->abbrev, fw_len)) {
if ((gsize) strlen(hfinfo->abbrev) != fw_len) field_list << hfinfo->abbrev;
}
}
}
}
field_list.sort();
completion_model_->setStringList(field_list);
completer()->setCompletionPrefix(field_word);
}
void FieldFilterEdit::clearFilter()
{
clear();
QString new_filter;
emit filterPackets(new_filter, true);
}
void FieldFilterEdit::applyDisplayFilter()
{
if (syntaxState() == Invalid) {
return;
}
QString new_filter = text();
emit filterPackets(new_filter, true);
}
void FieldFilterEdit::changeEvent(QEvent* event)
{
if (0 != event)
{
switch (event->type())
{
case QEvent::LanguageChange:
setDefaultPlaceholderText();
break;
default:
break;
}
}
SyntaxLineEdit::changeEvent(event);
}
void FieldFilterEdit::showFilters()
{
FilterDialog *display_filter_dlg = new FilterDialog(window(), FilterDialog::DisplayFilter);
display_filter_dlg->setWindowModality(Qt::ApplicationModal);
display_filter_dlg->setAttribute(Qt::WA_DeleteOnClose);
display_filter_dlg->show();
}
void FieldFilterEdit::prepareFilter()
{
QAction *pa = qobject_cast<QAction*>(sender());
if (!pa || pa->data().toString().isEmpty()) return;
setText(pa->data().toString());
} |
C/C++ | wireshark/ui/qt/widgets/field_filter_edit.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef FIELDFILTEREDIT_H
#define FIELDFILTEREDIT_H
#include <ui/qt/widgets/syntax_line_edit.h>
class QEvent;
class StockIconToolButton;
class FieldFilterEdit : public SyntaxLineEdit
{
Q_OBJECT
public:
explicit FieldFilterEdit(QWidget *parent = 0);
protected:
void keyPressEvent(QKeyEvent *event) { completionKeyPressEvent(event); }
void focusInEvent(QFocusEvent *event) { completionFocusInEvent(event); }
void focusOutEvent(QFocusEvent *event);
public slots:
bool checkFilter();
void applyDisplayFilter();
private slots:
void checkFilter(const QString &filter_text);
void clearFilter();
void changeEvent(QEvent* event);
void showFilters();
void prepareFilter();
private:
QString placeholder_text_;
void setDefaultPlaceholderText();
void buildCompletionList(const QString &field_word, const QString &preamble);
signals:
void pushFilterSyntaxStatus(const QString&);
void popFilterSyntaxStatus();
void pushFilterSyntaxWarning(const QString&);
void filterPackets(QString new_filter, bool force);
};
#endif // FIELDFILTEREDIT_H |
C++ | wireshark/ui/qt/widgets/filter_expression_toolbar.cpp | /* filter_expression_toolbar.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/filter_expression_toolbar.h>
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/utils/wireshark_mime_data.h>
#include <ui/qt/models/uat_model.h>
#include <ui/qt/filter_action.h>
#include <ui/qt/main_application.h>
#include <epan/filter_expressions.h>
#include <ui/preference_utils.h>
#include <QApplication>
#include <QFrame>
#include <QMenu>
#include <QEvent>
#include <QContextMenuEvent>
#include <QToolButton>
#include <QToolTip>
static const char *dfe_property_ = "display filter expression"; //TODO : Fix Translate
static const char *dfe_property_label_ = "display_filter_expression_label";
static const char *dfe_property_expression_ = "display_filter_expression_expr";
static const char *dfe_property_comment_ = "display_filter_expression_comment";
static const char *dfe_menu_ = "filter_menu";
#define PARENT_SEPARATOR "//"
struct filter_expression_data
{
FilterExpressionToolBar* toolbar;
bool actions_added;
};
FilterExpressionToolBar::FilterExpressionToolBar(QWidget * parent) :
DragDropToolBar(parent)
{
updateStyleSheet();
setContextMenuPolicy(Qt::CustomContextMenu);
/* Give minimum space to the bar, so that drops on an empty bar will work */
setMinimumWidth(10);
connect (this, &QWidget::customContextMenuRequested, this, &FilterExpressionToolBar::onCustomMenuHandler);
connect(this, &DragDropToolBar::actionMoved, this, &FilterExpressionToolBar::onActionMoved);
connect(this, &DragDropToolBar::newFilterDropped, this, &FilterExpressionToolBar::onFilterDropped);
connect(mainApp, &MainApplication::appInitialized,
this, &FilterExpressionToolBar::filterExpressionsChanged);
connect(mainApp, &MainApplication::filterExpressionsChanged,
this, &FilterExpressionToolBar::filterExpressionsChanged);
}
bool FilterExpressionToolBar::event(QEvent *event)
{
switch (event->type()) {
case QEvent::ApplicationPaletteChange:
updateStyleSheet();
break;
default:
break;
}
return DragDropToolBar::event(event);
}
void FilterExpressionToolBar::onCustomMenuHandler(const QPoint& pos)
{
QAction * filterAction = actionAt(pos);
if (! filterAction)
return;
customMenu(this, filterAction, pos);
}
void FilterExpressionToolBar::customMenu(FilterExpressionToolBar * target, QAction * filterAction, const QPoint& pos)
{
QMenu * filterMenu = new QMenu(target);
filterMenu->setAttribute(Qt::WA_DeleteOnClose);
/* Only display context menu for actual filter actions */
QString filterText = filterAction->property(dfe_property_expression_).toString().trimmed();
if (!filterText.isEmpty())
{
filterMenu->addMenu(FilterAction::createFilterMenu(FilterAction::ActionApply, filterText, true, target));
filterMenu->addMenu(FilterAction::createFilterMenu(FilterAction::ActionPrepare, filterText, true, target));
filterMenu->addSeparator();
filterMenu->addAction(FilterAction::copyFilterAction(filterText, target));
filterMenu->addSeparator();
QAction * actEdit = filterMenu->addAction(tr("Edit"));
connect(actEdit, &QAction::triggered, target, &FilterExpressionToolBar::editFilter);
actEdit->setProperty(dfe_property_label_, filterAction->property(dfe_property_label_));
actEdit->setProperty(dfe_property_expression_, filterAction->property(dfe_property_expression_));
actEdit->setData(filterAction->data());
QAction * actDisable = filterMenu->addAction(tr("Disable"));
connect(actDisable, &QAction::triggered, target, &FilterExpressionToolBar::disableFilter);
actDisable->setProperty(dfe_property_label_, filterAction->property(dfe_property_label_));
actDisable->setProperty(dfe_property_expression_, filterAction->property(dfe_property_expression_));
actDisable->setData(filterAction->data());
QAction * actRemove = filterMenu->addAction(tr("Remove"));
connect(actRemove, &QAction::triggered, target, &FilterExpressionToolBar::removeFilter);
actRemove->setProperty(dfe_property_label_, filterAction->property(dfe_property_label_));
actRemove->setProperty(dfe_property_expression_, filterAction->property(dfe_property_expression_));
actRemove->setData(filterAction->data());
filterMenu->addSeparator();
}
QAction *actFilter = filterMenu->addAction(tr("Filter Button Preferences..."));
connect(actFilter, &QAction::triggered, target, &FilterExpressionToolBar::toolBarShowPreferences);
/* Forcing the menus to get closed, no matter which action has been triggered */
connect(filterMenu, &QMenu::triggered, this, &FilterExpressionToolBar::closeMenu);
filterMenu->popup(mapToGlobal(pos));
}
void FilterExpressionToolBar::filterExpressionsChanged()
{
struct filter_expression_data data;
data.toolbar = this;
data.actions_added = false;
// Hiding and showing seems to be the only way to get the layout to
// work correctly in some cases. See bug 14121 for details.
clear();
setUpdatesEnabled(false);
hide();
// XXX Add a context menu for removing and changing buttons.
filter_expression_iterate_expressions(filter_expression_add_action, &data);
show();
setUpdatesEnabled(true);
}
void FilterExpressionToolBar::removeFilter()
{
UatModel * uatModel = new UatModel(this, "Display expressions");
QString label = ((QAction *)sender())->property(dfe_property_label_).toString();
QString expr = ((QAction *)sender())->property(dfe_property_expression_).toString();
int idx = uatRowIndexForFilter(label, expr);
QModelIndex rowIndex = uatModel->index(idx, 0);
if (rowIndex.isValid()) {
uatModel->removeRow(rowIndex.row());
save_migrated_uat("Display expressions", &prefs.filter_expressions_old);
filterExpressionsChanged();
}
}
WiresharkMimeData * FilterExpressionToolBar::createMimeData(QString name, int position)
{
ToolbarEntryMimeData * element = new ToolbarEntryMimeData(name, position);
UatModel * uatModel = new UatModel(this, "Display expressions");
QModelIndex rowIndex;
for (int cnt = 0; cnt < uatModel->rowCount() && ! rowIndex.isValid(); cnt++)
{
if (uatModel->data(uatModel->index(cnt, 1), Qt::DisplayRole).toString().compare(name) == 0)
{
rowIndex = uatModel->index(cnt, 2);
element->setFilter(rowIndex.data().toString());
}
}
return element;
}
void FilterExpressionToolBar::onActionMoved(QAction* action, int oldPos, int newPos)
{
gchar* err = NULL;
if (oldPos == newPos)
return;
QString label = action->property(dfe_property_label_).toString();
QString expr = action->property(dfe_property_expression_).toString();
int idx = uatRowIndexForFilter(label, expr);
if (idx > -1 && oldPos > -1 && newPos > -1)
{
uat_t * table = uat_get_table_by_name("Display expressions");
uat_move_index(table, oldPos, newPos);
uat_save(table, &err);
g_free(err);
}
}
void FilterExpressionToolBar::disableFilter()
{
QString label = ((QAction *)sender())->property(dfe_property_label_).toString();
QString expr = ((QAction *)sender())->property(dfe_property_expression_).toString();
int idx = uatRowIndexForFilter(label, expr);
UatModel * uatModel = new UatModel(this, "Display expressions");
QModelIndex rowIndex = uatModel->index(idx, 0);
if (rowIndex.isValid()) {
uatModel->setData(rowIndex, QVariant::fromValue(false));
save_migrated_uat("Display expressions", &prefs.filter_expressions_old);
filterExpressionsChanged();
}
}
void FilterExpressionToolBar::editFilter()
{
if (! sender())
return;
QString label = ((QAction *)sender())->property(dfe_property_label_).toString();
QString expr = ((QAction *)sender())->property(dfe_property_expression_).toString();
int idx = uatRowIndexForFilter(label, expr);
if (idx > -1)
emit filterEdit(idx);
}
void FilterExpressionToolBar::onFilterDropped(QString description, QString filter)
{
if (filter.length() == 0)
return;
filter_expression_new(qUtf8Printable(description),
qUtf8Printable(filter), qUtf8Printable(description), TRUE);
save_migrated_uat("Display expressions", &prefs.filter_expressions_old);
filterExpressionsChanged();
}
void FilterExpressionToolBar::toolBarShowPreferences()
{
emit filterPreferences();
}
void FilterExpressionToolBar::updateStyleSheet()
{
// Try to draw 1-pixel-wide separator lines from the button label
// ascent to its baseline.
setStyleSheet(QString(
"QToolBar { background: none; border: none; spacing: 1px; }"
"QFrame { background: none; min-width: 1px; max-width: 1px; }"
));
}
int FilterExpressionToolBar::uatRowIndexForFilter(QString label, QString expression)
{
int result = -1;
if (expression.length() == 0)
return result;
UatModel * uatModel = new UatModel(this, "Display expressions");
QModelIndex rowIndex;
if (label.length() > 0)
{
for (int cnt = 0; cnt < uatModel->rowCount() && ! rowIndex.isValid(); cnt++)
{
if (uatModel->data(uatModel->index(cnt, 1), Qt::DisplayRole).toString().compare(label) == 0 &&
uatModel->data(uatModel->index(cnt, 2), Qt::DisplayRole).toString().compare(expression) == 0)
{
rowIndex = uatModel->index(cnt, 2);
}
}
}
else
{
rowIndex = uatModel->findRowForColumnContent(((QAction *)sender())->data(), 2);
}
if (rowIndex.isValid())
result = rowIndex.row();
delete uatModel;
return result;
}
bool FilterExpressionToolBar::eventFilter(QObject *obj, QEvent *event)
{
QMenu * qm = qobject_cast<QMenu *>(obj);
if (qm && qm->property(dfe_menu_).toBool())
{
if (event->type() == QEvent::ContextMenu)
{
QContextMenuEvent *ctx = static_cast<QContextMenuEvent *>(event);
QAction * filterAction = qm->actionAt(ctx->pos());
if (filterAction)
customMenu(this, filterAction, ctx->pos());
return true;
}
else if (event->type() == QEvent::ToolTip)
{
QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
QAction * filterAction = qm->actionAt(helpEvent->pos());
if (filterAction) {
QToolTip::showText(helpEvent->globalPos(), filterAction->property(dfe_property_comment_).toString().trimmed());
} else {
QToolTip::hideText();
event->ignore();
}
return true;
}
}
return QToolBar::eventFilter(obj, event);
}
void FilterExpressionToolBar::closeMenu(QAction * /*sender*/)
{
foreach(QAction * entry, actions())
{
QWidget * widget = widgetForAction(entry);
QToolButton * tb = qobject_cast<QToolButton *>(widget);
if (tb && tb->menu())
tb->menu()->close();
}
}
QMenu * FilterExpressionToolBar::findParentMenu(const QStringList tree, void *fed_data, QMenu *parent )
{
if (!fed_data)
return Q_NULLPTR;
struct filter_expression_data* data = (filter_expression_data*)fed_data;
if (!data->toolbar)
return Q_NULLPTR;
if (! tree.isEmpty())
{
if (!parent)
{
/* Searching existing main menus */
foreach(QAction * entry, data->toolbar->actions())
{
QWidget * widget = data->toolbar->widgetForAction(entry);
QToolButton * tb = qobject_cast<QToolButton *>(widget);
if (tb && tb->menu() && tb->text().compare(tree.at(0).trimmed()) == 0)
return findParentMenu(tree.mid(1), fed_data, tb->menu());
}
}
else if (parent)
{
QString menuName = tree.at(0).trimmed();
/* Iterate to see, if we next have to jump into another submenu */
foreach(QAction *entry, parent->actions())
{
if (entry->menu() && entry->text().compare(menuName) == 0)
return findParentMenu(tree.mid(1), fed_data, entry->menu());
}
/* Submenu not found, creating */
QMenu * subMenu = new QMenu(menuName);
subMenu->installEventFilter(data->toolbar);
subMenu->setProperty(dfe_menu_, QVariant::fromValue(true));
parent->addMenu(subMenu);
return findParentMenu(tree.mid(1), fed_data, subMenu);
}
/* No menu has been found, create one */
QString parentName = tree.at(0).trimmed();
QToolButton * menuButton = new QToolButton();
menuButton->setText(parentName);
menuButton->setPopupMode(QToolButton::MenuButtonPopup);
QMenu * parentMenu = new QMenu(menuButton);
parentMenu->installEventFilter(data->toolbar);
parentMenu->setProperty(dfe_menu_, QVariant::fromValue(true));
menuButton->setMenu(parentMenu);
// Required for QToolButton::MenuButtonPopup.
connect(menuButton, &QToolButton::pressed, menuButton, &QToolButton::showMenu);
data->toolbar->addWidget(menuButton);
return findParentMenu(tree.mid(1), fed_data, parentMenu);
}
else if (parent)
return parent;
return Q_NULLPTR;
}
bool FilterExpressionToolBar::filter_expression_add_action(const void *key _U_, void *value, void *user_data)
{
filter_expression_t* fe = (filter_expression_t*)value;
struct filter_expression_data* data = (filter_expression_data*)user_data;
if (!fe->enabled)
return FALSE;
QString label = QString(fe->label);
/* Search for parent menu and create if not found */
QStringList tree = label.split(PARENT_SEPARATOR);
if (!tree.isEmpty())
tree.removeLast();
QMenu * parentMenu = findParentMenu(tree, data);
if (parentMenu)
label = label.mid(label.lastIndexOf(PARENT_SEPARATOR) + QString(PARENT_SEPARATOR).length()).trimmed();
QAction *dfb_action = new QAction(label, data->toolbar);
if (strlen(fe->comment) > 0)
{
QString tooltip = QString("%1\n%2").arg(fe->comment).arg(fe->expression);
dfb_action->setToolTip(tooltip);
dfb_action->setProperty(dfe_property_comment_, tooltip);
}
else
{
dfb_action->setToolTip(fe->expression);
dfb_action->setProperty(dfe_property_comment_, QString(fe->expression));
}
dfb_action->setData(QString::fromUtf8(fe->expression));
dfb_action->setProperty(dfe_property_, true);
dfb_action->setProperty(dfe_property_label_, QString(fe->label));
dfb_action->setProperty(dfe_property_expression_, QString(fe->expression));
if (data->actions_added) {
QFrame *sep = new QFrame();
sep->setEnabled(false);
data->toolbar->addWidget(sep);
}
if (parentMenu)
parentMenu->addAction(dfb_action);
else
data->toolbar->addAction(dfb_action);
connect(dfb_action, &QAction::triggered, data->toolbar, &FilterExpressionToolBar::filterClicked);
data->actions_added = true;
return FALSE;
}
void FilterExpressionToolBar::filterClicked()
{
bool prepare = false;
QAction *dfb_action = qobject_cast<QAction*>(sender());
if (!dfb_action)
return;
QString filterText = dfb_action->data().toString();
prepare = (QApplication::keyboardModifiers() & Qt::ShiftModifier);
emit filterSelected(filterText, prepare);
} |
C/C++ | wireshark/ui/qt/widgets/filter_expression_toolbar.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/drag_drop_toolbar.h>
#include <glib.h>
#include <QMenu>
#ifndef FILTER_EXPRESSION_TOOLBAR_H
#define FILTER_EXPRESSION_TOOLBAR_H
class FilterExpressionToolBar : public DragDropToolBar
{
Q_OBJECT
public:
explicit FilterExpressionToolBar(QWidget * parent = Q_NULLPTR);
protected:
virtual bool event(QEvent *event) override;
virtual bool eventFilter(QObject *obj, QEvent *ev) override;
virtual WiresharkMimeData * createMimeData(QString name, int position) override;
public slots:
void filterExpressionsChanged();
signals:
void filterSelected(QString, bool);
void filterPreferences();
void filterEdit(int uatIndex);
protected slots:
void onCustomMenuHandler(const QPoint &pos);
void onActionMoved(QAction * action, int oldPos, int newPos);
void onFilterDropped(QString description, QString filter);
private slots:
void removeFilter();
void disableFilter();
void editFilter();
void filterClicked();
void toolBarShowPreferences();
void closeMenu(QAction *);
private:
void updateStyleSheet();
int uatRowIndexForFilter(QString label, QString expression);
void customMenu(FilterExpressionToolBar * target, QAction * filterAction, const QPoint& pos);
static bool filter_expression_add_action(const void *key, void *value, void *user_data);
static QMenu * findParentMenu(const QStringList tree, void *fed_data, QMenu *parent = Q_NULLPTR);
};
#endif //FILTER_EXPRESSION_TOOLBAR_H |
C++ | wireshark/ui/qt/widgets/find_line_edit.cpp | /* find_line_edit.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/find_line_edit.h>
#include <ui/qt/utils/color_utils.h>
#include "epan/prefs.h"
#include <QAction>
#include <QKeyEvent>
#include <QMenu>
#include <QRegularExpression>
void FindLineEdit::contextMenuEvent(QContextMenuEvent *event)
{
QMenu *menu = createStandardContextMenu();
QAction *action;
menu->setAttribute(Qt::WA_DeleteOnClose);
menu->addSeparator();
action = menu->addAction(tr("Textual Find"));
action->setCheckable(true);
action->setChecked(!use_regex_);
connect(action, &QAction::triggered, this, &FindLineEdit::setUseTextual);
action = menu->addAction(tr("Regular Expression Find"));
action->setCheckable(true);
action->setChecked(use_regex_);
connect(action, &QAction::triggered, this, &FindLineEdit::setUseRegex);
menu->popup(event->globalPos());
}
void FindLineEdit::keyPressEvent(QKeyEvent *event)
{
QLineEdit::keyPressEvent(event);
if (use_regex_) {
validateText();
}
}
void FindLineEdit::validateText()
{
QString style("QLineEdit { background-color: %1; }");
if (!use_regex_ || text().isEmpty()) {
setStyleSheet(style.arg(QString("")));
} else {
QRegularExpression regexp(text(), QRegularExpression::UseUnicodePropertiesOption);
if (regexp.isValid()) {
setStyleSheet(style.arg(ColorUtils::fromColorT(prefs.gui_text_valid).name()));
} else {
setStyleSheet(style.arg(ColorUtils::fromColorT(prefs.gui_text_invalid).name()));
}
}
}
void FindLineEdit::setUseTextual()
{
use_regex_ = false;
validateText();
emit useRegexFind(use_regex_);
}
void FindLineEdit::setUseRegex()
{
use_regex_ = true;
validateText();
emit useRegexFind(use_regex_);
} |
C/C++ | wireshark/ui/qt/widgets/find_line_edit.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef FIND_LINE_EDIT_H
#define FIND_LINE_EDIT_H
#include <QLineEdit>
namespace Ui {
class FindLineEdit;
}
class FindLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit FindLineEdit(QWidget *parent = 0) : QLineEdit(parent), use_regex_(false) { }
~FindLineEdit() { }
signals:
void useRegexFind(bool);
private slots:
void setUseTextual();
void setUseRegex();
private:
void contextMenuEvent(QContextMenuEvent *event);
void keyPressEvent(QKeyEvent *event);
void validateText();
bool use_regex_;
};
#endif // FIND_LINE_EDIT_H |
C++ | wireshark/ui/qt/widgets/follow_stream_text.cpp | /* follow_stream_text.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/follow_stream_text.h>
#include <main_application.h>
#include <QMouseEvent>
#include <QTextCursor>
// To do:
// - Draw text by hand similar to ByteViewText. This would let us add
// extra information, e.g. a timestamp column and get rid of
// max_document_length_ in FollowStreamDialog.
FollowStreamText::FollowStreamText(QWidget *parent) :
QPlainTextEdit(parent)
{
setMouseTracking(true);
// setMaximumBlockCount(1);
QTextDocument *text_doc = document();
text_doc->setDefaultFont(mainApp->monospaceFont());
}
void FollowStreamText::mouseMoveEvent(QMouseEvent *event)
{
emit mouseMovedToTextCursorPosition(cursorForPosition(event->pos()).position());
QPlainTextEdit::mouseMoveEvent(event);
}
void FollowStreamText::mousePressEvent(QMouseEvent *event)
{
emit mouseClickedOnTextCursorPosition(cursorForPosition(event->pos()).position());
QPlainTextEdit::mousePressEvent(event);
}
void FollowStreamText::leaveEvent(QEvent *event)
{
emit mouseMovedToTextCursorPosition(-1);
QPlainTextEdit::leaveEvent(event);
} |
C/C++ | wireshark/ui/qt/widgets/follow_stream_text.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef FOLLOW_STREAM_TEXT_H
#define FOLLOW_STREAM_TEXT_H
#include <QPlainTextEdit>
class FollowStreamText : public QPlainTextEdit
{
Q_OBJECT
public:
explicit FollowStreamText(QWidget *parent = 0);
protected:
void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
void leaveEvent(QEvent *event);
signals:
// Perhaps this is not descriptive enough. We should add more words.
void mouseMovedToTextCursorPosition(int);
void mouseClickedOnTextCursorPosition(int);
public slots:
};
#endif // FOLLOW_STREAM_TEXT_H |
C++ | wireshark/ui/qt/widgets/interface_toolbar_lineedit.cpp | /* interface_toolbar_lineedit.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <ui/qt/widgets/interface_toolbar_lineedit.h>
#include <ui/qt/widgets/stock_icon_tool_button.h>
#include "epan/prefs.h"
#include <ui/qt/utils/color_utils.h>
#include <QStyle>
// To do:
// - Make a narrower apply button
InterfaceToolbarLineEdit::InterfaceToolbarLineEdit(QWidget *parent, QString validation_regex, bool is_required) :
QLineEdit(parent),
regex_expr_(validation_regex, QRegularExpression::UseUnicodePropertiesOption),
is_required_(is_required),
text_edited_(false)
{
apply_button_ = new StockIconToolButton(this, "x-filter-apply");
apply_button_->setCursor(Qt::ArrowCursor);
apply_button_->setEnabled(false);
apply_button_->setToolTip(tr("Apply changes"));
apply_button_->setIconSize(QSize(24, 14));
apply_button_->setStyleSheet(
"QToolButton {"
" border: none;"
" background: transparent;" // Disables platform style on Windows.
" padding: 0 0 0 0;"
"}"
);
updateStyleSheet(isValid());
connect(this, &InterfaceToolbarLineEdit::textChanged, this, &InterfaceToolbarLineEdit::validateText);
connect(this, &InterfaceToolbarLineEdit::textEdited, this, &InterfaceToolbarLineEdit::validateEditedText);
connect(this, &InterfaceToolbarLineEdit::returnPressed, this, &InterfaceToolbarLineEdit::applyEditedText);
connect(apply_button_, &StockIconToolButton::clicked, this, &InterfaceToolbarLineEdit::applyEditedText);
}
void InterfaceToolbarLineEdit::validateText()
{
bool valid = isValid();
apply_button_->setEnabled(valid);
updateStyleSheet(valid);
}
void InterfaceToolbarLineEdit::validateEditedText()
{
text_edited_ = true;
}
void InterfaceToolbarLineEdit::applyEditedText()
{
if (text_edited_ && isValid())
{
emit editedTextApplied();
disableApplyButton();
}
}
void InterfaceToolbarLineEdit::disableApplyButton()
{
apply_button_->setEnabled(false);
text_edited_ = false;
}
bool InterfaceToolbarLineEdit::isValid()
{
bool valid = true;
if (is_required_ && text().length() == 0)
{
valid = false;
}
if (!regex_expr_.pattern().isEmpty() && text().length() > 0)
{
if (!regex_expr_.isValid() || !regex_expr_.match(text()).hasMatch())
{
valid = false;
}
}
return valid;
}
void InterfaceToolbarLineEdit::updateStyleSheet(bool is_valid)
{
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
QSize apsz = apply_button_->sizeHint();
QString style_sheet = QString(
"InterfaceToolbarLineEdit {"
" padding-right: %1px;"
" background-color: %2;"
"}"
)
.arg(apsz.width() + frameWidth)
.arg(is_valid || !isEnabled() ? QString("") : ColorUtils::fromColorT(prefs.gui_text_invalid).name());
setStyleSheet(style_sheet);
}
void InterfaceToolbarLineEdit::resizeEvent(QResizeEvent *)
{
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
QSize apsz = apply_button_->sizeHint();
apply_button_->move(contentsRect().right() - frameWidth - apsz.width() + 2,
contentsRect().top());
apply_button_->setMinimumHeight(contentsRect().height());
apply_button_->setMaximumHeight(contentsRect().height());
} |
C/C++ | wireshark/ui/qt/widgets/interface_toolbar_lineedit.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef INTERFACE_TOOLBAR_LINEEDIT_H
#define INTERFACE_TOOLBAR_LINEEDIT_H
#include <QLineEdit>
#include <QRegularExpression>
class StockIconToolButton;
class InterfaceToolbarLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit InterfaceToolbarLineEdit(QWidget *parent = 0, QString validation_regex = QString(), bool is_required = false);
void disableApplyButton();
protected:
void resizeEvent(QResizeEvent *);
signals:
void editedTextApplied();
private slots:
void validateText();
void validateEditedText();
void applyEditedText();
private:
bool isValid();
void updateStyleSheet(bool is_valid);
StockIconToolButton *apply_button_;
QRegularExpression regex_expr_;
bool is_required_;
bool text_edited_;
};
#endif // INTERFACE_TOOLBAR_LINEEDIT_H |
C++ | wireshark/ui/qt/widgets/label_stack.cpp | /* label_stack.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/label_stack.h>
#include <QContextMenuEvent>
#include <QPainter>
#include <QMouseEvent>
#include <QStyleOption>
#include <ui/qt/utils/color_utils.h>
/* Temporary message timeouts */
const int temporary_interval_ = 1000;
const int temporary_msg_timeout_ = temporary_interval_ * 9;
const int temporary_flash_timeout_ = temporary_interval_ / 5;
const int num_flashes_ = 3;
LabelStack::LabelStack(QWidget *parent) :
QLabel(parent),
temporary_ctx_(-1),
shrinkable_(false)
{
#ifdef Q_OS_MAC
setAttribute(Qt::WA_MacSmallSize, true);
#endif
fillLabel();
connect(&temporary_timer_, &QTimer::timeout, this, &LabelStack::updateTemporaryStatus);
}
void LabelStack::setTemporaryContext(const int ctx) {
temporary_ctx_ = ctx;
}
void LabelStack::fillLabel() {
StackItem si;
QString style_sheet;
style_sheet =
"QLabel {"
" margin-left: 0.5em;";
if (labels_.isEmpty()) {
clear();
return;
}
si = labels_.first();
if (si.ctx == temporary_ctx_) {
style_sheet += QString(
" border-radius: 0.25em;"
" background-color: %2;"
)
.arg(ColorUtils::warningBackground().name());
}
style_sheet += "}";
if (styleSheet().size() != style_sheet.size()) {
// Can be computationally expensive.
setStyleSheet(style_sheet);
}
setText(si.text);
}
void LabelStack::pushText(const QString &text, int ctx) {
popText(ctx);
if (ctx == temporary_ctx_) {
temporary_timer_.stop();
temporary_epoch_.start();
temporary_timer_.start(temporary_flash_timeout_);
emit toggleTemporaryFlash(true);
}
StackItem si;
si.text = text;
si.ctx = ctx;
labels_.prepend(si);
fillLabel();
}
void LabelStack::setShrinkable(bool shrinkable)
{
shrinkable_ = shrinkable;
int min_width = 0;
if (shrinkable) {
min_width = fontMetrics().height() * 5; // em-widths
}
setMinimumWidth(min_width);
fillLabel();
}
void LabelStack::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
emit mousePressedAt(event->globalPosition().toPoint(), Qt::LeftButton);
#else
emit mousePressedAt(event->globalPos(), Qt::LeftButton);
#endif
}
}
void LabelStack::mouseReleaseEvent(QMouseEvent *)
{
}
void LabelStack::mouseDoubleClickEvent(QMouseEvent *)
{
}
void LabelStack::mouseMoveEvent(QMouseEvent *)
{
}
void LabelStack::contextMenuEvent(QContextMenuEvent *event)
{
emit mousePressedAt(QPoint(event->globalPos()), Qt::RightButton);
}
void LabelStack::paintEvent(QPaintEvent *event)
{
if (!shrinkable_) {
QLabel::paintEvent(event);
return;
}
QFrame::paintEvent(event);
QString elided_text = fontMetrics().elidedText(text(), Qt::ElideMiddle, width());
QPainter painter(this);
QRect contents_rect = contentsRect();
QStyleOption opt;
contents_rect.adjust(margin(), margin(), -margin(), -margin());
opt.initFrom(this);
style()->drawItemText(&painter, contents_rect, alignment(), opt.palette,
isEnabled(), elided_text, foregroundRole());
}
void LabelStack::popText(int ctx) {
QMutableListIterator<StackItem> iter(labels_);
while (iter.hasNext()) {
if (iter.next().ctx == ctx) {
iter.remove();
break;
}
}
fillLabel();
}
void LabelStack::updateTemporaryStatus() {
if (temporary_epoch_.elapsed() >= temporary_msg_timeout_) {
popText(temporary_ctx_);
emit toggleTemporaryFlash(false);
temporary_timer_.stop();
} else {
for (int i = (num_flashes_ * 2); i > 0; i--) {
if (temporary_epoch_.elapsed() >= temporary_flash_timeout_ * i) {
emit toggleTemporaryFlash(i % 2);
break;
}
}
}
} |
C/C++ | wireshark/ui/qt/widgets/label_stack.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef LABEL_STACK_H
#define LABEL_STACK_H
#include <QLabel>
#include <QStack>
#include <QElapsedTimer>
#include <QTimer>
class LabelStack : public QLabel
{
Q_OBJECT
public:
explicit LabelStack(QWidget *parent = 0);
void setTemporaryContext(const int ctx);
void pushText(const QString &text, int ctx);
void setShrinkable(bool shrinkable = true);
protected:
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseDoubleClickEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void contextMenuEvent(QContextMenuEvent *event);
void paintEvent (QPaintEvent *event);
private:
typedef struct _StackItem {
QString text;
int ctx;
} StackItem;
int temporary_ctx_;
QList<StackItem> labels_;
bool shrinkable_;
QElapsedTimer temporary_epoch_;
QTimer temporary_timer_;
void fillLabel();
signals:
void toggleTemporaryFlash(bool enable);
void mousePressedAt(const QPoint &global_pos, Qt::MouseButton button);
public slots:
void popText(int ctx);
private slots:
void updateTemporaryStatus();
};
#endif // LABEL_STACK_H |
C++ | wireshark/ui/qt/widgets/overlay_scroll_bar.cpp | /* overlay_scroll_bar.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/overlay_scroll_bar.h>
#include <ui/qt/utils/color_utils.h>
#include <QMouseEvent>
#include <QPainter>
#include <QResizeEvent>
#include <QStyleOptionSlider>
// To do:
// - We could graph something useful (e.g. delay times) in packet_map_img_.
// https://www.wireshark.org/lists/ethereal-dev/200011/msg00122.html
// - Properly handle transience.
// We want a normal scrollbar with space on either side on which we can draw
// and receive mouse events. Adding space using a stylesheet loses native
// styling on Windows. Overriding QProxyStyle::drawComplexControl (which is
// called by QScrollBar::paintEvent) results in odd behavior on Windows.
//
// The best solution so far seems to be to simply create a normal-sized child
// scrollbar, manually position it, and synchronize it with its parent. We
// can then alter the parent's mouse and paint behavior to our heart's
// content.
class OsbProxyStyle : public QProxyStyle
{
public:
// Disable transient behavior. Mainly for macOS but possibly applies to
// other platforms. If we want to enable transience we'll have to
// handle the following at a minimum:
//
// setProperty("visible") from QScrollbarStyleAnimation.
// Other visibility changes.
// HoverEnter & HoverLeave events from QAbstractScrollArea.
// Size (and possibly opacity) changes while painting.
//
// Another approach would be to flip the child-parent relationship
// and make the parent a normal scroll bar with a manually-placed
// packet map child. This might make the packet list geometry a bit
// wonky, however.
virtual int styleHint(StyleHint hint, const QStyleOption *option = NULL, const QWidget *widget = NULL, QStyleHintReturn *returnData = NULL) const {
if (hint == SH_ScrollBar_Transient) return false;
return QProxyStyle::styleHint(hint, option, widget, returnData);
}
};
OverlayScrollBar::OverlayScrollBar(Qt::Orientation orientation, QWidget *parent) :
QScrollBar(orientation, parent),
child_sb_(orientation, this),
packet_map_img_(QImage()),
packet_map_width_(0),
marked_packet_width_(0),
packet_count_(-1),
start_pos_(-1),
end_pos_(-1),
positions_(QList<int>())
{
style_ = new OsbProxyStyle();
setStyle(style_);
child_style_ = new OsbProxyStyle();
child_sb_.raise();
child_sb_.installEventFilter(this);
child_sb_.setStyle(child_style_);
// XXX Do we need to connect anything else?
connect(this, &OverlayScrollBar::rangeChanged, this, &OverlayScrollBar::setChildRange);
connect(this, &OverlayScrollBar::valueChanged, &child_sb_, &QScrollBar::setValue);
connect(&child_sb_, &QScrollBar::valueChanged, this, &OverlayScrollBar::setValue);
connect(&child_sb_, &QScrollBar::actionTriggered, this, &OverlayScrollBar::actionTriggered);
}
OverlayScrollBar::~OverlayScrollBar()
{
delete child_style_;
delete style_;
}
QSize OverlayScrollBar::sizeHint() const
{
return QSize(packet_map_width_ + child_sb_.sizeHint().width(),
QScrollBar::sizeHint().height());
}
int OverlayScrollBar::sliderPosition()
{
return child_sb_.sliderPosition();
}
void OverlayScrollBar::setNearOverlayImage(QImage& overlay_image, int packet_count, int start_pos, int end_pos, QList<int> positions, int rowHeight)
{
int old_width = packet_map_img_.width();
packet_map_img_ = overlay_image;
packet_count_ = packet_count;
start_pos_ = start_pos;
end_pos_ = end_pos;
positions_ = positions;
row_height_ = rowHeight > devicePixelRatio() ? rowHeight : devicePixelRatio();
if (old_width != packet_map_img_.width()) {
qreal dp_ratio = devicePixelRatio();
packet_map_width_ = packet_map_img_.width() / dp_ratio;
updateGeometry();
}
update();
}
void OverlayScrollBar::setMarkedPacketImage(QImage &mp_image)
{
qreal dp_ratio = devicePixelRatio();
marked_packet_img_ = mp_image;
marked_packet_width_ = mp_image.width() / dp_ratio;
child_sb_.update();
}
QRect OverlayScrollBar::grooveRect()
{
QStyleOptionSlider opt;
initStyleOption(&opt);
opt.rect = child_sb_.rect();
return child_sb_.style()->subControlRect(QStyle::CC_ScrollBar, &opt, QStyle::SC_ScrollBarGroove, &child_sb_);
}
void OverlayScrollBar::resizeEvent(QResizeEvent *event)
{
QScrollBar::resizeEvent(event);
child_sb_.move(packet_map_width_, 0);
child_sb_.resize(child_sb_.sizeHint().width(), height());
#ifdef Q_OS_MAC
child_sb_.setPageStep(height());
#endif
}
void OverlayScrollBar::paintEvent(QPaintEvent *event)
{
qreal dp_ratio = devicePixelRatio();
QSize pm_size(packet_map_width_, geometry().height());
pm_size *= dp_ratio;
QPainter painter(this);
painter.fillRect(event->rect(), palette().base());
if (!packet_map_img_.isNull()) {
QImage packet_map(pm_size, QImage::Format_ARGB32_Premultiplied);
packet_map.fill(Qt::transparent);
// Draw the image supplied by the packet list.
QPainter pm_painter(&packet_map);
pm_painter.setPen(Qt::NoPen);
QRect near_dest(0, 0, pm_size.width(), pm_size.height());
pm_painter.drawImage(near_dest, packet_map_img_.scaled(near_dest.size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
// Selected packet indicator
if (positions_.count() > 0)
{
foreach (int selected_pos_, positions_)
{
int pmiHeight = packet_map_img_.height();
if (selected_pos_ >= 0 && selected_pos_ < pmiHeight) {
pm_painter.save();
int no_pos = near_dest.height() * selected_pos_ / pmiHeight;
pm_painter.setBrush(palette().highlight().color());
pm_painter.drawRect(0, no_pos, pm_size.width(), row_height_);
pm_painter.restore();
}
}
}
// Borders
pm_painter.save();
QColor border_color(ColorUtils::alphaBlend(palette().text(), palette().window(), 0.25));
pm_painter.setPen(border_color);
pm_painter.drawLine(near_dest.topLeft(), near_dest.bottomLeft());
pm_painter.drawLine(near_dest.topRight(), near_dest.bottomRight());
pm_painter.drawLine(near_dest.bottomLeft(), near_dest.bottomRight());
pm_painter.restore();
// Draw the map.
packet_map.setDevicePixelRatio(dp_ratio);
painter.drawImage(0, 0, packet_map);
}
}
bool OverlayScrollBar::eventFilter(QObject *watched, QEvent *event)
{
bool ret = false;
if (watched == &child_sb_ && event->type() == QEvent::Paint) {
// Paint the scrollbar first.
child_sb_.event(event);
ret = true;
if (!marked_packet_img_.isNull()) {
QRect groove_rect = grooveRect();
qreal dp_ratio = devicePixelRatio();
groove_rect.setTopLeft(groove_rect.topLeft() * dp_ratio);
groove_rect.setSize(groove_rect.size() * dp_ratio);
QImage marked_map(groove_rect.width(), groove_rect.height(), QImage::Format_ARGB32_Premultiplied);
marked_map.fill(Qt::transparent);
QPainter mm_painter(&marked_map);
mm_painter.setPen(Qt::NoPen);
QRect far_dest(0, 0, groove_rect.width(), groove_rect.height());
mm_painter.drawImage(far_dest, marked_packet_img_.scaled(far_dest.size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
marked_map.setDevicePixelRatio(dp_ratio);
QPainter painter(&child_sb_);
painter.drawImage(groove_rect.left(), groove_rect.top(), marked_map);
}
}
return ret;
}
void OverlayScrollBar::mouseReleaseEvent(QMouseEvent *event)
{
QRect pm_r(0, 0, packet_map_width_, height());
if (pm_r.contains(event->pos()) && geometry().height() > 0 && packet_count_ > 0 && pageStep() > 0) {
double map_ratio = double(end_pos_ - start_pos_) / geometry().height();
int clicked_packet = (event->pos().y() * map_ratio) + start_pos_;
/* The first packet is at minimum(). The last packet is at
* maximum() + pageStep(). (maximum() corresponds to the first
* packet shown when the scrollbar at at the maximum position.)
* https://doc.qt.io/qt-6/qscrollbar.html#details
*/
double packet_to_sb_value = double(maximum() + pageStep() - minimum()) / packet_count_;
int top_pad = pageStep() / 4; // Land near, but not at, the top.
setValue((clicked_packet * packet_to_sb_value) - top_pad);
}
} |
C/C++ | wireshark/ui/qt/widgets/overlay_scroll_bar.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __OVERLAY_SCROLL_BAR_H__
#define __OVERLAY_SCROLL_BAR_H__
#include <QScrollBar>
#include <QProxyStyle>
class OverlayScrollBar : public QScrollBar
{
Q_OBJECT
public:
OverlayScrollBar(Qt::Orientation orientation, QWidget * parent = 0);
virtual ~OverlayScrollBar();
virtual QSize sizeHint() const;
virtual int sliderPosition();
/** Set the "near" overlay image.
* @param overlay_image An image containing a 1:1 mapping of nearby
* packet colors to raster lines. It should be sized in device
* pixels.
* @param packet_count Number of packets.
* @param start_pos The first packet number represented by the image.
* -1 means no packet is selected.
* @param end_pos The last packet number represented by the image. -1
* means no packet is selected.
* @param positions The positions of the selected packets within the
* image.
* @param rowHeight The row height to be used for displaying the mark
*/
void setNearOverlayImage(QImage &overlay_image, int packet_count = -1, int start_pos = -1, int end_pos = -1, QList<int> positions = QList<int>(), int rowHeight = 1);
/** Set the "far" overlay image.
* @param mp_image An image showing the position of marked, ignored,
* and reference time packets over the entire packet list. It
* should be sized in device pixels.
*/
void setMarkedPacketImage(QImage &mp_image);
/** The "groove" area of the child scrollbar.
*/
QRect grooveRect();
public slots:
void setChildRange(int min, int max) { child_sb_.setRange(min, max); }
protected:
virtual void resizeEvent(QResizeEvent * event);
virtual void paintEvent(QPaintEvent * event);
virtual bool eventFilter(QObject *watched, QEvent *event);
virtual void mousePressEvent(QMouseEvent *) { /* No-op */ }
virtual void mouseReleaseEvent(QMouseEvent * event);
private:
QProxyStyle* style_;
QProxyStyle* child_style_;
QScrollBar child_sb_;
QImage packet_map_img_;
QImage marked_packet_img_;
int packet_map_width_;
int marked_packet_width_;
int packet_count_;
int start_pos_;
int end_pos_;
QList<int> positions_;
int row_height_;
};
#endif // __OVERLAY_SCROLL_BAR_H__ |
C++ | wireshark/ui/qt/widgets/packet_list_header.cpp | /* packet_list_header.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <QDropEvent>
#include <QMimeData>
#include <QToolTip>
#include <QAction>
#include <QInputDialog>
#include <QJsonDocument>
#include <QJsonObject>
#include <packet_list.h>
#include <main_application.h>
#include <epan/column.h>
#include <ui/recent.h>
#include <ui/preference_utils.h>
#include <ui/packet_list_utils.h>
#include <ui/qt/main_window.h>
#include <models/packet_list_model.h>
#include <models/pref_models.h>
#include <ui/qt/utils/wireshark_mime_data.h>
#include <ui/qt/widgets/packet_list_header.h>
PacketListHeader::PacketListHeader(Qt::Orientation orientation, QWidget *parent) :
QHeaderView(orientation, parent),
sectionIdx(-1)
{
setAcceptDrops(true);
setSectionsMovable(true);
setStretchLastSection(true);
setDefaultAlignment(Qt::AlignLeft|Qt::AlignVCenter);
}
void PacketListHeader::dragEnterEvent(QDragEnterEvent *event)
{
if (! event || ! event->mimeData())
return;
if (event->mimeData()->hasFormat(WiresharkMimeData::DisplayFilterMimeType) && event->source() != this->parent())
{
if (event->source() != this)
{
event->setDropAction(Qt::CopyAction);
event->accept();
} else {
event->acceptProposedAction();
}
}
else
QHeaderView::dragEnterEvent(event);
}
void PacketListHeader::dragMoveEvent(QDragMoveEvent *event)
{
if (! event || ! event->mimeData())
return;
if (event->mimeData()->hasFormat(WiresharkMimeData::DisplayFilterMimeType))
{
if (event->source() != this)
{
event->setDropAction(Qt::CopyAction);
event->accept();
} else {
event->acceptProposedAction();
}
}
else
QHeaderView::dragMoveEvent(event);
}
void PacketListHeader::dropEvent(QDropEvent *event)
{
if (! event || ! event->mimeData())
return;
/* Moving items around */
if (event->mimeData()->hasFormat(WiresharkMimeData::DisplayFilterMimeType))
{
QByteArray jsonData = event->mimeData()->data(WiresharkMimeData::DisplayFilterMimeType);
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData);
if (! jsonDoc.isObject())
return;
QJsonObject data = jsonDoc.object();
if ( event->source() != this && data.contains("description") && data.contains("name") )
{
event->setDropAction(Qt::CopyAction);
event->accept();
MainWindow * mw = qobject_cast<MainWindow *>(mainApp->mainWindow());
if (mw)
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
int idx = logicalIndexAt(event->position().toPoint());
#else
int idx = logicalIndexAt(event->pos());
#endif
mw->insertColumn(data["description"].toString(), data["name"].toString(), idx);
}
} else {
event->acceptProposedAction();
}
}
else
QHeaderView::dropEvent(event);
}
void PacketListHeader::mousePressEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton && sectionIdx < 0)
{
/* No move happening yet */
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
int sectIdx = logicalIndexAt(e->position().toPoint().x() - 4, e->position().toPoint().y());
#else
int sectIdx = logicalIndexAt(e->localPos().x() - 4, e->localPos().y());
#endif
QString headerName = model()->headerData(sectIdx, orientation()).toString();
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
QToolTip::showText(e->globalPosition().toPoint(), QString("Width: %1").arg(sectionSize(sectIdx)));
#else
QToolTip::showText(e->globalPos(), QString("Width: %1").arg(sectionSize(sectIdx)));
#endif
}
QHeaderView::mousePressEvent(e);
}
void PacketListHeader::mouseMoveEvent(QMouseEvent *e)
{
if (e->button() == Qt::NoButton || ! (e->buttons() & Qt::LeftButton))
{
/* no move is happening */
sectionIdx = -1;
}
else if (e->buttons() & Qt::LeftButton)
{
/* section being moved */
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
int triggeredSection = logicalIndexAt(e->position().toPoint().x() - 4, e->position().toPoint().y());
#else
int triggeredSection = logicalIndexAt(e->localPos().x() - 4, e->localPos().y());
#endif
if (sectionIdx < 0)
sectionIdx = triggeredSection;
else if (sectionIdx == triggeredSection)
{
/* Only run for the current moving section after a change */
QString headerName = model()->headerData(sectionIdx, orientation()).toString();
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
QToolTip::showText(e->globalPosition().toPoint(), QString("Width: %1").arg(sectionSize(sectionIdx)));
#else
QToolTip::showText(e->globalPos(), QString("Width: %1").arg(sectionSize(sectionIdx)));
#endif
}
}
QHeaderView::mouseMoveEvent(e);
}
void PacketListHeader::contextMenuEvent(QContextMenuEvent *event)
{
int sectionIdx = logicalIndexAt(event->pos());
if (sectionIdx < 0 || sectionIdx >= prefs.num_cols)
return;
char xalign = recent_get_column_xalign(sectionIdx);
QAction * action = nullptr;
QMenu * contextMenu = new QMenu(this);
contextMenu->setAttribute(Qt::WA_DeleteOnClose);
contextMenu->setProperty("column", QVariant::fromValue(sectionIdx));
QActionGroup * alignmentActions = new QActionGroup(contextMenu);
alignmentActions->setExclusive(false);
alignmentActions->setProperty("column", QVariant::fromValue(sectionIdx));
action = alignmentActions->addAction(tr("Align Left"));
action->setCheckable(true);
action->setChecked(xalign == COLUMN_XALIGN_LEFT ? true : false);
action->setData(QVariant::fromValue(COLUMN_XALIGN_LEFT));
action = alignmentActions->addAction(tr("Align Center"));
action->setCheckable(true);
action->setChecked(xalign == COLUMN_XALIGN_CENTER ? true : false);
action->setData(QVariant::fromValue(COLUMN_XALIGN_CENTER));
action = alignmentActions->addAction(tr("Align Right"));
action->setCheckable(true);
action->setChecked(xalign == COLUMN_XALIGN_RIGHT ? true : false);
action->setData(QVariant::fromValue(COLUMN_XALIGN_RIGHT));
connect(alignmentActions, &QActionGroup::triggered, this, &PacketListHeader::setAlignment);
contextMenu->addActions(alignmentActions->actions());
contextMenu->addSeparator();
action = contextMenu->addAction(tr("Column Preferences…"));
connect(action, &QAction::triggered, this, &PacketListHeader::showColumnPrefs);
action = contextMenu->addAction(tr("Edit Column"));
connect(action, &QAction::triggered, this, &PacketListHeader::doEditColumn);
action = contextMenu->addAction(tr("Resize to Contents"));
connect(action, &QAction::triggered, this, &PacketListHeader::resizeToContent);
action = contextMenu->addAction(tr("Resize Column to Width…"));
connect(action, &QAction::triggered, this, &PacketListHeader::resizeToWidth);
action = contextMenu->addAction(tr("Resolve Names"));
bool canResolve = model()->headerData(sectionIdx, Qt::Horizontal, PacketListModel::HEADER_CAN_RESOLVE).toBool();
action->setEnabled(canResolve);
action->setCheckable(true);
action->setChecked(canResolve && get_column_resolved(sectionIdx));
connect(action, &QAction::triggered, this, &PacketListHeader::doResolveNames);
contextMenu->addSeparator();
for (int cnt = 0; cnt < prefs.num_cols; cnt++) {
QString title(get_column_title(cnt));
QString detail;
if (get_column_format(cnt) == COL_CUSTOM) {
detail = get_column_custom_fields(cnt);
} else {
detail = col_format_desc(get_column_format(cnt));
}
if (prefs.gui_packet_header_column_definition)
title.append(QString("\t%1").arg(detail));
QAction *action = new QAction(title, this);
action->setToolTip(detail);
action->setCheckable(true);
action->setChecked(get_column_visible(cnt));
action->setData(QVariant::fromValue(cnt));
connect(action, &QAction::triggered, this, &PacketListHeader::columnVisibilityTriggered);
contextMenu->addAction(action);
}
contextMenu->setToolTipsVisible(true);
contextMenu->addSeparator();
action = contextMenu->addAction(tr("Remove this Column"));
action->setEnabled(sectionIdx >= 0 && count() > 2);
connect(action, &QAction::triggered, this, &PacketListHeader::removeColumn);
contextMenu->popup(viewport()->mapToGlobal(event->pos()));
}
void PacketListHeader::columnVisibilityTriggered()
{
QAction *ha = qobject_cast<QAction*>(sender());
if (!ha) return;
int col = ha->data().toInt();
set_column_visible(col, ha->isChecked());
setSectionHidden(col, ha->isChecked() ? false : true);
if (ha->isChecked())
emit resetColumnWidth(col);
prefs_main_write();
}
void PacketListHeader::setAlignment(QAction *action)
{
if (!action)
return;
QActionGroup * group = action->actionGroup();
if (! group)
return;
int section = group->property("column").toInt();
if (section >= 0)
{
QChar data = action->data().toChar();
recent_set_column_xalign(section, action->isChecked() ? data.toLatin1() : COLUMN_XALIGN_DEFAULT);
emit updatePackets(false);
}
}
void PacketListHeader::showColumnPrefs()
{
emit showColumnPreferences(PrefsModel::typeToString(PrefsModel::Columns));
}
void PacketListHeader::doEditColumn()
{
QAction * action = qobject_cast<QAction *>(sender());
if (!action)
return;
QMenu * menu = qobject_cast<QMenu *>(action->parent());
if (! menu)
return;
int section = menu->property("column").toInt();
emit editColumn(section);
}
void PacketListHeader::doResolveNames()
{
QAction * action = qobject_cast<QAction *>(sender());
if (!action)
return;
QMenu * menu = qobject_cast<QMenu *>(action->parent());
if (!menu)
return;
int section = menu->property("column").toInt();
set_column_resolved(section, action->isChecked());
prefs_main_write();
emit updatePackets(true);
}
void PacketListHeader::resizeToContent()
{
QAction * action = qobject_cast<QAction *>(sender());
if (!action)
return;
QMenu * menu = qobject_cast<QMenu *>(action->parent());
if (!menu)
return;
int section = menu->property("column").toInt();
PacketList * packetList = qobject_cast<PacketList *>(parent());
if (packetList)
packetList->resizeColumnToContents(section);
}
void PacketListHeader::removeColumn()
{
QAction * action = qobject_cast<QAction *>(sender());
if (!action)
return;
QMenu * menu = qobject_cast<QMenu *>(action->parent());
if (!menu)
return;
int section = menu->property("column").toInt();
if (count() > 2) {
column_prefs_remove_nth(section);
emit columnsChanged();
prefs_main_write();
}
}
void PacketListHeader::resizeToWidth()
{
QAction * action = qobject_cast<QAction *>(sender());
if (!action)
return;
QMenu * menu = qobject_cast<QMenu *>(action->parent());
if (!menu)
return;
bool ok = false;
int width = -1;
int section = menu->property("column").toInt();
QString headerName = model()->headerData(section, orientation()).toString();
width = QInputDialog::getInt(this, tr("Column %1").arg(headerName), tr("Width:"),
sectionSize(section), 0, 1000, 1, &ok);
if (ok)
resizeSection(section, width);
} |
C/C++ | wireshark/ui/qt/widgets/packet_list_header.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef UI_QT_WIDGETS_PACKET_LIST_HEADER_H_
#define UI_QT_WIDGETS_PACKET_LIST_HEADER_H_
#include <cfile.h>
#include <QHeaderView>
#include <QDrag>
#include <QMenu>
class QEvent;
class PacketListHeader : public QHeaderView
{
Q_OBJECT
public:
PacketListHeader(Qt::Orientation orientation, QWidget *parent = nullptr);
protected:
virtual void dropEvent(QDropEvent *event) override;
virtual void dragEnterEvent(QDragEnterEvent *event) override;
virtual void dragMoveEvent(QDragMoveEvent *event) override;
virtual void mouseMoveEvent(QMouseEvent *e) override;
virtual void mousePressEvent(QMouseEvent *e) override;
virtual void contextMenuEvent(QContextMenuEvent *event) override;
protected slots:
void columnVisibilityTriggered();
void setAlignment(QAction *);
void showColumnPrefs();
void doEditColumn();
void doResolveNames();
void resizeToContent();
void removeColumn();
void resizeToWidth();
signals:
void resetColumnWidth(int col);
void updatePackets(bool redraw);
void showColumnPreferences(QString pane_name);
void editColumn(int column);
void columnsChanged();
private:
int sectionIdx;
};
#endif |
C++ | wireshark/ui/qt/widgets/path_selection_edit.cpp | /* path_chooser_delegate.cpp
* Delegate to select a file path for a treeview entry
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include "epan/prefs.h"
#include "ui/last_open_dir.h"
#include <ui/qt/widgets/path_selection_edit.h>
#include "ui/qt/widgets/wireshark_file_dialog.h"
#include <QHBoxLayout>
#include <QToolButton>
#include <QWidget>
#include <QLineEdit>
PathSelectionEdit::PathSelectionEdit(QString title, QString path, bool selectFile, QWidget *parent) :
QWidget(parent)
{
_title = title;
_path = path;
_selectFile = selectFile;
_edit = new QLineEdit(this);
_edit->setText(_path);
connect(_edit, &QLineEdit::textChanged, this, &PathSelectionEdit::setPath);
_button = new QToolButton(this);
_button->setText(tr("Browse"));
connect(_button, &QToolButton::clicked, this, &PathSelectionEdit::browseForPath);
setContentsMargins(0, 0, 0, 0);
QHBoxLayout *hbox = new QHBoxLayout(this);
hbox->setContentsMargins(0, 0, 0, 0);
hbox->addWidget(_edit);
hbox->addWidget(_button);
hbox->setSizeConstraint(QLayout::SetMinimumSize);
setLayout(hbox);
setFocusProxy(_edit);
setFocusPolicy(_edit->focusPolicy());
}
PathSelectionEdit::PathSelectionEdit(QWidget *parent) :
PathSelectionEdit(tr("Select a path"), QString(), true, parent)
{}
void PathSelectionEdit::setPath(QString newPath)
{
_path = newPath;
if (!sender()) {
_edit->blockSignals(true);
_edit->setText(newPath);
_edit->blockSignals(false);
} else {
emit pathChanged(newPath);
}
}
QString PathSelectionEdit::path() const
{
return _path;
}
void PathSelectionEdit::browseForPath()
{
QString openDir = _path;
if (openDir.isEmpty()) {
if (prefs.gui_fileopen_style == FO_STYLE_LAST_OPENED) {
openDir = QString(get_last_open_dir());
} else if (prefs.gui_fileopen_style == FO_STYLE_SPECIFIED) {
openDir = QString(prefs.gui_fileopen_dir);
}
}
QString newPath;
if ( _selectFile )
newPath = WiresharkFileDialog::getOpenFileName(this, _title, openDir);
else
newPath = WiresharkFileDialog::getExistingDirectory(this, _title, openDir);
if (!newPath.isEmpty()) {
_edit->setText(newPath);
}
} |
C/C++ | wireshark/ui/qt/widgets/path_selection_edit.h | /* path_chooser_delegate.cpp
* Delegate to select a file path for a treeview entry
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PATH_SELECTOR_EDIT_H
#define PATH_SELECTOR_EDIT_H
#include <QWidget>
#include <QString>
#include <QLineEdit>
#include <QToolButton>
class PathSelectionEdit : public QWidget
{
Q_OBJECT
public:
PathSelectionEdit(QString title, QString path, bool selectFile, QWidget *parent = 0);
PathSelectionEdit(QWidget *parent = 0);
QString path() const;
public slots:
void setPath(QString newPath = QString());
signals:
void pathChanged(QString newPath);
protected slots:
void browseForPath();
private:
QString _title;
QString _path;
bool _selectFile;
QLineEdit * _edit;
QToolButton * _button;
};
#endif // PATH_SELECTOR_EDIT_H |
C++ | wireshark/ui/qt/widgets/pref_module_view.cpp | /* pref_module_view.cpp
* Tree view of preference module data.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "pref_module_view.h"
#include <ui/qt/models/pref_models.h>
#include <QHeaderView>
PrefModuleTreeView::PrefModuleTreeView(QWidget *parent) : QTreeView(parent),
appearanceName_(PrefsModel::typeToString(PrefsModel::Appearance))
{
}
void PrefModuleTreeView::setPane(const QString module_name)
{
QModelIndex newIndex, modelIndex, appearanceIndex, protocolIndex, statIndex;
QString moduleName;
int row;
//look for the pane name in the main tree before trying children
for (row = 0; row < model()->rowCount(); row++)
{
modelIndex = model()->index(row, ModulePrefsModel::colName);
moduleName = model()->data(modelIndex, ModulePrefsModel::ModuleName).toString();
if (moduleName.compare(appearanceName_) == 0) {
appearanceIndex = modelIndex;
} else if (moduleName.compare("Protocols") == 0) {
protocolIndex = modelIndex;
} else if (moduleName.compare("Statistics") == 0) {
statIndex = modelIndex;
}
if (moduleName.compare(module_name) == 0) {
newIndex = modelIndex;
break;
}
}
//Look through appearance children
if (!newIndex.isValid()) {
newIndex = findModule(appearanceIndex, module_name);
}
//Look through protocol children
if (!newIndex.isValid()) {
newIndex = findModule(protocolIndex, module_name);
}
//Look through stat children
if (!newIndex.isValid()) {
newIndex = findModule(statIndex, module_name);
}
setCurrentIndex(newIndex);
}
QModelIndex PrefModuleTreeView::findModule(QModelIndex& parent, const QString& name)
{
QModelIndex findIndex, modelIndex;
QString module_name;
for (int row = 0; row < model()->rowCount(parent); row++)
{
modelIndex = model()->index(row, ModulePrefsModel::colName, parent);
module_name = model()->data(modelIndex, ModulePrefsModel::ModuleName).toString();
if (name.compare(module_name) == 0) {
findIndex = modelIndex;
break;
}
if (model()->rowCount(modelIndex) > 0) {
findIndex = findModule(modelIndex, name);
if (findIndex.isValid())
break;
}
}
return findIndex;
}
void PrefModuleTreeView::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
if (current.isValid())
{
QString module_name = model()->data(current, ModulePrefsModel::ModuleName).toString();
emit goToPane(module_name);
}
QTreeView::currentChanged(current, previous);
} |
C/C++ | wireshark/ui/qt/widgets/pref_module_view.h | /** @file
*
* Tree view of preference module data.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PREFERENCE_MODULE_VIEW_H
#define PREFERENCE_MODULE_VIEW_H
#include <config.h>
#include <QTreeView>
class PrefModuleTreeView : public QTreeView
{
Q_OBJECT
public:
PrefModuleTreeView(QWidget *parent = 0);
void setPane(const QString module_name);
signals:
void goToPane(QString module_name);
protected slots:
void currentChanged(const QModelIndex ¤t, const QModelIndex &previous);
private:
QModelIndex findModule(QModelIndex &parent, const QString& name);
//cache the translation of the module names we check frequently
QString appearanceName_;
};
#endif // PREFERENCE_MODULE_VIEW_H |
C++ | wireshark/ui/qt/widgets/profile_tree_view.cpp | /* profile_tree_view.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/url_link_delegate.h>
#include <ui/qt/models/profile_model.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/widgets/profile_tree_view.h>
#include <QDesktopServices>
#include <QDir>
#include <QItemDelegate>
#include <QLineEdit>
#include <QUrl>
ProfileUrlLinkDelegate::ProfileUrlLinkDelegate(QObject *parent) : UrlLinkDelegate (parent) {}
void ProfileUrlLinkDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
/* Only paint links for valid paths */
if (index.data(ProfileModel::DATA_PATH_IS_NOT_DESCRIPTION).toBool())
UrlLinkDelegate::paint(painter, option, index);
else
QStyledItemDelegate::paint(painter, option, index);
}
ProfileTreeEditDelegate::ProfileTreeEditDelegate(QWidget *parent) : QItemDelegate(parent), editor_(Q_NULLPTR) {}
void ProfileTreeEditDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
if (qobject_cast<QLineEdit *>(editor))
{
QLineEdit * ql = qobject_cast<QLineEdit *>(editor);
ql->setText(index.data().toString());
}
}
ProfileTreeView::ProfileTreeView(QWidget *parent) :
QTreeView (parent)
{
delegate_ = new ProfileTreeEditDelegate();
setItemDelegateForColumn(ProfileModel::COL_NAME, delegate_);
connect(this, &QAbstractItemView::clicked, this, &ProfileTreeView::clicked);
connect(delegate_, &ProfileTreeEditDelegate::commitData, this, &ProfileTreeView::itemUpdated);
}
ProfileTreeView::~ProfileTreeView()
{
delete delegate_;
}
void ProfileTreeView::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
QTreeView::selectionChanged(selected, deselected);
if (model())
{
qsizetype offColumn = model()->columnCount();
qsizetype idxCount = selectedIndexes().count() / offColumn;
qsizetype dselCount = deselected.count() > 0 ? deselected.at(0).indexes().count() / offColumn : 0;
/* Ensure, that the last selected row cannot be deselected */
if (idxCount == 0 && dselCount == 1)
{
QModelIndex idx = deselected.at(0).indexes().at(0);
/* If the last item is no longer valid or the row is out of bounds, select default */
if (! idx.isValid() || idx.row() >= model()->rowCount())
idx = model()->index(0, ProfileModel::COL_NAME);
selectRow(idx.row());
}
else if (selectedIndexes().count() == 0)
selectRow(0);
}
}
void ProfileTreeView::clicked(const QModelIndex &index)
{
if (!index.isValid())
return;
/* Only paint links for valid paths */
if (index.data(ProfileModel::DATA_INDEX_VALUE_IS_URL).toBool())
{
QString path = QDir::toNativeSeparators(index.data().toString());
QDesktopServices::openUrl(QUrl::fromLocalFile(path));
}
}
void ProfileTreeView::selectRow(int row)
{
if (row < 0)
return;
setCurrentIndex(model()->index(row, 0));
selectionModel()->select(
QItemSelection(model()->index(row, 0), model()->index(row, model()->columnCount() -1)),
QItemSelectionModel::ClearAndSelect);
}
void ProfileTreeView::mouseDoubleClickEvent(QMouseEvent *ev)
{
/* due to the fact, that we allow only row selection, selected rows are always added with all columns */
if (selectedIndexes().count() <= model()->columnCount())
QTreeView::mouseDoubleClickEvent(ev);
}
bool ProfileTreeView::activeEdit()
{
return (state() == QAbstractItemView::EditingState);
} |
C/C++ | wireshark/ui/qt/widgets/profile_tree_view.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PROFILE_TREEVIEW_H
#define PROFILE_TREEVIEW_H
#include <ui/qt/models/url_link_delegate.h>
#include <QTreeView>
#include <QItemDelegate>
class ProfileUrlLinkDelegate : public UrlLinkDelegate
{
Q_OBJECT
public:
explicit ProfileUrlLinkDelegate(QObject *parent = Q_NULLPTR);
virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
class ProfileTreeEditDelegate : public QItemDelegate
{
Q_OBJECT
public:
ProfileTreeEditDelegate(QWidget *parent = Q_NULLPTR);
// QAbstractItemDelegate interface
virtual void setEditorData(QWidget *editor, const QModelIndex &index) const;
private:
QWidget * editor_;
QModelIndex index_;
};
class ProfileTreeView : public QTreeView
{
Q_OBJECT
public:
ProfileTreeView(QWidget *parent = nullptr);
~ProfileTreeView();
void selectRow(int row);
bool activeEdit();
signals:
void itemUpdated();
// QWidget interface
protected:
virtual void mouseDoubleClickEvent(QMouseEvent *event);
// QAbstractItemView interface
protected slots:
virtual void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
virtual void clicked(const QModelIndex &index);
private:
ProfileTreeEditDelegate *delegate_;
};
#endif |
C++ | wireshark/ui/qt/widgets/qcustomplot.cpp | /***************************************************************************
** **
** QCustomPlot, an easy to use, modern plotting widget for Qt **
** Copyright (C) 2011-2022 Emanuel Eichhammer **
** **
****************************************************************************
** Author: Emanuel Eichhammer **
** Website/Contact: https://www.qcustomplot.com/ **
** Date: 06.11.22 **
** Version: 2.1.1 **
** **
** Emanuel Eichhammer has granted Wireshark permission to use QCustomPlot **
** under the terms of the GNU General Public License version 2. **
** Date: 22.12.15 (V1.3.2) **
** 13.09.19 (V2.0.1) **
** **
** SPDX-License-Identifier: GPL-2.0-or-later **
****************************************************************************/
#include "qcustomplot.h"
/* including file 'src/vector2d.cpp' */
/* modified 2022-11-06T12:45:56, size 7973 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPVector2D
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPVector2D
\brief Represents two doubles as a mathematical 2D vector
This class acts as a replacement for QVector2D with the advantage of double precision instead of
single, and some convenience methods tailored for the QCustomPlot library.
*/
/* start documentation of inline functions */
/*! \fn void QCPVector2D::setX(double x)
Sets the x coordinate of this vector to \a x.
\see setY
*/
/*! \fn void QCPVector2D::setY(double y)
Sets the y coordinate of this vector to \a y.
\see setX
*/
/*! \fn double QCPVector2D::length() const
Returns the length of this vector.
\see lengthSquared
*/
/*! \fn double QCPVector2D::lengthSquared() const
Returns the squared length of this vector. In some situations, e.g. when just trying to find the
shortest vector of a group, this is faster than calculating \ref length, because it avoids
calculation of a square root.
\see length
*/
/*! \fn double QCPVector2D::angle() const
Returns the angle of the vector in radians. The angle is measured between the positive x line and
the vector, counter-clockwise in a mathematical coordinate system (y axis upwards positive). In
screen/widget coordinates where the y axis is inverted, the angle appears clockwise.
*/
/*! \fn QPoint QCPVector2D::toPoint() const
Returns a QPoint which has the x and y coordinates of this vector, truncating any floating point
information.
\see toPointF
*/
/*! \fn QPointF QCPVector2D::toPointF() const
Returns a QPointF which has the x and y coordinates of this vector.
\see toPoint
*/
/*! \fn bool QCPVector2D::isNull() const
Returns whether this vector is null. A vector is null if \c qIsNull returns true for both x and y
coordinates, i.e. if both are binary equal to 0.
*/
/*! \fn QCPVector2D QCPVector2D::perpendicular() const
Returns a vector perpendicular to this vector, with the same length.
*/
/*! \fn double QCPVector2D::dot() const
Returns the dot/scalar product of this vector with the specified vector \a vec.
*/
/* end documentation of inline functions */
/*!
Creates a QCPVector2D object and initializes the x and y coordinates to 0.
*/
QCPVector2D::QCPVector2D() :
mX(0),
mY(0)
{
}
/*!
Creates a QCPVector2D object and initializes the \a x and \a y coordinates with the specified
values.
*/
QCPVector2D::QCPVector2D(double x, double y) :
mX(x),
mY(y)
{
}
/*!
Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of
the specified \a point.
*/
QCPVector2D::QCPVector2D(const QPoint &point) :
mX(point.x()),
mY(point.y())
{
}
/*!
Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of
the specified \a point.
*/
QCPVector2D::QCPVector2D(const QPointF &point) :
mX(point.x()),
mY(point.y())
{
}
/*!
Normalizes this vector. After this operation, the length of the vector is equal to 1.
If the vector has both entries set to zero, this method does nothing.
\see normalized, length, lengthSquared
*/
void QCPVector2D::normalize()
{
if (mX == 0.0 && mY == 0.0) return;
const double lenInv = 1.0/length();
mX *= lenInv;
mY *= lenInv;
}
/*!
Returns a normalized version of this vector. The length of the returned vector is equal to 1.
If the vector has both entries set to zero, this method returns the vector unmodified.
\see normalize, length, lengthSquared
*/
QCPVector2D QCPVector2D::normalized() const
{
if (mX == 0.0 && mY == 0.0) return *this;
const double lenInv = 1.0/length();
return QCPVector2D(mX*lenInv, mY*lenInv);
}
/*! \overload
Returns the squared shortest distance of this vector (interpreted as a point) to the finite line
segment given by \a start and \a end.
\see distanceToStraightLine
*/
double QCPVector2D::distanceSquaredToLine(const QCPVector2D &start, const QCPVector2D &end) const
{
const QCPVector2D v(end-start);
const double vLengthSqr = v.lengthSquared();
if (!qFuzzyIsNull(vLengthSqr))
{
const double mu = v.dot(*this-start)/vLengthSqr;
if (mu < 0)
return (*this-start).lengthSquared();
else if (mu > 1)
return (*this-end).lengthSquared();
else
return ((start + mu*v)-*this).lengthSquared();
} else
return (*this-start).lengthSquared();
}
/*! \overload
Returns the squared shortest distance of this vector (interpreted as a point) to the finite line
segment given by \a line.
\see distanceToStraightLine
*/
double QCPVector2D::distanceSquaredToLine(const QLineF &line) const
{
return distanceSquaredToLine(QCPVector2D(line.p1()), QCPVector2D(line.p2()));
}
/*!
Returns the shortest distance of this vector (interpreted as a point) to the infinite straight
line given by a \a base point and a \a direction vector.
\see distanceSquaredToLine
*/
double QCPVector2D::distanceToStraightLine(const QCPVector2D &base, const QCPVector2D &direction) const
{
return qAbs((*this-base).dot(direction.perpendicular()))/direction.length();
}
/*!
Scales this vector by the given \a factor, i.e. the x and y components are multiplied by \a
factor.
*/
QCPVector2D &QCPVector2D::operator*=(double factor)
{
mX *= factor;
mY *= factor;
return *this;
}
/*!
Scales this vector by the given \a divisor, i.e. the x and y components are divided by \a
divisor.
*/
QCPVector2D &QCPVector2D::operator/=(double divisor)
{
mX /= divisor;
mY /= divisor;
return *this;
}
/*!
Adds the given \a vector to this vector component-wise.
*/
QCPVector2D &QCPVector2D::operator+=(const QCPVector2D &vector)
{
mX += vector.mX;
mY += vector.mY;
return *this;
}
/*!
subtracts the given \a vector from this vector component-wise.
*/
QCPVector2D &QCPVector2D::operator-=(const QCPVector2D &vector)
{
mX -= vector.mX;
mY -= vector.mY;
return *this;
}
/* end of 'src/vector2d.cpp' */
/* including file 'src/painter.cpp' */
/* modified 2022-11-06T12:45:56, size 8656 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPainter
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPainter
\brief QPainter subclass used internally
This QPainter subclass is used to provide some extended functionality e.g. for tweaking position
consistency between antialiased and non-antialiased painting. Further it provides workarounds
for QPainter quirks.
\warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and
restore. So while it is possible to pass a QCPPainter instance to a function that expects a
QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because
it will call the base class implementations of the functions actually hidden by QCPPainter).
*/
/*!
Creates a new QCPPainter instance and sets default values
*/
QCPPainter::QCPPainter() :
mModes(pmDefault),
mIsAntialiasing(false)
{
// don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and
// a call to begin() will follow
}
/*!
Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just
like the analogous QPainter constructor, begins painting on \a device immediately.
Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5.
*/
QCPPainter::QCPPainter(QPaintDevice *device) :
QPainter(device),
mModes(pmDefault),
mIsAntialiasing(false)
{
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions.
if (isActive())
setRenderHint(QPainter::NonCosmeticDefaultPen);
#endif
}
/*!
Sets the pen of the painter and applies certain fixes to it, depending on the mode of this
QCPPainter.
\note this function hides the non-virtual base class implementation.
*/
void QCPPainter::setPen(const QPen &pen)
{
QPainter::setPen(pen);
if (mModes.testFlag(pmNonCosmetic))
makeNonCosmetic();
}
/*! \overload
Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of
this QCPPainter.
\note this function hides the non-virtual base class implementation.
*/
void QCPPainter::setPen(const QColor &color)
{
QPainter::setPen(color);
if (mModes.testFlag(pmNonCosmetic))
makeNonCosmetic();
}
/*! \overload
Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of
this QCPPainter.
\note this function hides the non-virtual base class implementation.
*/
void QCPPainter::setPen(Qt::PenStyle penStyle)
{
QPainter::setPen(penStyle);
if (mModes.testFlag(pmNonCosmetic))
makeNonCosmetic();
}
/*! \overload
Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when
antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to
integer coordinates and then passes it to the original drawLine.
\note this function hides the non-virtual base class implementation.
*/
void QCPPainter::drawLine(const QLineF &line)
{
if (mIsAntialiasing || mModes.testFlag(pmVectorized))
QPainter::drawLine(line);
else
QPainter::drawLine(line.toLine());
}
/*!
Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint
with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between
antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for
AA/Non-AA painting).
*/
void QCPPainter::setAntialiasing(bool enabled)
{
setRenderHint(QPainter::Antialiasing, enabled);
if (mIsAntialiasing != enabled)
{
mIsAntialiasing = enabled;
if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs
{
if (mIsAntialiasing)
translate(0.5, 0.5);
else
translate(-0.5, -0.5);
}
}
}
/*!
Sets the mode of the painter. This controls whether the painter shall adjust its
fixes/workarounds optimized for certain output devices.
*/
void QCPPainter::setModes(QCPPainter::PainterModes modes)
{
mModes = modes;
}
/*!
Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a
device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5,
all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that
behaviour.
The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets
the render hint as appropriate.
\note this function hides the non-virtual base class implementation.
*/
bool QCPPainter::begin(QPaintDevice *device)
{
bool result = QPainter::begin(device);
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions.
if (result)
setRenderHint(QPainter::NonCosmeticDefaultPen);
#endif
return result;
}
/*! \overload
Sets the mode of the painter. This controls whether the painter shall adjust its
fixes/workarounds optimized for certain output devices.
*/
void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled)
{
if (!enabled && mModes.testFlag(mode))
mModes &= ~mode;
else if (enabled && !mModes.testFlag(mode))
mModes |= mode;
}
/*!
Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to
QPainter, the save/restore functions are reimplemented to also save/restore those members.
\note this function hides the non-virtual base class implementation.
\see restore
*/
void QCPPainter::save()
{
mAntialiasingStack.push(mIsAntialiasing);
QPainter::save();
}
/*!
Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to
QPainter, the save/restore functions are reimplemented to also save/restore those members.
\note this function hides the non-virtual base class implementation.
\see save
*/
void QCPPainter::restore()
{
if (!mAntialiasingStack.isEmpty())
mIsAntialiasing = mAntialiasingStack.pop();
else
qDebug() << Q_FUNC_INFO << "Unbalanced save/restore";
QPainter::restore();
}
/*!
Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen
overrides when the \ref pmNonCosmetic mode is set.
*/
void QCPPainter::makeNonCosmetic()
{
if (qFuzzyIsNull(pen().widthF()))
{
QPen p = pen();
p.setWidth(1);
QPainter::setPen(p);
}
}
/* end of 'src/painter.cpp' */
/* including file 'src/paintbuffer.cpp' */
/* modified 2022-11-06T12:45:56, size 18915 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAbstractPaintBuffer
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAbstractPaintBuffer
\brief The abstract base class for paint buffers, which define the rendering backend
This abstract base class defines the basic interface that a paint buffer needs to provide in
order to be usable by QCustomPlot.
A paint buffer manages both a surface to draw onto, and the matching paint device. The size of
the surface can be changed via \ref setSize. External classes (\ref QCustomPlot and \ref
QCPLayer) request a painter via \ref startPainting and then perform the draw calls. Once the
painting is complete, \ref donePainting is called, so the paint buffer implementation can do
clean up if necessary. Before rendering a frame, each paint buffer is usually filled with a color
using \ref clear (usually the color is \c Qt::transparent), to remove the contents of the
previous frame.
The simplest paint buffer implementation is \ref QCPPaintBufferPixmap which allows regular
software rendering via the raster engine. Hardware accelerated rendering via pixel buffers and
frame buffer objects is provided by \ref QCPPaintBufferGlPbuffer and \ref QCPPaintBufferGlFbo.
They are used automatically if \ref QCustomPlot::setOpenGl is enabled.
*/
/* start documentation of pure virtual functions */
/*! \fn virtual QCPPainter *QCPAbstractPaintBuffer::startPainting() = 0
Returns a \ref QCPPainter which is ready to draw to this buffer. The ownership and thus the
responsibility to delete the painter after the painting operations are complete is given to the
caller of this method.
Once you are done using the painter, delete the painter and call \ref donePainting.
While a painter generated with this method is active, you must not call \ref setSize, \ref
setDevicePixelRatio or \ref clear.
This method may return 0, if a painter couldn't be activated on the buffer. This usually
indicates a problem with the respective painting backend.
*/
/*! \fn virtual void QCPAbstractPaintBuffer::draw(QCPPainter *painter) const = 0
Draws the contents of this buffer with the provided \a painter. This is the method that is used
to finally join all paint buffers and draw them onto the screen.
*/
/*! \fn virtual void QCPAbstractPaintBuffer::clear(const QColor &color) = 0
Fills the entire buffer with the provided \a color. To have an empty transparent buffer, use the
named color \c Qt::transparent.
This method must not be called if there is currently a painter (acquired with \ref startPainting)
active.
*/
/*! \fn virtual void QCPAbstractPaintBuffer::reallocateBuffer() = 0
Reallocates the internal buffer with the currently configured size (\ref setSize) and device
pixel ratio, if applicable (\ref setDevicePixelRatio). It is called as soon as any of those
properties are changed on this paint buffer.
\note Subclasses of \ref QCPAbstractPaintBuffer must call their reimplementation of this method
in their constructor, to perform the first allocation (this can not be done by the base class
because calling pure virtual methods in base class constructors is not possible).
*/
/* end documentation of pure virtual functions */
/* start documentation of inline functions */
/*! \fn virtual void QCPAbstractPaintBuffer::donePainting()
If you have acquired a \ref QCPPainter to paint onto this paint buffer via \ref startPainting,
call this method as soon as you are done with the painting operations and have deleted the
painter.
paint buffer subclasses may use this method to perform any type of cleanup that is necessary. The
default implementation does nothing.
*/
/* end documentation of inline functions */
/*!
Creates a paint buffer and initializes it with the provided \a size and \a devicePixelRatio.
Subclasses must call their \ref reallocateBuffer implementation in their respective constructors.
*/
QCPAbstractPaintBuffer::QCPAbstractPaintBuffer(const QSize &size, double devicePixelRatio) :
mSize(size),
mDevicePixelRatio(devicePixelRatio),
mInvalidated(true)
{
}
QCPAbstractPaintBuffer::~QCPAbstractPaintBuffer()
{
}
/*!
Sets the paint buffer size.
The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained
by \ref startPainting are invalidated and must not be used after calling this method.
If \a size is already the current buffer size, this method does nothing.
*/
void QCPAbstractPaintBuffer::setSize(const QSize &size)
{
if (mSize != size)
{
mSize = size;
reallocateBuffer();
}
}
/*!
Sets the invalidated flag to \a invalidated.
This mechanism is used internally in conjunction with isolated replotting of \ref QCPLayer
instances (in \ref QCPLayer::lmBuffered mode). If \ref QCPLayer::replot is called on a buffered
layer, i.e. an isolated repaint of only that layer (and its dedicated paint buffer) is requested,
QCustomPlot will decide depending on the invalidated flags of other paint buffers whether it also
replots them, instead of only the layer on which the replot was called.
The invalidated flag is set to true when \ref QCPLayer association has changed, i.e. if layers
were added or removed from this buffer, or if they were reordered. It is set to false as soon as
all associated \ref QCPLayer instances are drawn onto the buffer.
Under normal circumstances, it is not necessary to manually call this method.
*/
void QCPAbstractPaintBuffer::setInvalidated(bool invalidated)
{
mInvalidated = invalidated;
}
/*!
Sets the device pixel ratio to \a ratio. This is useful to render on high-DPI output devices.
The ratio is automatically set to the device pixel ratio used by the parent QCustomPlot instance.
The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained
by \ref startPainting are invalidated and must not be used after calling this method.
\note This method is only available for Qt versions 5.4 and higher.
*/
void QCPAbstractPaintBuffer::setDevicePixelRatio(double ratio)
{
if (!qFuzzyCompare(ratio, mDevicePixelRatio))
{
#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
mDevicePixelRatio = ratio;
reallocateBuffer();
#else
qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
mDevicePixelRatio = 1.0;
#endif
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPaintBufferPixmap
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPaintBufferPixmap
\brief A paint buffer based on QPixmap, using software raster rendering
This paint buffer is the default and fall-back paint buffer which uses software rendering and
QPixmap as internal buffer. It is used if \ref QCustomPlot::setOpenGl is false.
*/
/*!
Creates a pixmap paint buffer instancen with the specified \a size and \a devicePixelRatio, if
applicable.
*/
QCPPaintBufferPixmap::QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio) :
QCPAbstractPaintBuffer(size, devicePixelRatio)
{
QCPPaintBufferPixmap::reallocateBuffer();
}
QCPPaintBufferPixmap::~QCPPaintBufferPixmap()
{
}
/* inherits documentation from base class */
QCPPainter *QCPPaintBufferPixmap::startPainting()
{
QCPPainter *result = new QCPPainter(&mBuffer);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
result->setRenderHint(QPainter::Antialiasing);
#endif
return result;
}
/* inherits documentation from base class */
void QCPPaintBufferPixmap::draw(QCPPainter *painter) const
{
if (painter && painter->isActive())
painter->drawPixmap(0, 0, mBuffer);
else
qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
}
/* inherits documentation from base class */
void QCPPaintBufferPixmap::clear(const QColor &color)
{
mBuffer.fill(color);
}
/* inherits documentation from base class */
void QCPPaintBufferPixmap::reallocateBuffer()
{
setInvalidated();
if (!qFuzzyCompare(1.0, mDevicePixelRatio))
{
#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
mBuffer = QPixmap(mSize*mDevicePixelRatio);
mBuffer.setDevicePixelRatio(mDevicePixelRatio);
#else
qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
mDevicePixelRatio = 1.0;
mBuffer = QPixmap(mSize);
#endif
} else
{
mBuffer = QPixmap(mSize);
}
}
#ifdef QCP_OPENGL_PBUFFER
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPaintBufferGlPbuffer
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPaintBufferGlPbuffer
\brief A paint buffer based on OpenGL pixel buffers, using hardware accelerated rendering
This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot
rendering. It is based on OpenGL pixel buffers (pbuffer) and is used in Qt versions before 5.0.
(See \ref QCPPaintBufferGlFbo used in newer Qt versions.)
The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are
supported by the system.
*/
/*!
Creates a \ref QCPPaintBufferGlPbuffer instance with the specified \a size and \a
devicePixelRatio, if applicable.
The parameter \a multisamples defines how many samples are used per pixel. Higher values thus
result in higher quality antialiasing. If the specified \a multisamples value exceeds the
capability of the graphics hardware, the highest supported multisampling is used.
*/
QCPPaintBufferGlPbuffer::QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples) :
QCPAbstractPaintBuffer(size, devicePixelRatio),
mGlPBuffer(0),
mMultisamples(qMax(0, multisamples))
{
QCPPaintBufferGlPbuffer::reallocateBuffer();
}
QCPPaintBufferGlPbuffer::~QCPPaintBufferGlPbuffer()
{
if (mGlPBuffer)
delete mGlPBuffer;
}
/* inherits documentation from base class */
QCPPainter *QCPPaintBufferGlPbuffer::startPainting()
{
if (!mGlPBuffer->isValid())
{
qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
return 0;
}
QCPPainter *result = new QCPPainter(mGlPBuffer);
result->setRenderHint(QPainter::Antialiasing);
return result;
}
/* inherits documentation from base class */
void QCPPaintBufferGlPbuffer::draw(QCPPainter *painter) const
{
if (!painter || !painter->isActive())
{
qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
return;
}
if (!mGlPBuffer->isValid())
{
qDebug() << Q_FUNC_INFO << "OpenGL pbuffer isn't valid, reallocateBuffer was not called?";
return;
}
painter->drawImage(0, 0, mGlPBuffer->toImage());
}
/* inherits documentation from base class */
void QCPPaintBufferGlPbuffer::clear(const QColor &color)
{
if (mGlPBuffer->isValid())
{
mGlPBuffer->makeCurrent();
glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
mGlPBuffer->doneCurrent();
} else
qDebug() << Q_FUNC_INFO << "OpenGL pbuffer invalid or context not current";
}
/* inherits documentation from base class */
void QCPPaintBufferGlPbuffer::reallocateBuffer()
{
if (mGlPBuffer)
delete mGlPBuffer;
QGLFormat format;
format.setAlpha(true);
format.setSamples(mMultisamples);
mGlPBuffer = new QGLPixelBuffer(mSize, format);
}
#endif // QCP_OPENGL_PBUFFER
#ifdef QCP_OPENGL_FBO
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPaintBufferGlFbo
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPaintBufferGlFbo
\brief A paint buffer based on OpenGL frame buffers objects, using hardware accelerated rendering
This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot
rendering. It is based on OpenGL frame buffer objects (fbo) and is used in Qt versions 5.0 and
higher. (See \ref QCPPaintBufferGlPbuffer used in older Qt versions.)
The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are
supported by the system.
*/
/*!
Creates a \ref QCPPaintBufferGlFbo instance with the specified \a size and \a devicePixelRatio,
if applicable.
All frame buffer objects shall share one OpenGL context and paint device, which need to be set up
externally and passed via \a glContext and \a glPaintDevice. The set-up is done in \ref
QCustomPlot::setupOpenGl and the context and paint device are managed by the parent QCustomPlot
instance.
*/
QCPPaintBufferGlFbo::QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer<QOpenGLContext> glContext, QWeakPointer<QOpenGLPaintDevice> glPaintDevice) :
QCPAbstractPaintBuffer(size, devicePixelRatio),
mGlContext(glContext),
mGlPaintDevice(glPaintDevice),
mGlFrameBuffer(0)
{
QCPPaintBufferGlFbo::reallocateBuffer();
}
QCPPaintBufferGlFbo::~QCPPaintBufferGlFbo()
{
if (mGlFrameBuffer)
delete mGlFrameBuffer;
}
/* inherits documentation from base class */
QCPPainter *QCPPaintBufferGlFbo::startPainting()
{
QSharedPointer<QOpenGLPaintDevice> paintDevice = mGlPaintDevice.toStrongRef();
QSharedPointer<QOpenGLContext> context = mGlContext.toStrongRef();
if (!paintDevice)
{
qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist";
return 0;
}
if (!context)
{
qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
return 0;
}
if (!mGlFrameBuffer)
{
qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
return 0;
}
if (QOpenGLContext::currentContext() != context.data())
context->makeCurrent(context->surface());
mGlFrameBuffer->bind();
QCPPainter *result = new QCPPainter(paintDevice.data());
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
result->setRenderHint(QPainter::Antialiasing);
#endif
return result;
}
/* inherits documentation from base class */
void QCPPaintBufferGlFbo::donePainting()
{
if (mGlFrameBuffer && mGlFrameBuffer->isBound())
mGlFrameBuffer->release();
else
qDebug() << Q_FUNC_INFO << "Either OpenGL frame buffer not valid or was not bound";
}
/* inherits documentation from base class */
void QCPPaintBufferGlFbo::draw(QCPPainter *painter) const
{
if (!painter || !painter->isActive())
{
qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
return;
}
if (!mGlFrameBuffer)
{
qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
return;
}
painter->drawImage(0, 0, mGlFrameBuffer->toImage());
}
/* inherits documentation from base class */
void QCPPaintBufferGlFbo::clear(const QColor &color)
{
QSharedPointer<QOpenGLContext> context = mGlContext.toStrongRef();
if (!context)
{
qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
return;
}
if (!mGlFrameBuffer)
{
qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
return;
}
if (QOpenGLContext::currentContext() != context.data())
context->makeCurrent(context->surface());
mGlFrameBuffer->bind();
glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
mGlFrameBuffer->release();
}
/* inherits documentation from base class */
void QCPPaintBufferGlFbo::reallocateBuffer()
{
// release and delete possibly existing framebuffer:
if (mGlFrameBuffer)
{
if (mGlFrameBuffer->isBound())
mGlFrameBuffer->release();
delete mGlFrameBuffer;
mGlFrameBuffer = 0;
}
QSharedPointer<QOpenGLPaintDevice> paintDevice = mGlPaintDevice.toStrongRef();
QSharedPointer<QOpenGLContext> context = mGlContext.toStrongRef();
if (!paintDevice)
{
qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist";
return;
}
if (!context)
{
qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
return;
}
// create new fbo with appropriate size:
context->makeCurrent(context->surface());
QOpenGLFramebufferObjectFormat frameBufferFormat;
frameBufferFormat.setSamples(context->format().samples());
frameBufferFormat.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
mGlFrameBuffer = new QOpenGLFramebufferObject(mSize*mDevicePixelRatio, frameBufferFormat);
if (paintDevice->size() != mSize*mDevicePixelRatio)
paintDevice->setSize(mSize*mDevicePixelRatio);
#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
paintDevice->setDevicePixelRatio(mDevicePixelRatio);
#endif
}
#endif // QCP_OPENGL_FBO
/* end of 'src/paintbuffer.cpp' */
/* including file 'src/layer.cpp' */
/* modified 2022-11-06T12:45:56, size 37615 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayer
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayer
\brief A layer that may contain objects, to control the rendering order
The Layering system of QCustomPlot is the mechanism to control the rendering order of the
elements inside the plot.
It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of
one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer,
QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers
bottom to top and successively draws the layerables of the layers into the paint buffer(s).
A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base
class from which almost all visible objects derive, like axes, grids, graphs, items, etc.
\section qcplayer-defaultlayers Default layers
Initially, QCustomPlot has six layers: "background", "grid", "main", "axes", "legend" and
"overlay" (in that order). On top is the "overlay" layer, which only contains the QCustomPlot's
selection rect (\ref QCustomPlot::selectionRect). The next two layers "axes" and "legend" contain
the default axes and legend, so they will be drawn above plottables. In the middle, there is the
"main" layer. It is initially empty and set as the current layer (see
QCustomPlot::setCurrentLayer). This means, all new plottables, items etc. are created on this
layer by default. Then comes the "grid" layer which contains the QCPGrid instances (which belong
tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background shall be drawn behind
everything else, thus the default QCPAxisRect instance is placed on the "background" layer. Of
course, the layer affiliation of the individual objects can be changed as required (\ref
QCPLayerable::setLayer).
\section qcplayer-ordering Controlling the rendering order via layers
Controlling the ordering of layerables in the plot is easy: Create a new layer in the position
you want the layerable to be in, e.g. above "main", with \ref QCustomPlot::addLayer. Then set the
current layer with \ref QCustomPlot::setCurrentLayer to that new layer and finally create the
objects normally. They will be placed on the new layer automatically, due to the current layer
setting. Alternatively you could have also ignored the current layer setting and just moved the
objects with \ref QCPLayerable::setLayer to the desired layer after creating them.
It is also possible to move whole layers. For example, If you want the grid to be shown in front
of all plottables/items on the "main" layer, just move it above "main" with
QCustomPlot::moveLayer.
The rendering order within one layer is simply by order of creation or insertion. The item
created last (or added last to the layer), is drawn on top of all other objects on that layer.
When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below
the deleted layer, see QCustomPlot::removeLayer.
\section qcplayer-buffering Replotting only a specific layer
If the layer mode (\ref setMode) is set to \ref lmBuffered, you can replot only this specific
layer by calling \ref replot. In certain situations this can provide better replot performance,
compared with a full replot of all layers. Upon creation of a new layer, the layer mode is
initialized to \ref lmLogical. The only layer that is set to \ref lmBuffered in a new \ref
QCustomPlot instance is the "overlay" layer, containing the selection rect.
*/
/* start documentation of inline functions */
/*! \fn QList<QCPLayerable*> QCPLayer::children() const
Returns a list of all layerables on this layer. The order corresponds to the rendering order:
layerables with higher indices are drawn above layerables with lower indices.
*/
/*! \fn int QCPLayer::index() const
Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be
accessed via \ref QCustomPlot::layer.
Layers with higher indices will be drawn above layers with lower indices.
*/
/* end documentation of inline functions */
/*!
Creates a new QCPLayer instance.
Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead.
\warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot.
This check is only performed by \ref QCustomPlot::addLayer.
*/
QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) :
QObject(parentPlot),
mParentPlot(parentPlot),
mName(layerName),
mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function
mVisible(true),
mMode(lmLogical)
{
// Note: no need to make sure layerName is unique, because layer
// management is done with QCustomPlot functions.
}
QCPLayer::~QCPLayer()
{
// If child layerables are still on this layer, detach them, so they don't try to reach back to this
// then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted
// directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to
// call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.)
while (!mChildren.isEmpty())
mChildren.last()->setLayer(nullptr); // removes itself from mChildren via removeChild()
if (mParentPlot->currentLayer() == this)
qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or nullptr beforehand.";
}
/*!
Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this
layer will be invisible.
This function doesn't change the visibility property of the layerables (\ref
QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the
visibility of the parent layer into account.
*/
void QCPLayer::setVisible(bool visible)
{
mVisible = visible;
}
/*!
Sets the rendering mode of this layer.
If \a mode is set to \ref lmBuffered for a layer, it will be given a dedicated paint buffer by
the parent QCustomPlot instance. This means it may be replotted individually by calling \ref
QCPLayer::replot, without needing to replot all other layers.
Layers which are set to \ref lmLogical (the default) are used only to define the rendering order
and can't be replotted individually.
Note that each layer which is set to \ref lmBuffered requires additional paint buffers for the
layers below, above and for the layer itself. This increases the memory consumption and
(slightly) decreases the repainting speed because multiple paint buffers need to be joined. So
you should carefully choose which layers benefit from having their own paint buffer. A typical
example would be a layer which contains certain layerables (e.g. items) that need to be changed
and thus replotted regularly, while all other layerables on other layers stay static. By default,
only the topmost layer called "overlay" is in mode \ref lmBuffered, and contains the selection
rect.
\see replot
*/
void QCPLayer::setMode(QCPLayer::LayerMode mode)
{
if (mMode != mode)
{
mMode = mode;
if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
pb->setInvalidated();
}
}
/*! \internal
Draws the contents of this layer with the provided \a painter.
\see replot, drawToPaintBuffer
*/
void QCPLayer::draw(QCPPainter *painter)
{
foreach (QCPLayerable *child, mChildren)
{
if (child->realVisibility())
{
painter->save();
painter->setClipRect(child->clipRect().translated(0, -1));
child->applyDefaultAntialiasingHint(painter);
child->draw(painter);
painter->restore();
}
}
}
/*! \internal
Draws the contents of this layer into the paint buffer which is associated with this layer. The
association is established by the parent QCustomPlot, which manages all paint buffers (see \ref
QCustomPlot::setupPaintBuffers).
\see draw
*/
void QCPLayer::drawToPaintBuffer()
{
if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
{
if (QCPPainter *painter = pb->startPainting())
{
if (painter->isActive())
draw(painter);
else
qDebug() << Q_FUNC_INFO << "paint buffer returned inactive painter";
delete painter;
pb->donePainting();
} else
qDebug() << Q_FUNC_INFO << "paint buffer returned nullptr painter";
} else
qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer";
}
/*!
If the layer mode (\ref setMode) is set to \ref lmBuffered, this method allows replotting only
the layerables on this specific layer, without the need to replot all other layers (as a call to
\ref QCustomPlot::replot would do).
QCustomPlot also makes sure to replot all layers instead of only this one, if the layer ordering
or any layerable-layer-association has changed since the last full replot and any other paint
buffers were thus invalidated.
If the layer mode is \ref lmLogical however, this method simply calls \ref QCustomPlot::replot on
the parent QCustomPlot instance.
\see draw
*/
void QCPLayer::replot()
{
if (mMode == lmBuffered && !mParentPlot->hasInvalidatedPaintBuffers())
{
if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
{
pb->clear(Qt::transparent);
drawToPaintBuffer();
pb->setInvalidated(false); // since layer is lmBuffered, we know only this layer is on buffer and we can reset invalidated flag
mParentPlot->update();
} else
qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer";
} else
mParentPlot->replot();
}
/*! \internal
Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will
be prepended to the list, i.e. be drawn beneath the other layerables already in the list.
This function does not change the \a mLayer member of \a layerable to this layer. (Use
QCPLayerable::setLayer to change the layer of an object, not this function.)
\see removeChild
*/
void QCPLayer::addChild(QCPLayerable *layerable, bool prepend)
{
if (!mChildren.contains(layerable))
{
if (prepend)
mChildren.prepend(layerable);
else
mChildren.append(layerable);
if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
pb->setInvalidated();
} else
qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast<quintptr>(layerable);
}
/*! \internal
Removes the \a layerable from the list of this layer.
This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer
to change the layer of an object, not this function.)
\see addChild
*/
void QCPLayer::removeChild(QCPLayerable *layerable)
{
if (mChildren.removeOne(layerable))
{
if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
pb->setInvalidated();
} else
qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast<quintptr>(layerable);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayerable
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayerable
\brief Base class for all drawable objects
This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid
etc.
Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking
the layers accordingly.
For details about the layering mechanism, see the QCPLayer documentation.
*/
/* start documentation of inline functions */
/*! \fn QCPLayerable *QCPLayerable::parentLayerable() const
Returns the parent layerable of this layerable. The parent layerable is used to provide
visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables
only get drawn if their parent layerables are visible, too.
Note that a parent layerable is not necessarily also the QObject parent for memory management.
Further, a layerable doesn't always have a parent layerable, so this function may return \c
nullptr.
A parent layerable is set implicitly when placed inside layout elements and doesn't need to be
set manually by the user.
*/
/* end documentation of inline functions */
/* start documentation of pure virtual functions */
/*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0
\internal
This function applies the default antialiasing setting to the specified \a painter, using the
function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when
\ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing
setting may be specified individually, this function should set the antialiasing state of the
most prominent entity. In this case however, the \ref draw function usually calls the specialized
versions of this function before drawing each entity, effectively overriding the setting of the
default antialiasing hint.
<b>First example:</b> QCPGraph has multiple entities that have an antialiasing setting: The graph
line, fills and scatters. Those can be configured via QCPGraph::setAntialiased,
QCPGraph::setAntialiasedFill and QCPGraph::setAntialiasedScatters. Consequently, there isn't only
the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's
antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and
QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw
calls the respective specialized applyAntialiasingHint function.
<b>Second example:</b> QCPItemLine consists only of a line so there is only one antialiasing
setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by
all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the
respective layerable subclass.) Consequently it only has the normal
QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to
care about setting any antialiasing states, because the default antialiasing hint is already set
on the painter when the \ref draw function is called, and that's the state it wants to draw the
line with.
*/
/*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0
\internal
This function draws the layerable with the specified \a painter. It is only called by
QCustomPlot, if the layerable is visible (\ref setVisible).
Before this function is called, the painter's antialiasing state is set via \ref
applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was
set to \ref clipRect.
*/
/* end documentation of pure virtual functions */
/* start documentation of signals */
/*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer);
This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to
a different layer.
\see setLayer
*/
/* end documentation of signals */
/*!
Creates a new QCPLayerable instance.
Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the
derived classes.
If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a
targetLayer is an empty string, it places itself on the current layer of the plot (see \ref
QCustomPlot::setCurrentLayer).
It is possible to provide \c nullptr as \a plot. In that case, you should assign a parent plot at
a later time with \ref initializeParentPlot.
The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable
parents are mainly used to control visibility in a hierarchy of layerables. This means a
layerable is only drawn, if all its ancestor layerables are also visible. Note that \a
parentLayerable does not become the QObject-parent (for memory management) of this layerable, \a
plot does. It is not uncommon to set the QObject-parent to something else in the constructors of
QCPLayerable subclasses, to guarantee a working destruction hierarchy.
*/
QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) :
QObject(plot),
mVisible(true),
mParentPlot(plot),
mParentLayerable(parentLayerable),
mLayer(nullptr),
mAntialiased(true)
{
if (mParentPlot)
{
if (targetLayer.isEmpty())
setLayer(mParentPlot->currentLayer());
else if (!setLayer(targetLayer))
qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed.";
}
}
QCPLayerable::~QCPLayerable()
{
if (mLayer)
{
mLayer->removeChild(this);
mLayer = nullptr;
}
}
/*!
Sets the visibility of this layerable object. If an object is not visible, it will not be drawn
on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not
possible.
*/
void QCPLayerable::setVisible(bool on)
{
mVisible = on;
}
/*!
Sets the \a layer of this layerable object. The object will be placed on top of the other objects
already on \a layer.
If \a layer is 0, this layerable will not be on any layer and thus not appear in the plot (or
interact/receive events).
Returns true if the layer of this layerable was successfully changed to \a layer.
*/
bool QCPLayerable::setLayer(QCPLayer *layer)
{
return moveToLayer(layer, false);
}
/*! \overload
Sets the layer of this layerable object by name
Returns true on success, i.e. if \a layerName is a valid layer name.
*/
bool QCPLayerable::setLayer(const QString &layerName)
{
if (!mParentPlot)
{
qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
return false;
}
if (QCPLayer *layer = mParentPlot->layer(layerName))
{
return setLayer(layer);
} else
{
qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName;
return false;
}
}
/*!
Sets whether this object will be drawn antialiased or not.
Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
QCustomPlot::setNotAntialiasedElements.
*/
void QCPLayerable::setAntialiased(bool enabled)
{
mAntialiased = enabled;
}
/*!
Returns whether this layerable is visible, taking the visibility of the layerable parent and the
visibility of this layerable's layer into account. This is the method that is consulted to decide
whether a layerable shall be drawn or not.
If this layerable has a direct layerable parent (usually set via hierarchies implemented in
subclasses, like in the case of \ref QCPLayoutElement), this function returns true only if this
layerable has its visibility set to true and the parent layerable's \ref realVisibility returns
true.
*/
bool QCPLayerable::realVisibility() const
{
return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility());
}
/*!
This function is used to decide whether a click hits a layerable object or not.
\a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the
shortest pixel distance of this point to the object. If the object is either invisible or the
distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the
object is not selectable, -1.0 is returned, too.
If the object is represented not by single lines but by an area like a \ref QCPItemText or the
bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In
these cases this function thus returns a constant value greater zero but still below the parent
plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99).
Providing a constant value for area objects allows selecting line objects even when they are
obscured by such area objects, by clicking close to the lines (i.e. closer than
0.99*selectionTolerance).
The actual setting of the selection state is not done by this function. This is handled by the
parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified
via the \ref selectEvent/\ref deselectEvent methods.
\a details is an optional output parameter. Every layerable subclass may place any information
in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot
decides on the basis of this selectTest call, that the object was successfully selected. The
subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part
objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked
is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be
placed in \a details. So in the subsequent \ref selectEvent, the decision which part was
selected doesn't have to be done a second time for a single selection operation.
In the case of 1D Plottables (\ref QCPAbstractPlottable1D, like \ref QCPGraph or \ref QCPBars) \a
details will be set to a \ref QCPDataSelection, describing the closest data point to \a pos.
You may pass \c nullptr as \a details to indicate that you are not interested in those selection
details.
\see selectEvent, deselectEvent, mousePressEvent, wheelEvent, QCustomPlot::setInteractions,
QCPAbstractPlottable1D::selectTestRect
*/
double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(pos)
Q_UNUSED(onlySelectable)
Q_UNUSED(details)
return -1.0;
}
/*! \internal
Sets the parent plot of this layerable. Use this function once to set the parent plot if you have
passed \c nullptr in the constructor. It can not be used to move a layerable from one QCustomPlot
to another one.
Note that, unlike when passing a non \c nullptr parent plot in the constructor, this function
does not make \a parentPlot the QObject-parent of this layerable. If you want this, call
QObject::setParent(\a parentPlot) in addition to this function.
Further, you will probably want to set a layer (\ref setLayer) after calling this function, to
make the layerable appear on the QCustomPlot.
The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized
so they can react accordingly (e.g. also initialize the parent plot of child layerables, like
QCPLayout does).
*/
void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot)
{
if (mParentPlot)
{
qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized";
return;
}
if (!parentPlot)
qDebug() << Q_FUNC_INFO << "called with parentPlot zero";
mParentPlot = parentPlot;
parentPlotInitialized(mParentPlot);
}
/*! \internal
Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not
become the QObject-parent (for memory management) of this layerable.
The parent layerable has influence on the return value of the \ref realVisibility method. Only
layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be
drawn.
\see realVisibility
*/
void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable)
{
mParentLayerable = parentLayerable;
}
/*! \internal
Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to
the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is
false, the object will be appended.
Returns true on success, i.e. if \a layer is a valid layer.
*/
bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend)
{
if (layer && !mParentPlot)
{
qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
return false;
}
if (layer && layer->parentPlot() != mParentPlot)
{
qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable";
return false;
}
QCPLayer *oldLayer = mLayer;
if (mLayer)
mLayer->removeChild(this);
mLayer = layer;
if (mLayer)
mLayer->addChild(this, prepend);
if (mLayer != oldLayer)
emit layerChanged(mLayer);
return true;
}
/*! \internal
Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a
localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is
controlled via \a overrideElement.
*/
void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const
{
if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement))
painter->setAntialiasing(false);
else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement))
painter->setAntialiasing(true);
else
painter->setAntialiasing(localAntialiased);
}
/*! \internal
This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting
of a parent plot. This is the case when \c nullptr was passed as parent plot in the constructor,
and the parent plot is set at a later time.
For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any
QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level
element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To
propagate the parent plot to all the children of the hierarchy, the top level element then uses
this function to pass the parent plot on to its child elements.
The default implementation does nothing.
\see initializeParentPlot
*/
void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot)
{
Q_UNUSED(parentPlot)
}
/*! \internal
Returns the selection category this layerable shall belong to. The selection category is used in
conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and
which aren't.
Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref
QCP::iSelectOther. This is what the default implementation returns.
\see QCustomPlot::setInteractions
*/
QCP::Interaction QCPLayerable::selectionCategory() const
{
return QCP::iSelectOther;
}
/*! \internal
Returns the clipping rectangle of this layerable object. By default, this is the viewport of the
parent QCustomPlot. Specific subclasses may reimplement this function to provide different
clipping rects.
The returned clipping rect is set on the painter before the draw function of the respective
object is called.
*/
QRect QCPLayerable::clipRect() const
{
if (mParentPlot)
return mParentPlot->viewport();
else
return {};
}
/*! \internal
This event is called when the layerable shall be selected, as a consequence of a click by the
user. Subclasses should react to it by setting their selection state appropriately. The default
implementation does nothing.
\a event is the mouse event that caused the selection. \a additive indicates, whether the user
was holding the multi-select-modifier while performing the selection (see \ref
QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled
(i.e. become selected when unselected and unselected when selected).
Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e.
returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot).
The \a details data you output from \ref selectTest is fed back via \a details here. You may
use it to transport any kind of information from the selectTest to the possibly subsequent
selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable
that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need
to do the calculation again to find out which part was actually clicked.
\a selectionStateChanged is an output parameter. If the pointer is non-null, this function must
set the value either to true or false, depending on whether the selection state of this layerable
was actually changed. For layerables that only are selectable as a whole and not in parts, this
is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the
selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the
layerable was previously unselected and now is switched to the selected state.
\see selectTest, deselectEvent
*/
void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(additive)
Q_UNUSED(details)
Q_UNUSED(selectionStateChanged)
}
/*! \internal
This event is called when the layerable shall be deselected, either as consequence of a user
interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by
unsetting their selection appropriately.
just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must
return true or false when the selection state of this layerable has changed or not changed,
respectively.
\see selectTest, selectEvent
*/
void QCPLayerable::deselectEvent(bool *selectionStateChanged)
{
Q_UNUSED(selectionStateChanged)
}
/*!
This event gets called when the user presses a mouse button while the cursor is over the
layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref
selectTest.
The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
event->pos(). The parameter \a details contains layerable-specific details about the hit, which
were generated in the previous call to \ref selectTest. For example, One-dimensional plottables
like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as
\ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c
SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes).
QCustomPlot uses an event propagation system that works the same as Qt's system. If your
layerable doesn't reimplement the \ref mousePressEvent or explicitly calls \c event->ignore() in
its reimplementation, the event will be propagated to the next layerable in the stacking order.
Once a layerable has accepted the \ref mousePressEvent, it is considered the mouse grabber and
will receive all following calls to \ref mouseMoveEvent or \ref mouseReleaseEvent for this mouse
interaction (a "mouse interaction" in this context ends with the release).
The default implementation does nothing except explicitly ignoring the event with \c
event->ignore().
\see mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent
*/
void QCPLayerable::mousePressEvent(QMouseEvent *event, const QVariant &details)
{
Q_UNUSED(details)
event->ignore();
}
/*!
This event gets called when the user moves the mouse while holding a mouse button, after this
layerable has become the mouse grabber by accepting the preceding \ref mousePressEvent.
The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
event->pos(). The parameter \a startPos indicates the position where the initial \ref
mousePressEvent occurred, that started the mouse interaction.
The default implementation does nothing.
\see mousePressEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent
*/
void QCPLayerable::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
{
Q_UNUSED(startPos)
event->ignore();
}
/*!
This event gets called when the user releases the mouse button, after this layerable has become
the mouse grabber by accepting the preceding \ref mousePressEvent.
The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
event->pos(). The parameter \a startPos indicates the position where the initial \ref
mousePressEvent occurred, that started the mouse interaction.
The default implementation does nothing.
\see mousePressEvent, mouseMoveEvent, mouseDoubleClickEvent, wheelEvent
*/
void QCPLayerable::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
{
Q_UNUSED(startPos)
event->ignore();
}
/*!
This event gets called when the user presses the mouse button a second time in a double-click,
while the cursor is over the layerable. Whether a cursor is over the layerable is decided by a
preceding call to \ref selectTest.
The \ref mouseDoubleClickEvent is called instead of the second \ref mousePressEvent. So in the
case of a double-click, the event succession is
<i>pressEvent – releaseEvent – doubleClickEvent – releaseEvent</i>.
The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
event->pos(). The parameter \a details contains layerable-specific details about the hit, which
were generated in the previous call to \ref selectTest. For example, One-dimensional plottables
like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as
\ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c
SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes).
Similarly to \ref mousePressEvent, once a layerable has accepted the \ref mouseDoubleClickEvent,
it is considered the mouse grabber and will receive all following calls to \ref mouseMoveEvent
and \ref mouseReleaseEvent for this mouse interaction (a "mouse interaction" in this context ends
with the release).
The default implementation does nothing except explicitly ignoring the event with \c
event->ignore().
\see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, wheelEvent
*/
void QCPLayerable::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
{
Q_UNUSED(details)
event->ignore();
}
/*!
This event gets called when the user turns the mouse scroll wheel while the cursor is over the
layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref
selectTest.
The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
event->pos().
The \c event->angleDelta() indicates how far the mouse wheel was turned, which is usually +/- 120
for single rotation steps. However, if the mouse wheel is turned rapidly, multiple steps may
accumulate to one event, making the delta larger. On the other hand, if the wheel has very smooth
steps or none at all, the delta may be smaller.
The default implementation does nothing.
\see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent
*/
void QCPLayerable::wheelEvent(QWheelEvent *event)
{
event->ignore();
}
/* end of 'src/layer.cpp' */
/* including file 'src/axis/range.cpp' */
/* modified 2022-11-06T12:45:56, size 12221 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPRange
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPRange
\brief Represents the range an axis is encompassing.
contains a \a lower and \a upper double value and provides convenience input, output and
modification functions.
\see QCPAxis::setRange
*/
/* start of documentation of inline functions */
/*! \fn double QCPRange::size() const
Returns the size of the range, i.e. \a upper-\a lower
*/
/*! \fn double QCPRange::center() const
Returns the center of the range, i.e. (\a upper+\a lower)*0.5
*/
/*! \fn void QCPRange::normalize()
Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values are
swapped.
*/
/*! \fn bool QCPRange::contains(double value) const
Returns true when \a value lies within or exactly on the borders of the range.
*/
/*! \fn QCPRange &QCPRange::operator+=(const double& value)
Adds \a value to both boundaries of the range.
*/
/*! \fn QCPRange &QCPRange::operator-=(const double& value)
Subtracts \a value from both boundaries of the range.
*/
/*! \fn QCPRange &QCPRange::operator*=(const double& value)
Multiplies both boundaries of the range by \a value.
*/
/*! \fn QCPRange &QCPRange::operator/=(const double& value)
Divides both boundaries of the range by \a value.
*/
/* end of documentation of inline functions */
/*!
Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller
intervals would cause errors due to the 11-bit exponent of double precision numbers,
corresponding to a minimum magnitude of roughly 1e-308.
\warning Do not use this constant to indicate "arbitrarily small" values in plotting logic (as
values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to
prevent axis ranges from obtaining underflowing ranges.
\see validRange, maxRange
*/
const double QCPRange::minRange = 1e-280;
/*!
Maximum values (negative and positive) the range will accept in range-changing functions.
Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers,
corresponding to a maximum magnitude of roughly 1e308.
\warning Do not use this constant to indicate "arbitrarily large" values in plotting logic (as
values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to
prevent axis ranges from obtaining overflowing ranges.
\see validRange, minRange
*/
const double QCPRange::maxRange = 1e250;
/*!
Constructs a range with \a lower and \a upper set to zero.
*/
QCPRange::QCPRange() :
lower(0),
upper(0)
{
}
/*! \overload
Constructs a range with the specified \a lower and \a upper values.
The resulting range will be normalized (see \ref normalize), so if \a lower is not numerically
smaller than \a upper, they will be swapped.
*/
QCPRange::QCPRange(double lower, double upper) :
lower(lower),
upper(upper)
{
normalize();
}
/*! \overload
Expands this range such that \a otherRange is contained in the new range. It is assumed that both
this range and \a otherRange are normalized (see \ref normalize).
If this range contains NaN as lower or upper bound, it will be replaced by the respective bound
of \a otherRange.
If \a otherRange is already inside the current range, this function does nothing.
\see expanded
*/
void QCPRange::expand(const QCPRange &otherRange)
{
if (lower > otherRange.lower || qIsNaN(lower))
lower = otherRange.lower;
if (upper < otherRange.upper || qIsNaN(upper))
upper = otherRange.upper;
}
/*! \overload
Expands this range such that \a includeCoord is contained in the new range. It is assumed that
this range is normalized (see \ref normalize).
If this range contains NaN as lower or upper bound, the respective bound will be set to \a
includeCoord.
If \a includeCoord is already inside the current range, this function does nothing.
\see expand
*/
void QCPRange::expand(double includeCoord)
{
if (lower > includeCoord || qIsNaN(lower))
lower = includeCoord;
if (upper < includeCoord || qIsNaN(upper))
upper = includeCoord;
}
/*! \overload
Returns an expanded range that contains this and \a otherRange. It is assumed that both this
range and \a otherRange are normalized (see \ref normalize).
If this range contains NaN as lower or upper bound, the returned range's bound will be taken from
\a otherRange.
\see expand
*/
QCPRange QCPRange::expanded(const QCPRange &otherRange) const
{
QCPRange result = *this;
result.expand(otherRange);
return result;
}
/*! \overload
Returns an expanded range that includes the specified \a includeCoord. It is assumed that this
range is normalized (see \ref normalize).
If this range contains NaN as lower or upper bound, the returned range's bound will be set to \a
includeCoord.
\see expand
*/
QCPRange QCPRange::expanded(double includeCoord) const
{
QCPRange result = *this;
result.expand(includeCoord);
return result;
}
/*!
Returns this range, possibly modified to not exceed the bounds provided as \a lowerBound and \a
upperBound. If possible, the size of the current range is preserved in the process.
If the range shall only be bounded at the lower side, you can set \a upperBound to \ref
QCPRange::maxRange. If it shall only be bounded at the upper side, set \a lowerBound to -\ref
QCPRange::maxRange.
*/
QCPRange QCPRange::bounded(double lowerBound, double upperBound) const
{
if (lowerBound > upperBound)
qSwap(lowerBound, upperBound);
QCPRange result(lower, upper);
if (result.lower < lowerBound)
{
result.lower = lowerBound;
result.upper = lowerBound + size();
if (result.upper > upperBound || qFuzzyCompare(size(), upperBound-lowerBound))
result.upper = upperBound;
} else if (result.upper > upperBound)
{
result.upper = upperBound;
result.lower = upperBound - size();
if (result.lower < lowerBound || qFuzzyCompare(size(), upperBound-lowerBound))
result.lower = lowerBound;
}
return result;
}
/*!
Returns a sanitized version of the range. Sanitized means for logarithmic scales, that
the range won't span the positive and negative sign domain, i.e. contain zero. Further
\a lower will always be numerically smaller (or equal) to \a upper.
If the original range does span positive and negative sign domains or contains zero,
the returned range will try to approximate the original range as good as possible.
If the positive interval of the original range is wider than the negative interval, the
returned range will only contain the positive interval, with lower bound set to \a rangeFac or
\a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval
is wider than the positive interval, this time by changing the \a upper bound.
*/
QCPRange QCPRange::sanitizedForLogScale() const
{
double rangeFac = 1e-3;
QCPRange sanitizedRange(lower, upper);
sanitizedRange.normalize();
// can't have range spanning negative and positive values in log plot, so change range to fix it
//if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1))
if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0)
{
// case lower is 0
if (rangeFac < sanitizedRange.upper*rangeFac)
sanitizedRange.lower = rangeFac;
else
sanitizedRange.lower = sanitizedRange.upper*rangeFac;
} //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1))
else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0)
{
// case upper is 0
if (-rangeFac > sanitizedRange.lower*rangeFac)
sanitizedRange.upper = -rangeFac;
else
sanitizedRange.upper = sanitizedRange.lower*rangeFac;
} else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0)
{
// find out whether negative or positive interval is wider to decide which sign domain will be chosen
if (-sanitizedRange.lower > sanitizedRange.upper)
{
// negative is wider, do same as in case upper is 0
if (-rangeFac > sanitizedRange.lower*rangeFac)
sanitizedRange.upper = -rangeFac;
else
sanitizedRange.upper = sanitizedRange.lower*rangeFac;
} else
{
// positive is wider, do same as in case lower is 0
if (rangeFac < sanitizedRange.upper*rangeFac)
sanitizedRange.lower = rangeFac;
else
sanitizedRange.lower = sanitizedRange.upper*rangeFac;
}
}
// due to normalization, case lower>0 && upper<0 should never occur, because that implies upper<lower
return sanitizedRange;
}
/*!
Returns a sanitized version of the range. Sanitized means for linear scales, that
\a lower will always be numerically smaller (or equal) to \a upper.
*/
QCPRange QCPRange::sanitizedForLinScale() const
{
QCPRange sanitizedRange(lower, upper);
sanitizedRange.normalize();
return sanitizedRange;
}
/*!
Checks, whether the specified range is within valid bounds, which are defined
as QCPRange::maxRange and QCPRange::minRange.
A valid range means:
\li range bounds within -maxRange and maxRange
\li range size above minRange
\li range size below maxRange
*/
bool QCPRange::validRange(double lower, double upper)
{
return (lower > -maxRange &&
upper < maxRange &&
qAbs(lower-upper) > minRange &&
qAbs(lower-upper) < maxRange &&
!(lower > 0 && qIsInf(upper/lower)) &&
!(upper < 0 && qIsInf(lower/upper)));
}
/*!
\overload
Checks, whether the specified range is within valid bounds, which are defined
as QCPRange::maxRange and QCPRange::minRange.
A valid range means:
\li range bounds within -maxRange and maxRange
\li range size above minRange
\li range size below maxRange
*/
bool QCPRange::validRange(const QCPRange &range)
{
return (range.lower > -maxRange &&
range.upper < maxRange &&
qAbs(range.lower-range.upper) > minRange &&
qAbs(range.lower-range.upper) < maxRange &&
!(range.lower > 0 && qIsInf(range.upper/range.lower)) &&
!(range.upper < 0 && qIsInf(range.lower/range.upper)));
}
/* end of 'src/axis/range.cpp' */
/* including file 'src/selection.cpp' */
/* modified 2022-11-06T12:45:56, size 21837 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPDataRange
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPDataRange
\brief Describes a data range given by begin and end index
QCPDataRange holds two integers describing the begin (\ref setBegin) and end (\ref setEnd) index
of a contiguous set of data points. The \a end index corresponds to the data point just after the
last data point of the data range, like in standard iterators.
Data Ranges are not bound to a certain plottable, thus they can be freely exchanged, created and
modified. If a non-contiguous data set shall be described, the class \ref QCPDataSelection is
used, which holds and manages multiple instances of \ref QCPDataRange. In most situations, \ref
QCPDataSelection is thus used.
Both \ref QCPDataRange and \ref QCPDataSelection offer convenience methods to work with them,
e.g. \ref bounded, \ref expanded, \ref intersects, \ref intersection, \ref adjusted, \ref
contains. Further, addition and subtraction operators (defined in \ref QCPDataSelection) can be
used to join/subtract data ranges and data selections (or mixtures), to retrieve a corresponding
\ref QCPDataSelection.
%QCustomPlot's \ref dataselection "data selection mechanism" is based on \ref QCPDataSelection and
QCPDataRange.
\note Do not confuse \ref QCPDataRange with \ref QCPRange. A \ref QCPRange describes an interval
in floating point plot coordinates, e.g. the current axis range.
*/
/* start documentation of inline functions */
/*! \fn int QCPDataRange::size() const
Returns the number of data points described by this data range. This is equal to the end index
minus the begin index.
\see length
*/
/*! \fn int QCPDataRange::length() const
Returns the number of data points described by this data range. Equivalent to \ref size.
*/
/*! \fn void QCPDataRange::setBegin(int begin)
Sets the begin of this data range. The \a begin index points to the first data point that is part
of the data range.
No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
\see setEnd
*/
/*! \fn void QCPDataRange::setEnd(int end)
Sets the end of this data range. The \a end index points to the data point just after the last
data point that is part of the data range.
No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
\see setBegin
*/
/*! \fn bool QCPDataRange::isValid() const
Returns whether this range is valid. A valid range has a begin index greater or equal to 0, and
an end index greater or equal to the begin index.
\note Invalid ranges should be avoided and are never the result of any of QCustomPlot's methods
(unless they are themselves fed with invalid ranges). Do not pass invalid ranges to QCustomPlot's
methods. The invalid range is not inherently prevented in QCPDataRange, to allow temporary
invalid begin/end values while manipulating the range. An invalid range is not necessarily empty
(\ref isEmpty), since its \ref length can be negative and thus non-zero.
*/
/*! \fn bool QCPDataRange::isEmpty() const
Returns whether this range is empty, i.e. whether its begin index equals its end index.
\see size, length
*/
/*! \fn QCPDataRange QCPDataRange::adjusted(int changeBegin, int changeEnd) const
Returns a data range where \a changeBegin and \a changeEnd were added to the begin and end
indices, respectively.
*/
/* end documentation of inline functions */
/*!
Creates an empty QCPDataRange, with begin and end set to 0.
*/
QCPDataRange::QCPDataRange() :
mBegin(0),
mEnd(0)
{
}
/*!
Creates a QCPDataRange, initialized with the specified \a begin and \a end.
No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
*/
QCPDataRange::QCPDataRange(int begin, int end) :
mBegin(begin),
mEnd(end)
{
}
/*!
Returns a data range that matches this data range, except that parts exceeding \a other are
excluded.
This method is very similar to \ref intersection, with one distinction: If this range and the \a
other range share no intersection, the returned data range will be empty with begin and end set
to the respective boundary side of \a other, at which this range is residing. (\ref intersection
would just return a range with begin and end set to 0.)
*/
QCPDataRange QCPDataRange::bounded(const QCPDataRange &other) const
{
QCPDataRange result(intersection(other));
if (result.isEmpty()) // no intersection, preserve respective bounding side of otherRange as both begin and end of return value
{
if (mEnd <= other.mBegin)
result = QCPDataRange(other.mBegin, other.mBegin);
else
result = QCPDataRange(other.mEnd, other.mEnd);
}
return result;
}
/*!
Returns a data range that contains both this data range as well as \a other.
*/
QCPDataRange QCPDataRange::expanded(const QCPDataRange &other) const
{
return {qMin(mBegin, other.mBegin), qMax(mEnd, other.mEnd)};
}
/*!
Returns the data range which is contained in both this data range and \a other.
This method is very similar to \ref bounded, with one distinction: If this range and the \a other
range share no intersection, the returned data range will be empty with begin and end set to 0.
(\ref bounded would return a range with begin and end set to one of the boundaries of \a other,
depending on which side this range is on.)
\see QCPDataSelection::intersection
*/
QCPDataRange QCPDataRange::intersection(const QCPDataRange &other) const
{
QCPDataRange result(qMax(mBegin, other.mBegin), qMin(mEnd, other.mEnd));
if (result.isValid())
return result;
else
return {};
}
/*!
Returns whether this data range and \a other share common data points.
\see intersection, contains
*/
bool QCPDataRange::intersects(const QCPDataRange &other) const
{
return !( (mBegin > other.mBegin && mBegin >= other.mEnd) ||
(mEnd <= other.mBegin && mEnd < other.mEnd) );
}
/*!
Returns whether all data points of \a other are also contained inside this data range.
\see intersects
*/
bool QCPDataRange::contains(const QCPDataRange &other) const
{
return mBegin <= other.mBegin && mEnd >= other.mEnd;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPDataSelection
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPDataSelection
\brief Describes a data set by holding multiple QCPDataRange instances
QCPDataSelection manages multiple instances of QCPDataRange in order to represent any (possibly
disjoint) set of data selection.
The data selection can be modified with addition and subtraction operators which take
QCPDataSelection and QCPDataRange instances, as well as methods such as \ref addDataRange and
\ref clear. Read access is provided by \ref dataRange, \ref dataRanges, \ref dataRangeCount, etc.
The method \ref simplify is used to join directly adjacent or even overlapping QCPDataRange
instances. QCPDataSelection automatically simplifies when using the addition/subtraction
operators. The only case when \ref simplify is left to the user, is when calling \ref
addDataRange, with the parameter \a simplify explicitly set to false. This is useful if many data
ranges will be added to the selection successively and the overhead for simplifying after each
iteration shall be avoided. In this case, you should make sure to call \ref simplify after
completing the operation.
Use \ref enforceType to bring the data selection into a state complying with the constraints for
selections defined in \ref QCP::SelectionType.
%QCustomPlot's \ref dataselection "data selection mechanism" is based on QCPDataSelection and
QCPDataRange.
\section qcpdataselection-iterating Iterating over a data selection
As an example, the following code snippet calculates the average value of a graph's data
\ref QCPAbstractPlottable::selection "selection":
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpdataselection-iterating-1
*/
/* start documentation of inline functions */
/*! \fn int QCPDataSelection::dataRangeCount() const
Returns the number of ranges that make up the data selection. The ranges can be accessed by \ref
dataRange via their index.
\see dataRange, dataPointCount
*/
/*! \fn QList<QCPDataRange> QCPDataSelection::dataRanges() const
Returns all data ranges that make up the data selection. If the data selection is simplified (the
usual state of the selection, see \ref simplify), the ranges are sorted by ascending data point
index.
\see dataRange
*/
/*! \fn bool QCPDataSelection::isEmpty() const
Returns true if there are no data ranges, and thus no data points, in this QCPDataSelection
instance.
\see dataRangeCount
*/
/* end documentation of inline functions */
/*!
Creates an empty QCPDataSelection.
*/
QCPDataSelection::QCPDataSelection()
{
}
/*!
Creates a QCPDataSelection containing the provided \a range.
*/
QCPDataSelection::QCPDataSelection(const QCPDataRange &range)
{
mDataRanges.append(range);
}
/*!
Returns true if this selection is identical (contains the same data ranges with the same begin
and end indices) to \a other.
Note that both data selections must be in simplified state (the usual state of the selection, see
\ref simplify) for this operator to return correct results.
*/
bool QCPDataSelection::operator==(const QCPDataSelection &other) const
{
if (mDataRanges.size() != other.mDataRanges.size())
return false;
for (int i=0; i<mDataRanges.size(); ++i)
{
if (mDataRanges.at(i) != other.mDataRanges.at(i))
return false;
}
return true;
}
/*!
Adds the data selection of \a other to this data selection, and then simplifies this data
selection (see \ref simplify).
*/
QCPDataSelection &QCPDataSelection::operator+=(const QCPDataSelection &other)
{
mDataRanges << other.mDataRanges;
simplify();
return *this;
}
/*!
Adds the data range \a other to this data selection, and then simplifies this data selection (see
\ref simplify).
*/
QCPDataSelection &QCPDataSelection::operator+=(const QCPDataRange &other)
{
addDataRange(other);
return *this;
}
/*!
Removes all data point indices that are described by \a other from this data selection.
*/
QCPDataSelection &QCPDataSelection::operator-=(const QCPDataSelection &other)
{
for (int i=0; i<other.dataRangeCount(); ++i)
*this -= other.dataRange(i);
return *this;
}
/*!
Removes all data point indices that are described by \a other from this data selection.
*/
QCPDataSelection &QCPDataSelection::operator-=(const QCPDataRange &other)
{
if (other.isEmpty() || isEmpty())
return *this;
simplify();
int i=0;
while (i < mDataRanges.size())
{
const int thisBegin = mDataRanges.at(i).begin();
const int thisEnd = mDataRanges.at(i).end();
if (thisBegin >= other.end())
break; // since data ranges are sorted after the simplify() call, no ranges which contain other will come after this
if (thisEnd > other.begin()) // ranges which don't fulfill this are entirely before other and can be ignored
{
if (thisBegin >= other.begin()) // range leading segment is encompassed
{
if (thisEnd <= other.end()) // range fully encompassed, remove completely
{
mDataRanges.removeAt(i);
continue;
} else // only leading segment is encompassed, trim accordingly
mDataRanges[i].setBegin(other.end());
} else // leading segment is not encompassed
{
if (thisEnd <= other.end()) // only trailing segment is encompassed, trim accordingly
{
mDataRanges[i].setEnd(other.begin());
} else // other lies inside this range, so split range
{
mDataRanges[i].setEnd(other.begin());
mDataRanges.insert(i+1, QCPDataRange(other.end(), thisEnd));
break; // since data ranges are sorted (and don't overlap) after simplify() call, we're done here
}
}
}
++i;
}
return *this;
}
/*!
Returns the total number of data points contained in all data ranges that make up this data
selection.
*/
int QCPDataSelection::dataPointCount() const
{
int result = 0;
foreach (QCPDataRange dataRange, mDataRanges)
result += dataRange.length();
return result;
}
/*!
Returns the data range with the specified \a index.
If the data selection is simplified (the usual state of the selection, see \ref simplify), the
ranges are sorted by ascending data point index.
\see dataRangeCount
*/
QCPDataRange QCPDataSelection::dataRange(int index) const
{
if (index >= 0 && index < mDataRanges.size())
{
return mDataRanges.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of range:" << index;
return {};
}
}
/*!
Returns a \ref QCPDataRange which spans the entire data selection, including possible
intermediate segments which are not part of the original data selection.
*/
QCPDataRange QCPDataSelection::span() const
{
if (isEmpty())
return {};
else
return {mDataRanges.first().begin(), mDataRanges.last().end()};
}
/*!
Adds the given \a dataRange to this data selection. This is equivalent to the += operator but
allows disabling immediate simplification by setting \a simplify to false. This can improve
performance if adding a very large amount of data ranges successively. In this case, make sure to
call \ref simplify manually, after the operation.
*/
void QCPDataSelection::addDataRange(const QCPDataRange &dataRange, bool simplify)
{
mDataRanges.append(dataRange);
if (simplify)
this->simplify();
}
/*!
Removes all data ranges. The data selection then contains no data points.
\ref isEmpty
*/
void QCPDataSelection::clear()
{
mDataRanges.clear();
}
/*!
Sorts all data ranges by range begin index in ascending order, and then joins directly adjacent
or overlapping ranges. This can reduce the number of individual data ranges in the selection, and
prevents possible double-counting when iterating over the data points held by the data ranges.
This method is automatically called when using the addition/subtraction operators. The only case
when \ref simplify is left to the user, is when calling \ref addDataRange, with the parameter \a
simplify explicitly set to false.
*/
void QCPDataSelection::simplify()
{
// remove any empty ranges:
for (int i=static_cast<int>(mDataRanges.size())-1; i>=0; --i)
{
if (mDataRanges.at(i).isEmpty())
mDataRanges.removeAt(i);
}
if (mDataRanges.isEmpty())
return;
// sort ranges by starting value, ascending:
std::sort(mDataRanges.begin(), mDataRanges.end(), lessThanDataRangeBegin);
// join overlapping/contiguous ranges:
int i = 1;
while (i < mDataRanges.size())
{
if (mDataRanges.at(i-1).end() >= mDataRanges.at(i).begin()) // range i overlaps/joins with i-1, so expand range i-1 appropriately and remove range i from list
{
mDataRanges[i-1].setEnd(qMax(mDataRanges.at(i-1).end(), mDataRanges.at(i).end()));
mDataRanges.removeAt(i);
} else
++i;
}
}
/*!
Makes sure this data selection conforms to the specified \a type selection type. Before the type
is enforced, \ref simplify is called.
Depending on \a type, enforcing means adding new data points that were previously not part of the
selection, or removing data points from the selection. If the current selection already conforms
to \a type, the data selection is not changed.
\see QCP::SelectionType
*/
void QCPDataSelection::enforceType(QCP::SelectionType type)
{
simplify();
switch (type)
{
case QCP::stNone:
{
mDataRanges.clear();
break;
}
case QCP::stWhole:
{
// whole selection isn't defined by data range, so don't change anything (is handled in plottable methods)
break;
}
case QCP::stSingleData:
{
// reduce all data ranges to the single first data point:
if (!mDataRanges.isEmpty())
{
if (mDataRanges.size() > 1)
mDataRanges = QList<QCPDataRange>() << mDataRanges.first();
if (mDataRanges.first().length() > 1)
mDataRanges.first().setEnd(mDataRanges.first().begin()+1);
}
break;
}
case QCP::stDataRange:
{
if (!isEmpty())
mDataRanges = QList<QCPDataRange>() << span();
break;
}
case QCP::stMultipleDataRanges:
{
// this is the selection type that allows all concievable combinations of ranges, so do nothing
break;
}
}
}
/*!
Returns true if the data selection \a other is contained entirely in this data selection, i.e.
all data point indices that are in \a other are also in this data selection.
\see QCPDataRange::contains
*/
bool QCPDataSelection::contains(const QCPDataSelection &other) const
{
if (other.isEmpty()) return false;
int otherIndex = 0;
int thisIndex = 0;
while (thisIndex < mDataRanges.size() && otherIndex < other.mDataRanges.size())
{
if (mDataRanges.at(thisIndex).contains(other.mDataRanges.at(otherIndex)))
++otherIndex;
else
++thisIndex;
}
return thisIndex < mDataRanges.size(); // if thisIndex ran all the way to the end to find a containing range for the current otherIndex, other is not contained in this
}
/*!
Returns a data selection containing the points which are both in this data selection and in the
data range \a other.
A common use case is to limit an unknown data selection to the valid range of a data container,
using \ref QCPDataContainer::dataRange as \a other. One can then safely iterate over the returned
data selection without exceeding the data container's bounds.
*/
QCPDataSelection QCPDataSelection::intersection(const QCPDataRange &other) const
{
QCPDataSelection result;
foreach (QCPDataRange dataRange, mDataRanges)
result.addDataRange(dataRange.intersection(other), false);
result.simplify();
return result;
}
/*!
Returns a data selection containing the points which are both in this data selection and in the
data selection \a other.
*/
QCPDataSelection QCPDataSelection::intersection(const QCPDataSelection &other) const
{
QCPDataSelection result;
for (int i=0; i<other.dataRangeCount(); ++i)
result += intersection(other.dataRange(i));
result.simplify();
return result;
}
/*!
Returns a data selection which is the exact inverse of this data selection, with \a outerRange
defining the base range on which to invert. If \a outerRange is smaller than the \ref span of
this data selection, it is expanded accordingly.
For example, this method can be used to retrieve all unselected segments by setting \a outerRange
to the full data range of the plottable, and calling this method on a data selection holding the
selected segments.
*/
QCPDataSelection QCPDataSelection::inverse(const QCPDataRange &outerRange) const
{
if (isEmpty())
return QCPDataSelection(outerRange);
QCPDataRange fullRange = outerRange.expanded(span());
QCPDataSelection result;
// first unselected segment:
if (mDataRanges.first().begin() != fullRange.begin())
result.addDataRange(QCPDataRange(fullRange.begin(), mDataRanges.first().begin()), false);
// intermediate unselected segments:
for (int i=1; i<mDataRanges.size(); ++i)
result.addDataRange(QCPDataRange(mDataRanges.at(i-1).end(), mDataRanges.at(i).begin()), false);
// last unselected segment:
if (mDataRanges.last().end() != fullRange.end())
result.addDataRange(QCPDataRange(mDataRanges.last().end(), fullRange.end()), false);
result.simplify();
return result;
}
/* end of 'src/selection.cpp' */
/* including file 'src/selectionrect.cpp' */
/* modified 2022-11-06T12:45:56, size 9215 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPSelectionRect
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPSelectionRect
\brief Provides rect/rubber-band data selection and range zoom interaction
QCPSelectionRect is used by QCustomPlot when the \ref QCustomPlot::setSelectionRectMode is not
\ref QCP::srmNone. When the user drags the mouse across the plot, the current selection rect
instance (\ref QCustomPlot::setSelectionRect) is forwarded these events and makes sure an
according rect shape is drawn. At the begin, during, and after completion of the interaction, it
emits the corresponding signals \ref started, \ref changed, \ref canceled, and \ref accepted.
The QCustomPlot instance connects own slots to the current selection rect instance, in order to
react to an accepted selection rect interaction accordingly.
\ref isActive can be used to check whether the selection rect is currently active. An ongoing
selection interaction can be cancelled programmatically via calling \ref cancel at any time.
The appearance of the selection rect can be controlled via \ref setPen and \ref setBrush.
If you wish to provide custom behaviour, e.g. a different visual representation of the selection
rect (\ref QCPSelectionRect::draw), you can subclass QCPSelectionRect and pass an instance of
your subclass to \ref QCustomPlot::setSelectionRect.
*/
/* start of documentation of inline functions */
/*! \fn bool QCPSelectionRect::isActive() const
Returns true if there is currently a selection going on, i.e. the user has started dragging a
selection rect, but hasn't released the mouse button yet.
\see cancel
*/
/* end of documentation of inline functions */
/* start documentation of signals */
/*! \fn void QCPSelectionRect::started(QMouseEvent *event);
This signal is emitted when a selection rect interaction was initiated, i.e. the user just
started dragging the selection rect with the mouse.
*/
/*! \fn void QCPSelectionRect::changed(const QRect &rect, QMouseEvent *event);
This signal is emitted while the selection rect interaction is ongoing and the \a rect has
changed its size due to the user moving the mouse.
Note that \a rect may have a negative width or height, if the selection is being dragged to the
upper or left side of the selection rect origin.
*/
/*! \fn void QCPSelectionRect::canceled(const QRect &rect, QInputEvent *event);
This signal is emitted when the selection interaction was cancelled. Note that \a event is \c
nullptr if the selection interaction was cancelled programmatically, by a call to \ref cancel.
The user may cancel the selection interaction by pressing the escape key. In this case, \a event
holds the respective input event.
Note that \a rect may have a negative width or height, if the selection is being dragged to the
upper or left side of the selection rect origin.
*/
/*! \fn void QCPSelectionRect::accepted(const QRect &rect, QMouseEvent *event);
This signal is emitted when the selection interaction was completed by the user releasing the
mouse button.
Note that \a rect may have a negative width or height, if the selection is being dragged to the
upper or left side of the selection rect origin.
*/
/* end documentation of signals */
/*!
Creates a new QCPSelectionRect instance. To make QCustomPlot use the selection rect instance,
pass it to \ref QCustomPlot::setSelectionRect. \a parentPlot should be set to the same
QCustomPlot widget.
*/
QCPSelectionRect::QCPSelectionRect(QCustomPlot *parentPlot) :
QCPLayerable(parentPlot),
mPen(QBrush(Qt::gray), 0, Qt::DashLine),
mBrush(Qt::NoBrush),
mActive(false)
{
}
QCPSelectionRect::~QCPSelectionRect()
{
cancel();
}
/*!
A convenience function which returns the coordinate range of the provided \a axis, that this
selection rect currently encompasses.
*/
QCPRange QCPSelectionRect::range(const QCPAxis *axis) const
{
if (axis)
{
if (axis->orientation() == Qt::Horizontal)
return {axis->pixelToCoord(mRect.left()), axis->pixelToCoord(mRect.left()+mRect.width())};
else
return {axis->pixelToCoord(mRect.top()+mRect.height()), axis->pixelToCoord(mRect.top())};
} else
{
qDebug() << Q_FUNC_INFO << "called with axis zero";
return {};
}
}
/*!
Sets the pen that will be used to draw the selection rect outline.
\see setBrush
*/
void QCPSelectionRect::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the brush that will be used to fill the selection rect. By default the selection rect is not
filled, i.e. \a brush is <tt>Qt::NoBrush</tt>.
\see setPen
*/
void QCPSelectionRect::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
If there is currently a selection interaction going on (\ref isActive), the interaction is
canceled. The selection rect will emit the \ref canceled signal.
*/
void QCPSelectionRect::cancel()
{
if (mActive)
{
mActive = false;
emit canceled(mRect, nullptr);
}
}
/*! \internal
This method is called by QCustomPlot to indicate that a selection rect interaction was initiated.
The default implementation sets the selection rect to active, initializes the selection rect
geometry and emits the \ref started signal.
*/
void QCPSelectionRect::startSelection(QMouseEvent *event)
{
mActive = true;
mRect = QRect(event->pos(), event->pos());
emit started(event);
}
/*! \internal
This method is called by QCustomPlot to indicate that an ongoing selection rect interaction needs
to update its geometry. The default implementation updates the rect and emits the \ref changed
signal.
*/
void QCPSelectionRect::moveSelection(QMouseEvent *event)
{
mRect.setBottomRight(event->pos());
emit changed(mRect, event);
layer()->replot();
}
/*! \internal
This method is called by QCustomPlot to indicate that an ongoing selection rect interaction has
finished by the user releasing the mouse button. The default implementation deactivates the
selection rect and emits the \ref accepted signal.
*/
void QCPSelectionRect::endSelection(QMouseEvent *event)
{
mRect.setBottomRight(event->pos());
mActive = false;
emit accepted(mRect, event);
}
/*! \internal
This method is called by QCustomPlot when a key has been pressed by the user while the selection
rect interaction is active. The default implementation allows to \ref cancel the interaction by
hitting the escape key.
*/
void QCPSelectionRect::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Escape && mActive)
{
mActive = false;
emit canceled(mRect, event);
}
}
/* inherits documentation from base class */
void QCPSelectionRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
}
/*! \internal
If the selection rect is active (\ref isActive), draws the selection rect defined by \a mRect.
\seebaseclassmethod
*/
void QCPSelectionRect::draw(QCPPainter *painter)
{
if (mActive)
{
painter->setPen(mPen);
painter->setBrush(mBrush);
painter->drawRect(mRect);
}
}
/* end of 'src/selectionrect.cpp' */
/* including file 'src/layout.cpp' */
/* modified 2022-11-06T12:45:56, size 78863 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPMarginGroup
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPMarginGroup
\brief A margin group allows synchronization of margin sides if working with multiple layout elements.
QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that
they will all have the same size, based on the largest required margin in the group.
\n
\image html QCPMarginGroup.png "Demonstration of QCPMarginGroup"
\n
In certain situations it is desirable that margins at specific sides are synchronized across
layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will
provide a cleaner look to the user if the left and right margins of the two axis rects are of the
same size. The left axis of the top axis rect will then be at the same horizontal position as the
left axis of the lower axis rect, making them appear aligned. The same applies for the right
axes. This is what QCPMarginGroup makes possible.
To add/remove a specific side of a layout element to/from a margin group, use the \ref
QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call
\ref clear, or just delete the margin group.
\section QCPMarginGroup-example Example
First create a margin group:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1
Then set this group on the layout element sides:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-2
Here, we've used the first two axis rects of the plot and synchronized their left margins with
each other and their right margins with each other.
*/
/* start documentation of inline functions */
/*! \fn QList<QCPLayoutElement*> QCPMarginGroup::elements(QCP::MarginSide side) const
Returns a list of all layout elements that have their margin \a side associated with this margin
group.
*/
/* end documentation of inline functions */
/*!
Creates a new QCPMarginGroup instance in \a parentPlot.
*/
QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) :
QObject(parentPlot),
mParentPlot(parentPlot)
{
mChildren.insert(QCP::msLeft, QList<QCPLayoutElement*>());
mChildren.insert(QCP::msRight, QList<QCPLayoutElement*>());
mChildren.insert(QCP::msTop, QList<QCPLayoutElement*>());
mChildren.insert(QCP::msBottom, QList<QCPLayoutElement*>());
}
QCPMarginGroup::~QCPMarginGroup()
{
clear();
}
/*!
Returns whether this margin group is empty. If this function returns true, no layout elements use
this margin group to synchronize margin sides.
*/
bool QCPMarginGroup::isEmpty() const
{
QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
while (it.hasNext())
{
it.next();
if (!it.value().isEmpty())
return false;
}
return true;
}
/*!
Clears this margin group. The synchronization of the margin sides that use this margin group is
lifted and they will use their individual margin sizes again.
*/
void QCPMarginGroup::clear()
{
// make all children remove themselves from this margin group:
QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
while (it.hasNext())
{
it.next();
const QList<QCPLayoutElement*> elements = it.value();
for (int i=static_cast<int>(elements.size())-1; i>=0; --i)
elements.at(i)->setMarginGroup(it.key(), nullptr); // removes itself from mChildren via removeChild
}
}
/*! \internal
Returns the synchronized common margin for \a side. This is the margin value that will be used by
the layout element on the respective side, if it is part of this margin group.
The common margin is calculated by requesting the automatic margin (\ref
QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin
group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into
account, too.)
*/
int QCPMarginGroup::commonMargin(QCP::MarginSide side) const
{
// query all automatic margins of the layout elements in this margin group side and find maximum:
int result = 0;
foreach (QCPLayoutElement *el, mChildren.value(side))
{
if (!el->autoMargins().testFlag(side))
continue;
int m = qMax(el->calculateAutoMargin(side), QCP::getMarginValue(el->minimumMargins(), side));
if (m > result)
result = m;
}
return result;
}
/*! \internal
Adds \a element to the internal list of child elements, for the margin \a side.
This function does not modify the margin group property of \a element.
*/
void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element)
{
if (!mChildren[side].contains(element))
mChildren[side].append(element);
else
qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast<quintptr>(element);
}
/*! \internal
Removes \a element from the internal list of child elements, for the margin \a side.
This function does not modify the margin group property of \a element.
*/
void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element)
{
if (!mChildren[side].removeOne(element))
qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast<quintptr>(element);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayoutElement
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayoutElement
\brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system".
This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses.
A Layout element is a rectangular object which can be placed in layouts. It has an outer rect
(QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference
between outer and inner rect is called its margin. The margin can either be set to automatic or
manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be
set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic,
the layout element subclass will control the value itself (via \ref calculateAutoMargin).
Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level
layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref
QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested.
Thus in QCustomPlot one can divide layout elements into two categories: The ones that are
invisible by themselves, because they don't draw anything. Their only purpose is to manage the
position and size of other layout elements. This category of layout elements usually use
QCPLayout as base class. Then there is the category of layout elements which actually draw
something. For example, QCPAxisRect, QCPLegend and QCPTextElement are of this category. This does
not necessarily mean that the latter category can't have child layout elements. QCPLegend for
instance, actually derives from QCPLayoutGrid and the individual legend items are child layout
elements in the grid layout.
*/
/* start documentation of inline functions */
/*! \fn QCPLayout *QCPLayoutElement::layout() const
Returns the parent layout of this layout element.
*/
/*! \fn QRect QCPLayoutElement::rect() const
Returns the inner rect of this layout element. The inner rect is the outer rect (\ref outerRect, \ref
setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins).
In some cases, the area between outer and inner rect is left blank. In other cases the margin
area is used to display peripheral graphics while the main content is in the inner rect. This is
where automatic margin calculation becomes interesting because it allows the layout element to
adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect
draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if
\ref setAutoMargins is enabled) according to the space required by the labels of the axes.
\see outerRect
*/
/*! \fn QRect QCPLayoutElement::outerRect() const
Returns the outer rect of this layout element. The outer rect is the inner rect expanded by the
margins (\ref setMargins, \ref setAutoMargins). The outer rect is used (and set via \ref
setOuterRect) by the parent \ref QCPLayout to control the size of this layout element.
\see rect
*/
/* end documentation of inline functions */
/*!
Creates an instance of QCPLayoutElement and sets default values.
*/
QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) :
QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout)
mParentLayout(nullptr),
mMinimumSize(),
mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX),
mSizeConstraintRect(scrInnerRect),
mRect(0, 0, 0, 0),
mOuterRect(0, 0, 0, 0),
mMargins(0, 0, 0, 0),
mMinimumMargins(0, 0, 0, 0),
mAutoMargins(QCP::msAll)
{
}
QCPLayoutElement::~QCPLayoutElement()
{
setMarginGroup(QCP::msAll, nullptr); // unregister at margin groups, if there are any
// unregister at layout:
if (qobject_cast<QCPLayout*>(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor
mParentLayout->take(this);
}
/*!
Sets the outer rect of this layout element. If the layout element is inside a layout, the layout
sets the position and size of this layout element using this function.
Calling this function externally has no effect, since the layout will overwrite any changes to
the outer rect upon the next replot.
The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect.
\see rect
*/
void QCPLayoutElement::setOuterRect(const QRect &rect)
{
if (mOuterRect != rect)
{
mOuterRect = rect;
mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
}
}
/*!
Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all
sides, this function is used to manually set the margin on those sides. Sides that are still set
to be handled automatically are ignored and may have any value in \a margins.
The margin is the distance between the outer rect (controlled by the parent layout via \ref
setOuterRect) and the inner \ref rect (which usually contains the main content of this layout
element).
\see setAutoMargins
*/
void QCPLayoutElement::setMargins(const QMargins &margins)
{
if (mMargins != margins)
{
mMargins = margins;
mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
}
}
/*!
If \ref setAutoMargins is enabled on some or all margins, this function is used to provide
minimum values for those margins.
The minimum values are not enforced on margin sides that were set to be under manual control via
\ref setAutoMargins.
\see setAutoMargins
*/
void QCPLayoutElement::setMinimumMargins(const QMargins &margins)
{
if (mMinimumMargins != margins)
{
mMinimumMargins = margins;
}
}
/*!
Sets on which sides the margin shall be calculated automatically. If a side is calculated
automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is
set to be controlled manually, the value may be specified with \ref setMargins.
Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref
setMarginGroup), to synchronize (align) it with other layout elements in the plot.
\see setMinimumMargins, setMargins, QCP::MarginSide
*/
void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides)
{
mAutoMargins = sides;
}
/*!
Sets the minimum size of this layout element. A parent layout tries to respect the \a size here
by changing row/column sizes in the layout accordingly.
If the parent layout size is not sufficient to satisfy all minimum size constraints of its child
layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot
propagates the layout's size constraints to the outside by setting its own minimum QWidget size
accordingly, so violations of \a size should be exceptions.
Whether this constraint applies to the inner or the outer rect can be specified with \ref
setSizeConstraintRect (see \ref rect and \ref outerRect).
*/
void QCPLayoutElement::setMinimumSize(const QSize &size)
{
if (mMinimumSize != size)
{
mMinimumSize = size;
if (mParentLayout)
mParentLayout->sizeConstraintsChanged();
}
}
/*! \overload
Sets the minimum size of this layout element.
Whether this constraint applies to the inner or the outer rect can be specified with \ref
setSizeConstraintRect (see \ref rect and \ref outerRect).
*/
void QCPLayoutElement::setMinimumSize(int width, int height)
{
setMinimumSize(QSize(width, height));
}
/*!
Sets the maximum size of this layout element. A parent layout tries to respect the \a size here
by changing row/column sizes in the layout accordingly.
Whether this constraint applies to the inner or the outer rect can be specified with \ref
setSizeConstraintRect (see \ref rect and \ref outerRect).
*/
void QCPLayoutElement::setMaximumSize(const QSize &size)
{
if (mMaximumSize != size)
{
mMaximumSize = size;
if (mParentLayout)
mParentLayout->sizeConstraintsChanged();
}
}
/*! \overload
Sets the maximum size of this layout element.
Whether this constraint applies to the inner or the outer rect can be specified with \ref
setSizeConstraintRect (see \ref rect and \ref outerRect).
*/
void QCPLayoutElement::setMaximumSize(int width, int height)
{
setMaximumSize(QSize(width, height));
}
/*!
Sets to which rect of a layout element the size constraints apply. Size constraints can be set
via \ref setMinimumSize and \ref setMaximumSize.
The outer rect (\ref outerRect) includes the margins (e.g. in the case of a QCPAxisRect the axis
labels), whereas the inner rect (\ref rect) does not.
\see setMinimumSize, setMaximumSize
*/
void QCPLayoutElement::setSizeConstraintRect(SizeConstraintRect constraintRect)
{
if (mSizeConstraintRect != constraintRect)
{
mSizeConstraintRect = constraintRect;
if (mParentLayout)
mParentLayout->sizeConstraintsChanged();
}
}
/*!
Sets the margin \a group of the specified margin \a sides.
Margin groups allow synchronizing specified margins across layout elements, see the documentation
of \ref QCPMarginGroup.
To unset the margin group of \a sides, set \a group to \c nullptr.
Note that margin groups only work for margin sides that are set to automatic (\ref
setAutoMargins).
\see QCP::MarginSide
*/
void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group)
{
QVector<QCP::MarginSide> sideVector;
if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft);
if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight);
if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop);
if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom);
foreach (QCP::MarginSide side, sideVector)
{
if (marginGroup(side) != group)
{
QCPMarginGroup *oldGroup = marginGroup(side);
if (oldGroup) // unregister at old group
oldGroup->removeChild(side, this);
if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there
{
mMarginGroups.remove(side);
} else // setting to a new group
{
mMarginGroups[side] = group;
group->addChild(side, this);
}
}
}
}
/*!
Updates the layout element and sub-elements. This function is automatically called before every
replot by the parent layout element. It is called multiple times, once for every \ref
UpdatePhase. The phases are run through in the order of the enum values. For details about what
happens at the different phases, see the documentation of \ref UpdatePhase.
Layout elements that have child elements should call the \ref update method of their child
elements, and pass the current \a phase unchanged.
The default implementation executes the automatic margin mechanism in the \ref upMargins phase.
Subclasses should make sure to call the base class implementation.
*/
void QCPLayoutElement::update(UpdatePhase phase)
{
if (phase == upMargins)
{
if (mAutoMargins != QCP::msNone)
{
// set the margins of this layout element according to automatic margin calculation, either directly or via a margin group:
QMargins newMargins = mMargins;
const QList<QCP::MarginSide> allMarginSides = QList<QCP::MarginSide>() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom;
foreach (QCP::MarginSide side, allMarginSides)
{
if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically
{
if (mMarginGroups.contains(side))
QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group
else
QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly
// apply minimum margin restrictions:
if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side))
QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side));
}
}
setMargins(newMargins);
}
}
}
/*!
Returns the suggested minimum size this layout element (the \ref outerRect) may be compressed to,
if no manual minimum size is set.
if a minimum size (\ref setMinimumSize) was not set manually, parent layouts use the returned size
(usually indirectly through \ref QCPLayout::getFinalMinimumOuterSize) to determine the minimum
allowed size of this layout element.
A manual minimum size is considered set if it is non-zero.
The default implementation simply returns the sum of the horizontal margins for the width and the
sum of the vertical margins for the height. Reimplementations may use their detailed knowledge
about the layout element's content to provide size hints.
*/
QSize QCPLayoutElement::minimumOuterSizeHint() const
{
return {mMargins.left()+mMargins.right(), mMargins.top()+mMargins.bottom()};
}
/*!
Returns the suggested maximum size this layout element (the \ref outerRect) may be expanded to,
if no manual maximum size is set.
if a maximum size (\ref setMaximumSize) was not set manually, parent layouts use the returned
size (usually indirectly through \ref QCPLayout::getFinalMaximumOuterSize) to determine the
maximum allowed size of this layout element.
A manual maximum size is considered set if it is smaller than Qt's \c QWIDGETSIZE_MAX.
The default implementation simply returns \c QWIDGETSIZE_MAX for both width and height, implying
no suggested maximum size. Reimplementations may use their detailed knowledge about the layout
element's content to provide size hints.
*/
QSize QCPLayoutElement::maximumOuterSizeHint() const
{
return {QWIDGETSIZE_MAX, QWIDGETSIZE_MAX};
}
/*!
Returns a list of all child elements in this layout element. If \a recursive is true, all
sub-child elements are included in the list, too.
\warning There may be \c nullptr entries in the returned list. For example, QCPLayoutGrid may
have empty cells which yield \c nullptr at the respective index.
*/
QList<QCPLayoutElement*> QCPLayoutElement::elements(bool recursive) const
{
Q_UNUSED(recursive)
return QList<QCPLayoutElement*>();
}
/*!
Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer
rect, this method returns a value corresponding to 0.99 times the parent plot's selection
tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is
true, -1.0 is returned.
See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
QCPLayoutElement subclasses may reimplement this method to provide more specific selection test
behaviour.
*/
double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable)
return -1;
if (QRectF(mOuterRect).contains(pos))
{
if (mParentPlot)
return mParentPlot->selectionTolerance()*0.99;
else
{
qDebug() << Q_FUNC_INFO << "parent plot not defined";
return -1;
}
} else
return -1;
}
/*! \internal
propagates the parent plot initialization to all child elements, by calling \ref
QCPLayerable::initializeParentPlot on them.
*/
void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot)
{
foreach (QCPLayoutElement *el, elements(false))
{
if (!el->parentPlot())
el->initializeParentPlot(parentPlot);
}
}
/*! \internal
Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a
side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the
returned value will not be smaller than the specified minimum margin.
The default implementation just returns the respective manual margin (\ref setMargins) or the
minimum margin, whichever is larger.
*/
int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side)
{
return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side));
}
/*! \internal
This virtual method is called when this layout element was moved to a different QCPLayout, or
when this layout element has changed its logical position (e.g. row and/or column) within the
same QCPLayout. Subclasses may use this to react accordingly.
Since this method is called after the completion of the move, you can access the new parent
layout via \ref layout().
The default implementation does nothing.
*/
void QCPLayoutElement::layoutChanged()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayout
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayout
\brief The abstract base class for layouts
This is an abstract base class for layout elements whose main purpose is to define the position
and size of other child layout elements. In most cases, layouts don't draw anything themselves
(but there are exceptions to this, e.g. QCPLegend).
QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts.
QCPLayout introduces a common interface for accessing and manipulating the child elements. Those
functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref
simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions
to this interface which are more specialized to the form of the layout. For example, \ref
QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid
more conveniently.
Since this is an abstract base class, you can't instantiate it directly. Rather use one of its
subclasses like QCPLayoutGrid or QCPLayoutInset.
For a general introduction to the layout system, see the dedicated documentation page \ref
thelayoutsystem "The Layout System".
*/
/* start documentation of pure virtual functions */
/*! \fn virtual int QCPLayout::elementCount() const = 0
Returns the number of elements/cells in the layout.
\see elements, elementAt
*/
/*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0
Returns the element in the cell with the given \a index. If \a index is invalid, returns \c
nullptr.
Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g.
QCPLayoutGrid), so this function may return \c nullptr in those cases. You may use this function
to check whether a cell is empty or not.
\see elements, elementCount, takeAt
*/
/*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0
Removes the element with the given \a index from the layout and returns it.
If the \a index is invalid or the cell with that index is empty, returns \c nullptr.
Note that some layouts don't remove the respective cell right away but leave an empty cell after
successful removal of the layout element. To collapse empty cells, use \ref simplify.
\see elementAt, take
*/
/*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0
Removes the specified \a element from the layout and returns true on success.
If the \a element isn't in this layout, returns false.
Note that some layouts don't remove the respective cell right away but leave an empty cell after
successful removal of the layout element. To collapse empty cells, use \ref simplify.
\see takeAt
*/
/* end documentation of pure virtual functions */
/*!
Creates an instance of QCPLayout and sets default values. Note that since QCPLayout
is an abstract base class, it can't be instantiated directly.
*/
QCPLayout::QCPLayout()
{
}
/*!
If \a phase is \ref upLayout, calls \ref updateLayout, which subclasses may reimplement to
reposition and resize their cells.
Finally, the call is propagated down to all child \ref QCPLayoutElement "QCPLayoutElements".
For details about this method and the update phases, see the documentation of \ref
QCPLayoutElement::update.
*/
void QCPLayout::update(UpdatePhase phase)
{
QCPLayoutElement::update(phase);
// set child element rects according to layout:
if (phase == upLayout)
updateLayout();
// propagate update call to child elements:
const int elCount = elementCount();
for (int i=0; i<elCount; ++i)
{
if (QCPLayoutElement *el = elementAt(i))
el->update(phase);
}
}
/* inherits documentation from base class */
QList<QCPLayoutElement*> QCPLayout::elements(bool recursive) const
{
const int c = elementCount();
QList<QCPLayoutElement*> result;
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
result.reserve(c);
#endif
for (int i=0; i<c; ++i)
result.append(elementAt(i));
if (recursive)
{
for (int i=0; i<c; ++i)
{
if (result.at(i))
result << result.at(i)->elements(recursive);
}
}
return result;
}
/*!
Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the
default implementation does nothing.
Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit
simplification while QCPLayoutGrid does.
*/
void QCPLayout::simplify()
{
}
/*!
Removes and deletes the element at the provided \a index. Returns true on success. If \a index is
invalid or points to an empty cell, returns false.
This function internally uses \ref takeAt to remove the element from the layout and then deletes
the returned element. Note that some layouts don't remove the respective cell right away but leave an
empty cell after successful removal of the layout element. To collapse empty cells, use \ref
simplify.
\see remove, takeAt
*/
bool QCPLayout::removeAt(int index)
{
if (QCPLayoutElement *el = takeAt(index))
{
delete el;
return true;
} else
return false;
}
/*!
Removes and deletes the provided \a element. Returns true on success. If \a element is not in the
layout, returns false.
This function internally uses \ref takeAt to remove the element from the layout and then deletes
the element. Note that some layouts don't remove the respective cell right away but leave an
empty cell after successful removal of the layout element. To collapse empty cells, use \ref
simplify.
\see removeAt, take
*/
bool QCPLayout::remove(QCPLayoutElement *element)
{
if (take(element))
{
delete element;
return true;
} else
return false;
}
/*!
Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure
all empty cells are collapsed.
\see remove, removeAt
*/
void QCPLayout::clear()
{
for (int i=elementCount()-1; i>=0; --i)
{
if (elementAt(i))
removeAt(i);
}
simplify();
}
/*!
Subclasses call this method to report changed (minimum/maximum) size constraints.
If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref
sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of
QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout,
it may update itself and resize cells accordingly.
*/
void QCPLayout::sizeConstraintsChanged() const
{
if (QWidget *w = qobject_cast<QWidget*>(parent()))
w->updateGeometry();
else if (QCPLayout *l = qobject_cast<QCPLayout*>(parent()))
l->sizeConstraintsChanged();
}
/*! \internal
Subclasses reimplement this method to update the position and sizes of the child elements/cells
via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing.
The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay
within that rect.
\ref getSectionSizes may help with the reimplementation of this function.
\see update
*/
void QCPLayout::updateLayout()
{
}
/*! \internal
Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the
\ref QCPLayerable::parentLayerable and the QObject parent to this layout.
Further, if \a el didn't previously have a parent plot, calls \ref
QCPLayerable::initializeParentPlot on \a el to set the paret plot.
This method is used by subclass specific methods that add elements to the layout. Note that this
method only changes properties in \a el. The removal from the old layout and the insertion into
the new layout must be done additionally.
*/
void QCPLayout::adoptElement(QCPLayoutElement *el)
{
if (el)
{
el->mParentLayout = this;
el->setParentLayerable(this);
el->setParent(this);
if (!el->parentPlot())
el->initializeParentPlot(mParentPlot);
el->layoutChanged();
} else
qDebug() << Q_FUNC_INFO << "Null element passed";
}
/*! \internal
Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout
and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent
QCustomPlot.
This method is used by subclass specific methods that remove elements from the layout (e.g. \ref
take or \ref takeAt). Note that this method only changes properties in \a el. The removal from
the old layout must be done additionally.
*/
void QCPLayout::releaseElement(QCPLayoutElement *el)
{
if (el)
{
el->mParentLayout = nullptr;
el->setParentLayerable(nullptr);
el->setParent(mParentPlot);
// Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot
} else
qDebug() << Q_FUNC_INFO << "Null element passed";
}
/*! \internal
This is a helper function for the implementation of \ref updateLayout in subclasses.
It calculates the sizes of one-dimensional sections with provided constraints on maximum section
sizes, minimum section sizes, relative stretch factors and the final total size of all sections.
The QVector entries refer to the sections. Thus all QVectors must have the same size.
\a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size
imposed, set all vector values to Qt's QWIDGETSIZE_MAX.
\a minSizes gives the minimum allowed size of each section. If there shall be no minimum size
imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than
\a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words,
not exceeding the allowed total size is taken to be more important than not going below minimum
section sizes.)
\a stretchFactors give the relative proportions of the sections to each other. If all sections
shall be scaled equally, set all values equal. If the first section shall be double the size of
each individual other section, set the first number of \a stretchFactors to double the value of
the other individual values (e.g. {2, 1, 1, 1}).
\a totalSize is the value that the final section sizes will add up to. Due to rounding, the
actual sum may differ slightly. If you want the section sizes to sum up to exactly that value,
you could distribute the remaining difference on the sections.
The return value is a QVector containing the section sizes.
*/
QVector<int> QCPLayout::getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes, QVector<double> stretchFactors, int totalSize) const
{
if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size())
{
qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors;
return QVector<int>();
}
if (stretchFactors.isEmpty())
return QVector<int>();
int sectionCount = static_cast<int>(stretchFactors.size());
QVector<double> sectionSizes(sectionCount);
// if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections):
int minSizeSum = 0;
for (int i=0; i<sectionCount; ++i)
minSizeSum += minSizes.at(i);
if (totalSize < minSizeSum)
{
// new stretch factors are minimum sizes and minimum sizes are set to zero:
for (int i=0; i<sectionCount; ++i)
{
stretchFactors[i] = minSizes.at(i);
minSizes[i] = 0;
}
}
QList<int> minimumLockedSections;
QList<int> unfinishedSections;
for (int i=0; i<sectionCount; ++i)
unfinishedSections.append(i);
double freeSize = totalSize;
int outerIterations = 0;
while (!unfinishedSections.isEmpty() && outerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
{
++outerIterations;
int innerIterations = 0;
while (!unfinishedSections.isEmpty() && innerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
{
++innerIterations;
// find section that hits its maximum next:
int nextId = -1;
double nextMax = 1e12;
foreach (int secId, unfinishedSections)
{
double hitsMaxAt = (maxSizes.at(secId)-sectionSizes.at(secId))/stretchFactors.at(secId);
if (hitsMaxAt < nextMax)
{
nextMax = hitsMaxAt;
nextId = secId;
}
}
// check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining sections so far that the found section
// actually hits its maximum, without exceeding the total size when we add up all sections)
double stretchFactorSum = 0;
foreach (int secId, unfinishedSections)
stretchFactorSum += stretchFactors.at(secId);
double nextMaxLimit = freeSize/stretchFactorSum;
if (nextMax < nextMaxLimit) // next maximum is actually hit, move forward to that point and fix the size of that section
{
foreach (int secId, unfinishedSections)
{
sectionSizes[secId] += nextMax*stretchFactors.at(secId); // increment all sections
freeSize -= nextMax*stretchFactors.at(secId);
}
unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes
} else // next maximum isn't hit, just distribute rest of free space on remaining sections
{
foreach (int secId, unfinishedSections)
sectionSizes[secId] += nextMaxLimit*stretchFactors.at(secId); // increment all sections
unfinishedSections.clear();
}
}
if (innerIterations == sectionCount*2)
qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
// now check whether the resulting section sizes violate minimum restrictions:
bool foundMinimumViolation = false;
for (int i=0; i<sectionSizes.size(); ++i)
{
if (minimumLockedSections.contains(i))
continue;
if (sectionSizes.at(i) < minSizes.at(i)) // section violates minimum
{
sectionSizes[i] = minSizes.at(i); // set it to minimum
foundMinimumViolation = true; // make sure we repeat the whole optimization process
minimumLockedSections.append(i);
}
}
if (foundMinimumViolation)
{
freeSize = totalSize;
for (int i=0; i<sectionCount; ++i)
{
if (!minimumLockedSections.contains(i)) // only put sections that haven't hit their minimum back into the pool
unfinishedSections.append(i);
else
freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round
}
// reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum):
foreach (int secId, unfinishedSections)
sectionSizes[secId] = 0;
}
}
if (outerIterations == sectionCount*2)
qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
QVector<int> result(sectionCount);
for (int i=0; i<sectionCount; ++i)
result[i] = qRound(sectionSizes.at(i));
return result;
}
/*! \internal
This is a helper function for the implementation of subclasses.
It returns the minimum size that should finally be used for the outer rect of the passed layout
element \a el.
It takes into account whether a manual minimum size is set (\ref
QCPLayoutElement::setMinimumSize), which size constraint is set (\ref
QCPLayoutElement::setSizeConstraintRect), as well as the minimum size hint, if no manual minimum
size was set (\ref QCPLayoutElement::minimumOuterSizeHint).
*/
QSize QCPLayout::getFinalMinimumOuterSize(const QCPLayoutElement *el)
{
QSize minOuterHint = el->minimumOuterSizeHint();
QSize minOuter = el->minimumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset minimum of 0)
if (minOuter.width() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
minOuter.rwidth() += el->margins().left() + el->margins().right();
if (minOuter.height() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
minOuter.rheight() += el->margins().top() + el->margins().bottom();
return {minOuter.width() > 0 ? minOuter.width() : minOuterHint.width(),
minOuter.height() > 0 ? minOuter.height() : minOuterHint.height()};
}
/*! \internal
This is a helper function for the implementation of subclasses.
It returns the maximum size that should finally be used for the outer rect of the passed layout
element \a el.
It takes into account whether a manual maximum size is set (\ref
QCPLayoutElement::setMaximumSize), which size constraint is set (\ref
QCPLayoutElement::setSizeConstraintRect), as well as the maximum size hint, if no manual maximum
size was set (\ref QCPLayoutElement::maximumOuterSizeHint).
*/
QSize QCPLayout::getFinalMaximumOuterSize(const QCPLayoutElement *el)
{
QSize maxOuterHint = el->maximumOuterSizeHint();
QSize maxOuter = el->maximumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset maximum of QWIDGETSIZE_MAX)
if (maxOuter.width() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
maxOuter.rwidth() += el->margins().left() + el->margins().right();
if (maxOuter.height() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
maxOuter.rheight() += el->margins().top() + el->margins().bottom();
return {maxOuter.width() < QWIDGETSIZE_MAX ? maxOuter.width() : maxOuterHint.width(),
maxOuter.height() < QWIDGETSIZE_MAX ? maxOuter.height() : maxOuterHint.height()};
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayoutGrid
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayoutGrid
\brief A layout that arranges child elements in a grid
Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor,
\ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing).
Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or
column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref
hasElement, that element can be retrieved with \ref element. If rows and columns that only have
empty cells shall be removed, call \ref simplify. Removal of elements is either done by just
adding the element to a different layout or by using the QCPLayout interface \ref take or \ref
remove.
If you use \ref addElement(QCPLayoutElement*) without explicit parameters for \a row and \a
column, the grid layout will choose the position according to the current \ref setFillOrder and
the wrapping (\ref setWrap).
Row and column insertion can be performed with \ref insertRow and \ref insertColumn.
*/
/* start documentation of inline functions */
/*! \fn int QCPLayoutGrid::rowCount() const
Returns the number of rows in the layout.
\see columnCount
*/
/*! \fn int QCPLayoutGrid::columnCount() const
Returns the number of columns in the layout.
\see rowCount
*/
/* end documentation of inline functions */
/*!
Creates an instance of QCPLayoutGrid and sets default values.
*/
QCPLayoutGrid::QCPLayoutGrid() :
mColumnSpacing(5),
mRowSpacing(5),
mWrap(0),
mFillOrder(foColumnsFirst)
{
}
QCPLayoutGrid::~QCPLayoutGrid()
{
// clear all child layout elements. This is important because only the specific layouts know how
// to handle removing elements (clear calls virtual removeAt method to do that).
clear();
}
/*!
Returns the element in the cell in \a row and \a column.
Returns \c nullptr if either the row/column is invalid or if the cell is empty. In those cases, a
qDebug message is printed. To check whether a cell exists and isn't empty, use \ref hasElement.
\see addElement, hasElement
*/
QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const
{
if (row >= 0 && row < mElements.size())
{
if (column >= 0 && column < mElements.first().size())
{
if (QCPLayoutElement *result = mElements.at(row).at(column))
return result;
else
qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column;
} else
qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column;
} else
qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column;
return nullptr;
}
/*! \overload
Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it
is first removed from there. If \a row or \a column don't exist yet, the layout is expanded
accordingly.
Returns true if the element was added successfully, i.e. if the cell at \a row and \a column
didn't already have an element.
Use the overload of this method without explicit row/column index to place the element according
to the configured fill order and wrapping settings.
\see element, hasElement, take, remove
*/
bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element)
{
if (!hasElement(row, column))
{
if (element && element->layout()) // remove from old layout first
element->layout()->take(element);
expandTo(row+1, column+1);
mElements[row][column] = element;
if (element)
adoptElement(element);
return true;
} else
qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column;
return false;
}
/*! \overload
Adds the \a element to the next empty cell according to the current fill order (\ref
setFillOrder) and wrapping (\ref setWrap). If \a element is already in a layout, it is first
removed from there. If necessary, the layout is expanded to hold the new element.
Returns true if the element was added successfully.
\see setFillOrder, setWrap, element, hasElement, take, remove
*/
bool QCPLayoutGrid::addElement(QCPLayoutElement *element)
{
int rowIndex = 0;
int colIndex = 0;
if (mFillOrder == foColumnsFirst)
{
while (hasElement(rowIndex, colIndex))
{
++colIndex;
if (colIndex >= mWrap && mWrap > 0)
{
colIndex = 0;
++rowIndex;
}
}
} else
{
while (hasElement(rowIndex, colIndex))
{
++rowIndex;
if (rowIndex >= mWrap && mWrap > 0)
{
rowIndex = 0;
++colIndex;
}
}
}
return addElement(rowIndex, colIndex, element);
}
/*!
Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't
empty.
\see element
*/
bool QCPLayoutGrid::hasElement(int row, int column)
{
if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount())
return mElements.at(row).at(column);
else
return false;
}
/*!
Sets the stretch \a factor of \a column.
Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
QCPLayoutElement::setSizeConstraintRect.)
The default stretch factor of newly created rows/columns is 1.
\see setColumnStretchFactors, setRowStretchFactor
*/
void QCPLayoutGrid::setColumnStretchFactor(int column, double factor)
{
if (column >= 0 && column < columnCount())
{
if (factor > 0)
mColumnStretchFactors[column] = factor;
else
qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
} else
qDebug() << Q_FUNC_INFO << "Invalid column:" << column;
}
/*!
Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount.
Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
QCPLayoutElement::setSizeConstraintRect.)
The default stretch factor of newly created rows/columns is 1.
\see setColumnStretchFactor, setRowStretchFactors
*/
void QCPLayoutGrid::setColumnStretchFactors(const QList<double> &factors)
{
if (factors.size() == mColumnStretchFactors.size())
{
mColumnStretchFactors = factors;
for (int i=0; i<mColumnStretchFactors.size(); ++i)
{
if (mColumnStretchFactors.at(i) <= 0)
{
qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mColumnStretchFactors.at(i);
mColumnStretchFactors[i] = 1;
}
}
} else
qDebug() << Q_FUNC_INFO << "Column count not equal to passed stretch factor count:" << factors;
}
/*!
Sets the stretch \a factor of \a row.
Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
QCPLayoutElement::setSizeConstraintRect.)
The default stretch factor of newly created rows/columns is 1.
\see setColumnStretchFactors, setRowStretchFactor
*/
void QCPLayoutGrid::setRowStretchFactor(int row, double factor)
{
if (row >= 0 && row < rowCount())
{
if (factor > 0)
mRowStretchFactors[row] = factor;
else
qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
} else
qDebug() << Q_FUNC_INFO << "Invalid row:" << row;
}
/*!
Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount.
Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
QCPLayoutElement::setSizeConstraintRect.)
The default stretch factor of newly created rows/columns is 1.
\see setRowStretchFactor, setColumnStretchFactors
*/
void QCPLayoutGrid::setRowStretchFactors(const QList<double> &factors)
{
if (factors.size() == mRowStretchFactors.size())
{
mRowStretchFactors = factors;
for (int i=0; i<mRowStretchFactors.size(); ++i)
{
if (mRowStretchFactors.at(i) <= 0)
{
qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at(i);
mRowStretchFactors[i] = 1;
}
}
} else
qDebug() << Q_FUNC_INFO << "Row count not equal to passed stretch factor count:" << factors;
}
/*!
Sets the gap that is left blank between columns to \a pixels.
\see setRowSpacing
*/
void QCPLayoutGrid::setColumnSpacing(int pixels)
{
mColumnSpacing = pixels;
}
/*!
Sets the gap that is left blank between rows to \a pixels.
\see setColumnSpacing
*/
void QCPLayoutGrid::setRowSpacing(int pixels)
{
mRowSpacing = pixels;
}
/*!
Sets the maximum number of columns or rows that are used, before new elements added with \ref
addElement(QCPLayoutElement*) will start to fill the next row or column, respectively. It depends
on \ref setFillOrder, whether rows or columns are wrapped.
If \a count is set to zero, no wrapping will ever occur.
If you wish to re-wrap the elements currently in the layout, call \ref setFillOrder with \a
rearrange set to true (the actual fill order doesn't need to be changed for the rearranging to be
done).
Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
explicitly stated row and column is not subject to wrapping and can place elements even beyond
the specified wrapping point.
\see setFillOrder
*/
void QCPLayoutGrid::setWrap(int count)
{
mWrap = qMax(0, count);
}
/*!
Sets the filling order and wrapping behaviour that is used when adding new elements with the
method \ref addElement(QCPLayoutElement*).
The specified \a order defines whether rows or columns are filled first. Using \ref setWrap, you
can control at which row/column count wrapping into the next column/row will occur. If you set it
to zero, no wrapping will ever occur. Changing the fill order also changes the meaning of the
linear index used e.g. in \ref elementAt and \ref takeAt. The default fill order for \ref
QCPLayoutGrid is \ref foColumnsFirst.
If you want to have all current elements arranged in the new order, set \a rearrange to true. The
elements will be rearranged in a way that tries to preserve their linear index. However, empty
cells are skipped during build-up of the new cell order, which shifts the succeeding element's
index. The rearranging is performed even if the specified \a order is already the current fill
order. Thus this method can be used to re-wrap the current elements.
If \a rearrange is false, the current element arrangement is not changed, which means the
linear indexes change (because the linear index is dependent on the fill order).
Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
explicitly stated row and column is not subject to wrapping and can place elements even beyond
the specified wrapping point.
\see setWrap, addElement(QCPLayoutElement*)
*/
void QCPLayoutGrid::setFillOrder(FillOrder order, bool rearrange)
{
// if rearranging, take all elements via linear index of old fill order:
const int elCount = elementCount();
QVector<QCPLayoutElement*> tempElements;
if (rearrange)
{
tempElements.reserve(elCount);
for (int i=0; i<elCount; ++i)
{
if (elementAt(i))
tempElements.append(takeAt(i));
}
simplify();
}
// change fill order as requested:
mFillOrder = order;
// if rearranging, re-insert via linear index according to new fill order:
if (rearrange)
{
foreach (QCPLayoutElement *tempElement, tempElements)
addElement(tempElement);
}
}
/*!
Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid
row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1.
If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount,
this function does nothing in that dimension.
Newly created cells are empty, new rows and columns have the stretch factor 1.
Note that upon a call to \ref addElement, the layout is expanded automatically to contain the
specified row and column, using this function.
\see simplify
*/
void QCPLayoutGrid::expandTo(int newRowCount, int newColumnCount)
{
// add rows as necessary:
while (rowCount() < newRowCount)
{
mElements.append(QList<QCPLayoutElement*>());
mRowStretchFactors.append(1);
}
// go through rows and expand columns as necessary:
int newColCount = qMax(columnCount(), newColumnCount);
for (int i=0; i<rowCount(); ++i)
{
while (mElements.at(i).size() < newColCount)
mElements[i].append(nullptr);
}
while (mColumnStretchFactors.size() < newColCount)
mColumnStretchFactors.append(1);
}
/*!
Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex
range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom).
\see insertColumn
*/
void QCPLayoutGrid::insertRow(int newIndex)
{
if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
{
expandTo(1, 1);
return;
}
if (newIndex < 0)
newIndex = 0;
if (newIndex > rowCount())
newIndex = rowCount();
mRowStretchFactors.insert(newIndex, 1);
QList<QCPLayoutElement*> newRow;
for (int col=0; col<columnCount(); ++col)
newRow.append(nullptr);
mElements.insert(newIndex, newRow);
}
/*!
Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a
newIndex range from 0 (inserts a column at the left) to \a columnCount (appends a column at the
right).
\see insertRow
*/
void QCPLayoutGrid::insertColumn(int newIndex)
{
if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
{
expandTo(1, 1);
return;
}
if (newIndex < 0)
newIndex = 0;
if (newIndex > columnCount())
newIndex = columnCount();
mColumnStretchFactors.insert(newIndex, 1);
for (int row=0; row<rowCount(); ++row)
mElements[row].insert(newIndex, nullptr);
}
/*!
Converts the given \a row and \a column to the linear index used by some methods of \ref
QCPLayoutGrid and \ref QCPLayout.
The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
increase top to bottom and then left to right.
For the returned index to be valid, \a row and \a column must be valid indices themselves, i.e.
greater or equal to zero and smaller than the current \ref rowCount/\ref columnCount.
\see indexToRowCol
*/
int QCPLayoutGrid::rowColToIndex(int row, int column) const
{
if (row >= 0 && row < rowCount())
{
if (column >= 0 && column < columnCount())
{
switch (mFillOrder)
{
case foRowsFirst: return column*rowCount() + row;
case foColumnsFirst: return row*columnCount() + column;
}
} else
qDebug() << Q_FUNC_INFO << "row index out of bounds:" << row;
} else
qDebug() << Q_FUNC_INFO << "column index out of bounds:" << column;
return 0;
}
/*!
Converts the linear index to row and column indices and writes the result to \a row and \a
column.
The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
increase top to bottom and then left to right.
If there are no cells (i.e. column or row count is zero), sets \a row and \a column to -1.
For the retrieved \a row and \a column to be valid, the passed \a index must be valid itself,
i.e. greater or equal to zero and smaller than the current \ref elementCount.
\see rowColToIndex
*/
void QCPLayoutGrid::indexToRowCol(int index, int &row, int &column) const
{
row = -1;
column = -1;
const int nCols = columnCount();
const int nRows = rowCount();
if (nCols == 0 || nRows == 0)
return;
if (index < 0 || index >= elementCount())
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return;
}
switch (mFillOrder)
{
case foRowsFirst:
{
column = index / nRows;
row = index % nRows;
break;
}
case foColumnsFirst:
{
row = index / nCols;
column = index % nCols;
break;
}
}
}
/* inherits documentation from base class */
void QCPLayoutGrid::updateLayout()
{
QVector<int> minColWidths, minRowHeights, maxColWidths, maxRowHeights;
getMinimumRowColSizes(&minColWidths, &minRowHeights);
getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
int totalRowSpacing = (rowCount()-1) * mRowSpacing;
int totalColSpacing = (columnCount()-1) * mColumnSpacing;
QVector<int> colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing);
QVector<int> rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing);
// go through cells and set rects accordingly:
int yOffset = mRect.top();
for (int row=0; row<rowCount(); ++row)
{
if (row > 0)
yOffset += rowHeights.at(row-1)+mRowSpacing;
int xOffset = mRect.left();
for (int col=0; col<columnCount(); ++col)
{
if (col > 0)
xOffset += colWidths.at(col-1)+mColumnSpacing;
if (mElements.at(row).at(col))
mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row)));
}
}
}
/*!
\seebaseclassmethod
Note that the association of the linear \a index to the row/column based cells depends on the
current setting of \ref setFillOrder.
\see rowColToIndex
*/
QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const
{
if (index >= 0 && index < elementCount())
{
int row, col;
indexToRowCol(index, row, col);
return mElements.at(row).at(col);
} else
return nullptr;
}
/*!
\seebaseclassmethod
Note that the association of the linear \a index to the row/column based cells depends on the
current setting of \ref setFillOrder.
\see rowColToIndex
*/
QCPLayoutElement *QCPLayoutGrid::takeAt(int index)
{
if (QCPLayoutElement *el = elementAt(index))
{
releaseElement(el);
int row, col;
indexToRowCol(index, row, col);
mElements[row][col] = nullptr;
return el;
} else
{
qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
return nullptr;
}
}
/* inherits documentation from base class */
bool QCPLayoutGrid::take(QCPLayoutElement *element)
{
if (element)
{
for (int i=0; i<elementCount(); ++i)
{
if (elementAt(i) == element)
{
takeAt(i);
return true;
}
}
qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
} else
qDebug() << Q_FUNC_INFO << "Can't take nullptr element";
return false;
}
/* inherits documentation from base class */
QList<QCPLayoutElement*> QCPLayoutGrid::elements(bool recursive) const
{
QList<QCPLayoutElement*> result;
const int elCount = elementCount();
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
result.reserve(elCount);
#endif
for (int i=0; i<elCount; ++i)
result.append(elementAt(i));
if (recursive)
{
for (int i=0; i<elCount; ++i)
{
if (result.at(i))
result << result.at(i)->elements(recursive);
}
}
return result;
}
/*!
Simplifies the layout by collapsing rows and columns which only contain empty cells.
*/
void QCPLayoutGrid::simplify()
{
// remove rows with only empty cells:
for (int row=rowCount()-1; row>=0; --row)
{
bool hasElements = false;
for (int col=0; col<columnCount(); ++col)
{
if (mElements.at(row).at(col))
{
hasElements = true;
break;
}
}
if (!hasElements)
{
mRowStretchFactors.removeAt(row);
mElements.removeAt(row);
if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now)
mColumnStretchFactors.clear();
}
}
// remove columns with only empty cells:
for (int col=columnCount()-1; col>=0; --col)
{
bool hasElements = false;
for (int row=0; row<rowCount(); ++row)
{
if (mElements.at(row).at(col))
{
hasElements = true;
break;
}
}
if (!hasElements)
{
mColumnStretchFactors.removeAt(col);
for (int row=0; row<rowCount(); ++row)
mElements[row].removeAt(col);
}
}
}
/* inherits documentation from base class */
QSize QCPLayoutGrid::minimumOuterSizeHint() const
{
QVector<int> minColWidths, minRowHeights;
getMinimumRowColSizes(&minColWidths, &minRowHeights);
QSize result(0, 0);
foreach (int w, minColWidths)
result.rwidth() += w;
foreach (int h, minRowHeights)
result.rheight() += h;
result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing;
result.rheight() += qMax(0, rowCount()-1) * mRowSpacing;
result.rwidth() += mMargins.left()+mMargins.right();
result.rheight() += mMargins.top()+mMargins.bottom();
return result;
}
/* inherits documentation from base class */
QSize QCPLayoutGrid::maximumOuterSizeHint() const
{
QVector<int> maxColWidths, maxRowHeights;
getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
QSize result(0, 0);
foreach (int w, maxColWidths)
result.setWidth(qMin(result.width()+w, QWIDGETSIZE_MAX));
foreach (int h, maxRowHeights)
result.setHeight(qMin(result.height()+h, QWIDGETSIZE_MAX));
result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing;
result.rheight() += qMax(0, rowCount()-1) * mRowSpacing;
result.rwidth() += mMargins.left()+mMargins.right();
result.rheight() += mMargins.top()+mMargins.bottom();
if (result.height() > QWIDGETSIZE_MAX)
result.setHeight(QWIDGETSIZE_MAX);
if (result.width() > QWIDGETSIZE_MAX)
result.setWidth(QWIDGETSIZE_MAX);
return result;
}
/*! \internal
Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights
respectively.
The minimum height of a row is the largest minimum height of any element's outer rect in that
row. The minimum width of a column is the largest minimum width of any element's outer rect in
that column.
This is a helper function for \ref updateLayout.
\see getMaximumRowColSizes
*/
void QCPLayoutGrid::getMinimumRowColSizes(QVector<int> *minColWidths, QVector<int> *minRowHeights) const
{
*minColWidths = QVector<int>(columnCount(), 0);
*minRowHeights = QVector<int>(rowCount(), 0);
for (int row=0; row<rowCount(); ++row)
{
for (int col=0; col<columnCount(); ++col)
{
if (QCPLayoutElement *el = mElements.at(row).at(col))
{
QSize minSize = getFinalMinimumOuterSize(el);
if (minColWidths->at(col) < minSize.width())
(*minColWidths)[col] = minSize.width();
if (minRowHeights->at(row) < minSize.height())
(*minRowHeights)[row] = minSize.height();
}
}
}
}
/*! \internal
Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights
respectively.
The maximum height of a row is the smallest maximum height of any element's outer rect in that
row. The maximum width of a column is the smallest maximum width of any element's outer rect in
that column.
This is a helper function for \ref updateLayout.
\see getMinimumRowColSizes
*/
void QCPLayoutGrid::getMaximumRowColSizes(QVector<int> *maxColWidths, QVector<int> *maxRowHeights) const
{
*maxColWidths = QVector<int>(columnCount(), QWIDGETSIZE_MAX);
*maxRowHeights = QVector<int>(rowCount(), QWIDGETSIZE_MAX);
for (int row=0; row<rowCount(); ++row)
{
for (int col=0; col<columnCount(); ++col)
{
if (QCPLayoutElement *el = mElements.at(row).at(col))
{
QSize maxSize = getFinalMaximumOuterSize(el);
if (maxColWidths->at(col) > maxSize.width())
(*maxColWidths)[col] = maxSize.width();
if (maxRowHeights->at(row) > maxSize.height())
(*maxRowHeights)[row] = maxSize.height();
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayoutInset
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayoutInset
\brief A layout that places child elements aligned to the border or arbitrarily positioned
Elements are placed either aligned to the border or at arbitrary position in the area of the
layout. Which placement applies is controlled with the \ref InsetPlacement (\ref
setInsetPlacement).
Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or
addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset
placement will default to \ref ipBorderAligned and the element will be aligned according to the
\a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at
arbitrary position and size, defined by \a rect.
The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively.
This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout.
*/
/* start documentation of inline functions */
/*! \fn virtual void QCPLayoutInset::simplify()
The QCPInsetLayout does not need simplification since it can never have empty cells due to its
linear index structure. This method does nothing.
*/
/* end documentation of inline functions */
/*!
Creates an instance of QCPLayoutInset and sets default values.
*/
QCPLayoutInset::QCPLayoutInset()
{
}
QCPLayoutInset::~QCPLayoutInset()
{
// clear all child layout elements. This is important because only the specific layouts know how
// to handle removing elements (clear calls virtual removeAt method to do that).
clear();
}
/*!
Returns the placement type of the element with the specified \a index.
*/
QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const
{
if (elementAt(index))
return mInsetPlacement.at(index);
else
{
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
return ipFree;
}
}
/*!
Returns the alignment of the element with the specified \a index. The alignment only has a
meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned.
*/
Qt::Alignment QCPLayoutInset::insetAlignment(int index) const
{
if (elementAt(index))
return mInsetAlignment.at(index);
else
{
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
#if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
return nullptr;
#else
return {};
#endif
}
}
/*!
Returns the rect of the element with the specified \a index. The rect only has a
meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree.
*/
QRectF QCPLayoutInset::insetRect(int index) const
{
if (elementAt(index))
return mInsetRect.at(index);
else
{
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
return {};
}
}
/*!
Sets the inset placement type of the element with the specified \a index to \a placement.
\see InsetPlacement
*/
void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement)
{
if (elementAt(index))
mInsetPlacement[index] = placement;
else
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
}
/*!
If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function
is used to set the alignment of the element with the specified \a index to \a alignment.
\a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
alignment flags will be ignored.
*/
void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment)
{
if (elementAt(index))
mInsetAlignment[index] = alignment;
else
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
}
/*!
If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the
position and size of the element with the specified \a index to \a rect.
\a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
corner of the layout, with 35% width and height of the parent layout.
Note that the minimum and maximum sizes of the embedded element (\ref
QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced.
*/
void QCPLayoutInset::setInsetRect(int index, const QRectF &rect)
{
if (elementAt(index))
mInsetRect[index] = rect;
else
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
}
/* inherits documentation from base class */
void QCPLayoutInset::updateLayout()
{
for (int i=0; i<mElements.size(); ++i)
{
QCPLayoutElement *el = mElements.at(i);
QRect insetRect;
QSize finalMinSize = getFinalMinimumOuterSize(el);
QSize finalMaxSize = getFinalMaximumOuterSize(el);
if (mInsetPlacement.at(i) == ipFree)
{
insetRect = QRect(int( rect().x()+rect().width()*mInsetRect.at(i).x() ),
int( rect().y()+rect().height()*mInsetRect.at(i).y() ),
int( rect().width()*mInsetRect.at(i).width() ),
int( rect().height()*mInsetRect.at(i).height() ));
if (insetRect.size().width() < finalMinSize.width())
insetRect.setWidth(finalMinSize.width());
if (insetRect.size().height() < finalMinSize.height())
insetRect.setHeight(finalMinSize.height());
if (insetRect.size().width() > finalMaxSize.width())
insetRect.setWidth(finalMaxSize.width());
if (insetRect.size().height() > finalMaxSize.height())
insetRect.setHeight(finalMaxSize.height());
} else if (mInsetPlacement.at(i) == ipBorderAligned)
{
insetRect.setSize(finalMinSize);
Qt::Alignment al = mInsetAlignment.at(i);
if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x());
else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width());
else insetRect.moveLeft(int( rect().x()+rect().width()*0.5-finalMinSize.width()*0.5 )); // default to Qt::AlignHCenter
if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y());
else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height());
else insetRect.moveTop(int( rect().y()+rect().height()*0.5-finalMinSize.height()*0.5 )); // default to Qt::AlignVCenter
}
mElements.at(i)->setOuterRect(insetRect);
}
}
/* inherits documentation from base class */
int QCPLayoutInset::elementCount() const
{
return static_cast<int>(mElements.size());
}
/* inherits documentation from base class */
QCPLayoutElement *QCPLayoutInset::elementAt(int index) const
{
if (index >= 0 && index < mElements.size())
return mElements.at(index);
else
return nullptr;
}
/* inherits documentation from base class */
QCPLayoutElement *QCPLayoutInset::takeAt(int index)
{
if (QCPLayoutElement *el = elementAt(index))
{
releaseElement(el);
mElements.removeAt(index);
mInsetPlacement.removeAt(index);
mInsetAlignment.removeAt(index);
mInsetRect.removeAt(index);
return el;
} else
{
qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
return nullptr;
}
}
/* inherits documentation from base class */
bool QCPLayoutInset::take(QCPLayoutElement *element)
{
if (element)
{
for (int i=0; i<elementCount(); ++i)
{
if (elementAt(i) == element)
{
takeAt(i);
return true;
}
}
qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
} else
qDebug() << Q_FUNC_INFO << "Can't take nullptr element";
return false;
}
/*!
The inset layout is sensitive to events only at areas where its (visible) child elements are
sensitive. If the selectTest method of any of the child elements returns a positive number for \a
pos, this method returns a value corresponding to 0.99 times the parent plot's selection
tolerance. The inset layout is not selectable itself by default. So if \a onlySelectable is true,
-1.0 is returned.
See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
*/
double QCPLayoutInset::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable)
return -1;
foreach (QCPLayoutElement *el, mElements)
{
// inset layout shall only return positive selectTest, if actually an inset object is at pos
// else it would block the entire underlying QCPAxisRect with its surface.
if (el->realVisibility() && el->selectTest(pos, onlySelectable) >= 0)
return mParentPlot->selectionTolerance()*0.99;
}
return -1;
}
/*!
Adds the specified \a element to the layout as an inset aligned at the border (\ref
setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a
alignment.
\a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
alignment flags will be ignored.
\see addElement(QCPLayoutElement *element, const QRectF &rect)
*/
void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment)
{
if (element)
{
if (element->layout()) // remove from old layout first
element->layout()->take(element);
mElements.append(element);
mInsetPlacement.append(ipBorderAligned);
mInsetAlignment.append(alignment);
mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4));
adoptElement(element);
} else
qDebug() << Q_FUNC_INFO << "Can't add nullptr element";
}
/*!
Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref
setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a
rect.
\a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
corner of the layout, with 35% width and height of the parent layout.
\see addElement(QCPLayoutElement *element, Qt::Alignment alignment)
*/
void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect)
{
if (element)
{
if (element->layout()) // remove from old layout first
element->layout()->take(element);
mElements.append(element);
mInsetPlacement.append(ipFree);
mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop);
mInsetRect.append(rect);
adoptElement(element);
} else
qDebug() << Q_FUNC_INFO << "Can't add nullptr element";
}
/* end of 'src/layout.cpp' */
/* including file 'src/lineending.cpp' */
/* modified 2022-11-06T12:45:56, size 11189 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLineEnding
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLineEnding
\brief Handles the different ending decorations for line-like items
\image html QCPLineEnding.png "The various ending styles currently supported"
For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine
has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail.
The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can
be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of
the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item.
For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite
directions, e.g. "outward". This can be changed by \ref setInverted, which would make the
respective arrow point inward.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify a
QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g.
\snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead
*/
/*!
Creates a QCPLineEnding instance with default values (style \ref esNone).
*/
QCPLineEnding::QCPLineEnding() :
mStyle(esNone),
mWidth(8),
mLength(10),
mInverted(false)
{
}
/*!
Creates a QCPLineEnding instance with the specified values.
*/
QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) :
mStyle(style),
mWidth(width),
mLength(length),
mInverted(inverted)
{
}
/*!
Sets the style of the ending decoration.
*/
void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style)
{
mStyle = style;
}
/*!
Sets the width of the ending decoration, if the style supports it. On arrows, for example, the
width defines the size perpendicular to the arrow's pointing direction.
\see setLength
*/
void QCPLineEnding::setWidth(double width)
{
mWidth = width;
}
/*!
Sets the length of the ending decoration, if the style supports it. On arrows, for example, the
length defines the size in pointing direction.
\see setWidth
*/
void QCPLineEnding::setLength(double length)
{
mLength = length;
}
/*!
Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point
inward when \a inverted is set to true.
Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or
discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are
affected by it, which can be used to control to which side the half bar points to.
*/
void QCPLineEnding::setInverted(bool inverted)
{
mInverted = inverted;
}
/*! \internal
Returns the maximum pixel radius the ending decoration might cover, starting from the position
the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item).
This is relevant for clipping. Only omit painting of the decoration when the position where the
decoration is supposed to be drawn is farther away from the clipping rect than the returned
distance.
*/
double QCPLineEnding::boundingDistance() const
{
switch (mStyle)
{
case esNone:
return 0;
case esFlatArrow:
case esSpikeArrow:
case esLineArrow:
case esSkewedBar:
return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length
case esDisc:
case esSquare:
case esDiamond:
case esBar:
case esHalfBar:
return mWidth*1.42; // items that only have a width -> width*sqrt(2)
}
return 0;
}
/*!
Starting from the origin of this line ending (which is style specific), returns the length
covered by the line ending symbol, in backward direction.
For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if
both have the same \ref setLength value, because the spike arrow has an inward curved back, which
reduces the length along its center axis (the drawing origin for arrows is at the tip).
This function is used for precise, style specific placement of line endings, for example in
QCPAxes.
*/
double QCPLineEnding::realLength() const
{
switch (mStyle)
{
case esNone:
case esLineArrow:
case esSkewedBar:
case esBar:
case esHalfBar:
return 0;
case esFlatArrow:
return mLength;
case esDisc:
case esSquare:
case esDiamond:
return mWidth*0.5;
case esSpikeArrow:
return mLength*0.8;
}
return 0;
}
/*! \internal
Draws the line ending with the specified \a painter at the position \a pos. The direction of the
line ending is controlled with \a dir.
*/
void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const
{
if (mStyle == esNone)
return;
QCPVector2D lengthVec = dir.normalized() * mLength*(mInverted ? -1 : 1);
if (lengthVec.isNull())
lengthVec = QCPVector2D(1, 0);
QCPVector2D widthVec = dir.normalized().perpendicular() * mWidth*0.5*(mInverted ? -1 : 1);
QPen penBackup = painter->pen();
QBrush brushBackup = painter->brush();
QPen miterPen = penBackup;
miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey
QBrush brush(painter->pen().color(), Qt::SolidPattern);
switch (mStyle)
{
case esNone: break;
case esFlatArrow:
{
QPointF points[3] = {pos.toPointF(),
(pos-lengthVec+widthVec).toPointF(),
(pos-lengthVec-widthVec).toPointF()
};
painter->setPen(miterPen);
painter->setBrush(brush);
painter->drawConvexPolygon(points, 3);
painter->setBrush(brushBackup);
painter->setPen(penBackup);
break;
}
case esSpikeArrow:
{
QPointF points[4] = {pos.toPointF(),
(pos-lengthVec+widthVec).toPointF(),
(pos-lengthVec*0.8).toPointF(),
(pos-lengthVec-widthVec).toPointF()
};
painter->setPen(miterPen);
painter->setBrush(brush);
painter->drawConvexPolygon(points, 4);
painter->setBrush(brushBackup);
painter->setPen(penBackup);
break;
}
case esLineArrow:
{
QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(),
pos.toPointF(),
(pos-lengthVec-widthVec).toPointF()
};
painter->setPen(miterPen);
painter->drawPolyline(points, 3);
painter->setPen(penBackup);
break;
}
case esDisc:
{
painter->setBrush(brush);
painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5);
painter->setBrush(brushBackup);
break;
}
case esSquare:
{
QCPVector2D widthVecPerp = widthVec.perpendicular();
QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(),
(pos-widthVecPerp-widthVec).toPointF(),
(pos+widthVecPerp-widthVec).toPointF(),
(pos+widthVecPerp+widthVec).toPointF()
};
painter->setPen(miterPen);
painter->setBrush(brush);
painter->drawConvexPolygon(points, 4);
painter->setBrush(brushBackup);
painter->setPen(penBackup);
break;
}
case esDiamond:
{
QCPVector2D widthVecPerp = widthVec.perpendicular();
QPointF points[4] = {(pos-widthVecPerp).toPointF(),
(pos-widthVec).toPointF(),
(pos+widthVecPerp).toPointF(),
(pos+widthVec).toPointF()
};
painter->setPen(miterPen);
painter->setBrush(brush);
painter->drawConvexPolygon(points, 4);
painter->setBrush(brushBackup);
painter->setPen(penBackup);
break;
}
case esBar:
{
painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF());
break;
}
case esHalfBar:
{
painter->drawLine((pos+widthVec).toPointF(), pos.toPointF());
break;
}
case esSkewedBar:
{
QCPVector2D shift;
if (!qFuzzyIsNull(painter->pen().widthF()) || painter->modes().testFlag(QCPPainter::pmNonCosmetic))
shift = dir.normalized()*qMax(qreal(1.0), painter->pen().widthF())*qreal(0.5);
// if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly
painter->drawLine((pos+widthVec+lengthVec*0.2*(mInverted?-1:1)+shift).toPointF(),
(pos-widthVec-lengthVec*0.2*(mInverted?-1:1)+shift).toPointF());
break;
}
}
}
/*! \internal
\overload
Draws the line ending. The direction is controlled with the \a angle parameter in radians.
*/
void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const
{
draw(painter, pos, QCPVector2D(qCos(angle), qSin(angle)));
}
/* end of 'src/lineending.cpp' */
/* including file 'src/axis/labelpainter.cpp' */
/* modified 2022-11-06T12:45:56, size 27519 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLabelPainterPrivate
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! QCPLabelPainterPrivate
\internal
\brief (Private)
This is a private class and not part of the public QCustomPlot interface.
*/
const QChar QCPLabelPainterPrivate::SymbolDot(183);
const QChar QCPLabelPainterPrivate::SymbolCross(215);
/*!
Constructs a QCPLabelPainterPrivate instance. Make sure to not create a new
instance on every redraw, to utilize the caching mechanisms.
the \a parentPlot does not take ownership of the label painter. Make sure
to delete it appropriately.
*/
QCPLabelPainterPrivate::QCPLabelPainterPrivate(QCustomPlot *parentPlot) :
mAnchorMode(amRectangular),
mAnchorSide(asLeft),
mAnchorReferenceType(artNormal),
mColor(Qt::black),
mPadding(0),
mRotation(0),
mSubstituteExponent(true),
mMultiplicationSymbol(QChar(215)),
mAbbreviateDecimalPowers(false),
mParentPlot(parentPlot),
mLabelCache(16)
{
analyzeFontMetrics();
}
QCPLabelPainterPrivate::~QCPLabelPainterPrivate()
{
}
void QCPLabelPainterPrivate::setAnchorSide(AnchorSide side)
{
mAnchorSide = side;
}
void QCPLabelPainterPrivate::setAnchorMode(AnchorMode mode)
{
mAnchorMode = mode;
}
void QCPLabelPainterPrivate::setAnchorReference(const QPointF &pixelPoint)
{
mAnchorReference = pixelPoint;
}
void QCPLabelPainterPrivate::setAnchorReferenceType(AnchorReferenceType type)
{
mAnchorReferenceType = type;
}
void QCPLabelPainterPrivate::setFont(const QFont &font)
{
if (mFont != font)
{
mFont = font;
analyzeFontMetrics();
}
}
void QCPLabelPainterPrivate::setColor(const QColor &color)
{
mColor = color;
}
void QCPLabelPainterPrivate::setPadding(int padding)
{
mPadding = padding;
}
void QCPLabelPainterPrivate::setRotation(double rotation)
{
mRotation = qBound(-90.0, rotation, 90.0);
}
void QCPLabelPainterPrivate::setSubstituteExponent(bool enabled)
{
mSubstituteExponent = enabled;
}
void QCPLabelPainterPrivate::setMultiplicationSymbol(QChar symbol)
{
mMultiplicationSymbol = symbol;
}
void QCPLabelPainterPrivate::setAbbreviateDecimalPowers(bool enabled)
{
mAbbreviateDecimalPowers = enabled;
}
void QCPLabelPainterPrivate::setCacheSize(int labelCount)
{
mLabelCache.setMaxCost(labelCount);
}
int QCPLabelPainterPrivate::cacheSize() const
{
return static_cast<int>(mLabelCache.maxCost());
}
void QCPLabelPainterPrivate::drawTickLabel(QCPPainter *painter, const QPointF &tickPos, const QString &text)
{
double realRotation = mRotation;
AnchorSide realSide = mAnchorSide;
// for circular axes, the anchor side is determined depending on the quadrant of tickPos with respect to mCircularReference
if (mAnchorMode == amSkewedUpright)
{
realSide = skewedAnchorSide(tickPos, 0.2, 0.3);
} else if (mAnchorMode == amSkewedRotated) // in this mode every label is individually rotated to match circle tangent
{
realSide = skewedAnchorSide(tickPos, 0, 0);
realRotation += QCPVector2D(tickPos-mAnchorReference).angle()/M_PI*180.0;
if (realRotation > 90) realRotation -= 180;
else if (realRotation < -90) realRotation += 180;
}
realSide = rotationCorrectedSide(realSide, realRotation); // rotation angles may change the true anchor side of the label
drawLabelMaybeCached(painter, mFont, mColor, getAnchorPos(tickPos), realSide, realRotation, text);
}
/*! \internal
Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
direction) needed to fit the axis.
*/
/* TODO: needed?
int QCPLabelPainterPrivate::size() const
{
int result = 0;
// get length of tick marks pointing outwards:
if (!tickPositions.isEmpty())
result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
// calculate size of tick labels:
if (tickLabelSide == QCPAxis::lsOutside)
{
QSize tickLabelsSize(0, 0);
if (!tickLabels.isEmpty())
{
for (int i=0; i<tickLabels.size(); ++i)
getMaxTickLabelSize(tickLabelFont, tickLabels.at(i), &tickLabelsSize);
result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
result += tickLabelPadding;
}
}
// calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
if (!label.isEmpty())
{
QFontMetrics fontMetrics(labelFont);
QRect bounds;
bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
result += bounds.height() + labelPadding;
}
return result;
}
*/
/*! \internal
Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
method is called automatically if any parameters have changed that invalidate the cached labels,
such as font, color, etc. Usually you won't need to call this method manually.
*/
void QCPLabelPainterPrivate::clearCache()
{
mLabelCache.clear();
}
/*! \internal
Returns a hash that allows uniquely identifying whether the label parameters have changed such
that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
return value of this method hasn't changed since the last redraw, the respective label parameters
haven't changed and cached labels may be used.
*/
QByteArray QCPLabelPainterPrivate::generateLabelParameterHash() const
{
QByteArray result;
result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio()));
result.append(QByteArray::number(mRotation));
//result.append(QByteArray::number(int(tickLabelSide))); TODO: check whether this is really a cache-invalidating property
result.append(QByteArray::number(int(mSubstituteExponent)));
result.append(QString(mMultiplicationSymbol).toUtf8());
result.append(mColor.name().toLatin1()+QByteArray::number(mColor.alpha(), 16));
result.append(mFont.toString().toLatin1());
return result;
}
/*! \internal
Draws a single tick label with the provided \a painter, utilizing the internal label cache to
significantly speed up drawing of labels that were drawn in previous calls. The tick label is
always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
at which the label should be drawn.
In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
holds.
The label is drawn with the font and pen that are currently set on the \a painter. To draw
superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
getTickLabelData).
*/
void QCPLabelPainterPrivate::drawLabelMaybeCached(QCPPainter *painter, const QFont &font, const QColor &color, const QPointF &pos, AnchorSide side, double rotation, const QString &text)
{
// warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
if (text.isEmpty()) return;
QSize finalSize;
if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
{
QByteArray key = cacheKey(text, color, rotation, side);
CachedLabel *cachedLabel = mLabelCache.take(QString::fromUtf8(key)); // attempt to take label from cache (don't use object() because we want ownership/prevent deletion during our operations, we re-insert it afterwards)
if (!cachedLabel) // no cached label existed, create it
{
LabelData labelData = getTickLabelData(font, color, rotation, side, text);
cachedLabel = createCachedLabel(labelData);
}
// if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
bool labelClippedByBorder = false;
/*
if (tickLabelSide == QCPAxis::lsOutside)
{
if (QCPAxis::orientation(type) == Qt::Horizontal)
labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
else
labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
}
*/
if (!labelClippedByBorder)
{
painter->drawPixmap(pos+cachedLabel->offset, cachedLabel->pixmap);
finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio(); // TODO: collect this in a member rect list?
}
mLabelCache.insert(QString::fromUtf8(key), cachedLabel);
} else // label caching disabled, draw text directly on surface:
{
LabelData labelData = getTickLabelData(font, color, rotation, side, text);
// if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
bool labelClippedByBorder = false;
/*
if (tickLabelSide == QCPAxis::lsOutside)
{
if (QCPAxis::orientation(type) == Qt::Horizontal)
labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left();
else
labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top();
}
*/
if (!labelClippedByBorder)
{
drawText(painter, pos, labelData);
finalSize = labelData.rotatedTotalBounds.size();
}
}
/*
// expand passed tickLabelsSize if current tick label is larger:
if (finalSize.width() > tickLabelsSize->width())
tickLabelsSize->setWidth(finalSize.width());
if (finalSize.height() > tickLabelsSize->height())
tickLabelsSize->setHeight(finalSize.height());
*/
}
QPointF QCPLabelPainterPrivate::getAnchorPos(const QPointF &tickPos)
{
switch (mAnchorMode)
{
case amRectangular:
{
switch (mAnchorSide)
{
case asLeft: return tickPos+QPointF(mPadding, 0);
case asRight: return tickPos+QPointF(-mPadding, 0);
case asTop: return tickPos+QPointF(0, mPadding);
case asBottom: return tickPos+QPointF(0, -mPadding);
case asTopLeft: return tickPos+QPointF(mPadding*M_SQRT1_2, mPadding*M_SQRT1_2);
case asTopRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, mPadding*M_SQRT1_2);
case asBottomRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2);
case asBottomLeft: return tickPos+QPointF(mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2);
default: qDebug() << Q_FUNC_INFO << "invalid mode for anchor side: " << mAnchorSide; break;
}
break;
}
case amSkewedUpright:
// fall through
case amSkewedRotated:
{
QCPVector2D anchorNormal(tickPos-mAnchorReference);
if (mAnchorReferenceType == artTangent)
anchorNormal = anchorNormal.perpendicular();
anchorNormal.normalize();
return tickPos+(anchorNormal*mPadding).toPointF();
}
default: qDebug() << Q_FUNC_INFO << "invalid mode for anchor mode: " << mAnchorMode; break;
}
return tickPos;
}
/*! \internal
This is a \ref placeTickLabel helper function.
Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
QCP::phCacheLabels plotting hint is not set.
*/
void QCPLabelPainterPrivate::drawText(QCPPainter *painter, const QPointF &pos, const LabelData &labelData) const
{
// backup painter settings that we're about to change:
QTransform oldTransform = painter->transform();
QFont oldFont = painter->font();
QPen oldPen = painter->pen();
// transform painter to position/rotation:
painter->translate(pos);
painter->setTransform(labelData.transform, true);
// draw text:
painter->setFont(labelData.baseFont);
painter->setPen(QPen(labelData.color));
if (!labelData.expPart.isEmpty()) // use superscripted exponent typesetting
{
painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
if (!labelData.suffixPart.isEmpty())
painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart);
painter->setFont(labelData.expFont);
painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
} else
{
painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
}
/* Debug code to draw label bounding boxes, baseline, and capheight
painter->save();
painter->setPen(QPen(QColor(0, 0, 0, 150)));
painter->drawRect(labelData.totalBounds);
const int baseline = labelData.totalBounds.height()-mLetterDescent;
painter->setPen(QPen(QColor(255, 0, 0, 150)));
painter->drawLine(QLineF(0, baseline, labelData.totalBounds.width(), baseline));
painter->setPen(QPen(QColor(0, 0, 255, 150)));
painter->drawLine(QLineF(0, baseline-mLetterCapHeight, labelData.totalBounds.width(), baseline-mLetterCapHeight));
painter->restore();
*/
// reset painter settings to what it was before:
painter->setTransform(oldTransform);
painter->setFont(oldFont);
painter->setPen(oldPen);
}
/*! \internal
This is a \ref placeTickLabel helper function.
Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
*/
QCPLabelPainterPrivate::LabelData QCPLabelPainterPrivate::getTickLabelData(const QFont &font, const QColor &color, double rotation, AnchorSide side, const QString &text) const
{
LabelData result;
result.rotation = rotation;
result.side = side;
result.color = color;
// determine whether beautiful decimal powers should be used
bool useBeautifulPowers = false;
int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
if (mSubstituteExponent)
{
ePos = static_cast<int>(text.indexOf(QLatin1Char('e')));
if (ePos > 0 && text.at(ePos-1).isDigit())
{
eLast = ePos;
while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
++eLast;
if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
useBeautifulPowers = true;
}
}
// calculate text bounding rects and do string preparation for beautiful decimal powers:
result.baseFont = font;
if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line
result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding
QFontMetrics baseFontMetrics(result.baseFont);
if (useBeautifulPowers)
{
// split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
result.basePart = text.left(ePos);
result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent
// in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
if (mAbbreviateDecimalPowers && result.basePart == QLatin1String("1"))
result.basePart = QLatin1String("10");
else
result.basePart += QString(mMultiplicationSymbol) + QLatin1String("10");
result.expPart = text.mid(ePos+1, eLast-ePos);
// clip "+" and leading zeros off expPart:
while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
result.expPart.remove(1, 1);
if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
result.expPart.remove(0, 1);
// prepare smaller font for exponent:
result.expFont = font;
if (result.expFont.pointSize() > 0)
result.expFont.setPointSize(result.expFont.pointSize()*0.75);
else
result.expFont.setPixelSize(result.expFont.pixelSize()*0.75);
// calculate bounding rects of base part(s), exponent part and total one:
result.baseBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
if (!result.suffixPart.isEmpty())
result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart);
result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+result.suffixBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA
} else // useBeautifulPowers == false
{
result.basePart = text;
result.totalBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
}
result.totalBounds.moveTopLeft(QPoint(0, 0));
applyAnchorTransform(result);
result.rotatedTotalBounds = result.transform.mapRect(result.totalBounds);
return result;
}
void QCPLabelPainterPrivate::applyAnchorTransform(LabelData &labelData) const
{
if (!qFuzzyIsNull(labelData.rotation))
labelData.transform.rotate(labelData.rotation); // rotates effectively clockwise (due to flipped y axis of painter vs widget coordinate system)
// from now on we translate in rotated label-local coordinate system.
// shift origin of coordinate system to appropriate point on label:
labelData.transform.translate(0, -labelData.totalBounds.height()+mLetterDescent+mLetterCapHeight); // shifts origin to true top of capital (or number) characters
if (labelData.side == asLeft || labelData.side == asRight) // anchor is centered vertically
labelData.transform.translate(0, -mLetterCapHeight/2.0);
else if (labelData.side == asTop || labelData.side == asBottom) // anchor is centered horizontally
labelData.transform.translate(-labelData.totalBounds.width()/2.0, 0);
if (labelData.side == asTopRight || labelData.side == asRight || labelData.side == asBottomRight) // anchor is at right
labelData.transform.translate(-labelData.totalBounds.width(), 0);
if (labelData.side == asBottomLeft || labelData.side == asBottom || labelData.side == asBottomRight) // anchor is at bottom (no elseif!)
labelData.transform.translate(0, -mLetterCapHeight);
}
/*! \internal
Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
smaller width/height.
*/
/*
void QCPLabelPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const
{
// note: this function must return the same tick label sizes as the placeTickLabel function.
QSize finalSize;
if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
{
const CachedLabel *cachedLabel = mLabelCache.object(text);
finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
} else // label caching disabled or no label with this text cached:
{
// TODO: LabelData labelData = getTickLabelData(font, text);
// TODO: finalSize = labelData.rotatedTotalBounds.size();
}
// expand passed tickLabelsSize if current tick label is larger:
if (finalSize.width() > tickLabelsSize->width())
tickLabelsSize->setWidth(finalSize.width());
if (finalSize.height() > tickLabelsSize->height())
tickLabelsSize->setHeight(finalSize.height());
}
*/
QCPLabelPainterPrivate::CachedLabel *QCPLabelPainterPrivate::createCachedLabel(const LabelData &labelData) const
{
CachedLabel *result = new CachedLabel;
// allocate pixmap with the correct size and pixel ratio:
if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio()))
{
result->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio());
#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
# ifdef QCP_DEVICEPIXELRATIO_FLOAT
result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF());
# else
result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio());
# endif
#endif
} else
result->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
result->pixmap.fill(Qt::transparent);
// draw the label into the pixmap
// offset is between label anchor and topleft of cache pixmap, so pixmap can be drawn at pos+offset to make the label anchor appear at pos.
// We use rotatedTotalBounds.topLeft() because rotatedTotalBounds is in a coordinate system where the label anchor is at (0, 0)
result->offset = labelData.rotatedTotalBounds.topLeft();
QCPPainter cachePainter(&result->pixmap);
drawText(&cachePainter, -result->offset, labelData);
return result;
}
QByteArray QCPLabelPainterPrivate::cacheKey(const QString &text, const QColor &color, double rotation, AnchorSide side) const
{
return text.toUtf8()+
QByteArray::number(color.red()+256*color.green()+65536*color.blue(), 36)+
QByteArray::number(color.alpha()+256*int(side), 36)+
QByteArray::number(int(rotation*100), 36);
}
QCPLabelPainterPrivate::AnchorSide QCPLabelPainterPrivate::skewedAnchorSide(const QPointF &tickPos, double sideExpandHorz, double sideExpandVert) const
{
QCPVector2D anchorNormal = QCPVector2D(tickPos-mAnchorReference);
if (mAnchorReferenceType == artTangent)
anchorNormal = anchorNormal.perpendicular();
const double radius = anchorNormal.length();
const double sideHorz = sideExpandHorz*radius;
const double sideVert = sideExpandVert*radius;
if (anchorNormal.x() > sideHorz)
{
if (anchorNormal.y() > sideVert) return asTopLeft;
else if (anchorNormal.y() < -sideVert) return asBottomLeft;
else return asLeft;
} else if (anchorNormal.x() < -sideHorz)
{
if (anchorNormal.y() > sideVert) return asTopRight;
else if (anchorNormal.y() < -sideVert) return asBottomRight;
else return asRight;
} else
{
if (anchorNormal.y() > 0) return asTop;
else return asBottom;
}
return asBottom; // should never be reached
}
QCPLabelPainterPrivate::AnchorSide QCPLabelPainterPrivate::rotationCorrectedSide(AnchorSide side, double rotation) const
{
AnchorSide result = side;
const bool rotateClockwise = rotation > 0;
if (!qFuzzyIsNull(rotation))
{
if (!qFuzzyCompare(qAbs(rotation), 90)) // avoid graphical collision with anchor tangent (e.g. axis line) when rotating, so change anchor side appropriately:
{
if (side == asTop) result = rotateClockwise ? asLeft : asRight;
else if (side == asBottom) result = rotateClockwise ? asRight : asLeft;
else if (side == asTopLeft) result = rotateClockwise ? asLeft : asTop;
else if (side == asTopRight) result = rotateClockwise ? asTop : asRight;
else if (side == asBottomLeft) result = rotateClockwise ? asBottom : asLeft;
else if (side == asBottomRight) result = rotateClockwise ? asRight : asBottom;
} else // for full rotation by +/-90 degrees, other sides are more appropriate for centering on anchor:
{
if (side == asLeft) result = rotateClockwise ? asBottom : asTop;
else if (side == asRight) result = rotateClockwise ? asTop : asBottom;
else if (side == asTop) result = rotateClockwise ? asLeft : asRight;
else if (side == asBottom) result = rotateClockwise ? asRight : asLeft;
else if (side == asTopLeft) result = rotateClockwise ? asBottomLeft : asTopRight;
else if (side == asTopRight) result = rotateClockwise ? asTopLeft : asBottomRight;
else if (side == asBottomLeft) result = rotateClockwise ? asBottomRight : asTopLeft;
else if (side == asBottomRight) result = rotateClockwise ? asTopRight : asBottomLeft;
}
}
return result;
}
void QCPLabelPainterPrivate::analyzeFontMetrics()
{
const QFontMetrics fm(mFont);
mLetterCapHeight = fm.tightBoundingRect(QLatin1String("8")).height(); // this method is slow, that's why we query it only upon font change
mLetterDescent = fm.descent();
}
/* end of 'src/axis/labelpainter.cpp' */
/* including file 'src/axis/axisticker.cpp' */
/* modified 2022-11-06T12:45:56, size 18693 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxisTicker
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxisTicker
\brief The base class tick generator used by QCPAxis to create tick positions and tick labels
Each QCPAxis has an internal QCPAxisTicker (or a subclass) in order to generate tick positions
and tick labels for the current axis range. The ticker of an axis can be set via \ref
QCPAxis::setTicker. Since that method takes a <tt>QSharedPointer<QCPAxisTicker></tt>, multiple
axes can share the same ticker instance.
This base class generates normal tick coordinates and numeric labels for linear axes. It picks a
reasonable tick step (the separation between ticks) which results in readable tick labels. The
number of ticks that should be approximately generated can be set via \ref setTickCount.
Depending on the current tick step strategy (\ref setTickStepStrategy), the algorithm either
sacrifices readability to better match the specified tick count (\ref
QCPAxisTicker::tssMeetTickCount) or relaxes the tick count in favor of better tick steps (\ref
QCPAxisTicker::tssReadability), which is the default.
The following more specialized axis ticker subclasses are available, see details in the
respective class documentation:
<center>
<table>
<tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerFixed</td><td>\image html axisticker-fixed.png</td></tr>
<tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerLog</td><td>\image html axisticker-log.png</td></tr>
<tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerPi</td><td>\image html axisticker-pi.png</td></tr>
<tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerText</td><td>\image html axisticker-text.png</td></tr>
<tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerDateTime</td><td>\image html axisticker-datetime.png</td></tr>
<tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerTime</td><td>\image html axisticker-time.png
\image html axisticker-time2.png</td></tr>
</table>
</center>
\section axisticker-subclassing Creating own axis tickers
Creating own axis tickers can be achieved very easily by sublassing QCPAxisTicker and
reimplementing some or all of the available virtual methods.
In the simplest case you might wish to just generate different tick steps than the other tickers,
so you only reimplement the method \ref getTickStep. If you additionally want control over the
string that will be shown as tick label, reimplement \ref getTickLabel.
If you wish to have complete control, you can generate the tick vectors and tick label vectors
yourself by reimplementing \ref createTickVector and \ref createLabelVector. The default
implementations use the previously mentioned virtual methods \ref getTickStep and \ref
getTickLabel, but your reimplementations don't necessarily need to do so. For example in the case
of unequal tick steps, the method \ref getTickStep loses its usefulness and can be ignored.
The sub tick count between major ticks can be controlled with \ref getSubTickCount. Full sub tick
placement control is obtained by reimplementing \ref createSubTickVector.
See the documentation of all these virtual methods in QCPAxisTicker for detailed information
about the parameters and expected return values.
*/
/*!
Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
*/
QCPAxisTicker::QCPAxisTicker() :
mTickStepStrategy(tssReadability),
mTickCount(5),
mTickOrigin(0)
{
}
QCPAxisTicker::~QCPAxisTicker()
{
}
/*!
Sets which strategy the axis ticker follows when choosing the size of the tick step. For the
available strategies, see \ref TickStepStrategy.
*/
void QCPAxisTicker::setTickStepStrategy(QCPAxisTicker::TickStepStrategy strategy)
{
mTickStepStrategy = strategy;
}
/*!
Sets how many ticks this ticker shall aim to generate across the axis range. Note that \a count
is not guaranteed to be matched exactly, as generating readable tick intervals may conflict with
the requested number of ticks.
Whether the readability has priority over meeting the requested \a count can be specified with
\ref setTickStepStrategy.
*/
void QCPAxisTicker::setTickCount(int count)
{
if (count > 0)
mTickCount = count;
else
qDebug() << Q_FUNC_INFO << "tick count must be greater than zero:" << count;
}
/*!
Sets the mathematical coordinate (or "offset") of the zeroth tick. This tick coordinate is just a
concept and doesn't need to be inside the currently visible axis range.
By default \a origin is zero, which for example yields ticks {-5, 0, 5, 10, 15,...} when the tick
step is five. If \a origin is now set to 1 instead, the correspondingly generated ticks would be
{-4, 1, 6, 11, 16,...}.
*/
void QCPAxisTicker::setTickOrigin(double origin)
{
mTickOrigin = origin;
}
/*!
This is the method called by QCPAxis in order to actually generate tick coordinates (\a ticks),
tick label strings (\a tickLabels) and sub tick coordinates (\a subTicks).
The ticks are generated for the specified \a range. The generated labels typically follow the
specified \a locale, \a formatChar and number \a precision, however this might be different (or
even irrelevant) for certain QCPAxisTicker subclasses.
The output parameter \a ticks is filled with the generated tick positions in axis coordinates.
The output parameters \a subTicks and \a tickLabels are optional (set them to \c nullptr if not
needed) and are respectively filled with sub tick coordinates, and tick label strings belonging
to \a ticks by index.
*/
void QCPAxisTicker::generate(const QCPRange &range, const QLocale &locale, QChar formatChar, int precision, QVector<double> &ticks, QVector<double> *subTicks, QVector<QString> *tickLabels)
{
// generate (major) ticks:
double tickStep = getTickStep(range);
ticks = createTickVector(tickStep, range);
trimTicks(range, ticks, true); // trim ticks to visible range plus one outer tick on each side (incase a subclass createTickVector creates more)
// generate sub ticks between major ticks:
if (subTicks)
{
if (!ticks.isEmpty())
{
*subTicks = createSubTickVector(getSubTickCount(tickStep), ticks);
trimTicks(range, *subTicks, false);
} else
*subTicks = QVector<double>();
}
// finally trim also outliers (no further clipping happens in axis drawing):
trimTicks(range, ticks, false);
// generate labels for visible ticks if requested:
if (tickLabels)
*tickLabels = createLabelVector(ticks, locale, formatChar, precision);
}
/*! \internal
Takes the entire currently visible axis range and returns a sensible tick step in
order to provide readable tick labels as well as a reasonable number of tick counts (see \ref
setTickCount, \ref setTickStepStrategy).
If a QCPAxisTicker subclass only wants a different tick step behaviour than the default
implementation, it should reimplement this method. See \ref cleanMantissa for a possible helper
function.
*/
double QCPAxisTicker::getTickStep(const QCPRange &range)
{
double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
return cleanMantissa(exactStep);
}
/*! \internal
Takes the \a tickStep, i.e. the distance between two consecutive ticks, and returns
an appropriate number of sub ticks for that specific tick step.
Note that a returned sub tick count of e.g. 4 will split each tick interval into 5 sections.
*/
int QCPAxisTicker::getSubTickCount(double tickStep)
{
int result = 1; // default to 1, if no proper value can be found
// separate integer and fractional part of mantissa:
double epsilon = 0.01;
double intPartf;
int intPart;
double fracPart = modf(getMantissa(tickStep), &intPartf);
intPart = int(intPartf);
// handle cases with (almost) integer mantissa:
if (fracPart < epsilon || 1.0-fracPart < epsilon)
{
if (1.0-fracPart < epsilon)
++intPart;
switch (intPart)
{
case 1: result = 4; break; // 1.0 -> 0.2 substep
case 2: result = 3; break; // 2.0 -> 0.5 substep
case 3: result = 2; break; // 3.0 -> 1.0 substep
case 4: result = 3; break; // 4.0 -> 1.0 substep
case 5: result = 4; break; // 5.0 -> 1.0 substep
case 6: result = 2; break; // 6.0 -> 2.0 substep
case 7: result = 6; break; // 7.0 -> 1.0 substep
case 8: result = 3; break; // 8.0 -> 2.0 substep
case 9: result = 2; break; // 9.0 -> 3.0 substep
}
} else
{
// handle cases with significantly fractional mantissa:
if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa
{
switch (intPart)
{
case 1: result = 2; break; // 1.5 -> 0.5 substep
case 2: result = 4; break; // 2.5 -> 0.5 substep
case 3: result = 4; break; // 3.5 -> 0.7 substep
case 4: result = 2; break; // 4.5 -> 1.5 substep
case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with default getTickStep from here on)
case 6: result = 4; break; // 6.5 -> 1.3 substep
case 7: result = 2; break; // 7.5 -> 2.5 substep
case 8: result = 4; break; // 8.5 -> 1.7 substep
case 9: result = 4; break; // 9.5 -> 1.9 substep
}
}
// if mantissa fraction isn't 0.0 or 0.5, don't bother finding good sub tick marks, leave default
}
return result;
}
/*! \internal
This method returns the tick label string as it should be printed under the \a tick coordinate.
If a textual number is returned, it should respect the provided \a locale, \a formatChar and \a
precision.
If the returned value contains exponentials of the form "2e5" and beautifully typeset powers is
enabled in the QCPAxis number format (\ref QCPAxis::setNumberFormat), the exponential part will
be formatted accordingly using multiplication symbol and superscript during rendering of the
label automatically.
*/
QString QCPAxisTicker::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
{
return locale.toString(tick, formatChar.toLatin1(), precision);
}
/*! \internal
Returns a vector containing all coordinates of sub ticks that should be drawn. It generates \a
subTickCount sub ticks between each tick pair given in \a ticks.
If a QCPAxisTicker subclass needs maximal control over the generated sub ticks, it should
reimplement this method. Depending on the purpose of the subclass it doesn't necessarily need to
base its result on \a subTickCount or \a ticks.
*/
QVector<double> QCPAxisTicker::createSubTickVector(int subTickCount, const QVector<double> &ticks)
{
QVector<double> result;
if (subTickCount <= 0 || ticks.size() < 2)
return result;
result.reserve((ticks.size()-1)*subTickCount);
for (int i=1; i<ticks.size(); ++i)
{
double subTickStep = (ticks.at(i)-ticks.at(i-1))/double(subTickCount+1);
for (int k=1; k<=subTickCount; ++k)
result.append(ticks.at(i-1) + k*subTickStep);
}
return result;
}
/*! \internal
Returns a vector containing all coordinates of ticks that should be drawn. The default
implementation generates ticks with a spacing of \a tickStep (mathematically starting at the tick
step origin, see \ref setTickOrigin) distributed over the passed \a range.
In order for the axis ticker to generate proper sub ticks, it is necessary that the first and
last tick coordinates returned by this method are just below/above the provided \a range.
Otherwise the outer intervals won't contain any sub ticks.
If a QCPAxisTicker subclass needs maximal control over the generated ticks, it should reimplement
this method. Depending on the purpose of the subclass it doesn't necessarily need to base its
result on \a tickStep, e.g. when the ticks are spaced unequally like in the case of
QCPAxisTickerLog.
*/
QVector<double> QCPAxisTicker::createTickVector(double tickStep, const QCPRange &range)
{
QVector<double> result;
// Generate tick positions according to tickStep:
qint64 firstStep = qint64(floor((range.lower-mTickOrigin)/tickStep)); // do not use qFloor here, or we'll lose 64 bit precision
qint64 lastStep = qint64(ceil((range.upper-mTickOrigin)/tickStep)); // do not use qCeil here, or we'll lose 64 bit precision
int tickcount = int(lastStep-firstStep+1);
if (tickcount < 0) tickcount = 0;
result.resize(tickcount);
for (int i=0; i<tickcount; ++i)
result[i] = mTickOrigin + (firstStep+i)*tickStep;
return result;
}
/*! \internal
Returns a vector containing all tick label strings corresponding to the tick coordinates provided
in \a ticks. The default implementation calls \ref getTickLabel to generate the respective
strings.
It is possible but uncommon for QCPAxisTicker subclasses to reimplement this method, as
reimplementing \ref getTickLabel often achieves the intended result easier.
*/
QVector<QString> QCPAxisTicker::createLabelVector(const QVector<double> &ticks, const QLocale &locale, QChar formatChar, int precision)
{
QVector<QString> result;
result.reserve(ticks.size());
foreach (double tickCoord, ticks)
result.append(getTickLabel(tickCoord, locale, formatChar, precision));
return result;
}
/*! \internal
Removes tick coordinates from \a ticks which lie outside the specified \a range. If \a
keepOneOutlier is true, it preserves one tick just outside the range on both sides, if present.
The passed \a ticks must be sorted in ascending order.
*/
void QCPAxisTicker::trimTicks(const QCPRange &range, QVector<double> &ticks, bool keepOneOutlier) const
{
bool lowFound = false;
bool highFound = false;
int lowIndex = 0;
int highIndex = -1;
for (int i=0; i < ticks.size(); ++i)
{
if (ticks.at(i) >= range.lower)
{
lowFound = true;
lowIndex = i;
break;
}
}
for (int i=static_cast<int>(ticks.size())-1; i >= 0; --i)
{
if (ticks.at(i) <= range.upper)
{
highFound = true;
highIndex = i;
break;
}
}
if (highFound && lowFound)
{
int trimFront = qMax(0, lowIndex-(keepOneOutlier ? 1 : 0));
int trimBack = qMax(0, static_cast<int>(ticks.size())-(keepOneOutlier ? 2 : 1)-highIndex);
if (trimFront > 0 || trimBack > 0)
ticks = ticks.mid(trimFront, ticks.size()-trimFront-trimBack);
} else // all ticks are either all below or all above the range
ticks.clear();
}
/*! \internal
Returns the coordinate contained in \a candidates which is closest to the provided \a target.
This method assumes \a candidates is not empty and sorted in ascending order.
*/
double QCPAxisTicker::pickClosest(double target, const QVector<double> &candidates) const
{
if (candidates.size() == 1)
return candidates.first();
QVector<double>::const_iterator it = std::lower_bound(candidates.constBegin(), candidates.constEnd(), target);
if (it == candidates.constEnd())
return *(it-1);
else if (it == candidates.constBegin())
return *it;
else
return target-*(it-1) < *it-target ? *(it-1) : *it;
}
/*! \internal
Returns the decimal mantissa of \a input. Optionally, if \a magnitude is not set to zero, it also
returns the magnitude of \a input as a power of 10.
For example, an input of 142.6 will return a mantissa of 1.426 and a magnitude of 100.
*/
double QCPAxisTicker::getMantissa(double input, double *magnitude) const
{
const double mag = std::pow(10.0, std::floor(std::log10(input)));
if (magnitude) *magnitude = mag;
return input/mag;
}
/*! \internal
Returns a number that is close to \a input but has a clean, easier human readable mantissa. How
strongly the mantissa is altered, and thus how strong the result deviates from the original \a
input, depends on the current tick step strategy (see \ref setTickStepStrategy).
*/
double QCPAxisTicker::cleanMantissa(double input) const
{
double magnitude;
const double mantissa = getMantissa(input, &magnitude);
switch (mTickStepStrategy)
{
case tssReadability:
{
return pickClosest(mantissa, QVector<double>() << 1.0 << 2.0 << 2.5 << 5.0 << 10.0)*magnitude;
}
case tssMeetTickCount:
{
// this gives effectively a mantissa of 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 6.0, 8.0, 10.0
if (mantissa <= 5.0)
return int(mantissa*2)/2.0*magnitude; // round digit after decimal point to 0.5
else
return int(mantissa/2.0)*2.0*magnitude; // round to first digit in multiples of 2
}
}
return input;
}
/* end of 'src/axis/axisticker.cpp' */
/* including file 'src/axis/axistickerdatetime.cpp' */
/* modified 2022-11-06T12:45:56, size 18829 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxisTickerDateTime
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxisTickerDateTime
\brief Specialized axis ticker for calendar dates and times as axis ticks
\image html axisticker-datetime.png
This QCPAxisTicker subclass generates ticks that correspond to real calendar dates and times. The
plot axis coordinate is interpreted as Unix Time, so seconds since Epoch (January 1, 1970, 00:00
UTC). This is also used for example by QDateTime in the <tt>toTime_t()/setTime_t()</tt> methods
with a precision of one second. Since Qt 4.7, millisecond accuracy can be obtained from QDateTime
by using <tt>QDateTime::fromMSecsSinceEpoch()/1000.0</tt>. The static methods \ref dateTimeToKey
and \ref keyToDateTime conveniently perform this conversion achieving a precision of one
millisecond on all Qt versions.
The format of the date/time display in the tick labels is controlled with \ref setDateTimeFormat.
If a different time spec or time zone shall be used for the tick label appearance, see \ref
setDateTimeSpec or \ref setTimeZone, respectively.
This ticker produces unequal tick spacing in order to provide intuitive date and time-of-day
ticks. For example, if the axis range spans a few years such that there is one tick per year,
ticks will be positioned on 1. January of every year. This is intuitive but, due to leap years,
will result in slightly unequal tick intervals (visually unnoticeable). The same can be seen in
the image above: even though the number of days varies month by month, this ticker generates
ticks on the same day of each month.
If you would like to change the date/time that is used as a (mathematical) starting date for the
ticks, use the \ref setTickOrigin(const QDateTime &origin) method overload, which takes a
QDateTime. If you pass 15. July, 9:45 to this method, the yearly ticks will end up on 15. July at
9:45 of every year.
The ticker can be created and assigned to an axis like this:
\snippet documentation/doc-image-generator/mainwindow.cpp axistickerdatetime-creation
\note If you rather wish to display relative times in terms of days, hours, minutes, seconds and
milliseconds, and are not interested in the intricacies of real calendar dates with months and
(leap) years, have a look at QCPAxisTickerTime instead.
*/
/*!
Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
*/
QCPAxisTickerDateTime::QCPAxisTickerDateTime() :
mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")),
mDateTimeSpec(Qt::LocalTime),
mDateStrategy(dsNone)
{
setTickCount(4);
}
/*!
Sets the format in which dates and times are displayed as tick labels. For details about the \a
format string, see the documentation of QDateTime::toString().
Typical expressions are
<table>
<tr><td>\c d</td><td>The day as a number without a leading zero (1 to 31)</td></tr>
<tr><td>\c dd</td><td>The day as a number with a leading zero (01 to 31)</td></tr>
<tr><td>\c ddd</td><td>The abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses the system locale to localize the name, i.e. QLocale::system().</td></tr>
<tr><td>\c dddd</td><td>The long localized day name (e.g. 'Monday' to 'Sunday'). Uses the system locale to localize the name, i.e. QLocale::system().</td></tr>
<tr><td>\c M</td><td>The month as a number without a leading zero (1 to 12)</td></tr>
<tr><td>\c MM</td><td>The month as a number with a leading zero (01 to 12)</td></tr>
<tr><td>\c MMM</td><td>The abbreviated localized month name (e.g. 'Jan' to 'Dec'). Uses the system locale to localize the name, i.e. QLocale::system().</td></tr>
<tr><td>\c MMMM</td><td>The long localized month name (e.g. 'January' to 'December'). Uses the system locale to localize the name, i.e. QLocale::system().</td></tr>
<tr><td>\c yy</td><td>The year as a two digit number (00 to 99)</td></tr>
<tr><td>\c yyyy</td><td>The year as a four digit number. If the year is negative, a minus sign is prepended, making five characters.</td></tr>
<tr><td>\c h</td><td>The hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)</td></tr>
<tr><td>\c hh</td><td>The hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)</td></tr>
<tr><td>\c H</td><td>The hour without a leading zero (0 to 23, even with AM/PM display)</td></tr>
<tr><td>\c HH</td><td>The hour with a leading zero (00 to 23, even with AM/PM display)</td></tr>
<tr><td>\c m</td><td>The minute without a leading zero (0 to 59)</td></tr>
<tr><td>\c mm</td><td>The minute with a leading zero (00 to 59)</td></tr>
<tr><td>\c s</td><td>The whole second, without any leading zero (0 to 59)</td></tr>
<tr><td>\c ss</td><td>The whole second, with a leading zero where applicable (00 to 59)</td></tr>
<tr><td>\c z</td><td>The fractional part of the second, to go after a decimal point, without trailing zeroes (0 to 999). Thus "s.z" reports the seconds to full available (millisecond) precision without trailing zeroes.</td></tr>
<tr><td>\c zzz</td><td>The fractional part of the second, to millisecond precision, including trailing zeroes where applicable (000 to 999).</td></tr>
<tr><td>\c AP or \c A</td><td>Use AM/PM display. A/AP will be replaced by an upper-case version of either QLocale::amText() or QLocale::pmText().</td></tr>
<tr><td>\c ap or \c a</td><td>Use am/pm display. a/ap will be replaced by a lower-case version of either QLocale::amText() or QLocale::pmText().</td></tr>
<tr><td>\c t</td><td>The timezone (for example "CEST")</td></tr>
</table>
Newlines can be inserted with \c "\n", literal strings (even when containing above expressions)
by encapsulating them using single-quotes. A literal single quote can be generated by using two
consecutive single quotes in the format.
\see setDateTimeSpec, setTimeZone
*/
void QCPAxisTickerDateTime::setDateTimeFormat(const QString &format)
{
mDateTimeFormat = format;
}
/*!
Sets the time spec that is used for creating the tick labels from corresponding dates/times.
The default value of QDateTime objects (and also QCPAxisTickerDateTime) is
<tt>Qt::LocalTime</tt>. However, if the displayed tick labels shall be given in UTC, set \a spec
to <tt>Qt::UTC</tt>.
Tick labels corresponding to other time zones can be achieved with \ref setTimeZone (which sets
\a spec to \c Qt::TimeZone internally). Note that if \a spec is afterwards set to not be \c
Qt::TimeZone again, the \ref setTimeZone setting will be ignored accordingly.
\see setDateTimeFormat, setTimeZone
*/
void QCPAxisTickerDateTime::setDateTimeSpec(Qt::TimeSpec spec)
{
mDateTimeSpec = spec;
}
# if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
/*!
Sets the time zone that is used for creating the tick labels from corresponding dates/times. The
time spec (\ref setDateTimeSpec) is set to \c Qt::TimeZone.
\see setDateTimeFormat, setTimeZone
*/
void QCPAxisTickerDateTime::setTimeZone(const QTimeZone &zone)
{
mTimeZone = zone;
mDateTimeSpec = Qt::TimeZone;
}
#endif
/*!
Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) in seconds since Epoch (1. Jan 1970,
00:00 UTC). For the date time ticker it might be more intuitive to use the overload which
directly takes a QDateTime, see \ref setTickOrigin(const QDateTime &origin).
This is useful to define the month/day/time recurring at greater tick interval steps. For
example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
per year, the ticks will end up on 15. July at 9:45 of every year.
*/
void QCPAxisTickerDateTime::setTickOrigin(double origin)
{
QCPAxisTicker::setTickOrigin(origin);
}
/*!
Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) as a QDateTime \a origin.
This is useful to define the month/day/time recurring at greater tick interval steps. For
example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
per year, the ticks will end up on 15. July at 9:45 of every year.
*/
void QCPAxisTickerDateTime::setTickOrigin(const QDateTime &origin)
{
setTickOrigin(dateTimeToKey(origin));
}
/*! \internal
Returns a sensible tick step with intervals appropriate for a date-time-display, such as weekly,
monthly, bi-monthly, etc.
Note that this tick step isn't used exactly when generating the tick vector in \ref
createTickVector, but only as a guiding value requiring some correction for each individual tick
interval. Otherwise this would lead to unintuitive date displays, e.g. jumping between first day
in the month to the last day in the previous month from tick to tick, due to the non-uniform
length of months. The same problem arises with leap years.
\seebaseclassmethod
*/
double QCPAxisTickerDateTime::getTickStep(const QCPRange &range)
{
double result = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
mDateStrategy = dsNone; // leaving it at dsNone means tick coordinates will not be tuned in any special way in createTickVector
if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
{
result = cleanMantissa(result);
} else if (result < 86400*30.4375*12) // below a year
{
result = pickClosest(result, QVector<double>()
<< 1 << 2.5 << 5 << 10 << 15 << 30 << 60 << 2.5*60 << 5*60 << 10*60 << 15*60 << 30*60 << 60*60 // second, minute, hour range
<< 3600*2 << 3600*3 << 3600*6 << 3600*12 << 3600*24 // hour to day range
<< 86400*2 << 86400*5 << 86400*7 << 86400*14 << 86400*30.4375 << 86400*30.4375*2 << 86400*30.4375*3 << 86400*30.4375*6 << 86400*30.4375*12); // day, week, month range (avg. days per month includes leap years)
if (result > 86400*30.4375-1) // month tick intervals or larger
mDateStrategy = dsUniformDayInMonth;
else if (result > 3600*24-1) // day tick intervals or larger
mDateStrategy = dsUniformTimeInDay;
} else // more than a year, go back to normal clean mantissa algorithm but in units of years
{
const double secondsPerYear = 86400*30.4375*12; // average including leap years
result = cleanMantissa(result/secondsPerYear)*secondsPerYear;
mDateStrategy = dsUniformDayInMonth;
}
return result;
}
/*! \internal
Returns a sensible sub tick count with intervals appropriate for a date-time-display, such as weekly,
monthly, bi-monthly, etc.
\seebaseclassmethod
*/
int QCPAxisTickerDateTime::getSubTickCount(double tickStep)
{
int result = QCPAxisTicker::getSubTickCount(tickStep);
switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day/week/month range (as specified in getTickStep)
{
case 5*60: result = 4; break;
case 10*60: result = 1; break;
case 15*60: result = 2; break;
case 30*60: result = 1; break;
case 60*60: result = 3; break;
case 3600*2: result = 3; break;
case 3600*3: result = 2; break;
case 3600*6: result = 1; break;
case 3600*12: result = 3; break;
case 3600*24: result = 3; break;
case 86400*2: result = 1; break;
case 86400*5: result = 4; break;
case 86400*7: result = 6; break;
case 86400*14: result = 1; break;
case int(86400*30.4375+0.5): result = 3; break;
case int(86400*30.4375*2+0.5): result = 1; break;
case int(86400*30.4375*3+0.5): result = 2; break;
case int(86400*30.4375*6+0.5): result = 5; break;
case int(86400*30.4375*12+0.5): result = 3; break;
}
return result;
}
/*! \internal
Generates a date/time tick label for tick coordinate \a tick, based on the currently set format
(\ref setDateTimeFormat), time spec (\ref setDateTimeSpec), and possibly time zone (\ref
setTimeZone).
\seebaseclassmethod
*/
QString QCPAxisTickerDateTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
{
Q_UNUSED(precision)
Q_UNUSED(formatChar)
# if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
if (mDateTimeSpec == Qt::TimeZone)
return locale.toString(keyToDateTime(tick).toTimeZone(mTimeZone), mDateTimeFormat);
else
return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
# else
return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
# endif
}
/*! \internal
Uses the passed \a tickStep as a guiding value and applies corrections in order to obtain
non-uniform tick intervals but intuitive tick labels, e.g. falling on the same day of each month.
\seebaseclassmethod
*/
QVector<double> QCPAxisTickerDateTime::createTickVector(double tickStep, const QCPRange &range)
{
QVector<double> result = QCPAxisTicker::createTickVector(tickStep, range);
if (!result.isEmpty())
{
if (mDateStrategy == dsUniformTimeInDay)
{
QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // the time of this datetime will be set for all other ticks, if possible
QDateTime tickDateTime;
for (int i=0; i<result.size(); ++i)
{
tickDateTime = keyToDateTime(result.at(i));
tickDateTime.setTime(uniformDateTime.time());
result[i] = dateTimeToKey(tickDateTime);
}
} else if (mDateStrategy == dsUniformDayInMonth)
{
QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // this day (in month) and time will be set for all other ticks, if possible
QDateTime tickDateTime;
for (int i=0; i<result.size(); ++i)
{
tickDateTime = keyToDateTime(result.at(i));
tickDateTime.setTime(uniformDateTime.time());
int thisUniformDay = uniformDateTime.date().day() <= tickDateTime.date().daysInMonth() ? uniformDateTime.date().day() : tickDateTime.date().daysInMonth(); // don't exceed month (e.g. try to set day 31 in February)
if (thisUniformDay-tickDateTime.date().day() < -15) // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day
tickDateTime = tickDateTime.addMonths(1);
else if (thisUniformDay-tickDateTime.date().day() > 15) // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day
tickDateTime = tickDateTime.addMonths(-1);
tickDateTime.setDate(QDate(tickDateTime.date().year(), tickDateTime.date().month(), thisUniformDay));
result[i] = dateTimeToKey(tickDateTime);
}
}
}
return result;
}
/*!
A convenience method which turns \a key (in seconds since Epoch 1. Jan 1970, 00:00 UTC) into a
QDateTime object. This can be used to turn axis coordinates to actual QDateTimes.
The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
works around the lack of a QDateTime::fromMSecsSinceEpoch in Qt 4.6)
\see dateTimeToKey
*/
QDateTime QCPAxisTickerDateTime::keyToDateTime(double key)
{
# if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
return QDateTime::fromTime_t(key).addMSecs((key-(qint64)key)*1000);
# else
return QDateTime::fromMSecsSinceEpoch(qint64(key*1000.0));
# endif
}
/*! \overload
A convenience method which turns a QDateTime object into a double value that corresponds to
seconds since Epoch (1. Jan 1970, 00:00 UTC). This is the format used as axis coordinates by
QCPAxisTickerDateTime.
The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
works around the lack of a QDateTime::toMSecsSinceEpoch in Qt 4.6)
\see keyToDateTime
*/
double QCPAxisTickerDateTime::dateTimeToKey(const QDateTime &dateTime)
{
# if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
return dateTime.toTime_t()+dateTime.time().msec()/1000.0;
# else
return dateTime.toMSecsSinceEpoch()/1000.0;
# endif
}
/*! \overload
A convenience method which turns a QDate object into a double value that corresponds to seconds
since Epoch (1. Jan 1970, 00:00 UTC). This is the format used
as axis coordinates by QCPAxisTickerDateTime.
The returned value will be the start of the passed day of \a date, interpreted in the given \a
timeSpec.
\see keyToDateTime
*/
double QCPAxisTickerDateTime::dateTimeToKey(const QDate &date, Qt::TimeSpec timeSpec)
{
# if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
return QDateTime(date, QTime(0, 0), timeSpec).toTime_t();
# elif QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
return QDateTime(date, QTime(0, 0), timeSpec).toMSecsSinceEpoch()/1000.0;
# else
return date.startOfDay(timeSpec).toMSecsSinceEpoch()/1000.0;
# endif
}
/* end of 'src/axis/axistickerdatetime.cpp' */
/* including file 'src/axis/axistickertime.cpp' */
/* modified 2022-11-06T12:45:56, size 11745 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxisTickerTime
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxisTickerTime
\brief Specialized axis ticker for time spans in units of milliseconds to days
\image html axisticker-time.png
This QCPAxisTicker subclass generates ticks that corresponds to time intervals.
The format of the time display in the tick labels is controlled with \ref setTimeFormat and \ref
setFieldWidth. The time coordinate is in the unit of seconds with respect to the time coordinate
zero. Unlike with QCPAxisTickerDateTime, the ticks don't correspond to a specific calendar date
and time.
The time can be displayed in milliseconds, seconds, minutes, hours and days. Depending on the
largest available unit in the format specified with \ref setTimeFormat, any time spans above will
be carried in that largest unit. So for example if the format string is "%m:%s" and a tick at
coordinate value 7815 (being 2 hours, 10 minutes and 15 seconds) is created, the resulting tick
label will show "130:15" (130 minutes, 15 seconds). If the format string is "%h:%m:%s", the hour
unit will be used and the label will thus be "02:10:15". Negative times with respect to the axis
zero will carry a leading minus sign.
The ticker can be created and assigned to an axis like this:
\snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation
Here is an example of a time axis providing time information in days, hours and minutes. Due to
the axis range spanning a few days and the wanted tick count (\ref setTickCount), the ticker
decided to use tick steps of 12 hours:
\image html axisticker-time2.png
The format string for this example is
\snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation-2
\note If you rather wish to display calendar dates and times, have a look at QCPAxisTickerDateTime
instead.
*/
/*!
Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
*/
QCPAxisTickerTime::QCPAxisTickerTime() :
mTimeFormat(QLatin1String("%h:%m:%s")),
mSmallestUnit(tuSeconds),
mBiggestUnit(tuHours)
{
setTickCount(4);
mFieldWidth[tuMilliseconds] = 3;
mFieldWidth[tuSeconds] = 2;
mFieldWidth[tuMinutes] = 2;
mFieldWidth[tuHours] = 2;
mFieldWidth[tuDays] = 1;
mFormatPattern[tuMilliseconds] = QLatin1String("%z");
mFormatPattern[tuSeconds] = QLatin1String("%s");
mFormatPattern[tuMinutes] = QLatin1String("%m");
mFormatPattern[tuHours] = QLatin1String("%h");
mFormatPattern[tuDays] = QLatin1String("%d");
}
/*!
Sets the format that will be used to display time in the tick labels.
The available patterns are:
- %%z for milliseconds
- %%s for seconds
- %%m for minutes
- %%h for hours
- %%d for days
The field width (zero padding) can be controlled for each unit with \ref setFieldWidth.
The largest unit that appears in \a format will carry all the remaining time of a certain tick
coordinate, even if it overflows the natural limit of the unit. For example, if %%m is the
largest unit it might become larger than 59 in order to consume larger time values. If on the
other hand %%h is available, the minutes will wrap around to zero after 59 and the time will
carry to the hour digit.
*/
void QCPAxisTickerTime::setTimeFormat(const QString &format)
{
mTimeFormat = format;
// determine smallest and biggest unit in format, to optimize unit replacement and allow biggest
// unit to consume remaining time of a tick value and grow beyond its modulo (e.g. min > 59)
mSmallestUnit = tuMilliseconds;
mBiggestUnit = tuMilliseconds;
bool hasSmallest = false;
for (int i = tuMilliseconds; i <= tuDays; ++i)
{
TimeUnit unit = static_cast<TimeUnit>(i);
if (mTimeFormat.contains(mFormatPattern.value(unit)))
{
if (!hasSmallest)
{
mSmallestUnit = unit;
hasSmallest = true;
}
mBiggestUnit = unit;
}
}
}
/*!
Sets the field widh of the specified \a unit to be \a width digits, when displayed in the tick
label. If the number for the specific unit is shorter than \a width, it will be padded with an
according number of zeros to the left in order to reach the field width.
\see setTimeFormat
*/
void QCPAxisTickerTime::setFieldWidth(QCPAxisTickerTime::TimeUnit unit, int width)
{
mFieldWidth[unit] = qMax(width, 1);
}
/*! \internal
Returns the tick step appropriate for time displays, depending on the provided \a range and the
smallest available time unit in the current format (\ref setTimeFormat). For example if the unit
of seconds isn't available in the format, this method will not generate steps (like 2.5 minutes)
that require sub-minute precision to be displayed correctly.
\seebaseclassmethod
*/
double QCPAxisTickerTime::getTickStep(const QCPRange &range)
{
double result = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
{
if (mSmallestUnit == tuMilliseconds)
result = qMax(cleanMantissa(result), 0.001); // smallest tick step is 1 millisecond
else // have no milliseconds available in format, so stick with 1 second tickstep
result = 1.0;
} else if (result < 3600*24) // below a day
{
// the filling of availableSteps seems a bit contorted but it fills in a sorted fashion and thus saves a post-fill sorting run
QVector<double> availableSteps;
// seconds range:
if (mSmallestUnit <= tuSeconds)
availableSteps << 1;
if (mSmallestUnit == tuMilliseconds)
availableSteps << 2.5; // only allow half second steps if milliseconds are there to display it
else if (mSmallestUnit == tuSeconds)
availableSteps << 2;
if (mSmallestUnit <= tuSeconds)
availableSteps << 5 << 10 << 15 << 30;
// minutes range:
if (mSmallestUnit <= tuMinutes)
availableSteps << 1*60;
if (mSmallestUnit <= tuSeconds)
availableSteps << 2.5*60; // only allow half minute steps if seconds are there to display it
else if (mSmallestUnit == tuMinutes)
availableSteps << 2*60;
if (mSmallestUnit <= tuMinutes)
availableSteps << 5*60 << 10*60 << 15*60 << 30*60;
// hours range:
if (mSmallestUnit <= tuHours)
availableSteps << 1*3600 << 2*3600 << 3*3600 << 6*3600 << 12*3600 << 24*3600;
// pick available step that is most appropriate to approximate ideal step:
result = pickClosest(result, availableSteps);
} else // more than a day, go back to normal clean mantissa algorithm but in units of days
{
const double secondsPerDay = 3600*24;
result = cleanMantissa(result/secondsPerDay)*secondsPerDay;
}
return result;
}
/*! \internal
Returns the sub tick count appropriate for the provided \a tickStep and time displays.
\seebaseclassmethod
*/
int QCPAxisTickerTime::getSubTickCount(double tickStep)
{
int result = QCPAxisTicker::getSubTickCount(tickStep);
switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day range (as specified in getTickStep)
{
case 5*60: result = 4; break;
case 10*60: result = 1; break;
case 15*60: result = 2; break;
case 30*60: result = 1; break;
case 60*60: result = 3; break;
case 3600*2: result = 3; break;
case 3600*3: result = 2; break;
case 3600*6: result = 1; break;
case 3600*12: result = 3; break;
case 3600*24: result = 3; break;
}
return result;
}
/*! \internal
Returns the tick label corresponding to the provided \a tick and the configured format and field
widths (\ref setTimeFormat, \ref setFieldWidth).
\seebaseclassmethod
*/
QString QCPAxisTickerTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
{
Q_UNUSED(precision)
Q_UNUSED(formatChar)
Q_UNUSED(locale)
bool negative = tick < 0;
if (negative) tick *= -1;
double values[tuDays+1]; // contains the msec/sec/min/... value with its respective modulo (e.g. minute 0..59)
double restValues[tuDays+1]; // contains the msec/sec/min/... value as if it's the largest available unit and thus consumes the remaining time
restValues[tuMilliseconds] = tick*1000;
values[tuMilliseconds] = modf(restValues[tuMilliseconds]/1000, &restValues[tuSeconds])*1000;
values[tuSeconds] = modf(restValues[tuSeconds]/60, &restValues[tuMinutes])*60;
values[tuMinutes] = modf(restValues[tuMinutes]/60, &restValues[tuHours])*60;
values[tuHours] = modf(restValues[tuHours]/24, &restValues[tuDays])*24;
// no need to set values[tuDays] because days are always a rest value (there is no higher unit so it consumes all remaining time)
QString result = mTimeFormat;
for (int i = mSmallestUnit; i <= mBiggestUnit; ++i)
{
TimeUnit iUnit = static_cast<TimeUnit>(i);
replaceUnit(result, iUnit, qRound(iUnit == mBiggestUnit ? restValues[iUnit] : values[iUnit]));
}
if (negative)
result.prepend(QLatin1Char('-'));
return result;
}
/*! \internal
Replaces all occurrences of the format pattern belonging to \a unit in \a text with the specified
\a value, using the field width as specified with \ref setFieldWidth for the \a unit.
*/
void QCPAxisTickerTime::replaceUnit(QString &text, QCPAxisTickerTime::TimeUnit unit, int value) const
{
QString valueStr = QString::number(value);
while (valueStr.size() < mFieldWidth.value(unit))
valueStr.prepend(QLatin1Char('0'));
text.replace(mFormatPattern.value(unit), valueStr);
}
/* end of 'src/axis/axistickertime.cpp' */
/* including file 'src/axis/axistickerfixed.cpp' */
/* modified 2022-11-06T12:45:56, size 5575 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxisTickerFixed
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxisTickerFixed
\brief Specialized axis ticker with a fixed tick step
\image html axisticker-fixed.png
This QCPAxisTicker subclass generates ticks with a fixed tick step set with \ref setTickStep. It
is also possible to allow integer multiples and integer powers of the specified tick step with
\ref setScaleStrategy.
A typical application of this ticker is to make an axis only display integers, by setting the
tick step of the ticker to 1.0 and the scale strategy to \ref ssMultiples.
Another case is when a certain number has a special meaning and axis ticks should only appear at
multiples of that value. In this case you might also want to consider \ref QCPAxisTickerPi
because despite the name it is not limited to only pi symbols/values.
The ticker can be created and assigned to an axis like this:
\snippet documentation/doc-image-generator/mainwindow.cpp axistickerfixed-creation
*/
/*!
Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
*/
QCPAxisTickerFixed::QCPAxisTickerFixed() :
mTickStep(1.0),
mScaleStrategy(ssNone)
{
}
/*!
Sets the fixed tick interval to \a step.
The axis ticker will only use this tick step when generating axis ticks. This might cause a very
high tick density and overlapping labels if the axis range is zoomed out. Using \ref
setScaleStrategy it is possible to relax the fixed step and also allow multiples or powers of \a
step. This will enable the ticker to reduce the number of ticks to a reasonable amount (see \ref
setTickCount).
*/
void QCPAxisTickerFixed::setTickStep(double step)
{
if (step > 0)
mTickStep = step;
else
qDebug() << Q_FUNC_INFO << "tick step must be greater than zero:" << step;
}
/*!
Sets whether the specified tick step (\ref setTickStep) is absolutely fixed or whether
modifications may be applied to it before calculating the finally used tick step, such as
permitting multiples or powers. See \ref ScaleStrategy for details.
The default strategy is \ref ssNone, which means the tick step is absolutely fixed.
*/
void QCPAxisTickerFixed::setScaleStrategy(QCPAxisTickerFixed::ScaleStrategy strategy)
{
mScaleStrategy = strategy;
}
/*! \internal
Determines the actually used tick step from the specified tick step and scale strategy (\ref
setTickStep, \ref setScaleStrategy).
This method either returns the specified tick step exactly, or, if the scale strategy is not \ref
ssNone, a modification of it to allow varying the number of ticks in the current axis range.
\seebaseclassmethod
*/
double QCPAxisTickerFixed::getTickStep(const QCPRange &range)
{
switch (mScaleStrategy)
{
case ssNone:
{
return mTickStep;
}
case ssMultiples:
{
double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
if (exactStep < mTickStep)
return mTickStep;
else
return qint64(cleanMantissa(exactStep/mTickStep)+0.5)*mTickStep;
}
case ssPowers:
{
double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
return qPow(mTickStep, int(qLn(exactStep)/qLn(mTickStep)+0.5));
}
}
return mTickStep;
}
/* end of 'src/axis/axistickerfixed.cpp' */
/* including file 'src/axis/axistickertext.cpp' */
/* modified 2022-11-06T12:45:56, size 8742 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxisTickerText
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxisTickerText
\brief Specialized axis ticker which allows arbitrary labels at specified coordinates
\image html axisticker-text.png
This QCPAxisTicker subclass generates ticks which can be directly specified by the user as
coordinates and associated strings. They can be passed as a whole with \ref setTicks or one at a
time with \ref addTick. Alternatively you can directly access the internal storage via \ref ticks
and modify the tick/label data there.
This is useful for cases where the axis represents categories rather than numerical values.
If you are updating the ticks of this ticker regularly and in a dynamic fasion (e.g. dependent on
the axis range), it is a sign that you should probably create an own ticker by subclassing
QCPAxisTicker, instead of using this one.
The ticker can be created and assigned to an axis like this:
\snippet documentation/doc-image-generator/mainwindow.cpp axistickertext-creation
*/
/* start of documentation of inline functions */
/*! \fn QMap<double, QString> &QCPAxisTickerText::ticks()
Returns a non-const reference to the internal map which stores the tick coordinates and their
labels.
You can access the map directly in order to add, remove or manipulate ticks, as an alternative to
using the methods provided by QCPAxisTickerText, such as \ref setTicks and \ref addTick.
*/
/* end of documentation of inline functions */
/*!
Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
*/
QCPAxisTickerText::QCPAxisTickerText() :
mSubTickCount(0)
{
}
/*! \overload
Sets the ticks that shall appear on the axis. The map key of \a ticks corresponds to the axis
coordinate, and the map value is the string that will appear as tick label.
An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
getter.
\see addTicks, addTick, clear
*/
void QCPAxisTickerText::setTicks(const QMap<double, QString> &ticks)
{
mTicks = ticks;
}
/*! \overload
Sets the ticks that shall appear on the axis. The entries of \a positions correspond to the axis
coordinates, and the entries of \a labels are the respective strings that will appear as tick
labels.
\see addTicks, addTick, clear
*/
void QCPAxisTickerText::setTicks(const QVector<double> &positions, const QVector<QString> &labels)
{
clear();
addTicks(positions, labels);
}
/*!
Sets the number of sub ticks that shall appear between ticks. For QCPAxisTickerText, there is no
automatic sub tick count calculation. So if sub ticks are needed, they must be configured with this
method.
*/
void QCPAxisTickerText::setSubTickCount(int subTicks)
{
if (subTicks >= 0)
mSubTickCount = subTicks;
else
qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
}
/*!
Clears all ticks.
An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
getter.
\see setTicks, addTicks, addTick
*/
void QCPAxisTickerText::clear()
{
mTicks.clear();
}
/*!
Adds a single tick to the axis at the given axis coordinate \a position, with the provided tick \a
label.
\see addTicks, setTicks, clear
*/
void QCPAxisTickerText::addTick(double position, const QString &label)
{
mTicks.insert(position, label);
}
/*! \overload
Adds the provided \a ticks to the ones already existing. The map key of \a ticks corresponds to
the axis coordinate, and the map value is the string that will appear as tick label.
An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
getter.
\see addTick, setTicks, clear
*/
void QCPAxisTickerText::addTicks(const QMap<double, QString> &ticks)
{
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
mTicks.unite(ticks);
#else
mTicks.insert(ticks);
#endif
}
/*! \overload
Adds the provided ticks to the ones already existing. The entries of \a positions correspond to
the axis coordinates, and the entries of \a labels are the respective strings that will appear as
tick labels.
An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
getter.
\see addTick, setTicks, clear
*/
void QCPAxisTickerText::addTicks(const QVector<double> &positions, const QVector<QString> &labels)
{
if (positions.size() != labels.size())
qDebug() << Q_FUNC_INFO << "passed unequal length vectors for positions and labels:" << positions.size() << labels.size();
int n = static_cast<int>(qMin(positions.size(), labels.size()));
for (int i=0; i<n; ++i)
mTicks.insert(positions.at(i), labels.at(i));
}
/*!
Since the tick coordinates are provided externally, this method implementation does nothing.
\seebaseclassmethod
*/
double QCPAxisTickerText::getTickStep(const QCPRange &range)
{
// text axis ticker has manual tick positions, so doesn't need this method
Q_UNUSED(range)
return 1.0;
}
/*!
Returns the sub tick count that was configured with \ref setSubTickCount.
\seebaseclassmethod
*/
int QCPAxisTickerText::getSubTickCount(double tickStep)
{
Q_UNUSED(tickStep)
return mSubTickCount;
}
/*!
Returns the tick label which corresponds to the key \a tick in the internal tick storage. Since
the labels are provided externally, \a locale, \a formatChar, and \a precision are ignored.
\seebaseclassmethod
*/
QString QCPAxisTickerText::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
{
Q_UNUSED(locale)
Q_UNUSED(formatChar)
Q_UNUSED(precision)
return mTicks.value(tick);
}
/*!
Returns the externally provided tick coordinates which are in the specified \a range. If
available, one tick above and below the range is provided in addition, to allow possible sub tick
calculation. The parameter \a tickStep is ignored.
\seebaseclassmethod
*/
QVector<double> QCPAxisTickerText::createTickVector(double tickStep, const QCPRange &range)
{
Q_UNUSED(tickStep)
QVector<double> result;
if (mTicks.isEmpty())
return result;
QMap<double, QString>::const_iterator start = mTicks.lowerBound(range.lower);
QMap<double, QString>::const_iterator end = mTicks.upperBound(range.upper);
// this method should try to give one tick outside of range so proper subticks can be generated:
if (start != mTicks.constBegin()) --start;
if (end != mTicks.constEnd()) ++end;
for (QMap<double, QString>::const_iterator it = start; it != end; ++it)
result.append(it.key());
return result;
}
/* end of 'src/axis/axistickertext.cpp' */
/* including file 'src/axis/axistickerpi.cpp' */
/* modified 2022-11-06T12:45:56, size 11177 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxisTickerPi
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxisTickerPi
\brief Specialized axis ticker to display ticks in units of an arbitrary constant, for example pi
\image html axisticker-pi.png
This QCPAxisTicker subclass generates ticks that are expressed with respect to a given symbolic
constant with a numerical value specified with \ref setPiValue and an appearance in the tick
labels specified with \ref setPiSymbol.
Ticks may be generated at fractions of the symbolic constant. How these fractions appear in the
tick label can be configured with \ref setFractionStyle.
The ticker can be created and assigned to an axis like this:
\snippet documentation/doc-image-generator/mainwindow.cpp axistickerpi-creation
*/
/*!
Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
*/
QCPAxisTickerPi::QCPAxisTickerPi() :
mPiSymbol(QLatin1String(" ")+QChar(0x03C0)),
mPiValue(M_PI),
mPeriodicity(0),
mFractionStyle(fsUnicodeFractions),
mPiTickStep(0)
{
setTickCount(4);
}
/*!
Sets how the symbol part (which is always a suffix to the number) shall appear in the axis tick
label.
If a space shall appear between the number and the symbol, make sure the space is contained in \a
symbol.
*/
void QCPAxisTickerPi::setPiSymbol(QString symbol)
{
mPiSymbol = symbol;
}
/*!
Sets the numerical value that the symbolic constant has.
This will be used to place the appropriate fractions of the symbol at the respective axis
coordinates.
*/
void QCPAxisTickerPi::setPiValue(double pi)
{
mPiValue = pi;
}
/*!
Sets whether the axis labels shall appear periodicly and if so, at which multiplicity of the
symbolic constant.
To disable periodicity, set \a multiplesOfPi to zero.
For example, an axis that identifies 0 with 2pi would set \a multiplesOfPi to two.
*/
void QCPAxisTickerPi::setPeriodicity(int multiplesOfPi)
{
mPeriodicity = qAbs(multiplesOfPi);
}
/*!
Sets how the numerical/fractional part preceding the symbolic constant is displayed in tick
labels. See \ref FractionStyle for the various options.
*/
void QCPAxisTickerPi::setFractionStyle(QCPAxisTickerPi::FractionStyle style)
{
mFractionStyle = style;
}
/*! \internal
Returns the tick step, using the constant's value (\ref setPiValue) as base unit. In consequence
the numerical/fractional part preceding the symbolic constant is made to have a readable
mantissa.
\seebaseclassmethod
*/
double QCPAxisTickerPi::getTickStep(const QCPRange &range)
{
mPiTickStep = range.size()/mPiValue/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
mPiTickStep = cleanMantissa(mPiTickStep);
return mPiTickStep*mPiValue;
}
/*! \internal
Returns the sub tick count, using the constant's value (\ref setPiValue) as base unit. In
consequence the sub ticks divide the numerical/fractional part preceding the symbolic constant
reasonably, and not the total tick coordinate.
\seebaseclassmethod
*/
int QCPAxisTickerPi::getSubTickCount(double tickStep)
{
return QCPAxisTicker::getSubTickCount(tickStep/mPiValue);
}
/*! \internal
Returns the tick label as a fractional/numerical part and a symbolic string as suffix. The
formatting of the fraction is done according to the specified \ref setFractionStyle. The appended
symbol is specified with \ref setPiSymbol.
\seebaseclassmethod
*/
QString QCPAxisTickerPi::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
{
double tickInPis = tick/mPiValue;
if (mPeriodicity > 0)
tickInPis = fmod(tickInPis, mPeriodicity);
if (mFractionStyle != fsFloatingPoint && mPiTickStep > 0.09 && mPiTickStep < 50)
{
// simply construct fraction from decimal like 1.234 -> 1234/1000 and then simplify fraction, smaller digits are irrelevant due to mPiTickStep conditional above
int denominator = 1000;
int numerator = qRound(tickInPis*denominator);
simplifyFraction(numerator, denominator);
if (qAbs(numerator) == 1 && denominator == 1)
return (numerator < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
else if (numerator == 0)
return QLatin1String("0");
else
return fractionToString(numerator, denominator) + mPiSymbol;
} else
{
if (qFuzzyIsNull(tickInPis))
return QLatin1String("0");
else if (qFuzzyCompare(qAbs(tickInPis), 1.0))
return (tickInPis < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
else
return QCPAxisTicker::getTickLabel(tickInPis, locale, formatChar, precision) + mPiSymbol;
}
}
/*! \internal
Takes the fraction given by \a numerator and \a denominator and modifies the values to make sure
the fraction is in irreducible form, i.e. numerator and denominator don't share any common
factors which could be cancelled.
*/
void QCPAxisTickerPi::simplifyFraction(int &numerator, int &denominator) const
{
if (numerator == 0 || denominator == 0)
return;
int num = numerator;
int denom = denominator;
while (denom != 0) // euclidean gcd algorithm
{
int oldDenom = denom;
denom = num % denom;
num = oldDenom;
}
// num is now gcd of numerator and denominator
numerator /= num;
denominator /= num;
}
/*! \internal
Takes the fraction given by \a numerator and \a denominator and returns a string representation.
The result depends on the configured fraction style (\ref setFractionStyle).
This method is used to format the numerical/fractional part when generating tick labels. It
simplifies the passed fraction to an irreducible form using \ref simplifyFraction and factors out
any integer parts of the fraction (e.g. "10/4" becomes "2 1/2").
*/
QString QCPAxisTickerPi::fractionToString(int numerator, int denominator) const
{
if (denominator == 0)
{
qDebug() << Q_FUNC_INFO << "called with zero denominator";
return QString();
}
if (mFractionStyle == fsFloatingPoint) // should never be the case when calling this function
{
qDebug() << Q_FUNC_INFO << "shouldn't be called with fraction style fsDecimal";
return QString::number(numerator/double(denominator)); // failsafe
}
int sign = numerator*denominator < 0 ? -1 : 1;
numerator = qAbs(numerator);
denominator = qAbs(denominator);
if (denominator == 1)
{
return QString::number(sign*numerator);
} else
{
int integerPart = numerator/denominator;
int remainder = numerator%denominator;
if (remainder == 0)
{
return QString::number(sign*integerPart);
} else
{
if (mFractionStyle == fsAsciiFractions)
{
return QString(QLatin1String("%1%2%3/%4"))
.arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
.arg(integerPart > 0 ? QString::number(integerPart)+QLatin1String(" ") : QString(QLatin1String("")))
.arg(remainder)
.arg(denominator);
} else if (mFractionStyle == fsUnicodeFractions)
{
return QString(QLatin1String("%1%2%3"))
.arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
.arg(integerPart > 0 ? QString::number(integerPart) : QLatin1String(""))
.arg(unicodeFraction(remainder, denominator));
}
}
}
return QString();
}
/*! \internal
Returns the unicode string representation of the fraction given by \a numerator and \a
denominator. This is the representation used in \ref fractionToString when the fraction style
(\ref setFractionStyle) is \ref fsUnicodeFractions.
This method doesn't use the single-character common fractions but builds each fraction from a
superscript unicode number, the unicode fraction character, and a subscript unicode number.
*/
QString QCPAxisTickerPi::unicodeFraction(int numerator, int denominator) const
{
return unicodeSuperscript(numerator)+QChar(0x2044)+unicodeSubscript(denominator);
}
/*! \internal
Returns the unicode string representing \a number as superscript. This is used to build
unicode fractions in \ref unicodeFraction.
*/
QString QCPAxisTickerPi::unicodeSuperscript(int number) const
{
if (number == 0)
return QString(QChar(0x2070));
QString result;
while (number > 0)
{
const int digit = number%10;
switch (digit)
{
case 1: { result.prepend(QChar(0x00B9)); break; }
case 2: { result.prepend(QChar(0x00B2)); break; }
case 3: { result.prepend(QChar(0x00B3)); break; }
default: { result.prepend(QChar(0x2070+digit)); break; }
}
number /= 10;
}
return result;
}
/*! \internal
Returns the unicode string representing \a number as subscript. This is used to build unicode
fractions in \ref unicodeFraction.
*/
QString QCPAxisTickerPi::unicodeSubscript(int number) const
{
if (number == 0)
return QString(QChar(0x2080));
QString result;
while (number > 0)
{
result.prepend(QChar(0x2080+number%10));
number /= 10;
}
return result;
}
/* end of 'src/axis/axistickerpi.cpp' */
/* including file 'src/axis/axistickerlog.cpp' */
/* modified 2022-11-06T12:45:56, size 7890 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxisTickerLog
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxisTickerLog
\brief Specialized axis ticker suited for logarithmic axes
\image html axisticker-log.png
This QCPAxisTicker subclass generates ticks with unequal tick intervals suited for logarithmic
axis scales. The ticks are placed at powers of the specified log base (\ref setLogBase).
Especially in the case of a log base equal to 10 (the default), it might be desirable to have
tick labels in the form of powers of ten without mantissa display. To achieve this, set the
number precision (\ref QCPAxis::setNumberPrecision) to zero and the number format (\ref
QCPAxis::setNumberFormat) to scientific (exponential) display with beautifully typeset decimal
powers, so a format string of <tt>"eb"</tt>. This will result in the following axis tick labels:
\image html axisticker-log-powers.png
The ticker can be created and assigned to an axis like this:
\snippet documentation/doc-image-generator/mainwindow.cpp axistickerlog-creation
Note that the nature of logarithmic ticks imply that there exists a smallest possible tick step,
corresponding to one multiplication by the log base. If the user zooms in further than that, no
new ticks would appear, leading to very sparse or even no axis ticks on the axis. To prevent this
situation, this ticker falls back to regular tick generation if the axis range would be covered
by too few logarithmically placed ticks.
*/
/*!
Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
*/
QCPAxisTickerLog::QCPAxisTickerLog() :
mLogBase(10.0),
mSubTickCount(8), // generates 10 intervals
mLogBaseLnInv(1.0/qLn(mLogBase))
{
}
/*!
Sets the logarithm base used for tick coordinate generation. The ticks will be placed at integer
powers of \a base.
*/
void QCPAxisTickerLog::setLogBase(double base)
{
if (base > 0)
{
mLogBase = base;
mLogBaseLnInv = 1.0/qLn(mLogBase);
} else
qDebug() << Q_FUNC_INFO << "log base has to be greater than zero:" << base;
}
/*!
Sets the number of sub ticks in a tick interval. Within each interval, the sub ticks are spaced
linearly to provide a better visual guide, so the sub tick density increases toward the higher
tick.
Note that \a subTicks is the number of sub ticks (not sub intervals) in one tick interval. So in
the case of logarithm base 10 an intuitive sub tick spacing would be achieved with eight sub
ticks (the default). This means e.g. between the ticks 10 and 100 there will be eight ticks,
namely at 20, 30, 40, 50, 60, 70, 80 and 90.
*/
void QCPAxisTickerLog::setSubTickCount(int subTicks)
{
if (subTicks >= 0)
mSubTickCount = subTicks;
else
qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
}
/*! \internal
Returns the sub tick count specified in \ref setSubTickCount. For QCPAxisTickerLog, there is no
automatic sub tick count calculation necessary.
\seebaseclassmethod
*/
int QCPAxisTickerLog::getSubTickCount(double tickStep)
{
Q_UNUSED(tickStep)
return mSubTickCount;
}
/*! \internal
Creates ticks with a spacing given by the logarithm base and an increasing integer power in the
provided \a range. The step in which the power increases tick by tick is chosen in order to keep
the total number of ticks as close as possible to the tick count (\ref setTickCount).
The parameter \a tickStep is ignored for the normal logarithmic ticker generation. Only when
zoomed in very far such that not enough logarithmically placed ticks would be visible, this
function falls back to the regular QCPAxisTicker::createTickVector, which then uses \a tickStep.
\seebaseclassmethod
*/
QVector<double> QCPAxisTickerLog::createTickVector(double tickStep, const QCPRange &range)
{
QVector<double> result;
if (range.lower > 0 && range.upper > 0) // positive range
{
const double baseTickCount = qLn(range.upper/range.lower)*mLogBaseLnInv;
if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation
return QCPAxisTicker::createTickVector(tickStep, range);
const double exactPowerStep = baseTickCount/double(mTickCount+1e-10);
const double newLogBase = qPow(mLogBase, qMax(int(cleanMantissa(exactPowerStep)), 1));
double currentTick = qPow(newLogBase, qFloor(qLn(range.lower)/qLn(newLogBase)));
result.append(currentTick);
while (currentTick < range.upper && currentTick > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
{
currentTick *= newLogBase;
result.append(currentTick);
}
} else if (range.lower < 0 && range.upper < 0) // negative range
{
const double baseTickCount = qLn(range.lower/range.upper)*mLogBaseLnInv;
if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation
return QCPAxisTicker::createTickVector(tickStep, range);
const double exactPowerStep = baseTickCount/double(mTickCount+1e-10);
const double newLogBase = qPow(mLogBase, qMax(int(cleanMantissa(exactPowerStep)), 1));
double currentTick = -qPow(newLogBase, qCeil(qLn(-range.lower)/qLn(newLogBase)));
result.append(currentTick);
while (currentTick < range.upper && currentTick < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
{
currentTick /= newLogBase;
result.append(currentTick);
}
} else // invalid range for logarithmic scale, because lower and upper have different sign
{
qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << range.lower << ".." << range.upper;
}
return result;
}
/* end of 'src/axis/axistickerlog.cpp' */
/* including file 'src/axis/axis.cpp' */
/* modified 2022-11-06T12:45:56, size 99911 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPGrid
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPGrid
\brief Responsible for drawing the grid of a QCPAxis.
This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the
grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref
QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself.
The axis and grid drawing was split into two classes to allow them to be placed on different
layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid
in the background and the axes in the foreground, and any plottables/items in between. This
described situation is the default setup, see the QCPLayer documentation.
*/
/*!
Creates a QCPGrid instance and sets default values.
You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid.
*/
QCPGrid::QCPGrid(QCPAxis *parentAxis) :
QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
mSubGridVisible{},
mAntialiasedSubGrid{},
mAntialiasedZeroLine{},
mParentAxis(parentAxis)
{
// warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called
setParent(parentAxis);
setPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
setSubGridVisible(false);
setAntialiased(false);
setAntialiasedSubGrid(false);
setAntialiasedZeroLine(false);
}
/*!
Sets whether grid lines at sub tick marks are drawn.
\see setSubGridPen
*/
void QCPGrid::setSubGridVisible(bool visible)
{
mSubGridVisible = visible;
}
/*!
Sets whether sub grid lines are drawn antialiased.
*/
void QCPGrid::setAntialiasedSubGrid(bool enabled)
{
mAntialiasedSubGrid = enabled;
}
/*!
Sets whether zero lines are drawn antialiased.
*/
void QCPGrid::setAntialiasedZeroLine(bool enabled)
{
mAntialiasedZeroLine = enabled;
}
/*!
Sets the pen with which (major) grid lines are drawn.
*/
void QCPGrid::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen with which sub grid lines are drawn.
*/
void QCPGrid::setSubGridPen(const QPen &pen)
{
mSubGridPen = pen;
}
/*!
Sets the pen with which zero lines are drawn.
Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid
lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen.
*/
void QCPGrid::setZeroLinePen(const QPen &pen)
{
mZeroLinePen = pen;
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing the major grid lines.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased
*/
void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
}
/*! \internal
Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
*/
void QCPGrid::draw(QCPPainter *painter)
{
if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
if (mParentAxis->subTicks() && mSubGridVisible)
drawSubGridLines(painter);
drawGridLines(painter);
}
/*! \internal
Draws the main grid lines and possibly a zero line with the specified painter.
This is a helper function called by \ref draw.
*/
void QCPGrid::drawGridLines(QCPPainter *painter) const
{
if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
const int tickCount = static_cast<int>(mParentAxis->mTickVector.size());
double t; // helper variable, result of coordinate-to-pixel transforms
if (mParentAxis->orientation() == Qt::Horizontal)
{
// draw zeroline:
int zeroLineIndex = -1;
if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
{
applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
painter->setPen(mZeroLinePen);
double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero
for (int i=0; i<tickCount; ++i)
{
if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
{
zeroLineIndex = i;
t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
break;
}
}
}
// draw grid lines:
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
for (int i=0; i<tickCount; ++i)
{
if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
}
} else
{
// draw zeroline:
int zeroLineIndex = -1;
if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
{
applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
painter->setPen(mZeroLinePen);
double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero
for (int i=0; i<tickCount; ++i)
{
if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
{
zeroLineIndex = i;
t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
break;
}
}
}
// draw grid lines:
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
for (int i=0; i<tickCount; ++i)
{
if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
}
}
}
/*! \internal
Draws the sub grid lines with the specified painter.
This is a helper function called by \ref draw.
*/
void QCPGrid::drawSubGridLines(QCPPainter *painter) const
{
if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid);
double t; // helper variable, result of coordinate-to-pixel transforms
painter->setPen(mSubGridPen);
if (mParentAxis->orientation() == Qt::Horizontal)
{
foreach (double tickCoord, mParentAxis->mSubTickVector)
{
t = mParentAxis->coordToPixel(tickCoord); // x
painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
}
} else
{
foreach (double tickCoord, mParentAxis->mSubTickVector)
{
t = mParentAxis->coordToPixel(tickCoord); // y
painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxis
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxis
\brief Manages a single axis inside a QCustomPlot.
Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via
QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and
QCustomPlot::yAxis2 (right).
Axes are always part of an axis rect, see QCPAxisRect.
\image html AxisNamesOverview.png
<center>Naming convention of axis parts</center>
\n
\image html AxisRectSpacingOverview.png
<center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line
on the left represents the QCustomPlot widget border.</center>
Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
documentation of QCPAxisTicker.
*/
/* start of documentation of inline functions */
/*! \fn Qt::Orientation QCPAxis::orientation() const
Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced
from the axis type (left, top, right or bottom).
\see orientation(AxisType type), pixelOrientation
*/
/*! \fn QCPGrid *QCPAxis::grid() const
Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the
grid is displayed.
*/
/*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type)
Returns the orientation of the specified axis type
\see orientation(), pixelOrientation
*/
/*! \fn int QCPAxis::pixelOrientation() const
Returns which direction points towards higher coordinate values/keys, in pixel space.
This method returns either 1 or -1. If it returns 1, then going in the positive direction along
the orientation of the axis in pixels corresponds to going from lower to higher axis coordinates.
On the other hand, if this method returns -1, going to smaller pixel values corresponds to going
from lower to higher axis coordinates.
For example, this is useful to easily shift axis coordinates by a certain amount given in pixels,
without having to care about reversed or vertically aligned axes:
\code
double newKey = keyAxis->pixelToCoord(keyAxis->coordToPixel(oldKey)+10*keyAxis->pixelOrientation());
\endcode
\a newKey will then contain a key that is ten pixels towards higher keys, starting from \a oldKey.
*/
/*! \fn QSharedPointer<QCPAxisTicker> QCPAxis::ticker() const
Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
responsible for generating the tick positions and tick labels of this axis. You can access the
\ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
(\ref QCPAxisTicker::setTickCount).
You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
the documentation there. A new axis ticker can be set with \ref setTicker.
Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
ticker simply by passing the same shared pointer to multiple axes.
\see setTicker
*/
/* end of documentation of inline functions */
/* start of documentation of signals */
/*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange)
This signal is emitted when the range of this axis has changed. You can connect it to the \ref
setRange slot of another axis to communicate the new range to the other axis, in order for it to
be synchronized.
You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
slot would limit the x axis to ranges between 0 and 10:
\code
customPlot->xAxis->setRange(newRange.bounded(0, 10))
\endcode
*/
/*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
\overload
Additionally to the new range, this signal also provides the previous range held by the axis as
\a oldRange.
*/
/*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType);
This signal is emitted when the scale type changes, by calls to \ref setScaleType
*/
/*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection)
This signal is emitted when the selection state of this axis has changed, either by user interaction
or by a direct call to \ref setSelectedParts.
*/
/*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts);
This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
*/
/* end of documentation of signals */
/*!
Constructs an Axis instance of Type \a type for the axis rect \a parent.
Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
create them manually and then inject them also via \ref QCPAxisRect::addAxis.
*/
QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) :
QCPLayerable(parent->parentPlot(), QString(), parent),
// axis base:
mAxisType(type),
mAxisRect(parent),
mPadding(5),
mOrientation(orientation(type)),
mSelectableParts(spAxis | spTickLabels | spAxisLabel),
mSelectedParts(spNone),
mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedBasePen(QPen(Qt::blue, 2)),
// axis label:
mLabel(),
mLabelFont(mParentPlot->font()),
mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
mLabelColor(Qt::black),
mSelectedLabelColor(Qt::blue),
// tick labels:
mTickLabels(true),
mTickLabelFont(mParentPlot->font()),
mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
mTickLabelColor(Qt::black),
mSelectedTickLabelColor(Qt::blue),
mNumberPrecision(6),
mNumberFormatChar('g'),
mNumberBeautifulPowers(true),
// ticks and subticks:
mTicks(true),
mSubTicks(true),
mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedTickPen(QPen(Qt::blue, 2)),
mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedSubTickPen(QPen(Qt::blue, 2)),
// scale and range:
mRange(0, 5),
mRangeReversed(false),
mScaleType(stLinear),
// internal members:
mGrid(new QCPGrid(this)),
mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())),
mTicker(new QCPAxisTicker),
mCachedMarginValid(false),
mCachedMargin(0),
mDragging(false)
{
setParent(parent);
mGrid->setVisible(false);
setAntialiased(false);
setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again
if (type == atTop)
{
setTickLabelPadding(3);
setLabelPadding(6);
} else if (type == atRight)
{
setTickLabelPadding(7);
setLabelPadding(12);
} else if (type == atBottom)
{
setTickLabelPadding(3);
setLabelPadding(3);
} else if (type == atLeft)
{
setTickLabelPadding(5);
setLabelPadding(10);
}
}
QCPAxis::~QCPAxis()
{
delete mAxisPainter;
delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
}
/* No documentation as it is a property getter */
int QCPAxis::tickLabelPadding() const
{
return mAxisPainter->tickLabelPadding;
}
/* No documentation as it is a property getter */
double QCPAxis::tickLabelRotation() const
{
return mAxisPainter->tickLabelRotation;
}
/* No documentation as it is a property getter */
QCPAxis::LabelSide QCPAxis::tickLabelSide() const
{
return mAxisPainter->tickLabelSide;
}
/* No documentation as it is a property getter */
QString QCPAxis::numberFormat() const
{
QString result;
result.append(mNumberFormatChar);
if (mNumberBeautifulPowers)
{
result.append(QLatin1Char('b'));
if (mAxisPainter->numberMultiplyCross)
result.append(QLatin1Char('c'));
}
return result;
}
/* No documentation as it is a property getter */
int QCPAxis::tickLengthIn() const
{
return mAxisPainter->tickLengthIn;
}
/* No documentation as it is a property getter */
int QCPAxis::tickLengthOut() const
{
return mAxisPainter->tickLengthOut;
}
/* No documentation as it is a property getter */
int QCPAxis::subTickLengthIn() const
{
return mAxisPainter->subTickLengthIn;
}
/* No documentation as it is a property getter */
int QCPAxis::subTickLengthOut() const
{
return mAxisPainter->subTickLengthOut;
}
/* No documentation as it is a property getter */
int QCPAxis::labelPadding() const
{
return mAxisPainter->labelPadding;
}
/* No documentation as it is a property getter */
int QCPAxis::offset() const
{
return mAxisPainter->offset;
}
/* No documentation as it is a property getter */
QCPLineEnding QCPAxis::lowerEnding() const
{
return mAxisPainter->lowerEnding;
}
/* No documentation as it is a property getter */
QCPLineEnding QCPAxis::upperEnding() const
{
return mAxisPainter->upperEnding;
}
/*!
Sets whether the axis uses a linear scale or a logarithmic scale.
Note that this method controls the coordinate transformation. For logarithmic scales, you will
likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
the axis ticker to an instance of \ref QCPAxisTickerLog :
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation
See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
creation.
\ref setNumberPrecision
*/
void QCPAxis::setScaleType(QCPAxis::ScaleType type)
{
if (mScaleType != type)
{
mScaleType = type;
if (mScaleType == stLogarithmic)
setRange(mRange.sanitizedForLogScale());
mCachedMarginValid = false;
emit scaleTypeChanged(mScaleType);
}
}
/*!
Sets the range of the axis.
This slot may be connected with the \ref rangeChanged signal of another axis so this axis
is always synchronized with the other axis range, when it changes.
To invert the direction of an axis, use \ref setRangeReversed.
*/
void QCPAxis::setRange(const QCPRange &range)
{
if (range.lower == mRange.lower && range.upper == mRange.upper)
return;
if (!QCPRange::validRange(range)) return;
QCPRange oldRange = mRange;
if (mScaleType == stLogarithmic)
{
mRange = range.sanitizedForLogScale();
} else
{
mRange = range.sanitizedForLinScale();
}
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
(When \ref QCustomPlot::setInteractions contains iSelectAxes.)
However, even when \a selectable is set to a value not allowing the selection of a specific part,
it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
directly.
\see SelectablePart, setSelectedParts
*/
void QCPAxis::setSelectableParts(const SelectableParts &selectable)
{
if (mSelectableParts != selectable)
{
mSelectableParts = selectable;
emit selectableChanged(mSelectableParts);
}
}
/*!
Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
is selected, it uses a different pen/font.
The entire selection mechanism for axes is handled automatically when \ref
QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
wish to change the selection state manually.
This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
\see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
*/
void QCPAxis::setSelectedParts(const SelectableParts &selected)
{
if (mSelectedParts != selected)
{
mSelectedParts = selected;
emit selectionChanged(mSelectedParts);
}
}
/*!
\overload
Sets the lower and upper bound of the axis range.
To invert the direction of an axis, use \ref setRangeReversed.
There is also a slot to set a range, see \ref setRange(const QCPRange &range).
*/
void QCPAxis::setRange(double lower, double upper)
{
if (lower == mRange.lower && upper == mRange.upper)
return;
if (!QCPRange::validRange(lower, upper)) return;
QCPRange oldRange = mRange;
mRange.lower = lower;
mRange.upper = upper;
if (mScaleType == stLogarithmic)
{
mRange = mRange.sanitizedForLogScale();
} else
{
mRange = mRange.sanitizedForLinScale();
}
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
\overload
Sets the range of the axis.
The \a position coordinate indicates together with the \a alignment parameter, where the new
range will be positioned. \a size defines the size of the new axis range. \a alignment may be
Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
or center of the range to be aligned with \a position. Any other values of \a alignment will
default to Qt::AlignCenter.
*/
void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment)
{
if (alignment == Qt::AlignLeft)
setRange(position, position+size);
else if (alignment == Qt::AlignRight)
setRange(position-size, position);
else // alignment == Qt::AlignCenter
setRange(position-size/2.0, position+size/2.0);
}
/*!
Sets the lower bound of the axis range. The upper bound is not changed.
\see setRange
*/
void QCPAxis::setRangeLower(double lower)
{
if (mRange.lower == lower)
return;
QCPRange oldRange = mRange;
mRange.lower = lower;
if (mScaleType == stLogarithmic)
{
mRange = mRange.sanitizedForLogScale();
} else
{
mRange = mRange.sanitizedForLinScale();
}
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets the upper bound of the axis range. The lower bound is not changed.
\see setRange
*/
void QCPAxis::setRangeUpper(double upper)
{
if (mRange.upper == upper)
return;
QCPRange oldRange = mRange;
mRange.upper = upper;
if (mScaleType == stLogarithmic)
{
mRange = mRange.sanitizedForLogScale();
} else
{
mRange = mRange.sanitizedForLinScale();
}
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
direction of increasing values is inverted.
Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
of the \ref setRange interface will still reference the mathematically smaller number than the \a
upper part.
*/
void QCPAxis::setRangeReversed(bool reversed)
{
mRangeReversed = reversed;
}
/*!
The axis ticker is responsible for generating the tick positions and tick labels. See the
documentation of QCPAxisTicker for details on how to work with axis tickers.
You can change the tick positioning/labeling behaviour of this axis by setting a different
QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
ticker, access it via \ref ticker.
Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
ticker simply by passing the same shared pointer to multiple axes.
\see ticker
*/
void QCPAxis::setTicker(QSharedPointer<QCPAxisTicker> ticker)
{
if (ticker)
mTicker = ticker;
else
qDebug() << Q_FUNC_INFO << "can not set nullptr as axis ticker";
// no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
}
/*!
Sets whether tick marks are displayed.
Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
that, see \ref setTickLabels.
\see setSubTicks
*/
void QCPAxis::setTicks(bool show)
{
if (mTicks != show)
{
mTicks = show;
mCachedMarginValid = false;
}
}
/*!
Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
*/
void QCPAxis::setTickLabels(bool show)
{
if (mTickLabels != show)
{
mTickLabels = show;
mCachedMarginValid = false;
if (!mTickLabels)
mTickVectorLabels.clear();
}
}
/*!
Sets the distance between the axis base line (including any outward ticks) and the tick labels.
\see setLabelPadding, setPadding
*/
void QCPAxis::setTickLabelPadding(int padding)
{
if (mAxisPainter->tickLabelPadding != padding)
{
mAxisPainter->tickLabelPadding = padding;
mCachedMarginValid = false;
}
}
/*!
Sets the font of the tick labels.
\see setTickLabels, setTickLabelColor
*/
void QCPAxis::setTickLabelFont(const QFont &font)
{
if (font != mTickLabelFont)
{
mTickLabelFont = font;
mCachedMarginValid = false;
}
}
/*!
Sets the color of the tick labels.
\see setTickLabels, setTickLabelFont
*/
void QCPAxis::setTickLabelColor(const QColor &color)
{
mTickLabelColor = color;
}
/*!
Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
from -90 to 90 degrees.
If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
other angles, the label is drawn with an offset such that it seems to point toward or away from
the tick mark.
*/
void QCPAxis::setTickLabelRotation(double degrees)
{
if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation))
{
mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0);
mCachedMarginValid = false;
}
}
/*!
Sets whether the tick labels (numbers) shall appear inside or outside the axis rect.
The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels
to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels
appear on the inside are additionally clipped to the axis rect.
*/
void QCPAxis::setTickLabelSide(LabelSide side)
{
mAxisPainter->tickLabelSide = side;
mCachedMarginValid = false;
}
/*!
Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
that, see the "Argument Formats" section in the detailed description of the QString class.
\a formatCode is a string of one, two or three characters.
<b>The first character</b> is identical to
the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
format, 'g'/'G' scientific or fixed, whichever is shorter. For the 'e', 'E', and 'f' formats,
the precision set by \ref setNumberPrecision represents the number of digits after the decimal
point. For the 'g' and 'G' formats, the precision represents the maximum number of significant
digits, trailing zeroes are omitted.
<b>The second and third characters</b> are optional and specific to QCustomPlot:\n
If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
"5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
"beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
[multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
cross and 183 (0xB7) for the dot.
Examples for \a formatCode:
\li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
normal scientific format is used
\li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
beautifully typeset decimal powers and a dot as multiplication sign
\li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
multiplication sign
\li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
powers. Format code will be reduced to 'f'.
\li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
code will not be changed.
*/
void QCPAxis::setNumberFormat(const QString &formatCode)
{
if (formatCode.isEmpty())
{
qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
return;
}
mCachedMarginValid = false;
// interpret first char as number format char:
QString allowedFormatChars(QLatin1String("eEfgG"));
if (allowedFormatChars.contains(formatCode.at(0)))
{
mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
} else
{
qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
return;
}
if (formatCode.length() < 2)
{
mNumberBeautifulPowers = false;
mAxisPainter->numberMultiplyCross = false;
return;
}
// interpret second char as indicator for beautiful decimal powers:
if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
{
mNumberBeautifulPowers = true;
} else
{
qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
return;
}
if (formatCode.length() < 3)
{
mAxisPainter->numberMultiplyCross = false;
return;
}
// interpret third char as indicator for dot or cross multiplication symbol:
if (formatCode.at(2) == QLatin1Char('c'))
{
mAxisPainter->numberMultiplyCross = true;
} else if (formatCode.at(2) == QLatin1Char('d'))
{
mAxisPainter->numberMultiplyCross = false;
} else
{
qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
return;
}
}
/*!
Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
for details. The effect of precisions are most notably for number Formats starting with 'e', see
\ref setNumberFormat
*/
void QCPAxis::setNumberPrecision(int precision)
{
if (mNumberPrecision != precision)
{
mNumberPrecision = precision;
mCachedMarginValid = false;
}
}
/*!
Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
zero, the tick labels and axis label will increase their distance to the axis accordingly, so
they won't collide with the ticks.
\see setSubTickLength, setTickLengthIn, setTickLengthOut
*/
void QCPAxis::setTickLength(int inside, int outside)
{
setTickLengthIn(inside);
setTickLengthOut(outside);
}
/*!
Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
inside the plot.
\see setTickLengthOut, setTickLength, setSubTickLength
*/
void QCPAxis::setTickLengthIn(int inside)
{
if (mAxisPainter->tickLengthIn != inside)
{
mAxisPainter->tickLengthIn = inside;
}
}
/*!
Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
outside the plot. If \a outside is greater than zero, the tick labels and axis label will
increase their distance to the axis accordingly, so they won't collide with the ticks.
\see setTickLengthIn, setTickLength, setSubTickLength
*/
void QCPAxis::setTickLengthOut(int outside)
{
if (mAxisPainter->tickLengthOut != outside)
{
mAxisPainter->tickLengthOut = outside;
mCachedMarginValid = false; // only outside tick length can change margin
}
}
/*!
Sets whether sub tick marks are displayed.
Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
\see setTicks
*/
void QCPAxis::setSubTicks(bool show)
{
if (mSubTicks != show)
{
mSubTicks = show;
mCachedMarginValid = false;
}
}
/*!
Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
than zero, the tick labels and axis label will increase their distance to the axis accordingly,
so they won't collide with the ticks.
\see setTickLength, setSubTickLengthIn, setSubTickLengthOut
*/
void QCPAxis::setSubTickLength(int inside, int outside)
{
setSubTickLengthIn(inside);
setSubTickLengthOut(outside);
}
/*!
Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
the plot.
\see setSubTickLengthOut, setSubTickLength, setTickLength
*/
void QCPAxis::setSubTickLengthIn(int inside)
{
if (mAxisPainter->subTickLengthIn != inside)
{
mAxisPainter->subTickLengthIn = inside;
}
}
/*!
Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
outside the plot. If \a outside is greater than zero, the tick labels will increase their
distance to the axis accordingly, so they won't collide with the ticks.
\see setSubTickLengthIn, setSubTickLength, setTickLength
*/
void QCPAxis::setSubTickLengthOut(int outside)
{
if (mAxisPainter->subTickLengthOut != outside)
{
mAxisPainter->subTickLengthOut = outside;
mCachedMarginValid = false; // only outside tick length can change margin
}
}
/*!
Sets the pen, the axis base line is drawn with.
\see setTickPen, setSubTickPen
*/
void QCPAxis::setBasePen(const QPen &pen)
{
mBasePen = pen;
}
/*!
Sets the pen, tick marks will be drawn with.
\see setTickLength, setBasePen
*/
void QCPAxis::setTickPen(const QPen &pen)
{
mTickPen = pen;
}
/*!
Sets the pen, subtick marks will be drawn with.
\see setSubTickCount, setSubTickLength, setBasePen
*/
void QCPAxis::setSubTickPen(const QPen &pen)
{
mSubTickPen = pen;
}
/*!
Sets the font of the axis label.
\see setLabelColor
*/
void QCPAxis::setLabelFont(const QFont &font)
{
if (mLabelFont != font)
{
mLabelFont = font;
mCachedMarginValid = false;
}
}
/*!
Sets the color of the axis label.
\see setLabelFont
*/
void QCPAxis::setLabelColor(const QColor &color)
{
mLabelColor = color;
}
/*!
Sets the text of the axis label that will be shown below/above or next to the axis, depending on
its orientation. To disable axis labels, pass an empty string as \a str.
*/
void QCPAxis::setLabel(const QString &str)
{
if (mLabel != str)
{
mLabel = str;
mCachedMarginValid = false;
}
}
/*!
Sets the distance between the tick labels and the axis label.
\see setTickLabelPadding, setPadding
*/
void QCPAxis::setLabelPadding(int padding)
{
if (mAxisPainter->labelPadding != padding)
{
mAxisPainter->labelPadding = padding;
mCachedMarginValid = false;
}
}
/*!
Sets the padding of the axis.
When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space,
that is left blank.
The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled.
\see setLabelPadding, setTickLabelPadding
*/
void QCPAxis::setPadding(int padding)
{
if (mPadding != padding)
{
mPadding = padding;
mCachedMarginValid = false;
}
}
/*!
Sets the offset the axis has to its axis rect side.
If an axis rect side has multiple axes and automatic margin calculation is enabled for that side,
only the offset of the inner most axis has meaning (even if it is set to be invisible). The
offset of the other, outer axes is controlled automatically, to place them at appropriate
positions.
*/
void QCPAxis::setOffset(int offset)
{
mAxisPainter->offset = offset;
}
/*!
Sets the font that is used for tick labels when they are selected.
\see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedTickLabelFont(const QFont &font)
{
if (font != mSelectedTickLabelFont)
{
mSelectedTickLabelFont = font;
// don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
}
}
/*!
Sets the font that is used for the axis label when it is selected.
\see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedLabelFont(const QFont &font)
{
mSelectedLabelFont = font;
// don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
}
/*!
Sets the color that is used for tick labels when they are selected.
\see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedTickLabelColor(const QColor &color)
{
if (color != mSelectedTickLabelColor)
{
mSelectedTickLabelColor = color;
}
}
/*!
Sets the color that is used for the axis label when it is selected.
\see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedLabelColor(const QColor &color)
{
mSelectedLabelColor = color;
}
/*!
Sets the pen that is used to draw the axis base line when selected.
\see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedBasePen(const QPen &pen)
{
mSelectedBasePen = pen;
}
/*!
Sets the pen that is used to draw the (major) ticks when selected.
\see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedTickPen(const QPen &pen)
{
mSelectedTickPen = pen;
}
/*!
Sets the pen that is used to draw the subticks when selected.
\see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedSubTickPen(const QPen &pen)
{
mSelectedSubTickPen = pen;
}
/*!
Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available
styles.
For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending.
Note that this meaning does not change when the axis range is reversed with \ref
setRangeReversed.
\see setUpperEnding
*/
void QCPAxis::setLowerEnding(const QCPLineEnding &ending)
{
mAxisPainter->lowerEnding = ending;
}
/*!
Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available
styles.
For horizontal axes, this method refers to the right ending, for vertical axes the top ending.
Note that this meaning does not change when the axis range is reversed with \ref
setRangeReversed.
\see setLowerEnding
*/
void QCPAxis::setUpperEnding(const QCPLineEnding &ending)
{
mAxisPainter->upperEnding = ending;
}
/*!
If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
bounds of the range. The range is simply moved by \a diff.
If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
*/
void QCPAxis::moveRange(double diff)
{
QCPRange oldRange = mRange;
if (mScaleType == stLinear)
{
mRange.lower += diff;
mRange.upper += diff;
} else // mScaleType == stLogarithmic
{
mRange.lower *= diff;
mRange.upper *= diff;
}
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Scales the range of this axis by \a factor around the center of the current axis range. For
example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
the center will have moved symmetrically closer).
If you wish to scale around a different coordinate than the current axis range center, use the
overload \ref scaleRange(double factor, double center).
*/
void QCPAxis::scaleRange(double factor)
{
scaleRange(factor, range().center());
}
/*! \overload
Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
around 1.0 will have moved symmetrically closer to 1.0).
\see scaleRange(double factor)
*/
void QCPAxis::scaleRange(double factor, double center)
{
QCPRange oldRange = mRange;
if (mScaleType == stLinear)
{
QCPRange newRange;
newRange.lower = (mRange.lower-center)*factor + center;
newRange.upper = (mRange.upper-center)*factor + center;
if (QCPRange::validRange(newRange))
mRange = newRange.sanitizedForLinScale();
} else // mScaleType == stLogarithmic
{
if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
{
QCPRange newRange;
newRange.lower = qPow(mRange.lower/center, factor)*center;
newRange.upper = qPow(mRange.upper/center, factor)*center;
if (QCPRange::validRange(newRange))
mRange = newRange.sanitizedForLogScale();
} else
qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
}
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will
be done around the center of the current axis range.
For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs
plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the
axis rect has.
This is an operation that changes the range of this axis once, it doesn't fix the scale ratio
indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent
won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent
will follow.
*/
void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio)
{
int otherPixelSize, ownPixelSize;
if (otherAxis->orientation() == Qt::Horizontal)
otherPixelSize = otherAxis->axisRect()->width();
else
otherPixelSize = otherAxis->axisRect()->height();
if (orientation() == Qt::Horizontal)
ownPixelSize = axisRect()->width();
else
ownPixelSize = axisRect()->height();
double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/double(otherPixelSize);
setRange(range().center(), newRangeSize, Qt::AlignCenter);
}
/*!
Changes the axis range such that all plottables associated with this axis are fully visible in
that dimension.
\see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
*/
void QCPAxis::rescale(bool onlyVisiblePlottables)
{
QCPRange newRange;
bool haveRange = false;
foreach (QCPAbstractPlottable *plottable, plottables())
{
if (!plottable->realVisibility() && onlyVisiblePlottables)
continue;
QCPRange plottableRange;
bool currentFoundRange;
QCP::SignDomain signDomain = QCP::sdBoth;
if (mScaleType == stLogarithmic)
signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
if (plottable->keyAxis() == this)
plottableRange = plottable->getKeyRange(currentFoundRange, signDomain);
else
plottableRange = plottable->getValueRange(currentFoundRange, signDomain);
if (currentFoundRange)
{
if (!haveRange)
newRange = plottableRange;
else
newRange.expand(plottableRange);
haveRange = true;
}
}
if (haveRange)
{
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
if (mScaleType == stLinear)
{
newRange.lower = center-mRange.size()/2.0;
newRange.upper = center+mRange.size()/2.0;
} else // mScaleType == stLogarithmic
{
newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
}
}
setRange(newRange);
}
}
/*!
Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
*/
double QCPAxis::pixelToCoord(double value) const
{
if (orientation() == Qt::Horizontal)
{
if (mScaleType == stLinear)
{
if (!mRangeReversed)
return (value-mAxisRect->left())/double(mAxisRect->width())*mRange.size()+mRange.lower;
else
return -(value-mAxisRect->left())/double(mAxisRect->width())*mRange.size()+mRange.upper;
} else // mScaleType == stLogarithmic
{
if (!mRangeReversed)
return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/double(mAxisRect->width()))*mRange.lower;
else
return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/double(mAxisRect->width()))*mRange.upper;
}
} else // orientation() == Qt::Vertical
{
if (mScaleType == stLinear)
{
if (!mRangeReversed)
return (mAxisRect->bottom()-value)/double(mAxisRect->height())*mRange.size()+mRange.lower;
else
return -(mAxisRect->bottom()-value)/double(mAxisRect->height())*mRange.size()+mRange.upper;
} else // mScaleType == stLogarithmic
{
if (!mRangeReversed)
return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/double(mAxisRect->height()))*mRange.lower;
else
return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/double(mAxisRect->height()))*mRange.upper;
}
}
}
/*!
Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
*/
double QCPAxis::coordToPixel(double value) const
{
if (orientation() == Qt::Horizontal)
{
if (mScaleType == stLinear)
{
if (!mRangeReversed)
return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left();
else
return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left();
} else // mScaleType == stLogarithmic
{
if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range
return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200;
else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range
return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200;
else
{
if (!mRangeReversed)
return qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
else
return qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
}
}
} else // orientation() == Qt::Vertical
{
if (mScaleType == stLinear)
{
if (!mRangeReversed)
return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height();
else
return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height();
} else // mScaleType == stLogarithmic
{
if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range
return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200;
else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range
return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200;
else
{
if (!mRangeReversed)
return mAxisRect->bottom()-qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
else
return mAxisRect->bottom()-qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
}
}
}
}
/*!
Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
function does not change the current selection state of the axis.
If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
\see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
*/
QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const
{
if (!mVisible)
return spNone;
if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
return spAxis;
else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
return spTickLabels;
else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
return spAxisLabel;
else
return spNone;
}
/* inherits documentation from base class */
double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
if (!mParentPlot) return -1;
SelectablePart part = getPartAt(pos);
if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
return -1;
if (details)
details->setValue(part);
return mParentPlot->selectionTolerance()*0.99;
}
/*!
Returns a list of all the plottables that have this axis as key or value axis.
If you are only interested in plottables of type QCPGraph, see \ref graphs.
\see graphs, items
*/
QList<QCPAbstractPlottable*> QCPAxis::plottables() const
{
QList<QCPAbstractPlottable*> result;
if (!mParentPlot) return result;
foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables)
{
if (plottable->keyAxis() == this || plottable->valueAxis() == this)
result.append(plottable);
}
return result;
}
/*!
Returns a list of all the graphs that have this axis as key or value axis.
\see plottables, items
*/
QList<QCPGraph*> QCPAxis::graphs() const
{
QList<QCPGraph*> result;
if (!mParentPlot) return result;
foreach (QCPGraph *graph, mParentPlot->mGraphs)
{
if (graph->keyAxis() == this || graph->valueAxis() == this)
result.append(graph);
}
return result;
}
/*!
Returns a list of all the items that are associated with this axis. An item is considered
associated with an axis if at least one of its positions uses the axis as key or value axis.
\see plottables, graphs
*/
QList<QCPAbstractItem*> QCPAxis::items() const
{
QList<QCPAbstractItem*> result;
if (!mParentPlot) return result;
foreach (QCPAbstractItem *item, mParentPlot->mItems)
{
foreach (QCPItemPosition *position, item->positions())
{
if (position->keyAxis() == this || position->valueAxis() == this)
{
result.append(item);
break;
}
}
}
return result;
}
/*!
Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to
QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.)
*/
QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side)
{
switch (side)
{
case QCP::msLeft: return atLeft;
case QCP::msRight: return atRight;
case QCP::msTop: return atTop;
case QCP::msBottom: return atBottom;
default: break;
}
qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << static_cast<int>(side);
return atLeft;
}
/*!
Returns the axis type that describes the opposite axis of an axis with the specified \a type.
*/
QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type)
{
switch (type)
{
case atLeft: return atRight;
case atRight: return atLeft;
case atBottom: return atTop;
case atTop: return atBottom;
}
qDebug() << Q_FUNC_INFO << "invalid axis type";
return atLeft;
}
/* inherits documentation from base class */
void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
SelectablePart part = details.value<SelectablePart>();
if (mSelectableParts.testFlag(part))
{
SelectableParts selBefore = mSelectedParts;
setSelectedParts(additive ? mSelectedParts^part : part);
if (selectionStateChanged)
*selectionStateChanged = mSelectedParts != selBefore;
}
}
/* inherits documentation from base class */
void QCPAxis::deselectEvent(bool *selectionStateChanged)
{
SelectableParts selBefore = mSelectedParts;
setSelectedParts(mSelectedParts & ~mSelectableParts);
if (selectionStateChanged)
*selectionStateChanged = mSelectedParts != selBefore;
}
/*! \internal
This mouse event reimplementation provides the functionality to let the user drag individual axes
exclusively, by startig the drag on top of the axis.
For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect
must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis
(\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref
QCPAxisRect::setRangeDragAxes)
\seebaseclassmethod
\note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
*/
void QCPAxis::mousePressEvent(QMouseEvent *event, const QVariant &details)
{
Q_UNUSED(details)
if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag) ||
!mAxisRect->rangeDrag().testFlag(orientation()) ||
!mAxisRect->rangeDragAxes(orientation()).contains(this))
{
event->ignore();
return;
}
if (event->buttons() & Qt::LeftButton)
{
mDragging = true;
// initialize antialiasing backup in case we start dragging:
if (mParentPlot->noAntialiasingOnDrag())
{
mAADragBackup = mParentPlot->antialiasedElements();
mNotAADragBackup = mParentPlot->notAntialiasedElements();
}
// Mouse range dragging interaction:
if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
mDragStartRange = mRange;
}
}
/*! \internal
This mouse event reimplementation provides the functionality to let the user drag individual axes
exclusively, by startig the drag on top of the axis.
\seebaseclassmethod
\note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
\see QCPAxis::mousePressEvent
*/
void QCPAxis::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
{
if (mDragging)
{
const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y();
const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y();
if (mScaleType == QCPAxis::stLinear)
{
const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel);
setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff);
} else if (mScaleType == QCPAxis::stLogarithmic)
{
const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel);
setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff);
}
if (mParentPlot->noAntialiasingOnDrag())
mParentPlot->setNotAntialiasedElements(QCP::aeAll);
mParentPlot->replot(QCustomPlot::rpQueuedReplot);
}
}
/*! \internal
This mouse event reimplementation provides the functionality to let the user drag individual axes
exclusively, by startig the drag on top of the axis.
\seebaseclassmethod
\note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
\see QCPAxis::mousePressEvent
*/
void QCPAxis::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
{
Q_UNUSED(event)
Q_UNUSED(startPos)
mDragging = false;
if (mParentPlot->noAntialiasingOnDrag())
{
mParentPlot->setAntialiasedElements(mAADragBackup);
mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
}
}
/*! \internal
This mouse event reimplementation provides the functionality to let the user zoom individual axes
exclusively, by performing the wheel event on top of the axis.
For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect
must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis
(\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref
QCPAxisRect::setRangeZoomAxes)
\seebaseclassmethod
\note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the
axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent.
*/
void QCPAxis::wheelEvent(QWheelEvent *event)
{
// Mouse range zooming interaction:
if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom) ||
!mAxisRect->rangeZoom().testFlag(orientation()) ||
!mAxisRect->rangeZoomAxes(orientation()).contains(this))
{
event->ignore();
return;
}
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
const double delta = event->delta();
#else
const double delta = event->angleDelta().y();
#endif
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
const QPointF pos = event->pos();
#else
const QPointF pos = event->position();
#endif
const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
const double factor = qPow(mAxisRect->rangeZoomFactor(orientation()), wheelSteps);
scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? pos.x() : pos.y()));
mParentPlot->replot();
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing axis lines.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\seebaseclassmethod
\see setAntialiased
*/
void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
}
/*! \internal
Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
\seebaseclassmethod
*/
void QCPAxis::draw(QCPPainter *painter)
{
QVector<double> subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
tickPositions.reserve(mTickVector.size());
tickLabels.reserve(mTickVector.size());
subTickPositions.reserve(mSubTickVector.size());
if (mTicks)
{
for (int i=0; i<mTickVector.size(); ++i)
{
tickPositions.append(coordToPixel(mTickVector.at(i)));
if (mTickLabels)
tickLabels.append(mTickVectorLabels.at(i));
}
if (mSubTicks)
{
const int subTickCount = static_cast<int>(mSubTickVector.size());
for (int i=0; i<subTickCount; ++i)
subTickPositions.append(coordToPixel(mSubTickVector.at(i)));
}
}
// transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis.
// Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
mAxisPainter->type = mAxisType;
mAxisPainter->basePen = getBasePen();
mAxisPainter->labelFont = getLabelFont();
mAxisPainter->labelColor = getLabelColor();
mAxisPainter->label = mLabel;
mAxisPainter->substituteExponent = mNumberBeautifulPowers;
mAxisPainter->tickPen = getTickPen();
mAxisPainter->subTickPen = getSubTickPen();
mAxisPainter->tickLabelFont = getTickLabelFont();
mAxisPainter->tickLabelColor = getTickLabelColor();
mAxisPainter->axisRect = mAxisRect->rect();
mAxisPainter->viewportRect = mParentPlot->viewport();
mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic;
mAxisPainter->reversedEndings = mRangeReversed;
mAxisPainter->tickPositions = tickPositions;
mAxisPainter->tickLabels = tickLabels;
mAxisPainter->subTickPositions = subTickPositions;
mAxisPainter->draw(painter);
}
/*! \internal
Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
QCPAxisTicker::generate on the currently installed ticker.
If a change in the label text/count is detected, the cached axis margin is invalidated to make
sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
*/
void QCPAxis::setupTickVectors()
{
if (!mParentPlot) return;
if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
QVector<QString> oldLabels = mTickVectorLabels;
mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : nullptr, mTickLabels ? &mTickVectorLabels : nullptr);
mCachedMarginValid &= mTickVectorLabels == oldLabels; // if labels have changed, margin might have changed, too
}
/*! \internal
Returns the pen that is used to draw the axis base line. Depending on the selection state, this
is either mSelectedBasePen or mBasePen.
*/
QPen QCPAxis::getBasePen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
}
/*! \internal
Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
is either mSelectedTickPen or mTickPen.
*/
QPen QCPAxis::getTickPen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
}
/*! \internal
Returns the pen that is used to draw the subticks. Depending on the selection state, this
is either mSelectedSubTickPen or mSubTickPen.
*/
QPen QCPAxis::getSubTickPen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
}
/*! \internal
Returns the font that is used to draw the tick labels. Depending on the selection state, this
is either mSelectedTickLabelFont or mTickLabelFont.
*/
QFont QCPAxis::getTickLabelFont() const
{
return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
}
/*! \internal
Returns the font that is used to draw the axis label. Depending on the selection state, this
is either mSelectedLabelFont or mLabelFont.
*/
QFont QCPAxis::getLabelFont() const
{
return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
}
/*! \internal
Returns the color that is used to draw the tick labels. Depending on the selection state, this
is either mSelectedTickLabelColor or mTickLabelColor.
*/
QColor QCPAxis::getTickLabelColor() const
{
return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
}
/*! \internal
Returns the color that is used to draw the axis label. Depending on the selection state, this
is either mSelectedLabelColor or mLabelColor.
*/
QColor QCPAxis::getLabelColor() const
{
return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
}
/*! \internal
Returns the appropriate outward margin for this axis. It is needed if \ref
QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref
atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom
margin and so forth. For the calculation, this function goes through similar steps as \ref draw,
so changing one function likely requires the modification of the other one as well.
The margin consists of the outward tick length, tick label padding, tick label size, label
padding, label size, and padding.
The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc.
unchanged are very fast.
*/
int QCPAxis::calculateMargin()
{
if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis
return 0;
if (mCachedMarginValid)
return mCachedMargin;
// run through similar steps as QCPAxis::draw, and calculate margin needed to fit axis and its labels
int margin = 0;
QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
tickPositions.reserve(mTickVector.size());
tickLabels.reserve(mTickVector.size());
if (mTicks)
{
for (int i=0; i<mTickVector.size(); ++i)
{
tickPositions.append(coordToPixel(mTickVector.at(i)));
if (mTickLabels)
tickLabels.append(mTickVectorLabels.at(i));
}
}
// transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size.
// Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
mAxisPainter->type = mAxisType;
mAxisPainter->labelFont = getLabelFont();
mAxisPainter->label = mLabel;
mAxisPainter->tickLabelFont = mTickLabelFont;
mAxisPainter->axisRect = mAxisRect->rect();
mAxisPainter->viewportRect = mParentPlot->viewport();
mAxisPainter->tickPositions = tickPositions;
mAxisPainter->tickLabels = tickLabels;
margin += mAxisPainter->size();
margin += mPadding;
mCachedMargin = margin;
mCachedMarginValid = true;
return margin;
}
/* inherits documentation from base class */
QCP::Interaction QCPAxis::selectionCategory() const
{
return QCP::iSelectAxes;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxisPainterPrivate
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxisPainterPrivate
\internal
\brief (Private)
This is a private class and not part of the public QCustomPlot interface.
It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and
axis label. It also buffers the labels to reduce replot times. The parameters are configured by
directly accessing the public member variables.
*/
/*!
Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every
redraw, to utilize the caching mechanisms.
*/
QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) :
type(QCPAxis::atLeft),
basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
lowerEnding(QCPLineEnding::esNone),
upperEnding(QCPLineEnding::esNone),
labelPadding(0),
tickLabelPadding(0),
tickLabelRotation(0),
tickLabelSide(QCPAxis::lsOutside),
substituteExponent(true),
numberMultiplyCross(false),
tickLengthIn(5),
tickLengthOut(0),
subTickLengthIn(2),
subTickLengthOut(0),
tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
offset(0),
abbreviateDecimalPowers(false),
reversedEndings(false),
mParentPlot(parentPlot),
mLabelCache(16) // cache at most 16 (tick) labels
{
}
QCPAxisPainterPrivate::~QCPAxisPainterPrivate()
{
}
/*! \internal
Draws the axis with the specified \a painter.
The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set
here, too.
*/
void QCPAxisPainterPrivate::draw(QCPPainter *painter)
{
QByteArray newHash = generateLabelParameterHash();
if (newHash != mLabelParameterHash)
{
mLabelCache.clear();
mLabelParameterHash = newHash;
}
QPoint origin;
switch (type)
{
case QCPAxis::atLeft: origin = axisRect.bottomLeft() +QPoint(-offset, 0); break;
case QCPAxis::atRight: origin = axisRect.bottomRight()+QPoint(+offset, 0); break;
case QCPAxis::atTop: origin = axisRect.topLeft() +QPoint(0, -offset); break;
case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break;
}
double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes)
switch (type)
{
case QCPAxis::atTop: yCor = -1; break;
case QCPAxis::atRight: xCor = 1; break;
default: break;
}
int margin = 0;
// draw baseline:
QLineF baseLine;
painter->setPen(basePen);
if (QCPAxis::orientation(type) == Qt::Horizontal)
baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor));
else
baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor));
if (reversedEndings)
baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later
painter->drawLine(baseLine);
// draw ticks:
if (!tickPositions.isEmpty())
{
painter->setPen(tickPen);
int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis)
if (QCPAxis::orientation(type) == Qt::Horizontal)
{
foreach (double tickPos, tickPositions)
painter->drawLine(QLineF(tickPos+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPos+xCor, origin.y()+tickLengthIn*tickDir+yCor));
} else
{
foreach (double tickPos, tickPositions)
painter->drawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPos+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPos+yCor));
}
}
// draw subticks:
if (!subTickPositions.isEmpty())
{
painter->setPen(subTickPen);
// direction of ticks ("inward" is right for left axis and left for right axis)
int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1;
if (QCPAxis::orientation(type) == Qt::Horizontal)
{
foreach (double subTickPos, subTickPositions)
painter->drawLine(QLineF(subTickPos+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPos+xCor, origin.y()+subTickLengthIn*tickDir+yCor));
} else
{
foreach (double subTickPos, subTickPositions)
painter->drawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPos+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPos+yCor));
}
}
margin += qMax(0, qMax(tickLengthOut, subTickLengthOut));
// draw axis base endings:
bool antialiasingBackup = painter->antialiasing();
painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't
painter->setBrush(QBrush(basePen.color()));
QCPVector2D baseLineVector(baseLine.dx(), baseLine.dy());
if (lowerEnding.style() != QCPLineEnding::esNone)
lowerEnding.draw(painter, QCPVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector);
if (upperEnding.style() != QCPLineEnding::esNone)
upperEnding.draw(painter, QCPVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector);
painter->setAntialiasing(antialiasingBackup);
// tick labels:
QRect oldClipRect;
if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect
{
oldClipRect = painter->clipRegion().boundingRect();
painter->setClipRect(axisRect);
}
QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label
if (!tickLabels.isEmpty())
{
if (tickLabelSide == QCPAxis::lsOutside)
margin += tickLabelPadding;
painter->setFont(tickLabelFont);
painter->setPen(QPen(tickLabelColor));
const int maxLabelIndex = static_cast<int>(qMin(tickPositions.size(), tickLabels.size()));
int distanceToAxis = margin;
if (tickLabelSide == QCPAxis::lsInside)
distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
for (int i=0; i<maxLabelIndex; ++i)
placeTickLabel(painter, tickPositions.at(i), distanceToAxis, tickLabels.at(i), &tickLabelsSize);
if (tickLabelSide == QCPAxis::lsOutside)
margin += (QCPAxis::orientation(type) == Qt::Horizontal) ? tickLabelsSize.height() : tickLabelsSize.width();
}
if (tickLabelSide == QCPAxis::lsInside)
painter->setClipRect(oldClipRect);
// axis label:
QRect labelBounds;
if (!label.isEmpty())
{
margin += labelPadding;
painter->setFont(labelFont);
painter->setPen(QPen(labelColor));
labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label);
if (type == QCPAxis::atLeft)
{
QTransform oldTransform = painter->transform();
painter->translate((origin.x()-margin-labelBounds.height()), origin.y());
painter->rotate(-90);
painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
painter->setTransform(oldTransform);
}
else if (type == QCPAxis::atRight)
{
QTransform oldTransform = painter->transform();
painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height());
painter->rotate(90);
painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
painter->setTransform(oldTransform);
}
else if (type == QCPAxis::atTop)
painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
else if (type == QCPAxis::atBottom)
painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
}
// set selection boxes:
int selectionTolerance = 0;
if (mParentPlot)
selectionTolerance = mParentPlot->selectionTolerance();
else
qDebug() << Q_FUNC_INFO << "mParentPlot is null";
int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance);
int selAxisInSize = selectionTolerance;
int selTickLabelSize;
int selTickLabelOffset;
if (tickLabelSide == QCPAxis::lsOutside)
{
selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding;
} else
{
selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
}
int selLabelSize = labelBounds.height();
int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding;
if (type == QCPAxis::atLeft)
{
mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom());
mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom());
mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom());
} else if (type == QCPAxis::atRight)
{
mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom());
mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom());
mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom());
} else if (type == QCPAxis::atTop)
{
mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize);
mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset);
mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset);
} else if (type == QCPAxis::atBottom)
{
mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize);
mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset);
mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset);
}
mAxisSelectionBox = mAxisSelectionBox.normalized();
mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized();
mLabelSelectionBox = mLabelSelectionBox.normalized();
// draw hitboxes for debug purposes:
//painter->setBrush(Qt::NoBrush);
//painter->drawRects(QVector<QRect>() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox);
}
/*! \internal
Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
direction) needed to fit the axis.
*/
int QCPAxisPainterPrivate::size()
{
int result = 0;
QByteArray newHash = generateLabelParameterHash();
if (newHash != mLabelParameterHash)
{
mLabelCache.clear();
mLabelParameterHash = newHash;
}
// get length of tick marks pointing outwards:
if (!tickPositions.isEmpty())
result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
// calculate size of tick labels:
if (tickLabelSide == QCPAxis::lsOutside)
{
QSize tickLabelsSize(0, 0);
if (!tickLabels.isEmpty())
{
foreach (const QString &tickLabel, tickLabels)
getMaxTickLabelSize(tickLabelFont, tickLabel, &tickLabelsSize);
result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
result += tickLabelPadding;
}
}
// calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
if (!label.isEmpty())
{
QFontMetrics fontMetrics(labelFont);
QRect bounds;
bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
result += bounds.height() + labelPadding;
}
return result;
}
/*! \internal
Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
method is called automatically in \ref draw, if any parameters have changed that invalidate the
cached labels, such as font, color, etc.
*/
void QCPAxisPainterPrivate::clearCache()
{
mLabelCache.clear();
}
/*! \internal
Returns a hash that allows uniquely identifying whether the label parameters have changed such
that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
return value of this method hasn't changed since the last redraw, the respective label parameters
haven't changed and cached labels may be used.
*/
QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const
{
QByteArray result;
result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio()));
result.append(QByteArray::number(tickLabelRotation));
result.append(QByteArray::number(int(tickLabelSide)));
result.append(QByteArray::number(int(substituteExponent)));
result.append(QByteArray::number(int(numberMultiplyCross)));
result.append(tickLabelColor.name().toLatin1()+QByteArray::number(tickLabelColor.alpha(), 16));
result.append(tickLabelFont.toString().toLatin1());
return result;
}
/*! \internal
Draws a single tick label with the provided \a painter, utilizing the internal label cache to
significantly speed up drawing of labels that were drawn in previous calls. The tick label is
always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
at which the label should be drawn.
In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
holds.
The label is drawn with the font and pen that are currently set on the \a painter. To draw
superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
getTickLabelData).
*/
void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize)
{
// warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
if (text.isEmpty()) return;
QSize finalSize;
QPointF labelAnchor;
switch (type)
{
case QCPAxis::atLeft: labelAnchor = QPointF(axisRect.left()-distanceToAxis-offset, position); break;
case QCPAxis::atRight: labelAnchor = QPointF(axisRect.right()+distanceToAxis+offset, position); break;
case QCPAxis::atTop: labelAnchor = QPointF(position, axisRect.top()-distanceToAxis-offset); break;
case QCPAxis::atBottom: labelAnchor = QPointF(position, axisRect.bottom()+distanceToAxis+offset); break;
}
if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
{
CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache
if (!cachedLabel) // no cached label existed, create it
{
cachedLabel = new CachedLabel;
TickLabelData labelData = getTickLabelData(painter->font(), text);
cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft();
if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio()))
{
cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio());
#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
# ifdef QCP_DEVICEPIXELRATIO_FLOAT
cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF());
# else
cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio());
# endif
#endif
} else
cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
cachedLabel->pixmap.fill(Qt::transparent);
QCPPainter cachePainter(&cachedLabel->pixmap);
cachePainter.setPen(painter->pen());
drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData);
}
// if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
bool labelClippedByBorder = false;
if (tickLabelSide == QCPAxis::lsOutside)
{
if (QCPAxis::orientation(type) == Qt::Horizontal)
labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
else
labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
}
if (!labelClippedByBorder)
{
painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap);
finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
}
mLabelCache.insert(text, cachedLabel); // return label to cache or insert for the first time if newly created
} else // label caching disabled, draw text directly on surface:
{
TickLabelData labelData = getTickLabelData(painter->font(), text);
QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData);
// if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
bool labelClippedByBorder = false;
if (tickLabelSide == QCPAxis::lsOutside)
{
if (QCPAxis::orientation(type) == Qt::Horizontal)
labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left();
else
labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top();
}
if (!labelClippedByBorder)
{
drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData);
finalSize = labelData.rotatedTotalBounds.size();
}
}
// expand passed tickLabelsSize if current tick label is larger:
if (finalSize.width() > tickLabelsSize->width())
tickLabelsSize->setWidth(finalSize.width());
if (finalSize.height() > tickLabelsSize->height())
tickLabelsSize->setHeight(finalSize.height());
}
/*! \internal
This is a \ref placeTickLabel helper function.
Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
QCP::phCacheLabels plotting hint is not set.
*/
void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const
{
// backup painter settings that we're about to change:
QTransform oldTransform = painter->transform();
QFont oldFont = painter->font();
// transform painter to position/rotation:
painter->translate(x, y);
if (!qFuzzyIsNull(tickLabelRotation))
painter->rotate(tickLabelRotation);
// draw text:
if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used
{
painter->setFont(labelData.baseFont);
painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
if (!labelData.suffixPart.isEmpty())
painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart);
painter->setFont(labelData.expFont);
painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
} else
{
painter->setFont(labelData.baseFont);
painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
}
// reset painter settings to what it was before:
painter->setTransform(oldTransform);
painter->setFont(oldFont);
}
/*! \internal
This is a \ref placeTickLabel helper function.
Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
*/
QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const
{
TickLabelData result;
// determine whether beautiful decimal powers should be used
bool useBeautifulPowers = false;
int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
if (substituteExponent)
{
ePos = static_cast<int>(text.indexOf(QString(mParentPlot->locale().exponential())));
if (ePos > 0 && text.at(ePos-1).isDigit())
{
eLast = ePos;
while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
++eLast;
if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
useBeautifulPowers = true;
}
}
// calculate text bounding rects and do string preparation for beautiful decimal powers:
result.baseFont = font;
if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line
result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding
if (useBeautifulPowers)
{
// split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
result.basePart = text.left(ePos);
result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent
// in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
if (abbreviateDecimalPowers && result.basePart == QLatin1String("1"))
result.basePart = QLatin1String("10");
else
result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + QLatin1String("10");
result.expPart = text.mid(ePos+1, eLast-ePos);
// clip "+" and leading zeros off expPart:
while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
result.expPart.remove(1, 1);
if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
result.expPart.remove(0, 1);
// prepare smaller font for exponent:
result.expFont = font;
if (result.expFont.pointSize() > 0)
result.expFont.setPointSize(int(result.expFont.pointSize()*0.75));
else
result.expFont.setPixelSize(int(result.expFont.pixelSize()*0.75));
// calculate bounding rects of base part(s), exponent part and total one:
result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
if (!result.suffixPart.isEmpty())
result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart);
result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+result.suffixBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA
} else // useBeautifulPowers == false
{
result.basePart = text;
result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
}
result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler
// calculate possibly different bounding rect after rotation:
result.rotatedTotalBounds = result.totalBounds;
if (!qFuzzyIsNull(tickLabelRotation))
{
QTransform transform;
transform.rotate(tickLabelRotation);
result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds);
}
return result;
}
/*! \internal
This is a \ref placeTickLabel helper function.
Calculates the offset at which the top left corner of the specified tick label shall be drawn.
The offset is relative to a point right next to the tick the label belongs to.
This function is thus responsible for e.g. centering tick labels under ticks and positioning them
appropriately when they are rotated.
*/
QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const
{
/*
calculate label offset from base point at tick (non-trivial, for best visual appearance): short
explanation for bottom axis: The anchor, i.e. the point in the label that is placed
horizontally under the corresponding tick is always on the label side that is closer to the
axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height
is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text
will be centered under the tick (i.e. displaced horizontally by half its height). At the same
time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick
labels.
*/
bool doRotation = !qFuzzyIsNull(tickLabelRotation);
bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes.
double radians = tickLabelRotation/180.0*M_PI;
double x = 0;
double y = 0;
if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label
{
if (doRotation)
{
if (tickLabelRotation > 0)
{
x = -qCos(radians)*labelData.totalBounds.width();
y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0;
} else
{
x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height();
y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0;
}
} else
{
x = -labelData.totalBounds.width();
y = -labelData.totalBounds.height()/2.0;
}
} else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label
{
if (doRotation)
{
if (tickLabelRotation > 0)
{
x = +qSin(radians)*labelData.totalBounds.height();
y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0;
} else
{
x = 0;
y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0;
}
} else
{
x = 0;
y = -labelData.totalBounds.height()/2.0;
}
} else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label
{
if (doRotation)
{
if (tickLabelRotation > 0)
{
x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0;
y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height();
} else
{
x = -qSin(-radians)*labelData.totalBounds.height()/2.0;
y = -qCos(-radians)*labelData.totalBounds.height();
}
} else
{
x = -labelData.totalBounds.width()/2.0;
y = -labelData.totalBounds.height();
}
} else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label
{
if (doRotation)
{
if (tickLabelRotation > 0)
{
x = +qSin(radians)*labelData.totalBounds.height()/2.0;
y = 0;
} else
{
x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0;
y = +qSin(-radians)*labelData.totalBounds.width();
}
} else
{
x = -labelData.totalBounds.width()/2.0;
y = 0;
}
}
return {x, y};
}
/*! \internal
Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
smaller width/height.
*/
void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const
{
// note: this function must return the same tick label sizes as the placeTickLabel function.
QSize finalSize;
if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
{
const CachedLabel *cachedLabel = mLabelCache.object(text);
finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
} else // label caching disabled or no label with this text cached:
{
TickLabelData labelData = getTickLabelData(font, text);
finalSize = labelData.rotatedTotalBounds.size();
}
// expand passed tickLabelsSize if current tick label is larger:
if (finalSize.width() > tickLabelsSize->width())
tickLabelsSize->setWidth(finalSize.width());
if (finalSize.height() > tickLabelsSize->height())
tickLabelsSize->setHeight(finalSize.height());
}
/* end of 'src/axis/axis.cpp' */
/* including file 'src/scatterstyle.cpp' */
/* modified 2022-11-06T12:45:56, size 17466 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPScatterStyle
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPScatterStyle
\brief Represents the visual appearance of scatter points
This class holds information about shape, color and size of scatter points. In plottables like
QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
be controlled with \ref setSize.
\section QCPScatterStyle-defining Specifying a scatter style
You can set all these configurations either by calling the respective functions on an instance:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1
Or you can use one of the various constructors that take different parameter combinations, making
it easy to specify a scatter style in a single call, like so:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2
\section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
isPenDefined will return false. It leads to scatter points that inherit the pen from the
plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line
color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes
it very convenient to set up typical scatter settings:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation
Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
ScatterShape, where actually a QCPScatterStyle is expected.
\section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
setCustomPath function or call the constructor that takes a painter path. The scatter shape will
automatically be set to \ref ssCustom.
For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
Note that \ref setSize does not influence the appearance of the pixmap.
*/
/* start documentation of inline functions */
/*! \fn bool QCPScatterStyle::isNone() const
Returns whether the scatter shape is \ref ssNone.
\see setShape
*/
/*! \fn bool QCPScatterStyle::isPenDefined() const
Returns whether a pen has been defined for this scatter style.
The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those
are \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen
is undefined, the pen of the respective plottable will be used for drawing scatters.
If a pen was defined for this scatter style instance, and you now wish to undefine the pen, call
\ref undefinePen.
\see setPen
*/
/* end documentation of inline functions */
/*!
Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
from the plottable that uses this scatter style.
*/
QCPScatterStyle::QCPScatterStyle() :
mSize(6),
mShape(ssNone),
mPen(Qt::NoPen),
mBrush(Qt::NoBrush),
mPenDefined(false)
{
}
/*!
Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
brush is defined.
Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
from the plottable that uses this scatter style.
*/
QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) :
mSize(size),
mShape(shape),
mPen(Qt::NoPen),
mBrush(Qt::NoBrush),
mPenDefined(false)
{
}
/*!
Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
*/
QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) :
mSize(size),
mShape(shape),
mPen(QPen(color)),
mBrush(Qt::NoBrush),
mPenDefined(true)
{
}
/*!
Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
the brush color to \a fill (with a solid pattern), and size to \a size.
*/
QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) :
mSize(size),
mShape(shape),
mPen(QPen(color)),
mBrush(QBrush(fill)),
mPenDefined(true)
{
}
/*!
Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
brush to \a brush, and size to \a size.
\warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen
and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n
<tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n
doesn't necessarily lead C++ to use this constructor in some cases, but might mistake
<tt>Qt::NoPen</tt> for a QColor and use the
\ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size)
constructor instead (which will lead to an unexpected look of the scatter points). To prevent
this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt>
instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is
wanted.
*/
QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) :
mSize(size),
mShape(shape),
mPen(pen),
mBrush(brush),
mPenDefined(pen.style() != Qt::NoPen)
{
}
/*!
Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
is set to \ref ssPixmap.
*/
QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) :
mSize(5),
mShape(ssPixmap),
mPen(Qt::NoPen),
mBrush(Qt::NoBrush),
mPixmap(pixmap),
mPenDefined(false)
{
}
/*!
Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
scatter shape is set to \ref ssCustom.
The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
different meaning than for built-in scatter points: The custom path will be drawn scaled by a
factor of \a size/6.0. Since the default \a size is 6, the custom path will appear in its
original size by default. To for example double the size of the path, set \a size to 12.
*/
QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) :
mSize(size),
mShape(ssCustom),
mPen(pen),
mBrush(brush),
mCustomPath(customPath),
mPenDefined(pen.style() != Qt::NoPen)
{
}
/*!
Copies the specified \a properties from the \a other scatter style to this scatter style.
*/
void QCPScatterStyle::setFromOther(const QCPScatterStyle &other, ScatterProperties properties)
{
if (properties.testFlag(spPen))
{
setPen(other.pen());
if (!other.isPenDefined())
undefinePen();
}
if (properties.testFlag(spBrush))
setBrush(other.brush());
if (properties.testFlag(spSize))
setSize(other.size());
if (properties.testFlag(spShape))
{
setShape(other.shape());
if (other.shape() == ssPixmap)
setPixmap(other.pixmap());
else if (other.shape() == ssCustom)
setCustomPath(other.customPath());
}
}
/*!
Sets the size (pixel diameter) of the drawn scatter points to \a size.
\see setShape
*/
void QCPScatterStyle::setSize(double size)
{
mSize = size;
}
/*!
Sets the shape to \a shape.
Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
ssPixmap and \ref ssCustom, respectively.
\see setSize
*/
void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
{
mShape = shape;
}
/*!
Sets the pen that will be used to draw scatter points to \a pen.
If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
a call to this function, even if \a pen is <tt>Qt::NoPen</tt>. If you have defined a pen
previously by calling this function and now wish to undefine the pen, call \ref undefinePen.
\see setBrush
*/
void QCPScatterStyle::setPen(const QPen &pen)
{
mPenDefined = true;
mPen = pen;
}
/*!
Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
\see setPen
*/
void QCPScatterStyle::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the pixmap that will be drawn as scatter point to \a pixmap.
Note that \ref setSize does not influence the appearance of the pixmap.
The scatter shape is automatically set to \ref ssPixmap.
*/
void QCPScatterStyle::setPixmap(const QPixmap &pixmap)
{
setShape(ssPixmap);
mPixmap = pixmap;
}
/*!
Sets the custom shape that will be drawn as scatter point to \a customPath.
The scatter shape is automatically set to \ref ssCustom.
*/
void QCPScatterStyle::setCustomPath(const QPainterPath &customPath)
{
setShape(ssCustom);
mCustomPath = customPath;
}
/*!
Sets this scatter style to have an undefined pen (see \ref isPenDefined for what an undefined pen
implies).
A call to \ref setPen will define a pen.
*/
void QCPScatterStyle::undefinePen()
{
mPenDefined = false;
}
/*!
Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
This function is used by plottables (or any class that wants to draw scatters) just before a
number of scatters with this style shall be drawn with the \a painter.
\see drawShape
*/
void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const
{
painter->setPen(mPenDefined ? mPen : defaultPen);
painter->setBrush(mBrush);
}
/*!
Draws the scatter shape with \a painter at position \a pos.
This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
called before scatter points are drawn with \ref drawShape.
\see applyTo
*/
void QCPScatterStyle::drawShape(QCPPainter *painter, const QPointF &pos) const
{
drawShape(painter, pos.x(), pos.y());
}
/*! \overload
Draws the scatter shape with \a painter at position \a x and \a y.
*/
void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const
{
double w = mSize/2.0;
switch (mShape)
{
case ssNone: break;
case ssDot:
{
painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y));
break;
}
case ssCross:
{
painter->drawLine(QLineF(x-w, y-w, x+w, y+w));
painter->drawLine(QLineF(x-w, y+w, x+w, y-w));
break;
}
case ssPlus:
{
painter->drawLine(QLineF(x-w, y, x+w, y));
painter->drawLine(QLineF( x, y+w, x, y-w));
break;
}
case ssCircle:
{
painter->drawEllipse(QPointF(x , y), w, w);
break;
}
case ssDisc:
{
QBrush b = painter->brush();
painter->setBrush(painter->pen().color());
painter->drawEllipse(QPointF(x , y), w, w);
painter->setBrush(b);
break;
}
case ssSquare:
{
painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
break;
}
case ssDiamond:
{
QPointF lineArray[4] = {QPointF(x-w, y),
QPointF( x, y-w),
QPointF(x+w, y),
QPointF( x, y+w)};
painter->drawPolygon(lineArray, 4);
break;
}
case ssStar:
{
painter->drawLine(QLineF(x-w, y, x+w, y));
painter->drawLine(QLineF( x, y+w, x, y-w));
painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707));
painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707));
break;
}
case ssTriangle:
{
QPointF lineArray[3] = {QPointF(x-w, y+0.755*w),
QPointF(x+w, y+0.755*w),
QPointF( x, y-0.977*w)};
painter->drawPolygon(lineArray, 3);
break;
}
case ssTriangleInverted:
{
QPointF lineArray[3] = {QPointF(x-w, y-0.755*w),
QPointF(x+w, y-0.755*w),
QPointF( x, y+0.977*w)};
painter->drawPolygon(lineArray, 3);
break;
}
case ssCrossSquare:
{
painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95));
painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w));
break;
}
case ssPlusSquare:
{
painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
painter->drawLine(QLineF(x-w, y, x+w*0.95, y));
painter->drawLine(QLineF( x, y+w, x, y-w));
break;
}
case ssCrossCircle:
{
painter->drawEllipse(QPointF(x, y), w, w);
painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670));
painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707));
break;
}
case ssPlusCircle:
{
painter->drawEllipse(QPointF(x, y), w, w);
painter->drawLine(QLineF(x-w, y, x+w, y));
painter->drawLine(QLineF( x, y+w, x, y-w));
break;
}
case ssPeace:
{
painter->drawEllipse(QPointF(x, y), w, w);
painter->drawLine(QLineF(x, y-w, x, y+w));
painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707));
painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707));
break;
}
case ssPixmap:
{
const double widthHalf = mPixmap.width()*0.5;
const double heightHalf = mPixmap.height()*0.5;
#if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
const QRectF clipRect = painter->clipRegion().boundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
#else
const QRectF clipRect = painter->clipBoundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
#endif
if (clipRect.contains(x, y))
painter->drawPixmap(qRound(x-widthHalf), qRound(y-heightHalf), mPixmap);
break;
}
case ssCustom:
{
QTransform oldTransform = painter->transform();
painter->translate(x, y);
painter->scale(mSize/6.0, mSize/6.0);
painter->drawPath(mCustomPath);
painter->setTransform(oldTransform);
break;
}
}
}
/* end of 'src/scatterstyle.cpp' */
/* including file 'src/plottable.cpp' */
/* modified 2022-11-06T12:45:56, size 38818 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPSelectionDecorator
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPSelectionDecorator
\brief Controls how a plottable's data selection is drawn
Each \ref QCPAbstractPlottable instance has one \ref QCPSelectionDecorator (accessible via \ref
QCPAbstractPlottable::selectionDecorator) and uses it when drawing selected segments of its data.
The selection decorator controls both pen (\ref setPen) and brush (\ref setBrush), as well as the
scatter style (\ref setScatterStyle) if the plottable draws scatters. Since a \ref
QCPScatterStyle is itself composed of different properties such as color shape and size, the
decorator allows specifying exactly which of those properties shall be used for the selected data
point, via \ref setUsedScatterProperties.
A \ref QCPSelectionDecorator subclass instance can be passed to a plottable via \ref
QCPAbstractPlottable::setSelectionDecorator, allowing greater customizability of the appearance
of selected segments.
Use \ref copyFrom to easily transfer the settings of one decorator to another one. This is
especially useful since plottables take ownership of the passed selection decorator, and thus the
same decorator instance can not be passed to multiple plottables.
Selection decorators can also themselves perform drawing operations by reimplementing \ref
drawDecoration, which is called by the plottable's draw method. The base class \ref
QCPSelectionDecorator does not make use of this however. For example, \ref
QCPSelectionDecoratorBracket draws brackets around selected data segments.
*/
/*!
Creates a new QCPSelectionDecorator instance with default values
*/
QCPSelectionDecorator::QCPSelectionDecorator() :
mPen(QColor(80, 80, 255), 2.5),
mBrush(Qt::NoBrush),
mUsedScatterProperties(QCPScatterStyle::spNone),
mPlottable(nullptr)
{
}
QCPSelectionDecorator::~QCPSelectionDecorator()
{
}
/*!
Sets the pen that will be used by the parent plottable to draw selected data segments.
*/
void QCPSelectionDecorator::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the brush that will be used by the parent plottable to draw selected data segments.
*/
void QCPSelectionDecorator::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the scatter style that will be used by the parent plottable to draw scatters in selected
data segments.
\a usedProperties specifies which parts of the passed \a scatterStyle will be used by the
plottable. The used properties can also be changed via \ref setUsedScatterProperties.
*/
void QCPSelectionDecorator::setScatterStyle(const QCPScatterStyle &scatterStyle, QCPScatterStyle::ScatterProperties usedProperties)
{
mScatterStyle = scatterStyle;
setUsedScatterProperties(usedProperties);
}
/*!
Use this method to define which properties of the scatter style (set via \ref setScatterStyle)
will be used for selected data segments. All properties of the scatter style that are not
specified in \a properties will remain as specified in the plottable's original scatter style.
\see QCPScatterStyle::ScatterProperty
*/
void QCPSelectionDecorator::setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties)
{
mUsedScatterProperties = properties;
}
/*!
Sets the pen of \a painter to the pen of this selection decorator.
\see applyBrush, getFinalScatterStyle
*/
void QCPSelectionDecorator::applyPen(QCPPainter *painter) const
{
painter->setPen(mPen);
}
/*!
Sets the brush of \a painter to the brush of this selection decorator.
\see applyPen, getFinalScatterStyle
*/
void QCPSelectionDecorator::applyBrush(QCPPainter *painter) const
{
painter->setBrush(mBrush);
}
/*!
Returns the scatter style that the parent plottable shall use for selected scatter points. The
plottable's original (unselected) scatter style must be passed as \a unselectedStyle. Depending
on the setting of \ref setUsedScatterProperties, the returned scatter style is a mixture of this
selecion decorator's scatter style (\ref setScatterStyle), and \a unselectedStyle.
\see applyPen, applyBrush, setScatterStyle
*/
QCPScatterStyle QCPSelectionDecorator::getFinalScatterStyle(const QCPScatterStyle &unselectedStyle) const
{
QCPScatterStyle result(unselectedStyle);
result.setFromOther(mScatterStyle, mUsedScatterProperties);
// if style shall inherit pen from plottable (has no own pen defined), give it the selected
// plottable pen explicitly, so it doesn't use the unselected plottable pen when used in the
// plottable:
if (!result.isPenDefined())
result.setPen(mPen);
return result;
}
/*!
Copies all properties (e.g. color, fill, scatter style) of the \a other selection decorator to
this selection decorator.
*/
void QCPSelectionDecorator::copyFrom(const QCPSelectionDecorator *other)
{
setPen(other->pen());
setBrush(other->brush());
setScatterStyle(other->scatterStyle(), other->usedScatterProperties());
}
/*!
This method is called by all plottables' draw methods to allow custom selection decorations to be
drawn. Use the passed \a painter to perform the drawing operations. \a selection carries the data
selection for which the decoration shall be drawn.
The default base class implementation of \ref QCPSelectionDecorator has no special decoration, so
this method does nothing.
*/
void QCPSelectionDecorator::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
{
Q_UNUSED(painter)
Q_UNUSED(selection)
}
/*! \internal
This method is called as soon as a selection decorator is associated with a plottable, by a call
to \ref QCPAbstractPlottable::setSelectionDecorator. This way the selection decorator can obtain a pointer to the plottable that uses it (e.g. to access
data points via the \ref QCPAbstractPlottable::interface1D interface).
If the selection decorator was already added to a different plottable before, this method aborts
the registration and returns false.
*/
bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottable)
{
if (!mPlottable)
{
mPlottable = plottable;
return true;
} else
{
qDebug() << Q_FUNC_INFO << "This selection decorator is already registered with plottable:" << reinterpret_cast<quintptr>(mPlottable);
return false;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAbstractPlottable
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAbstractPlottable
\brief The abstract base class for all data representing objects in a plot.
It defines a very basic interface like name, pen, brush, visibility etc. Since this class is
abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to
create new ways of displaying data (see "Creating own plottables" below). Plottables that display
one-dimensional data (i.e. data points have a single key dimension and one or multiple values at
each key) are based off of the template subclass \ref QCPAbstractPlottable1D, see details
there.
All further specifics are in the subclasses, for example:
\li A normal graph with possibly a line and/or scatter points \ref QCPGraph
(typically created with \ref QCustomPlot::addGraph)
\li A parametric curve: \ref QCPCurve
\li A bar chart: \ref QCPBars
\li A statistical box plot: \ref QCPStatisticalBox
\li A color encoded two-dimensional map: \ref QCPColorMap
\li An OHLC/Candlestick chart: \ref QCPFinancial
\section plottables-subclassing Creating own plottables
Subclassing directly from QCPAbstractPlottable is only recommended if you wish to display
two-dimensional data like \ref QCPColorMap, i.e. two logical key dimensions and one (or more)
data dimensions. If you want to display data with only one logical key dimension, you should
rather derive from \ref QCPAbstractPlottable1D.
If subclassing QCPAbstractPlottable directly, these are the pure virtual functions you must
implement:
\li \ref selectTest
\li \ref draw
\li \ref drawLegendIcon
\li \ref getKeyRange
\li \ref getValueRange
See the documentation of those functions for what they need to do.
For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot
coordinates to pixel coordinates. This function is quite convenient, because it takes the
orientation of the key and value axes into account for you (x and y are swapped when the key axis
is vertical and the value axis horizontal). If you are worried about performance (i.e. you need
to translate many points in a loop like QCPGraph), you can directly use \ref
QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis
yourself.
Here are some important members you inherit from QCPAbstractPlottable:
<table>
<tr>
<td>QCustomPlot *\b mParentPlot</td>
<td>A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.</td>
</tr><tr>
<td>QString \b mName</td>
<td>The name of the plottable.</td>
</tr><tr>
<td>QPen \b mPen</td>
<td>The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable
(e.g QCPGraph uses this pen for its graph lines and scatters)</td>
</tr><tr>
<td>QBrush \b mBrush</td>
<td>The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable
(e.g. QCPGraph uses this brush to control filling under the graph)</td>
</tr><tr>
<td>QPointer<\ref QCPAxis> \b mKeyAxis, \b mValueAxis</td>
<td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates
to pixels in either the key or value dimension. Make sure to check whether the pointer is \c nullptr before using it. If one of
the axes is null, don't draw the plottable.</td>
</tr><tr>
<td>\ref QCPSelectionDecorator \b mSelectionDecorator</td>
<td>The currently set selection decorator which specifies how selected data of the plottable shall be drawn and decorated.
When drawing your data, you must consult this decorator for the appropriate pen/brush before drawing unselected/selected data segments.
Finally, you should call its \ref QCPSelectionDecorator::drawDecoration method at the end of your \ref draw implementation.</td>
</tr><tr>
<td>\ref QCP::SelectionType \b mSelectable</td>
<td>In which composition, if at all, this plottable's data may be selected. Enforcing this setting on the data selection is done
by QCPAbstractPlottable automatically.</td>
</tr><tr>
<td>\ref QCPDataSelection \b mSelection</td>
<td>Holds the current selection state of the plottable's data, i.e. the selected data ranges (\ref QCPDataRange).</td>
</tr>
</table>
*/
/* start of documentation of inline functions */
/*! \fn QCPSelectionDecorator *QCPAbstractPlottable::selectionDecorator() const
Provides access to the selection decorator of this plottable. The selection decorator controls
how selected data ranges are drawn (e.g. their pen color and fill), see \ref
QCPSelectionDecorator for details.
If you wish to use an own \ref QCPSelectionDecorator subclass, pass an instance of it to \ref
setSelectionDecorator.
*/
/*! \fn bool QCPAbstractPlottable::selected() const
Returns true if there are any data points of the plottable currently selected. Use \ref selection
to retrieve the current \ref QCPDataSelection.
*/
/*! \fn QCPDataSelection QCPAbstractPlottable::selection() const
Returns a \ref QCPDataSelection encompassing all the data points that are currently selected on
this plottable.
\see selected, setSelection, setSelectable
*/
/*! \fn virtual QCPPlottableInterface1D *QCPAbstractPlottable::interface1D()
If this plottable is a one-dimensional plottable, i.e. it implements the \ref
QCPPlottableInterface1D, returns the \a this pointer with that type. Otherwise (e.g. in the case
of a \ref QCPColorMap) returns zero.
You can use this method to gain read access to data coordinates while holding a pointer to the
abstract base class only.
*/
/* end of documentation of inline functions */
/* start of documentation of pure virtual functions */
/*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0
\internal
called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation
of this plottable inside \a rect, next to the plottable name.
The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't
appear outside the legend icon border.
*/
/*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const = 0
Returns the coordinate range that all data in this plottable span in the key axis dimension. For
logarithmic plots, one can set \a inSignDomain to either \ref QCP::sdNegative or \ref
QCP::sdPositive in order to restrict the returned range to that sign domain. E.g. when only
negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and all positive points
will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref
QCP::sdBoth (default). \a foundRange is an output parameter that indicates whether a range could
be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data).
Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
this function may have size zero (e.g. when there is only one data point). In this case \a
foundRange would return true, but the returned range is not a valid range in terms of \ref
QCPRange::validRange.
\see rescaleAxes, getValueRange
*/
/*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const = 0
Returns the coordinate range that the data points in the specified key range (\a inKeyRange) span
in the value axis dimension. For logarithmic plots, one can set \a inSignDomain to either \ref
QCP::sdNegative or \ref QCP::sdPositive in order to restrict the returned range to that sign
domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and
all positive points will be ignored for range calculation. For no restriction, just set \a
inSignDomain to \ref QCP::sdBoth (default). \a foundRange is an output parameter that indicates
whether a range could be found or not. If this is false, you shouldn't use the returned range
(e.g. no points in data).
If \a inKeyRange has both lower and upper bound set to zero (is equal to <tt>QCPRange()</tt>),
all data points are considered, without any restriction on the keys.
Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
this function may have size zero (e.g. when there is only one data point). In this case \a
foundRange would return true, but the returned range is not a valid range in terms of \ref
QCPRange::validRange.
\see rescaleAxes, getKeyRange
*/
/* end of documentation of pure virtual functions */
/* start of documentation of signals */
/*! \fn void QCPAbstractPlottable::selectionChanged(bool selected)
This signal is emitted when the selection state of this plottable has changed, either by user
interaction or by a direct call to \ref setSelection. The parameter \a selected indicates whether
there are any points selected or not.
\see selectionChanged(const QCPDataSelection &selection)
*/
/*! \fn void QCPAbstractPlottable::selectionChanged(const QCPDataSelection &selection)
This signal is emitted when the selection state of this plottable has changed, either by user
interaction or by a direct call to \ref setSelection. The parameter \a selection holds the
currently selected data ranges.
\see selectionChanged(bool selected)
*/
/*! \fn void QCPAbstractPlottable::selectableChanged(QCP::SelectionType selectable);
This signal is emitted when the selectability of this plottable has changed.
\see setSelectable
*/
/* end of documentation of signals */
/*!
Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as
its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance
and have perpendicular orientations. If either of these restrictions is violated, a corresponding
message is printed to the debug output (qDebug), the construction is not aborted, though.
Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables,
it can't be directly instantiated.
You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead.
*/
QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()),
mName(),
mAntialiasedFill(true),
mAntialiasedScatters(true),
mPen(Qt::black),
mBrush(Qt::NoBrush),
mKeyAxis(keyAxis),
mValueAxis(valueAxis),
mSelectable(QCP::stWhole),
mSelectionDecorator(nullptr)
{
if (keyAxis->parentPlot() != valueAxis->parentPlot())
qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
if (keyAxis->orientation() == valueAxis->orientation())
qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other.";
mParentPlot->registerPlottable(this);
setSelectionDecorator(new QCPSelectionDecorator);
}
QCPAbstractPlottable::~QCPAbstractPlottable()
{
if (mSelectionDecorator)
{
delete mSelectionDecorator;
mSelectionDecorator = nullptr;
}
}
/*!
The name is the textual representation of this plottable as it is displayed in the legend
(\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
*/
void QCPAbstractPlottable::setName(const QString &name)
{
mName = name;
}
/*!
Sets whether fills of this plottable are drawn antialiased or not.
Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
*/
void QCPAbstractPlottable::setAntialiasedFill(bool enabled)
{
mAntialiasedFill = enabled;
}
/*!
Sets whether the scatter symbols of this plottable are drawn antialiased or not.
Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
*/
void QCPAbstractPlottable::setAntialiasedScatters(bool enabled)
{
mAntialiasedScatters = enabled;
}
/*!
The pen is used to draw basic lines that make up the plottable representation in the
plot.
For example, the \ref QCPGraph subclass draws its graph lines with this pen.
\see setBrush
*/
void QCPAbstractPlottable::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
The brush is used to draw basic fills of the plottable representation in the
plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
it's not set to Qt::NoBrush.
\see setPen
*/
void QCPAbstractPlottable::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
to the plottable's value axis. This function performs no checks to make sure this is the case.
The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
y-axis (QCustomPlot::yAxis) as value axis.
Normally, the key and value axes are set in the constructor of the plottable (or \ref
QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
\see setValueAxis
*/
void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis)
{
mKeyAxis = axis;
}
/*!
The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
the y-axis (QCustomPlot::yAxis) as value axis.
Normally, the key and value axes are set in the constructor of the plottable (or \ref
QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
\see setKeyAxis
*/
void QCPAbstractPlottable::setValueAxis(QCPAxis *axis)
{
mValueAxis = axis;
}
/*!
Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
(e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
selectionDecorator).
The entire selection mechanism for plottables is handled automatically when \ref
QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
you wish to change the selection state programmatically.
Using \ref setSelectable you can further specify for each plottable whether and to which
granularity it is selectable. If \a selection is not compatible with the current \ref
QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
accordingly (see \ref QCPDataSelection::enforceType).
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
\see setSelectable, selectTest
*/
void QCPAbstractPlottable::setSelection(QCPDataSelection selection)
{
selection.enforceType(mSelectable);
if (mSelection != selection)
{
mSelection = selection;
emit selectionChanged(selected());
emit selectionChanged(mSelection);
}
}
/*!
Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
customize the visual representation of selected data ranges further than by using the default
QCPSelectionDecorator.
The plottable takes ownership of the \a decorator.
The currently set decorator can be accessed via \ref selectionDecorator.
*/
void QCPAbstractPlottable::setSelectionDecorator(QCPSelectionDecorator *decorator)
{
if (decorator)
{
if (decorator->registerWithPlottable(this))
{
delete mSelectionDecorator; // delete old decorator if necessary
mSelectionDecorator = decorator;
}
} else if (mSelectionDecorator) // just clear decorator
{
delete mSelectionDecorator;
mSelectionDecorator = nullptr;
}
}
/*!
Sets whether and to which granularity this plottable can be selected.
A selection can happen by clicking on the QCustomPlot surface (When \ref
QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
(When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
calling \ref setSelection.
\see setSelection, QCP::SelectionType
*/
void QCPAbstractPlottable::setSelectable(QCP::SelectionType selectable)
{
if (mSelectable != selectable)
{
mSelectable = selectable;
QCPDataSelection oldSelection = mSelection;
mSelection.enforceType(mSelectable);
emit selectableChanged(mSelectable);
if (mSelection != oldSelection)
{
emit selectionChanged(selected());
emit selectionChanged(mSelection);
}
}
}
/*!
Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
taking the orientations of the axes associated with this plottable into account (e.g. whether key
represents x or y).
\a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
\see pixelsToCoords, QCPAxis::coordToPixel
*/
void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (keyAxis->orientation() == Qt::Horizontal)
{
x = keyAxis->coordToPixel(key);
y = valueAxis->coordToPixel(value);
} else
{
y = keyAxis->coordToPixel(key);
x = valueAxis->coordToPixel(value);
}
}
/*! \overload
Transforms the given \a key and \a value to pixel coordinates and returns them in a QPointF.
*/
const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
if (keyAxis->orientation() == Qt::Horizontal)
return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
else
return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
}
/*!
Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates,
taking the orientations of the axes associated with this plottable into account (e.g. whether key
represents x or y).
\a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
\see coordsToPixels, QCPAxis::coordToPixel
*/
void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (keyAxis->orientation() == Qt::Horizontal)
{
key = keyAxis->pixelToCoord(x);
value = valueAxis->pixelToCoord(y);
} else
{
key = keyAxis->pixelToCoord(y);
value = valueAxis->pixelToCoord(x);
}
}
/*! \overload
Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
*/
void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
{
pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
}
/*!
Rescales the key and value axes associated with this plottable to contain all displayed data, so
the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make
sure not to rescale to an illegal range i.e. a range containing different signs and/or zero.
Instead it will stay in the current sign domain and ignore all parts of the plottable that lie
outside of that domain.
\a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show
multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has
\a onlyEnlarge set to false (the default), and all subsequent set to true.
\see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale
*/
void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const
{
rescaleKeyAxis(onlyEnlarge);
rescaleValueAxis(onlyEnlarge);
}
/*!
Rescales the key axis of the plottable so the whole plottable is visible.
See \ref rescaleAxes for detailed behaviour.
*/
void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
{
QCPAxis *keyAxis = mKeyAxis.data();
if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
QCP::SignDomain signDomain = QCP::sdBoth;
if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
signDomain = (keyAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
bool foundRange;
QCPRange newRange = getKeyRange(foundRange, signDomain);
if (foundRange)
{
if (onlyEnlarge)
newRange.expand(keyAxis->range());
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
if (keyAxis->scaleType() == QCPAxis::stLinear)
{
newRange.lower = center-keyAxis->range().size()/2.0;
newRange.upper = center+keyAxis->range().size()/2.0;
} else // scaleType() == stLogarithmic
{
newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower);
newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower);
}
}
keyAxis->setRange(newRange);
}
}
/*!
Rescales the value axis of the plottable so the whole plottable is visible. If \a inKeyRange is
set to true, only the data points which are in the currently visible key axis range are
considered.
Returns true if the axis was actually scaled. This might not be the case if this plottable has an
invalid range, e.g. because it has no data points.
See \ref rescaleAxes for detailed behaviour.
*/
void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
QCP::SignDomain signDomain = QCP::sdBoth;
if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
bool foundRange;
QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
if (foundRange)
{
if (onlyEnlarge)
newRange.expand(valueAxis->range());
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
if (valueAxis->scaleType() == QCPAxis::stLinear)
{
newRange.lower = center-valueAxis->range().size()/2.0;
newRange.upper = center+valueAxis->range().size()/2.0;
} else // scaleType() == stLogarithmic
{
newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
}
}
valueAxis->setRange(newRange);
}
}
/*! \overload
Adds this plottable to the specified \a legend.
Creates a QCPPlottableLegendItem which is inserted into the legend. Returns true on success, i.e.
when the legend exists and a legend item associated with this plottable isn't already in the
legend.
If the plottable needs a more specialized representation in the legend, you can create a
corresponding subclass of \ref QCPPlottableLegendItem and add it to the legend manually instead
of calling this method.
\see removeFromLegend, QCPLegend::addItem
*/
bool QCPAbstractPlottable::addToLegend(QCPLegend *legend)
{
if (!legend)
{
qDebug() << Q_FUNC_INFO << "passed legend is null";
return false;
}
if (legend->parentPlot() != mParentPlot)
{
qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
return false;
}
if (!legend->hasItemWithPlottable(this))
{
legend->addItem(new QCPPlottableLegendItem(legend, this));
return true;
} else
return false;
}
/*! \overload
Adds this plottable to the legend of the parent QCustomPlot (\ref QCustomPlot::legend).
\see removeFromLegend
*/
bool QCPAbstractPlottable::addToLegend()
{
if (!mParentPlot || !mParentPlot->legend)
return false;
else
return addToLegend(mParentPlot->legend);
}
/*! \overload
Removes the plottable from the specifed \a legend. This means the \ref QCPPlottableLegendItem
that is associated with this plottable is removed.
Returns true on success, i.e. if the legend exists and a legend item associated with this
plottable was found and removed.
\see addToLegend, QCPLegend::removeItem
*/
bool QCPAbstractPlottable::removeFromLegend(QCPLegend *legend) const
{
if (!legend)
{
qDebug() << Q_FUNC_INFO << "passed legend is null";
return false;
}
if (QCPPlottableLegendItem *lip = legend->itemWithPlottable(this))
return legend->removeItem(lip);
else
return false;
}
/*! \overload
Removes the plottable from the legend of the parent QCustomPlot.
\see addToLegend
*/
bool QCPAbstractPlottable::removeFromLegend() const
{
if (!mParentPlot || !mParentPlot->legend)
return false;
else
return removeFromLegend(mParentPlot->legend);
}
/* inherits documentation from base class */
QRect QCPAbstractPlottable::clipRect() const
{
if (mKeyAxis && mValueAxis)
return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
else
return {};
}
/* inherits documentation from base class */
QCP::Interaction QCPAbstractPlottable::selectionCategory() const
{
return QCP::iSelectPlottables;
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing plottable lines.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\seebaseclassmethod
\see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint
*/
void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing plottable fills.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint
*/
void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing plottable scatter points.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint
*/
void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
}
/* inherits documentation from base class */
void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
if (mSelectable != QCP::stNone)
{
QCPDataSelection newSelection = details.value<QCPDataSelection>();
QCPDataSelection selectionBefore = mSelection;
if (additive)
{
if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
{
if (selected())
setSelection(QCPDataSelection());
else
setSelection(newSelection);
} else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
{
if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
setSelection(mSelection-newSelection);
else
setSelection(mSelection+newSelection);
}
} else
setSelection(newSelection);
if (selectionStateChanged)
*selectionStateChanged = mSelection != selectionBefore;
}
}
/* inherits documentation from base class */
void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged)
{
if (mSelectable != QCP::stNone)
{
QCPDataSelection selectionBefore = mSelection;
setSelection(QCPDataSelection());
if (selectionStateChanged)
*selectionStateChanged = mSelection != selectionBefore;
}
}
/* end of 'src/plottable.cpp' */
/* including file 'src/item.cpp' */
/* modified 2022-11-06T12:45:56, size 49486 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemAnchor
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemAnchor
\brief An anchor of an item to which positions can be attached to.
An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't
control anything on its item, but provides a way to tie other items via their positions to the
anchor.
For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight.
Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can
attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by
calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the
QCPItemRect. This way the start of the line will now always follow the respective anchor location
on the rect item.
Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an
anchor to other positions.
To learn how to provide anchors in your own item subclasses, see the subclassing section of the
QCPAbstractItem documentation.
*/
/* start documentation of inline functions */
/*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition()
Returns \c nullptr if this instance is merely a QCPItemAnchor, and a valid pointer of type
QCPItemPosition* if it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor).
This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids
dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with
gcc compiler).
*/
/* end documentation of inline functions */
/*!
Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if
you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as
explained in the subclassing section of the QCPAbstractItem documentation.
*/
QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId) :
mName(name),
mParentPlot(parentPlot),
mParentItem(parentItem),
mAnchorId(anchorId)
{
}
QCPItemAnchor::~QCPItemAnchor()
{
// unregister as parent at children:
foreach (QCPItemPosition *child, mChildrenX.values())
{
if (child->parentAnchorX() == this)
child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX
}
foreach (QCPItemPosition *child, mChildrenY.values())
{
if (child->parentAnchorY() == this)
child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY
}
}
/*!
Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface.
The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the
parent item, QCPItemAnchor is just an intermediary.
*/
QPointF QCPItemAnchor::pixelPosition() const
{
if (mParentItem)
{
if (mAnchorId > -1)
{
return mParentItem->anchorPixelPosition(mAnchorId);
} else
{
qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId;
return {};
}
} else
{
qDebug() << Q_FUNC_INFO << "no parent item set";
return {};
}
}
/*! \internal
Adds \a pos to the childX list of this anchor, which keeps track of which children use this
anchor as parent anchor for the respective coordinate. This is necessary to notify the children
prior to destruction of the anchor.
Note that this function does not change the parent setting in \a pos.
*/
void QCPItemAnchor::addChildX(QCPItemPosition *pos)
{
if (!mChildrenX.contains(pos))
mChildrenX.insert(pos);
else
qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
}
/*! \internal
Removes \a pos from the childX list of this anchor.
Note that this function does not change the parent setting in \a pos.
*/
void QCPItemAnchor::removeChildX(QCPItemPosition *pos)
{
if (!mChildrenX.remove(pos))
qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
}
/*! \internal
Adds \a pos to the childY list of this anchor, which keeps track of which children use this
anchor as parent anchor for the respective coordinate. This is necessary to notify the children
prior to destruction of the anchor.
Note that this function does not change the parent setting in \a pos.
*/
void QCPItemAnchor::addChildY(QCPItemPosition *pos)
{
if (!mChildrenY.contains(pos))
mChildrenY.insert(pos);
else
qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
}
/*! \internal
Removes \a pos from the childY list of this anchor.
Note that this function does not change the parent setting in \a pos.
*/
void QCPItemAnchor::removeChildY(QCPItemPosition *pos)
{
if (!mChildrenY.remove(pos))
qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemPosition
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemPosition
\brief Manages the position of an item.
Every item has at least one public QCPItemPosition member pointer which provides ways to position the
item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two:
\a topLeft and \a bottomRight.
QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type
defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel
coordinates, as plot coordinates of certain axes (\ref QCPItemPosition::setAxes), as fractions of
the axis rect (\ref QCPItemPosition::setAxisRect), etc. For more advanced plots it is also
possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref
setTypeY). This way an item could be positioned for example at a fixed pixel distance from the
top in the Y direction, while following a plot coordinate in the X direction.
A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie
multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords)
are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0)
means directly ontop of the parent anchor. For example, You could attach the \a start position of
a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line
always be centered under the text label, no matter where the text is moved to. For more advanced
plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see
\ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X
direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B
in Y.
Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent
anchor for other positions.
To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPosition. This
works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref
setPixelPosition transforms the coordinates appropriately, to make the position appear at the specified
pixel values.
*/
/* start documentation of inline functions */
/*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const
Returns the current position type.
If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the
type of the X coordinate. In that case rather use \a typeX() and \a typeY().
\see setType
*/
/*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const
Returns the current parent anchor.
If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY),
this method returns the parent anchor of the Y coordinate. In that case rather use \a
parentAnchorX() and \a parentAnchorY().
\see setParentAnchor
*/
/* end documentation of inline functions */
/*!
Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if
you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as
explained in the subclassing section of the QCPAbstractItem documentation.
*/
QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name) :
QCPItemAnchor(parentPlot, parentItem, name),
mPositionTypeX(ptAbsolute),
mPositionTypeY(ptAbsolute),
mKey(0),
mValue(0),
mParentAnchorX(nullptr),
mParentAnchorY(nullptr)
{
}
QCPItemPosition::~QCPItemPosition()
{
// unregister as parent at children:
// Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then
// the setParentAnchor(0) call the correct QCPItemPosition::pixelPosition function instead of QCPItemAnchor::pixelPosition
foreach (QCPItemPosition *child, mChildrenX.values())
{
if (child->parentAnchorX() == this)
child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX
}
foreach (QCPItemPosition *child, mChildrenY.values())
{
if (child->parentAnchorY() == this)
child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY
}
// unregister as child in parent:
if (mParentAnchorX)
mParentAnchorX->removeChildX(this);
if (mParentAnchorY)
mParentAnchorY->removeChildY(this);
}
/* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
QCPAxisRect *QCPItemPosition::axisRect() const
{
return mAxisRect.data();
}
/*!
Sets the type of the position. The type defines how the coordinates passed to \ref setCoords
should be handled and how the QCPItemPosition should behave in the plot.
The possible values for \a type can be separated in two main categories:
\li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords
and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes.
By default, the QCustomPlot's x- and yAxis are used.
\li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This
corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref
ptAxisRectRatio. They differ only in the way the absolute position is described, see the
documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify
the axis rect with \ref setAxisRect. By default this is set to the main axis rect.
Note that the position type \ref ptPlotCoords is only available (and sensible) when the position
has no parent anchor (\ref setParentAnchor).
If the type is changed, the apparent pixel position on the plot is preserved. This means
the coordinates as retrieved with coords() and set with \ref setCoords may change in the process.
This method sets the type for both X and Y directions. It is also possible to set different types
for X and Y, see \ref setTypeX, \ref setTypeY.
*/
void QCPItemPosition::setType(QCPItemPosition::PositionType type)
{
setTypeX(type);
setTypeY(type);
}
/*!
This method sets the position type of the X coordinate to \a type.
For a detailed description of what a position type is, see the documentation of \ref setType.
\see setType, setTypeY
*/
void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type)
{
if (mPositionTypeX != type)
{
// if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
// were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
bool retainPixelPosition = true;
if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
retainPixelPosition = false;
if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
retainPixelPosition = false;
QPointF pixel;
if (retainPixelPosition)
pixel = pixelPosition();
mPositionTypeX = type;
if (retainPixelPosition)
setPixelPosition(pixel);
}
}
/*!
This method sets the position type of the Y coordinate to \a type.
For a detailed description of what a position type is, see the documentation of \ref setType.
\see setType, setTypeX
*/
void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type)
{
if (mPositionTypeY != type)
{
// if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
// were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
bool retainPixelPosition = true;
if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
retainPixelPosition = false;
if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
retainPixelPosition = false;
QPointF pixel;
if (retainPixelPosition)
pixel = pixelPosition();
mPositionTypeY = type;
if (retainPixelPosition)
setPixelPosition(pixel);
}
}
/*!
Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now
follow any position changes of the anchor. The local coordinate system of positions with a parent
anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence
the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.)
if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved
during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position
will be exactly on top of the parent anchor.
To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to \c nullptr.
If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is
set to \ref ptAbsolute, to keep the position in a valid state.
This method sets the parent anchor for both X and Y directions. It is also possible to set
different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY.
*/
bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
{
bool successX = setParentAnchorX(parentAnchor, keepPixelPosition);
bool successY = setParentAnchorY(parentAnchor, keepPixelPosition);
return successX && successY;
}
/*!
This method sets the parent anchor of the X coordinate to \a parentAnchor.
For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
\see setParentAnchor, setParentAnchorY
*/
bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
{
// make sure self is not assigned as parent:
if (parentAnchor == this)
{
qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
// make sure no recursive parent-child-relationships are created:
QCPItemAnchor *currentParent = parentAnchor;
while (currentParent)
{
if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
{
// is a QCPItemPosition, might have further parent, so keep iterating
if (currentParentPos == this)
{
qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
currentParent = currentParentPos->parentAnchorX();
} else
{
// is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
// same, to prevent a position being child of an anchor which itself depends on the position,
// because they're both on the same item:
if (currentParent->mParentItem == mParentItem)
{
qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
break;
}
}
// if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
if (!mParentAnchorX && mPositionTypeX == ptPlotCoords)
setTypeX(ptAbsolute);
// save pixel position:
QPointF pixelP;
if (keepPixelPosition)
pixelP = pixelPosition();
// unregister at current parent anchor:
if (mParentAnchorX)
mParentAnchorX->removeChildX(this);
// register at new parent anchor:
if (parentAnchor)
parentAnchor->addChildX(this);
mParentAnchorX = parentAnchor;
// restore pixel position under new parent:
if (keepPixelPosition)
setPixelPosition(pixelP);
else
setCoords(0, coords().y());
return true;
}
/*!
This method sets the parent anchor of the Y coordinate to \a parentAnchor.
For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
\see setParentAnchor, setParentAnchorX
*/
bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
{
// make sure self is not assigned as parent:
if (parentAnchor == this)
{
qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
// make sure no recursive parent-child-relationships are created:
QCPItemAnchor *currentParent = parentAnchor;
while (currentParent)
{
if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
{
// is a QCPItemPosition, might have further parent, so keep iterating
if (currentParentPos == this)
{
qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
currentParent = currentParentPos->parentAnchorY();
} else
{
// is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
// same, to prevent a position being child of an anchor which itself depends on the position,
// because they're both on the same item:
if (currentParent->mParentItem == mParentItem)
{
qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
break;
}
}
// if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
if (!mParentAnchorY && mPositionTypeY == ptPlotCoords)
setTypeY(ptAbsolute);
// save pixel position:
QPointF pixelP;
if (keepPixelPosition)
pixelP = pixelPosition();
// unregister at current parent anchor:
if (mParentAnchorY)
mParentAnchorY->removeChildY(this);
// register at new parent anchor:
if (parentAnchor)
parentAnchor->addChildY(this);
mParentAnchorY = parentAnchor;
// restore pixel position under new parent:
if (keepPixelPosition)
setPixelPosition(pixelP);
else
setCoords(coords().x(), 0);
return true;
}
/*!
Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type
(\ref setType, \ref setTypeX, \ref setTypeY).
For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position
on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the
QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the
plot coordinate system defined by the axes set by \ref setAxes. By default those are the
QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available
coordinate types and their meaning.
If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a
value must also be provided in the different coordinate systems. Here, the X type refers to \a
key, and the Y type refers to \a value.
\see setPixelPosition
*/
void QCPItemPosition::setCoords(double key, double value)
{
mKey = key;
mValue = value;
}
/*! \overload
Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the
meaning of \a value of the \ref setCoords(double key, double value) method.
*/
void QCPItemPosition::setCoords(const QPointF &pos)
{
setCoords(pos.x(), pos.y());
}
/*!
Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It
includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor).
\see setPixelPosition
*/
QPointF QCPItemPosition::pixelPosition() const
{
QPointF result;
// determine X:
switch (mPositionTypeX)
{
case ptAbsolute:
{
result.rx() = mKey;
if (mParentAnchorX)
result.rx() += mParentAnchorX->pixelPosition().x();
break;
}
case ptViewportRatio:
{
result.rx() = mKey*mParentPlot->viewport().width();
if (mParentAnchorX)
result.rx() += mParentAnchorX->pixelPosition().x();
else
result.rx() += mParentPlot->viewport().left();
break;
}
case ptAxisRectRatio:
{
if (mAxisRect)
{
result.rx() = mKey*mAxisRect.data()->width();
if (mParentAnchorX)
result.rx() += mParentAnchorX->pixelPosition().x();
else
result.rx() += mAxisRect.data()->left();
} else
qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
break;
}
case ptPlotCoords:
{
if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
result.rx() = mKeyAxis.data()->coordToPixel(mKey);
else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
result.rx() = mValueAxis.data()->coordToPixel(mValue);
else
qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
break;
}
}
// determine Y:
switch (mPositionTypeY)
{
case ptAbsolute:
{
result.ry() = mValue;
if (mParentAnchorY)
result.ry() += mParentAnchorY->pixelPosition().y();
break;
}
case ptViewportRatio:
{
result.ry() = mValue*mParentPlot->viewport().height();
if (mParentAnchorY)
result.ry() += mParentAnchorY->pixelPosition().y();
else
result.ry() += mParentPlot->viewport().top();
break;
}
case ptAxisRectRatio:
{
if (mAxisRect)
{
result.ry() = mValue*mAxisRect.data()->height();
if (mParentAnchorY)
result.ry() += mParentAnchorY->pixelPosition().y();
else
result.ry() += mAxisRect.data()->top();
} else
qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
break;
}
case ptPlotCoords:
{
if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
result.ry() = mKeyAxis.data()->coordToPixel(mKey);
else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
result.ry() = mValueAxis.data()->coordToPixel(mValue);
else
qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
break;
}
}
return result;
}
/*!
When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the
coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and
yAxis of the QCustomPlot.
*/
void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis)
{
mKeyAxis = keyAxis;
mValueAxis = valueAxis;
}
/*!
When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the
coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of
the QCustomPlot.
*/
void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect)
{
mAxisRect = axisRect;
}
/*!
Sets the apparent pixel position. This works no matter what type (\ref setType) this
QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed
appropriately, to make the position finally appear at the specified pixel values.
Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is
identical to that of \ref setCoords.
\see pixelPosition, setCoords
*/
void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition)
{
double x = pixelPosition.x();
double y = pixelPosition.y();
switch (mPositionTypeX)
{
case ptAbsolute:
{
if (mParentAnchorX)
x -= mParentAnchorX->pixelPosition().x();
break;
}
case ptViewportRatio:
{
if (mParentAnchorX)
x -= mParentAnchorX->pixelPosition().x();
else
x -= mParentPlot->viewport().left();
x /= double(mParentPlot->viewport().width());
break;
}
case ptAxisRectRatio:
{
if (mAxisRect)
{
if (mParentAnchorX)
x -= mParentAnchorX->pixelPosition().x();
else
x -= mAxisRect.data()->left();
x /= double(mAxisRect.data()->width());
} else
qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
break;
}
case ptPlotCoords:
{
if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
x = mKeyAxis.data()->pixelToCoord(x);
else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
y = mValueAxis.data()->pixelToCoord(x);
else
qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
break;
}
}
switch (mPositionTypeY)
{
case ptAbsolute:
{
if (mParentAnchorY)
y -= mParentAnchorY->pixelPosition().y();
break;
}
case ptViewportRatio:
{
if (mParentAnchorY)
y -= mParentAnchorY->pixelPosition().y();
else
y -= mParentPlot->viewport().top();
y /= double(mParentPlot->viewport().height());
break;
}
case ptAxisRectRatio:
{
if (mAxisRect)
{
if (mParentAnchorY)
y -= mParentAnchorY->pixelPosition().y();
else
y -= mAxisRect.data()->top();
y /= double(mAxisRect.data()->height());
} else
qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
break;
}
case ptPlotCoords:
{
if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
x = mKeyAxis.data()->pixelToCoord(y);
else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
y = mValueAxis.data()->pixelToCoord(y);
else
qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
break;
}
}
setCoords(x, y);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAbstractItem
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAbstractItem
\brief The abstract base class for all items in a plot.
In QCustomPlot, items are supplemental graphical elements that are neither plottables
(QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus
plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each
specific item has at least one QCPItemPosition member which controls the positioning. Some items
are defined by more than one coordinate and thus have two or more QCPItemPosition members (For
example, QCPItemRect has \a topLeft and \a bottomRight).
This abstract base class defines a very basic interface like visibility and clipping. Since this
class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass
yourself to create new items.
The built-in items are:
<table>
<tr><td>QCPItemLine</td><td>A line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).</td></tr>
<tr><td>QCPItemStraightLine</td><td>A straight line defined by a start and a direction point. Unlike QCPItemLine, the straight line is infinitely long and has no endings.</td></tr>
<tr><td>QCPItemCurve</td><td>A curve defined by start, end and two intermediate control points. May have different ending styles on each side (e.g. arrows).</td></tr>
<tr><td>QCPItemRect</td><td>A rectangle</td></tr>
<tr><td>QCPItemEllipse</td><td>An ellipse</td></tr>
<tr><td>QCPItemPixmap</td><td>An arbitrary pixmap</td></tr>
<tr><td>QCPItemText</td><td>A text label</td></tr>
<tr><td>QCPItemBracket</td><td>A bracket which may be used to reference/highlight certain parts in the plot.</td></tr>
<tr><td>QCPItemTracer</td><td>An item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.</td></tr>
</table>
\section items-clipping Clipping
Items are by default clipped to the main axis rect (they are only visible inside the axis rect).
To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect
"setClipToAxisRect(false)".
On the other hand if you want the item to be clipped to a different axis rect, specify it via
\ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour, and
in principle is independent of the coordinate axes the item might be tied to via its position
members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping
also contains the axes used for the item positions.
\section items-using Using items
First you instantiate the item you want to use and add it to the plot:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1
by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just
set the plot coordinates where the line should start/end:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-2
If we don't want the line to be positioned in plot coordinates but a different coordinate system,
e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-3
Then we can set the coordinates, this time in pixels:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4
and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5
For more advanced plots, it is even possible to set different types and parent anchors per X/Y
coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref
QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition.
\section items-subclassing Creating own items
To create an own item, you implement a subclass of QCPAbstractItem. These are the pure
virtual functions, you must implement:
\li \ref selectTest
\li \ref draw
See the documentation of those functions for what they need to do.
\subsection items-positioning Allowing the item to be positioned
As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall
have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add
a public member of type QCPItemPosition like so:
\code QCPItemPosition * const myPosition;\endcode
the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition
instance it points to, can be modified, of course).
The initialization of this pointer is made easy with the \ref createPosition function. Just assign
the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition
takes a string which is the name of the position, typically this is identical to the variable name.
For example, the constructor of QCPItemExample could look like this:
\code
QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
myPosition(createPosition("myPosition"))
{
// other constructor code
}
\endcode
\subsection items-drawing The draw function
To give your item a visual representation, reimplement the \ref draw function and use the passed
QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the
position member(s) via \ref QCPItemPosition::pixelPosition.
To optimize performance you should calculate a bounding rect first (don't forget to take the pen
width into account), check whether it intersects the \ref clipRect, and only draw the item at all
if this is the case.
\subsection items-selection The selectTest function
Your implementation of the \ref selectTest function may use the helpers \ref
QCPVector2D::distanceSquaredToLine and \ref rectDistance. With these, the implementation of the
selection test becomes significantly simpler for most items. See the documentation of \ref
selectTest for what the function parameters mean and what the function should return.
\subsection anchors Providing anchors
Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public
member, e.g.
\code QCPItemAnchor * const bottom;\endcode
and create it in the constructor with the \ref createAnchor function, assigning it a name and an
anchor id (an integer enumerating all anchors on the item, you may create an own enum for this).
Since anchors can be placed anywhere, relative to the item's position(s), your item needs to
provide the position of every anchor with the reimplementation of the \ref anchorPixelPosition(int
anchorId) function.
In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel
position when anything attached to the anchor needs to know the coordinates.
*/
/* start of documentation of inline functions */
/*! \fn QList<QCPItemPosition*> QCPAbstractItem::positions() const
Returns all positions of the item in a list.
\see anchors, position
*/
/*! \fn QList<QCPItemAnchor*> QCPAbstractItem::anchors() const
Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always
also an anchor, the list will also contain the positions of this item.
\see positions, anchor
*/
/* end of documentation of inline functions */
/* start documentation of pure virtual functions */
/*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0
\internal
Draws this item with the provided \a painter.
The cliprect of the provided painter is set to the rect returned by \ref clipRect before this
function is called. The clipRect depends on the clipping settings defined by \ref
setClipToAxisRect and \ref setClipAxisRect.
*/
/* end documentation of pure virtual functions */
/* start documentation of signals */
/*! \fn void QCPAbstractItem::selectionChanged(bool selected)
This signal is emitted when the selection state of this item has changed, either by user interaction
or by a direct call to \ref setSelected.
*/
/* end documentation of signals */
/*!
Base class constructor which initializes base class members.
*/
QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) :
QCPLayerable(parentPlot),
mClipToAxisRect(false),
mSelectable(true),
mSelected(false)
{
parentPlot->registerItem(this);
QList<QCPAxisRect*> rects = parentPlot->axisRects();
if (!rects.isEmpty())
{
setClipToAxisRect(true);
setClipAxisRect(rects.first());
}
}
QCPAbstractItem::~QCPAbstractItem()
{
// don't delete mPositions because every position is also an anchor and thus in mAnchors
qDeleteAll(mAnchors);
}
/* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
QCPAxisRect *QCPAbstractItem::clipAxisRect() const
{
return mClipAxisRect.data();
}
/*!
Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the
entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect.
\see setClipAxisRect
*/
void QCPAbstractItem::setClipToAxisRect(bool clip)
{
mClipToAxisRect = clip;
if (mClipToAxisRect)
setParentLayerable(mClipAxisRect.data());
}
/*!
Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref
setClipToAxisRect is set to true.
\see setClipToAxisRect
*/
void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect)
{
mClipAxisRect = rect;
if (mClipToAxisRect)
setParentLayerable(mClipAxisRect.data());
}
/*!
Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface.
(When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.)
However, even when \a selectable was set to false, it is possible to set the selection manually,
by calling \ref setSelected.
\see QCustomPlot::setInteractions, setSelected
*/
void QCPAbstractItem::setSelectable(bool selectable)
{
if (mSelectable != selectable)
{
mSelectable = selectable;
emit selectableChanged(mSelectable);
}
}
/*!
Sets whether this item is selected or not. When selected, it might use a different visual
appearance (e.g. pen and brush), this depends on the specific item though.
The entire selection mechanism for items is handled automatically when \ref
QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this
function when you wish to change the selection state manually.
This function can change the selection state even when \ref setSelectable was set to false.
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
\see setSelectable, selectTest
*/
void QCPAbstractItem::setSelected(bool selected)
{
if (mSelected != selected)
{
mSelected = selected;
emit selectionChanged(mSelected);
}
}
/*!
Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by
that name, returns \c nullptr.
This function provides an alternative way to access item positions. Normally, you access
positions direcly by their member pointers (which typically have the same variable name as \a
name).
\see positions, anchor
*/
QCPItemPosition *QCPAbstractItem::position(const QString &name) const
{
foreach (QCPItemPosition *position, mPositions)
{
if (position->name() == name)
return position;
}
qDebug() << Q_FUNC_INFO << "position with name not found:" << name;
return nullptr;
}
/*!
Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by
that name, returns \c nullptr.
This function provides an alternative way to access item anchors. Normally, you access
anchors direcly by their member pointers (which typically have the same variable name as \a
name).
\see anchors, position
*/
QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const
{
foreach (QCPItemAnchor *anchor, mAnchors)
{
if (anchor->name() == name)
return anchor;
}
qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name;
return nullptr;
}
/*!
Returns whether this item has an anchor with the specified \a name.
Note that you can check for positions with this function, too. This is because every position is
also an anchor (QCPItemPosition inherits from QCPItemAnchor).
\see anchor, position
*/
bool QCPAbstractItem::hasAnchor(const QString &name) const
{
foreach (QCPItemAnchor *anchor, mAnchors)
{
if (anchor->name() == name)
return true;
}
return false;
}
/*! \internal
Returns the rect the visual representation of this item is clipped to. This depends on the
current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect.
If the item is not clipped to an axis rect, QCustomPlot's viewport rect is returned.
\see draw
*/
QRect QCPAbstractItem::clipRect() const
{
if (mClipToAxisRect && mClipAxisRect)
return mClipAxisRect.data()->rect();
else
return mParentPlot->viewport();
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing item lines.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased
*/
void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeItems);
}
/*! \internal
A convenience function which returns the selectTest value for a specified \a rect and a specified
click position \a pos. \a filledRect defines whether a click inside the rect should also be
considered a hit or whether only the rect border is sensitive to hits.
This function may be used to help with the implementation of the \ref selectTest function for
specific items.
For example, if your item consists of four rects, call this function four times, once for each
rect, in your \ref selectTest reimplementation. Finally, return the minimum (non -1) of all four
returned values.
*/
double QCPAbstractItem::rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const
{
double result = -1;
// distance to border:
const QList<QLineF> lines = QList<QLineF>() << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight())
<< QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight());
const QCPVector2D posVec(pos);
double minDistSqr = (std::numeric_limits<double>::max)();
foreach (const QLineF &line, lines)
{
double distSqr = posVec.distanceSquaredToLine(line.p1(), line.p2());
if (distSqr < minDistSqr)
minDistSqr = distSqr;
}
result = qSqrt(minDistSqr);
// filled rect, allow click inside to count as hit:
if (filledRect && result > mParentPlot->selectionTolerance()*0.99)
{
if (rect.contains(pos))
result = mParentPlot->selectionTolerance()*0.99;
}
return result;
}
/*! \internal
Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in
item subclasses if they want to provide anchors (QCPItemAnchor).
For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor
ids and returns the respective pixel points of the specified anchor.
\see createAnchor
*/
QPointF QCPAbstractItem::anchorPixelPosition(int anchorId) const
{
qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId;
return {};
}
/*! \internal
Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified
\a name must be a unique string that is usually identical to the variable name of the position
member (This is needed to provide the name-based \ref position access to positions).
Don't delete positions created by this function manually, as the item will take care of it.
Use this function in the constructor (initialization list) of the specific item subclass to
create each position member. Don't create QCPItemPositions with \b new yourself, because they
won't be registered with the item properly.
\see createAnchor
*/
QCPItemPosition *QCPAbstractItem::createPosition(const QString &name)
{
if (hasAnchor(name))
qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name);
mPositions.append(newPosition);
mAnchors.append(newPosition); // every position is also an anchor
newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis);
newPosition->setType(QCPItemPosition::ptPlotCoords);
if (mParentPlot->axisRect())
newPosition->setAxisRect(mParentPlot->axisRect());
newPosition->setCoords(0, 0);
return newPosition;
}
/*! \internal
Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified
\a name must be a unique string that is usually identical to the variable name of the anchor
member (This is needed to provide the name based \ref anchor access to anchors).
The \a anchorId must be a number identifying the created anchor. It is recommended to create an
enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor
to identify itself when it calls QCPAbstractItem::anchorPixelPosition. That function then returns
the correct pixel coordinates for the passed anchor id.
Don't delete anchors created by this function manually, as the item will take care of it.
Use this function in the constructor (initialization list) of the specific item subclass to
create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they
won't be registered with the item properly.
\see createPosition
*/
QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId)
{
if (hasAnchor(name))
qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId);
mAnchors.append(newAnchor);
return newAnchor;
}
/* inherits documentation from base class */
void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(details)
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(additive ? !mSelected : true);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
void QCPAbstractItem::deselectEvent(bool *selectionStateChanged)
{
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(false);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
QCP::Interaction QCPAbstractItem::selectionCategory() const
{
return QCP::iSelectItems;
}
/* end of 'src/item.cpp' */
/* including file 'src/core.cpp' */
/* modified 2022-11-06T12:45:56, size 127625 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCustomPlot
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCustomPlot
\brief The central class of the library. This is the QWidget which displays the plot and
interacts with the user.
For tutorials on how to use QCustomPlot, see the website\n
https://www.qcustomplot.com/
*/
/* start of documentation of inline functions */
/*! \fn QCPSelectionRect *QCustomPlot::selectionRect() const
Allows access to the currently used QCPSelectionRect instance (or subclass thereof), that is used
to handle and draw selection rect interactions (see \ref setSelectionRectMode).
\see setSelectionRect
*/
/*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const
Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just
one cell with the main QCPAxisRect inside.
*/
/* end of documentation of inline functions */
/* start of documentation of signals */
/*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse double click event.
*/
/*! \fn void QCustomPlot::mousePress(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse press event.
It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
QCPAxisRect::setRangeDragAxes.
*/
/*! \fn void QCustomPlot::mouseMove(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse move event.
It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
QCPAxisRect::setRangeDragAxes.
\warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here,
because the dragging starting point was saved the moment the mouse was pressed. Thus it only has
a meaning for the range drag axes that were set at that moment. If you want to change the drag
axes, consider doing this in the \ref mousePress signal instead.
*/
/*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse release event.
It is emitted before QCustomPlot handles any other mechanisms like object selection. So a
slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or
\ref QCPAbstractPlottable::setSelectable.
*/
/*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse wheel event.
It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot
connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref
QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor.
*/
/*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
This signal is emitted when a plottable is clicked.
\a event is the mouse event that caused the click and \a plottable is the plottable that received
the click. The parameter \a dataIndex indicates the data point that was closest to the click
position.
\see plottableDoubleClick
*/
/*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
This signal is emitted when a plottable is double clicked.
\a event is the mouse event that caused the click and \a plottable is the plottable that received
the click. The parameter \a dataIndex indicates the data point that was closest to the click
position.
\see plottableClick
*/
/*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event)
This signal is emitted when an item is clicked.
\a event is the mouse event that caused the click and \a item is the item that received the
click.
\see itemDoubleClick
*/
/*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event)
This signal is emitted when an item is double clicked.
\a event is the mouse event that caused the click and \a item is the item that received the
click.
\see itemClick
*/
/*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
This signal is emitted when an axis is clicked.
\a event is the mouse event that caused the click, \a axis is the axis that received the click and
\a part indicates the part of the axis that was clicked.
\see axisDoubleClick
*/
/*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
This signal is emitted when an axis is double clicked.
\a event is the mouse event that caused the click, \a axis is the axis that received the click and
\a part indicates the part of the axis that was clicked.
\see axisClick
*/
/*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
This signal is emitted when a legend (item) is clicked.
\a event is the mouse event that caused the click, \a legend is the legend that received the
click and \a item is the legend item that received the click. If only the legend and no item is
clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space
between two items.
\see legendDoubleClick
*/
/*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
This signal is emitted when a legend (item) is double clicked.
\a event is the mouse event that caused the click, \a legend is the legend that received the
click and \a item is the legend item that received the click. If only the legend and no item is
clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space
between two items.
\see legendClick
*/
/*! \fn void QCustomPlot::selectionChangedByUser()
This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by
clicking. It is not emitted when the selection state of an object has changed programmatically by
a direct call to <tt>setSelected()</tt>/<tt>setSelection()</tt> on an object or by calling \ref
deselectAll.
In addition to this signal, selectable objects also provide individual signals, for example \ref
QCPAxis::selectionChanged or \ref QCPAbstractPlottable::selectionChanged. Note that those signals
are emitted even if the selection state is changed programmatically.
See the documentation of \ref setInteractions for details about the selection mechanism.
\see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends
*/
/*! \fn void QCustomPlot::beforeReplot()
This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref
replot).
It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
replot synchronously, it won't cause an infinite recursion.
\see replot, afterReplot, afterLayout
*/
/*! \fn void QCustomPlot::afterLayout()
This signal is emitted immediately after the layout step has been completed, which occurs right
before drawing the plot. This is typically during a call to \ref replot, and in such cases this
signal is emitted in between the signals \ref beforeReplot and \ref afterReplot. Unlike those
signals however, this signal is also emitted during off-screen painting, such as when calling
\ref toPixmap or \ref savePdf.
The layout step queries all layouts and layout elements in the plot for their proposed size and
arranges the objects accordingly as preparation for the subsequent drawing step. Through this
signal, you have the opportunity to update certain things in your plot that depend crucially on
the exact dimensions/positioning of layout elements such as axes and axis rects.
\warning However, changing any parameters of this QCustomPlot instance which would normally
affect the layouting (e.g. axis range order of magnitudes, tick label sizes, etc.) will not issue
a second run of the layout step. It will propagate directly to the draw step and may cause
graphical inconsistencies such as overlapping objects, if sizes or positions have changed.
\see updateLayout, beforeReplot, afterReplot
*/
/*! \fn void QCustomPlot::afterReplot()
This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref
replot).
It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
replot synchronously, it won't cause an infinite recursion.
\see replot, beforeReplot, afterLayout
*/
/* end of documentation of signals */
/* start of documentation of public members */
/*! \var QCPAxis *QCustomPlot::xAxis
A pointer to the primary x Axis (bottom) of the main axis rect of the plot.
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become \c nullptr.
If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
is added after the main legend was removed before.
*/
/*! \var QCPAxis *QCustomPlot::yAxis
A pointer to the primary y Axis (left) of the main axis rect of the plot.
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become \c nullptr.
If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
is added after the main legend was removed before.
*/
/*! \var QCPAxis *QCustomPlot::xAxis2
A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are
invisible by default. Use QCPAxis::setVisible to change this (or use \ref
QCPAxisRect::setupFullAxesBox).
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become \c nullptr.
If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
is added after the main legend was removed before.
*/
/*! \var QCPAxis *QCustomPlot::yAxis2
A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are
invisible by default. Use QCPAxis::setVisible to change this (or use \ref
QCPAxisRect::setupFullAxesBox).
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become \c nullptr.
If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
is added after the main legend was removed before.
*/
/*! \var QCPLegend *QCustomPlot::legend
A pointer to the default legend of the main axis rect. The legend is invisible by default. Use
QCPLegend::setVisible to change this.
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple legends to the plot, use the layout system interface to
access the new legend. For example, legends can be placed inside an axis rect's \ref
QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If
the default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointer becomes \c nullptr.
If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
is added after the main legend was removed before.
*/
/* end of documentation of public members */
/*!
Constructs a QCustomPlot and sets reasonable default values.
*/
QCustomPlot::QCustomPlot(QWidget *parent) :
QWidget(parent),
xAxis(nullptr),
yAxis(nullptr),
xAxis2(nullptr),
yAxis2(nullptr),
legend(nullptr),
mBufferDevicePixelRatio(1.0), // will be adapted to true value below
mPlotLayout(nullptr),
mAutoAddPlottableToLegend(true),
mAntialiasedElements(QCP::aeNone),
mNotAntialiasedElements(QCP::aeNone),
mInteractions(QCP::iNone),
mSelectionTolerance(8),
mNoAntialiasingOnDrag(false),
mBackgroundBrush(Qt::white, Qt::SolidPattern),
mBackgroundScaled(true),
mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
mCurrentLayer(nullptr),
mPlottingHints(QCP::phCacheLabels|QCP::phImmediateRefresh),
mMultiSelectModifier(Qt::ControlModifier),
mSelectionRectMode(QCP::srmNone),
mSelectionRect(nullptr),
mOpenGl(false),
mMouseHasMoved(false),
mMouseEventLayerable(nullptr),
mMouseSignalLayerable(nullptr),
mReplotting(false),
mReplotQueued(false),
mReplotTime(0),
mReplotTimeAverage(0),
mOpenGlMultisamples(16),
mOpenGlAntialiasedElementsBackup(QCP::aeNone),
mOpenGlCacheLabelsBackup(true)
{
setAttribute(Qt::WA_NoMousePropagation);
setFocusPolicy(Qt::ClickFocus);
setMouseTracking(true);
QLocale currentLocale = locale();
currentLocale.setNumberOptions(QLocale::OmitGroupSeparator);
setLocale(currentLocale);
#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
# ifdef QCP_DEVICEPIXELRATIO_FLOAT
setBufferDevicePixelRatio(QWidget::devicePixelRatioF());
# else
setBufferDevicePixelRatio(QWidget::devicePixelRatio());
# endif
#endif
mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
// create initial layers:
mLayers.append(new QCPLayer(this, QLatin1String("background")));
mLayers.append(new QCPLayer(this, QLatin1String("grid")));
mLayers.append(new QCPLayer(this, QLatin1String("main")));
mLayers.append(new QCPLayer(this, QLatin1String("axes")));
mLayers.append(new QCPLayer(this, QLatin1String("legend")));
mLayers.append(new QCPLayer(this, QLatin1String("overlay")));
updateLayerIndices();
setCurrentLayer(QLatin1String("main"));
layer(QLatin1String("overlay"))->setMode(QCPLayer::lmBuffered);
// create initial layout, axis rect and legend:
mPlotLayout = new QCPLayoutGrid;
mPlotLayout->initializeParentPlot(this);
mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry
mPlotLayout->setLayer(QLatin1String("main"));
QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true);
mPlotLayout->addElement(0, 0, defaultAxisRect);
xAxis = defaultAxisRect->axis(QCPAxis::atBottom);
yAxis = defaultAxisRect->axis(QCPAxis::atLeft);
xAxis2 = defaultAxisRect->axis(QCPAxis::atTop);
yAxis2 = defaultAxisRect->axis(QCPAxis::atRight);
legend = new QCPLegend;
legend->setVisible(false);
defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop);
defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12));
defaultAxisRect->setLayer(QLatin1String("background"));
xAxis->setLayer(QLatin1String("axes"));
yAxis->setLayer(QLatin1String("axes"));
xAxis2->setLayer(QLatin1String("axes"));
yAxis2->setLayer(QLatin1String("axes"));
xAxis->grid()->setLayer(QLatin1String("grid"));
yAxis->grid()->setLayer(QLatin1String("grid"));
xAxis2->grid()->setLayer(QLatin1String("grid"));
yAxis2->grid()->setLayer(QLatin1String("grid"));
legend->setLayer(QLatin1String("legend"));
// create selection rect instance:
mSelectionRect = new QCPSelectionRect(this);
mSelectionRect->setLayer(QLatin1String("overlay"));
setViewport(rect()); // needs to be called after mPlotLayout has been created
replot(rpQueuedReplot);
}
QCustomPlot::~QCustomPlot()
{
clearPlottables();
clearItems();
if (mPlotLayout)
{
delete mPlotLayout;
mPlotLayout = nullptr;
}
mCurrentLayer = nullptr;
qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed
mLayers.clear();
}
/*!
Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement.
This overrides the antialiasing settings for whole element groups, normally controlled with the
\a setAntialiasing function on the individual elements. If an element is neither specified in
\ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
each individual element instance is used.
For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be
drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
to.
if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is
removed from there.
\see setNotAntialiasedElements
*/
void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements)
{
mAntialiasedElements = antialiasedElements;
// make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
mNotAntialiasedElements |= ~mAntialiasedElements;
}
/*!
Sets whether the specified \a antialiasedElement is forcibly drawn antialiased.
See \ref setAntialiasedElements for details.
\see setNotAntialiasedElement
*/
void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled)
{
if (!enabled && mAntialiasedElements.testFlag(antialiasedElement))
mAntialiasedElements &= ~antialiasedElement;
else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement))
mAntialiasedElements |= antialiasedElement;
// make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
mNotAntialiasedElements |= ~mAntialiasedElements;
}
/*!
Sets which elements are forcibly drawn not antialiased as an \a or combination of
QCP::AntialiasedElement.
This overrides the antialiasing settings for whole element groups, normally controlled with the
\a setAntialiasing function on the individual elements. If an element is neither specified in
\ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
each individual element instance is used.
For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be
drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
to.
if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is
removed from there.
\see setAntialiasedElements
*/
void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements)
{
mNotAntialiasedElements = notAntialiasedElements;
// make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
mAntialiasedElements |= ~mNotAntialiasedElements;
}
/*!
Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased.
See \ref setNotAntialiasedElements for details.
\see setAntialiasedElement
*/
void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled)
{
if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement))
mNotAntialiasedElements &= ~notAntialiasedElement;
else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement))
mNotAntialiasedElements |= notAntialiasedElement;
// make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
mAntialiasedElements |= ~mNotAntialiasedElements;
}
/*!
If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the
plottable to the legend (QCustomPlot::legend).
\see addGraph, QCPLegend::addItem
*/
void QCustomPlot::setAutoAddPlottableToLegend(bool on)
{
mAutoAddPlottableToLegend = on;
}
/*!
Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction
enums. There are the following types of interactions:
<b>Axis range manipulation</b> is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the
respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel.
For details how to control which axes the user may drag/zoom and in what orientations, see \ref
QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes,
\ref QCPAxisRect::setRangeZoomAxes.
<b>Plottable data selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref
QCP::iSelectPlottables is set, the user may select plottables (graphs, curves, bars,...) and
their data by clicking on them or in their vicinity (\ref setSelectionTolerance). Whether the
user can actually select a plottable and its data can further be restricted with the \ref
QCPAbstractPlottable::setSelectable method on the specific plottable. For details, see the
special page about the \ref dataselection "data selection mechanism". To retrieve a list of all
currently selected plottables, call \ref selectedPlottables. If you're only interested in
QCPGraphs, you may use the convenience function \ref selectedGraphs.
<b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user
may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find
out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of
all currently selected items, call \ref selectedItems.
<b>Axis selection</b> is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user
may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick
labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for
each axis. To retrieve a list of all axes that currently contain selected parts, call \ref
selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts().
<b>Legend selection</b> is controlled with \ref QCP::iSelectLegend. If this is set, the user may
select the legend itself or individual items by clicking on them. What parts exactly are
selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the
legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To
find out which child items are selected, call \ref QCPLegend::selectedItems.
<b>All other selectable elements</b> The selection of all other selectable objects (e.g.
QCPTextElement, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the
user may select those objects by clicking on them. To find out which are currently selected, you
need to check their selected state explicitly.
If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is
emitted. Each selectable object additionally emits an individual selectionChanged signal whenever
their selection state has changed, i.e. not only by user interaction.
To allow multiple objects to be selected by holding the selection modifier (\ref
setMultiSelectModifier), set the flag \ref QCP::iMultiSelect.
\note In addition to the selection mechanism presented here, QCustomPlot always emits
corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and
\ref plottableDoubleClick for example.
\see setInteraction, setSelectionTolerance
*/
void QCustomPlot::setInteractions(const QCP::Interactions &interactions)
{
mInteractions = interactions;
}
/*!
Sets the single \a interaction of this QCustomPlot to \a enabled.
For details about the interaction system, see \ref setInteractions.
\see setInteractions
*/
void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled)
{
if (!enabled && mInteractions.testFlag(interaction))
mInteractions &= ~interaction;
else if (enabled && !mInteractions.testFlag(interaction))
mInteractions |= interaction;
}
/*!
Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or
not.
If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a
potential selection when the minimum distance between the click position and the graph line is
smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks
directly inside the area and ignore this selection tolerance. In other words, it only has meaning
for parts of objects that are too thin to exactly hit with a click and thus need such a
tolerance.
\see setInteractions, QCPLayerable::selectTest
*/
void QCustomPlot::setSelectionTolerance(int pixels)
{
mSelectionTolerance = pixels;
}
/*!
Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes
ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves
performance during dragging. Thus it creates a more responsive user experience. As soon as the
user stops dragging, the last replot is done with normal antialiasing, to restore high image
quality.
\see setAntialiasedElements, setNotAntialiasedElements
*/
void QCustomPlot::setNoAntialiasingOnDrag(bool enabled)
{
mNoAntialiasingOnDrag = enabled;
}
/*!
Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint.
\see setPlottingHint
*/
void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints)
{
mPlottingHints = hints;
}
/*!
Sets the specified plotting \a hint to \a enabled.
\see setPlottingHints
*/
void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled)
{
QCP::PlottingHints newHints = mPlottingHints;
if (!enabled)
newHints &= ~hint;
else
newHints |= hint;
if (newHints != mPlottingHints)
setPlottingHints(newHints);
}
/*!
Sets the keyboard modifier that will be recognized as multi-select-modifier.
If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple
objects (or data points) by clicking on them one after the other while holding down \a modifier.
By default the multi-select-modifier is set to Qt::ControlModifier.
\see setInteractions
*/
void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier)
{
mMultiSelectModifier = modifier;
}
/*!
Sets how QCustomPlot processes mouse click-and-drag interactions by the user.
If \a mode is \ref QCP::srmNone, the mouse drag is forwarded to the underlying objects. For
example, QCPAxisRect may process a mouse drag by dragging axis ranges, see \ref
QCPAxisRect::setRangeDrag. If \a mode is not \ref QCP::srmNone, the current selection rect (\ref
selectionRect) becomes activated and allows e.g. rect zooming and data point selection.
If you wish to provide your user both with axis range dragging and data selection/range zooming,
use this method to switch between the modes just before the interaction is processed, e.g. in
reaction to the \ref mousePress or \ref mouseMove signals. For example you could check whether
the user is holding a certain keyboard modifier, and then decide which \a mode shall be set.
If a selection rect interaction is currently active, and \a mode is set to \ref QCP::srmNone, the
interaction is canceled (\ref QCPSelectionRect::cancel). Switching between any of the other modes
will keep the selection rect active. Upon completion of the interaction, the behaviour is as
defined by the currently set \a mode, not the mode that was set when the interaction started.
\see setInteractions, setSelectionRect, QCPSelectionRect
*/
void QCustomPlot::setSelectionRectMode(QCP::SelectionRectMode mode)
{
if (mSelectionRect)
{
if (mode == QCP::srmNone)
mSelectionRect->cancel(); // when switching to none, we immediately want to abort a potentially active selection rect
// disconnect old connections:
if (mSelectionRectMode == QCP::srmSelect)
disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
else if (mSelectionRectMode == QCP::srmZoom)
disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
// establish new ones:
if (mode == QCP::srmSelect)
connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
else if (mode == QCP::srmZoom)
connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
}
mSelectionRectMode = mode;
}
/*!
Sets the \ref QCPSelectionRect instance that QCustomPlot will use if \a mode is not \ref
QCP::srmNone and the user performs a click-and-drag interaction. QCustomPlot takes ownership of
the passed \a selectionRect. It can be accessed later via \ref selectionRect.
This method is useful if you wish to replace the default QCPSelectionRect instance with an
instance of a QCPSelectionRect subclass, to introduce custom behaviour of the selection rect.
\see setSelectionRectMode
*/
void QCustomPlot::setSelectionRect(QCPSelectionRect *selectionRect)
{
delete mSelectionRect;
mSelectionRect = selectionRect;
if (mSelectionRect)
{
// establish connections with new selection rect:
if (mSelectionRectMode == QCP::srmSelect)
connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
else if (mSelectionRectMode == QCP::srmZoom)
connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
}
}
/*!
\warning This is still an experimental feature and its performance depends on the system that it
runs on. Having multiple QCustomPlot widgets in one application with enabled OpenGL rendering
might cause context conflicts on some systems.
This method allows to enable OpenGL plot rendering, for increased plotting performance of
graphically demanding plots (thick lines, translucent fills, etc.).
If \a enabled is set to true, QCustomPlot will try to initialize OpenGL and, if successful,
continue plotting with hardware acceleration. The parameter \a multisampling controls how many
samples will be used per pixel, it essentially controls the antialiasing quality. If \a
multisampling is set too high for the current graphics hardware, the maximum allowed value will
be used.
You can test whether switching to OpenGL rendering was successful by checking whether the
according getter \a QCustomPlot::openGl() returns true. If the OpenGL initialization fails,
rendering continues with the regular software rasterizer, and an according qDebug output is
generated.
If switching to OpenGL was successful, this method disables label caching (\ref setPlottingHint
"setPlottingHint(QCP::phCacheLabels, false)") and turns on QCustomPlot's antialiasing override
for all elements (\ref setAntialiasedElements "setAntialiasedElements(QCP::aeAll)"), leading to a
higher quality output. The antialiasing override allows for pixel-grid aligned drawing in the
OpenGL paint device. As stated before, in OpenGL rendering the actual antialiasing of the plot is
controlled with \a multisampling. If \a enabled is set to false, the antialiasing/label caching
settings are restored to what they were before OpenGL was enabled, if they weren't altered in the
meantime.
\note OpenGL support is only enabled if QCustomPlot is compiled with the macro \c QCUSTOMPLOT_USE_OPENGL
defined. This define must be set before including the QCustomPlot header both during compilation
of the QCustomPlot library as well as when compiling your application. It is best to just include
the line <tt>DEFINES += QCUSTOMPLOT_USE_OPENGL</tt> in the respective qmake project files.
\note If you are using a Qt version before 5.0, you must also add the module "opengl" to your \c
QT variable in the qmake project files. For Qt versions 5.0 and higher, QCustomPlot switches to a
newer OpenGL interface which is already in the "gui" module.
*/
void QCustomPlot::setOpenGl(bool enabled, int multisampling)
{
mOpenGlMultisamples = qMax(0, multisampling);
#ifdef QCUSTOMPLOT_USE_OPENGL
mOpenGl = enabled;
if (mOpenGl)
{
if (setupOpenGl())
{
// backup antialiasing override and labelcaching setting so we can restore upon disabling OpenGL
mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
// set antialiasing override to antialias all (aligns gl pixel grid properly), and disable label caching (would use software rasterizer for pixmap caches):
setAntialiasedElements(QCP::aeAll);
setPlottingHint(QCP::phCacheLabels, false);
} else
{
qDebug() << Q_FUNC_INFO << "Failed to enable OpenGL, continuing plotting without hardware acceleration.";
mOpenGl = false;
}
} else
{
// restore antialiasing override and labelcaching to what it was before enabling OpenGL, if nobody changed it in the meantime:
if (mAntialiasedElements == QCP::aeAll)
setAntialiasedElements(mOpenGlAntialiasedElementsBackup);
if (!mPlottingHints.testFlag(QCP::phCacheLabels))
setPlottingHint(QCP::phCacheLabels, mOpenGlCacheLabelsBackup);
freeOpenGl();
}
// recreate all paint buffers:
mPaintBuffers.clear();
setupPaintBuffers();
#else
Q_UNUSED(enabled)
qDebug() << Q_FUNC_INFO << "QCustomPlot can't use OpenGL because QCUSTOMPLOT_USE_OPENGL was not defined during compilation (add 'DEFINES += QCUSTOMPLOT_USE_OPENGL' to your qmake .pro file)";
#endif
}
/*!
Sets the viewport of this QCustomPlot. Usually users of QCustomPlot don't need to change the
viewport manually.
The viewport is the area in which the plot is drawn. All mechanisms, e.g. margin calculation take
the viewport to be the outer border of the plot. The viewport normally is the rect() of the
QCustomPlot widget, i.e. a rect with top left (0, 0) and size of the QCustomPlot widget.
Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
and contains also the axes themselves, their tick numbers, their labels, or even additional axis
rects, color scales and other layout elements.
This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref
savePdf, etc. by temporarily changing the viewport size.
*/
void QCustomPlot::setViewport(const QRect &rect)
{
mViewport = rect;
if (mPlotLayout)
mPlotLayout->setOuterRect(mViewport);
}
/*!
Sets the device pixel ratio used by the paint buffers of this QCustomPlot instance.
Normally, this doesn't need to be set manually, because it is initialized with the regular \a
QWidget::devicePixelRatio which is configured by Qt to fit the display device (e.g. 1 for normal
displays, 2 for High-DPI displays).
Device pixel ratios are supported by Qt only for Qt versions since 5.4. If this method is called
when QCustomPlot is being used with older Qt versions, outputs an according qDebug message and
leaves the internal buffer device pixel ratio at 1.0.
*/
void QCustomPlot::setBufferDevicePixelRatio(double ratio)
{
if (!qFuzzyCompare(ratio, mBufferDevicePixelRatio))
{
#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
mBufferDevicePixelRatio = ratio;
foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
buffer->setDevicePixelRatio(mBufferDevicePixelRatio);
// Note: axis label cache has devicePixelRatio as part of cache hash, so no need to manually clear cache here
#else
qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
mBufferDevicePixelRatio = 1.0;
#endif
}
}
/*!
Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn
below all other objects in the plot.
For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be
enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is
preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
consider using the overloaded version of this function.
If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will
first be filled with that brush, before drawing the background pixmap. This can be useful for
background pixmaps with translucent areas.
\see setBackgroundScaled, setBackgroundScaledMode
*/
void QCustomPlot::setBackground(const QPixmap &pm)
{
mBackgroundPixmap = pm;
mScaledBackgroundPixmap = QPixmap();
}
/*!
Sets the background brush of the viewport (see \ref setViewport).
Before drawing everything else, the background is filled with \a brush. If a background pixmap
was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport
before the background pixmap is drawn. This can be useful for background pixmaps with translucent
areas.
Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be
useful for exporting to image formats which support transparency, e.g. \ref savePng.
\see setBackgroundScaled, setBackgroundScaledMode
*/
void QCustomPlot::setBackground(const QBrush &brush)
{
mBackgroundBrush = brush;
}
/*! \overload
Allows setting the background pixmap of the viewport, whether it shall be scaled and how it
shall be scaled in one call.
\see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
*/
void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
{
mBackgroundPixmap = pm;
mScaledBackgroundPixmap = QPixmap();
mBackgroundScaled = scaled;
mBackgroundScaledMode = mode;
}
/*!
Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is
set to true, control whether and how the aspect ratio of the original pixmap is preserved with
\ref setBackgroundScaledMode.
Note that the scaled version of the original pixmap is buffered, so there is no performance
penalty on replots. (Except when the viewport dimensions are changed continuously.)
\see setBackground, setBackgroundScaledMode
*/
void QCustomPlot::setBackgroundScaled(bool scaled)
{
mBackgroundScaled = scaled;
}
/*!
If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this
function to define whether and how the aspect ratio of the original pixmap is preserved.
\see setBackground, setBackgroundScaled
*/
void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode)
{
mBackgroundScaledMode = mode;
}
/*!
Returns the plottable with \a index. If the index is invalid, returns \c nullptr.
There is an overloaded version of this function with no parameter which returns the last added
plottable, see QCustomPlot::plottable()
\see plottableCount
*/
QCPAbstractPlottable *QCustomPlot::plottable(int index)
{
if (index >= 0 && index < mPlottables.size())
{
return mPlottables.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return nullptr;
}
}
/*! \overload
Returns the last plottable that was added to the plot. If there are no plottables in the plot,
returns \c nullptr.
\see plottableCount
*/
QCPAbstractPlottable *QCustomPlot::plottable()
{
if (!mPlottables.isEmpty())
{
return mPlottables.last();
} else
return nullptr;
}
/*!
Removes the specified plottable from the plot and deletes it. If necessary, the corresponding
legend item is also removed from the default legend (QCustomPlot::legend).
Returns true on success.
\see clearPlottables
*/
bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable)
{
if (!mPlottables.contains(plottable))
{
qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast<quintptr>(plottable);
return false;
}
// remove plottable from legend:
plottable->removeFromLegend();
// special handling for QCPGraphs to maintain the simple graph interface:
if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
mGraphs.removeOne(graph);
// remove plottable:
delete plottable;
mPlottables.removeOne(plottable);
return true;
}
/*! \overload
Removes and deletes the plottable by its \a index.
*/
bool QCustomPlot::removePlottable(int index)
{
if (index >= 0 && index < mPlottables.size())
return removePlottable(mPlottables[index]);
else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return false;
}
}
/*!
Removes all plottables from the plot and deletes them. Corresponding legend items are also
removed from the default legend (QCustomPlot::legend).
Returns the number of plottables removed.
\see removePlottable
*/
int QCustomPlot::clearPlottables()
{
int c = static_cast<int>(mPlottables.size());
for (int i=c-1; i >= 0; --i)
removePlottable(mPlottables[i]);
return c;
}
/*!
Returns the number of currently existing plottables in the plot
\see plottable
*/
int QCustomPlot::plottableCount() const
{
return static_cast<int>(mPlottables.size());
}
/*!
Returns a list of the selected plottables. If no plottables are currently selected, the list is empty.
There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs.
\see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
*/
QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const
{
QList<QCPAbstractPlottable*> result;
foreach (QCPAbstractPlottable *plottable, mPlottables)
{
if (plottable->selected())
result.append(plottable);
}
return result;
}
/*!
Returns any plottable at the pixel position \a pos. Since it can capture all plottables, the
return type is the abstract base class of all plottables, QCPAbstractPlottable.
For details, and if you wish to specify a certain plottable type (e.g. QCPGraph), see the
template method plottableAt<PlottableType>()
\see plottableAt<PlottableType>(), itemAt, layoutElementAt
*/
QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable, int *dataIndex) const
{
return plottableAt<QCPAbstractPlottable>(pos, onlySelectable, dataIndex);
}
/*!
Returns whether this QCustomPlot instance contains the \a plottable.
*/
bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const
{
return mPlottables.contains(plottable);
}
/*!
Returns the graph with \a index. If the index is invalid, returns \c nullptr.
There is an overloaded version of this function with no parameter which returns the last created
graph, see QCustomPlot::graph()
\see graphCount, addGraph
*/
QCPGraph *QCustomPlot::graph(int index) const
{
if (index >= 0 && index < mGraphs.size())
{
return mGraphs.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return nullptr;
}
}
/*! \overload
Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot,
returns \c nullptr.
\see graphCount, addGraph
*/
QCPGraph *QCustomPlot::graph() const
{
if (!mGraphs.isEmpty())
{
return mGraphs.last();
} else
return nullptr;
}
/*!
Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the
bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a
keyAxis and \a valueAxis must reside in this QCustomPlot.
\a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically
"y") for the graph.
Returns a pointer to the newly created graph, or \c nullptr if adding the graph failed.
\see graph, graphCount, removeGraph, clearGraphs
*/
QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
{
if (!keyAxis) keyAxis = xAxis;
if (!valueAxis) valueAxis = yAxis;
if (!keyAxis || !valueAxis)
{
qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)";
return nullptr;
}
if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this)
{
qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent";
return nullptr;
}
QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis);
newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size()));
return newGraph;
}
/*!
Removes the specified \a graph from the plot and deletes it. If necessary, the corresponding
legend item is also removed from the default legend (QCustomPlot::legend). If any other graphs in
the plot have a channel fill set towards the removed graph, the channel fill property of those
graphs is reset to \c nullptr (no channel fill).
Returns true on success.
\see clearGraphs
*/
bool QCustomPlot::removeGraph(QCPGraph *graph)
{
return removePlottable(graph);
}
/*! \overload
Removes and deletes the graph by its \a index.
*/
bool QCustomPlot::removeGraph(int index)
{
if (index >= 0 && index < mGraphs.size())
return removeGraph(mGraphs[index]);
else
return false;
}
/*!
Removes all graphs from the plot and deletes them. Corresponding legend items are also removed
from the default legend (QCustomPlot::legend).
Returns the number of graphs removed.
\see removeGraph
*/
int QCustomPlot::clearGraphs()
{
int c = static_cast<int>(mGraphs.size());
for (int i=c-1; i >= 0; --i)
removeGraph(mGraphs[i]);
return c;
}
/*!
Returns the number of currently existing graphs in the plot
\see graph, addGraph
*/
int QCustomPlot::graphCount() const
{
return static_cast<int>(mGraphs.size());
}
/*!
Returns a list of the selected graphs. If no graphs are currently selected, the list is empty.
If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars,
etc., use \ref selectedPlottables.
\see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
*/
QList<QCPGraph*> QCustomPlot::selectedGraphs() const
{
QList<QCPGraph*> result;
foreach (QCPGraph *graph, mGraphs)
{
if (graph->selected())
result.append(graph);
}
return result;
}
/*!
Returns the item with \a index. If the index is invalid, returns \c nullptr.
There is an overloaded version of this function with no parameter which returns the last added
item, see QCustomPlot::item()
\see itemCount
*/
QCPAbstractItem *QCustomPlot::item(int index) const
{
if (index >= 0 && index < mItems.size())
{
return mItems.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return nullptr;
}
}
/*! \overload
Returns the last item that was added to this plot. If there are no items in the plot,
returns \c nullptr.
\see itemCount
*/
QCPAbstractItem *QCustomPlot::item() const
{
if (!mItems.isEmpty())
{
return mItems.last();
} else
return nullptr;
}
/*!
Removes the specified item from the plot and deletes it.
Returns true on success.
\see clearItems
*/
bool QCustomPlot::removeItem(QCPAbstractItem *item)
{
if (mItems.contains(item))
{
delete item;
mItems.removeOne(item);
return true;
} else
{
qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast<quintptr>(item);
return false;
}
}
/*! \overload
Removes and deletes the item by its \a index.
*/
bool QCustomPlot::removeItem(int index)
{
if (index >= 0 && index < mItems.size())
return removeItem(mItems[index]);
else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return false;
}
}
/*!
Removes all items from the plot and deletes them.
Returns the number of items removed.
\see removeItem
*/
int QCustomPlot::clearItems()
{
int c = static_cast<int>(mItems.size());
for (int i=c-1; i >= 0; --i)
removeItem(mItems[i]);
return c;
}
/*!
Returns the number of currently existing items in the plot
\see item
*/
int QCustomPlot::itemCount() const
{
return static_cast<int>(mItems.size());
}
/*!
Returns a list of the selected items. If no items are currently selected, the list is empty.
\see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected
*/
QList<QCPAbstractItem*> QCustomPlot::selectedItems() const
{
QList<QCPAbstractItem*> result;
foreach (QCPAbstractItem *item, mItems)
{
if (item->selected())
result.append(item);
}
return result;
}
/*!
Returns the item at the pixel position \a pos. Since it can capture all items, the
return type is the abstract base class of all items, QCPAbstractItem.
For details, and if you wish to specify a certain item type (e.g. QCPItemLine), see the
template method itemAt<ItemType>()
\see itemAt<ItemType>(), plottableAt, layoutElementAt
*/
QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const
{
return itemAt<QCPAbstractItem>(pos, onlySelectable);
}
/*!
Returns whether this QCustomPlot contains the \a item.
\see item
*/
bool QCustomPlot::hasItem(QCPAbstractItem *item) const
{
return mItems.contains(item);
}
/*!
Returns the layer with the specified \a name. If there is no layer with the specified name, \c
nullptr is returned.
Layer names are case-sensitive.
\see addLayer, moveLayer, removeLayer
*/
QCPLayer *QCustomPlot::layer(const QString &name) const
{
foreach (QCPLayer *layer, mLayers)
{
if (layer->name() == name)
return layer;
}
return nullptr;
}
/*! \overload
Returns the layer by \a index. If the index is invalid, \c nullptr is returned.
\see addLayer, moveLayer, removeLayer
*/
QCPLayer *QCustomPlot::layer(int index) const
{
if (index >= 0 && index < mLayers.size())
{
return mLayers.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return nullptr;
}
}
/*!
Returns the layer that is set as current layer (see \ref setCurrentLayer).
*/
QCPLayer *QCustomPlot::currentLayer() const
{
return mCurrentLayer;
}
/*!
Sets the layer with the specified \a name to be the current layer. All layerables (\ref
QCPLayerable), e.g. plottables and items, are created on the current layer.
Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot.
Layer names are case-sensitive.
\see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer
*/
bool QCustomPlot::setCurrentLayer(const QString &name)
{
if (QCPLayer *newCurrentLayer = layer(name))
{
return setCurrentLayer(newCurrentLayer);
} else
{
qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name;
return false;
}
}
/*! \overload
Sets the provided \a layer to be the current layer.
Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot.
\see addLayer, moveLayer, removeLayer
*/
bool QCustomPlot::setCurrentLayer(QCPLayer *layer)
{
if (!mLayers.contains(layer))
{
qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
return false;
}
mCurrentLayer = layer;
return true;
}
/*!
Returns the number of currently existing layers in the plot
\see layer, addLayer
*/
int QCustomPlot::layerCount() const
{
return static_cast<int>(mLayers.size());
}
/*!
Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which
must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer.
Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a
valid layer inside this QCustomPlot.
If \a otherLayer is 0, the highest layer in the QCustomPlot will be used.
For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer.
\see layer, moveLayer, removeLayer
*/
bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
{
if (!otherLayer)
otherLayer = mLayers.last();
if (!mLayers.contains(otherLayer))
{
qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
return false;
}
if (layer(name))
{
qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name;
return false;
}
QCPLayer *newLayer = new QCPLayer(this, name);
mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer);
updateLayerIndices();
setupPaintBuffers(); // associates new layer with the appropriate paint buffer
return true;
}
/*!
Removes the specified \a layer and returns true on success.
All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below
\a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both
cases, the total rendering order of all layerables in the QCustomPlot is preserved.
If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom
layer) becomes the new current layer.
It is not possible to remove the last layer of the plot.
\see layer, addLayer, moveLayer
*/
bool QCustomPlot::removeLayer(QCPLayer *layer)
{
if (!mLayers.contains(layer))
{
qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
return false;
}
if (mLayers.size() < 2)
{
qDebug() << Q_FUNC_INFO << "can't remove last layer";
return false;
}
// append all children of this layer to layer below (if this is lowest layer, prepend to layer above)
int removedIndex = layer->index();
bool isFirstLayer = removedIndex==0;
QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1);
QList<QCPLayerable*> children = layer->children();
if (isFirstLayer) // prepend in reverse order (such that relative order stays the same)
std::reverse(children.begin(), children.end());
foreach (QCPLayerable *child, children)
child->moveToLayer(targetLayer, isFirstLayer); // prepend if isFirstLayer, otherwise append
// if removed layer is current layer, change current layer to layer below/above:
if (layer == mCurrentLayer)
setCurrentLayer(targetLayer);
// invalidate the paint buffer that was responsible for this layer:
if (QSharedPointer<QCPAbstractPaintBuffer> pb = layer->mPaintBuffer.toStrongRef())
pb->setInvalidated();
// remove layer:
delete layer;
mLayers.removeOne(layer);
updateLayerIndices();
return true;
}
/*!
Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or
below is controlled with \a insertMode.
Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the
QCustomPlot.
\see layer, addLayer, moveLayer
*/
bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
{
if (!mLayers.contains(layer))
{
qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
return false;
}
if (!mLayers.contains(otherLayer))
{
qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
return false;
}
if (layer->index() > otherLayer->index())
mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0));
else if (layer->index() < otherLayer->index())
mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 0:-1));
// invalidate the paint buffers that are responsible for the layers:
if (QSharedPointer<QCPAbstractPaintBuffer> pb = layer->mPaintBuffer.toStrongRef())
pb->setInvalidated();
if (QSharedPointer<QCPAbstractPaintBuffer> pb = otherLayer->mPaintBuffer.toStrongRef())
pb->setInvalidated();
updateLayerIndices();
return true;
}
/*!
Returns the number of axis rects in the plot.
All axis rects can be accessed via QCustomPlot::axisRect().
Initially, only one axis rect exists in the plot.
\see axisRect, axisRects
*/
int QCustomPlot::axisRectCount() const
{
return static_cast<int>(axisRects().size());
}
/*!
Returns the axis rect with \a index.
Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were
added, all of them may be accessed with this function in a linear fashion (even when they are
nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout).
The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding
them. For example, if the axis rects are in the top level grid layout (accessible via \ref
QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's
default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst
"foColumnsFirst" wasn't changed.
If you want to access axis rects by their row and column index, use the layout interface. For
example, use \ref QCPLayoutGrid::element of the top level grid layout, and \c qobject_cast the
returned layout element to \ref QCPAxisRect. (See also \ref thelayoutsystem.)
\see axisRectCount, axisRects, QCPLayoutGrid::setFillOrder
*/
QCPAxisRect *QCustomPlot::axisRect(int index) const
{
const QList<QCPAxisRect*> rectList = axisRects();
if (index >= 0 && index < rectList.size())
{
return rectList.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index;
return nullptr;
}
}
/*!
Returns all axis rects in the plot.
The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding
them. For example, if the axis rects are in the top level grid layout (accessible via \ref
QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's
default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst
"foColumnsFirst" wasn't changed.
\see axisRectCount, axisRect, QCPLayoutGrid::setFillOrder
*/
QList<QCPAxisRect*> QCustomPlot::axisRects() const
{
QList<QCPAxisRect*> result;
QStack<QCPLayoutElement*> elementStack;
if (mPlotLayout)
elementStack.push(mPlotLayout);
while (!elementStack.isEmpty())
{
foreach (QCPLayoutElement *element, elementStack.pop()->elements(false))
{
if (element)
{
elementStack.push(element);
if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(element))
result.append(ar);
}
}
}
return result;
}
/*!
Returns the layout element at pixel position \a pos. If there is no element at that position,
returns \c nullptr.
Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on
any of its parent elements is set to false, it will not be considered.
\see itemAt, plottableAt
*/
QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const
{
QCPLayoutElement *currentElement = mPlotLayout;
bool searchSubElements = true;
while (searchSubElements && currentElement)
{
searchSubElements = false;
foreach (QCPLayoutElement *subElement, currentElement->elements(false))
{
if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
{
currentElement = subElement;
searchSubElements = true;
break;
}
}
}
return currentElement;
}
/*!
Returns the layout element of type \ref QCPAxisRect at pixel position \a pos. This method ignores
other layout elements even if they are visually in front of the axis rect (e.g. a \ref
QCPLegend). If there is no axis rect at that position, returns \c nullptr.
Only visible axis rects are used. If \ref QCPLayoutElement::setVisible on the axis rect itself or
on any of its parent elements is set to false, it will not be considered.
\see layoutElementAt
*/
QCPAxisRect *QCustomPlot::axisRectAt(const QPointF &pos) const
{
QCPAxisRect *result = nullptr;
QCPLayoutElement *currentElement = mPlotLayout;
bool searchSubElements = true;
while (searchSubElements && currentElement)
{
searchSubElements = false;
foreach (QCPLayoutElement *subElement, currentElement->elements(false))
{
if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
{
currentElement = subElement;
searchSubElements = true;
if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(currentElement))
result = ar;
break;
}
}
}
return result;
}
/*!
Returns the axes that currently have selected parts, i.e. whose selection state is not \ref
QCPAxis::spNone.
\see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts,
QCPAxis::setSelectableParts
*/
QList<QCPAxis*> QCustomPlot::selectedAxes() const
{
QList<QCPAxis*> result, allAxes;
foreach (QCPAxisRect *rect, axisRects())
allAxes << rect->axes();
foreach (QCPAxis *axis, allAxes)
{
if (axis->selectedParts() != QCPAxis::spNone)
result.append(axis);
}
return result;
}
/*!
Returns the legends that currently have selected parts, i.e. whose selection state is not \ref
QCPLegend::spNone.
\see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts,
QCPLegend::setSelectableParts, QCPLegend::selectedItems
*/
QList<QCPLegend*> QCustomPlot::selectedLegends() const
{
QList<QCPLegend*> result;
QStack<QCPLayoutElement*> elementStack;
if (mPlotLayout)
elementStack.push(mPlotLayout);
while (!elementStack.isEmpty())
{
foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false))
{
if (subElement)
{
elementStack.push(subElement);
if (QCPLegend *leg = qobject_cast<QCPLegend*>(subElement))
{
if (leg->selectedParts() != QCPLegend::spNone)
result.append(leg);
}
}
}
}
return result;
}
/*!
Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot.
Since calling this function is not a user interaction, this does not emit the \ref
selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the
objects were previously selected.
\see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends
*/
void QCustomPlot::deselectAll()
{
foreach (QCPLayer *layer, mLayers)
{
foreach (QCPLayerable *layerable, layer->children())
layerable->deselectEvent(nullptr);
}
}
/*!
Causes a complete replot into the internal paint buffer(s). Finally, the widget surface is
refreshed with the new buffer contents. This is the method that must be called to make changes to
the plot, e.g. on the axis ranges or data points of graphs, visible.
The parameter \a refreshPriority can be used to fine-tune the timing of the replot. For example
if your application calls \ref replot very quickly in succession (e.g. multiple independent
functions change some aspects of the plot and each wants to make sure the change gets replotted),
it is advisable to set \a refreshPriority to \ref QCustomPlot::rpQueuedReplot. This way, the
actual replotting is deferred to the next event loop iteration. Multiple successive calls of \ref
replot with this priority will only cause a single replot, avoiding redundant replots and
improving performance.
Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the
QCustomPlot widget and user interactions (object selection and range dragging/zooming).
Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref
afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two
signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite
recursion.
If a layer is in mode \ref QCPLayer::lmBuffered (\ref QCPLayer::setMode), it is also possible to
replot only that specific layer via \ref QCPLayer::replot. See the documentation there for
details.
\see replotTime
*/
void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority)
{
if (refreshPriority == QCustomPlot::rpQueuedReplot)
{
if (!mReplotQueued)
{
mReplotQueued = true;
QTimer::singleShot(0, this, SLOT(replot()));
}
return;
}
if (mReplotting) // incase signals loop back to replot slot
return;
mReplotting = true;
mReplotQueued = false;
emit beforeReplot();
# if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
QTime replotTimer;
replotTimer.start();
# else
QElapsedTimer replotTimer;
replotTimer.start();
# endif
updateLayout();
// draw all layered objects (grid, axes, plottables, items, legend,...) into their buffers:
setupPaintBuffers();
foreach (QCPLayer *layer, mLayers)
layer->drawToPaintBuffer();
foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
buffer->setInvalidated(false);
if ((refreshPriority == rpRefreshHint && mPlottingHints.testFlag(QCP::phImmediateRefresh)) || refreshPriority==rpImmediateRefresh)
repaint();
else
update();
# if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
mReplotTime = replotTimer.elapsed();
# else
mReplotTime = replotTimer.nsecsElapsed()*1e-6;
# endif
if (!qFuzzyIsNull(mReplotTimeAverage))
mReplotTimeAverage = mReplotTimeAverage*0.9 + mReplotTime*0.1; // exponential moving average with a time constant of 10 last replots
else
mReplotTimeAverage = mReplotTime; // no previous replots to average with, so initialize with replot time
emit afterReplot();
mReplotting = false;
}
/*!
Returns the time in milliseconds that the last replot took. If \a average is set to true, an
exponential moving average over the last couple of replots is returned.
\see replot
*/
double QCustomPlot::replotTime(bool average) const
{
return average ? mReplotTimeAverage : mReplotTime;
}
/*!
Rescales the axes such that all plottables (like graphs) in the plot are fully visible.
if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true
(QCPLayerable::setVisible), will be used to rescale the axes.
\see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale
*/
void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
{
QList<QCPAxis*> allAxes;
foreach (QCPAxisRect *rect, axisRects())
allAxes << rect->axes();
foreach (QCPAxis *axis, allAxes)
axis->rescale(onlyVisiblePlottables);
}
/*!
Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale
of texts and lines will be derived from the specified \a width and \a height. This means, the
output will look like the normal on-screen output of a QCustomPlot widget with the corresponding
pixel width and height. If either \a width or \a height is zero, the exported image will have the
same dimensions as the QCustomPlot widget currently has.
Setting \a exportPen to \ref QCP::epNoCosmetic allows to disable the use of cosmetic pens when
drawing to the PDF file. Cosmetic pens are pens with numerical width 0, which are always drawn as
a one pixel wide line, no matter what zoom factor is set in the PDF-Viewer. For more information
about cosmetic pens, see the QPainter and QPen documentation.
The objects of the plot will appear in the current selection state. If you don't want any
selected objects to be painted in their selected look, deselect everything with \ref deselectAll
before calling this function.
Returns true on success.
\li If you plan on editing the exported PDF file with a vector graphics editor like Inkscape, it
is advised to set \a exportPen to \ref QCP::epNoCosmetic to avoid losing those cosmetic lines
(which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks).
\li If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
function uses the current width and height of the QCustomPlot widget. However, in Qt, these
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
\a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting
PDF file.
\note On Android systems, this method does nothing and issues an according qDebug warning
message. This is also the case if for other reasons the define flag \c QT_NO_PRINTER is set.
\see savePng, saveBmp, saveJpg, saveRastered
*/
bool QCustomPlot::savePdf(const QString &fileName, int width, int height, QCP::ExportPen exportPen, const QString &pdfCreator, const QString &pdfTitle)
{
bool success = false;
#ifdef QT_NO_PRINTER
Q_UNUSED(fileName)
Q_UNUSED(exportPen)
Q_UNUSED(width)
Q_UNUSED(height)
Q_UNUSED(pdfCreator)
Q_UNUSED(pdfTitle)
qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created.";
#else
int newWidth, newHeight;
if (width == 0 || height == 0)
{
newWidth = this->width();
newHeight = this->height();
} else
{
newWidth = width;
newHeight = height;
}
QPrinter printer(QPrinter::ScreenResolution);
printer.setOutputFileName(fileName);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setColorMode(QPrinter::Color);
printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator);
printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle);
QRect oldViewport = viewport();
setViewport(QRect(0, 0, newWidth, newHeight));
#if QT_VERSION < QT_VERSION_CHECK(5, 3, 0)
printer.setFullPage(true);
printer.setPaperSize(viewport().size(), QPrinter::DevicePixel);
#else
QPageLayout pageLayout;
pageLayout.setMode(QPageLayout::FullPageMode);
pageLayout.setOrientation(QPageLayout::Portrait);
pageLayout.setMargins(QMarginsF(0, 0, 0, 0));
pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch));
printer.setPageLayout(pageLayout);
#endif
QCPPainter printpainter;
if (printpainter.begin(&printer))
{
printpainter.setMode(QCPPainter::pmVectorized);
printpainter.setMode(QCPPainter::pmNoCaching);
printpainter.setMode(QCPPainter::pmNonCosmetic, exportPen==QCP::epNoCosmetic);
printpainter.setWindow(mViewport);
if (mBackgroundBrush.style() != Qt::NoBrush &&
mBackgroundBrush.color() != Qt::white &&
mBackgroundBrush.color() != Qt::transparent &&
mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent
printpainter.fillRect(viewport(), mBackgroundBrush);
draw(&printpainter);
printpainter.end();
success = true;
}
setViewport(oldViewport);
#endif // QT_NO_PRINTER
return success;
}
/*!
Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width
and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
parameter.
For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
200*200 pixel resolution.
If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
QCustomPlot to place objects with sub-pixel accuracy.
image compression can be controlled with the \a quality parameter which must be between 0 and 100
or -1 to use the default setting.
The \a resolution will be written to the image file header and has no direct consequence for the
quality or the pixel size. However, if opening the image with a tool which respects the metadata,
it will be able to scale the image to match either a given size in real units of length (inch,
centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
resolution unit internally.
Returns true on success. If this function fails, most likely the PNG format isn't supported by
the system, see Qt docs about QImageWriter::supportedImageFormats().
The objects of the plot will appear in the current selection state. If you don't want any selected
objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
this function.
If you want the PNG to have a transparent background, call \ref setBackground(const QBrush &brush)
with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
\warning If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
function uses the current width and height of the QCustomPlot widget. However, in Qt, these
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
\see savePdf, saveBmp, saveJpg, saveRastered
*/
bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
{
return saveRastered(fileName, width, height, scale, "PNG", quality, resolution, resolutionUnit);
}
/*!
Saves a JPEG image file to \a fileName on disc. The output plot will have the dimensions \a width
and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
parameter.
For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
200*200 pixel resolution.
If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
QCustomPlot to place objects with sub-pixel accuracy.
image compression can be controlled with the \a quality parameter which must be between 0 and 100
or -1 to use the default setting.
The \a resolution will be written to the image file header and has no direct consequence for the
quality or the pixel size. However, if opening the image with a tool which respects the metadata,
it will be able to scale the image to match either a given size in real units of length (inch,
centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
resolution unit internally.
Returns true on success. If this function fails, most likely the JPEG format isn't supported by
the system, see Qt docs about QImageWriter::supportedImageFormats().
The objects of the plot will appear in the current selection state. If you don't want any selected
objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
this function.
\warning If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
function uses the current width and height of the QCustomPlot widget. However, in Qt, these
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
\see savePdf, savePng, saveBmp, saveRastered
*/
bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
{
return saveRastered(fileName, width, height, scale, "JPG", quality, resolution, resolutionUnit);
}
/*!
Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width
and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
parameter.
For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
200*200 pixel resolution.
If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
QCustomPlot to place objects with sub-pixel accuracy.
The \a resolution will be written to the image file header and has no direct consequence for the
quality or the pixel size. However, if opening the image with a tool which respects the metadata,
it will be able to scale the image to match either a given size in real units of length (inch,
centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
resolution unit internally.
Returns true on success. If this function fails, most likely the BMP format isn't supported by
the system, see Qt docs about QImageWriter::supportedImageFormats().
The objects of the plot will appear in the current selection state. If you don't want any selected
objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
this function.
\warning If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
function uses the current width and height of the QCustomPlot widget. However, in Qt, these
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
\see savePdf, savePng, saveJpg, saveRastered
*/
bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale, int resolution, QCP::ResolutionUnit resolutionUnit)
{
return saveRastered(fileName, width, height, scale, "BMP", -1, resolution, resolutionUnit);
}
/*! \internal
Returns a minimum size hint that corresponds to the minimum size of the top level layout
(\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum
size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot.
This is especially important, when placed in a QLayout where other components try to take in as
much space as possible (e.g. QMdiArea).
*/
QSize QCustomPlot::minimumSizeHint() const
{
return mPlotLayout->minimumOuterSizeHint();
}
/*! \internal
Returns a size hint that is the same as \ref minimumSizeHint.
*/
QSize QCustomPlot::sizeHint() const
{
return mPlotLayout->minimumOuterSizeHint();
}
/*! \internal
Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but
draws the internal buffer on the widget surface.
*/
void QCustomPlot::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
// detect if the device pixel ratio has changed (e.g. moving window between different DPI screens), and adapt buffers if necessary:
#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
# ifdef QCP_DEVICEPIXELRATIO_FLOAT
double newDpr = devicePixelRatioF();
# else
double newDpr = devicePixelRatio();
# endif
if (!qFuzzyCompare(mBufferDevicePixelRatio, newDpr))
{
setBufferDevicePixelRatio(newDpr);
replot(QCustomPlot::rpQueuedRefresh);
return;
}
#endif
QCPPainter painter(this);
if (painter.isActive())
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
painter.setRenderHint(QPainter::Antialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem
#endif
if (mBackgroundBrush.style() != Qt::NoBrush)
painter.fillRect(mViewport, mBackgroundBrush);
drawBackground(&painter);
foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
buffer->draw(&painter);
}
}
/*! \internal
Event handler for a resize of the QCustomPlot widget. The viewport (which becomes the outer rect
of mPlotLayout) is resized appropriately. Finally a \ref replot is performed.
*/
void QCustomPlot::resizeEvent(QResizeEvent *event)
{
Q_UNUSED(event)
// resize and repaint the buffer:
setViewport(rect());
replot(rpQueuedRefresh); // queued refresh is important here, to prevent painting issues in some contexts (e.g. MDI subwindow)
}
/*! \internal
Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then
determines the layerable under the cursor and forwards the event to it. Finally, emits the
specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
axisDoubleClick, etc.).
\see mousePressEvent, mouseReleaseEvent
*/
void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event)
{
emit mouseDoubleClick(event);
mMouseHasMoved = false;
mMousePressPos = event->pos();
// determine layerable under the cursor (this event is called instead of the second press event in a double-click):
QList<QVariant> details;
QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
for (int i=0; i<candidates.size(); ++i)
{
event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
candidates.at(i)->mouseDoubleClickEvent(event, details.at(i));
if (event->isAccepted())
{
mMouseEventLayerable = candidates.at(i);
mMouseEventLayerableDetails = details.at(i);
break;
}
}
// emit specialized object double click signals:
if (!candidates.isEmpty())
{
if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(candidates.first()))
{
int dataIndex = 0;
if (!details.first().value<QCPDataSelection>().isEmpty())
dataIndex = details.first().value<QCPDataSelection>().dataRange().begin();
emit plottableDoubleClick(ap, dataIndex, event);
} else if (QCPAxis *ax = qobject_cast<QCPAxis*>(candidates.first()))
emit axisDoubleClick(ax, details.first().value<QCPAxis::SelectablePart>(), event);
else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(candidates.first()))
emit itemDoubleClick(ai, event);
else if (QCPLegend *lg = qobject_cast<QCPLegend*>(candidates.first()))
emit legendDoubleClick(lg, nullptr, event);
else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(candidates.first()))
emit legendDoubleClick(li->parentLegend(), li, event);
}
event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
}
/*! \internal
Event handler for when a mouse button is pressed. Emits the mousePress signal.
If the current \ref setSelectionRectMode is not \ref QCP::srmNone, passes the event to the
selection rect. Otherwise determines the layerable under the cursor and forwards the event to it.
\see mouseMoveEvent, mouseReleaseEvent
*/
void QCustomPlot::mousePressEvent(QMouseEvent *event)
{
emit mousePress(event);
// save some state to tell in releaseEvent whether it was a click:
mMouseHasMoved = false;
mMousePressPos = event->pos();
if (mSelectionRect && mSelectionRectMode != QCP::srmNone)
{
if (mSelectionRectMode != QCP::srmZoom || qobject_cast<QCPAxisRect*>(axisRectAt(mMousePressPos))) // in zoom mode only activate selection rect if on an axis rect
mSelectionRect->startSelection(event);
} else
{
// no selection rect interaction, prepare for click signal emission and forward event to layerable under the cursor:
QList<QVariant> details;
QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
if (!candidates.isEmpty())
{
mMouseSignalLayerable = candidates.first(); // candidate for signal emission is always topmost hit layerable (signal emitted in release event)
mMouseSignalLayerableDetails = details.first();
}
// forward event to topmost candidate which accepts the event:
for (int i=0; i<candidates.size(); ++i)
{
event->accept(); // default impl of QCPLayerable's mouse events call ignore() on the event, in that case propagate to next candidate in list
candidates.at(i)->mousePressEvent(event, details.at(i));
if (event->isAccepted())
{
mMouseEventLayerable = candidates.at(i);
mMouseEventLayerableDetails = details.at(i);
break;
}
}
}
event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
}
/*! \internal
Event handler for when the cursor is moved. Emits the \ref mouseMove signal.
If the selection rect (\ref setSelectionRect) is currently active, the event is forwarded to it
in order to update the rect geometry.
Otherwise, if a layout element has mouse capture focus (a mousePressEvent happened on top of the
layout element before), the mouseMoveEvent is forwarded to that element.
\see mousePressEvent, mouseReleaseEvent
*/
void QCustomPlot::mouseMoveEvent(QMouseEvent *event)
{
emit mouseMove(event);
if (!mMouseHasMoved && (mMousePressPos-event->pos()).manhattanLength() > 3)
mMouseHasMoved = true; // moved too far from mouse press position, don't handle as click on mouse release
if (mSelectionRect && mSelectionRect->isActive())
mSelectionRect->moveSelection(event);
else if (mMouseEventLayerable) // call event of affected layerable:
mMouseEventLayerable->mouseMoveEvent(event, mMousePressPos);
event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
}
/*! \internal
Event handler for when a mouse button is released. Emits the \ref mouseRelease signal.
If the mouse was moved less than a certain threshold in any direction since the \ref
mousePressEvent, it is considered a click which causes the selection mechanism (if activated via
\ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse
click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.)
If a layerable is the mouse capturer (a \ref mousePressEvent happened on top of the layerable
before), the \ref mouseReleaseEvent is forwarded to that element.
\see mousePressEvent, mouseMoveEvent
*/
void QCustomPlot::mouseReleaseEvent(QMouseEvent *event)
{
emit mouseRelease(event);
if (!mMouseHasMoved) // mouse hasn't moved (much) between press and release, so handle as click
{
if (mSelectionRect && mSelectionRect->isActive()) // a simple click shouldn't successfully finish a selection rect, so cancel it here
mSelectionRect->cancel();
if (event->button() == Qt::LeftButton)
processPointSelection(event);
// emit specialized click signals of QCustomPlot instance:
if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(mMouseSignalLayerable))
{
int dataIndex = 0;
if (!mMouseSignalLayerableDetails.value<QCPDataSelection>().isEmpty())
dataIndex = mMouseSignalLayerableDetails.value<QCPDataSelection>().dataRange().begin();
emit plottableClick(ap, dataIndex, event);
} else if (QCPAxis *ax = qobject_cast<QCPAxis*>(mMouseSignalLayerable))
emit axisClick(ax, mMouseSignalLayerableDetails.value<QCPAxis::SelectablePart>(), event);
else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(mMouseSignalLayerable))
emit itemClick(ai, event);
else if (QCPLegend *lg = qobject_cast<QCPLegend*>(mMouseSignalLayerable))
emit legendClick(lg, nullptr, event);
else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(mMouseSignalLayerable))
emit legendClick(li->parentLegend(), li, event);
mMouseSignalLayerable = nullptr;
}
if (mSelectionRect && mSelectionRect->isActive()) // Note: if a click was detected above, the selection rect is canceled there
{
// finish selection rect, the appropriate action will be taken via signal-slot connection:
mSelectionRect->endSelection(event);
} else
{
// call event of affected layerable:
if (mMouseEventLayerable)
{
mMouseEventLayerable->mouseReleaseEvent(event, mMousePressPos);
mMouseEventLayerable = nullptr;
}
}
if (noAntialiasingOnDrag())
replot(rpQueuedReplot);
event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
}
/*! \internal
Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then
determines the affected layerable and forwards the event to it.
*/
void QCustomPlot::wheelEvent(QWheelEvent *event)
{
emit mouseWheel(event);
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
const QPointF pos = event->pos();
#else
const QPointF pos = event->position();
#endif
// forward event to layerable under cursor:
foreach (QCPLayerable *candidate, layerableListAt(pos, false))
{
event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
candidate->wheelEvent(event);
if (event->isAccepted())
break;
}
event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
}
/*! \internal
This function draws the entire plot, including background pixmap, with the specified \a painter.
It does not make use of the paint buffers like \ref replot, so this is the function typically
used by saving/exporting methods such as \ref savePdf or \ref toPainter.
Note that it does not fill the background with the background brush (as the user may specify with
\ref setBackground(const QBrush &brush)), this is up to the respective functions calling this
method.
*/
void QCustomPlot::draw(QCPPainter *painter)
{
updateLayout();
// draw viewport background pixmap:
drawBackground(painter);
// draw all layered objects (grid, axes, plottables, items, legend,...):
foreach (QCPLayer *layer, mLayers)
layer->draw(painter);
/* Debug code to draw all layout element rects
foreach (QCPLayoutElement *el, findChildren<QCPLayoutElement*>())
{
painter->setBrush(Qt::NoBrush);
painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine));
painter->drawRect(el->rect());
painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine));
painter->drawRect(el->outerRect());
}
*/
}
/*! \internal
Performs the layout update steps defined by \ref QCPLayoutElement::UpdatePhase, by calling \ref
QCPLayoutElement::update on the main plot layout.
Here, the layout elements calculate their positions and margins, and prepare for the following
draw call.
*/
void QCustomPlot::updateLayout()
{
// run through layout phases:
mPlotLayout->update(QCPLayoutElement::upPreparation);
mPlotLayout->update(QCPLayoutElement::upMargins);
mPlotLayout->update(QCPLayoutElement::upLayout);
emit afterLayout();
}
/*! \internal
Draws the viewport background pixmap of the plot.
If a pixmap was provided via \ref setBackground, this function buffers the scaled version
depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
the viewport with the provided \a painter. The scaled version is buffered in
mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
the axis rect has changed in a way that requires a rescale of the background pixmap (this is
dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
set.
Note that this function does not draw a fill with the background brush
(\ref setBackground(const QBrush &brush)) beneath the pixmap.
\see setBackground, setBackgroundScaled, setBackgroundScaledMode
*/
void QCustomPlot::drawBackground(QCPPainter *painter)
{
// Note: background color is handled in individual replot/save functions
// draw background pixmap (on top of fill, if brush specified):
if (!mBackgroundPixmap.isNull())
{
if (mBackgroundScaled)
{
// check whether mScaledBackground needs to be updated:
QSize scaledSize(mBackgroundPixmap.size());
scaledSize.scale(mViewport.size(), mBackgroundScaledMode);
if (mScaledBackgroundPixmap.size() != scaledSize)
mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect());
} else
{
painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()));
}
}
}
/*! \internal
Goes through the layers and makes sure this QCustomPlot instance holds the correct number of
paint buffers and that they have the correct configuration (size, pixel ratio, etc.).
Allocations, reallocations and deletions of paint buffers are performed as necessary. It also
associates the paint buffers with the layers, so they draw themselves into the right buffer when
\ref QCPLayer::drawToPaintBuffer is called. This means it associates adjacent \ref
QCPLayer::lmLogical layers to a mutual paint buffer and creates dedicated paint buffers for
layers in \ref QCPLayer::lmBuffered mode.
This method uses \ref createPaintBuffer to create new paint buffers.
After this method, the paint buffers are empty (filled with \c Qt::transparent) and invalidated
(so an attempt to replot only a single buffered layer causes a full replot).
This method is called in every \ref replot call, prior to actually drawing the layers (into their
associated paint buffer). If the paint buffers don't need changing/reallocating, this method
basically leaves them alone and thus finishes very fast.
*/
void QCustomPlot::setupPaintBuffers()
{
int bufferIndex = 0;
if (mPaintBuffers.isEmpty())
mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
for (int layerIndex = 0; layerIndex < mLayers.size(); ++layerIndex)
{
QCPLayer *layer = mLayers.at(layerIndex);
if (layer->mode() == QCPLayer::lmLogical)
{
layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
} else if (layer->mode() == QCPLayer::lmBuffered)
{
++bufferIndex;
if (bufferIndex >= mPaintBuffers.size())
mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
if (layerIndex < mLayers.size()-1 && mLayers.at(layerIndex+1)->mode() == QCPLayer::lmLogical) // not last layer, and next one is logical, so prepare another buffer for next layerables
{
++bufferIndex;
if (bufferIndex >= mPaintBuffers.size())
mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
}
}
}
// remove unneeded buffers:
while (mPaintBuffers.size()-1 > bufferIndex)
mPaintBuffers.removeLast();
// resize buffers to viewport size and clear contents:
foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
{
buffer->setSize(viewport().size()); // won't do anything if already correct size
buffer->clear(Qt::transparent);
buffer->setInvalidated();
}
}
/*! \internal
This method is used by \ref setupPaintBuffers when it needs to create new paint buffers.
Depending on the current setting of \ref setOpenGl, and the current Qt version, different
backends (subclasses of \ref QCPAbstractPaintBuffer) are created, initialized with the proper
size and device pixel ratio, and returned.
*/
QCPAbstractPaintBuffer *QCustomPlot::createPaintBuffer()
{
if (mOpenGl)
{
#if defined(QCP_OPENGL_FBO)
return new QCPPaintBufferGlFbo(viewport().size(), mBufferDevicePixelRatio, mGlContext, mGlPaintDevice);
#elif defined(QCP_OPENGL_PBUFFER)
return new QCPPaintBufferGlPbuffer(viewport().size(), mBufferDevicePixelRatio, mOpenGlMultisamples);
#else
qDebug() << Q_FUNC_INFO << "OpenGL enabled even though no support for it compiled in, this shouldn't have happened. Falling back to pixmap paint buffer.";
return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
#endif
} else
return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
}
/*!
This method returns whether any of the paint buffers held by this QCustomPlot instance are
invalidated.
If any buffer is invalidated, a partial replot (\ref QCPLayer::replot) is not allowed and always
causes a full replot (\ref QCustomPlot::replot) of all layers. This is the case when for example
the layer order has changed, new layers were added or removed, layer modes were changed (\ref
QCPLayer::setMode), or layerables were added or removed.
\see QCPAbstractPaintBuffer::setInvalidated
*/
bool QCustomPlot::hasInvalidatedPaintBuffers()
{
foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
{
if (buffer->invalidated())
return true;
}
return false;
}
/*! \internal
When \ref setOpenGl is set to true, this method is used to initialize OpenGL (create a context,
surface, paint device).
Returns true on success.
If this method is successful, all paint buffers should be deleted and then reallocated by calling
\ref setupPaintBuffers, so the OpenGL-based paint buffer subclasses (\ref
QCPPaintBufferGlPbuffer, \ref QCPPaintBufferGlFbo) are used for subsequent replots.
\see freeOpenGl
*/
bool QCustomPlot::setupOpenGl()
{
#ifdef QCP_OPENGL_FBO
freeOpenGl();
QSurfaceFormat proposedSurfaceFormat;
proposedSurfaceFormat.setSamples(mOpenGlMultisamples);
#ifdef QCP_OPENGL_OFFSCREENSURFACE
QOffscreenSurface *surface = new QOffscreenSurface;
#else
QWindow *surface = new QWindow;
surface->setSurfaceType(QSurface::OpenGLSurface);
#endif
surface->setFormat(proposedSurfaceFormat);
surface->create();
mGlSurface = QSharedPointer<QSurface>(surface);
mGlContext = QSharedPointer<QOpenGLContext>(new QOpenGLContext);
mGlContext->setFormat(mGlSurface->format());
if (!mGlContext->create())
{
qDebug() << Q_FUNC_INFO << "Failed to create OpenGL context";
mGlContext.clear();
mGlSurface.clear();
return false;
}
if (!mGlContext->makeCurrent(mGlSurface.data())) // context needs to be current to create paint device
{
qDebug() << Q_FUNC_INFO << "Failed to make opengl context current";
mGlContext.clear();
mGlSurface.clear();
return false;
}
if (!QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
{
qDebug() << Q_FUNC_INFO << "OpenGL of this system doesn't support frame buffer objects";
mGlContext.clear();
mGlSurface.clear();
return false;
}
mGlPaintDevice = QSharedPointer<QOpenGLPaintDevice>(new QOpenGLPaintDevice);
return true;
#elif defined(QCP_OPENGL_PBUFFER)
return QGLFormat::hasOpenGL();
#else
return false;
#endif
}
/*! \internal
When \ref setOpenGl is set to false, this method is used to deinitialize OpenGL (releases the
context and frees resources).
After OpenGL is disabled, all paint buffers should be deleted and then reallocated by calling
\ref setupPaintBuffers, so the standard software rendering paint buffer subclass (\ref
QCPPaintBufferPixmap) is used for subsequent replots.
\see setupOpenGl
*/
void QCustomPlot::freeOpenGl()
{
#ifdef QCP_OPENGL_FBO
mGlPaintDevice.clear();
mGlContext.clear();
mGlSurface.clear();
#endif
}
/*! \internal
This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot
so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly.
*/
void QCustomPlot::axisRemoved(QCPAxis *axis)
{
if (xAxis == axis)
xAxis = nullptr;
if (xAxis2 == axis)
xAxis2 = nullptr;
if (yAxis == axis)
yAxis = nullptr;
if (yAxis2 == axis)
yAxis2 = nullptr;
// Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers
}
/*! \internal
This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so
it may clear its QCustomPlot::legend member accordingly.
*/
void QCustomPlot::legendRemoved(QCPLegend *legend)
{
if (this->legend == legend)
this->legend = nullptr;
}
/*! \internal
This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
setSelectionRectMode is set to \ref QCP::srmSelect.
First, it determines which axis rect was the origin of the selection rect judging by the starting
point of the selection. Then it goes through the plottables (\ref QCPAbstractPlottable1D to be
precise) associated with that axis rect and finds the data points that are in \a rect. It does
this by querying their \ref QCPAbstractPlottable1D::selectTestRect method.
Then, the actual selection is done by calling the plottables' \ref
QCPAbstractPlottable::selectEvent, placing the found selected data points in the \a details
parameter as <tt>QVariant(QCPDataSelection)</tt>. All plottables that weren't touched by \a
rect receive a \ref QCPAbstractPlottable::deselectEvent.
\see processRectZoom
*/
void QCustomPlot::processRectSelection(QRect rect, QMouseEvent *event)
{
typedef QPair<QCPAbstractPlottable*, QCPDataSelection> SelectionCandidate;
typedef QMultiMap<int, SelectionCandidate> SelectionCandidates; // map key is number of selected data points, so we have selections sorted by size
bool selectionStateChanged = false;
if (mInteractions.testFlag(QCP::iSelectPlottables))
{
SelectionCandidates potentialSelections;
QRectF rectF(rect.normalized());
if (QCPAxisRect *affectedAxisRect = axisRectAt(rectF.topLeft()))
{
// determine plottables that were hit by the rect and thus are candidates for selection:
foreach (QCPAbstractPlottable *plottable, affectedAxisRect->plottables())
{
if (QCPPlottableInterface1D *plottableInterface = plottable->interface1D())
{
QCPDataSelection dataSel = plottableInterface->selectTestRect(rectF, true);
if (!dataSel.isEmpty())
potentialSelections.insert(dataSel.dataPointCount(), SelectionCandidate(plottable, dataSel));
}
}
if (!mInteractions.testFlag(QCP::iMultiSelect))
{
// only leave plottable with most selected points in map, since we will only select a single plottable:
if (!potentialSelections.isEmpty())
{
SelectionCandidates::iterator it = potentialSelections.begin();
while (it != std::prev(potentialSelections.end())) // erase all except last element
it = potentialSelections.erase(it);
}
}
bool additive = event->modifiers().testFlag(mMultiSelectModifier);
// deselect all other layerables if not additive selection:
if (!additive)
{
// emit deselection except to those plottables who will be selected afterwards:
foreach (QCPLayer *layer, mLayers)
{
foreach (QCPLayerable *layerable, layer->children())
{
if ((potentialSelections.isEmpty() || potentialSelections.constBegin()->first != layerable) && mInteractions.testFlag(layerable->selectionCategory()))
{
bool selChanged = false;
layerable->deselectEvent(&selChanged);
selectionStateChanged |= selChanged;
}
}
}
}
// go through selections in reverse (largest selection first) and emit select events:
SelectionCandidates::const_iterator it = potentialSelections.constEnd();
while (it != potentialSelections.constBegin())
{
--it;
if (mInteractions.testFlag(it.value().first->selectionCategory()))
{
bool selChanged = false;
it.value().first->selectEvent(event, additive, QVariant::fromValue(it.value().second), &selChanged);
selectionStateChanged |= selChanged;
}
}
}
}
if (selectionStateChanged)
{
emit selectionChangedByUser();
replot(rpQueuedReplot);
} else if (mSelectionRect)
mSelectionRect->layer()->replot();
}
/*! \internal
This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
setSelectionRectMode is set to \ref QCP::srmZoom.
It determines which axis rect was the origin of the selection rect judging by the starting point
of the selection, and then zooms the axes defined via \ref QCPAxisRect::setRangeZoomAxes to the
provided \a rect (see \ref QCPAxisRect::zoom).
\see processRectSelection
*/
void QCustomPlot::processRectZoom(QRect rect, QMouseEvent *event)
{
Q_UNUSED(event)
if (QCPAxisRect *axisRect = axisRectAt(rect.topLeft()))
{
QList<QCPAxis*> affectedAxes = QList<QCPAxis*>() << axisRect->rangeZoomAxes(Qt::Horizontal) << axisRect->rangeZoomAxes(Qt::Vertical);
affectedAxes.removeAll(static_cast<QCPAxis*>(nullptr));
axisRect->zoom(QRectF(rect), affectedAxes);
}
replot(rpQueuedReplot); // always replot to make selection rect disappear
}
/*! \internal
This method is called when a simple left mouse click was detected on the QCustomPlot surface.
It first determines the layerable that was hit by the click, and then calls its \ref
QCPLayerable::selectEvent. All other layerables receive a QCPLayerable::deselectEvent (unless the
multi-select modifier was pressed, see \ref setMultiSelectModifier).
In this method the hit layerable is determined a second time using \ref layerableAt (after the
one in \ref mousePressEvent), because we want \a onlySelectable set to true this time. This
implies that the mouse event grabber (mMouseEventLayerable) may be a different one from the
clicked layerable determined here. For example, if a non-selectable layerable is in front of a
selectable layerable at the click position, the front layerable will receive mouse events but the
selectable one in the back will receive the \ref QCPLayerable::selectEvent.
\see processRectSelection, QCPLayerable::selectTest
*/
void QCustomPlot::processPointSelection(QMouseEvent *event)
{
QVariant details;
QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details);
bool selectionStateChanged = false;
bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier);
// deselect all other layerables if not additive selection:
if (!additive)
{
foreach (QCPLayer *layer, mLayers)
{
foreach (QCPLayerable *layerable, layer->children())
{
if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory()))
{
bool selChanged = false;
layerable->deselectEvent(&selChanged);
selectionStateChanged |= selChanged;
}
}
}
}
if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory()))
{
// a layerable was actually clicked, call its selectEvent:
bool selChanged = false;
clickedLayerable->selectEvent(event, additive, details, &selChanged);
selectionStateChanged |= selChanged;
}
if (selectionStateChanged)
{
emit selectionChangedByUser();
replot(rpQueuedReplot);
}
}
/*! \internal
Registers the specified plottable with this QCustomPlot and, if \ref setAutoAddPlottableToLegend
is enabled, adds it to the legend (QCustomPlot::legend). QCustomPlot takes ownership of the
plottable.
Returns true on success, i.e. when \a plottable isn't already in this plot and the parent plot of
\a plottable is this QCustomPlot.
This method is called automatically in the QCPAbstractPlottable base class constructor.
*/
bool QCustomPlot::registerPlottable(QCPAbstractPlottable *plottable)
{
if (mPlottables.contains(plottable))
{
qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable);
return false;
}
if (plottable->parentPlot() != this)
{
qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable);
return false;
}
mPlottables.append(plottable);
// possibly add plottable to legend:
if (mAutoAddPlottableToLegend)
plottable->addToLegend();
if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
plottable->setLayer(currentLayer());
return true;
}
/*! \internal
In order to maintain the simplified graph interface of QCustomPlot, this method is called by the
QCPGraph constructor to register itself with this QCustomPlot's internal graph list. Returns true
on success, i.e. if \a graph is valid and wasn't already registered with this QCustomPlot.
This graph specific registration happens in addition to the call to \ref registerPlottable by the
QCPAbstractPlottable base class.
*/
bool QCustomPlot::registerGraph(QCPGraph *graph)
{
if (!graph)
{
qDebug() << Q_FUNC_INFO << "passed graph is zero";
return false;
}
if (mGraphs.contains(graph))
{
qDebug() << Q_FUNC_INFO << "graph already registered with this QCustomPlot";
return false;
}
mGraphs.append(graph);
return true;
}
/*! \internal
Registers the specified item with this QCustomPlot. QCustomPlot takes ownership of the item.
Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
item is this QCustomPlot.
This method is called automatically in the QCPAbstractItem base class constructor.
*/
bool QCustomPlot::registerItem(QCPAbstractItem *item)
{
if (mItems.contains(item))
{
qDebug() << Q_FUNC_INFO << "item already added to this QCustomPlot:" << reinterpret_cast<quintptr>(item);
return false;
}
if (item->parentPlot() != this)
{
qDebug() << Q_FUNC_INFO << "item not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item);
return false;
}
mItems.append(item);
if (!item->layer()) // usually the layer is already set in the constructor of the item (via QCPLayerable constructor)
item->setLayer(currentLayer());
return true;
}
/*! \internal
Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called
after every operation that changes the layer indices, like layer removal, layer creation, layer
moving.
*/
void QCustomPlot::updateLayerIndices() const
{
for (int i=0; i<mLayers.size(); ++i)
mLayers.at(i)->mIndex = i;
}
/*! \internal
Returns the top-most layerable at pixel position \a pos. If \a onlySelectable is set to true,
only those layerables that are selectable will be considered. (Layerable subclasses communicate
their selectability via the QCPLayerable::selectTest method, by returning -1.)
\a selectionDetails is an output parameter that contains selection specifics of the affected
layerable. This is useful if the respective layerable shall be given a subsequent
QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
information about which part of the layerable was hit, in multi-part layerables (e.g.
QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
QCPDataSelection instance with the single data point which is closest to \a pos.
\see layerableListAt, layoutElementAt, axisRectAt
*/
QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const
{
QList<QVariant> details;
QList<QCPLayerable*> candidates = layerableListAt(pos, onlySelectable, selectionDetails ? &details : nullptr);
if (selectionDetails && !details.isEmpty())
*selectionDetails = details.first();
if (!candidates.isEmpty())
return candidates.first();
else
return nullptr;
}
/*! \internal
Returns the layerables at pixel position \a pos. If \a onlySelectable is set to true, only those
layerables that are selectable will be considered. (Layerable subclasses communicate their
selectability via the QCPLayerable::selectTest method, by returning -1.)
The returned list is sorted by the layerable/drawing order such that the layerable that appears
on top in the plot is at index 0 of the returned list. If you only need to know the top
layerable, rather use \ref layerableAt.
\a selectionDetails is an output parameter that contains selection specifics of the affected
layerable. This is useful if the respective layerable shall be given a subsequent
QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
information about which part of the layerable was hit, in multi-part layerables (e.g.
QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
QCPDataSelection instance with the single data point which is closest to \a pos.
\see layerableAt, layoutElementAt, axisRectAt
*/
QList<QCPLayerable*> QCustomPlot::layerableListAt(const QPointF &pos, bool onlySelectable, QList<QVariant> *selectionDetails) const
{
QList<QCPLayerable*> result;
for (int layerIndex=static_cast<int>(mLayers.size())-1; layerIndex>=0; --layerIndex)
{
const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
for (int i=static_cast<int>(layerables.size())-1; i>=0; --i)
{
if (!layerables.at(i)->realVisibility())
continue;
QVariant details;
double dist = layerables.at(i)->selectTest(pos, onlySelectable, selectionDetails ? &details : nullptr);
if (dist >= 0 && dist < selectionTolerance())
{
result.append(layerables.at(i));
if (selectionDetails)
selectionDetails->append(details);
}
}
}
return result;
}
/*!
Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is
sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead
to a full resolution file with width 200.) If the \a format supports compression, \a quality may
be between 0 and 100 to control it.
Returns true on success. If this function fails, most likely the given \a format isn't supported
by the system, see Qt docs about QImageWriter::supportedImageFormats().
The \a resolution will be written to the image file header (if the file format supports this) and
has no direct consequence for the quality or the pixel size. However, if opening the image with a
tool which respects the metadata, it will be able to scale the image to match either a given size
in real units of length (inch, centimeters, etc.), or the target display DPI. You can specify in
which units \a resolution is given, by setting \a resolutionUnit. The \a resolution is converted
to the format's expected resolution unit internally.
\see saveBmp, saveJpg, savePng, savePdf
*/
bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
{
QImage buffer = toPixmap(width, height, scale).toImage();
int dotsPerMeter = 0;
switch (resolutionUnit)
{
case QCP::ruDotsPerMeter: dotsPerMeter = resolution; break;
case QCP::ruDotsPerCentimeter: dotsPerMeter = resolution*100; break;
case QCP::ruDotsPerInch: dotsPerMeter = int(resolution/0.0254); break;
}
buffer.setDotsPerMeterX(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
buffer.setDotsPerMeterY(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
if (!buffer.isNull())
return buffer.save(fileName, format, quality);
else
return false;
}
/*!
Renders the plot to a pixmap and returns it.
The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and
scale 2.0 lead to a full resolution pixmap with width 200.)
\see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf
*/
QPixmap QCustomPlot::toPixmap(int width, int height, double scale)
{
// this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too.
int newWidth, newHeight;
if (width == 0 || height == 0)
{
newWidth = this->width();
newHeight = this->height();
} else
{
newWidth = width;
newHeight = height;
}
int scaledWidth = qRound(scale*newWidth);
int scaledHeight = qRound(scale*newHeight);
QPixmap result(scaledWidth, scaledHeight);
result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later
QCPPainter painter;
painter.begin(&result);
if (painter.isActive())
{
QRect oldViewport = viewport();
setViewport(QRect(0, 0, newWidth, newHeight));
painter.setMode(QCPPainter::pmNoCaching);
if (!qFuzzyCompare(scale, 1.0))
{
if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales
painter.setMode(QCPPainter::pmNonCosmetic);
painter.scale(scale, scale);
}
if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill
painter.fillRect(mViewport, mBackgroundBrush);
draw(&painter);
setViewport(oldViewport);
painter.end();
} else // might happen if pixmap has width or height zero
{
qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap";
return QPixmap();
}
return result;
}
/*!
Renders the plot using the passed \a painter.
The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will
appear scaled accordingly.
\note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter
on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with
the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter.
\see toPixmap
*/
void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
{
// this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too.
int newWidth, newHeight;
if (width == 0 || height == 0)
{
newWidth = this->width();
newHeight = this->height();
} else
{
newWidth = width;
newHeight = height;
}
if (painter->isActive())
{
QRect oldViewport = viewport();
setViewport(QRect(0, 0, newWidth, newHeight));
painter->setMode(QCPPainter::pmNoCaching);
if (mBackgroundBrush.style() != Qt::NoBrush) // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here
painter->fillRect(mViewport, mBackgroundBrush);
draw(painter);
setViewport(oldViewport);
} else
qDebug() << Q_FUNC_INFO << "Passed painter is not active";
}
/* end of 'src/core.cpp' */
/* including file 'src/colorgradient.cpp' */
/* modified 2022-11-06T12:45:56, size 25408 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPColorGradient
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPColorGradient
\brief Defines a color gradient for use with e.g. \ref QCPColorMap
This class describes a color gradient which can be used to encode data with color. For example,
QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which
take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color)
with a \a position from 0 to 1. In between these defined color positions, the
color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation.
Alternatively, load one of the preset color gradients shown in the image below, with \ref
loadPreset, or by directly specifying the preset in the constructor.
Apart from red, green and blue components, the gradient also interpolates the alpha values of the
configured color stops. This allows to display some portions of the data range as transparent in
the plot.
How NaN values are interpreted can be configured with \ref setNanHandling.
\image html QCPColorGradient.png
The constructor \ref QCPColorGradient(GradientPreset preset) allows directly converting a \ref
GradientPreset to a QCPColorGradient. This means that you can directly pass \ref GradientPreset
to all the \a setGradient methods, e.g.:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient
The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the
color gradient shall be applied periodically (wrapping around) to data values that lie outside
the data range specified on the plottable instance can be controlled with \ref setPeriodic.
*/
/*!
Constructs a new, empty QCPColorGradient with no predefined color stops. You can add own color
stops with \ref setColorStopAt.
The color level count is initialized to 350.
*/
QCPColorGradient::QCPColorGradient() :
mLevelCount(350),
mColorInterpolation(ciRGB),
mNanHandling(nhNone),
mNanColor(Qt::black),
mPeriodic(false),
mColorBufferInvalidated(true)
{
mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
}
/*!
Constructs a new QCPColorGradient initialized with the colors and color interpolation according
to \a preset.
The color level count is initialized to 350.
*/
QCPColorGradient::QCPColorGradient(GradientPreset preset) :
mLevelCount(350),
mColorInterpolation(ciRGB),
mNanHandling(nhNone),
mNanColor(Qt::black),
mPeriodic(false),
mColorBufferInvalidated(true)
{
mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
loadPreset(preset);
}
/* undocumented operator */
bool QCPColorGradient::operator==(const QCPColorGradient &other) const
{
return ((other.mLevelCount == this->mLevelCount) &&
(other.mColorInterpolation == this->mColorInterpolation) &&
(other.mNanHandling == this ->mNanHandling) &&
(other.mNanColor == this->mNanColor) &&
(other.mPeriodic == this->mPeriodic) &&
(other.mColorStops == this->mColorStops));
}
/*!
Sets the number of discretization levels of the color gradient to \a n. The default is 350 which
is typically enough to create a smooth appearance. The minimum number of levels is 2.
\image html QCPColorGradient-levelcount.png
*/
void QCPColorGradient::setLevelCount(int n)
{
if (n < 2)
{
qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n;
n = 2;
}
if (n != mLevelCount)
{
mLevelCount = n;
mColorBufferInvalidated = true;
}
}
/*!
Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the
colors are the values of the passed QMap \a colorStops. In between these color stops, the color
is interpolated according to \ref setColorInterpolation.
A more convenient way to create a custom gradient may be to clear all color stops with \ref
clearColorStops (or creating a new, empty QCPColorGradient) and then adding them one by one with
\ref setColorStopAt.
\see clearColorStops
*/
void QCPColorGradient::setColorStops(const QMap<double, QColor> &colorStops)
{
mColorStops = colorStops;
mColorBufferInvalidated = true;
}
/*!
Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between
these color stops, the color is interpolated according to \ref setColorInterpolation.
\see setColorStops, clearColorStops
*/
void QCPColorGradient::setColorStopAt(double position, const QColor &color)
{
mColorStops.insert(position, color);
mColorBufferInvalidated = true;
}
/*!
Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be
interpolated linearly in RGB or in HSV color space.
For example, a sweep in RGB space from red to green will have a muddy brown intermediate color,
whereas in HSV space the intermediate color is yellow.
*/
void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation)
{
if (interpolation != mColorInterpolation)
{
mColorInterpolation = interpolation;
mColorBufferInvalidated = true;
}
}
/*!
Sets how NaNs in the data are displayed in the plot.
\see setNanColor
*/
void QCPColorGradient::setNanHandling(QCPColorGradient::NanHandling handling)
{
mNanHandling = handling;
}
/*!
Sets the color that NaN data is represented by, if \ref setNanHandling is set
to ref nhNanColor.
\see setNanHandling
*/
void QCPColorGradient::setNanColor(const QColor &color)
{
mNanColor = color;
}
/*!
Sets whether data points that are outside the configured data range (e.g. \ref
QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether
they all have the same color, corresponding to the respective gradient boundary color.
\image html QCPColorGradient-periodic.png
As shown in the image above, gradients that have the same start and end color are especially
suitable for a periodic gradient mapping, since they produce smooth color transitions throughout
the color map. A preset that has this property is \ref gpHues.
In practice, using periodic color gradients makes sense when the data corresponds to a periodic
dimension, such as an angle or a phase. If this is not the case, the color encoding might become
ambiguous, because multiple different data values are shown as the same color.
*/
void QCPColorGradient::setPeriodic(bool enabled)
{
mPeriodic = enabled;
}
/*! \overload
This method is used to quickly convert a \a data array to colors. The colors will be output in
the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this
function. The data range that shall be used for mapping the data value to the gradient is passed
in \a range. \a logarithmic indicates whether the data values shall be mapped to colors
logarithmically.
if \a data actually contains 2D-data linearized via <tt>[row*columnCount + column]</tt>, you can
set \a dataIndexFactor to <tt>columnCount</tt> to convert a column instead of a row of the data
array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data
is addressed <tt>data[i*dataIndexFactor]</tt>.
Use the overloaded method to additionally provide alpha map data.
The QRgb values that are placed in \a scanLine have their r, g, and b components premultiplied
with alpha (see QImage::Format_ARGB32_Premultiplied).
*/
void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
{
// If you change something here, make sure to also adapt color() and the other colorize() overload
if (!data)
{
qDebug() << Q_FUNC_INFO << "null pointer given as data";
return;
}
if (!scanLine)
{
qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
return;
}
if (mColorBufferInvalidated)
updateColorBuffer();
const bool skipNanCheck = mNanHandling == nhNone;
const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
for (int i=0; i<n; ++i)
{
const double value = data[dataIndexFactor*i];
if (skipNanCheck || !std::isnan(value))
{
qint64 index = qint64((!logarithmic ? value-range.lower : qLn(value/range.lower)) * posToIndexFactor);
if (!mPeriodic)
{
index = qBound(qint64(0), index, qint64(mLevelCount-1));
} else
{
index %= mLevelCount;
if (index < 0)
index += mLevelCount;
}
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
scanLine[i] = mColorBuffer.at(static_cast<int>(index));
#else
scanLine[i] = mColorBuffer.at(index);
#endif
} else
{
switch(mNanHandling)
{
case nhLowestColor: scanLine[i] = mColorBuffer.first(); break;
case nhHighestColor: scanLine[i] = mColorBuffer.last(); break;
case nhTransparent: scanLine[i] = qRgba(0, 0, 0, 0); break;
case nhNanColor: scanLine[i] = mNanColor.rgba(); break;
case nhNone: break; // shouldn't happen
}
}
}
}
/*! \overload
Additionally to the other overload of \ref colorize, this method takes the array \a alpha, which
has the same size and structure as \a data and encodes the alpha information per data point.
The QRgb values that are placed in \a scanLine have their r, g and b components premultiplied
with alpha (see QImage::Format_ARGB32_Premultiplied).
*/
void QCPColorGradient::colorize(const double *data, const unsigned char *alpha, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
{
// If you change something here, make sure to also adapt color() and the other colorize() overload
if (!data)
{
qDebug() << Q_FUNC_INFO << "null pointer given as data";
return;
}
if (!alpha)
{
qDebug() << Q_FUNC_INFO << "null pointer given as alpha";
return;
}
if (!scanLine)
{
qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
return;
}
if (mColorBufferInvalidated)
updateColorBuffer();
const bool skipNanCheck = mNanHandling == nhNone;
const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
for (int i=0; i<n; ++i)
{
const double value = data[dataIndexFactor*i];
if (skipNanCheck || !std::isnan(value))
{
qint64 index = qint64((!logarithmic ? value-range.lower : qLn(value/range.lower)) * posToIndexFactor);
if (!mPeriodic)
{
index = qBound(qint64(0), index, qint64(mLevelCount-1));
} else
{
index %= mLevelCount;
if (index < 0)
index += mLevelCount;
}
if (alpha[dataIndexFactor*i] == 255)
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
scanLine[i] = mColorBuffer.at(static_cast<int>(index));
#else
scanLine[i] = mColorBuffer.at(index);
#endif
} else
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
const QRgb rgb = mColorBuffer.at(static_cast<int>(index));
#else
const QRgb rgb = mColorBuffer.at(index);
#endif
const float alphaF = alpha[dataIndexFactor*i]/255.0f;
scanLine[i] = qRgba(int(qRed(rgb)*alphaF), int(qGreen(rgb)*alphaF), int(qBlue(rgb)*alphaF), int(qAlpha(rgb)*alphaF)); // also multiply r,g,b with alpha, to conform to Format_ARGB32_Premultiplied
}
} else
{
switch(mNanHandling)
{
case nhLowestColor: scanLine[i] = mColorBuffer.first(); break;
case nhHighestColor: scanLine[i] = mColorBuffer.last(); break;
case nhTransparent: scanLine[i] = qRgba(0, 0, 0, 0); break;
case nhNanColor: scanLine[i] = mNanColor.rgba(); break;
case nhNone: break; // shouldn't happen
}
}
}
}
/*! \internal
This method is used to colorize a single data value given in \a position, to colors. The data
range that shall be used for mapping the data value to the gradient is passed in \a range. \a
logarithmic indicates whether the data value shall be mapped to a color logarithmically.
If an entire array of data values shall be converted, rather use \ref colorize, for better
performance.
The returned QRgb has its r, g and b components premultiplied with alpha (see
QImage::Format_ARGB32_Premultiplied).
*/
QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic)
{
// If you change something here, make sure to also adapt ::colorize()
if (mColorBufferInvalidated)
updateColorBuffer();
const bool skipNanCheck = mNanHandling == nhNone;
if (!skipNanCheck && std::isnan(position))
{
switch(mNanHandling)
{
case nhLowestColor: return mColorBuffer.first();
case nhHighestColor: return mColorBuffer.last();
case nhTransparent: return qRgba(0, 0, 0, 0);
case nhNanColor: return mNanColor.rgba();
case nhNone: return qRgba(0, 0, 0, 0); // shouldn't happen
}
}
const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
int index = int((!logarithmic ? position-range.lower : qLn(position/range.lower)) * posToIndexFactor);
if (!mPeriodic)
{
index = qBound(0, index, mLevelCount-1);
} else
{
index %= mLevelCount;
if (index < 0)
index += mLevelCount;
}
return mColorBuffer.at(index);
}
/*!
Clears the current color stops and loads the specified \a preset. A preset consists of predefined
color stops and the corresponding color interpolation method.
The available presets are:
\image html QCPColorGradient.png
*/
void QCPColorGradient::loadPreset(GradientPreset preset)
{
clearColorStops();
switch (preset)
{
case gpGrayscale:
setColorInterpolation(ciRGB);
setColorStopAt(0, Qt::black);
setColorStopAt(1, Qt::white);
break;
case gpHot:
setColorInterpolation(ciRGB);
setColorStopAt(0, QColor(50, 0, 0));
setColorStopAt(0.2, QColor(180, 10, 0));
setColorStopAt(0.4, QColor(245, 50, 0));
setColorStopAt(0.6, QColor(255, 150, 10));
setColorStopAt(0.8, QColor(255, 255, 50));
setColorStopAt(1, QColor(255, 255, 255));
break;
case gpCold:
setColorInterpolation(ciRGB);
setColorStopAt(0, QColor(0, 0, 50));
setColorStopAt(0.2, QColor(0, 10, 180));
setColorStopAt(0.4, QColor(0, 50, 245));
setColorStopAt(0.6, QColor(10, 150, 255));
setColorStopAt(0.8, QColor(50, 255, 255));
setColorStopAt(1, QColor(255, 255, 255));
break;
case gpNight:
setColorInterpolation(ciHSV);
setColorStopAt(0, QColor(10, 20, 30));
setColorStopAt(1, QColor(250, 255, 250));
break;
case gpCandy:
setColorInterpolation(ciHSV);
setColorStopAt(0, QColor(0, 0, 255));
setColorStopAt(1, QColor(255, 250, 250));
break;
case gpGeography:
setColorInterpolation(ciRGB);
setColorStopAt(0, QColor(70, 170, 210));
setColorStopAt(0.20, QColor(90, 160, 180));
setColorStopAt(0.25, QColor(45, 130, 175));
setColorStopAt(0.30, QColor(100, 140, 125));
setColorStopAt(0.5, QColor(100, 140, 100));
setColorStopAt(0.6, QColor(130, 145, 120));
setColorStopAt(0.7, QColor(140, 130, 120));
setColorStopAt(0.9, QColor(180, 190, 190));
setColorStopAt(1, QColor(210, 210, 230));
break;
case gpIon:
setColorInterpolation(ciHSV);
setColorStopAt(0, QColor(50, 10, 10));
setColorStopAt(0.45, QColor(0, 0, 255));
setColorStopAt(0.8, QColor(0, 255, 255));
setColorStopAt(1, QColor(0, 255, 0));
break;
case gpThermal:
setColorInterpolation(ciRGB);
setColorStopAt(0, QColor(0, 0, 50));
setColorStopAt(0.15, QColor(20, 0, 120));
setColorStopAt(0.33, QColor(200, 30, 140));
setColorStopAt(0.6, QColor(255, 100, 0));
setColorStopAt(0.85, QColor(255, 255, 40));
setColorStopAt(1, QColor(255, 255, 255));
break;
case gpPolar:
setColorInterpolation(ciRGB);
setColorStopAt(0, QColor(50, 255, 255));
setColorStopAt(0.18, QColor(10, 70, 255));
setColorStopAt(0.28, QColor(10, 10, 190));
setColorStopAt(0.5, QColor(0, 0, 0));
setColorStopAt(0.72, QColor(190, 10, 10));
setColorStopAt(0.82, QColor(255, 70, 10));
setColorStopAt(1, QColor(255, 255, 50));
break;
case gpSpectrum:
setColorInterpolation(ciHSV);
setColorStopAt(0, QColor(50, 0, 50));
setColorStopAt(0.15, QColor(0, 0, 255));
setColorStopAt(0.35, QColor(0, 255, 255));
setColorStopAt(0.6, QColor(255, 255, 0));
setColorStopAt(0.75, QColor(255, 30, 0));
setColorStopAt(1, QColor(50, 0, 0));
break;
case gpJet:
setColorInterpolation(ciRGB);
setColorStopAt(0, QColor(0, 0, 100));
setColorStopAt(0.15, QColor(0, 50, 255));
setColorStopAt(0.35, QColor(0, 255, 255));
setColorStopAt(0.65, QColor(255, 255, 0));
setColorStopAt(0.85, QColor(255, 30, 0));
setColorStopAt(1, QColor(100, 0, 0));
break;
case gpHues:
setColorInterpolation(ciHSV);
setColorStopAt(0, QColor(255, 0, 0));
setColorStopAt(1.0/3.0, QColor(0, 0, 255));
setColorStopAt(2.0/3.0, QColor(0, 255, 0));
setColorStopAt(1, QColor(255, 0, 0));
break;
}
}
/*!
Clears all color stops.
\see setColorStops, setColorStopAt
*/
void QCPColorGradient::clearColorStops()
{
mColorStops.clear();
mColorBufferInvalidated = true;
}
/*!
Returns an inverted gradient. The inverted gradient has all properties as this \ref
QCPColorGradient, but the order of the color stops is inverted.
\see setColorStops, setColorStopAt
*/
QCPColorGradient QCPColorGradient::inverted() const
{
QCPColorGradient result(*this);
result.clearColorStops();
for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
result.setColorStopAt(1.0-it.key(), it.value());
return result;
}
/*! \internal
Returns true if the color gradient uses transparency, i.e. if any of the configured color stops
has an alpha value below 255.
*/
bool QCPColorGradient::stopsUseAlpha() const
{
for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
{
if (it.value().alpha() < 255)
return true;
}
return false;
}
/*! \internal
Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly
convert positions to colors. This is where the interpolation between color stops is calculated.
*/
void QCPColorGradient::updateColorBuffer()
{
if (mColorBuffer.size() != mLevelCount)
mColorBuffer.resize(mLevelCount);
if (mColorStops.size() > 1)
{
double indexToPosFactor = 1.0/double(mLevelCount-1);
const bool useAlpha = stopsUseAlpha();
for (int i=0; i<mLevelCount; ++i)
{
double position = i*indexToPosFactor;
QMap<double, QColor>::const_iterator it = const_cast<const QMap<double, QColor>*>(&mColorStops)->lowerBound(position); // force using the const lowerBound method
if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop
{
if (useAlpha)
{
const QColor col = std::prev(it).value();
const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied
mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier),
int(col.green()*alphaPremultiplier),
int(col.blue()*alphaPremultiplier),
col.alpha());
} else
mColorBuffer[i] = std::prev(it).value().rgba();
} else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop
{
if (useAlpha)
{
const QColor &col = it.value();
const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied
mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier),
int(col.green()*alphaPremultiplier),
int(col.blue()*alphaPremultiplier),
col.alpha());
} else
mColorBuffer[i] = it.value().rgba();
} else // position is in between stops (or on an intermediate stop), interpolate color
{
QMap<double, QColor>::const_iterator high = it;
QMap<double, QColor>::const_iterator low = std::prev(it);
double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1
switch (mColorInterpolation)
{
case ciRGB:
{
if (useAlpha)
{
const int alpha = int((1-t)*low.value().alpha() + t*high.value().alpha());
const double alphaPremultiplier = alpha/255.0; // since we use QImage::Format_ARGB32_Premultiplied
mColorBuffer[i] = qRgba(int( ((1-t)*low.value().red() + t*high.value().red())*alphaPremultiplier ),
int( ((1-t)*low.value().green() + t*high.value().green())*alphaPremultiplier ),
int( ((1-t)*low.value().blue() + t*high.value().blue())*alphaPremultiplier ),
alpha);
} else
{
mColorBuffer[i] = qRgb(int( ((1-t)*low.value().red() + t*high.value().red()) ),
int( ((1-t)*low.value().green() + t*high.value().green()) ),
int( ((1-t)*low.value().blue() + t*high.value().blue())) );
}
break;
}
case ciHSV:
{
QColor lowHsv = low.value().toHsv();
QColor highHsv = high.value().toHsv();
double hue = 0;
double hueDiff = highHsv.hueF()-lowHsv.hueF();
if (hueDiff > 0.5)
hue = lowHsv.hueF() - t*(1.0-hueDiff);
else if (hueDiff < -0.5)
hue = lowHsv.hueF() + t*(1.0+hueDiff);
else
hue = lowHsv.hueF() + t*hueDiff;
if (hue < 0) hue += 1.0;
else if (hue >= 1.0) hue -= 1.0;
if (useAlpha)
{
const QRgb rgb = QColor::fromHsvF(hue,
(1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
(1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
const double alpha = (1-t)*lowHsv.alphaF() + t*highHsv.alphaF();
mColorBuffer[i] = qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha));
}
else
{
mColorBuffer[i] = QColor::fromHsvF(hue,
(1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
(1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
}
break;
}
}
}
}
} else if (mColorStops.size() == 1)
{
const QRgb rgb = mColorStops.constBegin().value().rgb();
const double alpha = mColorStops.constBegin().value().alphaF();
mColorBuffer.fill(qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha)));
} else // mColorStops is empty, fill color buffer with black
{
mColorBuffer.fill(qRgb(0, 0, 0));
}
mColorBufferInvalidated = false;
}
/* end of 'src/colorgradient.cpp' */
/* including file 'src/selectiondecorator-bracket.cpp' */
/* modified 2022-11-06T12:45:56, size 12308 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPSelectionDecoratorBracket
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPSelectionDecoratorBracket
\brief A selection decorator which draws brackets around each selected data segment
Additionally to the regular highlighting of selected segments via color, fill and scatter style,
this \ref QCPSelectionDecorator subclass draws markers at the begin and end of each selected data
segment of the plottable.
The shape of the markers can be controlled with \ref setBracketStyle, \ref setBracketWidth and
\ref setBracketHeight. The color/fill can be controlled with \ref setBracketPen and \ref
setBracketBrush.
To introduce custom bracket styles, it is only necessary to sublcass \ref
QCPSelectionDecoratorBracket and reimplement \ref drawBracket. The rest will be managed by the
base class.
*/
/*!
Creates a new QCPSelectionDecoratorBracket instance with default values.
*/
QCPSelectionDecoratorBracket::QCPSelectionDecoratorBracket() :
mBracketPen(QPen(Qt::black)),
mBracketBrush(Qt::NoBrush),
mBracketWidth(5),
mBracketHeight(50),
mBracketStyle(bsSquareBracket),
mTangentToData(false),
mTangentAverage(2)
{
}
QCPSelectionDecoratorBracket::~QCPSelectionDecoratorBracket()
{
}
/*!
Sets the pen that will be used to draw the brackets at the beginning and end of each selected
data segment.
*/
void QCPSelectionDecoratorBracket::setBracketPen(const QPen &pen)
{
mBracketPen = pen;
}
/*!
Sets the brush that will be used to draw the brackets at the beginning and end of each selected
data segment.
*/
void QCPSelectionDecoratorBracket::setBracketBrush(const QBrush &brush)
{
mBracketBrush = brush;
}
/*!
Sets the width of the drawn bracket. The width dimension is always parallel to the key axis of
the data, or the tangent direction of the current data slope, if \ref setTangentToData is
enabled.
*/
void QCPSelectionDecoratorBracket::setBracketWidth(int width)
{
mBracketWidth = width;
}
/*!
Sets the height of the drawn bracket. The height dimension is always perpendicular to the key axis
of the data, or the tangent direction of the current data slope, if \ref setTangentToData is
enabled.
*/
void QCPSelectionDecoratorBracket::setBracketHeight(int height)
{
mBracketHeight = height;
}
/*!
Sets the shape that the bracket/marker will have.
\see setBracketWidth, setBracketHeight
*/
void QCPSelectionDecoratorBracket::setBracketStyle(QCPSelectionDecoratorBracket::BracketStyle style)
{
mBracketStyle = style;
}
/*!
Sets whether the brackets will be rotated such that they align with the slope of the data at the
position that they appear in.
For noisy data, it might be more visually appealing to average the slope over multiple data
points. This can be configured via \ref setTangentAverage.
*/
void QCPSelectionDecoratorBracket::setTangentToData(bool enabled)
{
mTangentToData = enabled;
}
/*!
Controls over how many data points the slope shall be averaged, when brackets shall be aligned
with the data (if \ref setTangentToData is true).
From the position of the bracket, \a pointCount points towards the selected data range will be
taken into account. The smallest value of \a pointCount is 1, which is effectively equivalent to
disabling \ref setTangentToData.
*/
void QCPSelectionDecoratorBracket::setTangentAverage(int pointCount)
{
mTangentAverage = pointCount;
if (mTangentAverage < 1)
mTangentAverage = 1;
}
/*!
Draws the bracket shape with \a painter. The parameter \a direction is either -1 or 1 and
indicates whether the bracket shall point to the left or the right (i.e. is a closing or opening
bracket, respectively).
The passed \a painter already contains all transformations that are necessary to position and
rotate the bracket appropriately. Painting operations can be performed as if drawing upright
brackets on flat data with horizontal key axis, with (0, 0) being the center of the bracket.
If you wish to sublcass \ref QCPSelectionDecoratorBracket in order to provide custom bracket
shapes (see \ref QCPSelectionDecoratorBracket::bsUserStyle), this is the method you should
reimplement.
*/
void QCPSelectionDecoratorBracket::drawBracket(QCPPainter *painter, int direction) const
{
switch (mBracketStyle)
{
case bsSquareBracket:
{
painter->drawLine(QLineF(mBracketWidth*direction, -mBracketHeight*0.5, 0, -mBracketHeight*0.5));
painter->drawLine(QLineF(mBracketWidth*direction, mBracketHeight*0.5, 0, mBracketHeight*0.5));
painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
break;
}
case bsHalfEllipse:
{
painter->drawArc(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight), -90*16, -180*16*direction);
break;
}
case bsEllipse:
{
painter->drawEllipse(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight));
break;
}
case bsPlus:
{
painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
painter->drawLine(QLineF(-mBracketWidth*0.5, 0, mBracketWidth*0.5, 0));
break;
}
default:
{
qDebug() << Q_FUNC_INFO << "unknown/custom bracket style can't be handled by default implementation:" << static_cast<int>(mBracketStyle);
break;
}
}
}
/*!
Draws the bracket decoration on the data points at the begin and end of each selected data
segment given in \a seletion.
It uses the method \ref drawBracket to actually draw the shapes.
\seebaseclassmethod
*/
void QCPSelectionDecoratorBracket::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
{
if (!mPlottable || selection.isEmpty()) return;
if (QCPPlottableInterface1D *interface1d = mPlottable->interface1D())
{
foreach (const QCPDataRange &dataRange, selection.dataRanges())
{
// determine position and (if tangent mode is enabled) angle of brackets:
int openBracketDir = (mPlottable->keyAxis() && !mPlottable->keyAxis()->rangeReversed()) ? 1 : -1;
int closeBracketDir = -openBracketDir;
QPointF openBracketPos = getPixelCoordinates(interface1d, dataRange.begin());
QPointF closeBracketPos = getPixelCoordinates(interface1d, dataRange.end()-1);
double openBracketAngle = 0;
double closeBracketAngle = 0;
if (mTangentToData)
{
openBracketAngle = getTangentAngle(interface1d, dataRange.begin(), openBracketDir);
closeBracketAngle = getTangentAngle(interface1d, dataRange.end()-1, closeBracketDir);
}
// draw opening bracket:
QTransform oldTransform = painter->transform();
painter->setPen(mBracketPen);
painter->setBrush(mBracketBrush);
painter->translate(openBracketPos);
painter->rotate(openBracketAngle/M_PI*180.0);
drawBracket(painter, openBracketDir);
painter->setTransform(oldTransform);
// draw closing bracket:
painter->setPen(mBracketPen);
painter->setBrush(mBracketBrush);
painter->translate(closeBracketPos);
painter->rotate(closeBracketAngle/M_PI*180.0);
drawBracket(painter, closeBracketDir);
painter->setTransform(oldTransform);
}
}
}
/*! \internal
If \ref setTangentToData is enabled, brackets need to be rotated according to the data slope.
This method returns the angle in radians by which a bracket at the given \a dataIndex must be
rotated.
The parameter \a direction must be set to either -1 or 1, representing whether it is an opening
or closing bracket. Since for slope calculation multiple data points are required, this defines
the direction in which the algorithm walks, starting at \a dataIndex, to average those data
points. (see \ref setTangentToData and \ref setTangentAverage)
\a interface1d is the interface to the plottable's data which is used to query data coordinates.
*/
double QCPSelectionDecoratorBracket::getTangentAngle(const QCPPlottableInterface1D *interface1d, int dataIndex, int direction) const
{
if (!interface1d || dataIndex < 0 || dataIndex >= interface1d->dataCount())
return 0;
direction = direction < 0 ? -1 : 1; // enforce direction is either -1 or 1
// how many steps we can actually go from index in the given direction without exceeding data bounds:
int averageCount;
if (direction < 0)
averageCount = qMin(mTangentAverage, dataIndex);
else
averageCount = qMin(mTangentAverage, interface1d->dataCount()-1-dataIndex);
qDebug() << averageCount;
// calculate point average of averageCount points:
QVector<QPointF> points(averageCount);
QPointF pointsAverage;
int currentIndex = dataIndex;
for (int i=0; i<averageCount; ++i)
{
points[i] = getPixelCoordinates(interface1d, currentIndex);
pointsAverage += points[i];
currentIndex += direction;
}
pointsAverage /= double(averageCount);
// calculate slope of linear regression through points:
double numSum = 0;
double denomSum = 0;
for (int i=0; i<averageCount; ++i)
{
const double dx = points.at(i).x()-pointsAverage.x();
const double dy = points.at(i).y()-pointsAverage.y();
numSum += dx*dy;
denomSum += dx*dx;
}
if (!qFuzzyIsNull(denomSum) && !qFuzzyIsNull(numSum))
{
return qAtan2(numSum, denomSum);
} else // undetermined angle, probably mTangentAverage == 1, so using only one data point
return 0;
}
/*! \internal
Returns the pixel coordinates of the data point at \a dataIndex, using \a interface1d to access
the data points.
*/
QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInterface1D *interface1d, int dataIndex) const
{
QCPAxis *keyAxis = mPlottable->keyAxis();
QCPAxis *valueAxis = mPlottable->valueAxis();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {0, 0}; }
if (keyAxis->orientation() == Qt::Horizontal)
return {keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)), valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex))};
else
return {valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)), keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex))};
}
/* end of 'src/selectiondecorator-bracket.cpp' */
/* including file 'src/layoutelements/layoutelement-axisrect.cpp' */
/* modified 2022-11-06T12:45:56, size 47193 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxisRect
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxisRect
\brief Holds multiple axes and arranges them in a rectangular shape.
This class represents an axis rect, a rectangular area that is bounded on all sides with an
arbitrary number of axes.
Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the
layout system allows to have multiple axis rects, e.g. arranged in a grid layout
(QCustomPlot::plotLayout).
By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be
accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index.
If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be
invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref
addAxes. To remove an axis, use \ref removeAxis.
The axis rect layerable itself only draws a background pixmap or color, if specified (\ref
setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an
explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be
placed on other layers, independently of the axis rect.
Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref
insetLayout and can be used to have other layout elements (or even other layouts with multiple
elements) hovering inside the axis rect.
If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The
behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel
is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable
via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are
only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref
QCP::iRangeZoom.
\image html AxisRectSpacingOverview.png
<center>Overview of the spacings and paddings that define the geometry of an axis. The dashed
line on the far left indicates the viewport/widget border.</center>
*/
/* start documentation of inline functions */
/*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const
Returns the inset layout of this axis rect. It can be used to place other layout elements (or
even layouts with multiple other elements) inside/on top of an axis rect.
\see QCPLayoutInset
*/
/*! \fn int QCPAxisRect::left() const
Returns the pixel position of the left border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::right() const
Returns the pixel position of the right border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::top() const
Returns the pixel position of the top border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::bottom() const
Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::width() const
Returns the pixel width of this axis rect. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::height() const
Returns the pixel height of this axis rect. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/*! \fn QSize QCPAxisRect::size() const
Returns the pixel size of this axis rect. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::topLeft() const
Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::topRight() const
Returns the top right corner of this axis rect in pixels. Margins are not taken into account
here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::bottomLeft() const
Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::bottomRight() const
Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::center() const
Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/* end documentation of inline functions */
/*!
Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four
sides, the top and right axes are set invisible initially.
*/
QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) :
QCPLayoutElement(parentPlot),
mBackgroundBrush(Qt::NoBrush),
mBackgroundScaled(true),
mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
mInsetLayout(new QCPLayoutInset),
mRangeDrag(Qt::Horizontal|Qt::Vertical),
mRangeZoom(Qt::Horizontal|Qt::Vertical),
mRangeZoomFactorHorz(0.85),
mRangeZoomFactorVert(0.85),
mDragging(false)
{
mInsetLayout->initializeParentPlot(mParentPlot);
mInsetLayout->setParentLayerable(this);
mInsetLayout->setParent(this);
setMinimumSize(50, 50);
setMinimumMargins(QMargins(15, 15, 15, 15));
mAxes.insert(QCPAxis::atLeft, QList<QCPAxis*>());
mAxes.insert(QCPAxis::atRight, QList<QCPAxis*>());
mAxes.insert(QCPAxis::atTop, QList<QCPAxis*>());
mAxes.insert(QCPAxis::atBottom, QList<QCPAxis*>());
if (setupDefaultAxes)
{
QCPAxis *xAxis = addAxis(QCPAxis::atBottom);
QCPAxis *yAxis = addAxis(QCPAxis::atLeft);
QCPAxis *xAxis2 = addAxis(QCPAxis::atTop);
QCPAxis *yAxis2 = addAxis(QCPAxis::atRight);
setRangeDragAxes(xAxis, yAxis);
setRangeZoomAxes(xAxis, yAxis);
xAxis2->setVisible(false);
yAxis2->setVisible(false);
xAxis->grid()->setVisible(true);
yAxis->grid()->setVisible(true);
xAxis2->grid()->setVisible(false);
yAxis2->grid()->setVisible(false);
xAxis2->grid()->setZeroLinePen(Qt::NoPen);
yAxis2->grid()->setZeroLinePen(Qt::NoPen);
xAxis2->grid()->setVisible(false);
yAxis2->grid()->setVisible(false);
}
}
QCPAxisRect::~QCPAxisRect()
{
delete mInsetLayout;
mInsetLayout = nullptr;
foreach (QCPAxis *axis, axes())
removeAxis(axis);
}
/*!
Returns the number of axes on the axis rect side specified with \a type.
\see axis
*/
int QCPAxisRect::axisCount(QCPAxis::AxisType type) const
{
return static_cast<int>(mAxes.value(type).size());
}
/*!
Returns the axis with the given \a index on the axis rect side specified with \a type.
\see axisCount, axes
*/
QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const
{
QList<QCPAxis*> ax(mAxes.value(type));
if (index >= 0 && index < ax.size())
{
return ax.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
return nullptr;
}
}
/*!
Returns all axes on the axis rect sides specified with \a types.
\a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
multiple sides.
\see axis
*/
QList<QCPAxis*> QCPAxisRect::axes(QCPAxis::AxisTypes types) const
{
QList<QCPAxis*> result;
if (types.testFlag(QCPAxis::atLeft))
result << mAxes.value(QCPAxis::atLeft);
if (types.testFlag(QCPAxis::atRight))
result << mAxes.value(QCPAxis::atRight);
if (types.testFlag(QCPAxis::atTop))
result << mAxes.value(QCPAxis::atTop);
if (types.testFlag(QCPAxis::atBottom))
result << mAxes.value(QCPAxis::atBottom);
return result;
}
/*! \overload
Returns all axes of this axis rect.
*/
QList<QCPAxis*> QCPAxisRect::axes() const
{
QList<QCPAxis*> result;
QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
while (it.hasNext())
{
it.next();
result << it.value();
}
return result;
}
/*!
Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
remove an axis, use \ref removeAxis instead of deleting it manually.
You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was
previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
with this axis rect as parent and with the same axis type as specified in \a type. If this is not
the case, a debug output is generated, the axis is not added, and the method returns \c nullptr.
This method can not be used to move \a axis between axis rects. The same \a axis instance must
not be added multiple times to the same or different axis rects.
If an axis rect side already contains one or more axes, the lower and upper endings of the new
axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
QCPLineEnding::esHalfBar.
\see addAxes, setupFullAxesBox
*/
QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis)
{
QCPAxis *newAxis = axis;
if (!newAxis)
{
newAxis = new QCPAxis(this, type);
} else // user provided existing axis instance, do some sanity checks
{
if (newAxis->axisType() != type)
{
qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter";
return nullptr;
}
if (newAxis->axisRect() != this)
{
qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect";
return nullptr;
}
if (axes().contains(newAxis))
{
qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect";
return nullptr;
}
}
if (!mAxes[type].isEmpty()) // multiple axes on one side, add half-bar axis ending to additional axes with offset
{
bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom);
newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert));
newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert));
}
mAxes[type].append(newAxis);
// reset convenience axis pointers on parent QCustomPlot if they are unset:
if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
{
switch (type)
{
case QCPAxis::atBottom: { if (!mParentPlot->xAxis) mParentPlot->xAxis = newAxis; break; }
case QCPAxis::atLeft: { if (!mParentPlot->yAxis) mParentPlot->yAxis = newAxis; break; }
case QCPAxis::atTop: { if (!mParentPlot->xAxis2) mParentPlot->xAxis2 = newAxis; break; }
case QCPAxis::atRight: { if (!mParentPlot->yAxis2) mParentPlot->yAxis2 = newAxis; break; }
}
}
return newAxis;
}
/*!
Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an
<tt>or</tt>-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once.
Returns a list of the added axes.
\see addAxis, setupFullAxesBox
*/
QList<QCPAxis*> QCPAxisRect::addAxes(QCPAxis::AxisTypes types)
{
QList<QCPAxis*> result;
if (types.testFlag(QCPAxis::atLeft))
result << addAxis(QCPAxis::atLeft);
if (types.testFlag(QCPAxis::atRight))
result << addAxis(QCPAxis::atRight);
if (types.testFlag(QCPAxis::atTop))
result << addAxis(QCPAxis::atTop);
if (types.testFlag(QCPAxis::atBottom))
result << addAxis(QCPAxis::atBottom);
return result;
}
/*!
Removes the specified \a axis from the axis rect and deletes it.
Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
\see addAxis
*/
bool QCPAxisRect::removeAxis(QCPAxis *axis)
{
// don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers:
QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
while (it.hasNext())
{
it.next();
if (it.value().contains(axis))
{
if (it.value().first() == axis && it.value().size() > 1) // if removing first axis, transfer axis offset to the new first axis (which at this point is the second axis, if it exists)
it.value()[1]->setOffset(axis->offset());
mAxes[it.key()].removeOne(axis);
if (qobject_cast<QCustomPlot*>(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot)
parentPlot()->axisRemoved(axis);
delete axis;
return true;
}
}
qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast<quintptr>(axis);
return false;
}
/*!
Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
All axes of this axis rect will have their range zoomed accordingly. If you only wish to zoom
specific axes, use the overloaded version of this method.
\see QCustomPlot::setSelectionRectMode
*/
void QCPAxisRect::zoom(const QRectF &pixelRect)
{
zoom(pixelRect, axes());
}
/*! \overload
Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
Only the axes passed in \a affectedAxes will have their ranges zoomed accordingly.
\see QCustomPlot::setSelectionRectMode
*/
void QCPAxisRect::zoom(const QRectF &pixelRect, const QList<QCPAxis*> &affectedAxes)
{
foreach (QCPAxis *axis, affectedAxes)
{
if (!axis)
{
qDebug() << Q_FUNC_INFO << "a passed axis was zero";
continue;
}
QCPRange pixelRange;
if (axis->orientation() == Qt::Horizontal)
pixelRange = QCPRange(pixelRect.left(), pixelRect.right());
else
pixelRange = QCPRange(pixelRect.top(), pixelRect.bottom());
axis->setRange(axis->pixelToCoord(pixelRange.lower), axis->pixelToCoord(pixelRange.upper));
}
}
/*!
Convenience function to create an axis on each side that doesn't have any axes yet and set their
visibility to true. Further, the top/right axes are assigned the following properties of the
bottom/left axes:
\li range (\ref QCPAxis::setRange)
\li range reversed (\ref QCPAxis::setRangeReversed)
\li scale type (\ref QCPAxis::setScaleType)
\li tick visibility (\ref QCPAxis::setTicks)
\li number format (\ref QCPAxis::setNumberFormat)
\li number precision (\ref QCPAxis::setNumberPrecision)
\li tick count of ticker (\ref QCPAxisTicker::setTickCount)
\li tick origin of ticker (\ref QCPAxisTicker::setTickOrigin)
Tick label visibility (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom
and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes.
*/
void QCPAxisRect::setupFullAxesBox(bool connectRanges)
{
QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
if (axisCount(QCPAxis::atBottom) == 0)
xAxis = addAxis(QCPAxis::atBottom);
else
xAxis = axis(QCPAxis::atBottom);
if (axisCount(QCPAxis::atLeft) == 0)
yAxis = addAxis(QCPAxis::atLeft);
else
yAxis = axis(QCPAxis::atLeft);
if (axisCount(QCPAxis::atTop) == 0)
xAxis2 = addAxis(QCPAxis::atTop);
else
xAxis2 = axis(QCPAxis::atTop);
if (axisCount(QCPAxis::atRight) == 0)
yAxis2 = addAxis(QCPAxis::atRight);
else
yAxis2 = axis(QCPAxis::atRight);
xAxis->setVisible(true);
yAxis->setVisible(true);
xAxis2->setVisible(true);
yAxis2->setVisible(true);
xAxis2->setTickLabels(false);
yAxis2->setTickLabels(false);
xAxis2->setRange(xAxis->range());
xAxis2->setRangeReversed(xAxis->rangeReversed());
xAxis2->setScaleType(xAxis->scaleType());
xAxis2->setTicks(xAxis->ticks());
xAxis2->setNumberFormat(xAxis->numberFormat());
xAxis2->setNumberPrecision(xAxis->numberPrecision());
xAxis2->ticker()->setTickCount(xAxis->ticker()->tickCount());
xAxis2->ticker()->setTickOrigin(xAxis->ticker()->tickOrigin());
yAxis2->setRange(yAxis->range());
yAxis2->setRangeReversed(yAxis->rangeReversed());
yAxis2->setScaleType(yAxis->scaleType());
yAxis2->setTicks(yAxis->ticks());
yAxis2->setNumberFormat(yAxis->numberFormat());
yAxis2->setNumberPrecision(yAxis->numberPrecision());
yAxis2->ticker()->setTickCount(yAxis->ticker()->tickCount());
yAxis2->ticker()->setTickOrigin(yAxis->ticker()->tickOrigin());
if (connectRanges)
{
connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange)));
connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange)));
}
}
/*!
Returns a list of all the plottables that are associated with this axis rect.
A plottable is considered associated with an axis rect if its key or value axis (or both) is in
this axis rect.
\see graphs, items
*/
QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const
{
// Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries
QList<QCPAbstractPlottable*> result;
foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables)
{
if (plottable->keyAxis()->axisRect() == this || plottable->valueAxis()->axisRect() == this)
result.append(plottable);
}
return result;
}
/*!
Returns a list of all the graphs that are associated with this axis rect.
A graph is considered associated with an axis rect if its key or value axis (or both) is in
this axis rect.
\see plottables, items
*/
QList<QCPGraph*> QCPAxisRect::graphs() const
{
// Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries
QList<QCPGraph*> result;
foreach (QCPGraph *graph, mParentPlot->mGraphs)
{
if (graph->keyAxis()->axisRect() == this || graph->valueAxis()->axisRect() == this)
result.append(graph);
}
return result;
}
/*!
Returns a list of all the items that are associated with this axis rect.
An item is considered associated with an axis rect if any of its positions has key or value axis
set to an axis that is in this axis rect, or if any of its positions has \ref
QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref
QCPAbstractItem::setClipAxisRect) is set to this axis rect.
\see plottables, graphs
*/
QList<QCPAbstractItem *> QCPAxisRect::items() const
{
// Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries
// and miss those items that have this axis rect as clipAxisRect.
QList<QCPAbstractItem*> result;
foreach (QCPAbstractItem *item, mParentPlot->mItems)
{
if (item->clipAxisRect() == this)
{
result.append(item);
continue;
}
foreach (QCPItemPosition *position, item->positions())
{
if (position->axisRect() == this ||
position->keyAxis()->axisRect() == this ||
position->valueAxis()->axisRect() == this)
{
result.append(item);
break;
}
}
}
return result;
}
/*!
This method is called automatically upon replot and doesn't need to be called by users of
QCPAxisRect.
Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
QCPInsetLayout::update function.
\seebaseclassmethod
*/
void QCPAxisRect::update(UpdatePhase phase)
{
QCPLayoutElement::update(phase);
switch (phase)
{
case upPreparation:
{
foreach (QCPAxis *axis, axes())
axis->setupTickVectors();
break;
}
case upLayout:
{
mInsetLayout->setOuterRect(rect());
break;
}
default: break;
}
// pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout):
mInsetLayout->update(phase);
}
/* inherits documentation from base class */
QList<QCPLayoutElement*> QCPAxisRect::elements(bool recursive) const
{
QList<QCPLayoutElement*> result;
if (mInsetLayout)
{
result << mInsetLayout;
if (recursive)
result << mInsetLayout->elements(recursive);
}
return result;
}
/* inherits documentation from base class */
void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
painter->setAntialiasing(false);
}
/* inherits documentation from base class */
void QCPAxisRect::draw(QCPPainter *painter)
{
drawBackground(painter);
}
/*!
Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
backgrounds are usually drawn below everything else.
For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
consider using the overloaded version of this function.
Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
setBackground(const QBrush &brush).
\see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
*/
void QCPAxisRect::setBackground(const QPixmap &pm)
{
mBackgroundPixmap = pm;
mScaledBackgroundPixmap = QPixmap();
}
/*! \overload
Sets \a brush as the background brush. The axis rect background will be filled with this brush.
Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
are usually drawn below everything else.
The brush will be drawn before (under) any background pixmap, which may be specified with \ref
setBackground(const QPixmap &pm).
To disable drawing of a background brush, set \a brush to Qt::NoBrush.
\see setBackground(const QPixmap &pm)
*/
void QCPAxisRect::setBackground(const QBrush &brush)
{
mBackgroundBrush = brush;
}
/*! \overload
Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
shall be scaled in one call.
\see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
*/
void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
{
mBackgroundPixmap = pm;
mScaledBackgroundPixmap = QPixmap();
mBackgroundScaled = scaled;
mBackgroundScaledMode = mode;
}
/*!
Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
is set to true, you may control whether and how the aspect ratio of the original pixmap is
preserved with \ref setBackgroundScaledMode.
Note that the scaled version of the original pixmap is buffered, so there is no performance
penalty on replots. (Except when the axis rect dimensions are changed continuously.)
\see setBackground, setBackgroundScaledMode
*/
void QCPAxisRect::setBackgroundScaled(bool scaled)
{
mBackgroundScaled = scaled;
}
/*!
If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
\see setBackground, setBackgroundScaled
*/
void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode)
{
mBackgroundScaledMode = mode;
}
/*!
Returns the range drag axis of the \a orientation provided. If multiple axes were set, returns
the first one (use \ref rangeDragAxes to retrieve a list with all set axes).
\see setRangeDragAxes
*/
QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation)
{
if (orientation == Qt::Horizontal)
return mRangeDragHorzAxis.isEmpty() ? nullptr : mRangeDragHorzAxis.first().data();
else
return mRangeDragVertAxis.isEmpty() ? nullptr : mRangeDragVertAxis.first().data();
}
/*!
Returns the range zoom axis of the \a orientation provided. If multiple axes were set, returns
the first one (use \ref rangeZoomAxes to retrieve a list with all set axes).
\see setRangeZoomAxes
*/
QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation)
{
if (orientation == Qt::Horizontal)
return mRangeZoomHorzAxis.isEmpty() ? nullptr : mRangeZoomHorzAxis.first().data();
else
return mRangeZoomVertAxis.isEmpty() ? nullptr : mRangeZoomVertAxis.first().data();
}
/*!
Returns all range drag axes of the \a orientation provided.
\see rangeZoomAxis, setRangeZoomAxes
*/
QList<QCPAxis*> QCPAxisRect::rangeDragAxes(Qt::Orientation orientation)
{
QList<QCPAxis*> result;
if (orientation == Qt::Horizontal)
{
foreach (QPointer<QCPAxis> axis, mRangeDragHorzAxis)
{
if (!axis.isNull())
result.append(axis.data());
}
} else
{
foreach (QPointer<QCPAxis> axis, mRangeDragVertAxis)
{
if (!axis.isNull())
result.append(axis.data());
}
}
return result;
}
/*!
Returns all range zoom axes of the \a orientation provided.
\see rangeDragAxis, setRangeDragAxes
*/
QList<QCPAxis*> QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation)
{
QList<QCPAxis*> result;
if (orientation == Qt::Horizontal)
{
foreach (QPointer<QCPAxis> axis, mRangeZoomHorzAxis)
{
if (!axis.isNull())
result.append(axis.data());
}
} else
{
foreach (QPointer<QCPAxis> axis, mRangeZoomVertAxis)
{
if (!axis.isNull())
result.append(axis.data());
}
}
return result;
}
/*!
Returns the range zoom factor of the \a orientation provided.
\see setRangeZoomFactor
*/
double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation)
{
return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert);
}
/*!
Sets which axis orientation may be range dragged by the user with mouse interaction.
What orientation corresponds to which specific axis can be set with
\ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By
default, the horizontal axis is the bottom axis (xAxis) and the vertical axis
is the left axis (yAxis).
To disable range dragging entirely, pass \c nullptr as \a orientations or remove \ref
QCP::iRangeDrag from \ref QCustomPlot::setInteractions. To enable range dragging for both
directions, pass <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations.
In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
contains \ref QCP::iRangeDrag to enable the range dragging interaction.
\see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag
*/
void QCPAxisRect::setRangeDrag(Qt::Orientations orientations)
{
mRangeDrag = orientations;
}
/*!
Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation
corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal,
QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical
axis is the left axis (yAxis).
To disable range zooming entirely, pass \c nullptr as \a orientations or remove \ref
QCP::iRangeZoom from \ref QCustomPlot::setInteractions. To enable range zooming for both
directions, pass <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations.
In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
contains \ref QCP::iRangeZoom to enable the range zooming interaction.
\see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag
*/
void QCPAxisRect::setRangeZoom(Qt::Orientations orientations)
{
mRangeZoom = orientations;
}
/*! \overload
Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on
the QCustomPlot widget. Pass \c nullptr if no axis shall be dragged in the respective
orientation.
Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
react to dragging interactions.
\see setRangeZoomAxes
*/
void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical)
{
QList<QCPAxis*> horz, vert;
if (horizontal)
horz.append(horizontal);
if (vertical)
vert.append(vertical);
setRangeDragAxes(horz, vert);
}
/*! \overload
This method allows to set up multiple axes to react to horizontal and vertical dragging. The drag
orientation that the respective axis will react to is deduced from its orientation (\ref
QCPAxis::orientation).
In the unusual case that you wish to e.g. drag a vertically oriented axis with a horizontal drag
motion, use the overload taking two separate lists for horizontal and vertical dragging.
*/
void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> axes)
{
QList<QCPAxis*> horz, vert;
foreach (QCPAxis *ax, axes)
{
if (ax->orientation() == Qt::Horizontal)
horz.append(ax);
else
vert.append(ax);
}
setRangeDragAxes(horz, vert);
}
/*! \overload
This method allows to set multiple axes up to react to horizontal and vertical dragging, and
define specifically which axis reacts to which drag orientation (irrespective of the axis
orientation).
*/
void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
{
mRangeDragHorzAxis.clear();
foreach (QCPAxis *ax, horizontal)
{
QPointer<QCPAxis> axPointer(ax);
if (!axPointer.isNull())
mRangeDragHorzAxis.append(axPointer);
else
qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
}
mRangeDragVertAxis.clear();
foreach (QCPAxis *ax, vertical)
{
QPointer<QCPAxis> axPointer(ax);
if (!axPointer.isNull())
mRangeDragVertAxis.append(axPointer);
else
qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
}
}
/*!
Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on
the QCustomPlot widget. Pass \c nullptr if no axis shall be zoomed in the respective orientation.
The two axes can be zoomed with different strengths, when different factors are passed to \ref
setRangeZoomFactor(double horizontalFactor, double verticalFactor).
Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
react to zooming interactions.
\see setRangeDragAxes
*/
void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical)
{
QList<QCPAxis*> horz, vert;
if (horizontal)
horz.append(horizontal);
if (vertical)
vert.append(vertical);
setRangeZoomAxes(horz, vert);
}
/*! \overload
This method allows to set up multiple axes to react to horizontal and vertical range zooming. The
zoom orientation that the respective axis will react to is deduced from its orientation (\ref
QCPAxis::orientation).
In the unusual case that you wish to e.g. zoom a vertically oriented axis with a horizontal zoom
interaction, use the overload taking two separate lists for horizontal and vertical zooming.
*/
void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> axes)
{
QList<QCPAxis*> horz, vert;
foreach (QCPAxis *ax, axes)
{
if (ax->orientation() == Qt::Horizontal)
horz.append(ax);
else
vert.append(ax);
}
setRangeZoomAxes(horz, vert);
}
/*! \overload
This method allows to set multiple axes up to react to horizontal and vertical zooming, and
define specifically which axis reacts to which zoom orientation (irrespective of the axis
orientation).
*/
void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
{
mRangeZoomHorzAxis.clear();
foreach (QCPAxis *ax, horizontal)
{
QPointer<QCPAxis> axPointer(ax);
if (!axPointer.isNull())
mRangeZoomHorzAxis.append(axPointer);
else
qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
}
mRangeZoomVertAxis.clear();
foreach (QCPAxis *ax, vertical)
{
QPointer<QCPAxis> axPointer(ax);
if (!axPointer.isNull())
mRangeZoomVertAxis.append(axPointer);
else
qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
}
}
/*!
Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with
\ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to
let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal
and which is vertical, can be set with \ref setRangeZoomAxes.
When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user)
will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the
same scrolling direction will zoom out.
*/
void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor)
{
mRangeZoomFactorHorz = horizontalFactor;
mRangeZoomFactorVert = verticalFactor;
}
/*! \overload
Sets both the horizontal and vertical zoom \a factor.
*/
void QCPAxisRect::setRangeZoomFactor(double factor)
{
mRangeZoomFactorHorz = factor;
mRangeZoomFactorVert = factor;
}
/*! \internal
Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
pixmap.
If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
according filling inside the axis rect with the provided \a painter.
Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
the axis rect with the provided \a painter. The scaled version is buffered in
mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
the axis rect has changed in a way that requires a rescale of the background pixmap (this is
dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
set.
\see setBackground, setBackgroundScaled, setBackgroundScaledMode
*/
void QCPAxisRect::drawBackground(QCPPainter *painter)
{
// draw background fill:
if (mBackgroundBrush != Qt::NoBrush)
painter->fillRect(mRect, mBackgroundBrush);
// draw background pixmap (on top of fill, if brush specified):
if (!mBackgroundPixmap.isNull())
{
if (mBackgroundScaled)
{
// check whether mScaledBackground needs to be updated:
QSize scaledSize(mBackgroundPixmap.size());
scaledSize.scale(mRect.size(), mBackgroundScaledMode);
if (mScaledBackgroundPixmap.size() != scaledSize)
mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
} else
{
painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
}
}
}
/*! \internal
This function makes sure multiple axes on the side specified with \a type don't collide, but are
distributed according to their respective space requirement (QCPAxis::calculateMargin).
It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the
one with index zero.
This function is called by \ref calculateAutoMargin.
*/
void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type)
{
const QList<QCPAxis*> axesList = mAxes.value(type);
if (axesList.isEmpty())
return;
bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false
for (int i=1; i<axesList.size(); ++i)
{
int offset = axesList.at(i-1)->offset() + axesList.at(i-1)->calculateMargin();
if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible)
{
if (!isFirstVisible)
offset += axesList.at(i)->tickLengthIn();
isFirstVisible = false;
}
axesList.at(i)->setOffset(offset);
}
}
/* inherits documentation from base class */
int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
{
if (!mAutoMargins.testFlag(side))
qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin";
updateAxesOffset(QCPAxis::marginSideToAxisType(side));
// note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call
const QList<QCPAxis*> axesList = mAxes.value(QCPAxis::marginSideToAxisType(side));
if (!axesList.isEmpty())
return axesList.last()->offset() + axesList.last()->calculateMargin();
else
return 0;
}
/*! \internal
Reacts to a change in layout to potentially set the convenience axis pointers \ref
QCustomPlot::xAxis, \ref QCustomPlot::yAxis, etc. of the parent QCustomPlot to the respective
axes of this axis rect. This is only done if the respective convenience pointer is currently zero
and if there is no QCPAxisRect at position (0, 0) of the plot layout.
This automation makes it simpler to replace the main axis rect with a newly created one, without
the need to manually reset the convenience pointers.
*/
void QCPAxisRect::layoutChanged()
{
if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
{
if (axisCount(QCPAxis::atBottom) > 0 && !mParentPlot->xAxis)
mParentPlot->xAxis = axis(QCPAxis::atBottom);
if (axisCount(QCPAxis::atLeft) > 0 && !mParentPlot->yAxis)
mParentPlot->yAxis = axis(QCPAxis::atLeft);
if (axisCount(QCPAxis::atTop) > 0 && !mParentPlot->xAxis2)
mParentPlot->xAxis2 = axis(QCPAxis::atTop);
if (axisCount(QCPAxis::atRight) > 0 && !mParentPlot->yAxis2)
mParentPlot->yAxis2 = axis(QCPAxis::atRight);
}
}
/*! \internal
Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
pressed, the range dragging interaction is initialized (the actual range manipulation happens in
the \ref mouseMoveEvent).
The mDragging flag is set to true and some anchor points are set that are needed to determine the
distance the mouse was dragged in the mouse move/release events later.
\see mouseMoveEvent, mouseReleaseEvent
*/
void QCPAxisRect::mousePressEvent(QMouseEvent *event, const QVariant &details)
{
Q_UNUSED(details)
if (event->buttons() & Qt::LeftButton)
{
mDragging = true;
// initialize antialiasing backup in case we start dragging:
if (mParentPlot->noAntialiasingOnDrag())
{
mAADragBackup = mParentPlot->antialiasedElements();
mNotAADragBackup = mParentPlot->notAntialiasedElements();
}
// Mouse range dragging interaction:
if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
{
mDragStartHorzRange.clear();
foreach (QPointer<QCPAxis> axis, mRangeDragHorzAxis)
mDragStartHorzRange.append(axis.isNull() ? QCPRange() : axis->range());
mDragStartVertRange.clear();
foreach (QPointer<QCPAxis> axis, mRangeDragVertAxis)
mDragStartVertRange.append(axis.isNull() ? QCPRange() : axis->range());
}
}
}
/*! \internal
Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
preceding \ref mousePressEvent, the range is moved accordingly.
\see mousePressEvent, mouseReleaseEvent
*/
void QCPAxisRect::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
{
Q_UNUSED(startPos)
// Mouse range dragging interaction:
if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
{
if (mRangeDrag.testFlag(Qt::Horizontal))
{
for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
{
QCPAxis *ax = mRangeDragHorzAxis.at(i).data();
if (!ax)
continue;
if (i >= mDragStartHorzRange.size())
break;
if (ax->mScaleType == QCPAxis::stLinear)
{
double diff = ax->pixelToCoord(startPos.x()) - ax->pixelToCoord(event->pos().x());
ax->setRange(mDragStartHorzRange.at(i).lower+diff, mDragStartHorzRange.at(i).upper+diff);
} else if (ax->mScaleType == QCPAxis::stLogarithmic)
{
double diff = ax->pixelToCoord(startPos.x()) / ax->pixelToCoord(event->pos().x());
ax->setRange(mDragStartHorzRange.at(i).lower*diff, mDragStartHorzRange.at(i).upper*diff);
}
}
}
if (mRangeDrag.testFlag(Qt::Vertical))
{
for (int i=0; i<mRangeDragVertAxis.size(); ++i)
{
QCPAxis *ax = mRangeDragVertAxis.at(i).data();
if (!ax)
continue;
if (i >= mDragStartVertRange.size())
break;
if (ax->mScaleType == QCPAxis::stLinear)
{
double diff = ax->pixelToCoord(startPos.y()) - ax->pixelToCoord(event->pos().y());
ax->setRange(mDragStartVertRange.at(i).lower+diff, mDragStartVertRange.at(i).upper+diff);
} else if (ax->mScaleType == QCPAxis::stLogarithmic)
{
double diff = ax->pixelToCoord(startPos.y()) / ax->pixelToCoord(event->pos().y());
ax->setRange(mDragStartVertRange.at(i).lower*diff, mDragStartVertRange.at(i).upper*diff);
}
}
}
if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot
{
if (mParentPlot->noAntialiasingOnDrag())
mParentPlot->setNotAntialiasedElements(QCP::aeAll);
mParentPlot->replot(QCustomPlot::rpQueuedReplot);
}
}
}
/* inherits documentation from base class */
void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
{
Q_UNUSED(event)
Q_UNUSED(startPos)
mDragging = false;
if (mParentPlot->noAntialiasingOnDrag())
{
mParentPlot->setAntialiasedElements(mAADragBackup);
mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
}
}
/*! \internal
Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
the scaling operation is the current cursor position inside the axis rect. The scaling factor is
dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
Note, that event->angleDelta() is usually +/-120 for single rotation steps. However, if the mouse
wheel is turned rapidly, many steps may bunch up to one event, so the delta may then be multiples
of 120. This is taken into account here, by calculating \a wheelSteps and using it as exponent of
the range zoom factor. This takes care of the wheel direction automatically, by inverting the
factor, when the wheel step is negative (f^-1 = 1/f).
*/
void QCPAxisRect::wheelEvent(QWheelEvent *event)
{
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
const double delta = event->delta();
#else
const double delta = event->angleDelta().y();
#endif
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
const QPointF pos = event->pos();
#else
const QPointF pos = event->position();
#endif
// Mouse range zooming interaction:
if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
{
if (mRangeZoom != 0)
{
double factor;
double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
if (mRangeZoom.testFlag(Qt::Horizontal))
{
factor = qPow(mRangeZoomFactorHorz, wheelSteps);
foreach (QPointer<QCPAxis> axis, mRangeZoomHorzAxis)
{
if (!axis.isNull())
axis->scaleRange(factor, axis->pixelToCoord(pos.x()));
}
}
if (mRangeZoom.testFlag(Qt::Vertical))
{
factor = qPow(mRangeZoomFactorVert, wheelSteps);
foreach (QPointer<QCPAxis> axis, mRangeZoomVertAxis)
{
if (!axis.isNull())
axis->scaleRange(factor, axis->pixelToCoord(pos.y()));
}
}
mParentPlot->replot();
}
}
}
/* end of 'src/layoutelements/layoutelement-axisrect.cpp' */
/* including file 'src/layoutelements/layoutelement-legend.cpp' */
/* modified 2022-11-06T12:45:56, size 31762 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAbstractLegendItem
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAbstractLegendItem
\brief The abstract base class for all entries in a QCPLegend.
It defines a very basic interface for entries in a QCPLegend. For representing plottables in the
legend, the subclass \ref QCPPlottableLegendItem is more suitable.
Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry
that's not even associated with a plottable).
You must implement the following pure virtual functions:
\li \ref draw (from QCPLayerable)
You inherit the following members you may use:
<table>
<tr>
<td>QCPLegend *\b mParentLegend</td>
<td>A pointer to the parent QCPLegend.</td>
</tr><tr>
<td>QFont \b mFont</td>
<td>The generic font of the item. You should use this font for all or at least the most prominent text of the item.</td>
</tr>
</table>
*/
/* start of documentation of signals */
/*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected)
This signal is emitted when the selection state of this legend item has changed, either by user
interaction or by a direct call to \ref setSelected.
*/
/* end of documentation of signals */
/*!
Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not
cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately.
*/
QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) :
QCPLayoutElement(parent->parentPlot()),
mParentLegend(parent),
mFont(parent->font()),
mTextColor(parent->textColor()),
mSelectedFont(parent->selectedFont()),
mSelectedTextColor(parent->selectedTextColor()),
mSelectable(true),
mSelected(false)
{
setLayer(QLatin1String("legend"));
setMargins(QMargins(0, 0, 0, 0));
}
/*!
Sets the default font of this specific legend item to \a font.
\see setTextColor, QCPLegend::setFont
*/
void QCPAbstractLegendItem::setFont(const QFont &font)
{
mFont = font;
}
/*!
Sets the default text color of this specific legend item to \a color.
\see setFont, QCPLegend::setTextColor
*/
void QCPAbstractLegendItem::setTextColor(const QColor &color)
{
mTextColor = color;
}
/*!
When this legend item is selected, \a font is used to draw generic text, instead of the normal
font set with \ref setFont.
\see setFont, QCPLegend::setSelectedFont
*/
void QCPAbstractLegendItem::setSelectedFont(const QFont &font)
{
mSelectedFont = font;
}
/*!
When this legend item is selected, \a color is used to draw generic text, instead of the normal
color set with \ref setTextColor.
\see setTextColor, QCPLegend::setSelectedTextColor
*/
void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color)
{
mSelectedTextColor = color;
}
/*!
Sets whether this specific legend item is selectable.
\see setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAbstractLegendItem::setSelectable(bool selectable)
{
if (mSelectable != selectable)
{
mSelectable = selectable;
emit selectableChanged(mSelectable);
}
}
/*!
Sets whether this specific legend item is selected.
It is possible to set the selection state of this item by calling this function directly, even if
setSelectable is set to false.
\see setSelectableParts, QCustomPlot::setInteractions
*/
void QCPAbstractLegendItem::setSelected(bool selected)
{
if (mSelected != selected)
{
mSelected = selected;
emit selectionChanged(mSelected);
}
}
/* inherits documentation from base class */
double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (!mParentPlot) return -1;
if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems)))
return -1;
if (mRect.contains(pos.toPoint()))
return mParentPlot->selectionTolerance()*0.99;
else
return -1;
}
/* inherits documentation from base class */
void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems);
}
/* inherits documentation from base class */
QRect QCPAbstractLegendItem::clipRect() const
{
return mOuterRect;
}
/* inherits documentation from base class */
void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(details)
if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
{
bool selBefore = mSelected;
setSelected(additive ? !mSelected : true);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged)
{
if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
{
bool selBefore = mSelected;
setSelected(false);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPlottableLegendItem
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPlottableLegendItem
\brief A legend item representing a plottable with an icon and the plottable name.
This is the standard legend item for plottables. It displays an icon of the plottable next to the
plottable name. The icon is drawn by the respective plottable itself (\ref
QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable.
For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the
middle.
Legend items of this type are always associated with one plottable (retrievable via the
plottable() function and settable with the constructor). You may change the font of the plottable
name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref
QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding.
The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend
creates/removes legend items of this type.
Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of
QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout
interface, QCPLegend has specialized functions for handling legend items conveniently, see the
documentation of \ref QCPLegend.
*/
/*!
Creates a new legend item associated with \a plottable.
Once it's created, it can be added to the legend via \ref QCPLegend::addItem.
A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref
QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend.
*/
QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) :
QCPAbstractLegendItem(parent),
mPlottable(plottable)
{
setAntialiased(false);
}
/*! \internal
Returns the pen that shall be used to draw the icon border, taking into account the selection
state of this item.
*/
QPen QCPPlottableLegendItem::getIconBorderPen() const
{
return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
}
/*! \internal
Returns the text color that shall be used to draw text, taking into account the selection state
of this item.
*/
QColor QCPPlottableLegendItem::getTextColor() const
{
return mSelected ? mSelectedTextColor : mTextColor;
}
/*! \internal
Returns the font that shall be used to draw text, taking into account the selection state of this
item.
*/
QFont QCPPlottableLegendItem::getFont() const
{
return mSelected ? mSelectedFont : mFont;
}
/*! \internal
Draws the item with \a painter. The size and position of the drawn legend item is defined by the
parent layout (typically a \ref QCPLegend) and the \ref minimumOuterSizeHint and \ref
maximumOuterSizeHint of this legend item.
*/
void QCPPlottableLegendItem::draw(QCPPainter *painter)
{
if (!mPlottable) return;
painter->setFont(getFont());
painter->setPen(QPen(getTextColor()));
QSize iconSize = mParentLegend->iconSize();
QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
QRect iconRect(mRect.topLeft(), iconSize);
int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name());
// draw icon:
painter->save();
painter->setClipRect(iconRect, Qt::IntersectClip);
mPlottable->drawLegendIcon(painter, iconRect);
painter->restore();
// draw icon border:
if (getIconBorderPen().style() != Qt::NoPen)
{
painter->setPen(getIconBorderPen());
painter->setBrush(Qt::NoBrush);
int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
painter->drawRect(iconRect);
}
}
/*! \internal
Calculates and returns the size of this item. This includes the icon, the text and the padding in
between.
\seebaseclassmethod
*/
QSize QCPPlottableLegendItem::minimumOuterSizeHint() const
{
if (!mPlottable) return {};
QSize result(0, 0);
QRect textRect;
QFontMetrics fontMetrics(getFont());
QSize iconSize = mParentLegend->iconSize();
textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width());
result.setHeight(qMax(textRect.height(), iconSize.height()));
result.rwidth() += mMargins.left()+mMargins.right();
result.rheight() += mMargins.top()+mMargins.bottom();
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLegend
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLegend
\brief Manages a legend inside a QCustomPlot.
A legend is a small box somewhere in the plot which lists plottables with their name and icon.
A legend is populated with legend items by calling \ref QCPAbstractPlottable::addToLegend on the
plottable, for which a legend item shall be created. In the case of the main legend (\ref
QCustomPlot::legend), simply adding plottables to the plot while \ref
QCustomPlot::setAutoAddPlottableToLegend is set to true (the default) creates corresponding
legend items. The legend item associated with a certain plottable can be removed with \ref
QCPAbstractPlottable::removeFromLegend. However, QCPLegend also offers an interface to add and
manipulate legend items directly: \ref item, \ref itemWithPlottable, \ref itemCount, \ref
addItem, \ref removeItem, etc.
Since \ref QCPLegend derives from \ref QCPLayoutGrid, it can be placed in any position a \ref
QCPLayoutElement may be positioned. The legend items are themselves \ref QCPLayoutElement
"QCPLayoutElements" which are placed in the grid layout of the legend. \ref QCPLegend only adds
an interface specialized for handling child elements of type \ref QCPAbstractLegendItem, as
mentioned above. In principle, any other layout elements may also be added to a legend via the
normal \ref QCPLayoutGrid interface. See the special page about \link thelayoutsystem The Layout
System\endlink for examples on how to add other elements to the legend and move it outside the axis
rect.
Use the methods \ref setFillOrder and \ref setWrap inherited from \ref QCPLayoutGrid to control
in which order (column first or row first) the legend is filled up when calling \ref addItem, and
at which column or row wrapping occurs. The default fill order for legends is \ref foRowsFirst.
By default, every QCustomPlot has one legend (\ref QCustomPlot::legend) which is placed in the
inset layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend
outside of the axis rect, place it anywhere else with the \ref QCPLayout/\ref QCPLayoutElement
interface.
*/
/* start of documentation of signals */
/*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection);
This signal is emitted when the selection state of this legend has changed.
\see setSelectedParts, setSelectableParts
*/
/* end of documentation of signals */
/*!
Constructs a new QCPLegend instance with default values.
Note that by default, QCustomPlot already contains a legend ready to be used as \ref
QCustomPlot::legend
*/
QCPLegend::QCPLegend() :
mIconTextPadding{}
{
setFillOrder(QCPLayoutGrid::foRowsFirst);
setWrap(0);
setRowSpacing(3);
setColumnSpacing(8);
setMargins(QMargins(7, 5, 7, 4));
setAntialiased(false);
setIconSize(32, 18);
setIconTextPadding(7);
setSelectableParts(spLegendBox | spItems);
setSelectedParts(spNone);
setBorderPen(QPen(Qt::black, 0));
setSelectedBorderPen(QPen(Qt::blue, 2));
setIconBorderPen(Qt::NoPen);
setSelectedIconBorderPen(QPen(Qt::blue, 2));
setBrush(Qt::white);
setSelectedBrush(Qt::white);
setTextColor(Qt::black);
setSelectedTextColor(Qt::blue);
}
QCPLegend::~QCPLegend()
{
clearItems();
if (qobject_cast<QCustomPlot*>(mParentPlot)) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot)
mParentPlot->legendRemoved(this);
}
/* no doc for getter, see setSelectedParts */
QCPLegend::SelectableParts QCPLegend::selectedParts() const
{
// check whether any legend elements selected, if yes, add spItems to return value
bool hasSelectedItems = false;
for (int i=0; i<itemCount(); ++i)
{
if (item(i) && item(i)->selected())
{
hasSelectedItems = true;
break;
}
}
if (hasSelectedItems)
return mSelectedParts | spItems;
else
return mSelectedParts & ~spItems;
}
/*!
Sets the pen, the border of the entire legend is drawn with.
*/
void QCPLegend::setBorderPen(const QPen &pen)
{
mBorderPen = pen;
}
/*!
Sets the brush of the legend background.
*/
void QCPLegend::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will
use this font by default. However, a different font can be specified on a per-item-basis by
accessing the specific legend item.
This function will also set \a font on all already existing legend items.
\see QCPAbstractLegendItem::setFont
*/
void QCPLegend::setFont(const QFont &font)
{
mFont = font;
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setFont(mFont);
}
}
/*!
Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph)
will use this color by default. However, a different colors can be specified on a per-item-basis
by accessing the specific legend item.
This function will also set \a color on all already existing legend items.
\see QCPAbstractLegendItem::setTextColor
*/
void QCPLegend::setTextColor(const QColor &color)
{
mTextColor = color;
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setTextColor(color);
}
}
/*!
Sets the size of legend icons. Legend items that draw an icon (e.g. a visual
representation of the graph) will use this size by default.
*/
void QCPLegend::setIconSize(const QSize &size)
{
mIconSize = size;
}
/*! \overload
*/
void QCPLegend::setIconSize(int width, int height)
{
mIconSize.setWidth(width);
mIconSize.setHeight(height);
}
/*!
Sets the horizontal space in pixels between the legend icon and the text next to it.
Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the
name of the graph) will use this space by default.
*/
void QCPLegend::setIconTextPadding(int padding)
{
mIconTextPadding = padding;
}
/*!
Sets the pen used to draw a border around each legend icon. Legend items that draw an
icon (e.g. a visual representation of the graph) will use this pen by default.
If no border is wanted, set this to \a Qt::NoPen.
*/
void QCPLegend::setIconBorderPen(const QPen &pen)
{
mIconBorderPen = pen;
}
/*!
Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
(When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.)
However, even when \a selectable is set to a value not allowing the selection of a specific part,
it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
directly.
\see SelectablePart, setSelectedParts
*/
void QCPLegend::setSelectableParts(const SelectableParts &selectable)
{
if (mSelectableParts != selectable)
{
mSelectableParts = selectable;
emit selectableChanged(mSelectableParts);
}
}
/*!
Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part
is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected
doesn't contain \ref spItems, those items become deselected.
The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions
contains iSelectLegend. You only need to call this function when you wish to change the selection
state manually.
This function can change the selection state of a part even when \ref setSelectableParts was set to a
value that actually excludes the part.
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set
before, because there's no way to specify which exact items to newly select. Do this by calling
\ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select.
\see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush,
setSelectedFont
*/
void QCPLegend::setSelectedParts(const SelectableParts &selected)
{
SelectableParts newSelected = selected;
mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed
if (mSelectedParts != newSelected)
{
if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that)
{
qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function";
newSelected &= ~spItems;
}
if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection
{
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setSelected(false);
}
}
mSelectedParts = newSelected;
emit selectionChanged(mSelectedParts);
}
}
/*!
When the legend box is selected, this pen is used to draw the border instead of the normal pen
set via \ref setBorderPen.
\see setSelectedParts, setSelectableParts, setSelectedBrush
*/
void QCPLegend::setSelectedBorderPen(const QPen &pen)
{
mSelectedBorderPen = pen;
}
/*!
Sets the pen legend items will use to draw their icon borders, when they are selected.
\see setSelectedParts, setSelectableParts, setSelectedFont
*/
void QCPLegend::setSelectedIconBorderPen(const QPen &pen)
{
mSelectedIconBorderPen = pen;
}
/*!
When the legend box is selected, this brush is used to draw the legend background instead of the normal brush
set via \ref setBrush.
\see setSelectedParts, setSelectableParts, setSelectedBorderPen
*/
void QCPLegend::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/*!
Sets the default font that is used by legend items when they are selected.
This function will also set \a font on all already existing legend items.
\see setFont, QCPAbstractLegendItem::setSelectedFont
*/
void QCPLegend::setSelectedFont(const QFont &font)
{
mSelectedFont = font;
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setSelectedFont(font);
}
}
/*!
Sets the default text color that is used by legend items when they are selected.
This function will also set \a color on all already existing legend items.
\see setTextColor, QCPAbstractLegendItem::setSelectedTextColor
*/
void QCPLegend::setSelectedTextColor(const QColor &color)
{
mSelectedTextColor = color;
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setSelectedTextColor(color);
}
}
/*!
Returns the item with index \a i. If non-legend items were added to the legend, and the element
at the specified cell index is not a QCPAbstractLegendItem, returns \c nullptr.
Note that the linear index depends on the current fill order (\ref setFillOrder).
\see itemCount, addItem, itemWithPlottable
*/
QCPAbstractLegendItem *QCPLegend::item(int index) const
{
return qobject_cast<QCPAbstractLegendItem*>(elementAt(index));
}
/*!
Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
If such an item isn't in the legend, returns \c nullptr.
\see hasItemWithPlottable
*/
QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const
{
for (int i=0; i<itemCount(); ++i)
{
if (QCPPlottableLegendItem *pli = qobject_cast<QCPPlottableLegendItem*>(item(i)))
{
if (pli->plottable() == plottable)
return pli;
}
}
return nullptr;
}
/*!
Returns the number of items currently in the legend. It is identical to the base class
QCPLayoutGrid::elementCount(), and unlike the other "item" interface methods of QCPLegend,
doesn't only address elements which can be cast to QCPAbstractLegendItem.
Note that if empty cells are in the legend (e.g. by calling methods of the \ref QCPLayoutGrid
base class which allows creating empty cells), they are included in the returned count.
\see item
*/
int QCPLegend::itemCount() const
{
return elementCount();
}
/*!
Returns whether the legend contains \a item.
\see hasItemWithPlottable
*/
bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const
{
for (int i=0; i<itemCount(); ++i)
{
if (item == this->item(i))
return true;
}
return false;
}
/*!
Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
If such an item isn't in the legend, returns false.
\see itemWithPlottable
*/
bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const
{
return itemWithPlottable(plottable);
}
/*!
Adds \a item to the legend, if it's not present already. The element is arranged according to the
current fill order (\ref setFillOrder) and wrapping (\ref setWrap).
Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added.
The legend takes ownership of the item.
\see removeItem, item, hasItem
*/
bool QCPLegend::addItem(QCPAbstractLegendItem *item)
{
return addElement(item);
}
/*! \overload
Removes the item with the specified \a index from the legend and deletes it.
After successful removal, the legend is reordered according to the current fill order (\ref
setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
Returns true, if successful. Unlike \ref QCPLayoutGrid::removeAt, this method only removes
elements derived from \ref QCPAbstractLegendItem.
\see itemCount, clearItems
*/
bool QCPLegend::removeItem(int index)
{
if (QCPAbstractLegendItem *ali = item(index))
{
bool success = remove(ali);
if (success)
setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
return success;
} else
return false;
}
/*! \overload
Removes \a item from the legend and deletes it.
After successful removal, the legend is reordered according to the current fill order (\ref
setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
Returns true, if successful.
\see clearItems
*/
bool QCPLegend::removeItem(QCPAbstractLegendItem *item)
{
bool success = remove(item);
if (success)
setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
return success;
}
/*!
Removes all items from the legend.
*/
void QCPLegend::clearItems()
{
for (int i=elementCount()-1; i>=0; --i)
{
if (item(i))
removeAt(i); // don't use removeItem() because it would unnecessarily reorder the whole legend for each item
}
setFillOrder(fillOrder(), true); // get rid of empty cells by reordering once after all items are removed
}
/*!
Returns the legend items that are currently selected. If no items are selected,
the list is empty.
\see QCPAbstractLegendItem::setSelected, setSelectable
*/
QList<QCPAbstractLegendItem *> QCPLegend::selectedItems() const
{
QList<QCPAbstractLegendItem*> result;
for (int i=0; i<itemCount(); ++i)
{
if (QCPAbstractLegendItem *ali = item(i))
{
if (ali->selected())
result.append(ali);
}
}
return result;
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing main legend elements.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\seebaseclassmethod
\see setAntialiased
*/
void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend);
}
/*! \internal
Returns the pen used to paint the border of the legend, taking into account the selection state
of the legend box.
*/
QPen QCPLegend::getBorderPen() const
{
return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen;
}
/*! \internal
Returns the brush used to paint the background of the legend, taking into account the selection
state of the legend box.
*/
QBrush QCPLegend::getBrush() const
{
return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush;
}
/*! \internal
Draws the legend box with the provided \a painter. The individual legend items are layerables
themselves, thus are drawn independently.
*/
void QCPLegend::draw(QCPPainter *painter)
{
// draw background rect:
painter->setBrush(getBrush());
painter->setPen(getBorderPen());
painter->drawRect(mOuterRect);
}
/* inherits documentation from base class */
double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
if (!mParentPlot) return -1;
if (onlySelectable && !mSelectableParts.testFlag(spLegendBox))
return -1;
if (mOuterRect.contains(pos.toPoint()))
{
if (details) details->setValue(spLegendBox);
return mParentPlot->selectionTolerance()*0.99;
}
return -1;
}
/* inherits documentation from base class */
void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
mSelectedParts = selectedParts(); // in case item selection has changed
if (details.value<SelectablePart>() == spLegendBox && mSelectableParts.testFlag(spLegendBox))
{
SelectableParts selBefore = mSelectedParts;
setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent)
if (selectionStateChanged)
*selectionStateChanged = mSelectedParts != selBefore;
}
}
/* inherits documentation from base class */
void QCPLegend::deselectEvent(bool *selectionStateChanged)
{
mSelectedParts = selectedParts(); // in case item selection has changed
if (mSelectableParts.testFlag(spLegendBox))
{
SelectableParts selBefore = mSelectedParts;
setSelectedParts(selectedParts() & ~spLegendBox);
if (selectionStateChanged)
*selectionStateChanged = mSelectedParts != selBefore;
}
}
/* inherits documentation from base class */
QCP::Interaction QCPLegend::selectionCategory() const
{
return QCP::iSelectLegend;
}
/* inherits documentation from base class */
QCP::Interaction QCPAbstractLegendItem::selectionCategory() const
{
return QCP::iSelectLegend;
}
/* inherits documentation from base class */
void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot)
{
if (parentPlot && !parentPlot->legend)
parentPlot->legend = this;
}
/* end of 'src/layoutelements/layoutelement-legend.cpp' */
/* including file 'src/layoutelements/layoutelement-textelement.cpp' */
/* modified 2022-11-06T12:45:56, size 12925 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPTextElement
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPTextElement
\brief A layout element displaying a text
The text may be specified with \ref setText, the formatting can be controlled with \ref setFont,
\ref setTextColor, and \ref setTextFlags.
A text element can be added as follows:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcptextelement-creation
*/
/* start documentation of signals */
/*! \fn void QCPTextElement::selectionChanged(bool selected)
This signal is emitted when the selection state has changed to \a selected, either by user
interaction or by a direct call to \ref setSelected.
\see setSelected, setSelectable
*/
/*! \fn void QCPTextElement::clicked(QMouseEvent *event)
This signal is emitted when the text element is clicked.
\see doubleClicked, selectTest
*/
/*! \fn void QCPTextElement::doubleClicked(QMouseEvent *event)
This signal is emitted when the text element is double clicked.
\see clicked, selectTest
*/
/* end documentation of signals */
/*! \overload
Creates a new QCPTextElement instance and sets default values. The initial text is empty (\ref
setText).
*/
QCPTextElement::QCPTextElement(QCustomPlot *parentPlot) :
QCPLayoutElement(parentPlot),
mText(),
mTextFlags(Qt::AlignCenter),
mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
mTextColor(Qt::black),
mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
mSelectedTextColor(Qt::blue),
mSelectable(false),
mSelected(false)
{
if (parentPlot)
{
mFont = parentPlot->font();
mSelectedFont = parentPlot->font();
}
setMargins(QMargins(2, 2, 2, 2));
}
/*! \overload
Creates a new QCPTextElement instance and sets default values.
The initial text is set to \a text.
*/
QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text) :
QCPLayoutElement(parentPlot),
mText(text),
mTextFlags(Qt::AlignCenter),
mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
mTextColor(Qt::black),
mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
mSelectedTextColor(Qt::blue),
mSelectable(false),
mSelected(false)
{
if (parentPlot)
{
mFont = parentPlot->font();
mSelectedFont = parentPlot->font();
}
setMargins(QMargins(2, 2, 2, 2));
}
/*! \overload
Creates a new QCPTextElement instance and sets default values.
The initial text is set to \a text with \a pointSize.
*/
QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, double pointSize) :
QCPLayoutElement(parentPlot),
mText(text),
mTextFlags(Qt::AlignCenter),
mFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below
mTextColor(Qt::black),
mSelectedFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below
mSelectedTextColor(Qt::blue),
mSelectable(false),
mSelected(false)
{
mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer
if (parentPlot)
{
mFont = parentPlot->font();
mFont.setPointSizeF(pointSize);
mSelectedFont = parentPlot->font();
mSelectedFont.setPointSizeF(pointSize);
}
setMargins(QMargins(2, 2, 2, 2));
}
/*! \overload
Creates a new QCPTextElement instance and sets default values.
The initial text is set to \a text with \a pointSize and the specified \a fontFamily.
*/
QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QString &fontFamily, double pointSize) :
QCPLayoutElement(parentPlot),
mText(text),
mTextFlags(Qt::AlignCenter),
mFont(QFont(fontFamily, int(pointSize))),
mTextColor(Qt::black),
mSelectedFont(QFont(fontFamily, int(pointSize))),
mSelectedTextColor(Qt::blue),
mSelectable(false),
mSelected(false)
{
mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer
setMargins(QMargins(2, 2, 2, 2));
}
/*! \overload
Creates a new QCPTextElement instance and sets default values.
The initial text is set to \a text with the specified \a font.
*/
QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QFont &font) :
QCPLayoutElement(parentPlot),
mText(text),
mTextFlags(Qt::AlignCenter),
mFont(font),
mTextColor(Qt::black),
mSelectedFont(font),
mSelectedTextColor(Qt::blue),
mSelectable(false),
mSelected(false)
{
setMargins(QMargins(2, 2, 2, 2));
}
/*!
Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n".
\see setFont, setTextColor, setTextFlags
*/
void QCPTextElement::setText(const QString &text)
{
mText = text;
}
/*!
Sets options for text alignment and wrapping behaviour. \a flags is a bitwise OR-combination of
\c Qt::AlignmentFlag and \c Qt::TextFlag enums.
Possible enums are:
- Qt::AlignLeft
- Qt::AlignRight
- Qt::AlignHCenter
- Qt::AlignJustify
- Qt::AlignTop
- Qt::AlignBottom
- Qt::AlignVCenter
- Qt::AlignCenter
- Qt::TextDontClip
- Qt::TextSingleLine
- Qt::TextExpandTabs
- Qt::TextShowMnemonic
- Qt::TextWordWrap
- Qt::TextIncludeTrailingSpaces
*/
void QCPTextElement::setTextFlags(int flags)
{
mTextFlags = flags;
}
/*!
Sets the \a font of the text.
\see setTextColor, setSelectedFont
*/
void QCPTextElement::setFont(const QFont &font)
{
mFont = font;
}
/*!
Sets the \a color of the text.
\see setFont, setSelectedTextColor
*/
void QCPTextElement::setTextColor(const QColor &color)
{
mTextColor = color;
}
/*!
Sets the \a font of the text that will be used if the text element is selected (\ref setSelected).
\see setFont
*/
void QCPTextElement::setSelectedFont(const QFont &font)
{
mSelectedFont = font;
}
/*!
Sets the \a color of the text that will be used if the text element is selected (\ref setSelected).
\see setTextColor
*/
void QCPTextElement::setSelectedTextColor(const QColor &color)
{
mSelectedTextColor = color;
}
/*!
Sets whether the user may select this text element.
Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed
programmatically via \ref setSelected.
*/
void QCPTextElement::setSelectable(bool selectable)
{
if (mSelectable != selectable)
{
mSelectable = selectable;
emit selectableChanged(mSelectable);
}
}
/*!
Sets the selection state of this text element to \a selected. If the selection has changed, \ref
selectionChanged is emitted.
Note that this function can change the selection state independently of the current \ref
setSelectable state.
*/
void QCPTextElement::setSelected(bool selected)
{
if (mSelected != selected)
{
mSelected = selected;
emit selectionChanged(mSelected);
}
}
/* inherits documentation from base class */
void QCPTextElement::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
}
/* inherits documentation from base class */
void QCPTextElement::draw(QCPPainter *painter)
{
painter->setFont(mainFont());
painter->setPen(QPen(mainTextColor()));
painter->drawText(mRect, mTextFlags, mText, &mTextBoundingRect);
}
/* inherits documentation from base class */
QSize QCPTextElement::minimumOuterSizeHint() const
{
QFontMetrics metrics(mFont);
QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size());
result.rwidth() += mMargins.left()+mMargins.right();
result.rheight() += mMargins.top()+mMargins.bottom();
return result;
}
/* inherits documentation from base class */
QSize QCPTextElement::maximumOuterSizeHint() const
{
QFontMetrics metrics(mFont);
QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size());
result.setWidth(QWIDGETSIZE_MAX);
result.rheight() += mMargins.top()+mMargins.bottom();
return result;
}
/* inherits documentation from base class */
void QCPTextElement::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(details)
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(additive ? !mSelected : true);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
void QCPTextElement::deselectEvent(bool *selectionStateChanged)
{
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(false);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/*!
Returns 0.99*selectionTolerance (see \ref QCustomPlot::setSelectionTolerance) when \a pos is
within the bounding box of the text element's text. Note that this bounding box is updated in the
draw call.
If \a pos is outside the text's bounding box or if \a onlySelectable is true and this text
element is not selectable (\ref setSelectable), returns -1.
\seebaseclassmethod
*/
double QCPTextElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
if (mTextBoundingRect.contains(pos.toPoint()))
return mParentPlot->selectionTolerance()*0.99;
else
return -1;
}
/*!
Accepts the mouse event in order to emit the according click signal in the \ref
mouseReleaseEvent.
\seebaseclassmethod
*/
void QCPTextElement::mousePressEvent(QMouseEvent *event, const QVariant &details)
{
Q_UNUSED(details)
event->accept();
}
/*!
Emits the \ref clicked signal if the cursor hasn't moved by more than a few pixels since the \ref
mousePressEvent.
\seebaseclassmethod
*/
void QCPTextElement::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
{
if ((QPointF(event->pos())-startPos).manhattanLength() <= 3)
emit clicked(event);
}
/*!
Emits the \ref doubleClicked signal.
\seebaseclassmethod
*/
void QCPTextElement::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
{
Q_UNUSED(details)
emit doubleClicked(event);
}
/*! \internal
Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to
<tt>true</tt>, else mFont is returned.
*/
QFont QCPTextElement::mainFont() const
{
return mSelected ? mSelectedFont : mFont;
}
/*! \internal
Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to
<tt>true</tt>, else mTextColor is returned.
*/
QColor QCPTextElement::mainTextColor() const
{
return mSelected ? mSelectedTextColor : mTextColor;
}
/* end of 'src/layoutelements/layoutelement-textelement.cpp' */
/* including file 'src/layoutelements/layoutelement-colorscale.cpp' */
/* modified 2022-11-06T12:45:56, size 26531 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPColorScale
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPColorScale
\brief A color scale for use with color coding data such as QCPColorMap
This layout element can be placed on the plot to correlate a color gradient with data values. It
is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps".
\image html QCPColorScale.png
The color scale can be either horizontal or vertical, as shown in the image above. The
orientation and the side where the numbers appear is controlled with \ref setType.
Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are
connected, they share their gradient, data range and data scale type (\ref setGradient, \ref
setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color
scale, to make them all synchronize these properties.
To have finer control over the number display and axis behaviour, you can directly access the
\ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if
you want to change the number of automatically generated ticks, call
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-tickcount
Placing a color scale next to the main axis rect works like with any other layout element:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation
In this case we have placed it to the right of the default axis rect, so it wasn't necessary to
call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color
scale can be set with \ref setLabel.
For optimum appearance (like in the image above), it may be desirable to line up the axis rect and
the borders of the color scale. Use a \ref QCPMarginGroup to achieve this:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup
Color scales are initialized with a non-zero minimum top and bottom margin (\ref
setMinimumMargins), because vertical color scales are most common and the minimum top/bottom
margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a
horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you
might want to also change the minimum margins accordingly, e.g. <tt>setMinimumMargins(QMargins(6, 0, 6, 0))</tt>.
*/
/* start documentation of inline functions */
/*! \fn QCPAxis *QCPColorScale::axis() const
Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the
appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its
interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref
setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref
QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on
the QCPColorScale or on its QCPAxis.
If the type of the color scale is changed with \ref setType, the axis returned by this method
will change, too, to either the left, right, bottom or top axis, depending on which type was set.
*/
/* end documentation of signals */
/* start documentation of signals */
/*! \fn void QCPColorScale::dataRangeChanged(const QCPRange &newRange);
This signal is emitted when the data range changes.
\see setDataRange
*/
/*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
This signal is emitted when the data scale type changes.
\see setDataScaleType
*/
/*! \fn void QCPColorScale::gradientChanged(const QCPColorGradient &newGradient);
This signal is emitted when the gradient changes.
\see setGradient
*/
/* end documentation of signals */
/*!
Constructs a new QCPColorScale.
*/
QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) :
QCPLayoutElement(parentPlot),
mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight
mDataScaleType(QCPAxis::stLinear),
mGradient(QCPColorGradient::gpCold),
mBarWidth(20),
mAxisRect(new QCPColorScaleAxisRectPrivate(this))
{
setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used)
setType(QCPAxis::atRight);
setDataRange(QCPRange(0, 6));
}
QCPColorScale::~QCPColorScale()
{
delete mAxisRect;
}
/* undocumented getter */
QString QCPColorScale::label() const
{
if (!mColorAxis)
{
qDebug() << Q_FUNC_INFO << "internal color axis undefined";
return QString();
}
return mColorAxis.data()->label();
}
/* undocumented getter */
bool QCPColorScale::rangeDrag() const
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return false;
}
return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) &&
mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) &&
mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
}
/* undocumented getter */
bool QCPColorScale::rangeZoom() const
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return false;
}
return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) &&
mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) &&
mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
}
/*!
Sets at which side of the color scale the axis is placed, and thus also its orientation.
Note that after setting \a type to a different value, the axis returned by \ref axis() will
be a different one. The new axis will adopt the following properties from the previous axis: The
range, scale type, label and ticker (the latter will be shared and not copied).
*/
void QCPColorScale::setType(QCPAxis::AxisType type)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
if (mType != type)
{
mType = type;
QCPRange rangeTransfer(0, 6);
QString labelTransfer;
QSharedPointer<QCPAxisTicker> tickerTransfer;
// transfer/revert some settings on old axis if it exists:
bool doTransfer = !mColorAxis.isNull();
if (doTransfer)
{
rangeTransfer = mColorAxis.data()->range();
labelTransfer = mColorAxis.data()->label();
tickerTransfer = mColorAxis.data()->ticker();
mColorAxis.data()->setLabel(QString());
disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
}
const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop;
foreach (QCPAxis::AxisType atype, allAxisTypes)
{
mAxisRect.data()->axis(atype)->setTicks(atype == mType);
mAxisRect.data()->axis(atype)->setTickLabels(atype== mType);
}
// set new mColorAxis pointer:
mColorAxis = mAxisRect.data()->axis(mType);
// transfer settings to new axis:
if (doTransfer)
{
mColorAxis.data()->setRange(rangeTransfer); // range transfer necessary if axis changes from vertical to horizontal or vice versa (axes with same orientation are synchronized via signals)
mColorAxis.data()->setLabel(labelTransfer);
mColorAxis.data()->setTicker(tickerTransfer);
}
connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
mAxisRect.data()->setRangeDragAxes(QList<QCPAxis*>() << mColorAxis.data());
}
}
/*!
Sets the range spanned by the color gradient and that is shown by the axis in the color scale.
It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is
also equivalent to directly accessing the \ref axis and setting its range with \ref
QCPAxis::setRange.
\see setDataScaleType, setGradient, rescaleDataRange
*/
void QCPColorScale::setDataRange(const QCPRange &dataRange)
{
if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
{
mDataRange = dataRange;
if (mColorAxis)
mColorAxis.data()->setRange(mDataRange);
emit dataRangeChanged(mDataRange);
}
}
/*!
Sets the scale type of the color scale, i.e. whether values are associated with colors linearly
or logarithmically.
It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is
also equivalent to directly accessing the \ref axis and setting its scale type with \ref
QCPAxis::setScaleType.
Note that this method controls the coordinate transformation. For logarithmic scales, you will
likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
the color scale's \ref axis ticker to an instance of \ref QCPAxisTickerLog :
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-colorscale
See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
creation.
\see setDataRange, setGradient
*/
void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType)
{
if (mDataScaleType != scaleType)
{
mDataScaleType = scaleType;
if (mColorAxis)
mColorAxis.data()->setScaleType(mDataScaleType);
if (mDataScaleType == QCPAxis::stLogarithmic)
setDataRange(mDataRange.sanitizedForLogScale());
emit dataScaleTypeChanged(mDataScaleType);
}
}
/*!
Sets the color gradient that will be used to represent data values.
It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps.
\see setDataRange, setDataScaleType
*/
void QCPColorScale::setGradient(const QCPColorGradient &gradient)
{
if (mGradient != gradient)
{
mGradient = gradient;
if (mAxisRect)
mAxisRect.data()->mGradientImageInvalidated = true;
emit gradientChanged(mGradient);
}
}
/*!
Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on
the internal \ref axis.
*/
void QCPColorScale::setLabel(const QString &str)
{
if (!mColorAxis)
{
qDebug() << Q_FUNC_INFO << "internal color axis undefined";
return;
}
mColorAxis.data()->setLabel(str);
}
/*!
Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed
will have.
*/
void QCPColorScale::setBarWidth(int width)
{
mBarWidth = width;
}
/*!
Sets whether the user can drag the data range (\ref setDataRange).
Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref
QCustomPlot::setInteractions) to allow range dragging.
*/
void QCPColorScale::setRangeDrag(bool enabled)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
if (enabled)
{
mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType));
} else
{
#if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
mAxisRect.data()->setRangeDrag(nullptr);
#else
mAxisRect.data()->setRangeDrag({});
#endif
}
}
/*!
Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel.
Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref
QCustomPlot::setInteractions) to allow range dragging.
*/
void QCPColorScale::setRangeZoom(bool enabled)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
if (enabled)
{
mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType));
} else
{
#if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
mAxisRect.data()->setRangeDrag(nullptr);
#else
mAxisRect.data()->setRangeZoom({});
#endif
}
}
/*!
Returns a list of all the color maps associated with this color scale.
*/
QList<QCPColorMap*> QCPColorScale::colorMaps() const
{
QList<QCPColorMap*> result;
for (int i=0; i<mParentPlot->plottableCount(); ++i)
{
if (QCPColorMap *cm = qobject_cast<QCPColorMap*>(mParentPlot->plottable(i)))
if (cm->colorScale() == this)
result.append(cm);
}
return result;
}
/*!
Changes the data range such that all color maps associated with this color scale are fully mapped
to the gradient in the data dimension.
\see setDataRange
*/
void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps)
{
QList<QCPColorMap*> maps = colorMaps();
QCPRange newRange;
bool haveRange = false;
QCP::SignDomain sign = QCP::sdBoth;
if (mDataScaleType == QCPAxis::stLogarithmic)
sign = (mDataRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
foreach (QCPColorMap *map, maps)
{
if (!map->realVisibility() && onlyVisibleMaps)
continue;
QCPRange mapRange;
if (map->colorScale() == this)
{
bool currentFoundRange = true;
mapRange = map->data()->dataBounds();
if (sign == QCP::sdPositive)
{
if (mapRange.lower <= 0 && mapRange.upper > 0)
mapRange.lower = mapRange.upper*1e-3;
else if (mapRange.lower <= 0 && mapRange.upper <= 0)
currentFoundRange = false;
} else if (sign == QCP::sdNegative)
{
if (mapRange.upper >= 0 && mapRange.lower < 0)
mapRange.upper = mapRange.lower*1e-3;
else if (mapRange.upper >= 0 && mapRange.lower >= 0)
currentFoundRange = false;
}
if (currentFoundRange)
{
if (!haveRange)
newRange = mapRange;
else
newRange.expand(mapRange);
haveRange = true;
}
}
}
if (haveRange)
{
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
if (mDataScaleType == QCPAxis::stLinear)
{
newRange.lower = center-mDataRange.size()/2.0;
newRange.upper = center+mDataRange.size()/2.0;
} else // mScaleType == stLogarithmic
{
newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower);
newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower);
}
}
setDataRange(newRange);
}
}
/* inherits documentation from base class */
void QCPColorScale::update(UpdatePhase phase)
{
QCPLayoutElement::update(phase);
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
mAxisRect.data()->update(phase);
switch (phase)
{
case upMargins:
{
if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop)
{
setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom());
setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom());
} else
{
setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), QWIDGETSIZE_MAX);
setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), 0);
}
break;
}
case upLayout:
{
mAxisRect.data()->setOuterRect(rect());
break;
}
default: break;
}
}
/* inherits documentation from base class */
void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
painter->setAntialiasing(false);
}
/* inherits documentation from base class */
void QCPColorScale::mousePressEvent(QMouseEvent *event, const QVariant &details)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
mAxisRect.data()->mousePressEvent(event, details);
}
/* inherits documentation from base class */
void QCPColorScale::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
mAxisRect.data()->mouseMoveEvent(event, startPos);
}
/* inherits documentation from base class */
void QCPColorScale::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
mAxisRect.data()->mouseReleaseEvent(event, startPos);
}
/* inherits documentation from base class */
void QCPColorScale::wheelEvent(QWheelEvent *event)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
mAxisRect.data()->wheelEvent(event);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPColorScaleAxisRectPrivate
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPColorScaleAxisRectPrivate
\internal
\brief An axis rect subclass for use in a QCPColorScale
This is a private class and not part of the public QCustomPlot interface.
It provides the axis rect functionality for the QCPColorScale class.
*/
/*!
Creates a new instance, as a child of \a parentColorScale.
*/
QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) :
QCPAxisRect(parentColorScale->parentPlot(), true),
mParentColorScale(parentColorScale),
mGradientImageInvalidated(true)
{
setParentLayerable(parentColorScale);
setMinimumMargins(QMargins(0, 0, 0, 0));
const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
foreach (QCPAxis::AxisType type, allAxisTypes)
{
axis(type)->setVisible(true);
axis(type)->grid()->setVisible(false);
axis(type)->setPadding(0);
connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts)));
connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts)));
}
connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange)));
connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange)));
connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange)));
connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange)));
connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType)));
connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType)));
connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType)));
connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType)));
// make layer transfers of color scale transfer to axis rect and axes
// the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect:
connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*)));
foreach (QCPAxis::AxisType type, allAxisTypes)
connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*)));
}
/*! \internal
Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws
it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation.
\seebaseclassmethod
*/
void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter)
{
if (mGradientImageInvalidated)
updateGradientImage();
bool mirrorHorz = false;
bool mirrorVert = false;
if (mParentColorScale->mColorAxis)
{
mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop);
mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight);
}
painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert));
QCPAxisRect::draw(painter);
}
/*! \internal
Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to
generate a gradient image. This gradient image will be used in the \ref draw method.
*/
void QCPColorScaleAxisRectPrivate::updateGradientImage()
{
if (rect().isEmpty())
return;
const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
int n = mParentColorScale->mGradient.levelCount();
int w, h;
QVector<double> data(n);
for (int i=0; i<n; ++i)
data[i] = i;
if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop)
{
w = n;
h = rect().height();
mGradientImage = QImage(w, h, format);
QVector<QRgb*> pixels;
for (int y=0; y<h; ++y)
pixels.append(reinterpret_cast<QRgb*>(mGradientImage.scanLine(y)));
mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n);
for (int y=1; y<h; ++y)
memcpy(pixels.at(y), pixels.first(), size_t(n)*sizeof(QRgb));
} else
{
w = rect().width();
h = n;
mGradientImage = QImage(w, h, format);
for (int y=0; y<h; ++y)
{
QRgb *pixels = reinterpret_cast<QRgb*>(mGradientImage.scanLine(y));
const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1));
for (int x=0; x<w; ++x)
pixels[x] = lineColor;
}
}
mGradientImageInvalidated = false;
}
/*! \internal
This slot is connected to the selectionChanged signals of the four axes in the constructor. It
synchronizes the selection state of the axes.
*/
void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts)
{
// axis bases of four axes shall always (de-)selected synchronously:
const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
foreach (QCPAxis::AxisType type, allAxisTypes)
{
if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
if (senderAxis->axisType() == type)
continue;
if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
{
if (selectedParts.testFlag(QCPAxis::spAxis))
axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis);
else
axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis);
}
}
}
/*! \internal
This slot is connected to the selectableChanged signals of the four axes in the constructor. It
synchronizes the selectability of the axes.
*/
void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts)
{
// synchronize axis base selectability:
const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
foreach (QCPAxis::AxisType type, allAxisTypes)
{
if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
if (senderAxis->axisType() == type)
continue;
if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
{
if (selectableParts.testFlag(QCPAxis::spAxis))
axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis);
else
axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis);
}
}
}
/* end of 'src/layoutelements/layoutelement-colorscale.cpp' */
/* including file 'src/plottables/plottable-graph.cpp' */
/* modified 2022-11-06T12:45:57, size 74926 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPGraphData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPGraphData
\brief Holds the data of one single data point for QCPGraph.
The stored data is:
\li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
\li \a value: coordinate on the value axis of this data point (this is the \a mainValue)
The container for storing multiple data points is \ref QCPGraphDataContainer. It is a typedef for
\ref QCPDataContainer with \ref QCPGraphData as the DataType template parameter. See the
documentation there for an explanation regarding the data type's generic methods.
\see QCPGraphDataContainer
*/
/* start documentation of inline functions */
/*! \fn double QCPGraphData::sortKey() const
Returns the \a key member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn static QCPGraphData QCPGraphData::fromSortKey(double sortKey)
Returns a data point with the specified \a sortKey. All other members are set to zero.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn static static bool QCPGraphData::sortKeyIsMainKey()
Since the member \a key is both the data point key coordinate and the data ordering parameter,
this method returns true.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn double QCPGraphData::mainKey() const
Returns the \a key member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn double QCPGraphData::mainValue() const
Returns the \a value member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn QCPRange QCPGraphData::valueRange() const
Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/* end documentation of inline functions */
/*!
Constructs a data point with key and value set to zero.
*/
QCPGraphData::QCPGraphData() :
key(0),
value(0)
{
}
/*!
Constructs a data point with the specified \a key and \a value.
*/
QCPGraphData::QCPGraphData(double key, double value) :
key(key),
value(value)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPGraph
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPGraph
\brief A plottable representing a graph in a plot.
\image html QCPGraph.png
Usually you create new graphs by calling QCustomPlot::addGraph. The resulting instance can be
accessed via QCustomPlot::graph.
To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
also access and modify the data via the \ref data method, which returns a pointer to the internal
\ref QCPGraphDataContainer.
Graphs are used to display single-valued data. Single-valued means that there should only be one
data point per unique key coordinate. In other words, the graph can't have \a loops. If you do
want to plot non-single-valued curves, rather use the QCPCurve plottable.
Gaps in the graph line can be created by adding data points with NaN as value
(<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
separated.
\section qcpgraph-appearance Changing the appearance
The appearance of the graph is mainly determined by the line style, scatter style, brush and pen
of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen).
\subsection filling Filling under or between graphs
QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to
the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill,
just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent.
By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill
between this graph and another one, call \ref setChannelFillGraph with the other graph as
parameter.
\see QCustomPlot::addGraph, QCustomPlot::graph
*/
/* start of documentation of inline functions */
/*! \fn QSharedPointer<QCPGraphDataContainer> QCPGraph::data() const
Returns a shared pointer to the internal data storage of type \ref QCPGraphDataContainer. You may
use it to directly manipulate the data, which may be more convenient and faster than using the
regular \ref setData or \ref addData methods.
*/
/* end of documentation of inline functions */
/*!
Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
the same orientation. If either of these restrictions is violated, a corresponding message is
printed to the debug output (qDebug), the construction is not aborted, though.
The created QCPGraph is automatically registered with the QCustomPlot instance inferred from \a
keyAxis. This QCustomPlot instance takes ownership of the QCPGraph, so do not delete it manually
but use QCustomPlot::removePlottable() instead.
To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function.
*/
QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable1D<QCPGraphData>(keyAxis, valueAxis),
mLineStyle{},
mScatterSkip{},
mAdaptiveSampling{}
{
// special handling for QCPGraphs to maintain the simple graph interface:
mParentPlot->registerGraph(this);
setPen(QPen(Qt::blue, 0));
setBrush(Qt::NoBrush);
setLineStyle(lsLine);
setScatterSkip(0);
setChannelFillGraph(nullptr);
setAdaptiveSampling(true);
}
QCPGraph::~QCPGraph()
{
}
/*! \overload
Replaces the current data container with the provided \a data container.
Since a QSharedPointer is used, multiple QCPGraphs may share the same data container safely.
Modifying the data in the container will then affect all graphs that share the container. Sharing
can be achieved by simply exchanging the data containers wrapped in shared pointers:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-1
If you do not wish to share containers, but create a copy from an existing container, rather use
the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-2
\see addData
*/
void QCPGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
{
mDataContainer = data;
}
/*! \overload
Replaces the current data with the provided points in \a keys and \a values. The provided
vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
can set \a alreadySorted to true, to improve performance by saving a sorting run.
\see addData
*/
void QCPGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
{
mDataContainer->clear();
addData(keys, values, alreadySorted);
}
/*!
Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
\ref lsNone and \ref setScatterStyle to the desired scatter style.
\see setScatterStyle
*/
void QCPGraph::setLineStyle(LineStyle ls)
{
mLineStyle = ls;
}
/*!
Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
are drawn (e.g. for line-only-plots with appropriate line style).
\see QCPScatterStyle, setLineStyle
*/
void QCPGraph::setScatterStyle(const QCPScatterStyle &style)
{
mScatterStyle = style;
}
/*!
If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
scatter points are skipped/not drawn after every drawn scatter point.
This can be used to make the data appear sparser while for example still having a smooth line,
and to improve performance for very high density plots.
If \a skip is set to 0 (default), all scatter points are drawn.
\see setScatterStyle
*/
void QCPGraph::setScatterSkip(int skip)
{
mScatterSkip = qMax(0, skip);
}
/*!
Sets the target graph for filling the area between this graph and \a targetGraph with the current
brush (\ref setBrush).
When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To
disable any filling, set the brush to Qt::NoBrush.
\see setBrush
*/
void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph)
{
// prevent setting channel target to this graph itself:
if (targetGraph == this)
{
qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself";
mChannelFillGraph = nullptr;
return;
}
// prevent setting channel target to a graph not in the plot:
if (targetGraph && targetGraph->mParentPlot != mParentPlot)
{
qDebug() << Q_FUNC_INFO << "targetGraph not in same plot";
mChannelFillGraph = nullptr;
return;
}
mChannelFillGraph = targetGraph;
}
/*!
Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive
sampling technique can drastically improve the replot performance for graphs with a larger number
of points (e.g. above 10,000), without notably changing the appearance of the graph.
By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive
sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no
disadvantage in almost all cases.
\image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling"
As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are
reproduced reliably, as well as the overall shape of the data set. The replot time reduces
dramatically though. This allows QCustomPlot to display large amounts of data in realtime.
\image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling"
Care must be taken when using high-density scatter plots in combination with adaptive sampling.
The adaptive sampling algorithm treats scatter plots more carefully than line plots which still
gives a significant reduction of replot times, but not quite as much as for line plots. This is
because scatter plots inherently need more data points to be preserved in order to still resemble
the original, non-adaptive-sampling plot. As shown above, the results still aren't quite
identical, as banding occurs for the outer data points. This is in fact intentional, such that
the boundaries of the data cloud stay visible to the viewer. How strong the banding appears,
depends on the point density, i.e. the number of points in the plot.
For some situations with scatter plots it might thus be desirable to manually turn adaptive
sampling off. For example, when saving the plot to disk. This can be achieved by setting \a
enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled
back to true afterwards.
*/
void QCPGraph::setAdaptiveSampling(bool enabled)
{
mAdaptiveSampling = enabled;
}
/*! \overload
Adds the provided points in \a keys and \a values to the current data. The provided vectors
should have equal length. Else, the number of added points will be the size of the smallest
vector.
If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
can set \a alreadySorted to true, to improve performance by saving a sorting run.
Alternatively, you can also access and modify the data directly via the \ref data method, which
returns a pointer to the internal data container.
*/
void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
{
if (keys.size() != values.size())
qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
const int n = static_cast<int>(qMin(keys.size(), values.size()));
QVector<QCPGraphData> tempData(n);
QVector<QCPGraphData>::iterator it = tempData.begin();
const QVector<QCPGraphData>::iterator itEnd = tempData.end();
int i = 0;
while (it != itEnd)
{
it->key = keys[i];
it->value = values[i];
++it;
++i;
}
mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
}
/*! \overload
Adds the provided data point as \a key and \a value to the current data.
Alternatively, you can also access and modify the data directly via the \ref data method, which
returns a pointer to the internal data container.
*/
void QCPGraph::addData(double key, double value)
{
mDataContainer->add(QCPGraphData(key, value));
}
/*!
Implements a selectTest specific to this plottable's point geometry.
If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
point to \a pos.
\seebaseclassmethod \ref QCPAbstractPlottable::selectTest
*/
double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
return -1;
if (!mKeyAxis || !mValueAxis)
return -1;
if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
{
QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
double result = pointDistance(pos, closestDataPoint);
if (details)
{
int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
}
return result;
} else
return -1;
}
/* inherits documentation from base class */
QCPRange QCPGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
{
return mDataContainer->keyRange(foundRange, inSignDomain);
}
/* inherits documentation from base class */
QCPRange QCPGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
{
return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
}
/* inherits documentation from base class */
void QCPGraph::draw(QCPPainter *painter)
{
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
// loop over and draw segments of unselected/selected data:
QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
getDataSegments(selectedSegments, unselectedSegments);
allSegments << unselectedSegments << selectedSegments;
for (int i=0; i<allSegments.size(); ++i)
{
bool isSelectedSegment = i >= unselectedSegments.size();
// get line pixel points appropriate to line style:
QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getLines takes care)
getLines(&lines, lineDataRange);
// check data validity if flag set:
#ifdef QCUSTOMPLOT_CHECK_DATA
QCPGraphDataContainer::const_iterator it;
for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
{
if (QCP::isInvalidData(it->key, it->value))
qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
}
#endif
// draw fill of graph:
if (isSelectedSegment && mSelectionDecorator)
mSelectionDecorator->applyBrush(painter);
else
painter->setBrush(mBrush);
painter->setPen(Qt::NoPen);
drawFill(painter, &lines);
// draw line:
if (mLineStyle != lsNone)
{
if (isSelectedSegment && mSelectionDecorator)
mSelectionDecorator->applyPen(painter);
else
painter->setPen(mPen);
painter->setBrush(Qt::NoBrush);
if (mLineStyle == lsImpulse)
drawImpulsePlot(painter, lines);
else
drawLinePlot(painter, lines); // also step plots can be drawn as a line plot
}
// draw scatters:
QCPScatterStyle finalScatterStyle = mScatterStyle;
if (isSelectedSegment && mSelectionDecorator)
finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
if (!finalScatterStyle.isNone())
{
getScatters(&scatters, allSegments.at(i));
drawScatterPlot(painter, scatters, finalScatterStyle);
}
}
// draw other selection decoration that isn't just line/scatter pens and brushes:
if (mSelectionDecorator)
mSelectionDecorator->drawDecoration(painter, selection());
}
/* inherits documentation from base class */
void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
// draw fill:
if (mBrush.style() != Qt::NoBrush)
{
applyFillAntialiasingHint(painter);
painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
}
// draw line vertically centered:
if (mLineStyle != lsNone)
{
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
}
// draw scatter symbol:
if (!mScatterStyle.isNone())
{
applyScattersAntialiasingHint(painter);
// scale scatter pixmap if it's too large to fit in legend icon rect:
if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
{
QCPScatterStyle scaledStyle(mScatterStyle);
scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
scaledStyle.applyTo(painter, mPen);
scaledStyle.drawShape(painter, QRectF(rect).center());
} else
{
mScatterStyle.applyTo(painter, mPen);
mScatterStyle.drawShape(painter, QRectF(rect).center());
}
}
}
/*! \internal
This method retrieves an optimized set of data points via \ref getOptimizedLineData, and branches
out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
according to the line style of the graph.
\a lines will be filled with points in pixel coordinates, that can be drawn with the according
draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
aren't necessarily the original data points. For example, step line styles require additional
points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
lines vector will be empty.
\a dataRange specifies the beginning and ending data indices that will be taken into account for
conversion. In this function, the specified range may exceed the total data bounds without harm:
a correspondingly trimmed data range will be used. This takes the burden off the user of this
function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
getDataSegments.
\see getScatters
*/
void QCPGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
{
if (!lines) return;
QCPGraphDataContainer::const_iterator begin, end;
getVisibleDataBounds(begin, end, dataRange);
if (begin == end)
{
lines->clear();
return;
}
QVector<QCPGraphData> lineData;
if (mLineStyle != lsNone)
getOptimizedLineData(&lineData, begin, end);
if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in lineData (significantly simplifies following processing)
std::reverse(lineData.begin(), lineData.end());
switch (mLineStyle)
{
case lsNone: lines->clear(); break;
case lsLine: *lines = dataToLines(lineData); break;
case lsStepLeft: *lines = dataToStepLeftLines(lineData); break;
case lsStepRight: *lines = dataToStepRightLines(lineData); break;
case lsStepCenter: *lines = dataToStepCenterLines(lineData); break;
case lsImpulse: *lines = dataToImpulseLines(lineData); break;
}
}
/*! \internal
This method retrieves an optimized set of data points via \ref getOptimizedScatterData and then
converts them to pixel coordinates. The resulting points are returned in \a scatters, and can be
passed to \ref drawScatterPlot.
\a dataRange specifies the beginning and ending data indices that will be taken into account for
conversion. In this function, the specified range may exceed the total data bounds without harm:
a correspondingly trimmed data range will be used. This takes the burden off the user of this
function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
getDataSegments.
*/
void QCPGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
{
if (!scatters) return;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; scatters->clear(); return; }
QCPGraphDataContainer::const_iterator begin, end;
getVisibleDataBounds(begin, end, dataRange);
if (begin == end)
{
scatters->clear();
return;
}
QVector<QCPGraphData> data;
getOptimizedScatterData(&data, begin, end);
if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in data (significantly simplifies following processing)
std::reverse(data.begin(), data.end());
scatters->resize(data.size());
if (keyAxis->orientation() == Qt::Vertical)
{
for (int i=0; i<data.size(); ++i)
{
if (!qIsNaN(data.at(i).value))
{
(*scatters)[i].setX(valueAxis->coordToPixel(data.at(i).value));
(*scatters)[i].setY(keyAxis->coordToPixel(data.at(i).key));
}
}
} else
{
for (int i=0; i<data.size(); ++i)
{
if (!qIsNaN(data.at(i).value))
{
(*scatters)[i].setX(keyAxis->coordToPixel(data.at(i).key));
(*scatters)[i].setY(valueAxis->coordToPixel(data.at(i).value));
}
}
}
}
/*! \internal
Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
coordinate points which are suitable for drawing the line style \ref lsLine.
The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
getLines if the line style is set accordingly.
\see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
*/
QVector<QPointF> QCPGraph::dataToLines(const QVector<QCPGraphData> &data) const
{
QVector<QPointF> result;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
result.resize(data.size());
// transform data points to pixels:
if (keyAxis->orientation() == Qt::Vertical)
{
for (int i=0; i<data.size(); ++i)
{
result[i].setX(valueAxis->coordToPixel(data.at(i).value));
result[i].setY(keyAxis->coordToPixel(data.at(i).key));
}
} else // key axis is horizontal
{
for (int i=0; i<data.size(); ++i)
{
result[i].setX(keyAxis->coordToPixel(data.at(i).key));
result[i].setY(valueAxis->coordToPixel(data.at(i).value));
}
}
return result;
}
/*! \internal
Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
coordinate points which are suitable for drawing the line style \ref lsStepLeft.
The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
getLines if the line style is set accordingly.
\see dataToLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
*/
QVector<QPointF> QCPGraph::dataToStepLeftLines(const QVector<QCPGraphData> &data) const
{
QVector<QPointF> result;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
result.resize(data.size()*2);
// calculate steps from data and transform to pixel coordinates:
if (keyAxis->orientation() == Qt::Vertical)
{
double lastValue = valueAxis->coordToPixel(data.first().value);
for (int i=0; i<data.size(); ++i)
{
const double key = keyAxis->coordToPixel(data.at(i).key);
result[i*2+0].setX(lastValue);
result[i*2+0].setY(key);
lastValue = valueAxis->coordToPixel(data.at(i).value);
result[i*2+1].setX(lastValue);
result[i*2+1].setY(key);
}
} else // key axis is horizontal
{
double lastValue = valueAxis->coordToPixel(data.first().value);
for (int i=0; i<data.size(); ++i)
{
const double key = keyAxis->coordToPixel(data.at(i).key);
result[i*2+0].setX(key);
result[i*2+0].setY(lastValue);
lastValue = valueAxis->coordToPixel(data.at(i).value);
result[i*2+1].setX(key);
result[i*2+1].setY(lastValue);
}
}
return result;
}
/*! \internal
Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
coordinate points which are suitable for drawing the line style \ref lsStepRight.
The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
getLines if the line style is set accordingly.
\see dataToLines, dataToStepLeftLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
*/
QVector<QPointF> QCPGraph::dataToStepRightLines(const QVector<QCPGraphData> &data) const
{
QVector<QPointF> result;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
result.resize(data.size()*2);
// calculate steps from data and transform to pixel coordinates:
if (keyAxis->orientation() == Qt::Vertical)
{
double lastKey = keyAxis->coordToPixel(data.first().key);
for (int i=0; i<data.size(); ++i)
{
const double value = valueAxis->coordToPixel(data.at(i).value);
result[i*2+0].setX(value);
result[i*2+0].setY(lastKey);
lastKey = keyAxis->coordToPixel(data.at(i).key);
result[i*2+1].setX(value);
result[i*2+1].setY(lastKey);
}
} else // key axis is horizontal
{
double lastKey = keyAxis->coordToPixel(data.first().key);
for (int i=0; i<data.size(); ++i)
{
const double value = valueAxis->coordToPixel(data.at(i).value);
result[i*2+0].setX(lastKey);
result[i*2+0].setY(value);
lastKey = keyAxis->coordToPixel(data.at(i).key);
result[i*2+1].setX(lastKey);
result[i*2+1].setY(value);
}
}
return result;
}
/*! \internal
Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
coordinate points which are suitable for drawing the line style \ref lsStepCenter.
The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
getLines if the line style is set accordingly.
\see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToImpulseLines, getLines, drawLinePlot
*/
QVector<QPointF> QCPGraph::dataToStepCenterLines(const QVector<QCPGraphData> &data) const
{
QVector<QPointF> result;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
result.resize(data.size()*2);
// calculate steps from data and transform to pixel coordinates:
if (keyAxis->orientation() == Qt::Vertical)
{
double lastKey = keyAxis->coordToPixel(data.first().key);
double lastValue = valueAxis->coordToPixel(data.first().value);
result[0].setX(lastValue);
result[0].setY(lastKey);
for (int i=1; i<data.size(); ++i)
{
const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
result[i*2-1].setX(lastValue);
result[i*2-1].setY(key);
lastValue = valueAxis->coordToPixel(data.at(i).value);
lastKey = keyAxis->coordToPixel(data.at(i).key);
result[i*2+0].setX(lastValue);
result[i*2+0].setY(key);
}
result[data.size()*2-1].setX(lastValue);
result[data.size()*2-1].setY(lastKey);
} else // key axis is horizontal
{
double lastKey = keyAxis->coordToPixel(data.first().key);
double lastValue = valueAxis->coordToPixel(data.first().value);
result[0].setX(lastKey);
result[0].setY(lastValue);
for (int i=1; i<data.size(); ++i)
{
const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
result[i*2-1].setX(key);
result[i*2-1].setY(lastValue);
lastValue = valueAxis->coordToPixel(data.at(i).value);
lastKey = keyAxis->coordToPixel(data.at(i).key);
result[i*2+0].setX(key);
result[i*2+0].setY(lastValue);
}
result[data.size()*2-1].setX(lastKey);
result[data.size()*2-1].setY(lastValue);
}
return result;
}
/*! \internal
Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
coordinate points which are suitable for drawing the line style \ref lsImpulse.
The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
getLines if the line style is set accordingly.
\see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, getLines, drawImpulsePlot
*/
QVector<QPointF> QCPGraph::dataToImpulseLines(const QVector<QCPGraphData> &data) const
{
QVector<QPointF> result;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
result.resize(data.size()*2);
// transform data points to pixels:
if (keyAxis->orientation() == Qt::Vertical)
{
for (int i=0; i<data.size(); ++i)
{
const QCPGraphData ¤t = data.at(i);
if (!qIsNaN(current.value))
{
const double key = keyAxis->coordToPixel(current.key);
result[i*2+0].setX(valueAxis->coordToPixel(0));
result[i*2+0].setY(key);
result[i*2+1].setX(valueAxis->coordToPixel(current.value));
result[i*2+1].setY(key);
} else
{
result[i*2+0] = QPointF(0, 0);
result[i*2+1] = QPointF(0, 0);
}
}
} else // key axis is horizontal
{
for (int i=0; i<data.size(); ++i)
{
const QCPGraphData ¤t = data.at(i);
if (!qIsNaN(current.value))
{
const double key = keyAxis->coordToPixel(data.at(i).key);
result[i*2+0].setX(key);
result[i*2+0].setY(valueAxis->coordToPixel(0));
result[i*2+1].setX(key);
result[i*2+1].setY(valueAxis->coordToPixel(data.at(i).value));
} else
{
result[i*2+0] = QPointF(0, 0);
result[i*2+1] = QPointF(0, 0);
}
}
}
return result;
}
/*! \internal
Draws the fill of the graph using the specified \a painter, with the currently set brush.
Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref
getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons.
In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas),
this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to
operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN
segments of the two involved graphs, before passing the overlapping pairs to \ref
getChannelFillPolygon.
Pass the points of this graph's line as \a lines, in pixel coordinates.
\see drawLinePlot, drawImpulsePlot, drawScatterPlot
*/
void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
{
if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot
if (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) return;
applyFillAntialiasingHint(painter);
const QVector<QCPDataRange> segments = getNonNanSegments(lines, keyAxis()->orientation());
if (!mChannelFillGraph)
{
// draw base fill under graph, fill goes all the way to the zero-value-line:
foreach (QCPDataRange segment, segments)
painter->drawPolygon(getFillPolygon(lines, segment));
} else
{
// draw fill between this graph and mChannelFillGraph:
QVector<QPointF> otherLines;
mChannelFillGraph->getLines(&otherLines, QCPDataRange(0, mChannelFillGraph->dataCount()));
if (!otherLines.isEmpty())
{
QVector<QCPDataRange> otherSegments = getNonNanSegments(&otherLines, mChannelFillGraph->keyAxis()->orientation());
QVector<QPair<QCPDataRange, QCPDataRange> > segmentPairs = getOverlappingSegments(segments, lines, otherSegments, &otherLines);
for (int i=0; i<segmentPairs.size(); ++i)
painter->drawPolygon(getChannelFillPolygon(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second));
}
}
}
/*! \internal
Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
scatters will be drawn with \a painter and have the appearance as specified in \a style.
\see drawLinePlot, drawImpulsePlot
*/
void QCPGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
{
applyScattersAntialiasingHint(painter);
style.applyTo(painter, mPen);
foreach (const QPointF &scatter, scatters)
style.drawShape(painter, scatter.x(), scatter.y());
}
/*! \internal
Draws lines between the points in \a lines, given in pixel coordinates.
\see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
*/
void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
{
if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
{
applyDefaultAntialiasingHint(painter);
drawPolyline(painter, lines);
}
}
/*! \internal
Draws impulses from the provided data, i.e. it connects all line pairs in \a lines, given in
pixel coordinates. The \a lines necessary for impulses are generated by \ref dataToImpulseLines
from the regular graph data points.
\see drawLinePlot, drawScatterPlot
*/
void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
{
if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
{
applyDefaultAntialiasingHint(painter);
QPen oldPen = painter->pen();
QPen newPen = painter->pen();
newPen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
painter->setPen(newPen);
painter->drawLines(lines);
painter->setPen(oldPen);
}
}
/*! \internal
Returns via \a lineData the data points that need to be visualized for this graph when plotting
graph lines, taking into consideration the currently visible axis ranges and, if \ref
setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
getDataSegments).
This method is used by \ref getLines to retrieve the basic working set of data.
\see getOptimizedScatterData
*/
void QCPGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
{
if (!lineData) return;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (begin == end) return;
int dataCount = int(end-begin);
int maxCount = (std::numeric_limits<int>::max)();
if (mAdaptiveSampling)
{
double keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key));
if (2*keyPixelSpan+2 < static_cast<double>((std::numeric_limits<int>::max)()))
maxCount = int(2*keyPixelSpan+2);
}
if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
{
QCPGraphDataContainer::const_iterator it = begin;
double minValue = it->value;
double maxValue = it->value;
QCPGraphDataContainer::const_iterator currentIntervalFirstPoint = it;
int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound));
double lastIntervalEndKey = currentIntervalStartKey;
double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
int intervalDataCount = 1;
++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
while (it != end)
{
if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary
{
if (it->value < minValue)
minValue = it->value;
else if (it->value > maxValue)
maxValue = it->value;
++intervalDataCount;
} else // new pixel interval started
{
if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
{
if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point
lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
if (it->key > currentIntervalStartKey+keyEpsilon*2) // new pixel started further away from previous cluster, so make sure the last point of the cluster is at a real data point
lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.8, (it-1)->value));
} else
lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
lastIntervalEndKey = (it-1)->key;
minValue = it->value;
maxValue = it->value;
currentIntervalFirstPoint = it;
currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(it->key)+reversedRound));
if (keyEpsilonVariable)
keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
intervalDataCount = 1;
}
++it;
}
// handle last interval:
if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
{
if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point
lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
} else
lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
} else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
{
lineData->resize(dataCount);
std::copy(begin, end, lineData->begin());
}
}
/*! \internal
Returns via \a scatterData the data points that need to be visualized for this graph when
plotting scatter points, taking into consideration the currently visible axis ranges and, if \ref
setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
getDataSegments).
This method is used by \ref getScatters to retrieve the basic working set of data.
\see getOptimizedLineData
*/
void QCPGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
{
if (!scatterData) return;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
const int scatterModulo = mScatterSkip+1;
const bool doScatterSkip = mScatterSkip > 0;
int beginIndex = int(begin-mDataContainer->constBegin());
int endIndex = int(end-mDataContainer->constBegin());
while (doScatterSkip && begin != end && beginIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
{
++beginIndex;
++begin;
}
if (begin == end) return;
int dataCount = int(end-begin);
int maxCount = (std::numeric_limits<int>::max)();
if (mAdaptiveSampling)
{
int keyPixelSpan = int(qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key)));
maxCount = 2*keyPixelSpan+2;
}
if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
{
double valueMaxRange = valueAxis->range().upper;
double valueMinRange = valueAxis->range().lower;
QCPGraphDataContainer::const_iterator it = begin;
int itIndex = int(beginIndex);
double minValue = it->value;
double maxValue = it->value;
QCPGraphDataContainer::const_iterator minValueIt = it;
QCPGraphDataContainer::const_iterator maxValueIt = it;
QCPGraphDataContainer::const_iterator currentIntervalStart = it;
int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound));
double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
int intervalDataCount = 1;
// advance iterator to second (non-skipped) data point because adaptive sampling works in 1 point retrospect:
if (!doScatterSkip)
++it;
else
{
itIndex += scatterModulo;
if (itIndex < endIndex) // make sure we didn't jump over end
it += scatterModulo;
else
{
it = end;
itIndex = endIndex;
}
}
// main loop over data points:
while (it != end)
{
if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary
{
if (it->value < minValue && it->value > valueMinRange && it->value < valueMaxRange)
{
minValue = it->value;
minValueIt = it;
} else if (it->value > maxValue && it->value > valueMinRange && it->value < valueMaxRange)
{
maxValue = it->value;
maxValueIt = it;
}
++intervalDataCount;
} else // new pixel started
{
if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
{
// determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
// [ However, make sure that the span is at least 1 pixel ]
double valuePixelSpan = qMax(1.0, qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)));
double pointsToAdd = valuePixelSpan/4.0; // add approximately one data point for every 4 value pixels
int dataModulo = qMax(1, qRound(intervalDataCount/pointsToAdd));
QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
int c = 0;
while (intervalIt != it)
{
if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
scatterData->append(*intervalIt);
++c;
if (!doScatterSkip)
++intervalIt;
else
intervalIt += scatterModulo; // since we know indices of "currentIntervalStart", "intervalIt" and "it" are multiples of scatterModulo, we can't accidentally jump over "it" here
}
} else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
scatterData->append(*currentIntervalStart);
minValue = it->value;
maxValue = it->value;
currentIntervalStart = it;
currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(it->key)+reversedRound));
if (keyEpsilonVariable)
keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
intervalDataCount = 1;
}
// advance to next data point:
if (!doScatterSkip)
++it;
else
{
itIndex += scatterModulo;
if (itIndex < endIndex) // make sure we didn't jump over end
it += scatterModulo;
else
{
it = end;
itIndex = endIndex;
}
}
}
// handle last interval:
if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
{
// determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
// [ However, make sure that the span is at least 1 pixel ]
double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
double pointsToAdd = valuePixelSpan/4.0; // add approximately one data point for every 4 value pixels
int dataModulo = qMax(1, qRound(intervalDataCount/pointsToAdd));
QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
int intervalItIndex = int(intervalIt-mDataContainer->constBegin());
int c = 0;
while (intervalIt != it)
{
if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
scatterData->append(*intervalIt);
++c;
if (!doScatterSkip)
++intervalIt;
else // here we can't guarantee that adding scatterModulo doesn't exceed "it" (because "it" is equal to "end" here, and "end" isn't scatterModulo-aligned), so check via index comparison:
{
intervalItIndex += scatterModulo;
if (intervalItIndex < itIndex)
intervalIt += scatterModulo;
else
{
intervalIt = it;
intervalItIndex = itIndex;
}
}
}
} else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
scatterData->append(*currentIntervalStart);
} else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
{
QCPGraphDataContainer::const_iterator it = begin;
int itIndex = beginIndex;
scatterData->reserve(dataCount);
while (it != end)
{
scatterData->append(*it);
// advance to next data point:
if (!doScatterSkip)
++it;
else
{
itIndex += scatterModulo;
if (itIndex < endIndex)
it += scatterModulo;
else
{
it = end;
itIndex = endIndex;
}
}
}
}
}
/*!
This method outputs the currently visible data range via \a begin and \a end. The returned range
will also never exceed \a rangeRestriction.
This method takes into account that the drawing of data lines at the axis rect border always
requires the points just outside the visible axis range. So \a begin and \a end may actually
indicate a range that contains one additional data point to the left and right of the visible
axis range.
*/
void QCPGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
{
if (rangeRestriction.isEmpty())
{
end = mDataContainer->constEnd();
begin = end;
} else
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
// get visible data range:
begin = mDataContainer->findBegin(keyAxis->range().lower);
end = mDataContainer->findEnd(keyAxis->range().upper);
// limit lower/upperEnd to rangeRestriction:
mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
}
}
/*! \internal
This method goes through the passed points in \a lineData and returns a list of the segments
which don't contain NaN data points.
\a keyOrientation defines whether the \a x or \a y member of the passed QPointF is used to check
for NaN. If \a keyOrientation is \c Qt::Horizontal, the \a y member is checked, if it is \c
Qt::Vertical, the \a x member is checked.
\see getOverlappingSegments, drawFill
*/
QVector<QCPDataRange> QCPGraph::getNonNanSegments(const QVector<QPointF> *lineData, Qt::Orientation keyOrientation) const
{
QVector<QCPDataRange> result;
const int n = static_cast<int>(lineData->size());
QCPDataRange currentSegment(-1, -1);
int i = 0;
if (keyOrientation == Qt::Horizontal)
{
while (i < n)
{
while (i < n && qIsNaN(lineData->at(i).y())) // seek next non-NaN data point
++i;
if (i == n)
break;
currentSegment.setBegin(i++);
while (i < n && !qIsNaN(lineData->at(i).y())) // seek next NaN data point or end of data
++i;
currentSegment.setEnd(i++);
result.append(currentSegment);
}
} else // keyOrientation == Qt::Vertical
{
while (i < n)
{
while (i < n && qIsNaN(lineData->at(i).x())) // seek next non-NaN data point
++i;
if (i == n)
break;
currentSegment.setBegin(i++);
while (i < n && !qIsNaN(lineData->at(i).x())) // seek next NaN data point or end of data
++i;
currentSegment.setEnd(i++);
result.append(currentSegment);
}
}
return result;
}
/*! \internal
This method takes two segment lists (e.g. created by \ref getNonNanSegments) \a thisSegments and
\a otherSegments, and their associated point data \a thisData and \a otherData.
It returns all pairs of segments (the first from \a thisSegments, the second from \a
otherSegments), which overlap in plot coordinates.
This method is useful in the case of a channel fill between two graphs, when only those non-NaN
segments which actually overlap in their key coordinate shall be considered for drawing a channel
fill polygon.
It is assumed that the passed segments in \a thisSegments are ordered ascending by index, and
that the segments don't overlap themselves. The same is assumed for the segments in \a
otherSegments. This is fulfilled when the segments are obtained via \ref getNonNanSegments.
\see getNonNanSegments, segmentsIntersect, drawFill, getChannelFillPolygon
*/
QVector<QPair<QCPDataRange, QCPDataRange> > QCPGraph::getOverlappingSegments(QVector<QCPDataRange> thisSegments, const QVector<QPointF> *thisData, QVector<QCPDataRange> otherSegments, const QVector<QPointF> *otherData) const
{
QVector<QPair<QCPDataRange, QCPDataRange> > result;
if (thisData->isEmpty() || otherData->isEmpty() || thisSegments.isEmpty() || otherSegments.isEmpty())
return result;
int thisIndex = 0;
int otherIndex = 0;
const bool verticalKey = mKeyAxis->orientation() == Qt::Vertical;
while (thisIndex < thisSegments.size() && otherIndex < otherSegments.size())
{
if (thisSegments.at(thisIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow
{
++thisIndex;
continue;
}
if (otherSegments.at(otherIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow
{
++otherIndex;
continue;
}
double thisLower, thisUpper, otherLower, otherUpper;
if (!verticalKey)
{
thisLower = thisData->at(thisSegments.at(thisIndex).begin()).x();
thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).x();
otherLower = otherData->at(otherSegments.at(otherIndex).begin()).x();
otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).x();
} else
{
thisLower = thisData->at(thisSegments.at(thisIndex).begin()).y();
thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).y();
otherLower = otherData->at(otherSegments.at(otherIndex).begin()).y();
otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).y();
}
int bPrecedence;
if (segmentsIntersect(thisLower, thisUpper, otherLower, otherUpper, bPrecedence))
result.append(QPair<QCPDataRange, QCPDataRange>(thisSegments.at(thisIndex), otherSegments.at(otherIndex)));
if (bPrecedence <= 0) // otherSegment doesn't reach as far as thisSegment, so continue with next otherSegment, keeping current thisSegment
++otherIndex;
else // otherSegment reaches further than thisSegment, so continue with next thisSegment, keeping current otherSegment
++thisIndex;
}
return result;
}
/*! \internal
Returns whether the segments defined by the coordinates (aLower, aUpper) and (bLower, bUpper)
have overlap.
The output parameter \a bPrecedence indicates whether the \a b segment reaches farther than the
\a a segment or not. If \a bPrecedence returns 1, segment \a b reaches the farthest to higher
coordinates (i.e. bUpper > aUpper). If it returns -1, segment \a a reaches the farthest. Only if
both segment's upper bounds are identical, 0 is returned as \a bPrecedence.
It is assumed that the lower bounds always have smaller or equal values than the upper bounds.
\see getOverlappingSegments
*/
bool QCPGraph::segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const
{
bPrecedence = 0;
if (aLower > bUpper)
{
bPrecedence = -1;
return false;
} else if (bLower > aUpper)
{
bPrecedence = 1;
return false;
} else
{
if (aUpper > bUpper)
bPrecedence = -1;
else if (aUpper < bUpper)
bPrecedence = 1;
return true;
}
}
/*! \internal
Returns the point which closes the fill polygon on the zero-value-line parallel to the key axis.
The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates
is in positive or negative infinity. So this case is handled separately by just closing the fill
polygon on the axis which lies in the direction towards the zero value.
\a matchingDataPoint will provide the key (in pixels) of the returned point. Depending on whether
the key axis of this graph is horizontal or vertical, \a matchingDataPoint will provide the x or
y value of the returned point, respectively.
*/
QPointF QCPGraph::getFillBasePoint(QPointF matchingDataPoint) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
QPointF result;
if (valueAxis->scaleType() == QCPAxis::stLinear)
{
if (keyAxis->orientation() == Qt::Horizontal)
{
result.setX(matchingDataPoint.x());
result.setY(valueAxis->coordToPixel(0));
} else // keyAxis->orientation() == Qt::Vertical
{
result.setX(valueAxis->coordToPixel(0));
result.setY(matchingDataPoint.y());
}
} else // valueAxis->mScaleType == QCPAxis::stLogarithmic
{
// In logarithmic scaling we can't just draw to value 0 so we just fill all the way
// to the axis which is in the direction towards 0
if (keyAxis->orientation() == Qt::Vertical)
{
if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
(valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
result.setX(keyAxis->axisRect()->right());
else
result.setX(keyAxis->axisRect()->left());
result.setY(matchingDataPoint.y());
} else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
{
result.setX(matchingDataPoint.x());
if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
(valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
result.setY(keyAxis->axisRect()->top());
else
result.setY(keyAxis->axisRect()->bottom());
}
}
return result;
}
/*! \internal
Returns the polygon needed for drawing normal fills between this graph and the key axis.
Pass the graph's data points (in pixel coordinates) as \a lineData, and specify the \a segment
which shall be used for the fill. The collection of \a lineData points described by \a segment
must not contain NaN data points (see \ref getNonNanSegments).
The returned fill polygon will be closed at the key axis (the zero-value line) for linear value
axes. For logarithmic value axes the polygon will reach just beyond the corresponding axis rect
side (see \ref getFillBasePoint).
For increased performance (due to implicit sharing), keep the returned QPolygonF const.
\see drawFill, getNonNanSegments
*/
const QPolygonF QCPGraph::getFillPolygon(const QVector<QPointF> *lineData, QCPDataRange segment) const
{
if (segment.size() < 2)
return QPolygonF();
QPolygonF result(segment.size()+2);
result[0] = getFillBasePoint(lineData->at(segment.begin()));
std::copy(lineData->constBegin()+segment.begin(), lineData->constBegin()+segment.end(), result.begin()+1);
result[result.size()-1] = getFillBasePoint(lineData->at(segment.end()-1));
return result;
}
/*! \internal
Returns the polygon needed for drawing (partial) channel fills between this graph and the graph
specified by \ref setChannelFillGraph.
The data points of this graph are passed as pixel coordinates via \a thisData, the data of the
other graph as \a otherData. The returned polygon will be calculated for the specified data
segments \a thisSegment and \a otherSegment, pertaining to the respective \a thisData and \a
otherData, respectively.
The passed \a thisSegment and \a otherSegment should correspond to the segment pairs returned by
\ref getOverlappingSegments, to make sure only segments that actually have key coordinate overlap
need to be processed here.
For increased performance due to implicit sharing, keep the returned QPolygonF const.
\see drawFill, getOverlappingSegments, getNonNanSegments
*/
const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *thisData, QCPDataRange thisSegment, const QVector<QPointF> *otherData, QCPDataRange otherSegment) const
{
if (!mChannelFillGraph)
return QPolygonF();
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); }
if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); }
if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation())
return QPolygonF(); // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis)
if (thisData->isEmpty()) return QPolygonF();
QVector<QPointF> thisSegmentData(thisSegment.size());
QVector<QPointF> otherSegmentData(otherSegment.size());
std::copy(thisData->constBegin()+thisSegment.begin(), thisData->constBegin()+thisSegment.end(), thisSegmentData.begin());
std::copy(otherData->constBegin()+otherSegment.begin(), otherData->constBegin()+otherSegment.end(), otherSegmentData.begin());
// pointers to be able to swap them, depending which data range needs cropping:
QVector<QPointF> *staticData = &thisSegmentData;
QVector<QPointF> *croppedData = &otherSegmentData;
// crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType):
if (keyAxis->orientation() == Qt::Horizontal)
{
// x is key
// crop lower bound:
if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
qSwap(staticData, croppedData);
const int lowBound = findIndexBelowX(croppedData, staticData->first().x());
if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
croppedData->remove(0, lowBound);
// set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
double slope;
if (!qFuzzyCompare(croppedData->at(1).x(), croppedData->at(0).x()))
slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x());
else
slope = 0;
(*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x()));
(*croppedData)[0].setX(staticData->first().x());
// crop upper bound:
if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
qSwap(staticData, croppedData);
int highBound = findIndexAboveX(croppedData, staticData->last().x());
if (highBound == -1) return QPolygonF(); // key ranges have no overlap
croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
// set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
const int li = static_cast<int>(croppedData->size())-1; // last index
if (!qFuzzyCompare(croppedData->at(li).x(), croppedData->at(li-1).x()))
slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x());
else
slope = 0;
(*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x()));
(*croppedData)[li].setX(staticData->last().x());
} else // mKeyAxis->orientation() == Qt::Vertical
{
// y is key
// crop lower bound:
if (staticData->first().y() < croppedData->first().y()) // other one must be cropped
qSwap(staticData, croppedData);
int lowBound = findIndexBelowY(croppedData, staticData->first().y());
if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
croppedData->remove(0, lowBound);
// set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
double slope;
if (!qFuzzyCompare(croppedData->at(1).y(), croppedData->at(0).y())) // avoid division by zero in step plots
slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y());
else
slope = 0;
(*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y()));
(*croppedData)[0].setY(staticData->first().y());
// crop upper bound:
if (staticData->last().y() > croppedData->last().y()) // other one must be cropped
qSwap(staticData, croppedData);
int highBound = findIndexAboveY(croppedData, staticData->last().y());
if (highBound == -1) return QPolygonF(); // key ranges have no overlap
croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
// set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
int li = static_cast<int>(croppedData->size())-1; // last index
if (!qFuzzyCompare(croppedData->at(li).y(), croppedData->at(li-1).y())) // avoid division by zero in step plots
slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y());
else
slope = 0;
(*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y()));
(*croppedData)[li].setY(staticData->last().y());
}
// return joined:
for (int i=static_cast<int>(otherSegmentData.size())-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted
thisSegmentData << otherSegmentData.at(i);
return QPolygonF(thisSegmentData);
}
/*! \internal
Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in
\a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
axis is horizontal.
Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
*/
int QCPGraph::findIndexAboveX(const QVector<QPointF> *data, double x) const
{
for (int i=static_cast<int>(data->size())-1; i>=0; --i)
{
if (data->at(i).x() < x)
{
if (i<data->size()-1)
return i+1;
else
return static_cast<int>(data->size())-1;
}
}
return -1;
}
/*! \internal
Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in
\a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
axis is horizontal.
Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
*/
int QCPGraph::findIndexBelowX(const QVector<QPointF> *data, double x) const
{
for (int i=0; i<data->size(); ++i)
{
if (data->at(i).x() > x)
{
if (i>0)
return i-1;
else
return 0;
}
}
return -1;
}
/*! \internal
Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in
\a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
axis is vertical.
Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
*/
int QCPGraph::findIndexAboveY(const QVector<QPointF> *data, double y) const
{
for (int i=static_cast<int>(data->size())-1; i>=0; --i)
{
if (data->at(i).y() < y)
{
if (i<data->size()-1)
return i+1;
else
return static_cast<int>(data->size())-1;
}
}
return -1;
}
/*! \internal
Calculates the minimum distance in pixels the graph's representation has from the given \a
pixelPoint. This is used to determine whether the graph was clicked or not, e.g. in \ref
selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that if
the graph has a line representation, the returned distance may be smaller than the distance to
the \a closestData point, since the distance to the graph line is also taken into account.
If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape
is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns -1.0.
*/
double QCPGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
{
closestData = mDataContainer->constEnd();
if (mDataContainer->isEmpty())
return -1.0;
if (mLineStyle == lsNone && mScatterStyle.isNone())
return -1.0;
// calculate minimum distances to graph data points and find closestData iterator:
double minDistSqr = (std::numeric_limits<double>::max)();
// determine which key range comes into question, taking selection tolerance around pos into account:
double posKeyMin = 0.0, posKeyMax = 0.0, dummy;
pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
if (posKeyMin > posKeyMax)
qSwap(posKeyMin, posKeyMax);
// iterate over found data points and then choose the one with the shortest distance to pos:
QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
{
const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
if (currentDistSqr < minDistSqr)
{
minDistSqr = currentDistSqr;
closestData = it;
}
}
// calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
if (mLineStyle != lsNone)
{
// line displayed, calculate distance to line segments:
QVector<QPointF> lineData;
getLines(&lineData, QCPDataRange(0, dataCount())); // don't limit data range further since with sharp data spikes, line segments may be closer to test point than segments with closer key coordinate
QCPVector2D p(pixelPoint);
const int step = mLineStyle==lsImpulse ? 2 : 1; // impulse plot differs from other line styles in that the lineData points are only pairwise connected
for (int i=0; i<lineData.size()-1; i+=step)
{
const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
}
return qSqrt(minDistSqr);
}
/*! \internal
Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in
\a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
axis is vertical.
Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
*/
int QCPGraph::findIndexBelowY(const QVector<QPointF> *data, double y) const
{
for (int i=0; i<data->size(); ++i)
{
if (data->at(i).y() > y)
{
if (i>0)
return i-1;
else
return 0;
}
}
return -1;
}
/* end of 'src/plottables/plottable-graph.cpp' */
/* including file 'src/plottables/plottable-curve.cpp' */
/* modified 2022-11-06T12:45:56, size 63851 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPCurveData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPCurveData
\brief Holds the data of one single data point for QCPCurve.
The stored data is:
\li \a t: the free ordering parameter of this curve point, like in the mathematical vector <em>(x(t), y(t))</em>. (This is the \a sortKey)
\li \a key: coordinate on the key axis of this curve point (this is the \a mainKey)
\li \a value: coordinate on the value axis of this curve point (this is the \a mainValue)
The container for storing multiple data points is \ref QCPCurveDataContainer. It is a typedef for
\ref QCPDataContainer with \ref QCPCurveData as the DataType template parameter. See the
documentation there for an explanation regarding the data type's generic methods.
\see QCPCurveDataContainer
*/
/* start documentation of inline functions */
/*! \fn double QCPCurveData::sortKey() const
Returns the \a t member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn static QCPCurveData QCPCurveData::fromSortKey(double sortKey)
Returns a data point with the specified \a sortKey (assigned to the data point's \a t member).
All other members are set to zero.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn static static bool QCPCurveData::sortKeyIsMainKey()
Since the member \a key is the data point key coordinate and the member \a t is the data ordering
parameter, this method returns false.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn double QCPCurveData::mainKey() const
Returns the \a key member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn double QCPCurveData::mainValue() const
Returns the \a value member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn QCPRange QCPCurveData::valueRange() const
Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/* end documentation of inline functions */
/*!
Constructs a curve data point with t, key and value set to zero.
*/
QCPCurveData::QCPCurveData() :
t(0),
key(0),
value(0)
{
}
/*!
Constructs a curve data point with the specified \a t, \a key and \a value.
*/
QCPCurveData::QCPCurveData(double t, double key, double value) :
t(t),
key(key),
value(value)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPCurve
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPCurve
\brief A plottable representing a parametric curve in a plot.
\image html QCPCurve.png
Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate,
so their visual representation can have \a loops. This is realized by introducing a third
coordinate \a t, which defines the order of the points described by the other two coordinates \a
x and \a y.
To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
also access and modify the curve's data via the \ref data method, which returns a pointer to the
internal \ref QCPCurveDataContainer.
Gaps in the curve can be created by adding data points with NaN as key and value
(<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
separated.
\section qcpcurve-appearance Changing the appearance
The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush).
\section qcpcurve-usage Usage
Like all data representing objects in QCustomPlot, the QCPCurve is a plottable
(QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
(QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
Usually, you first create an instance:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1
which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
The newly created plottable can be modified, e.g.:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2
*/
/* start of documentation of inline functions */
/*! \fn QSharedPointer<QCPCurveDataContainer> QCPCurve::data() const
Returns a shared pointer to the internal data storage of type \ref QCPCurveDataContainer. You may
use it to directly manipulate the data, which may be more convenient and faster than using the
regular \ref setData or \ref addData methods.
*/
/* end of documentation of inline functions */
/*!
Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
the same orientation. If either of these restrictions is violated, a corresponding message is
printed to the debug output (qDebug), the construction is not aborted, though.
The created QCPCurve is automatically registered with the QCustomPlot instance inferred from \a
keyAxis. This QCustomPlot instance takes ownership of the QCPCurve, so do not delete it manually
but use QCustomPlot::removePlottable() instead.
*/
QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable1D<QCPCurveData>(keyAxis, valueAxis),
mScatterSkip{},
mLineStyle{}
{
// modify inherited properties from abstract plottable:
setPen(QPen(Qt::blue, 0));
setBrush(Qt::NoBrush);
setScatterStyle(QCPScatterStyle());
setLineStyle(lsLine);
setScatterSkip(0);
}
QCPCurve::~QCPCurve()
{
}
/*! \overload
Replaces the current data container with the provided \a data container.
Since a QSharedPointer is used, multiple QCPCurves may share the same data container safely.
Modifying the data in the container will then affect all curves that share the container. Sharing
can be achieved by simply exchanging the data containers wrapped in shared pointers:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-1
If you do not wish to share containers, but create a copy from an existing container, rather use
the \ref QCPDataContainer<DataType>::set method on the curve's data container directly:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-2
\see addData
*/
void QCPCurve::setData(QSharedPointer<QCPCurveDataContainer> data)
{
mDataContainer = data;
}
/*! \overload
Replaces the current data with the provided points in \a t, \a keys and \a values. The provided
vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
If you can guarantee that the passed data points are sorted by \a t in ascending order, you can
set \a alreadySorted to true, to improve performance by saving a sorting run.
\see addData
*/
void QCPCurve::setData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
{
mDataContainer->clear();
addData(t, keys, values, alreadySorted);
}
/*! \overload
Replaces the current data with the provided points in \a keys and \a values. The provided vectors
should have equal length. Else, the number of added points will be the size of the smallest
vector.
The t parameter of each data point will be set to the integer index of the respective key/value
pair.
\see addData
*/
void QCPCurve::setData(const QVector<double> &keys, const QVector<double> &values)
{
mDataContainer->clear();
addData(keys, values);
}
/*!
Sets the visual appearance of single data points in the plot. If set to \ref
QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate
line style).
\see QCPScatterStyle, setLineStyle
*/
void QCPCurve::setScatterStyle(const QCPScatterStyle &style)
{
mScatterStyle = style;
}
/*!
If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
scatter points are skipped/not drawn after every drawn scatter point.
This can be used to make the data appear sparser while for example still having a smooth line,
and to improve performance for very high density plots.
If \a skip is set to 0 (default), all scatter points are drawn.
\see setScatterStyle
*/
void QCPCurve::setScatterSkip(int skip)
{
mScatterSkip = qMax(0, skip);
}
/*!
Sets how the single data points are connected in the plot or how they are represented visually
apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref
setScatterStyle to the desired scatter style.
\see setScatterStyle
*/
void QCPCurve::setLineStyle(QCPCurve::LineStyle style)
{
mLineStyle = style;
}
/*! \overload
Adds the provided points in \a t, \a keys and \a values to the current data. The provided vectors
should have equal length. Else, the number of added points will be the size of the smallest
vector.
If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
can set \a alreadySorted to true, to improve performance by saving a sorting run.
Alternatively, you can also access and modify the data directly via the \ref data method, which
returns a pointer to the internal data container.
*/
void QCPCurve::addData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
{
if (t.size() != keys.size() || t.size() != values.size())
qDebug() << Q_FUNC_INFO << "ts, keys and values have different sizes:" << t.size() << keys.size() << values.size();
const int n = static_cast<int>(qMin(qMin(t.size(), keys.size()), values.size()));
QVector<QCPCurveData> tempData(n);
QVector<QCPCurveData>::iterator it = tempData.begin();
const QVector<QCPCurveData>::iterator itEnd = tempData.end();
int i = 0;
while (it != itEnd)
{
it->t = t[i];
it->key = keys[i];
it->value = values[i];
++it;
++i;
}
mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
}
/*! \overload
Adds the provided points in \a keys and \a values to the current data. The provided vectors
should have equal length. Else, the number of added points will be the size of the smallest
vector.
The t parameter of each data point will be set to the integer index of the respective key/value
pair.
Alternatively, you can also access and modify the data directly via the \ref data method, which
returns a pointer to the internal data container.
*/
void QCPCurve::addData(const QVector<double> &keys, const QVector<double> &values)
{
if (keys.size() != values.size())
qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
const int n = static_cast<int>(qMin(keys.size(), values.size()));
double tStart;
if (!mDataContainer->isEmpty())
tStart = (mDataContainer->constEnd()-1)->t + 1.0;
else
tStart = 0;
QVector<QCPCurveData> tempData(n);
QVector<QCPCurveData>::iterator it = tempData.begin();
const QVector<QCPCurveData>::iterator itEnd = tempData.end();
int i = 0;
while (it != itEnd)
{
it->t = tStart + i;
it->key = keys[i];
it->value = values[i];
++it;
++i;
}
mDataContainer->add(tempData, true); // don't modify tempData beyond this to prevent copy on write
}
/*! \overload
Adds the provided data point as \a t, \a key and \a value to the current data.
Alternatively, you can also access and modify the data directly via the \ref data method, which
returns a pointer to the internal data container.
*/
void QCPCurve::addData(double t, double key, double value)
{
mDataContainer->add(QCPCurveData(t, key, value));
}
/*! \overload
Adds the provided data point as \a key and \a value to the current data.
The t parameter is generated automatically by increments of 1 for each point, starting at the
highest t of previously existing data or 0, if the curve data is empty.
Alternatively, you can also access and modify the data directly via the \ref data method, which
returns a pointer to the internal data container.
*/
void QCPCurve::addData(double key, double value)
{
if (!mDataContainer->isEmpty())
mDataContainer->add(QCPCurveData((mDataContainer->constEnd()-1)->t + 1.0, key, value));
else
mDataContainer->add(QCPCurveData(0.0, key, value));
}
/*!
Implements a selectTest specific to this plottable's point geometry.
If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
point to \a pos.
\seebaseclassmethod \ref QCPAbstractPlottable::selectTest
*/
double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
return -1;
if (!mKeyAxis || !mValueAxis)
return -1;
if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
{
QCPCurveDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
double result = pointDistance(pos, closestDataPoint);
if (details)
{
int pointIndex = int( closestDataPoint-mDataContainer->constBegin() );
details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
}
return result;
} else
return -1;
}
/* inherits documentation from base class */
QCPRange QCPCurve::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
{
return mDataContainer->keyRange(foundRange, inSignDomain);
}
/* inherits documentation from base class */
QCPRange QCPCurve::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
{
return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
}
/* inherits documentation from base class */
void QCPCurve::draw(QCPPainter *painter)
{
if (mDataContainer->isEmpty()) return;
// allocate line vector:
QVector<QPointF> lines, scatters;
// loop over and draw segments of unselected/selected data:
QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
getDataSegments(selectedSegments, unselectedSegments);
allSegments << unselectedSegments << selectedSegments;
for (int i=0; i<allSegments.size(); ++i)
{
bool isSelectedSegment = i >= unselectedSegments.size();
// fill with curve data:
QPen finalCurvePen = mPen; // determine the final pen already here, because the line optimization depends on its stroke width
if (isSelectedSegment && mSelectionDecorator)
finalCurvePen = mSelectionDecorator->pen();
QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getCurveLines takes care)
getCurveLines(&lines, lineDataRange, finalCurvePen.widthF());
// check data validity if flag set:
#ifdef QCUSTOMPLOT_CHECK_DATA
for (QCPCurveDataContainer::const_iterator it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
{
if (QCP::isInvalidData(it->t) ||
QCP::isInvalidData(it->key, it->value))
qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
}
#endif
// draw curve fill:
applyFillAntialiasingHint(painter);
if (isSelectedSegment && mSelectionDecorator)
mSelectionDecorator->applyBrush(painter);
else
painter->setBrush(mBrush);
painter->setPen(Qt::NoPen);
if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
painter->drawPolygon(QPolygonF(lines));
// draw curve line:
if (mLineStyle != lsNone)
{
painter->setPen(finalCurvePen);
painter->setBrush(Qt::NoBrush);
drawCurveLine(painter, lines);
}
// draw scatters:
QCPScatterStyle finalScatterStyle = mScatterStyle;
if (isSelectedSegment && mSelectionDecorator)
finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
if (!finalScatterStyle.isNone())
{
getScatters(&scatters, allSegments.at(i), finalScatterStyle.size());
drawScatterPlot(painter, scatters, finalScatterStyle);
}
}
// draw other selection decoration that isn't just line/scatter pens and brushes:
if (mSelectionDecorator)
mSelectionDecorator->drawDecoration(painter, selection());
}
/* inherits documentation from base class */
void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
// draw fill:
if (mBrush.style() != Qt::NoBrush)
{
applyFillAntialiasingHint(painter);
painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
}
// draw line vertically centered:
if (mLineStyle != lsNone)
{
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
}
// draw scatter symbol:
if (!mScatterStyle.isNone())
{
applyScattersAntialiasingHint(painter);
// scale scatter pixmap if it's too large to fit in legend icon rect:
if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
{
QCPScatterStyle scaledStyle(mScatterStyle);
scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
scaledStyle.applyTo(painter, mPen);
scaledStyle.drawShape(painter, QRectF(rect).center());
} else
{
mScatterStyle.applyTo(painter, mPen);
mScatterStyle.drawShape(painter, QRectF(rect).center());
}
}
}
/*! \internal
Draws lines between the points in \a lines, given in pixel coordinates.
\see drawScatterPlot, getCurveLines
*/
void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector<QPointF> &lines) const
{
if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
{
applyDefaultAntialiasingHint(painter);
drawPolyline(painter, lines);
}
}
/*! \internal
Draws scatter symbols at every point passed in \a points, given in pixel coordinates. The
scatters will be drawn with \a painter and have the appearance as specified in \a style.
\see drawCurveLine, getCurveLines
*/
void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &points, const QCPScatterStyle &style) const
{
// draw scatter point symbols:
applyScattersAntialiasingHint(painter);
style.applyTo(painter, mPen);
foreach (const QPointF &point, points)
if (!qIsNaN(point.x()) && !qIsNaN(point.y()))
style.drawShape(painter, point);
}
/*! \internal
Called by \ref draw to generate points in pixel coordinates which represent the line of the
curve.
Line segments that aren't visible in the current axis rect are handled in an optimized way. They
are projected onto a rectangle slightly larger than the visible axis rect and simplified
regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside
the visible axis rect by generating new temporary points on the outer rect if necessary.
\a lines will be filled with points in pixel coordinates, that can be drawn with \ref
drawCurveLine.
\a dataRange specifies the beginning and ending data indices that will be taken into account for
conversion. In this function, the specified range may exceed the total data bounds without harm:
a correspondingly trimmed data range will be used. This takes the burden off the user of this
function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
getDataSegments.
\a penWidth specifies the pen width that will be used to later draw the lines generated by this
function. This is needed here to calculate an accordingly wider margin around the axis rect when
performing the line optimization.
Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref
getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints.
\see drawCurveLine, drawScatterPlot
*/
void QCPCurve::getCurveLines(QVector<QPointF> *lines, const QCPDataRange &dataRange, double penWidth) const
{
if (!lines) return;
lines->clear();
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
// add margins to rect to compensate for stroke width
const double strokeMargin = qMax(qreal(1.0), qreal(penWidth*0.75)); // stroke radius + 50% safety
const double keyMin = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*keyAxis->pixelOrientation());
const double keyMax = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*keyAxis->pixelOrientation());
const double valueMin = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)-strokeMargin*valueAxis->pixelOrientation());
const double valueMax = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)+strokeMargin*valueAxis->pixelOrientation());
QCPCurveDataContainer::const_iterator itBegin = mDataContainer->constBegin();
QCPCurveDataContainer::const_iterator itEnd = mDataContainer->constEnd();
mDataContainer->limitIteratorsToDataRange(itBegin, itEnd, dataRange);
if (itBegin == itEnd)
return;
QCPCurveDataContainer::const_iterator it = itBegin;
QCPCurveDataContainer::const_iterator prevIt = itEnd-1;
int prevRegion = getRegion(prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin);
QVector<QPointF> trailingPoints; // points that must be applied after all other points (are generated only when handling first point to get virtual segment between last and first point right)
while (it != itEnd)
{
const int currentRegion = getRegion(it->key, it->value, keyMin, valueMax, keyMax, valueMin);
if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R
{
if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal
{
QPointF crossA, crossB;
if (prevRegion == 5) // we're coming from R, so add this point optimized
{
lines->append(getOptimizedPoint(currentRegion, it->key, it->value, prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin));
// in the situations 5->1/7/9/3 the segment may leave R and directly cross through two outer regions. In these cases we need to add an additional corner point
*lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
} else if (mayTraverse(prevRegion, currentRegion) &&
getTraverse(prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin, crossA, crossB))
{
// add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point:
QVector<QPointF> beforeTraverseCornerPoints, afterTraverseCornerPoints;
getTraverseCornerPoints(prevRegion, currentRegion, keyMin, valueMax, keyMax, valueMin, beforeTraverseCornerPoints, afterTraverseCornerPoints);
if (it != itBegin)
{
*lines << beforeTraverseCornerPoints;
lines->append(crossA);
lines->append(crossB);
*lines << afterTraverseCornerPoints;
} else
{
lines->append(crossB);
*lines << afterTraverseCornerPoints;
trailingPoints << beforeTraverseCornerPoints << crossA ;
}
} else // doesn't cross R, line is just moving around in outside regions, so only need to add optimized point(s) at the boundary corner(s)
{
*lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
}
} else // segment does end in R, so we add previous point optimized and this point at original position
{
if (it == itBegin) // it is first point in curve and prevIt is last one. So save optimized point for adding it to the lineData in the end
trailingPoints << getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
else
lines->append(getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin));
lines->append(coordsToPixels(it->key, it->value));
}
} else // region didn't change
{
if (currentRegion == 5) // still in R, keep adding original points
{
lines->append(coordsToPixels(it->key, it->value));
} else // still outside R, no need to add anything
{
// see how this is not doing anything? That's the main optimization...
}
}
prevIt = it;
prevRegion = currentRegion;
++it;
}
*lines << trailingPoints;
}
/*! \internal
Called by \ref draw to generate points in pixel coordinates which represent the scatters of the
curve. If a scatter skip is configured (\ref setScatterSkip), the returned points are accordingly
sparser.
Scatters that aren't visible in the current axis rect are optimized away.
\a scatters will be filled with points in pixel coordinates, that can be drawn with \ref
drawScatterPlot.
\a dataRange specifies the beginning and ending data indices that will be taken into account for
conversion.
\a scatterWidth specifies the scatter width that will be used to later draw the scatters at pixel
coordinates generated by this function. This is needed here to calculate an accordingly wider
margin around the axis rect when performing the data point reduction.
\see draw, drawScatterPlot
*/
void QCPCurve::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange, double scatterWidth) const
{
if (!scatters) return;
scatters->clear();
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
mDataContainer->limitIteratorsToDataRange(begin, end, dataRange);
if (begin == end)
return;
const int scatterModulo = mScatterSkip+1;
const bool doScatterSkip = mScatterSkip > 0;
int endIndex = int( end-mDataContainer->constBegin() );
QCPRange keyRange = keyAxis->range();
QCPRange valueRange = valueAxis->range();
// extend range to include width of scatter symbols:
keyRange.lower = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.lower)-scatterWidth*keyAxis->pixelOrientation());
keyRange.upper = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.upper)+scatterWidth*keyAxis->pixelOrientation());
valueRange.lower = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.lower)-scatterWidth*valueAxis->pixelOrientation());
valueRange.upper = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.upper)+scatterWidth*valueAxis->pixelOrientation());
QCPCurveDataContainer::const_iterator it = begin;
int itIndex = int( begin-mDataContainer->constBegin() );
while (doScatterSkip && it != end && itIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
{
++itIndex;
++it;
}
if (keyAxis->orientation() == Qt::Vertical)
{
while (it != end)
{
if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
scatters->append(QPointF(valueAxis->coordToPixel(it->value), keyAxis->coordToPixel(it->key)));
// advance iterator to next (non-skipped) data point:
if (!doScatterSkip)
++it;
else
{
itIndex += scatterModulo;
if (itIndex < endIndex) // make sure we didn't jump over end
it += scatterModulo;
else
{
it = end;
itIndex = endIndex;
}
}
}
} else
{
while (it != end)
{
if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
scatters->append(QPointF(keyAxis->coordToPixel(it->key), valueAxis->coordToPixel(it->value)));
// advance iterator to next (non-skipped) data point:
if (!doScatterSkip)
++it;
else
{
itIndex += scatterModulo;
if (itIndex < endIndex) // make sure we didn't jump over end
it += scatterModulo;
else
{
it = end;
itIndex = endIndex;
}
}
}
}
}
/*! \internal
This function is part of the curve optimization algorithm of \ref getCurveLines.
It returns the region of the given point (\a key, \a value) with respect to a rectangle defined
by \a keyMin, \a keyMax, \a valueMin, and \a valueMax.
The regions are enumerated from top to bottom (\a valueMin to \a valueMax) and left to right (\a
keyMin to \a keyMax):
<table style="width:10em; text-align:center">
<tr><td>1</td><td>4</td><td>7</td></tr>
<tr><td>2</td><td style="border:1px solid black">5</td><td>8</td></tr>
<tr><td>3</td><td>6</td><td>9</td></tr>
</table>
With the rectangle being region 5, and the outer regions extending infinitely outwards. In the
curve optimization algorithm, region 5 is considered to be the visible portion of the plot.
*/
int QCPCurve::getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
{
if (key < keyMin) // region 123
{
if (value > valueMax)
return 1;
else if (value < valueMin)
return 3;
else
return 2;
} else if (key > keyMax) // region 789
{
if (value > valueMax)
return 7;
else if (value < valueMin)
return 9;
else
return 8;
} else // region 456
{
if (value > valueMax)
return 4;
else if (value < valueMin)
return 6;
else
return 5;
}
}
/*! \internal
This function is part of the curve optimization algorithm of \ref getCurveLines.
This method is used in case the current segment passes from inside the visible rect (region 5,
see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by
the line connecting (\a key, \a value) with (\a otherKey, \a otherValue).
It returns the intersection point of the segment with the border of region 5.
For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or
whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or
leaving it. It is important though that \a otherRegion correctly identifies the other region not
equal to 5.
*/
QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
{
// The intersection point interpolation here is done in pixel coordinates, so we don't need to
// differentiate between different axis scale types. Note that the nomenclature
// top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be
// different in pixel coordinates (horz/vert key axes, reversed ranges)
const double keyMinPx = mKeyAxis->coordToPixel(keyMin);
const double keyMaxPx = mKeyAxis->coordToPixel(keyMax);
const double valueMinPx = mValueAxis->coordToPixel(valueMin);
const double valueMaxPx = mValueAxis->coordToPixel(valueMax);
const double otherValuePx = mValueAxis->coordToPixel(otherValue);
const double valuePx = mValueAxis->coordToPixel(value);
const double otherKeyPx = mKeyAxis->coordToPixel(otherKey);
const double keyPx = mKeyAxis->coordToPixel(key);
double intersectKeyPx = keyMinPx; // initial key just a fail-safe
double intersectValuePx = valueMinPx; // initial value just a fail-safe
switch (otherRegion)
{
case 1: // top and left edge
{
intersectValuePx = valueMaxPx;
intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether top edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed)
{
intersectKeyPx = keyMinPx;
intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
}
break;
}
case 2: // left edge
{
intersectKeyPx = keyMinPx;
intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
break;
}
case 3: // bottom and left edge
{
intersectValuePx = valueMinPx;
intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether bottom edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed)
{
intersectKeyPx = keyMinPx;
intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
}
break;
}
case 4: // top edge
{
intersectValuePx = valueMaxPx;
intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
break;
}
case 5:
{
break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table
}
case 6: // bottom edge
{
intersectValuePx = valueMinPx;
intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
break;
}
case 7: // top and right edge
{
intersectValuePx = valueMaxPx;
intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether top edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed)
{
intersectKeyPx = keyMaxPx;
intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
}
break;
}
case 8: // right edge
{
intersectKeyPx = keyMaxPx;
intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
break;
}
case 9: // bottom and right edge
{
intersectValuePx = valueMinPx;
intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether bottom edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed)
{
intersectKeyPx = keyMaxPx;
intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
}
break;
}
}
if (mKeyAxis->orientation() == Qt::Horizontal)
return {intersectKeyPx, intersectValuePx};
else
return {intersectValuePx, intersectKeyPx};
}
/*! \internal
This function is part of the curve optimization algorithm of \ref getCurveLines.
In situations where a single segment skips over multiple regions it might become necessary to add
extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment
doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts.
This method provides these points that must be added, assuming the original segment doesn't
start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by
\ref getTraverseCornerPoints.)
For example, consider a segment which directly goes from region 4 to 2 but originally is far out
to the top left such that it doesn't cross region 5. Naively optimizing these points by
projecting them on the top and left borders of region 5 will create a segment that surely crosses
5, creating a visual artifact in the plot. This method prevents this by providing extra points at
the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without
traversing 5.
*/
QVector<QPointF> QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
{
QVector<QPointF> result;
switch (prevRegion)
{
case 1:
{
switch (currentRegion)
{
case 2: { result << coordsToPixels(keyMin, valueMax); break; }
case 4: { result << coordsToPixels(keyMin, valueMax); break; }
case 3: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); break; }
case 7: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); break; }
case 6: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
case 8: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
case 9: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
{ result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
else
{ result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
break;
}
}
break;
}
case 2:
{
switch (currentRegion)
{
case 1: { result << coordsToPixels(keyMin, valueMax); break; }
case 3: { result << coordsToPixels(keyMin, valueMin); break; }
case 4: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
case 6: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
case 7: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
case 9: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
}
break;
}
case 3:
{
switch (currentRegion)
{
case 2: { result << coordsToPixels(keyMin, valueMin); break; }
case 6: { result << coordsToPixels(keyMin, valueMin); break; }
case 1: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); break; }
case 9: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); break; }
case 4: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
case 8: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
case 7: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
{ result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
else
{ result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
break;
}
}
break;
}
case 4:
{
switch (currentRegion)
{
case 1: { result << coordsToPixels(keyMin, valueMax); break; }
case 7: { result << coordsToPixels(keyMax, valueMax); break; }
case 2: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
case 8: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
case 3: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
case 9: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
}
break;
}
case 5:
{
switch (currentRegion)
{
case 1: { result << coordsToPixels(keyMin, valueMax); break; }
case 7: { result << coordsToPixels(keyMax, valueMax); break; }
case 9: { result << coordsToPixels(keyMax, valueMin); break; }
case 3: { result << coordsToPixels(keyMin, valueMin); break; }
}
break;
}
case 6:
{
switch (currentRegion)
{
case 3: { result << coordsToPixels(keyMin, valueMin); break; }
case 9: { result << coordsToPixels(keyMax, valueMin); break; }
case 2: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
case 8: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
case 1: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
case 7: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
}
break;
}
case 7:
{
switch (currentRegion)
{
case 4: { result << coordsToPixels(keyMax, valueMax); break; }
case 8: { result << coordsToPixels(keyMax, valueMax); break; }
case 1: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); break; }
case 9: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); break; }
case 2: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
case 6: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
case 3: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
{ result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
else
{ result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
break;
}
}
break;
}
case 8:
{
switch (currentRegion)
{
case 7: { result << coordsToPixels(keyMax, valueMax); break; }
case 9: { result << coordsToPixels(keyMax, valueMin); break; }
case 4: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
case 6: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
case 1: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
case 3: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
}
break;
}
case 9:
{
switch (currentRegion)
{
case 6: { result << coordsToPixels(keyMax, valueMin); break; }
case 8: { result << coordsToPixels(keyMax, valueMin); break; }
case 3: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); break; }
case 7: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); break; }
case 2: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
case 4: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
case 1: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
{ result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
else
{ result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
break;
}
}
break;
}
}
return result;
}
/*! \internal
This function is part of the curve optimization algorithm of \ref getCurveLines.
This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref
getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion
nor \a currentRegion is 5 itself.
If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the
segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref
getTraverse).
*/
bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const
{
switch (prevRegion)
{
case 1:
{
switch (currentRegion)
{
case 4:
case 7:
case 2:
case 3: return false;
default: return true;
}
}
case 2:
{
switch (currentRegion)
{
case 1:
case 3: return false;
default: return true;
}
}
case 3:
{
switch (currentRegion)
{
case 1:
case 2:
case 6:
case 9: return false;
default: return true;
}
}
case 4:
{
switch (currentRegion)
{
case 1:
case 7: return false;
default: return true;
}
}
case 5: return false; // should never occur
case 6:
{
switch (currentRegion)
{
case 3:
case 9: return false;
default: return true;
}
}
case 7:
{
switch (currentRegion)
{
case 1:
case 4:
case 8:
case 9: return false;
default: return true;
}
}
case 8:
{
switch (currentRegion)
{
case 7:
case 9: return false;
default: return true;
}
}
case 9:
{
switch (currentRegion)
{
case 3:
case 6:
case 8:
case 7: return false;
default: return true;
}
}
default: return true;
}
}
/*! \internal
This function is part of the curve optimization algorithm of \ref getCurveLines.
This method assumes that the \ref mayTraverse test has returned true, so there is a chance the
segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible
region 5.
The return value of this method indicates whether the segment actually traverses region 5 or not.
If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and
exit points of region 5. They will become the optimized points for that segment.
*/
bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const
{
// The intersection point interpolation here is done in pixel coordinates, so we don't need to
// differentiate between different axis scale types. Note that the nomenclature
// top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be
// different in pixel coordinates (horz/vert key axes, reversed ranges)
QList<QPointF> intersections;
const double valueMinPx = mValueAxis->coordToPixel(valueMin);
const double valueMaxPx = mValueAxis->coordToPixel(valueMax);
const double keyMinPx = mKeyAxis->coordToPixel(keyMin);
const double keyMaxPx = mKeyAxis->coordToPixel(keyMax);
const double keyPx = mKeyAxis->coordToPixel(key);
const double valuePx = mValueAxis->coordToPixel(value);
const double prevKeyPx = mKeyAxis->coordToPixel(prevKey);
const double prevValuePx = mValueAxis->coordToPixel(prevValue);
if (qFuzzyIsNull(keyPx-prevKeyPx)) // line is parallel to value axis
{
// due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here
intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMinPx) : QPointF(valueMinPx, keyPx)); // direction will be taken care of at end of method
intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMaxPx) : QPointF(valueMaxPx, keyPx));
} else if (qFuzzyIsNull(valuePx-prevValuePx)) // line is parallel to key axis
{
// due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here
intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, valuePx) : QPointF(valuePx, keyMinPx)); // direction will be taken care of at end of method
intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, valuePx) : QPointF(valuePx, keyMaxPx));
} else // line is skewed
{
double gamma;
double keyPerValuePx = (keyPx-prevKeyPx)/(valuePx-prevValuePx);
// check top of rect:
gamma = prevKeyPx + (valueMaxPx-prevValuePx)*keyPerValuePx;
if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed
intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMaxPx) : QPointF(valueMaxPx, gamma));
// check bottom of rect:
gamma = prevKeyPx + (valueMinPx-prevValuePx)*keyPerValuePx;
if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed
intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMinPx) : QPointF(valueMinPx, gamma));
const double valuePerKeyPx = 1.0/keyPerValuePx;
// check left of rect:
gamma = prevValuePx + (keyMinPx-prevKeyPx)*valuePerKeyPx;
if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed
intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, gamma) : QPointF(gamma, keyMinPx));
// check right of rect:
gamma = prevValuePx + (keyMaxPx-prevKeyPx)*valuePerKeyPx;
if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed
intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, gamma) : QPointF(gamma, keyMaxPx));
}
// handle cases where found points isn't exactly 2:
if (intersections.size() > 2)
{
// line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between:
double distSqrMax = 0;
QPointF pv1, pv2;
for (int i=0; i<intersections.size()-1; ++i)
{
for (int k=i+1; k<intersections.size(); ++k)
{
QPointF distPoint = intersections.at(i)-intersections.at(k);
double distSqr = distPoint.x()*distPoint.x()+distPoint.y()+distPoint.y();
if (distSqr > distSqrMax)
{
pv1 = intersections.at(i);
pv2 = intersections.at(k);
distSqrMax = distSqr;
}
}
}
intersections = QList<QPointF>() << pv1 << pv2;
} else if (intersections.size() != 2)
{
// one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment
return false;
}
// possibly re-sort points so optimized point segment has same direction as original segment:
double xDelta = keyPx-prevKeyPx;
double yDelta = valuePx-prevValuePx;
if (mKeyAxis->orientation() != Qt::Horizontal)
qSwap(xDelta, yDelta);
if (xDelta*(intersections.at(1).x()-intersections.at(0).x()) + yDelta*(intersections.at(1).y()-intersections.at(0).y()) < 0) // scalar product of both segments < 0 -> opposite direction
intersections.move(0, 1);
crossA = intersections.at(0);
crossB = intersections.at(1);
return true;
}
/*! \internal
This function is part of the curve optimization algorithm of \ref getCurveLines.
This method assumes that the \ref getTraverse test has returned true, so the segment definitely
traverses the visible region 5 when going from \a prevRegion to \a currentRegion.
In certain situations it is not sufficient to merely generate the entry and exit points of the
segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in
addition to traversing region 5, skips another region outside of region 5, which makes it
necessary to add an optimized corner point there (very similar to the job \ref
getOptimizedCornerPoints does for segments that are completely in outside regions and don't
traverse 5).
As an example, consider a segment going from region 1 to region 6, traversing the lower left
corner of region 5. In this configuration, the segment additionally crosses the border between
region 1 and 2 before entering region 5. This makes it necessary to add an additional point in
the top left corner, before adding the optimized traverse points. So in this case, the output
parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be
empty.
In some cases, such as when going from region 1 to 9, it may even be necessary to add additional
corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse
return the respective corner points.
*/
void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double keyMin, double valueMax, double keyMax, double valueMin, QVector<QPointF> &beforeTraverse, QVector<QPointF> &afterTraverse) const
{
switch (prevRegion)
{
case 1:
{
switch (currentRegion)
{
case 6: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
case 9: { beforeTraverse << coordsToPixels(keyMin, valueMax); afterTraverse << coordsToPixels(keyMax, valueMin); break; }
case 8: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
}
break;
}
case 2:
{
switch (currentRegion)
{
case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
}
break;
}
case 3:
{
switch (currentRegion)
{
case 4: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
case 7: { beforeTraverse << coordsToPixels(keyMin, valueMin); afterTraverse << coordsToPixels(keyMax, valueMax); break; }
case 8: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
}
break;
}
case 4:
{
switch (currentRegion)
{
case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
}
break;
}
case 5: { break; } // shouldn't happen because this method only handles full traverses
case 6:
{
switch (currentRegion)
{
case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
}
break;
}
case 7:
{
switch (currentRegion)
{
case 2: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
case 3: { beforeTraverse << coordsToPixels(keyMax, valueMax); afterTraverse << coordsToPixels(keyMin, valueMin); break; }
case 6: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
}
break;
}
case 8:
{
switch (currentRegion)
{
case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
}
break;
}
case 9:
{
switch (currentRegion)
{
case 2: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
case 1: { beforeTraverse << coordsToPixels(keyMax, valueMin); afterTraverse << coordsToPixels(keyMin, valueMax); break; }
case 4: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
}
break;
}
}
}
/*! \internal
Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a
pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in
\ref selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that
if the curve has a line representation, the returned distance may be smaller than the distance to
the \a closestData point, since the distance to the curve line is also taken into account.
If either the curve has no data or if the line style is \ref lsNone and the scatter style's shape
is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the curve), returns
-1.0.
*/
double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer::const_iterator &closestData) const
{
closestData = mDataContainer->constEnd();
if (mDataContainer->isEmpty())
return -1.0;
if (mLineStyle == lsNone && mScatterStyle.isNone())
return -1.0;
if (mDataContainer->size() == 1)
{
QPointF dataPoint = coordsToPixels(mDataContainer->constBegin()->key, mDataContainer->constBegin()->value);
closestData = mDataContainer->constBegin();
return QCPVector2D(dataPoint-pixelPoint).length();
}
// calculate minimum distances to curve data points and find closestData iterator:
double minDistSqr = (std::numeric_limits<double>::max)();
// iterate over found data points and then choose the one with the shortest distance to pos:
QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
for (QCPCurveDataContainer::const_iterator it=begin; it!=end; ++it)
{
const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
if (currentDistSqr < minDistSqr)
{
minDistSqr = currentDistSqr;
closestData = it;
}
}
// calculate distance to line if there is one (if so, will probably be smaller than distance to closest data point):
if (mLineStyle != lsNone)
{
QVector<QPointF> lines;
getCurveLines(&lines, QCPDataRange(0, dataCount()), mParentPlot->selectionTolerance()*1.2); // optimized lines outside axis rect shouldn't respond to clicks at the edge, so use 1.2*tolerance as pen width
for (int i=0; i<lines.size()-1; ++i)
{
double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(lines.at(i), lines.at(i+1));
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
}
return qSqrt(minDistSqr);
}
/* end of 'src/plottables/plottable-curve.cpp' */
/* including file 'src/plottables/plottable-bars.cpp' */
/* modified 2022-11-06T12:45:56, size 43907 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPBarsGroup
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPBarsGroup
\brief Groups multiple QCPBars together so they appear side by side
\image html QCPBarsGroup.png
When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable
to have them appearing next to each other at each key. This is what adding the respective QCPBars
plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each
other, see \ref QCPBars::moveAbove.)
\section qcpbarsgroup-usage Usage
To add a QCPBars plottable to the group, create a new group and then add the respective bars
intances:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation
Alternatively to appending to the group like shown above, you can also set the group on the
QCPBars plottable via \ref QCPBars::setBarsGroup.
The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The
bars in this group appear in the plot in the order they were appended. To insert a bars plottable
at a certain index position, or to reposition a bars plottable which is already in the group, use
\ref insert.
To remove specific bars from the group, use either \ref remove or call \ref
QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable.
To clear the entire group, call \ref clear, or simply delete the group.
\section qcpbarsgroup-example Example
The image above is generated with the following code:
\snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example
*/
/* start of documentation of inline functions */
/*! \fn QList<QCPBars*> QCPBarsGroup::bars() const
Returns all bars currently in this group.
\see bars(int index)
*/
/*! \fn int QCPBarsGroup::size() const
Returns the number of QCPBars plottables that are part of this group.
*/
/*! \fn bool QCPBarsGroup::isEmpty() const
Returns whether this bars group is empty.
\see size
*/
/*! \fn bool QCPBarsGroup::contains(QCPBars *bars)
Returns whether the specified \a bars plottable is part of this group.
*/
/* end of documentation of inline functions */
/*!
Constructs a new bars group for the specified QCustomPlot instance.
*/
QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) :
QObject(parentPlot),
mParentPlot(parentPlot),
mSpacingType(stAbsolute),
mSpacing(4)
{
}
QCPBarsGroup::~QCPBarsGroup()
{
clear();
}
/*!
Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType.
The actual spacing can then be specified with \ref setSpacing.
\see setSpacing
*/
void QCPBarsGroup::setSpacingType(SpacingType spacingType)
{
mSpacingType = spacingType;
}
/*!
Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is
defined by the current \ref SpacingType, which can be set with \ref setSpacingType.
\see setSpacingType
*/
void QCPBarsGroup::setSpacing(double spacing)
{
mSpacing = spacing;
}
/*!
Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars
exists, returns \c nullptr.
\see bars(), size
*/
QCPBars *QCPBarsGroup::bars(int index) const
{
if (index >= 0 && index < mBars.size())
{
return mBars.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return nullptr;
}
}
/*!
Removes all QCPBars plottables from this group.
\see isEmpty
*/
void QCPBarsGroup::clear()
{
const QList<QCPBars*> oldBars = mBars;
foreach (QCPBars *bars, oldBars)
bars->setBarsGroup(nullptr); // removes itself from mBars via removeBars
}
/*!
Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref
QCPBars::setBarsGroup on the \a bars instance.
\see insert, remove
*/
void QCPBarsGroup::append(QCPBars *bars)
{
if (!bars)
{
qDebug() << Q_FUNC_INFO << "bars is 0";
return;
}
if (!mBars.contains(bars))
bars->setBarsGroup(this);
else
qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast<quintptr>(bars);
}
/*!
Inserts the specified \a bars plottable into this group at the specified index position \a i.
This gives you full control over the ordering of the bars.
\a bars may already be part of this group. In that case, \a bars is just moved to the new index
position.
\see append, remove
*/
void QCPBarsGroup::insert(int i, QCPBars *bars)
{
if (!bars)
{
qDebug() << Q_FUNC_INFO << "bars is 0";
return;
}
// first append to bars list normally:
if (!mBars.contains(bars))
bars->setBarsGroup(this);
// then move to according position:
mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1));
}
/*!
Removes the specified \a bars plottable from this group.
\see contains, clear
*/
void QCPBarsGroup::remove(QCPBars *bars)
{
if (!bars)
{
qDebug() << Q_FUNC_INFO << "bars is 0";
return;
}
if (mBars.contains(bars))
bars->setBarsGroup(nullptr);
else
qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast<quintptr>(bars);
}
/*! \internal
Adds the specified \a bars to the internal mBars list of bars. This method does not change the
barsGroup property on \a bars.
\see unregisterBars
*/
void QCPBarsGroup::registerBars(QCPBars *bars)
{
if (!mBars.contains(bars))
mBars.append(bars);
}
/*! \internal
Removes the specified \a bars from the internal mBars list of bars. This method does not change
the barsGroup property on \a bars.
\see registerBars
*/
void QCPBarsGroup::unregisterBars(QCPBars *bars)
{
mBars.removeOne(bars);
}
/*! \internal
Returns the pixel offset in the key dimension the specified \a bars plottable should have at the
given key coordinate \a keyCoord. The offset is relative to the pixel position of the key
coordinate \a keyCoord.
*/
double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord)
{
// find list of all base bars in case some mBars are stacked:
QList<const QCPBars*> baseBars;
foreach (const QCPBars *b, mBars)
{
while (b->barBelow())
b = b->barBelow();
if (!baseBars.contains(b))
baseBars.append(b);
}
// find base bar this "bars" is stacked on:
const QCPBars *thisBase = bars;
while (thisBase->barBelow())
thisBase = thisBase->barBelow();
// determine key pixel offset of this base bars considering all other base bars in this barsgroup:
double result = 0;
int index = static_cast<int>(baseBars.indexOf(thisBase));
if (index >= 0)
{
if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose)
{
return result;
} else
{
double lowerPixelWidth, upperPixelWidth;
int startIndex;
int dir = (index <= (baseBars.size()-1)/2) ? -1 : 1; // if bar is to lower keys of center, dir is negative
if (baseBars.size() % 2 == 0) // even number of bars
{
startIndex = static_cast<int>(baseBars.size())/2 + (dir < 0 ? -1 : 0);
result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing
} else // uneven number of bars
{
startIndex = (static_cast<int>(baseBars.size())-1)/2+dir;
baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar
result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing
}
for (int i = startIndex; i != index; i += dir) // add widths and spacings of bars in between center and our bars
{
baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
result += qAbs(upperPixelWidth-lowerPixelWidth);
result += getPixelSpacing(baseBars.at(i), keyCoord);
}
// finally half of our bars width:
baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5;
// correct sign of result depending on orientation and direction of key axis:
result *= dir*thisBase->keyAxis()->pixelOrientation();
}
}
return result;
}
/*! \internal
Returns the spacing in pixels which is between this \a bars and the following one, both at the
key coordinate \a keyCoord.
\note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only
needed to get access to the key axis transformation and axis rect for the modes \ref
stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in
\ref stPlotCoords on a logarithmic axis.
*/
double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord)
{
switch (mSpacingType)
{
case stAbsolute:
{
return mSpacing;
}
case stAxisRectRatio:
{
if (bars->keyAxis()->orientation() == Qt::Horizontal)
return bars->keyAxis()->axisRect()->width()*mSpacing;
else
return bars->keyAxis()->axisRect()->height()*mSpacing;
}
case stPlotCoords:
{
double keyPixel = bars->keyAxis()->coordToPixel(keyCoord);
return qAbs(bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel);
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPBarsData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPBarsData
\brief Holds the data of one single data point (one bar) for QCPBars.
The stored data is:
\li \a key: coordinate on the key axis of this bar (this is the \a mainKey and the \a sortKey)
\li \a value: height coordinate on the value axis of this bar (this is the \a mainValue)
The container for storing multiple data points is \ref QCPBarsDataContainer. It is a typedef for
\ref QCPDataContainer with \ref QCPBarsData as the DataType template parameter. See the
documentation there for an explanation regarding the data type's generic methods.
\see QCPBarsDataContainer
*/
/* start documentation of inline functions */
/*! \fn double QCPBarsData::sortKey() const
Returns the \a key member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn static QCPBarsData QCPBarsData::fromSortKey(double sortKey)
Returns a data point with the specified \a sortKey. All other members are set to zero.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn static static bool QCPBarsData::sortKeyIsMainKey()
Since the member \a key is both the data point key coordinate and the data ordering parameter,
this method returns true.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn double QCPBarsData::mainKey() const
Returns the \a key member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn double QCPBarsData::mainValue() const
Returns the \a value member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn QCPRange QCPBarsData::valueRange() const
Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/* end documentation of inline functions */
/*!
Constructs a bar data point with key and value set to zero.
*/
QCPBarsData::QCPBarsData() :
key(0),
value(0)
{
}
/*!
Constructs a bar data point with the specified \a key and \a value.
*/
QCPBarsData::QCPBarsData(double key, double value) :
key(key),
value(value)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPBars
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPBars
\brief A plottable representing a bar chart in a plot.
\image html QCPBars.png
To plot data, assign it with the \ref setData or \ref addData functions.
\section qcpbars-appearance Changing the appearance
The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush).
The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth.
Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other
(see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear
stacked.
If you would like to group multiple QCPBars plottables together so they appear side by side as
shown below, use QCPBarsGroup.
\image html QCPBarsGroup.png
\section qcpbars-usage Usage
Like all data representing objects in QCustomPlot, the QCPBars is a plottable
(QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
(QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
Usually, you first create an instance:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1
which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
The newly created plottable can be modified, e.g.:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-2
*/
/* start of documentation of inline functions */
/*! \fn QSharedPointer<QCPBarsDataContainer> QCPBars::data() const
Returns a shared pointer to the internal data storage of type \ref QCPBarsDataContainer. You may
use it to directly manipulate the data, which may be more convenient and faster than using the
regular \ref setData or \ref addData methods.
*/
/*! \fn QCPBars *QCPBars::barBelow() const
Returns the bars plottable that is directly below this bars plottable.
If there is no such plottable, returns \c nullptr.
\see barAbove, moveBelow, moveAbove
*/
/*! \fn QCPBars *QCPBars::barAbove() const
Returns the bars plottable that is directly above this bars plottable.
If there is no such plottable, returns \c nullptr.
\see barBelow, moveBelow, moveAbove
*/
/* end of documentation of inline functions */
/*!
Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
the same orientation. If either of these restrictions is violated, a corresponding message is
printed to the debug output (qDebug), the construction is not aborted, though.
The created QCPBars is automatically registered with the QCustomPlot instance inferred from \a
keyAxis. This QCustomPlot instance takes ownership of the QCPBars, so do not delete it manually
but use QCustomPlot::removePlottable() instead.
*/
QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable1D<QCPBarsData>(keyAxis, valueAxis),
mWidth(0.75),
mWidthType(wtPlotCoords),
mBarsGroup(nullptr),
mBaseValue(0),
mStackingGap(1)
{
// modify inherited properties from abstract plottable:
mPen.setColor(Qt::blue);
mPen.setStyle(Qt::SolidLine);
mBrush.setColor(QColor(40, 50, 255, 30));
mBrush.setStyle(Qt::SolidPattern);
mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
}
QCPBars::~QCPBars()
{
setBarsGroup(nullptr);
if (mBarBelow || mBarAbove)
connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking
}
/*! \overload
Replaces the current data container with the provided \a data container.
Since a QSharedPointer is used, multiple QCPBars may share the same data container safely.
Modifying the data in the container will then affect all bars that share the container. Sharing
can be achieved by simply exchanging the data containers wrapped in shared pointers:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-1
If you do not wish to share containers, but create a copy from an existing container, rather use
the \ref QCPDataContainer<DataType>::set method on the bar's data container directly:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-2
\see addData
*/
void QCPBars::setData(QSharedPointer<QCPBarsDataContainer> data)
{
mDataContainer = data;
}
/*! \overload
Replaces the current data with the provided points in \a keys and \a values. The provided
vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
can set \a alreadySorted to true, to improve performance by saving a sorting run.
\see addData
*/
void QCPBars::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
{
mDataContainer->clear();
addData(keys, values, alreadySorted);
}
/*!
Sets the width of the bars.
How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...),
depends on the currently set width type, see \ref setWidthType and \ref WidthType.
*/
void QCPBars::setWidth(double width)
{
mWidth = width;
}
/*!
Sets how the width of the bars is defined. See the documentation of \ref WidthType for an
explanation of the possible values for \a widthType.
The default value is \ref wtPlotCoords.
\see setWidth
*/
void QCPBars::setWidthType(QCPBars::WidthType widthType)
{
mWidthType = widthType;
}
/*!
Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref
QCPBarsGroup::append.
To remove this QCPBars from any group, set \a barsGroup to \c nullptr.
*/
void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup)
{
// deregister at old group:
if (mBarsGroup)
mBarsGroup->unregisterBars(this);
mBarsGroup = barsGroup;
// register at new group:
if (mBarsGroup)
mBarsGroup->registerBars(this);
}
/*!
Sets the base value of this bars plottable.
The base value defines where on the value coordinate the bars start. How far the bars extend from
the base value is given by their individual value data. For example, if the base value is set to
1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at
3.
For stacked bars, only the base value of the bottom-most QCPBars has meaning.
The default base value is 0.
*/
void QCPBars::setBaseValue(double baseValue)
{
mBaseValue = baseValue;
}
/*!
If this bars plottable is stacked on top of another bars plottable (\ref moveAbove), this method
allows specifying a distance in \a pixels, by which the drawn bar rectangles will be separated by
the bars below it.
*/
void QCPBars::setStackingGap(double pixels)
{
mStackingGap = pixels;
}
/*! \overload
Adds the provided points in \a keys and \a values to the current data. The provided vectors
should have equal length. Else, the number of added points will be the size of the smallest
vector.
If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
can set \a alreadySorted to true, to improve performance by saving a sorting run.
Alternatively, you can also access and modify the data directly via the \ref data method, which
returns a pointer to the internal data container.
*/
void QCPBars::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
{
if (keys.size() != values.size())
qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
const int n = static_cast<int>(qMin(keys.size(), values.size()));
QVector<QCPBarsData> tempData(n);
QVector<QCPBarsData>::iterator it = tempData.begin();
const QVector<QCPBarsData>::iterator itEnd = tempData.end();
int i = 0;
while (it != itEnd)
{
it->key = keys[i];
it->value = values[i];
++it;
++i;
}
mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
}
/*! \overload
Adds the provided data point as \a key and \a value to the current data.
Alternatively, you can also access and modify the data directly via the \ref data method, which
returns a pointer to the internal data container.
*/
void QCPBars::addData(double key, double value)
{
mDataContainer->add(QCPBarsData(key, value));
}
/*!
Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear
below the bars of \a bars. The move target \a bars must use the same key and value axis as this
plottable.
Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
has a bars object below itself, this bars object is inserted between the two. If this bars object
is already between two other bars, the two other bars will be stacked on top of each other after
the operation.
To remove this bars plottable from any stacking, set \a bars to \c nullptr.
\see moveBelow, barAbove, barBelow
*/
void QCPBars::moveBelow(QCPBars *bars)
{
if (bars == this) return;
if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
{
qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
return;
}
// remove from stacking:
connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
// if new bar given, insert this bar below it:
if (bars)
{
if (bars->mBarBelow)
connectBars(bars->mBarBelow.data(), this);
connectBars(this, bars);
}
}
/*!
Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear
above the bars of \a bars. The move target \a bars must use the same key and value axis as this
plottable.
Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
has a bars object above itself, this bars object is inserted between the two. If this bars object
is already between two other bars, the two other bars will be stacked on top of each other after
the operation.
To remove this bars plottable from any stacking, set \a bars to \c nullptr.
\see moveBelow, barBelow, barAbove
*/
void QCPBars::moveAbove(QCPBars *bars)
{
if (bars == this) return;
if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
{
qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
return;
}
// remove from stacking:
connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
// if new bar given, insert this bar above it:
if (bars)
{
if (bars->mBarAbove)
connectBars(this, bars->mBarAbove.data());
connectBars(bars, this);
}
}
/*!
\copydoc QCPPlottableInterface1D::selectTestRect
*/
QCPDataSelection QCPBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
{
QCPDataSelection result;
if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
return result;
if (!mKeyAxis || !mValueAxis)
return result;
QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
getVisibleDataBounds(visibleBegin, visibleEnd);
for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
{
if (rect.intersects(getBarRect(it->key, it->value)))
result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
}
result.simplify();
return result;
}
/*!
Implements a selectTest specific to this plottable's point geometry.
If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
point to \a pos.
\seebaseclassmethod \ref QCPAbstractPlottable::selectTest
*/
double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
return -1;
if (!mKeyAxis || !mValueAxis)
return -1;
if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
{
// get visible data range:
QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
getVisibleDataBounds(visibleBegin, visibleEnd);
for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
{
if (getBarRect(it->key, it->value).contains(pos))
{
if (details)
{
int pointIndex = int(it-mDataContainer->constBegin());
details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
}
return mParentPlot->selectionTolerance()*0.99;
}
}
}
return -1;
}
/* inherits documentation from base class */
QCPRange QCPBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
{
/* Note: If this QCPBars uses absolute pixels as width (or is in a QCPBarsGroup with spacing in
absolute pixels), using this method to adapt the key axis range to fit the bars into the
currently visible axis range will not work perfectly. Because in the moment the axis range is
changed to the new range, the fixed pixel widths/spacings will represent different coordinate
spans than before, which in turn would require a different key range to perfectly fit, and so on.
The only solution would be to iteratively approach the perfect fitting axis range, but the
mismatch isn't large enough in most applications, to warrant this here. If a user does need a
better fit, he should call the corresponding axis rescale multiple times in a row.
*/
QCPRange range;
range = mDataContainer->keyRange(foundRange, inSignDomain);
// determine exact range of bars by including bar width and barsgroup offset:
if (foundRange && mKeyAxis)
{
double lowerPixelWidth, upperPixelWidth, keyPixel;
// lower range bound:
getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth);
keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth;
if (mBarsGroup)
keyPixel += mBarsGroup->keyPixelOffset(this, range.lower);
const double lowerCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
if (!qIsNaN(lowerCorrected) && qIsFinite(lowerCorrected) && range.lower > lowerCorrected)
range.lower = lowerCorrected;
// upper range bound:
getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth);
keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth;
if (mBarsGroup)
keyPixel += mBarsGroup->keyPixelOffset(this, range.upper);
const double upperCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
if (!qIsNaN(upperCorrected) && qIsFinite(upperCorrected) && range.upper < upperCorrected)
range.upper = upperCorrected;
}
return range;
}
/* inherits documentation from base class */
QCPRange QCPBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
{
// Note: can't simply use mDataContainer->valueRange here because we need to
// take into account bar base value and possible stacking of multiple bars
QCPRange range;
range.lower = mBaseValue;
range.upper = mBaseValue;
bool haveLower = true; // set to true, because baseValue should always be visible in bar charts
bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts
QCPBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
QCPBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
if (inKeyRange != QCPRange())
{
itBegin = mDataContainer->findBegin(inKeyRange.lower, false);
itEnd = mDataContainer->findEnd(inKeyRange.upper, false);
}
for (QCPBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
{
const double current = it->value + getStackedBaseValue(it->key, it->value >= 0);
if (qIsNaN(current)) continue;
if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
{
if (current < range.lower || !haveLower)
{
range.lower = current;
haveLower = true;
}
if (current > range.upper || !haveUpper)
{
range.upper = current;
haveUpper = true;
}
}
}
foundRange = true; // return true because bar charts always have the 0-line visible
return range;
}
/* inherits documentation from base class */
QPointF QCPBars::dataPixelPosition(int index) const
{
if (index >= 0 && index < mDataContainer->size())
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
const QCPDataContainer<QCPBarsData>::const_iterator it = mDataContainer->constBegin()+index;
const double valuePixel = valueAxis->coordToPixel(getStackedBaseValue(it->key, it->value >= 0) + it->value);
const double keyPixel = keyAxis->coordToPixel(it->key) + (mBarsGroup ? mBarsGroup->keyPixelOffset(this, it->key) : 0);
if (keyAxis->orientation() == Qt::Horizontal)
return {keyPixel, valuePixel};
else
return {valuePixel, keyPixel};
} else
{
qDebug() << Q_FUNC_INFO << "Index out of bounds" << index;
return {};
}
}
/* inherits documentation from base class */
void QCPBars::draw(QCPPainter *painter)
{
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (mDataContainer->isEmpty()) return;
QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
getVisibleDataBounds(visibleBegin, visibleEnd);
// loop over and draw segments of unselected/selected data:
QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
getDataSegments(selectedSegments, unselectedSegments);
allSegments << unselectedSegments << selectedSegments;
for (int i=0; i<allSegments.size(); ++i)
{
bool isSelectedSegment = i >= unselectedSegments.size();
QCPBarsDataContainer::const_iterator begin = visibleBegin;
QCPBarsDataContainer::const_iterator end = visibleEnd;
mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
if (begin == end)
continue;
for (QCPBarsDataContainer::const_iterator it=begin; it!=end; ++it)
{
// check data validity if flag set:
#ifdef QCUSTOMPLOT_CHECK_DATA
if (QCP::isInvalidData(it->key, it->value))
qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
#endif
// draw bar:
if (isSelectedSegment && mSelectionDecorator)
{
mSelectionDecorator->applyBrush(painter);
mSelectionDecorator->applyPen(painter);
} else
{
painter->setBrush(mBrush);
painter->setPen(mPen);
}
applyDefaultAntialiasingHint(painter);
painter->drawPolygon(getBarRect(it->key, it->value));
}
}
// draw other selection decoration that isn't just line/scatter pens and brushes:
if (mSelectionDecorator)
mSelectionDecorator->drawDecoration(painter, selection());
}
/* inherits documentation from base class */
void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
// draw filled rect:
applyDefaultAntialiasingHint(painter);
painter->setBrush(mBrush);
painter->setPen(mPen);
QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
r.moveCenter(rect.center());
painter->drawRect(r);
}
/*! \internal
called by \ref draw to determine which data (key) range is visible at the current key axis range
setting, so only that needs to be processed. It also takes into account the bar width.
\a begin returns an iterator to the lowest data point that needs to be taken into account when
plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
lower may still be just outside the visible range.
\a end returns an iterator one higher than the highest visible data point. Same as before, \a end
may also lie just outside of the visible range.
if the plottable contains no data, both \a begin and \a end point to constEnd.
*/
void QCPBars::getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const
{
if (!mKeyAxis)
{
qDebug() << Q_FUNC_INFO << "invalid key axis";
begin = mDataContainer->constEnd();
end = mDataContainer->constEnd();
return;
}
if (mDataContainer->isEmpty())
{
begin = mDataContainer->constEnd();
end = mDataContainer->constEnd();
return;
}
// get visible data range as QMap iterators
begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower);
end = mDataContainer->findEnd(mKeyAxis.data()->range().upper);
double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower);
double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper);
bool isVisible = false;
// walk left from begin to find lower bar that actually is completely outside visible pixel range:
QCPBarsDataContainer::const_iterator it = begin;
while (it != mDataContainer->constBegin())
{
--it;
const QRectF barRect = getBarRect(it->key, it->value);
if (mKeyAxis.data()->orientation() == Qt::Horizontal)
isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.left() <= lowerPixelBound));
else // keyaxis is vertical
isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.bottom() >= lowerPixelBound));
if (isVisible)
begin = it;
else
break;
}
// walk right from ubound to find upper bar that actually is completely outside visible pixel range:
it = end;
while (it != mDataContainer->constEnd())
{
const QRectF barRect = getBarRect(it->key, it->value);
if (mKeyAxis.data()->orientation() == Qt::Horizontal)
isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.right() >= upperPixelBound));
else // keyaxis is vertical
isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.top() <= upperPixelBound));
if (isVisible)
end = it+1;
else
break;
++it;
}
}
/*! \internal
Returns the rect in pixel coordinates of a single bar with the specified \a key and \a value. The
rect is shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref
setBaseValue), and to have non-overlapping border lines with the bars stacked below.
*/
QRectF QCPBars::getBarRect(double key, double value) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
double lowerPixelWidth, upperPixelWidth;
getPixelWidth(key, lowerPixelWidth, upperPixelWidth);
double base = getStackedBaseValue(key, value >= 0);
double basePixel = valueAxis->coordToPixel(base);
double valuePixel = valueAxis->coordToPixel(base+value);
double keyPixel = keyAxis->coordToPixel(key);
if (mBarsGroup)
keyPixel += mBarsGroup->keyPixelOffset(this, key);
double bottomOffset = (mBarBelow && mPen != Qt::NoPen ? 1 : 0)*(mPen.isCosmetic() ? 1 : mPen.widthF());
bottomOffset += mBarBelow ? mStackingGap : 0;
bottomOffset *= (value<0 ? -1 : 1)*valueAxis->pixelOrientation();
if (qAbs(valuePixel-basePixel) <= qAbs(bottomOffset))
bottomOffset = valuePixel-basePixel;
if (keyAxis->orientation() == Qt::Horizontal)
{
return QRectF(QPointF(keyPixel+lowerPixelWidth, valuePixel), QPointF(keyPixel+upperPixelWidth, basePixel+bottomOffset)).normalized();
} else
{
return QRectF(QPointF(basePixel+bottomOffset, keyPixel+lowerPixelWidth), QPointF(valuePixel, keyPixel+upperPixelWidth)).normalized();
}
}
/*! \internal
This function is used to determine the width of the bar at coordinate \a key, according to the
specified width (\ref setWidth) and width type (\ref setWidthType).
The output parameters \a lower and \a upper return the number of pixels the bar extends to lower
and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a
lower is negative and \a upper positive).
*/
void QCPBars::getPixelWidth(double key, double &lower, double &upper) const
{
lower = 0;
upper = 0;
switch (mWidthType)
{
case wtAbsolute:
{
upper = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
lower = -upper;
break;
}
case wtAxisRectRatio:
{
if (mKeyAxis && mKeyAxis.data()->axisRect())
{
if (mKeyAxis.data()->orientation() == Qt::Horizontal)
upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
else
upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
lower = -upper;
} else
qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
break;
}
case wtPlotCoords:
{
if (mKeyAxis)
{
double keyPixel = mKeyAxis.data()->coordToPixel(key);
upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel;
// no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by
// coordinate transform which includes range direction
} else
qDebug() << Q_FUNC_INFO << "No key axis defined";
break;
}
}
}
/*! \internal
This function is called to find at which value to start drawing the base of a bar at \a key, when
it is stacked on top of another QCPBars (e.g. with \ref moveAbove).
positive and negative bars are separated per stack (positive are stacked above baseValue upwards,
negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the
bar for which we need the base value is negative, set \a positive to false.
*/
double QCPBars::getStackedBaseValue(double key, bool positive) const
{
if (mBarBelow)
{
double max = 0; // don't initialize with mBaseValue here because only base value of bottom-most bar has meaning in a bar stack
// find bars of mBarBelow that are approximately at key and find largest one:
double epsilon = qAbs(key)*(sizeof(key)==4 ? 1e-6 : 1e-14); // should be safe even when changed to use float at some point
if (key == 0)
epsilon = (sizeof(key)==4 ? 1e-6 : 1e-14);
QCPBarsDataContainer::const_iterator it = mBarBelow.data()->mDataContainer->findBegin(key-epsilon);
QCPBarsDataContainer::const_iterator itEnd = mBarBelow.data()->mDataContainer->findEnd(key+epsilon);
while (it != itEnd)
{
if (it->key > key-epsilon && it->key < key+epsilon)
{
if ((positive && it->value > max) ||
(!positive && it->value < max))
max = it->value;
}
++it;
}
// recurse down the bar-stack to find the total height:
return max + mBarBelow.data()->getStackedBaseValue(key, positive);
} else
return mBaseValue;
}
/*! \internal
Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s)
currently above lower and below upper will become disconnected to lower/upper.
If lower is zero, upper will be disconnected at the bottom.
If upper is zero, lower will be disconnected at the top.
*/
void QCPBars::connectBars(QCPBars *lower, QCPBars *upper)
{
if (!lower && !upper) return;
if (!lower) // disconnect upper at bottom
{
// disconnect old bar below upper:
if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
upper->mBarBelow.data()->mBarAbove = nullptr;
upper->mBarBelow = nullptr;
} else if (!upper) // disconnect lower at top
{
// disconnect old bar above lower:
if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
lower->mBarAbove.data()->mBarBelow = nullptr;
lower->mBarAbove = nullptr;
} else // connect lower and upper
{
// disconnect old bar above lower:
if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
lower->mBarAbove.data()->mBarBelow = nullptr;
// disconnect old bar below upper:
if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
upper->mBarBelow.data()->mBarAbove = nullptr;
lower->mBarAbove = upper;
upper->mBarBelow = lower;
}
}
/* end of 'src/plottables/plottable-bars.cpp' */
/* including file 'src/plottables/plottable-statisticalbox.cpp' */
/* modified 2022-11-06T12:45:57, size 28951 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPStatisticalBoxData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPStatisticalBoxData
\brief Holds the data of one single data point for QCPStatisticalBox.
The stored data is:
\li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
\li \a minimum: the position of the lower whisker, typically the minimum measurement of the
sample that's not considered an outlier.
\li \a lowerQuartile: the lower end of the box. The lower and the upper quartiles are the two
statistical quartiles around the median of the sample, they should contain 50% of the sample
data.
\li \a median: the value of the median mark inside the quartile box. The median separates the
sample data in half (50% of the sample data is below/above the median). (This is the \a mainValue)
\li \a upperQuartile: the upper end of the box. The lower and the upper quartiles are the two
statistical quartiles around the median of the sample, they should contain 50% of the sample
data.
\li \a maximum: the position of the upper whisker, typically the maximum measurement of the
sample that's not considered an outlier.
\li \a outliers: a QVector of outlier values that will be drawn as scatter points at the \a key
coordinate of this data point (see \ref QCPStatisticalBox::setOutlierStyle)
The container for storing multiple data points is \ref QCPStatisticalBoxDataContainer. It is a
typedef for \ref QCPDataContainer with \ref QCPStatisticalBoxData as the DataType template
parameter. See the documentation there for an explanation regarding the data type's generic
methods.
\see QCPStatisticalBoxDataContainer
*/
/* start documentation of inline functions */
/*! \fn double QCPStatisticalBoxData::sortKey() const
Returns the \a key member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn static QCPStatisticalBoxData QCPStatisticalBoxData::fromSortKey(double sortKey)
Returns a data point with the specified \a sortKey. All other members are set to zero.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn static static bool QCPStatisticalBoxData::sortKeyIsMainKey()
Since the member \a key is both the data point key coordinate and the data ordering parameter,
this method returns true.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn double QCPStatisticalBoxData::mainKey() const
Returns the \a key member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn double QCPStatisticalBoxData::mainValue() const
Returns the \a median member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn QCPRange QCPStatisticalBoxData::valueRange() const
Returns a QCPRange spanning from the \a minimum to the \a maximum member of this statistical box
data point, possibly further expanded by outliers.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/* end documentation of inline functions */
/*!
Constructs a data point with key and all values set to zero.
*/
QCPStatisticalBoxData::QCPStatisticalBoxData() :
key(0),
minimum(0),
lowerQuartile(0),
median(0),
upperQuartile(0),
maximum(0)
{
}
/*!
Constructs a data point with the specified \a key, \a minimum, \a lowerQuartile, \a median, \a
upperQuartile, \a maximum and optionally a number of \a outliers.
*/
QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers) :
key(key),
minimum(minimum),
lowerQuartile(lowerQuartile),
median(median),
upperQuartile(upperQuartile),
maximum(maximum),
outliers(outliers)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPStatisticalBox
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPStatisticalBox
\brief A plottable representing a single statistical box in a plot.
\image html QCPStatisticalBox.png
To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
also access and modify the data via the \ref data method, which returns a pointer to the internal
\ref QCPStatisticalBoxDataContainer.
Additionally each data point can itself have a list of outliers, drawn as scatter points at the
key coordinate of the respective statistical box data point. They can either be set by using the
respective \ref addData(double,double,double,double,double,double,const QVector<double>&)
"addData" method or accessing the individual data points through \ref data, and setting the
<tt>QVector<double> outliers</tt> of the data points directly.
\section qcpstatisticalbox-appearance Changing the appearance
The appearance of each data point box, ranging from the lower to the upper quartile, is
controlled via \ref setPen and \ref setBrush. You may change the width of the boxes with \ref
setWidth in plot coordinates.
Each data point's visual representation also consists of two whiskers. Whiskers are the lines
which reach from the upper quartile to the maximum, and from the lower quartile to the minimum.
The appearance of the whiskers can be modified with: \ref setWhiskerPen, \ref setWhiskerBarPen,
\ref setWhiskerWidth. The whisker width is the width of the bar perpendicular to the whisker at
the top (for maximum) and bottom (for minimum). If the whisker pen is changed, make sure to set
the \c capStyle to \c Qt::FlatCap. Otherwise the backbone line might exceed the whisker bars by a
few pixels due to the pen cap being not perfectly flat.
The median indicator line inside the box has its own pen, \ref setMedianPen.
The outlier data points are drawn as normal scatter points. Their look can be controlled with
\ref setOutlierStyle
\section qcpstatisticalbox-usage Usage
Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable
(QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
(QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
Usually, you first create an instance:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1
which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
The newly created plottable can be modified, e.g.:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-2
*/
/* start documentation of inline functions */
/*! \fn QSharedPointer<QCPStatisticalBoxDataContainer> QCPStatisticalBox::data() const
Returns a shared pointer to the internal data storage of type \ref
QCPStatisticalBoxDataContainer. You may use it to directly manipulate the data, which may be more
convenient and faster than using the regular \ref setData or \ref addData methods.
*/
/* end documentation of inline functions */
/*!
Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its
value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and
not have the same orientation. If either of these restrictions is violated, a corresponding
message is printed to the debug output (qDebug), the construction is not aborted, though.
The created QCPStatisticalBox is automatically registered with the QCustomPlot instance inferred
from \a keyAxis. This QCustomPlot instance takes ownership of the QCPStatisticalBox, so do not
delete it manually but use QCustomPlot::removePlottable() instead.
*/
QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable1D<QCPStatisticalBoxData>(keyAxis, valueAxis),
mWidth(0.5),
mWhiskerWidth(0.2),
mWhiskerPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap),
mWhiskerBarPen(Qt::black),
mWhiskerAntialiased(false),
mMedianPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap),
mOutlierStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)
{
setPen(QPen(Qt::black));
setBrush(Qt::NoBrush);
}
/*! \overload
Replaces the current data container with the provided \a data container.
Since a QSharedPointer is used, multiple QCPStatisticalBoxes may share the same data container
safely. Modifying the data in the container will then affect all statistical boxes that share the
container. Sharing can be achieved by simply exchanging the data containers wrapped in shared
pointers:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-1
If you do not wish to share containers, but create a copy from an existing container, rather use
the \ref QCPDataContainer<DataType>::set method on the statistical box data container directly:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-2
\see addData
*/
void QCPStatisticalBox::setData(QSharedPointer<QCPStatisticalBoxDataContainer> data)
{
mDataContainer = data;
}
/*! \overload
Replaces the current data with the provided points in \a keys, \a minimum, \a lowerQuartile, \a
median, \a upperQuartile and \a maximum. The provided vectors should have equal length. Else, the
number of added points will be the size of the smallest vector.
If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
can set \a alreadySorted to true, to improve performance by saving a sorting run.
\see addData
*/
void QCPStatisticalBox::setData(const QVector<double> &keys, const QVector<double> &minimum, const QVector<double> &lowerQuartile, const QVector<double> &median, const QVector<double> &upperQuartile, const QVector<double> &maximum, bool alreadySorted)
{
mDataContainer->clear();
addData(keys, minimum, lowerQuartile, median, upperQuartile, maximum, alreadySorted);
}
/*!
Sets the width of the boxes in key coordinates.
\see setWhiskerWidth
*/
void QCPStatisticalBox::setWidth(double width)
{
mWidth = width;
}
/*!
Sets the width of the whiskers in key coordinates.
Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
quartile to the minimum.
\see setWidth
*/
void QCPStatisticalBox::setWhiskerWidth(double width)
{
mWhiskerWidth = width;
}
/*!
Sets the pen used for drawing the whisker backbone.
Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
quartile to the minimum.
Make sure to set the \c capStyle of the passed \a pen to \c Qt::FlatCap. Otherwise the backbone
line might exceed the whisker bars by a few pixels due to the pen cap being not perfectly flat.
\see setWhiskerBarPen
*/
void QCPStatisticalBox::setWhiskerPen(const QPen &pen)
{
mWhiskerPen = pen;
}
/*!
Sets the pen used for drawing the whisker bars. Those are the lines parallel to the key axis at
each end of the whisker backbone.
Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
quartile to the minimum.
\see setWhiskerPen
*/
void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen)
{
mWhiskerBarPen = pen;
}
/*!
Sets whether the statistical boxes whiskers are drawn with antialiasing or not.
Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
QCustomPlot::setNotAntialiasedElements.
*/
void QCPStatisticalBox::setWhiskerAntialiased(bool enabled)
{
mWhiskerAntialiased = enabled;
}
/*!
Sets the pen used for drawing the median indicator line inside the statistical boxes.
*/
void QCPStatisticalBox::setMedianPen(const QPen &pen)
{
mMedianPen = pen;
}
/*!
Sets the appearance of the outlier data points.
Outliers can be specified with the method
\ref addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
*/
void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style)
{
mOutlierStyle = style;
}
/*! \overload
Adds the provided points in \a keys, \a minimum, \a lowerQuartile, \a median, \a upperQuartile and
\a maximum to the current data. The provided vectors should have equal length. Else, the number
of added points will be the size of the smallest vector.
If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
can set \a alreadySorted to true, to improve performance by saving a sorting run.
Alternatively, you can also access and modify the data directly via the \ref data method, which
returns a pointer to the internal data container.
*/
void QCPStatisticalBox::addData(const QVector<double> &keys, const QVector<double> &minimum, const QVector<double> &lowerQuartile, const QVector<double> &median, const QVector<double> &upperQuartile, const QVector<double> &maximum, bool alreadySorted)
{
if (keys.size() != minimum.size() || minimum.size() != lowerQuartile.size() || lowerQuartile.size() != median.size() ||
median.size() != upperQuartile.size() || upperQuartile.size() != maximum.size() || maximum.size() != keys.size())
qDebug() << Q_FUNC_INFO << "keys, minimum, lowerQuartile, median, upperQuartile, maximum have different sizes:"
<< keys.size() << minimum.size() << lowerQuartile.size() << median.size() << upperQuartile.size() << maximum.size();
const int n = static_cast<int>(qMin(keys.size(), qMin(minimum.size(), qMin(lowerQuartile.size(), qMin(median.size(), qMin(upperQuartile.size(), maximum.size()))))));
QVector<QCPStatisticalBoxData> tempData(n);
QVector<QCPStatisticalBoxData>::iterator it = tempData.begin();
const QVector<QCPStatisticalBoxData>::iterator itEnd = tempData.end();
int i = 0;
while (it != itEnd)
{
it->key = keys[i];
it->minimum = minimum[i];
it->lowerQuartile = lowerQuartile[i];
it->median = median[i];
it->upperQuartile = upperQuartile[i];
it->maximum = maximum[i];
++it;
++i;
}
mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
}
/*! \overload
Adds the provided data point as \a key, \a minimum, \a lowerQuartile, \a median, \a upperQuartile
and \a maximum to the current data.
Alternatively, you can also access and modify the data directly via the \ref data method, which
returns a pointer to the internal data container.
*/
void QCPStatisticalBox::addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
{
mDataContainer->add(QCPStatisticalBoxData(key, minimum, lowerQuartile, median, upperQuartile, maximum, outliers));
}
/*!
\copydoc QCPPlottableInterface1D::selectTestRect
*/
QCPDataSelection QCPStatisticalBox::selectTestRect(const QRectF &rect, bool onlySelectable) const
{
QCPDataSelection result;
if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
return result;
if (!mKeyAxis || !mValueAxis)
return result;
QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
getVisibleDataBounds(visibleBegin, visibleEnd);
for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
{
if (rect.intersects(getQuartileBox(it)))
result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
}
result.simplify();
return result;
}
/*!
Implements a selectTest specific to this plottable's point geometry.
If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
point to \a pos.
\seebaseclassmethod \ref QCPAbstractPlottable::selectTest
*/
double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
return -1;
if (!mKeyAxis || !mValueAxis)
return -1;
if (mKeyAxis->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
{
// get visible data range:
QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
QCPStatisticalBoxDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
getVisibleDataBounds(visibleBegin, visibleEnd);
double minDistSqr = (std::numeric_limits<double>::max)();
for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
{
if (getQuartileBox(it).contains(pos)) // quartile box
{
double currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
if (currentDistSqr < minDistSqr)
{
minDistSqr = currentDistSqr;
closestDataPoint = it;
}
} else // whiskers
{
const QVector<QLineF> whiskerBackbones = getWhiskerBackboneLines(it);
const QCPVector2D posVec(pos);
foreach (const QLineF &backbone, whiskerBackbones)
{
double currentDistSqr = posVec.distanceSquaredToLine(backbone);
if (currentDistSqr < minDistSqr)
{
minDistSqr = currentDistSqr;
closestDataPoint = it;
}
}
}
}
if (details)
{
int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
}
return qSqrt(minDistSqr);
}
return -1;
}
/* inherits documentation from base class */
QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
{
QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
// determine exact range by including width of bars/flags:
if (foundRange)
{
if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0)
range.lower -= mWidth*0.5;
if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0)
range.upper += mWidth*0.5;
}
return range;
}
/* inherits documentation from base class */
QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
{
return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
}
/* inherits documentation from base class */
void QCPStatisticalBox::draw(QCPPainter *painter)
{
if (mDataContainer->isEmpty()) return;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
getVisibleDataBounds(visibleBegin, visibleEnd);
// loop over and draw segments of unselected/selected data:
QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
getDataSegments(selectedSegments, unselectedSegments);
allSegments << unselectedSegments << selectedSegments;
for (int i=0; i<allSegments.size(); ++i)
{
bool isSelectedSegment = i >= unselectedSegments.size();
QCPStatisticalBoxDataContainer::const_iterator begin = visibleBegin;
QCPStatisticalBoxDataContainer::const_iterator end = visibleEnd;
mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
if (begin == end)
continue;
for (QCPStatisticalBoxDataContainer::const_iterator it=begin; it!=end; ++it)
{
// check data validity if flag set:
# ifdef QCUSTOMPLOT_CHECK_DATA
if (QCP::isInvalidData(it->key, it->minimum) ||
QCP::isInvalidData(it->lowerQuartile, it->median) ||
QCP::isInvalidData(it->upperQuartile, it->maximum))
qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range has invalid data." << "Plottable name:" << name();
for (int i=0; i<it->outliers.size(); ++i)
if (QCP::isInvalidData(it->outliers.at(i)))
qDebug() << Q_FUNC_INFO << "Data point outlier at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
# endif
if (isSelectedSegment && mSelectionDecorator)
{
mSelectionDecorator->applyPen(painter);
mSelectionDecorator->applyBrush(painter);
} else
{
painter->setPen(mPen);
painter->setBrush(mBrush);
}
QCPScatterStyle finalOutlierStyle = mOutlierStyle;
if (isSelectedSegment && mSelectionDecorator)
finalOutlierStyle = mSelectionDecorator->getFinalScatterStyle(mOutlierStyle);
drawStatisticalBox(painter, it, finalOutlierStyle);
}
}
// draw other selection decoration that isn't just line/scatter pens and brushes:
if (mSelectionDecorator)
mSelectionDecorator->drawDecoration(painter, selection());
}
/* inherits documentation from base class */
void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
// draw filled rect:
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
painter->setBrush(mBrush);
QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
r.moveCenter(rect.center());
painter->drawRect(r);
}
/*!
Draws the graphical representation of a single statistical box with the data given by the
iterator \a it with the provided \a painter.
If the statistical box has a set of outlier data points, they are drawn with \a outlierStyle.
\see getQuartileBox, getWhiskerBackboneLines, getWhiskerBarLines
*/
void QCPStatisticalBox::drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const
{
// draw quartile box:
applyDefaultAntialiasingHint(painter);
const QRectF quartileBox = getQuartileBox(it);
painter->drawRect(quartileBox);
// draw median line with cliprect set to quartile box:
painter->save();
painter->setClipRect(quartileBox, Qt::IntersectClip);
painter->setPen(mMedianPen);
painter->drawLine(QLineF(coordsToPixels(it->key-mWidth*0.5, it->median), coordsToPixels(it->key+mWidth*0.5, it->median)));
painter->restore();
// draw whisker lines:
applyAntialiasingHint(painter, mWhiskerAntialiased, QCP::aePlottables);
painter->setPen(mWhiskerPen);
painter->drawLines(getWhiskerBackboneLines(it));
painter->setPen(mWhiskerBarPen);
painter->drawLines(getWhiskerBarLines(it));
// draw outliers:
applyScattersAntialiasingHint(painter);
outlierStyle.applyTo(painter, mPen);
for (int i=0; i<it->outliers.size(); ++i)
outlierStyle.drawShape(painter, coordsToPixels(it->key, it->outliers.at(i)));
}
/*! \internal
called by \ref draw to determine which data (key) range is visible at the current key axis range
setting, so only that needs to be processed. It also takes into account the bar width.
\a begin returns an iterator to the lowest data point that needs to be taken into account when
plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
lower may still be just outside the visible range.
\a end returns an iterator one higher than the highest visible data point. Same as before, \a end
may also lie just outside of the visible range.
if the plottable contains no data, both \a begin and \a end point to constEnd.
*/
void QCPStatisticalBox::getVisibleDataBounds(QCPStatisticalBoxDataContainer::const_iterator &begin, QCPStatisticalBoxDataContainer::const_iterator &end) const
{
if (!mKeyAxis)
{
qDebug() << Q_FUNC_INFO << "invalid key axis";
begin = mDataContainer->constEnd();
end = mDataContainer->constEnd();
return;
}
begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of box to include partially visible data points
end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of box to include partially visible data points
}
/*! \internal
Returns the box in plot coordinates (keys in x, values in y of the returned rect) that covers the
value range from the lower to the upper quartile, of the data given by \a it.
\see drawStatisticalBox, getWhiskerBackboneLines, getWhiskerBarLines
*/
QRectF QCPStatisticalBox::getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const
{
QRectF result;
result.setTopLeft(coordsToPixels(it->key-mWidth*0.5, it->upperQuartile));
result.setBottomRight(coordsToPixels(it->key+mWidth*0.5, it->lowerQuartile));
return result;
}
/*! \internal
Returns the whisker backbones (keys in x, values in y of the returned lines) that cover the value
range from the minimum to the lower quartile, and from the upper quartile to the maximum of the
data given by \a it.
\see drawStatisticalBox, getQuartileBox, getWhiskerBarLines
*/
QVector<QLineF> QCPStatisticalBox::getWhiskerBackboneLines(QCPStatisticalBoxDataContainer::const_iterator it) const
{
QVector<QLineF> result(2);
result[0].setPoints(coordsToPixels(it->key, it->lowerQuartile), coordsToPixels(it->key, it->minimum)); // min backbone
result[1].setPoints(coordsToPixels(it->key, it->upperQuartile), coordsToPixels(it->key, it->maximum)); // max backbone
return result;
}
/*! \internal
Returns the whisker bars (keys in x, values in y of the returned lines) that are placed at the
end of the whisker backbones, at the minimum and maximum of the data given by \a it.
\see drawStatisticalBox, getQuartileBox, getWhiskerBackboneLines
*/
QVector<QLineF> QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataContainer::const_iterator it) const
{
QVector<QLineF> result(2);
result[0].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->minimum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->minimum)); // min bar
result[1].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->maximum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->maximum)); // max bar
return result;
}
/* end of 'src/plottables/plottable-statisticalbox.cpp' */
/* including file 'src/plottables/plottable-colormap.cpp' */
/* modified 2022-11-06T12:45:56, size 48189 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPColorMapData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPColorMapData
\brief Holds the two-dimensional data of a QCPColorMap plottable.
This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref
QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a
color, depending on the value.
The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize).
Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref
setKeyRange, \ref setValueRange).
The data cells can be accessed in two ways: They can be directly addressed by an integer index
with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot
coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are
provided by the functions \ref coordToCell and \ref cellToCoord.
A \ref QCPColorMapData also holds an on-demand two-dimensional array of alpha values which (if
allocated) has the same size as the data map. It can be accessed via \ref setAlpha, \ref
fillAlpha and \ref clearAlpha. The memory for the alpha map is only allocated if needed, i.e. on
the first call of \ref setAlpha. \ref clearAlpha restores full opacity and frees the alpha map.
This class also buffers the minimum and maximum values that are in the data set, to provide
QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value
that is greater than the current maximum increases this maximum to the new value. However,
setting the cell that currently holds the maximum value to a smaller value doesn't decrease the
maximum again, because finding the true new maximum would require going through the entire data
array, which might be time consuming. The same holds for the data minimum. This functionality is
given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the
true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience
parameter \a recalculateDataBounds which may be set to true to automatically call \ref
recalculateDataBounds internally.
*/
/* start of documentation of inline functions */
/*! \fn bool QCPColorMapData::isEmpty() const
Returns whether this instance carries no data. This is equivalent to having a size where at least
one of the dimensions is 0 (see \ref setSize).
*/
/* end of documentation of inline functions */
/*!
Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction
and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap
at the coordinates \a keyRange and \a valueRange.
\see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange
*/
QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) :
mKeySize(0),
mValueSize(0),
mKeyRange(keyRange),
mValueRange(valueRange),
mIsEmpty(true),
mData(nullptr),
mAlpha(nullptr),
mDataModified(true)
{
setSize(keySize, valueSize);
fill(0);
}
QCPColorMapData::~QCPColorMapData()
{
delete[] mData;
delete[] mAlpha;
}
/*!
Constructs a new QCPColorMapData instance copying the data and range of \a other.
*/
QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) :
mKeySize(0),
mValueSize(0),
mIsEmpty(true),
mData(nullptr),
mAlpha(nullptr),
mDataModified(true)
{
*this = other;
}
/*!
Overwrites this color map data instance with the data stored in \a other. The alpha map state is
transferred, too.
*/
QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other)
{
if (&other != this)
{
const int keySize = other.keySize();
const int valueSize = other.valueSize();
if (!other.mAlpha && mAlpha)
clearAlpha();
setSize(keySize, valueSize);
if (other.mAlpha && !mAlpha)
createAlpha(false);
setRange(other.keyRange(), other.valueRange());
if (!isEmpty())
{
memcpy(mData, other.mData, sizeof(mData[0])*size_t(keySize*valueSize));
if (mAlpha && other.mAlpha)
memcpy(mAlpha, other.mAlpha, sizeof(mAlpha[0])*size_t(keySize*valueSize));
}
mDataBounds = other.mDataBounds;
mDataModified = true;
}
return *this;
}
/* undocumented getter */
double QCPColorMapData::data(double key, double value)
{
int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
return mData[valueCell*mKeySize + keyCell];
else
return 0;
}
/* undocumented getter */
double QCPColorMapData::cell(int keyIndex, int valueIndex)
{
if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
return mData[valueIndex*mKeySize + keyIndex];
else
return 0;
}
/*!
Returns the alpha map value of the cell with the indices \a keyIndex and \a valueIndex.
If this color map data doesn't have an alpha map (because \ref setAlpha was never called after
creation or after a call to \ref clearAlpha), returns 255, which corresponds to full opacity.
\see setAlpha
*/
unsigned char QCPColorMapData::alpha(int keyIndex, int valueIndex)
{
if (mAlpha && keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
return mAlpha[valueIndex*mKeySize + keyIndex];
else
return 255;
}
/*!
Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in
the value dimension.
The current data is discarded and the map cells are set to 0, unless the map had already the
requested size.
Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref
isEmpty returns true.
\see setRange, setKeySize, setValueSize
*/
void QCPColorMapData::setSize(int keySize, int valueSize)
{
if (keySize != mKeySize || valueSize != mValueSize)
{
mKeySize = keySize;
mValueSize = valueSize;
delete[] mData;
mIsEmpty = mKeySize == 0 || mValueSize == 0;
if (!mIsEmpty)
{
#ifdef __EXCEPTIONS
try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
#endif
mData = new double[size_t(mKeySize*mValueSize)];
#ifdef __EXCEPTIONS
} catch (...) { mData = nullptr; }
#endif
if (mData)
fill(0);
else
qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
} else
mData = nullptr;
if (mAlpha) // if we had an alpha map, recreate it with new size
createAlpha();
mDataModified = true;
}
}
/*!
Resizes the data array to have \a keySize cells in the key dimension.
The current data is discarded and the map cells are set to 0, unless the map had already the
requested size.
Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true.
\see setKeyRange, setSize, setValueSize
*/
void QCPColorMapData::setKeySize(int keySize)
{
setSize(keySize, mValueSize);
}
/*!
Resizes the data array to have \a valueSize cells in the value dimension.
The current data is discarded and the map cells are set to 0, unless the map had already the
requested size.
Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true.
\see setValueRange, setSize, setKeySize
*/
void QCPColorMapData::setValueSize(int valueSize)
{
setSize(mKeySize, valueSize);
}
/*!
Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area
covered by the color map in plot coordinates.
The outer cells will be centered on the range boundaries given to this function. For example, if
the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
be cells centered on the key coordinates 2, 2.5 and 3.
\see setSize
*/
void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange)
{
setKeyRange(keyRange);
setValueRange(valueRange);
}
/*!
Sets the coordinate range the data shall be distributed over in the key dimension. Together with
the value range, This defines the rectangular area covered by the color map in plot coordinates.
The outer cells will be centered on the range boundaries given to this function. For example, if
the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
be cells centered on the key coordinates 2, 2.5 and 3.
\see setRange, setValueRange, setSize
*/
void QCPColorMapData::setKeyRange(const QCPRange &keyRange)
{
mKeyRange = keyRange;
}
/*!
Sets the coordinate range the data shall be distributed over in the value dimension. Together with
the key range, This defines the rectangular area covered by the color map in plot coordinates.
The outer cells will be centered on the range boundaries given to this function. For example, if
the value size (\ref setValueSize) is 3 and \a valueRange is set to <tt>QCPRange(2, 3)</tt> there
will be cells centered on the value coordinates 2, 2.5 and 3.
\see setRange, setKeyRange, setSize
*/
void QCPColorMapData::setValueRange(const QCPRange &valueRange)
{
mValueRange = valueRange;
}
/*!
Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a
z.
\note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
determine the cell index. Rather directly access the cell index with \ref
QCPColorMapData::setCell.
\see setCell, setRange
*/
void QCPColorMapData::setData(double key, double value, double z)
{
int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
{
mData[valueCell*mKeySize + keyCell] = z;
if (z < mDataBounds.lower)
mDataBounds.lower = z;
if (z > mDataBounds.upper)
mDataBounds.upper = z;
mDataModified = true;
}
}
/*!
Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices
enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see
\ref setSize).
In the standard plot configuration (horizontal key axis and vertical value axis, both not
range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with
indices (keySize-1, valueSize-1) is in the top right corner of the color map.
\see setData, setSize
*/
void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z)
{
if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
{
mData[valueIndex*mKeySize + keyIndex] = z;
if (z < mDataBounds.lower)
mDataBounds.lower = z;
if (z > mDataBounds.upper)
mDataBounds.upper = z;
mDataModified = true;
} else
qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
}
/*!
Sets the alpha of the color map cell given by \a keyIndex and \a valueIndex to \a alpha. A value
of 0 for \a alpha results in a fully transparent cell, and a value of 255 results in a fully
opaque cell.
If an alpha map doesn't exist yet for this color map data, it will be created here. If you wish
to restore full opacity and free any allocated memory of the alpha map, call \ref clearAlpha.
Note that the cell-wise alpha which can be configured here is independent of any alpha configured
in the color map's gradient (\ref QCPColorGradient). If a cell is affected both by the cell-wise
and gradient alpha, the alpha values will be blended accordingly during rendering of the color
map.
\see fillAlpha, clearAlpha
*/
void QCPColorMapData::setAlpha(int keyIndex, int valueIndex, unsigned char alpha)
{
if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
{
if (mAlpha || createAlpha())
{
mAlpha[valueIndex*mKeySize + keyIndex] = alpha;
mDataModified = true;
}
} else
qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
}
/*!
Goes through the data and updates the buffered minimum and maximum data values.
Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange
and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten
with a smaller or larger value respectively, since the buffered maximum/minimum values have been
updated the last time. Why this is the case is explained in the class description (\ref
QCPColorMapData).
Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a
recalculateDataBounds for convenience. Setting this to true will call this method for you, before
doing the rescale.
*/
void QCPColorMapData::recalculateDataBounds()
{
if (mKeySize > 0 && mValueSize > 0)
{
double minHeight = std::numeric_limits<double>::max();
double maxHeight = -std::numeric_limits<double>::max();
const int dataCount = mValueSize*mKeySize;
for (int i=0; i<dataCount; ++i)
{
if (mData[i] > maxHeight)
maxHeight = mData[i];
if (mData[i] < minHeight)
minHeight = mData[i];
}
mDataBounds.lower = minHeight;
mDataBounds.upper = maxHeight;
}
}
/*!
Frees the internal data memory.
This is equivalent to calling \ref setSize "setSize(0, 0)".
*/
void QCPColorMapData::clear()
{
setSize(0, 0);
}
/*!
Frees the internal alpha map. The color map will have full opacity again.
*/
void QCPColorMapData::clearAlpha()
{
if (mAlpha)
{
delete[] mAlpha;
mAlpha = nullptr;
mDataModified = true;
}
}
/*!
Sets all cells to the value \a z.
*/
void QCPColorMapData::fill(double z)
{
const int dataCount = mValueSize*mKeySize;
memset(mData, z, dataCount*sizeof(*mData));
mDataBounds = QCPRange(z, z);
mDataModified = true;
}
/*!
Sets the opacity of all color map cells to \a alpha. A value of 0 for \a alpha results in a fully
transparent color map, and a value of 255 results in a fully opaque color map.
If you wish to restore opacity to 100% and free any used memory for the alpha map, rather use
\ref clearAlpha.
\see setAlpha
*/
void QCPColorMapData::fillAlpha(unsigned char alpha)
{
if (mAlpha || createAlpha(false))
{
const int dataCount = mValueSize*mKeySize;
memset(mAlpha, alpha, dataCount*sizeof(*mAlpha));
mDataModified = true;
}
}
/*!
Transforms plot coordinates given by \a key and \a value to cell indices of this QCPColorMapData
instance. The resulting cell indices are returned via the output parameters \a keyIndex and \a
valueIndex.
The retrieved key/value cell indices can then be used for example with \ref setCell.
If you are only interested in a key or value index, you may pass \c nullptr as \a valueIndex or
\a keyIndex.
\note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
you shouldn't use the \ref QCPColorMapData::coordToCell method as it uses a linear transformation to
determine the cell index.
\see cellToCoord, QCPAxis::coordToPixel
*/
void QCPColorMapData::coordToCell(double key, double value, int *keyIndex, int *valueIndex) const
{
if (keyIndex)
*keyIndex = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
if (valueIndex)
*valueIndex = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
}
/*!
Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices of this QCPColorMapData
instance. The resulting coordinates are returned via the output parameters \a key and \a
value.
If you are only interested in a key or value coordinate, you may pass \c nullptr as \a key or \a
value.
\note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
you shouldn't use the \ref QCPColorMapData::cellToCoord method as it uses a linear transformation to
determine the cell index.
\see coordToCell, QCPAxis::pixelToCoord
*/
void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const
{
if (key)
*key = keyIndex/double(mKeySize-1)*(mKeyRange.upper-mKeyRange.lower)+mKeyRange.lower;
if (value)
*value = valueIndex/double(mValueSize-1)*(mValueRange.upper-mValueRange.lower)+mValueRange.lower;
}
/*! \internal
Allocates the internal alpha map with the current data map key/value size and, if \a
initializeOpaque is true, initializes all values to 255. If \a initializeOpaque is false, the
values are not initialized at all. In this case, the alpha map should be initialized manually,
e.g. with \ref fillAlpha.
If an alpha map exists already, it is deleted first. If this color map is empty (has either key
or value size zero, see \ref isEmpty), the alpha map is cleared.
The return value indicates the existence of the alpha map after the call. So this method returns
true if the data map isn't empty and an alpha map was successfully allocated.
*/
bool QCPColorMapData::createAlpha(bool initializeOpaque)
{
clearAlpha();
if (isEmpty())
return false;
#ifdef __EXCEPTIONS
try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
#endif
mAlpha = new unsigned char[size_t(mKeySize*mValueSize)];
#ifdef __EXCEPTIONS
} catch (...) { mAlpha = nullptr; }
#endif
if (mAlpha)
{
if (initializeOpaque)
fillAlpha(255);
return true;
} else
{
qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
return false;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPColorMap
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPColorMap
\brief A plottable representing a two-dimensional color map in a plot.
\image html QCPColorMap.png
The data is stored in the class \ref QCPColorMapData, which can be accessed via the data()
method.
A color map has three dimensions to represent a data point: The \a key dimension, the \a value
dimension and the \a data dimension. As with other plottables such as graphs, \a key and \a value
correspond to two orthogonal axes on the QCustomPlot surface that you specify in the QCPColorMap
constructor. The \a data dimension however is encoded as the color of the point at (\a key, \a
value).
Set the number of points (or \a cells) in the key/value dimension via \ref
QCPColorMapData::setSize. The plot coordinate range over which these points will be displayed is
specified via \ref QCPColorMapData::setRange. The first cell will be centered on the lower range
boundary and the last cell will be centered on the upper range boundary. The data can be set by
either accessing the cells directly with QCPColorMapData::setCell or by addressing the cells via
their plot coordinates with \ref QCPColorMapData::setData. If possible, you should prefer
setCell, since it doesn't need to do any coordinate transformation and thus performs a bit
better.
The cell with index (0, 0) is at the bottom left, if the color map uses normal (i.e. not reversed)
key and value axes.
To show the user which colors correspond to which \a data values, a \ref QCPColorScale is
typically placed to the right of the axis rect. See the documentation there for details on how to
add and use a color scale.
\section qcpcolormap-appearance Changing the appearance
Most important to the appearance is the color gradient, which can be specified via \ref
setGradient. See the documentation of \ref QCPColorGradient for details on configuring a color
gradient.
The \a data range that is mapped to the colors of the gradient can be specified with \ref
setDataRange. To make the data range encompass the whole data set minimum to maximum, call \ref
rescaleDataRange. If your data may contain NaN values, use \ref QCPColorGradient::setNanHandling
to define how they are displayed.
\section qcpcolormap-transparency Transparency
Transparency in color maps can be achieved by two mechanisms. On one hand, you can specify alpha
values for color stops of the \ref QCPColorGradient, via the regular QColor interface. This will
cause the color map data which gets mapped to colors around those color stops to appear with the
accordingly interpolated transparency.
On the other hand you can also directly apply an alpha value to each cell independent of its
data, by using the alpha map feature of \ref QCPColorMapData. The relevant methods are \ref
QCPColorMapData::setAlpha, QCPColorMapData::fillAlpha and \ref QCPColorMapData::clearAlpha().
The two transparencies will be joined together in the plot and otherwise not interfere with each
other. They are mixed in a multiplicative matter, so an alpha of e.g. 50% (128/255) in both modes
simultaneously, will result in a total transparency of 25% (64/255).
\section qcpcolormap-usage Usage
Like all data representing objects in QCustomPlot, the QCPColorMap is a plottable
(QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
(QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
Usually, you first create an instance:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-1
which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
The newly created plottable can be modified, e.g.:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-2
\note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
determine the cell index. Rather directly access the cell index with \ref
QCPColorMapData::setCell.
*/
/* start documentation of inline functions */
/*! \fn QCPColorMapData *QCPColorMap::data() const
Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to
modify data points (cells) and the color map key/value range.
\see setData
*/
/* end documentation of inline functions */
/* start documentation of signals */
/*! \fn void QCPColorMap::dataRangeChanged(const QCPRange &newRange);
This signal is emitted when the data range changes.
\see setDataRange
*/
/*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
This signal is emitted when the data scale type changes.
\see setDataScaleType
*/
/*! \fn void QCPColorMap::gradientChanged(const QCPColorGradient &newGradient);
This signal is emitted when the gradient changes.
\see setGradient
*/
/* end documentation of signals */
/*!
Constructs a color map with the specified \a keyAxis and \a valueAxis.
The created QCPColorMap is automatically registered with the QCustomPlot instance inferred from
\a keyAxis. This QCustomPlot instance takes ownership of the QCPColorMap, so do not delete it
manually but use QCustomPlot::removePlottable() instead.
*/
QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable(keyAxis, valueAxis),
mDataScaleType(QCPAxis::stLinear),
mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))),
mGradient(QCPColorGradient::gpCold),
mInterpolate(true),
mTightBoundary(false),
mMapImageInvalidated(true)
{
}
QCPColorMap::~QCPColorMap()
{
delete mMapData;
}
/*!
Replaces the current \ref data with the provided \a data.
If \a copy is set to true, the \a data object will only be copied. if false, the color map
takes ownership of the passed data and replaces the internal data pointer with it. This is
significantly faster than copying for large datasets.
*/
void QCPColorMap::setData(QCPColorMapData *data, bool copy)
{
if (mMapData == data)
{
qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
return;
}
if (copy)
{
*mMapData = *data;
} else
{
delete mMapData;
mMapData = data;
}
mMapImageInvalidated = true;
}
/*!
Sets the data range of this color map to \a dataRange. The data range defines which data values
are mapped to the color gradient.
To make the data range span the full range of the data set, use \ref rescaleDataRange.
\see QCPColorScale::setDataRange
*/
void QCPColorMap::setDataRange(const QCPRange &dataRange)
{
if (!QCPRange::validRange(dataRange)) return;
if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
{
if (mDataScaleType == QCPAxis::stLogarithmic)
mDataRange = dataRange.sanitizedForLogScale();
else
mDataRange = dataRange.sanitizedForLinScale();
mMapImageInvalidated = true;
emit dataRangeChanged(mDataRange);
}
}
/*!
Sets whether the data is correlated with the color gradient linearly or logarithmically.
\see QCPColorScale::setDataScaleType
*/
void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType)
{
if (mDataScaleType != scaleType)
{
mDataScaleType = scaleType;
mMapImageInvalidated = true;
emit dataScaleTypeChanged(mDataScaleType);
if (mDataScaleType == QCPAxis::stLogarithmic)
setDataRange(mDataRange.sanitizedForLogScale());
}
}
/*!
Sets the color gradient that is used to represent the data. For more details on how to create an
own gradient or use one of the preset gradients, see \ref QCPColorGradient.
The colors defined by the gradient will be used to represent data values in the currently set
data range, see \ref setDataRange. Data points that are outside this data range will either be
colored uniformly with the respective gradient boundary color, or the gradient will repeat,
depending on \ref QCPColorGradient::setPeriodic.
\see QCPColorScale::setGradient
*/
void QCPColorMap::setGradient(const QCPColorGradient &gradient)
{
if (mGradient != gradient)
{
mGradient = gradient;
mMapImageInvalidated = true;
emit gradientChanged(mGradient);
}
}
/*!
Sets whether the color map image shall use bicubic interpolation when displaying the color map
shrinked or expanded, and not at a 1:1 pixel-to-data scale.
\image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled"
*/
void QCPColorMap::setInterpolate(bool enabled)
{
mInterpolate = enabled;
mMapImageInvalidated = true; // because oversampling factors might need to change
}
/*!
Sets whether the outer most data rows and columns are clipped to the specified key and value
range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange).
if \a enabled is set to false, the data points at the border of the color map are drawn with the
same width and height as all other data points. Since the data points are represented by
rectangles of one color centered on the data coordinate, this means that the shown color map
extends by half a data point over the specified key/value range in each direction.
\image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled"
*/
void QCPColorMap::setTightBoundary(bool enabled)
{
mTightBoundary = enabled;
}
/*!
Associates the color scale \a colorScale with this color map.
This means that both the color scale and the color map synchronize their gradient, data range and
data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps
can be associated with one single color scale. This causes the color maps to also synchronize
those properties, via the mutual color scale.
This function causes the color map to adopt the current color gradient, data range and data scale
type of \a colorScale. After this call, you may change these properties at either the color map
or the color scale, and the setting will be applied to both.
Pass \c nullptr as \a colorScale to disconnect the color scale from this color map again.
*/
void QCPColorMap::setColorScale(QCPColorScale *colorScale)
{
if (mColorScale) // unconnect signals from old color scale
{
disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
}
mColorScale = colorScale;
if (mColorScale) // connect signals to new color scale
{
setGradient(mColorScale.data()->gradient());
setDataRange(mColorScale.data()->dataRange());
setDataScaleType(mColorScale.data()->dataScaleType());
connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
}
}
/*!
Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the
current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods,
only for the third data dimension of the color map.
The minimum and maximum values of the data set are buffered in the internal QCPColorMapData
instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref
QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For
performance reasons, however, they are only updated in an expanding fashion. So the buffered
maximum can only increase and the buffered minimum can only decrease. In consequence, changes to
the data that actually lower the maximum of the data set (by overwriting the cell holding the
current maximum with a smaller value), aren't recognized and the buffered maximum overestimates
the true maximum of the data set. The same happens for the buffered minimum. To recalculate the
true minimum and maximum by explicitly looking at each cell, the method
QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a
recalculateDataBounds calls this method before setting the data range to the buffered minimum and
maximum.
\see setDataRange
*/
void QCPColorMap::rescaleDataRange(bool recalculateDataBounds)
{
if (recalculateDataBounds)
mMapData->recalculateDataBounds();
setDataRange(mMapData->dataBounds());
}
/*!
Takes the current appearance of the color map and updates the legend icon, which is used to
represent this color map in the legend (see \ref QCPLegend).
The \a transformMode specifies whether the rescaling is done by a faster, low quality image
scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm
(Qt::SmoothTransformation).
The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to
the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured
legend icon size, the thumb will be rescaled during drawing of the legend item.
\see setDataRange
*/
void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize)
{
if (mMapImage.isNull() && !data()->isEmpty())
updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet)
if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again
{
bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode);
}
}
/* inherits documentation from base class */
double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if ((onlySelectable && mSelectable == QCP::stNone) || mMapData->isEmpty())
return -1;
if (!mKeyAxis || !mValueAxis)
return -1;
if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
{
double posKey = 0.0, posValue = 0.0;
pixelsToCoords(pos, posKey, posValue);
if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue))
{
if (details)
details->setValue(QCPDataSelection(QCPDataRange(0, 1))); // temporary solution, to facilitate whole-plottable selection. Replace in future version with segmented 2D selection.
return mParentPlot->selectionTolerance()*0.99;
}
}
return -1;
}
/* inherits documentation from base class */
QCPRange QCPColorMap::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
{
foundRange = true;
QCPRange result = mMapData->keyRange();
result.normalize();
if (inSignDomain == QCP::sdPositive)
{
if (result.lower <= 0 && result.upper > 0)
result.lower = result.upper*1e-3;
else if (result.lower <= 0 && result.upper <= 0)
foundRange = false;
} else if (inSignDomain == QCP::sdNegative)
{
if (result.upper >= 0 && result.lower < 0)
result.upper = result.lower*1e-3;
else if (result.upper >= 0 && result.lower >= 0)
foundRange = false;
}
return result;
}
/* inherits documentation from base class */
QCPRange QCPColorMap::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
{
if (inKeyRange != QCPRange())
{
if (mMapData->keyRange().upper < inKeyRange.lower || mMapData->keyRange().lower > inKeyRange.upper)
{
foundRange = false;
return {};
}
}
foundRange = true;
QCPRange result = mMapData->valueRange();
result.normalize();
if (inSignDomain == QCP::sdPositive)
{
if (result.lower <= 0 && result.upper > 0)
result.lower = result.upper*1e-3;
else if (result.lower <= 0 && result.upper <= 0)
foundRange = false;
} else if (inSignDomain == QCP::sdNegative)
{
if (result.upper >= 0 && result.lower < 0)
result.upper = result.lower*1e-3;
else if (result.upper >= 0 && result.lower >= 0)
foundRange = false;
}
return result;
}
/*! \internal
Updates the internal map image buffer by going through the internal \ref QCPColorMapData and
turning the data values into color pixels with \ref QCPColorGradient::colorize.
This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image
has been invalidated for a different reason (e.g. a change of the data range with \ref
setDataRange).
If the map cell count is low, the image created will be oversampled in order to avoid a
QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images
without smooth transform enabled. Accordingly, oversampling isn't performed if \ref
setInterpolate is true.
*/
void QCPColorMap::updateMapImage()
{
QCPAxis *keyAxis = mKeyAxis.data();
if (!keyAxis) return;
if (mMapData->isEmpty()) return;
const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
const int keySize = mMapData->keySize();
const int valueSize = mMapData->valueSize();
int keyOversamplingFactor = mInterpolate ? 1 : int(1.0+100.0/double(keySize)); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on
int valueOversamplingFactor = mInterpolate ? 1 : int(1.0+100.0/double(valueSize)); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on
// resize mMapImage to correct dimensions including possible oversampling factors, according to key/value axes orientation:
if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.width() != keySize*keyOversamplingFactor || mMapImage.height() != valueSize*valueOversamplingFactor))
mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), format);
else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor))
mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), format);
if (mMapImage.isNull())
{
qDebug() << Q_FUNC_INFO << "Couldn't create map image (possibly too large for memory)";
mMapImage = QImage(QSize(10, 10), format);
mMapImage.fill(Qt::black);
} else
{
QImage *localMapImage = &mMapImage; // this is the image on which the colorization operates. Either the final mMapImage, or if we need oversampling, mUndersampledMapImage
if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
{
// resize undersampled map image to actual key/value cell sizes:
if (keyAxis->orientation() == Qt::Horizontal && (mUndersampledMapImage.width() != keySize || mUndersampledMapImage.height() != valueSize))
mUndersampledMapImage = QImage(QSize(keySize, valueSize), format);
else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize))
mUndersampledMapImage = QImage(QSize(valueSize, keySize), format);
localMapImage = &mUndersampledMapImage; // make the colorization run on the undersampled image
} else if (!mUndersampledMapImage.isNull())
mUndersampledMapImage = QImage(); // don't need oversampling mechanism anymore (map size has changed) but mUndersampledMapImage still has nonzero size, free it
const double *rawData = mMapData->mData;
const unsigned char *rawAlpha = mMapData->mAlpha;
if (keyAxis->orientation() == Qt::Horizontal)
{
const int lineCount = valueSize;
const int rowCount = keySize;
for (int line=0; line<lineCount; ++line)
{
QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system)
if (rawAlpha)
mGradient.colorize(rawData+line*rowCount, rawAlpha+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
else
mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
}
} else // keyAxis->orientation() == Qt::Vertical
{
const int lineCount = keySize;
const int rowCount = valueSize;
for (int line=0; line<lineCount; ++line)
{
QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system)
if (rawAlpha)
mGradient.colorize(rawData+line, rawAlpha+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
else
mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
}
}
if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
{
if (keyAxis->orientation() == Qt::Horizontal)
mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
else
mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
}
}
mMapData->mDataModified = false;
mMapImageInvalidated = false;
}
/* inherits documentation from base class */
void QCPColorMap::draw(QCPPainter *painter)
{
if (mMapData->isEmpty()) return;
if (!mKeyAxis || !mValueAxis) return;
applyDefaultAntialiasingHint(painter);
if (mMapData->mDataModified || mMapImageInvalidated)
updateMapImage();
// use buffer if painting vectorized (PDF):
const bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized);
QCPPainter *localPainter = painter; // will be redirected to paint on mapBuffer if painting vectorized
QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map portion/buffer will end up in
QPixmap mapBuffer;
if (useBuffer)
{
const double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps
mapBufferTarget = painter->clipRegion().boundingRect();
mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize());
mapBuffer.fill(Qt::transparent);
localPainter = new QCPPainter(&mapBuffer);
localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio);
localPainter->translate(-mapBufferTarget.topLeft());
}
QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
// extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary):
double halfCellWidth = 0; // in pixels
double halfCellHeight = 0; // in pixels
if (keyAxis()->orientation() == Qt::Horizontal)
{
if (mMapData->keySize() > 1)
halfCellWidth = 0.5*imageRect.width()/double(mMapData->keySize()-1);
if (mMapData->valueSize() > 1)
halfCellHeight = 0.5*imageRect.height()/double(mMapData->valueSize()-1);
} else // keyAxis orientation is Qt::Vertical
{
if (mMapData->keySize() > 1)
halfCellHeight = 0.5*imageRect.height()/double(mMapData->keySize()-1);
if (mMapData->valueSize() > 1)
halfCellWidth = 0.5*imageRect.width()/double(mMapData->valueSize()-1);
}
imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight);
const bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
const bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
const bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform);
localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate);
QRegion clipBackup;
if (mTightBoundary)
{
clipBackup = localPainter->clipRegion();
QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
localPainter->setClipRect(tightClipRect, Qt::IntersectClip);
}
localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY));
if (mTightBoundary)
localPainter->setClipRegion(clipBackup);
localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup);
if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter
{
delete localPainter;
painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer);
}
}
/* inherits documentation from base class */
void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
applyDefaultAntialiasingHint(painter);
// draw map thumbnail:
if (!mLegendIcon.isNull())
{
QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation);
QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height());
iconRect.moveCenter(rect.center());
painter->drawPixmap(iconRect.topLeft(), scaledIcon);
}
/*
// draw frame:
painter->setBrush(Qt::NoBrush);
painter->setPen(Qt::black);
painter->drawRect(rect.adjusted(1, 1, 0, 0));
*/
}
/* end of 'src/plottables/plottable-colormap.cpp' */
/* including file 'src/plottables/plottable-financial.cpp' */
/* modified 2022-11-06T12:45:57, size 42914 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPFinancialData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPFinancialData
\brief Holds the data of one single data point for QCPFinancial.
The stored data is:
\li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
\li \a open: The opening value at the data point (this is the \a mainValue)
\li \a high: The high/maximum value at the data point
\li \a low: The low/minimum value at the data point
\li \a close: The closing value at the data point
The container for storing multiple data points is \ref QCPFinancialDataContainer. It is a typedef
for \ref QCPDataContainer with \ref QCPFinancialData as the DataType template parameter. See the
documentation there for an explanation regarding the data type's generic methods.
\see QCPFinancialDataContainer
*/
/* start documentation of inline functions */
/*! \fn double QCPFinancialData::sortKey() const
Returns the \a key member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn static QCPFinancialData QCPFinancialData::fromSortKey(double sortKey)
Returns a data point with the specified \a sortKey. All other members are set to zero.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn static static bool QCPFinancialData::sortKeyIsMainKey()
Since the member \a key is both the data point key coordinate and the data ordering parameter,
this method returns true.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn double QCPFinancialData::mainKey() const
Returns the \a key member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn double QCPFinancialData::mainValue() const
Returns the \a open member of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/*! \fn QCPRange QCPFinancialData::valueRange() const
Returns a QCPRange spanning from the \a low to the \a high value of this data point.
For a general explanation of what this method is good for in the context of the data container,
see the documentation of \ref QCPDataContainer.
*/
/* end documentation of inline functions */
/*!
Constructs a data point with key and all values set to zero.
*/
QCPFinancialData::QCPFinancialData() :
key(0),
open(0),
high(0),
low(0),
close(0)
{
}
/*!
Constructs a data point with the specified \a key and OHLC values.
*/
QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) :
key(key),
open(open),
high(high),
low(low),
close(close)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPFinancial
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPFinancial
\brief A plottable representing a financial stock chart
\image html QCPFinancial.png
This plottable represents time series data binned to certain intervals, mainly used for stock
charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be
set via \ref setChartStyle.
The data is passed via \ref setData as a set of open/high/low/close values at certain keys
(typically times). This means the data must be already binned appropriately. If data is only
available as a series of values (e.g. \a price against \a time), you can use the static
convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed
to \ref setData.
The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and \ref
setWidthType. A typical choice is to set the width type to \ref wtPlotCoords (the default) and
the width to (or slightly less than) one time bin interval width.
\section qcpfinancial-appearance Changing the appearance
Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored,
lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush).
If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are
represented with a different pen and brush than negative changes (\a close < \a open). These can
be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref
setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection
however, the normal selected pen/brush (provided by the \ref selectionDecorator) is used,
irrespective of whether the chart is single- or two-colored.
\section qcpfinancial-usage Usage
Like all data representing objects in QCustomPlot, the QCPFinancial is a plottable
(QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
(QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
Usually, you first create an instance:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-1
which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot
instance takes ownership of the plottable, so do not delete it manually but use
QCustomPlot::removePlottable() instead. The newly created plottable can be modified, e.g.:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-2
Here we have used the static helper method \ref timeSeriesToOhlc, to turn a time-price data
series into a 24-hour binned open-high-low-close data series as QCPFinancial uses.
*/
/* start of documentation of inline functions */
/*! \fn QCPFinancialDataContainer *QCPFinancial::data() const
Returns a pointer to the internal data storage of type \ref QCPFinancialDataContainer. You may
use it to directly manipulate the data, which may be more convenient and faster than using the
regular \ref setData or \ref addData methods, in certain situations.
*/
/* end of documentation of inline functions */
/*!
Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
the same orientation. If either of these restrictions is violated, a corresponding message is
printed to the debug output (qDebug), the construction is not aborted, though.
The created QCPFinancial is automatically registered with the QCustomPlot instance inferred from \a
keyAxis. This QCustomPlot instance takes ownership of the QCPFinancial, so do not delete it manually
but use QCustomPlot::removePlottable() instead.
*/
QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable1D<QCPFinancialData>(keyAxis, valueAxis),
mChartStyle(csCandlestick),
mWidth(0.5),
mWidthType(wtPlotCoords),
mTwoColored(true),
mBrushPositive(QBrush(QColor(50, 160, 0))),
mBrushNegative(QBrush(QColor(180, 0, 15))),
mPenPositive(QPen(QColor(40, 150, 0))),
mPenNegative(QPen(QColor(170, 5, 5)))
{
mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
}
QCPFinancial::~QCPFinancial()
{
}
/*! \overload
Replaces the current data container with the provided \a data container.
Since a QSharedPointer is used, multiple QCPFinancials may share the same data container safely.
Modifying the data in the container will then affect all financials that share the container.
Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-1
If you do not wish to share containers, but create a copy from an existing container, rather use
the \ref QCPDataContainer<DataType>::set method on the financial's data container directly:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-2
\see addData, timeSeriesToOhlc
*/
void QCPFinancial::setData(QSharedPointer<QCPFinancialDataContainer> data)
{
mDataContainer = data;
}
/*! \overload
Replaces the current data with the provided points in \a keys, \a open, \a high, \a low and \a
close. The provided vectors should have equal length. Else, the number of added points will be
the size of the smallest vector.
If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
can set \a alreadySorted to true, to improve performance by saving a sorting run.
\see addData, timeSeriesToOhlc
*/
void QCPFinancial::setData(const QVector<double> &keys, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close, bool alreadySorted)
{
mDataContainer->clear();
addData(keys, open, high, low, close, alreadySorted);
}
/*!
Sets which representation style shall be used to display the OHLC data.
*/
void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style)
{
mChartStyle = style;
}
/*!
Sets the width of the individual bars/candlesticks to \a width in plot key coordinates.
A typical choice is to set it to (or slightly less than) one bin interval width.
*/
void QCPFinancial::setWidth(double width)
{
mWidth = width;
}
/*!
Sets how the width of the financial bars is defined. See the documentation of \ref WidthType for
an explanation of the possible values for \a widthType.
The default value is \ref wtPlotCoords.
\see setWidth
*/
void QCPFinancial::setWidthType(QCPFinancial::WidthType widthType)
{
mWidthType = widthType;
}
/*!
Sets whether this chart shall contrast positive from negative trends per data point by using two
separate colors to draw the respective bars/candlesticks.
If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
setBrush).
\see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative
*/
void QCPFinancial::setTwoColored(bool twoColored)
{
mTwoColored = twoColored;
}
/*!
If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
of data points with a positive trend (i.e. bars/candlesticks with close >= open).
If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
setBrush).
\see setBrushNegative, setPenPositive, setPenNegative
*/
void QCPFinancial::setBrushPositive(const QBrush &brush)
{
mBrushPositive = brush;
}
/*!
If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
of data points with a negative trend (i.e. bars/candlesticks with close < open).
If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
setBrush).
\see setBrushPositive, setPenNegative, setPenPositive
*/
void QCPFinancial::setBrushNegative(const QBrush &brush)
{
mBrushNegative = brush;
}
/*!
If \ref setTwoColored is set to true, this function controls the pen that is used to draw
outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open).
If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
setBrush).
\see setPenNegative, setBrushPositive, setBrushNegative
*/
void QCPFinancial::setPenPositive(const QPen &pen)
{
mPenPositive = pen;
}
/*!
If \ref setTwoColored is set to true, this function controls the pen that is used to draw
outlines of data points with a negative trend (i.e. bars/candlesticks with close < open).
If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
setBrush).
\see setPenPositive, setBrushNegative, setBrushPositive
*/
void QCPFinancial::setPenNegative(const QPen &pen)
{
mPenNegative = pen;
}
/*! \overload
Adds the provided points in \a keys, \a open, \a high, \a low and \a close to the current data.
The provided vectors should have equal length. Else, the number of added points will be the size
of the smallest vector.
If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
can set \a alreadySorted to true, to improve performance by saving a sorting run.
Alternatively, you can also access and modify the data directly via the \ref data method, which
returns a pointer to the internal data container.
\see timeSeriesToOhlc
*/
void QCPFinancial::addData(const QVector<double> &keys, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close, bool alreadySorted)
{
if (keys.size() != open.size() || open.size() != high.size() || high.size() != low.size() || low.size() != close.size() || close.size() != keys.size())
qDebug() << Q_FUNC_INFO << "keys, open, high, low, close have different sizes:" << keys.size() << open.size() << high.size() << low.size() << close.size();
const int n = static_cast<int>(qMin(keys.size(), qMin(open.size(), qMin(high.size(), qMin(low.size(), close.size())))));
QVector<QCPFinancialData> tempData(n);
QVector<QCPFinancialData>::iterator it = tempData.begin();
const QVector<QCPFinancialData>::iterator itEnd = tempData.end();
int i = 0;
while (it != itEnd)
{
it->key = keys[i];
it->open = open[i];
it->high = high[i];
it->low = low[i];
it->close = close[i];
++it;
++i;
}
mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
}
/*! \overload
Adds the provided data point as \a key, \a open, \a high, \a low and \a close to the current
data.
Alternatively, you can also access and modify the data directly via the \ref data method, which
returns a pointer to the internal data container.
\see timeSeriesToOhlc
*/
void QCPFinancial::addData(double key, double open, double high, double low, double close)
{
mDataContainer->add(QCPFinancialData(key, open, high, low, close));
}
/*!
\copydoc QCPPlottableInterface1D::selectTestRect
*/
QCPDataSelection QCPFinancial::selectTestRect(const QRectF &rect, bool onlySelectable) const
{
QCPDataSelection result;
if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
return result;
if (!mKeyAxis || !mValueAxis)
return result;
QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
getVisibleDataBounds(visibleBegin, visibleEnd);
for (QCPFinancialDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
{
if (rect.intersects(selectionHitBox(it)))
result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
}
result.simplify();
return result;
}
/*!
Implements a selectTest specific to this plottable's point geometry.
If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
point to \a pos.
\seebaseclassmethod \ref QCPAbstractPlottable::selectTest
*/
double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
return -1;
if (!mKeyAxis || !mValueAxis)
return -1;
if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
{
// get visible data range:
QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
QCPFinancialDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
getVisibleDataBounds(visibleBegin, visibleEnd);
// perform select test according to configured style:
double result = -1;
switch (mChartStyle)
{
case QCPFinancial::csOhlc:
result = ohlcSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
case QCPFinancial::csCandlestick:
result = candlestickSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
}
if (details)
{
int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
}
return result;
}
return -1;
}
/* inherits documentation from base class */
QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
{
QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
// determine exact range by including width of bars/flags:
if (foundRange)
{
if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0)
range.lower -= mWidth*0.5;
if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0)
range.upper += mWidth*0.5;
}
return range;
}
/* inherits documentation from base class */
QCPRange QCPFinancial::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
{
return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
}
/*!
A convenience function that converts time series data (\a value against \a time) to OHLC binned
data points. The return value can then be passed on to \ref QCPFinancialDataContainer::set(const
QCPFinancialDataContainer&).
The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given.
For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour
each, set \a timeBinSize to 3600.
\a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The
value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys.
It merely defines the mathematical offset/phase of the bins that will be used to process the
data.
*/
QCPFinancialDataContainer QCPFinancial::timeSeriesToOhlc(const QVector<double> &time, const QVector<double> &value, double timeBinSize, double timeBinOffset)
{
QCPFinancialDataContainer data;
int count = static_cast<int>(qMin(time.size(), value.size()));
if (count == 0)
return QCPFinancialDataContainer();
QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first());
int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5);
for (int i=0; i<count; ++i)
{
int index = qFloor((time.at(i)-timeBinOffset)/timeBinSize+0.5);
if (currentBinIndex == index) // data point still in current bin, extend high/low:
{
if (value.at(i) < currentBinData.low) currentBinData.low = value.at(i);
if (value.at(i) > currentBinData.high) currentBinData.high = value.at(i);
if (i == count-1) // last data point is in current bin, finalize bin:
{
currentBinData.close = value.at(i);
currentBinData.key = timeBinOffset+(index)*timeBinSize;
data.add(currentBinData);
}
} else // data point not anymore in current bin, set close of old and open of new bin, and add old to map:
{
// finalize current bin:
currentBinData.close = value.at(i-1);
currentBinData.key = timeBinOffset+(index-1)*timeBinSize;
data.add(currentBinData);
// start next bin:
currentBinIndex = index;
currentBinData.open = value.at(i);
currentBinData.high = value.at(i);
currentBinData.low = value.at(i);
}
}
return data;
}
/* inherits documentation from base class */
void QCPFinancial::draw(QCPPainter *painter)
{
// get visible data range:
QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
getVisibleDataBounds(visibleBegin, visibleEnd);
// loop over and draw segments of unselected/selected data:
QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
getDataSegments(selectedSegments, unselectedSegments);
allSegments << unselectedSegments << selectedSegments;
for (int i=0; i<allSegments.size(); ++i)
{
bool isSelectedSegment = i >= unselectedSegments.size();
QCPFinancialDataContainer::const_iterator begin = visibleBegin;
QCPFinancialDataContainer::const_iterator end = visibleEnd;
mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
if (begin == end)
continue;
// draw data segment according to configured style:
switch (mChartStyle)
{
case QCPFinancial::csOhlc:
drawOhlcPlot(painter, begin, end, isSelectedSegment); break;
case QCPFinancial::csCandlestick:
drawCandlestickPlot(painter, begin, end, isSelectedSegment); break;
}
}
// draw other selection decoration that isn't just line/scatter pens and brushes:
if (mSelectionDecorator)
mSelectionDecorator->drawDecoration(painter, selection());
}
/* inherits documentation from base class */
void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing
if (mChartStyle == csOhlc)
{
if (mTwoColored)
{
// draw upper left half icon with positive color:
painter->setBrush(mBrushPositive);
painter->setPen(mPenPositive);
painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
// draw bottom right half icon with negative color:
painter->setBrush(mBrushNegative);
painter->setPen(mPenNegative);
painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
} else
{
painter->setBrush(mBrush);
painter->setPen(mPen);
painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
}
} else if (mChartStyle == csCandlestick)
{
if (mTwoColored)
{
// draw upper left half icon with positive color:
painter->setBrush(mBrushPositive);
painter->setPen(mPenPositive);
painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
// draw bottom right half icon with negative color:
painter->setBrush(mBrushNegative);
painter->setPen(mPenNegative);
painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
} else
{
painter->setBrush(mBrush);
painter->setPen(mPen);
painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
}
}
}
/*! \internal
Draws the data from \a begin to \a end-1 as OHLC bars with the provided \a painter.
This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc.
*/
void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (keyAxis->orientation() == Qt::Horizontal)
{
for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
{
if (isSelected && mSelectionDecorator)
mSelectionDecorator->applyPen(painter);
else if (mTwoColored)
painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
else
painter->setPen(mPen);
double keyPixel = keyAxis->coordToPixel(it->key);
double openPixel = valueAxis->coordToPixel(it->open);
double closePixel = valueAxis->coordToPixel(it->close);
// draw backbone:
painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(it->low)));
// draw open:
double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
painter->drawLine(QPointF(keyPixel-pixelWidth, openPixel), QPointF(keyPixel, openPixel));
// draw close:
painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+pixelWidth, closePixel));
}
} else
{
for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
{
if (isSelected && mSelectionDecorator)
mSelectionDecorator->applyPen(painter);
else if (mTwoColored)
painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
else
painter->setPen(mPen);
double keyPixel = keyAxis->coordToPixel(it->key);
double openPixel = valueAxis->coordToPixel(it->open);
double closePixel = valueAxis->coordToPixel(it->close);
// draw backbone:
painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(it->low), keyPixel));
// draw open:
double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
painter->drawLine(QPointF(openPixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel));
// draw close:
painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+pixelWidth));
}
}
}
/*! \internal
Draws the data from \a begin to \a end-1 as Candlesticks with the provided \a painter.
This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick.
*/
void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (keyAxis->orientation() == Qt::Horizontal)
{
for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
{
if (isSelected && mSelectionDecorator)
{
mSelectionDecorator->applyPen(painter);
mSelectionDecorator->applyBrush(painter);
} else if (mTwoColored)
{
painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
} else
{
painter->setPen(mPen);
painter->setBrush(mBrush);
}
double keyPixel = keyAxis->coordToPixel(it->key);
double openPixel = valueAxis->coordToPixel(it->open);
double closePixel = valueAxis->coordToPixel(it->close);
// draw high:
painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
// draw low:
painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
// draw open-close box:
double pixelWidth = getPixelWidth(it->key, keyPixel);
painter->drawRect(QRectF(QPointF(keyPixel-pixelWidth, closePixel), QPointF(keyPixel+pixelWidth, openPixel)));
}
} else // keyAxis->orientation() == Qt::Vertical
{
for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
{
if (isSelected && mSelectionDecorator)
{
mSelectionDecorator->applyPen(painter);
mSelectionDecorator->applyBrush(painter);
} else if (mTwoColored)
{
painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
} else
{
painter->setPen(mPen);
painter->setBrush(mBrush);
}
double keyPixel = keyAxis->coordToPixel(it->key);
double openPixel = valueAxis->coordToPixel(it->open);
double closePixel = valueAxis->coordToPixel(it->close);
// draw high:
painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
// draw low:
painter->drawLine(QPointF(valueAxis->coordToPixel(it->low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
// draw open-close box:
double pixelWidth = getPixelWidth(it->key, keyPixel);
painter->drawRect(QRectF(QPointF(closePixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel+pixelWidth)));
}
}
}
/*! \internal
This function is used to determine the width of the bar at coordinate \a key, according to the
specified width (\ref setWidth) and width type (\ref setWidthType). Provide the pixel position of
\a key in \a keyPixel (because usually this was already calculated via \ref QCPAxis::coordToPixel
when this function is called).
It returns the number of pixels the bar extends to higher keys, relative to the \a key
coordinate. So with a non-reversed horizontal axis, the return value is positive. With a reversed
horizontal axis, the return value is negative. This is important so the open/close flags on the
\ref csOhlc bar are drawn to the correct side.
*/
double QCPFinancial::getPixelWidth(double key, double keyPixel) const
{
double result = 0;
switch (mWidthType)
{
case wtAbsolute:
{
if (mKeyAxis)
result = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
break;
}
case wtAxisRectRatio:
{
if (mKeyAxis && mKeyAxis.data()->axisRect())
{
if (mKeyAxis.data()->orientation() == Qt::Horizontal)
result = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
else
result = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
} else
qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
break;
}
case wtPlotCoords:
{
if (mKeyAxis)
result = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
else
qDebug() << Q_FUNC_INFO << "No key axis defined";
break;
}
}
return result;
}
/*! \internal
This method is a helper function for \ref selectTest. It is used to test for selection when the
chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end.
Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
representation of the plottable, and \a closestDataPoint will point to the respective data point.
*/
double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
{
closestDataPoint = mDataContainer->constEnd();
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
double minDistSqr = (std::numeric_limits<double>::max)();
if (keyAxis->orientation() == Qt::Horizontal)
{
for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
{
double keyPixel = keyAxis->coordToPixel(it->key);
// calculate distance to backbone:
double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)));
if (currentDistSqr < minDistSqr)
{
minDistSqr = currentDistSqr;
closestDataPoint = it;
}
}
} else // keyAxis->orientation() == Qt::Vertical
{
for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
{
double keyPixel = keyAxis->coordToPixel(it->key);
// calculate distance to backbone:
double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel));
if (currentDistSqr < minDistSqr)
{
minDistSqr = currentDistSqr;
closestDataPoint = it;
}
}
}
return qSqrt(minDistSqr);
}
/*! \internal
This method is a helper function for \ref selectTest. It is used to test for selection when the
chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a
end.
Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
representation of the plottable, and \a closestDataPoint will point to the respective data point.
*/
double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
{
closestDataPoint = mDataContainer->constEnd();
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
double minDistSqr = (std::numeric_limits<double>::max)();
if (keyAxis->orientation() == Qt::Horizontal)
{
for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
{
double currentDistSqr;
// determine whether pos is in open-close-box:
QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
QCPRange boxValueRange(it->close, it->open);
double posKey = 0.0, posValue = 0.0;
pixelsToCoords(pos, posKey, posValue);
if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
{
currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
} else
{
// calculate distance to high/low lines:
double keyPixel = keyAxis->coordToPixel(it->key);
double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
}
if (currentDistSqr < minDistSqr)
{
minDistSqr = currentDistSqr;
closestDataPoint = it;
}
}
} else // keyAxis->orientation() == Qt::Vertical
{
for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
{
double currentDistSqr;
// determine whether pos is in open-close-box:
QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
QCPRange boxValueRange(it->close, it->open);
double posKey = 0.0, posValue = 0.0;
pixelsToCoords(pos, posKey, posValue);
if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
{
currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
} else
{
// calculate distance to high/low lines:
double keyPixel = keyAxis->coordToPixel(it->key);
double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
}
if (currentDistSqr < minDistSqr)
{
minDistSqr = currentDistSqr;
closestDataPoint = it;
}
}
}
return qSqrt(minDistSqr);
}
/*! \internal
called by the drawing methods to determine which data (key) range is visible at the current key
axis range setting, so only that needs to be processed.
\a begin returns an iterator to the lowest data point that needs to be taken into account when
plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
begin may still be just outside the visible range.
\a end returns the iterator just above the highest data point that needs to be taken into
account. Same as before, \a end may also lie just outside of the visible range
if the plottable contains no data, both \a begin and \a end point to \c constEnd.
*/
void QCPFinancial::getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const
{
if (!mKeyAxis)
{
qDebug() << Q_FUNC_INFO << "invalid key axis";
begin = mDataContainer->constEnd();
end = mDataContainer->constEnd();
return;
}
begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of ohlc/candlestick to include partially visible data points
end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of ohlc/candlestick to include partially visible data points
}
/*! \internal
Returns the hit box in pixel coordinates that will be used for data selection with the selection
rect (\ref selectTestRect), of the data point given by \a it.
*/
QRectF QCPFinancial::selectionHitBox(QCPFinancialDataContainer::const_iterator it) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
double keyPixel = keyAxis->coordToPixel(it->key);
double highPixel = valueAxis->coordToPixel(it->high);
double lowPixel = valueAxis->coordToPixel(it->low);
double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it->key-mWidth*0.5);
if (keyAxis->orientation() == Qt::Horizontal)
return QRectF(keyPixel-keyWidthPixels, highPixel, keyWidthPixels*2, lowPixel-highPixel).normalized();
else
return QRectF(highPixel, keyPixel-keyWidthPixels, lowPixel-highPixel, keyWidthPixels*2).normalized();
}
/* end of 'src/plottables/plottable-financial.cpp' */
/* including file 'src/plottables/plottable-errorbar.cpp' */
/* modified 2022-11-06T12:45:56, size 37679 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPErrorBarsData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPErrorBarsData
\brief Holds the data of one single error bar for QCPErrorBars.
The stored data is:
\li \a errorMinus: how much the error bar extends towards negative coordinates from the data
point position
\li \a errorPlus: how much the error bar extends towards positive coordinates from the data point
position
The container for storing the error bar information is \ref QCPErrorBarsDataContainer. It is a
typedef for <tt>QVector<QCPErrorBarsData></tt>.
\see QCPErrorBarsDataContainer
*/
/*!
Constructs an error bar with errors set to zero.
*/
QCPErrorBarsData::QCPErrorBarsData() :
errorMinus(0),
errorPlus(0)
{
}
/*!
Constructs an error bar with equal \a error in both negative and positive direction.
*/
QCPErrorBarsData::QCPErrorBarsData(double error) :
errorMinus(error),
errorPlus(error)
{
}
/*!
Constructs an error bar with negative and positive errors set to \a errorMinus and \a errorPlus,
respectively.
*/
QCPErrorBarsData::QCPErrorBarsData(double errorMinus, double errorPlus) :
errorMinus(errorMinus),
errorPlus(errorPlus)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPErrorBars
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPErrorBars
\brief A plottable that adds a set of error bars to other plottables.
\image html QCPErrorBars.png
The \ref QCPErrorBars plottable can be attached to other one-dimensional plottables (e.g. \ref
QCPGraph, \ref QCPCurve, \ref QCPBars, etc.) and equips them with error bars.
Use \ref setDataPlottable to define for which plottable the \ref QCPErrorBars shall display the
error bars. The orientation of the error bars can be controlled with \ref setErrorType.
By using \ref setData, you can supply the actual error data, either as symmetric error or
plus/minus asymmetric errors. \ref QCPErrorBars only stores the error data. The absolute
key/value position of each error bar will be adopted from the configured data plottable. The
error data of the \ref QCPErrorBars are associated one-to-one via their index to the data points
of the data plottable. You can directly access and manipulate the error bar data via \ref data.
Set either of the plus/minus errors to NaN (<tt>qQNaN()</tt> or
<tt>std::numeric_limits<double>::quiet_NaN()</tt>) to not show the respective error bar on the data point at
that index.
\section qcperrorbars-appearance Changing the appearance
The appearance of the error bars is defined by the pen (\ref setPen), and the width of the
whiskers (\ref setWhiskerWidth). Further, the error bar backbones may leave a gap around the data
point center to prevent that error bars are drawn too close to or even through scatter points.
This gap size can be controlled via \ref setSymbolGap.
*/
/* start of documentation of inline functions */
/*! \fn QSharedPointer<QCPErrorBarsDataContainer> QCPErrorBars::data() const
Returns a shared pointer to the internal data storage of type \ref QCPErrorBarsDataContainer. You
may use it to directly manipulate the error values, which may be more convenient and faster than
using the regular \ref setData methods.
*/
/* end of documentation of inline functions */
/*!
Constructs an error bars plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
the same orientation. If either of these restrictions is violated, a corresponding message is
printed to the debug output (qDebug), the construction is not aborted, though.
It is also important that the \a keyAxis and \a valueAxis are the same for the error bars
plottable and the data plottable that the error bars shall be drawn on (\ref setDataPlottable).
The created \ref QCPErrorBars is automatically registered with the QCustomPlot instance inferred
from \a keyAxis. This QCustomPlot instance takes ownership of the \ref QCPErrorBars, so do not
delete it manually but use \ref QCustomPlot::removePlottable() instead.
*/
QCPErrorBars::QCPErrorBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable(keyAxis, valueAxis),
mDataContainer(new QVector<QCPErrorBarsData>),
mErrorType(etValueError),
mWhiskerWidth(9),
mSymbolGap(10)
{
setPen(QPen(Qt::black, 0));
setBrush(Qt::NoBrush);
}
QCPErrorBars::~QCPErrorBars()
{
}
/*! \overload
Replaces the current data container with the provided \a data container.
Since a QSharedPointer is used, multiple \ref QCPErrorBars instances may share the same data
container safely. Modifying the data in the container will then affect all \ref QCPErrorBars
instances that share the container. Sharing can be achieved by simply exchanging the data
containers wrapped in shared pointers:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-1
If you do not wish to share containers, but create a copy from an existing container, assign the
data containers directly:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-2
(This uses different notation compared with other plottables, because the \ref QCPErrorBars
uses a \c QVector<QCPErrorBarsData> as its data container, instead of a \ref QCPDataContainer.)
\see addData
*/
void QCPErrorBars::setData(QSharedPointer<QCPErrorBarsDataContainer> data)
{
mDataContainer = data;
}
/*! \overload
Sets symmetrical error values as specified in \a error. The errors will be associated one-to-one
by the data point index to the associated data plottable (\ref setDataPlottable).
You can directly access and manipulate the error bar data via \ref data.
\see addData
*/
void QCPErrorBars::setData(const QVector<double> &error)
{
mDataContainer->clear();
addData(error);
}
/*! \overload
Sets asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
associated one-to-one by the data point index to the associated data plottable (\ref
setDataPlottable).
You can directly access and manipulate the error bar data via \ref data.
\see addData
*/
void QCPErrorBars::setData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
{
mDataContainer->clear();
addData(errorMinus, errorPlus);
}
/*!
Sets the data plottable to which the error bars will be applied. The error values specified e.g.
via \ref setData will be associated one-to-one by the data point index to the data points of \a
plottable. This means that the error bars will adopt the key/value coordinates of the data point
with the same index.
The passed \a plottable must be a one-dimensional plottable, i.e. it must implement the \ref
QCPPlottableInterface1D. Further, it must not be a \ref QCPErrorBars instance itself. If either
of these restrictions is violated, a corresponding qDebug output is generated, and the data
plottable of this \ref QCPErrorBars instance is set to zero.
For proper display, care must also be taken that the key and value axes of the \a plottable match
those configured for this \ref QCPErrorBars instance.
*/
void QCPErrorBars::setDataPlottable(QCPAbstractPlottable *plottable)
{
if (plottable && qobject_cast<QCPErrorBars*>(plottable))
{
mDataPlottable = nullptr;
qDebug() << Q_FUNC_INFO << "can't set another QCPErrorBars instance as data plottable";
return;
}
if (plottable && !plottable->interface1D())
{
mDataPlottable = nullptr;
qDebug() << Q_FUNC_INFO << "passed plottable doesn't implement 1d interface, can't associate with QCPErrorBars";
return;
}
mDataPlottable = plottable;
}
/*!
Sets in which orientation the error bars shall appear on the data points. If your data needs both
error dimensions, create two \ref QCPErrorBars with different \a type.
*/
void QCPErrorBars::setErrorType(ErrorType type)
{
mErrorType = type;
}
/*!
Sets the width of the whiskers (the short bars at the end of the actual error bar backbones) to
\a pixels.
*/
void QCPErrorBars::setWhiskerWidth(double pixels)
{
mWhiskerWidth = pixels;
}
/*!
Sets the gap diameter around the data points that will be left out when drawing the error bar
backbones. This gap prevents that error bars are drawn too close to or even through scatter
points.
*/
void QCPErrorBars::setSymbolGap(double pixels)
{
mSymbolGap = pixels;
}
/*! \overload
Adds symmetrical error values as specified in \a error. The errors will be associated one-to-one
by the data point index to the associated data plottable (\ref setDataPlottable).
You can directly access and manipulate the error bar data via \ref data.
\see setData
*/
void QCPErrorBars::addData(const QVector<double> &error)
{
addData(error, error);
}
/*! \overload
Adds asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
associated one-to-one by the data point index to the associated data plottable (\ref
setDataPlottable).
You can directly access and manipulate the error bar data via \ref data.
\see setData
*/
void QCPErrorBars::addData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
{
if (errorMinus.size() != errorPlus.size())
qDebug() << Q_FUNC_INFO << "minus and plus error vectors have different sizes:" << errorMinus.size() << errorPlus.size();
const int n = static_cast<int>(qMin(errorMinus.size(), errorPlus.size()));
mDataContainer->reserve(n);
for (int i=0; i<n; ++i)
mDataContainer->append(QCPErrorBarsData(errorMinus.at(i), errorPlus.at(i)));
}
/*! \overload
Adds a single symmetrical error bar as specified in \a error. The errors will be associated
one-to-one by the data point index to the associated data plottable (\ref setDataPlottable).
You can directly access and manipulate the error bar data via \ref data.
\see setData
*/
void QCPErrorBars::addData(double error)
{
mDataContainer->append(QCPErrorBarsData(error));
}
/*! \overload
Adds a single asymmetrical error bar as specified in \a errorMinus and \a errorPlus. The errors
will be associated one-to-one by the data point index to the associated data plottable (\ref
setDataPlottable).
You can directly access and manipulate the error bar data via \ref data.
\see setData
*/
void QCPErrorBars::addData(double errorMinus, double errorPlus)
{
mDataContainer->append(QCPErrorBarsData(errorMinus, errorPlus));
}
/* inherits documentation from base class */
int QCPErrorBars::dataCount() const
{
return static_cast<int>(mDataContainer->size());
}
/* inherits documentation from base class */
double QCPErrorBars::dataMainKey(int index) const
{
if (mDataPlottable)
return mDataPlottable->interface1D()->dataMainKey(index);
else
qDebug() << Q_FUNC_INFO << "no data plottable set";
return 0;
}
/* inherits documentation from base class */
double QCPErrorBars::dataSortKey(int index) const
{
if (mDataPlottable)
return mDataPlottable->interface1D()->dataSortKey(index);
else
qDebug() << Q_FUNC_INFO << "no data plottable set";
return 0;
}
/* inherits documentation from base class */
double QCPErrorBars::dataMainValue(int index) const
{
if (mDataPlottable)
return mDataPlottable->interface1D()->dataMainValue(index);
else
qDebug() << Q_FUNC_INFO << "no data plottable set";
return 0;
}
/* inherits documentation from base class */
QCPRange QCPErrorBars::dataValueRange(int index) const
{
if (mDataPlottable)
{
const double value = mDataPlottable->interface1D()->dataMainValue(index);
if (index >= 0 && index < mDataContainer->size() && mErrorType == etValueError)
return {value-mDataContainer->at(index).errorMinus, value+mDataContainer->at(index).errorPlus};
else
return {value, value};
} else
{
qDebug() << Q_FUNC_INFO << "no data plottable set";
return {};
}
}
/* inherits documentation from base class */
QPointF QCPErrorBars::dataPixelPosition(int index) const
{
if (mDataPlottable)
return mDataPlottable->interface1D()->dataPixelPosition(index);
else
qDebug() << Q_FUNC_INFO << "no data plottable set";
return {};
}
/* inherits documentation from base class */
bool QCPErrorBars::sortKeyIsMainKey() const
{
if (mDataPlottable)
{
return mDataPlottable->interface1D()->sortKeyIsMainKey();
} else
{
qDebug() << Q_FUNC_INFO << "no data plottable set";
return true;
}
}
/*!
\copydoc QCPPlottableInterface1D::selectTestRect
*/
QCPDataSelection QCPErrorBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
{
QCPDataSelection result;
if (!mDataPlottable)
return result;
if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
return result;
if (!mKeyAxis || !mValueAxis)
return result;
QCPErrorBarsDataContainer::const_iterator visibleBegin, visibleEnd;
getVisibleDataBounds(visibleBegin, visibleEnd, QCPDataRange(0, dataCount()));
QVector<QLineF> backbones, whiskers;
for (QCPErrorBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
{
backbones.clear();
whiskers.clear();
getErrorBarLines(it, backbones, whiskers);
foreach (const QLineF &backbone, backbones)
{
if (rectIntersectsLine(rect, backbone))
{
result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
break;
}
}
}
result.simplify();
return result;
}
/* inherits documentation from base class */
int QCPErrorBars::findBegin(double sortKey, bool expandedRange) const
{
if (mDataPlottable)
{
if (mDataContainer->isEmpty())
return 0;
int beginIndex = mDataPlottable->interface1D()->findBegin(sortKey, expandedRange);
if (beginIndex >= mDataContainer->size())
beginIndex = static_cast<int>(mDataContainer->size())-1;
return beginIndex;
} else
qDebug() << Q_FUNC_INFO << "no data plottable set";
return 0;
}
/* inherits documentation from base class */
int QCPErrorBars::findEnd(double sortKey, bool expandedRange) const
{
if (mDataPlottable)
{
if (mDataContainer->isEmpty())
return 0;
int endIndex = mDataPlottable->interface1D()->findEnd(sortKey, expandedRange);
if (endIndex > mDataContainer->size())
endIndex = static_cast<int>(mDataContainer->size());
return endIndex;
} else
qDebug() << Q_FUNC_INFO << "no data plottable set";
return 0;
}
/*!
Implements a selectTest specific to this plottable's point geometry.
If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
point to \a pos.
\seebaseclassmethod \ref QCPAbstractPlottable::selectTest
*/
double QCPErrorBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
if (!mDataPlottable) return -1;
if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
return -1;
if (!mKeyAxis || !mValueAxis)
return -1;
if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
{
QCPErrorBarsDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
double result = pointDistance(pos, closestDataPoint);
if (details)
{
int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
}
return result;
} else
return -1;
}
/* inherits documentation from base class */
void QCPErrorBars::draw(QCPPainter *painter)
{
if (!mDataPlottable) return;
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
// if the sort key isn't the main key, we must check the visibility for each data point/error bar individually
// (getVisibleDataBounds applies range restriction, but otherwise can only return full data range):
bool checkPointVisibility = !mDataPlottable->interface1D()->sortKeyIsMainKey();
// check data validity if flag set:
#ifdef QCUSTOMPLOT_CHECK_DATA
QCPErrorBarsDataContainer::const_iterator it;
for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
{
if (QCP::isInvalidData(it->errorMinus, it->errorPlus))
qDebug() << Q_FUNC_INFO << "Data point at index" << it-mDataContainer->constBegin() << "invalid." << "Plottable name:" << name();
}
#endif
applyDefaultAntialiasingHint(painter);
painter->setBrush(Qt::NoBrush);
// loop over and draw segments of unselected/selected data:
QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
getDataSegments(selectedSegments, unselectedSegments);
allSegments << unselectedSegments << selectedSegments;
QVector<QLineF> backbones, whiskers;
for (int i=0; i<allSegments.size(); ++i)
{
QCPErrorBarsDataContainer::const_iterator begin, end;
getVisibleDataBounds(begin, end, allSegments.at(i));
if (begin == end)
continue;
bool isSelectedSegment = i >= unselectedSegments.size();
if (isSelectedSegment && mSelectionDecorator)
mSelectionDecorator->applyPen(painter);
else
painter->setPen(mPen);
if (painter->pen().capStyle() == Qt::SquareCap)
{
QPen capFixPen(painter->pen());
capFixPen.setCapStyle(Qt::FlatCap);
painter->setPen(capFixPen);
}
backbones.clear();
whiskers.clear();
for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
{
if (!checkPointVisibility || errorBarVisible(int(it-mDataContainer->constBegin())))
getErrorBarLines(it, backbones, whiskers);
}
painter->drawLines(backbones);
painter->drawLines(whiskers);
}
// draw other selection decoration that isn't just line/scatter pens and brushes:
if (mSelectionDecorator)
mSelectionDecorator->drawDecoration(painter, selection());
}
/* inherits documentation from base class */
void QCPErrorBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
if (mErrorType == etValueError && mValueAxis && mValueAxis->orientation() == Qt::Vertical)
{
painter->drawLine(QLineF(rect.center().x(), rect.top()+2, rect.center().x(), rect.bottom()-1));
painter->drawLine(QLineF(rect.center().x()-4, rect.top()+2, rect.center().x()+4, rect.top()+2));
painter->drawLine(QLineF(rect.center().x()-4, rect.bottom()-1, rect.center().x()+4, rect.bottom()-1));
} else
{
painter->drawLine(QLineF(rect.left()+2, rect.center().y(), rect.right()-2, rect.center().y()));
painter->drawLine(QLineF(rect.left()+2, rect.center().y()-4, rect.left()+2, rect.center().y()+4));
painter->drawLine(QLineF(rect.right()-2, rect.center().y()-4, rect.right()-2, rect.center().y()+4));
}
}
/* inherits documentation from base class */
QCPRange QCPErrorBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
{
if (!mDataPlottable)
{
foundRange = false;
return {};
}
QCPRange range;
bool haveLower = false;
bool haveUpper = false;
QCPErrorBarsDataContainer::const_iterator it;
for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
{
if (mErrorType == etValueError)
{
// error bar doesn't extend in key dimension (except whisker but we ignore that here), so only use data point center
const double current = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
if (qIsNaN(current)) continue;
if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
{
if (current < range.lower || !haveLower)
{
range.lower = current;
haveLower = true;
}
if (current > range.upper || !haveUpper)
{
range.upper = current;
haveUpper = true;
}
}
} else // mErrorType == etKeyError
{
const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
if (qIsNaN(dataKey)) continue;
// plus error:
double current = dataKey + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
{
if (current > range.upper || !haveUpper)
{
range.upper = current;
haveUpper = true;
}
}
// minus error:
current = dataKey - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
{
if (current < range.lower || !haveLower)
{
range.lower = current;
haveLower = true;
}
}
}
}
if (haveUpper && !haveLower)
{
range.lower = range.upper;
haveLower = true;
} else if (haveLower && !haveUpper)
{
range.upper = range.lower;
haveUpper = true;
}
foundRange = haveLower && haveUpper;
return range;
}
/* inherits documentation from base class */
QCPRange QCPErrorBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
{
if (!mDataPlottable)
{
foundRange = false;
return {};
}
QCPRange range;
const bool restrictKeyRange = inKeyRange != QCPRange();
bool haveLower = false;
bool haveUpper = false;
QCPErrorBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
QCPErrorBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
if (mDataPlottable->interface1D()->sortKeyIsMainKey() && restrictKeyRange)
{
itBegin = mDataContainer->constBegin()+findBegin(inKeyRange.lower, false);
itEnd = mDataContainer->constBegin()+findEnd(inKeyRange.upper, false);
}
for (QCPErrorBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
{
if (restrictKeyRange)
{
const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
if (dataKey < inKeyRange.lower || dataKey > inKeyRange.upper)
continue;
}
if (mErrorType == etValueError)
{
const double dataValue = mDataPlottable->interface1D()->dataMainValue(int(it-mDataContainer->constBegin()));
if (qIsNaN(dataValue)) continue;
// plus error:
double current = dataValue + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
{
if (current > range.upper || !haveUpper)
{
range.upper = current;
haveUpper = true;
}
}
// minus error:
current = dataValue - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
{
if (current < range.lower || !haveLower)
{
range.lower = current;
haveLower = true;
}
}
} else // mErrorType == etKeyError
{
// error bar doesn't extend in value dimension (except whisker but we ignore that here), so only use data point center
const double current = mDataPlottable->interface1D()->dataMainValue(int(it-mDataContainer->constBegin()));
if (qIsNaN(current)) continue;
if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
{
if (current < range.lower || !haveLower)
{
range.lower = current;
haveLower = true;
}
if (current > range.upper || !haveUpper)
{
range.upper = current;
haveUpper = true;
}
}
}
}
if (haveUpper && !haveLower)
{
range.lower = range.upper;
haveLower = true;
} else if (haveLower && !haveUpper)
{
range.upper = range.lower;
haveUpper = true;
}
foundRange = haveLower && haveUpper;
return range;
}
/*! \internal
Calculates the lines that make up the error bar belonging to the data point \a it.
The resulting lines are added to \a backbones and \a whiskers. The vectors are not cleared, so
calling this method with different \a it but the same \a backbones and \a whiskers allows to
accumulate lines for multiple data points.
This method assumes that \a it is a valid iterator within the bounds of this \ref QCPErrorBars
instance and within the bounds of the associated data plottable.
*/
void QCPErrorBars::getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it, QVector<QLineF> &backbones, QVector<QLineF> &whiskers) const
{
if (!mDataPlottable) return;
int index = int(it-mDataContainer->constBegin());
QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
if (qIsNaN(centerPixel.x()) || qIsNaN(centerPixel.y()))
return;
QCPAxis *errorAxis = mErrorType == etValueError ? mValueAxis.data() : mKeyAxis.data();
QCPAxis *orthoAxis = mErrorType == etValueError ? mKeyAxis.data() : mValueAxis.data();
const double centerErrorAxisPixel = errorAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
const double centerOrthoAxisPixel = orthoAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
const double centerErrorAxisCoord = errorAxis->pixelToCoord(centerErrorAxisPixel); // depending on plottable, this might be different from just mDataPlottable->interface1D()->dataMainKey/Value
const double symbolGap = mSymbolGap*0.5*errorAxis->pixelOrientation();
// plus error:
double errorStart, errorEnd;
if (!qIsNaN(it->errorPlus))
{
errorStart = centerErrorAxisPixel+symbolGap;
errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord+it->errorPlus);
if (errorAxis->orientation() == Qt::Vertical)
{
if ((errorStart > errorEnd) != errorAxis->rangeReversed())
backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
} else
{
if ((errorStart < errorEnd) != errorAxis->rangeReversed())
backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
}
}
// minus error:
if (!qIsNaN(it->errorMinus))
{
errorStart = centerErrorAxisPixel-symbolGap;
errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord-it->errorMinus);
if (errorAxis->orientation() == Qt::Vertical)
{
if ((errorStart < errorEnd) != errorAxis->rangeReversed())
backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
} else
{
if ((errorStart > errorEnd) != errorAxis->rangeReversed())
backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
}
}
}
/*! \internal
This method outputs the currently visible data range via \a begin and \a end. The returned range
will also never exceed \a rangeRestriction.
Since error bars with type \ref etKeyError may extend to arbitrarily positive and negative key
coordinates relative to their data point key, this method checks all outer error bars whether
they truly don't reach into the visible portion of the axis rect, by calling \ref
errorBarVisible. On the other hand error bars with type \ref etValueError that are associated
with data plottables whose sort key is equal to the main key (see \ref qcpdatacontainer-datatype
"QCPDataContainer DataType") can be handled very efficiently by finding the visible range of
error bars through binary search (\ref QCPPlottableInterface1D::findBegin and \ref
QCPPlottableInterface1D::findEnd).
If the plottable's sort key is not equal to the main key, this method returns the full data
range, only restricted by \a rangeRestriction. Drawing optimization then has to be done on a
point-by-point basis in the \ref draw method.
*/
void QCPErrorBars::getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterator &begin, QCPErrorBarsDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis)
{
qDebug() << Q_FUNC_INFO << "invalid key or value axis";
end = mDataContainer->constEnd();
begin = end;
return;
}
if (!mDataPlottable || rangeRestriction.isEmpty())
{
end = mDataContainer->constEnd();
begin = end;
return;
}
if (!mDataPlottable->interface1D()->sortKeyIsMainKey())
{
// if the sort key isn't the main key, it's not possible to find a contiguous range of visible
// data points, so this method then only applies the range restriction and otherwise returns
// the full data range. Visibility checks must be done on a per-datapoin-basis during drawing
QCPDataRange dataRange(0, static_cast<int>(mDataContainer->size()));
dataRange = dataRange.bounded(rangeRestriction);
begin = mDataContainer->constBegin()+dataRange.begin();
end = mDataContainer->constBegin()+dataRange.end();
return;
}
// get visible data range via interface from data plottable, and then restrict to available error data points:
const int n = static_cast<int>(qMin(mDataContainer->size(), mDataPlottable->interface1D()->dataCount()));
int beginIndex = mDataPlottable->interface1D()->findBegin(keyAxis->range().lower);
int endIndex = mDataPlottable->interface1D()->findEnd(keyAxis->range().upper);
int i = beginIndex;
while (i > 0 && i < n && i > rangeRestriction.begin())
{
if (errorBarVisible(i))
beginIndex = i;
--i;
}
i = endIndex;
while (i >= 0 && i < n && i < rangeRestriction.end())
{
if (errorBarVisible(i))
endIndex = i+1;
++i;
}
QCPDataRange dataRange(beginIndex, endIndex);
dataRange = dataRange.bounded(rangeRestriction.bounded(QCPDataRange(0, static_cast<int>(mDataContainer->size()))));
begin = mDataContainer->constBegin()+dataRange.begin();
end = mDataContainer->constBegin()+dataRange.end();
}
/*! \internal
Calculates the minimum distance in pixels the error bars' representation has from the given \a
pixelPoint. This is used to determine whether the error bar was clicked or not, e.g. in \ref
selectTest. The closest data point to \a pixelPoint is returned in \a closestData.
*/
double QCPErrorBars::pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const
{
closestData = mDataContainer->constEnd();
if (!mDataPlottable || mDataContainer->isEmpty())
return -1.0;
if (!mKeyAxis || !mValueAxis)
{
qDebug() << Q_FUNC_INFO << "invalid key or value axis";
return -1.0;
}
QCPErrorBarsDataContainer::const_iterator begin, end;
getVisibleDataBounds(begin, end, QCPDataRange(0, dataCount()));
// calculate minimum distances to error backbones (whiskers are ignored for speed) and find closestData iterator:
double minDistSqr = (std::numeric_limits<double>::max)();
QVector<QLineF> backbones, whiskers;
for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
{
getErrorBarLines(it, backbones, whiskers);
foreach (const QLineF &backbone, backbones)
{
const double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(backbone);
if (currentDistSqr < minDistSqr)
{
minDistSqr = currentDistSqr;
closestData = it;
}
}
}
return qSqrt(minDistSqr);
}
/*! \internal
\note This method is identical to \ref QCPAbstractPlottable1D::getDataSegments but needs to be
reproduced here since the \ref QCPErrorBars plottable, as a special case that doesn't have its
own key/value data coordinates, doesn't derive from \ref QCPAbstractPlottable1D. See the
documentation there for details.
*/
void QCPErrorBars::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
{
selectedSegments.clear();
unselectedSegments.clear();
if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
{
if (selected())
selectedSegments << QCPDataRange(0, dataCount());
else
unselectedSegments << QCPDataRange(0, dataCount());
} else
{
QCPDataSelection sel(selection());
sel.simplify();
selectedSegments = sel.dataRanges();
unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
}
}
/*! \internal
Returns whether the error bar at the specified \a index is visible within the current key axis
range.
This method assumes for performance reasons without checking that the key axis, the value axis,
and the data plottable (\ref setDataPlottable) are not \c nullptr and that \a index is within
valid bounds of this \ref QCPErrorBars instance and the bounds of the data plottable.
*/
bool QCPErrorBars::errorBarVisible(int index) const
{
QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
const double centerKeyPixel = mKeyAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
if (qIsNaN(centerKeyPixel))
return false;
double keyMin, keyMax;
if (mErrorType == etKeyError)
{
const double centerKey = mKeyAxis->pixelToCoord(centerKeyPixel);
const double errorPlus = mDataContainer->at(index).errorPlus;
const double errorMinus = mDataContainer->at(index).errorMinus;
keyMax = centerKey+(qIsNaN(errorPlus) ? 0 : errorPlus);
keyMin = centerKey-(qIsNaN(errorMinus) ? 0 : errorMinus);
} else // mErrorType == etValueError
{
keyMax = mKeyAxis->pixelToCoord(centerKeyPixel+mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
keyMin = mKeyAxis->pixelToCoord(centerKeyPixel-mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
}
return ((keyMax > mKeyAxis->range().lower) && (keyMin < mKeyAxis->range().upper));
}
/*! \internal
Returns whether \a line intersects (or is contained in) \a pixelRect.
\a line is assumed to be either perfectly horizontal or perfectly vertical, as is the case for
error bar lines.
*/
bool QCPErrorBars::rectIntersectsLine(const QRectF &pixelRect, const QLineF &line) const
{
if (pixelRect.left() > line.x1() && pixelRect.left() > line.x2())
return false;
else if (pixelRect.right() < line.x1() && pixelRect.right() < line.x2())
return false;
else if (pixelRect.top() > line.y1() && pixelRect.top() > line.y2())
return false;
else if (pixelRect.bottom() < line.y1() && pixelRect.bottom() < line.y2())
return false;
else
return true;
}
/* end of 'src/plottables/plottable-errorbar.cpp' */
/* including file 'src/items/item-straightline.cpp' */
/* modified 2022-11-06T12:45:56, size 7596 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemStraightLine
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemStraightLine
\brief A straight line that spans infinitely in both directions
\image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a point1 and \a point2, which define the straight line.
*/
/*!
Creates a straight line item and sets default values.
The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
*/
QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
point1(createPosition(QLatin1String("point1"))),
point2(createPosition(QLatin1String("point2")))
{
point1->setCoords(0, 0);
point2->setCoords(1, 1);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue,2));
}
QCPItemStraightLine::~QCPItemStraightLine()
{
}
/*!
Sets the pen that will be used to draw the line
\see setSelectedPen
*/
void QCPItemStraightLine::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line when selected
\see setPen, setSelected
*/
void QCPItemStraightLine::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/* inherits documentation from base class */
double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
return QCPVector2D(pos).distanceToStraightLine(point1->pixelPosition(), point2->pixelPosition()-point1->pixelPosition());
}
/* inherits documentation from base class */
void QCPItemStraightLine::draw(QCPPainter *painter)
{
QCPVector2D start(point1->pixelPosition());
QCPVector2D end(point2->pixelPosition());
// get visible segment of straight line inside clipRect:
int clipPad = qCeil(mainPen().widthF());
QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
// paint visible segment, if existent:
if (!line.isNull())
{
painter->setPen(mainPen());
painter->drawLine(line);
}
}
/*! \internal
Returns the section of the straight line defined by \a base and direction vector \a
vec, that is visible in the specified \a rect.
This is a helper function for \ref draw.
*/
QLineF QCPItemStraightLine::getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const
{
double bx, by;
double gamma;
QLineF result;
if (vec.x() == 0 && vec.y() == 0)
return result;
if (qFuzzyIsNull(vec.x())) // line is vertical
{
// check top of rect:
bx = rect.left();
by = rect.top();
gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
if (gamma >= 0 && gamma <= rect.width())
result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical
} else if (qFuzzyIsNull(vec.y())) // line is horizontal
{
// check left of rect:
bx = rect.left();
by = rect.top();
gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
if (gamma >= 0 && gamma <= rect.height())
result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal
} else // line is skewed
{
QList<QCPVector2D> pointVectors;
// check top of rect:
bx = rect.left();
by = rect.top();
gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
if (gamma >= 0 && gamma <= rect.width())
pointVectors.append(QCPVector2D(bx+gamma, by));
// check bottom of rect:
bx = rect.left();
by = rect.bottom();
gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
if (gamma >= 0 && gamma <= rect.width())
pointVectors.append(QCPVector2D(bx+gamma, by));
// check left of rect:
bx = rect.left();
by = rect.top();
gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
if (gamma >= 0 && gamma <= rect.height())
pointVectors.append(QCPVector2D(bx, by+gamma));
// check right of rect:
bx = rect.right();
by = rect.top();
gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
if (gamma >= 0 && gamma <= rect.height())
pointVectors.append(QCPVector2D(bx, by+gamma));
// evaluate points:
if (pointVectors.size() == 2)
{
result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
} else if (pointVectors.size() > 2)
{
// line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
double distSqrMax = 0;
QCPVector2D pv1, pv2;
for (int i=0; i<pointVectors.size()-1; ++i)
{
for (int k=i+1; k<pointVectors.size(); ++k)
{
double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
if (distSqr > distSqrMax)
{
pv1 = pointVectors.at(i);
pv2 = pointVectors.at(k);
distSqrMax = distSqr;
}
}
}
result.setPoints(pv1.toPointF(), pv2.toPointF());
}
}
return result;
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the
item is not selected and mSelectedPen when it is.
*/
QPen QCPItemStraightLine::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/* end of 'src/items/item-straightline.cpp' */
/* including file 'src/items/item-line.cpp' */
/* modified 2022-11-06T12:45:56, size 8525 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemLine
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemLine
\brief A line from one point to another
\image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a start and \a end, which define the end points of the line.
With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow.
*/
/*!
Creates a line item and sets default values.
The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
*/
QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
start(createPosition(QLatin1String("start"))),
end(createPosition(QLatin1String("end")))
{
start->setCoords(0, 0);
end->setCoords(1, 1);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue,2));
}
QCPItemLine::~QCPItemLine()
{
}
/*!
Sets the pen that will be used to draw the line
\see setSelectedPen
*/
void QCPItemLine::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line when selected
\see setPen, setSelected
*/
void QCPItemLine::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the line ending style of the head. The head corresponds to the \a end position.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify
a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
\see setTail
*/
void QCPItemLine::setHead(const QCPLineEnding &head)
{
mHead = head;
}
/*!
Sets the line ending style of the tail. The tail corresponds to the \a start position.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify
a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
\see setHead
*/
void QCPItemLine::setTail(const QCPLineEnding &tail)
{
mTail = tail;
}
/* inherits documentation from base class */
double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
return qSqrt(QCPVector2D(pos).distanceSquaredToLine(start->pixelPosition(), end->pixelPosition()));
}
/* inherits documentation from base class */
void QCPItemLine::draw(QCPPainter *painter)
{
QCPVector2D startVec(start->pixelPosition());
QCPVector2D endVec(end->pixelPosition());
if (qFuzzyIsNull((startVec-endVec).lengthSquared()))
return;
// get visible segment of straight line inside clipRect:
int clipPad = int(qMax(mHead.boundingDistance(), mTail.boundingDistance()));
clipPad = qMax(clipPad, qCeil(mainPen().widthF()));
QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
// paint visible segment, if existent:
if (!line.isNull())
{
painter->setPen(mainPen());
painter->drawLine(line);
painter->setBrush(Qt::SolidPattern);
if (mTail.style() != QCPLineEnding::esNone)
mTail.draw(painter, startVec, startVec-endVec);
if (mHead.style() != QCPLineEnding::esNone)
mHead.draw(painter, endVec, endVec-startVec);
}
}
/*! \internal
Returns the section of the line defined by \a start and \a end, that is visible in the specified
\a rect.
This is a helper function for \ref draw.
*/
QLineF QCPItemLine::getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const
{
bool containsStart = rect.contains(qRound(start.x()), qRound(start.y()));
bool containsEnd = rect.contains(qRound(end.x()), qRound(end.y()));
if (containsStart && containsEnd)
return {start.toPointF(), end.toPointF()};
QCPVector2D base = start;
QCPVector2D vec = end-start;
double bx, by;
double gamma, mu;
QLineF result;
QList<QCPVector2D> pointVectors;
if (!qFuzzyIsNull(vec.y())) // line is not horizontal
{
// check top of rect:
bx = rect.left();
by = rect.top();
mu = (by-base.y())/vec.y();
if (mu >= 0 && mu <= 1)
{
gamma = base.x()-bx + mu*vec.x();
if (gamma >= 0 && gamma <= rect.width())
pointVectors.append(QCPVector2D(bx+gamma, by));
}
// check bottom of rect:
bx = rect.left();
by = rect.bottom();
mu = (by-base.y())/vec.y();
if (mu >= 0 && mu <= 1)
{
gamma = base.x()-bx + mu*vec.x();
if (gamma >= 0 && gamma <= rect.width())
pointVectors.append(QCPVector2D(bx+gamma, by));
}
}
if (!qFuzzyIsNull(vec.x())) // line is not vertical
{
// check left of rect:
bx = rect.left();
by = rect.top();
mu = (bx-base.x())/vec.x();
if (mu >= 0 && mu <= 1)
{
gamma = base.y()-by + mu*vec.y();
if (gamma >= 0 && gamma <= rect.height())
pointVectors.append(QCPVector2D(bx, by+gamma));
}
// check right of rect:
bx = rect.right();
by = rect.top();
mu = (bx-base.x())/vec.x();
if (mu >= 0 && mu <= 1)
{
gamma = base.y()-by + mu*vec.y();
if (gamma >= 0 && gamma <= rect.height())
pointVectors.append(QCPVector2D(bx, by+gamma));
}
}
if (containsStart)
pointVectors.append(start);
if (containsEnd)
pointVectors.append(end);
// evaluate points:
if (pointVectors.size() == 2)
{
result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
} else if (pointVectors.size() > 2)
{
// line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
double distSqrMax = 0;
QCPVector2D pv1, pv2;
for (int i=0; i<pointVectors.size()-1; ++i)
{
for (int k=i+1; k<pointVectors.size(); ++k)
{
double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
if (distSqr > distSqrMax)
{
pv1 = pointVectors.at(i);
pv2 = pointVectors.at(k);
distSqrMax = distSqr;
}
}
}
result.setPoints(pv1.toPointF(), pv2.toPointF());
}
return result;
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the
item is not selected and mSelectedPen when it is.
*/
QPen QCPItemLine::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/* end of 'src/items/item-line.cpp' */
/* including file 'src/items/item-curve.cpp' */
/* modified 2022-11-06T12:45:56, size 7273 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemCurve
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemCurve
\brief A curved line from one point to another
\image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions."
It has four positions, \a start and \a end, which define the end points of the line, and two
control points which define the direction the line exits from the start and the direction from
which it approaches the end: \a startDir and \a endDir.
With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an
arrow.
Often it is desirable for the control points to stay at fixed relative positions to the start/end
point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start,
and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir.
*/
/*!
Creates a curve item and sets default values.
The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
*/
QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
start(createPosition(QLatin1String("start"))),
startDir(createPosition(QLatin1String("startDir"))),
endDir(createPosition(QLatin1String("endDir"))),
end(createPosition(QLatin1String("end")))
{
start->setCoords(0, 0);
startDir->setCoords(0.5, 0);
endDir->setCoords(0, 0.5);
end->setCoords(1, 1);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue,2));
}
QCPItemCurve::~QCPItemCurve()
{
}
/*!
Sets the pen that will be used to draw the line
\see setSelectedPen
*/
void QCPItemCurve::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line when selected
\see setPen, setSelected
*/
void QCPItemCurve::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the line ending style of the head. The head corresponds to the \a end position.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify
a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
\see setTail
*/
void QCPItemCurve::setHead(const QCPLineEnding &head)
{
mHead = head;
}
/*!
Sets the line ending style of the tail. The tail corresponds to the \a start position.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify
a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
\see setHead
*/
void QCPItemCurve::setTail(const QCPLineEnding &tail)
{
mTail = tail;
}
/* inherits documentation from base class */
double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
QPointF startVec(start->pixelPosition());
QPointF startDirVec(startDir->pixelPosition());
QPointF endDirVec(endDir->pixelPosition());
QPointF endVec(end->pixelPosition());
QPainterPath cubicPath(startVec);
cubicPath.cubicTo(startDirVec, endDirVec, endVec);
QList<QPolygonF> polygons = cubicPath.toSubpathPolygons();
if (polygons.isEmpty())
return -1;
const QPolygonF polygon = polygons.first();
QCPVector2D p(pos);
double minDistSqr = (std::numeric_limits<double>::max)();
for (int i=1; i<polygon.size(); ++i)
{
double distSqr = p.distanceSquaredToLine(polygon.at(i-1), polygon.at(i));
if (distSqr < minDistSqr)
minDistSqr = distSqr;
}
return qSqrt(minDistSqr);
}
/* inherits documentation from base class */
void QCPItemCurve::draw(QCPPainter *painter)
{
QCPVector2D startVec(start->pixelPosition());
QCPVector2D startDirVec(startDir->pixelPosition());
QCPVector2D endDirVec(endDir->pixelPosition());
QCPVector2D endVec(end->pixelPosition());
if ((endVec-startVec).length() > 1e10) // too large curves cause crash
return;
QPainterPath cubicPath(startVec.toPointF());
cubicPath.cubicTo(startDirVec.toPointF(), endDirVec.toPointF(), endVec.toPointF());
// paint visible segment, if existent:
const int clipEnlarge = qCeil(mainPen().widthF());
QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
QRect cubicRect = cubicPath.controlPointRect().toRect();
if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position
cubicRect.adjust(0, 0, 1, 1);
if (clip.intersects(cubicRect))
{
painter->setPen(mainPen());
painter->drawPath(cubicPath);
painter->setBrush(Qt::SolidPattern);
if (mTail.style() != QCPLineEnding::esNone)
mTail.draw(painter, startVec, M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI);
if (mHead.style() != QCPLineEnding::esNone)
mHead.draw(painter, endVec, -cubicPath.angleAtPercent(1)/180.0*M_PI);
}
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the
item is not selected and mSelectedPen when it is.
*/
QPen QCPItemCurve::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/* end of 'src/items/item-curve.cpp' */
/* including file 'src/items/item-rect.cpp' */
/* modified 2022-11-06T12:45:56, size 6472 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemRect
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemRect
\brief A rectangle
\image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a topLeft and \a bottomRight, which define the rectangle.
*/
/*!
Creates a rectangle item and sets default values.
The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
*/
QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
topLeft(createPosition(QLatin1String("topLeft"))),
bottomRight(createPosition(QLatin1String("bottomRight"))),
top(createAnchor(QLatin1String("top"), aiTop)),
topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
right(createAnchor(QLatin1String("right"), aiRight)),
bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
left(createAnchor(QLatin1String("left"), aiLeft))
{
topLeft->setCoords(0, 1);
bottomRight->setCoords(1, 0);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue,2));
setBrush(Qt::NoBrush);
setSelectedBrush(Qt::NoBrush);
}
QCPItemRect::~QCPItemRect()
{
}
/*!
Sets the pen that will be used to draw the line of the rectangle
\see setSelectedPen, setBrush
*/
void QCPItemRect::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line of the rectangle when selected
\see setPen, setSelected
*/
void QCPItemRect::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to
Qt::NoBrush.
\see setSelectedBrush, setPen
*/
void QCPItemRect::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a
brush to Qt::NoBrush.
\see setBrush
*/
void QCPItemRect::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/* inherits documentation from base class */
double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()).normalized();
bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
return rectDistance(rect, pos, filledRect);
}
/* inherits documentation from base class */
void QCPItemRect::draw(QCPPainter *painter)
{
QPointF p1 = topLeft->pixelPosition();
QPointF p2 = bottomRight->pixelPosition();
if (p1.toPoint() == p2.toPoint())
return;
QRectF rect = QRectF(p1, p2).normalized();
double clipPad = mainPen().widthF();
QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect
{
painter->setPen(mainPen());
painter->setBrush(mainBrush());
painter->drawRect(rect);
}
}
/* inherits documentation from base class */
QPointF QCPItemRect::anchorPixelPosition(int anchorId) const
{
QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
switch (anchorId)
{
case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
case aiTopRight: return rect.topRight();
case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
case aiBottomLeft: return rect.bottomLeft();
case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return {};
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemRect::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/*! \internal
Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
is not selected and mSelectedBrush when it is.
*/
QBrush QCPItemRect::mainBrush() const
{
return mSelected ? mSelectedBrush : mBrush;
}
/* end of 'src/items/item-rect.cpp' */
/* including file 'src/items/item-text.cpp' */
/* modified 2022-11-06T12:45:56, size 13335 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemText
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemText
\brief A text label
\image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions."
Its position is defined by the member \a position and the setting of \ref setPositionAlignment.
The latter controls which part of the text rect shall be aligned with \a position.
The text alignment itself (i.e. left, center, right) can be controlled with \ref
setTextAlignment.
The text may be rotated around the \a position point with \ref setRotation.
*/
/*!
Creates a text item and sets default values.
The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
*/
QCPItemText::QCPItemText(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
position(createPosition(QLatin1String("position"))),
topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)),
top(createAnchor(QLatin1String("top"), aiTop)),
topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
right(createAnchor(QLatin1String("right"), aiRight)),
bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)),
bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
left(createAnchor(QLatin1String("left"), aiLeft)),
mText(QLatin1String("text")),
mPositionAlignment(Qt::AlignCenter),
mTextAlignment(Qt::AlignTop|Qt::AlignHCenter),
mRotation(0)
{
position->setCoords(0, 0);
setPen(Qt::NoPen);
setSelectedPen(Qt::NoPen);
setBrush(Qt::NoBrush);
setSelectedBrush(Qt::NoBrush);
setColor(Qt::black);
setSelectedColor(Qt::blue);
}
QCPItemText::~QCPItemText()
{
}
/*!
Sets the color of the text.
*/
void QCPItemText::setColor(const QColor &color)
{
mColor = color;
}
/*!
Sets the color of the text that will be used when the item is selected.
*/
void QCPItemText::setSelectedColor(const QColor &color)
{
mSelectedColor = color;
}
/*!
Sets the pen that will be used do draw a rectangular border around the text. To disable the
border, set \a pen to Qt::NoPen.
\see setSelectedPen, setBrush, setPadding
*/
void QCPItemText::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used do draw a rectangular border around the text, when the item is
selected. To disable the border, set \a pen to Qt::NoPen.
\see setPen
*/
void QCPItemText::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the brush that will be used do fill the background of the text. To disable the
background, set \a brush to Qt::NoBrush.
\see setSelectedBrush, setPen, setPadding
*/
void QCPItemText::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the
background, set \a brush to Qt::NoBrush.
\see setBrush
*/
void QCPItemText::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/*!
Sets the font of the text.
\see setSelectedFont, setColor
*/
void QCPItemText::setFont(const QFont &font)
{
mFont = font;
}
/*!
Sets the font of the text that will be used when the item is selected.
\see setFont
*/
void QCPItemText::setSelectedFont(const QFont &font)
{
mSelectedFont = font;
}
/*!
Sets the text that will be displayed. Multi-line texts are supported by inserting a line break
character, e.g. '\n'.
\see setFont, setColor, setTextAlignment
*/
void QCPItemText::setText(const QString &text)
{
mText = text;
}
/*!
Sets which point of the text rect shall be aligned with \a position.
Examples:
\li If \a alignment is <tt>Qt::AlignHCenter | Qt::AlignTop</tt>, the text will be positioned such
that the top of the text rect will be horizontally centered on \a position.
\li If \a alignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt>, \a position will indicate the
bottom left corner of the text rect.
If you want to control the alignment of (multi-lined) text within the text rect, use \ref
setTextAlignment.
*/
void QCPItemText::setPositionAlignment(Qt::Alignment alignment)
{
mPositionAlignment = alignment;
}
/*!
Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight).
*/
void QCPItemText::setTextAlignment(Qt::Alignment alignment)
{
mTextAlignment = alignment;
}
/*!
Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated
around \a position.
*/
void QCPItemText::setRotation(double degrees)
{
mRotation = degrees;
}
/*!
Sets the distance between the border of the text rectangle and the text. The appearance (and
visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush.
*/
void QCPItemText::setPadding(const QMargins &padding)
{
mPadding = padding;
}
/* inherits documentation from base class */
double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
// The rect may be rotated, so we transform the actual clicked pos to the rotated
// coordinate system, so we can use the normal rectDistance function for non-rotated rects:
QPointF positionPixels(position->pixelPosition());
QTransform inputTransform;
inputTransform.translate(positionPixels.x(), positionPixels.y());
inputTransform.rotate(-mRotation);
inputTransform.translate(-positionPixels.x(), -positionPixels.y());
QPointF rotatedPos = inputTransform.map(pos);
QFontMetrics fontMetrics(mFont);
QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment);
textBoxRect.moveTopLeft(textPos.toPoint());
return rectDistance(textBoxRect, rotatedPos, true);
}
/* inherits documentation from base class */
void QCPItemText::draw(QCPPainter *painter)
{
QPointF pos(position->pixelPosition());
QTransform transform = painter->transform();
transform.translate(pos.x(), pos.y());
if (!qFuzzyIsNull(mRotation))
transform.rotate(mRotation);
painter->setFont(mainFont());
QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top()));
textBoxRect.moveTopLeft(textPos.toPoint());
int clipPad = qCeil(mainPen().widthF());
QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect())))
{
painter->setTransform(transform);
if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) ||
(mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0))
{
painter->setPen(mainPen());
painter->setBrush(mainBrush());
painter->drawRect(textBoxRect);
}
painter->setBrush(Qt::NoBrush);
painter->setPen(QPen(mainColor()));
painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText);
}
}
/* inherits documentation from base class */
QPointF QCPItemText::anchorPixelPosition(int anchorId) const
{
// get actual rect points (pretty much copied from draw function):
QPointF pos(position->pixelPosition());
QTransform transform;
transform.translate(pos.x(), pos.y());
if (!qFuzzyIsNull(mRotation))
transform.rotate(mRotation);
QFontMetrics fontMetrics(mainFont());
QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
textBoxRect.moveTopLeft(textPos.toPoint());
QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect));
switch (anchorId)
{
case aiTopLeft: return rectPoly.at(0);
case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5;
case aiTopRight: return rectPoly.at(1);
case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5;
case aiBottomRight: return rectPoly.at(2);
case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5;
case aiBottomLeft: return rectPoly.at(3);
case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5;
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return {};
}
/*! \internal
Returns the point that must be given to the QPainter::drawText function (which expects the top
left point of the text rect), according to the position \a pos, the text bounding box \a rect and
the requested \a positionAlignment.
For example, if \a positionAlignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt> the returned point
will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally
drawn at that point, the lower left corner of the resulting text rect is at \a pos.
*/
QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const
{
if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop))
return pos;
QPointF result = pos; // start at top left
if (positionAlignment.testFlag(Qt::AlignHCenter))
result.rx() -= rect.width()/2.0;
else if (positionAlignment.testFlag(Qt::AlignRight))
result.rx() -= rect.width();
if (positionAlignment.testFlag(Qt::AlignVCenter))
result.ry() -= rect.height()/2.0;
else if (positionAlignment.testFlag(Qt::AlignBottom))
result.ry() -= rect.height();
return result;
}
/*! \internal
Returns the font that should be used for drawing text. Returns mFont when the item is not selected
and mSelectedFont when it is.
*/
QFont QCPItemText::mainFont() const
{
return mSelected ? mSelectedFont : mFont;
}
/*! \internal
Returns the color that should be used for drawing text. Returns mColor when the item is not
selected and mSelectedColor when it is.
*/
QColor QCPItemText::mainColor() const
{
return mSelected ? mSelectedColor : mColor;
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemText::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/*! \internal
Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
is not selected and mSelectedBrush when it is.
*/
QBrush QCPItemText::mainBrush() const
{
return mSelected ? mSelectedBrush : mBrush;
}
/* end of 'src/items/item-text.cpp' */
/* including file 'src/items/item-ellipse.cpp' */
/* modified 2022-11-06T12:45:56, size 7881 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemEllipse
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemEllipse
\brief An ellipse
\image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in.
*/
/*!
Creates an ellipse item and sets default values.
The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
*/
QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
topLeft(createPosition(QLatin1String("topLeft"))),
bottomRight(createPosition(QLatin1String("bottomRight"))),
topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)),
top(createAnchor(QLatin1String("top"), aiTop)),
topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)),
right(createAnchor(QLatin1String("right"), aiRight)),
bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)),
bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)),
left(createAnchor(QLatin1String("left"), aiLeft)),
center(createAnchor(QLatin1String("center"), aiCenter))
{
topLeft->setCoords(0, 1);
bottomRight->setCoords(1, 0);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue, 2));
setBrush(Qt::NoBrush);
setSelectedBrush(Qt::NoBrush);
}
QCPItemEllipse::~QCPItemEllipse()
{
}
/*!
Sets the pen that will be used to draw the line of the ellipse
\see setSelectedPen, setBrush
*/
void QCPItemEllipse::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line of the ellipse when selected
\see setPen, setSelected
*/
void QCPItemEllipse::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to
Qt::NoBrush.
\see setSelectedBrush, setPen
*/
void QCPItemEllipse::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a
brush to Qt::NoBrush.
\see setBrush
*/
void QCPItemEllipse::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/* inherits documentation from base class */
double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
QPointF p1 = topLeft->pixelPosition();
QPointF p2 = bottomRight->pixelPosition();
QPointF center((p1+p2)/2.0);
double a = qAbs(p1.x()-p2.x())/2.0;
double b = qAbs(p1.y()-p2.y())/2.0;
double x = pos.x()-center.x();
double y = pos.y()-center.y();
// distance to border:
double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b));
double result = qAbs(c-1)*qSqrt(x*x+y*y);
// filled ellipse, allow click inside to count as hit:
if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
{
if (x*x/(a*a) + y*y/(b*b) <= 1)
result = mParentPlot->selectionTolerance()*0.99;
}
return result;
}
/* inherits documentation from base class */
void QCPItemEllipse::draw(QCPPainter *painter)
{
QPointF p1 = topLeft->pixelPosition();
QPointF p2 = bottomRight->pixelPosition();
if (p1.toPoint() == p2.toPoint())
return;
QRectF ellipseRect = QRectF(p1, p2).normalized();
const int clipEnlarge = qCeil(mainPen().widthF());
QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect
{
painter->setPen(mainPen());
painter->setBrush(mainBrush());
#ifdef __EXCEPTIONS
try // drawEllipse sometimes throws exceptions if ellipse is too big
{
#endif
painter->drawEllipse(ellipseRect);
#ifdef __EXCEPTIONS
} catch (...)
{
qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible";
setVisible(false);
}
#endif
}
}
/* inherits documentation from base class */
QPointF QCPItemEllipse::anchorPixelPosition(int anchorId) const
{
QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
switch (anchorId)
{
case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2);
case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2);
case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2);
case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2);
case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5;
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return {};
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemEllipse::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/*! \internal
Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
is not selected and mSelectedBrush when it is.
*/
QBrush QCPItemEllipse::mainBrush() const
{
return mSelected ? mSelectedBrush : mBrush;
}
/* end of 'src/items/item-ellipse.cpp' */
/* including file 'src/items/item-pixmap.cpp' */
/* modified 2022-11-06T12:45:56, size 10622 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemPixmap
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemPixmap
\brief An arbitrary pixmap
\image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will
be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to
fit the rectangle or be drawn aligned to the topLeft position.
If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown
on the right side of the example image), the pixmap will be flipped in the respective
orientations.
*/
/*!
Creates a rectangle item and sets default values.
The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
*/
QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
topLeft(createPosition(QLatin1String("topLeft"))),
bottomRight(createPosition(QLatin1String("bottomRight"))),
top(createAnchor(QLatin1String("top"), aiTop)),
topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
right(createAnchor(QLatin1String("right"), aiRight)),
bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
left(createAnchor(QLatin1String("left"), aiLeft)),
mScaled(false),
mScaledPixmapInvalidated(true),
mAspectRatioMode(Qt::KeepAspectRatio),
mTransformationMode(Qt::SmoothTransformation)
{
topLeft->setCoords(0, 1);
bottomRight->setCoords(1, 0);
setPen(Qt::NoPen);
setSelectedPen(QPen(Qt::blue));
}
QCPItemPixmap::~QCPItemPixmap()
{
}
/*!
Sets the pixmap that will be displayed.
*/
void QCPItemPixmap::setPixmap(const QPixmap &pixmap)
{
mPixmap = pixmap;
mScaledPixmapInvalidated = true;
if (mPixmap.isNull())
qDebug() << Q_FUNC_INFO << "pixmap is null";
}
/*!
Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a
bottomRight positions.
*/
void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode)
{
mScaled = scaled;
mAspectRatioMode = aspectRatioMode;
mTransformationMode = transformationMode;
mScaledPixmapInvalidated = true;
}
/*!
Sets the pen that will be used to draw a border around the pixmap.
\see setSelectedPen, setBrush
*/
void QCPItemPixmap::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw a border around the pixmap when selected
\see setPen, setSelected
*/
void QCPItemPixmap::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/* inherits documentation from base class */
double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
return rectDistance(getFinalRect(), pos, true);
}
/* inherits documentation from base class */
void QCPItemPixmap::draw(QCPPainter *painter)
{
bool flipHorz = false;
bool flipVert = false;
QRect rect = getFinalRect(&flipHorz, &flipVert);
int clipPad = mainPen().style() == Qt::NoPen ? 0 : qCeil(mainPen().widthF());
QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
if (boundingRect.intersects(clipRect()))
{
updateScaledPixmap(rect, flipHorz, flipVert);
painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap);
QPen pen = mainPen();
if (pen.style() != Qt::NoPen)
{
painter->setPen(pen);
painter->setBrush(Qt::NoBrush);
painter->drawRect(rect);
}
}
}
/* inherits documentation from base class */
QPointF QCPItemPixmap::anchorPixelPosition(int anchorId) const
{
bool flipHorz = false;
bool flipVert = false;
QRect rect = getFinalRect(&flipHorz, &flipVert);
// we actually want denormal rects (negative width/height) here, so restore
// the flipped state:
if (flipHorz)
rect.adjust(rect.width(), 0, -rect.width(), 0);
if (flipVert)
rect.adjust(0, rect.height(), 0, -rect.height());
switch (anchorId)
{
case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
case aiTopRight: return rect.topRight();
case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
case aiBottomLeft: return rect.bottomLeft();
case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return {};
}
/*! \internal
Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The
parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped
horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a
bottomRight.)
This function only creates the scaled pixmap when the buffered pixmap has a different size than
the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does
not cause expensive rescaling every time.
If scaling is disabled, sets mScaledPixmap to a null QPixmap.
*/
void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert)
{
if (mPixmap.isNull())
return;
if (mScaled)
{
#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
double devicePixelRatio = mPixmap.devicePixelRatio();
#else
double devicePixelRatio = 1.0;
#endif
if (finalRect.isNull())
finalRect = getFinalRect(&flipHorz, &flipVert);
if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()/devicePixelRatio)
{
mScaledPixmap = mPixmap.scaled(finalRect.size()*devicePixelRatio, mAspectRatioMode, mTransformationMode);
if (flipHorz || flipVert)
mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert));
#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
mScaledPixmap.setDevicePixelRatio(devicePixelRatio);
#endif
}
} else if (!mScaledPixmap.isNull())
mScaledPixmap = QPixmap();
mScaledPixmapInvalidated = false;
}
/*! \internal
Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions
and scaling settings.
The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn
flipped horizontally or vertically in the returned rect. (The returned rect itself is always
normalized, i.e. the top left corner of the rect is actually further to the top/left than the
bottom right corner). This is the case when the item position \a topLeft is further to the
bottom/right than \a bottomRight.
If scaling is disabled, returns a rect with size of the original pixmap and the top left corner
aligned with the item position \a topLeft. The position \a bottomRight is ignored.
*/
QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const
{
QRect result;
bool flipHorz = false;
bool flipVert = false;
QPoint p1 = topLeft->pixelPosition().toPoint();
QPoint p2 = bottomRight->pixelPosition().toPoint();
if (p1 == p2)
return {p1, QSize(0, 0)};
if (mScaled)
{
QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y());
QPoint topLeft = p1;
if (newSize.width() < 0)
{
flipHorz = true;
newSize.rwidth() *= -1;
topLeft.setX(p2.x());
}
if (newSize.height() < 0)
{
flipVert = true;
newSize.rheight() *= -1;
topLeft.setY(p2.y());
}
QSize scaledSize = mPixmap.size();
#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
scaledSize /= mPixmap.devicePixelRatio();
scaledSize.scale(newSize*mPixmap.devicePixelRatio(), mAspectRatioMode);
#else
scaledSize.scale(newSize, mAspectRatioMode);
#endif
result = QRect(topLeft, scaledSize);
} else
{
#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
result = QRect(p1, mPixmap.size()/mPixmap.devicePixelRatio());
#else
result = QRect(p1, mPixmap.size());
#endif
}
if (flippedHorz)
*flippedHorz = flipHorz;
if (flippedVert)
*flippedVert = flipVert;
return result;
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemPixmap::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/* end of 'src/items/item-pixmap.cpp' */
/* including file 'src/items/item-tracer.cpp' */
/* modified 2022-11-06T12:45:56, size 14645 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemTracer
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemTracer
\brief Item that sticks to QCPGraph data points
\image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions."
The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt
the coordinate axes of the graph and update its \a position to be on the graph's data. This means
the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a
QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a
position will have no effect because they will be overriden in the next redraw (this is when the
coordinate update happens).
If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will
stay at the corresponding end of the graph.
With \ref setInterpolating you may specify whether the tracer may only stay exactly on data
points or whether it interpolates data points linearly, if given a key that lies between two data
points of the graph.
The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer
have no own visual appearance (set the style to \ref tsNone), and just connect other item
positions to the tracer \a position (used as an anchor) via \ref
QCPItemPosition::setParentAnchor.
\note The tracer position is only automatically updated upon redraws. So when the data of the
graph changes and immediately afterwards (without a redraw) the position coordinates of the
tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref
updatePosition must be called manually, prior to reading the tracer coordinates.
*/
/*!
Creates a tracer item and sets default values.
The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
*/
QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
position(createPosition(QLatin1String("position"))),
mSize(6),
mStyle(tsCrosshair),
mGraph(nullptr),
mGraphKey(0),
mInterpolating(false)
{
position->setCoords(0, 0);
setBrush(Qt::NoBrush);
setSelectedBrush(Qt::NoBrush);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue, 2));
}
QCPItemTracer::~QCPItemTracer()
{
}
/*!
Sets the pen that will be used to draw the line of the tracer
\see setSelectedPen, setBrush
*/
void QCPItemTracer::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line of the tracer when selected
\see setPen, setSelected
*/
void QCPItemTracer::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the brush that will be used to draw any fills of the tracer
\see setSelectedBrush, setPen
*/
void QCPItemTracer::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the brush that will be used to draw any fills of the tracer, when selected.
\see setBrush, setSelected
*/
void QCPItemTracer::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/*!
Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare
does, \ref tsCrosshair does not).
*/
void QCPItemTracer::setSize(double size)
{
mSize = size;
}
/*!
Sets the style/visual appearance of the tracer.
If you only want to use the tracer \a position as an anchor for other items, set \a style to
\ref tsNone.
*/
void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style)
{
mStyle = style;
}
/*!
Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type
QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph.
To free the tracer from any graph, set \a graph to \c nullptr. The tracer \a position can then be
placed freely like any other item position. This is the state the tracer will assume when its
graph gets deleted while still attached to it.
\see setGraphKey
*/
void QCPItemTracer::setGraph(QCPGraph *graph)
{
if (graph)
{
if (graph->parentPlot() == mParentPlot)
{
position->setType(QCPItemPosition::ptPlotCoords);
position->setAxes(graph->keyAxis(), graph->valueAxis());
mGraph = graph;
updatePosition();
} else
qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item";
} else
{
mGraph = nullptr;
}
}
/*!
Sets the key of the graph's data point the tracer will be positioned at. This is the only free
coordinate of a tracer when attached to a graph.
Depending on \ref setInterpolating, the tracer will be either positioned on the data point
closest to \a key, or will stay exactly at \a key and interpolate the value linearly.
\see setGraph, setInterpolating
*/
void QCPItemTracer::setGraphKey(double key)
{
mGraphKey = key;
}
/*!
Sets whether the value of the graph's data points shall be interpolated, when positioning the
tracer.
If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on
the data point of the graph which is closest to the key, but which is not necessarily exactly
there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and
the appropriate value will be interpolated from the graph's data points linearly.
\see setGraph, setGraphKey
*/
void QCPItemTracer::setInterpolating(bool enabled)
{
mInterpolating = enabled;
}
/* inherits documentation from base class */
double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
QPointF center(position->pixelPosition());
double w = mSize/2.0;
QRect clip = clipRect();
switch (mStyle)
{
case tsNone: return -1;
case tsPlus:
{
if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(center+QPointF(-w, 0), center+QPointF(w, 0)),
QCPVector2D(pos).distanceSquaredToLine(center+QPointF(0, -w), center+QPointF(0, w))));
break;
}
case tsCrosshair:
{
return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(clip.left(), center.y()), QCPVector2D(clip.right(), center.y())),
QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(center.x(), clip.top()), QCPVector2D(center.x(), clip.bottom()))));
}
case tsCircle:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
{
// distance to border:
double centerDist = QCPVector2D(center-pos).length();
double circleLine = w;
double result = qAbs(centerDist-circleLine);
// filled ellipse, allow click inside to count as hit:
if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
{
if (centerDist <= circleLine)
result = mParentPlot->selectionTolerance()*0.99;
}
return result;
}
break;
}
case tsSquare:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
{
QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w));
bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
return rectDistance(rect, pos, filledRect);
}
break;
}
}
return -1;
}
/* inherits documentation from base class */
void QCPItemTracer::draw(QCPPainter *painter)
{
updatePosition();
if (mStyle == tsNone)
return;
painter->setPen(mainPen());
painter->setBrush(mainBrush());
QPointF center(position->pixelPosition());
double w = mSize/2.0;
QRect clip = clipRect();
switch (mStyle)
{
case tsNone: return;
case tsPlus:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
{
painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0)));
painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w)));
}
break;
}
case tsCrosshair:
{
if (center.y() > clip.top() && center.y() < clip.bottom())
painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y()));
if (center.x() > clip.left() && center.x() < clip.right())
painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom()));
break;
}
case tsCircle:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
painter->drawEllipse(center, w, w);
break;
}
case tsSquare:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w)));
break;
}
}
}
/*!
If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a
position to reside on the graph data, depending on the configured key (\ref setGraphKey).
It is called automatically on every redraw and normally doesn't need to be called manually. One
exception is when you want to read the tracer coordinates via \a position and are not sure that
the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw.
In that situation, call this function before accessing \a position, to make sure you don't get
out-of-date coordinates.
If there is no graph set on this tracer, this function does nothing.
*/
void QCPItemTracer::updatePosition()
{
if (mGraph)
{
if (mParentPlot->hasPlottable(mGraph))
{
if (mGraph->data()->size() > 1)
{
QCPGraphDataContainer::const_iterator first = mGraph->data()->constBegin();
QCPGraphDataContainer::const_iterator last = mGraph->data()->constEnd()-1;
if (mGraphKey <= first->key)
position->setCoords(first->key, first->value);
else if (mGraphKey >= last->key)
position->setCoords(last->key, last->value);
else
{
QCPGraphDataContainer::const_iterator it = mGraph->data()->findBegin(mGraphKey);
if (it != mGraph->data()->constEnd()) // mGraphKey is not exactly on last iterator, but somewhere between iterators
{
QCPGraphDataContainer::const_iterator prevIt = it;
++it; // won't advance to constEnd because we handled that case (mGraphKey >= last->key) before
if (mInterpolating)
{
// interpolate between iterators around mGraphKey:
double slope = 0;
if (!qFuzzyCompare(double(it->key), double(prevIt->key)))
slope = (it->value-prevIt->value)/(it->key-prevIt->key);
position->setCoords(mGraphKey, (mGraphKey-prevIt->key)*slope+prevIt->value);
} else
{
// find iterator with key closest to mGraphKey:
if (mGraphKey < (prevIt->key+it->key)*0.5)
position->setCoords(prevIt->key, prevIt->value);
else
position->setCoords(it->key, it->value);
}
} else // mGraphKey is exactly on last iterator (should actually be caught when comparing first/last keys, but this is a failsafe for fp uncertainty)
position->setCoords(it->key, it->value);
}
} else if (mGraph->data()->size() == 1)
{
QCPGraphDataContainer::const_iterator it = mGraph->data()->constBegin();
position->setCoords(it->key, it->value);
} else
qDebug() << Q_FUNC_INFO << "graph has no data";
} else
qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)";
}
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemTracer::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/*! \internal
Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
is not selected and mSelectedBrush when it is.
*/
QBrush QCPItemTracer::mainBrush() const
{
return mSelected ? mSelectedBrush : mBrush;
}
/* end of 'src/items/item-tracer.cpp' */
/* including file 'src/items/item-bracket.cpp' */
/* modified 2022-11-06T12:45:56, size 10705 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemBracket
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemBracket
\brief A bracket for referencing/highlighting certain parts in the plot.
\image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a left and \a right, which define the span of the bracket. If \a left is
actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the
example image.
The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket
stretches away from the embraced span, can be controlled with \ref setLength.
\image html QCPItemBracket-length.png
<center>Demonstrating the effect of different values for \ref setLength, for styles \ref
bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine
or QCPItemCurve) or a text label (QCPItemText), to the bracket.
*/
/*!
Creates a bracket item and sets default values.
The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
*/
QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
left(createPosition(QLatin1String("left"))),
right(createPosition(QLatin1String("right"))),
center(createAnchor(QLatin1String("center"), aiCenter)),
mLength(8),
mStyle(bsCalligraphic)
{
left->setCoords(0, 0);
right->setCoords(1, 1);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue, 2));
}
QCPItemBracket::~QCPItemBracket()
{
}
/*!
Sets the pen that will be used to draw the bracket.
Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the
stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use
\ref setLength, which has a similar effect.
\see setSelectedPen
*/
void QCPItemBracket::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the bracket when selected
\see setPen, setSelected
*/
void QCPItemBracket::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the \a length in pixels how far the bracket extends in the direction towards the embraced
span of the bracket (i.e. perpendicular to the <i>left</i>-<i>right</i>-direction)
\image html QCPItemBracket-length.png
<center>Demonstrating the effect of different values for \ref setLength, for styles \ref
bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
*/
void QCPItemBracket::setLength(double length)
{
mLength = length;
}
/*!
Sets the style of the bracket, i.e. the shape/visual appearance.
\see setPen
*/
void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style)
{
mStyle = style;
}
/* inherits documentation from base class */
double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
QCPVector2D p(pos);
QCPVector2D leftVec(left->pixelPosition());
QCPVector2D rightVec(right->pixelPosition());
if (leftVec.toPoint() == rightVec.toPoint())
return -1;
QCPVector2D widthVec = (rightVec-leftVec)*0.5;
QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
switch (mStyle)
{
case QCPItemBracket::bsSquare:
case QCPItemBracket::bsRound:
{
double a = p.distanceSquaredToLine(centerVec-widthVec, centerVec+widthVec);
double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec, centerVec-widthVec);
double c = p.distanceSquaredToLine(centerVec+widthVec+lengthVec, centerVec+widthVec);
return qSqrt(qMin(qMin(a, b), c));
}
case QCPItemBracket::bsCurly:
case QCPItemBracket::bsCalligraphic:
{
double a = p.distanceSquaredToLine(centerVec-widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec*0.7, centerVec-widthVec*0.75+lengthVec*0.15);
double c = p.distanceSquaredToLine(centerVec+widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
double d = p.distanceSquaredToLine(centerVec+widthVec+lengthVec*0.7, centerVec+widthVec*0.75+lengthVec*0.15);
return qSqrt(qMin(qMin(a, b), qMin(c, d)));
}
}
return -1;
}
/* inherits documentation from base class */
void QCPItemBracket::draw(QCPPainter *painter)
{
QCPVector2D leftVec(left->pixelPosition());
QCPVector2D rightVec(right->pixelPosition());
if (leftVec.toPoint() == rightVec.toPoint())
return;
QCPVector2D widthVec = (rightVec-leftVec)*0.5;
QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
QPolygon boundingPoly;
boundingPoly << leftVec.toPoint() << rightVec.toPoint()
<< (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint();
const int clipEnlarge = qCeil(mainPen().widthF());
QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
if (clip.intersects(boundingPoly.boundingRect()))
{
painter->setPen(mainPen());
switch (mStyle)
{
case bsSquare:
{
painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF());
painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
break;
}
case bsRound:
{
painter->setBrush(Qt::NoBrush);
QPainterPath path;
path.moveTo((centerVec+widthVec+lengthVec).toPointF());
path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF());
path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
painter->drawPath(path);
break;
}
case bsCurly:
{
painter->setBrush(Qt::NoBrush);
QPainterPath path;
path.moveTo((centerVec+widthVec+lengthVec).toPointF());
path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+lengthVec).toPointF(), centerVec.toPointF());
path.cubicTo((centerVec-0.4*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
painter->drawPath(path);
break;
}
case bsCalligraphic:
{
painter->setPen(Qt::NoPen);
painter->setBrush(QBrush(mainPen().color()));
QPainterPath path;
path.moveTo((centerVec+widthVec+lengthVec).toPointF());
path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+0.8*lengthVec).toPointF(), centerVec.toPointF());
path.cubicTo((centerVec-0.4*widthVec+0.8*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
path.cubicTo((centerVec-widthVec-lengthVec*0.5).toPointF(), (centerVec-0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+lengthVec*0.2).toPointF());
path.cubicTo((centerVec+0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
painter->drawPath(path);
break;
}
}
}
}
/* inherits documentation from base class */
QPointF QCPItemBracket::anchorPixelPosition(int anchorId) const
{
QCPVector2D leftVec(left->pixelPosition());
QCPVector2D rightVec(right->pixelPosition());
if (leftVec.toPoint() == rightVec.toPoint())
return leftVec.toPointF();
QCPVector2D widthVec = (rightVec-leftVec)*0.5;
QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
switch (anchorId)
{
case aiCenter:
return centerVec.toPointF();
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return {};
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the
item is not selected and mSelectedPen when it is.
*/
QPen QCPItemBracket::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/* end of 'src/items/item-bracket.cpp' */
/* including file 'src/polar/radialaxis.cpp' */
/* modified 2022-11-06T12:45:57, size 49415 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPolarAxisRadial
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPolarAxisRadial
\brief The radial axis inside a radial plot
\warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
functionality to be incomplete, as well as changing public interfaces in the future.
Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
documentation of QCPAxisTicker.
*/
/* start of documentation of inline functions */
/*! \fn QSharedPointer<QCPAxisTicker> QCPPolarAxisRadial::ticker() const
Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
responsible for generating the tick positions and tick labels of this axis. You can access the
\ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
(\ref QCPAxisTicker::setTickCount).
You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
the documentation there. A new axis ticker can be set with \ref setTicker.
Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
ticker simply by passing the same shared pointer to multiple axes.
\see setTicker
*/
/* end of documentation of inline functions */
/* start of documentation of signals */
/*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange)
This signal is emitted when the range of this axis has changed. You can connect it to the \ref
setRange slot of another axis to communicate the new range to the other axis, in order for it to
be synchronized.
You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
slot would limit the x axis to ranges between 0 and 10:
\code
customPlot->xAxis->setRange(newRange.bounded(0, 10))
\endcode
*/
/*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
\overload
Additionally to the new range, this signal also provides the previous range held by the axis as
\a oldRange.
*/
/*! \fn void QCPPolarAxisRadial::scaleTypeChanged(QCPPolarAxisRadial::ScaleType scaleType);
This signal is emitted when the scale type changes, by calls to \ref setScaleType
*/
/*! \fn void QCPPolarAxisRadial::selectionChanged(QCPPolarAxisRadial::SelectableParts selection)
This signal is emitted when the selection state of this axis has changed, either by user interaction
or by a direct call to \ref setSelectedParts.
*/
/*! \fn void QCPPolarAxisRadial::selectableChanged(const QCPPolarAxisRadial::SelectableParts &parts);
This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
*/
/* end of documentation of signals */
/*!
Constructs an Axis instance of Type \a type for the axis rect \a parent.
Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
create them manually and then inject them also via \ref QCPAxisRect::addAxis.
*/
QCPPolarAxisRadial::QCPPolarAxisRadial(QCPPolarAxisAngular *parent) :
QCPLayerable(parent->parentPlot(), QString(), parent),
mRangeDrag(true),
mRangeZoom(true),
mRangeZoomFactor(0.85),
// axis base:
mAngularAxis(parent),
mAngle(45),
mAngleReference(arAngularAxis),
mSelectableParts(spAxis | spTickLabels | spAxisLabel),
mSelectedParts(spNone),
mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedBasePen(QPen(Qt::blue, 2)),
// axis label:
mLabelPadding(0),
mLabel(),
mLabelFont(mParentPlot->font()),
mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
mLabelColor(Qt::black),
mSelectedLabelColor(Qt::blue),
// tick labels:
// mTickLabelPadding(0), in label painter
mTickLabels(true),
// mTickLabelRotation(0), in label painter
mTickLabelFont(mParentPlot->font()),
mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
mTickLabelColor(Qt::black),
mSelectedTickLabelColor(Qt::blue),
mNumberPrecision(6),
mNumberFormatChar('g'),
mNumberBeautifulPowers(true),
mNumberMultiplyCross(false),
// ticks and subticks:
mTicks(true),
mSubTicks(true),
mTickLengthIn(5),
mTickLengthOut(0),
mSubTickLengthIn(2),
mSubTickLengthOut(0),
mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedTickPen(QPen(Qt::blue, 2)),
mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedSubTickPen(QPen(Qt::blue, 2)),
// scale and range:
mRange(0, 5),
mRangeReversed(false),
mScaleType(stLinear),
// internal members:
mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect
mTicker(new QCPAxisTicker),
mLabelPainter(mParentPlot)
{
setParent(parent);
setAntialiased(true);
setTickLabelPadding(5);
setTickLabelRotation(0);
setTickLabelMode(lmUpright);
mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artTangent);
mLabelPainter.setAbbreviateDecimalPowers(false);
}
QCPPolarAxisRadial::~QCPPolarAxisRadial()
{
}
QCPPolarAxisRadial::LabelMode QCPPolarAxisRadial::tickLabelMode() const
{
switch (mLabelPainter.anchorMode())
{
case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright;
case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated;
default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break;
}
return lmUpright;
}
/* No documentation as it is a property getter */
QString QCPPolarAxisRadial::numberFormat() const
{
QString result;
result.append(mNumberFormatChar);
if (mNumberBeautifulPowers)
{
result.append(QLatin1Char('b'));
if (mNumberMultiplyCross)
result.append(QLatin1Char('c'));
}
return result;
}
/* No documentation as it is a property getter */
int QCPPolarAxisRadial::tickLengthIn() const
{
return mTickLengthIn;
}
/* No documentation as it is a property getter */
int QCPPolarAxisRadial::tickLengthOut() const
{
return mTickLengthOut;
}
/* No documentation as it is a property getter */
int QCPPolarAxisRadial::subTickLengthIn() const
{
return mSubTickLengthIn;
}
/* No documentation as it is a property getter */
int QCPPolarAxisRadial::subTickLengthOut() const
{
return mSubTickLengthOut;
}
/* No documentation as it is a property getter */
int QCPPolarAxisRadial::labelPadding() const
{
return mLabelPadding;
}
void QCPPolarAxisRadial::setRangeDrag(bool enabled)
{
mRangeDrag = enabled;
}
void QCPPolarAxisRadial::setRangeZoom(bool enabled)
{
mRangeZoom = enabled;
}
void QCPPolarAxisRadial::setRangeZoomFactor(double factor)
{
mRangeZoomFactor = factor;
}
/*!
Sets whether the axis uses a linear scale or a logarithmic scale.
Note that this method controls the coordinate transformation. For logarithmic scales, you will
likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
the axis ticker to an instance of \ref QCPAxisTickerLog :
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation
See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
creation.
\ref setNumberPrecision
*/
void QCPPolarAxisRadial::setScaleType(QCPPolarAxisRadial::ScaleType type)
{
if (mScaleType != type)
{
mScaleType = type;
if (mScaleType == stLogarithmic)
setRange(mRange.sanitizedForLogScale());
//mCachedMarginValid = false;
emit scaleTypeChanged(mScaleType);
}
}
/*!
Sets the range of the axis.
This slot may be connected with the \ref rangeChanged signal of another axis so this axis
is always synchronized with the other axis range, when it changes.
To invert the direction of an axis, use \ref setRangeReversed.
*/
void QCPPolarAxisRadial::setRange(const QCPRange &range)
{
if (range.lower == mRange.lower && range.upper == mRange.upper)
return;
if (!QCPRange::validRange(range)) return;
QCPRange oldRange = mRange;
if (mScaleType == stLogarithmic)
{
mRange = range.sanitizedForLogScale();
} else
{
mRange = range.sanitizedForLinScale();
}
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
(When \ref QCustomPlot::setInteractions contains iSelectAxes.)
However, even when \a selectable is set to a value not allowing the selection of a specific part,
it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
directly.
\see SelectablePart, setSelectedParts
*/
void QCPPolarAxisRadial::setSelectableParts(const SelectableParts &selectable)
{
if (mSelectableParts != selectable)
{
mSelectableParts = selectable;
emit selectableChanged(mSelectableParts);
}
}
/*!
Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
is selected, it uses a different pen/font.
The entire selection mechanism for axes is handled automatically when \ref
QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
wish to change the selection state manually.
This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
\see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
*/
void QCPPolarAxisRadial::setSelectedParts(const SelectableParts &selected)
{
if (mSelectedParts != selected)
{
mSelectedParts = selected;
emit selectionChanged(mSelectedParts);
}
}
/*!
\overload
Sets the lower and upper bound of the axis range.
To invert the direction of an axis, use \ref setRangeReversed.
There is also a slot to set a range, see \ref setRange(const QCPRange &range).
*/
void QCPPolarAxisRadial::setRange(double lower, double upper)
{
if (lower == mRange.lower && upper == mRange.upper)
return;
if (!QCPRange::validRange(lower, upper)) return;
QCPRange oldRange = mRange;
mRange.lower = lower;
mRange.upper = upper;
if (mScaleType == stLogarithmic)
{
mRange = mRange.sanitizedForLogScale();
} else
{
mRange = mRange.sanitizedForLinScale();
}
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
\overload
Sets the range of the axis.
The \a position coordinate indicates together with the \a alignment parameter, where the new
range will be positioned. \a size defines the size of the new axis range. \a alignment may be
Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
or center of the range to be aligned with \a position. Any other values of \a alignment will
default to Qt::AlignCenter.
*/
void QCPPolarAxisRadial::setRange(double position, double size, Qt::AlignmentFlag alignment)
{
if (alignment == Qt::AlignLeft)
setRange(position, position+size);
else if (alignment == Qt::AlignRight)
setRange(position-size, position);
else // alignment == Qt::AlignCenter
setRange(position-size/2.0, position+size/2.0);
}
/*!
Sets the lower bound of the axis range. The upper bound is not changed.
\see setRange
*/
void QCPPolarAxisRadial::setRangeLower(double lower)
{
if (mRange.lower == lower)
return;
QCPRange oldRange = mRange;
mRange.lower = lower;
if (mScaleType == stLogarithmic)
{
mRange = mRange.sanitizedForLogScale();
} else
{
mRange = mRange.sanitizedForLinScale();
}
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets the upper bound of the axis range. The lower bound is not changed.
\see setRange
*/
void QCPPolarAxisRadial::setRangeUpper(double upper)
{
if (mRange.upper == upper)
return;
QCPRange oldRange = mRange;
mRange.upper = upper;
if (mScaleType == stLogarithmic)
{
mRange = mRange.sanitizedForLogScale();
} else
{
mRange = mRange.sanitizedForLinScale();
}
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
direction of increasing values is inverted.
Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
of the \ref setRange interface will still reference the mathematically smaller number than the \a
upper part.
*/
void QCPPolarAxisRadial::setRangeReversed(bool reversed)
{
mRangeReversed = reversed;
}
void QCPPolarAxisRadial::setAngle(double degrees)
{
mAngle = degrees;
}
void QCPPolarAxisRadial::setAngleReference(AngleReference reference)
{
mAngleReference = reference;
}
/*!
The axis ticker is responsible for generating the tick positions and tick labels. See the
documentation of QCPAxisTicker for details on how to work with axis tickers.
You can change the tick positioning/labeling behaviour of this axis by setting a different
QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
ticker, access it via \ref ticker.
Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
ticker simply by passing the same shared pointer to multiple axes.
\see ticker
*/
void QCPPolarAxisRadial::setTicker(QSharedPointer<QCPAxisTicker> ticker)
{
if (ticker)
mTicker = ticker;
else
qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
// no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
}
/*!
Sets whether tick marks are displayed.
Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
that, see \ref setTickLabels.
\see setSubTicks
*/
void QCPPolarAxisRadial::setTicks(bool show)
{
if (mTicks != show)
{
mTicks = show;
//mCachedMarginValid = false;
}
}
/*!
Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
*/
void QCPPolarAxisRadial::setTickLabels(bool show)
{
if (mTickLabels != show)
{
mTickLabels = show;
//mCachedMarginValid = false;
if (!mTickLabels)
mTickVectorLabels.clear();
}
}
/*!
Sets the distance between the axis base line (including any outward ticks) and the tick labels.
\see setLabelPadding, setPadding
*/
void QCPPolarAxisRadial::setTickLabelPadding(int padding)
{
mLabelPainter.setPadding(padding);
}
/*!
Sets the font of the tick labels.
\see setTickLabels, setTickLabelColor
*/
void QCPPolarAxisRadial::setTickLabelFont(const QFont &font)
{
if (font != mTickLabelFont)
{
mTickLabelFont = font;
//mCachedMarginValid = false;
}
}
/*!
Sets the color of the tick labels.
\see setTickLabels, setTickLabelFont
*/
void QCPPolarAxisRadial::setTickLabelColor(const QColor &color)
{
mTickLabelColor = color;
}
/*!
Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
from -90 to 90 degrees.
If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
other angles, the label is drawn with an offset such that it seems to point toward or away from
the tick mark.
*/
void QCPPolarAxisRadial::setTickLabelRotation(double degrees)
{
mLabelPainter.setRotation(degrees);
}
void QCPPolarAxisRadial::setTickLabelMode(LabelMode mode)
{
switch (mode)
{
case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break;
case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break;
}
}
/*!
Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
that, see the "Argument Formats" section in the detailed description of the QString class.
\a formatCode is a string of one, two or three characters. The first character is identical to
the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
format, 'g'/'G' scientific or fixed, whichever is shorter.
The second and third characters are optional and specific to QCustomPlot:\n
If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
"5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
"beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
[multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
cross and 183 (0xB7) for the dot.
Examples for \a formatCode:
\li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
normal scientific format is used
\li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
beautifully typeset decimal powers and a dot as multiplication sign
\li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
multiplication sign
\li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
powers. Format code will be reduced to 'f'.
\li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
code will not be changed.
*/
void QCPPolarAxisRadial::setNumberFormat(const QString &formatCode)
{
if (formatCode.isEmpty())
{
qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
return;
}
//mCachedMarginValid = false;
// interpret first char as number format char:
QString allowedFormatChars(QLatin1String("eEfgG"));
if (allowedFormatChars.contains(formatCode.at(0)))
{
mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
} else
{
qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
return;
}
if (formatCode.length() < 2)
{
mNumberBeautifulPowers = false;
mNumberMultiplyCross = false;
} else
{
// interpret second char as indicator for beautiful decimal powers:
if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
mNumberBeautifulPowers = true;
else
qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
if (formatCode.length() < 3)
{
mNumberMultiplyCross = false;
} else
{
// interpret third char as indicator for dot or cross multiplication symbol:
if (formatCode.at(2) == QLatin1Char('c'))
mNumberMultiplyCross = true;
else if (formatCode.at(2) == QLatin1Char('d'))
mNumberMultiplyCross = false;
else
qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
}
}
mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers);
mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot);
}
/*!
Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
for details. The effect of precisions are most notably for number Formats starting with 'e', see
\ref setNumberFormat
*/
void QCPPolarAxisRadial::setNumberPrecision(int precision)
{
if (mNumberPrecision != precision)
{
mNumberPrecision = precision;
//mCachedMarginValid = false;
}
}
/*!
Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
zero, the tick labels and axis label will increase their distance to the axis accordingly, so
they won't collide with the ticks.
\see setSubTickLength, setTickLengthIn, setTickLengthOut
*/
void QCPPolarAxisRadial::setTickLength(int inside, int outside)
{
setTickLengthIn(inside);
setTickLengthOut(outside);
}
/*!
Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
inside the plot.
\see setTickLengthOut, setTickLength, setSubTickLength
*/
void QCPPolarAxisRadial::setTickLengthIn(int inside)
{
if (mTickLengthIn != inside)
{
mTickLengthIn = inside;
}
}
/*!
Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
outside the plot. If \a outside is greater than zero, the tick labels and axis label will
increase their distance to the axis accordingly, so they won't collide with the ticks.
\see setTickLengthIn, setTickLength, setSubTickLength
*/
void QCPPolarAxisRadial::setTickLengthOut(int outside)
{
if (mTickLengthOut != outside)
{
mTickLengthOut = outside;
//mCachedMarginValid = false; // only outside tick length can change margin
}
}
/*!
Sets whether sub tick marks are displayed.
Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
\see setTicks
*/
void QCPPolarAxisRadial::setSubTicks(bool show)
{
if (mSubTicks != show)
{
mSubTicks = show;
//mCachedMarginValid = false;
}
}
/*!
Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
than zero, the tick labels and axis label will increase their distance to the axis accordingly,
so they won't collide with the ticks.
\see setTickLength, setSubTickLengthIn, setSubTickLengthOut
*/
void QCPPolarAxisRadial::setSubTickLength(int inside, int outside)
{
setSubTickLengthIn(inside);
setSubTickLengthOut(outside);
}
/*!
Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
the plot.
\see setSubTickLengthOut, setSubTickLength, setTickLength
*/
void QCPPolarAxisRadial::setSubTickLengthIn(int inside)
{
if (mSubTickLengthIn != inside)
{
mSubTickLengthIn = inside;
}
}
/*!
Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
outside the plot. If \a outside is greater than zero, the tick labels will increase their
distance to the axis accordingly, so they won't collide with the ticks.
\see setSubTickLengthIn, setSubTickLength, setTickLength
*/
void QCPPolarAxisRadial::setSubTickLengthOut(int outside)
{
if (mSubTickLengthOut != outside)
{
mSubTickLengthOut = outside;
//mCachedMarginValid = false; // only outside tick length can change margin
}
}
/*!
Sets the pen, the axis base line is drawn with.
\see setTickPen, setSubTickPen
*/
void QCPPolarAxisRadial::setBasePen(const QPen &pen)
{
mBasePen = pen;
}
/*!
Sets the pen, tick marks will be drawn with.
\see setTickLength, setBasePen
*/
void QCPPolarAxisRadial::setTickPen(const QPen &pen)
{
mTickPen = pen;
}
/*!
Sets the pen, subtick marks will be drawn with.
\see setSubTickCount, setSubTickLength, setBasePen
*/
void QCPPolarAxisRadial::setSubTickPen(const QPen &pen)
{
mSubTickPen = pen;
}
/*!
Sets the font of the axis label.
\see setLabelColor
*/
void QCPPolarAxisRadial::setLabelFont(const QFont &font)
{
if (mLabelFont != font)
{
mLabelFont = font;
//mCachedMarginValid = false;
}
}
/*!
Sets the color of the axis label.
\see setLabelFont
*/
void QCPPolarAxisRadial::setLabelColor(const QColor &color)
{
mLabelColor = color;
}
/*!
Sets the text of the axis label that will be shown below/above or next to the axis, depending on
its orientation. To disable axis labels, pass an empty string as \a str.
*/
void QCPPolarAxisRadial::setLabel(const QString &str)
{
if (mLabel != str)
{
mLabel = str;
//mCachedMarginValid = false;
}
}
/*!
Sets the distance between the tick labels and the axis label.
\see setTickLabelPadding, setPadding
*/
void QCPPolarAxisRadial::setLabelPadding(int padding)
{
if (mLabelPadding != padding)
{
mLabelPadding = padding;
//mCachedMarginValid = false;
}
}
/*!
Sets the font that is used for tick labels when they are selected.
\see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPPolarAxisRadial::setSelectedTickLabelFont(const QFont &font)
{
if (font != mSelectedTickLabelFont)
{
mSelectedTickLabelFont = font;
// don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
}
}
/*!
Sets the font that is used for the axis label when it is selected.
\see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPPolarAxisRadial::setSelectedLabelFont(const QFont &font)
{
mSelectedLabelFont = font;
// don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
}
/*!
Sets the color that is used for tick labels when they are selected.
\see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPPolarAxisRadial::setSelectedTickLabelColor(const QColor &color)
{
if (color != mSelectedTickLabelColor)
{
mSelectedTickLabelColor = color;
}
}
/*!
Sets the color that is used for the axis label when it is selected.
\see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPPolarAxisRadial::setSelectedLabelColor(const QColor &color)
{
mSelectedLabelColor = color;
}
/*!
Sets the pen that is used to draw the axis base line when selected.
\see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPPolarAxisRadial::setSelectedBasePen(const QPen &pen)
{
mSelectedBasePen = pen;
}
/*!
Sets the pen that is used to draw the (major) ticks when selected.
\see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPPolarAxisRadial::setSelectedTickPen(const QPen &pen)
{
mSelectedTickPen = pen;
}
/*!
Sets the pen that is used to draw the subticks when selected.
\see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPPolarAxisRadial::setSelectedSubTickPen(const QPen &pen)
{
mSelectedSubTickPen = pen;
}
/*!
If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
bounds of the range. The range is simply moved by \a diff.
If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
*/
void QCPPolarAxisRadial::moveRange(double diff)
{
QCPRange oldRange = mRange;
if (mScaleType == stLinear)
{
mRange.lower += diff;
mRange.upper += diff;
} else // mScaleType == stLogarithmic
{
mRange.lower *= diff;
mRange.upper *= diff;
}
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Scales the range of this axis by \a factor around the center of the current axis range. For
example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
the center will have moved symmetrically closer).
If you wish to scale around a different coordinate than the current axis range center, use the
overload \ref scaleRange(double factor, double center).
*/
void QCPPolarAxisRadial::scaleRange(double factor)
{
scaleRange(factor, range().center());
}
/*! \overload
Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
around 1.0 will have moved symmetrically closer to 1.0).
\see scaleRange(double factor)
*/
void QCPPolarAxisRadial::scaleRange(double factor, double center)
{
QCPRange oldRange = mRange;
if (mScaleType == stLinear)
{
QCPRange newRange;
newRange.lower = (mRange.lower-center)*factor + center;
newRange.upper = (mRange.upper-center)*factor + center;
if (QCPRange::validRange(newRange))
mRange = newRange.sanitizedForLinScale();
} else // mScaleType == stLogarithmic
{
if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
{
QCPRange newRange;
newRange.lower = qPow(mRange.lower/center, factor)*center;
newRange.upper = qPow(mRange.upper/center, factor)*center;
if (QCPRange::validRange(newRange))
mRange = newRange.sanitizedForLogScale();
} else
qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
}
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Changes the axis range such that all plottables associated with this axis are fully visible in
that dimension.
\see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
*/
void QCPPolarAxisRadial::rescale(bool onlyVisiblePlottables)
{
Q_UNUSED(onlyVisiblePlottables)
/* TODO
QList<QCPAbstractPlottable*> p = plottables();
QCPRange newRange;
bool haveRange = false;
for (int i=0; i<p.size(); ++i)
{
if (!p.at(i)->realVisibility() && onlyVisiblePlottables)
continue;
QCPRange plottableRange;
bool currentFoundRange;
QCP::SignDomain signDomain = QCP::sdBoth;
if (mScaleType == stLogarithmic)
signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
if (p.at(i)->keyAxis() == this)
plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain);
else
plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain);
if (currentFoundRange)
{
if (!haveRange)
newRange = plottableRange;
else
newRange.expand(plottableRange);
haveRange = true;
}
}
if (haveRange)
{
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
if (mScaleType == stLinear)
{
newRange.lower = center-mRange.size()/2.0;
newRange.upper = center+mRange.size()/2.0;
} else // mScaleType == stLogarithmic
{
newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
}
}
setRange(newRange);
}
*/
}
/*!
Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
*/
void QCPPolarAxisRadial::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const
{
QCPVector2D posVector(pixelPos-mCenter);
radiusCoord = radiusToCoord(posVector.length());
angleCoord = mAngularAxis->angleRadToCoord(posVector.angle());
}
/*!
Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
*/
QPointF QCPPolarAxisRadial::coordToPixel(double angleCoord, double radiusCoord) const
{
const double radiusPixel = coordToRadius(radiusCoord);
const double angleRad = mAngularAxis->coordToAngleRad(angleCoord);
return QPointF(mCenter.x()+qCos(angleRad)*radiusPixel, mCenter.y()+qSin(angleRad)*radiusPixel);
}
double QCPPolarAxisRadial::coordToRadius(double coord) const
{
if (mScaleType == stLinear)
{
if (!mRangeReversed)
return (coord-mRange.lower)/mRange.size()*mRadius;
else
return (mRange.upper-coord)/mRange.size()*mRadius;
} else // mScaleType == stLogarithmic
{
if (coord >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just return outside visible range
return !mRangeReversed ? mRadius+200 : mRadius-200;
else if (coord <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just return outside visible range
return !mRangeReversed ? mRadius-200 :mRadius+200;
else
{
if (!mRangeReversed)
return qLn(coord/mRange.lower)/qLn(mRange.upper/mRange.lower)*mRadius;
else
return qLn(mRange.upper/coord)/qLn(mRange.upper/mRange.lower)*mRadius;
}
}
}
double QCPPolarAxisRadial::radiusToCoord(double radius) const
{
if (mScaleType == stLinear)
{
if (!mRangeReversed)
return (radius)/mRadius*mRange.size()+mRange.lower;
else
return -(radius)/mRadius*mRange.size()+mRange.upper;
} else // mScaleType == stLogarithmic
{
if (!mRangeReversed)
return qPow(mRange.upper/mRange.lower, (radius)/mRadius)*mRange.lower;
else
return qPow(mRange.upper/mRange.lower, (-radius)/mRadius)*mRange.upper;
}
}
/*!
Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
function does not change the current selection state of the axis.
If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
\see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
*/
QCPPolarAxisRadial::SelectablePart QCPPolarAxisRadial::getPartAt(const QPointF &pos) const
{
Q_UNUSED(pos) // TODO remove later
if (!mVisible)
return spNone;
/*
TODO:
if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
return spAxis;
else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
return spTickLabels;
else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
return spAxisLabel;
else
return spNone;
*/
return spNone;
}
/* inherits documentation from base class */
double QCPPolarAxisRadial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
if (!mParentPlot) return -1;
SelectablePart part = getPartAt(pos);
if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
return -1;
if (details)
details->setValue(part);
return mParentPlot->selectionTolerance()*0.99;
}
/* inherits documentation from base class */
void QCPPolarAxisRadial::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
SelectablePart part = details.value<SelectablePart>();
if (mSelectableParts.testFlag(part))
{
SelectableParts selBefore = mSelectedParts;
setSelectedParts(additive ? mSelectedParts^part : part);
if (selectionStateChanged)
*selectionStateChanged = mSelectedParts != selBefore;
}
}
/* inherits documentation from base class */
void QCPPolarAxisRadial::deselectEvent(bool *selectionStateChanged)
{
SelectableParts selBefore = mSelectedParts;
setSelectedParts(mSelectedParts & ~mSelectableParts);
if (selectionStateChanged)
*selectionStateChanged = mSelectedParts != selBefore;
}
/*! \internal
This mouse event reimplementation provides the functionality to let the user drag individual axes
exclusively, by startig the drag on top of the axis.
For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect
must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis
(\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref
QCPAxisRect::setRangeDragAxes)
\seebaseclassmethod
\note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
*/
void QCPPolarAxisRadial::mousePressEvent(QMouseEvent *event, const QVariant &details)
{
Q_UNUSED(details)
if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag))
{
event->ignore();
return;
}
if (event->buttons() & Qt::LeftButton)
{
mDragging = true;
// initialize antialiasing backup in case we start dragging:
if (mParentPlot->noAntialiasingOnDrag())
{
mAADragBackup = mParentPlot->antialiasedElements();
mNotAADragBackup = mParentPlot->notAntialiasedElements();
}
// Mouse range dragging interaction:
if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
mDragStartRange = mRange;
}
}
/*! \internal
This mouse event reimplementation provides the functionality to let the user drag individual axes
exclusively, by startig the drag on top of the axis.
\seebaseclassmethod
\note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
\see QCPAxis::mousePressEvent
*/
void QCPPolarAxisRadial::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
{
Q_UNUSED(event) // TODO remove later
Q_UNUSED(startPos) // TODO remove later
if (mDragging)
{
/* TODO
const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y();
const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y();
if (mScaleType == QCPPolarAxisRadial::stLinear)
{
const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel);
setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff);
} else if (mScaleType == QCPPolarAxisRadial::stLogarithmic)
{
const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel);
setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff);
}
*/
if (mParentPlot->noAntialiasingOnDrag())
mParentPlot->setNotAntialiasedElements(QCP::aeAll);
mParentPlot->replot(QCustomPlot::rpQueuedReplot);
}
}
/*! \internal
This mouse event reimplementation provides the functionality to let the user drag individual axes
exclusively, by startig the drag on top of the axis.
\seebaseclassmethod
\note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
\see QCPAxis::mousePressEvent
*/
void QCPPolarAxisRadial::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
{
Q_UNUSED(event)
Q_UNUSED(startPos)
mDragging = false;
if (mParentPlot->noAntialiasingOnDrag())
{
mParentPlot->setAntialiasedElements(mAADragBackup);
mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
}
}
/*! \internal
This mouse event reimplementation provides the functionality to let the user zoom individual axes
exclusively, by performing the wheel event on top of the axis.
For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect
must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis
(\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref
QCPAxisRect::setRangeZoomAxes)
\seebaseclassmethod
\note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the
axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent.
*/
void QCPPolarAxisRadial::wheelEvent(QWheelEvent *event)
{
// Mouse range zooming interaction:
if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom))
{
event->ignore();
return;
}
// TODO:
//const double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually
//const double factor = qPow(mRangeZoomFactor, wheelSteps);
//scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y()));
mParentPlot->replot();
}
void QCPPolarAxisRadial::updateGeometry(const QPointF ¢er, double radius)
{
mCenter = center;
mRadius = radius;
if (mRadius < 1) mRadius = 1;
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing axis lines.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\seebaseclassmethod
\see setAntialiased
*/
void QCPPolarAxisRadial::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
}
/*! \internal
Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
\seebaseclassmethod
*/
void QCPPolarAxisRadial::draw(QCPPainter *painter)
{
const double axisAngleRad = (mAngle+(mAngleReference==arAngularAxis ? mAngularAxis->angle() : 0))/180.0*M_PI;
const QPointF axisVector(qCos(axisAngleRad), qSin(axisAngleRad)); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF
const QPointF tickNormal = QCPVector2D(axisVector).perpendicular().toPointF(); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF
// draw baseline:
painter->setPen(getBasePen());
painter->drawLine(QLineF(mCenter, mCenter+axisVector*(mRadius-0.5)));
// draw subticks:
if (!mSubTickVector.isEmpty())
{
painter->setPen(getSubTickPen());
for (int i=0; i<mSubTickVector.size(); ++i)
{
const QPointF tickPosition = mCenter+axisVector*coordToRadius(mSubTickVector.at(i));
painter->drawLine(QLineF(tickPosition-tickNormal*mSubTickLengthIn, tickPosition+tickNormal*mSubTickLengthOut));
}
}
// draw ticks and labels:
if (!mTickVector.isEmpty())
{
mLabelPainter.setAnchorReference(mCenter-axisVector); // subtract (normalized) axisVector, just to prevent degenerate tangents for tick label at exact lower axis range
mLabelPainter.setFont(getTickLabelFont());
mLabelPainter.setColor(getTickLabelColor());
const QPen ticksPen = getTickPen();
painter->setPen(ticksPen);
for (int i=0; i<mTickVector.size(); ++i)
{
const double r = coordToRadius(mTickVector.at(i));
const QPointF tickPosition = mCenter+axisVector*r;
painter->drawLine(QLineF(tickPosition-tickNormal*mTickLengthIn, tickPosition+tickNormal*mTickLengthOut));
// possibly draw tick labels:
if (!mTickVectorLabels.isEmpty())
{
if ((!mRangeReversed && (i < mTickVectorLabels.count()-1 || mRadius-r > 10)) ||
(mRangeReversed && (i > 0 || mRadius-r > 10))) // skip last label if it's closer than 10 pixels to angular axis
mLabelPainter.drawTickLabel(painter, tickPosition+tickNormal*mSubTickLengthOut, mTickVectorLabels.at(i));
}
}
}
}
/*! \internal
Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
QCPAxisTicker::generate on the currently installed ticker.
If a change in the label text/count is detected, the cached axis margin is invalidated to make
sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
*/
void QCPPolarAxisRadial::setupTickVectors()
{
if (!mParentPlot) return;
if ((!mTicks && !mTickLabels) || mRange.size() <= 0) return;
mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0);
}
/*! \internal
Returns the pen that is used to draw the axis base line. Depending on the selection state, this
is either mSelectedBasePen or mBasePen.
*/
QPen QCPPolarAxisRadial::getBasePen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
}
/*! \internal
Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
is either mSelectedTickPen or mTickPen.
*/
QPen QCPPolarAxisRadial::getTickPen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
}
/*! \internal
Returns the pen that is used to draw the subticks. Depending on the selection state, this
is either mSelectedSubTickPen or mSubTickPen.
*/
QPen QCPPolarAxisRadial::getSubTickPen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
}
/*! \internal
Returns the font that is used to draw the tick labels. Depending on the selection state, this
is either mSelectedTickLabelFont or mTickLabelFont.
*/
QFont QCPPolarAxisRadial::getTickLabelFont() const
{
return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
}
/*! \internal
Returns the font that is used to draw the axis label. Depending on the selection state, this
is either mSelectedLabelFont or mLabelFont.
*/
QFont QCPPolarAxisRadial::getLabelFont() const
{
return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
}
/*! \internal
Returns the color that is used to draw the tick labels. Depending on the selection state, this
is either mSelectedTickLabelColor or mTickLabelColor.
*/
QColor QCPPolarAxisRadial::getTickLabelColor() const
{
return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
}
/*! \internal
Returns the color that is used to draw the axis label. Depending on the selection state, this
is either mSelectedLabelColor or mLabelColor.
*/
QColor QCPPolarAxisRadial::getLabelColor() const
{
return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
}
/* inherits documentation from base class */
QCP::Interaction QCPPolarAxisRadial::selectionCategory() const
{
return QCP::iSelectAxes;
}
/* end of 'src/polar/radialaxis.cpp' */
/* including file 'src/polar/layoutelement-angularaxis.cpp' */
/* modified 2022-11-06T12:45:57, size 57266 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPolarAxisAngular
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPolarAxisAngular
\brief The main container for polar plots, representing the angular axis as a circle
\warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
functionality to be incomplete, as well as changing public interfaces in the future.
*/
/* start documentation of inline functions */
/*! \fn QCPLayoutInset *QCPPolarAxisAngular::insetLayout() const
Returns the inset layout of this axis rect. It can be used to place other layout elements (or
even layouts with multiple other elements) inside/on top of an axis rect.
\see QCPLayoutInset
*/
/*! \fn int QCPPolarAxisAngular::left() const
Returns the pixel position of the left border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPPolarAxisAngular::right() const
Returns the pixel position of the right border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPPolarAxisAngular::top() const
Returns the pixel position of the top border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPPolarAxisAngular::bottom() const
Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPPolarAxisAngular::width() const
Returns the pixel width of this axis rect. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPPolarAxisAngular::height() const
Returns the pixel height of this axis rect. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/*! \fn QSize QCPPolarAxisAngular::size() const
Returns the pixel size of this axis rect. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPPolarAxisAngular::topLeft() const
Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPPolarAxisAngular::topRight() const
Returns the top right corner of this axis rect in pixels. Margins are not taken into account
here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPPolarAxisAngular::bottomLeft() const
Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPPolarAxisAngular::bottomRight() const
Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPPolarAxisAngular::center() const
Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/* end documentation of inline functions */
/*!
Creates a QCPPolarAxis instance and sets default values. An axis is added for each of the four
sides, the top and right axes are set invisible initially.
*/
QCPPolarAxisAngular::QCPPolarAxisAngular(QCustomPlot *parentPlot) :
QCPLayoutElement(parentPlot),
mBackgroundBrush(Qt::NoBrush),
mBackgroundScaled(true),
mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
mInsetLayout(new QCPLayoutInset),
mRangeDrag(false),
mRangeZoom(false),
mRangeZoomFactor(0.85),
// axis base:
mAngle(-90),
mAngleRad(mAngle/180.0*M_PI),
mSelectableParts(spAxis | spTickLabels | spAxisLabel),
mSelectedParts(spNone),
mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedBasePen(QPen(Qt::blue, 2)),
// axis label:
mLabelPadding(0),
mLabel(),
mLabelFont(mParentPlot->font()),
mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
mLabelColor(Qt::black),
mSelectedLabelColor(Qt::blue),
// tick labels:
//mTickLabelPadding(0), in label painter
mTickLabels(true),
//mTickLabelRotation(0), in label painter
mTickLabelFont(mParentPlot->font()),
mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
mTickLabelColor(Qt::black),
mSelectedTickLabelColor(Qt::blue),
mNumberPrecision(6),
mNumberFormatChar('g'),
mNumberBeautifulPowers(true),
mNumberMultiplyCross(false),
// ticks and subticks:
mTicks(true),
mSubTicks(true),
mTickLengthIn(5),
mTickLengthOut(0),
mSubTickLengthIn(2),
mSubTickLengthOut(0),
mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedTickPen(QPen(Qt::blue, 2)),
mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedSubTickPen(QPen(Qt::blue, 2)),
// scale and range:
mRange(0, 360),
mRangeReversed(false),
// internal members:
mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect
mGrid(new QCPPolarGrid(this)),
mTicker(new QCPAxisTickerFixed),
mDragging(false),
mLabelPainter(parentPlot)
{
// TODO:
//mInsetLayout->initializeParentPlot(mParentPlot);
//mInsetLayout->setParentLayerable(this);
//mInsetLayout->setParent(this);
if (QCPAxisTickerFixed *fixedTicker = mTicker.dynamicCast<QCPAxisTickerFixed>().data())
{
fixedTicker->setTickStep(30);
}
setAntialiased(true);
setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again
setTickLabelPadding(5);
setTickLabelRotation(0);
setTickLabelMode(lmUpright);
mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artNormal);
mLabelPainter.setAbbreviateDecimalPowers(false);
mLabelPainter.setCacheSize(24); // so we can cache up to 15-degree intervals, polar angular axis uses a bit larger cache than normal axes
setMinimumSize(50, 50);
setMinimumMargins(QMargins(30, 30, 30, 30));
addRadialAxis();
mGrid->setRadialAxis(radialAxis());
}
QCPPolarAxisAngular::~QCPPolarAxisAngular()
{
delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
mGrid = 0;
delete mInsetLayout;
mInsetLayout = 0;
QList<QCPPolarAxisRadial*> radialAxesList = radialAxes();
for (int i=0; i<radialAxesList.size(); ++i)
removeRadialAxis(radialAxesList.at(i));
}
QCPPolarAxisAngular::LabelMode QCPPolarAxisAngular::tickLabelMode() const
{
switch (mLabelPainter.anchorMode())
{
case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright;
case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated;
default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break;
}
return lmUpright;
}
/* No documentation as it is a property getter */
QString QCPPolarAxisAngular::numberFormat() const
{
QString result;
result.append(mNumberFormatChar);
if (mNumberBeautifulPowers)
{
result.append(QLatin1Char('b'));
if (mLabelPainter.multiplicationSymbol() == QCPLabelPainterPrivate::SymbolCross)
result.append(QLatin1Char('c'));
}
return result;
}
/*!
Returns the number of axes on the axis rect side specified with \a type.
\see axis
*/
int QCPPolarAxisAngular::radialAxisCount() const
{
return static_cast<int>(mRadialAxes.size());
}
/*!
Returns the axis with the given \a index on the axis rect side specified with \a type.
\see axisCount, axes
*/
QCPPolarAxisRadial *QCPPolarAxisAngular::radialAxis(int index) const
{
if (index >= 0 && index < mRadialAxes.size())
{
return mRadialAxes.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
return 0;
}
}
/*!
Returns all axes on the axis rect sides specified with \a types.
\a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
multiple sides.
\see axis
*/
QList<QCPPolarAxisRadial*> QCPPolarAxisAngular::radialAxes() const
{
return mRadialAxes;
}
/*!
Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
remove an axis, use \ref removeAxis instead of deleting it manually.
You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was
previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
with this axis rect as parent and with the same axis type as specified in \a type. If this is not
the case, a debug output is generated, the axis is not added, and the method returns 0.
This method can not be used to move \a axis between axis rects. The same \a axis instance must
not be added multiple times to the same or different axis rects.
If an axis rect side already contains one or more axes, the lower and upper endings of the new
axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
QCPLineEnding::esHalfBar.
\see addAxes, setupFullAxesBox
*/
QCPPolarAxisRadial *QCPPolarAxisAngular::addRadialAxis(QCPPolarAxisRadial *axis)
{
QCPPolarAxisRadial *newAxis = axis;
if (!newAxis)
{
newAxis = new QCPPolarAxisRadial(this);
} else // user provided existing axis instance, do some sanity checks
{
if (newAxis->angularAxis() != this)
{
qDebug() << Q_FUNC_INFO << "passed radial axis doesn't have this angular axis as parent angular axis";
return 0;
}
if (radialAxes().contains(newAxis))
{
qDebug() << Q_FUNC_INFO << "passed axis is already owned by this angular axis";
return 0;
}
}
mRadialAxes.append(newAxis);
return newAxis;
}
/*!
Removes the specified \a axis from the axis rect and deletes it.
Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
\see addAxis
*/
bool QCPPolarAxisAngular::removeRadialAxis(QCPPolarAxisRadial *radialAxis)
{
if (mRadialAxes.contains(radialAxis))
{
mRadialAxes.removeOne(radialAxis);
delete radialAxis;
return true;
} else
{
qDebug() << Q_FUNC_INFO << "Radial axis isn't associated with this angular axis:" << reinterpret_cast<quintptr>(radialAxis);
return false;
}
}
QRegion QCPPolarAxisAngular::exactClipRegion() const
{
return QRegion(mCenter.x()-mRadius, mCenter.y()-mRadius, qRound(2*mRadius), qRound(2*mRadius), QRegion::Ellipse);
}
/*!
If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
bounds of the range. The range is simply moved by \a diff.
If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
*/
void QCPPolarAxisAngular::moveRange(double diff)
{
QCPRange oldRange = mRange;
mRange.lower += diff;
mRange.upper += diff;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Scales the range of this axis by \a factor around the center of the current axis range. For
example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
the center will have moved symmetrically closer).
If you wish to scale around a different coordinate than the current axis range center, use the
overload \ref scaleRange(double factor, double center).
*/
void QCPPolarAxisAngular::scaleRange(double factor)
{
scaleRange(factor, range().center());
}
/*! \overload
Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
around 1.0 will have moved symmetrically closer to 1.0).
\see scaleRange(double factor)
*/
void QCPPolarAxisAngular::scaleRange(double factor, double center)
{
QCPRange oldRange = mRange;
QCPRange newRange;
newRange.lower = (mRange.lower-center)*factor + center;
newRange.upper = (mRange.upper-center)*factor + center;
if (QCPRange::validRange(newRange))
mRange = newRange.sanitizedForLinScale();
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Changes the axis range such that all plottables associated with this axis are fully visible in
that dimension.
\see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
*/
void QCPPolarAxisAngular::rescale(bool onlyVisiblePlottables)
{
QCPRange newRange;
bool haveRange = false;
for (int i=0; i<mGraphs.size(); ++i)
{
if (!mGraphs.at(i)->realVisibility() && onlyVisiblePlottables)
continue;
QCPRange range;
bool currentFoundRange;
if (mGraphs.at(i)->keyAxis() == this)
range = mGraphs.at(i)->getKeyRange(currentFoundRange, QCP::sdBoth);
else
range = mGraphs.at(i)->getValueRange(currentFoundRange, QCP::sdBoth);
if (currentFoundRange)
{
if (!haveRange)
newRange = range;
else
newRange.expand(range);
haveRange = true;
}
}
if (haveRange)
{
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
newRange.lower = center-mRange.size()/2.0;
newRange.upper = center+mRange.size()/2.0;
}
setRange(newRange);
}
}
/*!
Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
*/
void QCPPolarAxisAngular::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const
{
if (!mRadialAxes.isEmpty())
mRadialAxes.first()->pixelToCoord(pixelPos, angleCoord, radiusCoord);
else
qDebug() << Q_FUNC_INFO << "no radial axis configured";
}
/*!
Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
*/
QPointF QCPPolarAxisAngular::coordToPixel(double angleCoord, double radiusCoord) const
{
if (!mRadialAxes.isEmpty())
{
return mRadialAxes.first()->coordToPixel(angleCoord, radiusCoord);
} else
{
qDebug() << Q_FUNC_INFO << "no radial axis configured";
return QPointF();
}
}
/*!
Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
function does not change the current selection state of the axis.
If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
\see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
*/
QCPPolarAxisAngular::SelectablePart QCPPolarAxisAngular::getPartAt(const QPointF &pos) const
{
Q_UNUSED(pos) // TODO remove later
if (!mVisible)
return spNone;
/*
TODO:
if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
return spAxis;
else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
return spTickLabels;
else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
return spAxisLabel;
return spNone;
*/
return spNone;
}
/* inherits documentation from base class */
double QCPPolarAxisAngular::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
/*
if (!mParentPlot) return -1;
SelectablePart part = getPartAt(pos);
if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
return -1;
if (details)
details->setValue(part);
return mParentPlot->selectionTolerance()*0.99;
*/
Q_UNUSED(details)
if (onlySelectable)
return -1;
if (QRectF(mOuterRect).contains(pos))
{
if (mParentPlot)
return mParentPlot->selectionTolerance()*0.99;
else
{
qDebug() << Q_FUNC_INFO << "parent plot not defined";
return -1;
}
} else
return -1;
}
/*!
This method is called automatically upon replot and doesn't need to be called by users of
QCPPolarAxisAngular.
Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
QCPInsetLayout::update function.
\seebaseclassmethod
*/
void QCPPolarAxisAngular::update(UpdatePhase phase)
{
QCPLayoutElement::update(phase);
switch (phase)
{
case upPreparation:
{
setupTickVectors();
for (int i=0; i<mRadialAxes.size(); ++i)
mRadialAxes.at(i)->setupTickVectors();
break;
}
case upLayout:
{
mCenter = mRect.center();
mRadius = 0.5*qMin(qAbs(mRect.width()), qAbs(mRect.height()));
if (mRadius < 1) mRadius = 1; // prevent cases where radius might become 0 which causes trouble
for (int i=0; i<mRadialAxes.size(); ++i)
mRadialAxes.at(i)->updateGeometry(mCenter, mRadius);
mInsetLayout->setOuterRect(rect());
break;
}
default: break;
}
// pass update call on to inset layout (doesn't happen automatically, because QCPPolarAxis doesn't derive from QCPLayout):
mInsetLayout->update(phase);
}
/* inherits documentation from base class */
QList<QCPLayoutElement*> QCPPolarAxisAngular::elements(bool recursive) const
{
QList<QCPLayoutElement*> result;
if (mInsetLayout)
{
result << mInsetLayout;
if (recursive)
result << mInsetLayout->elements(recursive);
}
return result;
}
bool QCPPolarAxisAngular::removeGraph(QCPPolarGraph *graph)
{
if (!mGraphs.contains(graph))
{
qDebug() << Q_FUNC_INFO << "graph not in list:" << reinterpret_cast<quintptr>(graph);
return false;
}
// remove plottable from legend:
graph->removeFromLegend();
// remove plottable:
delete graph;
mGraphs.removeOne(graph);
return true;
}
/* inherits documentation from base class */
void QCPPolarAxisAngular::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
}
/* inherits documentation from base class */
void QCPPolarAxisAngular::draw(QCPPainter *painter)
{
drawBackground(painter, mCenter, mRadius);
// draw baseline circle:
painter->setPen(getBasePen());
painter->drawEllipse(mCenter, mRadius, mRadius);
// draw subticks:
if (!mSubTickVector.isEmpty())
{
painter->setPen(getSubTickPen());
for (int i=0; i<mSubTickVector.size(); ++i)
{
painter->drawLine(mCenter+mSubTickVectorCosSin.at(i)*(mRadius-mSubTickLengthIn),
mCenter+mSubTickVectorCosSin.at(i)*(mRadius+mSubTickLengthOut));
}
}
// draw ticks and labels:
if (!mTickVector.isEmpty())
{
mLabelPainter.setAnchorReference(mCenter);
mLabelPainter.setFont(getTickLabelFont());
mLabelPainter.setColor(getTickLabelColor());
const QPen ticksPen = getTickPen();
painter->setPen(ticksPen);
for (int i=0; i<mTickVector.size(); ++i)
{
const QPointF outerTick = mCenter+mTickVectorCosSin.at(i)*(mRadius+mTickLengthOut);
painter->drawLine(mCenter+mTickVectorCosSin.at(i)*(mRadius-mTickLengthIn), outerTick);
// draw tick labels:
if (!mTickVectorLabels.isEmpty())
{
if (i < mTickVectorLabels.count()-1 || (mTickVectorCosSin.at(i)-mTickVectorCosSin.first()).manhattanLength() > 5/180.0*M_PI) // skip last label if it's closer than approx 5 degrees to first
mLabelPainter.drawTickLabel(painter, outerTick, mTickVectorLabels.at(i));
}
}
}
}
/* inherits documentation from base class */
QCP::Interaction QCPPolarAxisAngular::selectionCategory() const
{
return QCP::iSelectAxes;
}
/*!
Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
backgrounds are usually drawn below everything else.
For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
consider using the overloaded version of this function.
Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
setBackground(const QBrush &brush).
\see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
*/
void QCPPolarAxisAngular::setBackground(const QPixmap &pm)
{
mBackgroundPixmap = pm;
mScaledBackgroundPixmap = QPixmap();
}
/*! \overload
Sets \a brush as the background brush. The axis rect background will be filled with this brush.
Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
are usually drawn below everything else.
The brush will be drawn before (under) any background pixmap, which may be specified with \ref
setBackground(const QPixmap &pm).
To disable drawing of a background brush, set \a brush to Qt::NoBrush.
\see setBackground(const QPixmap &pm)
*/
void QCPPolarAxisAngular::setBackground(const QBrush &brush)
{
mBackgroundBrush = brush;
}
/*! \overload
Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
shall be scaled in one call.
\see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
*/
void QCPPolarAxisAngular::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
{
mBackgroundPixmap = pm;
mScaledBackgroundPixmap = QPixmap();
mBackgroundScaled = scaled;
mBackgroundScaledMode = mode;
}
/*!
Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
is set to true, you may control whether and how the aspect ratio of the original pixmap is
preserved with \ref setBackgroundScaledMode.
Note that the scaled version of the original pixmap is buffered, so there is no performance
penalty on replots. (Except when the axis rect dimensions are changed continuously.)
\see setBackground, setBackgroundScaledMode
*/
void QCPPolarAxisAngular::setBackgroundScaled(bool scaled)
{
mBackgroundScaled = scaled;
}
/*!
If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
\see setBackground, setBackgroundScaled
*/
void QCPPolarAxisAngular::setBackgroundScaledMode(Qt::AspectRatioMode mode)
{
mBackgroundScaledMode = mode;
}
void QCPPolarAxisAngular::setRangeDrag(bool enabled)
{
mRangeDrag = enabled;
}
void QCPPolarAxisAngular::setRangeZoom(bool enabled)
{
mRangeZoom = enabled;
}
void QCPPolarAxisAngular::setRangeZoomFactor(double factor)
{
mRangeZoomFactor = factor;
}
/*!
Sets the range of the axis.
This slot may be connected with the \ref rangeChanged signal of another axis so this axis
is always synchronized with the other axis range, when it changes.
To invert the direction of an axis, use \ref setRangeReversed.
*/
void QCPPolarAxisAngular::setRange(const QCPRange &range)
{
if (range.lower == mRange.lower && range.upper == mRange.upper)
return;
if (!QCPRange::validRange(range)) return;
QCPRange oldRange = mRange;
mRange = range.sanitizedForLinScale();
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
(When \ref QCustomPlot::setInteractions contains iSelectAxes.)
However, even when \a selectable is set to a value not allowing the selection of a specific part,
it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
directly.
\see SelectablePart, setSelectedParts
*/
void QCPPolarAxisAngular::setSelectableParts(const SelectableParts &selectable)
{
if (mSelectableParts != selectable)
{
mSelectableParts = selectable;
emit selectableChanged(mSelectableParts);
}
}
/*!
Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
is selected, it uses a different pen/font.
The entire selection mechanism for axes is handled automatically when \ref
QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
wish to change the selection state manually.
This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
\see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
*/
void QCPPolarAxisAngular::setSelectedParts(const SelectableParts &selected)
{
if (mSelectedParts != selected)
{
mSelectedParts = selected;
emit selectionChanged(mSelectedParts);
}
}
/*!
\overload
Sets the lower and upper bound of the axis range.
To invert the direction of an axis, use \ref setRangeReversed.
There is also a slot to set a range, see \ref setRange(const QCPRange &range).
*/
void QCPPolarAxisAngular::setRange(double lower, double upper)
{
if (lower == mRange.lower && upper == mRange.upper)
return;
if (!QCPRange::validRange(lower, upper)) return;
QCPRange oldRange = mRange;
mRange.lower = lower;
mRange.upper = upper;
mRange = mRange.sanitizedForLinScale();
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
\overload
Sets the range of the axis.
The \a position coordinate indicates together with the \a alignment parameter, where the new
range will be positioned. \a size defines the size of the new axis range. \a alignment may be
Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
or center of the range to be aligned with \a position. Any other values of \a alignment will
default to Qt::AlignCenter.
*/
void QCPPolarAxisAngular::setRange(double position, double size, Qt::AlignmentFlag alignment)
{
if (alignment == Qt::AlignLeft)
setRange(position, position+size);
else if (alignment == Qt::AlignRight)
setRange(position-size, position);
else // alignment == Qt::AlignCenter
setRange(position-size/2.0, position+size/2.0);
}
/*!
Sets the lower bound of the axis range. The upper bound is not changed.
\see setRange
*/
void QCPPolarAxisAngular::setRangeLower(double lower)
{
if (mRange.lower == lower)
return;
QCPRange oldRange = mRange;
mRange.lower = lower;
mRange = mRange.sanitizedForLinScale();
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets the upper bound of the axis range. The lower bound is not changed.
\see setRange
*/
void QCPPolarAxisAngular::setRangeUpper(double upper)
{
if (mRange.upper == upper)
return;
QCPRange oldRange = mRange;
mRange.upper = upper;
mRange = mRange.sanitizedForLinScale();
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
direction of increasing values is inverted.
Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
of the \ref setRange interface will still reference the mathematically smaller number than the \a
upper part.
*/
void QCPPolarAxisAngular::setRangeReversed(bool reversed)
{
mRangeReversed = reversed;
}
void QCPPolarAxisAngular::setAngle(double degrees)
{
mAngle = degrees;
mAngleRad = mAngle/180.0*M_PI;
}
/*!
The axis ticker is responsible for generating the tick positions and tick labels. See the
documentation of QCPAxisTicker for details on how to work with axis tickers.
You can change the tick positioning/labeling behaviour of this axis by setting a different
QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
ticker, access it via \ref ticker.
Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
ticker simply by passing the same shared pointer to multiple axes.
\see ticker
*/
void QCPPolarAxisAngular::setTicker(QSharedPointer<QCPAxisTicker> ticker)
{
if (ticker)
mTicker = ticker;
else
qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
// no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
}
/*!
Sets whether tick marks are displayed.
Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
that, see \ref setTickLabels.
\see setSubTicks
*/
void QCPPolarAxisAngular::setTicks(bool show)
{
if (mTicks != show)
{
mTicks = show;
//mCachedMarginValid = false;
}
}
/*!
Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
*/
void QCPPolarAxisAngular::setTickLabels(bool show)
{
if (mTickLabels != show)
{
mTickLabels = show;
//mCachedMarginValid = false;
if (!mTickLabels)
mTickVectorLabels.clear();
}
}
/*!
Sets the distance between the axis base line (including any outward ticks) and the tick labels.
\see setLabelPadding, setPadding
*/
void QCPPolarAxisAngular::setTickLabelPadding(int padding)
{
mLabelPainter.setPadding(padding);
}
/*!
Sets the font of the tick labels.
\see setTickLabels, setTickLabelColor
*/
void QCPPolarAxisAngular::setTickLabelFont(const QFont &font)
{
mTickLabelFont = font;
}
/*!
Sets the color of the tick labels.
\see setTickLabels, setTickLabelFont
*/
void QCPPolarAxisAngular::setTickLabelColor(const QColor &color)
{
mTickLabelColor = color;
}
/*!
Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
from -90 to 90 degrees.
If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
other angles, the label is drawn with an offset such that it seems to point toward or away from
the tick mark.
*/
void QCPPolarAxisAngular::setTickLabelRotation(double degrees)
{
mLabelPainter.setRotation(degrees);
}
void QCPPolarAxisAngular::setTickLabelMode(LabelMode mode)
{
switch (mode)
{
case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break;
case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break;
}
}
/*!
Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
that, see the "Argument Formats" section in the detailed description of the QString class.
\a formatCode is a string of one, two or three characters. The first character is identical to
the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
format, 'g'/'G' scientific or fixed, whichever is shorter.
The second and third characters are optional and specific to QCustomPlot:\n If the first char was
'e' or 'g', numbers are/might be displayed in the scientific format, e.g. "5.5e9", which might be
visually unappealing in a plot. So when the second char of \a formatCode is set to 'b' (for
"beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
[multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
cross and 183 (0xB7) for the dot.
Examples for \a formatCode:
\li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
normal scientific format is used
\li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
beautifully typeset decimal powers and a dot as multiplication sign
\li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
multiplication sign
\li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
powers. Format code will be reduced to 'f'.
\li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
code will not be changed.
*/
void QCPPolarAxisAngular::setNumberFormat(const QString &formatCode)
{
if (formatCode.isEmpty())
{
qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
return;
}
//mCachedMarginValid = false;
// interpret first char as number format char:
QString allowedFormatChars(QLatin1String("eEfgG"));
if (allowedFormatChars.contains(formatCode.at(0)))
{
mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
} else
{
qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
return;
}
if (formatCode.length() < 2)
{
mNumberBeautifulPowers = false;
mNumberMultiplyCross = false;
} else
{
// interpret second char as indicator for beautiful decimal powers:
if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
mNumberBeautifulPowers = true;
else
qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
if (formatCode.length() < 3)
{
mNumberMultiplyCross = false;
} else
{
// interpret third char as indicator for dot or cross multiplication symbol:
if (formatCode.at(2) == QLatin1Char('c'))
mNumberMultiplyCross = true;
else if (formatCode.at(2) == QLatin1Char('d'))
mNumberMultiplyCross = false;
else
qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
}
}
mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers);
mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot);
}
/*!
Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
for details. The effect of precisions are most notably for number Formats starting with 'e', see
\ref setNumberFormat
*/
void QCPPolarAxisAngular::setNumberPrecision(int precision)
{
if (mNumberPrecision != precision)
{
mNumberPrecision = precision;
//mCachedMarginValid = false;
}
}
/*!
Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
zero, the tick labels and axis label will increase their distance to the axis accordingly, so
they won't collide with the ticks.
\see setSubTickLength, setTickLengthIn, setTickLengthOut
*/
void QCPPolarAxisAngular::setTickLength(int inside, int outside)
{
setTickLengthIn(inside);
setTickLengthOut(outside);
}
/*!
Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
inside the plot.
\see setTickLengthOut, setTickLength, setSubTickLength
*/
void QCPPolarAxisAngular::setTickLengthIn(int inside)
{
if (mTickLengthIn != inside)
{
mTickLengthIn = inside;
}
}
/*!
Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
outside the plot. If \a outside is greater than zero, the tick labels and axis label will
increase their distance to the axis accordingly, so they won't collide with the ticks.
\see setTickLengthIn, setTickLength, setSubTickLength
*/
void QCPPolarAxisAngular::setTickLengthOut(int outside)
{
if (mTickLengthOut != outside)
{
mTickLengthOut = outside;
//mCachedMarginValid = false; // only outside tick length can change margin
}
}
/*!
Sets whether sub tick marks are displayed.
Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
\see setTicks
*/
void QCPPolarAxisAngular::setSubTicks(bool show)
{
if (mSubTicks != show)
{
mSubTicks = show;
//mCachedMarginValid = false;
}
}
/*!
Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
than zero, the tick labels and axis label will increase their distance to the axis accordingly,
so they won't collide with the ticks.
\see setTickLength, setSubTickLengthIn, setSubTickLengthOut
*/
void QCPPolarAxisAngular::setSubTickLength(int inside, int outside)
{
setSubTickLengthIn(inside);
setSubTickLengthOut(outside);
}
/*!
Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
the plot.
\see setSubTickLengthOut, setSubTickLength, setTickLength
*/
void QCPPolarAxisAngular::setSubTickLengthIn(int inside)
{
if (mSubTickLengthIn != inside)
{
mSubTickLengthIn = inside;
}
}
/*!
Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
outside the plot. If \a outside is greater than zero, the tick labels will increase their
distance to the axis accordingly, so they won't collide with the ticks.
\see setSubTickLengthIn, setSubTickLength, setTickLength
*/
void QCPPolarAxisAngular::setSubTickLengthOut(int outside)
{
if (mSubTickLengthOut != outside)
{
mSubTickLengthOut = outside;
//mCachedMarginValid = false; // only outside tick length can change margin
}
}
/*!
Sets the pen, the axis base line is drawn with.
\see setTickPen, setSubTickPen
*/
void QCPPolarAxisAngular::setBasePen(const QPen &pen)
{
mBasePen = pen;
}
/*!
Sets the pen, tick marks will be drawn with.
\see setTickLength, setBasePen
*/
void QCPPolarAxisAngular::setTickPen(const QPen &pen)
{
mTickPen = pen;
}
/*!
Sets the pen, subtick marks will be drawn with.
\see setSubTickCount, setSubTickLength, setBasePen
*/
void QCPPolarAxisAngular::setSubTickPen(const QPen &pen)
{
mSubTickPen = pen;
}
/*!
Sets the font of the axis label.
\see setLabelColor
*/
void QCPPolarAxisAngular::setLabelFont(const QFont &font)
{
if (mLabelFont != font)
{
mLabelFont = font;
//mCachedMarginValid = false;
}
}
/*!
Sets the color of the axis label.
\see setLabelFont
*/
void QCPPolarAxisAngular::setLabelColor(const QColor &color)
{
mLabelColor = color;
}
/*!
Sets the text of the axis label that will be shown below/above or next to the axis, depending on
its orientation. To disable axis labels, pass an empty string as \a str.
*/
void QCPPolarAxisAngular::setLabel(const QString &str)
{
if (mLabel != str)
{
mLabel = str;
//mCachedMarginValid = false;
}
}
/*!
Sets the distance between the tick labels and the axis label.
\see setTickLabelPadding, setPadding
*/
void QCPPolarAxisAngular::setLabelPadding(int padding)
{
if (mLabelPadding != padding)
{
mLabelPadding = padding;
//mCachedMarginValid = false;
}
}
/*!
Sets the font that is used for tick labels when they are selected.
\see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPPolarAxisAngular::setSelectedTickLabelFont(const QFont &font)
{
if (font != mSelectedTickLabelFont)
{
mSelectedTickLabelFont = font;
// don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
}
}
/*!
Sets the font that is used for the axis label when it is selected.
\see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPPolarAxisAngular::setSelectedLabelFont(const QFont &font)
{
mSelectedLabelFont = font;
// don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
}
/*!
Sets the color that is used for tick labels when they are selected.
\see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPPolarAxisAngular::setSelectedTickLabelColor(const QColor &color)
{
if (color != mSelectedTickLabelColor)
{
mSelectedTickLabelColor = color;
}
}
/*!
Sets the color that is used for the axis label when it is selected.
\see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPPolarAxisAngular::setSelectedLabelColor(const QColor &color)
{
mSelectedLabelColor = color;
}
/*!
Sets the pen that is used to draw the axis base line when selected.
\see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPPolarAxisAngular::setSelectedBasePen(const QPen &pen)
{
mSelectedBasePen = pen;
}
/*!
Sets the pen that is used to draw the (major) ticks when selected.
\see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPPolarAxisAngular::setSelectedTickPen(const QPen &pen)
{
mSelectedTickPen = pen;
}
/*!
Sets the pen that is used to draw the subticks when selected.
\see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPPolarAxisAngular::setSelectedSubTickPen(const QPen &pen)
{
mSelectedSubTickPen = pen;
}
/*! \internal
Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
pixmap.
If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
according filling inside the axis rect with the provided \a painter.
Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
the axis rect with the provided \a painter. The scaled version is buffered in
mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
the axis rect has changed in a way that requires a rescale of the background pixmap (this is
dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
set.
\see setBackground, setBackgroundScaled, setBackgroundScaledMode
*/
void QCPPolarAxisAngular::drawBackground(QCPPainter *painter, const QPointF ¢er, double radius)
{
// draw background fill (don't use circular clip, looks bad):
if (mBackgroundBrush != Qt::NoBrush)
{
QPainterPath ellipsePath;
ellipsePath.addEllipse(center, radius, radius);
painter->fillPath(ellipsePath, mBackgroundBrush);
}
// draw background pixmap (on top of fill, if brush specified):
if (!mBackgroundPixmap.isNull())
{
QRegion clipCircle(center.x()-radius, center.y()-radius, qRound(2*radius), qRound(2*radius), QRegion::Ellipse);
QRegion originalClip = painter->clipRegion();
painter->setClipRegion(clipCircle);
if (mBackgroundScaled)
{
// check whether mScaledBackground needs to be updated:
QSize scaledSize(mBackgroundPixmap.size());
scaledSize.scale(mRect.size(), mBackgroundScaledMode);
if (mScaledBackgroundPixmap.size() != scaledSize)
mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
} else
{
painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
}
painter->setClipRegion(originalClip);
}
}
/*! \internal
Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
QCPAxisTicker::generate on the currently installed ticker.
If a change in the label text/count is detected, the cached axis margin is invalidated to make
sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
*/
void QCPPolarAxisAngular::setupTickVectors()
{
if (!mParentPlot) return;
if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
mSubTickVector.clear(); // since we might not pass it to mTicker->generate(), and we don't want old data in there
mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0);
// fill cos/sin buffers which will be used by draw() and QCPPolarGrid::draw(), so we don't have to calculate it twice:
mTickVectorCosSin.resize(mTickVector.size());
for (int i=0; i<mTickVector.size(); ++i)
{
const double theta = coordToAngleRad(mTickVector.at(i));
mTickVectorCosSin[i] = QPointF(qCos(theta), qSin(theta));
}
mSubTickVectorCosSin.resize(mSubTickVector.size());
for (int i=0; i<mSubTickVector.size(); ++i)
{
const double theta = coordToAngleRad(mSubTickVector.at(i));
mSubTickVectorCosSin[i] = QPointF(qCos(theta), qSin(theta));
}
}
/*! \internal
Returns the pen that is used to draw the axis base line. Depending on the selection state, this
is either mSelectedBasePen or mBasePen.
*/
QPen QCPPolarAxisAngular::getBasePen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
}
/*! \internal
Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
is either mSelectedTickPen or mTickPen.
*/
QPen QCPPolarAxisAngular::getTickPen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
}
/*! \internal
Returns the pen that is used to draw the subticks. Depending on the selection state, this
is either mSelectedSubTickPen or mSubTickPen.
*/
QPen QCPPolarAxisAngular::getSubTickPen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
}
/*! \internal
Returns the font that is used to draw the tick labels. Depending on the selection state, this
is either mSelectedTickLabelFont or mTickLabelFont.
*/
QFont QCPPolarAxisAngular::getTickLabelFont() const
{
return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
}
/*! \internal
Returns the font that is used to draw the axis label. Depending on the selection state, this
is either mSelectedLabelFont or mLabelFont.
*/
QFont QCPPolarAxisAngular::getLabelFont() const
{
return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
}
/*! \internal
Returns the color that is used to draw the tick labels. Depending on the selection state, this
is either mSelectedTickLabelColor or mTickLabelColor.
*/
QColor QCPPolarAxisAngular::getTickLabelColor() const
{
return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
}
/*! \internal
Returns the color that is used to draw the axis label. Depending on the selection state, this
is either mSelectedLabelColor or mLabelColor.
*/
QColor QCPPolarAxisAngular::getLabelColor() const
{
return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
}
/*! \internal
Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
pressed, the range dragging interaction is initialized (the actual range manipulation happens in
the \ref mouseMoveEvent).
The mDragging flag is set to true and some anchor points are set that are needed to determine the
distance the mouse was dragged in the mouse move/release events later.
\see mouseMoveEvent, mouseReleaseEvent
*/
void QCPPolarAxisAngular::mousePressEvent(QMouseEvent *event, const QVariant &details)
{
Q_UNUSED(details)
if (event->buttons() & Qt::LeftButton)
{
mDragging = true;
// initialize antialiasing backup in case we start dragging:
if (mParentPlot->noAntialiasingOnDrag())
{
mAADragBackup = mParentPlot->antialiasedElements();
mNotAADragBackup = mParentPlot->notAntialiasedElements();
}
// Mouse range dragging interaction:
if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
{
mDragAngularStart = range();
mDragRadialStart.clear();
for (int i=0; i<mRadialAxes.size(); ++i)
mDragRadialStart.append(mRadialAxes.at(i)->range());
}
}
}
/*! \internal
Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
preceding \ref mousePressEvent, the range is moved accordingly.
\see mousePressEvent, mouseReleaseEvent
*/
void QCPPolarAxisAngular::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
{
Q_UNUSED(startPos)
bool doReplot = false;
// Mouse range dragging interaction:
if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
{
if (mRangeDrag)
{
doReplot = true;
double angleCoordStart, radiusCoordStart;
double angleCoord = 0.0, radiusCoord = 0.0;
pixelToCoord(startPos, angleCoordStart, radiusCoordStart);
pixelToCoord(event->pos(), angleCoord, radiusCoord);
double diff = angleCoordStart - angleCoord;
setRange(mDragAngularStart.lower+diff, mDragAngularStart.upper+diff);
}
for (int i=0; i<mRadialAxes.size(); ++i)
{
QCPPolarAxisRadial *ax = mRadialAxes.at(i);
if (!ax->rangeDrag())
continue;
doReplot = true;
double angleCoordStart, radiusCoordStart;
double angleCoord, radiusCoord;
ax->pixelToCoord(startPos, angleCoordStart, radiusCoordStart);
ax->pixelToCoord(event->pos(), angleCoord, radiusCoord);
if (ax->scaleType() == QCPPolarAxisRadial::stLinear)
{
double diff = radiusCoordStart - radiusCoord;
ax->setRange(mDragRadialStart.at(i).lower+diff, mDragRadialStart.at(i).upper+diff);
} else if (ax->scaleType() == QCPPolarAxisRadial::stLogarithmic)
{
if (radiusCoord != 0)
{
double diff = radiusCoordStart/radiusCoord;
ax->setRange(mDragRadialStart.at(i).lower*diff, mDragRadialStart.at(i).upper*diff);
}
}
}
if (doReplot) // if either vertical or horizontal drag was enabled, do a replot
{
if (mParentPlot->noAntialiasingOnDrag())
mParentPlot->setNotAntialiasedElements(QCP::aeAll);
mParentPlot->replot(QCustomPlot::rpQueuedReplot);
}
}
}
/* inherits documentation from base class */
void QCPPolarAxisAngular::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
{
Q_UNUSED(event)
Q_UNUSED(startPos)
mDragging = false;
if (mParentPlot->noAntialiasingOnDrag())
{
mParentPlot->setAntialiasedElements(mAADragBackup);
mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
}
}
/*! \internal
Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
the scaling operation is the current cursor position inside the axis rect. The scaling factor is
dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse
wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be
multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as
exponent of the range zoom factor. This takes care of the wheel direction automatically, by
inverting the factor, when the wheel step is negative (f^-1 = 1/f).
*/
void QCPPolarAxisAngular::wheelEvent(QWheelEvent *event)
{
bool doReplot = false;
// Mouse range zooming interaction:
if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
{
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
const double delta = event->delta();
#else
const double delta = event->angleDelta().y();
#endif
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
const QPointF pos = event->pos();
#else
const QPointF pos = event->position();
#endif
const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
if (mRangeZoom)
{
double angleCoord = 0.0, radiusCoord = 0.0;
pixelToCoord(pos, angleCoord, radiusCoord);
scaleRange(qPow(mRangeZoomFactor, wheelSteps), angleCoord);
}
for (int i=0; i<mRadialAxes.size(); ++i)
{
QCPPolarAxisRadial *ax = mRadialAxes.at(i);
if (!ax->rangeZoom())
continue;
doReplot = true;
double angleCoord, radiusCoord;
ax->pixelToCoord(pos, angleCoord, radiusCoord);
ax->scaleRange(qPow(ax->rangeZoomFactor(), wheelSteps), radiusCoord);
}
}
if (doReplot)
mParentPlot->replot();
}
bool QCPPolarAxisAngular::registerPolarGraph(QCPPolarGraph *graph)
{
if (mGraphs.contains(graph))
{
qDebug() << Q_FUNC_INFO << "plottable already added:" << reinterpret_cast<quintptr>(graph);
return false;
}
if (graph->keyAxis() != this)
{
qDebug() << Q_FUNC_INFO << "plottable not created with this as axis:" << reinterpret_cast<quintptr>(graph);
return false;
}
mGraphs.append(graph);
// possibly add plottable to legend:
if (mParentPlot->autoAddPlottableToLegend())
graph->addToLegend();
if (!graph->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
graph->setLayer(mParentPlot->currentLayer());
return true;
}
/* end of 'src/polar/layoutelement-angularaxis.cpp' */
/* including file 'src/polar/polargrid.cpp' */
/* modified 2022-11-06T12:45:57, size 7493 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPolarGrid
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPolarGrid
\brief The grid in both angular and radial dimensions for polar plots
\warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
functionality to be incomplete, as well as changing public interfaces in the future.
*/
/*!
Creates a QCPPolarGrid instance and sets default values.
You shouldn't instantiate grids on their own, since every axis brings its own grid.
*/
QCPPolarGrid::QCPPolarGrid(QCPPolarAxisAngular *parentAxis) :
QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
mType(gtNone),
mSubGridType(gtNone),
mAntialiasedSubGrid(true),
mAntialiasedZeroLine(true),
mParentAxis(parentAxis)
{
// warning: this is called in QCPPolarAxisAngular constructor, so parentAxis members should not be accessed/called
setParent(parentAxis);
setType(gtAll);
setSubGridType(gtNone);
setAngularPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
setAngularSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
setRadialPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
setRadialSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
setRadialZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
setAntialiased(true);
}
void QCPPolarGrid::setRadialAxis(QCPPolarAxisRadial *axis)
{
mRadialAxis = axis;
}
void QCPPolarGrid::setType(GridTypes type)
{
mType = type;
}
void QCPPolarGrid::setSubGridType(GridTypes type)
{
mSubGridType = type;
}
/*!
Sets whether sub grid lines are drawn antialiased.
*/
void QCPPolarGrid::setAntialiasedSubGrid(bool enabled)
{
mAntialiasedSubGrid = enabled;
}
/*!
Sets whether zero lines are drawn antialiased.
*/
void QCPPolarGrid::setAntialiasedZeroLine(bool enabled)
{
mAntialiasedZeroLine = enabled;
}
/*!
Sets the pen with which (major) grid lines are drawn.
*/
void QCPPolarGrid::setAngularPen(const QPen &pen)
{
mAngularPen = pen;
}
/*!
Sets the pen with which sub grid lines are drawn.
*/
void QCPPolarGrid::setAngularSubGridPen(const QPen &pen)
{
mAngularSubGridPen = pen;
}
void QCPPolarGrid::setRadialPen(const QPen &pen)
{
mRadialPen = pen;
}
void QCPPolarGrid::setRadialSubGridPen(const QPen &pen)
{
mRadialSubGridPen = pen;
}
void QCPPolarGrid::setRadialZeroLinePen(const QPen &pen)
{
mRadialZeroLinePen = pen;
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing the major grid lines.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased
*/
void QCPPolarGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
}
/*! \internal
Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
*/
void QCPPolarGrid::draw(QCPPainter *painter)
{
if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
const QPointF center = mParentAxis->mCenter;
const double radius = mParentAxis->mRadius;
painter->setBrush(Qt::NoBrush);
// draw main angular grid:
if (mType.testFlag(gtAngular))
drawAngularGrid(painter, center, radius, mParentAxis->mTickVectorCosSin, mAngularPen);
// draw main radial grid:
if (mType.testFlag(gtRadial) && mRadialAxis)
drawRadialGrid(painter, center, mRadialAxis->tickVector(), mRadialPen, mRadialZeroLinePen);
applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeGrid);
// draw sub angular grid:
if (mSubGridType.testFlag(gtAngular))
drawAngularGrid(painter, center, radius, mParentAxis->mSubTickVectorCosSin, mAngularSubGridPen);
// draw sub radial grid:
if (mSubGridType.testFlag(gtRadial) && mRadialAxis)
drawRadialGrid(painter, center, mRadialAxis->subTickVector(), mRadialSubGridPen);
}
void QCPPolarGrid::drawRadialGrid(QCPPainter *painter, const QPointF ¢er, const QVector<double> &coords, const QPen &pen, const QPen &zeroPen)
{
if (!mRadialAxis) return;
if (coords.isEmpty()) return;
const bool drawZeroLine = zeroPen != Qt::NoPen;
const double zeroLineEpsilon = qAbs(coords.last()-coords.first())*1e-6;
painter->setPen(pen);
for (int i=0; i<coords.size(); ++i)
{
const double r = mRadialAxis->coordToRadius(coords.at(i));
if (drawZeroLine && qAbs(coords.at(i)) < zeroLineEpsilon)
{
applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
painter->setPen(zeroPen);
painter->drawEllipse(center, r, r);
painter->setPen(pen);
applyDefaultAntialiasingHint(painter);
} else
{
painter->drawEllipse(center, r, r);
}
}
}
void QCPPolarGrid::drawAngularGrid(QCPPainter *painter, const QPointF ¢er, double radius, const QVector<QPointF> &ticksCosSin, const QPen &pen)
{
if (ticksCosSin.isEmpty()) return;
painter->setPen(pen);
for (int i=0; i<ticksCosSin.size(); ++i)
painter->drawLine(center, center+ticksCosSin.at(i)*radius);
}
/* end of 'src/polar/polargrid.cpp' */
/* including file 'src/polar/polargraph.cpp' */
/* modified 2022-11-06T12:45:57, size 44035 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPolarLegendItem
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! QCPPolarLegendItem
\brief A legend item for polar plots
\warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
functionality to be incomplete, as well as changing public interfaces in the future.
*/
QCPPolarLegendItem::QCPPolarLegendItem(QCPLegend *parent, QCPPolarGraph *graph) :
QCPAbstractLegendItem(parent),
mPolarGraph(graph)
{
setAntialiased(false);
}
void QCPPolarLegendItem::draw(QCPPainter *painter)
{
if (!mPolarGraph) return;
painter->setFont(getFont());
painter->setPen(QPen(getTextColor()));
QSizeF iconSize = mParentLegend->iconSize();
QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name());
QRectF iconRect(mRect.topLeft(), iconSize);
int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPolarGraph->name());
// draw icon:
painter->save();
painter->setClipRect(iconRect, Qt::IntersectClip);
mPolarGraph->drawLegendIcon(painter, iconRect);
painter->restore();
// draw icon border:
if (getIconBorderPen().style() != Qt::NoPen)
{
painter->setPen(getIconBorderPen());
painter->setBrush(Qt::NoBrush);
int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
painter->drawRect(iconRect);
}
}
QSize QCPPolarLegendItem::minimumOuterSizeHint() const
{
if (!mPolarGraph) return QSize();
QSize result(0, 0);
QRect textRect;
QFontMetrics fontMetrics(getFont());
QSize iconSize = mParentLegend->iconSize();
textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name());
result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width());
result.setHeight(qMax(textRect.height(), iconSize.height()));
result.rwidth() += mMargins.left()+mMargins.right();
result.rheight() += mMargins.top()+mMargins.bottom();
return result;
}
QPen QCPPolarLegendItem::getIconBorderPen() const
{
return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
}
QColor QCPPolarLegendItem::getTextColor() const
{
return mSelected ? mSelectedTextColor : mTextColor;
}
QFont QCPPolarLegendItem::getFont() const
{
return mSelected ? mSelectedFont : mFont;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPolarGraph
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPolarGraph
\brief A radial graph used to display data in polar plots
\warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
functionality to be incomplete, as well as changing public interfaces in the future.
*/
/* start of documentation of inline functions */
// TODO
/* end of documentation of inline functions */
/*!
Constructs a graph which uses \a keyAxis as its angular and \a valueAxis as its radial axis. \a
keyAxis and \a valueAxis must reside in the same QCustomPlot, and the radial axis must be
associated with the angular axis. If either of these restrictions is violated, a corresponding
message is printed to the debug output (qDebug), the construction is not aborted, though.
The created QCPPolarGraph is automatically registered with the QCustomPlot instance inferred from
\a keyAxis. This QCustomPlot instance takes ownership of the QCPPolarGraph, so do not delete it
manually but use QCPPolarAxisAngular::removeGraph() instead.
To directly create a QCPPolarGraph inside a plot, you shoud use the QCPPolarAxisAngular::addGraph
method.
*/
QCPPolarGraph::QCPPolarGraph(QCPPolarAxisAngular *keyAxis, QCPPolarAxisRadial *valueAxis) :
QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis),
mDataContainer(new QCPGraphDataContainer),
mName(),
mAntialiasedFill(true),
mAntialiasedScatters(true),
mPen(Qt::black),
mBrush(Qt::NoBrush),
mPeriodic(true),
mKeyAxis(keyAxis),
mValueAxis(valueAxis),
mSelectable(QCP::stWhole)
//mSelectionDecorator(0) // TODO
{
if (keyAxis->parentPlot() != valueAxis->parentPlot())
qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
mKeyAxis->registerPolarGraph(this);
//setSelectionDecorator(new QCPSelectionDecorator); // TODO
setPen(QPen(Qt::blue, 0));
setBrush(Qt::NoBrush);
setLineStyle(lsLine);
}
QCPPolarGraph::~QCPPolarGraph()
{
/* TODO
if (mSelectionDecorator)
{
delete mSelectionDecorator;
mSelectionDecorator = 0;
}
*/
}
/*!
The name is the textual representation of this plottable as it is displayed in the legend
(\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
*/
void QCPPolarGraph::setName(const QString &name)
{
mName = name;
}
/*!
Sets whether fills of this plottable are drawn antialiased or not.
Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
*/
void QCPPolarGraph::setAntialiasedFill(bool enabled)
{
mAntialiasedFill = enabled;
}
/*!
Sets whether the scatter symbols of this plottable are drawn antialiased or not.
Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
*/
void QCPPolarGraph::setAntialiasedScatters(bool enabled)
{
mAntialiasedScatters = enabled;
}
/*!
The pen is used to draw basic lines that make up the plottable representation in the
plot.
For example, the \ref QCPGraph subclass draws its graph lines with this pen.
\see setBrush
*/
void QCPPolarGraph::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
The brush is used to draw basic fills of the plottable representation in the
plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
it's not set to Qt::NoBrush.
\see setPen
*/
void QCPPolarGraph::setBrush(const QBrush &brush)
{
mBrush = brush;
}
void QCPPolarGraph::setPeriodic(bool enabled)
{
mPeriodic = enabled;
}
/*!
The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
to the plottable's value axis. This function performs no checks to make sure this is the case.
The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
y-axis (QCustomPlot::yAxis) as value axis.
Normally, the key and value axes are set in the constructor of the plottable (or \ref
QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
\see setValueAxis
*/
void QCPPolarGraph::setKeyAxis(QCPPolarAxisAngular *axis)
{
mKeyAxis = axis;
}
/*!
The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
the y-axis (QCustomPlot::yAxis) as value axis.
Normally, the key and value axes are set in the constructor of the plottable (or \ref
QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
\see setKeyAxis
*/
void QCPPolarGraph::setValueAxis(QCPPolarAxisRadial *axis)
{
mValueAxis = axis;
}
/*!
Sets whether and to which granularity this plottable can be selected.
A selection can happen by clicking on the QCustomPlot surface (When \ref
QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
(When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
calling \ref setSelection.
\see setSelection, QCP::SelectionType
*/
void QCPPolarGraph::setSelectable(QCP::SelectionType selectable)
{
if (mSelectable != selectable)
{
mSelectable = selectable;
QCPDataSelection oldSelection = mSelection;
mSelection.enforceType(mSelectable);
emit selectableChanged(mSelectable);
if (mSelection != oldSelection)
{
emit selectionChanged(selected());
emit selectionChanged(mSelection);
}
}
}
/*!
Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
(e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
selectionDecorator).
The entire selection mechanism for plottables is handled automatically when \ref
QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
you wish to change the selection state programmatically.
Using \ref setSelectable you can further specify for each plottable whether and to which
granularity it is selectable. If \a selection is not compatible with the current \ref
QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
accordingly (see \ref QCPDataSelection::enforceType).
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
\see setSelectable, selectTest
*/
void QCPPolarGraph::setSelection(QCPDataSelection selection)
{
selection.enforceType(mSelectable);
if (mSelection != selection)
{
mSelection = selection;
emit selectionChanged(selected());
emit selectionChanged(mSelection);
}
}
/*! \overload
Replaces the current data container with the provided \a data container.
Since a QSharedPointer is used, multiple QCPPolarGraphs may share the same data container safely.
Modifying the data in the container will then affect all graphs that share the container. Sharing
can be achieved by simply exchanging the data containers wrapped in shared pointers:
\snippet documentation/doc-code-snippets/mainwindow.cpp QCPPolarGraph-datasharing-1
If you do not wish to share containers, but create a copy from an existing container, rather use
the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
\snippet documentation/doc-code-snippets/mainwindow.cpp QCPPolarGraph-datasharing-2
\see addData
*/
void QCPPolarGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
{
mDataContainer = data;
}
/*! \overload
Replaces the current data with the provided points in \a keys and \a values. The provided
vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
can set \a alreadySorted to true, to improve performance by saving a sorting run.
\see addData
*/
void QCPPolarGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
{
mDataContainer->clear();
addData(keys, values, alreadySorted);
}
/*!
Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
\ref lsNone and \ref setScatterStyle to the desired scatter style.
\see setScatterStyle
*/
void QCPPolarGraph::setLineStyle(LineStyle ls)
{
mLineStyle = ls;
}
/*!
Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
are drawn (e.g. for line-only-plots with appropriate line style).
\see QCPScatterStyle, setLineStyle
*/
void QCPPolarGraph::setScatterStyle(const QCPScatterStyle &style)
{
mScatterStyle = style;
}
void QCPPolarGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
{
if (keys.size() != values.size())
qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
const int n = static_cast<int>(qMin(keys.size(), values.size()));
QVector<QCPGraphData> tempData(n);
QVector<QCPGraphData>::iterator it = tempData.begin();
const QVector<QCPGraphData>::iterator itEnd = tempData.end();
int i = 0;
while (it != itEnd)
{
it->key = keys[i];
it->value = values[i];
++it;
++i;
}
mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
}
void QCPPolarGraph::addData(double key, double value)
{
mDataContainer->add(QCPGraphData(key, value));
}
/*!
Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
customize the visual representation of selected data ranges further than by using the default
QCPSelectionDecorator.
The plottable takes ownership of the \a decorator.
The currently set decorator can be accessed via \ref selectionDecorator.
*/
/*
void QCPPolarGraph::setSelectionDecorator(QCPSelectionDecorator *decorator)
{
if (decorator)
{
if (decorator->registerWithPlottable(this))
{
if (mSelectionDecorator) // delete old decorator if necessary
delete mSelectionDecorator;
mSelectionDecorator = decorator;
}
} else if (mSelectionDecorator) // just clear decorator
{
delete mSelectionDecorator;
mSelectionDecorator = 0;
}
}
*/
void QCPPolarGraph::coordsToPixels(double key, double value, double &x, double &y) const
{
if (mValueAxis)
{
const QPointF point = mValueAxis->coordToPixel(key, value);
x = point.x();
y = point.y();
} else
{
qDebug() << Q_FUNC_INFO << "invalid key or value axis";
}
}
const QPointF QCPPolarGraph::coordsToPixels(double key, double value) const
{
if (mValueAxis)
{
return mValueAxis->coordToPixel(key, value);
} else
{
qDebug() << Q_FUNC_INFO << "invalid key or value axis";
return QPointF();
}
}
void QCPPolarGraph::pixelsToCoords(double x, double y, double &key, double &value) const
{
if (mValueAxis)
{
mValueAxis->pixelToCoord(QPointF(x, y), key, value);
} else
{
qDebug() << Q_FUNC_INFO << "invalid key or value axis";
}
}
void QCPPolarGraph::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
{
if (mValueAxis)
{
mValueAxis->pixelToCoord(pixelPos, key, value);
} else
{
qDebug() << Q_FUNC_INFO << "invalid key or value axis";
}
}
void QCPPolarGraph::rescaleAxes(bool onlyEnlarge) const
{
rescaleKeyAxis(onlyEnlarge);
rescaleValueAxis(onlyEnlarge);
}
void QCPPolarGraph::rescaleKeyAxis(bool onlyEnlarge) const
{
QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
bool foundRange;
QCPRange newRange = getKeyRange(foundRange, QCP::sdBoth);
if (foundRange)
{
if (onlyEnlarge)
newRange.expand(keyAxis->range());
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
newRange.lower = center-keyAxis->range().size()/2.0;
newRange.upper = center+keyAxis->range().size()/2.0;
}
keyAxis->setRange(newRange);
}
}
void QCPPolarGraph::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
{
QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
QCPPolarAxisRadial *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
QCP::SignDomain signDomain = QCP::sdBoth;
if (valueAxis->scaleType() == QCPPolarAxisRadial::stLogarithmic)
signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
bool foundRange;
QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
if (foundRange)
{
if (onlyEnlarge)
newRange.expand(valueAxis->range());
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
if (valueAxis->scaleType() == QCPPolarAxisRadial::stLinear)
{
newRange.lower = center-valueAxis->range().size()/2.0;
newRange.upper = center+valueAxis->range().size()/2.0;
} else // scaleType() == stLogarithmic
{
newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
}
}
valueAxis->setRange(newRange);
}
}
bool QCPPolarGraph::addToLegend(QCPLegend *legend)
{
if (!legend)
{
qDebug() << Q_FUNC_INFO << "passed legend is null";
return false;
}
if (legend->parentPlot() != mParentPlot)
{
qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
return false;
}
//if (!legend->hasItemWithPlottable(this)) // TODO
//{
legend->addItem(new QCPPolarLegendItem(legend, this));
return true;
//} else
// return false;
}
bool QCPPolarGraph::addToLegend()
{
if (!mParentPlot || !mParentPlot->legend)
return false;
else
return addToLegend(mParentPlot->legend);
}
bool QCPPolarGraph::removeFromLegend(QCPLegend *legend) const
{
if (!legend)
{
qDebug() << Q_FUNC_INFO << "passed legend is null";
return false;
}
QCPPolarLegendItem *removableItem = 0;
for (int i=0; i<legend->itemCount(); ++i) // TODO: reduce this to code in QCPAbstractPlottable::removeFromLegend once unified
{
if (QCPPolarLegendItem *pli = qobject_cast<QCPPolarLegendItem*>(legend->item(i)))
{
if (pli->polarGraph() == this)
{
removableItem = pli;
break;
}
}
}
if (removableItem)
return legend->removeItem(removableItem);
else
return false;
}
bool QCPPolarGraph::removeFromLegend() const
{
if (!mParentPlot || !mParentPlot->legend)
return false;
else
return removeFromLegend(mParentPlot->legend);
}
double QCPPolarGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
return -1;
if (!mKeyAxis || !mValueAxis)
return -1;
if (mKeyAxis->rect().contains(pos.toPoint()))
{
QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
double result = pointDistance(pos, closestDataPoint);
if (details)
{
int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
}
return result;
} else
return -1;
}
/* inherits documentation from base class */
QCPRange QCPPolarGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
{
return mDataContainer->keyRange(foundRange, inSignDomain);
}
/* inherits documentation from base class */
QCPRange QCPPolarGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
{
return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
}
/* inherits documentation from base class */
QRect QCPPolarGraph::clipRect() const
{
if (mKeyAxis)
return mKeyAxis.data()->rect();
else
return QRect();
}
void QCPPolarGraph::draw(QCPPainter *painter)
{
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
painter->setClipRegion(mKeyAxis->exactClipRegion());
QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
// loop over and draw segments of unselected/selected data:
QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
getDataSegments(selectedSegments, unselectedSegments);
allSegments << unselectedSegments << selectedSegments;
for (int i=0; i<allSegments.size(); ++i)
{
bool isSelectedSegment = i >= unselectedSegments.size();
// get line pixel points appropriate to line style:
QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getLines takes care)
getLines(&lines, lineDataRange);
// check data validity if flag set:
#ifdef QCUSTOMPLOT_CHECK_DATA
QCPGraphDataContainer::const_iterator it;
for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
{
if (QCP::isInvalidData(it->key, it->value))
qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
}
#endif
// draw fill of graph:
//if (isSelectedSegment && mSelectionDecorator)
// mSelectionDecorator->applyBrush(painter);
//else
painter->setBrush(mBrush);
painter->setPen(Qt::NoPen);
drawFill(painter, &lines);
// draw line:
if (mLineStyle != lsNone)
{
//if (isSelectedSegment && mSelectionDecorator)
// mSelectionDecorator->applyPen(painter);
//else
painter->setPen(mPen);
painter->setBrush(Qt::NoBrush);
drawLinePlot(painter, lines);
}
// draw scatters:
QCPScatterStyle finalScatterStyle = mScatterStyle;
//if (isSelectedSegment && mSelectionDecorator)
// finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
if (!finalScatterStyle.isNone())
{
getScatters(&scatters, allSegments.at(i));
drawScatterPlot(painter, scatters, finalScatterStyle);
}
}
// draw other selection decoration that isn't just line/scatter pens and brushes:
//if (mSelectionDecorator)
// mSelectionDecorator->drawDecoration(painter, selection());
}
QCP::Interaction QCPPolarGraph::selectionCategory() const
{
return QCP::iSelectPlottables;
}
void QCPPolarGraph::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
}
/* inherits documentation from base class */
void QCPPolarGraph::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
if (mSelectable != QCP::stNone)
{
QCPDataSelection newSelection = details.value<QCPDataSelection>();
QCPDataSelection selectionBefore = mSelection;
if (additive)
{
if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
{
if (selected())
setSelection(QCPDataSelection());
else
setSelection(newSelection);
} else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
{
if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
setSelection(mSelection-newSelection);
else
setSelection(mSelection+newSelection);
}
} else
setSelection(newSelection);
if (selectionStateChanged)
*selectionStateChanged = mSelection != selectionBefore;
}
}
/* inherits documentation from base class */
void QCPPolarGraph::deselectEvent(bool *selectionStateChanged)
{
if (mSelectable != QCP::stNone)
{
QCPDataSelection selectionBefore = mSelection;
setSelection(QCPDataSelection());
if (selectionStateChanged)
*selectionStateChanged = mSelection != selectionBefore;
}
}
/*! \internal
Draws lines between the points in \a lines, given in pixel coordinates.
\see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
*/
void QCPPolarGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
{
if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
{
applyDefaultAntialiasingHint(painter);
drawPolyline(painter, lines);
}
}
/*! \internal
Draws the fill of the graph using the specified \a painter, with the currently set brush.
Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref
getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons.
In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas),
this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to
operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN
segments of the two involved graphs, before passing the overlapping pairs to \ref
getChannelFillPolygon.
Pass the points of this graph's line as \a lines, in pixel coordinates.
\see drawLinePlot, drawImpulsePlot, drawScatterPlot
*/
void QCPPolarGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
{
applyFillAntialiasingHint(painter);
if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
painter->drawPolygon(QPolygonF(*lines));
}
/*! \internal
Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
scatters will be drawn with \a painter and have the appearance as specified in \a style.
\see drawLinePlot, drawImpulsePlot
*/
void QCPPolarGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
{
applyScattersAntialiasingHint(painter);
style.applyTo(painter, mPen);
for (int i=0; i<scatters.size(); ++i)
style.drawShape(painter, scatters.at(i).x(), scatters.at(i).y());
}
void QCPPolarGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
// draw fill:
if (mBrush.style() != Qt::NoBrush)
{
applyFillAntialiasingHint(painter);
painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
}
// draw line vertically centered:
if (mLineStyle != lsNone)
{
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
}
// draw scatter symbol:
if (!mScatterStyle.isNone())
{
applyScattersAntialiasingHint(painter);
// scale scatter pixmap if it's too large to fit in legend icon rect:
if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
{
QCPScatterStyle scaledStyle(mScatterStyle);
scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
scaledStyle.applyTo(painter, mPen);
scaledStyle.drawShape(painter, QRectF(rect).center());
} else
{
mScatterStyle.applyTo(painter, mPen);
mScatterStyle.drawShape(painter, QRectF(rect).center());
}
}
}
void QCPPolarGraph::applyFillAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
}
void QCPPolarGraph::applyScattersAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
}
double QCPPolarGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
{
closestData = mDataContainer->constEnd();
if (mDataContainer->isEmpty())
return -1.0;
if (mLineStyle == lsNone && mScatterStyle.isNone())
return -1.0;
// calculate minimum distances to graph data points and find closestData iterator:
double minDistSqr = (std::numeric_limits<double>::max)();
// determine which key range comes into question, taking selection tolerance around pos into account:
double posKeyMin = 0.0, posKeyMax = 0.0, dummy;
pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
if (posKeyMin > posKeyMax)
qSwap(posKeyMin, posKeyMax);
// iterate over found data points and then choose the one with the shortest distance to pos:
QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
{
const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
if (currentDistSqr < minDistSqr)
{
minDistSqr = currentDistSqr;
closestData = it;
}
}
// calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
if (mLineStyle != lsNone)
{
// line displayed, calculate distance to line segments:
QVector<QPointF> lineData;
getLines(&lineData, QCPDataRange(0, dataCount()));
QCPVector2D p(pixelPoint);
for (int i=0; i<lineData.size()-1; ++i)
{
const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
}
return qSqrt(minDistSqr);
}
int QCPPolarGraph::dataCount() const
{
return mDataContainer->size();
}
void QCPPolarGraph::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
{
selectedSegments.clear();
unselectedSegments.clear();
if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
{
if (selected())
selectedSegments << QCPDataRange(0, dataCount());
else
unselectedSegments << QCPDataRange(0, dataCount());
} else
{
QCPDataSelection sel(selection());
sel.simplify();
selectedSegments = sel.dataRanges();
unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
}
}
void QCPPolarGraph::drawPolyline(QCPPainter *painter, const QVector<QPointF> &lineData) const
{
// if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
painter->pen().style() == Qt::SolidLine &&
!painter->modes().testFlag(QCPPainter::pmVectorized) &&
!painter->modes().testFlag(QCPPainter::pmNoCaching))
{
int i = 0;
bool lastIsNan = false;
const int lineDataSize = static_cast<int>(lineData.size());
while (i < lineDataSize && (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()))) // make sure first point is not NaN
++i;
++i; // because drawing works in 1 point retrospect
while (i < lineDataSize)
{
if (!qIsNaN(lineData.at(i).y()) && !qIsNaN(lineData.at(i).x())) // NaNs create a gap in the line
{
if (!lastIsNan)
painter->drawLine(lineData.at(i-1), lineData.at(i));
else
lastIsNan = false;
} else
lastIsNan = true;
++i;
}
} else
{
int segmentStart = 0;
int i = 0;
const int lineDataSize = static_cast<int>(lineData.size());
while (i < lineDataSize)
{
if (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()) || qIsInf(lineData.at(i).y())) // NaNs create a gap in the line. Also filter Infs which make drawPolyline block
{
painter->drawPolyline(lineData.constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point
segmentStart = i+1;
}
++i;
}
// draw last segment:
painter->drawPolyline(lineData.constData()+segmentStart, lineDataSize-segmentStart);
}
}
void QCPPolarGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
{
if (rangeRestriction.isEmpty())
{
end = mDataContainer->constEnd();
begin = end;
} else
{
QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
QCPPolarAxisRadial *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
// get visible data range:
if (mPeriodic)
{
begin = mDataContainer->constBegin();
end = mDataContainer->constEnd();
} else
{
begin = mDataContainer->findBegin(keyAxis->range().lower);
end = mDataContainer->findEnd(keyAxis->range().upper);
}
// limit lower/upperEnd to rangeRestriction:
mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
}
}
/*! \internal
This method retrieves an optimized set of data points via \ref getOptimizedLineData, an branches
out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
according to the line style of the graph.
\a lines will be filled with points in pixel coordinates, that can be drawn with the according
draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
aren't necessarily the original data points. For example, step line styles require additional
points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
lines vector will be empty.
\a dataRange specifies the beginning and ending data indices that will be taken into account for
conversion. In this function, the specified range may exceed the total data bounds without harm:
a correspondingly trimmed data range will be used. This takes the burden off the user of this
function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
getDataSegments.
\see getScatters
*/
void QCPPolarGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
{
if (!lines) return;
QCPGraphDataContainer::const_iterator begin, end;
getVisibleDataBounds(begin, end, dataRange);
if (begin == end)
{
lines->clear();
return;
}
QVector<QCPGraphData> lineData;
if (mLineStyle != lsNone)
getOptimizedLineData(&lineData, begin, end);
switch (mLineStyle)
{
case lsNone: lines->clear(); break;
case lsLine: *lines = dataToLines(lineData); break;
}
}
void QCPPolarGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
{
QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
QCPPolarAxisRadial *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (!scatters) return;
QCPGraphDataContainer::const_iterator begin, end;
getVisibleDataBounds(begin, end, dataRange);
if (begin == end)
{
scatters->clear();
return;
}
QVector<QCPGraphData> data;
getOptimizedScatterData(&data, begin, end);
scatters->resize(data.size());
for (int i=0; i<data.size(); ++i)
{
if (!qIsNaN(data.at(i).value))
(*scatters)[i] = valueAxis->coordToPixel(data.at(i).key, data.at(i).value);
}
}
void QCPPolarGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
{
lineData->clear();
// TODO: fix for log axes and thick line style
const QCPRange range = mValueAxis->range();
bool reversed = mValueAxis->rangeReversed();
const double clipMargin = range.size()*0.05; // extra distance from visible circle, so optimized outside lines can cover more angle before having to place a dummy point to prevent tangents
const double upperClipValue = range.upper + (reversed ? 0 : range.size()*0.05+clipMargin); // clip slightly outside of actual range to avoid line thicknesses to peek into visible circle
const double lowerClipValue = range.lower - (reversed ? range.size()*0.05+clipMargin : 0); // clip slightly outside of actual range to avoid line thicknesses to peek into visible circle
const double maxKeySkip = qAsin(qSqrt(clipMargin*(clipMargin+2*range.size()))/(range.size()+clipMargin))/M_PI*mKeyAxis->range().size(); // the maximum angle between two points on outer circle (r=clipValue+clipMargin) before connecting line becomes tangent to inner circle (r=clipValue)
double skipBegin = 0;
bool belowRange = false;
bool aboveRange = false;
QCPGraphDataContainer::const_iterator it = begin;
while (it != end)
{
if (it->value < lowerClipValue)
{
if (aboveRange) // jumped directly from above to below visible range, draw previous point so entry angle is correct
{
aboveRange = false;
if (!reversed) // TODO: with inner radius, we'll need else case here with projected border point
lineData->append(*(it-1));
}
if (!belowRange)
{
skipBegin = it->key;
lineData->append(QCPGraphData(it->key, lowerClipValue));
belowRange = true;
}
if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle)
{
skipBegin += maxKeySkip;
lineData->append(QCPGraphData(skipBegin, lowerClipValue));
}
} else if (it->value > upperClipValue)
{
if (belowRange) // jumped directly from below to above visible range, draw previous point so entry angle is correct (if lower means outer, so if reversed axis)
{
belowRange = false;
if (reversed)
lineData->append(*(it-1));
}
if (!aboveRange)
{
skipBegin = it->key;
lineData->append(QCPGraphData(it->key, upperClipValue));
aboveRange = true;
}
if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle)
{
skipBegin += maxKeySkip;
lineData->append(QCPGraphData(skipBegin, upperClipValue));
}
} else // value within bounds where we don't optimize away points
{
if (aboveRange)
{
aboveRange = false;
if (!reversed)
lineData->append(*(it-1)); // just entered from above, draw previous point so entry angle is correct (if above means outer, so if not reversed axis)
}
if (belowRange)
{
belowRange = false;
if (reversed)
lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis)
}
lineData->append(*it); // inside visible circle, add point normally
}
++it;
}
// to make fill not erratic, add last point normally if it was outside visible circle:
if (aboveRange)
{
// aboveRange = false; // Dead store
if (!reversed)
lineData->append(*(it-1)); // just entered from above, draw previous point so entry angle is correct (if above means outer, so if not reversed axis)
}
if (belowRange)
{
// belowRange = false; // Dead store
if (reversed)
lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis)
}
}
void QCPPolarGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
{
scatterData->clear();
const QCPRange range = mValueAxis->range();
bool reversed = mValueAxis->rangeReversed();
const double clipMargin = range.size()*0.05;
const double upperClipValue = range.upper + (reversed ? 0 : clipMargin); // clip slightly outside of actual range to avoid scatter size to peek into visible circle
const double lowerClipValue = range.lower - (reversed ? clipMargin : 0); // clip slightly outside of actual range to avoid scatter size to peek into visible circle
QCPGraphDataContainer::const_iterator it = begin;
while (it != end)
{
if (it->value > lowerClipValue && it->value < upperClipValue)
scatterData->append(*it);
++it;
}
}
/*! \internal
Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
coordinate points which are suitable for drawing the line style \ref lsLine.
The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
getLines if the line style is set accordingly.
\see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
*/
QVector<QPointF> QCPPolarGraph::dataToLines(const QVector<QCPGraphData> &data) const
{
QVector<QPointF> result;
QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
QCPPolarAxisRadial *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
// transform data points to pixels:
result.resize(data.size());
for (int i=0; i<data.size(); ++i)
result[i] = mValueAxis->coordToPixel(data.at(i).key, data.at(i).value);
return result;
}
/* end of 'src/polar/polargraph.cpp' */ |
C/C++ | wireshark/ui/qt/widgets/qcustomplot.h | /** @file
**
****************************************************************************
** **
** QCustomPlot, an easy to use, modern plotting widget for Qt **
** Copyright (C) 2011-2022 Emanuel Eichhammer **
** **
****************************************************************************
** Author: Emanuel Eichhammer **
** Website/Contact: https://www.qcustomplot.com/ **
** Date: 06.11.22 **
** Version: 2.1.1 **
** **
** Emanuel Eichhammer has granted Wireshark permission to use QCustomPlot **
** under the terms of the GNU General Public License version 2. **
** Date: 22.12.15 (V1.3.2) **
** 13.09.19 (V2.0.1) **
** **
** SPDX-License-Identifier: GPL-2.0-or-later **
****************************************************************************/
#ifndef QCUSTOMPLOT_H
#define QCUSTOMPLOT_H
#include <QtCore/qglobal.h>
// some Qt version/configuration dependent macros to include or exclude certain code paths:
#ifdef QCUSTOMPLOT_USE_OPENGL
# if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
# define QCP_OPENGL_PBUFFER
# else
# define QCP_OPENGL_FBO
# endif
# if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)
# define QCP_OPENGL_OFFSCREENSURFACE
# endif
#endif
#if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)
# define QCP_DEVICEPIXELRATIO_SUPPORTED
# if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
# define QCP_DEVICEPIXELRATIO_FLOAT
# endif
#endif
#include <QtCore/QObject>
#include <QtCore/QPointer>
#include <QtCore/QSharedPointer>
#include <QtCore/QTimer>
#include <QtGui/QPainter>
#include <QtGui/QPainterPath>
#include <QtGui/QPaintEvent>
#include <QtGui/QMouseEvent>
#include <QtGui/QWheelEvent>
#include <QtGui/QPixmap>
#include <QtCore/QVector>
#include <QtCore/QString>
#include <QtCore/QDateTime>
#include <QtCore/QMultiMap>
#include <QtCore/QFlags>
#include <QtCore/QDebug>
#include <QtCore/QStack>
#include <QtCore/QCache>
#include <QtCore/QMargins>
#include <qmath.h>
#include <limits>
#include <algorithm>
#ifdef QCP_OPENGL_FBO
# include <QtGui/QOpenGLContext>
# if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
# include <QtGui/QOpenGLFramebufferObject>
# else
# include <QOpenGLFramebufferObject>
# include <QOpenGLPaintDevice>
# endif
# ifdef QCP_OPENGL_OFFSCREENSURFACE
# include <QtGui/QOffscreenSurface>
# else
# include <QtGui/QWindow>
# endif
#endif
#ifdef QCP_OPENGL_PBUFFER
# include <QtOpenGL/QGLPixelBuffer>
#endif
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
# include <qnumeric.h>
# include <QtGui/QWidget>
# include <QtGui/QPrinter>
# include <QtGui/QPrintEngine>
#else
# include <QtNumeric>
# include <QtWidgets/QWidget>
# include <QtPrintSupport/QtPrintSupport>
#endif
#if QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)
# include <QtCore/QElapsedTimer>
#endif
# if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
# include <QtCore/QTimeZone>
#endif
class QCPPainter;
class QCustomPlot;
class QCPLayerable;
class QCPLayoutElement;
class QCPLayout;
class QCPAxis;
class QCPAxisRect;
class QCPAxisPainterPrivate;
class QCPAbstractPlottable;
class QCPGraph;
class QCPAbstractItem;
class QCPPlottableInterface1D;
class QCPLegend;
class QCPItemPosition;
class QCPLayer;
class QCPAbstractLegendItem;
class QCPSelectionRect;
class QCPColorMap;
class QCPColorScale;
class QCPBars;
class QCPPolarAxisRadial;
class QCPPolarAxisAngular;
class QCPPolarGrid;
class QCPPolarGraph;
/* including file 'src/global.h' */
/* modified 2022-11-06T12:45:57, size 18102 */
#define QCUSTOMPLOT_VERSION_STR "2.1.1"
#define QCUSTOMPLOT_VERSION 0x020101
// decl definitions for shared library compilation/usage:
#if defined(QT_STATIC_BUILD)
# define QCP_LIB_DECL
#elif defined(QCUSTOMPLOT_COMPILE_LIBRARY)
# define QCP_LIB_DECL Q_DECL_EXPORT
#elif defined(QCUSTOMPLOT_USE_LIBRARY)
# define QCP_LIB_DECL Q_DECL_IMPORT
#else
# define QCP_LIB_DECL
#endif
// define empty macro for Q_DECL_OVERRIDE if it doesn't exist (Qt < 5)
#ifndef Q_DECL_OVERRIDE
# define Q_DECL_OVERRIDE
#endif
/*!
The QCP Namespace contains general enums, QFlags and functions used throughout the QCustomPlot
library.
It provides QMetaObject-based reflection of its enums and flags via \a QCP::staticMetaObject.
*/
// Qt version < 6.2.0: to get metatypes Q_GADGET/Q_ENUMS/Q_FLAGS in namespace we have to make it look like a class during moc-run
#if QT_VERSION >= 0x060200 // don't use QT_VERSION_CHECK here, some moc versions don't understand it
namespace QCP {
Q_NAMESPACE // this is how to add the staticMetaObject to namespaces in newer Qt versions
#else // Qt version older than 6.2.0
# ifndef Q_MOC_RUN
namespace QCP {
# else // not in moc run
class QCP {
Q_GADGET
Q_ENUMS(ExportPen)
Q_ENUMS(ResolutionUnit)
Q_ENUMS(SignDomain)
Q_ENUMS(MarginSide)
Q_ENUMS(AntialiasedElement)
Q_ENUMS(PlottingHint)
Q_ENUMS(Interaction)
Q_ENUMS(SelectionRectMode)
Q_ENUMS(SelectionType)
Q_FLAGS(AntialiasedElements)
Q_FLAGS(PlottingHints)
Q_FLAGS(MarginSides)
Q_FLAGS(Interactions)
public:
# endif
#endif
/*!
Defines the different units in which the image resolution can be specified in the export
functions.
\see QCustomPlot::savePng, QCustomPlot::saveJpg, QCustomPlot::saveBmp, QCustomPlot::saveRastered
*/
enum ResolutionUnit { ruDotsPerMeter ///< Resolution is given in dots per meter (dpm)
,ruDotsPerCentimeter ///< Resolution is given in dots per centimeter (dpcm)
,ruDotsPerInch ///< Resolution is given in dots per inch (DPI/PPI)
};
/*!
Defines how cosmetic pens (pens with numerical width 0) are handled during export.
\see QCustomPlot::savePdf
*/
enum ExportPen { epNoCosmetic ///< Cosmetic pens are converted to pens with pixel width 1 when exporting
,epAllowCosmetic ///< Cosmetic pens are exported normally (e.g. in PDF exports, cosmetic pens always appear as 1 pixel on screen, independent of viewer zoom level)
};
/*!
Represents negative and positive sign domain, e.g. for passing to \ref
QCPAbstractPlottable::getKeyRange and \ref QCPAbstractPlottable::getValueRange.
This is primarily needed when working with logarithmic axis scales, since only one of the sign
domains can be visible at a time.
*/
enum SignDomain { sdNegative ///< The negative sign domain, i.e. numbers smaller than zero
,sdBoth ///< Both sign domains, including zero, i.e. all numbers
,sdPositive ///< The positive sign domain, i.e. numbers greater than zero
};
/*!
Defines the sides of a rectangular entity to which margins can be applied.
\see QCPLayoutElement::setAutoMargins, QCPAxisRect::setAutoMargins
*/
enum MarginSide { msLeft = 0x01 ///< <tt>0x01</tt> left margin
,msRight = 0x02 ///< <tt>0x02</tt> right margin
,msTop = 0x04 ///< <tt>0x04</tt> top margin
,msBottom = 0x08 ///< <tt>0x08</tt> bottom margin
,msAll = 0xFF ///< <tt>0xFF</tt> all margins
,msNone = 0x00 ///< <tt>0x00</tt> no margin
};
Q_DECLARE_FLAGS(MarginSides, MarginSide)
/*!
Defines what objects of a plot can be forcibly drawn antialiased/not antialiased. If an object is
neither forcibly drawn antialiased nor forcibly drawn not antialiased, it is up to the respective
element how it is drawn. Typically it provides a \a setAntialiased function for this.
\c AntialiasedElements is a flag of or-combined elements of this enum type.
\see QCustomPlot::setAntialiasedElements, QCustomPlot::setNotAntialiasedElements
*/
enum AntialiasedElement { aeAxes = 0x0001 ///< <tt>0x0001</tt> Axis base line and tick marks
,aeGrid = 0x0002 ///< <tt>0x0002</tt> Grid lines
,aeSubGrid = 0x0004 ///< <tt>0x0004</tt> Sub grid lines
,aeLegend = 0x0008 ///< <tt>0x0008</tt> Legend box
,aeLegendItems = 0x0010 ///< <tt>0x0010</tt> Legend items
,aePlottables = 0x0020 ///< <tt>0x0020</tt> Main lines of plottables
,aeItems = 0x0040 ///< <tt>0x0040</tt> Main lines of items
,aeScatters = 0x0080 ///< <tt>0x0080</tt> Scatter symbols of plottables (excluding scatter symbols of type ssPixmap)
,aeFills = 0x0100 ///< <tt>0x0100</tt> Borders of fills (e.g. under or between graphs)
,aeZeroLine = 0x0200 ///< <tt>0x0200</tt> Zero-lines, see \ref QCPGrid::setZeroLinePen
,aeOther = 0x8000 ///< <tt>0x8000</tt> Other elements that don't fit into any of the existing categories
,aeAll = 0xFFFF ///< <tt>0xFFFF</tt> All elements
,aeNone = 0x0000 ///< <tt>0x0000</tt> No elements
};
Q_DECLARE_FLAGS(AntialiasedElements, AntialiasedElement)
/*!
Defines plotting hints that control various aspects of the quality and speed of plotting.
\see QCustomPlot::setPlottingHints
*/
enum PlottingHint { phNone = 0x000 ///< <tt>0x000</tt> No hints are set
,phFastPolylines = 0x001 ///< <tt>0x001</tt> Graph/Curve lines are drawn with a faster method. This reduces the quality especially of the line segment
///< joins, thus is most effective for pen sizes larger than 1. It is only used for solid line pens.
,phImmediateRefresh = 0x002 ///< <tt>0x002</tt> causes an immediate repaint() instead of a soft update() when QCustomPlot::replot() is called with parameter \ref QCustomPlot::rpRefreshHint.
///< This is set by default to prevent the plot from freezing on fast consecutive replots (e.g. user drags ranges with mouse).
,phCacheLabels = 0x004 ///< <tt>0x004</tt> axis (tick) labels will be cached as pixmaps, increasing replot performance.
};
Q_DECLARE_FLAGS(PlottingHints, PlottingHint)
/*!
Defines the mouse interactions possible with QCustomPlot.
\c Interactions is a flag of or-combined elements of this enum type.
\see QCustomPlot::setInteractions
*/
enum Interaction { iNone = 0x000 ///< <tt>0x000</tt> None of the interactions are possible
,iRangeDrag = 0x001 ///< <tt>0x001</tt> Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes)
,iRangeZoom = 0x002 ///< <tt>0x002</tt> Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes)
,iMultiSelect = 0x004 ///< <tt>0x004</tt> The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking
,iSelectPlottables = 0x008 ///< <tt>0x008</tt> Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable)
,iSelectAxes = 0x010 ///< <tt>0x010</tt> Axes are selectable (or parts of them, see QCPAxis::setSelectableParts)
,iSelectLegend = 0x020 ///< <tt>0x020</tt> Legends are selectable (or their child items, see QCPLegend::setSelectableParts)
,iSelectItems = 0x040 ///< <tt>0x040</tt> Items are selectable (Rectangles, Arrows, Textitems, etc. see \ref QCPAbstractItem)
,iSelectOther = 0x080 ///< <tt>0x080</tt> All other objects are selectable (e.g. your own derived layerables, other layout elements,...)
,iSelectPlottablesBeyondAxisRect = 0x100 ///< <tt>0x100</tt> When performing plottable selection/hit tests, this flag extends the sensitive area beyond the axis rect
};
Q_DECLARE_FLAGS(Interactions, Interaction)
/*!
Defines the behaviour of the selection rect.
\see QCustomPlot::setSelectionRectMode, QCustomPlot::selectionRect, QCPSelectionRect
*/
enum SelectionRectMode { srmNone ///< The selection rect is disabled, and all mouse events are forwarded to the underlying objects, e.g. for axis range dragging
,srmZoom ///< When dragging the mouse, a selection rect becomes active. Upon releasing, the axes that are currently set as range zoom axes (\ref QCPAxisRect::setRangeZoomAxes) will have their ranges zoomed accordingly.
,srmSelect ///< When dragging the mouse, a selection rect becomes active. Upon releasing, plottable data points that were within the selection rect are selected, if the plottable's selectability setting permits. (See \ref dataselection "data selection mechanism" for details.)
,srmCustom ///< When dragging the mouse, a selection rect becomes active. It is the programmer's responsibility to connect according slots to the selection rect's signals (e.g. \ref QCPSelectionRect::accepted) in order to process the user interaction.
};
/*!
Defines the different ways a plottable can be selected. These images show the effect of the
different selection types, when the indicated selection rect was dragged:
<center>
<table>
<tr>
<td>\image html selectiontype-none.png stNone</td>
<td>\image html selectiontype-whole.png stWhole</td>
<td>\image html selectiontype-singledata.png stSingleData</td>
<td>\image html selectiontype-datarange.png stDataRange</td>
<td>\image html selectiontype-multipledataranges.png stMultipleDataRanges</td>
</tr>
</table>
</center>
\see QCPAbstractPlottable::setSelectable, QCPDataSelection::enforceType
*/
enum SelectionType { stNone ///< The plottable is not selectable
,stWhole ///< Selection behaves like \ref stMultipleDataRanges, but if there are any data points selected, the entire plottable is drawn as selected.
,stSingleData ///< One individual data point can be selected at a time
,stDataRange ///< Multiple contiguous data points (a data range) can be selected
,stMultipleDataRanges ///< Any combination of data points/ranges can be selected
};
/*! \internal
Returns whether the specified \a value is considered an invalid data value for plottables (i.e.
is \e nan or \e +/-inf). This function is used to check data validity upon replots, when the
compiler flag \c QCUSTOMPLOT_CHECK_DATA is set.
*/
inline bool isInvalidData(double value)
{
return qIsNaN(value) || qIsInf(value);
}
/*! \internal
\overload
Checks two arguments instead of one.
*/
inline bool isInvalidData(double value1, double value2)
{
return isInvalidData(value1) || isInvalidData(value2);
}
/*! \internal
Sets the specified \a side of \a margins to \a value
\see getMarginValue
*/
inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value)
{
switch (side)
{
case QCP::msLeft: margins.setLeft(value); break;
case QCP::msRight: margins.setRight(value); break;
case QCP::msTop: margins.setTop(value); break;
case QCP::msBottom: margins.setBottom(value); break;
case QCP::msAll: margins = QMargins(value, value, value, value); break;
default: break;
}
}
/*! \internal
Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or
\ref QCP::msAll, returns 0.
\see setMarginValue
*/
inline int getMarginValue(const QMargins &margins, QCP::MarginSide side)
{
switch (side)
{
case QCP::msLeft: return margins.left();
case QCP::msRight: return margins.right();
case QCP::msTop: return margins.top();
case QCP::msBottom: return margins.bottom();
default: break;
}
return 0;
}
// for newer Qt versions we have to declare the enums/flags as metatypes inside the namespace using Q_ENUM_NS/Q_FLAG_NS:
// if you change anything here, don't forget to change it for older Qt versions below, too,
// and at the start of the namespace in the fake moc-run class
#if QT_VERSION >= 0x060200
Q_ENUM_NS(ExportPen)
Q_ENUM_NS(ResolutionUnit)
Q_ENUM_NS(SignDomain)
Q_ENUM_NS(MarginSide)
Q_ENUM_NS(AntialiasedElement)
Q_ENUM_NS(PlottingHint)
Q_ENUM_NS(Interaction)
Q_ENUM_NS(SelectionRectMode)
Q_ENUM_NS(SelectionType)
Q_FLAG_NS(AntialiasedElements)
Q_FLAG_NS(PlottingHints)
Q_FLAG_NS(MarginSides)
Q_FLAG_NS(Interactions)
#else
extern const QMetaObject staticMetaObject;
#endif
} // end of namespace QCP
Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::AntialiasedElements)
Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::PlottingHints)
Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::MarginSides)
Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::Interactions)
// for older Qt versions we have to declare the enums/flags as metatypes outside the namespace using Q_DECLARE_METATYPE:
// if you change anything here, don't forget to change it for newer Qt versions above, too,
// and at the start of the namespace in the fake moc-run class
#if QT_VERSION < QT_VERSION_CHECK(6, 2, 0)
Q_DECLARE_METATYPE(QCP::ExportPen)
Q_DECLARE_METATYPE(QCP::ResolutionUnit)
Q_DECLARE_METATYPE(QCP::SignDomain)
Q_DECLARE_METATYPE(QCP::MarginSide)
Q_DECLARE_METATYPE(QCP::AntialiasedElement)
Q_DECLARE_METATYPE(QCP::PlottingHint)
Q_DECLARE_METATYPE(QCP::Interaction)
Q_DECLARE_METATYPE(QCP::SelectionRectMode)
Q_DECLARE_METATYPE(QCP::SelectionType)
#endif
/* end of 'src/global.h' */
/* including file 'src/vector2d.h' */
/* modified 2022-11-06T12:45:56, size 4988 */
class QCP_LIB_DECL QCPVector2D
{
public:
QCPVector2D();
QCPVector2D(double x, double y);
QCPVector2D(const QPoint &point);
QCPVector2D(const QPointF &point);
// getters:
double x() const { return mX; }
double y() const { return mY; }
double &rx() { return mX; }
double &ry() { return mY; }
// setters:
void setX(double x) { mX = x; }
void setY(double y) { mY = y; }
// non-virtual methods:
double length() const { return qSqrt(mX*mX+mY*mY); }
double lengthSquared() const { return mX*mX+mY*mY; }
double angle() const { return qAtan2(mY, mX); }
QPoint toPoint() const { return QPoint(int(mX), int(mY)); }
QPointF toPointF() const { return QPointF(mX, mY); }
bool isNull() const { return qIsNull(mX) && qIsNull(mY); }
void normalize();
QCPVector2D normalized() const;
QCPVector2D perpendicular() const { return QCPVector2D(-mY, mX); }
double dot(const QCPVector2D &vec) const { return mX*vec.mX+mY*vec.mY; }
double distanceSquaredToLine(const QCPVector2D &start, const QCPVector2D &end) const;
double distanceSquaredToLine(const QLineF &line) const;
double distanceToStraightLine(const QCPVector2D &base, const QCPVector2D &direction) const;
QCPVector2D &operator*=(double factor);
QCPVector2D &operator/=(double divisor);
QCPVector2D &operator+=(const QCPVector2D &vector);
QCPVector2D &operator-=(const QCPVector2D &vector);
private:
// property members:
double mX, mY;
friend inline const QCPVector2D operator*(double factor, const QCPVector2D &vec);
friend inline const QCPVector2D operator*(const QCPVector2D &vec, double factor);
friend inline const QCPVector2D operator/(const QCPVector2D &vec, double divisor);
friend inline const QCPVector2D operator+(const QCPVector2D &vec1, const QCPVector2D &vec2);
friend inline const QCPVector2D operator-(const QCPVector2D &vec1, const QCPVector2D &vec2);
friend inline const QCPVector2D operator-(const QCPVector2D &vec);
};
Q_DECLARE_TYPEINFO(QCPVector2D, Q_MOVABLE_TYPE);
inline const QCPVector2D operator*(double factor, const QCPVector2D &vec) { return QCPVector2D(vec.mX*factor, vec.mY*factor); }
inline const QCPVector2D operator*(const QCPVector2D &vec, double factor) { return QCPVector2D(vec.mX*factor, vec.mY*factor); }
inline const QCPVector2D operator/(const QCPVector2D &vec, double divisor) { return QCPVector2D(vec.mX/divisor, vec.mY/divisor); }
inline const QCPVector2D operator+(const QCPVector2D &vec1, const QCPVector2D &vec2) { return QCPVector2D(vec1.mX+vec2.mX, vec1.mY+vec2.mY); }
inline const QCPVector2D operator-(const QCPVector2D &vec1, const QCPVector2D &vec2) { return QCPVector2D(vec1.mX-vec2.mX, vec1.mY-vec2.mY); }
inline const QCPVector2D operator-(const QCPVector2D &vec) { return QCPVector2D(-vec.mX, -vec.mY); }
/*! \relates QCPVector2D
Prints \a vec in a human readable format to the qDebug output.
*/
inline QDebug operator<< (QDebug d, const QCPVector2D &vec)
{
d.nospace() << "QCPVector2D(" << vec.x() << ", " << vec.y() << ")";
return d.space();
}
/* end of 'src/vector2d.h' */
/* including file 'src/painter.h' */
/* modified 2022-11-06T12:45:56, size 4035 */
class QCP_LIB_DECL QCPPainter : public QPainter
{
Q_GADGET
public:
/*!
Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds,
depending on whether they are wanted on the respective output device.
*/
enum PainterMode { pmDefault = 0x00 ///< <tt>0x00</tt> Default mode for painting on screen devices
,pmVectorized = 0x01 ///< <tt>0x01</tt> Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes.
,pmNoCaching = 0x02 ///< <tt>0x02</tt> Mode for all sorts of exports (e.g. PNG, PDF,...). For example, this prevents using cached pixmap labels
,pmNonCosmetic = 0x04 ///< <tt>0x04</tt> Turns pen widths 0 to 1, i.e. disables cosmetic pens. (A cosmetic pen is always drawn with width 1 pixel in the vector image/pdf viewer, independent of zoom.)
};
Q_ENUMS(PainterMode)
Q_FLAGS(PainterModes)
Q_DECLARE_FLAGS(PainterModes, PainterMode)
QCPPainter();
explicit QCPPainter(QPaintDevice *device);
// getters:
bool antialiasing() const { return testRenderHint(QPainter::Antialiasing); }
PainterModes modes() const { return mModes; }
// setters:
void setAntialiasing(bool enabled);
void setMode(PainterMode mode, bool enabled=true);
void setModes(PainterModes modes);
// methods hiding non-virtual base class functions (QPainter bug workarounds):
bool begin(QPaintDevice *device);
void setPen(const QPen &pen);
void setPen(const QColor &color);
void setPen(Qt::PenStyle penStyle);
void drawLine(const QLineF &line);
void drawLine(const QPointF &p1, const QPointF &p2) {drawLine(QLineF(p1, p2));}
void save();
void restore();
// non-virtual methods:
void makeNonCosmetic();
protected:
// property members:
PainterModes mModes;
bool mIsAntialiasing;
// non-property members:
QStack<bool> mAntialiasingStack;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes)
Q_DECLARE_METATYPE(QCPPainter::PainterMode)
/* end of 'src/painter.h' */
/* including file 'src/paintbuffer.h' */
/* modified 2022-11-06T12:45:56, size 5006 */
class QCP_LIB_DECL QCPAbstractPaintBuffer
{
public:
explicit QCPAbstractPaintBuffer(const QSize &size, double devicePixelRatio);
virtual ~QCPAbstractPaintBuffer();
// getters:
QSize size() const { return mSize; }
bool invalidated() const { return mInvalidated; }
double devicePixelRatio() const { return mDevicePixelRatio; }
// setters:
void setSize(const QSize &size);
void setInvalidated(bool invalidated=true);
void setDevicePixelRatio(double ratio);
// introduced virtual methods:
virtual QCPPainter *startPainting() = 0;
virtual void donePainting() {}
virtual void draw(QCPPainter *painter) const = 0;
virtual void clear(const QColor &color) = 0;
protected:
// property members:
QSize mSize;
double mDevicePixelRatio;
// non-property members:
bool mInvalidated;
// introduced virtual methods:
virtual void reallocateBuffer() = 0;
};
class QCP_LIB_DECL QCPPaintBufferPixmap : public QCPAbstractPaintBuffer
{
public:
explicit QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio);
virtual ~QCPPaintBufferPixmap() Q_DECL_OVERRIDE;
// reimplemented virtual methods:
virtual QCPPainter *startPainting() Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) const Q_DECL_OVERRIDE;
void clear(const QColor &color) Q_DECL_OVERRIDE;
protected:
// non-property members:
QPixmap mBuffer;
// reimplemented virtual methods:
virtual void reallocateBuffer() Q_DECL_OVERRIDE;
};
#ifdef QCP_OPENGL_PBUFFER
class QCP_LIB_DECL QCPPaintBufferGlPbuffer : public QCPAbstractPaintBuffer
{
public:
explicit QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples);
virtual ~QCPPaintBufferGlPbuffer() Q_DECL_OVERRIDE;
// reimplemented virtual methods:
virtual QCPPainter *startPainting() Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) const Q_DECL_OVERRIDE;
void clear(const QColor &color) Q_DECL_OVERRIDE;
protected:
// non-property members:
QGLPixelBuffer *mGlPBuffer;
int mMultisamples;
// reimplemented virtual methods:
virtual void reallocateBuffer() Q_DECL_OVERRIDE;
};
#endif // QCP_OPENGL_PBUFFER
#ifdef QCP_OPENGL_FBO
class QCP_LIB_DECL QCPPaintBufferGlFbo : public QCPAbstractPaintBuffer
{
public:
explicit QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer<QOpenGLContext> glContext, QWeakPointer<QOpenGLPaintDevice> glPaintDevice);
virtual ~QCPPaintBufferGlFbo() Q_DECL_OVERRIDE;
// reimplemented virtual methods:
virtual QCPPainter *startPainting() Q_DECL_OVERRIDE;
virtual void donePainting() Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) const Q_DECL_OVERRIDE;
void clear(const QColor &color) Q_DECL_OVERRIDE;
protected:
// non-property members:
QWeakPointer<QOpenGLContext> mGlContext;
QWeakPointer<QOpenGLPaintDevice> mGlPaintDevice;
QOpenGLFramebufferObject *mGlFrameBuffer;
// reimplemented virtual methods:
virtual void reallocateBuffer() Q_DECL_OVERRIDE;
};
#endif // QCP_OPENGL_FBO
/* end of 'src/paintbuffer.h' */
/* including file 'src/layer.h' */
/* modified 2022-11-06T12:45:56, size 7038 */
class QCP_LIB_DECL QCPLayer : public QObject
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot)
Q_PROPERTY(QString name READ name)
Q_PROPERTY(int index READ index)
Q_PROPERTY(QList<QCPLayerable*> children READ children)
Q_PROPERTY(bool visible READ visible WRITE setVisible)
Q_PROPERTY(LayerMode mode READ mode WRITE setMode)
/// \endcond
public:
/*!
Defines the different rendering modes of a layer. Depending on the mode, certain layers can be
replotted individually, without the need to replot (possibly complex) layerables on other
layers.
\see setMode
*/
enum LayerMode { lmLogical ///< Layer is used only for rendering order, and shares paint buffer with all other adjacent logical layers.
,lmBuffered ///< Layer has its own paint buffer and may be replotted individually (see \ref replot).
};
Q_ENUMS(LayerMode)
QCPLayer(QCustomPlot* parentPlot, const QString &layerName);
virtual ~QCPLayer();
// getters:
QCustomPlot *parentPlot() const { return mParentPlot; }
QString name() const { return mName; }
int index() const { return mIndex; }
QList<QCPLayerable*> children() const { return mChildren; }
bool visible() const { return mVisible; }
LayerMode mode() const { return mMode; }
// setters:
void setVisible(bool visible);
void setMode(LayerMode mode);
// non-virtual methods:
void replot();
protected:
// property members:
QCustomPlot *mParentPlot;
QString mName;
int mIndex;
QList<QCPLayerable*> mChildren;
bool mVisible;
LayerMode mMode;
// non-property members:
QWeakPointer<QCPAbstractPaintBuffer> mPaintBuffer;
// non-virtual methods:
void draw(QCPPainter *painter);
void drawToPaintBuffer();
void addChild(QCPLayerable *layerable, bool prepend);
void removeChild(QCPLayerable *layerable);
private:
Q_DISABLE_COPY(QCPLayer)
friend class QCustomPlot;
friend class QCPLayerable;
};
Q_DECLARE_METATYPE(QCPLayer::LayerMode)
class QCP_LIB_DECL QCPLayerable : public QObject
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(bool visible READ visible WRITE setVisible)
Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot)
Q_PROPERTY(QCPLayerable* parentLayerable READ parentLayerable)
Q_PROPERTY(QCPLayer* layer READ layer WRITE setLayer NOTIFY layerChanged)
Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased)
/// \endcond
public:
QCPLayerable(QCustomPlot *plot, QString targetLayer=QString(), QCPLayerable *parentLayerable=nullptr);
virtual ~QCPLayerable();
// getters:
bool visible() const { return mVisible; }
QCustomPlot *parentPlot() const { return mParentPlot; }
QCPLayerable *parentLayerable() const { return mParentLayerable.data(); }
QCPLayer *layer() const { return mLayer; }
bool antialiased() const { return mAntialiased; }
// setters:
void setVisible(bool on);
Q_SLOT bool setLayer(QCPLayer *layer);
bool setLayer(const QString &layerName);
void setAntialiased(bool enabled);
// introduced virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const;
// non-property methods:
bool realVisibility() const;
signals:
void layerChanged(QCPLayer *newLayer);
protected:
// property members:
bool mVisible;
QCustomPlot *mParentPlot;
QPointer<QCPLayerable> mParentLayerable;
QCPLayer *mLayer;
bool mAntialiased;
// introduced virtual methods:
virtual void parentPlotInitialized(QCustomPlot *parentPlot);
virtual QCP::Interaction selectionCategory() const;
virtual QRect clipRect() const;
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0;
virtual void draw(QCPPainter *painter) = 0;
// selection events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged);
virtual void deselectEvent(bool *selectionStateChanged);
// low-level mouse events:
virtual void mousePressEvent(QMouseEvent *event, const QVariant &details);
virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos);
virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos);
virtual void mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details);
virtual void wheelEvent(QWheelEvent *event);
// non-property methods:
void initializeParentPlot(QCustomPlot *parentPlot);
void setParentLayerable(QCPLayerable* parentLayerable);
bool moveToLayer(QCPLayer *layer, bool prepend);
void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const;
private:
Q_DISABLE_COPY(QCPLayerable)
friend class QCustomPlot;
friend class QCPLayer;
friend class QCPAxisRect;
};
/* end of 'src/layer.h' */
/* including file 'src/axis/range.h' */
/* modified 2022-11-06T12:45:56, size 5280 */
class QCP_LIB_DECL QCPRange
{
public:
double lower, upper;
QCPRange();
QCPRange(double lower, double upper);
bool operator==(const QCPRange& other) const { return lower == other.lower && upper == other.upper; }
bool operator!=(const QCPRange& other) const { return !(*this == other); }
QCPRange &operator+=(const double& value) { lower+=value; upper+=value; return *this; }
QCPRange &operator-=(const double& value) { lower-=value; upper-=value; return *this; }
QCPRange &operator*=(const double& value) { lower*=value; upper*=value; return *this; }
QCPRange &operator/=(const double& value) { lower/=value; upper/=value; return *this; }
friend inline const QCPRange operator+(const QCPRange&, double);
friend inline const QCPRange operator+(double, const QCPRange&);
friend inline const QCPRange operator-(const QCPRange& range, double value);
friend inline const QCPRange operator*(const QCPRange& range, double value);
friend inline const QCPRange operator*(double value, const QCPRange& range);
friend inline const QCPRange operator/(const QCPRange& range, double value);
double size() const { return upper-lower; }
double center() const { return (upper+lower)*0.5; }
void normalize() { if (lower > upper) qSwap(lower, upper); }
void expand(const QCPRange &otherRange);
void expand(double includeCoord);
QCPRange expanded(const QCPRange &otherRange) const;
QCPRange expanded(double includeCoord) const;
QCPRange bounded(double lowerBound, double upperBound) const;
QCPRange sanitizedForLogScale() const;
QCPRange sanitizedForLinScale() const;
bool contains(double value) const { return value >= lower && value <= upper; }
static bool validRange(double lower, double upper);
static bool validRange(const QCPRange &range);
static const double minRange;
static const double maxRange;
};
Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE);
/*! \relates QCPRange
Prints \a range in a human readable format to the qDebug output.
*/
inline QDebug operator<< (QDebug d, const QCPRange &range)
{
d.nospace() << "QCPRange(" << range.lower << ", " << range.upper << ")";
return d.space();
}
/*!
Adds \a value to both boundaries of the range.
*/
inline const QCPRange operator+(const QCPRange& range, double value)
{
QCPRange result(range);
result += value;
return result;
}
/*!
Adds \a value to both boundaries of the range.
*/
inline const QCPRange operator+(double value, const QCPRange& range)
{
QCPRange result(range);
result += value;
return result;
}
/*!
Subtracts \a value from both boundaries of the range.
*/
inline const QCPRange operator-(const QCPRange& range, double value)
{
QCPRange result(range);
result -= value;
return result;
}
/*!
Multiplies both boundaries of the range by \a value.
*/
inline const QCPRange operator*(const QCPRange& range, double value)
{
QCPRange result(range);
result *= value;
return result;
}
/*!
Multiplies both boundaries of the range by \a value.
*/
inline const QCPRange operator*(double value, const QCPRange& range)
{
QCPRange result(range);
result *= value;
return result;
}
/*!
Divides both boundaries of the range by \a value.
*/
inline const QCPRange operator/(const QCPRange& range, double value)
{
QCPRange result(range);
result /= value;
return result;
}
/* end of 'src/axis/range.h' */
/* including file 'src/selection.h' */
/* modified 2022-11-06T12:45:56, size 8569 */
class QCP_LIB_DECL QCPDataRange
{
public:
QCPDataRange();
QCPDataRange(int begin, int end);
bool operator==(const QCPDataRange& other) const { return mBegin == other.mBegin && mEnd == other.mEnd; }
bool operator!=(const QCPDataRange& other) const { return !(*this == other); }
// getters:
int begin() const { return mBegin; }
int end() const { return mEnd; }
int size() const { return mEnd-mBegin; }
int length() const { return size(); }
// setters:
void setBegin(int begin) { mBegin = begin; }
void setEnd(int end) { mEnd = end; }
// non-property methods:
bool isValid() const { return (mEnd >= mBegin) && (mBegin >= 0); }
bool isEmpty() const { return length() == 0; }
QCPDataRange bounded(const QCPDataRange &other) const;
QCPDataRange expanded(const QCPDataRange &other) const;
QCPDataRange intersection(const QCPDataRange &other) const;
QCPDataRange adjusted(int changeBegin, int changeEnd) const { return QCPDataRange(mBegin+changeBegin, mEnd+changeEnd); }
bool intersects(const QCPDataRange &other) const;
bool contains(const QCPDataRange &other) const;
private:
// property members:
int mBegin, mEnd;
};
Q_DECLARE_TYPEINFO(QCPDataRange, Q_MOVABLE_TYPE);
class QCP_LIB_DECL QCPDataSelection
{
public:
explicit QCPDataSelection();
explicit QCPDataSelection(const QCPDataRange &range);
bool operator==(const QCPDataSelection& other) const;
bool operator!=(const QCPDataSelection& other) const { return !(*this == other); }
QCPDataSelection &operator+=(const QCPDataSelection& other);
QCPDataSelection &operator+=(const QCPDataRange& other);
QCPDataSelection &operator-=(const QCPDataSelection& other);
QCPDataSelection &operator-=(const QCPDataRange& other);
friend inline const QCPDataSelection operator+(const QCPDataSelection& a, const QCPDataSelection& b);
friend inline const QCPDataSelection operator+(const QCPDataRange& a, const QCPDataSelection& b);
friend inline const QCPDataSelection operator+(const QCPDataSelection& a, const QCPDataRange& b);
friend inline const QCPDataSelection operator+(const QCPDataRange& a, const QCPDataRange& b);
friend inline const QCPDataSelection operator-(const QCPDataSelection& a, const QCPDataSelection& b);
friend inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataSelection& b);
friend inline const QCPDataSelection operator-(const QCPDataSelection& a, const QCPDataRange& b);
friend inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataRange& b);
// getters:
int dataRangeCount() const { return static_cast<int>(mDataRanges.size()); }
int dataPointCount() const;
QCPDataRange dataRange(int index=0) const;
QList<QCPDataRange> dataRanges() const { return mDataRanges; }
QCPDataRange span() const;
// non-property methods:
void addDataRange(const QCPDataRange &dataRange, bool simplify=true);
void clear();
bool isEmpty() const { return mDataRanges.isEmpty(); }
void simplify();
void enforceType(QCP::SelectionType type);
bool contains(const QCPDataSelection &other) const;
QCPDataSelection intersection(const QCPDataRange &other) const;
QCPDataSelection intersection(const QCPDataSelection &other) const;
QCPDataSelection inverse(const QCPDataRange &outerRange) const;
private:
// property members:
QList<QCPDataRange> mDataRanges;
inline static bool lessThanDataRangeBegin(const QCPDataRange &a, const QCPDataRange &b) { return a.begin() < b.begin(); }
};
Q_DECLARE_METATYPE(QCPDataSelection)
/*!
Return a \ref QCPDataSelection with the data points in \a a joined with the data points in \a b.
The resulting data selection is already simplified (see \ref QCPDataSelection::simplify).
*/
inline const QCPDataSelection operator+(const QCPDataSelection& a, const QCPDataSelection& b)
{
QCPDataSelection result(a);
result += b;
return result;
}
/*!
Return a \ref QCPDataSelection with the data points in \a a joined with the data points in \a b.
The resulting data selection is already simplified (see \ref QCPDataSelection::simplify).
*/
inline const QCPDataSelection operator+(const QCPDataRange& a, const QCPDataSelection& b)
{
QCPDataSelection result(a);
result += b;
return result;
}
/*!
Return a \ref QCPDataSelection with the data points in \a a joined with the data points in \a b.
The resulting data selection is already simplified (see \ref QCPDataSelection::simplify).
*/
inline const QCPDataSelection operator+(const QCPDataSelection& a, const QCPDataRange& b)
{
QCPDataSelection result(a);
result += b;
return result;
}
/*!
Return a \ref QCPDataSelection with the data points in \a a joined with the data points in \a b.
The resulting data selection is already simplified (see \ref QCPDataSelection::simplify).
*/
inline const QCPDataSelection operator+(const QCPDataRange& a, const QCPDataRange& b)
{
QCPDataSelection result(a);
result += b;
return result;
}
/*!
Return a \ref QCPDataSelection with the data points which are in \a a but not in \a b.
*/
inline const QCPDataSelection operator-(const QCPDataSelection& a, const QCPDataSelection& b)
{
QCPDataSelection result(a);
result -= b;
return result;
}
/*!
Return a \ref QCPDataSelection with the data points which are in \a a but not in \a b.
*/
inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataSelection& b)
{
QCPDataSelection result(a);
result -= b;
return result;
}
/*!
Return a \ref QCPDataSelection with the data points which are in \a a but not in \a b.
*/
inline const QCPDataSelection operator-(const QCPDataSelection& a, const QCPDataRange& b)
{
QCPDataSelection result(a);
result -= b;
return result;
}
/*!
Return a \ref QCPDataSelection with the data points which are in \a a but not in \a b.
*/
inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataRange& b)
{
QCPDataSelection result(a);
result -= b;
return result;
}
/*! \relates QCPDataRange
Prints \a dataRange in a human readable format to the qDebug output.
*/
inline QDebug operator<< (QDebug d, const QCPDataRange &dataRange)
{
d.nospace() << "QCPDataRange(" << dataRange.begin() << ", " << dataRange.end() << ")";
return d;
}
/*! \relates QCPDataSelection
Prints \a selection in a human readable format to the qDebug output.
*/
inline QDebug operator<< (QDebug d, const QCPDataSelection &selection)
{
d.nospace() << "QCPDataSelection(";
for (int i=0; i<selection.dataRangeCount(); ++i)
{
if (i != 0)
d << ", ";
d << selection.dataRange(i);
}
d << ")";
return d;
}
/* end of 'src/selection.h' */
/* including file 'src/selectionrect.h' */
/* modified 2022-11-06T12:45:56, size 3354 */
class QCP_LIB_DECL QCPSelectionRect : public QCPLayerable
{
Q_OBJECT
public:
explicit QCPSelectionRect(QCustomPlot *parentPlot);
virtual ~QCPSelectionRect() Q_DECL_OVERRIDE;
// getters:
QRect rect() const { return mRect; }
QCPRange range(const QCPAxis *axis) const;
QPen pen() const { return mPen; }
QBrush brush() const { return mBrush; }
bool isActive() const { return mActive; }
// setters:
void setPen(const QPen &pen);
void setBrush(const QBrush &brush);
// non-property methods:
Q_SLOT void cancel();
signals:
void started(QMouseEvent *event);
void changed(const QRect &rect, QMouseEvent *event);
void canceled(const QRect &rect, QInputEvent *event);
void accepted(const QRect &rect, QMouseEvent *event);
protected:
// property members:
QRect mRect;
QPen mPen;
QBrush mBrush;
// non-property members:
bool mActive;
// introduced virtual methods:
virtual void startSelection(QMouseEvent *event);
virtual void moveSelection(QMouseEvent *event);
virtual void endSelection(QMouseEvent *event);
virtual void keyPressEvent(QKeyEvent *event);
// reimplemented virtual methods
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
friend class QCustomPlot;
};
/* end of 'src/selectionrect.h' */
/* including file 'src/layout.h' */
/* modified 2022-11-06T12:45:56, size 14279 */
class QCP_LIB_DECL QCPMarginGroup : public QObject
{
Q_OBJECT
public:
explicit QCPMarginGroup(QCustomPlot *parentPlot);
virtual ~QCPMarginGroup();
// non-virtual methods:
QList<QCPLayoutElement*> elements(QCP::MarginSide side) const { return mChildren.value(side); }
bool isEmpty() const;
void clear();
protected:
// non-property members:
QCustomPlot *mParentPlot;
QHash<QCP::MarginSide, QList<QCPLayoutElement*> > mChildren;
// introduced virtual methods:
virtual int commonMargin(QCP::MarginSide side) const;
// non-virtual methods:
void addChild(QCP::MarginSide side, QCPLayoutElement *element);
void removeChild(QCP::MarginSide side, QCPLayoutElement *element);
private:
Q_DISABLE_COPY(QCPMarginGroup)
friend class QCPLayoutElement;
};
class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QCPLayout* layout READ layout)
Q_PROPERTY(QRect rect READ rect)
Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect)
Q_PROPERTY(QMargins margins READ margins WRITE setMargins)
Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins)
Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize)
Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize)
Q_PROPERTY(SizeConstraintRect sizeConstraintRect READ sizeConstraintRect WRITE setSizeConstraintRect)
/// \endcond
public:
/*!
Defines the phases of the update process, that happens just before a replot. At each phase,
\ref update is called with the according UpdatePhase value.
*/
enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout
,upMargins ///< Phase in which the margins are calculated and set
,upLayout ///< Final phase in which the layout system places the rects of the elements
};
Q_ENUMS(UpdatePhase)
/*!
Defines to which rect of a layout element the size constraints that can be set via \ref
setMinimumSize and \ref setMaximumSize apply. The outer rect (\ref outerRect) includes the
margins (e.g. in the case of a QCPAxisRect the axis labels), whereas the inner rect (\ref rect)
does not.
\see setSizeConstraintRect
*/
enum SizeConstraintRect { scrInnerRect ///< Minimum/Maximum size constraints apply to inner rect
, scrOuterRect ///< Minimum/Maximum size constraints apply to outer rect, thus include layout element margins
};
Q_ENUMS(SizeConstraintRect)
explicit QCPLayoutElement(QCustomPlot *parentPlot=nullptr);
virtual ~QCPLayoutElement() Q_DECL_OVERRIDE;
// getters:
QCPLayout *layout() const { return mParentLayout; }
QRect rect() const { return mRect; }
QRect outerRect() const { return mOuterRect; }
QMargins margins() const { return mMargins; }
QMargins minimumMargins() const { return mMinimumMargins; }
QCP::MarginSides autoMargins() const { return mAutoMargins; }
QSize minimumSize() const { return mMinimumSize; }
QSize maximumSize() const { return mMaximumSize; }
SizeConstraintRect sizeConstraintRect() const { return mSizeConstraintRect; }
QCPMarginGroup *marginGroup(QCP::MarginSide side) const { return mMarginGroups.value(side, nullptr); }
QHash<QCP::MarginSide, QCPMarginGroup*> marginGroups() const { return mMarginGroups; }
// setters:
void setOuterRect(const QRect &rect);
void setMargins(const QMargins &margins);
void setMinimumMargins(const QMargins &margins);
void setAutoMargins(QCP::MarginSides sides);
void setMinimumSize(const QSize &size);
void setMinimumSize(int width, int height);
void setMaximumSize(const QSize &size);
void setMaximumSize(int width, int height);
void setSizeConstraintRect(SizeConstraintRect constraintRect);
void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group);
// introduced virtual methods:
virtual void update(UpdatePhase phase);
virtual QSize minimumOuterSizeHint() const;
virtual QSize maximumOuterSizeHint() const;
virtual QList<QCPLayoutElement*> elements(bool recursive) const;
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
protected:
// property members:
QCPLayout *mParentLayout;
QSize mMinimumSize, mMaximumSize;
SizeConstraintRect mSizeConstraintRect;
QRect mRect, mOuterRect;
QMargins mMargins, mMinimumMargins;
QCP::MarginSides mAutoMargins;
QHash<QCP::MarginSide, QCPMarginGroup*> mMarginGroups;
// introduced virtual methods:
virtual int calculateAutoMargin(QCP::MarginSide side);
virtual void layoutChanged();
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE { Q_UNUSED(painter) }
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE { Q_UNUSED(painter) }
virtual void parentPlotInitialized(QCustomPlot *parentPlot) Q_DECL_OVERRIDE;
private:
Q_DISABLE_COPY(QCPLayoutElement)
friend class QCustomPlot;
friend class QCPLayout;
friend class QCPMarginGroup;
};
Q_DECLARE_METATYPE(QCPLayoutElement::UpdatePhase)
class QCP_LIB_DECL QCPLayout : public QCPLayoutElement
{
Q_OBJECT
public:
explicit QCPLayout();
// reimplemented virtual methods:
virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE;
virtual QList<QCPLayoutElement*> elements(bool recursive) const Q_DECL_OVERRIDE;
// introduced virtual methods:
virtual int elementCount() const = 0;
virtual QCPLayoutElement* elementAt(int index) const = 0;
virtual QCPLayoutElement* takeAt(int index) = 0;
virtual bool take(QCPLayoutElement* element) = 0;
virtual void simplify();
// non-virtual methods:
bool removeAt(int index);
bool remove(QCPLayoutElement* element);
void clear();
protected:
// introduced virtual methods:
virtual void updateLayout();
// non-virtual methods:
void sizeConstraintsChanged() const;
void adoptElement(QCPLayoutElement *el);
void releaseElement(QCPLayoutElement *el);
QVector<int> getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes, QVector<double> stretchFactors, int totalSize) const;
static QSize getFinalMinimumOuterSize(const QCPLayoutElement *el);
static QSize getFinalMaximumOuterSize(const QCPLayoutElement *el);
private:
Q_DISABLE_COPY(QCPLayout)
friend class QCPLayoutElement;
};
class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(int rowCount READ rowCount)
Q_PROPERTY(int columnCount READ columnCount)
Q_PROPERTY(QList<double> columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors)
Q_PROPERTY(QList<double> rowStretchFactors READ rowStretchFactors WRITE setRowStretchFactors)
Q_PROPERTY(int columnSpacing READ columnSpacing WRITE setColumnSpacing)
Q_PROPERTY(int rowSpacing READ rowSpacing WRITE setRowSpacing)
Q_PROPERTY(FillOrder fillOrder READ fillOrder WRITE setFillOrder)
Q_PROPERTY(int wrap READ wrap WRITE setWrap)
/// \endcond
public:
/*!
Defines in which direction the grid is filled when using \ref addElement(QCPLayoutElement*).
The column/row at which wrapping into the next row/column occurs can be specified with \ref
setWrap.
\see setFillOrder
*/
enum FillOrder { foRowsFirst ///< Rows are filled first, and a new element is wrapped to the next column if the row count would exceed \ref setWrap.
,foColumnsFirst ///< Columns are filled first, and a new element is wrapped to the next row if the column count would exceed \ref setWrap.
};
Q_ENUMS(FillOrder)
explicit QCPLayoutGrid();
virtual ~QCPLayoutGrid() Q_DECL_OVERRIDE;
// getters:
int rowCount() const { return static_cast<int>(mElements.size()); }
int columnCount() const { return mElements.size() > 0 ? static_cast<int>(mElements.first().size()) : 0; }
QList<double> columnStretchFactors() const { return mColumnStretchFactors; }
QList<double> rowStretchFactors() const { return mRowStretchFactors; }
int columnSpacing() const { return mColumnSpacing; }
int rowSpacing() const { return mRowSpacing; }
int wrap() const { return mWrap; }
FillOrder fillOrder() const { return mFillOrder; }
// setters:
void setColumnStretchFactor(int column, double factor);
void setColumnStretchFactors(const QList<double> &factors);
void setRowStretchFactor(int row, double factor);
void setRowStretchFactors(const QList<double> &factors);
void setColumnSpacing(int pixels);
void setRowSpacing(int pixels);
void setWrap(int count);
void setFillOrder(FillOrder order, bool rearrange=true);
// reimplemented virtual methods:
virtual void updateLayout() Q_DECL_OVERRIDE;
virtual int elementCount() const Q_DECL_OVERRIDE { return rowCount()*columnCount(); }
virtual QCPLayoutElement* elementAt(int index) const Q_DECL_OVERRIDE;
virtual QCPLayoutElement* takeAt(int index) Q_DECL_OVERRIDE;
virtual bool take(QCPLayoutElement* element) Q_DECL_OVERRIDE;
virtual QList<QCPLayoutElement*> elements(bool recursive) const Q_DECL_OVERRIDE;
virtual void simplify() Q_DECL_OVERRIDE;
virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE;
virtual QSize maximumOuterSizeHint() const Q_DECL_OVERRIDE;
// non-virtual methods:
QCPLayoutElement *element(int row, int column) const;
bool addElement(int row, int column, QCPLayoutElement *element);
bool addElement(QCPLayoutElement *element);
bool hasElement(int row, int column);
void expandTo(int newRowCount, int newColumnCount);
void insertRow(int newIndex);
void insertColumn(int newIndex);
int rowColToIndex(int row, int column) const;
void indexToRowCol(int index, int &row, int &column) const;
protected:
// property members:
QList<QList<QCPLayoutElement*> > mElements;
QList<double> mColumnStretchFactors;
QList<double> mRowStretchFactors;
int mColumnSpacing, mRowSpacing;
int mWrap;
FillOrder mFillOrder;
// non-virtual methods:
void getMinimumRowColSizes(QVector<int> *minColWidths, QVector<int> *minRowHeights) const;
void getMaximumRowColSizes(QVector<int> *maxColWidths, QVector<int> *maxRowHeights) const;
private:
Q_DISABLE_COPY(QCPLayoutGrid)
};
Q_DECLARE_METATYPE(QCPLayoutGrid::FillOrder)
class QCP_LIB_DECL QCPLayoutInset : public QCPLayout
{
Q_OBJECT
public:
/*!
Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset.
*/
enum InsetPlacement { ipFree ///< The element may be positioned/sized arbitrarily, see \ref setInsetRect
,ipBorderAligned ///< The element is aligned to one of the layout sides, see \ref setInsetAlignment
};
Q_ENUMS(InsetPlacement)
explicit QCPLayoutInset();
virtual ~QCPLayoutInset() Q_DECL_OVERRIDE;
// getters:
InsetPlacement insetPlacement(int index) const;
Qt::Alignment insetAlignment(int index) const;
QRectF insetRect(int index) const;
// setters:
void setInsetPlacement(int index, InsetPlacement placement);
void setInsetAlignment(int index, Qt::Alignment alignment);
void setInsetRect(int index, const QRectF &rect);
// reimplemented virtual methods:
virtual void updateLayout() Q_DECL_OVERRIDE;
virtual int elementCount() const Q_DECL_OVERRIDE;
virtual QCPLayoutElement* elementAt(int index) const Q_DECL_OVERRIDE;
virtual QCPLayoutElement* takeAt(int index) Q_DECL_OVERRIDE;
virtual bool take(QCPLayoutElement* element) Q_DECL_OVERRIDE;
virtual void simplify() Q_DECL_OVERRIDE {}
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
// non-virtual methods:
void addElement(QCPLayoutElement *element, Qt::Alignment alignment);
void addElement(QCPLayoutElement *element, const QRectF &rect);
protected:
// property members:
QList<QCPLayoutElement*> mElements;
QList<InsetPlacement> mInsetPlacement;
QList<Qt::Alignment> mInsetAlignment;
QList<QRectF> mInsetRect;
private:
Q_DISABLE_COPY(QCPLayoutInset)
};
Q_DECLARE_METATYPE(QCPLayoutInset::InsetPlacement)
/* end of 'src/layout.h' */
/* including file 'src/lineending.h' */
/* modified 2022-11-06T12:45:56, size 4426 */
class QCP_LIB_DECL QCPLineEnding
{
Q_GADGET
public:
/*!
Defines the type of ending decoration for line-like items, e.g. an arrow.
\image html QCPLineEnding.png
The width and length of these decorations can be controlled with the functions \ref setWidth
and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only
support a width, the length property is ignored.
\see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding
*/
enum EndingStyle { esNone ///< No ending decoration
,esFlatArrow ///< A filled arrow head with a straight/flat back (a triangle)
,esSpikeArrow ///< A filled arrow head with an indented back
,esLineArrow ///< A non-filled arrow head with open back
,esDisc ///< A filled circle
,esSquare ///< A filled square
,esDiamond ///< A filled diamond (45 degrees rotated square)
,esBar ///< A bar perpendicular to the line
,esHalfBar ///< A bar perpendicular to the line, pointing out to only one side (to which side can be changed with \ref setInverted)
,esSkewedBar ///< A bar that is skewed (skew controllable via \ref setLength)
};
Q_ENUMS(EndingStyle)
QCPLineEnding();
QCPLineEnding(EndingStyle style, double width=8, double length=10, bool inverted=false);
// getters:
EndingStyle style() const { return mStyle; }
double width() const { return mWidth; }
double length() const { return mLength; }
bool inverted() const { return mInverted; }
// setters:
void setStyle(EndingStyle style);
void setWidth(double width);
void setLength(double length);
void setInverted(bool inverted);
// non-property methods:
double boundingDistance() const;
double realLength() const;
void draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const;
void draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const;
protected:
// property members:
EndingStyle mStyle;
double mWidth, mLength;
bool mInverted;
};
Q_DECLARE_TYPEINFO(QCPLineEnding, Q_MOVABLE_TYPE);
Q_DECLARE_METATYPE(QCPLineEnding::EndingStyle)
/* end of 'src/lineending.h' */
/* including file 'src/axis/labelpainter.h' */
/* modified 2022-11-06T12:45:56, size 7086 */
class QCPLabelPainterPrivate
{
Q_GADGET
public:
/*!
TODO
*/
enum AnchorMode { amRectangular ///<
,amSkewedUpright ///<
,amSkewedRotated ///<
};
Q_ENUMS(AnchorMode)
/*!
TODO
*/
enum AnchorReferenceType { artNormal ///<
,artTangent ///<
};
Q_ENUMS(AnchorReferenceType)
/*!
TODO
*/
enum AnchorSide { asLeft ///<
,asRight ///<
,asTop ///<
,asBottom ///<
,asTopLeft
,asTopRight
,asBottomRight
,asBottomLeft
};
Q_ENUMS(AnchorSide)
explicit QCPLabelPainterPrivate(QCustomPlot *parentPlot);
virtual ~QCPLabelPainterPrivate();
// setters:
void setAnchorSide(AnchorSide side);
void setAnchorMode(AnchorMode mode);
void setAnchorReference(const QPointF &pixelPoint);
void setAnchorReferenceType(AnchorReferenceType type);
void setFont(const QFont &font);
void setColor(const QColor &color);
void setPadding(int padding);
void setRotation(double rotation);
void setSubstituteExponent(bool enabled);
void setMultiplicationSymbol(QChar symbol);
void setAbbreviateDecimalPowers(bool enabled);
void setCacheSize(int labelCount);
// getters:
AnchorMode anchorMode() const { return mAnchorMode; }
AnchorSide anchorSide() const { return mAnchorSide; }
QPointF anchorReference() const { return mAnchorReference; }
AnchorReferenceType anchorReferenceType() const { return mAnchorReferenceType; }
QFont font() const { return mFont; }
QColor color() const { return mColor; }
int padding() const { return mPadding; }
double rotation() const { return mRotation; }
bool substituteExponent() const { return mSubstituteExponent; }
QChar multiplicationSymbol() const { return mMultiplicationSymbol; }
bool abbreviateDecimalPowers() const { return mAbbreviateDecimalPowers; }
int cacheSize() const;
//virtual int size() const;
// non-property methods:
void drawTickLabel(QCPPainter *painter, const QPointF &tickPos, const QString &text);
void clearCache();
// constants that may be used with setMultiplicationSymbol:
static const QChar SymbolDot;
static const QChar SymbolCross;
protected:
struct CachedLabel
{
QPoint offset;
QPixmap pixmap;
};
struct LabelData
{
AnchorSide side;
double rotation; // angle in degrees
QTransform transform; // the transform about the label anchor which is at (0, 0). Does not contain final absolute x/y positioning on the plot/axis
QString basePart, expPart, suffixPart;
QRect baseBounds, expBounds, suffixBounds;
QRect totalBounds; // is in a coordinate system where label top left is at (0, 0)
QRect rotatedTotalBounds; // is in a coordinate system where the label anchor is at (0, 0)
QFont baseFont, expFont;
QColor color;
};
// property members:
AnchorMode mAnchorMode;
AnchorSide mAnchorSide;
QPointF mAnchorReference;
AnchorReferenceType mAnchorReferenceType;
QFont mFont;
QColor mColor;
int mPadding;
double mRotation; // this is the rotation applied uniformly to all labels, not the heterogeneous rotation in amCircularRotated mode
bool mSubstituteExponent;
QChar mMultiplicationSymbol;
bool mAbbreviateDecimalPowers;
// non-property members:
QCustomPlot *mParentPlot;
QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters
QCache<QString, CachedLabel> mLabelCache;
QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox;
int mLetterCapHeight, mLetterDescent;
// introduced virtual methods:
virtual void drawLabelMaybeCached(QCPPainter *painter, const QFont &font, const QColor &color, const QPointF &pos, AnchorSide side, double rotation, const QString &text);
virtual QByteArray generateLabelParameterHash() const; // TODO: get rid of this in favor of invalidation flag upon setters?
// non-virtual methods:
QPointF getAnchorPos(const QPointF &tickPos);
void drawText(QCPPainter *painter, const QPointF &pos, const LabelData &labelData) const;
LabelData getTickLabelData(const QFont &font, const QColor &color, double rotation, AnchorSide side, const QString &text) const;
void applyAnchorTransform(LabelData &labelData) const;
//void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const;
CachedLabel *createCachedLabel(const LabelData &labelData) const;
QByteArray cacheKey(const QString &text, const QColor &color, double rotation, AnchorSide side) const;
AnchorSide skewedAnchorSide(const QPointF &tickPos, double sideExpandHorz, double sideExpandVert) const;
AnchorSide rotationCorrectedSide(AnchorSide side, double rotation) const;
void analyzeFontMetrics();
};
Q_DECLARE_METATYPE(QCPLabelPainterPrivate::AnchorMode)
Q_DECLARE_METATYPE(QCPLabelPainterPrivate::AnchorSide)
/* end of 'src/axis/labelpainter.h' */
/* including file 'src/axis/axisticker.h' */
/* modified 2022-11-06T12:45:56, size 4230 */
class QCP_LIB_DECL QCPAxisTicker
{
Q_GADGET
public:
/*!
Defines the strategies that the axis ticker may follow when choosing the size of the tick step.
\see setTickStepStrategy
*/
enum TickStepStrategy
{
tssReadability ///< A nicely readable tick step is prioritized over matching the requested number of ticks (see \ref setTickCount)
,tssMeetTickCount ///< Less readable tick steps are allowed which in turn facilitates getting closer to the requested tick count
};
Q_ENUMS(TickStepStrategy)
QCPAxisTicker();
virtual ~QCPAxisTicker();
// getters:
TickStepStrategy tickStepStrategy() const { return mTickStepStrategy; }
int tickCount() const { return mTickCount; }
double tickOrigin() const { return mTickOrigin; }
// setters:
void setTickStepStrategy(TickStepStrategy strategy);
void setTickCount(int count);
void setTickOrigin(double origin);
// introduced virtual methods:
virtual void generate(const QCPRange &range, const QLocale &locale, QChar formatChar, int precision, QVector<double> &ticks, QVector<double> *subTicks, QVector<QString> *tickLabels);
protected:
// property members:
TickStepStrategy mTickStepStrategy;
int mTickCount;
double mTickOrigin;
// introduced virtual methods:
virtual double getTickStep(const QCPRange &range);
virtual int getSubTickCount(double tickStep);
virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision);
virtual QVector<double> createTickVector(double tickStep, const QCPRange &range);
virtual QVector<double> createSubTickVector(int subTickCount, const QVector<double> &ticks);
virtual QVector<QString> createLabelVector(const QVector<double> &ticks, const QLocale &locale, QChar formatChar, int precision);
// non-virtual methods:
void trimTicks(const QCPRange &range, QVector<double> &ticks, bool keepOneOutlier) const;
double pickClosest(double target, const QVector<double> &candidates) const;
double getMantissa(double input, double *magnitude=nullptr) const;
double cleanMantissa(double input) const;
private:
Q_DISABLE_COPY(QCPAxisTicker)
};
Q_DECLARE_METATYPE(QCPAxisTicker::TickStepStrategy)
Q_DECLARE_METATYPE(QSharedPointer<QCPAxisTicker>)
/* end of 'src/axis/axisticker.h' */
/* including file 'src/axis/axistickerdatetime.h' */
/* modified 2022-11-06T12:45:56, size 3600 */
class QCP_LIB_DECL QCPAxisTickerDateTime : public QCPAxisTicker
{
public:
QCPAxisTickerDateTime();
// getters:
QString dateTimeFormat() const { return mDateTimeFormat; }
Qt::TimeSpec dateTimeSpec() const { return mDateTimeSpec; }
# if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
QTimeZone timeZone() const { return mTimeZone; }
#endif
// setters:
void setDateTimeFormat(const QString &format);
void setDateTimeSpec(Qt::TimeSpec spec);
# if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
void setTimeZone(const QTimeZone &zone);
# endif
void setTickOrigin(double origin); // hides base class method but calls baseclass implementation ("using" throws off IDEs and doxygen)
void setTickOrigin(const QDateTime &origin);
// static methods:
static QDateTime keyToDateTime(double key);
static double dateTimeToKey(const QDateTime &dateTime);
static double dateTimeToKey(const QDate &date, Qt::TimeSpec timeSpec=Qt::LocalTime);
protected:
// property members:
QString mDateTimeFormat;
Qt::TimeSpec mDateTimeSpec;
# if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
QTimeZone mTimeZone;
# endif
// non-property members:
enum DateStrategy {dsNone, dsUniformTimeInDay, dsUniformDayInMonth} mDateStrategy;
// reimplemented virtual methods:
virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE;
virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE;
virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) Q_DECL_OVERRIDE;
virtual QVector<double> createTickVector(double tickStep, const QCPRange &range) Q_DECL_OVERRIDE;
};
/* end of 'src/axis/axistickerdatetime.h' */
/* including file 'src/axis/axistickertime.h' */
/* modified 2022-11-06T12:45:56, size 3542 */
class QCP_LIB_DECL QCPAxisTickerTime : public QCPAxisTicker
{
Q_GADGET
public:
/*!
Defines the logical units in which fractions of time spans can be expressed.
\see setFieldWidth, setTimeFormat
*/
enum TimeUnit { tuMilliseconds ///< Milliseconds, one thousandth of a second (%%z in \ref setTimeFormat)
,tuSeconds ///< Seconds (%%s in \ref setTimeFormat)
,tuMinutes ///< Minutes (%%m in \ref setTimeFormat)
,tuHours ///< Hours (%%h in \ref setTimeFormat)
,tuDays ///< Days (%%d in \ref setTimeFormat)
};
Q_ENUMS(TimeUnit)
QCPAxisTickerTime();
// getters:
QString timeFormat() const { return mTimeFormat; }
int fieldWidth(TimeUnit unit) const { return mFieldWidth.value(unit); }
// setters:
void setTimeFormat(const QString &format);
void setFieldWidth(TimeUnit unit, int width);
protected:
// property members:
QString mTimeFormat;
QHash<TimeUnit, int> mFieldWidth;
// non-property members:
TimeUnit mSmallestUnit, mBiggestUnit;
QHash<TimeUnit, QString> mFormatPattern;
// reimplemented virtual methods:
virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE;
virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE;
virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) Q_DECL_OVERRIDE;
// non-virtual methods:
void replaceUnit(QString &text, TimeUnit unit, int value) const;
};
Q_DECLARE_METATYPE(QCPAxisTickerTime::TimeUnit)
/* end of 'src/axis/axistickertime.h' */
/* including file 'src/axis/axistickerfixed.h' */
/* modified 2022-11-06T12:45:56, size 3308 */
class QCP_LIB_DECL QCPAxisTickerFixed : public QCPAxisTicker
{
Q_GADGET
public:
/*!
Defines how the axis ticker may modify the specified tick step (\ref setTickStep) in order to
control the number of ticks in the axis range.
\see setScaleStrategy
*/
enum ScaleStrategy { ssNone ///< Modifications are not allowed, the specified tick step is absolutely fixed. This might cause a high tick density and overlapping labels if the axis range is zoomed out.
,ssMultiples ///< An integer multiple of the specified tick step is allowed. The used factor follows the base class properties of \ref setTickStepStrategy and \ref setTickCount.
,ssPowers ///< An integer power of the specified tick step is allowed.
};
Q_ENUMS(ScaleStrategy)
QCPAxisTickerFixed();
// getters:
double tickStep() const { return mTickStep; }
ScaleStrategy scaleStrategy() const { return mScaleStrategy; }
// setters:
void setTickStep(double step);
void setScaleStrategy(ScaleStrategy strategy);
protected:
// property members:
double mTickStep;
ScaleStrategy mScaleStrategy;
// reimplemented virtual methods:
virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE;
};
Q_DECLARE_METATYPE(QCPAxisTickerFixed::ScaleStrategy)
/* end of 'src/axis/axistickerfixed.h' */
/* including file 'src/axis/axistickertext.h' */
/* modified 2022-11-06T12:45:56, size 3090 */
class QCP_LIB_DECL QCPAxisTickerText : public QCPAxisTicker
{
public:
QCPAxisTickerText();
// getters:
QMap<double, QString> &ticks() { return mTicks; }
int subTickCount() const { return mSubTickCount; }
// setters:
void setTicks(const QMap<double, QString> &ticks);
void setTicks(const QVector<double> &positions, const QVector<QString> &labels);
void setSubTickCount(int subTicks);
// non-virtual methods:
void clear();
void addTick(double position, const QString &label);
void addTicks(const QMap<double, QString> &ticks);
void addTicks(const QVector<double> &positions, const QVector<QString> &labels);
protected:
// property members:
QMap<double, QString> mTicks;
int mSubTickCount;
// reimplemented virtual methods:
virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE;
virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE;
virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) Q_DECL_OVERRIDE;
virtual QVector<double> createTickVector(double tickStep, const QCPRange &range) Q_DECL_OVERRIDE;
};
/* end of 'src/axis/axistickertext.h' */
/* including file 'src/axis/axistickerpi.h' */
/* modified 2022-11-06T12:45:56, size 3911 */
class QCP_LIB_DECL QCPAxisTickerPi : public QCPAxisTicker
{
Q_GADGET
public:
/*!
Defines how fractions should be displayed in tick labels.
\see setFractionStyle
*/
enum FractionStyle { fsFloatingPoint ///< Fractions are displayed as regular decimal floating point numbers, e.g. "0.25" or "0.125".
,fsAsciiFractions ///< Fractions are written as rationals using ASCII characters only, e.g. "1/4" or "1/8"
,fsUnicodeFractions ///< Fractions are written using sub- and superscript UTF-8 digits and the fraction symbol.
};
Q_ENUMS(FractionStyle)
QCPAxisTickerPi();
// getters:
QString piSymbol() const { return mPiSymbol; }
double piValue() const { return mPiValue; }
bool periodicity() const { return mPeriodicity; }
FractionStyle fractionStyle() const { return mFractionStyle; }
// setters:
void setPiSymbol(QString symbol);
void setPiValue(double pi);
void setPeriodicity(int multiplesOfPi);
void setFractionStyle(FractionStyle style);
protected:
// property members:
QString mPiSymbol;
double mPiValue;
int mPeriodicity;
FractionStyle mFractionStyle;
// non-property members:
double mPiTickStep; // size of one tick step in units of mPiValue
// reimplemented virtual methods:
virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE;
virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE;
virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) Q_DECL_OVERRIDE;
// non-virtual methods:
void simplifyFraction(int &numerator, int &denominator) const;
QString fractionToString(int numerator, int denominator) const;
QString unicodeFraction(int numerator, int denominator) const;
QString unicodeSuperscript(int number) const;
QString unicodeSubscript(int number) const;
};
Q_DECLARE_METATYPE(QCPAxisTickerPi::FractionStyle)
/* end of 'src/axis/axistickerpi.h' */
/* including file 'src/axis/axistickerlog.h' */
/* modified 2022-11-06T12:45:56, size 2594 */
class QCP_LIB_DECL QCPAxisTickerLog : public QCPAxisTicker
{
public:
QCPAxisTickerLog();
// getters:
double logBase() const { return mLogBase; }
int subTickCount() const { return mSubTickCount; }
// setters:
void setLogBase(double base);
void setSubTickCount(int subTicks);
protected:
// property members:
double mLogBase;
int mSubTickCount;
// non-property members:
double mLogBaseLnInv;
// reimplemented virtual methods:
virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE;
virtual QVector<double> createTickVector(double tickStep, const QCPRange &range) Q_DECL_OVERRIDE;
};
/* end of 'src/axis/axistickerlog.h' */
/* including file 'src/axis/axis.h' */
/* modified 2022-11-06T12:45:56, size 20913 */
class QCP_LIB_DECL QCPGrid :public QCPLayerable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible)
Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid)
Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine)
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen)
Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen)
/// \endcond
public:
explicit QCPGrid(QCPAxis *parentAxis);
// getters:
bool subGridVisible() const { return mSubGridVisible; }
bool antialiasedSubGrid() const { return mAntialiasedSubGrid; }
bool antialiasedZeroLine() const { return mAntialiasedZeroLine; }
QPen pen() const { return mPen; }
QPen subGridPen() const { return mSubGridPen; }
QPen zeroLinePen() const { return mZeroLinePen; }
// setters:
void setSubGridVisible(bool visible);
void setAntialiasedSubGrid(bool enabled);
void setAntialiasedZeroLine(bool enabled);
void setPen(const QPen &pen);
void setSubGridPen(const QPen &pen);
void setZeroLinePen(const QPen &pen);
protected:
// property members:
bool mSubGridVisible;
bool mAntialiasedSubGrid, mAntialiasedZeroLine;
QPen mPen, mSubGridPen, mZeroLinePen;
// non-property members:
QCPAxis *mParentAxis;
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
// non-virtual methods:
void drawGridLines(QCPPainter *painter) const;
void drawSubGridLines(QCPPainter *painter) const;
friend class QCPAxis;
};
class QCP_LIB_DECL QCPAxis : public QCPLayerable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(AxisType axisType READ axisType)
Q_PROPERTY(QCPAxisRect* axisRect READ axisRect)
Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged)
Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged)
Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed)
Q_PROPERTY(QSharedPointer<QCPAxisTicker> ticker READ ticker WRITE setTicker)
Q_PROPERTY(bool ticks READ ticks WRITE setTicks)
Q_PROPERTY(bool tickLabels READ tickLabels WRITE setTickLabels)
Q_PROPERTY(int tickLabelPadding READ tickLabelPadding WRITE setTickLabelPadding)
Q_PROPERTY(QFont tickLabelFont READ tickLabelFont WRITE setTickLabelFont)
Q_PROPERTY(QColor tickLabelColor READ tickLabelColor WRITE setTickLabelColor)
Q_PROPERTY(double tickLabelRotation READ tickLabelRotation WRITE setTickLabelRotation)
Q_PROPERTY(LabelSide tickLabelSide READ tickLabelSide WRITE setTickLabelSide)
Q_PROPERTY(QString numberFormat READ numberFormat WRITE setNumberFormat)
Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision)
Q_PROPERTY(QVector<double> tickVector READ tickVector)
Q_PROPERTY(QVector<QString> tickVectorLabels READ tickVectorLabels)
Q_PROPERTY(int tickLengthIn READ tickLengthIn WRITE setTickLengthIn)
Q_PROPERTY(int tickLengthOut READ tickLengthOut WRITE setTickLengthOut)
Q_PROPERTY(bool subTicks READ subTicks WRITE setSubTicks)
Q_PROPERTY(int subTickLengthIn READ subTickLengthIn WRITE setSubTickLengthIn)
Q_PROPERTY(int subTickLengthOut READ subTickLengthOut WRITE setSubTickLengthOut)
Q_PROPERTY(QPen basePen READ basePen WRITE setBasePen)
Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen)
Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen)
Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont)
Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor)
Q_PROPERTY(QString label READ label WRITE setLabel)
Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding)
Q_PROPERTY(int padding READ padding WRITE setPadding)
Q_PROPERTY(int offset READ offset WRITE setOffset)
Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged)
Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged)
Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont)
Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont)
Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor)
Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor)
Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen)
Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen)
Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen)
Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding)
Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding)
Q_PROPERTY(QCPGrid* grid READ grid)
/// \endcond
public:
/*!
Defines at which side of the axis rect the axis will appear. This also affects how the tick
marks are drawn, on which side the labels are placed etc.
*/
enum AxisType { atLeft = 0x01 ///< <tt>0x01</tt> Axis is vertical and on the left side of the axis rect
,atRight = 0x02 ///< <tt>0x02</tt> Axis is vertical and on the right side of the axis rect
,atTop = 0x04 ///< <tt>0x04</tt> Axis is horizontal and on the top side of the axis rect
,atBottom = 0x08 ///< <tt>0x08</tt> Axis is horizontal and on the bottom side of the axis rect
};
Q_ENUMS(AxisType)
Q_FLAGS(AxisTypes)
Q_DECLARE_FLAGS(AxisTypes, AxisType)
/*!
Defines on which side of the axis the tick labels (numbers) shall appear.
\see setTickLabelSide
*/
enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect
,lsOutside ///< Tick labels will be displayed outside the axis rect
};
Q_ENUMS(LabelSide)
/*!
Defines the scale of an axis.
\see setScaleType
*/
enum ScaleType { stLinear ///< Linear scaling
,stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance).
};
Q_ENUMS(ScaleType)
/*!
Defines the selectable parts of an axis.
\see setSelectableParts, setSelectedParts
*/
enum SelectablePart { spNone = 0 ///< None of the selectable parts
,spAxis = 0x001 ///< The axis backbone and tick marks
,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually)
,spAxisLabel = 0x004 ///< The axis label
};
Q_ENUMS(SelectablePart)
Q_FLAGS(SelectableParts)
Q_DECLARE_FLAGS(SelectableParts, SelectablePart)
explicit QCPAxis(QCPAxisRect *parent, AxisType type);
virtual ~QCPAxis() Q_DECL_OVERRIDE;
// getters:
AxisType axisType() const { return mAxisType; }
QCPAxisRect *axisRect() const { return mAxisRect; }
ScaleType scaleType() const { return mScaleType; }
const QCPRange range() const { return mRange; }
bool rangeReversed() const { return mRangeReversed; }
QSharedPointer<QCPAxisTicker> ticker() const { return mTicker; }
bool ticks() const { return mTicks; }
bool tickLabels() const { return mTickLabels; }
int tickLabelPadding() const;
QFont tickLabelFont() const { return mTickLabelFont; }
QColor tickLabelColor() const { return mTickLabelColor; }
double tickLabelRotation() const;
LabelSide tickLabelSide() const;
QString numberFormat() const;
int numberPrecision() const { return mNumberPrecision; }
QVector<double> tickVector() const { return mTickVector; }
QVector<QString> tickVectorLabels() const { return mTickVectorLabels; }
int tickLengthIn() const;
int tickLengthOut() const;
bool subTicks() const { return mSubTicks; }
int subTickLengthIn() const;
int subTickLengthOut() const;
QPen basePen() const { return mBasePen; }
QPen tickPen() const { return mTickPen; }
QPen subTickPen() const { return mSubTickPen; }
QFont labelFont() const { return mLabelFont; }
QColor labelColor() const { return mLabelColor; }
QString label() const { return mLabel; }
int labelPadding() const;
int padding() const { return mPadding; }
int offset() const;
SelectableParts selectedParts() const { return mSelectedParts; }
SelectableParts selectableParts() const { return mSelectableParts; }
QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; }
QFont selectedLabelFont() const { return mSelectedLabelFont; }
QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; }
QColor selectedLabelColor() const { return mSelectedLabelColor; }
QPen selectedBasePen() const { return mSelectedBasePen; }
QPen selectedTickPen() const { return mSelectedTickPen; }
QPen selectedSubTickPen() const { return mSelectedSubTickPen; }
QCPLineEnding lowerEnding() const;
QCPLineEnding upperEnding() const;
QCPGrid *grid() const { return mGrid; }
// setters:
Q_SLOT void setScaleType(QCPAxis::ScaleType type);
Q_SLOT void setRange(const QCPRange &range);
void setRange(double lower, double upper);
void setRange(double position, double size, Qt::AlignmentFlag alignment);
void setRangeLower(double lower);
void setRangeUpper(double upper);
void setRangeReversed(bool reversed);
void setTicker(QSharedPointer<QCPAxisTicker> ticker);
void setTicks(bool show);
void setTickLabels(bool show);
void setTickLabelPadding(int padding);
void setTickLabelFont(const QFont &font);
void setTickLabelColor(const QColor &color);
void setTickLabelRotation(double degrees);
void setTickLabelSide(LabelSide side);
void setNumberFormat(const QString &formatCode);
void setNumberPrecision(int precision);
void setTickLength(int inside, int outside=0);
void setTickLengthIn(int inside);
void setTickLengthOut(int outside);
void setSubTicks(bool show);
void setSubTickLength(int inside, int outside=0);
void setSubTickLengthIn(int inside);
void setSubTickLengthOut(int outside);
void setBasePen(const QPen &pen);
void setTickPen(const QPen &pen);
void setSubTickPen(const QPen &pen);
void setLabelFont(const QFont &font);
void setLabelColor(const QColor &color);
void setLabel(const QString &str);
void setLabelPadding(int padding);
void setPadding(int padding);
void setOffset(int offset);
void setSelectedTickLabelFont(const QFont &font);
void setSelectedLabelFont(const QFont &font);
void setSelectedTickLabelColor(const QColor &color);
void setSelectedLabelColor(const QColor &color);
void setSelectedBasePen(const QPen &pen);
void setSelectedTickPen(const QPen &pen);
void setSelectedSubTickPen(const QPen &pen);
Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts);
Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts);
void setLowerEnding(const QCPLineEnding &ending);
void setUpperEnding(const QCPLineEnding &ending);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
// non-property methods:
Qt::Orientation orientation() const { return mOrientation; }
int pixelOrientation() const { return rangeReversed() != (orientation()==Qt::Vertical) ? -1 : 1; }
void moveRange(double diff);
void scaleRange(double factor);
void scaleRange(double factor, double center);
void setScaleRatio(const QCPAxis *otherAxis, double ratio=1.0);
void rescale(bool onlyVisiblePlottables=false);
double pixelToCoord(double value) const;
double coordToPixel(double value) const;
SelectablePart getPartAt(const QPointF &pos) const;
QList<QCPAbstractPlottable*> plottables() const;
QList<QCPGraph*> graphs() const;
QList<QCPAbstractItem*> items() const;
static AxisType marginSideToAxisType(QCP::MarginSide side);
static Qt::Orientation orientation(AxisType type) { return type==atBottom || type==atTop ? Qt::Horizontal : Qt::Vertical; }
static AxisType opposite(AxisType type);
signals:
void rangeChanged(const QCPRange &newRange);
void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange);
void scaleTypeChanged(QCPAxis::ScaleType scaleType);
void selectionChanged(const QCPAxis::SelectableParts &parts);
void selectableChanged(const QCPAxis::SelectableParts &parts);
protected:
// property members:
// axis base:
AxisType mAxisType;
QCPAxisRect *mAxisRect;
//int mOffset; // in QCPAxisPainter
int mPadding;
Qt::Orientation mOrientation;
SelectableParts mSelectableParts, mSelectedParts;
QPen mBasePen, mSelectedBasePen;
//QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter
// axis label:
//int mLabelPadding; // in QCPAxisPainter
QString mLabel;
QFont mLabelFont, mSelectedLabelFont;
QColor mLabelColor, mSelectedLabelColor;
// tick labels:
//int mTickLabelPadding; // in QCPAxisPainter
bool mTickLabels;
//double mTickLabelRotation; // in QCPAxisPainter
QFont mTickLabelFont, mSelectedTickLabelFont;
QColor mTickLabelColor, mSelectedTickLabelColor;
int mNumberPrecision;
QLatin1Char mNumberFormatChar;
bool mNumberBeautifulPowers;
//bool mNumberMultiplyCross; // QCPAxisPainter
// ticks and subticks:
bool mTicks;
bool mSubTicks;
//int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter
QPen mTickPen, mSelectedTickPen;
QPen mSubTickPen, mSelectedSubTickPen;
// scale and range:
QCPRange mRange;
bool mRangeReversed;
ScaleType mScaleType;
// non-property members:
QCPGrid *mGrid;
QCPAxisPainterPrivate *mAxisPainter;
QSharedPointer<QCPAxisTicker> mTicker;
QVector<double> mTickVector;
QVector<QString> mTickVectorLabels;
QVector<double> mSubTickVector;
bool mCachedMarginValid;
int mCachedMargin;
bool mDragging;
QCPRange mDragStartRange;
QCP::AntialiasedElements mAADragBackup, mNotAADragBackup;
// introduced virtual methods:
virtual int calculateMargin();
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE;
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE;
virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE;
// mouse events:
virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE;
virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE;
virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE;
virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE;
// non-virtual methods:
void setupTickVectors();
QPen getBasePen() const;
QPen getTickPen() const;
QPen getSubTickPen() const;
QFont getTickLabelFont() const;
QFont getLabelFont() const;
QColor getTickLabelColor() const;
QColor getLabelColor() const;
private:
Q_DISABLE_COPY(QCPAxis)
friend class QCustomPlot;
friend class QCPGrid;
friend class QCPAxisRect;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::SelectableParts)
Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::AxisTypes)
Q_DECLARE_METATYPE(QCPAxis::AxisType)
Q_DECLARE_METATYPE(QCPAxis::LabelSide)
Q_DECLARE_METATYPE(QCPAxis::ScaleType)
Q_DECLARE_METATYPE(QCPAxis::SelectablePart)
class QCPAxisPainterPrivate
{
public:
explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot);
virtual ~QCPAxisPainterPrivate();
virtual void draw(QCPPainter *painter);
virtual int size();
void clearCache();
QRect axisSelectionBox() const { return mAxisSelectionBox; }
QRect tickLabelsSelectionBox() const { return mTickLabelsSelectionBox; }
QRect labelSelectionBox() const { return mLabelSelectionBox; }
// public property members:
QCPAxis::AxisType type;
QPen basePen;
QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters
int labelPadding; // directly accessed by QCPAxis setters/getters
QFont labelFont;
QColor labelColor;
QString label;
int tickLabelPadding; // directly accessed by QCPAxis setters/getters
double tickLabelRotation; // directly accessed by QCPAxis setters/getters
QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters
bool substituteExponent;
bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters
int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters
QPen tickPen, subTickPen;
QFont tickLabelFont;
QColor tickLabelColor;
QRect axisRect, viewportRect;
int offset; // directly accessed by QCPAxis setters/getters
bool abbreviateDecimalPowers;
bool reversedEndings;
QVector<double> subTickPositions;
QVector<double> tickPositions;
QVector<QString> tickLabels;
protected:
struct CachedLabel
{
QPointF offset;
QPixmap pixmap;
};
struct TickLabelData
{
QString basePart, expPart, suffixPart;
QRect baseBounds, expBounds, suffixBounds, totalBounds, rotatedTotalBounds;
QFont baseFont, expFont;
};
QCustomPlot *mParentPlot;
QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters
QCache<QString, CachedLabel> mLabelCache;
QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox;
virtual QByteArray generateLabelParameterHash() const;
virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize);
virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const;
virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const;
virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const;
virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const;
};
/* end of 'src/axis/axis.h' */
/* including file 'src/scatterstyle.h' */
/* modified 2022-11-06T12:45:56, size 7275 */
class QCP_LIB_DECL QCPScatterStyle
{
Q_GADGET
public:
/*!
Represents the various properties of a scatter style instance. For example, this enum is used
to specify which properties of \ref QCPSelectionDecorator::setScatterStyle will be used when
highlighting selected data points.
Specific scatter properties can be transferred between \ref QCPScatterStyle instances via \ref
setFromOther.
*/
enum ScatterProperty { spNone = 0x00 ///< <tt>0x00</tt> None
,spPen = 0x01 ///< <tt>0x01</tt> The pen property, see \ref setPen
,spBrush = 0x02 ///< <tt>0x02</tt> The brush property, see \ref setBrush
,spSize = 0x04 ///< <tt>0x04</tt> The size property, see \ref setSize
,spShape = 0x08 ///< <tt>0x08</tt> The shape property, see \ref setShape
,spAll = 0xFF ///< <tt>0xFF</tt> All properties
};
Q_ENUMS(ScatterProperty)
Q_FLAGS(ScatterProperties)
Q_DECLARE_FLAGS(ScatterProperties, ScatterProperty)
/*!
Defines the shape used for scatter points.
On plottables/items that draw scatters, the sizes of these visualizations (with exception of
\ref ssDot and \ref ssPixmap) can be controlled with the \ref setSize function. Scatters are
drawn with the pen and brush specified with \ref setPen and \ref setBrush.
*/
enum ScatterShape { ssNone ///< no scatter symbols are drawn (e.g. in QCPGraph, data only represented with lines)
,ssDot ///< \enumimage{ssDot.png} a single pixel (use \ref ssDisc or \ref ssCircle if you want a round shape with a certain radius)
,ssCross ///< \enumimage{ssCross.png} a cross
,ssPlus ///< \enumimage{ssPlus.png} a plus
,ssCircle ///< \enumimage{ssCircle.png} a circle
,ssDisc ///< \enumimage{ssDisc.png} a circle which is filled with the pen's color (not the brush as with ssCircle)
,ssSquare ///< \enumimage{ssSquare.png} a square
,ssDiamond ///< \enumimage{ssDiamond.png} a diamond
,ssStar ///< \enumimage{ssStar.png} a star with eight arms, i.e. a combination of cross and plus
,ssTriangle ///< \enumimage{ssTriangle.png} an equilateral triangle, standing on baseline
,ssTriangleInverted ///< \enumimage{ssTriangleInverted.png} an equilateral triangle, standing on corner
,ssCrossSquare ///< \enumimage{ssCrossSquare.png} a square with a cross inside
,ssPlusSquare ///< \enumimage{ssPlusSquare.png} a square with a plus inside
,ssCrossCircle ///< \enumimage{ssCrossCircle.png} a circle with a cross inside
,ssPlusCircle ///< \enumimage{ssPlusCircle.png} a circle with a plus inside
,ssPeace ///< \enumimage{ssPeace.png} a circle, with one vertical and two downward diagonal lines
,ssPixmap ///< a custom pixmap specified by \ref setPixmap, centered on the data point coordinates
,ssCustom ///< custom painter operations are performed per scatter (As QPainterPath, see \ref setCustomPath)
};
Q_ENUMS(ScatterShape)
QCPScatterStyle();
QCPScatterStyle(ScatterShape shape, double size=6);
QCPScatterStyle(ScatterShape shape, const QColor &color, double size);
QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size);
QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size);
QCPScatterStyle(const QPixmap &pixmap);
QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush=Qt::NoBrush, double size=6);
// getters:
double size() const { return mSize; }
ScatterShape shape() const { return mShape; }
QPen pen() const { return mPen; }
QBrush brush() const { return mBrush; }
QPixmap pixmap() const { return mPixmap; }
QPainterPath customPath() const { return mCustomPath; }
// setters:
void setFromOther(const QCPScatterStyle &other, ScatterProperties properties);
void setSize(double size);
void setShape(ScatterShape shape);
void setPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setPixmap(const QPixmap &pixmap);
void setCustomPath(const QPainterPath &customPath);
// non-property methods:
bool isNone() const { return mShape == ssNone; }
bool isPenDefined() const { return mPenDefined; }
void undefinePen();
void applyTo(QCPPainter *painter, const QPen &defaultPen) const;
void drawShape(QCPPainter *painter, const QPointF &pos) const;
void drawShape(QCPPainter *painter, double x, double y) const;
protected:
// property members:
double mSize;
ScatterShape mShape;
QPen mPen;
QBrush mBrush;
QPixmap mPixmap;
QPainterPath mCustomPath;
// non-property members:
bool mPenDefined;
};
Q_DECLARE_TYPEINFO(QCPScatterStyle, Q_MOVABLE_TYPE);
Q_DECLARE_OPERATORS_FOR_FLAGS(QCPScatterStyle::ScatterProperties)
Q_DECLARE_METATYPE(QCPScatterStyle::ScatterProperty)
Q_DECLARE_METATYPE(QCPScatterStyle::ScatterShape)
/* end of 'src/scatterstyle.h' */
/* including file 'src/datacontainer.h' */
/* modified 2022-11-06T12:45:56, size 34305 */
/*! \relates QCPDataContainer
Returns whether the sort key of \a a is less than the sort key of \a b.
\see QCPDataContainer::sort
*/
template <class DataType>
inline bool qcpLessThanSortKey(const DataType &a, const DataType &b) { return a.sortKey() < b.sortKey(); }
template <class DataType>
class QCPDataContainer // no QCP_LIB_DECL, template class ends up in header (cpp included below)
{
public:
typedef typename QVector<DataType>::const_iterator const_iterator;
typedef typename QVector<DataType>::iterator iterator;
QCPDataContainer();
// getters:
int size() const { return static_cast<int>(mData.size()-mPreallocSize); }
bool isEmpty() const { return size() == 0; }
bool autoSqueeze() const { return mAutoSqueeze; }
// setters:
void setAutoSqueeze(bool enabled);
// non-virtual methods:
void set(const QCPDataContainer<DataType> &data);
void set(const QVector<DataType> &data, bool alreadySorted=false);
void add(const QCPDataContainer<DataType> &data);
void add(const QVector<DataType> &data, bool alreadySorted=false);
void add(const DataType &data);
void removeBefore(double sortKey);
void removeAfter(double sortKey);
void remove(double sortKeyFrom, double sortKeyTo);
void remove(double sortKey);
void clear();
void sort();
void squeeze(bool preAllocation=true, bool postAllocation=true);
const_iterator constBegin() const { return mData.constBegin()+mPreallocSize; }
const_iterator constEnd() const { return mData.constEnd(); }
iterator begin() { return mData.begin()+mPreallocSize; }
iterator end() { return mData.end(); }
const_iterator findBegin(double sortKey, bool expandedRange=true) const;
const_iterator findEnd(double sortKey, bool expandedRange=true) const;
const_iterator at(int index) const { return constBegin()+qBound(0, index, size()); }
QCPRange keyRange(bool &foundRange, QCP::SignDomain signDomain=QCP::sdBoth);
QCPRange valueRange(bool &foundRange, QCP::SignDomain signDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange());
QCPDataRange dataRange() const { return QCPDataRange(0, size()); }
void limitIteratorsToDataRange(const_iterator &begin, const_iterator &end, const QCPDataRange &dataRange) const;
protected:
// property members:
bool mAutoSqueeze;
// non-property memebers:
QVector<DataType> mData;
int mPreallocSize;
int mPreallocIteration;
// non-virtual methods:
void preallocateGrow(int minimumPreallocSize);
void performAutoSqueeze();
};
// include implementation in header since it is a class template:
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPDataContainer
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPDataContainer
\brief The generic data container for one-dimensional plottables
This class template provides a fast container for data storage of one-dimensional data. The data
type is specified as template parameter (called \a DataType in the following) and must provide
some methods as described in the \ref qcpdatacontainer-datatype "next section".
The data is stored in a sorted fashion, which allows very quick lookups by the sorted key as well
as retrieval of ranges (see \ref findBegin, \ref findEnd, \ref keyRange) using binary search. The
container uses a preallocation and a postallocation scheme, such that appending and prepending
data (with respect to the sort key) is very fast and minimizes reallocations. If data is added
which needs to be inserted between existing keys, the merge usually can be done quickly too,
using the fact that existing data is always sorted. The user can further improve performance by
specifying that added data is already itself sorted by key, if he can guarantee that this is the
case (see for example \ref add(const QVector<DataType> &data, bool alreadySorted)).
The data can be accessed with the provided const iterators (\ref constBegin, \ref constEnd). If
it is necessary to alter existing data in-place, the non-const iterators can be used (\ref begin,
\ref end). Changing data members that are not the sort key (for most data types called \a key) is
safe from the container's perspective.
Great care must be taken however if the sort key is modified through the non-const iterators. For
performance reasons, the iterators don't automatically cause a re-sorting upon their
manipulation. It is thus the responsibility of the user to leave the container in a sorted state
when finished with the data manipulation, before calling any other methods on the container. A
complete re-sort (e.g. after finishing all sort key manipulation) can be done by calling \ref
sort. Failing to do so can not be detected by the container efficiently and will cause both
rendering artifacts and potential data loss.
Implementing one-dimensional plottables that make use of a \ref QCPDataContainer<T> is usually
done by subclassing from \ref QCPAbstractPlottable1D "QCPAbstractPlottable1D<T>", which
introduces an according \a mDataContainer member and some convenience methods.
\section qcpdatacontainer-datatype Requirements for the DataType template parameter
The template parameter <tt>DataType</tt> is the type of the stored data points. It must be
trivially copyable and have the following public methods, preferably inline:
\li <tt>double sortKey() const</tt>\n Returns the member variable of this data point that is the
sort key, defining the ordering in the container. Often this variable is simply called \a key.
\li <tt>static DataType fromSortKey(double sortKey)</tt>\n Returns a new instance of the data
type initialized with its sort key set to \a sortKey.
\li <tt>static bool sortKeyIsMainKey()</tt>\n Returns true if the sort key is equal to the main
key (see method \c mainKey below). For most plottables this is the case. It is not the case for
example for \ref QCPCurve, which uses \a t as sort key and \a key as main key. This is the reason
why QCPCurve unlike QCPGraph can display parametric curves with loops.
\li <tt>double mainKey() const</tt>\n Returns the variable of this data point considered the main
key. This is commonly the variable that is used as the coordinate of this data point on the key
axis of the plottable. This method is used for example when determining the automatic axis
rescaling of key axes (\ref QCPAxis::rescale).
\li <tt>double mainValue() const</tt>\n Returns the variable of this data point considered the
main value. This is commonly the variable that is used as the coordinate of this data point on
the value axis of the plottable.
\li <tt>QCPRange valueRange() const</tt>\n Returns the range this data point spans in the value
axis coordinate. If the data is single-valued (e.g. QCPGraphData), this is simply a range with
both lower and upper set to the main data point value. However if the data points can represent
multiple values at once (e.g QCPFinancialData with its \a high, \a low, \a open and \a close
values at each \a key) this method should return the range those values span. This method is used
for example when determining the automatic axis rescaling of value axes (\ref
QCPAxis::rescale).
*/
/* start documentation of inline functions */
/*! \fn int QCPDataContainer<DataType>::size() const
Returns the number of data points in the container.
*/
/*! \fn bool QCPDataContainer<DataType>::isEmpty() const
Returns whether this container holds no data points.
*/
/*! \fn QCPDataContainer::const_iterator QCPDataContainer<DataType>::constBegin() const
Returns a const iterator to the first data point in this container.
*/
/*! \fn QCPDataContainer::const_iterator QCPDataContainer<DataType>::constEnd() const
Returns a const iterator to the element past the last data point in this container.
*/
/*! \fn QCPDataContainer::iterator QCPDataContainer<DataType>::begin() const
Returns a non-const iterator to the first data point in this container.
You can manipulate the data points in-place through the non-const iterators, but great care must
be taken when manipulating the sort key of a data point, see \ref sort, or the detailed
description of this class.
*/
/*! \fn QCPDataContainer::iterator QCPDataContainer<DataType>::end() const
Returns a non-const iterator to the element past the last data point in this container.
You can manipulate the data points in-place through the non-const iterators, but great care must
be taken when manipulating the sort key of a data point, see \ref sort, or the detailed
description of this class.
*/
/*! \fn QCPDataContainer::const_iterator QCPDataContainer<DataType>::at(int index) const
Returns a const iterator to the element with the specified \a index. If \a index points beyond
the available elements in this container, returns \ref constEnd, i.e. an iterator past the last
valid element.
You can use this method to easily obtain iterators from a \ref QCPDataRange, see the \ref
dataselection-accessing "data selection page" for an example.
*/
/*! \fn QCPDataRange QCPDataContainer::dataRange() const
Returns a \ref QCPDataRange encompassing the entire data set of this container. This means the
begin index of the returned range is 0, and the end index is \ref size.
*/
/* end documentation of inline functions */
/*!
Constructs a QCPDataContainer used for plottable classes that represent a series of key-sorted
data
*/
template <class DataType>
QCPDataContainer<DataType>::QCPDataContainer() :
mAutoSqueeze(true),
mPreallocSize(0),
mPreallocIteration(0)
{
}
/*!
Sets whether the container automatically decides when to release memory from its post- and
preallocation pools when data points are removed. By default this is enabled and for typical
applications shouldn't be changed.
If auto squeeze is disabled, you can manually decide when to release pre-/postallocation with
\ref squeeze.
*/
template <class DataType>
void QCPDataContainer<DataType>::setAutoSqueeze(bool enabled)
{
if (mAutoSqueeze != enabled)
{
mAutoSqueeze = enabled;
if (mAutoSqueeze)
performAutoSqueeze();
}
}
/*! \overload
Replaces the current data in this container with the provided \a data.
\see add, remove
*/
template <class DataType>
void QCPDataContainer<DataType>::set(const QCPDataContainer<DataType> &data)
{
clear();
add(data);
}
/*! \overload
Replaces the current data in this container with the provided \a data
If you can guarantee that the data points in \a data have ascending order with respect to the
DataType's sort key, set \a alreadySorted to true to avoid an unnecessary sorting run.
\see add, remove
*/
template <class DataType>
void QCPDataContainer<DataType>::set(const QVector<DataType> &data, bool alreadySorted)
{
mData = data;
mPreallocSize = 0;
mPreallocIteration = 0;
if (!alreadySorted)
sort();
}
/*! \overload
Adds the provided \a data to the current data in this container.
\see set, remove
*/
template <class DataType>
void QCPDataContainer<DataType>::add(const QCPDataContainer<DataType> &data)
{
if (data.isEmpty())
return;
const int n = data.size();
const int oldSize = size();
if (oldSize > 0 && !qcpLessThanSortKey<DataType>(*constBegin(), *(data.constEnd()-1))) // prepend if new data keys are all smaller than or equal to existing ones
{
if (mPreallocSize < n)
preallocateGrow(n);
mPreallocSize -= n;
std::copy(data.constBegin(), data.constEnd(), begin());
} else // don't need to prepend, so append and merge if necessary
{
mData.resize(mData.size()+n);
std::copy(data.constBegin(), data.constEnd(), end()-n);
if (oldSize > 0 && !qcpLessThanSortKey<DataType>(*(constEnd()-n-1), *(constEnd()-n))) // if appended range keys aren't all greater than existing ones, merge the two partitions
std::inplace_merge(begin(), end()-n, end(), qcpLessThanSortKey<DataType>);
}
}
/*!
Adds the provided data points in \a data to the current data.
If you can guarantee that the data points in \a data have ascending order with respect to the
DataType's sort key, set \a alreadySorted to true to avoid an unnecessary sorting run.
\see set, remove
*/
template <class DataType>
void QCPDataContainer<DataType>::add(const QVector<DataType> &data, bool alreadySorted)
{
if (data.isEmpty())
return;
if (isEmpty())
{
set(data, alreadySorted);
return;
}
const int n = static_cast<int>(data.size());
const int oldSize = size();
if (alreadySorted && oldSize > 0 && !qcpLessThanSortKey<DataType>(*constBegin(), *(data.constEnd()-1))) // prepend if new data is sorted and keys are all smaller than or equal to existing ones
{
if (mPreallocSize < n)
preallocateGrow(n);
mPreallocSize -= n;
std::copy(data.constBegin(), data.constEnd(), begin());
} else // don't need to prepend, so append and then sort and merge if necessary
{
mData.resize(mData.size()+n);
std::copy(data.constBegin(), data.constEnd(), end()-n);
if (!alreadySorted) // sort appended subrange if it wasn't already sorted
std::sort(end()-n, end(), qcpLessThanSortKey<DataType>);
if (oldSize > 0 && !qcpLessThanSortKey<DataType>(*(constEnd()-n-1), *(constEnd()-n))) // if appended range keys aren't all greater than existing ones, merge the two partitions
std::inplace_merge(begin(), end()-n, end(), qcpLessThanSortKey<DataType>);
}
}
/*! \overload
Adds the provided single data point to the current data.
\see remove
*/
template <class DataType>
void QCPDataContainer<DataType>::add(const DataType &data)
{
if (isEmpty() || !qcpLessThanSortKey<DataType>(data, *(constEnd()-1))) // quickly handle appends if new data key is greater or equal to existing ones
{
mData.append(data);
} else if (qcpLessThanSortKey<DataType>(data, *constBegin())) // quickly handle prepends using preallocated space
{
if (mPreallocSize < 1)
preallocateGrow(1);
--mPreallocSize;
*begin() = data;
} else // handle inserts, maintaining sorted keys
{
QCPDataContainer<DataType>::iterator insertionPoint = std::lower_bound(begin(), end(), data, qcpLessThanSortKey<DataType>);
mData.insert(insertionPoint, data);
}
}
/*!
Removes all data points with (sort-)keys smaller than or equal to \a sortKey.
\see removeAfter, remove, clear
*/
template <class DataType>
void QCPDataContainer<DataType>::removeBefore(double sortKey)
{
QCPDataContainer<DataType>::iterator it = begin();
QCPDataContainer<DataType>::iterator itEnd = std::lower_bound(begin(), end(), DataType::fromSortKey(sortKey), qcpLessThanSortKey<DataType>);
mPreallocSize += int(itEnd-it); // don't actually delete, just add it to the preallocated block (if it gets too large, squeeze will take care of it)
if (mAutoSqueeze)
performAutoSqueeze();
}
/*!
Removes all data points with (sort-)keys greater than or equal to \a sortKey.
\see removeBefore, remove, clear
*/
template <class DataType>
void QCPDataContainer<DataType>::removeAfter(double sortKey)
{
QCPDataContainer<DataType>::iterator it = std::upper_bound(begin(), end(), DataType::fromSortKey(sortKey), qcpLessThanSortKey<DataType>);
QCPDataContainer<DataType>::iterator itEnd = end();
mData.erase(it, itEnd); // typically adds it to the postallocated block
if (mAutoSqueeze)
performAutoSqueeze();
}
/*!
Removes all data points with (sort-)keys between \a sortKeyFrom and \a sortKeyTo. if \a
sortKeyFrom is greater or equal to \a sortKeyTo, the function does nothing. To remove a single
data point with known (sort-)key, use \ref remove(double sortKey).
\see removeBefore, removeAfter, clear
*/
template <class DataType>
void QCPDataContainer<DataType>::remove(double sortKeyFrom, double sortKeyTo)
{
if (sortKeyFrom >= sortKeyTo || isEmpty())
return;
QCPDataContainer<DataType>::iterator it = std::lower_bound(begin(), end(), DataType::fromSortKey(sortKeyFrom), qcpLessThanSortKey<DataType>);
QCPDataContainer<DataType>::iterator itEnd = std::upper_bound(it, end(), DataType::fromSortKey(sortKeyTo), qcpLessThanSortKey<DataType>);
mData.erase(it, itEnd);
if (mAutoSqueeze)
performAutoSqueeze();
}
/*! \overload
Removes a single data point at \a sortKey. If the position is not known with absolute (binary)
precision, consider using \ref remove(double sortKeyFrom, double sortKeyTo) with a small
fuzziness interval around the suspected position, depeding on the precision with which the
(sort-)key is known.
\see removeBefore, removeAfter, clear
*/
template <class DataType>
void QCPDataContainer<DataType>::remove(double sortKey)
{
QCPDataContainer::iterator it = std::lower_bound(begin(), end(), DataType::fromSortKey(sortKey), qcpLessThanSortKey<DataType>);
if (it != end() && it->sortKey() == sortKey)
{
if (it == begin())
++mPreallocSize; // don't actually delete, just add it to the preallocated block (if it gets too large, squeeze will take care of it)
else
mData.erase(it);
}
if (mAutoSqueeze)
performAutoSqueeze();
}
/*!
Removes all data points.
\see remove, removeAfter, removeBefore
*/
template <class DataType>
void QCPDataContainer<DataType>::clear()
{
mData.clear();
mPreallocIteration = 0;
mPreallocSize = 0;
}
/*!
Re-sorts all data points in the container by their sort key.
When setting, adding or removing points using the QCPDataContainer interface (\ref set, \ref add,
\ref remove, etc.), the container makes sure to always stay in a sorted state such that a full
resort is never necessary. However, if you choose to directly manipulate the sort key on data
points by accessing and modifying it through the non-const iterators (\ref begin, \ref end), it
is your responsibility to bring the container back into a sorted state before any other methods
are called on it. This can be achieved by calling this method immediately after finishing the
sort key manipulation.
*/
template <class DataType>
void QCPDataContainer<DataType>::sort()
{
std::sort(begin(), end(), qcpLessThanSortKey<DataType>);
}
/*!
Frees all unused memory that is currently in the preallocation and postallocation pools.
Note that QCPDataContainer automatically decides whether squeezing is necessary, if \ref
setAutoSqueeze is left enabled. It should thus not be necessary to use this method for typical
applications.
The parameters \a preAllocation and \a postAllocation control whether pre- and/or post allocation
should be freed, respectively.
*/
template <class DataType>
void QCPDataContainer<DataType>::squeeze(bool preAllocation, bool postAllocation)
{
if (preAllocation)
{
if (mPreallocSize > 0)
{
std::copy(begin(), end(), mData.begin());
mData.resize(size());
mPreallocSize = 0;
}
mPreallocIteration = 0;
}
if (postAllocation)
mData.squeeze();
}
/*!
Returns an iterator to the data point with a (sort-)key that is equal to, just below, or just
above \a sortKey. If \a expandedRange is true, the data point just below \a sortKey will be
considered, otherwise the one just above.
This can be used in conjunction with \ref findEnd to iterate over data points within a given key
range, including or excluding the bounding data points that are just beyond the specified range.
If \a expandedRange is true but there are no data points below \a sortKey, \ref constBegin is
returned.
If the container is empty, returns \ref constEnd.
\see findEnd, QCPPlottableInterface1D::findBegin
*/
template <class DataType>
typename QCPDataContainer<DataType>::const_iterator QCPDataContainer<DataType>::findBegin(double sortKey, bool expandedRange) const
{
if (isEmpty())
return constEnd();
QCPDataContainer<DataType>::const_iterator it = std::lower_bound(constBegin(), constEnd(), DataType::fromSortKey(sortKey), qcpLessThanSortKey<DataType>);
if (expandedRange && it != constBegin()) // also covers it == constEnd case, and we know --constEnd is valid because mData isn't empty
--it;
return it;
}
/*!
Returns an iterator to the element after the data point with a (sort-)key that is equal to, just
above or just below \a sortKey. If \a expandedRange is true, the data point just above \a sortKey
will be considered, otherwise the one just below.
This can be used in conjunction with \ref findBegin to iterate over data points within a given
key range, including the bounding data points that are just below and above the specified range.
If \a expandedRange is true but there are no data points above \a sortKey, \ref constEnd is
returned.
If the container is empty, \ref constEnd is returned.
\see findBegin, QCPPlottableInterface1D::findEnd
*/
template <class DataType>
typename QCPDataContainer<DataType>::const_iterator QCPDataContainer<DataType>::findEnd(double sortKey, bool expandedRange) const
{
if (isEmpty())
return constEnd();
QCPDataContainer<DataType>::const_iterator it = std::upper_bound(constBegin(), constEnd(), DataType::fromSortKey(sortKey), qcpLessThanSortKey<DataType>);
if (expandedRange && it != constEnd())
++it;
return it;
}
/*!
Returns the range encompassed by the (main-)key coordinate of all data points. The output
parameter \a foundRange indicates whether a sensible range was found. If this is false, you
should not use the returned QCPRange (e.g. the data container is empty or all points have the
same key).
Use \a signDomain to control which sign of the key coordinates should be considered. This is
relevant e.g. for logarithmic plots which can mathematically only display one sign domain at a
time.
If the DataType reports that its main key is equal to the sort key (\a sortKeyIsMainKey), as is
the case for most plottables, this method uses this fact and finds the range very quickly.
\see valueRange
*/
template <class DataType>
QCPRange QCPDataContainer<DataType>::keyRange(bool &foundRange, QCP::SignDomain signDomain)
{
if (isEmpty())
{
foundRange = false;
return QCPRange();
}
QCPRange range;
bool haveLower = false;
bool haveUpper = false;
double current;
QCPDataContainer<DataType>::const_iterator it = constBegin();
QCPDataContainer<DataType>::const_iterator itEnd = constEnd();
if (signDomain == QCP::sdBoth) // range may be anywhere
{
if (DataType::sortKeyIsMainKey()) // if DataType is sorted by main key (e.g. QCPGraph, but not QCPCurve), use faster algorithm by finding just first and last key with non-NaN value
{
while (it != itEnd) // find first non-nan going up from left
{
if (!qIsNaN(it->mainValue()))
{
range.lower = it->mainKey();
haveLower = true;
break;
}
++it;
}
it = itEnd;
while (it != constBegin()) // find first non-nan going down from right
{
--it;
if (!qIsNaN(it->mainValue()))
{
range.upper = it->mainKey();
haveUpper = true;
break;
}
}
} else // DataType is not sorted by main key, go through all data points and accordingly expand range
{
while (it != itEnd)
{
if (!qIsNaN(it->mainValue()))
{
current = it->mainKey();
if (current < range.lower || !haveLower)
{
range.lower = current;
haveLower = true;
}
if (current > range.upper || !haveUpper)
{
range.upper = current;
haveUpper = true;
}
}
++it;
}
}
} else if (signDomain == QCP::sdNegative) // range may only be in the negative sign domain
{
while (it != itEnd)
{
if (!qIsNaN(it->mainValue()))
{
current = it->mainKey();
if ((current < range.lower || !haveLower) && current < 0)
{
range.lower = current;
haveLower = true;
}
if ((current > range.upper || !haveUpper) && current < 0)
{
range.upper = current;
haveUpper = true;
}
}
++it;
}
} else if (signDomain == QCP::sdPositive) // range may only be in the positive sign domain
{
while (it != itEnd)
{
if (!qIsNaN(it->mainValue()))
{
current = it->mainKey();
if ((current < range.lower || !haveLower) && current > 0)
{
range.lower = current;
haveLower = true;
}
if ((current > range.upper || !haveUpper) && current > 0)
{
range.upper = current;
haveUpper = true;
}
}
++it;
}
}
foundRange = haveLower && haveUpper;
return range;
}
/*!
Returns the range encompassed by the value coordinates of the data points in the specified key
range (\a inKeyRange), using the full \a DataType::valueRange reported by the data points. The
output parameter \a foundRange indicates whether a sensible range was found. If this is false,
you should not use the returned QCPRange (e.g. the data container is empty or all points have the
same value).
Inf and -Inf data values are ignored.
If \a inKeyRange has both lower and upper bound set to zero (is equal to <tt>QCPRange()</tt>),
all data points are considered, without any restriction on the keys.
Use \a signDomain to control which sign of the value coordinates should be considered. This is
relevant e.g. for logarithmic plots which can mathematically only display one sign domain at a
time.
\see keyRange
*/
template <class DataType>
QCPRange QCPDataContainer<DataType>::valueRange(bool &foundRange, QCP::SignDomain signDomain, const QCPRange &inKeyRange)
{
if (isEmpty())
{
foundRange = false;
return QCPRange();
}
QCPRange range;
const bool restrictKeyRange = inKeyRange != QCPRange();
bool haveLower = false;
bool haveUpper = false;
QCPRange current;
QCPDataContainer<DataType>::const_iterator itBegin = constBegin();
QCPDataContainer<DataType>::const_iterator itEnd = constEnd();
if (DataType::sortKeyIsMainKey() && restrictKeyRange)
{
itBegin = findBegin(inKeyRange.lower, false);
itEnd = findEnd(inKeyRange.upper, false);
}
if (signDomain == QCP::sdBoth) // range may be anywhere
{
for (QCPDataContainer<DataType>::const_iterator it = itBegin; it != itEnd; ++it)
{
if (restrictKeyRange && (it->mainKey() < inKeyRange.lower || it->mainKey() > inKeyRange.upper))
continue;
current = it->valueRange();
if ((current.lower < range.lower || !haveLower) && !qIsNaN(current.lower) && std::isfinite(current.lower))
{
range.lower = current.lower;
haveLower = true;
}
if ((current.upper > range.upper || !haveUpper) && !qIsNaN(current.upper) && std::isfinite(current.upper))
{
range.upper = current.upper;
haveUpper = true;
}
}
} else if (signDomain == QCP::sdNegative) // range may only be in the negative sign domain
{
for (QCPDataContainer<DataType>::const_iterator it = itBegin; it != itEnd; ++it)
{
if (restrictKeyRange && (it->mainKey() < inKeyRange.lower || it->mainKey() > inKeyRange.upper))
continue;
current = it->valueRange();
if ((current.lower < range.lower || !haveLower) && current.lower < 0 && !qIsNaN(current.lower) && std::isfinite(current.lower))
{
range.lower = current.lower;
haveLower = true;
}
if ((current.upper > range.upper || !haveUpper) && current.upper < 0 && !qIsNaN(current.upper) && std::isfinite(current.upper))
{
range.upper = current.upper;
haveUpper = true;
}
}
} else if (signDomain == QCP::sdPositive) // range may only be in the positive sign domain
{
for (QCPDataContainer<DataType>::const_iterator it = itBegin; it != itEnd; ++it)
{
if (restrictKeyRange && (it->mainKey() < inKeyRange.lower || it->mainKey() > inKeyRange.upper))
continue;
current = it->valueRange();
if ((current.lower < range.lower || !haveLower) && current.lower > 0 && !qIsNaN(current.lower) && std::isfinite(current.lower))
{
range.lower = current.lower;
haveLower = true;
}
if ((current.upper > range.upper || !haveUpper) && current.upper > 0 && !qIsNaN(current.upper) && std::isfinite(current.upper))
{
range.upper = current.upper;
haveUpper = true;
}
}
}
foundRange = haveLower && haveUpper;
return range;
}
/*!
Makes sure \a begin and \a end mark a data range that is both within the bounds of this data
container's data, as well as within the specified \a dataRange. The initial range described by
the passed iterators \a begin and \a end is never expanded, only contracted if necessary.
This function doesn't require for \a dataRange to be within the bounds of this data container's
valid range.
*/
template <class DataType>
void QCPDataContainer<DataType>::limitIteratorsToDataRange(const_iterator &begin, const_iterator &end, const QCPDataRange &dataRange) const
{
QCPDataRange iteratorRange(int(begin-constBegin()), int(end-constBegin()));
iteratorRange = iteratorRange.bounded(dataRange.bounded(this->dataRange()));
begin = constBegin()+iteratorRange.begin();
end = constBegin()+iteratorRange.end();
}
/*! \internal
Increases the preallocation pool to have a size of at least \a minimumPreallocSize. Depending on
the preallocation history, the container will grow by more than requested, to speed up future
consecutive size increases.
if \a minimumPreallocSize is smaller than or equal to the current preallocation pool size, this
method does nothing.
*/
template <class DataType>
void QCPDataContainer<DataType>::preallocateGrow(int minimumPreallocSize)
{
if (minimumPreallocSize <= mPreallocSize)
return;
int newPreallocSize = minimumPreallocSize;
newPreallocSize += (1u<<qBound(4, mPreallocIteration+4, 15)) - 12; // do 4 up to 32768-12 preallocation, doubling in each intermediate iteration
++mPreallocIteration;
int sizeDifference = newPreallocSize-mPreallocSize;
mData.resize(mData.size()+sizeDifference);
std::copy_backward(mData.begin()+mPreallocSize, mData.end()-sizeDifference, mData.end());
mPreallocSize = newPreallocSize;
}
/*! \internal
This method decides, depending on the total allocation size and the size of the unused pre- and
postallocation pools, whether it is sensible to reduce the pools in order to free up unused
memory. It then possibly calls \ref squeeze to do the deallocation.
If \ref setAutoSqueeze is enabled, this method is called automatically each time data points are
removed from the container (e.g. \ref remove).
\note when changing the decision parameters, care must be taken not to cause a back-and-forth
between squeezing and reallocation due to the growth strategy of the internal QVector and \ref
preallocateGrow. The hysteresis between allocation and deallocation should be made high enough
(at the expense of possibly larger unused memory from time to time).
*/
template <class DataType>
void QCPDataContainer<DataType>::performAutoSqueeze()
{
const int totalAlloc = mData.capacity();
const int postAllocSize = totalAlloc-mData.size();
const int usedSize = size();
bool shrinkPostAllocation = false;
bool shrinkPreAllocation = false;
if (totalAlloc > 650000) // if allocation is larger, shrink earlier with respect to total used size
{
shrinkPostAllocation = postAllocSize > usedSize*1.5; // QVector grow strategy is 2^n for static data. Watch out not to oscillate!
shrinkPreAllocation = mPreallocSize*10 > usedSize;
} else if (totalAlloc > 1000) // below 10 MiB raw data be generous with preallocated memory, below 1k points don't even bother
{
shrinkPostAllocation = postAllocSize > usedSize*5;
shrinkPreAllocation = mPreallocSize > usedSize*1.5; // preallocation can grow into postallocation, so can be smaller
}
if (shrinkPreAllocation || shrinkPostAllocation)
squeeze(shrinkPreAllocation, shrinkPostAllocation);
}
/* end of 'src/datacontainer.h' */
/* including file 'src/plottable.h' */
/* modified 2022-11-06T12:45:56, size 8461 */
class QCP_LIB_DECL QCPSelectionDecorator
{
Q_GADGET
public:
QCPSelectionDecorator();
virtual ~QCPSelectionDecorator();
// getters:
QPen pen() const { return mPen; }
QBrush brush() const { return mBrush; }
QCPScatterStyle scatterStyle() const { return mScatterStyle; }
QCPScatterStyle::ScatterProperties usedScatterProperties() const { return mUsedScatterProperties; }
// setters:
void setPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setScatterStyle(const QCPScatterStyle &scatterStyle, QCPScatterStyle::ScatterProperties usedProperties=QCPScatterStyle::spPen);
void setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties);
// non-virtual methods:
void applyPen(QCPPainter *painter) const;
void applyBrush(QCPPainter *painter) const;
QCPScatterStyle getFinalScatterStyle(const QCPScatterStyle &unselectedStyle) const;
// introduced virtual methods:
virtual void copyFrom(const QCPSelectionDecorator *other);
virtual void drawDecoration(QCPPainter *painter, QCPDataSelection selection);
protected:
// property members:
QPen mPen;
QBrush mBrush;
QCPScatterStyle mScatterStyle;
QCPScatterStyle::ScatterProperties mUsedScatterProperties;
// non-property members:
QCPAbstractPlottable *mPlottable;
// introduced virtual methods:
virtual bool registerWithPlottable(QCPAbstractPlottable *plottable);
private:
Q_DISABLE_COPY(QCPSelectionDecorator)
friend class QCPAbstractPlottable;
};
Q_DECLARE_METATYPE(QCPSelectionDecorator*)
class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(bool antialiasedFill READ antialiasedFill WRITE setAntialiasedFill)
Q_PROPERTY(bool antialiasedScatters READ antialiasedScatters WRITE setAntialiasedScatters)
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QBrush brush READ brush WRITE setBrush)
Q_PROPERTY(QCPAxis* keyAxis READ keyAxis WRITE setKeyAxis)
Q_PROPERTY(QCPAxis* valueAxis READ valueAxis WRITE setValueAxis)
Q_PROPERTY(QCP::SelectionType selectable READ selectable WRITE setSelectable NOTIFY selectableChanged)
Q_PROPERTY(QCPDataSelection selection READ selection WRITE setSelection NOTIFY selectionChanged)
Q_PROPERTY(QCPSelectionDecorator* selectionDecorator READ selectionDecorator WRITE setSelectionDecorator)
/// \endcond
public:
QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis);
virtual ~QCPAbstractPlottable() Q_DECL_OVERRIDE;
// getters:
QString name() const { return mName; }
bool antialiasedFill() const { return mAntialiasedFill; }
bool antialiasedScatters() const { return mAntialiasedScatters; }
QPen pen() const { return mPen; }
QBrush brush() const { return mBrush; }
QCPAxis *keyAxis() const { return mKeyAxis.data(); }
QCPAxis *valueAxis() const { return mValueAxis.data(); }
QCP::SelectionType selectable() const { return mSelectable; }
bool selected() const { return !mSelection.isEmpty(); }
QCPDataSelection selection() const { return mSelection; }
QCPSelectionDecorator *selectionDecorator() const { return mSelectionDecorator; }
// setters:
void setName(const QString &name);
void setAntialiasedFill(bool enabled);
void setAntialiasedScatters(bool enabled);
void setPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setKeyAxis(QCPAxis *axis);
void setValueAxis(QCPAxis *axis);
Q_SLOT void setSelectable(QCP::SelectionType selectable);
Q_SLOT void setSelection(QCPDataSelection selection);
void setSelectionDecorator(QCPSelectionDecorator *decorator);
// introduced virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE = 0; // actually introduced in QCPLayerable as non-pure, but we want to force reimplementation for plottables
virtual QCPPlottableInterface1D *interface1D() { return nullptr; }
virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const = 0;
virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const = 0;
// non-property methods:
void coordsToPixels(double key, double value, double &x, double &y) const;
const QPointF coordsToPixels(double key, double value) const;
void pixelsToCoords(double x, double y, double &key, double &value) const;
void pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const;
void rescaleAxes(bool onlyEnlarge=false) const;
void rescaleKeyAxis(bool onlyEnlarge=false) const;
void rescaleValueAxis(bool onlyEnlarge=false, bool inKeyRange=false) const;
bool addToLegend(QCPLegend *legend);
bool addToLegend();
bool removeFromLegend(QCPLegend *legend) const;
bool removeFromLegend() const;
signals:
void selectionChanged(bool selected);
void selectionChanged(const QCPDataSelection &selection);
void selectableChanged(QCP::SelectionType selectable);
protected:
// property members:
QString mName;
bool mAntialiasedFill, mAntialiasedScatters;
QPen mPen;
QBrush mBrush;
QPointer<QCPAxis> mKeyAxis, mValueAxis;
QCP::SelectionType mSelectable;
QCPDataSelection mSelection;
QCPSelectionDecorator *mSelectionDecorator;
// reimplemented virtual methods:
virtual QRect clipRect() const Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE = 0;
virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE;
void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE;
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE;
virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE;
// introduced virtual methods:
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const = 0;
// non-virtual methods:
void applyFillAntialiasingHint(QCPPainter *painter) const;
void applyScattersAntialiasingHint(QCPPainter *painter) const;
private:
Q_DISABLE_COPY(QCPAbstractPlottable)
friend class QCustomPlot;
friend class QCPAxis;
friend class QCPPlottableLegendItem;
};
/* end of 'src/plottable.h' */
/* including file 'src/item.h' */
/* modified 2022-11-06T12:45:56, size 9425 */
class QCP_LIB_DECL QCPItemAnchor
{
Q_GADGET
public:
QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId=-1);
virtual ~QCPItemAnchor();
// getters:
QString name() const { return mName; }
virtual QPointF pixelPosition() const;
protected:
// property members:
QString mName;
// non-property members:
QCustomPlot *mParentPlot;
QCPAbstractItem *mParentItem;
int mAnchorId;
QSet<QCPItemPosition*> mChildrenX, mChildrenY;
// introduced virtual methods:
virtual QCPItemPosition *toQCPItemPosition() { return nullptr; }
// non-virtual methods:
void addChildX(QCPItemPosition* pos); // called from pos when this anchor is set as parent
void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted
void addChildY(QCPItemPosition* pos); // called from pos when this anchor is set as parent
void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted
private:
Q_DISABLE_COPY(QCPItemAnchor)
friend class QCPItemPosition;
};
class QCP_LIB_DECL QCPItemPosition : public QCPItemAnchor
{
Q_GADGET
public:
/*!
Defines the ways an item position can be specified. Thus it defines what the numbers passed to
\ref setCoords actually mean.
\see setType
*/
enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget.
,ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top
///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and
///< vertically at the top of the viewport/widget, etc.
,ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top
///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and
///< vertically at the top of the axis rect, etc. You can also go beyond the axis rect by providing negative coordinates or coordinates larger than 1.
,ptPlotCoords ///< Dynamic positioning at a plot coordinate defined by two axes (see \ref setAxes).
};
Q_ENUMS(PositionType)
QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name);
virtual ~QCPItemPosition() Q_DECL_OVERRIDE;
// getters:
PositionType type() const { return typeX(); }
PositionType typeX() const { return mPositionTypeX; }
PositionType typeY() const { return mPositionTypeY; }
QCPItemAnchor *parentAnchor() const { return parentAnchorX(); }
QCPItemAnchor *parentAnchorX() const { return mParentAnchorX; }
QCPItemAnchor *parentAnchorY() const { return mParentAnchorY; }
double key() const { return mKey; }
double value() const { return mValue; }
QPointF coords() const { return QPointF(mKey, mValue); }
QCPAxis *keyAxis() const { return mKeyAxis.data(); }
QCPAxis *valueAxis() const { return mValueAxis.data(); }
QCPAxisRect *axisRect() const;
virtual QPointF pixelPosition() const Q_DECL_OVERRIDE;
// setters:
void setType(PositionType type);
void setTypeX(PositionType type);
void setTypeY(PositionType type);
bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false);
bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false);
bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false);
void setCoords(double key, double value);
void setCoords(const QPointF &pos);
void setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis);
void setAxisRect(QCPAxisRect *axisRect);
void setPixelPosition(const QPointF &pixelPosition);
protected:
// property members:
PositionType mPositionTypeX, mPositionTypeY;
QPointer<QCPAxis> mKeyAxis, mValueAxis;
QPointer<QCPAxisRect> mAxisRect;
double mKey, mValue;
QCPItemAnchor *mParentAnchorX, *mParentAnchorY;
// reimplemented virtual methods:
virtual QCPItemPosition *toQCPItemPosition() Q_DECL_OVERRIDE { return this; }
private:
Q_DISABLE_COPY(QCPItemPosition)
};
Q_DECLARE_METATYPE(QCPItemPosition::PositionType)
class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect)
Q_PROPERTY(QCPAxisRect* clipAxisRect READ clipAxisRect WRITE setClipAxisRect)
Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged)
Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged)
/// \endcond
public:
explicit QCPAbstractItem(QCustomPlot *parentPlot);
virtual ~QCPAbstractItem() Q_DECL_OVERRIDE;
// getters:
bool clipToAxisRect() const { return mClipToAxisRect; }
QCPAxisRect *clipAxisRect() const;
bool selectable() const { return mSelectable; }
bool selected() const { return mSelected; }
// setters:
void setClipToAxisRect(bool clip);
void setClipAxisRect(QCPAxisRect *rect);
Q_SLOT void setSelectable(bool selectable);
Q_SLOT void setSelected(bool selected);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE = 0;
// non-virtual methods:
QList<QCPItemPosition*> positions() const { return mPositions; }
QList<QCPItemAnchor*> anchors() const { return mAnchors; }
QCPItemPosition *position(const QString &name) const;
QCPItemAnchor *anchor(const QString &name) const;
bool hasAnchor(const QString &name) const;
signals:
void selectionChanged(bool selected);
void selectableChanged(bool selectable);
protected:
// property members:
bool mClipToAxisRect;
QPointer<QCPAxisRect> mClipAxisRect;
QList<QCPItemPosition*> mPositions;
QList<QCPItemAnchor*> mAnchors;
bool mSelectable, mSelected;
// reimplemented virtual methods:
virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE;
virtual QRect clipRect() const Q_DECL_OVERRIDE;
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE = 0;
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE;
virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE;
// introduced virtual methods:
virtual QPointF anchorPixelPosition(int anchorId) const;
// non-virtual methods:
double rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const;
QCPItemPosition *createPosition(const QString &name);
QCPItemAnchor *createAnchor(const QString &name, int anchorId);
private:
Q_DISABLE_COPY(QCPAbstractItem)
friend class QCustomPlot;
friend class QCPItemAnchor;
};
/* end of 'src/item.h' */
/* including file 'src/core.h' */
/* modified 2022-11-06T12:45:56, size 19304 */
class QCP_LIB_DECL QCustomPlot : public QWidget
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QRect viewport READ viewport WRITE setViewport)
Q_PROPERTY(QPixmap background READ background WRITE setBackground)
Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled)
Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode)
Q_PROPERTY(QCPLayoutGrid* plotLayout READ plotLayout)
Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend)
Q_PROPERTY(int selectionTolerance READ selectionTolerance WRITE setSelectionTolerance)
Q_PROPERTY(bool noAntialiasingOnDrag READ noAntialiasingOnDrag WRITE setNoAntialiasingOnDrag)
Q_PROPERTY(Qt::KeyboardModifier multiSelectModifier READ multiSelectModifier WRITE setMultiSelectModifier)
Q_PROPERTY(bool openGl READ openGl WRITE setOpenGl)
/// \endcond
public:
/*!
Defines how a layer should be inserted relative to an other layer.
\see addLayer, moveLayer
*/
enum LayerInsertMode { limBelow ///< Layer is inserted below other layer
,limAbove ///< Layer is inserted above other layer
};
Q_ENUMS(LayerInsertMode)
/*!
Defines with what timing the QCustomPlot surface is refreshed after a replot.
\see replot
*/
enum RefreshPriority { rpImmediateRefresh ///< Replots immediately and repaints the widget immediately by calling QWidget::repaint() after the replot
,rpQueuedRefresh ///< Replots immediately, but queues the widget repaint, by calling QWidget::update() after the replot. This way multiple redundant widget repaints can be avoided.
,rpRefreshHint ///< Whether to use immediate or queued refresh depends on whether the plotting hint \ref QCP::phImmediateRefresh is set, see \ref setPlottingHints.
,rpQueuedReplot ///< Queues the entire replot for the next event loop iteration. This way multiple redundant replots can be avoided. The actual replot is then done with \ref rpRefreshHint priority.
};
Q_ENUMS(RefreshPriority)
explicit QCustomPlot(QWidget *parent = nullptr);
virtual ~QCustomPlot() Q_DECL_OVERRIDE;
// getters:
QRect viewport() const { return mViewport; }
double bufferDevicePixelRatio() const { return mBufferDevicePixelRatio; }
QPixmap background() const { return mBackgroundPixmap; }
bool backgroundScaled() const { return mBackgroundScaled; }
Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; }
QCPLayoutGrid *plotLayout() const { return mPlotLayout; }
QCP::AntialiasedElements antialiasedElements() const { return mAntialiasedElements; }
QCP::AntialiasedElements notAntialiasedElements() const { return mNotAntialiasedElements; }
bool autoAddPlottableToLegend() const { return mAutoAddPlottableToLegend; }
const QCP::Interactions interactions() const { return mInteractions; }
int selectionTolerance() const { return mSelectionTolerance; }
bool noAntialiasingOnDrag() const { return mNoAntialiasingOnDrag; }
QCP::PlottingHints plottingHints() const { return mPlottingHints; }
Qt::KeyboardModifier multiSelectModifier() const { return mMultiSelectModifier; }
QCP::SelectionRectMode selectionRectMode() const { return mSelectionRectMode; }
QCPSelectionRect *selectionRect() const { return mSelectionRect; }
bool openGl() const { return mOpenGl; }
// setters:
void setViewport(const QRect &rect);
void setBufferDevicePixelRatio(double ratio);
void setBackground(const QPixmap &pm);
void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding);
void setBackground(const QBrush &brush);
void setBackgroundScaled(bool scaled);
void setBackgroundScaledMode(Qt::AspectRatioMode mode);
void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements);
void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled=true);
void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements);
void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled=true);
void setAutoAddPlottableToLegend(bool on);
void setInteractions(const QCP::Interactions &interactions);
void setInteraction(const QCP::Interaction &interaction, bool enabled=true);
void setSelectionTolerance(int pixels);
void setNoAntialiasingOnDrag(bool enabled);
void setPlottingHints(const QCP::PlottingHints &hints);
void setPlottingHint(QCP::PlottingHint hint, bool enabled=true);
void setMultiSelectModifier(Qt::KeyboardModifier modifier);
void setSelectionRectMode(QCP::SelectionRectMode mode);
void setSelectionRect(QCPSelectionRect *selectionRect);
void setOpenGl(bool enabled, int multisampling=16);
// non-property methods:
// plottable interface:
QCPAbstractPlottable *plottable(int index);
QCPAbstractPlottable *plottable();
bool removePlottable(QCPAbstractPlottable *plottable);
bool removePlottable(int index);
int clearPlottables();
int plottableCount() const;
QList<QCPAbstractPlottable*> selectedPlottables() const;
template<class PlottableType>
PlottableType *plottableAt(const QPointF &pos, bool onlySelectable=false, int *dataIndex=nullptr) const;
QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable=false, int *dataIndex=nullptr) const;
bool hasPlottable(QCPAbstractPlottable *plottable) const;
// specialized interface for QCPGraph:
QCPGraph *graph(int index) const;
QCPGraph *graph() const;
QCPGraph *addGraph(QCPAxis *keyAxis=nullptr, QCPAxis *valueAxis=nullptr);
bool removeGraph(QCPGraph *graph);
bool removeGraph(int index);
int clearGraphs();
int graphCount() const;
QList<QCPGraph*> selectedGraphs() const;
// item interface:
QCPAbstractItem *item(int index) const;
QCPAbstractItem *item() const;
bool removeItem(QCPAbstractItem *item);
bool removeItem(int index);
int clearItems();
int itemCount() const;
QList<QCPAbstractItem*> selectedItems() const;
template<class ItemType>
ItemType *itemAt(const QPointF &pos, bool onlySelectable=false) const;
QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable=false) const;
bool hasItem(QCPAbstractItem *item) const;
// layer interface:
QCPLayer *layer(const QString &name) const;
QCPLayer *layer(int index) const;
QCPLayer *currentLayer() const;
bool setCurrentLayer(const QString &name);
bool setCurrentLayer(QCPLayer *layer);
int layerCount() const;
bool addLayer(const QString &name, QCPLayer *otherLayer=nullptr, LayerInsertMode insertMode=limAbove);
bool removeLayer(QCPLayer *layer);
bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode=limAbove);
// axis rect/layout interface:
int axisRectCount() const;
QCPAxisRect* axisRect(int index=0) const;
QList<QCPAxisRect*> axisRects() const;
QCPLayoutElement* layoutElementAt(const QPointF &pos) const;
QCPAxisRect* axisRectAt(const QPointF &pos) const;
Q_SLOT void rescaleAxes(bool onlyVisiblePlottables=false);
QList<QCPAxis*> selectedAxes() const;
QList<QCPLegend*> selectedLegends() const;
Q_SLOT void deselectAll();
bool savePdf(const QString &fileName, int width=0, int height=0, QCP::ExportPen exportPen=QCP::epAllowCosmetic, const QString &pdfCreator=QString(), const QString &pdfTitle=QString());
bool savePng(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1, int resolution=96, QCP::ResolutionUnit resolutionUnit=QCP::ruDotsPerInch);
bool saveJpg(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1, int resolution=96, QCP::ResolutionUnit resolutionUnit=QCP::ruDotsPerInch);
bool saveBmp(const QString &fileName, int width=0, int height=0, double scale=1.0, int resolution=96, QCP::ResolutionUnit resolutionUnit=QCP::ruDotsPerInch);
bool saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality=-1, int resolution=96, QCP::ResolutionUnit resolutionUnit=QCP::ruDotsPerInch);
QPixmap toPixmap(int width=0, int height=0, double scale=1.0);
void toPainter(QCPPainter *painter, int width=0, int height=0);
Q_SLOT void replot(QCustomPlot::RefreshPriority refreshPriority=QCustomPlot::rpRefreshHint);
double replotTime(bool average=false) const;
QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
QCPLegend *legend;
signals:
void mouseDoubleClick(QMouseEvent *event);
void mousePress(QMouseEvent *event);
void mouseMove(QMouseEvent *event);
void mouseRelease(QMouseEvent *event);
void mouseWheel(QWheelEvent *event);
void plottableClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event);
void plottableDoubleClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event);
void itemClick(QCPAbstractItem *item, QMouseEvent *event);
void itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event);
void axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event);
void axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event);
void legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event);
void legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event);
void selectionChangedByUser();
void beforeReplot();
void afterLayout();
void afterReplot();
protected:
// property members:
QRect mViewport;
double mBufferDevicePixelRatio;
QCPLayoutGrid *mPlotLayout;
bool mAutoAddPlottableToLegend;
QList<QCPAbstractPlottable*> mPlottables;
QList<QCPGraph*> mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph
QList<QCPAbstractItem*> mItems;
QList<QCPLayer*> mLayers;
QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements;
QCP::Interactions mInteractions;
int mSelectionTolerance;
bool mNoAntialiasingOnDrag;
QBrush mBackgroundBrush;
QPixmap mBackgroundPixmap;
QPixmap mScaledBackgroundPixmap;
bool mBackgroundScaled;
Qt::AspectRatioMode mBackgroundScaledMode;
QCPLayer *mCurrentLayer;
QCP::PlottingHints mPlottingHints;
Qt::KeyboardModifier mMultiSelectModifier;
QCP::SelectionRectMode mSelectionRectMode;
QCPSelectionRect *mSelectionRect;
bool mOpenGl;
// non-property members:
QList<QSharedPointer<QCPAbstractPaintBuffer> > mPaintBuffers;
QPoint mMousePressPos;
bool mMouseHasMoved;
QPointer<QCPLayerable> mMouseEventLayerable;
QPointer<QCPLayerable> mMouseSignalLayerable;
QVariant mMouseEventLayerableDetails;
QVariant mMouseSignalLayerableDetails;
bool mReplotting;
bool mReplotQueued;
double mReplotTime, mReplotTimeAverage;
int mOpenGlMultisamples;
QCP::AntialiasedElements mOpenGlAntialiasedElementsBackup;
bool mOpenGlCacheLabelsBackup;
#ifdef QCP_OPENGL_FBO
QSharedPointer<QOpenGLContext> mGlContext;
QSharedPointer<QSurface> mGlSurface;
QSharedPointer<QOpenGLPaintDevice> mGlPaintDevice;
#endif
// reimplemented virtual methods:
virtual QSize minimumSizeHint() const Q_DECL_OVERRIDE;
virtual QSize sizeHint() const Q_DECL_OVERRIDE;
virtual void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
virtual void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE;
virtual void mouseDoubleClickEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
virtual void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
virtual void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
virtual void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE;
// introduced virtual methods:
virtual void draw(QCPPainter *painter);
virtual void updateLayout();
virtual void axisRemoved(QCPAxis *axis);
virtual void legendRemoved(QCPLegend *legend);
Q_SLOT virtual void processRectSelection(QRect rect, QMouseEvent *event);
Q_SLOT virtual void processRectZoom(QRect rect, QMouseEvent *event);
Q_SLOT virtual void processPointSelection(QMouseEvent *event);
// non-virtual methods:
bool registerPlottable(QCPAbstractPlottable *plottable);
bool registerGraph(QCPGraph *graph);
bool registerItem(QCPAbstractItem* item);
void updateLayerIndices() const;
QCPLayerable *layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails=nullptr) const;
QList<QCPLayerable*> layerableListAt(const QPointF &pos, bool onlySelectable, QList<QVariant> *selectionDetails=nullptr) const;
void drawBackground(QCPPainter *painter);
void setupPaintBuffers();
QCPAbstractPaintBuffer *createPaintBuffer();
bool hasInvalidatedPaintBuffers();
bool setupOpenGl();
void freeOpenGl();
friend class QCPLegend;
friend class QCPAxis;
friend class QCPLayer;
friend class QCPAxisRect;
friend class QCPAbstractPlottable;
friend class QCPGraph;
friend class QCPAbstractItem;
};
Q_DECLARE_METATYPE(QCustomPlot::LayerInsertMode)
Q_DECLARE_METATYPE(QCustomPlot::RefreshPriority)
// implementation of template functions:
/*!
Returns the plottable at the pixel position \a pos. The plottable type (a QCPAbstractPlottable
subclass) that shall be taken into consideration can be specified via the template parameter.
Plottables that only consist of single lines (like graphs) have a tolerance band around them, see
\ref setSelectionTolerance. If multiple plottables come into consideration, the one closest to \a
pos is returned.
If \a onlySelectable is true, only plottables that are selectable
(QCPAbstractPlottable::setSelectable) are considered.
if \a dataIndex is non-null, it is set to the index of the plottable's data point that is closest
to \a pos.
If there is no plottable of the specified type at \a pos, returns \c nullptr.
\see itemAt, layoutElementAt
*/
template<class PlottableType>
PlottableType *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable, int *dataIndex) const
{
PlottableType *resultPlottable = 0;
QVariant resultDetails;
double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value
foreach (QCPAbstractPlottable *plottable, mPlottables)
{
PlottableType *currentPlottable = qobject_cast<PlottableType*>(plottable);
if (!currentPlottable || (onlySelectable && !currentPlottable->selectable())) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractPlottable::selectable
continue;
if (currentPlottable->clipRect().contains(pos.toPoint())) // only consider clicks where the plottable is actually visible
{
QVariant details;
double currentDistance = currentPlottable->selectTest(pos, false, dataIndex ? &details : nullptr);
if (currentDistance >= 0 && currentDistance < resultDistance)
{
resultPlottable = currentPlottable;
resultDetails = details;
resultDistance = currentDistance;
}
}
}
if (resultPlottable && dataIndex)
{
QCPDataSelection sel = resultDetails.value<QCPDataSelection>();
if (!sel.isEmpty())
*dataIndex = sel.dataRange(0).begin();
}
return resultPlottable;
}
/*!
Returns the item at the pixel position \a pos. The item type (a QCPAbstractItem subclass) that shall be
taken into consideration can be specified via the template parameter. Items that only consist of single
lines (e.g. \ref QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref
setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is returned.
If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are
considered.
If there is no item at \a pos, returns \c nullptr.
\see plottableAt, layoutElementAt
*/
template<class ItemType>
ItemType *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const
{
ItemType *resultItem = 0;
double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value
foreach (QCPAbstractItem *item, mItems)
{
ItemType *currentItem = qobject_cast<ItemType*>(item);
if (!currentItem || (onlySelectable && !currentItem->selectable())) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable
continue;
if (!currentItem->clipToAxisRect() || currentItem->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it
{
double currentDistance = currentItem->selectTest(pos, false);
if (currentDistance >= 0 && currentDistance < resultDistance)
{
resultItem = currentItem;
resultDistance = currentDistance;
}
}
}
return resultItem;
}
/* end of 'src/core.h' */
/* including file 'src/plottable1d.h' */
/* modified 2022-11-06T12:45:56, size 25638 */
class QCPPlottableInterface1D
{
public:
virtual ~QCPPlottableInterface1D() = default;
// introduced pure virtual methods:
virtual int dataCount() const = 0;
virtual double dataMainKey(int index) const = 0;
virtual double dataSortKey(int index) const = 0;
virtual double dataMainValue(int index) const = 0;
virtual QCPRange dataValueRange(int index) const = 0;
virtual QPointF dataPixelPosition(int index) const = 0;
virtual bool sortKeyIsMainKey() const = 0;
virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const = 0;
virtual int findBegin(double sortKey, bool expandedRange=true) const = 0;
virtual int findEnd(double sortKey, bool expandedRange=true) const = 0;
};
template <class DataType>
class QCPAbstractPlottable1D : public QCPAbstractPlottable, public QCPPlottableInterface1D // no QCP_LIB_DECL, template class ends up in header (cpp included below)
{
// No Q_OBJECT macro due to template class
public:
QCPAbstractPlottable1D(QCPAxis *keyAxis, QCPAxis *valueAxis);
virtual ~QCPAbstractPlottable1D() Q_DECL_OVERRIDE;
// virtual methods of 1d plottable interface:
virtual int dataCount() const Q_DECL_OVERRIDE;
virtual double dataMainKey(int index) const Q_DECL_OVERRIDE;
virtual double dataSortKey(int index) const Q_DECL_OVERRIDE;
virtual double dataMainValue(int index) const Q_DECL_OVERRIDE;
virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE;
virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE;
virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE;
virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE;
virtual int findBegin(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE;
virtual int findEnd(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE;
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
virtual QCPPlottableInterface1D *interface1D() Q_DECL_OVERRIDE { return this; }
protected:
// property members:
QSharedPointer<QCPDataContainer<DataType> > mDataContainer;
// helpers for subclasses:
void getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const;
void drawPolyline(QCPPainter *painter, const QVector<QPointF> &lineData) const;
private:
Q_DISABLE_COPY(QCPAbstractPlottable1D)
};
// include implementation in header since it is a class template:
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPlottableInterface1D
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPlottableInterface1D
\brief Defines an abstract interface for one-dimensional plottables
This class contains only pure virtual methods which define a common interface to the data
of one-dimensional plottables.
For example, it is implemented by the template class \ref QCPAbstractPlottable1D (the preferred
base class for one-dimensional plottables). So if you use that template class as base class of
your one-dimensional plottable, you won't have to care about implementing the 1d interface
yourself.
If your plottable doesn't derive from \ref QCPAbstractPlottable1D but still wants to provide a 1d
interface (e.g. like \ref QCPErrorBars does), you should inherit from both \ref
QCPAbstractPlottable and \ref QCPPlottableInterface1D and accordingly reimplement the pure
virtual methods of the 1d interface, matching your data container. Also, reimplement \ref
QCPAbstractPlottable::interface1D to return the \c this pointer.
If you have a \ref QCPAbstractPlottable pointer, you can check whether it implements this
interface by calling \ref QCPAbstractPlottable::interface1D and testing it for a non-zero return
value. If it indeed implements this interface, you may use it to access the plottable's data
without needing to know the exact type of the plottable or its data point type.
*/
/* start documentation of pure virtual functions */
/*! \fn virtual int QCPPlottableInterface1D::dataCount() const = 0;
Returns the number of data points of the plottable.
*/
/*! \fn virtual QCPDataSelection QCPPlottableInterface1D::selectTestRect(const QRectF &rect, bool onlySelectable) const = 0;
Returns a data selection containing all the data points of this plottable which are contained (or
hit by) \a rect. This is used mainly in the selection rect interaction for data selection (\ref
dataselection "data selection mechanism").
If \a onlySelectable is true, an empty QCPDataSelection is returned if this plottable is not
selectable (i.e. if \ref QCPAbstractPlottable::setSelectable is \ref QCP::stNone).
\note \a rect must be a normalized rect (positive or zero width and height). This is especially
important when using the rect of \ref QCPSelectionRect::accepted, which is not necessarily
normalized. Use <tt>QRect::normalized()</tt> when passing a rect which might not be normalized.
*/
/*! \fn virtual double QCPPlottableInterface1D::dataMainKey(int index) const = 0
Returns the main key of the data point at the given \a index.
What the main key is, is defined by the plottable's data type. See the \ref
qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming
convention.
*/
/*! \fn virtual double QCPPlottableInterface1D::dataSortKey(int index) const = 0
Returns the sort key of the data point at the given \a index.
What the sort key is, is defined by the plottable's data type. See the \ref
qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming
convention.
*/
/*! \fn virtual double QCPPlottableInterface1D::dataMainValue(int index) const = 0
Returns the main value of the data point at the given \a index.
What the main value is, is defined by the plottable's data type. See the \ref
qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming
convention.
*/
/*! \fn virtual QCPRange QCPPlottableInterface1D::dataValueRange(int index) const = 0
Returns the value range of the data point at the given \a index.
What the value range is, is defined by the plottable's data type. See the \ref
qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming
convention.
*/
/*! \fn virtual QPointF QCPPlottableInterface1D::dataPixelPosition(int index) const = 0
Returns the pixel position on the widget surface at which the data point at the given \a index
appears.
Usually this corresponds to the point of \ref dataMainKey/\ref dataMainValue, in pixel
coordinates. However, depending on the plottable, this might be a different apparent position
than just a coord-to-pixel transform of those values. For example, \ref QCPBars apparent data
values can be shifted depending on their stacking, bar grouping or configured base value.
*/
/*! \fn virtual bool QCPPlottableInterface1D::sortKeyIsMainKey() const = 0
Returns whether the sort key (\ref dataSortKey) is identical to the main key (\ref dataMainKey).
What the sort and main keys are, is defined by the plottable's data type. See the \ref
qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming
convention.
*/
/*! \fn virtual int QCPPlottableInterface1D::findBegin(double sortKey, bool expandedRange) const = 0
Returns the index of the data point with a (sort-)key that is equal to, just below, or just above
\a sortKey. If \a expandedRange is true, the data point just below \a sortKey will be considered,
otherwise the one just above.
This can be used in conjunction with \ref findEnd to iterate over data points within a given key
range, including or excluding the bounding data points that are just beyond the specified range.
If \a expandedRange is true but there are no data points below \a sortKey, 0 is returned.
If the container is empty, returns 0 (in that case, \ref findEnd will also return 0, so a loop
using these methods will not iterate over the index 0).
\see findEnd, QCPDataContainer::findBegin
*/
/*! \fn virtual int QCPPlottableInterface1D::findEnd(double sortKey, bool expandedRange) const = 0
Returns the index one after the data point with a (sort-)key that is equal to, just above, or
just below \a sortKey. If \a expandedRange is true, the data point just above \a sortKey will be
considered, otherwise the one just below.
This can be used in conjunction with \ref findBegin to iterate over data points within a given
key range, including the bounding data points that are just below and above the specified range.
If \a expandedRange is true but there are no data points above \a sortKey, the index just above the
highest data point is returned.
If the container is empty, returns 0.
\see findBegin, QCPDataContainer::findEnd
*/
/* end documentation of pure virtual functions */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAbstractPlottable1D
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAbstractPlottable1D
\brief A template base class for plottables with one-dimensional data
This template class derives from \ref QCPAbstractPlottable and from the abstract interface \ref
QCPPlottableInterface1D. It serves as a base class for all one-dimensional data (i.e. data with
one key dimension), such as \ref QCPGraph and QCPCurve.
The template parameter \a DataType is the type of the data points of this plottable (e.g. \ref
QCPGraphData or \ref QCPCurveData). The main purpose of this base class is to provide the member
\a mDataContainer (a shared pointer to a \ref QCPDataContainer "QCPDataContainer<DataType>") and
implement the according virtual methods of the \ref QCPPlottableInterface1D, such that most
subclassed plottables don't need to worry about this anymore.
Further, it provides a convenience method for retrieving selected/unselected data segments via
\ref getDataSegments. This is useful when subclasses implement their \ref draw method and need to
draw selected segments with a different pen/brush than unselected segments (also see \ref
QCPSelectionDecorator).
This class implements basic functionality of \ref QCPAbstractPlottable::selectTest and \ref
QCPPlottableInterface1D::selectTestRect, assuming point-like data points, based on the 1D data
interface. In spite of that, most plottable subclasses will want to reimplement those methods
again, to provide a more accurate hit test based on their specific data visualization geometry.
*/
/* start documentation of inline functions */
/*! \fn QCPPlottableInterface1D *QCPAbstractPlottable1D::interface1D()
Returns a \ref QCPPlottableInterface1D pointer to this plottable, providing access to its 1D
interface.
\seebaseclassmethod
*/
/* end documentation of inline functions */
/*!
Forwards \a keyAxis and \a valueAxis to the \ref QCPAbstractPlottable::QCPAbstractPlottable
"QCPAbstractPlottable" constructor and allocates the \a mDataContainer.
*/
template <class DataType>
QCPAbstractPlottable1D<DataType>::QCPAbstractPlottable1D(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable(keyAxis, valueAxis),
mDataContainer(new QCPDataContainer<DataType>)
{
}
template <class DataType>
QCPAbstractPlottable1D<DataType>::~QCPAbstractPlottable1D()
{
}
/*!
\copydoc QCPPlottableInterface1D::dataCount
*/
template <class DataType>
int QCPAbstractPlottable1D<DataType>::dataCount() const
{
return mDataContainer->size();
}
/*!
\copydoc QCPPlottableInterface1D::dataMainKey
*/
template <class DataType>
double QCPAbstractPlottable1D<DataType>::dataMainKey(int index) const
{
if (index >= 0 && index < mDataContainer->size())
{
return (mDataContainer->constBegin()+index)->mainKey();
} else
{
qDebug() << Q_FUNC_INFO << "Index out of bounds" << index;
return 0;
}
}
/*!
\copydoc QCPPlottableInterface1D::dataSortKey
*/
template <class DataType>
double QCPAbstractPlottable1D<DataType>::dataSortKey(int index) const
{
if (index >= 0 && index < mDataContainer->size())
{
return (mDataContainer->constBegin()+index)->sortKey();
} else
{
qDebug() << Q_FUNC_INFO << "Index out of bounds" << index;
return 0;
}
}
/*!
\copydoc QCPPlottableInterface1D::dataMainValue
*/
template <class DataType>
double QCPAbstractPlottable1D<DataType>::dataMainValue(int index) const
{
if (index >= 0 && index < mDataContainer->size())
{
return (mDataContainer->constBegin()+index)->mainValue();
} else
{
qDebug() << Q_FUNC_INFO << "Index out of bounds" << index;
return 0;
}
}
/*!
\copydoc QCPPlottableInterface1D::dataValueRange
*/
template <class DataType>
QCPRange QCPAbstractPlottable1D<DataType>::dataValueRange(int index) const
{
if (index >= 0 && index < mDataContainer->size())
{
return (mDataContainer->constBegin()+index)->valueRange();
} else
{
qDebug() << Q_FUNC_INFO << "Index out of bounds" << index;
return QCPRange(0, 0);
}
}
/*!
\copydoc QCPPlottableInterface1D::dataPixelPosition
*/
template <class DataType>
QPointF QCPAbstractPlottable1D<DataType>::dataPixelPosition(int index) const
{
if (index >= 0 && index < mDataContainer->size())
{
const typename QCPDataContainer<DataType>::const_iterator it = mDataContainer->constBegin()+index;
return coordsToPixels(it->mainKey(), it->mainValue());
} else
{
qDebug() << Q_FUNC_INFO << "Index out of bounds" << index;
return QPointF();
}
}
/*!
\copydoc QCPPlottableInterface1D::sortKeyIsMainKey
*/
template <class DataType>
bool QCPAbstractPlottable1D<DataType>::sortKeyIsMainKey() const
{
return DataType::sortKeyIsMainKey();
}
/*!
Implements a rect-selection algorithm assuming the data (accessed via the 1D data interface) is
point-like. Most subclasses will want to reimplement this method again, to provide a more
accurate hit test based on the true data visualization geometry.
\seebaseclassmethod
*/
template <class DataType>
QCPDataSelection QCPAbstractPlottable1D<DataType>::selectTestRect(const QRectF &rect, bool onlySelectable) const
{
QCPDataSelection result;
if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
return result;
if (!mKeyAxis || !mValueAxis)
return result;
// convert rect given in pixels to ranges given in plot coordinates:
double key1, value1, key2, value2;
pixelsToCoords(rect.topLeft(), key1, value1);
pixelsToCoords(rect.bottomRight(), key2, value2);
QCPRange keyRange(key1, key2); // QCPRange normalizes internally so we don't have to care about whether key1 < key2
QCPRange valueRange(value1, value2);
typename QCPDataContainer<DataType>::const_iterator begin = mDataContainer->constBegin();
typename QCPDataContainer<DataType>::const_iterator end = mDataContainer->constEnd();
if (DataType::sortKeyIsMainKey()) // we can assume that data is sorted by main key, so can reduce the searched key interval:
{
begin = mDataContainer->findBegin(keyRange.lower, false);
end = mDataContainer->findEnd(keyRange.upper, false);
}
if (begin == end)
return result;
int currentSegmentBegin = -1; // -1 means we're currently not in a segment that's contained in rect
for (typename QCPDataContainer<DataType>::const_iterator it=begin; it!=end; ++it)
{
if (currentSegmentBegin == -1)
{
if (valueRange.contains(it->mainValue()) && keyRange.contains(it->mainKey())) // start segment
currentSegmentBegin = int(it-mDataContainer->constBegin());
} else if (!valueRange.contains(it->mainValue()) || !keyRange.contains(it->mainKey())) // segment just ended
{
result.addDataRange(QCPDataRange(currentSegmentBegin, int(it-mDataContainer->constBegin())), false);
currentSegmentBegin = -1;
}
}
// process potential last segment:
if (currentSegmentBegin != -1)
result.addDataRange(QCPDataRange(currentSegmentBegin, int(end-mDataContainer->constBegin())), false);
result.simplify();
return result;
}
/*!
\copydoc QCPPlottableInterface1D::findBegin
*/
template <class DataType>
int QCPAbstractPlottable1D<DataType>::findBegin(double sortKey, bool expandedRange) const
{
return int(mDataContainer->findBegin(sortKey, expandedRange)-mDataContainer->constBegin());
}
/*!
\copydoc QCPPlottableInterface1D::findEnd
*/
template <class DataType>
int QCPAbstractPlottable1D<DataType>::findEnd(double sortKey, bool expandedRange) const
{
return int(mDataContainer->findEnd(sortKey, expandedRange)-mDataContainer->constBegin());
}
/*!
Implements a point-selection algorithm assuming the data (accessed via the 1D data interface) is
point-like. Most subclasses will want to reimplement this method again, to provide a more
accurate hit test based on the true data visualization geometry.
If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point
to \a pos.
\seebaseclassmethod
*/
template <class DataType>
double QCPAbstractPlottable1D<DataType>::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
return -1;
if (!mKeyAxis || !mValueAxis)
return -1;
QCPDataSelection selectionResult;
double minDistSqr = (std::numeric_limits<double>::max)();
int minDistIndex = mDataContainer->size();
typename QCPDataContainer<DataType>::const_iterator begin = mDataContainer->constBegin();
typename QCPDataContainer<DataType>::const_iterator end = mDataContainer->constEnd();
if (DataType::sortKeyIsMainKey()) // we can assume that data is sorted by main key, so can reduce the searched key interval:
{
// determine which key range comes into question, taking selection tolerance around pos into account:
double posKeyMin, posKeyMax, dummy;
pixelsToCoords(pos-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
pixelsToCoords(pos+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
if (posKeyMin > posKeyMax)
qSwap(posKeyMin, posKeyMax);
begin = mDataContainer->findBegin(posKeyMin, true);
end = mDataContainer->findEnd(posKeyMax, true);
}
if (begin == end)
return -1;
QCPRange keyRange(mKeyAxis->range());
QCPRange valueRange(mValueAxis->range());
for (typename QCPDataContainer<DataType>::const_iterator it=begin; it!=end; ++it)
{
const double mainKey = it->mainKey();
const double mainValue = it->mainValue();
if (keyRange.contains(mainKey) && valueRange.contains(mainValue)) // make sure data point is inside visible range, for speedup in cases where sort key isn't main key and we iterate over all points
{
const double currentDistSqr = QCPVector2D(coordsToPixels(mainKey, mainValue)-pos).lengthSquared();
if (currentDistSqr < minDistSqr)
{
minDistSqr = currentDistSqr;
minDistIndex = int(it-mDataContainer->constBegin());
}
}
}
if (minDistIndex != mDataContainer->size())
selectionResult.addDataRange(QCPDataRange(minDistIndex, minDistIndex+1), false);
selectionResult.simplify();
if (details)
details->setValue(selectionResult);
return qSqrt(minDistSqr);
}
/*!
Splits all data into selected and unselected segments and outputs them via \a selectedSegments
and \a unselectedSegments, respectively.
This is useful when subclasses implement their \ref draw method and need to draw selected
segments with a different pen/brush than unselected segments (also see \ref
QCPSelectionDecorator).
\see setSelection
*/
template <class DataType>
void QCPAbstractPlottable1D<DataType>::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
{
selectedSegments.clear();
unselectedSegments.clear();
if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
{
if (selected())
selectedSegments << QCPDataRange(0, dataCount());
else
unselectedSegments << QCPDataRange(0, dataCount());
} else
{
QCPDataSelection sel(selection());
sel.simplify();
selectedSegments = sel.dataRanges();
unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
}
}
/*!
A helper method which draws a line with the passed \a painter, according to the pixel data in \a
lineData. NaN points create gaps in the line, as expected from QCustomPlot's plottables (this is
the main difference to QPainter's regular drawPolyline, which handles NaNs by lagging or
crashing).
Further it uses a faster line drawing technique based on \ref QCPPainter::drawLine rather than \c
QPainter::drawPolyline if the configured \ref QCustomPlot::setPlottingHints() and \a painter
style allows.
*/
template <class DataType>
void QCPAbstractPlottable1D<DataType>::drawPolyline(QCPPainter *painter, const QVector<QPointF> &lineData) const
{
// if drawing lines in plot (instead of PDF), reduce 1px lines to cosmetic, because at least in
// Qt6 drawing of "1px" width lines is much slower even though it has same appearance apart from
// High-DPI. In High-DPI cases people must set a pen width slightly larger than 1.0 to get
// correct DPI scaling of width, but of course with performance penalty.
if (!painter->modes().testFlag(QCPPainter::pmVectorized) &&
qFuzzyCompare(painter->pen().widthF(), 1.0))
{
QPen newPen = painter->pen();
newPen.setWidth(0);
painter->setPen(newPen);
}
// if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
painter->pen().style() == Qt::SolidLine &&
!painter->modes().testFlag(QCPPainter::pmVectorized) &&
!painter->modes().testFlag(QCPPainter::pmNoCaching))
{
int i = 0;
bool lastIsNan = false;
const int lineDataSize = static_cast<int>(lineData.size());
while (i < lineDataSize && (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()))) // make sure first point is not NaN
++i;
++i; // because drawing works in 1 point retrospect
while (i < lineDataSize)
{
if (!qIsNaN(lineData.at(i).y()) && !qIsNaN(lineData.at(i).x())) // NaNs create a gap in the line
{
if (!lastIsNan)
painter->drawLine(lineData.at(i-1), lineData.at(i));
else
lastIsNan = false;
} else
lastIsNan = true;
++i;
}
} else
{
int segmentStart = 0;
int i = 0;
const int lineDataSize = static_cast<int>(lineData.size());
while (i < lineDataSize)
{
if (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()) || qIsInf(lineData.at(i).y())) // NaNs create a gap in the line. Also filter Infs which make drawPolyline block
{
painter->drawPolyline(lineData.constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point
segmentStart = i+1;
}
++i;
}
// draw last segment:
painter->drawPolyline(lineData.constData()+segmentStart, lineDataSize-segmentStart);
}
}
/* end of 'src/plottable1d.h' */
/* including file 'src/colorgradient.h' */
/* modified 2022-11-06T12:45:56, size 7262 */
class QCP_LIB_DECL QCPColorGradient
{
Q_GADGET
public:
/*!
Defines the color spaces in which color interpolation between gradient stops can be performed.
\see setColorInterpolation
*/
enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated
,ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance)
};
Q_ENUMS(ColorInterpolation)
/*!
Defines how NaN data points shall appear in the plot.
\see setNanHandling, setNanColor
*/
enum NanHandling { nhNone ///< NaN data points are not explicitly handled and shouldn't occur in the data (this gives slight performance improvement)
,nhLowestColor ///< NaN data points appear as the lowest color defined in this QCPColorGradient
,nhHighestColor ///< NaN data points appear as the highest color defined in this QCPColorGradient
,nhTransparent ///< NaN data points appear transparent
,nhNanColor ///< NaN data points appear as the color defined with \ref setNanColor
};
Q_ENUMS(NanHandling)
/*!
Defines the available presets that can be loaded with \ref loadPreset. See the documentation
there for an image of the presets.
*/
enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation)
,gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation)
,gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation)
,gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation)
,gpCandy ///< Blue over pink to white
,gpGeography ///< Colors suitable to represent different elevations on geographical maps
,gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates)
,gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white
,gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values
,gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates)
,gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates)
,gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic)
};
Q_ENUMS(GradientPreset)
QCPColorGradient();
QCPColorGradient(GradientPreset preset);
bool operator==(const QCPColorGradient &other) const;
bool operator!=(const QCPColorGradient &other) const { return !(*this == other); }
// getters:
int levelCount() const { return mLevelCount; }
QMap<double, QColor> colorStops() const { return mColorStops; }
ColorInterpolation colorInterpolation() const { return mColorInterpolation; }
NanHandling nanHandling() const { return mNanHandling; }
QColor nanColor() const { return mNanColor; }
bool periodic() const { return mPeriodic; }
// setters:
void setLevelCount(int n);
void setColorStops(const QMap<double, QColor> &colorStops);
void setColorStopAt(double position, const QColor &color);
void setColorInterpolation(ColorInterpolation interpolation);
void setNanHandling(NanHandling handling);
void setNanColor(const QColor &color);
void setPeriodic(bool enabled);
// non-property methods:
void colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor=1, bool logarithmic=false);
void colorize(const double *data, const unsigned char *alpha, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor=1, bool logarithmic=false);
QRgb color(double position, const QCPRange &range, bool logarithmic=false);
void loadPreset(GradientPreset preset);
void clearColorStops();
QCPColorGradient inverted() const;
protected:
// property members:
int mLevelCount;
QMap<double, QColor> mColorStops;
ColorInterpolation mColorInterpolation;
NanHandling mNanHandling;
QColor mNanColor;
bool mPeriodic;
// non-property members:
QVector<QRgb> mColorBuffer; // have colors premultiplied with alpha (for usage with QImage::Format_ARGB32_Premultiplied)
bool mColorBufferInvalidated;
// non-virtual methods:
bool stopsUseAlpha() const;
void updateColorBuffer();
};
Q_DECLARE_METATYPE(QCPColorGradient::ColorInterpolation)
Q_DECLARE_METATYPE(QCPColorGradient::NanHandling)
Q_DECLARE_METATYPE(QCPColorGradient::GradientPreset)
/* end of 'src/colorgradient.h' */
/* including file 'src/selectiondecorator-bracket.h' */
/* modified 2022-11-06T12:45:56, size 4458 */
class QCP_LIB_DECL QCPSelectionDecoratorBracket : public QCPSelectionDecorator
{
Q_GADGET
public:
/*!
Defines which shape is drawn at the boundaries of selected data ranges.
Some of the bracket styles further allow specifying a height and/or width, see \ref
setBracketHeight and \ref setBracketWidth.
*/
enum BracketStyle { bsSquareBracket ///< A square bracket is drawn.
,bsHalfEllipse ///< A half ellipse is drawn. The size of the ellipse is given by the bracket width/height properties.
,bsEllipse ///< An ellipse is drawn. The size of the ellipse is given by the bracket width/height properties.
,bsPlus ///< A plus is drawn.
,bsUserStyle ///< Start custom bracket styles at this index when subclassing and reimplementing \ref drawBracket.
};
Q_ENUMS(BracketStyle)
QCPSelectionDecoratorBracket();
virtual ~QCPSelectionDecoratorBracket() Q_DECL_OVERRIDE;
// getters:
QPen bracketPen() const { return mBracketPen; }
QBrush bracketBrush() const { return mBracketBrush; }
int bracketWidth() const { return mBracketWidth; }
int bracketHeight() const { return mBracketHeight; }
BracketStyle bracketStyle() const { return mBracketStyle; }
bool tangentToData() const { return mTangentToData; }
int tangentAverage() const { return mTangentAverage; }
// setters:
void setBracketPen(const QPen &pen);
void setBracketBrush(const QBrush &brush);
void setBracketWidth(int width);
void setBracketHeight(int height);
void setBracketStyle(BracketStyle style);
void setTangentToData(bool enabled);
void setTangentAverage(int pointCount);
// introduced virtual methods:
virtual void drawBracket(QCPPainter *painter, int direction) const;
// virtual methods:
virtual void drawDecoration(QCPPainter *painter, QCPDataSelection selection) Q_DECL_OVERRIDE;
protected:
// property members:
QPen mBracketPen;
QBrush mBracketBrush;
int mBracketWidth;
int mBracketHeight;
BracketStyle mBracketStyle;
bool mTangentToData;
int mTangentAverage;
// non-virtual methods:
double getTangentAngle(const QCPPlottableInterface1D *interface1d, int dataIndex, int direction) const;
QPointF getPixelCoordinates(const QCPPlottableInterface1D *interface1d, int dataIndex) const;
};
Q_DECLARE_METATYPE(QCPSelectionDecoratorBracket::BracketStyle)
/* end of 'src/selectiondecorator-bracket.h' */
/* including file 'src/layoutelements/layoutelement-axisrect.h' */
/* modified 2022-11-06T12:45:56, size 7529 */
class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPixmap background READ background WRITE setBackground)
Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled)
Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode)
Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag)
Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom)
/// \endcond
public:
explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes=true);
virtual ~QCPAxisRect() Q_DECL_OVERRIDE;
// getters:
QPixmap background() const { return mBackgroundPixmap; }
QBrush backgroundBrush() const { return mBackgroundBrush; }
bool backgroundScaled() const { return mBackgroundScaled; }
Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; }
Qt::Orientations rangeDrag() const { return mRangeDrag; }
Qt::Orientations rangeZoom() const { return mRangeZoom; }
QCPAxis *rangeDragAxis(Qt::Orientation orientation);
QCPAxis *rangeZoomAxis(Qt::Orientation orientation);
QList<QCPAxis*> rangeDragAxes(Qt::Orientation orientation);
QList<QCPAxis*> rangeZoomAxes(Qt::Orientation orientation);
double rangeZoomFactor(Qt::Orientation orientation);
// setters:
void setBackground(const QPixmap &pm);
void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding);
void setBackground(const QBrush &brush);
void setBackgroundScaled(bool scaled);
void setBackgroundScaledMode(Qt::AspectRatioMode mode);
void setRangeDrag(Qt::Orientations orientations);
void setRangeZoom(Qt::Orientations orientations);
void setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical);
void setRangeDragAxes(QList<QCPAxis*> axes);
void setRangeDragAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical);
void setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical);
void setRangeZoomAxes(QList<QCPAxis*> axes);
void setRangeZoomAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical);
void setRangeZoomFactor(double horizontalFactor, double verticalFactor);
void setRangeZoomFactor(double factor);
// non-property methods:
int axisCount(QCPAxis::AxisType type) const;
QCPAxis *axis(QCPAxis::AxisType type, int index=0) const;
QList<QCPAxis*> axes(QCPAxis::AxisTypes types) const;
QList<QCPAxis*> axes() const;
QCPAxis *addAxis(QCPAxis::AxisType type, QCPAxis *axis=nullptr);
QList<QCPAxis*> addAxes(QCPAxis::AxisTypes types);
bool removeAxis(QCPAxis *axis);
QCPLayoutInset *insetLayout() const { return mInsetLayout; }
void zoom(const QRectF &pixelRect);
void zoom(const QRectF &pixelRect, const QList<QCPAxis*> &affectedAxes);
void setupFullAxesBox(bool connectRanges=false);
QList<QCPAbstractPlottable*> plottables() const;
QList<QCPGraph*> graphs() const;
QList<QCPAbstractItem*> items() const;
// read-only interface imitating a QRect:
int left() const { return mRect.left(); }
int right() const { return mRect.right(); }
int top() const { return mRect.top(); }
int bottom() const { return mRect.bottom(); }
int width() const { return mRect.width(); }
int height() const { return mRect.height(); }
QSize size() const { return mRect.size(); }
QPoint topLeft() const { return mRect.topLeft(); }
QPoint topRight() const { return mRect.topRight(); }
QPoint bottomLeft() const { return mRect.bottomLeft(); }
QPoint bottomRight() const { return mRect.bottomRight(); }
QPoint center() const { return mRect.center(); }
// reimplemented virtual methods:
virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE;
virtual QList<QCPLayoutElement*> elements(bool recursive) const Q_DECL_OVERRIDE;
protected:
// property members:
QBrush mBackgroundBrush;
QPixmap mBackgroundPixmap;
QPixmap mScaledBackgroundPixmap;
bool mBackgroundScaled;
Qt::AspectRatioMode mBackgroundScaledMode;
QCPLayoutInset *mInsetLayout;
Qt::Orientations mRangeDrag, mRangeZoom;
QList<QPointer<QCPAxis> > mRangeDragHorzAxis, mRangeDragVertAxis;
QList<QPointer<QCPAxis> > mRangeZoomHorzAxis, mRangeZoomVertAxis;
double mRangeZoomFactorHorz, mRangeZoomFactorVert;
// non-property members:
QList<QCPRange> mDragStartHorzRange, mDragStartVertRange;
QCP::AntialiasedElements mAADragBackup, mNotAADragBackup;
bool mDragging;
QHash<QCPAxis::AxisType, QList<QCPAxis*> > mAxes;
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual int calculateAutoMargin(QCP::MarginSide side) Q_DECL_OVERRIDE;
virtual void layoutChanged() Q_DECL_OVERRIDE;
// events:
virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE;
virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE;
virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE;
virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE;
// non-property methods:
void drawBackground(QCPPainter *painter);
void updateAxesOffset(QCPAxis::AxisType type);
private:
Q_DISABLE_COPY(QCPAxisRect)
friend class QCustomPlot;
};
/* end of 'src/layoutelements/layoutelement-axisrect.h' */
/* including file 'src/layoutelements/layoutelement-legend.h' */
/* modified 2022-11-06T12:45:56, size 10425 */
class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QCPLegend* parentLegend READ parentLegend)
Q_PROPERTY(QFont font READ font WRITE setFont)
Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor)
Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont)
Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor)
Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged)
Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged)
/// \endcond
public:
explicit QCPAbstractLegendItem(QCPLegend *parent);
// getters:
QCPLegend *parentLegend() const { return mParentLegend; }
QFont font() const { return mFont; }
QColor textColor() const { return mTextColor; }
QFont selectedFont() const { return mSelectedFont; }
QColor selectedTextColor() const { return mSelectedTextColor; }
bool selectable() const { return mSelectable; }
bool selected() const { return mSelected; }
// setters:
void setFont(const QFont &font);
void setTextColor(const QColor &color);
void setSelectedFont(const QFont &font);
void setSelectedTextColor(const QColor &color);
Q_SLOT void setSelectable(bool selectable);
Q_SLOT void setSelected(bool selected);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
signals:
void selectionChanged(bool selected);
void selectableChanged(bool selectable);
protected:
// property members:
QCPLegend *mParentLegend;
QFont mFont;
QColor mTextColor;
QFont mSelectedFont;
QColor mSelectedTextColor;
bool mSelectable, mSelected;
// reimplemented virtual methods:
virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE;
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE;
virtual QRect clipRect() const Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE = 0;
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE;
virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE;
private:
Q_DISABLE_COPY(QCPAbstractLegendItem)
friend class QCPLegend;
};
class QCP_LIB_DECL QCPPlottableLegendItem : public QCPAbstractLegendItem
{
Q_OBJECT
public:
QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable);
// getters:
QCPAbstractPlottable *plottable() { return mPlottable; }
protected:
// property members:
QCPAbstractPlottable *mPlottable;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE;
// non-virtual methods:
QPen getIconBorderPen() const;
QColor getTextColor() const;
QFont getFont() const;
};
class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen)
Q_PROPERTY(QBrush brush READ brush WRITE setBrush)
Q_PROPERTY(QFont font READ font WRITE setFont)
Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor)
Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize)
Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding)
Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen)
Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged)
Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged)
Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen)
Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen)
Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush)
Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont)
Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor)
/// \endcond
public:
/*!
Defines the selectable parts of a legend
\see setSelectedParts, setSelectableParts
*/
enum SelectablePart { spNone = 0x000 ///< <tt>0x000</tt> None
,spLegendBox = 0x001 ///< <tt>0x001</tt> The legend box (frame)
,spItems = 0x002 ///< <tt>0x002</tt> Legend items individually (see \ref selectedItems)
};
Q_ENUMS(SelectablePart)
Q_FLAGS(SelectableParts)
Q_DECLARE_FLAGS(SelectableParts, SelectablePart)
explicit QCPLegend();
virtual ~QCPLegend() Q_DECL_OVERRIDE;
// getters:
QPen borderPen() const { return mBorderPen; }
QBrush brush() const { return mBrush; }
QFont font() const { return mFont; }
QColor textColor() const { return mTextColor; }
QSize iconSize() const { return mIconSize; }
int iconTextPadding() const { return mIconTextPadding; }
QPen iconBorderPen() const { return mIconBorderPen; }
SelectableParts selectableParts() const { return mSelectableParts; }
SelectableParts selectedParts() const;
QPen selectedBorderPen() const { return mSelectedBorderPen; }
QPen selectedIconBorderPen() const { return mSelectedIconBorderPen; }
QBrush selectedBrush() const { return mSelectedBrush; }
QFont selectedFont() const { return mSelectedFont; }
QColor selectedTextColor() const { return mSelectedTextColor; }
// setters:
void setBorderPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setFont(const QFont &font);
void setTextColor(const QColor &color);
void setIconSize(const QSize &size);
void setIconSize(int width, int height);
void setIconTextPadding(int padding);
void setIconBorderPen(const QPen &pen);
Q_SLOT void setSelectableParts(const SelectableParts &selectableParts);
Q_SLOT void setSelectedParts(const SelectableParts &selectedParts);
void setSelectedBorderPen(const QPen &pen);
void setSelectedIconBorderPen(const QPen &pen);
void setSelectedBrush(const QBrush &brush);
void setSelectedFont(const QFont &font);
void setSelectedTextColor(const QColor &color);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
// non-virtual methods:
QCPAbstractLegendItem *item(int index) const;
QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const;
int itemCount() const;
bool hasItem(QCPAbstractLegendItem *item) const;
bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const;
bool addItem(QCPAbstractLegendItem *item);
bool removeItem(int index);
bool removeItem(QCPAbstractLegendItem *item);
void clearItems();
QList<QCPAbstractLegendItem*> selectedItems() const;
signals:
void selectionChanged(QCPLegend::SelectableParts parts);
void selectableChanged(QCPLegend::SelectableParts parts);
protected:
// property members:
QPen mBorderPen, mIconBorderPen;
QBrush mBrush;
QFont mFont;
QColor mTextColor;
QSize mIconSize;
int mIconTextPadding;
SelectableParts mSelectedParts, mSelectableParts;
QPen mSelectedBorderPen, mSelectedIconBorderPen;
QBrush mSelectedBrush;
QFont mSelectedFont;
QColor mSelectedTextColor;
// reimplemented virtual methods:
virtual void parentPlotInitialized(QCustomPlot *parentPlot) Q_DECL_OVERRIDE;
virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE;
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE;
virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE;
// non-virtual methods:
QPen getBorderPen() const;
QBrush getBrush() const;
private:
Q_DISABLE_COPY(QCPLegend)
friend class QCustomPlot;
friend class QCPAbstractLegendItem;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts)
Q_DECLARE_METATYPE(QCPLegend::SelectablePart)
/* end of 'src/layoutelements/layoutelement-legend.h' */
/* including file 'src/layoutelements/layoutelement-textelement.h' */
/* modified 2022-11-06T12:45:56, size 5359 */
class QCP_LIB_DECL QCPTextElement : public QCPLayoutElement
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QString text READ text WRITE setText)
Q_PROPERTY(QFont font READ font WRITE setFont)
Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor)
Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont)
Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor)
Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged)
Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged)
/// \endcond
public:
explicit QCPTextElement(QCustomPlot *parentPlot);
QCPTextElement(QCustomPlot *parentPlot, const QString &text);
QCPTextElement(QCustomPlot *parentPlot, const QString &text, double pointSize);
QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QString &fontFamily, double pointSize);
QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QFont &font);
// getters:
QString text() const { return mText; }
int textFlags() const { return mTextFlags; }
QFont font() const { return mFont; }
QColor textColor() const { return mTextColor; }
QFont selectedFont() const { return mSelectedFont; }
QColor selectedTextColor() const { return mSelectedTextColor; }
bool selectable() const { return mSelectable; }
bool selected() const { return mSelected; }
// setters:
void setText(const QString &text);
void setTextFlags(int flags);
void setFont(const QFont &font);
void setTextColor(const QColor &color);
void setSelectedFont(const QFont &font);
void setSelectedTextColor(const QColor &color);
Q_SLOT void setSelectable(bool selectable);
Q_SLOT void setSelected(bool selected);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE;
virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE;
virtual void mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE;
signals:
void selectionChanged(bool selected);
void selectableChanged(bool selectable);
void clicked(QMouseEvent *event);
void doubleClicked(QMouseEvent *event);
protected:
// property members:
QString mText;
int mTextFlags;
QFont mFont;
QColor mTextColor;
QFont mSelectedFont;
QColor mSelectedTextColor;
QRect mTextBoundingRect;
bool mSelectable, mSelected;
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE;
virtual QSize maximumOuterSizeHint() const Q_DECL_OVERRIDE;
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE;
virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE;
// non-virtual methods:
QFont mainFont() const;
QColor mainTextColor() const;
private:
Q_DISABLE_COPY(QCPTextElement)
};
/* end of 'src/layoutelements/layoutelement-textelement.h' */
/* including file 'src/layoutelements/layoutelement-colorscale.h' */
/* modified 2022-11-06T12:45:56, size 5939 */
class QCPColorScaleAxisRectPrivate : public QCPAxisRect
{
Q_OBJECT
public:
explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale);
protected:
QCPColorScale *mParentColorScale;
QImage mGradientImage;
bool mGradientImageInvalidated;
// re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale
using QCPAxisRect::calculateAutoMargin;
using QCPAxisRect::mousePressEvent;
using QCPAxisRect::mouseMoveEvent;
using QCPAxisRect::mouseReleaseEvent;
using QCPAxisRect::wheelEvent;
using QCPAxisRect::update;
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
void updateGradientImage();
Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts);
Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts);
friend class QCPColorScale;
};
class QCP_LIB_DECL QCPColorScale : public QCPLayoutElement
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType)
Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged)
Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged)
Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged)
Q_PROPERTY(QString label READ label WRITE setLabel)
Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth)
Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag)
Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom)
/// \endcond
public:
explicit QCPColorScale(QCustomPlot *parentPlot);
virtual ~QCPColorScale() Q_DECL_OVERRIDE;
// getters:
QCPAxis *axis() const { return mColorAxis.data(); }
QCPAxis::AxisType type() const { return mType; }
QCPRange dataRange() const { return mDataRange; }
QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; }
QCPColorGradient gradient() const { return mGradient; }
QString label() const;
int barWidth () const { return mBarWidth; }
bool rangeDrag() const;
bool rangeZoom() const;
// setters:
void setType(QCPAxis::AxisType type);
Q_SLOT void setDataRange(const QCPRange &dataRange);
Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType);
Q_SLOT void setGradient(const QCPColorGradient &gradient);
void setLabel(const QString &str);
void setBarWidth(int width);
void setRangeDrag(bool enabled);
void setRangeZoom(bool enabled);
// non-property methods:
QList<QCPColorMap*> colorMaps() const;
void rescaleDataRange(bool onlyVisibleMaps);
// reimplemented virtual methods:
virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE;
signals:
void dataRangeChanged(const QCPRange &newRange);
void dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
void gradientChanged(const QCPColorGradient &newGradient);
protected:
// property members:
QCPAxis::AxisType mType;
QCPRange mDataRange;
QCPAxis::ScaleType mDataScaleType;
QCPColorGradient mGradient;
int mBarWidth;
// non-property members:
QPointer<QCPColorScaleAxisRectPrivate> mAxisRect;
QPointer<QCPAxis> mColorAxis;
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE;
// events:
virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE;
virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE;
virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE;
virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE;
private:
Q_DISABLE_COPY(QCPColorScale)
friend class QCPColorScaleAxisRectPrivate;
};
/* end of 'src/layoutelements/layoutelement-colorscale.h' */
/* including file 'src/plottables/plottable-graph.h' */
/* modified 2022-11-06T12:45:56, size 9316 */
class QCP_LIB_DECL QCPGraphData
{
public:
QCPGraphData();
QCPGraphData(double key, double value);
inline double sortKey() const { return key; }
inline static QCPGraphData fromSortKey(double sortKey) { return QCPGraphData(sortKey, 0); }
inline static bool sortKeyIsMainKey() { return true; }
inline double mainKey() const { return key; }
inline double mainValue() const { return value; }
inline QCPRange valueRange() const { return QCPRange(value, value); }
double key, value;
};
Q_DECLARE_TYPEINFO(QCPGraphData, Q_PRIMITIVE_TYPE);
/*! \typedef QCPGraphDataContainer
Container for storing \ref QCPGraphData points. The data is stored sorted by \a key.
This template instantiation is the container in which QCPGraph holds its data. For details about
the generic container, see the documentation of the class template \ref QCPDataContainer.
\see QCPGraphData, QCPGraph::setData
*/
typedef QCPDataContainer<QCPGraphData> QCPGraphDataContainer;
class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable1D<QCPGraphData>
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle)
Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle)
Q_PROPERTY(int scatterSkip READ scatterSkip WRITE setScatterSkip)
Q_PROPERTY(QCPGraph* channelFillGraph READ channelFillGraph WRITE setChannelFillGraph)
Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling)
/// \endcond
public:
/*!
Defines how the graph's line is represented visually in the plot. The line is drawn with the
current pen of the graph (\ref setPen).
\see setLineStyle
*/
enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented
///< with symbols according to the scatter style, see \ref setScatterStyle)
,lsLine ///< data points are connected by a straight line
,lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point
,lsStepRight ///< line is drawn as steps where the step height is the value of the right data point
,lsStepCenter ///< line is drawn as steps where the step is in between two data points
,lsImpulse ///< each data point is represented by a line parallel to the value axis, which reaches from the data point to the zero-value-line
};
Q_ENUMS(LineStyle)
explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis);
virtual ~QCPGraph() Q_DECL_OVERRIDE;
// getters:
QSharedPointer<QCPGraphDataContainer> data() const { return mDataContainer; }
LineStyle lineStyle() const { return mLineStyle; }
QCPScatterStyle scatterStyle() const { return mScatterStyle; }
int scatterSkip() const { return mScatterSkip; }
QCPGraph *channelFillGraph() const { return mChannelFillGraph.data(); }
bool adaptiveSampling() const { return mAdaptiveSampling; }
// setters:
void setData(QSharedPointer<QCPGraphDataContainer> data);
void setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted=false);
void setLineStyle(LineStyle ls);
void setScatterStyle(const QCPScatterStyle &style);
void setScatterSkip(int skip);
void setChannelFillGraph(QCPGraph *targetGraph);
void setAdaptiveSampling(bool enabled);
// non-property methods:
void addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted=false);
void addData(double key, double value);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE;
virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE;
protected:
// property members:
LineStyle mLineStyle;
QCPScatterStyle mScatterStyle;
int mScatterSkip;
QPointer<QCPGraph> mChannelFillGraph;
bool mAdaptiveSampling;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE;
// introduced virtual methods:
virtual void drawFill(QCPPainter *painter, QVector<QPointF> *lines) const;
virtual void drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const;
virtual void drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const;
virtual void drawImpulsePlot(QCPPainter *painter, const QVector<QPointF> &lines) const;
virtual void getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const;
virtual void getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const;
// non-virtual methods:
void getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const;
void getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const;
void getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const;
QVector<QPointF> dataToLines(const QVector<QCPGraphData> &data) const;
QVector<QPointF> dataToStepLeftLines(const QVector<QCPGraphData> &data) const;
QVector<QPointF> dataToStepRightLines(const QVector<QCPGraphData> &data) const;
QVector<QPointF> dataToStepCenterLines(const QVector<QCPGraphData> &data) const;
QVector<QPointF> dataToImpulseLines(const QVector<QCPGraphData> &data) const;
QVector<QCPDataRange> getNonNanSegments(const QVector<QPointF> *lineData, Qt::Orientation keyOrientation) const;
QVector<QPair<QCPDataRange, QCPDataRange> > getOverlappingSegments(QVector<QCPDataRange> thisSegments, const QVector<QPointF> *thisData, QVector<QCPDataRange> otherSegments, const QVector<QPointF> *otherData) const;
bool segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const;
QPointF getFillBasePoint(QPointF matchingDataPoint) const;
const QPolygonF getFillPolygon(const QVector<QPointF> *lineData, QCPDataRange segment) const;
const QPolygonF getChannelFillPolygon(const QVector<QPointF> *thisData, QCPDataRange thisSegment, const QVector<QPointF> *otherData, QCPDataRange otherSegment) const;
int findIndexBelowX(const QVector<QPointF> *data, double x) const;
int findIndexAboveX(const QVector<QPointF> *data, double x) const;
int findIndexBelowY(const QVector<QPointF> *data, double y) const;
int findIndexAboveY(const QVector<QPointF> *data, double y) const;
double pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const;
friend class QCustomPlot;
friend class QCPLegend;
};
Q_DECLARE_METATYPE(QCPGraph::LineStyle)
/* end of 'src/plottables/plottable-graph.h' */
/* including file 'src/plottables/plottable-curve.h' */
/* modified 2022-11-06T12:45:56, size 7434 */
class QCP_LIB_DECL QCPCurveData
{
public:
QCPCurveData();
QCPCurveData(double t, double key, double value);
inline double sortKey() const { return t; }
inline static QCPCurveData fromSortKey(double sortKey) { return QCPCurveData(sortKey, 0, 0); }
inline static bool sortKeyIsMainKey() { return false; }
inline double mainKey() const { return key; }
inline double mainValue() const { return value; }
inline QCPRange valueRange() const { return QCPRange(value, value); }
double t, key, value;
};
Q_DECLARE_TYPEINFO(QCPCurveData, Q_PRIMITIVE_TYPE);
/*! \typedef QCPCurveDataContainer
Container for storing \ref QCPCurveData points. The data is stored sorted by \a t, so the \a
sortKey() (returning \a t) is different from \a mainKey() (returning \a key).
This template instantiation is the container in which QCPCurve holds its data. For details about
the generic container, see the documentation of the class template \ref QCPDataContainer.
\see QCPCurveData, QCPCurve::setData
*/
typedef QCPDataContainer<QCPCurveData> QCPCurveDataContainer;
class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable1D<QCPCurveData>
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle)
Q_PROPERTY(int scatterSkip READ scatterSkip WRITE setScatterSkip)
Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle)
/// \endcond
public:
/*!
Defines how the curve's line is represented visually in the plot. The line is drawn with the
current pen of the curve (\ref setPen).
\see setLineStyle
*/
enum LineStyle { lsNone ///< No line is drawn between data points (e.g. only scatters)
,lsLine ///< Data points are connected with a straight line
};
Q_ENUMS(LineStyle)
explicit QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis);
virtual ~QCPCurve() Q_DECL_OVERRIDE;
// getters:
QSharedPointer<QCPCurveDataContainer> data() const { return mDataContainer; }
QCPScatterStyle scatterStyle() const { return mScatterStyle; }
int scatterSkip() const { return mScatterSkip; }
LineStyle lineStyle() const { return mLineStyle; }
// setters:
void setData(QSharedPointer<QCPCurveDataContainer> data);
void setData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted=false);
void setData(const QVector<double> &keys, const QVector<double> &values);
void setScatterStyle(const QCPScatterStyle &style);
void setScatterSkip(int skip);
void setLineStyle(LineStyle style);
// non-property methods:
void addData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted=false);
void addData(const QVector<double> &keys, const QVector<double> &values);
void addData(double t, double key, double value);
void addData(double key, double value);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE;
virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE;
protected:
// property members:
QCPScatterStyle mScatterStyle;
int mScatterSkip;
LineStyle mLineStyle;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE;
// introduced virtual methods:
virtual void drawCurveLine(QCPPainter *painter, const QVector<QPointF> &lines) const;
virtual void drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &points, const QCPScatterStyle &style) const;
// non-virtual methods:
void getCurveLines(QVector<QPointF> *lines, const QCPDataRange &dataRange, double penWidth) const;
void getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange, double scatterWidth) const;
int getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const;
QPointF getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const;
QVector<QPointF> getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const;
bool mayTraverse(int prevRegion, int currentRegion) const;
bool getTraverse(double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const;
void getTraverseCornerPoints(int prevRegion, int currentRegion, double keyMin, double valueMax, double keyMax, double valueMin, QVector<QPointF> &beforeTraverse, QVector<QPointF> &afterTraverse) const;
double pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer::const_iterator &closestData) const;
friend class QCustomPlot;
friend class QCPLegend;
};
Q_DECLARE_METATYPE(QCPCurve::LineStyle)
/* end of 'src/plottables/plottable-curve.h' */
/* including file 'src/plottables/plottable-bars.h' */
/* modified 2022-11-06T12:45:56, size 8955 */
class QCP_LIB_DECL QCPBarsGroup : public QObject
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType)
Q_PROPERTY(double spacing READ spacing WRITE setSpacing)
/// \endcond
public:
/*!
Defines the ways the spacing between bars in the group can be specified. Thus it defines what
the number passed to \ref setSpacing actually means.
\see setSpacingType, setSpacing
*/
enum SpacingType { stAbsolute ///< Bar spacing is in absolute pixels
,stAxisRectRatio ///< Bar spacing is given by a fraction of the axis rect size
,stPlotCoords ///< Bar spacing is in key coordinates and thus scales with the key axis range
};
Q_ENUMS(SpacingType)
explicit QCPBarsGroup(QCustomPlot *parentPlot);
virtual ~QCPBarsGroup();
// getters:
SpacingType spacingType() const { return mSpacingType; }
double spacing() const { return mSpacing; }
// setters:
void setSpacingType(SpacingType spacingType);
void setSpacing(double spacing);
// non-virtual methods:
QList<QCPBars*> bars() const { return mBars; }
QCPBars* bars(int index) const;
int size() const { return static_cast<int>(mBars.size()); }
bool isEmpty() const { return mBars.isEmpty(); }
void clear();
bool contains(QCPBars *bars) const { return mBars.contains(bars); }
void append(QCPBars *bars);
void insert(int i, QCPBars *bars);
void remove(QCPBars *bars);
protected:
// non-property members:
QCustomPlot *mParentPlot;
SpacingType mSpacingType;
double mSpacing;
QList<QCPBars*> mBars;
// non-virtual methods:
void registerBars(QCPBars *bars);
void unregisterBars(QCPBars *bars);
// virtual methods:
double keyPixelOffset(const QCPBars *bars, double keyCoord);
double getPixelSpacing(const QCPBars *bars, double keyCoord);
private:
Q_DISABLE_COPY(QCPBarsGroup)
friend class QCPBars;
};
Q_DECLARE_METATYPE(QCPBarsGroup::SpacingType)
class QCP_LIB_DECL QCPBarsData
{
public:
QCPBarsData();
QCPBarsData(double key, double value);
inline double sortKey() const { return key; }
inline static QCPBarsData fromSortKey(double sortKey) { return QCPBarsData(sortKey, 0); }
inline static bool sortKeyIsMainKey() { return true; }
inline double mainKey() const { return key; }
inline double mainValue() const { return value; }
inline QCPRange valueRange() const { return QCPRange(value, value); } // note that bar base value isn't held in each QCPBarsData and thus can't/shouldn't be returned here
double key, value;
};
Q_DECLARE_TYPEINFO(QCPBarsData, Q_PRIMITIVE_TYPE);
/*! \typedef QCPBarsDataContainer
Container for storing \ref QCPBarsData points. The data is stored sorted by \a key.
This template instantiation is the container in which QCPBars holds its data. For details about
the generic container, see the documentation of the class template \ref QCPDataContainer.
\see QCPBarsData, QCPBars::setData
*/
typedef QCPDataContainer<QCPBarsData> QCPBarsDataContainer;
class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable1D<QCPBarsData>
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(double width READ width WRITE setWidth)
Q_PROPERTY(WidthType widthType READ widthType WRITE setWidthType)
Q_PROPERTY(QCPBarsGroup* barsGroup READ barsGroup WRITE setBarsGroup)
Q_PROPERTY(double baseValue READ baseValue WRITE setBaseValue)
Q_PROPERTY(double stackingGap READ stackingGap WRITE setStackingGap)
Q_PROPERTY(QCPBars* barBelow READ barBelow)
Q_PROPERTY(QCPBars* barAbove READ barAbove)
/// \endcond
public:
/*!
Defines the ways the width of the bar can be specified. Thus it defines what the number passed
to \ref setWidth actually means.
\see setWidthType, setWidth
*/
enum WidthType { wtAbsolute ///< Bar width is in absolute pixels
,wtAxisRectRatio ///< Bar width is given by a fraction of the axis rect size
,wtPlotCoords ///< Bar width is in key coordinates and thus scales with the key axis range
};
Q_ENUMS(WidthType)
explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis);
virtual ~QCPBars() Q_DECL_OVERRIDE;
// getters:
double width() const { return mWidth; }
WidthType widthType() const { return mWidthType; }
QCPBarsGroup *barsGroup() const { return mBarsGroup; }
double baseValue() const { return mBaseValue; }
double stackingGap() const { return mStackingGap; }
QCPBars *barBelow() const { return mBarBelow.data(); }
QCPBars *barAbove() const { return mBarAbove.data(); }
QSharedPointer<QCPBarsDataContainer> data() const { return mDataContainer; }
// setters:
void setData(QSharedPointer<QCPBarsDataContainer> data);
void setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted=false);
void setWidth(double width);
void setWidthType(WidthType widthType);
void setBarsGroup(QCPBarsGroup *barsGroup);
void setBaseValue(double baseValue);
void setStackingGap(double pixels);
// non-property methods:
void addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted=false);
void addData(double key, double value);
void moveBelow(QCPBars *bars);
void moveAbove(QCPBars *bars);
// reimplemented virtual methods:
virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE;
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE;
virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE;
virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE;
protected:
// property members:
double mWidth;
WidthType mWidthType;
QCPBarsGroup *mBarsGroup;
double mBaseValue;
double mStackingGap;
QPointer<QCPBars> mBarBelow, mBarAbove;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE;
// non-virtual methods:
void getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const;
QRectF getBarRect(double key, double value) const;
void getPixelWidth(double key, double &lower, double &upper) const;
double getStackedBaseValue(double key, bool positive) const;
static void connectBars(QCPBars* lower, QCPBars* upper);
friend class QCustomPlot;
friend class QCPLegend;
friend class QCPBarsGroup;
};
Q_DECLARE_METATYPE(QCPBars::WidthType)
/* end of 'src/plottables/plottable-bars.h' */
/* including file 'src/plottables/plottable-statisticalbox.h' */
/* modified 2022-11-06T12:45:56, size 7522 */
class QCP_LIB_DECL QCPStatisticalBoxData
{
public:
QCPStatisticalBoxData();
QCPStatisticalBoxData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double>& outliers=QVector<double>());
inline double sortKey() const { return key; }
inline static QCPStatisticalBoxData fromSortKey(double sortKey) { return QCPStatisticalBoxData(sortKey, 0, 0, 0, 0, 0); }
inline static bool sortKeyIsMainKey() { return true; }
inline double mainKey() const { return key; }
inline double mainValue() const { return median; }
inline QCPRange valueRange() const
{
QCPRange result(minimum, maximum);
for (QVector<double>::const_iterator it = outliers.constBegin(); it != outliers.constEnd(); ++it)
result.expand(*it);
return result;
}
double key, minimum, lowerQuartile, median, upperQuartile, maximum;
QVector<double> outliers;
};
Q_DECLARE_TYPEINFO(QCPStatisticalBoxData, Q_MOVABLE_TYPE);
/*! \typedef QCPStatisticalBoxDataContainer
Container for storing \ref QCPStatisticalBoxData points. The data is stored sorted by \a key.
This template instantiation is the container in which QCPStatisticalBox holds its data. For
details about the generic container, see the documentation of the class template \ref
QCPDataContainer.
\see QCPStatisticalBoxData, QCPStatisticalBox::setData
*/
typedef QCPDataContainer<QCPStatisticalBoxData> QCPStatisticalBoxDataContainer;
class QCP_LIB_DECL QCPStatisticalBox : public QCPAbstractPlottable1D<QCPStatisticalBoxData>
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(double width READ width WRITE setWidth)
Q_PROPERTY(double whiskerWidth READ whiskerWidth WRITE setWhiskerWidth)
Q_PROPERTY(QPen whiskerPen READ whiskerPen WRITE setWhiskerPen)
Q_PROPERTY(QPen whiskerBarPen READ whiskerBarPen WRITE setWhiskerBarPen)
Q_PROPERTY(bool whiskerAntialiased READ whiskerAntialiased WRITE setWhiskerAntialiased)
Q_PROPERTY(QPen medianPen READ medianPen WRITE setMedianPen)
Q_PROPERTY(QCPScatterStyle outlierStyle READ outlierStyle WRITE setOutlierStyle)
/// \endcond
public:
explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis);
// getters:
QSharedPointer<QCPStatisticalBoxDataContainer> data() const { return mDataContainer; }
double width() const { return mWidth; }
double whiskerWidth() const { return mWhiskerWidth; }
QPen whiskerPen() const { return mWhiskerPen; }
QPen whiskerBarPen() const { return mWhiskerBarPen; }
bool whiskerAntialiased() const { return mWhiskerAntialiased; }
QPen medianPen() const { return mMedianPen; }
QCPScatterStyle outlierStyle() const { return mOutlierStyle; }
// setters:
void setData(QSharedPointer<QCPStatisticalBoxDataContainer> data);
void setData(const QVector<double> &keys, const QVector<double> &minimum, const QVector<double> &lowerQuartile, const QVector<double> &median, const QVector<double> &upperQuartile, const QVector<double> &maximum, bool alreadySorted=false);
void setWidth(double width);
void setWhiskerWidth(double width);
void setWhiskerPen(const QPen &pen);
void setWhiskerBarPen(const QPen &pen);
void setWhiskerAntialiased(bool enabled);
void setMedianPen(const QPen &pen);
void setOutlierStyle(const QCPScatterStyle &style);
// non-property methods:
void addData(const QVector<double> &keys, const QVector<double> &minimum, const QVector<double> &lowerQuartile, const QVector<double> &median, const QVector<double> &upperQuartile, const QVector<double> &maximum, bool alreadySorted=false);
void addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers=QVector<double>());
// reimplemented virtual methods:
virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE;
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE;
virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE;
protected:
// property members:
double mWidth;
double mWhiskerWidth;
QPen mWhiskerPen, mWhiskerBarPen;
bool mWhiskerAntialiased;
QPen mMedianPen;
QCPScatterStyle mOutlierStyle;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE;
// introduced virtual methods:
virtual void drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const;
// non-virtual methods:
void getVisibleDataBounds(QCPStatisticalBoxDataContainer::const_iterator &begin, QCPStatisticalBoxDataContainer::const_iterator &end) const;
QRectF getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const;
QVector<QLineF> getWhiskerBackboneLines(QCPStatisticalBoxDataContainer::const_iterator it) const;
QVector<QLineF> getWhiskerBarLines(QCPStatisticalBoxDataContainer::const_iterator it) const;
friend class QCustomPlot;
friend class QCPLegend;
};
/* end of 'src/plottables/plottable-statisticalbox.h' */
/* including file 'src/plottables/plottable-colormap.h' */
/* modified 2022-11-06T12:45:56, size 7092 */
class QCP_LIB_DECL QCPColorMapData
{
public:
QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange);
~QCPColorMapData();
QCPColorMapData(const QCPColorMapData &other);
QCPColorMapData &operator=(const QCPColorMapData &other);
// getters:
int keySize() const { return mKeySize; }
int valueSize() const { return mValueSize; }
QCPRange keyRange() const { return mKeyRange; }
QCPRange valueRange() const { return mValueRange; }
QCPRange dataBounds() const { return mDataBounds; }
double data(double key, double value);
double cell(int keyIndex, int valueIndex);
unsigned char alpha(int keyIndex, int valueIndex);
// setters:
void setSize(int keySize, int valueSize);
void setKeySize(int keySize);
void setValueSize(int valueSize);
void setRange(const QCPRange &keyRange, const QCPRange &valueRange);
void setKeyRange(const QCPRange &keyRange);
void setValueRange(const QCPRange &valueRange);
void setData(double key, double value, double z);
void setCell(int keyIndex, int valueIndex, double z);
void setAlpha(int keyIndex, int valueIndex, unsigned char alpha);
// non-property methods:
void recalculateDataBounds();
void clear();
void clearAlpha();
void fill(double z);
void fillAlpha(unsigned char alpha);
bool isEmpty() const { return mIsEmpty; }
void coordToCell(double key, double value, int *keyIndex, int *valueIndex) const;
void cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const;
protected:
// property members:
int mKeySize, mValueSize;
QCPRange mKeyRange, mValueRange;
bool mIsEmpty;
// non-property members:
double *mData;
unsigned char *mAlpha;
QCPRange mDataBounds;
bool mDataModified;
bool createAlpha(bool initializeOpaque=true);
friend class QCPColorMap;
};
class QCP_LIB_DECL QCPColorMap : public QCPAbstractPlottable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged)
Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged)
Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged)
Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate)
Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary)
Q_PROPERTY(QCPColorScale* colorScale READ colorScale WRITE setColorScale)
/// \endcond
public:
explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis);
virtual ~QCPColorMap() Q_DECL_OVERRIDE;
// getters:
QCPColorMapData *data() const { return mMapData; }
QCPRange dataRange() const { return mDataRange; }
QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; }
bool interpolate() const { return mInterpolate; }
bool tightBoundary() const { return mTightBoundary; }
QCPColorGradient gradient() const { return mGradient; }
QCPColorScale *colorScale() const { return mColorScale.data(); }
// setters:
void setData(QCPColorMapData *data, bool copy=false);
Q_SLOT void setDataRange(const QCPRange &dataRange);
Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType);
Q_SLOT void setGradient(const QCPColorGradient &gradient);
void setInterpolate(bool enabled);
void setTightBoundary(bool enabled);
void setColorScale(QCPColorScale *colorScale);
// non-property methods:
void rescaleDataRange(bool recalculateDataBounds=false);
Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode=Qt::SmoothTransformation, const QSize &thumbSize=QSize(32, 18));
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE;
virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE;
signals:
void dataRangeChanged(const QCPRange &newRange);
void dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
void gradientChanged(const QCPColorGradient &newGradient);
protected:
// property members:
QCPRange mDataRange;
QCPAxis::ScaleType mDataScaleType;
QCPColorMapData *mMapData;
QCPColorGradient mGradient;
bool mInterpolate;
bool mTightBoundary;
QPointer<QCPColorScale> mColorScale;
// non-property members:
QImage mMapImage, mUndersampledMapImage;
QPixmap mLegendIcon;
bool mMapImageInvalidated;
// introduced virtual methods:
virtual void updateMapImage();
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE;
friend class QCustomPlot;
friend class QCPLegend;
};
/* end of 'src/plottables/plottable-colormap.h' */
/* including file 'src/plottables/plottable-financial.h' */
/* modified 2022-11-06T12:45:56, size 8644 */
class QCP_LIB_DECL QCPFinancialData
{
public:
QCPFinancialData();
QCPFinancialData(double key, double open, double high, double low, double close);
inline double sortKey() const { return key; }
inline static QCPFinancialData fromSortKey(double sortKey) { return QCPFinancialData(sortKey, 0, 0, 0, 0); }
inline static bool sortKeyIsMainKey() { return true; }
inline double mainKey() const { return key; }
inline double mainValue() const { return open; }
inline QCPRange valueRange() const { return QCPRange(low, high); } // open and close must lie between low and high, so we don't need to check them
double key, open, high, low, close;
};
Q_DECLARE_TYPEINFO(QCPFinancialData, Q_PRIMITIVE_TYPE);
/*! \typedef QCPFinancialDataContainer
Container for storing \ref QCPFinancialData points. The data is stored sorted by \a key.
This template instantiation is the container in which QCPFinancial holds its data. For details
about the generic container, see the documentation of the class template \ref QCPDataContainer.
\see QCPFinancialData, QCPFinancial::setData
*/
typedef QCPDataContainer<QCPFinancialData> QCPFinancialDataContainer;
class QCP_LIB_DECL QCPFinancial : public QCPAbstractPlottable1D<QCPFinancialData>
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(ChartStyle chartStyle READ chartStyle WRITE setChartStyle)
Q_PROPERTY(double width READ width WRITE setWidth)
Q_PROPERTY(WidthType widthType READ widthType WRITE setWidthType)
Q_PROPERTY(bool twoColored READ twoColored WRITE setTwoColored)
Q_PROPERTY(QBrush brushPositive READ brushPositive WRITE setBrushPositive)
Q_PROPERTY(QBrush brushNegative READ brushNegative WRITE setBrushNegative)
Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive)
Q_PROPERTY(QPen penNegative READ penNegative WRITE setPenNegative)
/// \endcond
public:
/*!
Defines the ways the width of the financial bar can be specified. Thus it defines what the
number passed to \ref setWidth actually means.
\see setWidthType, setWidth
*/
enum WidthType { wtAbsolute ///< width is in absolute pixels
,wtAxisRectRatio ///< width is given by a fraction of the axis rect size
,wtPlotCoords ///< width is in key coordinates and thus scales with the key axis range
};
Q_ENUMS(WidthType)
/*!
Defines the possible representations of OHLC data in the plot.
\see setChartStyle
*/
enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation
,csCandlestick ///< Candlestick representation
};
Q_ENUMS(ChartStyle)
explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis);
virtual ~QCPFinancial() Q_DECL_OVERRIDE;
// getters:
QSharedPointer<QCPFinancialDataContainer> data() const { return mDataContainer; }
ChartStyle chartStyle() const { return mChartStyle; }
double width() const { return mWidth; }
WidthType widthType() const { return mWidthType; }
bool twoColored() const { return mTwoColored; }
QBrush brushPositive() const { return mBrushPositive; }
QBrush brushNegative() const { return mBrushNegative; }
QPen penPositive() const { return mPenPositive; }
QPen penNegative() const { return mPenNegative; }
// setters:
void setData(QSharedPointer<QCPFinancialDataContainer> data);
void setData(const QVector<double> &keys, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close, bool alreadySorted=false);
void setChartStyle(ChartStyle style);
void setWidth(double width);
void setWidthType(WidthType widthType);
void setTwoColored(bool twoColored);
void setBrushPositive(const QBrush &brush);
void setBrushNegative(const QBrush &brush);
void setPenPositive(const QPen &pen);
void setPenNegative(const QPen &pen);
// non-property methods:
void addData(const QVector<double> &keys, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close, bool alreadySorted=false);
void addData(double key, double open, double high, double low, double close);
// reimplemented virtual methods:
virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE;
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE;
virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE;
// static methods:
static QCPFinancialDataContainer timeSeriesToOhlc(const QVector<double> &time, const QVector<double> &value, double timeBinSize, double timeBinOffset = 0);
protected:
// property members:
ChartStyle mChartStyle;
double mWidth;
WidthType mWidthType;
bool mTwoColored;
QBrush mBrushPositive, mBrushNegative;
QPen mPenPositive, mPenNegative;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE;
// non-virtual methods:
void drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected);
void drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected);
double getPixelWidth(double key, double keyPixel) const;
double ohlcSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const;
double candlestickSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const;
void getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const;
QRectF selectionHitBox(QCPFinancialDataContainer::const_iterator it) const;
friend class QCustomPlot;
friend class QCPLegend;
};
Q_DECLARE_METATYPE(QCPFinancial::ChartStyle)
/* end of 'src/plottables/plottable-financial.h' */
/* including file 'src/plottables/plottable-errorbar.h' */
/* modified 2022-11-06T12:45:56, size 7749 */
class QCP_LIB_DECL QCPErrorBarsData
{
public:
QCPErrorBarsData();
explicit QCPErrorBarsData(double error);
QCPErrorBarsData(double errorMinus, double errorPlus);
double errorMinus, errorPlus;
};
Q_DECLARE_TYPEINFO(QCPErrorBarsData, Q_PRIMITIVE_TYPE);
/*! \typedef QCPErrorBarsDataContainer
Container for storing \ref QCPErrorBarsData points. It is a typedef for
<tt>QVector<QCPErrorBarsData></tt>.
This is the container in which \ref QCPErrorBars holds its data. Unlike most other data
containers for plottables, it is not based on \ref QCPDataContainer. This is because the error
bars plottable is special in that it doesn't store its own key and value coordinate per error
bar. It adopts the key and value from the plottable to which the error bars shall be applied
(\ref QCPErrorBars::setDataPlottable). So the stored \ref QCPErrorBarsData doesn't need a
sortable key, but merely an index (as \c QVector provides), which maps one-to-one to the indices
of the other plottable's data.
\see QCPErrorBarsData, QCPErrorBars::setData
*/
typedef QVector<QCPErrorBarsData> QCPErrorBarsDataContainer;
class QCP_LIB_DECL QCPErrorBars : public QCPAbstractPlottable, public QCPPlottableInterface1D
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QSharedPointer<QCPErrorBarsDataContainer> data READ data WRITE setData)
Q_PROPERTY(QCPAbstractPlottable* dataPlottable READ dataPlottable WRITE setDataPlottable)
Q_PROPERTY(ErrorType errorType READ errorType WRITE setErrorType)
Q_PROPERTY(double whiskerWidth READ whiskerWidth WRITE setWhiskerWidth)
Q_PROPERTY(double symbolGap READ symbolGap WRITE setSymbolGap)
/// \endcond
public:
/*!
Defines in which orientation the error bars shall appear. If your data needs both error
dimensions, create two \ref QCPErrorBars with different \ref ErrorType.
\see setErrorType
*/
enum ErrorType { etKeyError ///< The errors are for the key dimension (bars appear parallel to the key axis)
,etValueError ///< The errors are for the value dimension (bars appear parallel to the value axis)
};
Q_ENUMS(ErrorType)
explicit QCPErrorBars(QCPAxis *keyAxis, QCPAxis *valueAxis);
virtual ~QCPErrorBars() Q_DECL_OVERRIDE;
// getters:
QSharedPointer<QCPErrorBarsDataContainer> data() const { return mDataContainer; }
QCPAbstractPlottable *dataPlottable() const { return mDataPlottable.data(); }
ErrorType errorType() const { return mErrorType; }
double whiskerWidth() const { return mWhiskerWidth; }
double symbolGap() const { return mSymbolGap; }
// setters:
void setData(QSharedPointer<QCPErrorBarsDataContainer> data);
void setData(const QVector<double> &error);
void setData(const QVector<double> &errorMinus, const QVector<double> &errorPlus);
void setDataPlottable(QCPAbstractPlottable* plottable);
void setErrorType(ErrorType type);
void setWhiskerWidth(double pixels);
void setSymbolGap(double pixels);
// non-property methods:
void addData(const QVector<double> &error);
void addData(const QVector<double> &errorMinus, const QVector<double> &errorPlus);
void addData(double error);
void addData(double errorMinus, double errorPlus);
// virtual methods of 1d plottable interface:
virtual int dataCount() const Q_DECL_OVERRIDE;
virtual double dataMainKey(int index) const Q_DECL_OVERRIDE;
virtual double dataSortKey(int index) const Q_DECL_OVERRIDE;
virtual double dataMainValue(int index) const Q_DECL_OVERRIDE;
virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE;
virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE;
virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE;
virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE;
virtual int findBegin(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE;
virtual int findEnd(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE;
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
virtual QCPPlottableInterface1D *interface1D() Q_DECL_OVERRIDE { return this; }
protected:
// property members:
QSharedPointer<QCPErrorBarsDataContainer> mDataContainer;
QPointer<QCPAbstractPlottable> mDataPlottable;
ErrorType mErrorType;
double mWhiskerWidth;
double mSymbolGap;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE;
virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE;
virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE;
// non-virtual methods:
void getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it, QVector<QLineF> &backbones, QVector<QLineF> &whiskers) const;
void getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterator &begin, QCPErrorBarsDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const;
double pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const;
// helpers:
void getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const;
bool errorBarVisible(int index) const;
bool rectIntersectsLine(const QRectF &pixelRect, const QLineF &line) const;
friend class QCustomPlot;
friend class QCPLegend;
};
/* end of 'src/plottables/plottable-errorbar.h' */
/* including file 'src/items/item-straightline.h' */
/* modified 2022-11-06T12:45:56, size 3137 */
class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
/// \endcond
public:
explicit QCPItemStraightLine(QCustomPlot *parentPlot);
virtual ~QCPItemStraightLine() Q_DECL_OVERRIDE;
// getters:
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
// setters;
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
QCPItemPosition * const point1;
QCPItemPosition * const point2;
protected:
// property members:
QPen mPen, mSelectedPen;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
// non-virtual methods:
QLineF getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const;
QPen mainPen() const;
};
/* end of 'src/items/item-straightline.h' */
/* including file 'src/items/item-line.h' */
/* modified 2022-11-06T12:45:56, size 3429 */
class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(QCPLineEnding head READ head WRITE setHead)
Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail)
/// \endcond
public:
explicit QCPItemLine(QCustomPlot *parentPlot);
virtual ~QCPItemLine() Q_DECL_OVERRIDE;
// getters:
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
QCPLineEnding head() const { return mHead; }
QCPLineEnding tail() const { return mTail; }
// setters;
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setHead(const QCPLineEnding &head);
void setTail(const QCPLineEnding &tail);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
QCPItemPosition * const start;
QCPItemPosition * const end;
protected:
// property members:
QPen mPen, mSelectedPen;
QCPLineEnding mHead, mTail;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
// non-virtual methods:
QLineF getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const;
QPen mainPen() const;
};
/* end of 'src/items/item-line.h' */
/* including file 'src/items/item-curve.h' */
/* modified 2022-11-06T12:45:56, size 3401 */
class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(QCPLineEnding head READ head WRITE setHead)
Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail)
/// \endcond
public:
explicit QCPItemCurve(QCustomPlot *parentPlot);
virtual ~QCPItemCurve() Q_DECL_OVERRIDE;
// getters:
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
QCPLineEnding head() const { return mHead; }
QCPLineEnding tail() const { return mTail; }
// setters;
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setHead(const QCPLineEnding &head);
void setTail(const QCPLineEnding &tail);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
QCPItemPosition * const start;
QCPItemPosition * const startDir;
QCPItemPosition * const endDir;
QCPItemPosition * const end;
protected:
// property members:
QPen mPen, mSelectedPen;
QCPLineEnding mHead, mTail;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
// non-virtual methods:
QPen mainPen() const;
};
/* end of 'src/items/item-curve.h' */
/* including file 'src/items/item-rect.h' */
/* modified 2022-11-06T12:45:56, size 3710 */
class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(QBrush brush READ brush WRITE setBrush)
Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush)
/// \endcond
public:
explicit QCPItemRect(QCustomPlot *parentPlot);
virtual ~QCPItemRect() Q_DECL_OVERRIDE;
// getters:
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
QBrush brush() const { return mBrush; }
QBrush selectedBrush() const { return mSelectedBrush; }
// setters;
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setSelectedBrush(const QBrush &brush);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
QCPItemPosition * const topLeft;
QCPItemPosition * const bottomRight;
QCPItemAnchor * const top;
QCPItemAnchor * const topRight;
QCPItemAnchor * const right;
QCPItemAnchor * const bottom;
QCPItemAnchor * const bottomLeft;
QCPItemAnchor * const left;
protected:
enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft};
// property members:
QPen mPen, mSelectedPen;
QBrush mBrush, mSelectedBrush;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE;
// non-virtual methods:
QPen mainPen() const;
QBrush mainBrush() const;
};
/* end of 'src/items/item-rect.h' */
/* including file 'src/items/item-text.h' */
/* modified 2022-11-06T12:45:56, size 5576 */
class QCP_LIB_DECL QCPItemText : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QColor color READ color WRITE setColor)
Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor)
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(QBrush brush READ brush WRITE setBrush)
Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush)
Q_PROPERTY(QFont font READ font WRITE setFont)
Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont)
Q_PROPERTY(QString text READ text WRITE setText)
Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment)
Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment)
Q_PROPERTY(double rotation READ rotation WRITE setRotation)
Q_PROPERTY(QMargins padding READ padding WRITE setPadding)
/// \endcond
public:
explicit QCPItemText(QCustomPlot *parentPlot);
virtual ~QCPItemText() Q_DECL_OVERRIDE;
// getters:
QColor color() const { return mColor; }
QColor selectedColor() const { return mSelectedColor; }
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
QBrush brush() const { return mBrush; }
QBrush selectedBrush() const { return mSelectedBrush; }
QFont font() const { return mFont; }
QFont selectedFont() const { return mSelectedFont; }
QString text() const { return mText; }
Qt::Alignment positionAlignment() const { return mPositionAlignment; }
Qt::Alignment textAlignment() const { return mTextAlignment; }
double rotation() const { return mRotation; }
QMargins padding() const { return mPadding; }
// setters;
void setColor(const QColor &color);
void setSelectedColor(const QColor &color);
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setSelectedBrush(const QBrush &brush);
void setFont(const QFont &font);
void setSelectedFont(const QFont &font);
void setText(const QString &text);
void setPositionAlignment(Qt::Alignment alignment);
void setTextAlignment(Qt::Alignment alignment);
void setRotation(double degrees);
void setPadding(const QMargins &padding);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
QCPItemPosition * const position;
QCPItemAnchor * const topLeft;
QCPItemAnchor * const top;
QCPItemAnchor * const topRight;
QCPItemAnchor * const right;
QCPItemAnchor * const bottomRight;
QCPItemAnchor * const bottom;
QCPItemAnchor * const bottomLeft;
QCPItemAnchor * const left;
protected:
enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft};
// property members:
QColor mColor, mSelectedColor;
QPen mPen, mSelectedPen;
QBrush mBrush, mSelectedBrush;
QFont mFont, mSelectedFont;
QString mText;
Qt::Alignment mPositionAlignment;
Qt::Alignment mTextAlignment;
double mRotation;
QMargins mPadding;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE;
// non-virtual methods:
QPointF getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const;
QFont mainFont() const;
QColor mainColor() const;
QPen mainPen() const;
QBrush mainBrush() const;
};
/* end of 'src/items/item-text.h' */
/* including file 'src/items/item-ellipse.h' */
/* modified 2022-11-06T12:45:56, size 3890 */
class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(QBrush brush READ brush WRITE setBrush)
Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush)
/// \endcond
public:
explicit QCPItemEllipse(QCustomPlot *parentPlot);
virtual ~QCPItemEllipse() Q_DECL_OVERRIDE;
// getters:
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
QBrush brush() const { return mBrush; }
QBrush selectedBrush() const { return mSelectedBrush; }
// setters;
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setSelectedBrush(const QBrush &brush);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
QCPItemPosition * const topLeft;
QCPItemPosition * const bottomRight;
QCPItemAnchor * const topLeftRim;
QCPItemAnchor * const top;
QCPItemAnchor * const topRightRim;
QCPItemAnchor * const right;
QCPItemAnchor * const bottomRightRim;
QCPItemAnchor * const bottom;
QCPItemAnchor * const bottomLeftRim;
QCPItemAnchor * const left;
QCPItemAnchor * const center;
protected:
enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter};
// property members:
QPen mPen, mSelectedPen;
QBrush mBrush, mSelectedBrush;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE;
// non-virtual methods:
QPen mainPen() const;
QBrush mainBrush() const;
};
/* end of 'src/items/item-ellipse.h' */
/* including file 'src/items/item-pixmap.h' */
/* modified 2022-11-06T12:45:56, size 4407 */
class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap)
Q_PROPERTY(bool scaled READ scaled WRITE setScaled)
Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode)
Q_PROPERTY(Qt::TransformationMode transformationMode READ transformationMode)
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
/// \endcond
public:
explicit QCPItemPixmap(QCustomPlot *parentPlot);
virtual ~QCPItemPixmap() Q_DECL_OVERRIDE;
// getters:
QPixmap pixmap() const { return mPixmap; }
bool scaled() const { return mScaled; }
Qt::AspectRatioMode aspectRatioMode() const { return mAspectRatioMode; }
Qt::TransformationMode transformationMode() const { return mTransformationMode; }
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
// setters;
void setPixmap(const QPixmap &pixmap);
void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode=Qt::KeepAspectRatio, Qt::TransformationMode transformationMode=Qt::SmoothTransformation);
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
QCPItemPosition * const topLeft;
QCPItemPosition * const bottomRight;
QCPItemAnchor * const top;
QCPItemAnchor * const topRight;
QCPItemAnchor * const right;
QCPItemAnchor * const bottom;
QCPItemAnchor * const bottomLeft;
QCPItemAnchor * const left;
protected:
enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft};
// property members:
QPixmap mPixmap;
QPixmap mScaledPixmap;
bool mScaled;
bool mScaledPixmapInvalidated;
Qt::AspectRatioMode mAspectRatioMode;
Qt::TransformationMode mTransformationMode;
QPen mPen, mSelectedPen;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE;
// non-virtual methods:
void updateScaledPixmap(QRect finalRect=QRect(), bool flipHorz=false, bool flipVert=false);
QRect getFinalRect(bool *flippedHorz=nullptr, bool *flippedVert=nullptr) const;
QPen mainPen() const;
};
/* end of 'src/items/item-pixmap.h' */
/* including file 'src/items/item-tracer.h' */
/* modified 2022-11-06T12:45:56, size 4811 */
class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(QBrush brush READ brush WRITE setBrush)
Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush)
Q_PROPERTY(double size READ size WRITE setSize)
Q_PROPERTY(TracerStyle style READ style WRITE setStyle)
Q_PROPERTY(QCPGraph* graph READ graph WRITE setGraph)
Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey)
Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating)
/// \endcond
public:
/*!
The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize.
\see setStyle
*/
enum TracerStyle { tsNone ///< The tracer is not visible
,tsPlus ///< A plus shaped crosshair with limited size
,tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect
,tsCircle ///< A circle
,tsSquare ///< A square
};
Q_ENUMS(TracerStyle)
explicit QCPItemTracer(QCustomPlot *parentPlot);
virtual ~QCPItemTracer() Q_DECL_OVERRIDE;
// getters:
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
QBrush brush() const { return mBrush; }
QBrush selectedBrush() const { return mSelectedBrush; }
double size() const { return mSize; }
TracerStyle style() const { return mStyle; }
QCPGraph *graph() const { return mGraph; }
double graphKey() const { return mGraphKey; }
bool interpolating() const { return mInterpolating; }
// setters;
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setSelectedBrush(const QBrush &brush);
void setSize(double size);
void setStyle(TracerStyle style);
void setGraph(QCPGraph *graph);
void setGraphKey(double key);
void setInterpolating(bool enabled);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
// non-virtual methods:
void updatePosition();
QCPItemPosition * const position;
protected:
// property members:
QPen mPen, mSelectedPen;
QBrush mBrush, mSelectedBrush;
double mSize;
TracerStyle mStyle;
QCPGraph *mGraph;
double mGraphKey;
bool mInterpolating;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
// non-virtual methods:
QPen mainPen() const;
QBrush mainBrush() const;
};
Q_DECLARE_METATYPE(QCPItemTracer::TracerStyle)
/* end of 'src/items/item-tracer.h' */
/* including file 'src/items/item-bracket.h' */
/* modified 2022-11-06T12:45:56, size 3991 */
class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
Q_PROPERTY(QPen pen READ pen WRITE setPen)
Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen)
Q_PROPERTY(double length READ length WRITE setLength)
Q_PROPERTY(BracketStyle style READ style WRITE setStyle)
/// \endcond
public:
/*!
Defines the various visual shapes of the bracket item. The appearance can be further modified
by \ref setLength and \ref setPen.
\see setStyle
*/
enum BracketStyle { bsSquare ///< A brace with angled edges
,bsRound ///< A brace with round edges
,bsCurly ///< A curly brace
,bsCalligraphic ///< A curly brace with varying stroke width giving a calligraphic impression
};
Q_ENUMS(BracketStyle)
explicit QCPItemBracket(QCustomPlot *parentPlot);
virtual ~QCPItemBracket() Q_DECL_OVERRIDE;
// getters:
QPen pen() const { return mPen; }
QPen selectedPen() const { return mSelectedPen; }
double length() const { return mLength; }
BracketStyle style() const { return mStyle; }
// setters;
void setPen(const QPen &pen);
void setSelectedPen(const QPen &pen);
void setLength(double length);
void setStyle(BracketStyle style);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE;
QCPItemPosition * const left;
QCPItemPosition * const right;
QCPItemAnchor * const center;
protected:
// property members:
enum AnchorIndex {aiCenter};
QPen mPen, mSelectedPen;
double mLength;
BracketStyle mStyle;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE;
// non-virtual methods:
QPen mainPen() const;
};
Q_DECLARE_METATYPE(QCPItemBracket::BracketStyle)
/* end of 'src/items/item-bracket.h' */
/* including file 'src/polar/radialaxis.h' */
/* modified 2022-11-06T12:45:56, size 12227 */
class QCP_LIB_DECL QCPPolarAxisRadial : public QCPLayerable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
/// \endcond
public:
/*!
Defines the reference of the angle at which a radial axis is tilted (\ref setAngle).
*/
enum AngleReference { arAbsolute ///< The axis tilt is given in absolute degrees. The zero is to the right and positive angles are measured counter-clockwise.
,arAngularAxis ///< The axis tilt is measured in the angular coordinate system given by the parent angular axis.
};
Q_ENUMS(AngleReference)
/*!
Defines the scale of an axis.
\see setScaleType
*/
enum ScaleType { stLinear ///< Linear scaling
,stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance).
};
Q_ENUMS(ScaleType)
/*!
Defines the selectable parts of an axis.
\see setSelectableParts, setSelectedParts
*/
enum SelectablePart { spNone = 0 ///< None of the selectable parts
,spAxis = 0x001 ///< The axis backbone and tick marks
,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually)
,spAxisLabel = 0x004 ///< The axis label
};
Q_ENUMS(SelectablePart)
Q_FLAGS(SelectableParts)
Q_DECLARE_FLAGS(SelectableParts, SelectablePart)
enum LabelMode { lmUpright ///<
,lmRotated ///<
};
Q_ENUMS(LabelMode)
explicit QCPPolarAxisRadial(QCPPolarAxisAngular *parent);
virtual ~QCPPolarAxisRadial();
// getters:
bool rangeDrag() const { return mRangeDrag; }
bool rangeZoom() const { return mRangeZoom; }
double rangeZoomFactor() const { return mRangeZoomFactor; }
QCPPolarAxisAngular *angularAxis() const { return mAngularAxis; }
ScaleType scaleType() const { return mScaleType; }
const QCPRange range() const { return mRange; }
bool rangeReversed() const { return mRangeReversed; }
double angle() const { return mAngle; }
AngleReference angleReference() const { return mAngleReference; }
QSharedPointer<QCPAxisTicker> ticker() const { return mTicker; }
bool ticks() const { return mTicks; }
bool tickLabels() const { return mTickLabels; }
int tickLabelPadding() const { return mLabelPainter.padding(); }
QFont tickLabelFont() const { return mTickLabelFont; }
QColor tickLabelColor() const { return mTickLabelColor; }
double tickLabelRotation() const { return mLabelPainter.rotation(); }
LabelMode tickLabelMode() const;
QString numberFormat() const;
int numberPrecision() const { return mNumberPrecision; }
QVector<double> tickVector() const { return mTickVector; }
QVector<double> subTickVector() const { return mSubTickVector; }
QVector<QString> tickVectorLabels() const { return mTickVectorLabels; }
int tickLengthIn() const;
int tickLengthOut() const;
bool subTicks() const { return mSubTicks; }
int subTickLengthIn() const;
int subTickLengthOut() const;
QPen basePen() const { return mBasePen; }
QPen tickPen() const { return mTickPen; }
QPen subTickPen() const { return mSubTickPen; }
QFont labelFont() const { return mLabelFont; }
QColor labelColor() const { return mLabelColor; }
QString label() const { return mLabel; }
int labelPadding() const;
SelectableParts selectedParts() const { return mSelectedParts; }
SelectableParts selectableParts() const { return mSelectableParts; }
QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; }
QFont selectedLabelFont() const { return mSelectedLabelFont; }
QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; }
QColor selectedLabelColor() const { return mSelectedLabelColor; }
QPen selectedBasePen() const { return mSelectedBasePen; }
QPen selectedTickPen() const { return mSelectedTickPen; }
QPen selectedSubTickPen() const { return mSelectedSubTickPen; }
// setters:
void setRangeDrag(bool enabled);
void setRangeZoom(bool enabled);
void setRangeZoomFactor(double factor);
Q_SLOT void setScaleType(QCPPolarAxisRadial::ScaleType type);
Q_SLOT void setRange(const QCPRange &range);
void setRange(double lower, double upper);
void setRange(double position, double size, Qt::AlignmentFlag alignment);
void setRangeLower(double lower);
void setRangeUpper(double upper);
void setRangeReversed(bool reversed);
void setAngle(double degrees);
void setAngleReference(AngleReference reference);
void setTicker(QSharedPointer<QCPAxisTicker> ticker);
void setTicks(bool show);
void setTickLabels(bool show);
void setTickLabelPadding(int padding);
void setTickLabelFont(const QFont &font);
void setTickLabelColor(const QColor &color);
void setTickLabelRotation(double degrees);
void setTickLabelMode(LabelMode mode);
void setNumberFormat(const QString &formatCode);
void setNumberPrecision(int precision);
void setTickLength(int inside, int outside=0);
void setTickLengthIn(int inside);
void setTickLengthOut(int outside);
void setSubTicks(bool show);
void setSubTickLength(int inside, int outside=0);
void setSubTickLengthIn(int inside);
void setSubTickLengthOut(int outside);
void setBasePen(const QPen &pen);
void setTickPen(const QPen &pen);
void setSubTickPen(const QPen &pen);
void setLabelFont(const QFont &font);
void setLabelColor(const QColor &color);
void setLabel(const QString &str);
void setLabelPadding(int padding);
void setSelectedTickLabelFont(const QFont &font);
void setSelectedLabelFont(const QFont &font);
void setSelectedTickLabelColor(const QColor &color);
void setSelectedLabelColor(const QColor &color);
void setSelectedBasePen(const QPen &pen);
void setSelectedTickPen(const QPen &pen);
void setSelectedSubTickPen(const QPen &pen);
Q_SLOT void setSelectableParts(const QCPPolarAxisRadial::SelectableParts &selectableParts);
Q_SLOT void setSelectedParts(const QCPPolarAxisRadial::SelectableParts &selectedParts);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE;
// non-property methods:
void moveRange(double diff);
void scaleRange(double factor);
void scaleRange(double factor, double center);
void rescale(bool onlyVisiblePlottables=false);
void pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const;
QPointF coordToPixel(double angleCoord, double radiusCoord) const;
double coordToRadius(double coord) const;
double radiusToCoord(double radius) const;
SelectablePart getPartAt(const QPointF &pos) const;
signals:
void rangeChanged(const QCPRange &newRange);
void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange);
void scaleTypeChanged(QCPPolarAxisRadial::ScaleType scaleType);
void selectionChanged(const QCPPolarAxisRadial::SelectableParts &parts);
void selectableChanged(const QCPPolarAxisRadial::SelectableParts &parts);
protected:
// property members:
bool mRangeDrag;
bool mRangeZoom;
double mRangeZoomFactor;
// axis base:
QCPPolarAxisAngular *mAngularAxis;
double mAngle;
AngleReference mAngleReference;
SelectableParts mSelectableParts, mSelectedParts;
QPen mBasePen, mSelectedBasePen;
// axis label:
int mLabelPadding;
QString mLabel;
QFont mLabelFont, mSelectedLabelFont;
QColor mLabelColor, mSelectedLabelColor;
// tick labels:
//int mTickLabelPadding; in label painter
bool mTickLabels;
//double mTickLabelRotation; in label painter
QFont mTickLabelFont, mSelectedTickLabelFont;
QColor mTickLabelColor, mSelectedTickLabelColor;
int mNumberPrecision;
QLatin1Char mNumberFormatChar;
bool mNumberBeautifulPowers;
bool mNumberMultiplyCross;
// ticks and subticks:
bool mTicks;
bool mSubTicks;
int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut;
QPen mTickPen, mSelectedTickPen;
QPen mSubTickPen, mSelectedSubTickPen;
// scale and range:
QCPRange mRange;
bool mRangeReversed;
ScaleType mScaleType;
// non-property members:
QPointF mCenter;
double mRadius;
QSharedPointer<QCPAxisTicker> mTicker;
QVector<double> mTickVector;
QVector<QString> mTickVectorLabels;
QVector<double> mSubTickVector;
bool mDragging;
QCPRange mDragStartRange;
QCP::AntialiasedElements mAADragBackup, mNotAADragBackup;
QCPLabelPainterPrivate mLabelPainter;
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE;
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE;
virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE;
// mouse events:
virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE;
virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE;
virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE;
virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE;
// non-virtual methods:
void updateGeometry(const QPointF ¢er, double radius);
void setupTickVectors();
QPen getBasePen() const;
QPen getTickPen() const;
QPen getSubTickPen() const;
QFont getTickLabelFont() const;
QFont getLabelFont() const;
QColor getTickLabelColor() const;
QColor getLabelColor() const;
private:
Q_DISABLE_COPY(QCPPolarAxisRadial)
friend class QCustomPlot;
friend class QCPPolarAxisAngular;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPolarAxisRadial::SelectableParts)
Q_DECLARE_METATYPE(QCPPolarAxisRadial::AngleReference)
Q_DECLARE_METATYPE(QCPPolarAxisRadial::ScaleType)
Q_DECLARE_METATYPE(QCPPolarAxisRadial::SelectablePart)
/* end of 'src/polar/radialaxis.h' */
/* including file 'src/polar/layoutelement-angularaxis.h' */
/* modified 2022-11-06T12:45:56, size 13461 */
class QCP_LIB_DECL QCPPolarAxisAngular : public QCPLayoutElement
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
/// \endcond
public:
/*!
Defines the selectable parts of an axis.
\see setSelectableParts, setSelectedParts
*/
enum SelectablePart { spNone = 0 ///< None of the selectable parts
,spAxis = 0x001 ///< The axis backbone and tick marks
,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually)
,spAxisLabel = 0x004 ///< The axis label
};
Q_ENUMS(SelectablePart)
Q_FLAGS(SelectableParts)
Q_DECLARE_FLAGS(SelectableParts, SelectablePart)
/*!
TODO
*/
enum LabelMode { lmUpright ///<
,lmRotated ///<
};
Q_ENUMS(LabelMode)
explicit QCPPolarAxisAngular(QCustomPlot *parentPlot);
virtual ~QCPPolarAxisAngular();
// getters:
QPixmap background() const { return mBackgroundPixmap; }
QBrush backgroundBrush() const { return mBackgroundBrush; }
bool backgroundScaled() const { return mBackgroundScaled; }
Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; }
bool rangeDrag() const { return mRangeDrag; }
bool rangeZoom() const { return mRangeZoom; }
double rangeZoomFactor() const { return mRangeZoomFactor; }
const QCPRange range() const { return mRange; }
bool rangeReversed() const { return mRangeReversed; }
double angle() const { return mAngle; }
QSharedPointer<QCPAxisTicker> ticker() const { return mTicker; }
bool ticks() const { return mTicks; }
bool tickLabels() const { return mTickLabels; }
int tickLabelPadding() const { return mLabelPainter.padding(); }
QFont tickLabelFont() const { return mTickLabelFont; }
QColor tickLabelColor() const { return mTickLabelColor; }
double tickLabelRotation() const { return mLabelPainter.rotation(); }
LabelMode tickLabelMode() const;
QString numberFormat() const;
int numberPrecision() const { return mNumberPrecision; }
QVector<double> tickVector() const { return mTickVector; }
QVector<QString> tickVectorLabels() const { return mTickVectorLabels; }
int tickLengthIn() const { return mTickLengthIn; }
int tickLengthOut() const { return mTickLengthOut; }
bool subTicks() const { return mSubTicks; }
int subTickLengthIn() const { return mSubTickLengthIn; }
int subTickLengthOut() const { return mSubTickLengthOut; }
QPen basePen() const { return mBasePen; }
QPen tickPen() const { return mTickPen; }
QPen subTickPen() const { return mSubTickPen; }
QFont labelFont() const { return mLabelFont; }
QColor labelColor() const { return mLabelColor; }
QString label() const { return mLabel; }
int labelPadding() const { return mLabelPadding; }
SelectableParts selectedParts() const { return mSelectedParts; }
SelectableParts selectableParts() const { return mSelectableParts; }
QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; }
QFont selectedLabelFont() const { return mSelectedLabelFont; }
QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; }
QColor selectedLabelColor() const { return mSelectedLabelColor; }
QPen selectedBasePen() const { return mSelectedBasePen; }
QPen selectedTickPen() const { return mSelectedTickPen; }
QPen selectedSubTickPen() const { return mSelectedSubTickPen; }
QCPPolarGrid *grid() const { return mGrid; }
// setters:
void setBackground(const QPixmap &pm);
void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding);
void setBackground(const QBrush &brush);
void setBackgroundScaled(bool scaled);
void setBackgroundScaledMode(Qt::AspectRatioMode mode);
void setRangeDrag(bool enabled);
void setRangeZoom(bool enabled);
void setRangeZoomFactor(double factor);
Q_SLOT void setRange(const QCPRange &range);
void setRange(double lower, double upper);
void setRange(double position, double size, Qt::AlignmentFlag alignment);
void setRangeLower(double lower);
void setRangeUpper(double upper);
void setRangeReversed(bool reversed);
void setAngle(double degrees);
void setTicker(QSharedPointer<QCPAxisTicker> ticker);
void setTicks(bool show);
void setTickLabels(bool show);
void setTickLabelPadding(int padding);
void setTickLabelFont(const QFont &font);
void setTickLabelColor(const QColor &color);
void setTickLabelRotation(double degrees);
void setTickLabelMode(LabelMode mode);
void setNumberFormat(const QString &formatCode);
void setNumberPrecision(int precision);
void setTickLength(int inside, int outside=0);
void setTickLengthIn(int inside);
void setTickLengthOut(int outside);
void setSubTicks(bool show);
void setSubTickLength(int inside, int outside=0);
void setSubTickLengthIn(int inside);
void setSubTickLengthOut(int outside);
void setBasePen(const QPen &pen);
void setTickPen(const QPen &pen);
void setSubTickPen(const QPen &pen);
void setLabelFont(const QFont &font);
void setLabelColor(const QColor &color);
void setLabel(const QString &str);
void setLabelPadding(int padding);
void setLabelPosition(Qt::AlignmentFlag position);
void setSelectedTickLabelFont(const QFont &font);
void setSelectedLabelFont(const QFont &font);
void setSelectedTickLabelColor(const QColor &color);
void setSelectedLabelColor(const QColor &color);
void setSelectedBasePen(const QPen &pen);
void setSelectedTickPen(const QPen &pen);
void setSelectedSubTickPen(const QPen &pen);
Q_SLOT void setSelectableParts(const QCPPolarAxisAngular::SelectableParts &selectableParts);
Q_SLOT void setSelectedParts(const QCPPolarAxisAngular::SelectableParts &selectedParts);
// reimplemented virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE;
virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE;
virtual QList<QCPLayoutElement*> elements(bool recursive) const Q_DECL_OVERRIDE;
// non-property methods:
bool removeGraph(QCPPolarGraph *graph);
int radialAxisCount() const;
QCPPolarAxisRadial *radialAxis(int index=0) const;
QList<QCPPolarAxisRadial*> radialAxes() const;
QCPPolarAxisRadial *addRadialAxis(QCPPolarAxisRadial *axis=0);
bool removeRadialAxis(QCPPolarAxisRadial *axis);
QCPLayoutInset *insetLayout() const { return mInsetLayout; }
QRegion exactClipRegion() const;
void moveRange(double diff);
void scaleRange(double factor);
void scaleRange(double factor, double center);
void rescale(bool onlyVisiblePlottables=false);
double coordToAngleRad(double coord) const { return mAngleRad+(coord-mRange.lower)/mRange.size()*(mRangeReversed ? -2.0*M_PI : 2.0*M_PI); } // mention in doc that return doesn't wrap
double angleRadToCoord(double angleRad) const { return mRange.lower+(angleRad-mAngleRad)/(mRangeReversed ? -2.0*M_PI : 2.0*M_PI)*mRange.size(); }
void pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const;
QPointF coordToPixel(double angleCoord, double radiusCoord) const;
SelectablePart getPartAt(const QPointF &pos) const;
// read-only interface imitating a QRect:
int left() const { return mRect.left(); }
int right() const { return mRect.right(); }
int top() const { return mRect.top(); }
int bottom() const { return mRect.bottom(); }
int width() const { return mRect.width(); }
int height() const { return mRect.height(); }
QSize size() const { return mRect.size(); }
QPoint topLeft() const { return mRect.topLeft(); }
QPoint topRight() const { return mRect.topRight(); }
QPoint bottomLeft() const { return mRect.bottomLeft(); }
QPoint bottomRight() const { return mRect.bottomRight(); }
QPointF center() const { return mCenter; }
double radius() const { return mRadius; }
signals:
void rangeChanged(const QCPRange &newRange);
void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange);
void selectionChanged(const QCPPolarAxisAngular::SelectableParts &parts);
void selectableChanged(const QCPPolarAxisAngular::SelectableParts &parts);
protected:
// property members:
QBrush mBackgroundBrush;
QPixmap mBackgroundPixmap;
QPixmap mScaledBackgroundPixmap;
bool mBackgroundScaled;
Qt::AspectRatioMode mBackgroundScaledMode;
QCPLayoutInset *mInsetLayout;
bool mRangeDrag;
bool mRangeZoom;
double mRangeZoomFactor;
// axis base:
double mAngle, mAngleRad;
SelectableParts mSelectableParts, mSelectedParts;
QPen mBasePen, mSelectedBasePen;
// axis label:
int mLabelPadding;
QString mLabel;
QFont mLabelFont, mSelectedLabelFont;
QColor mLabelColor, mSelectedLabelColor;
// tick labels:
//int mTickLabelPadding; in label painter
bool mTickLabels;
//double mTickLabelRotation; in label painter
QFont mTickLabelFont, mSelectedTickLabelFont;
QColor mTickLabelColor, mSelectedTickLabelColor;
int mNumberPrecision;
QLatin1Char mNumberFormatChar;
bool mNumberBeautifulPowers;
bool mNumberMultiplyCross;
// ticks and subticks:
bool mTicks;
bool mSubTicks;
int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut;
QPen mTickPen, mSelectedTickPen;
QPen mSubTickPen, mSelectedSubTickPen;
// scale and range:
QCPRange mRange;
bool mRangeReversed;
// non-property members:
QPointF mCenter;
double mRadius;
QList<QCPPolarAxisRadial*> mRadialAxes;
QCPPolarGrid *mGrid;
QList<QCPPolarGraph*> mGraphs;
QSharedPointer<QCPAxisTicker> mTicker;
QVector<double> mTickVector;
QVector<QString> mTickVectorLabels;
QVector<QPointF> mTickVectorCosSin;
QVector<double> mSubTickVector;
QVector<QPointF> mSubTickVectorCosSin;
bool mDragging;
QCPRange mDragAngularStart;
QList<QCPRange> mDragRadialStart;
QCP::AntialiasedElements mAADragBackup, mNotAADragBackup;
QCPLabelPainterPrivate mLabelPainter;
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE;
// events:
virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE;
virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE;
virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE;
virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE;
// non-virtual methods:
bool registerPolarGraph(QCPPolarGraph *graph);
void drawBackground(QCPPainter *painter, const QPointF ¢er, double radius);
void setupTickVectors();
QPen getBasePen() const;
QPen getTickPen() const;
QPen getSubTickPen() const;
QFont getTickLabelFont() const;
QFont getLabelFont() const;
QColor getTickLabelColor() const;
QColor getLabelColor() const;
private:
Q_DISABLE_COPY(QCPPolarAxisAngular)
friend class QCustomPlot;
friend class QCPPolarGrid;
friend class QCPPolarGraph;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPolarAxisAngular::SelectableParts)
Q_DECLARE_METATYPE(QCPPolarAxisAngular::SelectablePart)
/* end of 'src/polar/layoutelement-angularaxis.h' */
/* including file 'src/polar/polargrid.h' */
/* modified 2022-11-06T12:45:56, size 4506 */
class QCP_LIB_DECL QCPPolarGrid :public QCPLayerable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
/// \endcond
public:
/*!
TODO
*/
enum GridType { gtAngular = 0x01 ///<
,gtRadial = 0x02 ///<
,gtAll = 0xFF ///<
,gtNone = 0x00 ///<
};
Q_ENUMS(GridType)
Q_FLAGS(GridTypes)
Q_DECLARE_FLAGS(GridTypes, GridType)
explicit QCPPolarGrid(QCPPolarAxisAngular *parentAxis);
// getters:
QCPPolarAxisRadial *radialAxis() const { return mRadialAxis.data(); }
GridTypes type() const { return mType; }
GridTypes subGridType() const { return mSubGridType; }
bool antialiasedSubGrid() const { return mAntialiasedSubGrid; }
bool antialiasedZeroLine() const { return mAntialiasedZeroLine; }
QPen angularPen() const { return mAngularPen; }
QPen angularSubGridPen() const { return mAngularSubGridPen; }
QPen radialPen() const { return mRadialPen; }
QPen radialSubGridPen() const { return mRadialSubGridPen; }
QPen radialZeroLinePen() const { return mRadialZeroLinePen; }
// setters:
void setRadialAxis(QCPPolarAxisRadial *axis);
void setType(GridTypes type);
void setSubGridType(GridTypes type);
void setAntialiasedSubGrid(bool enabled);
void setAntialiasedZeroLine(bool enabled);
void setAngularPen(const QPen &pen);
void setAngularSubGridPen(const QPen &pen);
void setRadialPen(const QPen &pen);
void setRadialSubGridPen(const QPen &pen);
void setRadialZeroLinePen(const QPen &pen);
protected:
// property members:
GridTypes mType;
GridTypes mSubGridType;
bool mAntialiasedSubGrid, mAntialiasedZeroLine;
QPen mAngularPen, mAngularSubGridPen;
QPen mRadialPen, mRadialSubGridPen, mRadialZeroLinePen;
// non-property members:
QCPPolarAxisAngular *mParentAxis;
QPointer<QCPPolarAxisRadial> mRadialAxis;
// reimplemented virtual methods:
virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE;
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
// non-virtual methods:
void drawRadialGrid(QCPPainter *painter, const QPointF ¢er, const QVector<double> &coords, const QPen &pen, const QPen &zeroPen=Qt::NoPen);
void drawAngularGrid(QCPPainter *painter, const QPointF ¢er, double radius, const QVector<QPointF> &ticksCosSin, const QPen &pen);
private:
Q_DISABLE_COPY(QCPPolarGrid)
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPolarGrid::GridTypes)
Q_DECLARE_METATYPE(QCPPolarGrid::GridType)
/* end of 'src/polar/polargrid.h' */
/* including file 'src/polar/polargraph.h' */
/* modified 2022-11-06T12:45:56, size 9606 */
class QCP_LIB_DECL QCPPolarLegendItem : public QCPAbstractLegendItem
{
Q_OBJECT
public:
QCPPolarLegendItem(QCPLegend *parent, QCPPolarGraph *graph);
// getters:
QCPPolarGraph *polarGraph() { return mPolarGraph; }
protected:
// property members:
QCPPolarGraph *mPolarGraph;
// reimplemented virtual methods:
virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;
virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE;
// non-virtual methods:
QPen getIconBorderPen() const;
QColor getTextColor() const;
QFont getFont() const;
};
class QCP_LIB_DECL QCPPolarGraph : public QCPLayerable
{
Q_OBJECT
/// \cond INCLUDE_QPROPERTIES
/// \endcond
public:
/*!
Defines how the graph's line is represented visually in the plot. The line is drawn with the
current pen of the graph (\ref setPen).
\see setLineStyle
*/
enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented
///< with symbols according to the scatter style, see \ref setScatterStyle)
,lsLine ///< data points are connected by a straight line
};
Q_ENUMS(LineStyle)
QCPPolarGraph(QCPPolarAxisAngular *keyAxis, QCPPolarAxisRadial *valueAxis);
virtual ~QCPPolarGraph();
// getters:
QString name() const { return mName; }
bool antialiasedFill() const { return mAntialiasedFill; }
bool antialiasedScatters() const { return mAntialiasedScatters; }
QPen pen() const { return mPen; }
QBrush brush() const { return mBrush; }
bool periodic() const { return mPeriodic; }
QCPPolarAxisAngular *keyAxis() const { return mKeyAxis.data(); }
QCPPolarAxisRadial *valueAxis() const { return mValueAxis.data(); }
QCP::SelectionType selectable() const { return mSelectable; }
bool selected() const { return !mSelection.isEmpty(); }
QCPDataSelection selection() const { return mSelection; }
//QCPSelectionDecorator *selectionDecorator() const { return mSelectionDecorator; }
QSharedPointer<QCPGraphDataContainer> data() const { return mDataContainer; }
LineStyle lineStyle() const { return mLineStyle; }
QCPScatterStyle scatterStyle() const { return mScatterStyle; }
// setters:
void setName(const QString &name);
void setAntialiasedFill(bool enabled);
void setAntialiasedScatters(bool enabled);
void setPen(const QPen &pen);
void setBrush(const QBrush &brush);
void setPeriodic(bool enabled);
void setKeyAxis(QCPPolarAxisAngular *axis);
void setValueAxis(QCPPolarAxisRadial *axis);
Q_SLOT void setSelectable(QCP::SelectionType selectable);
Q_SLOT void setSelection(QCPDataSelection selection);
//void setSelectionDecorator(QCPSelectionDecorator *decorator);
void setData(QSharedPointer<QCPGraphDataContainer> data);
void setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted=false);
void setLineStyle(LineStyle ls);
void setScatterStyle(const QCPScatterStyle &style);
// non-property methods:
void addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted=false);
void addData(double key, double value);
void coordsToPixels(double key, double value, double &x, double &y) const;
const QPointF coordsToPixels(double key, double value) const;
void pixelsToCoords(double x, double y, double &key, double &value) const;
void pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const;
void rescaleAxes(bool onlyEnlarge=false) const;
void rescaleKeyAxis(bool onlyEnlarge=false) const;
void rescaleValueAxis(bool onlyEnlarge=false, bool inKeyRange=false) const;
bool addToLegend(QCPLegend *legend);
bool addToLegend();
bool removeFromLegend(QCPLegend *legend) const;
bool removeFromLegend() const;
// introduced virtual methods:
virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // actually introduced in QCPLayerable as non-pure, but we want to force reimplementation for plottables
virtual QCPPlottableInterface1D *interface1D() { return 0; } // TODO: return this later, when QCPAbstractPolarPlottable is created
virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const;
virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const;
signals:
void selectionChanged(bool selected);
void selectionChanged(const QCPDataSelection &selection);
void selectableChanged(QCP::SelectionType selectable);
protected:
// property members:
QSharedPointer<QCPGraphDataContainer> mDataContainer;
LineStyle mLineStyle;
QCPScatterStyle mScatterStyle;
QString mName;
bool mAntialiasedFill, mAntialiasedScatters;
QPen mPen;
QBrush mBrush;
bool mPeriodic;
QPointer<QCPPolarAxisAngular> mKeyAxis;
QPointer<QCPPolarAxisRadial> mValueAxis;
QCP::SelectionType mSelectable;
QCPDataSelection mSelection;
//QCPSelectionDecorator *mSelectionDecorator;
// introduced virtual methods (later reimplemented TODO from QCPAbstractPolarPlottable):
virtual QRect clipRect() const;
virtual void draw(QCPPainter *painter);
virtual QCP::Interaction selectionCategory() const;
void applyDefaultAntialiasingHint(QCPPainter *painter) const;
// events:
virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged);
virtual void deselectEvent(bool *selectionStateChanged);
// virtual drawing helpers:
virtual void drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const;
virtual void drawFill(QCPPainter *painter, QVector<QPointF> *lines) const;
virtual void drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const;
// introduced virtual methods:
virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const;
// non-virtual methods:
void applyFillAntialiasingHint(QCPPainter *painter) const;
void applyScattersAntialiasingHint(QCPPainter *painter) const;
double pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const;
// drawing helpers:
virtual int dataCount() const;
void getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const;
void drawPolyline(QCPPainter *painter, const QVector<QPointF> &lineData) const;
void getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const;
void getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const;
void getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const;
void getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const;
void getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const;
QVector<QPointF> dataToLines(const QVector<QCPGraphData> &data) const;
private:
Q_DISABLE_COPY(QCPPolarGraph)
friend class QCPPolarLegendItem;
};
/* end of 'src/polar/polargraph.h' */
#endif // QCUSTOMPLOT_H |
C++ | wireshark/ui/qt/widgets/range_syntax_lineedit.cpp | /* range_syntax_lineedit.cpp
* Delegates for editing prefereneces.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/range_syntax_lineedit.h>
#include <epan/range.h>
RangeSyntaxLineEdit::RangeSyntaxLineEdit(QWidget *parent)
: SyntaxLineEdit(parent),
maxRange_(0xFFFFFFFF)
{
connect(this, &RangeSyntaxLineEdit::textChanged, this, &RangeSyntaxLineEdit::checkRange);
}
void RangeSyntaxLineEdit::setMaxRange(unsigned int max)
{
maxRange_ = max;
}
void RangeSyntaxLineEdit::checkRange(QString range)
{
if (range.isEmpty()) {
setSyntaxState(SyntaxLineEdit::Empty);
return;
}
range_t *newrange;
convert_ret_t ret = range_convert_str(NULL, &newrange, range.toUtf8().constData(), maxRange_);
if (ret == CVT_NO_ERROR) {
setSyntaxState(SyntaxLineEdit::Valid);
wmem_free(NULL, newrange);
} else {
setSyntaxState(SyntaxLineEdit::Invalid);
}
} |
C/C++ | wireshark/ui/qt/widgets/range_syntax_lineedit.h | /** @file
*
* Delegates for editing prefereneces.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef RANGE_SYNTAX_LINEEDIT_H
#define RANGE_SYNTAX_LINEEDIT_H
#include <ui/qt/widgets/syntax_line_edit.h>
#include <QWidget>
class RangeSyntaxLineEdit : public SyntaxLineEdit
{
Q_OBJECT
public:
explicit RangeSyntaxLineEdit(QWidget *parent = 0);
void setMaxRange(unsigned int max);
public slots:
void checkRange(QString range);
private:
unsigned int maxRange_;
};
#endif // RANGE_SYNTAX_LINEEDIT_H |
C++ | wireshark/ui/qt/widgets/rtp_audio_graph.cpp | /* rtp_audio_graph.c
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "rtp_audio_graph.h"
#include <glib.h>
#include <epan/prefs.h>
#include <ui/qt/utils/color_utils.h>
static const double wf_graph_normal_width_ = 0.5;
RtpAudioGraph::RtpAudioGraph(QCustomPlot *audio_plot, QRgb color) : QObject(audio_plot)
{
QPen p;
QPalette sel_pal;
color_ = color;
wave_ = audio_plot->addGraph();
p = QPen(wave_->pen());
p.setColor(color_);
p.setWidthF(wf_graph_normal_width_);
wave_->setPen(p);
wave_->setSelectable(QCP::stNone);
wave_->removeFromLegend();
selection_color_ = sel_pal.color(QPalette::Highlight);
}
// Indicate that audio will not be hearable
void RtpAudioGraph::setMuted(bool isMuted)
{
QPen p = wave_->pen();
if (isMuted) {
p.setStyle(Qt::DotLine);
} else {
p.setStyle(Qt::SolidLine);
}
wave_->setPen(p);
}
void RtpAudioGraph::setHighlight(bool isHighlighted)
{
wave_->setSelection(isHighlighted ? QCPDataSelection(QCPDataRange()) : QCPDataSelection());
QPen p = wave_->pen();
if (isHighlighted) {
p.setWidthF(wf_graph_normal_width_*2);
} else {
p.setWidthF(wf_graph_normal_width_);
}
wave_->setPen(p);
}
void RtpAudioGraph::setSelected(bool isSelected)
{
wave_->setSelection(isSelected ? QCPDataSelection(QCPDataRange()) : QCPDataSelection());
QPen p = wave_->pen();
if (isSelected) {
p.setColor(selection_color_);
} else {
p.setColor(color_);
}
wave_->setPen(p);
}
void RtpAudioGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
{
wave_->setData(keys, values, alreadySorted);
}
void RtpAudioGraph::remove(QCustomPlot *audioPlot)
{
audioPlot->removeGraph(wave_);
}
bool RtpAudioGraph::isMyPlottable(QCPAbstractPlottable *plottable)
{
if (plottable == wave_) {
return true;
} else {
return false;
}
} |
C/C++ | wireshark/ui/qt/widgets/rtp_audio_graph.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef RTP_AUDIO_GRAPH_H
#define RTP_AUDIO_GRAPH_H
#include "config.h"
#include <ui/qt/widgets/qcustomplot.h>
//class QCPItemStraightLine;
//class QCPAxisTicker;
//class QCPAxisTickerDateTime;
class RtpAudioGraph : public QObject
{
Q_OBJECT
public:
explicit RtpAudioGraph(QCustomPlot *audioPlot, QRgb color);
void setMuted(bool isMuted);
void setHighlight(bool isHighlighted);
void setSelected(bool isSelected);
void setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted=false);
void remove(QCustomPlot *audioPlot);
bool isMyPlottable(QCPAbstractPlottable *plottable);
private:
QCPGraph *wave_;
QRgb color_;
QColor selection_color_;
};
#endif // RTP_AUDIO_GRAPH_H |
C++ | wireshark/ui/qt/widgets/splash_overlay.cpp | /* splash_overlay.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "splash_overlay.h"
#include <ui_splash_overlay.h>
#include "main_application.h"
#include <QPainter>
#include "ui/util.h"
#include <wsutil/utf8_entities.h>
#include <ui/qt/utils/tango_colors.h>
#ifdef HAVE_LUA
#include "epan/wslua/init_wslua.h"
#endif
#include "extcap.h"
// Uncomment to slow the update progress
//#define THROTTLE_STARTUP 1
/*
* Update frequency for the splash screen, given in milliseconds.
*/
const int info_update_freq_ = 65; // ~15 fps
void splash_update(register_action_e action, const char *message, void *) {
emit mainApp->registerUpdate(action, message);
}
SplashOverlay::SplashOverlay(QWidget *parent) :
QWidget(parent),
so_ui_(new Ui::SplashOverlay),
last_action_(RA_NONE),
register_cur_(0)
{
so_ui_->setupUi(this);
int register_max = RA_BASE_COUNT;
#ifdef HAVE_LUA
register_max++;
#endif
register_max++;
so_ui_->progressBar->setMaximum(register_max);
elapsed_timer_.start();
QColor bg = QColor(tango_aluminium_6);
bg.setAlphaF(0.2f);
QPalette pal;
pal.setColor(QPalette::Window, bg);
setPalette(pal);
setAutoFillBackground(true);
setStyleSheet(QString(
"QFrame#progressBand {"
" background: %1;"
"}"
"QLabel {"
" color: white;"
" background: transparent;"
"}"
"QProgressBar {"
" height: 1em;"
" width: 20em;"
" border: 0.1em solid white;"
" border-radius: 0.2em;"
" color: white;"
" background: transparent;"
"}"
"QProgressBar::chunk {"
" width: 0.1em;"
" background: rgba(255, 255, 255, 50%);"
"}"
)
.arg(QColor(tango_aluminium_4).name()));
connect(mainApp, &MainApplication::splashUpdate, this, &SplashOverlay::splashUpdate);
}
SplashOverlay::~SplashOverlay()
{
delete so_ui_;
}
// Useful for debugging on fast machines.
#ifdef THROTTLE_STARTUP
#include <QThread>
class ThrottleThread : public QThread
{
public:
static void msleep(unsigned long msecs)
{
QThread::msleep(msecs);
}
};
#endif
void SplashOverlay::splashUpdate(register_action_e action, const char *message)
{
QString action_msg = UTF8_HORIZONTAL_ELLIPSIS;
#ifdef THROTTLE_STARTUP
ThrottleThread::msleep(10);
#endif
if (last_action_ == action && (elapsed_timer_.elapsed() < info_update_freq_)) {
// Nothing to update yet
return;
}
if (last_action_ != action) {
register_cur_++;
}
last_action_ = action;
switch(action) {
case RA_DISSECTORS:
action_msg = tr("Initializing dissectors");
break;
case RA_LISTENERS:
action_msg = tr("Initializing tap listeners");
break;
case RA_EXTCAP:
action_msg = tr("Initializing external capture plugins");
break;
case RA_REGISTER:
action_msg = tr("Registering dissectors");
break;
case RA_PLUGIN_REGISTER:
action_msg = tr("Registering plugins");
break;
case RA_HANDOFF:
action_msg = tr("Handing off dissectors");
break;
case RA_PLUGIN_HANDOFF:
action_msg = tr("Handing off plugins");
break;
case RA_LUA_PLUGINS:
action_msg = tr("Loading Lua plugins");
break;
case RA_LUA_DEREGISTER:
action_msg = tr("Removing Lua plugins");
break;
case RA_PREFERENCES:
action_msg = tr("Loading module preferences");
break;
case RA_INTERFACES:
action_msg = tr("Finding local interfaces");
break;
case RA_PREFERENCES_APPLY:
action_msg = tr("Applying changed preferences");
break;
default:
action_msg = tr("(Unknown action)");
break;
}
if (message) {
if (!strncmp(message, "proto_register_", 15))
message += 15;
else if (!strncmp(message, "proto_reg_handoff_", 18))
message += 18;
action_msg.append(" ").append(message);
}
so_ui_->actionLabel->setText(action_msg);
so_ui_->progressBar->setValue(register_cur_);
mainApp->processEvents(QEventLoop::ExcludeUserInputEvents | QEventLoop::ExcludeSocketNotifiers, 1);
elapsed_timer_.restart();
} |
C/C++ | wireshark/ui/qt/widgets/splash_overlay.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef SPLASH_OVERLAY_H
#define SPLASH_OVERLAY_H
#include <config.h>
#include <glib.h>
#include "epan/register.h"
#include <QWidget>
#include <QElapsedTimer>
void splash_update(register_action_e action, const char *message, void *dummy);
namespace Ui {
class SplashOverlay;
}
class SplashOverlay : public QWidget
{
Q_OBJECT
public:
explicit SplashOverlay(QWidget *parent = 0);
~SplashOverlay();
private:
Ui::SplashOverlay *so_ui_;
register_action_e last_action_;
int register_cur_;
QElapsedTimer elapsed_timer_;
private slots:
void splashUpdate(register_action_e action, const char *message);
};
#endif // SPLASH_OVERLAY_H |
User Interface | wireshark/ui/qt/widgets/splash_overlay.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SplashOverlay</class>
<widget class="QWidget" name="SplashOverlay">
<property name="enabled">
<bool>true</bool>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2" stretch="3,0,6">
<property name="leftMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<item>
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>53</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QFrame" name="progressBand">
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Plain</enum>
</property>
<property name="lineWidth">
<number>0</number>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>116</width>
<height>50</height>
</size>
</property>
</spacer>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="actionLabel">
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<widget class="QProgressBar" name="progressBar">
<property name="value">
<number>24</number>
</property>
<property name="textVisible">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>116</width>
<height>50</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>108</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui> |
C++ | wireshark/ui/qt/widgets/stock_icon_tool_button.cpp | /* stock_icon_tool_button.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/stock_icon_tool_button.h>
#include <ui/qt/utils/stock_icon.h>
#include <QApplication>
#include <QEvent>
#include <QMenu>
#include <QMouseEvent>
// We want nice icons that render correctly, and that are responsive
// when the user hovers and clicks them.
// Using setIcon renders correctly on normal and retina displays. It is
// not completely responsive, particularly on macOS.
// Calling setStyleSheet is responsive, but does not render correctly on
// retina displays: https://bugreports.qt.io/browse/QTBUG-36825
// Subclass QToolButton, which lets us catch events and set icons as needed.
StockIconToolButton::StockIconToolButton(QWidget * parent, QString stock_icon_name) :
QToolButton(parent)
{
setCursor(Qt::ArrowCursor);
setStockIcon(stock_icon_name);
}
void StockIconToolButton::setIconMode(QIcon::Mode mode)
{
QIcon mode_icon;
QList<QIcon::State> states = QList<QIcon::State>() << QIcon::Off << QIcon::On;
foreach (QIcon::State state, states) {
foreach (QSize size, base_icon_.availableSizes(mode, state)) {
mode_icon.addPixmap(base_icon_.pixmap(size, mode, state), mode, state);
}
}
setIcon(mode_icon);
}
void StockIconToolButton::setStockIcon(QString icon_name)
{
if (!icon_name.isEmpty()) {
icon_name_ = icon_name;
}
if (icon_name_.isEmpty()) {
return;
}
base_icon_ = StockIcon(icon_name_);
setIconMode();
}
bool StockIconToolButton::event(QEvent *event)
{
switch (event->type()) {
case QEvent::Enter:
if (isEnabled()) {
setIconMode(QIcon::Active);
}
break;
case QEvent::Leave:
if (isEnabled()) {
setIconMode();
}
break;
case QEvent::MouseButtonPress:
if (isEnabled()) {
setIconMode(QIcon::Selected);
}
break;
case QEvent::MouseButtonRelease:
setIconMode();
break;
case QEvent::ApplicationPaletteChange:
setStockIcon();
break;
default:
break;
}
return QToolButton::event(event);
} |
C/C++ | wireshark/ui/qt/widgets/stock_icon_tool_button.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef STOCKICONTOOLBUTTON_H
#define STOCKICONTOOLBUTTON_H
#include <QToolButton>
class StockIconToolButton : public QToolButton
{
public:
explicit StockIconToolButton(QWidget * parent = 0, QString stock_icon_name = QString());
void setIconMode(QIcon::Mode mode = QIcon::Normal);
void setStockIcon(QString icon_name = QString());
protected:
virtual bool event(QEvent *event);
private:
QIcon base_icon_;
QString icon_name_;
};
#endif // STOCKICONTOOLBUTTON_H |
C++ | wireshark/ui/qt/widgets/syntax_line_edit.cpp | /* syntax_line_edit.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <glib.h>
#include <epan/prefs.h>
#include <epan/proto.h>
#include <epan/dfilter/dfilter.h>
#include <epan/column.h>
#include <wsutil/utf8_entities.h>
#include <ui/qt/widgets/syntax_line_edit.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/utils/stock_icon.h>
#include <QAbstractItemView>
#include <QApplication>
#include <QCompleter>
#include <QKeyEvent>
#include <QPainter>
#include <QScrollBar>
#include <QStringListModel>
#include <QStyleOptionFrame>
#include <limits>
const int max_completion_items_ = 20;
SyntaxLineEdit::SyntaxLineEdit(QWidget *parent) :
QLineEdit(parent),
completer_(NULL),
completion_model_(NULL),
completion_enabled_(false)
{
setSyntaxState();
setMaxLength(std::numeric_limits<quint32>::max());
}
// Override setCompleter so that we don't clobber the filter text on activate.
void SyntaxLineEdit::setCompleter(QCompleter *c)
{
if (completer_)
QObject::disconnect(completer_, 0, this, 0);
completer_ = c;
if (!completer_)
return;
completer_->setWidget(this);
completer_->setCompletionMode(QCompleter::PopupCompletion);
completer_->setCaseSensitivity(Qt::CaseInsensitive);
// Completion items are not guaranteed to be sorted (recent filters +
// fields), so no setModelSorting.
completer_->setMaxVisibleItems(max_completion_items_);
QObject::connect(completer_, static_cast<void (QCompleter::*)(const QString &)>(&QCompleter::activated),
this, &SyntaxLineEdit::insertFieldCompletion);
// Auto-completion is turned on.
completion_enabled_ = true;
}
void SyntaxLineEdit::allowCompletion(bool enabled)
{
completion_enabled_ = enabled;
}
void SyntaxLineEdit::setSyntaxState(SyntaxState state) {
syntax_state_ = state;
// XXX Should we drop the background colors here in favor of ::paintEvent below?
QColor valid_bg = ColorUtils::fromColorT(&prefs.gui_text_valid);
QColor valid_fg = ColorUtils::contrastingTextColor(valid_bg);
QColor invalid_bg = ColorUtils::fromColorT(&prefs.gui_text_invalid);
QColor invalid_fg = ColorUtils::contrastingTextColor(invalid_bg);
QColor deprecated_bg = ColorUtils::fromColorT(&prefs.gui_text_deprecated);
QColor deprecated_fg = ColorUtils::contrastingTextColor(deprecated_bg);
// Try to matche QLineEdit's placeholder text color (which sets the
// alpha channel to 50%, which doesn't work in style sheets).
// Setting the foreground color lets us avoid yet another background
// color preference and should hopefully make things easier to
// distinguish for color blind folk.
QColor busy_fg = ColorUtils::alphaBlend(QApplication::palette().text(), QApplication::palette().base(), 0.5);
state_style_sheet_ = QString(
"SyntaxLineEdit[syntaxState=\"%1\"] {"
" color: %2;"
" background-color: %3;"
"}"
"SyntaxLineEdit[syntaxState=\"%4\"] {"
" color: %5;"
" background-color: %6;"
"}"
"SyntaxLineEdit[syntaxState=\"%7\"] {"
" color: %8;"
" background-color: %9;"
"}"
"SyntaxLineEdit[syntaxState=\"%10\"] {"
" color: %11;"
" background-color: %12;"
"}"
)
// CSS selector, foreground, background
.arg(Valid)
.arg(valid_fg.name())
.arg(valid_bg.name())
.arg(Invalid)
.arg(invalid_fg.name())
.arg(invalid_bg.name())
.arg(Deprecated)
.arg(deprecated_fg.name())
.arg(deprecated_bg.name())
.arg(Busy)
.arg(busy_fg.name())
.arg(palette().base().color().name())
;
setStyleSheet(style_sheet_);
}
QString SyntaxLineEdit::syntaxErrorMessage()
{
return syntax_error_message_;
}
QString SyntaxLineEdit::syntaxErrorMessageFull()
{
return syntax_error_message_full_;
}
QString SyntaxLineEdit::createSyntaxErrorMessageFull(
const QString &filter, const QString &err_msg,
qsizetype loc_start, size_t loc_length)
{
QString msg = tr("Invalid filter: %1").arg(err_msg);
if (loc_start >= 0 && loc_length >= 1) {
// Add underlined location
msg = QString("<p>%1<pre> %2\n %3^%4</pre></p>")
.arg(msg)
.arg(filter)
.arg(QString(' ').repeated(static_cast<int>(loc_start)))
.arg(QString('~').repeated(static_cast<int>(loc_length) - 1));
}
return msg;
}
QString SyntaxLineEdit::styleSheet() const {
return style_sheet_;
}
void SyntaxLineEdit::setStyleSheet(const QString &style_sheet) {
style_sheet_ = style_sheet;
QLineEdit::setStyleSheet(style_sheet_ + state_style_sheet_);
}
void SyntaxLineEdit::insertFilter(const QString &filter)
{
QString padded_filter = filter;
if (hasSelectedText()) {
backspace();
}
int pos = cursorPosition();
if (pos > 0 && !text().at(pos - 1).isSpace()) {
padded_filter.prepend(" ");
}
if (pos < text().length() - 1 && !text().at(pos + 1).isSpace()) {
padded_filter.append(" ");
}
insert(padded_filter);
}
bool SyntaxLineEdit::checkDisplayFilter(QString filter)
{
if (!completion_enabled_) {
return false;
}
if (filter.isEmpty()) {
setSyntaxState(SyntaxLineEdit::Empty);
return true;
}
dfilter_t *dfp = NULL;
df_error_t *df_err = NULL;
if (dfilter_compile(filter.toUtf8().constData(), &dfp, &df_err)) {
GSList *warn;
GPtrArray *depr = NULL;
if (dfp != NULL && (warn = dfilter_get_warnings(dfp)) != NULL) {
// FIXME Need to use a different state or rename ::Deprecated
setSyntaxState(SyntaxLineEdit::Deprecated);
/*
* We're being lazy and only printing the first warning.
* Would it be better to print all of them?
*/
syntax_error_message_ = QString(static_cast<gchar *>(warn->data));
} else if (dfp != NULL && (depr = dfilter_deprecated_tokens(dfp)) != NULL) {
// You keep using that word. I do not think it means what you think it means.
// Possible alternatives: ::Troubled, or ::Problematic maybe?
setSyntaxState(SyntaxLineEdit::Deprecated);
/*
* We're being lazy and only printing the first "problem" token.
* Would it be better to print all of them?
*/
QString token((const char *)g_ptr_array_index(depr, 0));
gchar *token_str = qstring_strdup(token.section('.', 0, 0));
header_field_info *hfi = proto_registrar_get_byalias(token_str);
if (hfi)
syntax_error_message_ = tr("\"%1\" is deprecated in favour of \"%2\". "
"See Help section 6.4.8 for details.").arg(token_str).arg(hfi->abbrev);
else
// The token_str is the message.
syntax_error_message_ = tr("%1").arg(token_str);
g_free(token_str);
} else {
setSyntaxState(SyntaxLineEdit::Valid);
}
} else {
setSyntaxState(SyntaxLineEdit::Invalid);
syntax_error_message_ = QString::fromUtf8(df_err->msg);
syntax_error_message_full_ = createSyntaxErrorMessageFull(filter, syntax_error_message_, df_err->loc.col_start, df_err->loc.col_len);
df_error_free(&df_err);
}
dfilter_free(dfp);
return true;
}
void SyntaxLineEdit::checkFieldName(QString field)
{
if (field.isEmpty()) {
setSyntaxState(SyntaxLineEdit::Empty);
return;
}
char invalid_char = proto_check_field_name(field.toUtf8().constData());
if (invalid_char) {
setSyntaxState(SyntaxLineEdit::Invalid);
} else {
checkDisplayFilter(field);
}
}
void SyntaxLineEdit::checkCustomColumn(QString fields)
{
if (fields.isEmpty()) {
setSyntaxState(SyntaxLineEdit::Empty);
return;
}
gchar **splitted_fields = g_regex_split_simple(COL_CUSTOM_PRIME_REGEX,
fields.toUtf8().constData(), G_REGEX_ANCHORED, G_REGEX_MATCH_ANCHORED);
for (guint i = 0; i < g_strv_length(splitted_fields); i++) {
if (splitted_fields[i] && *splitted_fields[i]) {
if (proto_check_field_name(splitted_fields[i]) != 0) {
setSyntaxState(SyntaxLineEdit::Invalid);
g_strfreev(splitted_fields);
return;
}
}
}
g_strfreev(splitted_fields);
checkDisplayFilter(fields);
}
void SyntaxLineEdit::checkInteger(QString number)
{
if (number.isEmpty()) {
setSyntaxState(SyntaxLineEdit::Empty);
return;
}
bool ok;
text().toInt(&ok);
if (ok) {
setSyntaxState(SyntaxLineEdit::Valid);
} else {
setSyntaxState(SyntaxLineEdit::Invalid);
}
}
bool SyntaxLineEdit::isComplexFilter(const QString &filter)
{
bool is_complex = false;
for (int i = 0; i < filter.length(); i++) {
if (!token_chars_.contains(filter.at(i))) {
is_complex = true;
break;
}
}
// Don't complete the current filter.
if (is_complex && filter.startsWith(text()) && filter.compare(text())) {
return true;
}
return false;
}
bool SyntaxLineEdit::event(QEvent *event)
{
if (event->type() == QEvent::ShortcutOverride) {
// You can't set time display formats while the display filter edit
// has focus.
// Keep shortcuts in the main window from stealing keyPressEvents
// with Ctrl+Alt modifiers from us. This is a problem for many AltGr
// combinations since they are delivered with Ctrl+Alt modifiers
// instead of Qt::Key_AltGr and they tend to match the time display
// format shortcuts.
// Uncommenting the qDebug line below prints the following here:
//
// US Keyboard:
// Ctrl+o: 79 QFlags<Qt::KeyboardModifiers>(ControlModifier) "\u000F"
// Ctrl+Alt+2: 50 QFlags<Qt::KeyboardModifiers>(ControlModifier|AltModifier) "2"
//
// Swedish (Sweden) Keyboard:
// Ctrl+o: 79 QFlags<Qt::KeyboardModifiers>(ControlModifier) "\u000F"
// Ctrl+Alt+2: 64 QFlags<Qt::KeyboardModifiers>(ControlModifier|AltModifier) "@"
// AltGr+{: 123 QFlags<Qt::KeyboardModifiers>(ControlModifier|AltModifier) "{"
QKeyEvent* key_event = static_cast<QKeyEvent*>(event);
// qDebug() << "=so" << key_event->key() << key_event->modifiers() << key_event->text();
if (key_event->modifiers() == Qt::KeyboardModifiers(Qt::ControlModifier|Qt::AltModifier)) {
event->accept();
return true;
}
}
return QLineEdit::event(event);
}
void SyntaxLineEdit::completionKeyPressEvent(QKeyEvent *event)
{
// Forward to the completer if needed...
if (completer_ && completer_->popup()->isVisible()) {
switch (event->key()) {
case Qt::Key_Enter:
case Qt::Key_Return:
break;
case Qt::Key_Tab:
focusNextChild();
break;
case Qt::Key_Escape:
case Qt::Key_Backtab:
event->ignore();
return;
default:
break;
}
}
// ...otherwise process the key ourselves.
SyntaxLineEdit::keyPressEvent(event);
if (!completion_enabled_ || !completer_ || !completion_model_ || !prefs.gui_autocomplete_filter) return;
// Do nothing on bare shift.
if ((event->modifiers() & Qt::ShiftModifier) && event->text().isEmpty()) return;
if (event->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier)) {
completer_->popup()->hide();
return;
}
QStringList sentence(splitLineUnderCursor());
Q_ASSERT(sentence.size() == 2); // (preamble, token)
buildCompletionList(sentence[1] /* token */, sentence[0] /* preamble */);
if (completion_model_->stringList().length() < 1) {
completer_->popup()->hide();
return;
}
QRect cr = cursorRect();
cr.setWidth(completer_->popup()->sizeHintForColumn(0)
+ completer_->popup()->verticalScrollBar()->sizeHint().width());
completer_->complete(cr);
}
void SyntaxLineEdit::completionFocusInEvent(QFocusEvent *event)
{
if (completer_)
completer_->setWidget(this);
SyntaxLineEdit::focusInEvent(event);
}
void SyntaxLineEdit::focusOutEvent(QFocusEvent *event)
{
if (completer_ && completer_->popup()->isVisible() && event->reason() == Qt::PopupFocusReason) {
// Pretend we still have focus so that we'll draw our cursor.
// If cursorRect() were more precise we could just draw the cursor
// during a paintEvent.
return;
}
QLineEdit::focusOutEvent(event);
}
// Add indicator icons for syntax states in order to make things more clear for
// color blind people.
void SyntaxLineEdit::paintEvent(QPaintEvent *event)
{
QStyleOptionFrame opt;
initStyleOption(&opt);
QRect cr = style()->subElementRect(QStyle::SE_LineEditContents, &opt, this);
QPainter painter(this);
// In my (gcc) testing here, if I add "background: yellow;" to the DisplayFilterCombo
// stylesheet, when building with Qt 5.15.2 the combobox background is yellow and the
// text entry area (between the bookmark and apply button) is drawn in the correct
// base color (white for light mode and black for dark mode), and the correct syntax
// color otherwise. When building with Qt 6.2.4 and 6.3.1, the combobox background is
// yellow and the text entry area is always yellow, i.e. QLineEdit isn't painting its
// background for some reason.
//
// It's not clear if this is a bug or just how things work under Qt6. Either way, it's
// easy to work around.
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
// Must match CaptureFilterEdit and DisplayFilterEdit stylesheets.
int pad = style()->pixelMetric(QStyle::PM_DefaultFrameWidth) + 1;
QRect full_cr = cr.adjusted(-pad, 0, -1, 0);
QBrush bg;
switch (syntax_state_) {
case Valid:
bg = ColorUtils::fromColorT(&prefs.gui_text_valid);
break;
case Invalid:
bg = ColorUtils::fromColorT(&prefs.gui_text_invalid);
break;
case Deprecated:
bg = ColorUtils::fromColorT(&prefs.gui_text_deprecated);
break;
default:
bg = palette().base();
break;
}
painter.fillRect(full_cr, bg);
#endif
QLineEdit::paintEvent(event);
QString si_name;
switch (syntax_state_) {
case Invalid:
si_name = "x-filter-invalid";
break;
case Deprecated:
si_name = "x-filter-deprecated";
break;
default:
return;
}
QRect sir = QRect(0, 0, 14, 14); // QIcon::paint scales, which is not what we want.
int textWidth = fontMetrics().boundingRect(text()).width();
// Qt always adds a margin of 6px between the border and text, see
// QLineEditPrivate::effectiveLeftTextMargin and
// QLineEditPrivate::sideWidgetParameters.
int margin = 2 * 6 + 1;
if (cr.width() - margin - textWidth < sir.width() || cr.height() < sir.height()) {
// No space to draw
return;
}
QIcon state_icon = StockIcon(si_name);
if (state_icon.isNull()) {
return;
}
int si_off = (cr.height() - sir.height()) / 2;
sir.moveTop(si_off);
sir.moveRight(cr.right() - si_off);
painter.save();
painter.setOpacity(0.25);
state_icon.paint(&painter, sir);
painter.restore();
}
void SyntaxLineEdit::insertFieldCompletion(const QString &completion_text)
{
if (!completer_) return;
QPoint field_coords(getTokenUnderCursor());
// Insert only if we have a matching field or if the entry is empty
if (field_coords.y() < 1 && !text().isEmpty()) {
completer_->popup()->hide();
return;
}
QString new_text = text().replace(field_coords.x(), field_coords.y(), completion_text);
setText(new_text);
setCursorPosition(field_coords.x() + static_cast<int>(completion_text.length()));
emit textEdited(new_text);
}
QPoint SyntaxLineEdit::getTokenUnderCursor()
{
if (selectionStart() >= 0) return (QPoint(0,0));
int pos = cursorPosition();
int start = pos;
int len = 0;
while (start > 0 && token_chars_.contains(text().at(start -1))) {
start--;
len++;
}
while (pos < text().length() && token_chars_.contains(text().at(pos))) {
pos++;
len++;
}
return QPoint(start, len);
}
QStringList SyntaxLineEdit::splitLineUnderCursor()
{
QPoint token_coords(getTokenUnderCursor());
// Split line into preamble and word under cursor.
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
QString preamble = text().first(token_coords.x()).trimmed();
#else
QString preamble = text().mid(0, token_coords.x()).trimmed();
#endif
// This should be trimmed already
QString token_word = text().mid(token_coords.x(), token_coords.y());
return QStringList{ preamble, token_word };
} |
C/C++ | wireshark/ui/qt/widgets/syntax_line_edit.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef SYNTAX_LINE_EDIT_H
#define SYNTAX_LINE_EDIT_H
#include <QLineEdit>
class QCompleter;
class QStringListModel;
// Autocompletion is partially implemented. Subclasses must:
// - Provide buildCompletionList
// - Call setCompletionTokenChars
class SyntaxLineEdit : public QLineEdit
{
Q_OBJECT
Q_PROPERTY(SyntaxState syntaxState READ syntaxState)
Q_ENUMS(SyntaxState)
public:
explicit SyntaxLineEdit(QWidget *parent = 0);
enum SyntaxState { Empty, Busy, Invalid, Deprecated, Valid };
SyntaxState syntaxState() const { return syntax_state_; }
void setSyntaxState(SyntaxState state = Empty);
QString syntaxErrorMessage();
// Error message with filter expression and location error.
QString syntaxErrorMessageFull();
QString styleSheet() const;
QString deprecatedToken();
void setCompleter(QCompleter *c);
QCompleter *completer() const { return completer_; }
void allowCompletion(bool enabled);
static QString createSyntaxErrorMessageFull(const QString &filter,
const QString &err_msg,
qsizetype loc_start, size_t loc_length);
public slots:
void setStyleSheet(const QString &style_sheet);
// Insert filter text at the current position, adding spaces where needed.
void insertFilter(const QString &filter);
// Built-in syntax checks. Connect textChanged to these as needed.
bool checkDisplayFilter(QString filter);
void checkFieldName(QString field);
void checkCustomColumn(QString fields);
void checkInteger(QString number);
protected:
QCompleter *completer_;
QStringListModel *completion_model_;
void setCompletionTokenChars(const QString &token_chars) { token_chars_ = token_chars; }
bool isComplexFilter(const QString &filter);
virtual void buildCompletionList(const QString &field_word, const QString &preamble) { Q_UNUSED(field_word); Q_UNUSED(preamble); }
// x = Start position, y = length
QPoint getTokenUnderCursor();
// Returns (preamble, token)
QStringList splitLineUnderCursor();
virtual bool event(QEvent *event);
void completionKeyPressEvent(QKeyEvent *event);
void completionFocusInEvent(QFocusEvent *event);
virtual void focusOutEvent(QFocusEvent *event);
virtual void paintEvent(QPaintEvent *event);
private:
SyntaxState syntax_state_;
QString style_sheet_;
QString state_style_sheet_;
QString syntax_error_message_;
QString syntax_error_message_full_;
QString token_chars_;
bool completion_enabled_;
private slots:
void insertFieldCompletion(const QString &completion_text);
signals:
};
#endif // SYNTAX_LINE_EDIT_H |
C++ | wireshark/ui/qt/widgets/tabnav_tree_view.cpp | /* tabnav_tree_view.cpp
* Tree view with saner tab navigation functionality.
*
* Copyright 2016 Peter Wu <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "tabnav_tree_view.h"
TabnavTreeView::TabnavTreeView(QWidget *parent) : QTreeView(parent)
{
}
// Note: if a QTableView is used, then this is not needed anymore since Tab
// works as "expected" (move to next cell instead of row).
// Note 2: this does not help with fields with no widget (like filename).
QModelIndex TabnavTreeView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers)
{
QModelIndex current = currentIndex();
// If an item is currently selected, interpret Next/Previous. Otherwise,
// fallback to the default selection (e.g. first row for Next).
if (current.isValid()) {
if (cursorAction == MoveNext) {
if (current.column() < model()->columnCount()) {
return current.sibling(current.row(), current.column() + 1);
}
return current;
} else if (cursorAction == MovePrevious) {
if (current.column() > 0) {
return current.sibling(current.row(), current.column() - 1);
}
return current;
}
}
return QTreeView::moveCursor(cursorAction, modifiers);
}
/*!
\fn void TabnavTreeView::currentItemChanged(QModelIndex *current, QModelIndex *previous)
This signal is emitted whenever the current item changes.
\a previous is the item that previously had the focus; \a current is the
new current item.
*/
void TabnavTreeView::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
QTreeView::currentChanged(current, previous);
emit currentItemChanged(current, previous);
} |
C/C++ | wireshark/ui/qt/widgets/tabnav_tree_view.h | /** @file
*
* Tree view with saner tab navigation functionality.
*
* Copyright 2016 Peter Wu <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef TABNAV_TREE_VIEW_H
#define TABNAV_TREE_VIEW_H
#include <config.h>
#include <QTreeView>
/**
* Like QTreeView, but instead of changing to the next row (same column) when
* pressing Tab while editing, change to the next column (same row).
*/
class TabnavTreeView : public QTreeView
{
Q_OBJECT
public:
TabnavTreeView(QWidget *parent = 0);
QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers);
protected slots:
void currentChanged(const QModelIndex ¤t, const QModelIndex &previous);
signals:
void currentItemChanged(const QModelIndex ¤t, const QModelIndex &previous);
};
#endif // TABNAV_TREE_VIEW_H |
C++ | wireshark/ui/qt/widgets/traffic_tab.cpp | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <epan/proto.h>
#include <epan/addr_resolv.h>
#include <epan/prefs.h>
#include <epan/maxmind_db.h>
#include <epan/conversation_table.h>
#include <wsutil/utf8_entities.h>
#include <wsutil/filesystem.h>
#include <ui/qt/main_application.h>
#include <ui/qt/filter_action.h>
#include <ui/qt/models/atap_data_model.h>
#include <ui/qt/utils/variant_pointer.h>
#include <ui/qt/widgets/traffic_tab.h>
#include <ui/qt/widgets/traffic_tree.h>
#include <ui/qt/widgets/traffic_types_list.h>
#include <ui/qt/widgets/detachable_tabwidget.h>
#include <QStringList>
#include <QTreeView>
#include <QList>
#include <QMap>
#include <QPushButton>
#include <QMenu>
#include <QSortFilterProxyModel>
#include <QTabBar>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QTextStream>
#include <QClipboard>
#include <QMessageBox>
#include <QUrl>
#include <QTemporaryFile>
#include <QHBoxLayout>
TabData::TabData() :
_name(QString()),
_protoId(-1)
{}
TabData::TabData(QString name, int protoId) :
_name(name),
_protoId(protoId)
{}
QString TabData::name() const
{
return _name;
}
int TabData::protoId() const
{
return _protoId;
}
TrafficTab::TrafficTab(QWidget * parent) :
DetachableTabWidget(parent)
{
_createModel = nullptr;
_createDelegate = nullptr;
_disableTaps = false;
_nameResolution = false;
setTabBasename(QString());
}
TrafficTab::~TrafficTab()
{}
void TrafficTab::setProtocolInfo(QString tableName, TrafficTypesList * trafficList, GList ** recentColumnList, ATapModelCallback createModel)
{
setTabBasename(tableName);
_allProtocols = trafficList->protocols();
if (createModel)
_createModel = createModel;
_recentColumnList = recentColumnList;
setOpenTabs(trafficList->protocols(true));
}
void TrafficTab::setDelegate(ATapCreateDelegate createDelegate)
{
if (! createDelegate)
return;
_createDelegate = createDelegate;
for (int idx = 0; idx < count(); idx++) {
if (qobject_cast<QTreeView *>(widget(idx)))
{
QTreeView * tree = qobject_cast<QTreeView *>(widget(idx));
tree->setItemDelegate(createDelegate(tree));
}
}
}
QTreeView * TrafficTab::createTree(int protoId)
{
TrafficTree * tree = new TrafficTree(tabBasename(), _recentColumnList, this);
if (_createModel) {
ATapDataModel * model = _createModel(protoId, "");
model->setParent(tree);
connect(model, &ATapDataModel::tapListenerChanged, tree, &TrafficTree::tapListenerEnabled);
model->enableTap();
if (_createDelegate)
{
tree->setItemDelegate(_createDelegate(tree));
}
TrafficDataFilterProxy * proxyModel = new TrafficDataFilterProxy(tree);
proxyModel->setSourceModel(model);
tree->setModel(proxyModel);
QItemSelectionModel * ism = new QItemSelectionModel(proxyModel, tree);
tree->setSelectionModel(ism);
connect(ism, &QItemSelectionModel::currentChanged, this, &TrafficTab::doCurrentIndexChange);
tree->applyRecentColumns();
tree->sortByColumn(0, Qt::AscendingOrder);
connect(proxyModel, &TrafficDataFilterProxy::modelReset, this, [tree]() {
if (tree->model()->rowCount() > 0) {
for (int col = 0; col < tree->model()->columnCount(); col++)
tree->resizeColumnToContents(col);
}
});
connect(proxyModel, &TrafficDataFilterProxy::modelReset, this, &TrafficTab::modelReset);
/* If the columns for the tree have changed, contact the tab. By also having the tab
* columns changed signal connecting back to the tree, it will propagate to all trees
* registered with this tab. Attention, this heavily relies on the fact, that all
* tree data models are identical */
connect(tree, &TrafficTree::columnsHaveChanged, this, &TrafficTab::columnsHaveChanged);
connect(this, &TrafficTab::columnsHaveChanged, tree, &TrafficTree::columnsChanged);
}
return tree;
}
void TrafficTab::useAbsoluteTime(bool absolute)
{
for(int idx = 0; idx < count(); idx++)
{
ATapDataModel * atdm = modelForTabIndex(idx);
if (atdm)
atdm->useAbsoluteTime(absolute);
}
}
void TrafficTab::useNanosecondTimestamps(bool nanoseconds)
{
for(int idx = 0; idx < count(); idx++)
{
ATapDataModel * atdm = modelForTabIndex(idx);
if (atdm)
atdm->useNanosecondTimestamps(nanoseconds);
}
}
void TrafficTab::disableTap()
{
for(int idx = 0; idx < count(); idx++)
{
ATapDataModel * atdm = modelForTabIndex(idx);
if (atdm)
atdm->disableTap();
}
_disableTaps = true;
emit disablingTaps();
}
void TrafficTab::setOpenTabs(QList<int> protocols)
{
QList<int> tabs = _tabs.keys();
QList<int> remove;
blockSignals(true);
foreach(int protocol, protocols)
{
if (! tabs.contains(protocol)) {
insertProtoTab(protocol, false);
}
tabs.removeAll(protocol);
}
foreach(int protocol, tabs)
removeProtoTab(protocol, false);
blockSignals(false);
emit tabsChanged(_tabs.keys());
emit retapRequired();
}
void TrafficTab::insertProtoTab(int protoId, bool emitSignals)
{
QList<int> lUsed = _tabs.keys();
if (lUsed.contains(protoId) && lUsed.count() != count())
{
_tabs.clear();
for (int idx = 0; idx < count(); idx++) {
TabData tabData = qvariant_cast<TabData>(tabBar()->tabData(idx));
_tabs.insert(tabData.protoId(), idx);
}
lUsed = _tabs.keys();
}
if (protoId <= 0 || lUsed.contains(protoId))
return;
QList<int> lFull = _allProtocols;
int idx = (int) lFull.indexOf(protoId);
if (idx < 0)
return;
QList<int> part = lFull.mid(0, idx);
int insertAt = 0;
if (part.count() > 0) {
for (int cnt = idx - 1; cnt >= 0; cnt--) {
if (lUsed.contains(part[cnt]) && part[cnt] != protoId) {
insertAt = (int) lUsed.indexOf(part[cnt]) + 1;
break;
}
}
}
QTreeView * tree = createTree(protoId);
QString tableName = proto_get_protocol_short_name(find_protocol_by_id(protoId));
TabData tabData(tableName, protoId);
QVariant storage;
storage.setValue(tabData);
if (tree->model()->rowCount() > 0)
tableName += QString(" %1 %2").arg(UTF8_MIDDLE_DOT).arg(tree->model()->rowCount());
int tabId = -1;
if (insertAt > -1)
tabId = insertTab(insertAt, tree, tableName);
else
tabId = addTab(tree, tableName);
if (tabId >= 0)
tabBar()->setTabData(tabId, storage);
/* We reset the correct tab idxs. That operations is costly, but it is only
* called during this operation and ensures, that other operations do not
* need to iterate, but rather can lookup the indeces. */
_tabs.clear();
for (int idx = 0; idx < count(); idx++) {
TabData tabData = qvariant_cast<TabData>(tabBar()->tabData(idx));
_tabs.insert(tabData.protoId(), idx);
}
if (emitSignals) {
emit tabsChanged(_tabs.keys());
emit retapRequired();
}
}
void TrafficTab::removeProtoTab(int protoId, bool emitSignals)
{
if (_tabs.keys().contains(protoId)) {
for(int idx = 0; idx < count(); idx++) {
TabData tabData = qvariant_cast<TabData>(tabBar()->tabData(idx));
if (protoId == tabData.protoId()) {
removeTab(idx);
break;
}
}
}
/* We reset the correct tab idxs. That operations is costly, but it is only
* called during this operation and ensures, that other operations do not
* need to iterate, but rather can lookup the indeces. */
_tabs.clear();
for (int idx = 0; idx < count(); idx++) {
TabData tabData = qvariant_cast<TabData>(tabBar()->tabData(idx));
_tabs.insert(tabData.protoId(), idx);
}
if (emitSignals) {
emit tabsChanged(_tabs.keys());
emit retapRequired();
}
}
void TrafficTab::doCurrentIndexChange(const QModelIndex & cur, const QModelIndex &)
{
if (! cur.isValid())
return;
const TrafficDataFilterProxy * proxy = qobject_cast<const TrafficDataFilterProxy *>(cur.model());
if (! proxy)
return;
ATapDataModel * model = qobject_cast<ATapDataModel *>(proxy->sourceModel());
if (! model)
return;
int tabId = _tabs[model->protoId()];
emit tabDataChanged(tabId);
}
QVariant TrafficTab::currentItemData(int role)
{
QTreeView * tree = qobject_cast<QTreeView *>(currentWidget());
if (tree) {
QModelIndex idx = tree->selectionModel()->currentIndex();
/* In case no selection has been made yet, we select the topmostleft index,
* to ensure proper handling. Especially ConversationDialog depends on this
* method always returning data */
if (!idx.isValid()) {
ATapDataModel * model = modelForTabIndex(currentIndex());
idx = model->index(0, 0);
}
return idx.data(role);
}
return QVariant();
}
void TrafficTab::modelReset()
{
if (! qobject_cast<TrafficDataFilterProxy *>(sender()))
return;
TrafficDataFilterProxy * qsfpm = qobject_cast<TrafficDataFilterProxy *>(sender());
if (!qsfpm || ! qobject_cast<ATapDataModel *>(qsfpm->sourceModel()))
return;
ATapDataModel * atdm = qobject_cast<ATapDataModel *>(qsfpm->sourceModel());
int protoId = atdm->protoId();
if (!_tabs.keys().contains(protoId))
return;
int tabIdx = _tabs[protoId];
TabData tabData = qvariant_cast<TabData>(tabBar()->tabData(tabIdx));
if (tabData.protoId() == protoId) {
if (qsfpm->rowCount() == 0)
setTabText(tabIdx, tabData.name());
else
setTabText(tabIdx, tabData.name() + QString(" %1 %2").arg(UTF8_MIDDLE_DOT).arg(qsfpm->rowCount()));
}
emit tabDataChanged(tabIdx);
}
ATapDataModel * TrafficTab::modelForTabIndex(int tabIdx)
{
if (tabIdx == -1)
tabIdx = currentIndex();
return modelForWidget(widget(tabIdx));
}
ATapDataModel * TrafficTab::modelForWidget(QWidget * searchWidget)
{
if (qobject_cast<QTreeView *>(searchWidget)) {
QTreeView * tree = qobject_cast<QTreeView *>(searchWidget);
if (qobject_cast<TrafficDataFilterProxy *>(tree->model())) {
TrafficDataFilterProxy * qsfpm = qobject_cast<TrafficDataFilterProxy *>(tree->model());
if (qsfpm && qobject_cast<ATapDataModel *>(qsfpm->sourceModel())) {
return qobject_cast<ATapDataModel *>(qsfpm->sourceModel());
}
}
}
return nullptr;
}
void TrafficTab::setFilter(QString filter)
{
for (int idx = 0; idx < count(); idx++ )
{
ATapDataModel * atdm = modelForTabIndex(idx);
if (! atdm)
continue;
atdm->setFilter(filter);
}
}
void TrafficTab::setNameResolution(bool checked)
{
if (checked == _nameResolution)
return;
for (int idx = 0; idx < count(); idx++ )
{
ATapDataModel * atdm = modelForTabIndex(idx);
if (! atdm)
continue;
atdm->setResolveNames(checked);
}
_nameResolution = checked;
/* Send the signal, that all tabs have potentially changed */
emit tabDataChanged(-1);
}
bool TrafficTab::hasNameResolution(int tabIdx)
{
int tab = tabIdx == -1 || tabIdx >= count() ? currentIndex() : tabIdx;
ATapDataModel * dataModel = modelForTabIndex(tab);
if (! dataModel)
return false;
return dataModel->allowsNameResolution();
}
QMenu * TrafficTab::createCopyMenu(QWidget *parent)
{
TrafficTree * tree = qobject_cast<TrafficTree *>(currentWidget());
if ( ! tree)
return nullptr;
return tree->createCopyMenu(parent);
}
#ifdef HAVE_MAXMINDDB
bool TrafficTab::hasGeoIPData(int tabIdx)
{
int tab = tabIdx == -1 || tabIdx >= count() ? currentIndex() : tabIdx;
ATapDataModel * dataModel = modelForTabIndex(tab);
return dataModel->hasGeoIPData();
}
bool
TrafficTab::writeGeoIPMapFile(QFile * fp, bool json_only, ATapDataModel * dataModel)
{
QTextStream out(fp);
if (!json_only) {
QFile ipmap(get_datafile_path("ipmap.html"));
if (!ipmap.open(QIODevice::ReadOnly)) {
QMessageBox::warning(this, tr("Map file error"), tr("Could not open base file %1 for reading: %2")
.arg(get_datafile_path("ipmap.html"))
.arg(g_strerror(errno))
);
return false;
}
/* Copy ipmap.html to map file. */
QTextStream in(&ipmap);
QString line;
while (in.readLineInto(&line)) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
out << line << Qt::endl;
#else
out << line << endl;
#endif
}
out << QString("<script id=\"ipmap-data\" type=\"application/json\">\n");
}
/*
* Writes a feature for each resolved address, the output will look like:
* {
* "type": "FeatureCollection",
* "features": [
* {
* "type": "Feature",
* "geometry": {
* "type": "Point",
* "coordinates": [ -97.821999, 37.750999 ]
* },
* "properties": {
* "ip": "8.8.4.4",
* "autonomous_system_number": 15169,
* "autonomous_system_organization": "Google LLC",
* "city": "(omitted, but key is shown for documentation reasons)",
* "country": "United States",
* "radius": 1000,
* "packets": 1,
* "bytes": 1543
* }
* }
* ]
* }
*/
QJsonObject root;
root["type"] = "FeatureCollection";
QJsonArray features;
/* Append map data. */
for(int row = 0; row < dataModel->rowCount(QModelIndex()); row++)
{
QModelIndex index = dataModel->index(row, 0);
const mmdb_lookup_t * result = VariantPointer<const mmdb_lookup_t>::asPtr(dataModel->data(index, ATapDataModel::GEODATA_LOOKUPTABLE));
if (!maxmind_db_has_coords(result)) {
// result could be NULL if the caller did not trigger a lookup
// before. result->found could be FALSE if no MMDB entry exists.
continue;
}
QJsonObject arrEntry;
arrEntry["type"] = "Feature";
QJsonObject geometry;
geometry["type"] = "Point";
QJsonArray coordinates;
coordinates.append(QJsonValue(result->longitude));
coordinates.append(QJsonValue(result->latitude));
geometry["coordinates"] = coordinates;
arrEntry["geometry"] = geometry;
QJsonObject property;
property["ip"] = dataModel->data(index, ATapDataModel::GEODATA_ADDRESS).toString();
if (result->as_number && result->as_org) {
property["autonomous_system_number"] = QJsonValue((int)(result->as_number));
property["autonomous_system_organization"] = QJsonValue(result->as_org);
}
if (result->city)
property["city"] = result->city;
if (result->country)
property["country"] = result->country;
if (result->accuracy)
property["radius"] = QJsonValue(result->accuracy);
if (qobject_cast<EndpointDataModel *>(dataModel)) {
EndpointDataModel * endpointModel = qobject_cast<EndpointDataModel *>(dataModel);
property["packets"] = endpointModel->data(endpointModel->index(row, EndpointDataModel::ENDP_COLUMN_PACKETS)).toString();
property["bytes"] = endpointModel->data(endpointModel->index(row, EndpointDataModel::ENDP_COLUMN_BYTES)).toString();
}
arrEntry["properties"] = property;
features.append(arrEntry);
}
root["features"] = features;
QJsonDocument doc;
doc.setObject(root);
out << doc.toJson();
if (!json_only)
out << QString("</script>\n");
out.flush();
return true;
}
QUrl TrafficTab::createGeoIPMap(bool json_only, int tabIdx)
{
int tab = tabIdx == -1 || tabIdx >= count() ? currentIndex() : tabIdx;
ATapDataModel * dataModel = modelForTabIndex(tab);
if (! (dataModel && dataModel->hasGeoIPData())) {
QMessageBox::warning(this, tr("Map file error"), tr("No endpoints available to map"));
return QUrl();
}
QString tempname = QString("%1/ipmapXXXXXX.html").arg(QDir::tempPath());
QTemporaryFile tf(tempname);
if (!tf.open()) {
QMessageBox::warning(this, tr("Map file error"), tr("Unable to create temporary file"));
return QUrl();
}
if (!writeGeoIPMapFile(&tf, json_only, dataModel)) {
tf.close();
return QUrl();
}
tf.setAutoRemove(false);
return QUrl::fromLocalFile(tf.fileName());
}
#endif
void TrafficTab::detachTab(int tabIdx, QPoint pos) {
ATapDataModel * model = modelForTabIndex(tabIdx);
if (!model)
return;
TrafficTree * tree = qobject_cast<TrafficTree *>(widget(tabIdx));
if (!tree)
return;
connect(this, &TrafficTab::disablingTaps ,tree , &TrafficTree::disableTap);
DetachableTabWidget::detachTab(tabIdx, pos);
removeProtoTab(model->protoId());
}
void TrafficTab::attachTab(QWidget * content, QString name)
{
ATapDataModel * model = modelForWidget(content);
if (!model) {
attachTab(content, name);
return;
}
insertProtoTab(model->protoId());
} |
C/C++ | wireshark/ui/qt/widgets/traffic_tab.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef TRAFFIC_TAB_H
#define TRAFFIC_TAB_H
#include "config.h"
#include <glib.h>
#include <ui/qt/models/atap_data_model.h>
#include <ui/qt/filter_action.h>
#include <ui/qt/widgets/detachable_tabwidget.h>
#include <ui/qt/widgets/traffic_types_list.h>
#include <QTabWidget>
#include <QTreeView>
#include <QFile>
#include <QUrl>
#include <QAbstractItemDelegate>
#include <QSortFilterProxyModel>
/**
* @brief Callback for creating an ATapDataModel
*
* @param protoId the protocol id for the callback to use
* @param filter setting the filter for the tap
* @return either null, if no model could be created, or an instance
* of the model itself.
*/
typedef ATapDataModel * (*ATapModelCallback)(int protoId, QString filter);
/**
* @brief Callback for creating an item delegate
*
* @param parent the parent for the delegate to attach to
* @return either null if no delegate had been created, or an instance for
* the delegate
*/
typedef QAbstractItemDelegate * (*ATapCreateDelegate)(QWidget * parent);
class TabData
{
public:
TabData();
TabData(const TabData &) = default;
TabData &operator=(const TabData &) = default;
TabData(QString name, int proto);
QString name() const;
int protoId() const;
private:
QString _name;
int _protoId;
};
Q_DECLARE_METATYPE(TabData)
/**
* @brief A QTabWidget class, providing tap information
*
* This class combines all required information, to display tapped data
* to the user. Specifically it handles all model data internally, therefore
* removing the need of the dialog to know how data is being stored or
* generated.
*/
class TrafficTab : public DetachableTabWidget
{
Q_OBJECT
public:
TrafficTab(QWidget *parent = nullptr);
virtual ~TrafficTab();
/**
* @brief Set the Protocol Info for the traffic tab
*
* This has to be called right after instantiating the class. The reason this is not
* done inside the constructor is such, that the object can be used with Qt Designer
* without having to removing the predefined object during setup of the UI.
*
* @param tableName The name for the table. Used for the protocol selection button
* @param trafficList an element of traffictypeslist, which handles all profile selections
* @param recentColumnList a list of columns to be displayed for this traffic type
* @param createModel A callback, which will create the correct model for the trees
*
* @see ATapModelCallback
*/
void setProtocolInfo(QString tableName, TrafficTypesList * trafficList, GList ** recentColumnList, ATapModelCallback createModel);
/**
* @brief Set the Delegate object for the tab. It will apply for all
* models residing in this tab object
*
* @param createDelegate the callback for the delegate creation
*
* @see ATapCreateDelegate
*/
void setDelegate(ATapCreateDelegate createDelegate);
/**
* @brief Set the filter or remove it by providing an empty filter
*
* This differs from filtering the model itself in such a way, that filtering is
* being done using the epan system. Therefore, once filtered, the only way to get
* all elements back is to set an empty string.
*
* @note Filtering will only work, as long as the capture file remains open. If
* taps have been disabled and capture has stopped, filtering will no longer work.
*
* @param filter the string to be filtered on
*/
void setFilter(QString filter = QString());
/**
* @brief Enable/Disable name resolution for the address column
*
* @param checked true to enable name resolution
*/
void setNameResolution(bool checked);
/**
* @brief Disables the taps for this traffic tab.
*
* Disables all taps for models used by this traffic tab. They cannot be re-enabled on purpose,
* as in most cases, disabling them is being done during closing of the original capture file.
* This also disabled all filter actions, as well as the tap selection button.
*/
void disableTap();
/**
* @brief Create a menu containing clipboard copy entries for this tab
*
* It will create all entries, including copying the content of the currently selected tab
* to CSV, YAML and JSON
*
* @param parent the parent object or null
* @return QMenu* the resulting menu or null
*/
QMenu * createCopyMenu(QWidget * parent = nullptr);
/**
* @brief Checks, wether the given tabpage support name resolution on the address column
*
* @param tabIdx the index of the page. If it is out of bounds or < 0, the current index is being used
* @return true if name resolution is being supported
* @return false if name resolution is not supported
*/
bool hasNameResolution(int tabIdx = -1);
#ifdef HAVE_MAXMINDDB
/**
* @brief Checks, wether the given tabpage support GeoIP data
*
* @param tabIdx the index of the page. If it is out of bounds or < 0, the current index is being used
* @return true if geoIP data is being supported
* @return false if geoIP data is not supported
*/
bool hasGeoIPData(int tabIdx = -1);
/**
* @brief Create a map of GeoIP data and write it to a temporary file
*
* @param onlyJSON only put the json content into the temporary file
* @param tabIdx the index of the page. If it is out of bounds or < 0, the current index is being used
* @return The path to the temporary file for the data
*/
QUrl createGeoIPMap(bool onlyJSON, int tabIdx = -1);
#endif
/**
* @brief Return the itemData for the currently selected index in the currently
* displayed treeview.
*
* @param role the role to be used, defaults to Qt::DisplayRole
* @return QVariant the resulting value as QVariant type
*/
QVariant currentItemData(int role = Qt::DisplayRole);
/**
* @brief Use nanosecond timestamps if requested
*
* @param useNSTime use nanosecond timestamps if required and requested
*/
void useNanosecondTimestamps(bool useNSTime);
public slots:
/**
* @brief Use absolute time for the time columns
*
* @param absolute true if absolute time should be used
*/
void useAbsoluteTime(bool absolute);
void setOpenTabs(QList<int> protocols);
signals:
void filterAction(QString filter, FilterAction::Action action, FilterAction::ActionType type);
void tabDataChanged(int idx);
void retapRequired();
void disablingTaps();
void tabsChanged(QList<int> protocols);
void columnsHaveChanged(QList<int> columns);
protected slots:
virtual void detachTab(int idx, QPoint pos) override;
virtual void attachTab(QWidget * content, QString name) override;
private:
QList<int> _allProtocols;
QMap<int, int> _tabs;
ATapModelCallback _createModel;
ATapCreateDelegate _createDelegate;
GList ** _recentColumnList;
bool _disableTaps;
bool _nameResolution;
QTreeView * createTree(int protoId);
ATapDataModel * modelForTabIndex(int tabIdx = -1);
ATapDataModel * modelForWidget(QWidget * widget);
void insertProtoTab(int protoId, bool emitSignals = true);
void removeProtoTab(int protoId, bool emitSignals = true);
#ifdef HAVE_MAXMINDDB
bool writeGeoIPMapFile(QFile * fp, bool json_only, ATapDataModel * dataModel);
#endif
private slots:
void modelReset();
void doCurrentIndexChange(const QModelIndex & cur, const QModelIndex & prev);
};
#endif // TRAFFIC_TAB_H |
C++ | wireshark/ui/qt/widgets/traffic_tree.cpp | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <epan/proto.h>
#include <epan/addr_resolv.h>
#include <epan/prefs.h>
#include <epan/maxmind_db.h>
#include <epan/conversation_table.h>
#include <wsutil/utf8_entities.h>
#include <wsutil/filesystem.h>
#include <wsutil/str_util.h>
#include "ui/recent.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/main_application.h>
#include <ui/qt/main_window.h>
#include <ui/qt/filter_action.h>
#include <ui/qt/models/atap_data_model.h>
#include <ui/qt/utils/variant_pointer.h>
#include <ui/qt/widgets/traffic_tab.h>
#include <ui/qt/widgets/traffic_tree.h>
#include <QStringList>
#include <QTreeView>
#include <QList>
#include <QMap>
#include <QMenu>
#include <QSortFilterProxyModel>
#include <QTextStream>
#include <QClipboard>
#include <QMessageBox>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QHeaderView>
#include <QWidgetAction>
#include <QLineEdit>
#include <QActionGroup>
#include <QDateTime>
#include <QTime>
MenuEditAction::MenuEditAction(QString text, QString hintText, QObject * parent) :
QWidgetAction(parent),
_hintText(hintText),
_text(text),
_lineEdit(nullptr)
{}
QWidget * MenuEditAction::createWidget(QWidget *parent) {
_lineEdit = new QLineEdit(parent);
_lineEdit->setAlignment(Qt::AlignRight);
_lineEdit->setText(_text);
_lineEdit->setPlaceholderText(_hintText);
connect(_lineEdit, &QLineEdit::returnPressed, this, &MenuEditAction::triggerEntry);
return _lineEdit;
}
void MenuEditAction::triggerEntry() {
if (_lineEdit)
_text = _lineEdit->text();
emit trigger();
}
QString MenuEditAction::text() const {
return _text;
}
TrafficTreeHeaderView::TrafficTreeHeaderView(GList ** recentColumnList, QWidget * parent):
QHeaderView(Qt::Horizontal, parent)
{
_recentColumnList = recentColumnList;
setContextMenuPolicy(Qt::CustomContextMenu);
_actions = new QActionGroup(this);
QAction * filterAction = _actions->addAction(tr("Less than"));
filterAction->setCheckable(true);
filterAction->setChecked(true);
filterAction->setProperty("filter_action", (int)TrafficDataFilterProxy::TRAFFIC_DATA_LESS);
filterAction = _actions->addAction(tr("Greater than"));
filterAction->setCheckable(true);
filterAction->setProperty("filter_action", (int)TrafficDataFilterProxy::TRAFFIC_DATA_GREATER);
filterAction = _actions->addAction(tr("Equal"));
filterAction->setCheckable(true);
filterAction->setProperty("filter_action", (int)TrafficDataFilterProxy::TRAFFIC_DATA_EQUAL);
connect(this, &QHeaderView::customContextMenuRequested, this, &TrafficTreeHeaderView::headerContextMenu);
}
TrafficTreeHeaderView::~TrafficTreeHeaderView()
{}
void TrafficTreeHeaderView::headerContextMenu(const QPoint &pos)
{
TrafficTree * tree = qobject_cast<TrafficTree *>(parent());
if (!tree)
return;
TrafficDataFilterProxy * proxy = qobject_cast<TrafficDataFilterProxy *>(tree->model());
if (sender() != this || ! proxy)
return;
QMenu * ctxMenu = new QMenu(this);
ctxMenu->setAttribute(Qt::WA_DeleteOnClose);
QAction * headerAction = ctxMenu->addAction(tr("Columns to display"));
headerAction->setEnabled(false);
for (int col = 0; col < tree->dataModel()->columnCount(); col++)
{
QString name = tree->dataModel()->headerData(col).toString();
QAction * action = new QAction(name);
action->setCheckable(true);
action->setChecked(proxy->columnVisible(col));
action->setProperty("col_nr", col);
ctxMenu->addAction(action);
connect(action, &QAction::triggered, this, &TrafficTreeHeaderView::columnTriggered);
}
ctxMenu->addSeparator();
int column = logicalIndexAt(pos);
bool is_address = false;
QModelIndex sourceIdx = proxy->mapToSource(proxy->index(0, column));
if (qobject_cast<EndpointDataModel *>(proxy->sourceModel()) && sourceIdx.column() == EndpointDataModel::ENDP_COLUMN_ADDR) {
is_address = true;
} else if (qobject_cast<ConversationDataModel *>(proxy->sourceModel()) && (sourceIdx.column() == ConversationDataModel::CONV_COLUMN_SRC_ADDR ||
sourceIdx.column() == ConversationDataModel::CONV_COLUMN_DST_ADDR)) {
is_address = true;
}
if (! is_address) {
QString columnText = model()->headerData(column, Qt::Horizontal).toString();
QAction * filterAction = ctxMenu->addAction(tr("Filter %1 by").arg(columnText));
filterAction->setEnabled(false);
ctxMenu->addActions(_actions->actions());
MenuEditAction * editAction = new MenuEditAction(_filterText, tr("Enter filter value"));
editAction->setProperty("column", column);
ctxMenu->addAction(editAction);
connect(editAction, &MenuEditAction::triggered, this, &TrafficTreeHeaderView::filterColumn);
}
connect(ctxMenu, &QMenu::triggered, this, &TrafficTreeHeaderView::menuActionTriggered);
ctxMenu->popup(mapToGlobal(pos));
}
void TrafficTreeHeaderView::applyRecent()
{
TrafficTree * tree = qobject_cast<TrafficTree *>(parent());
if (!tree)
return;
QList<int> columns;
for (GList * endTab = *_recentColumnList; endTab; endTab = endTab->next) {
QString colStr = QString((const char *)endTab->data);
bool ok = false;
int col = colStr.toInt(&ok);
if (ok)
columns << col;
}
if (columns.count() > 0) {
TrafficDataFilterProxy * proxy = qobject_cast<TrafficDataFilterProxy *>(tree->model());
for (int col = 0; col < tree->dataModel()->columnCount(); col++) {
proxy->setColumnVisibility(col, columns.contains(col));
}
}
}
void TrafficTreeHeaderView::columnTriggered(bool checked)
{
TrafficTree * tree = qobject_cast<TrafficTree *>(parent());
if (!tree)
return;
TrafficDataFilterProxy * proxy = qobject_cast<TrafficDataFilterProxy *>(tree->model());
QAction * entry = qobject_cast<QAction *>(sender());
if (! proxy || ! entry || ! entry->property("col_nr").isValid())
return;
int col = entry->property("col_nr").toInt();
proxy->setColumnVisibility(col, checked);
prefs_clear_string_list(*_recentColumnList);
*_recentColumnList = NULL;
QList<int> visible;
for (int col = 0; col < tree->dataModel()->columnCount(); col++) {
if (proxy->columnVisible(col)) {
visible << col;
gchar *nr = qstring_strdup(QString::number(col));
*_recentColumnList = g_list_append(*_recentColumnList, nr);
}
}
emit columnsHaveChanged(visible);
}
void TrafficTreeHeaderView::menuActionTriggered(QAction * act)
{
if (_actions && _actions->actions().contains(act)) {
QMenu * menu = qobject_cast<QMenu *>(sender());
if (menu) {
MenuEditAction * menuAction = nullptr;
foreach(QAction * _act, menu->actions()) {
if (qobject_cast<MenuEditAction *>(_act)) {
menuAction = qobject_cast<MenuEditAction *>(_act);
break;
}
}
int column = menuAction ? menuAction->property("column").toInt() : -1;
if (column >= 0) {
_filterText = menuAction->text().trimmed();
if (_filterText.length() == 0)
column = -1;
int filterOn = act->property("filter_action").toInt();
emit filterOnColumn(column, filterOn, _filterText);
}
}
}
}
void TrafficTreeHeaderView::filterColumn(bool)
{
MenuEditAction * menuAction = qobject_cast<MenuEditAction *>(sender());
if (!menuAction)
return;
int filterOn = TrafficDataFilterProxy::TRAFFIC_DATA_LESS;
foreach(QAction * act, _actions->actions()) {
if (act->isChecked() && act->property("filter_action").isValid()) {
filterOn = act->property("filter_action").toInt();
break;
}
}
int column = menuAction->property("column").toInt();
_filterText = menuAction->text().trimmed();
if (_filterText.length() == 0)
column = -1;
emit filterOnColumn(column, filterOn, _filterText);
}
TrafficDataFilterProxy::TrafficDataFilterProxy(QObject *parent) :
QSortFilterProxyModel(parent),
_filterColumn(-1),
_filterOn(-1),
_filterText(QString())
{
setSortRole(ATapDataModel::UNFORMATTED_DISPLAYDATA);
}
void TrafficDataFilterProxy::filterForColumn(int column, int filterOn, QString filterText)
{
if (filterOn < 0 || filterOn > TrafficDataFilterProxy::TRAFFIC_DATA_EQUAL)
column = -1;
_filterColumn = mapToSourceColumn(column);
_filterOn = filterOn;
_filterText = filterText;
invalidateFilter();
}
int TrafficDataFilterProxy::mapToSourceColumn(int proxyColumn) const
{
ATapDataModel * model = qobject_cast<ATapDataModel *>(sourceModel());
if (!model || proxyColumn == -1) {
return proxyColumn;
}
if (rowCount() > 0) {
return mapToSource(index(0, proxyColumn)).column();
}
/* mapToSource() requires a valid QModelIndex, and thus does not work when
* all rows are filtered out by the current filter. (E.g., the user has
* accidentally entered an incorrect filter or operator and wants to fix
* it.) Since our filterAcceptsColumn doesn't depend on the row, we can
* determine the mapping between the currently displayed column number and
* the column number in the model this way, even if no rows are displayed.
* It is linear time in the number of columns, though.
*/
int currentProxyColumn = 0;
for (int column=0; column < model->columnCount(); ++column) {
if (filterAcceptsColumn(column, QModelIndex())) {
if (currentProxyColumn++ == proxyColumn) {
return column;
}
}
}
return -1;
}
bool TrafficDataFilterProxy::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
ATapDataModel * dataModel = qobject_cast<ATapDataModel *>(sourceModel());
if (dataModel) {
bool isFiltered = dataModel->data(dataModel->index(source_row, 0), ATapDataModel::ROW_IS_FILTERED).toBool();
if (isFiltered && dataModel->filter().length() > 0)
return false;
/* XXX: What if the filter column is now hidden? Should the filter
* still apply or should it be cleared? Right now it is still applied.
*/
QModelIndex srcIdx = dataModel->index(source_row, _filterColumn);
if (srcIdx.isValid()) {
QVariant data = srcIdx.data(ATapDataModel::UNFORMATTED_DISPLAYDATA);
bool filtered = false;
/* QVariant comparisons coerce to the first parameter type, so
* putting data first and converting the string to it is important.
*/
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
/* QVariant::compare coerces strings to numeric types, but does
* not try to automatically convert them to datetime related types.
*/
QVariant rhs = QVariant(_filterText);
if (data.userType() == QMetaType::QDateTime) {
/* Try to parse with a date included in the filter, and
* fallback to time only if that fails.
*/
QDateTime filter_dt = QDateTime::fromString(_filterText, Qt::ISODateWithMs);
if (filter_dt.isValid()) {
rhs.setValue(filter_dt);
} else {
QTime filterTime = QTime::fromString(_filterText, Qt::ISODateWithMs);
if (filterTime.isValid()) {
rhs.setValue(filterTime);
data.setValue(data.toTime());
} else {
rhs = QVariant();
}
}
}
QPartialOrdering result = QVariant::compare(data, rhs);
if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_LESS)
filtered = result < 0;
else if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_GREATER)
filtered = result > 0;
else if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_EQUAL)
filtered = result == 0;
#else
/* The comparisons are deprecated in 5.15. This is most of the
* implementation of QAbstractItemModelPrivate::isVariantLessThan
* from the Qt source.
*/
if (_filterText.isEmpty())
filtered = true;
else if (data.isNull())
filtered = false;
else {
switch (data.userType()) {
case QMetaType::Int:
case QMetaType::UInt:
case QMetaType::LongLong:
if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_LESS)
filtered = data.toLongLong() < _filterText.toLongLong();
else if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_GREATER)
filtered = data.toLongLong() > _filterText.toLongLong();
else if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_EQUAL)
filtered = data.toLongLong() == _filterText.toLongLong();
break;
case QMetaType::Float:
case QMetaType::Double:
if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_LESS)
filtered = data.toDouble() < _filterText.toDouble();
else if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_GREATER)
filtered = data.toDouble() > _filterText.toDouble();
else if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_EQUAL)
filtered = data.toDouble() == _filterText.toDouble();
break;
case QMetaType::QDateTime:
{
/* Try to parse with a date included, and fall back to time
* only if that fails.
*/
QDateTime filter_dt = QDateTime::fromString(_filterText, Qt::ISODateWithMs);
if (filter_dt.isValid()) {
if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_LESS)
filtered = data.toDateTime() < filter_dt;
else if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_GREATER)
filtered = data.toDateTime() > filter_dt;
else if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_EQUAL)
filtered = data.toDateTime() == filter_dt;
break;
}
}
/* FALLTHROUGH */
case QMetaType::QTime:
{
QTime filter_t = QTime::fromString(_filterText, Qt::ISODateWithMs);
if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_LESS)
filtered = data.toTime() < filter_t;
else if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_GREATER)
filtered = data.toTime() > filter_t;
else if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_EQUAL)
filtered = data.toTime() == filter_t;
break;
}
case QMetaType::QString:
default:
/* XXX: We don't do UTF-8 aware coallating in Packet List
* (because it's slow), but possibly could here.
*/
if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_LESS)
filtered = data.toString() < _filterText;
else if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_GREATER)
filtered = data.toString() > _filterText;
else if (_filterOn == TrafficDataFilterProxy::TRAFFIC_DATA_EQUAL)
filtered = data.toString() == _filterText;
break;
}
}
#endif
if (!filtered)
return false;
}
}
return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent);
}
bool TrafficDataFilterProxy::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
{
if (! source_left.isValid() || ! qobject_cast<const ATapDataModel *>(source_left.model()))
return false;
if (! source_right.isValid() || ! qobject_cast<const ATapDataModel *>(source_right.model()))
return false;
ATapDataModel * model = qobject_cast<ATapDataModel *>(sourceModel());
if (! model || source_left.model() != model || source_right.model() != model)
return false;
QVariant datA = source_left.data(ATapDataModel::UNFORMATTED_DISPLAYDATA);
QVariant datB = source_right.data(ATapDataModel::UNFORMATTED_DISPLAYDATA);
bool is_address = false;
if (qobject_cast<EndpointDataModel *>(model) && source_left.column() == EndpointDataModel::ENDP_COLUMN_ADDR &&
source_left.column() == source_right.column()) {
is_address = true;
} else if (qobject_cast<ConversationDataModel *>(model) && (source_left.column() == ConversationDataModel::CONV_COLUMN_SRC_ADDR ||
source_left.column() == ConversationDataModel::CONV_COLUMN_DST_ADDR) && source_left.column() == source_right.column()) {
is_address = true;
}
if (is_address) {
bool result = false;
bool identical = false;
int addressTypeA = model->data(source_left, ATapDataModel::DATA_ADDRESS_TYPE).toInt();
int addressTypeB = model->data(source_right, ATapDataModel::DATA_ADDRESS_TYPE).toInt();
if (addressTypeA != 0 && addressTypeB != 0 && addressTypeA != addressTypeB) {
result = addressTypeA < addressTypeB;
} else if (addressTypeA != 0 && addressTypeA == addressTypeB) {
if (addressTypeA == AT_IPv4) {
quint32 valA = model->data(source_left, ATapDataModel::DATA_IPV4_INTEGER).value<quint32>();
quint32 valB = model->data(source_right, ATapDataModel::DATA_IPV4_INTEGER).value<quint32>();
result = valA < valB;
identical = valA == valB;
} else if (addressTypeA == AT_NUMERIC) {
quint32 valA = datA.toInt();
quint32 valB = datB.toInt();
result = valA < valB;
identical = valA == valB;
} else {
result = QString::compare(datA.toString(), datB.toString(), Qt::CaseInsensitive) < 0;
identical = QString::compare(datA.toString(), datB.toString(), Qt::CaseInsensitive) == 0;
}
int portColumn = EndpointDataModel::ENDP_COLUMN_PORT;
if (identical && qobject_cast<ConversationDataModel *>(model)) {
QModelIndex tstA, tstB;
if (source_left.column() == ConversationDataModel::CONV_COLUMN_SRC_ADDR) {
portColumn = ConversationDataModel::CONV_COLUMN_SRC_PORT;
int col = ConversationDataModel::CONV_COLUMN_DST_ADDR;
tstA = model->index(source_left.row(), col);
tstB = model->index(source_right.row(), col);
} else if (source_left.column() == ConversationDataModel::CONV_COLUMN_DST_ADDR) {
portColumn = ConversationDataModel::CONV_COLUMN_DST_PORT;
int col = ConversationDataModel::CONV_COLUMN_SRC_ADDR;
tstA = model->index(source_left.row(), col);
tstB = model->index(source_right.row(), col);
}
if (addressTypeA == AT_IPv4) {
quint32 valX = model->data(tstA, ATapDataModel::DATA_IPV4_INTEGER).value<quint32>();
quint32 valY = model->data(tstB, ATapDataModel::DATA_IPV4_INTEGER).value<quint32>();
result = valX < valY;
identical = valX == valY;
} else {
result = QString::compare(model->data(tstA).toString().toLower(), model->data(tstB).toString(), Qt::CaseInsensitive) < 0;
identical = QString::compare(model->data(tstA).toString().toLower(), model->data(tstB).toString(), Qt::CaseInsensitive) == 0;
}
}
if (! result && identical && ! model->portsAreHidden()) {
int portA = model->data(model->index(source_left.row(), portColumn)).toInt();
int portB = model->data(model->index(source_right.row(), portColumn)).toInt();
return portA < portB;
}
}
return result;
}
return QSortFilterProxyModel::lessThan(source_left, source_right);
}
bool TrafficDataFilterProxy::filterAcceptsColumn(int source_column, const QModelIndex &) const
{
if (hideColumns_.contains(source_column))
return false;
ATapDataModel * model = qobject_cast<ATapDataModel *>(sourceModel());
if (model) {
if (model->portsAreHidden()) {
if (qobject_cast<EndpointDataModel *>(model) && source_column == EndpointDataModel::ENDP_COLUMN_PORT)
return false;
if (qobject_cast<ConversationDataModel *>(model) &&
(source_column == ConversationDataModel::CONV_COLUMN_SRC_PORT || source_column == ConversationDataModel::CONV_COLUMN_DST_PORT))
return false;
}
if (! model->showTotalColumn()) {
if (qobject_cast<EndpointDataModel *>(model) &&
(source_column == EndpointDataModel::ENDP_COLUMN_PACKETS_TOTAL || source_column == EndpointDataModel::ENDP_COLUMN_BYTES_TOTAL))
return false;
if (qobject_cast<ConversationDataModel *>(model) &&
(source_column == ConversationDataModel::CONV_COLUMN_PACKETS_TOTAL || source_column == ConversationDataModel::CONV_COLUMN_BYTES_TOTAL))
return false;
}
if (qobject_cast<ConversationDataModel *>(model)) {
ConversationDataModel * convModel = qobject_cast<ConversationDataModel *>(model);
if (source_column == ConversationDataModel::CONV_COLUMN_CONV_ID && ! convModel->showConversationId())
return false;
}
}
return true;
}
void TrafficDataFilterProxy::setColumnVisibility(int column, bool visible)
{
hideColumns_.removeAll(column);
if (!visible)
hideColumns_.append(column);
invalidateFilter();
}
bool TrafficDataFilterProxy::columnVisible(int column) const
{
return ! hideColumns_.contains(column);
}
TrafficTree::TrafficTree(QString baseName, GList ** recentColumnList, QWidget *parent) :
QTreeView(parent)
{
_tapEnabled = true;
_saveRaw = true;
_baseName = baseName;
_exportRole = ATapDataModel::UNFORMATTED_DISPLAYDATA;
_header = nullptr;
setAlternatingRowColors(true);
setRootIsDecorated(false);
setSortingEnabled(true);
setContextMenuPolicy(Qt::CustomContextMenu);
_header = new TrafficTreeHeaderView(recentColumnList);
setHeader(_header);
connect(_header, &TrafficTreeHeaderView::columnsHaveChanged, this, &TrafficTree::columnsHaveChanged);
connect(this, &QTreeView::customContextMenuRequested, this, &TrafficTree::customContextMenu);
}
void TrafficTree::setModel(QAbstractItemModel * model)
{
if (model) {
TrafficDataFilterProxy * proxy = qobject_cast<TrafficDataFilterProxy *>(model);
if (proxy) {
connect(_header, &TrafficTreeHeaderView::filterOnColumn, proxy, &TrafficDataFilterProxy::filterForColumn);
}
}
QTreeView::setModel(model);
}
void TrafficTree::tapListenerEnabled(bool enable)
{
_tapEnabled = enable;
}
ATapDataModel * TrafficTree::dataModel()
{
QSortFilterProxyModel * proxy = qobject_cast<QSortFilterProxyModel *>(model());
if (proxy)
return qobject_cast<ATapDataModel *>(proxy->sourceModel());
return nullptr;
}
void TrafficTree::customContextMenu(const QPoint &pos)
{
if (sender() != this)
return;
QMenu * ctxMenu = new QMenu(this);
ctxMenu->setAttribute(Qt::WA_DeleteOnClose);
bool isConv = false;
QModelIndex idx = indexAt(pos);
TrafficDataFilterProxy * proxy = qobject_cast<TrafficDataFilterProxy *>(model());
if (proxy)
idx = proxy->mapToSource(idx);
ConversationDataModel * model = qobject_cast<ConversationDataModel *>(dataModel());
if (model)
isConv = true;
ctxMenu->addMenu(createActionSubMenu(FilterAction::ActionApply, idx, isConv));
ctxMenu->addMenu(createActionSubMenu(FilterAction::ActionPrepare, idx, isConv));
ctxMenu->addMenu(createActionSubMenu(FilterAction::ActionFind, idx, isConv));
ctxMenu->addMenu(createActionSubMenu(FilterAction::ActionColorize, idx, isConv));
ctxMenu->addSeparator();
ctxMenu->addMenu(createCopyMenu());
ctxMenu->addSeparator();
QAction * act = ctxMenu->addAction(tr("Resize all columns to content"));
connect(act, &QAction::triggered, this, &TrafficTree::resizeAction);
ctxMenu->popup(mapToGlobal(pos));
}
static QMap<FilterAction::ActionDirection, int> fad_to_cd_;
static void initDirection()
{
if (fad_to_cd_.count() == 0) {
fad_to_cd_[FilterAction::ActionDirectionAToFromB] = CONV_DIR_A_TO_FROM_B;
fad_to_cd_[FilterAction::ActionDirectionAToB] = CONV_DIR_A_TO_B;
fad_to_cd_[FilterAction::ActionDirectionAFromB] = CONV_DIR_A_FROM_B;
fad_to_cd_[FilterAction::ActionDirectionAToFromAny] = CONV_DIR_A_TO_FROM_ANY;
fad_to_cd_[FilterAction::ActionDirectionAToAny] = CONV_DIR_A_TO_ANY;
fad_to_cd_[FilterAction::ActionDirectionAFromAny] = CONV_DIR_A_FROM_ANY;
fad_to_cd_[FilterAction::ActionDirectionAnyToFromB] = CONV_DIR_ANY_TO_FROM_B;
fad_to_cd_[FilterAction::ActionDirectionAnyToB] = CONV_DIR_ANY_TO_B;
fad_to_cd_[FilterAction::ActionDirectionAnyFromB] = CONV_DIR_ANY_FROM_B;
}
}
QMenu * TrafficTree::createActionSubMenu(FilterAction::Action cur_action, QModelIndex idx, bool isConversation)
{
initDirection();
conv_item_t * conv_item = nullptr;
bool hasConvId = false;
if (isConversation)
{
ConversationDataModel * model = qobject_cast<ConversationDataModel *>(dataModel());
if (model) {
conv_item = model->itemForRow(idx.row());
hasConvId = model->showConversationId(idx.row());
}
}
QMenu * subMenu = new QMenu(FilterAction::actionName(cur_action));
subMenu->setEnabled(_tapEnabled);
foreach (FilterAction::ActionType at, FilterAction::actionTypes()) {
if (isConversation && conv_item) {
QMenu *subsubmenu = subMenu->addMenu(FilterAction::actionTypeName(at));
if (hasConvId && (cur_action == FilterAction::ActionApply || cur_action == FilterAction::ActionPrepare)) {
QString filter = QString("%1.stream eq %2").arg(conv_item->ctype == CONVERSATION_TCP ? "tcp" : "udp").arg(conv_item->conv_id);
FilterAction * act = new FilterAction(subsubmenu, cur_action, at, tr("Filter on stream id"));
act->setProperty("filter", filter);
subsubmenu->addAction(act);
connect(act, &QAction::triggered, this, &TrafficTree::useFilterAction);
}
foreach (FilterAction::ActionDirection ad, FilterAction::actionDirections()) {
FilterAction *fa = new FilterAction(subsubmenu, cur_action, at, ad);
QString filter = get_conversation_filter(conv_item, (conv_direction_e) fad_to_cd_[fa->actionDirection()]);
fa->setProperty("filter", filter);
subsubmenu->addAction(fa);
connect(fa, &QAction::triggered, this, &TrafficTree::useFilterAction);
}
} else {
FilterAction *fa = new FilterAction(subMenu, cur_action, at);
fa->setProperty("filter", idx.data(ATapDataModel::DISPLAY_FILTER));
subMenu->addAction(fa);
connect(fa, &QAction::triggered, this, &TrafficTree::useFilterAction);
}
}
return subMenu;
}
QMenu * TrafficTree::createCopyMenu(QWidget *parent)
{
QMenu *copy_menu = new QMenu(tr("Copy %1 table").arg(_baseName), parent);
QAction *ca;
ca = copy_menu->addAction(tr("as CSV"));
ca->setToolTip(tr("Copy all values of this page to the clipboard in CSV (Comma Separated Values) format."));
ca->setProperty("copy_as", TrafficTree::CLIPBOARD_CSV);
connect(ca, &QAction::triggered, this, &TrafficTree::clipboardAction);
ca = copy_menu->addAction(tr("as YAML"));
ca->setToolTip(tr("Copy all values of this page to the clipboard in the YAML data serialization format."));
ca->setProperty("copy_as", TrafficTree::CLIPBOARD_YAML);
connect(ca, &QAction::triggered, this, &TrafficTree::clipboardAction);
ca = copy_menu->addAction(tr("as JSON"));
ca->setToolTip(tr("Copy all values of this page to the clipboard in the JSON data serialization format."));
ca->setProperty("copy_as", TrafficTree::CLIPBOARD_JSON);
connect(ca, &QAction::triggered, this, &TrafficTree::clipboardAction);
copy_menu->addSeparator();
ca = copy_menu->addAction(tr("Save data as raw"));
ca->setToolTip(tr("Disable data formatting for export/clipboard and save as raw data"));
ca->setCheckable(true);
ca->setChecked(_exportRole == ATapDataModel::UNFORMATTED_DISPLAYDATA);
connect(ca, &QAction::triggered, this, &TrafficTree::toggleSaveRawAction);
return copy_menu;
}
void TrafficTree::useFilterAction()
{
FilterAction *fa = qobject_cast<FilterAction *>(sender());
if (!fa || !_tapEnabled)
return;
QString filter = fa->property("filter").toString();
if (filter.length() > 0)
{
MainWindow * mainWin = (MainWindow *)(mainApp->mainWindow());
mainWin->setDisplayFilter(filter, fa->action(), fa->actionType());
}
}
void TrafficTree::clipboardAction()
{
QAction * ca = qobject_cast<QAction *>(sender());
if (ca && ca->property("copy_as").isValid())
copyToClipboard((eTrafficTreeClipboard)ca->property("copy_as").toInt());
}
void TrafficTree::resizeAction()
{
for (int col = 0; col < model()->columnCount(); col++)
resizeColumnToContents(col);
}
void TrafficTree::toggleSaveRawAction()
{
if (_exportRole == ATapDataModel::UNFORMATTED_DISPLAYDATA)
_exportRole = Qt::DisplayRole;
else
_exportRole = ATapDataModel::UNFORMATTED_DISPLAYDATA;
}
void TrafficTree::copyToClipboard(eTrafficTreeClipboard type)
{
if (!model())
return;
QString clipText;
QTextStream stream(&clipText, QIODevice::Text);
if (type == CLIPBOARD_CSV) {
QMap<int, QString> headers;
QStringList rdsl;
for (int cnt = 0; cnt < model()->columnCount(); cnt++)
{
rdsl << model()->headerData(cnt, Qt::Horizontal, Qt::DisplayRole).toString();
}
stream << rdsl.join(",") << "\n";
for (int row = 0; row < model()->rowCount(); row++) {
rdsl.clear();
for (int col = 0; col < model()->columnCount(); col++) {
QModelIndex idx = model()->index(row, col);
QVariant v = model()->data(idx, _exportRole);
if (!v.isValid()) {
rdsl << "\"\"";
} else if (v.userType() == QMetaType::QString) {
rdsl << QString("\"%1\"").arg(v.toString());
} else {
rdsl << v.toString();
}
}
stream << rdsl.join(",") << '\n';
}
} else if (type == CLIPBOARD_YAML) {
stream << "---" << '\n';
QMap<int, QString> headers;
for (int cnt = 0; cnt < model()->columnCount(); cnt++)
headers.insert(cnt, model()->headerData(cnt, Qt::Horizontal, Qt::DisplayRole).toString());
for (int row = 0; row < model()->rowCount(); row++) {
stream << "-" << '\n';
for (int col = 0; col < model()->columnCount(); col++) {
QModelIndex idx = model()->index(row, col);
QVariant v = model()->data(idx, _exportRole);
stream << " - " << headers[col] << ": " << v.toString() << '\n';
}
}
} else if (type == CLIPBOARD_JSON) {
QMap<int, QString> headers;
for (int cnt = 0; cnt < model()->columnCount(); cnt++)
headers.insert(cnt, model()->headerData(cnt, Qt::Horizontal, Qt::DisplayRole).toString());
QJsonArray records;
for (int row = 0; row < model()->rowCount(); row++) {
QJsonObject rowData;
foreach(int col, headers.keys()) {
QModelIndex idx = model()->index(row, col);
rowData.insert(headers[col], model()->data(idx, _exportRole).toString());
}
records.push_back(rowData);
}
QJsonDocument json;
json.setArray(records);
stream << json.toJson();
}
mainApp->clipboard()->setText(stream.readAll());
}
void TrafficTree::disableTap()
{
ATapDataModel * model = dataModel();
if (!model)
return;
model->disableTap();
}
void TrafficTree::applyRecentColumns()
{
if (_header)
_header->applyRecent();
}
void TrafficTree::columnsChanged(QList<int> columns)
{
TrafficDataFilterProxy * proxy = qobject_cast<TrafficDataFilterProxy *>(model());
if (!proxy)
return;
for (int col = 0; col < dataModel()->columnCount(); col++) {
proxy->setColumnVisibility(col, columns.contains(col));
}
resizeAction();
} |
C/C++ | wireshark/ui/qt/widgets/traffic_tree.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef TRAFFIC_TREE_H
#define TRAFFIC_TREE_H
#include "config.h"
#include <glib.h>
#include <ui/recent.h>
#include <ui/qt/models/atap_data_model.h>
#include <ui/qt/filter_action.h>
#include <QTreeView>
#include <QMenu>
#include <QHeaderView>
#include <QSortFilterProxyModel>
#include <QWidgetAction>
#include <QLineEdit>
#include <QActionGroup>
class MenuEditAction : public QWidgetAction
{
Q_OBJECT
public:
MenuEditAction(QString text, QString hintText, QObject * parent = nullptr);
QString text() const;
protected:
virtual QWidget * createWidget(QWidget *parent);
private:
QString _hintText;
QString _text;
QLineEdit * _lineEdit;
private slots:
void triggerEntry();
};
class TrafficTreeHeaderView : public QHeaderView
{
Q_OBJECT
public:
TrafficTreeHeaderView(GList ** recentColumnList, QWidget * parent = nullptr);
~TrafficTreeHeaderView();
void applyRecent();
signals:
void columnsHaveChanged(QList<int> visible);
void filterOnColumn(int column, int filterOn, QString filterText);
private:
GList ** _recentColumnList;
QActionGroup * _actions;
QString _filterText;
private slots:
void headerContextMenu(const QPoint &pos);
void columnTriggered(bool checked = false);
void menuActionTriggered(QAction *);
void filterColumn(bool checked = false);
};
class TrafficDataFilterProxy : public QSortFilterProxyModel
{
Q_OBJECT
public:
enum {
TRAFFIC_DATA_LESS,
TRAFFIC_DATA_GREATER,
TRAFFIC_DATA_EQUAL,
};
TrafficDataFilterProxy(QObject *parent = nullptr);
void setColumnVisibility(int column, bool visible);
bool columnVisible(int column) const;
public slots:
void filterForColumn(int column, int filterOn, QString filterText);
protected:
virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const;
virtual bool filterAcceptsColumn(int source_column, const QModelIndex &source_parent) const;
virtual bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const;
private:
QList<int> hideColumns_;
int _filterColumn;
int _filterOn;
QString _filterText;
int mapToSourceColumn(int proxyColumn) const;
};
class TrafficTree : public QTreeView
{
Q_OBJECT
public:
/**
* @brief Type for the selection of export
* @see copyToClipboard
*/
typedef enum {
CLIPBOARD_CSV, /* export as CSV */
CLIPBOARD_YAML, /* export as YAML */
CLIPBOARD_JSON /* export as JSON */
} eTrafficTreeClipboard;
TrafficTree(QString baseName, GList ** recentColumnList, QWidget *parent = nullptr);
/**
* @brief Create a menu containing clipboard copy entries for this tab
*
* It will create all entries, including copying the content of the currently selected tab
* to CSV, YAML and JSON
*
* @param parent the parent object or null
* @return QMenu* the resulting menu or null
*/
QMenu * createCopyMenu(QWidget * parent = nullptr);
void applyRecentColumns();
virtual void setModel(QAbstractItemModel *model) override;
signals:
void filterAction(QString filter, FilterAction::Action action, FilterAction::ActionType type);
void columnsHaveChanged(QList<int> columns);
public slots:
void tapListenerEnabled(bool enable);
void disableTap();
void columnsChanged(QList<int> columns);
private:
bool _tapEnabled;
int _exportRole;
bool _saveRaw;
QString _baseName;
TrafficTreeHeaderView * _header;
ATapDataModel * dataModel();
QMenu * createActionSubMenu(FilterAction::Action cur_action, QModelIndex idx, bool isConversation);
void copyToClipboard(eTrafficTreeClipboard type);
friend class TrafficTreeHeaderView;
private slots:
void customContextMenu(const QPoint &pos);
void useFilterAction();
void clipboardAction();
void resizeAction();
void toggleSaveRawAction();
};
#endif // TRAFFIC_TREE_H |
C++ | wireshark/ui/qt/widgets/traffic_types_list.cpp | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <glib.h>
#include <epan/conversation_table.h>
#include <ui/qt/widgets/traffic_types_list.h>
#include <QStringList>
TrafficTypesRowData::TrafficTypesRowData(int protocol, QString name) :
_protocol(protocol),
_name(name),
_checked(false)
{}
int TrafficTypesRowData::protocol() const
{
return _protocol;
}
QString TrafficTypesRowData::name() const
{
return _name;
}
bool TrafficTypesRowData::checked() const
{
return _checked;
}
void TrafficTypesRowData::setChecked(bool checked)
{
_checked = checked;
}
static bool iterateProtocols(const void *key, void *value, void *userdata)
{
QList<TrafficTypesRowData> * protocols = (QList<TrafficTypesRowData> *)userdata;
register_ct_t* ct = (register_ct_t*)value;
const QString title = (const gchar*)key;
int proto_id = get_conversation_proto_id(ct);
TrafficTypesRowData entry(proto_id, title);
protocols->append(entry);
return FALSE;
}
TrafficTypesModel::TrafficTypesModel(GList ** recentList, QObject *parent) :
QAbstractListModel(parent),
_recentList(recentList)
{
conversation_table_iterate_tables(iterateProtocols, &_allTaps);
std::sort(_allTaps.begin(), _allTaps.end(), [](TrafficTypesRowData a, TrafficTypesRowData b) {
return a.name().compare(b.name(), Qt::CaseInsensitive) < 0;
});
QList<int> _protocols;
for (GList * endTab = *_recentList; endTab; endTab = endTab->next) {
int protoId = proto_get_id_by_short_name((const char *)endTab->data);
if (protoId > -1 && ! _protocols.contains(protoId))
_protocols.append(protoId);
}
if (_protocols.isEmpty()) {
QStringList protoNames = QStringList() << "eth" << "ip" << "ipv6" << "tcp" << "udp";
foreach(QString name, protoNames)
_protocols << proto_get_id_by_filter_name(name.toStdString().c_str());
}
for(int cnt = 0; cnt < _allTaps.count(); cnt++)
{
_allTaps[cnt].setChecked(false);
if (_protocols.contains(_allTaps[cnt].protocol()))
_allTaps[cnt].setChecked(true);
}
}
int TrafficTypesModel::rowCount(const QModelIndex &) const
{
return (int) _allTaps.count();
}
int TrafficTypesModel::columnCount(const QModelIndex &) const
{
return TrafficTypesModel::COL_NUM;
}
QVariant TrafficTypesModel::data(const QModelIndex &idx, int role) const
{
if (!idx.isValid())
return QVariant();
TrafficTypesRowData data = _allTaps[idx.row()];
if (role == Qt::DisplayRole)
{
switch(idx.column())
{
case(TrafficTypesModel::COL_NAME):
return data.name();
case(TrafficTypesModel::COL_PROTOCOL):
return data.protocol();
}
} else if (role == Qt::CheckStateRole && idx.column() == TrafficTypesModel::COL_CHECKED) {
return data.checked() ? Qt::Checked : Qt::Unchecked;
} else if (role == TrafficTypesModel::TRAFFIC_PROTOCOL) {
return data.protocol();
} else if (role == TrafficTypesModel::TRAFFIC_IS_CHECKED) {
return (bool)data.checked();
}
return QVariant();
}
QVariant TrafficTypesModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (section < 0 || role != Qt::DisplayRole || orientation != Qt::Horizontal)
return QVariant();
if (section == TrafficTypesModel::COL_NAME)
return tr("Protocol");
return QVariant();
}
Qt::ItemFlags TrafficTypesModel::flags (const QModelIndex & idx) const
{
Qt::ItemFlags defaultFlags = QAbstractListModel::flags(idx);
if (idx.isValid())
return defaultFlags | Qt::ItemIsUserCheckable;
return defaultFlags;
}
bool TrafficTypesModel::setData(const QModelIndex &idx, const QVariant &value, int role)
{
if(!idx.isValid() || role != Qt::CheckStateRole)
return false;
if (_allTaps.count() <= idx.row())
return false;
_allTaps[idx.row()].setChecked(value.toInt() == Qt::Checked);
QList<int> selected;
prefs_clear_string_list(*_recentList);
*_recentList = NULL;
for (int cnt = 0; cnt < _allTaps.count(); cnt++) {
if (_allTaps[cnt].checked()) {
int protoId = _allTaps[cnt].protocol();
selected.append(protoId);
char *title = g_strdup(proto_get_protocol_short_name(find_protocol_by_id(protoId)));
*_recentList = g_list_append(*_recentList, title);
}
}
emit protocolsChanged(selected);
emit dataChanged(idx, idx);
return true;
}
void TrafficTypesModel::selectProtocols(QList<int> protocols)
{
beginResetModel();
for (int cnt = 0; cnt < _allTaps.count(); cnt++) {
_allTaps[cnt].setChecked(false);
if (protocols.contains(_allTaps[cnt].protocol()))
_allTaps[cnt].setChecked(true);
}
endResetModel();
}
TrafficListSortModel::TrafficListSortModel(QObject * parent) :
QSortFilterProxyModel(parent)
{}
bool TrafficListSortModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
{
if (source_left.isValid() && source_left.column() == TrafficTypesModel::COL_NAME) {
QString valA = source_left.data().toString();
QString valB = source_right.data().toString();
return valA.compare(valB, Qt::CaseInsensitive) <= 0;
}
return QSortFilterProxyModel::lessThan(source_left, source_right);
}
void TrafficListSortModel::setFilter(QString filter)
{
if ( filter.compare(_filter) != 0 ) {
_filter = filter;
invalidateFilter();
}
}
bool TrafficListSortModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
if (sourceModel() && _filter.length() > 0) {
QModelIndex idx = sourceModel()->index(source_row, TrafficTypesModel::COL_NAME);
if (idx.isValid()) {
QString name = idx.data().toString();
if (name.contains(_filter, Qt::CaseInsensitive))
return true;
return false;
}
}
return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent);
}
TrafficTypesList::TrafficTypesList(QWidget *parent) :
QTreeView(parent)
{
_name = QString();
_model = nullptr;
_sortModel = nullptr;
setAlternatingRowColors(true);
setRootIsDecorated(false);
}
void TrafficTypesList::setProtocolInfo(QString name, GList ** recentList)
{
_name = name;
_sortModel = new TrafficListSortModel(this);
_model = new TrafficTypesModel(recentList, this);
_sortModel->setSourceModel(_model);
setModel(_sortModel);
setSortingEnabled(true);
sortByColumn(TrafficTypesModel::COL_NAME, Qt::AscendingOrder);
connect(_model, &TrafficTypesModel::protocolsChanged, this, &TrafficTypesList::protocolsChanged);
resizeColumnToContents(0);
resizeColumnToContents(1);
}
void TrafficTypesList::selectProtocols(QList<int> protocols)
{
if (_model) {
_model->selectProtocols(protocols);
emit clearFilterList();
}
}
QList<int> TrafficTypesList::protocols(bool onlySelected) const
{
QList<int> entries;
for (int cnt = 0; cnt < _model->rowCount(); cnt++) {
QModelIndex idx = _model->index(cnt, TrafficTypesModel::COL_CHECKED);
int protoId = _model->data(idx, TrafficTypesModel::TRAFFIC_PROTOCOL).toInt();
if (protoId > 0 && ! entries.contains(protoId)) {
if (!onlySelected || _model->data(idx, TrafficTypesModel::TRAFFIC_IS_CHECKED).toBool())
entries.append(protoId);
}
}
return entries;
}
void TrafficTypesList::filterList(QString filter)
{
_sortModel->setFilter(filter);
} |
C/C++ | wireshark/ui/qt/widgets/traffic_types_list.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef TRAFFIC_TYPES_LIST_H
#define TRAFFIC_TYPES_LIST_H
#include "config.h"
#include <glib.h>
#include <QTreeView>
#include <QAbstractListModel>
#include <QMap>
#include <QList>
#include <QString>
#include <QSortFilterProxyModel>
class TrafficTypesRowData
{
public:
TrafficTypesRowData(int protocol, QString name);
int protocol() const;
QString name() const;
bool checked() const;
void setChecked(bool checked);
private:
int _protocol;
QString _name;
bool _checked;
};
class TrafficTypesModel : public QAbstractListModel
{
Q_OBJECT
public:
enum {
TRAFFIC_PROTOCOL = Qt::UserRole,
TRAFFIC_IS_CHECKED,
} eTrafficUserData;
enum {
COL_CHECKED,
COL_NAME,
COL_NUM,
COL_PROTOCOL,
} eTrafficColumnNames;
TrafficTypesModel(GList ** recentList, QObject *parent = nullptr);
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const override;
virtual int columnCount(const QModelIndex &parent = QModelIndex()) const override;
virtual QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override;
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
virtual bool setData(const QModelIndex &idx, const QVariant &value, int role) override;
virtual Qt::ItemFlags flags (const QModelIndex & idx) const override;
QList<int> protocols() const;
public slots:
void selectProtocols(QList<int> protocols);
signals:
void protocolsChanged(QList<int> protocols);
private:
QList<TrafficTypesRowData> _allTaps;
GList ** _recentList;
};
class TrafficListSortModel : public QSortFilterProxyModel
{
Q_OBJECT
public:
TrafficListSortModel(QObject * parent = nullptr);
void setFilter(QString filter = QString());
protected:
virtual bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override;
virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override;
private:
QString _filter;
};
class TrafficTypesList : public QTreeView
{
Q_OBJECT
public:
TrafficTypesList(QWidget *parent = nullptr);
void setProtocolInfo(QString name, GList ** recentList);
QList<int> protocols(bool onlySelected = false) const;
public slots:
void selectProtocols(QList<int> protocols);
void filterList(QString);
signals:
void protocolsChanged(QList<int> protocols);
void clearFilterList();
private:
QString _name;
TrafficTypesModel * _model;
TrafficListSortModel * _sortModel;
};
#endif // TRAFFIC_TYPES_LIST_H |
C++ | wireshark/ui/qt/widgets/wireless_timeline.cpp | /* wireless_timeline.cpp
* GUI to show an 802.11 wireless timeline of packets
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* Copyright 2012 Parc Inc and Samsung Electronics
* Copyright 2015, 2016 & 2017 Cisco Inc
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "wireless_timeline.h"
#include <epan/packet.h>
#include <epan/prefs.h>
#include <epan/proto_data.h>
#include <epan/packet_info.h>
#include <epan/column-utils.h>
#include <epan/tap.h>
#include <cmath>
#include "globals.h"
#include <epan/dissectors/packet-ieee80211-radio.h>
#include <epan/color_filters.h>
#include "frame_tvbuff.h"
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
#include <wsutil/report_message.h>
#include <wsutil/utf8_entities.h>
#ifdef Q_OS_WIN
#include "wsutil/file_util.h"
#include <QSysInfo>
#endif
#include <QPaintEvent>
#include <QPainter>
#include <QGraphicsScene>
#include <QToolTip>
#include <ui/qt/main_window.h>
#include "packet_list.h"
#include <ui/qt/models/packet_list_model.h>
/* we start rendering this number of microseconds left of the left edge - to ensure
* NAV lines are drawn correctly, and that small errors in time order don't prevent some
* frames from being rendered.
* These errors in time order can come from generators that record PHY rate incorrectly
* in some circumstances.
*/
#define RENDER_EARLY 40000
const float fraction = 0.8F;
const float base = 0.1F;
class pcolor : public QColor
{
public:
inline pcolor(float red, float green, float blue) : QColor(
(int) (255*(red * fraction + base)),
(int) (255*(green * fraction + base)),
(int) (255*(blue * fraction + base))) { }
};
static void reset_rgb(float rgb[TIMELINE_HEIGHT][3])
{
int i;
for (i = 0; i < TIMELINE_HEIGHT; i++)
rgb[i][0] = rgb[i][1] = rgb[i][2] = 1.0;
}
static void render_pixels(QPainter &p, gint x, gint width, float rgb[TIMELINE_HEIGHT][3], float ratio)
{
int previous = 0, i;
for (i = 1; i <= TIMELINE_HEIGHT; i++) {
if (i != TIMELINE_HEIGHT &&
rgb[previous][0] == rgb[i][0] &&
rgb[previous][1] == rgb[i][1] &&
rgb[previous][2] == rgb[i][2])
continue;
if (rgb[previous][0] != 1.0 || rgb[previous][1] != 1.0 || rgb[previous][2] != 1.0) {
p.fillRect(QRectF(x/ratio, previous, width/ratio, i-previous), pcolor(rgb[previous][0],rgb[previous][1],rgb[previous][2]));
}
previous = i;
}
reset_rgb(rgb);
}
static void render_rectangle(QPainter &p, gint x, gint width, guint height, int dfilter, float r, float g, float b, float ratio)
{
p.fillRect(QRectF(x/ratio, TIMELINE_HEIGHT/2-height, width/ratio, dfilter ? height * 2 : height), pcolor(r,g,b));
}
static void accumulate_rgb(float rgb[TIMELINE_HEIGHT][3], int height, int dfilter, float width, float red, float green, float blue)
{
int i;
for (i = TIMELINE_HEIGHT/2-height; i < (TIMELINE_HEIGHT/2 + (dfilter ? height : 0)); i++) {
rgb[i][0] = rgb[i][0] - width + width * red;
rgb[i][1] = rgb[i][1] - width + width * green;
rgb[i][2] = rgb[i][2] - width + width * blue;
}
}
void WirelessTimeline::mousePressEvent(QMouseEvent *event)
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
start_x = last_x = event->position().x();
#else
start_x = last_x = event->localPos().x();
#endif
}
void WirelessTimeline::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() == Qt::NoButton)
return;
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
qreal offset = event->position().x() - last_x;
last_x = event->position().x();
#else
qreal offset = event->localPos().x() - last_x;
last_x = event->localPos().x();
#endif
qreal shift = ((qreal) (end_tsf - start_tsf))/width() * offset;
start_tsf -= shift;
end_tsf -= shift;
clip_tsf();
// TODO: scroll by moving pixels and redraw only exposed area
// render(p, ...)
// then update full widget only on release.
update();
}
void WirelessTimeline::mouseReleaseEvent(QMouseEvent *event)
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
QPointF localPos = event->position();
#else
QPointF localPos = event->localPos();
#endif
qreal offset = localPos.x() - start_x;
/* if this was a drag, ignore it */
if (std::abs(offset) > 3)
return;
/* this was a click */
guint num = find_packet(localPos.x());
if (num == 0)
return;
frame_data *fdata = frame_data_sequence_find(cfile.provider.frames, num);
if (!fdata->passed_dfilter && fdata->prev_dis_num > 0)
num = fdata->prev_dis_num;
cf_goto_frame(&cfile, num);
}
void WirelessTimeline::clip_tsf()
{
// did we go past the start of the file?
if (((gint64) start_tsf) < ((gint64) first->start_tsf)) {
// align the start of the file at the left edge
guint64 shift = first->start_tsf - start_tsf;
start_tsf += shift;
end_tsf += shift;
}
if (end_tsf > last->end_tsf) {
guint64 shift = end_tsf - last->end_tsf;
start_tsf -= shift;
end_tsf -= shift;
}
}
void WirelessTimeline::selectedFrameChanged(QList<int>)
{
if (isHidden())
return;
if (cfile.current_frame) {
struct wlan_radio *wr = get_wlan_radio(cfile.current_frame->num);
guint left_margin = 0.9 * start_tsf + 0.1 * end_tsf;
guint right_margin = 0.1 * start_tsf + 0.9 * end_tsf;
guint64 half_window = (end_tsf - start_tsf)/2;
if (wr) {
// are we to the left of the left margin?
if (wr->start_tsf < left_margin) {
// scroll the left edge back to the left margin
guint64 offset = left_margin - wr->start_tsf;
if (offset < half_window) {
// small movement; keep packet to margin
start_tsf -= offset;
end_tsf -= offset;
} else {
// large movement; move packet to center of window
guint64 center = (wr->start_tsf + wr->end_tsf)/2;
start_tsf = center - half_window;
end_tsf = center + half_window;
}
} else if (wr->end_tsf > right_margin) {
guint64 offset = wr->end_tsf - right_margin;
if (offset < half_window) {
start_tsf += offset;
end_tsf += offset;
} else {
guint64 center = (wr->start_tsf + wr->end_tsf)/2;
start_tsf = center - half_window;
end_tsf = center + half_window;
}
}
clip_tsf();
update();
}
}
}
/* given an x position find which packet that corresponds to.
* if it's inter frame space the subsequent packet is returned */
guint
WirelessTimeline::find_packet(qreal x_position)
{
guint64 x_time = start_tsf + (x_position/width() * (end_tsf - start_tsf));
return find_packet_tsf(x_time);
}
void WirelessTimeline::captureFileReadStarted(capture_file *cf)
{
capfile = cf;
hide();
// TODO: hide or grey the toolbar controls
}
void WirelessTimeline::captureFileReadFinished()
{
/* All frames must be included in packet list */
if (cfile.count == 0 || g_hash_table_size(radio_packet_list) != cfile.count)
return;
/* check that all frames have start and end tsf time and are reasonable time order.
* packet timing reference seems to be off a little on some generators, which
* causes frequent IFS values in the range 0 to -30. Some generators emit excessive
* data when an FCS error happens, and this results in the duration calculation for
* the error frame being excessively long. This can cause larger negative IFS values
* (-30 to -1000) for the subsequent frame. Ignore these cases, as they don't seem
* to impact the GUI too badly. If the TSF reference point is set wrong (TSF at
* start of frame when it is at the end) then larger negative offsets are often
* seen. Don't display the timeline in these cases.
*/
/* TODO: update GUI to handle captures with occasional frames missing TSF data */
/* TODO: indicate error message to the user */
for (guint32 n = 1; n < cfile.count; n++) {
struct wlan_radio *w = get_wlan_radio(n);
if (w->start_tsf == 0 || w->end_tsf == 0) {
QString err = tr("Packet number %1 does not include TSF timestamp, not showing timeline.").arg(n);
mainApp->pushStatus(MainApplication::TemporaryStatus, err);
return;
}
if (w->ifs < -RENDER_EARLY) {
QString err = tr("Packet number %u has large negative jump in TSF, not showing timeline. Perhaps TSF reference point is set wrong?").arg(n);
mainApp->pushStatus(MainApplication::TemporaryStatus, err);
return;
}
}
first = get_wlan_radio(1);
last = get_wlan_radio(cfile.count);
start_tsf = first->start_tsf;
end_tsf = last->end_tsf;
/* TODO: only reset the zoom level if the file is changed, not on redissection */
zoom_level = 0;
show();
selectedFrameChanged(QList<int>());
// TODO: show or ungrey the toolbar controls
update();
}
void WirelessTimeline::appInitialized()
{
connect(qobject_cast<MainWindow *>(mainApp->mainWindow()), &MainWindow::framesSelected, this, &WirelessTimeline::selectedFrameChanged);
GString *error_string;
error_string = register_tap_listener("wlan_radio_timeline", this, NULL, TL_REQUIRES_NOTHING, tap_timeline_reset, tap_timeline_packet, NULL/*tap_draw_cb tap_draw*/, NULL);
if (error_string) {
report_failure("Wireless Timeline - tap registration failed: %s", error_string->str);
g_string_free(error_string, TRUE);
}
}
void WirelessTimeline::resizeEvent(QResizeEvent*)
{
// TODO adjust scrollbar
}
// Calculate the x position on the GUI from the timestamp
int WirelessTimeline::position(guint64 tsf, float ratio)
{
int position = -100;
if (tsf != G_MAXUINT64) {
position = ((double) tsf - start_tsf)*width()*ratio/(end_tsf-start_tsf);
}
return position;
}
WirelessTimeline::WirelessTimeline(QWidget *parent) : QWidget(parent)
{
setHidden(true);
zoom_level = 1.0;
setFixedHeight(TIMELINE_HEIGHT);
first_packet = 1;
setMouseTracking(true);
start_x = 0;
last_x = 0;
packet_list = NULL;
start_tsf = 0;
end_tsf = 0;
first = NULL;
last = NULL;
capfile = NULL;
radio_packet_list = g_hash_table_new(g_direct_hash, g_direct_equal);
connect(mainApp, &MainApplication::appInitialized, this, &WirelessTimeline::appInitialized);
}
WirelessTimeline::~WirelessTimeline()
{
if (radio_packet_list != NULL)
{
g_hash_table_destroy(radio_packet_list);
}
}
void WirelessTimeline::setPacketList(PacketList *packet_list)
{
this->packet_list = packet_list;
}
void WirelessTimeline::tap_timeline_reset(void* tapdata)
{
WirelessTimeline* timeline = (WirelessTimeline*)tapdata;
if (timeline->radio_packet_list != NULL)
{
g_hash_table_destroy(timeline->radio_packet_list);
}
timeline->hide();
timeline->radio_packet_list = g_hash_table_new(g_direct_hash, g_direct_equal);
}
tap_packet_status WirelessTimeline::tap_timeline_packet(void *tapdata, packet_info* pinfo, epan_dissect_t* edt _U_, const void *data, tap_flags_t)
{
WirelessTimeline* timeline = (WirelessTimeline*)tapdata;
const struct wlan_radio *wlan_radio_info = (const struct wlan_radio *)data;
/* Save the radio information in our own (GUI) hashtable */
g_hash_table_insert(timeline->radio_packet_list, GUINT_TO_POINTER(pinfo->num), (gpointer)wlan_radio_info);
return TAP_PACKET_DONT_REDRAW;
}
struct wlan_radio* WirelessTimeline::get_wlan_radio(guint32 packet_num)
{
return (struct wlan_radio*)g_hash_table_lookup(radio_packet_list, GUINT_TO_POINTER(packet_num));
}
void WirelessTimeline::doToolTip(struct wlan_radio *wr, QPoint pos, int x)
{
if (x < position(wr->start_tsf, 1.0)) {
QToolTip::showText(pos, QString("Inter frame space %1 " UTF8_MICRO_SIGN "s").arg(wr->ifs));
} else {
QToolTip::showText(pos, QString("Total duration %1 " UTF8_MICRO_SIGN "s\nNAV %2 " UTF8_MICRO_SIGN "s")
.arg(wr->end_tsf-wr->start_tsf).arg(wr->nav));
}
}
bool WirelessTimeline::event(QEvent *event)
{
if (event->type() == QEvent::ToolTip) {
QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
guint packet = find_packet(helpEvent->pos().x());
if (packet) {
doToolTip(get_wlan_radio(packet), helpEvent->globalPos(), helpEvent->x());
} else {
QToolTip::hideText();
event->ignore();
}
return true;
}
return QWidget::event(event);
}
void WirelessTimeline::wheelEvent(QWheelEvent *event)
{
// "Most mouse types work in steps of 15 degrees, in which case the delta
// value is a multiple of 120; i.e., 120 units * 1/8 = 15 degrees"
double steps = event->angleDelta().y() / 120.0;
if (steps != 0.0) {
zoom_level += steps;
if (zoom_level < 0) zoom_level = 0;
if (zoom_level > TIMELINE_MAX_ZOOM) zoom_level = TIMELINE_MAX_ZOOM;
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
zoom(event->position().x() / width());
#else
zoom(event->posF().x() / width());
#endif
}
}
void WirelessTimeline::bgColorizationProgress(int first, int last)
{
if (isHidden()) return;
struct wlan_radio *first_wr = get_wlan_radio(first);
struct wlan_radio *last_wr = get_wlan_radio(last-1);
int x = position(first_wr->start_tsf, 1);
int x_end = position(last_wr->end_tsf, 1);
update(x, 0, x_end-x+1, height());
}
// zoom at relative position 0.0 <= x_fraction <= 1.0.
void WirelessTimeline::zoom(double x_fraction)
{
/* adjust the zoom around the selected packet */
guint64 file_range = last->end_tsf - first->start_tsf;
guint64 center = start_tsf + x_fraction * (end_tsf - start_tsf);
guint64 span = pow(file_range, 1.0 - zoom_level / TIMELINE_MAX_ZOOM);
start_tsf = center - span * x_fraction;
end_tsf = center + span * (1.0 - x_fraction);
clip_tsf();
update();
}
int WirelessTimeline::find_packet_tsf(guint64 tsf)
{
if (cfile.count < 1)
return 0;
if (cfile.count < 2)
return 1;
guint32 min_count = 1;
guint32 max_count = cfile.count-1;
guint64 min_tsf = get_wlan_radio(min_count)->end_tsf;
guint64 max_tsf = get_wlan_radio(max_count)->end_tsf;
for (;;) {
if (tsf >= max_tsf)
return max_count+1;
if (tsf < min_tsf)
return min_count;
guint32 middle = (min_count + max_count)/2;
if (middle == min_count)
return middle+1;
guint64 middle_tsf = get_wlan_radio(middle)->end_tsf;
if (tsf >= middle_tsf) {
min_count = middle;
min_tsf = middle_tsf;
} else {
max_count = middle;
max_tsf = middle_tsf;
}
};
}
void
WirelessTimeline::paintEvent(QPaintEvent *qpe)
{
QPainter p(this);
// painting is done in device pixels in the x axis, get the ratio here
float ratio = p.device()->devicePixelRatio();
unsigned int packet;
double zoom;
int last_x=-1;
int left = qpe->rect().left()*ratio;
int right = qpe->rect().right()*ratio;
float rgb[TIMELINE_HEIGHT][3];
reset_rgb(rgb);
zoom = ((double) width())/(end_tsf - start_tsf) * ratio;
/* background is light grey */
p.fillRect(0, 0, width(), TIMELINE_HEIGHT, QColor(240,240,240));
/* background of packets visible in packet_list is white */
int top = packet_list->indexAt(QPoint(0,0)).row();
int bottom = packet_list->indexAt(QPoint(0,packet_list->viewport()->height())).row();
frame_data * topData = packet_list->getFDataForRow(top);
frame_data * botData = packet_list->getFDataForRow(bottom);
if (! topData || ! botData)
return;
int x1 = top == -1 ? 0 : position(get_wlan_radio(topData->num)->start_tsf, ratio);
int x2 = bottom == -1 ? width() : position(get_wlan_radio(botData->num)->end_tsf, ratio);
p.fillRect(QRectF(x1/ratio, 0, (x2-x1+1)/ratio, TIMELINE_HEIGHT), Qt::white);
/* background of current packet is blue */
if (cfile.current_frame) {
struct wlan_radio *wr = get_wlan_radio(cfile.current_frame->num);
if (wr) {
x1 = position(wr->start_tsf, ratio);
x2 = position(wr->end_tsf, ratio);
p.fillRect(QRectF(x1/ratio, 0, (x2-x1+1)/ratio, TIMELINE_HEIGHT), Qt::blue);
}
}
QGraphicsScene qs;
for (packet = find_packet_tsf(start_tsf + left/zoom - RENDER_EARLY); packet <= cfile.count; packet++) {
frame_data *fdata = frame_data_sequence_find(cfile.provider.frames, packet);
struct wlan_radio *ri = get_wlan_radio(fdata->num);
float x, width, red, green, blue;
if (ri == NULL) continue;
gint8 rssi = ri->aggregate ? ri->aggregate->rssi : ri->rssi;
guint height = (rssi+100)/2;
gint end_nav;
/* leave a margin above the packets so the selected packet can be seen */
if (height > TIMELINE_HEIGHT/2-6)
height = TIMELINE_HEIGHT/2-6;
/* ensure shortest packets are clearly visible */
if (height < 2)
height = 2;
/* skip frames we don't have start and end data for */
/* TODO: show something, so it's clear a frame is missing */
if (ri->start_tsf == 0 || ri->end_tsf == 0)
continue;
x = ((gint64) (ri->start_tsf - start_tsf))*zoom;
/* is there a previous anti-aliased pixel to output */
if (last_x >= 0 && ((int) x) != last_x) {
/* write it out now */
render_pixels(p, last_x, 1, rgb, ratio);
last_x = -1;
}
/* does this packet start past the right edge of the window? */
if (x >= right) {
break;
}
width = (ri->end_tsf - ri->start_tsf)*zoom;
if (width < 0) {
continue;
}
/* is this packet completely to the left of the displayed area? */
// TODO clip NAV line properly if we are displaying it
if ((x + width) < left)
continue;
/* remember the first displayed packet */
if (first_packet < 0)
first_packet = packet;
if (fdata->color_filter) {
const color_t *c = &((const color_filter_t *) fdata->color_filter)->fg_color;
red = c->red / 65535.0;
green = c->green / 65535.0;
blue = c->blue / 65535.0;
} else {
red = green = blue = 0.0;
}
/* record NAV field at higher magnifications */
end_nav = x + width + ri->nav*zoom;
if (zoom >= 0.01 && ri->nav && end_nav > 0) {
gint y = 2*(packet % (TIMELINE_HEIGHT/2));
qs.addLine(QLineF((x+width)/ratio, y, end_nav/ratio, y), QPen(pcolor(red,green,blue)));
}
/* does this rectangle fit within one pixel? */
if (((int) x) == ((int) (x+width))) {
/* accumulate it for later rendering together
* with all other sub pixels that fall within this
* pixel */
last_x = x;
accumulate_rgb(rgb, height, fdata->passed_dfilter, width, red, green, blue);
} else {
/* it spans more than 1 pixel.
* first accumulate the part that does fit */
float partial = ((int) x) + 1 - x;
accumulate_rgb(rgb, height, fdata->passed_dfilter, partial, red, green, blue);
/* and render it */
render_pixels(p, (int) x, 1, rgb, ratio);
last_x = -1;
x += partial;
width -= partial;
/* are there any whole pixels of width left to draw? */
if (width > 1.0) {
render_rectangle(p, x, width, height, fdata->passed_dfilter, red, green, blue, ratio);
x += (int) width;
width -= (int) width;
}
/* is there a partial pixel left */
if (width > 0.0) {
last_x = x;
accumulate_rgb(rgb, height, fdata->passed_dfilter, width, red, green, blue);
}
}
}
// draw the NAV lines last, so they appear on top of the packets
qs.render(&p, rect(), rect());
} |
C/C++ | wireshark/ui/qt/widgets/wireless_timeline.h | /** @file
*
* GUI to show an 802.11 wireless timeline of packets
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* Copyright 2012 Parc Inc and Samsung Electronics
* Copyright 2015, 2016 & 2017 Cisco Inc
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <QScrollArea>
#ifndef WIRELESSTIMELINE_H
#define WIRELESSTIMELINE_H
#include <stdio.h>
#include <config.h>
#include <glib.h>
#include "file.h"
#include "ui/ws_ui_util.h"
#include <epan/prefs.h>
#include <epan/plugin_if.h>
#include <epan/tap.h>
#include <epan/timestamp.h>
#include <epan/dissectors/packet-ieee80211-radio.h>
#include <QScrollArea>
#include "cfile.h"
/* pixels height for rendered timeline */
#define TIMELINE_HEIGHT 64
/* Maximum zoom levels for the timeline */
#define TIMELINE_MAX_ZOOM 25.0
class WirelessTimeline;
class PacketList;
class WirelessTimeline : public QWidget
{
Q_OBJECT
public:
explicit WirelessTimeline(QWidget *parent);
~WirelessTimeline();
void setPacketList(PacketList *packet_list);
void captureFileReadStarted(capture_file *cf);
void captureFileReadFinished();
protected:
void resizeEvent(QResizeEvent *event);
void paintEvent(QPaintEvent *event);
void mousePressEvent (QMouseEvent *event);
void mouseMoveEvent (QMouseEvent *event);
void mouseReleaseEvent (QMouseEvent *event);
bool event(QEvent *event);
void wheelEvent(QWheelEvent *event);
public slots:
void bgColorizationProgress(int first, int last);
void appInitialized();
protected:
static void tap_timeline_reset(void* tapdata);
static tap_packet_status tap_timeline_packet(void *tapdata, packet_info* pinfo, epan_dissect_t* edt, const void *data, tap_flags_t flags);
struct wlan_radio* get_wlan_radio(guint32 packet_num);
void clip_tsf();
int position(guint64 tsf, float ratio);
int find_packet_tsf(guint64 tsf);
void doToolTip(struct wlan_radio *wr, QPoint pos, int x);
void zoom(double x_fraction);
double zoom_level;
qreal start_x, last_x;
PacketList *packet_list;
guint find_packet(qreal x);
float rgb[TIMELINE_HEIGHT][3];
guint64 start_tsf;
guint64 end_tsf;
int first_packet; /* first packet displayed */
struct wlan_radio *first, *last;
capture_file *capfile;
GHashTable* radio_packet_list;
protected slots:
void selectedFrameChanged(QList<int>);
};
#endif // WIRELESS_TIMELINE_H |
C++ | wireshark/ui/qt/widgets/wireshark_file_dialog.cpp | /* wireshark_file_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include "wireshark_file_dialog.h"
#ifdef Q_OS_WIN
#include <windows.h>
#include "ui/packet_range.h"
#include "ui/win32/file_dlg_win32.h"
#endif // Q_OS_WIN
WiresharkFileDialog::WiresharkFileDialog(QWidget *parent, const QString &caption, const QString &directory, const QString &filter) :
QFileDialog(parent, caption, directory, filter)
{
#ifdef Q_OS_MAC
// Add /Volumes to the sidebar. We might want to call
// setFilter(QDir::Hidden | QDir::AllEntries) in addition to or instead
// of this as recommended in QTBUG-6805 and QTBUG-6875, but you can
// access hidden files in the Qt file dialog by right-clicking on the
// file list or simply typing in the path in the "File name:" entry.
QList<QUrl> sb_urls = sidebarUrls();
bool have_volumes = false;
QString volumes = "/Volumes";
foreach (QUrl sbu, sb_urls) {
if (sbu.toLocalFile() == volumes) {
have_volumes = true;
}
}
if (! have_volumes) {
sb_urls << QUrl::fromLocalFile(volumes);
setSidebarUrls(sb_urls);
}
#endif
}
QString WiresharkFileDialog::getExistingDirectory(QWidget *parent, const QString &caption, const QString &dir, Options options)
{
#ifdef Q_OS_WIN
HANDLE da_ctx = set_thread_per_monitor_v2_awareness();
#endif
QString ed = QFileDialog::getExistingDirectory(parent, caption, dir, options);
#ifdef Q_OS_WIN
revert_thread_per_monitor_v2_awareness(da_ctx);
#endif
return ed;
}
QString WiresharkFileDialog::getOpenFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, Options options)
{
#ifdef Q_OS_WIN
HANDLE da_ctx = set_thread_per_monitor_v2_awareness();
#endif
QString ofn = QFileDialog::getOpenFileName(parent, caption, dir, filter, selectedFilter, options);
#ifdef Q_OS_WIN
revert_thread_per_monitor_v2_awareness(da_ctx);
#endif
return ofn;
}
QString WiresharkFileDialog::getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, Options options)
{
#ifdef Q_OS_WIN
HANDLE da_ctx = set_thread_per_monitor_v2_awareness();
#endif
QString sfn = QFileDialog::getSaveFileName(parent, caption, dir, filter, selectedFilter, options);
#ifdef Q_OS_WIN
revert_thread_per_monitor_v2_awareness(da_ctx);
#endif
return sfn;
} |
C/C++ | wireshark/ui/qt/widgets/wireshark_file_dialog.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef WIRESHARK_FILE_DIALOG_H
#define WIRESHARK_FILE_DIALOG_H
#include <QFileDialog>
/**
* @brief The WiresharkFileDialog class
*
* Qt <= 5.9 supports setting old (Windows 8.1) per-monitor DPI awareness
* via Qt:AA_EnableHighDpiScaling. We do this in main.cpp. In order for
* native dialogs to be rendered correctly we need to set per-monitor
* *v2* awareness prior to creating the dialog.
* Qt doesn't render correctly when per-monitor v2 awareness is enabled, so
* we need to revert our thread context when we're done.
* The class functions below are simple wrappers around their QFileDialog
* equivalents that set PMv2 awareness before showing native dialogs on
* Windows and resets it afterward.
*/
class WiresharkFileDialog : public QFileDialog
{
public:
WiresharkFileDialog(QWidget *parent = nullptr, const QString &caption = QString(), const QString &directory = QString(), const QString &filter = QString());
static QString getExistingDirectory(QWidget *parent = Q_NULLPTR, const QString &caption = QString(), const QString &dir = QString(), Options options = ShowDirsOnly);
static QString getOpenFileName(QWidget *parent = Q_NULLPTR, const QString &caption = QString(), const QString &dir = QString(), const QString &filter = QString(), QString *selectedFilter = Q_NULLPTR, Options options = Options());
static QString getSaveFileName(QWidget *parent = Q_NULLPTR, const QString &caption = QString(), const QString &dir = QString(), const QString &filter = QString(), QString *selectedFilter = Q_NULLPTR, Options options = Options());
};
#endif // WIRESHARK_FILE_DIALOG_H |
C++ | wireshark/ui/win32/file_dlg_win32.cpp | /* file_dlg_win32.c
* Native Windows file dialog routines
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 2004 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifdef _WIN32
#include "config.h"
#include <tchar.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string>
#include <windows.h>
#include <commdlg.h>
#include <richedit.h>
#include <strsafe.h>
#include "file.h"
#include "wsutil/file_util.h"
#include "wsutil/str_util.h"
#include "wsutil/unicode-utils.h"
#include <wsutil/ws_assert.h>
#include "wsutil/filesystem.h"
#include "epan/prefs.h"
#include "ui/alert_box.h"
#include "ui/help_url.h"
#include "ui/last_open_dir.h"
#include "ui/simple_dialog.h"
#include "ui/util.h"
#include "ui/ws_ui_util.h"
#include "ui/all_files_wildcard.h"
#include "file_dlg_win32.h"
typedef enum {
merge_append,
merge_chrono,
merge_prepend
} merge_action_e;
#define FILE_OPEN_DEFAULT 2 /* All Capture Files */
#define FILE_MERGE_DEFAULT FILE_OPEN_DEFAULT
#define FILE_TYPES_EXPORT \
_T("Plain text (*.txt)\0") _T("*.txt\0") \
_T("PostScript (*.ps)\0") _T("*.ps\0") \
_T("CSV (Comma Separated Values summary) (*.csv)\0") _T("*.csv\0") \
_T("PSML (XML packet summary) (*.psml)\0") _T("*.psml\0") \
_T("PDML (XML packet detail) (*.pdml)\0") _T("*.pdml\0") \
_T("C Arrays (packet bytes) (*.c)\0") _T("*.c\0") \
_T("JSON (*.json)\0") _T("*.json\0")
static const TCHAR *FILE_EXT_EXPORT[] =
{
_T(""), /* export type starts at 1 */
_T("txt"),
_T("ps"),
_T("csv"),
_T("psml"),
_T("pdml"),
_T("c"),
_T("json")
};
static UINT_PTR CALLBACK open_file_hook_proc(HWND of_hwnd, UINT ui_msg, WPARAM w_param, LPARAM l_param);
static UINT_PTR CALLBACK save_as_file_hook_proc(HWND of_hwnd, UINT ui_msg, WPARAM w_param, LPARAM l_param);
static UINT_PTR CALLBACK export_specified_packets_file_hook_proc(HWND of_hwnd, UINT ui_msg, WPARAM w_param, LPARAM l_param);
static UINT_PTR CALLBACK merge_file_hook_proc(HWND mf_hwnd, UINT ui_msg, WPARAM w_param, LPARAM l_param);
static UINT_PTR CALLBACK export_file_hook_proc(HWND of_hwnd, UINT ui_msg, WPARAM w_param, LPARAM l_param);
static void range_update_dynamics(HWND sf_hwnd, packet_range_t *range);
static void range_handle_wm_initdialog(HWND dlg_hwnd, packet_range_t *range);
static void range_handle_wm_command(HWND dlg_hwnd, HWND ctrl, WPARAM w_param, packet_range_t *range);
static TCHAR *build_file_open_type_list(void);
static TCHAR *build_file_save_type_list(GArray *savable_file_types);
#ifdef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
typedef DPI_AWARENESS_CONTEXT (WINAPI *GetThreadDpiAwarenessContextProc)(void);
typedef DPI_AWARENESS_CONTEXT (WINAPI *SetThreadDpiAwarenessContextProc)(DPI_AWARENESS_CONTEXT);
static GetThreadDpiAwarenessContextProc GetThreadDpiAwarenessContextP;
static SetThreadDpiAwarenessContextProc SetThreadDpiAwarenessContextP;
static gboolean got_proc_addresses = FALSE;
DIAG_OFF(cast-function-type)
static gboolean get_proc_addresses(void) {
if (got_proc_addresses) return TRUE;
HMODULE u32_module = LoadLibrary(_T("User32.dll"));
if (!u32_module) {
got_proc_addresses = FALSE;
return FALSE;
}
gboolean got_all = TRUE;
GetThreadDpiAwarenessContextP = (GetThreadDpiAwarenessContextProc) GetProcAddress(u32_module, "GetThreadDpiAwarenessContext");
if (!GetThreadDpiAwarenessContextP) got_all = FALSE;
SetThreadDpiAwarenessContextP = (SetThreadDpiAwarenessContextProc) GetProcAddress(u32_module, "SetThreadDpiAwarenessContext");
if (!SetThreadDpiAwarenessContextP) got_all = FALSE;
got_proc_addresses = got_all;
return got_all;
}
DIAG_ON(cast-function-type)
// Enabling DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 causes issues
// when dragging our open file dialog between differently-DPIed
// displays. It might be time to break down and switch to common
// item dialogs.
HANDLE set_thread_per_monitor_v2_awareness(void) {
if (! get_proc_addresses()) return 0;
#if 0
WCHAR info[100];
StringCchPrintf(info, 100,
L"GetThrDpiAwarenessCtx: %d",
GetThreadDpiAwarenessContextP());
MessageBox(NULL, info, _T("DPI info"), MB_OK);
#endif
return (HANDLE) SetThreadDpiAwarenessContextP(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
}
void revert_thread_per_monitor_v2_awareness(HANDLE context) {
if (! get_proc_addresses()) return;
SetThreadDpiAwarenessContextP((DPI_AWARENESS_CONTEXT) context);
}
#else // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
HANDLE set_thread_per_monitor_v2_awareness(void) { return 0; }
void revert_thread_per_monitor_v2_awareness(HANDLE context _U_) { }
#endif // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
static int g_filetype;
static gboolean g_compressed;
static packet_range_t *g_range;
static capture_file *g_cf;
static merge_action_e g_merge_action;
static print_args_t print_args;
/* XXX - The reason g_sf_hwnd exists is so that we can call
* range_update_dynamics() from anywhere; it's currently
* static, but if we move to using the native Windows
* print dialog and put range widgets in it as well,
* it might be moved to a separate file.
*
* However, the save file dialog hogs the foreground, so
* this may not be necessary (and, in fact, the file dialogs
* should arguably be modal to the window for the file
* being opened/saved/etc.).
*/
static HWND g_sf_hwnd = NULL;
static char *g_dfilter_str = NULL;
static unsigned int g_format_type = WTAP_TYPE_AUTO;
/*
* According to https://docs.microsoft.com/en-us/windows/win32/shell/common-file-dialog
* we should use IFileOpenDialog and IFileSaveDialog on Windows Vista
* and later.
*/
gboolean
win32_open_file (HWND h_wnd, const wchar_t *title, GString *file_name, unsigned int *type, GString *display_filter) {
OPENFILENAME *ofn;
TCHAR file_name16[MAX_PATH] = _T("");
int ofnsize = sizeof(OPENFILENAME);
BOOL gofn_ok;
if (!file_name || !display_filter)
return FALSE;
if (file_name->len > 0) {
StringCchCopy(file_name16, MAX_PATH, utf_8to16(file_name->str));
}
if (display_filter->len > 0) {
g_dfilter_str = g_strdup(display_filter->str);
} else if (g_dfilter_str) {
g_free(g_dfilter_str);
g_dfilter_str = NULL;
}
ofn = new OPENFILENAME();
ofn->lStructSize = ofnsize;
ofn->hwndOwner = h_wnd;
ofn->hInstance = (HINSTANCE) GetWindowLongPtr(h_wnd, GWLP_HINSTANCE);
ofn->lpstrFilter = build_file_open_type_list();
ofn->lpstrCustomFilter = NULL;
ofn->nMaxCustFilter = 0;
ofn->nFilterIndex = FILE_OPEN_DEFAULT;
ofn->lpstrFile = file_name16;
ofn->nMaxFile = MAX_PATH;
ofn->lpstrFileTitle = NULL;
ofn->nMaxFileTitle = 0;
if (prefs.gui_fileopen_style == FO_STYLE_SPECIFIED && prefs.gui_fileopen_dir[0] != '\0') {
ofn->lpstrInitialDir = utf_8to16(prefs.gui_fileopen_dir);
} else {
ofn->lpstrInitialDir = utf_8to16(get_last_open_dir());
}
ofn->lpstrTitle = title;
ofn->Flags = OFN_ENABLESIZING | OFN_ENABLETEMPLATE | OFN_EXPLORER |
OFN_NOCHANGEDIR | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY |
OFN_ENABLEHOOK | OFN_SHOWHELP;
ofn->lpstrDefExt = NULL;
ofn->lpfnHook = open_file_hook_proc;
ofn->lpTemplateName = _T("WIRESHARK_OPENFILENAME_TEMPLATE");
HANDLE save_da_ctx = set_thread_per_monitor_v2_awareness();
gofn_ok = GetOpenFileName(ofn);
revert_thread_per_monitor_v2_awareness(save_da_ctx);
if (gofn_ok) {
g_string_printf(file_name, "%s", utf_16to8(file_name16));
g_string_printf(display_filter, "%s", g_dfilter_str ? g_dfilter_str : "");
*type = g_format_type;
}
g_free( (void *) ofn->lpstrFilter);
delete ofn;
g_free(g_dfilter_str);
g_dfilter_str = NULL;
return gofn_ok;
}
gboolean
win32_save_as_file(HWND h_wnd, const wchar_t *title, capture_file *cf, GString *file_name, int *file_type,
wtap_compression_type *compression_type,
gboolean must_support_all_comments)
{
guint32 required_comment_types;
GArray *savable_file_types;
OPENFILENAME *ofn;
TCHAR file_name16[MAX_PATH] = _T("");
int ofnsize = sizeof(OPENFILENAME);
BOOL gsfn_ok;
if (!file_name || !file_type || !compression_type)
return FALSE;
if (file_name->len > 0) {
StringCchCopy(file_name16, MAX_PATH, utf_8to16(file_name->str));
}
/* What types of comments do we have to support? */
if (must_support_all_comments)
required_comment_types = cf_comment_types(cf); /* all the ones the file has */
else
required_comment_types = 0; /* none of them */
savable_file_types = wtap_get_savable_file_types_subtypes_for_file(cf->cd_t,
cf->linktypes,
required_comment_types,
FT_SORT_BY_DESCRIPTION);
if (savable_file_types == NULL)
return FALSE; /* shouldn't happen - the "Save As..." item should be disabled if we can't save the file */
g_compressed = FALSE;
ofn = new OPENFILENAME();
ofn->lStructSize = ofnsize;
ofn->hwndOwner = h_wnd;
ofn->hInstance = (HINSTANCE) GetWindowLongPtr(h_wnd, GWLP_HINSTANCE);
ofn->lpstrFilter = build_file_save_type_list(savable_file_types);
ofn->lpstrCustomFilter = NULL;
ofn->nMaxCustFilter = 0;
ofn->nFilterIndex = 1; /* the first entry is the best match; 1-origin indexing */
ofn->lpstrFile = file_name16;
ofn->nMaxFile = MAX_PATH;
ofn->lpstrFileTitle = NULL;
ofn->nMaxFileTitle = 0;
ofn->lpstrInitialDir = utf_8to16(get_last_open_dir());
ofn->lpstrTitle = title;
ofn->Flags = OFN_ENABLESIZING | OFN_ENABLETEMPLATE | OFN_EXPLORER |
OFN_NOCHANGEDIR | OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY |
OFN_PATHMUSTEXIST | OFN_ENABLEHOOK | OFN_SHOWHELP;
ofn->lpstrDefExt = NULL;
ofn->lCustData = (LPARAM) cf;
ofn->lpfnHook = save_as_file_hook_proc;
ofn->lpTemplateName = _T("WIRESHARK_SAVEASFILENAME_TEMPLATE");
HANDLE save_da_ctx = set_thread_per_monitor_v2_awareness();
gsfn_ok = GetSaveFileName(ofn);
revert_thread_per_monitor_v2_awareness(save_da_ctx);
if (gsfn_ok) {
g_string_printf(file_name, "%s", utf_16to8(file_name16));
/* What file format was specified? */
*file_type = g_array_index(savable_file_types, int, ofn->nFilterIndex - 1);
*compression_type = g_compressed ? WTAP_GZIP_COMPRESSED : WTAP_UNCOMPRESSED;
} else {
/* User cancelled or closed the dialog, or an error occurred. */
if (CommDlgExtendedError() != 0) {
/* XXX - pop up some error here. FNERR_INVALIDFILENAME
* might be a user error; if so, they should know about
* it. For now we force a do-over.
*/
g_string_truncate(file_name, 0);
gsfn_ok = TRUE;
}
}
g_sf_hwnd = NULL;
g_array_free(savable_file_types, TRUE);
g_free( (void *) ofn->lpstrFilter);
delete ofn;
return gsfn_ok;
}
gboolean
win32_export_specified_packets_file(HWND h_wnd, const wchar_t *title,
capture_file *cf,
GString *file_name,
int *file_type,
wtap_compression_type *compression_type,
packet_range_t *range) {
GArray *savable_file_types;
OPENFILENAME *ofn;
TCHAR file_name16[MAX_PATH] = _T("");
int ofnsize = sizeof(OPENFILENAME);
BOOL gsfn_ok;
if (!file_name || !file_type || !compression_type || !range)
return FALSE;
if (file_name->len > 0) {
StringCchCopy(file_name16, MAX_PATH, utf_8to16(file_name->str));
}
savable_file_types = wtap_get_savable_file_types_subtypes_for_file(cf->cd_t,
cf->linktypes, 0,
FT_SORT_BY_DESCRIPTION);
if (savable_file_types == NULL)
return FALSE; /* shouldn't happen - the "Save As..." item should be disabled if we can't save the file */
g_range = range;
g_cf = cf;
g_compressed = FALSE;
ofn = new OPENFILENAME();
ofn->lStructSize = ofnsize;
ofn->hwndOwner = h_wnd;
ofn->hInstance = (HINSTANCE) GetWindowLongPtr(h_wnd, GWLP_HINSTANCE);
ofn->lpstrFilter = build_file_save_type_list(savable_file_types);
ofn->lpstrCustomFilter = NULL;
ofn->nMaxCustFilter = 0;
ofn->nFilterIndex = 1; /* the first entry is the best match; 1-origin indexing */
ofn->lpstrFile = file_name16;
ofn->nMaxFile = MAX_PATH;
ofn->lpstrFileTitle = NULL;
ofn->nMaxFileTitle = 0;
ofn->lpstrInitialDir = utf_8to16(get_last_open_dir());
ofn->lpstrTitle = title;
ofn->Flags = OFN_ENABLESIZING | OFN_ENABLETEMPLATE | OFN_EXPLORER |
OFN_NOCHANGEDIR | OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY |
OFN_PATHMUSTEXIST | OFN_ENABLEHOOK | OFN_SHOWHELP;
ofn->lpstrDefExt = NULL;
ofn->lCustData = (LPARAM) cf;
ofn->lpfnHook = export_specified_packets_file_hook_proc;
ofn->lpTemplateName = _T("WIRESHARK_EXPORT_SPECIFIED_PACKETS_FILENAME_TEMPLATE");
HANDLE save_da_ctx = set_thread_per_monitor_v2_awareness();
gsfn_ok = GetSaveFileName(ofn);
revert_thread_per_monitor_v2_awareness(save_da_ctx);
if (gsfn_ok) {
g_string_printf(file_name, "%s", utf_16to8(file_name16));
/* What file format was specified? */
*file_type = g_array_index(savable_file_types, int, ofn->nFilterIndex - 1);
*compression_type = g_compressed ? WTAP_GZIP_COMPRESSED : WTAP_UNCOMPRESSED;
} else {
/* User cancelled or closed the dialog, or an error occurred. */
if (CommDlgExtendedError() != 0) {
/* XXX - pop up some error here. FNERR_INVALIDFILENAME
* might be a user error; if so, they should know about
* it. For now we force a do-over.
*/
g_string_truncate(file_name, 0);
gsfn_ok = TRUE;
}
}
g_sf_hwnd = NULL;
g_range = NULL;
g_cf = NULL;
g_array_free(savable_file_types, TRUE);
g_free( (void *) ofn->lpstrFilter);
delete ofn;
return gsfn_ok;
}
gboolean
win32_merge_file (HWND h_wnd, const wchar_t *title, GString *file_name, GString *display_filter, int *merge_type) {
OPENFILENAME *ofn;
TCHAR file_name16[MAX_PATH] = _T("");
int ofnsize = sizeof(OPENFILENAME);
BOOL gofn_ok;
if (!file_name || !display_filter || !merge_type)
return FALSE;
if (file_name->len > 0) {
StringCchCopy(file_name16, MAX_PATH, utf_8to16(file_name->str));
}
if (display_filter->len > 0) {
g_dfilter_str = g_strdup(display_filter->str);
} else if (g_dfilter_str) {
g_free(g_dfilter_str);
g_dfilter_str = NULL;
}
ofn = new OPENFILENAME();
ofn->lStructSize = ofnsize;
ofn->hwndOwner = h_wnd;
ofn->hInstance = (HINSTANCE) GetWindowLongPtr(h_wnd, GWLP_HINSTANCE);
ofn->lpstrFilter = build_file_open_type_list();
ofn->lpstrCustomFilter = NULL;
ofn->nMaxCustFilter = 0;
ofn->nFilterIndex = FILE_MERGE_DEFAULT;
ofn->lpstrFile = file_name16;
ofn->nMaxFile = MAX_PATH;
ofn->lpstrFileTitle = NULL;
ofn->nMaxFileTitle = 0;
if (prefs.gui_fileopen_style == FO_STYLE_SPECIFIED && prefs.gui_fileopen_dir[0] != '\0') {
ofn->lpstrInitialDir = utf_8to16(prefs.gui_fileopen_dir);
} else {
ofn->lpstrInitialDir = utf_8to16(get_last_open_dir());
}
ofn->lpstrTitle = title;
ofn->Flags = OFN_ENABLESIZING | OFN_ENABLETEMPLATE | OFN_EXPLORER |
OFN_NOCHANGEDIR | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY |
OFN_ENABLEHOOK | OFN_SHOWHELP;
ofn->lpstrDefExt = NULL;
ofn->lpfnHook = merge_file_hook_proc;
ofn->lpTemplateName = _T("WIRESHARK_MERGEFILENAME_TEMPLATE");
HANDLE save_da_ctx = set_thread_per_monitor_v2_awareness();
gofn_ok = GetOpenFileName(ofn);
revert_thread_per_monitor_v2_awareness(save_da_ctx);
if (gofn_ok) {
g_string_printf(file_name, "%s", utf_16to8(file_name16));
g_string_printf(display_filter, "%s", g_dfilter_str ? g_dfilter_str : "");
switch (g_merge_action) {
case merge_append:
*merge_type = 1;
break;
case merge_chrono:
*merge_type = 0;
break;
case merge_prepend:
*merge_type = -1;
break;
default:
ws_assert_not_reached();
}
}
g_free( (void *) ofn->lpstrFilter);
delete ofn;
g_free(g_dfilter_str);
g_dfilter_str = NULL;
return gofn_ok;
}
void
win32_export_file(HWND h_wnd, const wchar_t *title, capture_file *cf, export_type_e export_type, const gchar *range_) {
OPENFILENAME *ofn;
TCHAR file_name[MAX_PATH] = _T("");
char *dirname;
cf_print_status_t status;
int ofnsize = sizeof(OPENFILENAME);
g_cf = cf;
ofn = new OPENFILENAME();
ofn->lStructSize = ofnsize;
ofn->hwndOwner = h_wnd;
ofn->hInstance = (HINSTANCE) GetWindowLongPtr(h_wnd, GWLP_HINSTANCE);
ofn->lpstrFilter = FILE_TYPES_EXPORT;
ofn->lpstrCustomFilter = NULL;
ofn->nMaxCustFilter = 0;
ofn->nFilterIndex = export_type;
ofn->lpstrFile = file_name;
ofn->nMaxFile = MAX_PATH;
ofn->lpstrFileTitle = NULL;
ofn->nMaxFileTitle = 0;
ofn->lpstrInitialDir = utf_8to16(get_last_open_dir());
ofn->lpstrTitle = title;
ofn->Flags = OFN_ENABLESIZING | OFN_ENABLETEMPLATE | OFN_EXPLORER |
OFN_NOCHANGEDIR | OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY |
OFN_PATHMUSTEXIST | OFN_ENABLEHOOK | OFN_SHOWHELP;
ofn->lpstrDefExt = FILE_EXT_EXPORT[export_type];
ofn->lCustData = (LPARAM) cf;
ofn->lpfnHook = export_file_hook_proc;
ofn->lpTemplateName = _T("WIRESHARK_EXPORTFILENAME_TEMPLATE");
/* Fill in our print (and export) args */
/* init the printing range */
packet_range_init(&print_args.range, cf);
if (strlen(range_) > 0)
packet_range_convert_selection_str(&print_args.range, range_);
print_args.format = PR_FMT_TEXT;
print_args.to_file = TRUE;
print_args.cmd = NULL;
print_args.print_summary = TRUE;
print_args.print_col_headings = TRUE;
print_args.print_dissections = print_dissections_as_displayed;
print_args.print_hex = FALSE;
print_args.hexdump_options = HEXDUMP_SOURCE_MULTI;
print_args.print_formfeed = FALSE;
print_args.stream = NULL;
HANDLE save_da_ctx = set_thread_per_monitor_v2_awareness();
BOOL gsfn_ok = GetSaveFileName(ofn);
revert_thread_per_monitor_v2_awareness(save_da_ctx);
if (gsfn_ok) {
print_args.file = utf_16to8(file_name);
switch (ofn->nFilterIndex) {
case export_type_text: /* Text */
print_args.stream = print_stream_text_new(TRUE, print_args.file);
if (print_args.stream == NULL) {
open_failure_alert_box(print_args.file, errno, TRUE);
delete ofn;
return;
}
status = cf_print_packets(cf, &print_args, TRUE);
break;
case export_type_ps: /* PostScript (r) */
print_args.stream = print_stream_ps_new(TRUE, print_args.file);
if (print_args.stream == NULL) {
open_failure_alert_box(print_args.file, errno, TRUE);
delete ofn;
return;
}
status = cf_print_packets(cf, &print_args, TRUE);
break;
case export_type_csv: /* CSV */
status = cf_write_csv_packets(cf, &print_args);
break;
case export_type_carrays: /* C Arrays */
status = cf_write_carrays_packets(cf, &print_args);
break;
case export_type_psml: /* PSML */
status = cf_write_psml_packets(cf, &print_args);
break;
case export_type_pdml: /* PDML */
status = cf_write_pdml_packets(cf, &print_args);
break;
case export_type_json: /* JSON */
status = cf_write_json_packets(cf, &print_args);
break;
default:
delete ofn;
return;
}
switch (status) {
case CF_PRINT_OK:
break;
case CF_PRINT_OPEN_ERROR:
open_failure_alert_box(print_args.file, errno, TRUE);
break;
case CF_PRINT_WRITE_ERROR:
write_failure_alert_box(print_args.file, errno);
break;
}
/* Save the directory name for future file dialogs. */
dirname = get_dirname(utf_16to8(file_name)); /* Overwrites cf_name */
set_last_open_dir(dirname);
}
g_cf = NULL;
delete ofn;
}
/*
* Private routines
*/
/** Given a print_args_t struct, update a set of print/export format controls
* accordingly.
*
* @param dlg_hwnd HWND of the dialog in question.
* @param args Pointer to a print args struct.
*/
static void
print_update_dynamic(HWND dlg_hwnd, print_args_t *args) {
HWND cur_ctrl;
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_PKT_SUMMARY_CB);
if (SendMessage(cur_ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED) {
args->print_summary = TRUE;
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_COL_HEADINGS_CB);
EnableWindow(cur_ctrl, TRUE);
if (SendMessage(cur_ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED)
args->print_col_headings = TRUE;
else
args->print_col_headings = FALSE;
} else {
args->print_summary = FALSE;
args->print_col_headings = FALSE;
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_COL_HEADINGS_CB);
EnableWindow(cur_ctrl, FALSE);
}
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_PKT_DETAIL_CB);
if (SendMessage(cur_ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED) {
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_PKT_DETAIL_COMBO);
switch (SendMessage(cur_ctrl, CB_GETCURSEL, 0, 0)) {
case 0:
args->print_dissections = print_dissections_collapsed;
break;
case 1:
args->print_dissections = print_dissections_as_displayed;
break;
case 2:
args->print_dissections = print_dissections_expanded;
break;
default:
ws_assert_not_reached();
}
EnableWindow(cur_ctrl, TRUE);
} else {
args->print_dissections = print_dissections_none;
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_PKT_DETAIL_COMBO);
EnableWindow(cur_ctrl, FALSE);
}
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_PKT_BYTES_CB);
if (SendMessage(cur_ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED) {
args->print_hex = TRUE;
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_DATA_SOURCES_CB);
EnableWindow(cur_ctrl, TRUE);
if (SendMessage(cur_ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED)
args->hexdump_options = HEXDUMP_SOURCE_MULTI;
else
args->hexdump_options = HEXDUMP_SOURCE_PRIMARY;
} else {
args->print_hex = FALSE;
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_DATA_SOURCES_CB);
EnableWindow(cur_ctrl, FALSE);
}
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_PKT_NEW_PAGE_CB);
if (SendMessage(cur_ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED)
args->print_formfeed = TRUE;
else
args->print_formfeed = FALSE;
}
static void
format_handle_wm_initdialog(HWND dlg_hwnd, print_args_t *args) {
HWND cur_ctrl;
/* Set the "Packet summary" and "Include column headings" boxes */
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_PKT_SUMMARY_CB);
SendMessage(cur_ctrl, BM_SETCHECK, args->print_summary, 0);
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_COL_HEADINGS_CB);
SendMessage(cur_ctrl, BM_SETCHECK, args->print_col_headings, 0);
/* Set the "Packet details" box */
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_PKT_DETAIL_CB);
SendMessage(cur_ctrl, BM_SETCHECK, args->print_dissections != print_dissections_none, 0);
/* Set the "Packet details" combo */
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_PKT_DETAIL_COMBO);
SendMessage(cur_ctrl, CB_ADDSTRING, 0, (WPARAM) _T("All collapsed"));
SendMessage(cur_ctrl, CB_ADDSTRING, 0, (WPARAM) _T("As displayed"));
SendMessage(cur_ctrl, CB_ADDSTRING, 0, (WPARAM) _T("All expanded"));
switch (args->print_dissections) {
case print_dissections_none:
case print_dissections_collapsed:
SendMessage(cur_ctrl, CB_SETCURSEL, 0, 0);
break;
case print_dissections_as_displayed:
SendMessage(cur_ctrl, CB_SETCURSEL, 1, 0);
break;
case print_dissections_expanded:
SendMessage(cur_ctrl, CB_SETCURSEL, 2, 0);
break;
default:
ws_assert_not_reached();
}
/* Set the "Packet bytes" box */
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_PKT_BYTES_CB);
SendMessage(cur_ctrl, BM_SETCHECK, args->print_hex, 0);
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_DATA_SOURCES_CB);
SendMessage(cur_ctrl, BM_SETCHECK, !(args->hexdump_options & HEXDUMP_SOURCE_PRIMARY), 0);
/* Set the "Each packet on a new page" box */
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_PKT_NEW_PAGE_CB);
SendMessage(cur_ctrl, BM_SETCHECK, args->print_formfeed, 0);
print_update_dynamic(dlg_hwnd, args);
}
#define PREVIEW_STR_MAX 200
/* If preview_file is NULL, disable the elements. If not, enable and
* show the preview info. */
static gboolean
preview_set_file_info(HWND of_hwnd, gchar *preview_file) {
HWND cur_ctrl;
int i;
wtap *wth;
int err;
gchar *err_info;
ws_file_preview_stats stats;
ws_file_preview_stats_status status;
TCHAR string_buff[PREVIEW_STR_MAX];
TCHAR first_buff[PREVIEW_STR_MAX];
gint64 filesize;
gchar *size_str;
time_t ti_time;
struct tm *ti_tm;
guint elapsed_time;
for (i = EWFD_PTX_FORMAT; i <= EWFD_PTX_START_ELAPSED; i++) {
cur_ctrl = GetDlgItem(of_hwnd, i);
if (cur_ctrl) {
EnableWindow(cur_ctrl, FALSE);
}
}
for (i = EWFD_PTX_FORMAT; i <= EWFD_PTX_START_ELAPSED; i++) {
cur_ctrl = GetDlgItem(of_hwnd, i);
if (cur_ctrl) {
SetWindowText(cur_ctrl, _T("-"));
}
}
if (preview_file == NULL || strlen(preview_file) < 1) {
return FALSE;
}
/* Format: directory */
cur_ctrl = GetDlgItem(of_hwnd, EWFD_PTX_FORMAT);
if (test_for_directory(preview_file) == EISDIR) {
SetWindowText(cur_ctrl, _T("directory"));
return FALSE;
}
wth = wtap_open_offline(preview_file, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
if (cur_ctrl && wth == NULL) {
if(err == WTAP_ERR_FILE_UNKNOWN_FORMAT) {
SetWindowText(cur_ctrl, _T("unknown file format"));
} else {
SetWindowText(cur_ctrl, _T("error opening file"));
}
return FALSE;
}
/* Success! */
for (i = EWFD_PT_FORMAT; i <= EWFD_PTX_START_ELAPSED; i++) {
cur_ctrl = GetDlgItem(of_hwnd, i);
if (cur_ctrl) {
EnableWindow(cur_ctrl, TRUE);
}
}
/* Format */
cur_ctrl = GetDlgItem(of_hwnd, EWFD_PTX_FORMAT);
SetWindowText(cur_ctrl, utf_8to16(wtap_file_type_subtype_description(wtap_file_type_subtype(wth))));
/* Size */
filesize = wtap_file_size(wth, &err);
// Windows Explorer uses IEC.
size_str = format_size(filesize, FORMAT_SIZE_UNIT_BYTES, FORMAT_SIZE_PREFIX_IEC);
status = get_stats_for_preview(wth, &stats, &err, &err_info);
if(status == PREVIEW_READ_ERROR) {
/* XXX - give error details? */
g_free(err_info);
utf_8to16_snprintf(string_buff, PREVIEW_STR_MAX, "%s, error after %u records",
size_str, stats.records);
g_free(size_str);
cur_ctrl = GetDlgItem(of_hwnd, EWFD_PTX_SIZE);
SetWindowText(cur_ctrl, string_buff);
wtap_close(wth);
return TRUE;
}
/* Packet count */
if(status == PREVIEW_TIMED_OUT) {
utf_8to16_snprintf(string_buff, PREVIEW_STR_MAX, "%s, timed out at %u data records",
size_str, stats.data_records);
} else {
utf_8to16_snprintf(string_buff, PREVIEW_STR_MAX, "%s, %u data records",
size_str, stats.data_records);
}
g_free(size_str);
cur_ctrl = GetDlgItem(of_hwnd, EWFD_PTX_SIZE);
SetWindowText(cur_ctrl, string_buff);
/* First packet / elapsed time */
if(stats.have_times) {
/*
* We saw at least one record with a time stamp, so we can give
* a start time (if we have a mix of records with and without
* time stamps, and there were records without time stamps
* before the one with a time stamp, this may be inaccurate).
*/
ti_time = (long)stats.start_time;
ti_tm = localtime( &ti_time );
if(ti_tm) {
StringCchPrintf(first_buff, PREVIEW_STR_MAX,
_T("%04d-%02d-%02d %02d:%02d:%02d"),
ti_tm->tm_year + 1900,
ti_tm->tm_mon + 1,
ti_tm->tm_mday,
ti_tm->tm_hour,
ti_tm->tm_min,
ti_tm->tm_sec);
} else {
StringCchPrintf(first_buff, PREVIEW_STR_MAX, _T("?"));
}
} else {
StringCchPrintf(first_buff, PREVIEW_STR_MAX, _T("unknown"));
}
/* Elapsed time */
if(status == PREVIEW_SUCCEEDED && stats.have_times) {
/*
* We didn't time out, so we looked at all packets, and we got
* at least one packet with a time stamp, so we can calculate
* an elapsed time from the time stamp of the last packet with
* with a time stamp (if we have a mix of records with and without
* time stamps, and there were records without time stamps after
* the last one with a time stamp, this may be inaccurate).
*/
elapsed_time = (unsigned int)(stats.stop_time-stats.start_time);
if (elapsed_time/86400) {
StringCchPrintf(string_buff, PREVIEW_STR_MAX, _T("%s / %02u days %02u:%02u:%02u"),
first_buff, elapsed_time/86400, elapsed_time%86400/3600, elapsed_time%3600/60, elapsed_time%60);
} else {
StringCchPrintf(string_buff, PREVIEW_STR_MAX, _T("%s / %02u:%02u:%02u"),
first_buff, elapsed_time%86400/3600, elapsed_time%3600/60, elapsed_time%60);
}
} else {
StringCchPrintf(string_buff, PREVIEW_STR_MAX, _T("%s / unknown"),
first_buff);
}
cur_ctrl = GetDlgItem(of_hwnd, EWFD_PTX_START_ELAPSED);
SetWindowText(cur_ctrl, string_buff);
wtap_close(wth);
return TRUE;
}
static char *
filter_tb_get(HWND hwnd) {
TCHAR *strval = NULL;
gint len;
char *ret;
/* If filter_text is non-NULL, use it. Otherwise, grab the text from
* the window */
len = GetWindowTextLength(hwnd);
if (len > 0) {
len++;
strval = g_new(TCHAR, len);
len = GetWindowText(hwnd, strval, len);
ret = g_utf16_to_utf8((gunichar2 *) strval, -1, NULL, NULL, NULL);
g_free(strval);
return ret;
} else {
return NULL;
}
}
/* XXX - Copied from "filter-util.c" in the wireshark-win32 branch */
/* XXX - The only reason for the "filter_text" parameter is to be able to feed
* in the "real" filter string in the case of a CBN_SELCHANGE notification message.
*/
static void
filter_tb_syntax_check(HWND hwnd, const TCHAR *filter_text) {
std::wstring strval;
dfilter_t *dfp;
/* If filter_text is non-NULL, use it. Otherwise, grab the text from
* the window */
if (filter_text) {
strval = filter_text;
} else {
int len = GetWindowTextLength(hwnd);
if (len > 0) {
len++;
strval.resize(len);
len = GetWindowText(hwnd, &strval[0], len);
strval.resize(len);
}
}
if (strval.empty()) {
/* Default window background */
SendMessage(hwnd, EM_SETBKGNDCOLOR, (WPARAM) 1, COLOR_WINDOW);
return;
} else if (dfilter_compile(utf_16to8(strval.c_str()), &dfp, NULL)) { /* colorize filter string entry */
dfilter_free(dfp);
/* Valid (light green) */
SendMessage(hwnd, EM_SETBKGNDCOLOR, 0, RGB(0xe4, 0xff, 0xc7)); /* tango_chameleon_1 */
} else {
/* Invalid (light red) */
SendMessage(hwnd, EM_SETBKGNDCOLOR, 0, RGB(0xff, 0xcc, 0xcc)); /* tango_scarlet_red_1 */
}
}
static gint alpha_sort(gconstpointer a, gconstpointer b)
{
return g_ascii_strcasecmp(*(const char **)a, *(const char **)b);
}
static UINT_PTR CALLBACK
open_file_hook_proc(HWND of_hwnd, UINT msg, WPARAM w_param, LPARAM l_param) {
HWND cur_ctrl, parent;
OFNOTIFY *notify = (OFNOTIFY *) l_param;
TCHAR sel_name[MAX_PATH];
gint i;
switch(msg) {
case WM_INITDIALOG:
{
/* Retain the filter text, and fill it in. */
if(g_dfilter_str != NULL) {
cur_ctrl = GetDlgItem(of_hwnd, EWFD_FILTER_EDIT);
SetWindowText(cur_ctrl, utf_8to16(g_dfilter_str));
}
/* Put Auto, as well as pcap and pcapng (which are the first two entries in
open_routines), at the top of the file type list. */
cur_ctrl = GetDlgItem(of_hwnd, EWFD_FORMAT_TYPE);
SendMessage(cur_ctrl, CB_ADDSTRING, 0, (WPARAM) _T("Automatically detect file type"));
for (i = 0; i < 2; i += 1) {
SendMessage(cur_ctrl, CB_ADDSTRING, 0, (WPARAM) utf_8to16(open_routines[i].name));
}
/* Generate a sorted list of the remaining file types.
The magic number 60 is a rough starting point for how big the
GPtrArray should start. It'll automatically grow if needed, so
the exact number isn't critical. (This is good, because we don't have
an easy way to get the exact number.) */
GPtrArray *routine_names = g_ptr_array_sized_new(60);
for ( /* keep using i */ ; open_routines[i].name != NULL; i += 1) {
g_ptr_array_add(routine_names, (gpointer)open_routines[i].name);
}
g_ptr_array_sort(routine_names, alpha_sort);
for (guint i = 0; i < routine_names->len; i += 1) {
SendMessage(cur_ctrl, CB_ADDSTRING, 0, (WPARAM) utf_8to16((const char *)g_ptr_array_index(routine_names, i)));
}
g_ptr_array_free(routine_names, TRUE);
SendMessage(cur_ctrl, CB_SETCURSEL, 0, 0);
preview_set_file_info(of_hwnd, NULL);
}
break;
case WM_NOTIFY:
switch (notify->hdr.code) {
case CDN_FILEOK:
/* Fetch the read filter */
cur_ctrl = GetDlgItem(of_hwnd, EWFD_FILTER_EDIT);
g_free(g_dfilter_str);
g_dfilter_str = filter_tb_get(cur_ctrl);
cur_ctrl = GetDlgItem(of_hwnd, EWFD_FORMAT_TYPE);
g_format_type = (unsigned int) SendMessage(cur_ctrl, CB_GETCURSEL, 0, 0);
/* The list of file formats is sorted. Get the format by name. */
LRESULT label_len;
label_len = SendMessage(cur_ctrl, CB_GETLBTEXTLEN, (WPARAM) g_format_type, 0);
if (label_len != CB_ERR) {
TCHAR *label = g_new(TCHAR, label_len+1);
SendMessage(cur_ctrl, CB_GETLBTEXT, (WPARAM) g_format_type, (LPARAM) label);
g_format_type = open_info_name_to_type(utf_16to8(label));
g_free(label);
}
else {
/* Problem, fall back on automatic */
g_format_type = WTAP_TYPE_AUTO;
}
break;
case CDN_SELCHANGE:
/* This _almost_ works correctly. We need to handle directory
selections, etc. */
parent = GetParent(of_hwnd);
CommDlg_OpenSave_GetFilePath(parent, sel_name, MAX_PATH);
preview_set_file_info(of_hwnd, utf_16to8(sel_name));
break;
case CDN_HELP:
topic_action(HELP_OPEN_WIN32_DIALOG);
break;
default:
break;
}
break;
case WM_COMMAND:
cur_ctrl = (HWND) l_param;
switch(w_param) {
case (EN_UPDATE << 16) | EWFD_FILTER_EDIT:
filter_tb_syntax_check(cur_ctrl, NULL);
break;
/*
* If we ever figure out a way to integrate the Windows
* and GTK+ event loops (or make a native filter dialog),
* we can re-enable the "Filter" button.
*/
/*
case EWFD_FILTER_BTN:
break;
*/
default:
break;
}
break;
default:
break;
}
return 0;
}
/* Generate a list of the file types we can filter for in the open dialog. */
static void
append_file_extension_type(GArray *sa, int et)
{
GString* pattern_str = g_string_new("");
GString* description_str = g_string_new("");
gchar sep;
GSList *extensions_list, *extension;
const TCHAR *str16;
guint16 zero = 0;
/* Construct the list of patterns. */
extensions_list = wtap_get_file_extension_type_extensions(et);
sep = '\0';
for (extension = extensions_list; extension != NULL;
extension = g_slist_next(extension)) {
if (sep != '\0')
g_string_append_c(pattern_str, sep);
g_string_append_printf(pattern_str, "*.%s", (char *)extension->data);
sep = ';';
}
wtap_free_extensions_list(extensions_list);
/* Construct the description. */
g_string_printf(description_str, "%s (%s)",
wtap_get_file_extension_type_name(et),
pattern_str->str);
str16 = utf_8to16(description_str->str);
sa = g_array_append_vals(sa, str16, (guint) strlen(description_str->str));
sa = g_array_append_val(sa, zero);
g_string_free(description_str, TRUE);
str16 = utf_8to16(pattern_str->str);
sa = g_array_append_vals(sa, str16, (guint) strlen(pattern_str->str));
sa = g_array_append_val(sa, zero);
g_string_free(pattern_str, TRUE);
}
static TCHAR *
build_file_open_type_list(void) {
const TCHAR *str16;
int et;
GArray* sa;
static const guint16 zero = 0;
GString* pattern_str;
gchar sep;
GSList *extensions_list, *extension;
/*
* Microsoft's UI guidelines say, of the file filters in open and
* save dialogs:
*
* For meta-filters, remove the file extension list to eliminate
* clutter. Examples: "All files," "All pictures," "All music,"
* and "All videos."
*
* so we omit them (for "All Capture Files", the filter would be
* *really* long). On both Windows XP and Windows 7, Wordpad doesn't
* do that, but Paint does.
*/
/*
* Array of hexadectets used as a sequence of null-terminated
* UTF-16 strings.
*/
sa = g_array_new(FALSE /*zero_terminated*/, FALSE /*clear_*/,2 /*element_size*/);
/* Add the "All Files" entry. */
str16 = utf_8to16("All Files");
sa = g_array_append_vals(sa, str16, (guint) strlen("All Files"));
sa = g_array_append_val(sa, zero);
str16 = utf_8to16(ALL_FILES_WILDCARD);
sa = g_array_append_vals(sa, str16, (guint) strlen(ALL_FILES_WILDCARD));
sa = g_array_append_val(sa, zero);
/*
* Add an "All Capture Files" entry, with all the capture file
* extensions we know about.
*/
str16 = utf_8to16("All Capture Files");
sa = g_array_append_vals(sa, str16, (guint) strlen("All Capture Files"));
sa = g_array_append_val(sa, zero);
/*
* Construct its list of patterns.
*/
pattern_str = g_string_new("");
extensions_list = wtap_get_all_capture_file_extensions_list();
sep = '\0';
for (extension = extensions_list; extension != NULL;
extension = g_slist_next(extension)) {
if (sep != '\0')
g_string_append_c(pattern_str, sep);
g_string_append_printf(pattern_str, "*.%s", (char *)extension->data);
sep = ';';
}
wtap_free_extensions_list(extensions_list);
str16 = utf_8to16(pattern_str->str);
sa = g_array_append_vals(sa, str16, (guint) strlen(pattern_str->str));
sa = g_array_append_val(sa, zero);
/* Include all the file type extensions Wireshark supports. */
for (et = 0; et < wtap_get_num_file_type_extensions(); et++) {
append_file_extension_type(sa, et);
}
/* terminate the array */
sa = g_array_append_val(sa, zero);
return (TCHAR *) g_array_free(sa, FALSE /*free_segment*/);
}
/* Generate a list of the file types we can save this file as.
"g_filetype" is the type it has now.
"encap" is the encapsulation for its packets (which could be
"unknown" or "per-packet").
"filtered" is TRUE if we're to save only the packets that passed
the display filter (in which case we have to save it using Wiretap)
and FALSE if we're to save the entire file (in which case, if we're
saving it in the type it has already, we can just copy it).
The same applies for sel_curr, sel_all, sel_m_only, sel_m_range and sel_man_range
*/
static void
append_file_type(GArray *sa, int ft)
{
GString* pattern_str = g_string_new("");
GString* description_str = g_string_new("");
gchar sep;
GSList *extensions_list, *extension;
const TCHAR *str16;
guint16 zero = 0;
extensions_list = wtap_get_file_extensions_list(ft, TRUE);
if (extensions_list == NULL) {
/* This file type doesn't have any particular extension
conventionally used for it, so we'll just use a
wildcard that matches all file names - even those with
no extension, so we don't need to worry about compressed
file extensions. */
g_string_printf(pattern_str, ALL_FILES_WILDCARD);
} else {
/* Construct the list of patterns. */
sep = '\0';
for (extension = extensions_list; extension != NULL;
extension = g_slist_next(extension)) {
if (sep != '\0')
g_string_append_c(pattern_str, sep);
g_string_append_printf(pattern_str, "*.%s", (char *)extension->data);
sep = ';';
}
wtap_free_extensions_list(extensions_list);
}
/* Construct the description. */
g_string_printf(description_str, "%s (%s)", wtap_file_type_subtype_description(ft),
pattern_str->str);
str16 = utf_8to16(description_str->str);
sa = g_array_append_vals(sa, str16, (guint) strlen(description_str->str));
sa = g_array_append_val(sa, zero);
g_string_free(description_str, TRUE);
str16 = utf_8to16(pattern_str->str);
sa = g_array_append_vals(sa, str16, (guint) strlen(pattern_str->str));
sa = g_array_append_val(sa, zero);
g_string_free(pattern_str, TRUE);
}
static TCHAR *
build_file_save_type_list(GArray *savable_file_types) {
guint i;
int ft;
GArray* sa = g_array_new(FALSE /*zero_terminated*/, FALSE /*clear_*/,2 /*element_size*/);
guint16 zero = 0;
/* Get only the file types as which we can save this file. */
for (i = 0; i < savable_file_types->len; i++) {
ft = g_array_index(savable_file_types, int, i);
append_file_type(sa, ft);
}
/* terminate the array */
sa = g_array_append_val(sa, zero);
return (TCHAR *) g_array_free(sa, FALSE /*free_segment*/);
}
static UINT_PTR CALLBACK
save_as_file_hook_proc(HWND sf_hwnd, UINT msg, WPARAM w_param _U_, LPARAM l_param) {
HWND cur_ctrl;
OFNOTIFY *notify = (OFNOTIFY *) l_param;
/*int new_filetype, file_index;*/
switch(msg) {
case WM_INITDIALOG: {
OPENFILENAME *ofnp = (OPENFILENAME *) l_param;
capture_file *cf = (capture_file *) ofnp->lCustData;
g_sf_hwnd = sf_hwnd;
/* Default to saving in the file's current format. */
g_filetype = cf->cd_t;
/* Fill in the file format list */
/*build_file_format_list(sf_hwnd);*/
/* Fill in the compression checkbox */
cur_ctrl = GetDlgItem(sf_hwnd, EWFD_GZIP_CB);
SendMessage(cur_ctrl, BM_SETCHECK, g_compressed, 0);
break;
}
case WM_COMMAND:
break;
case WM_NOTIFY:
switch (notify->hdr.code) {
case CDN_HELP:
topic_action(HELP_SAVE_WIN32_DIALOG);
break;
case CDN_FILEOK: {
HWND parent;
char *file_name8;
OPENFILENAME *ofnp = (OPENFILENAME *) notify->lpOFN;
capture_file *cf = (capture_file *) ofnp->lCustData;
/* Fetch our compression value */
cur_ctrl = GetDlgItem(sf_hwnd, EWFD_GZIP_CB);
if (SendMessage(cur_ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED)
g_compressed = TRUE;
else
g_compressed = FALSE;
/* Check if we're trying to overwrite the currently open file */
parent = GetParent(sf_hwnd);
file_name8 = utf_16to8(notify->lpOFN->lpstrFile);
if (files_identical(cf->filename, file_name8)) {
/* XXX: Is MessageBox the best way to pop up an error ? How to make text bold ? */
gchar *str = ws_strdup_printf(
"Capture File \"%s\" identical to loaded file.\n\n"
"Please choose a different filename.",
file_name8);
MessageBox( parent, utf_8to16(str), _T("Error"), MB_ICONERROR | MB_APPLMODAL | MB_OK);
g_free(str);
SetWindowLongPtr(sf_hwnd, DWLP_MSGRESULT, 1L); /* Don't allow ! */
return 1;
}
}
break;
default:
break;
}
break;
default:
break;
}
return 0;
}
#define RANGE_TEXT_MAX 128
static UINT_PTR CALLBACK
export_specified_packets_file_hook_proc(HWND sf_hwnd, UINT msg, WPARAM w_param, LPARAM l_param) {
HWND cur_ctrl;
OFNOTIFY *notify = (OFNOTIFY *) l_param;
/*int new_filetype, file_index;*/
switch(msg) {
case WM_INITDIALOG: {
g_sf_hwnd = sf_hwnd;
/* Default to saving all packets, in the file's current format. */
g_filetype = g_cf->cd_t;
/* Fill in the file format list */
/*build_file_format_list(sf_hwnd);*/
range_handle_wm_initdialog(sf_hwnd, g_range);
/* Fill in the compression checkbox */
cur_ctrl = GetDlgItem(sf_hwnd, EWFD_GZIP_CB);
SendMessage(cur_ctrl, BM_SETCHECK, g_compressed, 0);
break;
}
case WM_COMMAND:
cur_ctrl = (HWND) l_param;
range_handle_wm_command(sf_hwnd, cur_ctrl, w_param, g_range);
break;
case WM_NOTIFY:
switch (notify->hdr.code) {
case CDN_HELP:
topic_action(HELP_SAVE_WIN32_DIALOG);
break;
case CDN_FILEOK: {
HWND parent;
char *file_name8;
OPENFILENAME *ofnp = (OPENFILENAME *) notify->lpOFN;
capture_file *cf = (capture_file *) ofnp->lCustData;
/* Fetch our compression value */
cur_ctrl = GetDlgItem(sf_hwnd, EWFD_GZIP_CB);
if (SendMessage(cur_ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED)
g_compressed = TRUE;
else
g_compressed = FALSE;
/* Check if we're trying to overwrite the currently open file */
parent = GetParent(sf_hwnd);
file_name8 = utf_16to8(notify->lpOFN->lpstrFile);
if (files_identical(cf->filename, file_name8)) {
/* XXX: Is MessageBox the best way to pop up an error ? How to make text bold ? */
gchar *str = ws_strdup_printf(
"Capture File \"%s\" identical to loaded file.\n\n"
"Please choose a different filename.",
file_name8);
MessageBox( parent, utf_8to16(str), _T("Error"), MB_ICONERROR | MB_APPLMODAL | MB_OK);
g_free(str);
SetWindowLongPtr(sf_hwnd, DWLP_MSGRESULT, 1L); /* Don't allow ! */
return 1;
}
}
break;
default:
break;
}
break;
default:
break;
}
return 0;
}
#define STATIC_LABEL_CHARS 100
/* For each range static control, fill in its value and enable/disable it. */
static void
range_update_dynamics(HWND dlg_hwnd, packet_range_t *range) {
HWND cur_ctrl;
gboolean filtered_active = FALSE;
TCHAR static_val[STATIC_LABEL_CHARS];
guint32 ignored_cnt = 0, displayed_ignored_cnt = 0;
guint32 displayed_cnt;
gboolean range_valid = TRUE;
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_DISPLAYED_BTN);
if (SendMessage(cur_ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED)
filtered_active = TRUE;
/* RANGE_SELECT_ALL */
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_ALL_PKTS_CAP);
EnableWindow(cur_ctrl, !filtered_active);
if (range->remove_ignored) {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), g_cf->count - range->ignored_cnt);
} else {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), g_cf->count);
}
SetWindowText(cur_ctrl, static_val);
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_ALL_PKTS_DISP);
EnableWindow(cur_ctrl, filtered_active);
if (range->include_dependents)
displayed_cnt = range->displayed_plus_dependents_cnt;
else
displayed_cnt = range->displayed_cnt;
if (range->remove_ignored) {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), displayed_cnt - range->displayed_ignored_cnt);
} else {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), displayed_cnt);
}
SetWindowText(cur_ctrl, static_val);
/* RANGE_SELECT_CURR */
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_SEL_PKT_CAP);
EnableWindow(cur_ctrl, range->selection_range_cnt > 0 && !filtered_active);
if (range->remove_ignored) {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%d"), range->selection_range_cnt - range->ignored_selection_range_cnt);
} else {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%d"), range->selection_range_cnt);
}
SetWindowText(cur_ctrl, static_val);
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_SEL_PKT_DISP);
EnableWindow(cur_ctrl, range->displayed_selection_range_cnt > 0 && filtered_active);
if (range->remove_ignored) {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%d"), range->displayed_selection_range_cnt - range->displayed_ignored_selection_range_cnt);
} else {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%d"), range->displayed_selection_range_cnt);
}
SetWindowText(cur_ctrl, static_val);
/* RANGE_SELECT_MARKED */
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_MARKED_BTN);
EnableWindow(cur_ctrl, g_cf->marked_count);
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_MARKED_CAP);
EnableWindow(cur_ctrl, g_cf->marked_count && !filtered_active);
if (range->remove_ignored) {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), g_cf->marked_count - range->ignored_marked_cnt);
} else {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), g_cf->marked_count);
}
SetWindowText(cur_ctrl, static_val);
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_MARKED_DISP);
EnableWindow(cur_ctrl, g_cf->marked_count && filtered_active);
if (range->remove_ignored) {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), range->displayed_marked_cnt - range->displayed_ignored_marked_cnt);
} else {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), range->displayed_marked_cnt);
}
SetWindowText(cur_ctrl, static_val);
/* RANGE_SELECT_MARKED_RANGE */
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_FIRST_LAST_BTN);
EnableWindow(cur_ctrl, range->mark_range_cnt);
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_FIRST_LAST_CAP);
EnableWindow(cur_ctrl, range->mark_range_cnt && !filtered_active);
if (range->remove_ignored) {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), range->mark_range_cnt - range->ignored_mark_range_cnt);
} else {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), range->mark_range_cnt);
}
SetWindowText(cur_ctrl, static_val);
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_FIRST_LAST_DISP);
EnableWindow(cur_ctrl, range->displayed_mark_range_cnt && filtered_active);
if (range->remove_ignored) {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), range->displayed_mark_range_cnt - range->displayed_ignored_mark_range_cnt);
} else {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), range->displayed_mark_range_cnt);
}
SetWindowText(cur_ctrl, static_val);
/* RANGE_SELECT_USER */
switch (packet_range_check(range)) {
case CVT_NO_ERROR:
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_RANGE_EDIT);
SendMessage(cur_ctrl, EM_SETBKGNDCOLOR, (WPARAM) 1, COLOR_WINDOW);
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_RANGE_CAP);
EnableWindow(cur_ctrl, !filtered_active);
if (range->remove_ignored) {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), range->user_range_cnt - range->ignored_user_range_cnt);
} else {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), range->user_range_cnt);
}
SetWindowText(cur_ctrl, static_val);
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_RANGE_DISP);
EnableWindow(cur_ctrl, filtered_active);
if (range->remove_ignored) {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), range->displayed_user_range_cnt - range->displayed_ignored_user_range_cnt);
} else {
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), range->displayed_user_range_cnt);
}
SetWindowText(cur_ctrl, static_val);
break;
case CVT_SYNTAX_ERROR:
if (range->process == range_process_user_range) range_valid = FALSE;
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_RANGE_EDIT);
SendMessage(cur_ctrl, EM_SETBKGNDCOLOR, 0, RGB(0xff, 0xcc, 0xcc));
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_RANGE_CAP);
SetWindowText(cur_ctrl, _T("Bad range"));
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_RANGE_DISP);
SetWindowText(cur_ctrl, _T("-"));
break;
case CVT_NUMBER_TOO_BIG:
if (range->process == range_process_user_range) range_valid = FALSE;
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_RANGE_EDIT);
SendMessage(cur_ctrl, EM_SETBKGNDCOLOR, 0, RGB(0xff, 0xcc, 0xcc));
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_RANGE_CAP);
SetWindowText(cur_ctrl, _T("Too large"));
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_RANGE_DISP);
SetWindowText(cur_ctrl, _T("-"));
break;
default:
ws_assert_not_reached();
}
/* RANGE_REMOVE_IGNORED_PACKETS */
switch(range->process) {
case(range_process_all):
ignored_cnt = range->ignored_cnt;
displayed_ignored_cnt = range->displayed_ignored_cnt;
break;
case(range_process_selected):
ignored_cnt = range->ignored_selection_range_cnt;
displayed_ignored_cnt = range->displayed_ignored_selection_range_cnt;
break;
case(range_process_marked):
ignored_cnt = range->ignored_marked_cnt;
displayed_ignored_cnt = range->displayed_ignored_marked_cnt;
break;
case(range_process_marked_range):
ignored_cnt = range->ignored_mark_range_cnt;
displayed_ignored_cnt = range->displayed_ignored_mark_range_cnt;
break;
case(range_process_user_range):
ignored_cnt = range->ignored_user_range_cnt;
displayed_ignored_cnt = range->displayed_ignored_user_range_cnt;
break;
default:
ws_assert_not_reached();
}
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_REMOVE_IGN_CB);
EnableWindow(cur_ctrl, ignored_cnt);
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_IGNORED_CAP);
EnableWindow(cur_ctrl, ignored_cnt && !filtered_active);
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), ignored_cnt);
SetWindowText(cur_ctrl, static_val);
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_IGNORED_DISP);
EnableWindow(cur_ctrl, displayed_ignored_cnt && filtered_active);
StringCchPrintf(static_val, STATIC_LABEL_CHARS, _T("%u"), displayed_ignored_cnt);
SetWindowText(cur_ctrl, static_val);
cur_ctrl = GetDlgItem(GetParent(dlg_hwnd), IDOK);
EnableWindow(cur_ctrl, range_valid);
}
static void
range_handle_wm_initdialog(HWND dlg_hwnd, packet_range_t *range) {
HWND cur_ctrl;
/* Set the appropriate captured/displayed radio */
if (range->process_filtered)
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_DISPLAYED_BTN);
else
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_CAPTURED_BTN);
SendMessage(cur_ctrl, BM_SETCHECK, TRUE, 0);
/* Retain the filter text, and fill it in. */
if(range->user_range != NULL) {
char* tmp_str;
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_RANGE_EDIT);
tmp_str = range_convert_range(NULL, range->user_range);
SetWindowText(cur_ctrl, utf_8to16(tmp_str));
wmem_free(NULL, tmp_str);
}
/* dynamic values in the range frame */
range_update_dynamics(dlg_hwnd, range);
/* Set the appropriate range radio */
switch(range->process) {
case(range_process_all):
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_ALL_PKTS_BTN);
break;
case(range_process_selected):
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_SEL_PKT_BTN);
break;
case(range_process_marked):
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_MARKED_BTN);
break;
case(range_process_marked_range):
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_FIRST_LAST_BTN);
break;
case(range_process_user_range):
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_RANGE_BTN);
break;
default:
ws_assert_not_reached();
}
SendMessage(cur_ctrl, BM_SETCHECK, TRUE, 0);
}
static void
range_handle_wm_command(HWND dlg_hwnd, HWND ctrl, WPARAM w_param, packet_range_t *range) {
HWND cur_ctrl;
TCHAR range_text[RANGE_TEXT_MAX];
if (!range) return;
switch(w_param) {
case (BN_CLICKED << 16) | EWFD_CAPTURED_BTN:
case (BN_CLICKED << 16) | EWFD_DISPLAYED_BTN:
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_CAPTURED_BTN);
if (SendMessage(cur_ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED)
range->process_filtered = FALSE;
else
range->process_filtered = TRUE;
range_update_dynamics(dlg_hwnd, range);
break;
case (BN_CLICKED << 16) | EWFD_ALL_PKTS_BTN:
if (SendMessage(ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED) {
range->process = range_process_all;
range_update_dynamics(dlg_hwnd, range);
}
break;
case (BN_CLICKED << 16) | EWFD_SEL_PKT_BTN:
if (SendMessage(ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED) {
range->process = range_process_selected;
range_update_dynamics(dlg_hwnd, range);
}
break;
case (BN_CLICKED << 16) | EWFD_MARKED_BTN:
if (SendMessage(ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED) {
range->process = range_process_marked;
range_update_dynamics(dlg_hwnd, range);
}
break;
case (BN_CLICKED << 16) | EWFD_FIRST_LAST_BTN:
if (SendMessage(ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED) {
range->process = range_process_marked_range;
range_update_dynamics(dlg_hwnd, range);
}
break;
case (BN_CLICKED << 16) | EWFD_RANGE_BTN:
if (SendMessage(ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED) {
range->process = range_process_user_range;
range_update_dynamics(dlg_hwnd, range);
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_RANGE_EDIT);
SetFocus(cur_ctrl);
}
break;
case (EN_SETFOCUS << 16) | EWFD_RANGE_EDIT:
cur_ctrl = GetDlgItem(dlg_hwnd, EWFD_RANGE_BTN);
SendMessage(cur_ctrl, BM_CLICK, 0, 0);
break;
case (EN_UPDATE << 16) | EWFD_RANGE_EDIT:
SendMessage(ctrl, WM_GETTEXT, (WPARAM) RANGE_TEXT_MAX, (LPARAM) range_text);
packet_range_convert_str(range, utf_16to8(range_text));
range_update_dynamics(dlg_hwnd, range);
break;
case (BN_CLICKED << 16) | EWFD_REMOVE_IGN_CB:
if (SendMessage(ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED) {
range->remove_ignored = TRUE;
} else {
range->remove_ignored = FALSE;
}
range_update_dynamics(dlg_hwnd, range);
break;
}
}
static UINT_PTR CALLBACK
merge_file_hook_proc(HWND mf_hwnd, UINT msg, WPARAM w_param, LPARAM l_param) {
HWND cur_ctrl, parent;
OFNOTIFY *notify = (OFNOTIFY *) l_param;
TCHAR sel_name[MAX_PATH];
switch(msg) {
case WM_INITDIALOG:
/* Retain the filter text, and fill it in. */
if(g_dfilter_str != NULL) {
cur_ctrl = GetDlgItem(mf_hwnd, EWFD_FILTER_EDIT);
SetWindowText(cur_ctrl, utf_8to16(g_dfilter_str));
}
/* Chrono by default */
cur_ctrl = GetDlgItem(mf_hwnd, EWFD_MERGE_CHRONO_BTN);
SendMessage(cur_ctrl, BM_SETCHECK, TRUE, 0);
g_merge_action = merge_append;
preview_set_file_info(mf_hwnd, NULL);
break;
case WM_NOTIFY:
switch (notify->hdr.code) {
case CDN_FILEOK:
/* Fetch the read filter */
cur_ctrl = GetDlgItem(mf_hwnd, EWFD_FILTER_EDIT);
g_free(g_dfilter_str);
g_dfilter_str = filter_tb_get(cur_ctrl);
cur_ctrl = GetDlgItem(mf_hwnd, EWFD_MERGE_CHRONO_BTN);
if(SendMessage(cur_ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED) {
g_merge_action = merge_chrono;
} else {
cur_ctrl = GetDlgItem(mf_hwnd, EWFD_MERGE_PREPEND_BTN);
if(SendMessage(cur_ctrl, BM_GETCHECK, 0, 0) == BST_CHECKED) {
g_merge_action = merge_prepend;
}
}
break;
case CDN_SELCHANGE:
/* This _almost_ works correctly. We need to handle directory
selections, etc. */
parent = GetParent(mf_hwnd);
CommDlg_OpenSave_GetFilePath(parent, sel_name, MAX_PATH);
preview_set_file_info(mf_hwnd, utf_16to8(sel_name));
break;
case CDN_HELP:
topic_action(HELP_MERGE_WIN32_DIALOG);
break;
default:
break;
}
break;
case WM_COMMAND:
cur_ctrl = (HWND) l_param;
switch(w_param) {
case (EN_UPDATE << 16) | EWFD_FILTER_EDIT:
filter_tb_syntax_check(cur_ctrl, NULL);
break;
default:
break;
}
break;
default:
break;
}
return 0;
}
static UINT_PTR CALLBACK
export_file_hook_proc(HWND ef_hwnd, UINT msg, WPARAM w_param, LPARAM l_param) {
HWND cur_ctrl;
OFNOTIFY *notify = (OFNOTIFY *) l_param;
gboolean pkt_fmt_enable;
int i, filter_index;
switch(msg) {
case WM_INITDIALOG: {
/* default to displayed packets */
print_args.range.process_filtered = TRUE;
range_handle_wm_initdialog(ef_hwnd, &print_args.range);
format_handle_wm_initdialog(ef_hwnd, &print_args);
break;
}
case WM_COMMAND:
cur_ctrl = (HWND) l_param;
switch (w_param) {
case (CBN_SELCHANGE << 16) | EWFD_PKT_DETAIL_COMBO:
default:
range_handle_wm_command(ef_hwnd, cur_ctrl, w_param, &print_args.range);
print_update_dynamic(ef_hwnd, &print_args);
break;
}
break;
case WM_NOTIFY:
switch (notify->hdr.code) {
case CDN_FILEOK:
break;
case CDN_TYPECHANGE:
filter_index = notify->lpOFN->nFilterIndex;
if (filter_index == 2) /* PostScript */
print_args.format = PR_FMT_TEXT;
else
print_args.format = PR_FMT_PS;
if (filter_index == 3 || filter_index == 4 || filter_index == 5 || filter_index == 6)
pkt_fmt_enable = FALSE;
else
pkt_fmt_enable = TRUE;
for (i = EWFD_PKT_FORMAT_GB; i <= EWFD_PKT_NEW_PAGE_CB; i++) {
cur_ctrl = GetDlgItem(ef_hwnd, i);
EnableWindow(cur_ctrl, pkt_fmt_enable);
}
break;
case CDN_HELP:
topic_action(HELP_EXPORT_FILE_WIN32_DIALOG);
break;
default:
break;
}
break;
default:
break;
}
return 0;
}
#endif // _WIN32 |
C/C++ | wireshark/ui/win32/file_dlg_win32.h | /** @file
*
* Native Windows file dialog routines
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 2006 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __FILE_DLG_WIN32_H__
#define __FILE_DLG_WIN32_H__
#ifndef RC_INVOKED // RC warns about gatomic's long identifiers.
#include "ui/file_dialog.h"
#include "ui/packet_range.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/**
* @brief set_thread_per_monitor_v2_awareness
*
* Qt <= 5.9 supports setting old (Windows 8.1) per-monitor DPI awareness
* via Qt:AA_EnableHighDpiScaling. We do this in main.cpp. In order for
* native dialogs to be rendered correctly we need to set per-monitor
* *v2* awareness prior to creating the dialog, which we can do here.
* Qt doesn't render correctly when per-monitor v2 awareness is enabled, so
* we need to revert our thread context when we're done.
*
* @return The current thread DPI awareness context, which should
* be passed to revert_thread_per_monitor_v2_awareness.
*/
HANDLE set_thread_per_monitor_v2_awareness(void);
/**
* @brief revert_thread_per_monitor_v2_awareness
* @param context
*/
void revert_thread_per_monitor_v2_awareness(HANDLE context);
/** Open the "Open" dialog box.
*
* @param h_wnd HWND of the parent window.
* @param file_name File name
* @param type File type
* @param display_filter a display filter
*/
gboolean win32_open_file (HWND h_wnd, const wchar_t *title, GString *file_name, unsigned int *type, GString *display_filter);
/** Open the "Save As" dialog box.
*
* @param h_wnd HWND of the parent window.
* @param cf capture_file Structure for the capture to be saved
* @param file_name File name. May be empty.
* @param file_type Wiretap file type.
* @param compression_type Compression type to use, or uncompressed.
* @param must_support_comments TRUE if the file format list should
* include only file formats that support comments
*
* @return TRUE if packets were discarded when saving, FALSE otherwise
*/
gboolean win32_save_as_file(HWND h_wnd, const wchar_t *title, capture_file *cf,
GString *file_name, int *file_type,
wtap_compression_type *compression_type,
gboolean must_support_comments);
/** Open the "Export Specified Packets" dialog box.
*
* @param h_wnd HWND of the parent window.
* @param cf capture_file Structure for the capture to be saved
* @param file_name File name. May be empty.
* @param file_type Wiretap file type.
* @param compression_type Compression type to use, or uncompressed.
* @param range Range of packets to export.
*
* @return TRUE if packets were discarded when saving, FALSE otherwise
*/
gboolean win32_export_specified_packets_file(HWND h_wnd,
const wchar_t *title,
capture_file *cf,
GString *file_name,
int *file_type,
wtap_compression_type *compression_type,
packet_range_t *range);
/** Open the "Merge" dialog box.
*
* @param h_wnd HWND of the parent window.
* @param file_name File name
* @param display_filter a display filter
* @param merge_type type of merge
*/
gboolean win32_merge_file (HWND h_wnd, const wchar_t *title, GString *file_name, GString *display_filter, int *merge_type);
/** Open the "Export" dialog box.
*
* @param h_wnd HWND of the parent window.
* @param cf capture_file Structure for the capture to be saved
* @param export_type The export type.
* @param range a possible range
*/
void win32_export_file (HWND h_wnd, const wchar_t *title, capture_file *cf, export_type_e export_type, const gchar *range);
/* Open dialog defines */
/* #define EWFD_FILTER_BTN 1000 */
#define EWFD_FILTER_LBL 1000
#define EWFD_FILTER_EDIT 1001
#define EWFD_MAC_NR_CB 1002
#define EWFD_NET_NR_CB 1003
#define EWFD_TRANS_NR_CB 1004
#define EWFD_EXTERNAL_NR_CB 1005
/* Note: The preview title (PT) and text (PTX) MUST have sequential IDs;
they're used in a for loop. EWFD_PT_FILENAME MUST be first, and
EWFD_PTX_ELAPSED MUST be last. (so why don't we just use an enum? */
#define EWFD_PT_FORMAT 1006
#define EWFD_PT_SIZE 1007
#define EWFD_PT_START_ELAPSED 1008
#define EWFD_PTX_FORMAT 1009
#define EWFD_PTX_SIZE 1010
#define EWFD_PTX_START_ELAPSED 1011
#define EWFD_FORMAT_TYPE 1020
/* Save as and export dialog defines */
#define EWFD_GZIP_CB 1040
/* Export dialog defines */
#define EWFD_CAPTURED_BTN 1000
#define EWFD_DISPLAYED_BTN 1001
#define EWFD_ALL_PKTS_BTN 1002
#define EWFD_SEL_PKT_BTN 1003
#define EWFD_MARKED_BTN 1004
#define EWFD_FIRST_LAST_BTN 1005
#define EWFD_RANGE_BTN 1006
#define EWFD_RANGE_EDIT 1007
#define EWFD_REMOVE_IGN_CB 1008
#define EWFD_ALL_PKTS_CAP 1009
#define EWFD_SEL_PKT_CAP 1010
#define EWFD_MARKED_CAP 1011
#define EWFD_FIRST_LAST_CAP 1012
#define EWFD_RANGE_CAP 1013
#define EWFD_IGNORED_CAP 1014
#define EWFD_ALL_PKTS_DISP 1015
#define EWFD_SEL_PKT_DISP 1016
#define EWFD_MARKED_DISP 1017
#define EWFD_FIRST_LAST_DISP 1018
#define EWFD_RANGE_DISP 1019
#define EWFD_IGNORED_DISP 1020
/* Merge dialog defines. Overlays Open dialog defines above. */
#define EWFD_MERGE_PREPEND_BTN 1050
#define EWFD_MERGE_CHRONO_BTN 1051
#define EWFD_MERGE_APPEND_BTN 1052
/* Export dialog defines. Overlays Save dialog defines above. */
/* These MUST be contiguous */
#define EWFD_PKT_FORMAT_GB 1050
#define EWFD_PKT_SUMMARY_CB 1051
#define EWFD_COL_HEADINGS_CB 1052
#define EWFD_PKT_DETAIL_CB 1053
#define EWFD_PKT_DETAIL_COMBO 1054
#define EWFD_PKT_BYTES_CB 1055
#define EWFD_DATA_SOURCES_CB 1056
#define EWFD_PKT_NEW_PAGE_CB 1057
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __FILE_DLG_WIN32_H__ */ |
wireshark/wiretap/.editorconfig | #
# Editor configuration
#
# https://editorconfig.org/
#
[5views.[ch]]
indent_style = tab
indent_size = tab
[aethra.[ch]]
indent_style = tab
indent_size = tab
[atm.[ch]]
indent_style = tab
indent_size = tab
[ber.[ch]]
indent_size = 2
[capsa.[ch]]
indent_style = tab
indent_size = tab
[commview.[ch]]
indent_style = tab
indent_size = tab
[cosine.[ch]]
indent_style = tab
indent_size = tab
[csids.[ch]]
indent_size = 2
[daintree-sna.[ch]]
indent_style = tab
indent_size = tab
[dct3trace.[ch]]
indent_style = tab
indent_size = tab
[erf.[ch]]
indent_size = 2
[eyesdn.[ch]]
indent_style = tab
indent_size = tab
[file_access.[ch]]
indent_style = tab
indent_size = tab
[hcidump.[ch]]
indent_style = tab
indent_size = tab
[i4btrace.[ch]]
indent_style = tab
indent_size = tab
[iptrace.[ch]]
indent_style = tab
indent_size = tab
[iseries.[ch]]
indent_size = 2
[lanalyzer.[ch]]
indent_size = 6
[libpcap.[ch]]
indent_style = tab
indent_size = tab
[mime_file.[ch]]
indent_style = tab
indent_size = tab
[mpeg.[ch]]
indent_style = tab
indent_size = tab
[netmon.[ch]]
indent_style = tab
indent_size = tab
[netscreen.[ch]]
indent_style = tab
indent_size = tab
[nettrace_3gpp_32_423.[ch]]
indent_style = tab
indent_size = tab
[netxray.[ch]]
indent_style = tab
indent_size = tab
[ngsniffer.[ch]]
indent_style = tab
indent_size = tab
[packetlogger.[ch]]
indent_style = tab
indent_size = tab
[pcap-common.[ch]]
indent_style = tab
indent_size = tab
[peekclassic.[ch]]
indent_style = tab
indent_size = tab
[pppdump.[ch]]
indent_style = tab
indent_size = tab
[radcom.[ch]]
indent_style = tab
indent_size = tab
[snoop.[ch]]
indent_style = tab
indent_size = tab
[stanag4607.[ch]]
indent_size = 2
[tnef.[ch]]
indent_size = 2
[toshiba.[ch]]
indent_style = tab
indent_size = tab
[wtap.[ch]]
indent_style = tab
indent_size = tab |
|
C | wireshark/wiretap/5views.c | /* 5views.c
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <string.h>
#include "wtap-int.h"
#include "file_wrappers.h"
#include "5views.h"
typedef struct
{
guint32 Signature;
guint32 Size; /* Total size of Header in bytes (included Signature) */
guint32 Version; /* Identify version and so the format of this record */
guint32 DataSize; /* Total size of data included in the Info Record (except the header size) */
guint32 FileType; /* Type of the file */
guint32 Reserved[3]; /* Reserved for future use */
}t_5VW_Info_Header;
typedef struct
{
guint32 Type; /* Id of the attribute */
guint16 Size; /* Size of the data part of the attribute (not including header size) */
guint16 Nb; /* Number of elements */
}t_5VW_Attributes_Header;
#define CST_5VW_INFO_HEADER_KEY 0xAAAAAAAAU /* signature */
#define CST_5VW_INFO_RECORD_VERSION 0x00010000U /* version */
#define CST_5VW_DECALE_FILE_TYPE 24
#define CST_5VW_SECTION_CAPTURES 0x08U
#define CST_5VW_CAPTURES_FILE (CST_5VW_SECTION_CAPTURES << CST_5VW_DECALE_FILE_TYPE) /* 0x08000000 */
#define CST_5VW_FLAT_FILE 0x10000000U
#define CST_5VW_CAPTURE_FILEID (CST_5VW_FLAT_FILE | CST_5VW_CAPTURES_FILE)
#define CST_5VW_FAMILY_CAP_ETH 0x01U
#define CST_5VW_FAMILY_CAP_WAN 0x02U
#define CST_5VW_DECALE_FILE_FAMILY 12
#define CST_5VW_CAP_ETH (CST_5VW_FAMILY_CAP_ETH << CST_5VW_DECALE_FILE_FAMILY) /* 0x00001000 */
#define CST_5VW_CAP_WAN (CST_5VW_FAMILY_CAP_WAN << CST_5VW_DECALE_FILE_FAMILY) /* 0x00002000 */
#define CST_5VW_CAPTURE_ETH_FILEID (CST_5VW_CAPTURE_FILEID | CST_5VW_CAP_ETH)
#define CST_5VW_CAPTURE_WAN_FILEID (CST_5VW_CAPTURE_FILEID | CST_5VW_CAP_WAN)
#define CST_5VW_CAPTURE_FILE_TYPE_MASK 0xFF000000U
#define CST_5VW_FRAME_RECORD 0x00000000U
#define CST_5VW_RECORDS_HEADER_KEY 0x3333EEEEU
typedef struct
{
t_5VW_Info_Header Info_Header;
t_5VW_Attributes_Header HeaderDateCreation;
guint32 Time;
t_5VW_Attributes_Header HeaderNbFrames;
guint32 TramesStockeesInFile;
}t_5VW_Capture_Header;
typedef struct
{
guint32 Key; /* 0x3333EEEE */
guint16 HeaderSize; /* Actual size of this header in bytes (32) */
guint16 HeaderType; /* Exact type of this header (0x4000) */
guint32 RecType; /* Type of record */
guint32 RecSubType; /* Subtype of record */
guint32 RecSize; /* Size of one record */
guint32 RecNb; /* Number of records */
guint32 Utc;
guint32 NanoSecondes;
guint32 RecInfo; /* Info about Alarm / Event / Frame captured */
}t_5VW_TimeStamped_Header;
#define CST_5VW_IA_CAP_INF_NB_TRAMES_STOCKEES 0x20000000U
#define CST_5VW_IA_DATE_CREATION 0x80000007U /* Struct t_Attrib_Date_Create */
#define CST_5VW_TIMESTAMPED_HEADER_TYPE 0x4000U
#define CST_5VW_CAPTURES_RECORD (CST_5VW_SECTION_CAPTURES << 28) /* 0x80000000 */
#define CST_5VW_SYSTEM_RECORD 0x00000000U
static gboolean _5views_read(wtap *wth, wtap_rec *rec, Buffer *buf, int *err,
gchar **err_info, gint64 *data_offset);
static gboolean _5views_seek_read(wtap *wth, gint64 seek_off, wtap_rec *rec,
Buffer *buf, int *err, gchar **err_info);
static int _5views_read_header(wtap *wth, FILE_T fh, t_5VW_TimeStamped_Header *hdr,
wtap_rec *rec, int *err, gchar **err_info);
static gboolean _5views_dump(wtap_dumper *wdh, const wtap_rec *rec, const guint8 *pd, int *err, gchar **err_info);
static gboolean _5views_dump_finish(wtap_dumper *wdh, int *err, gchar **err_info);
static int _5views_file_type_subtype = -1;
void register_5views(void);
wtap_open_return_val
_5views_open(wtap *wth, int *err, gchar **err_info)
{
t_5VW_Capture_Header Capture_Header;
int encap = WTAP_ENCAP_UNKNOWN;
if (!wtap_read_bytes(wth->fh, &Capture_Header.Info_Header,
sizeof(t_5VW_Info_Header), err, err_info)) {
if (*err != WTAP_ERR_SHORT_READ)
return WTAP_OPEN_ERROR;
return WTAP_OPEN_NOT_MINE;
}
/* Check whether that's 5Views format or not */
if(Capture_Header.Info_Header.Signature != CST_5VW_INFO_HEADER_KEY)
{
return WTAP_OPEN_NOT_MINE;
}
/* Check Version */
Capture_Header.Info_Header.Version =
pletoh32(&Capture_Header.Info_Header.Version);
switch (Capture_Header.Info_Header.Version) {
case CST_5VW_INFO_RECORD_VERSION:
break;
default:
*err = WTAP_ERR_UNSUPPORTED;
*err_info = ws_strdup_printf("5views: header version %u unsupported", Capture_Header.Info_Header.Version);
return WTAP_OPEN_ERROR;
}
/* Check File Type */
Capture_Header.Info_Header.FileType =
pletoh32(&Capture_Header.Info_Header.FileType);
if((Capture_Header.Info_Header.FileType & CST_5VW_CAPTURE_FILE_TYPE_MASK) != CST_5VW_CAPTURE_FILEID)
{
*err = WTAP_ERR_UNSUPPORTED;
*err_info = ws_strdup_printf("5views: file is not a capture file (filetype is %u)", Capture_Header.Info_Header.Version);
return WTAP_OPEN_ERROR;
}
/* Check possible Encap */
switch (Capture_Header.Info_Header.FileType) {
case CST_5VW_CAPTURE_ETH_FILEID:
encap = WTAP_ENCAP_ETHERNET;
break;
/* case CST_5VW_CAPTURE_WAN_FILEID:
break;
*/
default:
*err = WTAP_ERR_UNSUPPORTED;
*err_info = ws_strdup_printf("5views: network type %u unknown or unsupported",
Capture_Header.Info_Header.FileType);
return WTAP_OPEN_ERROR;
}
/* read the remaining header information */
if (!wtap_read_bytes(wth->fh, &Capture_Header.HeaderDateCreation,
sizeof (t_5VW_Capture_Header) - sizeof(t_5VW_Info_Header), err, err_info))
return WTAP_OPEN_ERROR;
/* This is a 5views capture file */
wth->file_type_subtype = _5views_file_type_subtype;
wth->subtype_read = _5views_read;
wth->subtype_seek_read = _5views_seek_read;
wth->file_encap = encap;
wth->snapshot_length = 0; /* not available in header */
wth->file_tsprec = WTAP_TSPREC_NSEC;
/*
* Add an IDB; we don't know how many interfaces were
* involved, so we just say one interface, about which
* we only know the link-layer type, snapshot length,
* and time stamp resolution.
*/
wtap_add_generated_idb(wth);
return WTAP_OPEN_MINE;
}
/* Read the next packet */
static gboolean
_5views_read(wtap *wth, wtap_rec *rec, Buffer *buf, int *err,
gchar **err_info, gint64 *data_offset)
{
t_5VW_TimeStamped_Header TimeStamped_Header;
/*
* Keep reading until we see a record with a subtype of
* CST_5VW_FRAME_RECORD.
*/
do
{
*data_offset = file_tell(wth->fh);
/* Read record header. */
if (!_5views_read_header(wth, wth->fh, &TimeStamped_Header,
rec, err, err_info))
return FALSE;
if (TimeStamped_Header.RecSubType == CST_5VW_FRAME_RECORD) {
/*
* OK, this is a packet.
*/
break;
}
/*
* Not a packet - skip to the next record.
*/
if (!wtap_read_bytes(wth->fh, NULL, TimeStamped_Header.RecSize, err, err_info))
return FALSE;
} while (1);
if (rec->rec_header.packet_header.caplen > WTAP_MAX_PACKET_SIZE_STANDARD) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("5views: File has %u-byte packet, bigger than maximum of %u",
rec->rec_header.packet_header.caplen, WTAP_MAX_PACKET_SIZE_STANDARD);
return FALSE;
}
return wtap_read_packet_bytes(wth->fh, buf,
rec->rec_header.packet_header.caplen, err, err_info);
}
static gboolean
_5views_seek_read(wtap *wth, gint64 seek_off, wtap_rec *rec,
Buffer *buf, int *err, gchar **err_info)
{
t_5VW_TimeStamped_Header TimeStamped_Header;
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
return FALSE;
/*
* Read the header.
*/
if (!_5views_read_header(wth, wth->random_fh, &TimeStamped_Header,
rec, err, err_info)) {
if (*err == 0)
*err = WTAP_ERR_SHORT_READ;
return FALSE;
}
/*
* Read the packet data.
*/
return wtap_read_packet_bytes(wth->random_fh, buf, rec->rec_header.packet_header.caplen,
err, err_info);
}
/* Read the header of the next packet. Return TRUE on success, FALSE
on error. */
static gboolean
_5views_read_header(wtap *wth, FILE_T fh, t_5VW_TimeStamped_Header *hdr,
wtap_rec *rec, int *err, gchar **err_info)
{
/* Read record header. */
if (!wtap_read_bytes_or_eof(fh, hdr, (unsigned int)sizeof(t_5VW_TimeStamped_Header),
err, err_info))
return FALSE;
hdr->Key = pletoh32(&hdr->Key);
if (hdr->Key != CST_5VW_RECORDS_HEADER_KEY) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("5views: Time-stamped header has bad key value 0x%08X",
hdr->Key);
return FALSE;
}
hdr->RecSubType = pletoh32(&hdr->RecSubType);
hdr->RecSize = pletoh32(&hdr->RecSize);
hdr->Utc = pletoh32(&hdr->Utc);
hdr->NanoSecondes = pletoh32(&hdr->NanoSecondes);
rec->rec_type = REC_TYPE_PACKET;
rec->block = wtap_block_create(WTAP_BLOCK_PACKET);
rec->presence_flags = WTAP_HAS_TS;
rec->ts.secs = hdr->Utc;
rec->ts.nsecs = hdr->NanoSecondes;
rec->rec_header.packet_header.caplen = hdr->RecSize;
rec->rec_header.packet_header.len = hdr->RecSize;
switch (wth->file_encap) {
case WTAP_ENCAP_ETHERNET:
/* We assume there's no FCS in this frame. */
rec->rec_header.packet_header.pseudo_header.eth.fcs_len = 0;
break;
}
return TRUE;
}
typedef struct {
guint32 nframes;
} _5views_dump_t;
static const int wtap_encap[] = {
-1, /* WTAP_ENCAP_UNKNOWN -> unsupported */
CST_5VW_CAPTURE_ETH_FILEID, /* WTAP_ENCAP_ETHERNET -> Ethernet */
};
#define NUM_WTAP_ENCAPS (sizeof wtap_encap / sizeof wtap_encap[0])
/* Returns 0 if we could write the specified encapsulation type,
an error indication otherwise. */
static int _5views_dump_can_write_encap(int encap)
{
/* Per-packet encapsulations aren't supported. */
if (encap == WTAP_ENCAP_PER_PACKET)
return WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED;
if (encap < 0 || (unsigned int) encap >= NUM_WTAP_ENCAPS || wtap_encap[encap] == -1)
return WTAP_ERR_UNWRITABLE_ENCAP;
return 0;
}
/* Returns TRUE on success, FALSE on failure; sets "*err" to an error code on
failure */
static gboolean _5views_dump_open(wtap_dumper *wdh, int *err, gchar **err_info _U_)
{
_5views_dump_t *_5views;
/* We can't fill in all the fields in the file header, as we
haven't yet written any packets. As we'll have to rewrite
the header when we've written out all the packets, we just
skip over the header for now. */
if (wtap_dump_file_seek(wdh, sizeof(t_5VW_Capture_Header), SEEK_SET, err) == -1)
return FALSE;
/* This is a 5Views file */
wdh->subtype_write = _5views_dump;
wdh->subtype_finish = _5views_dump_finish;
_5views = g_new(_5views_dump_t, 1);
wdh->priv = (void *)_5views;
_5views->nframes = 0;
return TRUE;
}
/* Write a record for a packet to a dump file.
Returns TRUE on success, FALSE on failure. */
static gboolean _5views_dump(wtap_dumper *wdh,
const wtap_rec *rec,
const guint8 *pd, int *err, gchar **err_info _U_)
{
_5views_dump_t *_5views = (_5views_dump_t *)wdh->priv;
t_5VW_TimeStamped_Header HeaderFrame;
/* We can only write packet records. */
if (rec->rec_type != REC_TYPE_PACKET) {
*err = WTAP_ERR_UNWRITABLE_REC_TYPE;
return FALSE;
}
/*
* Make sure this packet doesn't have a link-layer type that
* differs from the one for the file.
*/
if (wdh->file_encap != rec->rec_header.packet_header.pkt_encap) {
*err = WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED;
return FALSE;
}
/* Don't write out something bigger than we can read. */
if (rec->rec_header.packet_header.caplen > WTAP_MAX_PACKET_SIZE_STANDARD) {
*err = WTAP_ERR_PACKET_TOO_LARGE;
return FALSE;
}
/* Frame Header */
/* constant fields */
HeaderFrame.Key = GUINT32_TO_LE(CST_5VW_RECORDS_HEADER_KEY);
HeaderFrame.HeaderSize = GUINT16_TO_LE(sizeof(t_5VW_TimeStamped_Header));
HeaderFrame.HeaderType = GUINT16_TO_LE(CST_5VW_TIMESTAMPED_HEADER_TYPE);
HeaderFrame.RecType = GUINT32_TO_LE(CST_5VW_CAPTURES_RECORD | CST_5VW_SYSTEM_RECORD);
HeaderFrame.RecSubType = GUINT32_TO_LE(CST_5VW_FRAME_RECORD);
HeaderFrame.RecNb = GUINT32_TO_LE(1);
/* record-dependent fields */
/*
* XXX - is the frame time signed, or unsigned? If it's signed,
* we should check against G_MININT32 and G_MAXINT32 and make
* Utc a gint32.
*/
if (rec->ts.secs < 0 || rec->ts.secs > WTAP_NSTIME_32BIT_SECS_MAX) {
*err = WTAP_ERR_TIME_STAMP_NOT_SUPPORTED;
return FALSE;
}
HeaderFrame.Utc = GUINT32_TO_LE((guint32)rec->ts.secs);
HeaderFrame.NanoSecondes = GUINT32_TO_LE(rec->ts.nsecs);
HeaderFrame.RecSize = GUINT32_TO_LE(rec->rec_header.packet_header.len);
HeaderFrame.RecInfo = GUINT32_TO_LE(0);
/* write the record header */
if (!wtap_dump_file_write(wdh, &HeaderFrame,
sizeof(t_5VW_TimeStamped_Header), err))
return FALSE;
/* write the data */
if (!wtap_dump_file_write(wdh, pd, rec->rec_header.packet_header.caplen, err))
return FALSE;
_5views->nframes ++;
return TRUE;
}
static gboolean _5views_dump_finish(wtap_dumper *wdh, int *err, gchar **err_info _U_)
{
_5views_dump_t *_5views = (_5views_dump_t *)wdh->priv;
t_5VW_Capture_Header file_hdr;
if (wtap_dump_file_seek(wdh, 0, SEEK_SET, err) == -1)
return FALSE;
/* fill in the Info_Header */
file_hdr.Info_Header.Signature = GUINT32_TO_LE(CST_5VW_INFO_HEADER_KEY);
file_hdr.Info_Header.Size = GUINT32_TO_LE(sizeof(t_5VW_Info_Header)); /* Total size of Header in bytes (included Signature) */
file_hdr.Info_Header.Version = GUINT32_TO_LE(CST_5VW_INFO_RECORD_VERSION); /* Identify version and so the format of this record */
file_hdr.Info_Header.DataSize = GUINT32_TO_LE(sizeof(t_5VW_Attributes_Header)
+ sizeof(guint32)
+ sizeof(t_5VW_Attributes_Header)
+ sizeof(guint32));
/* Total size of data included in the Info Record (except the header size) */
file_hdr.Info_Header.FileType = GUINT32_TO_LE(wtap_encap[wdh->file_encap]); /* Type of the file */
file_hdr.Info_Header.Reserved[0] = 0; /* Reserved for future use */
file_hdr.Info_Header.Reserved[1] = 0; /* Reserved for future use */
file_hdr.Info_Header.Reserved[2] = 0; /* Reserved for future use */
/* fill in the HeaderDateCreation */
file_hdr.HeaderDateCreation.Type = GUINT32_TO_LE(CST_5VW_IA_DATE_CREATION); /* Id of the attribute */
file_hdr.HeaderDateCreation.Size = GUINT16_TO_LE(sizeof(guint32)); /* Size of the data part of the attribute (not including header size) */
file_hdr.HeaderDateCreation.Nb = GUINT16_TO_LE(1); /* Number of elements */
/* fill in the Time field */
#ifdef _WIN32
_tzset();
#endif
file_hdr.Time = GUINT32_TO_LE(time(NULL));
/* fill in the Time field */
file_hdr.HeaderNbFrames.Type = GUINT32_TO_LE(CST_5VW_IA_CAP_INF_NB_TRAMES_STOCKEES); /* Id of the attribute */
file_hdr.HeaderNbFrames.Size = GUINT16_TO_LE(sizeof(guint32)); /* Size of the data part of the attribute (not including header size) */
file_hdr.HeaderNbFrames.Nb = GUINT16_TO_LE(1); /* Number of elements */
/* fill in the number of frames saved */
file_hdr.TramesStockeesInFile = GUINT32_TO_LE(_5views->nframes);
/* Write the file header. */
if (!wtap_dump_file_write(wdh, &file_hdr, sizeof(t_5VW_Capture_Header),
err))
return FALSE;
return TRUE;
}
static const struct supported_block_type _5views_blocks_supported[] = {
/*
* We support packet blocks, with no comments or other options.
*/
{ WTAP_BLOCK_PACKET, MULTIPLE_BLOCKS_SUPPORTED, NO_OPTIONS_SUPPORTED }
};
static const struct file_type_subtype_info _5views_info = {
"InfoVista 5View capture", "5views", "5vw", NULL,
TRUE, BLOCKS_SUPPORTED(_5views_blocks_supported),
_5views_dump_can_write_encap, _5views_dump_open, NULL
};
void register_5views(void)
{
_5views_file_type_subtype = wtap_register_file_type_subtype(&_5views_info);
/*
* Register name for backwards compatibility with the
* wtap_filetypes table in Lua.
*/
wtap_register_backwards_compatibility_lua_name("5VIEWS",
_5views_file_type_subtype);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/ |
C/C++ | wireshark/wiretap/5views.h | /** @file
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __5VIEWS_H__
#define __5VIEWS_H__
#include <glib.h>
#include "wtap.h"
wtap_open_return_val _5views_open(wtap *wth, int *err, gchar **err_info);
#endif |
C | wireshark/wiretap/aethra.c | /* aethra.c
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <string.h>
#include "wtap-int.h"
#include "file_wrappers.h"
#include "aethra.h"
/* Magic number in Aethra PC108 files. */
#define MAGIC_SIZE 5
static const guchar aethra_magic[MAGIC_SIZE] = {
'V', '0', '2', '0', '8'
};
/* Aethra file header. */
struct aethra_hdr {
guchar magic[MAGIC_SIZE];
guint8 unknown1[39]; /* 5-43 */
guchar sw_vers[60]; /* 44-103 - software version string, not null-terminated */
guint8 unknown2[118]; /* 104-221 */
guint8 start_sec; /* 222 - seconds of capture start time */
guint8 start_min; /* 223 - minutes of capture start time */
guint8 start_hour; /* 224 - hour of capture start time */
guint8 unknown3[462]; /* 225-686 */
guchar xxx_string[37]; /* 687-723 - null-terminated short comment string? */
guint8 unknown3_5[4]; /* 724-727 */
guchar yyy_string[4504];/* 728-5231 - null-terminated long comment string? */
guint8 start_year[2]; /* 5232-5233 - year of capture start date */
guint8 start_month[2]; /* 5234-5235 - month of capture start date */
guint8 unknown4[2]; /* 5236-5237 */
guint8 start_day[2]; /* 5238-5239 - day of capture start date */
guint8 unknown5[8]; /* 5240-5247 */
guchar com_info[16]; /* 5248-5263 - COM port and speed, null-padded(?) */
guint8 unknown6[107]; /* 5264-5370 */
guchar xxx_vers[41]; /* 5371-5411 - unknown version string (longer, null-padded?) */
};
/* Aethra record header. Yes, the alignment is weird.
All multi-byte fields are little-endian. */
struct aethrarec_hdr {
guint8 rec_size[2]; /* record length, not counting the length itself */
guint8 rec_type; /* record type */
guint8 timestamp[4]; /* milliseconds since start of capture */
guint8 flags; /* low-order bit: 0 = N->U, 1 = U->N */
};
/*
* Record types.
*
* As the indications from the device and signalling messages appear not
* to have the 8th bit set, and at least some B-channel records do, we
* assume, for now, that the 8th bit indicates bearer information.
*
* 0x9F is the record type seen for B31 channel records; that might be
* 0x80|31, so, for now, we assume that if the 8th bit is set, the B
* channel number is in the low 7 bits.
*/
#define AETHRA_BEARER 0x80 /* bearer information */
#define AETHRA_DEVICE 0x00 /* indication from the monitoring device */
#define AETHRA_ISDN_LINK 0x01 /* information from the ISDN link */
/*
* In AETHRA_DEVICE records, the flags field has what appears to
* be a record subtype.
*/
#define AETHRA_DEVICE_STOP_MONITOR 0x00 /* Stop Monitor */
#define AETHRA_DEVICE_START_MONITOR 0x04 /* Start Monitor */
#define AETHRA_DEVICE_ACTIVATION 0x05 /* Activation */
#define AETHRA_DEVICE_START_CAPTURE 0x5F /* Start Capture */
/*
* In AETHRA_ISDN_LINK and bearer channel records, the flags field has
* a direction flag and possibly some other bits.
*
* In AETHRA_ISDN_LINK records, at least some of the other bits are
* a subtype.
*
* In bearer channel records, there are records with data and
* "Constant Value" records with a single byte. Data has a
* flags value of 0x14 ORed with the direction flag, and Constant Value
* records have a flags value of 0x16 ORed with the direction flag.
* There are also records of an unknown type with 0x02, probably
* ORed with the direction flag.
*/
#define AETHRA_U_TO_N 0x01 /* set for TE->NT */
#define AETHRA_ISDN_LINK_SUBTYPE 0xFE
#define AETHRA_ISDN_LINK_LAPD 0x00 /* LAPD frame */
#define AETHRA_ISDN_LINK_SA_BITS 0x2E /* 2048K PRI Sa bits (G.704 section 2.3.2) */
#define AETHRA_ISDN_LINK_ALL_ALARMS_CLEARED 0x30 /* All Alarms Cleared */
typedef struct {
time_t start;
} aethra_t;
static gboolean aethra_read(wtap *wth, wtap_rec *rec, Buffer *buf, int *err,
gchar **err_info, gint64 *data_offset);
static gboolean aethra_seek_read(wtap *wth, gint64 seek_off,
wtap_rec *rec, Buffer *buf, int *err, gchar **err_info);
static gboolean aethra_read_rec_header(wtap *wth, FILE_T fh, struct aethrarec_hdr *hdr,
wtap_rec *rec, int *err, gchar **err_info);
static int aethra_file_type_subtype = -1;
void register_aethra(void);
wtap_open_return_val aethra_open(wtap *wth, int *err, gchar **err_info)
{
struct aethra_hdr hdr;
struct tm tm;
aethra_t *aethra;
/* Read in the string that should be at the start of a "aethra" file */
if (!wtap_read_bytes(wth->fh, hdr.magic, sizeof hdr.magic, err,
err_info)) {
if (*err != WTAP_ERR_SHORT_READ)
return WTAP_OPEN_ERROR;
return WTAP_OPEN_NOT_MINE;
}
if (memcmp(hdr.magic, aethra_magic, sizeof aethra_magic) != 0)
return WTAP_OPEN_NOT_MINE;
/* Read the rest of the header. */
if (!wtap_read_bytes(wth->fh, (char *)&hdr + sizeof hdr.magic,
sizeof hdr - sizeof hdr.magic, err, err_info))
return WTAP_OPEN_ERROR;
wth->file_type_subtype = aethra_file_type_subtype;
aethra = g_new(aethra_t, 1);
wth->priv = (void *)aethra;
wth->subtype_read = aethra_read;
wth->subtype_seek_read = aethra_seek_read;
/*
* Convert the time stamp to a "time_t".
*/
tm.tm_year = pletoh16(&hdr.start_year) - 1900;
tm.tm_mon = pletoh16(&hdr.start_month) - 1;
tm.tm_mday = pletoh16(&hdr.start_day);
tm.tm_hour = hdr.start_hour;
tm.tm_min = hdr.start_min;
tm.tm_sec = hdr.start_sec;
tm.tm_isdst = -1;
aethra->start = mktime(&tm);
/*
* We've only seen ISDN files, so, for now, we treat all
* files as ISDN.
*/
wth->file_encap = WTAP_ENCAP_ISDN;
wth->snapshot_length = 0; /* not available in header */
wth->file_tsprec = WTAP_TSPREC_MSEC;
/*
* Add an IDB; we don't know how many interfaces were
* involved, so we just say one interface, about which
* we only know the link-layer type, snapshot length,
* and time stamp resolution.
*/
wtap_add_generated_idb(wth);
return WTAP_OPEN_MINE;
}
#if 0
static guint packet = 0;
#endif
/* Read the next packet */
static gboolean aethra_read(wtap *wth, wtap_rec *rec, Buffer *buf, int *err,
gchar **err_info, gint64 *data_offset)
{
struct aethrarec_hdr hdr;
/*
* Keep reading until we see an AETHRA_ISDN_LINK with a subtype
* of AETHRA_ISDN_LINK_LAPD record or get an end-of-file.
*/
for (;;) {
*data_offset = file_tell(wth->fh);
/* Read record header. */
if (!aethra_read_rec_header(wth, wth->fh, &hdr, rec, err, err_info))
return FALSE;
/*
* XXX - if this is big, we might waste memory by
* growing the buffer to handle it.
*/
if (rec->rec_header.packet_header.caplen != 0) {
if (!wtap_read_packet_bytes(wth->fh, buf,
rec->rec_header.packet_header.caplen, err, err_info))
return FALSE; /* Read error */
}
#if 0
packet++;
#endif
switch (hdr.rec_type) {
case AETHRA_ISDN_LINK:
#if 0
fprintf(stderr, "Packet %u: type 0x%02x (AETHRA_ISDN_LINK)\n",
packet, hdr.rec_type);
#endif
switch (hdr.flags & AETHRA_ISDN_LINK_SUBTYPE) {
case AETHRA_ISDN_LINK_LAPD:
/*
* The data is a LAPD frame.
*/
#if 0
fprintf(stderr, " subtype 0x%02x (AETHRA_ISDN_LINK_LAPD)\n", hdr.flags & AETHRA_ISDN_LINK_SUBTYPE);
#endif
goto found;
case AETHRA_ISDN_LINK_SA_BITS:
/*
* These records have one data byte, which
* has the Sa bits in the lower 5 bits.
*
* XXX - what about stuff other than 2048K
* PRI lines?
*/
#if 0
fprintf(stderr, " subtype 0x%02x (AETHRA_ISDN_LINK_SA_BITS)\n", hdr.flags & AETHRA_ISDN_LINK_SUBTYPE);
#endif
break;
case AETHRA_ISDN_LINK_ALL_ALARMS_CLEARED:
/*
* No data, just an "all alarms cleared"
* indication.
*/
#if 0
fprintf(stderr, " subtype 0x%02x (AETHRA_ISDN_LINK_ALL_ALARMS_CLEARED)\n", hdr.flags & AETHRA_ISDN_LINK_SUBTYPE);
#endif
break;
default:
#if 0
fprintf(stderr, " subtype 0x%02x, packet_size %u, direction 0x%02x\n",
hdr.flags & AETHRA_ISDN_LINK_SUBTYPE, rec->rec_header.packet_header.caplen, hdr.flags & AETHRA_U_TO_N);
#endif
break;
}
break;
default:
#if 0
fprintf(stderr, "Packet %u: type 0x%02x, packet_size %u, flags 0x%02x\n",
packet, hdr.rec_type, rec->rec_header.packet_header.caplen, hdr.flags);
#endif
break;
}
}
found:
return TRUE;
}
static gboolean
aethra_seek_read(wtap *wth, gint64 seek_off, wtap_rec *rec,
Buffer *buf, int *err, gchar **err_info)
{
struct aethrarec_hdr hdr;
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
return FALSE;
if (!aethra_read_rec_header(wth, wth->random_fh, &hdr, rec, err,
err_info)) {
if (*err == 0)
*err = WTAP_ERR_SHORT_READ;
return FALSE;
}
/*
* Read the packet data.
*/
if (!wtap_read_packet_bytes(wth->random_fh, buf, rec->rec_header.packet_header.caplen, err, err_info))
return FALSE; /* failed */
return TRUE;
}
static gboolean
aethra_read_rec_header(wtap *wth, FILE_T fh, struct aethrarec_hdr *hdr,
wtap_rec *rec, int *err, gchar **err_info)
{
aethra_t *aethra = (aethra_t *)wth->priv;
guint32 rec_size;
guint32 packet_size;
guint32 msecs;
/* Read record header. */
if (!wtap_read_bytes_or_eof(fh, hdr, sizeof *hdr, err, err_info))
return FALSE;
rec_size = pletoh16(hdr->rec_size);
if (rec_size < (sizeof *hdr - sizeof hdr->rec_size)) {
/* The record is shorter than a record header. */
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("aethra: File has %u-byte record, less than minimum of %u",
rec_size,
(unsigned int)(sizeof *hdr - sizeof hdr->rec_size));
return FALSE;
}
if (rec_size > WTAP_MAX_PACKET_SIZE_STANDARD) {
/*
* Probably a corrupt capture file; return an error,
* so that our caller doesn't blow up trying to allocate
* space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("aethra: File has %u-byte packet, bigger than maximum of %u",
rec_size, WTAP_MAX_PACKET_SIZE_STANDARD);
return FALSE;
}
packet_size = rec_size - (guint32)(sizeof *hdr - sizeof hdr->rec_size);
msecs = pletoh32(hdr->timestamp);
rec->rec_type = REC_TYPE_PACKET;
rec->block = wtap_block_create(WTAP_BLOCK_PACKET);
rec->presence_flags = WTAP_HAS_TS;
rec->ts.secs = aethra->start + (msecs / 1000);
rec->ts.nsecs = (msecs % 1000) * 1000000;
rec->rec_header.packet_header.caplen = packet_size;
rec->rec_header.packet_header.len = packet_size;
rec->rec_header.packet_header.pseudo_header.isdn.uton = (hdr->flags & AETHRA_U_TO_N);
rec->rec_header.packet_header.pseudo_header.isdn.channel = 0; /* XXX - D channel */
return TRUE;
}
static const struct supported_block_type aethra_blocks_supported[] = {
/*
* We support packet blocks, with no comments or other options.
*/
{ WTAP_BLOCK_PACKET, MULTIPLE_BLOCKS_SUPPORTED, NO_OPTIONS_SUPPORTED }
};
static const struct file_type_subtype_info aethra_info = {
"Aethra .aps file", "aethra", "aps", NULL,
FALSE, BLOCKS_SUPPORTED(aethra_blocks_supported),
NULL, NULL, NULL
};
void register_aethra(void)
{
aethra_file_type_subtype = wtap_register_file_type_subtype(&aethra_info);
/*
* Register name for backwards compatibility with the
* wtap_filetypes table in Lua.
*/
wtap_register_backwards_compatibility_lua_name("AETHRA",
aethra_file_type_subtype);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/ |
C/C++ | wireshark/wiretap/aethra.h | /** @file
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __W_AETHRA_H__
#define __W_AETHRA_H__
#include <glib.h>
#include "wtap.h"
wtap_open_return_val aethra_open(wtap *wth, int *err, gchar **err_info);
#endif |
C/C++ | wireshark/wiretap/ascend-int.h | /** @file
*
* Definitions for routines common to multiple modules in the Lucent/Ascend
* capture file reading code, but not used outside that code.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __ASCEND_INT_H__
#define __ASCEND_INT_H__
#include <glib.h>
#include <stdbool.h>
#include "ws_symbol_export.h"
typedef struct {
time_t inittime;
gboolean adjusted;
gint64 next_packet_seek_start;
} ascend_t;
typedef struct {
int length;
guint32 u32_val;
guint16 u16_val;
guint8 u8_val;
char str_val[ASCEND_MAX_STR_LEN];
} ascend_token_t;
typedef struct {
FILE_T fh;
const gchar *ascend_parse_error;
int err;
gchar *err_info;
struct ascend_phdr *pseudo_header;
guint8 *pkt_data;
gboolean saw_timestamp;
time_t timestamp;
gint64 first_hexbyte;
guint32 wirelen;
guint32 caplen;
time_t secs;
guint32 usecs;
ascend_token_t token;
} ascend_state_t;
extern bool
run_ascend_parser(guint8 *pd, ascend_state_t *parser_state, int *err, gchar **err_info);
#endif /* ! __ASCEND_INT_H__ */ |
C | wireshark/wiretap/ascendtext.c | /* ascendtext.c
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include "wtap-int.h"
#include "ascendtext.h"
#include "ascend-int.h"
#include "file_wrappers.h"
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <string.h>
/* Last updated: Feb 03 2005: Josh Bailey ([email protected]).
This module reads the text hex dump output of various TAOS
(Avaya/Alcatel/Lucent/Ascend Max, Max TNT, APX, etc) debug commands, including:
* pridisplay traces primary rate ISDN
* ether-display traces Ethernet packets (dangerous! CPU intensive)
* wanopening, wandisplay, wannext, wandsess
traces PPP or other WAN connections
Please see ascend_parser.lemon for examples.
Detailed documentation on TAOS products was at http://support.lucent.com;
that no longer works, and appears not to be available on the Wayback
Machine.
Some online manuals and other information include:
MAX Administration Guide:
https://downloads.avaya.com/elmodocs2/definity/def_r10_new/max/0678_002.pdf
Other MAX documentation:
https://support.avaya.com/products/P1192/max
https://web.archive.org/web/20201127014004/https://support.avaya.com/products/P1192/max#Tab4
Ascend Router Information:
http://maxrouter.rde.net/
https://web.archive.org/web/20200807215418/http://maxrouter.rde.net/
*/
typedef struct _ascend_magic_string {
guint type;
const gchar *strptr;
size_t strlength;
} ascend_magic_string;
/* these magic strings signify the headers of a supported debug commands */
#define ASCEND_MAGIC_ENTRY(type, string) \
{ type, string, sizeof string - 1 } /* strlen of a constant string */
static const ascend_magic_string ascend_magic[] = {
ASCEND_MAGIC_ENTRY(ASCEND_PFX_ISDN_X, "PRI-XMIT-"),
ASCEND_MAGIC_ENTRY(ASCEND_PFX_ISDN_R, "PRI-RCV-"),
ASCEND_MAGIC_ENTRY(ASCEND_PFX_WDS_X, "XMIT-"),
ASCEND_MAGIC_ENTRY(ASCEND_PFX_WDS_R, "RECV-"),
ASCEND_MAGIC_ENTRY(ASCEND_PFX_WDS_X, "XMIT:"),
ASCEND_MAGIC_ENTRY(ASCEND_PFX_WDS_R, "RECV:"),
ASCEND_MAGIC_ENTRY(ASCEND_PFX_WDS_X, "PPP-OUT"),
ASCEND_MAGIC_ENTRY(ASCEND_PFX_WDS_R, "PPP-IN"),
ASCEND_MAGIC_ENTRY(ASCEND_PFX_WDD, "WD_DIALOUT_DISP:"),
ASCEND_MAGIC_ENTRY(ASCEND_PFX_ETHER, "ETHER"),
};
#define ASCEND_MAGIC_STRINGS G_N_ELEMENTS(ascend_magic)
#define ASCEND_DATE "Date:"
static gboolean ascend_read(wtap *wth, wtap_rec *rec, Buffer *buf,
int *err, gchar **err_info, gint64 *data_offset);
static gboolean ascend_seek_read(wtap *wth, gint64 seek_off,
wtap_rec *rec, Buffer *buf,
int *err, gchar **err_info);
static int ascend_file_type_subtype = -1;
void register_ascend(void);
/* Seeks to the beginning of the next packet, and returns the
byte offset at which the header for that packet begins.
Returns -1 on failure. */
static gint64 ascend_find_next_packet(wtap *wth, int *err, gchar **err_info)
{
int byte;
gint64 date_off = -1, cur_off, packet_off;
size_t string_level[ASCEND_MAGIC_STRINGS];
guint string_i = 0;
static const gchar ascend_date[] = ASCEND_DATE;
size_t ascend_date_len = sizeof ascend_date - 1; /* strlen of a constant string */
size_t ascend_date_string_level;
guint excessive_read_count = 262144;
memset(&string_level, 0, sizeof(string_level));
ascend_date_string_level = 0;
while (((byte = file_getc(wth->fh)) != EOF)) {
excessive_read_count--;
if (!excessive_read_count) {
*err = 0;
return -1;
}
/*
* See whether this is the string_level[string_i]th character of
* Ascend magic string string_i.
*/
for (string_i = 0; string_i < ASCEND_MAGIC_STRINGS; string_i++) {
const gchar *strptr = ascend_magic[string_i].strptr;
size_t len = ascend_magic[string_i].strlength;
if (byte == *(strptr + string_level[string_i])) {
/*
* Yes, it is, so we need to check for the next character of
* that string.
*/
string_level[string_i]++;
/*
* Have we matched the entire string?
*/
if (string_level[string_i] >= len) {
/*
* Yes.
*/
cur_off = file_tell(wth->fh);
if (cur_off == -1) {
/* Error. */
*err = file_error(wth->fh, err_info);
return -1;
}
/* We matched some other type of header. */
if (date_off == -1) {
/* We haven't yet seen a date header, so this packet
doesn't have one.
Back up over the header we just read; that's where a read
of this packet should start. */
packet_off = cur_off - len;
} else {
/* This packet has a date/time header; a read of it should
start at the beginning of *that* header. */
packet_off = date_off;
}
goto found;
}
} else {
/*
* Not a match for this string, so reset the match process.
*/
string_level[string_i] = 0;
}
}
/*
* See whether this is the date_string_level'th character of
* ASCEND_DATE.
*/
if (byte == *(ascend_date + ascend_date_string_level)) {
/*
* Yes, it is, so we need to check for the next character of
* that string.
*/
ascend_date_string_level++;
/*
* Have we matched the entire string?
*/
if (ascend_date_string_level >= ascend_date_len) {
/* We matched a Date: header. It's a special case;
remember the offset, but keep looking for other
headers.
Reset the amount of Date: header that we've matched,
so that we start the process of matching a Date:
header all over again.
XXX - what if we match multiple Date: headers before
matching some other header? */
cur_off = file_tell(wth->fh);
if (cur_off == -1) {
/* Error. */
*err = file_error(wth->fh, err_info);
return -1;
}
date_off = cur_off - ascend_date_len;
ascend_date_string_level = 0;
}
} else {
/*
* Not a match for the Date: string, so reset the match process.
*/
ascend_date_string_level = 0;
}
}
*err = file_error(wth->fh, err_info);
return -1;
found:
/*
* Move to where the read for this packet should start, and return
* that seek offset.
*/
if (file_seek(wth->fh, packet_off, SEEK_SET, err) == -1)
return -1;
return packet_off;
}
wtap_open_return_val ascend_open(wtap *wth, int *err, gchar **err_info)
{
gint64 offset;
guint8 buf[ASCEND_MAX_PKT_LEN];
ascend_state_t parser_state = {0};
ws_statb64 statbuf;
ascend_t *ascend;
wtap_rec rec;
/* We haven't yet allocated a data structure for our private stuff;
set the pointer to null, so that "ascend_find_next_packet()" knows
not to fill it in. */
wth->priv = NULL;
offset = ascend_find_next_packet(wth, err, err_info);
if (offset == -1) {
if (*err != 0 && *err != WTAP_ERR_SHORT_READ)
return WTAP_OPEN_ERROR; /* read error */
return WTAP_OPEN_NOT_MINE; /* EOF */
}
/* Do a trial parse of the first packet just found to see if we might
really have an Ascend file. If it fails with an actual error,
fail; those will be I/O errors. */
parser_state.fh = wth->fh;
parser_state.pseudo_header = &rec.rec_header.packet_header.pseudo_header.ascend;
if (run_ascend_parser(buf, &parser_state, err, err_info) != 0 && *err != 0) {
/* An I/O error. */
return WTAP_OPEN_ERROR;
}
/* Either the parse succeeded, or it failed but didn't get an I/O
error.
If we got at least some data, return success even if the parser
reported an error. This is because the debug header gives the
number of bytes on the wire, not actually how many bytes are in
the trace. We won't know where the data ends until we run into
the next packet. */
if (parser_state.caplen == 0) {
/* We read no data, so this presumably isn't an Ascend file. */
return WTAP_OPEN_NOT_MINE;
}
wth->file_type_subtype = ascend_file_type_subtype;
wth->file_encap = WTAP_ENCAP_ASCEND;
wth->snapshot_length = ASCEND_MAX_PKT_LEN;
wth->subtype_read = ascend_read;
wth->subtype_seek_read = ascend_seek_read;
ascend = g_new(ascend_t, 1);
wth->priv = (void *)ascend;
/* The first packet we want to read is the one that
"ascend_find_next_packet()" just found; start searching
for it at the offset at which it found it. */
ascend->next_packet_seek_start = offset;
/* MAXen and Pipelines report the time since reboot. In order to keep
from reporting packet times near the epoch, we subtract the first
packet's timestamp from the capture file's ctime, which gives us an
offset that we can apply to each packet.
*/
if (wtap_fstat(wth, &statbuf, err) == -1) {
return WTAP_OPEN_ERROR;
}
ascend->inittime = statbuf.st_ctime;
ascend->adjusted = FALSE;
wth->file_tsprec = WTAP_TSPREC_USEC;
/*
* Add an IDB; we don't know how many interfaces were
* involved, so we just say one interface, about which
* we only know the link-layer type, snapshot length,
* and time stamp resolution.
*/
wtap_add_generated_idb(wth);
return WTAP_OPEN_MINE;
}
/* Parse the capture file.
Returns TRUE if we got a packet, FALSE otherwise. */
static gboolean
parse_ascend(ascend_t *ascend, FILE_T fh, wtap_rec *rec, Buffer *buf,
guint length, gint64 *next_packet_seek_start_ret,
int *err, gchar **err_info)
{
ascend_state_t parser_state = {0};
int retval;
ws_buffer_assure_space(buf, length);
parser_state.fh = fh;
parser_state.pseudo_header = &rec->rec_header.packet_header.pseudo_header.ascend;
retval = run_ascend_parser(ws_buffer_start_ptr(buf), &parser_state, err, err_info);
/* Did we see any data (hex bytes)? */
if (parser_state.first_hexbyte) {
/* Yes. Provide the offset of the first byte so that our caller can
tip off ascend_find_next_packet() as to where to look for the next
packet, if any. */
if (next_packet_seek_start_ret != NULL)
*next_packet_seek_start_ret = parser_state.first_hexbyte;
} else {
/* No. Maybe this record was broken; sometimes, a header will be
printed but the data will be omitted, or worse -- two headers will
be printed, followed by the data for each.
Because of this, we need to be fairly tolerant of what we accept
here. Provide our current offset so that our caller can tell
ascend_find_next_packet() to skip over what we've read so far so
we can try reading a new packet.
. That keeps us from getting into an infinite loop reading a broken
trace. */
if (next_packet_seek_start_ret != NULL)
*next_packet_seek_start_ret = file_tell(fh);
/* Don't treat that as a fatal error; pretend the parse succeeded. */
retval = 0;
}
/* if we got at least some data, return success even if the parser
reported an error. This is because the debug header gives the number
of bytes on the wire, not actually how many bytes are in the trace.
We won't know where the data ends until we run into the next packet. */
if (parser_state.caplen) {
if (! ascend->adjusted) {
ascend->adjusted = TRUE;
if (parser_state.saw_timestamp) {
/*
* Capture file contained a date and time.
* We do this only if this is the very first packet we've seen -
* i.e., if "ascend->adjusted" is false - because
* if we get a date and time after the first packet, we can't
* go back and adjust the time stamps of the packets we've already
* processed, and basing the time stamps of this and following
* packets on the time stamp from the file text rather than the
* ctime of the capture file means times before this and after
* this can't be compared.
*/
ascend->inittime = parser_state.timestamp;
}
if (ascend->inittime > parser_state.secs)
ascend->inittime -= parser_state.secs;
}
rec->rec_type = REC_TYPE_PACKET;
rec->block = wtap_block_create(WTAP_BLOCK_PACKET);
rec->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
rec->ts.secs = parser_state.secs + ascend->inittime;
rec->ts.nsecs = parser_state.usecs * 1000;
rec->rec_header.packet_header.caplen = parser_state.caplen;
rec->rec_header.packet_header.len = parser_state.wirelen;
return TRUE;
}
/* Didn't see any data. Still, perhaps the parser was happy. */
if (retval) {
if (*err == 0) {
/* Parser failed, but didn't report an I/O error, so a parse error.
Return WTAP_ERR_BAD_FILE, with the parse error as the error string. */
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup((parser_state.ascend_parse_error != NULL) ? parser_state.ascend_parse_error : "parse error");
}
} else {
if (*err == 0) {
/* Parser succeeded, but got no data, and didn't report an I/O error.
Return WTAP_ERR_BAD_FILE, with a "got no data" error string. */
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("no data returned by parse");
}
}
return FALSE;
}
/* Read the next packet; called from wtap_read(). */
static gboolean ascend_read(wtap *wth, wtap_rec *rec, Buffer *buf, int *err,
gchar **err_info, gint64 *data_offset)
{
ascend_t *ascend = (ascend_t *)wth->priv;
gint64 offset;
/* parse_ascend() will advance the point at which to look for the next
packet's header, to just after the last packet's header (ie. at the
start of the last packet's data). We have to get past the last
packet's header because we might mistake part of it for a new header. */
if (file_seek(wth->fh, ascend->next_packet_seek_start,
SEEK_SET, err) == -1)
return FALSE;
offset = ascend_find_next_packet(wth, err, err_info);
if (offset == -1) {
/* EOF or read error */
return FALSE;
}
if (!parse_ascend(ascend, wth->fh, rec, buf, wth->snapshot_length,
&ascend->next_packet_seek_start, err, err_info))
return FALSE;
/* Flex might have gotten an EOF and caused *err to be set to
WTAP_ERR_SHORT_READ. If so, that's not an error, as the parser
didn't return an error; set *err to 0, and get rid of any error
string. */
*err = 0;
if (*err_info != NULL) {
g_free(*err_info);
*err_info = NULL;
}
*data_offset = offset;
return TRUE;
}
static gboolean ascend_seek_read(wtap *wth, gint64 seek_off,
wtap_rec *rec, Buffer *buf,
int *err, gchar **err_info)
{
ascend_t *ascend = (ascend_t *)wth->priv;
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
return FALSE;
if (!parse_ascend(ascend, wth->random_fh, rec, buf,
wth->snapshot_length, NULL, err, err_info))
return FALSE;
/* Flex might have gotten an EOF and caused *err to be set to
WTAP_ERR_SHORT_READ. If so, that's not an error, as the parser
didn't return an error; set *err to 0, and get rid of any error
string. */
*err = 0;
if (*err_info != NULL) {
g_free(*err_info);
*err_info = NULL;
}
return TRUE;
}
static const struct supported_block_type ascend_blocks_supported[] = {
/*
* We support packet blocks, with no comments or other options.
*/
{ WTAP_BLOCK_PACKET, MULTIPLE_BLOCKS_SUPPORTED, NO_OPTIONS_SUPPORTED }
};
static const struct file_type_subtype_info ascend_info = {
"Lucent/Ascend access server trace", "ascend", "txt", NULL,
FALSE, BLOCKS_SUPPORTED(ascend_blocks_supported),
NULL, NULL, NULL
};
void register_ascend(void)
{
ascend_file_type_subtype = wtap_register_file_type_subtype(&ascend_info);
/*
* Register name for backwards compatibility with the
* wtap_filetypes table in Lua.
*/
wtap_register_backwards_compatibility_lua_name("ASCEND",
ascend_file_type_subtype);
} |
C/C++ | wireshark/wiretap/ascendtext.h | /** @file
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
*/
#ifndef __ASCENDTEXT_H__
#define __ASCENDTEXT_H__
#include <glib.h>
/*
* ASCEND_MAX_PKT_LEN is < WTAP_MAX_PACKET_SIZE_STANDARD, so we don't need to
* check the packet length.
*/
#define ASCEND_MAX_DATA_ROWS 8
#define ASCEND_MAX_DATA_COLS 16
#define ASCEND_MAX_PKT_LEN (ASCEND_MAX_DATA_ROWS * ASCEND_MAX_DATA_COLS)
wtap_open_return_val ascend_open(wtap *wth, int *err, gchar **err_info);
#endif |
wireshark/wiretap/ascend_parser.lemon | %include {
/* ascend_parser.lemon
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/*
Example 'pridisp' output data - one paragraph/frame:
PRI-XMIT-27: (task "l1Task" at 0x10216fe0, time: 560194.01) 4 octets @ 0x1027c5b0
[0000]: 00 01 01 a9 ....
PRI-RCV-27: (task "idle task" at 0x10123570, time: 560194.01) 4 octets @ 0x1027fb00
[0000]: 00 01 01 dd
Example 'pridisp' output data - two paragraphs/frame for XMIT case only:
PRI-XMIT-19/1: (task "l1Task" at 0x10216840, time: 274759.98) 4 octets @ 0x1027f230
[0000]: 00 01 30 d8 ..0.
PRI-XMIT-19/2 (task "l1Task" at 0x10216840, time: 274759.98) 11 octets @ 0x1027f234
[0000]: 08 02 8c bf 02 18 04 e9 82 83 8f ........ ...
Example 'ether-disp' output data:
ETHER3ND RECV: (task "_sarTask" at 0x802c6eb0, time: 259848.03) 775 octets @ 0xa8fb2020
[0000]: 00 d0 52 04 e7 1e 08 00 20 ae 51 b5 08 00 45 00 ..R..... .Q...E.
[0010]: 02 f9 05 e6 40 00 3f 11 6e 39 87 fe c4 95 3c 3c ....@.?. n9....<<
[0020]: 3c 05 13 c4 13 c4 02 e5 ef ed 49 4e 56 49 54 45 <....... ..INVITE
[0030]: 20 73 69 70 3a 35 32 30 37 33 40 36 30 2e 36 30 sip:520 [email protected]
[0040]: 2e 36 30 2e 35 20 53 49 50 2f 32 2e 30 0d 0a 56 .60.5 SI P/2.0..V
[0050]: 69 61 3a 20 53 49 50 2f 32 2e 30 2f 55 44 50 20 ia: SIP/ 2.0/UDP
[0060]: 31 33 35 2e 135.
Example 'wandsess' output data:
RECV-iguana:241:(task: B02614C0, time: 1975432.85) 49 octets @ 8003BD94
[0000]: FF 03 00 3D C0 06 CA 22 2F 45 00 00 28 6A 3B 40
[0010]: 00 3F 03 D7 37 CE 41 62 12 CF 00 FB 08 20 27 00
[0020]: 50 E4 08 DD D7 7C 4C 71 92 50 10 7D 78 67 C8 00
[0030]: 00
XMIT-iguana:241:(task: B04E12C0, time: 1975432.85) 53 octets @ 8009EB16
[0000]: FF 03 00 3D C0 09 1E 31 21 45 00 00 2C 2D BD 40
[0010]: 00 7A 06 D8 B1 CF 00 FB 08 CE 41 62 12 00 50 20
[0020]: 29 7C 4C 71 9C 9A 6A 93 A4 60 12 22 38 3F 10 00
[0030]: 00 02 04 05 B4
Example 'wdd' output data:
Date: 01/12/1990. Time: 12:22:33
Cause an attempt to place call to 14082750382
WD_DIALOUT_DISP: chunk 2515EE type IP.
(task: 251790, time: 994953.28) 44 octets @ 2782B8
[0000]: 00 C0 7B 71 45 6C 00 60 08 16 AA 51 08 00 45 00
[0010]: 00 2C 66 1C 40 00 80 06 53 F6 AC 14 00 18 CC 47
[0020]: C8 45 0A 31 00 50 3B D9 5B 75 00 00
The following output comes from a MAX with Software 7.2.3:
RECV-187:(task: B050B480, time: 18042248.03) 100 octets @ 800012C0
[0000]: FF 03 00 21 45 00 00 60 E3 49 00 00 7F 11 FD 7B
[0010]: C0 A8 F7 05 8A C8 18 51 00 89 00 89 00 4C C7 C1
[0020]: CC 8E 40 00 00 01 00 00 00 00 00 01 20 45 4A 45
[0030]: 42 45 43 45 48 43 4E 46 43 46 41 43 41 43 41 43
[0040]: 41 43 41 43 41 43 41 43 41 43 41 42 4E 00 00 20
[0050]: 00 01 C0 0C 00 20 00 01 00 04 93 E0 00 06 60 00
[0060]: C0 A8 F7 05
XMIT-187:(task: B0292CA0, time: 18042248.04) 60 octets @ 800AD576
[0000]: FF 03 00 21 45 00 00 38 D7 EE 00 00 0F 01 11 2B
[0010]: 0A FF FF FE C0 A8 F7 05 03 0D 33 D3 00 00 00 00
[0020]: 45 00 00 60 E3 49 00 00 7E 11 FE 7B C0 A8 F7 05
[0030]: 8A C8 18 51 00 89 00 89 00 4C C7 C1
RECV-187:(task: B0292CA0, time: 18042251.92) 16 octets @ 800018E8
[0000]: FF 03 C0 21 09 01 00 0C DE 61 96 4B 00 30 94 92
In TAOS 8.0, Lucent slightly changed the format as follows:
Example 'wandisp' output data (TAOS 8.0.3): (same format is used
for 'wanopen' and 'wannext' command)
RECV-14: (task "idle task" at 0xb05e6e00, time: 1279.01) 29 octets @ 0x8000e0fc
[0000]: ff 03 c0 21 01 01 00 19 01 04 05 f4 11 04 05 f4 ...!.... ........
[0010]: 13 09 03 00 c0 7b 9a 9f 2d 17 04 10 00 .....{.. -....
XMIT-14: (task "idle task" at 0xb05e6e00, time: 1279.02) 38 octets @ 0x8007fd56
[0000]: ff 03 c0 21 01 01 00 22 00 04 00 00 01 04 05 f4 ...!..." ........
[0010]: 03 05 c2 23 05 11 04 05 f4 13 09 03 00 c0 7b 80 ...#.... ......{.
[0020]: 7c ef 17 04 0e 00 |.....
XMIT-14: (task "idle task" at 0xb05e6e00, time: 1279.02) 29 octets @ 0x8007fa36
[0000]: ff 03 c0 21 02 01 00 19 01 04 05 f4 11 04 05 f4 ...!.... ........
[0010]: 13 09 03 00 c0 7b 9a 9f 2d 17 04 10 00 .....{.. -....
Example 'wandsess' output data (TAOS 8.0.3):
RECV-Max7:20: (task "_brouterControlTask" at 0xb094ac20, time: 1481.50) 20 octets @ 0x8000d198
[0000]: ff 03 00 3d c0 00 00 04 80 fd 02 01 00 0a 11 06 ...=.... ........
[0010]: 00 01 01 03 ....
XMIT-Max7:20: (task "_brouterControlTask" at 0xb094ac20, time: 1481.51) 26 octets @ 0x800806b6
[0000]: ff 03 00 3d c0 00 00 00 80 21 01 01 00 10 02 06 ...=.... .!......
[0010]: 00 2d 0f 01 03 06 89 64 03 08 .-.....d ..
XMIT-Max7:20: (task "_brouterControlTask" at 0xb094ac20, time: 1481.51) 20 octets @ 0x8007f716
[0000]: ff 03 00 3d c0 00 00 01 80 fd 01 01 00 0a 11 06 ...=.... ........
[0010]: 00 01 01 03 ....
The changes since TAOS 7.X are:
1) White space is added before "(task".
2) Task has a name, indicated by a subsequent string surrounded by a
double-quote.
3) Address expressed in hex number has a preceding "0x".
4) Hex numbers are in lower case.
5) There is a character display corresponding to hex data in each line.
*/
#include "config.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "wtap-int.h"
#include "ascendtext.h"
#include "ascend-int.h"
#include "ascend_parser.h"
#include "ascend_scanner_lex.h"
#include "file_wrappers.h"
#include <wsutil/wslog.h>
#define NO_USER "<none>"
static void *AscendParserAlloc(void *(*mallocProc)(size_t));
static void AscendParser(void *yyp, int yymajor, ascend_token_t yyminor, ascend_state_t *state);
static void AscendParserFree(void *p, void (*freeProc)(void*));
#if 0
#define ASCEND_PARSER_DEBUG 1
#undef NDEBUG
#define ascend_debug(...) ws_warning(__VA_ARGS__)
#else
#define ascend_debug(...)
#endif
DIAG_OFF_LEMON()
} /* end of %include */
%code {
DIAG_ON_LEMON()
}
%name AscendParser
%extra_argument { ascend_state_t *parser_state }
%token_type { ascend_token_t }
%token_destructor {
(void) parser_state;
(void) yypminor;
}
%type STRING { ascend_token_t* }
%type KEYWORD { ascend_token_t* }
%type WDD_DATE { ascend_token_t* }
%type WDD_DECNUM { ascend_token_t* }
%type WDD_TIME { ascend_token_t* }
%type WDD_CAUSE { ascend_token_t* }
%type WDD_CALLNUM { ascend_token_t* }
%type WDD_CHUNK { ascend_token_t* }
%type COUNTER { ascend_token_t* }
%type SLASH_SUFFIX { ascend_token_t* }
%type WDS_PREFIX { ascend_token_t* }
%type ISDN_PREFIX { ascend_token_t* }
%type ETHER_PREFIX { ascend_token_t* }
%type DECNUM { ascend_token_t* }
%type YEAR { ascend_token_t* }
%type MONTH { ascend_token_t* }
%type MDAY { ascend_token_t* }
%type HEXNUM { ascend_token_t* }
%type HEXBYTE { ascend_token_t* }
data_packet ::= ether_hdr datagroup .
data_packet ::= deferred_isdn_hdr datagroup deferred_isdn_hdr datagroup .
data_packet ::= isdn_hdr datagroup .
data_packet ::= wds_hdr datagroup .
data_packet ::= wds8_hdr datagroup .
data_packet ::= wdp7_hdr datagroup .
data_packet ::= wdp8_hdr datagroup .
data_packet ::= wdd_date wdd_hdr datagroup .
data_packet ::= wdd_hdr datagroup .
%type isdn_prefix { guint16 }
isdn_prefix(U16) ::= ISDN_PREFIX(A_TOK) . { U16 = A_TOK.u16_val; }
%type ether_prefix { guint16 }
ether_prefix(U16) ::= ETHER_PREFIX(A_TOK) . { U16 = A_TOK.u16_val; }
%type wds_prefix { guint16 }
wds_prefix(U16) ::= WDS_PREFIX(A_TOK) . { U16 = A_TOK.u16_val; }
string ::= STRING .
%type decnum { guint32 }
decnum(U32) ::= DECNUM(A_TOK) . { U32 = A_TOK.u32_val; }
%type hexnum { guint32 }
hexnum(U32) ::= HEXNUM(A_TOK) . { U32 = A_TOK.u32_val; }
%type wdd_decnum { guint32 }
wdd_decnum(U32) ::= WDD_DECNUM(A_TOK) . { U32 = A_TOK.u32_val; }
/*
pridisp special case - I-frame header printed separately from contents,
one frame across two messages.
PRI-XMIT-0/1: (task "l1Task" at 0x80152b20, time: 283529.65) 4 octets @
0x80128220
[0000]: 00 01 ae b2 ....
PRI-XMIT-0/2 (task "l1Task" at 0x80152b20, time: 283529.65) 10 octets @
0x80128224
[0000]: 08 02 d7 e3 02 18 03 a9 83 8a ........
*/
deferred_isdn_hdr ::= isdn_prefix(TYPE) decnum(SESS) SLASH_SUFFIX KEYWORD string KEYWORD hexnum(TASK) KEYWORD decnum(SECS) decnum(USECS) decnum(WIRELEN) KEYWORD HEXNUM . {
parser_state->wirelen += WIRELEN;
parser_state->secs = SECS;
parser_state->usecs = USECS;
if (parser_state->pseudo_header != NULL) {
parser_state->pseudo_header->type = TYPE;
parser_state->pseudo_header->sess = SESS;
parser_state->pseudo_header->call_num[0] = '\0';
parser_state->pseudo_header->chunk = 0;
parser_state->pseudo_header->task = TASK;
}
/* because we have two data groups */
parser_state->first_hexbyte = 0;
}
/*
PRI-XMIT-19: (task "l1Task" at 0x10216840, time: 274758.67) 4 octets @ 0x1027c1c0
... or ...
PRI-RCV-27: (task "idle task" at 0x10123570, time: 560194.01) 4 octets @ 0x1027fb00
*/
isdn_hdr ::= isdn_prefix(TYPE) decnum(SESS) KEYWORD string KEYWORD hexnum(TASK) KEYWORD decnum(SECS) decnum(USECS) decnum(WIRELEN) KEYWORD HEXNUM . {
parser_state->wirelen += WIRELEN;
parser_state->secs = SECS;
parser_state->usecs = USECS;
if (parser_state->pseudo_header != NULL) {
parser_state->pseudo_header->type = TYPE;
parser_state->pseudo_header->sess = SESS;
parser_state->pseudo_header->call_num[0] = '\0';
parser_state->pseudo_header->chunk = 0;
parser_state->pseudo_header->task = TASK;
}
parser_state->first_hexbyte = 0;
}
/*
ETHER3ND XMIT: (task "_sarTask" at 0x802c6eb0, time: 259848.11) 414 octets @ 0xa
885f80e
*/
ether_hdr ::= ether_prefix(TYPE) string KEYWORD string KEYWORD hexnum(TASK) KEYWORD decnum(SECS) decnum(USECS) decnum(WIRELEN) KEYWORD HEXNUM . {
parser_state->wirelen += WIRELEN;
parser_state->secs = SECS;
parser_state->usecs = USECS;
if (parser_state->pseudo_header != NULL) {
parser_state->pseudo_header->type = TYPE;
parser_state->pseudo_header->call_num[0] = '\0';
parser_state->pseudo_header->chunk = 0;
parser_state->pseudo_header->task = TASK;
}
}
/* RECV-iguana:241:(task: B02614C0, time: 1975432.85) 49 octets @ 8003BD94 */
/* 1 2 3 4 5 6 7 8 9 10 11 */
wds_hdr ::= wds_prefix(TYPE) string decnum(SESS) KEYWORD hexnum(TASK) KEYWORD decnum(SECS) decnum(USECS) decnum(WIRELEN) KEYWORD HEXNUM . {
parser_state->wirelen += WIRELEN;
parser_state->secs = SECS;
parser_state->usecs = USECS;
if (parser_state->pseudo_header != NULL) {
/* parser_state->pseudo_header->user is set in ascend_scanner.l */
parser_state->pseudo_header->type = TYPE;
parser_state->pseudo_header->sess = SESS;
parser_state->pseudo_header->call_num[0] = '\0';
parser_state->pseudo_header->chunk = 0;
parser_state->pseudo_header->task = TASK;
}
}
/* RECV-Max7:20: (task "_brouterControlTask" at 0xb094ac20, time: 1481.50) 20 octets @ 0x8000d198 */
/* 1 2 3 4 5 6 7 8 9 10 11 12 13 */
wds8_hdr ::= wds_prefix(TYPE) string decnum(SESS) KEYWORD string KEYWORD hexnum(TASK) KEYWORD decnum(SECS) decnum(USECS) decnum(WIRELEN) KEYWORD HEXNUM . {
parser_state->wirelen += WIRELEN;
parser_state->secs = SECS;
parser_state->usecs = USECS;
if (parser_state->pseudo_header != NULL) {
/* parser_state->pseudo_header->user is set in ascend_scanner.l */
parser_state->pseudo_header->type = TYPE;
parser_state->pseudo_header->sess = SESS;
parser_state->pseudo_header->call_num[0] = '\0';
parser_state->pseudo_header->chunk = 0;
parser_state->pseudo_header->task = TASK;
}
}
/* RECV-187:(task: B050B480, time: 18042248.03) 100 octets @ 800012C0 */
/* 1 2 3 4 5 6 7 8 9 10 */
wdp7_hdr ::= wds_prefix(TYPE) decnum(SESS) KEYWORD hexnum(TASK) KEYWORD decnum(SECS) decnum(USECS) decnum(WIRELEN) KEYWORD HEXNUM . {
parser_state->wirelen += WIRELEN;
parser_state->secs = SECS;
parser_state->usecs = USECS;
if (parser_state->pseudo_header != NULL) {
/* parser_state->pseudo_header->user is set in ascend_scanner.l */
parser_state->pseudo_header->type = TYPE;
parser_state->pseudo_header->sess = SESS;
parser_state->pseudo_header->call_num[0] = '\0';
parser_state->pseudo_header->chunk = 0;
parser_state->pseudo_header->task = TASK;
}
}
/* XMIT-44: (task "freedm_task" at 0xe051fd10, time: 6258.66) 29 octets @ 0x606d1f00 */
/* 1 2 3 4 5 6 7 8 9 10 11 12 */
wdp8_hdr ::= wds_prefix(TYPE) decnum(SESS) KEYWORD string KEYWORD hexnum(TASK) KEYWORD decnum(SECS) decnum(USECS) decnum(WIRELEN) KEYWORD HEXNUM . {
parser_state->wirelen += WIRELEN;
parser_state->secs = SECS;
parser_state->usecs = USECS;
if (parser_state->pseudo_header != NULL) {
/* parser_state->pseudo_header->user is set in ascend_scanner.l */
parser_state->pseudo_header->type = TYPE;
parser_state->pseudo_header->sess = SESS;
parser_state->pseudo_header->call_num[0] = '\0';
parser_state->pseudo_header->chunk = 0;
parser_state->pseudo_header->task = TASK;
}
}
/*
Date: 01/12/1990. Time: 12:22:33
Cause an attempt to place call to 14082750382
*/
/* 1 2 3 4 5 6 7 8 9 10*/
wdd_date ::= WDD_DATE wdd_decnum(MONTH) wdd_decnum(MDAY) wdd_decnum(YEAR) WDD_TIME wdd_decnum(HOUR) wdd_decnum(MINUTE) wdd_decnum(SECOND) WDD_CAUSE WDD_CALLNUM(CN_T) . {
/*
* Supply the date/time value to the code above us; it will use the
* first date/time value supplied as the capture start date/time.
*/
struct tm wddt;
wddt.tm_sec = SECOND;
wddt.tm_min = MINUTE;
wddt.tm_hour = HOUR;
wddt.tm_mday = MDAY;
wddt.tm_mon = MONTH - 1;
wddt.tm_year = (YEAR > 1970) ? YEAR - 1900 : 70;
wddt.tm_isdst = -1;
parser_state->timestamp = (guint32) mktime(&wddt);
parser_state->saw_timestamp = TRUE;
(void) g_strlcpy(parser_state->pseudo_header->call_num, CN_T.str_val, ASCEND_MAX_STR_LEN);
}
/*
WD_DIALOUT_DISP: chunk 2515EE type IP.
(task: 251790, time: 994953.28) 44 octets @ 2782B8
*/
/* 1 2 3 4 5 6 7 8 9 10 11*/
wdd_hdr ::= WDD_CHUNK hexnum(CHUNK) KEYWORD KEYWORD hexnum(TASK) KEYWORD decnum(SECS) decnum(USECS) decnum(WIRELEN) KEYWORD HEXNUM . {
parser_state->wirelen = WIRELEN;
parser_state->secs = SECS;
parser_state->usecs = USECS;
if (parser_state->pseudo_header != NULL) {
parser_state->pseudo_header->type = ASCEND_PFX_WDD;
parser_state->pseudo_header->user[0] = '\0';
parser_state->pseudo_header->sess = 0;
parser_state->pseudo_header->chunk = CHUNK;
parser_state->pseudo_header->task = TASK;
}
}
byte ::= HEXBYTE(A_TOK) . {
/* remember the position of the data group in the trace, to tip off
ascend_find_next_packet() as to where to look for the next header. */
if (parser_state->first_hexbyte == 0) {
parser_state->first_hexbyte = file_tell(parser_state->fh) - A_TOK.length;
}
/* XXX - if this test fails, it means that we parsed more bytes than
the header claimed there were. */
if (parser_state->caplen < parser_state->wirelen) {
parser_state->pkt_data[parser_state->caplen] = A_TOK.u8_val;
parser_state->caplen++;
}
}
/* XXX There must be a better way to do this... */
bytegroup ::= byte byte byte byte byte byte byte byte byte byte byte byte byte byte byte byte .
bytegroup ::= byte byte byte byte byte byte byte byte byte byte byte byte byte byte byte .
bytegroup ::= byte byte byte byte byte byte byte byte byte byte byte byte byte byte .
bytegroup ::= byte byte byte byte byte byte byte byte byte byte byte byte byte .
bytegroup ::= byte byte byte byte byte byte byte byte byte byte byte byte .
bytegroup ::= byte byte byte byte byte byte byte byte byte byte byte .
bytegroup ::= byte byte byte byte byte byte byte byte byte byte .
bytegroup ::= byte byte byte byte byte byte byte byte byte .
bytegroup ::= byte byte byte byte byte byte byte byte .
bytegroup ::= byte byte byte byte byte byte byte .
bytegroup ::= byte byte byte byte byte byte .
bytegroup ::= byte byte byte byte byte .
bytegroup ::= byte byte byte byte .
bytegroup ::= byte byte byte .
bytegroup ::= byte byte .
bytegroup ::= byte .
dataln ::= COUNTER bytegroup .
datagroup ::= dataln dataln dataln dataln dataln dataln dataln dataln .
datagroup ::= dataln dataln dataln dataln dataln dataln dataln .
datagroup ::= dataln dataln dataln dataln dataln dataln .
datagroup ::= dataln dataln dataln dataln dataln .
datagroup ::= dataln dataln dataln dataln .
datagroup ::= dataln dataln dataln .
datagroup ::= dataln dataln .
datagroup ::= dataln .
%syntax_error
{
/*
* We might be parsing output that includes console session output along
* with packet dumps.
*/
(void)yypParser;
(void)yyminor;
static char *err = "non-packet data";
parser_state->ascend_parse_error = err;
}
%code {
/* Run the parser. */
bool
run_ascend_parser(guint8 *pd, ascend_state_t *parser_state, int *err, gchar **err_info)
{
yyscan_t scanner = NULL;
void *parser;
if (ascend_lex_init(&scanner) != 0) {
/* errno is set if this fails */
*err = errno;
*err_info = NULL;
return false;
}
/* Associate the parser state with the lexical analyzer state */
ascend_set_extra(parser_state, scanner);
parser_state->ascend_parse_error = NULL;
parser_state->err = 0;
parser_state->err_info = NULL;
parser_state->pkt_data = pd;
/*
* We haven't seen a time stamp yet.
*/
parser_state->saw_timestamp = FALSE;
parser_state->timestamp = 0;
parser_state->first_hexbyte = 0;
parser_state->caplen = 0;
parser_state->wirelen = 0;
parser_state->secs = 0;
parser_state->usecs = 0;
/*
* Not all packets in a "wdd" dump necessarily have a "Cause an
* attempt to place call to" header (I presume this can happen if
* there was a call in progress when the packet was sent or
* received), so we won't necessarily have the phone number for
* the packet.
*
* XXX - we could assume, in the sequential pass, that it's the
* phone number from the last call, and remember that for use
* when doing random access.
*/
parser_state->pseudo_header->call_num[0] = '\0';
parser = AscendParserAlloc(g_malloc);
#ifdef ASCEND_PARSER_DEBUG
AscendParserTrace(stderr, "=AP ");
#endif
int token_id;
do {
token_id = ascend_lex(scanner);
ascend_debug("Got token %d at %" PRId64, token_id, file_tell(parser_state->fh));
AscendParser(parser, token_id, parser_state->token, parser_state);
} while (token_id && !parser_state->err && !parser_state->ascend_parse_error && parser_state->caplen < ASCEND_MAX_PKT_LEN);
AscendParserFree(parser, g_free);
ascend_lex_destroy(scanner);
if (parser_state->err) {
*err = parser_state->err;
*err_info = parser_state->err_info;
return false;
}
return true;
}
} // %code |
|
wireshark/wiretap/ascend_scanner.l | %top {
/* Include this before everything else, for various large-file definitions */
#include "config.h"
#include <wireshark.h>
}
/*
* We want a reentrant scanner.
*/
%option reentrant
/*
* We don't read interactively from the terminal.
*/
%option never-interactive
/*
* We want to stop processing when we get to the end of the input.
*/
%option noyywrap
/*
* The type for the state we keep for the scanner (and parser).
*/
%option extra-type="ascend_state_t *"
/*
* Prefix scanner routines with "ascend_" rather than "yy", so this scanner
* can coexist with other scanners.
*/
%option prefix="ascend_"
/*
* We have to override the memory allocators so that we don't get
* "unused argument" warnings from the yyscanner argument (which
* we don't use, as we have a global memory allocator).
*
* We provide, as macros, our own versions of the routines generated by Flex,
* which just call malloc()/realloc()/free() (as the Flex versions do),
* discarding the extra argument.
*/
%option noyyalloc
%option noyyrealloc
%option noyyfree
%{
/* ascend_scanner.l
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <stdlib.h>
#include <string.h>
#include "wtap-int.h"
#include "ascendtext.h"
#include "ascend-int.h"
#include "ascend_parser.h"
#include "file_wrappers.h"
/*
* Disable diagnostics in the code generated by Flex.
*/
DIAG_OFF_FLEX()
static int ascend_yyinput(void *buf, ascend_state_t *parser_state) {
int c = file_getc(parser_state->fh);
if (c == EOF) {
parser_state->err = file_error(parser_state->fh,
&parser_state->err_info);
if (parser_state->err == 0)
parser_state->err = WTAP_ERR_SHORT_READ;
return YY_NULL;
} else {
*(char *) buf = c;
return 1;
}
}
#define YY_INPUT(buf, result, max_size) \
do { (result) = ascend_yyinput((buf), yyextra); } while (0)
/* Count bytes read. This is required in order to rewind the file
* to the beginning of the next packet, since flex reads more bytes
* before executing the action that does yyterminate(). */
#define YY_USER_ACTION do { yyextra->token.length = yyleng; } while (0);
#define NO_USER "<none>"
#ifndef HAVE_UNISTD_H
#define YY_NO_UNISTD_H
#endif
/*
* Sleazy hack to suppress compiler warnings in yy_fatal_error().
*/
#define YY_EXIT_FAILURE ((void)yyscanner, 2)
/*
* Macros for the allocators, to discard the extra argument.
*/
#define ascend_alloc(size, yyscanner) (void *)malloc(size)
#define ascend_realloc(ptr, size, yyscanner) (void *)realloc((char *)(ptr), (size))
#define ascend_free(ptr, yyscanner) free((char *)ptr)
%}
D [0-9]
H [A-Fa-f0-9]
PPP_XPFX PPP-OUT
PPP_RPFX PPP-IN
ISDN_XPFX PRI-XMIT-
ISDN_RPFX PRI-RCV-
WAN_XPFX XMIT[\-:]*
WAN_RPFX RECV[\-:]*
ETHER_PFX ETHER
WDD_DATE "Date:"
WDD_TIME "Time:"
WDD_CAUSE "Cause an attempt to place call to "
WDD_CALLNUM [^\n\r\t ]+
WDD_CHUNK "WD_DIALOUT_DISP: chunk"
WDD_TYPE "type "[^\n\r\t ]+
%s sc_gen_task
%s sc_gen_time_s
%s sc_gen_time_u
%s sc_gen_octets
%s sc_gen_counter
%s sc_gen_byte
%s sc_wds_user
%s sc_wds_sess
%s sc_wdd_date_d
%s sc_wdd_date_m
%s sc_wdd_date_y
%s sc_wdd_time
%s sc_wdd_time_h
%s sc_wdd_time_m
%s sc_wdd_time_s
%s sc_wdd_cause
%s sc_wdd_callnum
%s sc_wdd_chunk
%s sc_wdd_chunknum
%s sc_wdd_type
%s sc_chardisp
%s sc_isdn_call
%s sc_ether_direction
%%
<INITIAL,sc_gen_byte>{ETHER_PFX} {
BEGIN(sc_ether_direction);
yyextra->token.u16_val = ASCEND_PFX_ETHER;
return ETHER_PREFIX;
}
<INITIAL,sc_gen_byte>{ISDN_XPFX} {
BEGIN(sc_isdn_call);
yyextra->token.u16_val = ASCEND_PFX_ISDN_X;
return ISDN_PREFIX;
}
<INITIAL,sc_gen_byte>{ISDN_RPFX} {
BEGIN(sc_isdn_call);
yyextra->token.u16_val = ASCEND_PFX_ISDN_R;
return ISDN_PREFIX;
}
<INITIAL,sc_gen_byte>{WAN_XPFX} {
BEGIN(sc_wds_user);
yyextra->token.u16_val = ASCEND_PFX_WDS_X;
return WDS_PREFIX;
}
<INITIAL,sc_gen_byte>{WAN_RPFX} {
BEGIN(sc_wds_user);
yyextra->token.u16_val = ASCEND_PFX_WDS_R;
return WDS_PREFIX;
}
<INITIAL,sc_gen_byte>{PPP_XPFX} {
BEGIN(sc_wds_user);
yyextra->token.u16_val = ASCEND_PFX_WDS_X;
return WDS_PREFIX;
}
<INITIAL,sc_gen_byte>{PPP_RPFX} {
BEGIN(sc_wds_user);
yyextra->token.u16_val = ASCEND_PFX_WDS_R;
return WDS_PREFIX;
}
/*
* If we allow an arbitrary non-zero number of non-left-parentheses after
* "ETHER", that means that some file that has ETHER followed by a lot of
* text (see, for example, tpncp/tpncp.dat in the source tree) can cause
* either an infinite loop or a loop that take forever to finish, as the
* scanner keeps swallowing characters. Limit it to 20 characters.
*
* XXX - any reason to require at least two of them?
*/
<sc_ether_direction>[^\(]{2,20} {
BEGIN(sc_gen_task);
return STRING;
}
/*
* If we allow an arbitrary non-zero number of non-slash, non-left-parentheses,
* non-colon characters after "PRI-XMIT", that means that some file that has
* PRI-XMIT= followed by a lot of text can cause either an infinite loop or
* a loop that take forever to finish, as the scanner keeps swallowing
* characters. Limit it to 20 characters.
*/
<sc_isdn_call>[^\/\(:]{1,20} {
BEGIN(sc_gen_task);
return DECNUM;
}
<sc_wds_user>[^:]{2,20} {
char *atcopy = g_strdup(yytext);
char colon = input(yyscanner);
char after = input(yyscanner);
int retval = STRING;
unput(after); unput(colon);
if (after != '(' && after != ' ') {
BEGIN(sc_wds_sess);
if (yyextra->pseudo_header != NULL && yyextra->pseudo_header->user[0] == '\0') {
(void) g_strlcpy(yyextra->pseudo_header->user, atcopy, ASCEND_MAX_STR_LEN);
}
} else { /* We have a version 7 file */
BEGIN(sc_gen_task);
if (yyextra->pseudo_header != NULL && yyextra->pseudo_header->user[0] == '\0') {
(void) g_strlcpy(yyextra->pseudo_header->user, NO_USER, ASCEND_MAX_STR_LEN);
}
/* Are valid values ever > 2^32? If so we need to adjust YYSTYPE and a lot of */
/* upstream code accordingly. */
yyextra->token.u32_val = (guint32) strtoul(yytext, NULL, 10);
retval = DECNUM;
}
g_free (atcopy);
return retval;
}
<sc_wds_sess>{D}* {
BEGIN(sc_gen_task);
yyextra->token.u32_val = (guint32) strtoul(yytext, NULL, 10);
return DECNUM;
}
<sc_gen_task>(0x|0X)?{H}{2,8} {
BEGIN(sc_gen_time_s);
yyextra->token.u32_val = (guint32) strtoul(yytext, NULL, 16);
return HEXNUM;
}
<sc_gen_task>\"[A-Za-z0-9_ ]+\" {
return STRING;
}
<sc_gen_time_s>{D}{1,10} {
BEGIN(sc_gen_time_u);
yyextra->token.u32_val = (guint32) strtoul(yytext, NULL, 10);
return DECNUM;
}
<sc_gen_time_u>{D}{1,6} {
char *atcopy = g_strdup(yytext);
BEGIN(sc_gen_octets);
/* only want the most significant 2 digits. convert to usecs */
if (strlen(atcopy) > 2)
atcopy[2] = '\0';
yyextra->token.u32_val = (guint32) strtoul(atcopy, NULL, 10) * 10000;
g_free(atcopy);
return DECNUM;
}
<sc_gen_octets>{D}{1,10} {
BEGIN(sc_gen_counter);
yyextra->token.u32_val = (guint32) strtoul(yytext, NULL, 10);
return DECNUM;
}
<sc_gen_counter,sc_gen_byte>"["{H}{4}"]:" {
BEGIN(sc_gen_byte);
return COUNTER;
}
<sc_gen_byte>{H}{2} {
yyextra->token.u8_val = (guint8) strtoul(yytext, NULL, 16);
return HEXBYTE;
}
<sc_gen_byte>" "{4} {
BEGIN(sc_chardisp);
}
<sc_chardisp>.* {
BEGIN(sc_gen_byte);
}
<INITIAL,sc_gen_byte>{WDD_DATE} {
BEGIN(sc_wdd_date_m);
return WDD_DATE;
}
/*
* Scan m/d/y as three separate m, /d/, and y tokens.
* We could alternately treat m/d/y as a single token.
*/
<sc_wdd_date_m>{D}{2} {
BEGIN(sc_wdd_date_d);
yyextra->token.u32_val = (guint32) strtoul(yytext, NULL, 10);
return WDD_DECNUM;
}
<sc_wdd_date_d>\/{D}{2}\/ {
BEGIN(sc_wdd_date_y);
yyextra->token.u32_val = (guint32) strtoul(yytext+1, NULL, 10);
return WDD_DECNUM;
}
<sc_wdd_date_y>{D}{4} {
BEGIN(sc_wdd_time);
yyextra->token.u32_val = (guint32) strtoul(yytext, NULL, 10);
return WDD_DECNUM;
}
<sc_wdd_time>{WDD_TIME} {
BEGIN(sc_wdd_time_h);
return WDD_TIME;
}
/*
* Scan h:m:s as three separate h, :m:, and s tokens similar to above.
*/
<sc_wdd_time_h>{D}{2} {
BEGIN(sc_wdd_time_m);
yyextra->token.u32_val = (guint32) strtoul(yytext, NULL, 10);
return WDD_DECNUM;
}
<sc_wdd_time_m>:{D}{2}: {
BEGIN(sc_wdd_time_s);
yyextra->token.u32_val = (guint32) strtoul(yytext+1, NULL, 10);
return WDD_DECNUM;
}
<sc_wdd_time_s>{D}{2} {
BEGIN(sc_wdd_cause);
yyextra->token.u32_val = (guint32) strtoul(yytext, NULL, 10);
return WDD_DECNUM;
}
<sc_wdd_cause>{WDD_CAUSE} {
BEGIN(sc_wdd_callnum);
return WDD_CAUSE;
}
<sc_wdd_callnum>{WDD_CALLNUM} {
BEGIN(sc_wdd_chunk);
(void) g_strlcpy(yyextra->token.str_val, yytext, ASCEND_MAX_STR_LEN);
return WDD_CALLNUM;
}
<INITIAL,sc_wdd_chunk,sc_gen_byte>{WDD_CHUNK} {
BEGIN(sc_wdd_chunknum);
return WDD_CHUNK;
}
<sc_wdd_chunknum>{H}{1,8} {
BEGIN(sc_wdd_type);
yyextra->token.u32_val = (guint32) strtoul(yytext, NULL, 16);
return HEXNUM;
}
<sc_wdd_type>{WDD_TYPE} {
BEGIN(sc_gen_task);
return KEYWORD;
}
<sc_gen_task>\/{D}+ {
return SLASH_SUFFIX;
}
(0x|0X)?{H}+ { return HEXNUM; }
task:|task|at|time:|octets { return KEYWORD; }
<<EOF>> { yyterminate(); }
(.|\n) ;
%%
/*
* Turn diagnostics back on, so we check the code that we've written.
*/
DIAG_ON_FLEX() |
|
C | wireshark/wiretap/atm.c | /* atm.c
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include "wtap-int.h"
#include "atm.h"
/*
* Routines to use with ATM capture file types that don't include information
* about the *type* of ATM traffic (or, at least, where we haven't found
* that information).
*
* We assume the traffic is AAL5, unless it's VPI 0/VCI 5, in which case
* we assume it's the signalling AAL.
*/
void
atm_guess_traffic_type(wtap_rec *rec, const guint8 *pd)
{
/*
* Start out assuming nothing other than that it's AAL5.
*/
rec->rec_header.packet_header.pseudo_header.atm.aal = AAL_5;
rec->rec_header.packet_header.pseudo_header.atm.type = TRAF_UNKNOWN;
rec->rec_header.packet_header.pseudo_header.atm.subtype = TRAF_ST_UNKNOWN;
if (rec->rec_header.packet_header.pseudo_header.atm.vpi == 0) {
/*
* Traffic on some PVCs with a VPI of 0 and certain
* VCIs is of particular types.
*/
switch (rec->rec_header.packet_header.pseudo_header.atm.vci) {
case 5:
/*
* Signalling AAL.
*/
rec->rec_header.packet_header.pseudo_header.atm.aal = AAL_SIGNALLING;
return;
case 16:
/*
* ILMI.
*/
rec->rec_header.packet_header.pseudo_header.atm.type = TRAF_ILMI;
return;
}
}
/*
* OK, we can't tell what it is based on the VPI/VCI; try
* guessing based on the contents, if we have enough data
* to guess.
*/
if (rec->rec_header.packet_header.caplen >= 3) {
if (pd[0] == 0xaa && pd[1] == 0xaa && pd[2] == 0x03) {
/*
* Looks like a SNAP header; assume it's LLC
* multiplexed RFC 1483 traffic.
*/
rec->rec_header.packet_header.pseudo_header.atm.type = TRAF_LLCMX;
} else if ((rec->rec_header.packet_header.pseudo_header.atm.aal5t_len && rec->rec_header.packet_header.pseudo_header.atm.aal5t_len < 16) ||
rec->rec_header.packet_header.caplen < 16) {
/*
* As this cannot be a LANE Ethernet frame (less
* than 2 bytes of LANE header + 14 bytes of
* Ethernet header) we can try it as a SSCOP frame.
*/
rec->rec_header.packet_header.pseudo_header.atm.aal = AAL_SIGNALLING;
} else if (pd[0] == 0x83 || pd[0] == 0x81) {
/*
* MTP3b headers often encapsulate
* a SCCP or MTN in the 3G network.
* This should cause 0x83 or 0x81
* in the first byte.
*/
rec->rec_header.packet_header.pseudo_header.atm.aal = AAL_SIGNALLING;
} else {
/*
* Assume it's LANE.
*/
rec->rec_header.packet_header.pseudo_header.atm.type = TRAF_LANE;
atm_guess_lane_type(rec, pd);
}
} else {
/*
* Not only VCI 5 is used for signaling. It might be
* one of these VCIs.
*/
rec->rec_header.packet_header.pseudo_header.atm.aal = AAL_SIGNALLING;
}
}
void
atm_guess_lane_type(wtap_rec *rec, const guint8 *pd)
{
if (rec->rec_header.packet_header.caplen >= 2) {
if (pd[0] == 0xff && pd[1] == 0x00) {
/*
* Looks like LE Control traffic.
*/
rec->rec_header.packet_header.pseudo_header.atm.subtype = TRAF_ST_LANE_LE_CTRL;
} else {
/*
* XXX - Ethernet, or Token Ring?
* Assume Ethernet for now; if we see earlier
* LANE traffic, we may be able to figure out
* the traffic type from that, but there may
* still be situations where the user has to
* tell us.
*/
rec->rec_header.packet_header.pseudo_header.atm.subtype = TRAF_ST_LANE_802_3;
}
}
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/ |
C/C++ | wireshark/wiretap/atm.h | /** @file
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __ATM_H__
#define __ATM_H__
#include <glib.h>
#include "ws_symbol_export.h"
/*
* Routines to use with ATM capture file types that don't include information
* about the *type* of ATM traffic (or, at least, where we haven't found
* that information).
*/
extern void
atm_guess_traffic_type(wtap_rec *rec, const guint8 *pd);
extern void
atm_guess_lane_type(wtap_rec *rec, const guint8 *pd);
#endif /* __ATM_H__ */ |
C | wireshark/wiretap/autosar_dlt.c | /* autosar_dlt.c
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* Support for DLT file format as defined by AUTOSAR et. al.
* Copyright (c) 2022-2022 by Dr. Lars Voelker <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/*
* Sources for specification:
* https://www.autosar.org/fileadmin/user_upload/standards/classic/21-11/AUTOSAR_SWS_DiagnosticLogAndTrace.pdf
* https://www.autosar.org/fileadmin/user_upload/standards/foundation/21-11/AUTOSAR_PRS_LogAndTraceProtocol.pdf
* https://github.com/COVESA/dlt-viewer
*/
#include <config.h>
#include <errno.h>
#include "autosar_dlt.h"
#include "file_wrappers.h"
#include "wtap-int.h"
static const guint8 dlt_magic[] = { 'D', 'L', 'T', 0x01 };
static int autosar_dlt_file_type_subtype = -1;
void register_autosar_dlt(void);
static gboolean autosar_dlt_read(wtap *wth, wtap_rec *rec, Buffer *buf, int *err, gchar **err_info, gint64 *data_offset);
static gboolean autosar_dlt_seek_read(wtap *wth, gint64 seek_off, wtap_rec* rec, Buffer *buf, int *err, gchar **err_info);
static void autosar_dlt_close(wtap *wth);
typedef struct autosar_dlt_blockheader {
guint8 magic[4];
guint32 timestamp_s;
guint32 timestamp_us;
guint8 ecu_id[4];
} autosar_dlt_blockheader_t;
typedef struct autosar_dlt_itemheader {
guint8 header_type;
guint8 counter;
guint16 length;
} autosar_dlt_itemheader_t;
typedef struct autosar_dlt_data {
GHashTable *ecu_to_iface_ht;
guint32 next_interface_id;
} autosar_dlt_t;
typedef struct autosar_dlt_params {
wtap *wth;
wtap_rec *rec;
Buffer *buf;
FILE_T fh;
autosar_dlt_t *dlt_data;
} autosar_dlt_params_t;
static gint
autosar_dlt_calc_key(guint8 ecu[4]) {
return (gint)(ecu[0] << 24 | ecu[1] << 16 | ecu[2] << 8 | ecu[3]);
}
static guint32
autosar_dlt_add_interface(autosar_dlt_params_t *params, guint8 ecu[4]) {
wtap_block_t int_data = wtap_block_create(WTAP_BLOCK_IF_ID_AND_INFO);
wtapng_if_descr_mandatory_t *if_descr_mand = (wtapng_if_descr_mandatory_t*)wtap_block_get_mandatory_data(int_data);
if_descr_mand->wtap_encap = WTAP_ENCAP_AUTOSAR_DLT;
wtap_block_add_string_option(int_data, OPT_IDB_NAME, (gchar *)ecu, 4);
if_descr_mand->time_units_per_second = 1000 * 1000 * 1000;
if_descr_mand->tsprecision = WTAP_TSPREC_NSEC;
wtap_block_add_uint8_option(int_data, OPT_IDB_TSRESOL, 9);
if_descr_mand->snap_len = WTAP_MAX_PACKET_SIZE_STANDARD;
if_descr_mand->num_stat_entries = 0;
if_descr_mand->interface_statistics = NULL;
wtap_add_idb(params->wth, int_data);
if (params->wth->file_encap == WTAP_ENCAP_UNKNOWN) {
params->wth->file_encap = if_descr_mand->wtap_encap;
} else {
if (params->wth->file_encap != if_descr_mand->wtap_encap) {
params->wth->file_encap = WTAP_ENCAP_PER_PACKET;
}
}
gint32 key = autosar_dlt_calc_key(ecu);
guint32 iface_id = params->dlt_data->next_interface_id++;
g_hash_table_insert(params->dlt_data->ecu_to_iface_ht, GINT_TO_POINTER(key), GUINT_TO_POINTER(iface_id));
return iface_id;
}
static guint32
autosar_dlt_lookup_interface(autosar_dlt_params_t *params, guint8 ecu[4]) {
gint32 key = autosar_dlt_calc_key(ecu);
if (params->dlt_data->ecu_to_iface_ht == NULL) {
return 0;
}
gpointer iface = NULL;
gboolean found = g_hash_table_lookup_extended(params->dlt_data->ecu_to_iface_ht, GINT_TO_POINTER(key), NULL, &iface);
if (found) {
return GPOINTER_TO_UINT(iface);
} else {
return autosar_dlt_add_interface(params, ecu);
}
}
static void
fix_endianness_autosar_dlt_blockheader(autosar_dlt_blockheader_t *header) {
header->timestamp_s = GUINT32_FROM_LE(header->timestamp_s);
header->timestamp_us = GUINT32_FROM_LE(header->timestamp_us);
}
static void
fix_endianness_autosar_dlt_itemheader(autosar_dlt_itemheader_t *header) {
header->length = GUINT16_FROM_BE(header->length);
}
static gboolean
autosar_dlt_read_block(autosar_dlt_params_t *params, gint64 start_pos, int *err, gchar **err_info) {
autosar_dlt_blockheader_t header;
autosar_dlt_itemheader_t item_header;
while (1) {
params->buf->first_free = params->buf->start;
if (!wtap_read_bytes_or_eof(params->fh, &header, sizeof header, err, err_info)) {
if (*err == WTAP_ERR_SHORT_READ) {
*err = WTAP_ERR_BAD_FILE;
g_free(*err_info);
*err_info = ws_strdup_printf("AUTOSAR DLT: Capture file cut short! Cannot find storage header at pos 0x%" PRIx64 "!", start_pos);
}
return FALSE;
}
fix_endianness_autosar_dlt_blockheader(&header);
if (memcmp(header.magic, dlt_magic, sizeof(dlt_magic))) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("AUTOSAR DLT: Bad capture file! Object magic is not DLT\\x01 at pos 0x%" PRIx64 "!", start_pos);
return FALSE;
}
/* Set to the byte after the magic. */
guint64 current_start_of_item = file_tell(params->fh) - sizeof header + 4;
if (!wtap_read_bytes_or_eof(params->fh, &item_header, sizeof item_header, err, err_info)) {
*err = WTAP_ERR_BAD_FILE;
g_free(*err_info);
*err_info = ws_strdup_printf("AUTOSAR DLT: Capture file cut short! Not enough bytes for item header at pos 0x%" PRIx64 "!", start_pos);
return FALSE;
}
fix_endianness_autosar_dlt_itemheader(&item_header);
if (file_seek(params->fh, current_start_of_item, SEEK_SET, err) < 0) {
return FALSE;
}
ws_buffer_assure_space(params->buf, (gsize)(item_header.length + sizeof header));
/* Creating AUTOSAR DLT Encapsulation Header:
* guint32 time_s
* guint32 time_us
* guint8[4] ecuname
* guint8[1] 0x00 (termination)
* guint8[3] reserved
*/
void *tmpbuf = g_malloc0(sizeof header);
if (!wtap_read_bytes_or_eof(params->fh, tmpbuf, sizeof header - 4, err, err_info)) {
/* this would have been caught before ...*/
*err = WTAP_ERR_BAD_FILE;
g_free(*err_info);
*err_info = ws_strdup_printf("AUTOSAR DLT: Internal Error! Not enough bytes for storage header at pos 0x%" PRIx64 "!", start_pos);
return FALSE;
}
ws_buffer_append(params->buf, tmpbuf, (gsize)(sizeof header));
g_free(tmpbuf);
tmpbuf = g_try_malloc0(item_header.length);
if (tmpbuf == NULL) {
*err = ENOMEM; /* we assume we're out of memory */
return FALSE;
}
if (!wtap_read_bytes_or_eof(params->fh, tmpbuf, item_header.length, err, err_info)) {
*err = WTAP_ERR_BAD_FILE;
g_free(*err_info);
*err_info = ws_strdup_printf("AUTOSAR DLT: Capture file cut short! Not enough bytes for item at pos 0x%" PRIx64 "!", start_pos);
return FALSE;
}
ws_buffer_append(params->buf, tmpbuf, (gsize)(item_header.length));
g_free(tmpbuf);
params->rec->rec_type = REC_TYPE_PACKET;
params->rec->block = wtap_block_create(WTAP_BLOCK_PACKET);
params->rec->presence_flags = WTAP_HAS_TS | WTAP_HAS_CAP_LEN | WTAP_HAS_INTERFACE_ID;
params->rec->tsprec = WTAP_TSPREC_USEC;
params->rec->ts.secs = header.timestamp_s;
params->rec->ts.nsecs = header.timestamp_us * 1000;
params->rec->rec_header.packet_header.caplen = (guint32)(item_header.length + sizeof header);
params->rec->rec_header.packet_header.len = (guint32)(item_header.length + sizeof header);
params->rec->rec_header.packet_header.pkt_encap = WTAP_ENCAP_AUTOSAR_DLT;
params->rec->rec_header.packet_header.interface_id = autosar_dlt_lookup_interface(params, header.ecu_id);
return TRUE;
}
return FALSE;
}
static gboolean autosar_dlt_read(wtap *wth, wtap_rec *rec, Buffer *buf, int *err, gchar **err_info, gint64 *data_offset) {
autosar_dlt_params_t dlt_tmp;
dlt_tmp.wth = wth;
dlt_tmp.fh = wth->fh;
dlt_tmp.rec = rec;
dlt_tmp.buf = buf;
dlt_tmp.dlt_data = (autosar_dlt_t *)wth->priv;
*data_offset = file_tell(wth->fh);
if (!autosar_dlt_read_block(&dlt_tmp, *data_offset, err, err_info)) {
ws_debug("couldn't read packet block (data_offset is %" PRId64 ")", *data_offset);
return FALSE;
}
return TRUE;
}
static gboolean autosar_dlt_seek_read(wtap *wth, gint64 seek_off, wtap_rec *rec, Buffer *buf, int *err, gchar **err_info) {
autosar_dlt_params_t dlt_tmp;
dlt_tmp.wth = wth;
dlt_tmp.fh = wth->random_fh;
dlt_tmp.rec = rec;
dlt_tmp.buf = buf;
dlt_tmp.dlt_data = (autosar_dlt_t *)wth->priv;
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
return FALSE;
if (!autosar_dlt_read_block(&dlt_tmp, seek_off, err, err_info)) {
ws_debug("couldn't read packet block (seek_off: %" PRId64 ") (err=%d).", seek_off, *err);
return FALSE;
}
return TRUE;
}
static void autosar_dlt_close(wtap *wth) {
autosar_dlt_t *dlt = (autosar_dlt_t *)wth->priv;
if (dlt != NULL && dlt->ecu_to_iface_ht != NULL) {
g_hash_table_destroy(dlt->ecu_to_iface_ht);
dlt->ecu_to_iface_ht = NULL;
}
g_free(dlt);
wth->priv = NULL;
return;
}
wtap_open_return_val
autosar_dlt_open(wtap *wth, int *err, gchar **err_info) {
guint8 magic[4];
autosar_dlt_t *dlt;
ws_debug("opening file");
if (!wtap_read_bytes_or_eof(wth->fh, &magic, sizeof magic, err, err_info)) {
ws_debug("wtap_read_bytes_or_eof() failed, err = %d.", *err);
if (*err == 0 || *err == WTAP_ERR_SHORT_READ) {
*err = 0;
g_free(*err_info);
*err_info = NULL;
return WTAP_OPEN_NOT_MINE;
}
return WTAP_OPEN_ERROR;
}
if (memcmp(magic, dlt_magic, sizeof(dlt_magic))) {
return WTAP_OPEN_NOT_MINE;
}
file_seek(wth->fh, 0, SEEK_SET, err);
dlt = g_new(autosar_dlt_t, 1);
dlt->ecu_to_iface_ht = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
dlt->next_interface_id = 0;
wth->priv = (void *)dlt;
wth->file_encap = WTAP_ENCAP_UNKNOWN;
wth->snapshot_length = 0;
wth->file_tsprec = WTAP_TSPREC_UNKNOWN;
wth->subtype_read = autosar_dlt_read;
wth->subtype_seek_read = autosar_dlt_seek_read;
wth->subtype_close = autosar_dlt_close;
wth->file_type_subtype = autosar_dlt_file_type_subtype;
return WTAP_OPEN_MINE;
}
/* Options for interface blocks. */
static const struct supported_option_type interface_block_options_supported[] = {
/* No comments, just an interface name. */
{ OPT_IDB_NAME, ONE_OPTION_SUPPORTED }
};
static const struct supported_block_type dlt_blocks_supported[] = {
{ WTAP_BLOCK_PACKET, MULTIPLE_BLOCKS_SUPPORTED, NO_OPTIONS_SUPPORTED },
{ WTAP_BLOCK_IF_ID_AND_INFO, MULTIPLE_BLOCKS_SUPPORTED, OPTION_TYPES_SUPPORTED(interface_block_options_supported) },
};
static const struct file_type_subtype_info dlt_info = {
"AUTOSAR DLT Logfile", "dlt", "dlt", NULL,
FALSE, BLOCKS_SUPPORTED(dlt_blocks_supported),
NULL, NULL, NULL
};
void register_autosar_dlt(void)
{
autosar_dlt_file_type_subtype = wtap_register_file_type_subtype(&dlt_info);
/*
* Register name for backwards compatibility with the
* wtap_filetypes table in Lua.
*/
wtap_register_backwards_compatibility_lua_name("DLT", autosar_dlt_file_type_subtype);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/ |
C/C++ | wireshark/wiretap/autosar_dlt.h | /* autosar_dlt.h
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* Support for DLT file format as defined by AUTOSAR et. al.
* Copyright (c) 2022-2022 by Dr. Lars Voelker <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/*
* Sources for specification:
* https://www.autosar.org/fileadmin/user_upload/standards/classic/21-11/AUTOSAR_SWS_DiagnosticLogAndTrace.pdf
* https://www.autosar.org/fileadmin/user_upload/standards/foundation/21-11/AUTOSAR_PRS_LogAndTraceProtocol.pdf
* https://github.com/COVESA/dlt-viewer
*/
#ifndef __W_AUTOSAR_DLT_H__
#define __W_AUTOSAR_DLT_H__
#include "wtap.h"
wtap_open_return_val autosar_dlt_open(wtap *wth, int *err, gchar **err_info);
#endif
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/ |
C | wireshark/wiretap/ber.c | /* ber.c
*
* Basic Encoding Rules (BER) file reading
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include "wtap-int.h"
#include "file_wrappers.h"
#include <wsutil/buffer.h>
#include "ber.h"
#define BER_CLASS_UNI 0
#define BER_CLASS_APP 1
#define BER_CLASS_CON 2
#define BER_UNI_TAG_SEQ 16 /* SEQUENCE, SEQUENCE OF */
#define BER_UNI_TAG_SET 17 /* SET, SET OF */
static int ber_file_type_subtype = -1;
void register_ber(void);
static gboolean ber_full_file_read(wtap *wth, wtap_rec *rec, Buffer *buf,
int *err, gchar **err_info,
gint64 *data_offset)
{
if (!wtap_full_file_read(wth, rec, buf, err, err_info, data_offset))
return FALSE;
/* Pass the file name. */
rec->rec_header.packet_header.pseudo_header.ber.pathname = wth->pathname;
return TRUE;
}
static gboolean ber_full_file_seek_read(wtap *wth, gint64 seek_off,
wtap_rec *rec, Buffer *buf,
int *err, gchar **err_info)
{
if (!wtap_full_file_seek_read(wth, seek_off, rec, buf, err, err_info))
return FALSE;
/* Pass the file name. */
rec->rec_header.packet_header.pseudo_header.ber.pathname = wth->pathname;
return TRUE;
}
wtap_open_return_val ber_open(wtap *wth, int *err, gchar **err_info)
{
#define BER_BYTES_TO_CHECK 8
guint8 bytes[BER_BYTES_TO_CHECK];
guint8 ber_id;
gint8 ber_class;
gint8 ber_tag;
gboolean ber_pc;
guint8 oct, nlb = 0;
int len = 0;
gint64 file_size;
int offset = 0, i;
if (!wtap_read_bytes(wth->fh, &bytes, BER_BYTES_TO_CHECK, err, err_info)) {
if (*err != WTAP_ERR_SHORT_READ)
return WTAP_OPEN_ERROR;
return WTAP_OPEN_NOT_MINE;
}
ber_id = bytes[offset++];
ber_class = (ber_id>>6) & 0x03;
ber_pc = (ber_id>>5) & 0x01;
ber_tag = ber_id & 0x1F;
/* it must be constructed and either a SET or a SEQUENCE */
/* or a CONTEXT/APPLICATION less than 32 (arbitrary) */
if(!(ber_pc &&
(((ber_class == BER_CLASS_UNI) && ((ber_tag == BER_UNI_TAG_SET) || (ber_tag == BER_UNI_TAG_SEQ))) ||
(((ber_class == BER_CLASS_CON) || (ber_class == BER_CLASS_APP)) && (ber_tag < 32)))))
return WTAP_OPEN_NOT_MINE;
/* now check the length */
oct = bytes[offset++];
if(oct != 0x80) {
/* not indefinite length encoded */
if(!(oct & 0x80))
/* length fits into a single byte */
len = oct;
else {
nlb = oct & 0x7F; /* number of length bytes */
if((nlb > 0) && (nlb <= (BER_BYTES_TO_CHECK - 2))) {
/* not indefinite length and we have read enough bytes to compute the length */
i = nlb;
while(i--) {
oct = bytes[offset++];
len = (len<<8) + oct;
}
}
}
len += (2 + nlb); /* add back Tag and Length bytes */
file_size = wtap_file_size(wth, err);
if(len != file_size) {
return WTAP_OPEN_NOT_MINE; /* not ASN.1 */
}
} else {
/* Indefinite length encoded - assume it is BER */
}
/* seek back to the start of the file */
if (file_seek(wth->fh, 0, SEEK_SET, err) == -1)
return WTAP_OPEN_ERROR;
wth->file_type_subtype = ber_file_type_subtype;
wth->file_encap = WTAP_ENCAP_BER;
wth->snapshot_length = 0;
wth->subtype_read = ber_full_file_read;
wth->subtype_seek_read = ber_full_file_seek_read;
wth->file_tsprec = WTAP_TSPREC_SEC;
return WTAP_OPEN_MINE;
}
static const struct supported_block_type ber_blocks_supported[] = {
/*
* These are file formats that we dissect, so we provide only one
* "packet" with the file's contents, and don't support any
* options.
*/
{ WTAP_BLOCK_PACKET, ONE_BLOCK_SUPPORTED, NO_OPTIONS_SUPPORTED }
};
static const struct file_type_subtype_info ber_info = {
"ASN.1 Basic Encoding Rules", "ber", NULL, NULL,
FALSE, BLOCKS_SUPPORTED(ber_blocks_supported),
NULL, NULL, NULL
};
void register_ber(void)
{
ber_file_type_subtype = wtap_register_file_type_subtype(&ber_info);
/*
* Register name for backwards compatibility with the
* wtap_filetypes table in Lua.
*/
wtap_register_backwards_compatibility_lua_name("BER", ber_file_type_subtype);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local Variables:
* c-basic-offset: 2
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=2 tabstop=8 expandtab:
* :indentSize=2:tabSize=8:noTabs=true:
*/ |
C/C++ | wireshark/wiretap/ber.h | /** @file
*
* Basic Encoding Rules (BER) file reading
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
*/
#ifndef __BER_H__
#define __BER_H__
#include <glib.h>
#include "ws_symbol_export.h"
wtap_open_return_val ber_open(wtap *wth, int *err, gchar **err_info);
#endif |
C | wireshark/wiretap/blf.c | /* blf.c
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* File format support for the Binary Log File (BLF) file format from
* Vector Informatik decoder
* Copyright (c) 2021-2022 by Dr. Lars Voelker <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/*
* The following was used as a reference for the file format:
* https://bitbucket.org/tobylorenz/vector_blf
* The repo above includes multiple examples files as well.
*/
#include <config.h>
#include "blf.h"
#include <epan/dissectors/packet-socketcan.h>
#include <string.h>
#include <errno.h>
#include <epan/value_string.h>
#include <wsutil/wslog.h>
#include <wsutil/exported_pdu_tlvs.h>
#include "file_wrappers.h"
#include "wtap-int.h"
#ifdef HAVE_ZLIB
#define ZLIB_CONST
#include <zlib.h>
#endif /* HAVE_ZLIB */
static const guint8 blf_magic[] = { 'L', 'O', 'G', 'G' };
static const guint8 blf_obj_magic[] = { 'L', 'O', 'B', 'J' };
static int blf_file_type_subtype = -1;
void register_blf(void);
static gboolean blf_read(wtap *wth, wtap_rec *rec, Buffer *buf, int *err, gchar **err_info, gint64 *data_offset);
static gboolean blf_seek_read(wtap *wth, gint64 seek_off, wtap_rec* rec, Buffer *buf, int *err, gchar **err_info);
static void blf_close(wtap *wth);
/*
* The virtual buffer looks like this (skips all headers):
* uncompressed log container data
* uncompressed log container data
* ...
*
* The "real" positions, length, etc. reference this layout and not the file.
* When no compression is used the file is accessed directly.
*/
typedef struct blf_log_container {
gint64 infile_start_pos; /* start position of log container in file */
guint64 infile_length; /* length of log container in file */
guint64 infile_data_start; /* start position of data in log container in file */
gint64 real_start_pos; /* decompressed (virtual) start position including header */
guint64 real_length; /* decompressed length */
gint64 real_first_object_pos; /* where does the first obj start? */
guint64 real_leftover_bytes; /* how many bytes are left over for the next container? */
guint16 compression_method; /* 0: uncompressed, 2: zlib */
unsigned char *real_data; /* cache for decompressed data */
} blf_log_container_t;
typedef struct blf_data {
gint64 start_of_last_obj;
gint64 current_real_seek_pos;
guint64 start_offset_ns;
guint current_log_container;
GArray *log_containers;
GHashTable *channel_to_iface_ht;
guint32 next_interface_id;
} blf_t;
typedef struct blf_params {
wtap *wth;
wtap_rec *rec;
Buffer *buf;
FILE_T fh;
blf_t *blf_data;
} blf_params_t;
typedef struct blf_channel_to_iface_entry {
int pkt_encap;
guint32 channel;
guint32 interface_id;
} blf_channel_to_iface_entry_t;
static void
blf_free_key(gpointer key) {
g_free(key);
}
static void
blf_free_channel_to_iface_entry(gpointer data) {
g_free(data);
}
static gint64
blf_calc_key_value(int pkt_encap, guint32 channel) {
return ((gint64)pkt_encap << 32) | channel;
}
static void add_interface_name(wtap_block_t *int_data, int pkt_encap, guint32 channel, gchar *name) {
if (name != NULL) {
wtap_block_add_string_option_format(*int_data, OPT_IDB_NAME, name, channel);
} else {
switch (pkt_encap) {
case WTAP_ENCAP_ETHERNET:
wtap_block_add_string_option_format(*int_data, OPT_IDB_NAME, "ETH-%u", channel);
break;
case WTAP_ENCAP_IEEE_802_11:
wtap_block_add_string_option_format(*int_data, OPT_IDB_NAME, "WLAN-%u", channel);
break;
case WTAP_ENCAP_FLEXRAY:
wtap_block_add_string_option_format(*int_data, OPT_IDB_NAME, "FR-%u", channel);
break;
case WTAP_ENCAP_LIN:
wtap_block_add_string_option_format(*int_data, OPT_IDB_NAME, "LIN-%u", channel);
break;
case WTAP_ENCAP_SOCKETCAN:
wtap_block_add_string_option_format(*int_data, OPT_IDB_NAME, "CAN-%u", channel);
break;
default:
wtap_block_add_string_option_format(*int_data, OPT_IDB_NAME, "ENCAP_%d-%u", pkt_encap, channel);
}
}
}
static guint32
blf_add_interface(blf_params_t *params, int pkt_encap, guint32 channel, gchar *name) {
wtap_block_t int_data = wtap_block_create(WTAP_BLOCK_IF_ID_AND_INFO);
wtapng_if_descr_mandatory_t *if_descr_mand = (wtapng_if_descr_mandatory_t*)wtap_block_get_mandatory_data(int_data);
blf_channel_to_iface_entry_t *item = NULL;
if_descr_mand->wtap_encap = pkt_encap;
add_interface_name(&int_data, pkt_encap, channel, name);
if_descr_mand->time_units_per_second = 1000 * 1000 * 1000;
if_descr_mand->tsprecision = WTAP_TSPREC_NSEC;
wtap_block_add_uint8_option(int_data, OPT_IDB_TSRESOL, 9);
if_descr_mand->snap_len = WTAP_MAX_PACKET_SIZE_STANDARD;
if_descr_mand->num_stat_entries = 0;
if_descr_mand->interface_statistics = NULL;
wtap_add_idb(params->wth, int_data);
if (params->wth->file_encap == WTAP_ENCAP_UNKNOWN) {
params->wth->file_encap = if_descr_mand->wtap_encap;
} else {
if (params->wth->file_encap != if_descr_mand->wtap_encap) {
params->wth->file_encap = WTAP_ENCAP_PER_PACKET;
}
}
gint64 *key = NULL;
key = g_new(gint64, 1);
*key = blf_calc_key_value(pkt_encap, channel);
item = g_new(blf_channel_to_iface_entry_t, 1);
item->channel = channel;
item->pkt_encap = pkt_encap;
item->interface_id = params->blf_data->next_interface_id++;
g_hash_table_insert(params->blf_data->channel_to_iface_ht, key, item);
return item->interface_id;
}
static guint32
blf_lookup_interface(blf_params_t *params, int pkt_encap, guint32 channel, gchar *name) {
gint64 key = blf_calc_key_value(pkt_encap, channel);
blf_channel_to_iface_entry_t *item = NULL;
if (params->blf_data->channel_to_iface_ht == NULL) {
return 0;
}
item = (blf_channel_to_iface_entry_t *)g_hash_table_lookup(params->blf_data->channel_to_iface_ht, &key);
if (item != NULL) {
return item->interface_id;
} else {
return blf_add_interface(params, pkt_encap, channel, name);
}
}
static void
fix_endianness_blf_date(blf_date_t *date) {
date->year = GUINT16_FROM_LE(date->year);
date->month = GUINT16_FROM_LE(date->month);
date->dayofweek = GUINT16_FROM_LE(date->dayofweek);
date->day = GUINT16_FROM_LE(date->day);
date->hour = GUINT16_FROM_LE(date->hour);
date->mins = GUINT16_FROM_LE(date->mins);
date->sec = GUINT16_FROM_LE(date->sec);
date->ms = GUINT16_FROM_LE(date->ms);
}
static void
fix_endianness_blf_fileheader(blf_fileheader_t *header) {
header->header_length = GUINT32_FROM_LE(header->header_length);
header->len_compressed = GUINT64_FROM_LE(header->len_compressed);
header->len_uncompressed = GUINT64_FROM_LE(header->len_uncompressed);
header->obj_count = GUINT32_FROM_LE(header->obj_count);
header->obj_read = GUINT32_FROM_LE(header->obj_read);
fix_endianness_blf_date(&(header->start_date));
fix_endianness_blf_date(&(header->end_date));
header->length3 = GUINT32_FROM_LE(header->length3);
}
static void
fix_endianness_blf_blockheader(blf_blockheader_t *header) {
header->header_length = GUINT16_FROM_LE(header->header_length);
header->header_type = GUINT16_FROM_LE(header->header_type);
header->object_length = GUINT32_FROM_LE(header->object_length);
header->object_type = GUINT32_FROM_LE(header->object_type);
}
static void
fix_endianness_blf_logcontainerheader(blf_logcontainerheader_t *header) {
header->compression_method = GUINT16_FROM_LE(header->compression_method);
header->res1 = GUINT16_FROM_LE(header->res1);
header->res2 = GUINT32_FROM_LE(header->res2);
header->uncompressed_size = GUINT32_FROM_LE(header->uncompressed_size);
header->res4 = GUINT32_FROM_LE(header->res4);
}
static void
fix_endianness_blf_logobjectheader(blf_logobjectheader_t *header) {
header->flags = GUINT32_FROM_LE(header->flags);
header->client_index = GUINT16_FROM_LE(header->client_index);
header->object_version = GUINT16_FROM_LE(header->object_version);
header->object_timestamp = GUINT64_FROM_LE(header->object_timestamp);
}
static void
fix_endianness_blf_logobjectheader2(blf_logobjectheader2_t *header) {
header->flags = GUINT32_FROM_LE(header->flags);
header->object_version = GUINT16_FROM_LE(header->object_version);
header->object_timestamp = GUINT64_FROM_LE(header->object_timestamp);
header->original_timestamp = GUINT64_FROM_LE(header->object_timestamp);
}
static void
fix_endianness_blf_logobjectheader3(blf_logobjectheader3_t *header) {
header->flags = GUINT32_FROM_LE(header->flags);
header->static_size = GUINT16_FROM_LE(header->static_size);
header->object_version = GUINT16_FROM_LE(header->object_version);
header->object_timestamp = GUINT64_FROM_LE(header->object_timestamp);
}
static void
fix_endianness_blf_ethernetframeheader(blf_ethernetframeheader_t *header) {
header->channel = GUINT16_FROM_LE(header->channel);
header->direction = GUINT16_FROM_LE(header->direction);
header->ethtype = GUINT16_FROM_LE(header->ethtype);
header->tpid = GUINT16_FROM_LE(header->tpid);
header->tci = GUINT16_FROM_LE(header->tci);
header->payloadlength = GUINT16_FROM_LE(header->payloadlength);
}
static void
fix_endianness_blf_ethernetframeheader_ex(blf_ethernetframeheader_ex_t *header) {
header->struct_length = GUINT16_FROM_LE(header->struct_length);
header->flags = GUINT16_FROM_LE(header->flags);
header->channel = GUINT16_FROM_LE(header->channel);
header->hw_channel = GUINT16_FROM_LE(header->hw_channel);
header->frame_duration = GUINT64_FROM_LE(header->frame_duration);
header->frame_checksum = GUINT32_FROM_LE(header->frame_checksum);
header->direction = GUINT16_FROM_LE(header->direction);
header->frame_length = GUINT16_FROM_LE(header->frame_length);
header->frame_handle = GUINT32_FROM_LE(header->frame_handle);
header->error = GUINT32_FROM_LE(header->error);
}
static void
fix_endianness_blf_wlanframeheader(blf_wlanframeheader_t* header) {
header->channel = GUINT16_FROM_LE(header->channel);
header->flags = GUINT16_FROM_LE(header->flags);
header->signal_strength = GUINT16_FROM_LE(header->signal_strength);
header->signal_quality = GUINT16_FROM_LE(header->signal_quality);
header->frame_length = GUINT16_FROM_LE(header->frame_length);
}
static void
fix_endianness_blf_canmessage(blf_canmessage_t *header) {
header->channel = GUINT16_FROM_LE(header->channel);
header->id = GUINT32_FROM_LE(header->id);
}
static void
fix_endianness_blf_canmessage2_trailer(blf_canmessage2_trailer_t *header) {
header->frameLength_in_ns = GUINT32_FROM_LE(header->frameLength_in_ns);
header->reserved2 = GUINT16_FROM_LE(header->reserved1);
}
static void
fix_endianness_blf_canfdmessage(blf_canfdmessage_t *header) {
header->channel = GUINT16_FROM_LE(header->channel);
header->id = GUINT32_FROM_LE(header->id);
header->frameLength_in_ns = GUINT32_FROM_LE(header->frameLength_in_ns);
header->reservedCanFdMessage2 = GUINT32_FROM_LE(header->reservedCanFdMessage2);
}
static void
fix_endianness_blf_canfdmessage64(blf_canfdmessage64_t *header) {
header->id = GUINT32_FROM_LE(header->id);
header->frameLength_in_ns = GUINT32_FROM_LE(header->frameLength_in_ns);
header->flags = GUINT32_FROM_LE(header->flags);
header->btrCfgArb = GUINT32_FROM_LE(header->btrCfgArb);
header->btrCfgData = GUINT32_FROM_LE(header->btrCfgData);
header->timeOffsetBrsNs = GUINT32_FROM_LE(header->timeOffsetBrsNs);
header->timeOffsetCrcDelNs = GUINT32_FROM_LE(header->timeOffsetCrcDelNs);
header->bitCount = GUINT16_FROM_LE(header->bitCount);
header->crc = GUINT32_FROM_LE(header->crc);
}
static void
fix_endianness_blf_canerror(blf_canerror_t *header) {
header->channel = GUINT16_FROM_LE(header->channel);
header->length = GUINT16_FROM_LE(header->length);
}
static void
fix_endianness_blf_canerrorext(blf_canerrorext_t *header) {
header->channel = GUINT16_FROM_LE(header->channel);
header->length = GUINT16_FROM_LE(header->length);
header->flags = GUINT32_FROM_LE(header->flags);
header->frameLength_in_ns = GUINT32_FROM_LE(header->frameLength_in_ns);
header->id = GUINT32_FROM_LE(header->id);
header->errorCodeExt = GUINT16_FROM_LE(header->errorCodeExt);
}
static void
fix_endianness_blf_canfderror64(blf_canfderror64_t *header) {
header->flags = GUINT16_FROM_LE(header->flags);
header->errorCodeExt = GUINT16_FROM_LE(header->errorCodeExt);
header->extFlags = GUINT16_FROM_LE(header->extFlags);
header->id = GUINT32_FROM_LE(header->id);
header->frameLength_in_ns = GUINT32_FROM_LE(header->frameLength_in_ns);
header->btrCfgArb = GUINT32_FROM_LE(header->btrCfgArb);
header->btrCfgData = GUINT32_FROM_LE(header->btrCfgData);
header->timeOffsetBrsNs = GUINT32_FROM_LE(header->timeOffsetBrsNs);
header->timeOffsetCrcDelNs = GUINT32_FROM_LE(header->timeOffsetCrcDelNs);
header->crc = GUINT32_FROM_LE(header->crc);
header->errorPosition = GUINT16_FROM_LE(header->errorPosition);
}
static void
fix_endianness_blf_flexraydata(blf_flexraydata_t *header) {
header->channel = GUINT16_FROM_LE(header->channel);
header->messageId = GUINT16_FROM_LE(header->messageId);
header->crc = GUINT16_FROM_LE(header->crc);
header->reservedFlexRayData2 = GUINT16_FROM_LE(header->reservedFlexRayData2);
}
static void
fix_endianness_blf_flexraymessage(blf_flexraymessage_t *header) {
header->channel = GUINT16_FROM_LE(header->channel);
header->fpgaTick = GUINT32_FROM_LE(header->fpgaTick);
header->fpgaTickOverflow = GUINT32_FROM_LE(header->fpgaTickOverflow);
header->clientIndexFlexRayV6Message = GUINT32_FROM_LE(header->clientIndexFlexRayV6Message);
header->clusterTime = GUINT32_FROM_LE(header->clusterTime);
header->frameId = GUINT16_FROM_LE(header->frameId);
header->headerCrc = GUINT16_FROM_LE(header->headerCrc);
header->frameState = GUINT16_FROM_LE(header->frameState);
header->reservedFlexRayV6Message2 = GUINT16_FROM_LE(header->reservedFlexRayV6Message2);
}
static void
fix_endianness_blf_flexrayrcvmessage(blf_flexrayrcvmessage_t *header) {
header->channel = GUINT16_FROM_LE(header->channel);
header->version = GUINT16_FROM_LE(header->version);
header->channelMask = GUINT16_FROM_LE(header->channelMask);
header->dir = GUINT16_FROM_LE(header->dir);
header->clientIndex = GUINT32_FROM_LE(header->clientIndex);
header->clusterNo = GUINT32_FROM_LE(header->clusterNo);
header->frameId = GUINT16_FROM_LE(header->frameId);
header->headerCrc1 = GUINT16_FROM_LE(header->headerCrc1);
header->headerCrc2 = GUINT16_FROM_LE(header->headerCrc2);
header->payloadLength = GUINT16_FROM_LE(header->payloadLength);
header->payloadLengthValid = GUINT16_FROM_LE(header->payloadLengthValid);
header->cycle = GUINT16_FROM_LE(header->cycle);
header->tag = GUINT32_FROM_LE(header->tag);
header->data = GUINT32_FROM_LE(header->data);
header->frameFlags = GUINT32_FROM_LE(header->frameFlags);
header->appParameter = GUINT32_FROM_LE(header->appParameter);
/* this would be extra for ext format:
header->frameCRC = GUINT32_FROM_LE(header->frameCRC);
header->frameLengthInNs = GUINT32_FROM_LE(header->frameLengthInNs);
header->frameId1 = GUINT16_FROM_LE(header->frameId1);
header->pduOffset = GUINT16_FROM_LE(header->pduOffset);
header->blfLogMask = GUINT16_FROM_LE(header->blfLogMask);
*/
}
static void
fix_endianness_blf_linmessage(blf_linmessage_t *header) {
header->channel = GUINT16_FROM_LE(header->channel);
}
static void
fix_endianness_blf_linmessage_trailer(blf_linmessage_trailer_t *header) {
header->crc = GUINT16_FROM_LE(header->crc);
/* skip the optional part
header->res2 = GUINT32_FROM_LE(header->res2);
*/
}
static void
fix_endianness_blf_apptext_header(blf_apptext_t *header) {
header->source = GUINT32_FROM_LE(header->source);
header->reservedAppText1 = GUINT32_FROM_LE(header->reservedAppText1);
header->textLength = GUINT32_FROM_LE(header->textLength);
header->reservedAppText2 = GUINT32_FROM_LE(header->reservedAppText2);
}
static void
fix_endianness_blf_ethernet_status_header(blf_ethernet_status_t* header) {
header->channel = GUINT16_FROM_LE(header->channel);
header->flags = GUINT16_FROM_LE(header->flags);
/*uint8_t linkStatus;*/
/*uint8_t ethernetPhy;*/
/*uint8_t duplex;*/
/*uint8_t mdi;*/
/*uint8_t connector;*/
/*uint8_t clockMode;*/
/*uint8_t pairs;*/
/*uint8_t hardwareChannel;*/
header->bitrate = GUINT32_FROM_LE(header->bitrate);
}
static guint64
blf_timestamp_to_ns(guint32 flags, guint64 timestamp) {
switch (flags) {
case BLF_TIMESTAMP_RESOLUTION_10US:
return 10000 * timestamp;
break;
case BLF_TIMESTAMP_RESOLUTION_1NS:
return timestamp;
break;
default:
/*
* XXX - report this as an error?
*
* Or provide a mechanism to allow file readers to report
* a warning (an error that the the reader tries to work
* around and that the caller should report)?
*/
ws_debug("I don't understand the flags 0x%x", flags);
return 0;
break;
}
}
static void
blf_init_logcontainer(blf_log_container_t *tmp) {
tmp->infile_start_pos = 0;
tmp->infile_length = 0;
tmp->infile_data_start = 0;
tmp->real_start_pos = 0;
tmp->real_length = 0;
tmp->real_first_object_pos = -1;
tmp->real_leftover_bytes = G_MAXUINT64;
tmp->real_data = NULL;
tmp->compression_method = 0;
}
static void
blf_add_logcontainer(blf_t *blf_data, blf_log_container_t log_container) {
if (blf_data->log_containers == NULL) {
blf_data->log_containers = g_array_sized_new(FALSE, FALSE, sizeof(blf_log_container_t), 1);
blf_data->current_log_container = 0;
} else {
blf_data->current_log_container++;
}
g_array_append_val(blf_data->log_containers, log_container);
}
static gboolean
blf_get_logcontainer_by_index(blf_t *blf_data, guint container_index, blf_log_container_t **ret) {
if (blf_data == NULL || blf_data->log_containers == NULL || container_index >= blf_data->log_containers->len) {
return FALSE;
}
*ret = &g_array_index(blf_data->log_containers, blf_log_container_t, container_index);
return TRUE;
}
static gboolean
blf_find_logcontainer_for_address(blf_t *blf_data, gint64 pos, blf_log_container_t **container, gint *container_index) {
blf_log_container_t *tmp;
if (blf_data == NULL || blf_data->log_containers == NULL) {
return FALSE;
}
for (guint i = 0; i < blf_data->log_containers->len; i++) {
tmp = &g_array_index(blf_data->log_containers, blf_log_container_t, i);
if (tmp->real_start_pos <= pos && pos < tmp->real_start_pos + (gint64)tmp->real_length) {
*container = tmp;
*container_index = i;
return TRUE;
}
}
return FALSE;
}
static gboolean
blf_pull_logcontainer_into_memory(blf_params_t *params, guint index_log_container, int *err, gchar **err_info) {
blf_t *blf_data = params->blf_data;
blf_log_container_t tmp;
if (index_log_container >= blf_data->log_containers->len) {
/*
* XXX - does this represent a bug (WTAP_ERR_INTERNAL) or a
* malformed file (WTAP_ERR_BAD_FILE)?
*/
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: index_log_container (%u) >= blf_data->log_containers->len (%u)",
index_log_container, blf_data->log_containers->len);
return FALSE;
}
tmp = g_array_index(blf_data->log_containers, blf_log_container_t, index_log_container);
if (tmp.real_data != NULL) {
return TRUE;
}
if (tmp.compression_method == BLF_COMPRESSION_ZLIB) {
#ifdef HAVE_ZLIB
if (file_seek(params->fh, tmp.infile_data_start, SEEK_SET, err) == -1) {
return FALSE;
}
/* pull compressed data into buffer */
if (tmp.infile_start_pos < 0) {
/*
* XXX - does this represent a bug (WTAP_ERR_INTERNAL) or a
* malformed file (WTAP_ERR_BAD_FILE)?
*/
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: tmp.infile_start_pos (%" G_GINT64_FORMAT ") < 0",
tmp.infile_start_pos);
return FALSE;
}
if (tmp.infile_data_start < (guint64)tmp.infile_start_pos) {
/*
* XXX - does this represent a bug (WTAP_ERR_INTERNAL) or a
* malformed file (WTAP_ERR_BAD_FILE)?
*/
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: tmp.infile_data_start (%" G_GUINT64_FORMAT ") < tmp.infile_start_pos (%" G_GINT64_FORMAT ")",
tmp.infile_data_start, tmp.infile_start_pos);
return FALSE;
}
if (tmp.infile_length < tmp.infile_data_start - (guint64)tmp.infile_start_pos) {
/*
* XXX - does this represent a bug (WTAP_ERR_INTERNAL) or a
* malformed file (WTAP_ERR_BAD_FILE)?
*/
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: tmp.infile_length (%" G_GUINT64_FORMAT ") < (tmp.infile_data_start (%" G_GUINT64_FORMAT ") - tmp.infile_start_pos (%" G_GINT64_FORMAT ")) = %" G_GUINT64_FORMAT,
tmp.infile_length,
tmp.infile_data_start, tmp.infile_start_pos,
tmp.infile_data_start - (guint64)tmp.infile_start_pos);
return FALSE;
}
guint64 data_length = tmp.infile_length - (tmp.infile_data_start - (guint64)tmp.infile_start_pos);
if (data_length > UINT_MAX) {
/*
* XXX - does this represent a bug (WTAP_ERR_INTERNAL) or a
* malformed file (WTAP_ERR_BAD_FILE)?
*/
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: data_length (%" G_GUINT64_FORMAT ") > UINT_MAX",
data_length);
return FALSE;
}
unsigned char *compressed_data = g_try_malloc0((gsize)tmp.infile_length);
if (!wtap_read_bytes_or_eof(params->fh, compressed_data, (unsigned int)data_length, err, err_info)) {
g_free(compressed_data);
if (*err == WTAP_ERR_SHORT_READ) {
/*
* XXX - our caller will turn this into an EOF.
* How *should* it be treated?
* For now, we turn it into Yet Another Internal Error,
* pending having better documentation of the file
* format.
*/
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup("blf_pull_logcontainer_into_memory: short read on compressed data");
}
return FALSE;
}
unsigned char *buf = g_try_malloc0((gsize)tmp.real_length);
z_stream infstream = {0};
infstream.avail_in = (unsigned int)data_length;
infstream.next_in = compressed_data;
infstream.avail_out = (unsigned int)tmp.real_length;
infstream.next_out = buf;
/* the actual DE-compression work. */
if (Z_OK != inflateInit(&infstream)) {
/*
* XXX - check the error code and handle this appropriately.
*/
g_free(buf);
g_free(compressed_data);
*err = WTAP_ERR_INTERNAL;
if (infstream.msg != NULL) {
*err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: inflateInit failed for LogContainer %u, message\"%s\"",
index_log_container,
infstream.msg);
} else {
*err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: inflateInit failed for LogContainer %u",
index_log_container);
}
ws_debug("inflateInit failed for LogContainer %u", index_log_container);
if (infstream.msg != NULL) {
ws_debug("inflateInit returned: \"%s\"", infstream.msg);
}
return FALSE;
}
int ret = inflate(&infstream, Z_NO_FLUSH);
/* Z_OK should not happen here since we know how big the buffer should be */
if (Z_STREAM_END != ret) {
switch (ret) {
case Z_NEED_DICT:
*err = WTAP_ERR_DECOMPRESS;
*err_info = ws_strdup("preset dictionary needed");
break;
case Z_STREAM_ERROR:
*err = WTAP_ERR_DECOMPRESS;
*err_info = (infstream.msg != NULL) ? ws_strdup(infstream.msg) : NULL;
break;
case Z_MEM_ERROR:
/* This means "not enough memory". */
*err = ENOMEM;
*err_info = NULL;
break;
case Z_DATA_ERROR:
/* This means "deflate stream invalid" */
*err = WTAP_ERR_DECOMPRESS;
*err_info = (infstream.msg != NULL) ? ws_strdup(infstream.msg) : NULL;
break;
case Z_BUF_ERROR:
/* XXX - this is recoverable; what should we do here? */
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: Z_BUF_ERROR from inflate(), message \"%s\"",
(infstream.msg != NULL) ? infstream.msg : "(none)");
break;
case Z_VERSION_ERROR:
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: Z_VERSION_ERROR from inflate(), message \"%s\"",
(infstream.msg != NULL) ? infstream.msg : "(none)");
break;
default:
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: unexpected error %d from inflate(), message \"%s\"",
ret,
(infstream.msg != NULL) ? infstream.msg : "(none)");
break;
}
g_free(buf);
g_free(compressed_data);
ws_debug("inflate failed (return code %d) for LogContainer %u", ret, index_log_container);
if (infstream.msg != NULL) {
ws_debug("inflate returned: \"%s\"", infstream.msg);
}
/* Free up any dynamically-allocated memory in infstream */
inflateEnd(&infstream);
return FALSE;
}
if (Z_OK != inflateEnd(&infstream)) {
/*
* The zlib manual says this only returns Z_OK on success
* and Z_STREAM_ERROR if the stream state was inconsistent.
*
* It's not clear what useful information can be reported
* for Z_STREAM_ERROR; a look at the 1.2.11 source indicates
* that no string is returned to indicate what the problem
* was.
*
* It's also not clear what to do about infstream if this
* fails.
*/
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("blf_pull_logcontainer_into_memory: inflateEnd failed for LogContainer %u", index_log_container);
g_free(buf);
g_free(compressed_data);
ws_debug("inflateEnd failed for LogContainer %u", index_log_container);
if (infstream.msg != NULL) {
ws_debug("inflateEnd returned: \"%s\"", infstream.msg);
}
return FALSE;
}
g_free(compressed_data);
tmp.real_data = buf;
g_array_index(blf_data->log_containers, blf_log_container_t, index_log_container) = tmp;
return TRUE;
#else
*err = WTAP_ERR_DECOMPRESSION_NOT_SUPPORTED;
*err_info = ws_strdup("blf_pull_logcontainer_into_memory: reading gzip-compressed containers isn't supported");
return FALSE;
#endif
}
return FALSE;
}
static gboolean
blf_read_bytes_or_eof(blf_params_t *params, guint64 real_pos, void *target_buffer, unsigned int count, int *err, gchar **err_info) {
blf_log_container_t *start_container;
blf_log_container_t *end_container;
blf_log_container_t *current_container;
gint start_container_index = -1;
gint end_container_index = -1;
gint current_container_index = -1;
unsigned int copied = 0;
unsigned int data_left;
unsigned int start_in_buf;
unsigned char *buf = (unsigned char *)target_buffer;
if (!blf_find_logcontainer_for_address(params->blf_data, real_pos, &start_container, &start_container_index)) {
/*
* XXX - why is this treated as an EOF rather than an error?
* *err appears to be 0, which means our caller treats it as an
* EOF, at least when reading the log object header.
*/
ws_debug("cannot read data because start position cannot be mapped");
return FALSE;
}
if (!blf_find_logcontainer_for_address(params->blf_data, real_pos + count - 1, &end_container, &end_container_index)) {
/*
* XXX - why is this treated as an EOF rather than an error?
* *err appears to be 0, which means our caller treats it as an
* EOF, at least when reading the log object header.
*/
ws_debug("cannot read data because end position cannot be mapped");
return FALSE;
}
current_container_index = start_container_index;
current_container = start_container;
start_in_buf = (unsigned int)real_pos - (unsigned int)start_container->real_start_pos;
switch (start_container->compression_method) {
case BLF_COMPRESSION_NONE:
while (current_container_index <= end_container_index) {
if (!blf_get_logcontainer_by_index(params->blf_data, current_container_index, ¤t_container)) {
/*
* XXX - does this represent a bug (WTAP_ERR_INTERNAL) or a
* malformed file (WTAP_ERR_BAD_FILE)?
*/
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("blf_read_bytes_or_eof: cannot refresh container");
ws_debug("cannot refresh container");
return FALSE;
}
data_left = (unsigned int)(current_container->real_length - start_in_buf);
if (file_seek(params->fh, current_container->infile_data_start + start_in_buf, SEEK_SET, err) < 0) {
ws_debug("cannot seek data");
return FALSE;
}
if (data_left < (count - copied)) {
if (!wtap_read_bytes_or_eof(params->fh, buf + copied, data_left, err, err_info)) {
ws_debug("cannot read data");
return FALSE;
}
copied += data_left;
current_container_index++;
start_in_buf = 0;
} else {
if (!wtap_read_bytes_or_eof(params->fh, buf + copied, count - copied, err, err_info)) {
ws_debug("cannot read data");
return FALSE;
}
return TRUE;
}
}
break;
case BLF_COMPRESSION_ZLIB:
while (current_container_index <= end_container_index) {
if (!blf_pull_logcontainer_into_memory(params, current_container_index, err, err_info)) {
return FALSE;
}
if (!blf_get_logcontainer_by_index(params->blf_data, current_container_index, ¤t_container)) {
/*
* XXX - does this represent a bug (WTAP_ERR_INTERNAL) or a
* malformed file (WTAP_ERR_BAD_FILE)?
*/
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("blf_read_bytes_or_eof: cannot refresh container");
ws_debug("cannot refresh container");
return FALSE;
}
if (current_container->real_data == NULL) {
/*
* XXX - does this represent a bug (WTAP_ERR_INTERNAL) or a
* malformed file (WTAP_ERR_BAD_FILE)?
*/
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("blf_read_bytes_or_eof: pulling in container failed hard");
ws_debug("pulling in container failed hard");
return FALSE;
}
data_left = (unsigned int)(current_container->real_length - start_in_buf);
if (data_left < (count - copied)) {
memcpy(buf + copied, current_container->real_data + start_in_buf, (unsigned int)data_left);
copied += data_left;
current_container_index++;
start_in_buf = 0;
} else {
memcpy(buf + copied, current_container->real_data + start_in_buf, count - copied);
return TRUE;
}
}
/*
* XXX - does this represent a bug (WTAP_ERR_INTERNAL) or a
* malformed file (WTAP_ERR_BAD_FILE)?
*/
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("blf_read_bytes_or_eof: ran out of items in container");
return FALSE;
break;
default:
*err = WTAP_ERR_UNSUPPORTED;
*err_info = ws_strdup_printf("blf: unknown compression method %u",
start_container->compression_method);
ws_debug("unknown compression method");
return FALSE;
}
return FALSE;
}
static gboolean
blf_read_bytes(blf_params_t *params, guint64 real_pos, void *target_buffer, unsigned int count, int *err, gchar **err_info) {
if (!blf_read_bytes_or_eof(params, real_pos, target_buffer, count, err, err_info)) {
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
return TRUE;
}
/* this is only called once on open to figure out the layout of the file */
static gboolean
blf_scan_file_for_logcontainers(blf_params_t *params) {
blf_blockheader_t header;
blf_logcontainerheader_t logcontainer_header;
blf_log_container_t tmp;
int err;
gchar *err_info;
guint64 current_start_pos;
guint64 current_real_start = 0;
while (1) {
current_start_pos = file_tell(params->fh);
/* Find Object */
while (1) {
if (!wtap_read_bytes_or_eof(params->fh, &header, sizeof header, &err, &err_info)) {
ws_debug("we found end of file");
/* lets ignore some bytes at the end since some implementations think it is ok to add a few zero bytes */
if (err == WTAP_ERR_SHORT_READ) {
err = 0;
}
return TRUE;
}
fix_endianness_blf_blockheader(&header);
if (memcmp(header.magic, blf_obj_magic, sizeof(blf_obj_magic))) {
ws_debug("object magic is not LOBJ (pos: 0x%" PRIx64 ")", current_start_pos);
} else {
break;
}
/* we are moving back and try again but 1 byte later */
/* TODO: better understand how this paddings works... */
current_start_pos++;
if (file_seek(params->fh, current_start_pos, SEEK_SET, &err) < 0) {
return FALSE;
}
}
if (header.header_type != BLF_HEADER_TYPE_DEFAULT) {
ws_debug("unknown header type, I know only BLF_HEADER_TYPE_DEFAULT (1)");
return FALSE;
}
switch (header.object_type) {
case BLF_OBJTYPE_LOG_CONTAINER:
if (header.header_length < sizeof(blf_blockheader_t)) {
ws_debug("log container header length too short");
return FALSE;
}
/* skip unknown header part if needed */
if (header.header_length - sizeof(blf_blockheader_t) > 0) {
/* seek over unknown header part */
if (file_seek(params->fh, current_start_pos + header.header_length, SEEK_SET, &err) < 0) {
ws_debug("cannot seek file for skipping unknown header bytes in log container");
return FALSE;
}
}
if (!wtap_read_bytes_or_eof(params->fh, &logcontainer_header, sizeof(blf_logcontainerheader_t), &err, &err_info)) {
ws_debug("not enough bytes for log container header");
return FALSE;
}
fix_endianness_blf_logcontainerheader(&logcontainer_header);
blf_init_logcontainer(&tmp);
tmp.infile_start_pos = current_start_pos;
tmp.infile_data_start = file_tell(params->fh);
tmp.infile_length = header.object_length;
tmp.real_start_pos = current_real_start;
tmp.real_length = logcontainer_header.uncompressed_size;
tmp.compression_method = logcontainer_header.compression_method;
/* set up next start position */
current_real_start += logcontainer_header.uncompressed_size;
if (file_seek(params->fh, current_start_pos + MAX(MAX(16, header.object_length), header.header_length), SEEK_SET, &err) < 0) {
ws_debug("cannot seek file for skipping log container bytes");
return FALSE;
}
blf_add_logcontainer(params->blf_data, tmp);
break;
default:
ws_debug("we found a non BLF log container on top level. this is unexpected.");
/* TODO: maybe create "fake Log Container" for this */
if (file_seek(params->fh, current_start_pos + MAX(MAX(16, header.object_length), header.header_length), SEEK_SET, &err) < 0) {
return FALSE;
}
}
}
return TRUE;
}
static void
blf_init_rec(blf_params_t *params, guint64 object_timestamp, int pkt_encap, guint32 channel, guint caplen, guint len) {
params->rec->rec_type = REC_TYPE_PACKET;
params->rec->block = wtap_block_create(WTAP_BLOCK_PACKET);
params->rec->presence_flags = WTAP_HAS_TS | WTAP_HAS_CAP_LEN | WTAP_HAS_INTERFACE_ID;
params->rec->tsprec = WTAP_TSPREC_NSEC; /* there is no 10us, maybe we should update this */
params->rec->ts.secs = object_timestamp / (1000 * 1000 * 1000);
params->rec->ts.nsecs = object_timestamp % (1000 * 1000 * 1000);
params->rec->rec_header.packet_header.caplen = caplen;
params->rec->rec_header.packet_header.len = len;
nstime_t tmp_ts;
tmp_ts.secs = params->blf_data->start_offset_ns / (1000 * 1000 * 1000);
tmp_ts.nsecs = params->blf_data->start_offset_ns % (1000 * 1000 * 1000);
nstime_delta(¶ms->rec->ts_rel_cap, ¶ms->rec->ts, &tmp_ts);
params->rec->ts_rel_cap_valid = true;
params->rec->rec_header.packet_header.pkt_encap = pkt_encap;
params->rec->rec_header.packet_header.interface_id = blf_lookup_interface(params, pkt_encap, channel, NULL);
/* TODO: before we had to remove comments and verdict here to not leak memory but APIs have changed ... */
}
static void
blf_add_direction_option(blf_params_t *params, guint16 direction) {
guint32 tmp = 0; /* dont care */
switch (direction) {
case BLF_DIR_RX:
tmp = 1; /* inbound */
break;
case BLF_DIR_TX:
case BLF_DIR_TX_RQ:
tmp = 2; /* outbound */
break;
}
/* pcapng.c: #define OPT_EPB_FLAGS 0x0002 */
wtap_block_add_uint32_option(params->rec->block, 0x0002, tmp);
}
static gboolean
blf_read_log_object_header(blf_params_t *params, int *err, gchar **err_info, gint64 header2_start, gint64 data_start, blf_logobjectheader_t *logheader) {
if (data_start - header2_start < (gint64)sizeof(blf_logobjectheader_t)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: not enough bytes for log object header");
ws_debug("not enough bytes for timestamp header");
return FALSE;
}
if (!blf_read_bytes_or_eof(params, header2_start, logheader, sizeof(*logheader), err, err_info)) {
ws_debug("not enough bytes for logheader");
return FALSE;
}
fix_endianness_blf_logobjectheader(logheader);
return TRUE;
}
static gboolean
blf_read_log_object_header2(blf_params_t *params, int *err, gchar **err_info, gint64 header2_start, gint64 data_start, blf_logobjectheader2_t *logheader) {
if (data_start - header2_start < (gint64)sizeof(blf_logobjectheader2_t)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: not enough bytes for log object header");
ws_debug("not enough bytes for timestamp header");
return FALSE;
}
if (!blf_read_bytes_or_eof(params, header2_start, logheader, sizeof(*logheader), err, err_info)) {
ws_debug("not enough bytes for logheader");
return FALSE;
}
fix_endianness_blf_logobjectheader2(logheader);
return TRUE;
}
static gboolean
blf_read_log_object_header3(blf_params_t *params, int *err, gchar **err_info, gint64 header2_start, gint64 data_start, blf_logobjectheader3_t *logheader) {
if (data_start - header2_start < (gint64)sizeof(blf_logobjectheader3_t)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: not enough bytes for log object header");
ws_debug("not enough bytes for timestamp header");
return FALSE;
}
if (!blf_read_bytes_or_eof(params, header2_start, logheader, sizeof(*logheader), err, err_info)) {
ws_debug("not enough bytes for logheader");
return FALSE;
}
fix_endianness_blf_logobjectheader3(logheader);
return TRUE;
}
static gboolean
blf_read_ethernetframe(blf_params_t *params, int *err, gchar **err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp) {
blf_ethernetframeheader_t ethheader;
guint8 tmpbuf[18];
guint caplen, len;
if (object_length < (data_start - block_start) + (int) sizeof(blf_ethernetframeheader_t)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: ETHERNET_FRAME: not enough bytes for ethernet frame header in object");
ws_debug("not enough bytes for ethernet frame header in object");
return FALSE;
}
if (!blf_read_bytes(params, data_start, ðheader, sizeof(ethheader), err, err_info)) {
ws_debug("not enough bytes for ethernet frame header in file");
return FALSE;
}
fix_endianness_blf_ethernetframeheader(ðheader);
/*
* BLF breaks up and reorders the Ethernet header and VLAN tag fields.
* This is a really bad design and makes this format one of the worst.
* If you want a fast format that keeps your data intact, avoid this format!
* So, lets hope we can reconstruct the original packet successfully.
*/
tmpbuf[0] = ethheader.dst_addr[0];
tmpbuf[1] = ethheader.dst_addr[1];
tmpbuf[2] = ethheader.dst_addr[2];
tmpbuf[3] = ethheader.dst_addr[3];
tmpbuf[4] = ethheader.dst_addr[4];
tmpbuf[5] = ethheader.dst_addr[5];
tmpbuf[6] = ethheader.src_addr[0];
tmpbuf[7] = ethheader.src_addr[1];
tmpbuf[8] = ethheader.src_addr[2];
tmpbuf[9] = ethheader.src_addr[3];
tmpbuf[10] = ethheader.src_addr[4];
tmpbuf[11] = ethheader.src_addr[5];
if (ethheader.tpid != 0 && ethheader.tci != 0) {
tmpbuf[12] = (ethheader.tpid & 0xff00) >> 8;
tmpbuf[13] = (ethheader.tpid & 0x00ff);
tmpbuf[14] = (ethheader.tci & 0xff00) >> 8;
tmpbuf[15] = (ethheader.tci & 0x00ff);
tmpbuf[16] = (ethheader.ethtype & 0xff00) >> 8;
tmpbuf[17] = (ethheader.ethtype & 0x00ff);
ws_buffer_assure_space(params->buf, (gsize)18 + ethheader.payloadlength);
ws_buffer_append(params->buf, tmpbuf, (gsize)18);
caplen = ((guint32)18 + ethheader.payloadlength);
len = ((guint32)18 + ethheader.payloadlength);
} else {
tmpbuf[12] = (ethheader.ethtype & 0xff00) >> 8;
tmpbuf[13] = (ethheader.ethtype & 0x00ff);
ws_buffer_assure_space(params->buf, (gsize)14 + ethheader.payloadlength);
ws_buffer_append(params->buf, tmpbuf, (gsize)14);
caplen = ((guint32)14 + ethheader.payloadlength);
len = ((guint32)14 + ethheader.payloadlength);
}
if (!blf_read_bytes(params, data_start + sizeof(blf_ethernetframeheader_t), ws_buffer_end_ptr(params->buf), ethheader.payloadlength, err, err_info)) {
ws_debug("copying ethernet frame failed");
return FALSE;
}
params->buf->first_free += ethheader.payloadlength;
blf_init_rec(params, timestamp, WTAP_ENCAP_ETHERNET, ethheader.channel, caplen, len);
blf_add_direction_option(params, ethheader.direction);
return TRUE;
}
static gboolean
blf_read_ethernetframe_ext(blf_params_t *params, int *err, gchar **err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp) {
blf_ethernetframeheader_ex_t ethheader;
if (object_length < (data_start - block_start) + (int) sizeof(blf_ethernetframeheader_ex_t)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: ETHERNET_FRAME_EX: not enough bytes for ethernet frame header in object");
ws_debug("not enough bytes for ethernet frame header in object");
return FALSE;
}
if (!blf_read_bytes(params, data_start, ðheader, sizeof(blf_ethernetframeheader_ex_t), err, err_info)) {
ws_debug("not enough bytes for ethernet frame header in file");
return FALSE;
}
fix_endianness_blf_ethernetframeheader_ex(ðheader);
ws_buffer_assure_space(params->buf, ethheader.frame_length);
if (object_length - (data_start - block_start) - sizeof(blf_ethernetframeheader_ex_t) < ethheader.frame_length) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: ETHERNET_FRAME_EX: frame too short");
ws_debug("frame too short");
return FALSE;
}
if (!blf_read_bytes(params, data_start + sizeof(blf_ethernetframeheader_ex_t), ws_buffer_start_ptr(params->buf), ethheader.frame_length, err, err_info)) {
ws_debug("copying ethernet frame failed");
return FALSE;
}
blf_init_rec(params, timestamp, WTAP_ENCAP_ETHERNET, ethheader.channel, ethheader.frame_length, ethheader.frame_length);
wtap_block_add_uint32_option(params->rec->block, OPT_PKT_QUEUE, ethheader.hw_channel);
blf_add_direction_option(params, ethheader.direction);
return TRUE;
}
/*
* XXX - provide radio information to our caller in the pseudo-header.
*/
static gboolean
blf_read_wlanframe(blf_params_t* params, int* err, gchar** err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp) {
blf_wlanframeheader_t wlanheader;
if (object_length < (data_start - block_start) + (int)sizeof(blf_wlanframeheader_t)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: WLAN_FRAME: not enough bytes for wlan frame header in object");
ws_debug("not enough bytes for wlan frame header in object");
return FALSE;
}
if (!blf_read_bytes(params, data_start, &wlanheader, sizeof(blf_wlanframeheader_t), err, err_info)) {
ws_debug("not enough bytes for wlan frame header in file");
return FALSE;
}
fix_endianness_blf_wlanframeheader(&wlanheader);
ws_buffer_assure_space(params->buf, wlanheader.frame_length);
if (object_length - (data_start - block_start) - sizeof(blf_wlanframeheader_t) < wlanheader.frame_length) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: WLAN_FRAME: frame too short");
ws_debug("frame too short");
return FALSE;
}
if (!blf_read_bytes(params, data_start + sizeof(blf_wlanframeheader_t), ws_buffer_start_ptr(params->buf), wlanheader.frame_length, err, err_info)) {
ws_debug("copying wlan frame failed");
return FALSE;
}
blf_init_rec(params, timestamp, WTAP_ENCAP_IEEE_802_11, wlanheader.channel, wlanheader.frame_length, wlanheader.frame_length);
blf_add_direction_option(params, wlanheader.direction);
return TRUE;
}
static guint8 can_dlc_to_length[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8, 8, 8 };
static guint8 canfd_dlc_to_length[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64 };
static gboolean
blf_can_fill_buf_and_rec(blf_params_t *params, int *err, gchar **err_info, guint32 canid, guint8 payload_length, guint8 payload_length_valid, guint64 start_position,
guint64 timestamp, guint32 channel) {
guint8 tmpbuf[8];
guint caplen, len;
tmpbuf[0] = (canid & 0xff000000) >> 24;
tmpbuf[1] = (canid & 0x00ff0000) >> 16;
tmpbuf[2] = (canid & 0x0000ff00) >> 8;
tmpbuf[3] = (canid & 0x000000ff);
tmpbuf[4] = payload_length;
tmpbuf[5] = 0;
tmpbuf[6] = 0;
tmpbuf[7] = 0;
ws_buffer_assure_space(params->buf, sizeof(tmpbuf) + payload_length_valid);
ws_buffer_append(params->buf, tmpbuf, sizeof(tmpbuf));
caplen = sizeof(tmpbuf) + payload_length_valid;
len = sizeof(tmpbuf) + payload_length;
if (payload_length_valid > 0 && !blf_read_bytes(params, start_position, ws_buffer_end_ptr(params->buf), payload_length_valid, err, err_info)) {
ws_debug("copying can payload failed");
return FALSE;
}
params->buf->first_free += payload_length_valid;
blf_init_rec(params, timestamp, WTAP_ENCAP_SOCKETCAN, channel, caplen, len);
return TRUE;
}
static gboolean
blf_read_canmessage(blf_params_t *params, int *err, gchar **err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp, gboolean can_message2) {
blf_canmessage_t canheader;
blf_canmessage2_trailer_t can2trailer;
guint32 canid;
guint8 payload_length;
guint8 payload_length_valid;
if (object_length < (data_start - block_start) + (int) sizeof(canheader)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: %s: not enough bytes for canfd header in object",
can_message2 ? "CAN_MESSAGE2" : "CAN_MESSAGE");
ws_debug("not enough bytes for canfd header in object");
return FALSE;
}
if (!blf_read_bytes(params, data_start, &canheader, sizeof(canheader), err, err_info)) {
ws_debug("not enough bytes for can header in file");
return FALSE;
}
fix_endianness_blf_canmessage(&canheader);
if (canheader.dlc > 15) {
canheader.dlc = 15;
}
payload_length = canheader.dlc;
if (payload_length > 8) {
ws_debug("regular CAN tries more than 8 bytes? Cutting to 8!");
payload_length = 8;
}
payload_length_valid = payload_length;
if (payload_length_valid > object_length - (data_start - block_start)) {
ws_debug("shortening CAN payload because buffer is too short!");
payload_length_valid = (guint8)(object_length - (data_start - block_start));
}
canid = canheader.id;
if ((canheader.flags & BLF_CANMESSAGE_FLAG_RTR) == BLF_CANMESSAGE_FLAG_RTR) {
canid |= CAN_RTR_FLAG;
payload_length_valid = 0;
}
if (!blf_can_fill_buf_and_rec(params, err, err_info, canid, payload_length, payload_length_valid, data_start + sizeof(canheader), timestamp, canheader.channel)) {
return FALSE;
}
/* actually, we do not really need the data, right now.... */
if (can_message2) {
if (object_length < (data_start - block_start) + (int) sizeof(canheader) + payload_length_valid + (int) sizeof(can2trailer)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: CAN_MESSAGE2: not enough bytes for can message 2 trailer");
ws_debug("not enough bytes for can message 2 trailer");
return FALSE;
}
if (!blf_read_bytes(params, data_start + sizeof(canheader) + payload_length_valid, &can2trailer, sizeof(can2trailer), err, err_info)) {
ws_debug("not enough bytes for can message 2 trailer in file");
return FALSE;
}
fix_endianness_blf_canmessage2_trailer(&can2trailer);
}
blf_add_direction_option(params, (canheader.flags & BLF_CANMESSAGE_FLAG_TX) == BLF_CANMESSAGE_FLAG_TX ? BLF_DIR_TX: BLF_DIR_RX);
return TRUE;
}
static gboolean
blf_read_canfdmessage(blf_params_t *params, int *err, gchar **err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp) {
blf_canfdmessage_t canheader;
gboolean canfd;
guint32 canid;
guint8 payload_length;
guint8 payload_length_valid;
if (object_length < (data_start - block_start) + (int) sizeof(canheader)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: CAN_FD_MESSAGE: not enough bytes for canfd header in object");
ws_debug("not enough bytes for canfd header in object");
return FALSE;
}
if (!blf_read_bytes(params, data_start, &canheader, sizeof(canheader), err, err_info)) {
ws_debug("not enough bytes for canfd header in file");
return FALSE;
}
fix_endianness_blf_canfdmessage(&canheader);
if (canheader.dlc > 15) {
canheader.dlc = 15;
}
canfd = (canheader.canfdflags & BLF_CANFDMESSAGE_CANFDFLAG_EDL) == BLF_CANFDMESSAGE_CANFDFLAG_EDL;
if (canfd) {
payload_length = canfd_dlc_to_length[canheader.dlc];
} else {
if (canheader.dlc > 8) {
ws_debug("regular CAN tries more than 8 bytes?");
}
payload_length = can_dlc_to_length[canheader.dlc];
}
payload_length_valid = payload_length;
if (payload_length_valid > canheader.validDataBytes) {
ws_debug("shortening canfd payload because valid data bytes shorter!");
payload_length_valid = canheader.validDataBytes;
}
if (payload_length_valid > object_length - (data_start - block_start) + sizeof(canheader)) {
ws_debug("shortening can payload because buffer is too short!");
payload_length_valid = (guint8)(object_length - (data_start - block_start));
}
canid = canheader.id;
if (!canfd && (canheader.flags & BLF_CANMESSAGE_FLAG_RTR) == BLF_CANMESSAGE_FLAG_RTR) {
canid |= CAN_RTR_FLAG;
payload_length_valid = 0;
}
if (!blf_can_fill_buf_and_rec(params, err, err_info, canid, payload_length, payload_length_valid, data_start + sizeof(canheader), timestamp, canheader.channel)) {
return FALSE;
}
blf_add_direction_option(params, (canheader.flags & BLF_CANMESSAGE_FLAG_TX) == BLF_CANMESSAGE_FLAG_TX ? BLF_DIR_TX : BLF_DIR_RX);
return TRUE;
}
static gboolean
blf_read_canfdmessage64(blf_params_t *params, int *err, gchar **err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp) {
blf_canfdmessage64_t canheader;
gboolean canfd;
guint32 canid;
guint8 payload_length;
guint8 payload_length_valid;
if (object_length < (data_start - block_start) + (int) sizeof(canheader)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: CAN_FD_MESSAGE_64: not enough bytes for canfd header in object");
ws_debug("not enough bytes for canfd header in object");
return FALSE;
}
if (!blf_read_bytes(params, data_start, &canheader, sizeof(canheader), err, err_info)) {
ws_debug("not enough bytes for canfd header in file");
return FALSE;
}
fix_endianness_blf_canfdmessage64(&canheader);
if (canheader.dlc > 15) {
canheader.dlc = 15;
}
canfd = (canheader.flags & BLF_CANFDMESSAGE64_FLAG_EDL) == BLF_CANFDMESSAGE64_FLAG_EDL;
if (canfd) {
payload_length = canfd_dlc_to_length[canheader.dlc];
} else {
if (canheader.dlc > 8) {
ws_debug("regular CAN tries more than 8 bytes?");
}
payload_length = can_dlc_to_length[canheader.dlc];
}
payload_length_valid = payload_length;
if (payload_length_valid > canheader.validDataBytes) {
ws_debug("shortening canfd payload because valid data bytes shorter!");
payload_length_valid = canheader.validDataBytes;
}
if (payload_length_valid > object_length - (data_start - block_start)) {
ws_debug("shortening can payload because buffer is too short!");
payload_length_valid = (guint8)(object_length - (data_start - block_start));
}
canid = canheader.id;
if (!canfd && (canheader.flags & BLF_CANFDMESSAGE64_FLAG_REMOTE_FRAME) == BLF_CANFDMESSAGE64_FLAG_REMOTE_FRAME) {
canid |= CAN_RTR_FLAG;
payload_length_valid = 0;
}
if (!blf_can_fill_buf_and_rec(params, err, err_info, canid, payload_length, payload_length_valid, data_start + sizeof(canheader), timestamp, canheader.channel)) {
return FALSE;
}
blf_add_direction_option(params, canheader.dir);
return TRUE;
}
static gboolean
blf_read_canerror(blf_params_t *params, int *err, gchar **err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp) {
blf_canerror_t canheader;
guint32 canid;
guint8 payload_length;
guint8 tmpbuf[16] = {0};
if (object_length < (data_start - block_start) + (int) sizeof(canheader)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: CAN_ERROR: not enough bytes for canerror header in object");
ws_debug("not enough bytes for canerror header in object");
return FALSE;
}
if (!blf_read_bytes(params, data_start, &canheader, sizeof(canheader), err, err_info)) {
ws_debug("not enough bytes for canerror header in file");
return FALSE;
}
fix_endianness_blf_canerror(&canheader);
// Set CAN_ERR_FLAG in unused bits of Can ID to indicate error in socketcan
canid = CAN_ERR_FLAG;
// Fixed packet data length for socketcan error messages
payload_length = CAN_ERR_DLC;
tmpbuf[0] = (canid & 0xff000000) >> 24;
tmpbuf[1] = (canid & 0x00ff0000) >> 16;
tmpbuf[2] = (canid & 0x0000ff00) >> 8;
tmpbuf[3] = (canid & 0x000000ff);
tmpbuf[4] = payload_length;
ws_buffer_assure_space(params->buf, sizeof(tmpbuf));
ws_buffer_append(params->buf, tmpbuf, sizeof(tmpbuf));
blf_init_rec(params, timestamp, WTAP_ENCAP_SOCKETCAN, canheader.channel, sizeof(tmpbuf), sizeof(tmpbuf));
return TRUE;
}
static gboolean
blf_read_canerrorext(blf_params_t *params, int *err, gchar **err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp) {
blf_canerrorext_t canheader;
gboolean err_ack = false;
gboolean err_prot = false;
gboolean direction_tx;
guint32 canid;
guint8 payload_length;
guint8 tmpbuf[16] = {0};
if (object_length < (data_start - block_start) + (int) sizeof(canheader)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: CAN_ERROR_EXT: not enough bytes for canerrorext header in object");
ws_debug("not enough bytes for canerrorext header in object");
return FALSE;
}
if (!blf_read_bytes(params, data_start, &canheader, sizeof(canheader), err, err_info)) {
ws_debug("not enough bytes for canerrorext header in file");
return FALSE;
}
fix_endianness_blf_canerrorext(&canheader);
if (canheader.flags & BLF_CANERROREXT_FLAG_CANCORE) {
// Map Vector Can Core error codes to compareable socketcan errors
switch ((canheader.errorCodeExt >> 6) & 0x3f) {
case BLF_CANERROREXT_ECC_MEANING_BIT_ERROR:
err_prot = true;
tmpbuf[10] = CAN_ERR_PROT_BIT;
break;
case BLF_CANERROREXT_ECC_MEANING_FORM_ERROR:
err_prot = true;
tmpbuf[10] = CAN_ERR_PROT_FORM;
break;
case BLF_CANERROREXT_ECC_MEANING_STUFF_ERROR:
err_prot = true;
tmpbuf[10] = CAN_ERR_PROT_STUFF;
break;
case BLF_CANERROREXT_ECC_MEANING_CRC_ERROR:
err_prot = true;
tmpbuf[11] = CAN_ERR_PROT_LOC_CRC_SEQ;
break;
case BLF_CANERROREXT_ECC_MEANING_NACK_ERROR:
err_ack = true;
tmpbuf[11] = CAN_ERR_PROT_LOC_ACK;
break;
case BLF_CANERROREXT_ECC_MEANING_OVERLOAD:
err_prot = true;
tmpbuf[10] = CAN_ERR_PROT_OVERLOAD;
break;
default:
err_prot = true;
tmpbuf[10] = CAN_ERR_PROT_UNSPEC;
break;
}
err_ack = err_ack || (canheader.errorCodeExt & BLF_CANERROREXT_EXTECC_NOT_ACK) == 0x0;
if (err_ack) {
// Don't set protocol error on ack errors
err_prot = false;
}
}
// CanID contains error class in socketcan
canid = CAN_ERR_FLAG;
canid |= err_prot ? CAN_ERR_PROT : 0;
canid |= err_ack ? CAN_ERR_ACK : 0;
// Fixed packet data length for socketcan error messages
payload_length = CAN_ERR_DLC;
canheader.dlc = payload_length;
tmpbuf[0] = (canid & 0xff000000) >> 24;
tmpbuf[1] = (canid & 0x00ff0000) >> 16;
tmpbuf[2] = (canid & 0x0000ff00) >> 8;
tmpbuf[3] = (canid & 0x000000ff);
tmpbuf[4] = payload_length;
ws_buffer_assure_space(params->buf, sizeof(tmpbuf));
ws_buffer_append(params->buf, tmpbuf, sizeof(tmpbuf));
blf_init_rec(params, timestamp, WTAP_ENCAP_SOCKETCAN, canheader.channel, sizeof(tmpbuf), sizeof(tmpbuf));
if (canheader.flags & BLF_CANERROREXT_FLAG_CANCORE) {
direction_tx = (canheader.errorCodeExt & BLF_CANERROREXT_EXTECC_TX) == BLF_CANERROREXT_EXTECC_TX;
blf_add_direction_option(params, direction_tx ? BLF_DIR_TX: BLF_DIR_RX);
}
return TRUE;
}
static gboolean
blf_read_canfderror64(blf_params_t *params, int *err, gchar **err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp) {
blf_canfderror64_t canheader;
gboolean err_ack = false;
gboolean err_prot = false;
gboolean direction_tx;
guint32 canid;
guint8 payload_length;
guint8 tmpbuf[16] = {0};
if (object_length < (data_start - block_start) + (int) sizeof(canheader)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: CAN_FD_ERROR_64: not enough bytes for canfderror header in object");
ws_debug("not enough bytes for canfderror header in object");
return FALSE;
}
if (!blf_read_bytes(params, data_start, &canheader, sizeof(canheader), err, err_info)) {
ws_debug("not enough bytes for canfderror header in file");
return FALSE;
}
fix_endianness_blf_canfderror64(&canheader);
if (canheader.flags & BLF_CANERROREXT_FLAG_CANCORE) {
// Map Vector Can Core error codes to compareable socketcan errors
switch ((canheader.errorCodeExt >> 6) & 0x3f) {
case BLF_CANERROREXT_ECC_MEANING_BIT_ERROR:
err_prot = true;
tmpbuf[10] = CAN_ERR_PROT_BIT;
break;
case BLF_CANERROREXT_ECC_MEANING_FORM_ERROR:
err_prot = true;
tmpbuf[10] = CAN_ERR_PROT_FORM;
break;
case BLF_CANERROREXT_ECC_MEANING_STUFF_ERROR:
err_prot = true;
tmpbuf[10] = CAN_ERR_PROT_STUFF;
break;
case BLF_CANERROREXT_ECC_MEANING_CRC_ERROR:
err_prot = true;
tmpbuf[11] = CAN_ERR_PROT_LOC_CRC_SEQ;
break;
case BLF_CANERROREXT_ECC_MEANING_NACK_ERROR:
err_ack = true;
tmpbuf[11] = CAN_ERR_PROT_LOC_ACK;
break;
case BLF_CANERROREXT_ECC_MEANING_OVERLOAD:
err_prot = true;
tmpbuf[10] = CAN_ERR_PROT_OVERLOAD;
break;
default:
err_prot = true;
tmpbuf[10] = CAN_ERR_PROT_UNSPEC;
break;
}
err_ack = err_ack || (canheader.errorCodeExt & BLF_CANERROREXT_EXTECC_NOT_ACK) == 0x0;
if (err_ack) {
// Don't set protocol error on ack errors
err_prot = false;
}
}
// CanID contains error class in socketcan
canid = CAN_ERR_FLAG;
canid |= err_prot ? CAN_ERR_PROT : 0;
canid |= err_ack ? CAN_ERR_ACK : 0;
// Fixed packet data length for socketcan error messages
payload_length = CAN_ERR_DLC;
canheader.dlc = payload_length;
tmpbuf[0] = (canid & 0xff000000) >> 24;
tmpbuf[1] = (canid & 0x00ff0000) >> 16;
tmpbuf[2] = (canid & 0x0000ff00) >> 8;
tmpbuf[3] = (canid & 0x000000ff);
tmpbuf[4] = payload_length;
ws_buffer_assure_space(params->buf, sizeof(tmpbuf));
ws_buffer_append(params->buf, tmpbuf, sizeof(tmpbuf));
blf_init_rec(params, timestamp, WTAP_ENCAP_SOCKETCAN, canheader.channel, sizeof(tmpbuf), sizeof(tmpbuf));
if (canheader.flags & BLF_CANERROREXT_FLAG_CANCORE) {
direction_tx = (canheader.errorCodeExt & BLF_CANERROREXT_EXTECC_TX) == BLF_CANERROREXT_EXTECC_TX;
blf_add_direction_option(params, direction_tx ? BLF_DIR_TX: BLF_DIR_RX);
}
return TRUE;
}
static gboolean
blf_read_flexraydata(blf_params_t *params, int *err, gchar **err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp) {
blf_flexraydata_t frheader;
guint8 payload_length;
guint8 payload_length_valid;
guint8 tmpbuf[7];
guint caplen, len;
if (object_length < (data_start - block_start) + (int) sizeof(frheader)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: FLEXRAY_DATA: not enough bytes for flexrayheader in object");
ws_debug("not enough bytes for flexrayheader in object");
return FALSE;
}
if (!blf_read_bytes(params, data_start, &frheader, sizeof(frheader), err, err_info)) {
ws_debug("not enough bytes for flexrayheader header in file");
return FALSE;
}
fix_endianness_blf_flexraydata(&frheader);
payload_length = frheader.len;
payload_length_valid = payload_length;
if ((frheader.len & 0x01) == 0x01) {
ws_debug("reading odd length in FlexRay!?");
}
if (payload_length_valid > object_length - (data_start - block_start) - sizeof(frheader)) {
ws_debug("shortening FlexRay payload because buffer is too short!");
payload_length_valid = (guint8)(object_length - (data_start - block_start) - sizeof(frheader));
}
if (frheader.channel != 0 && frheader.channel != 1) {
ws_debug("FlexRay supports only two channels.");
}
/* Measurement Header */
if (frheader.channel == 0) {
tmpbuf[0] = BLF_FLEXRAYDATA_FRAME;
} else {
tmpbuf[0] = BLF_FLEXRAYDATA_FRAME | BLF_FLEXRAYDATA_CHANNEL_B;
}
/* Error Flags */
tmpbuf[1] = 0;
/* Frame Header */
tmpbuf[2] = 0x20 | ((0x0700 & frheader.messageId) >> 8);
tmpbuf[3] = 0x00ff & frheader.messageId;
tmpbuf[4] = (0xfe & frheader.len) | ((frheader.crc & 0x0400) >> 10);
tmpbuf[5] = (0x03fc & frheader.crc) >> 2;
tmpbuf[6] = ((0x0003 & frheader.crc) << 6) | (0x3f & frheader.mux);
ws_buffer_assure_space(params->buf, sizeof(tmpbuf) + payload_length_valid);
ws_buffer_append(params->buf, tmpbuf, sizeof(tmpbuf));
caplen = sizeof(tmpbuf) + payload_length_valid;
len = sizeof(tmpbuf) + payload_length;
if (payload_length_valid > 0 && !blf_read_bytes(params, data_start + sizeof(frheader), ws_buffer_end_ptr(params->buf), payload_length_valid, err, err_info)) {
ws_debug("copying flexray payload failed");
return FALSE;
}
params->buf->first_free += payload_length_valid;
blf_init_rec(params, timestamp, WTAP_ENCAP_FLEXRAY, frheader.channel, caplen, len);
blf_add_direction_option(params, frheader.dir);
return TRUE;
}
static gboolean
blf_read_flexraymessage(blf_params_t *params, int *err, gchar **err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp) {
blf_flexraymessage_t frheader;
guint8 payload_length;
guint8 payload_length_valid;
guint8 tmpbuf[7];
guint caplen, len;
if (object_length < (data_start - block_start) + (int) sizeof(frheader)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: FLEXRAY_MESSAGE: not enough bytes for flexrayheader in object");
ws_debug("not enough bytes for flexrayheader in object");
return FALSE;
}
if (!blf_read_bytes(params, data_start, &frheader, sizeof(frheader), err, err_info)) {
ws_debug("not enough bytes for flexrayheader header in file");
return FALSE;
}
fix_endianness_blf_flexraymessage(&frheader);
payload_length = frheader.length;
payload_length_valid = payload_length;
if ((frheader.length & 0x01) == 0x01) {
ws_debug("reading odd length in FlexRay!?");
}
if (payload_length_valid > object_length - (data_start - block_start) - sizeof(frheader)) {
ws_debug("shortening FlexRay payload because buffer is too short!");
payload_length_valid = (guint8)(object_length - (data_start - block_start) - sizeof(frheader));
}
if (frheader.channel != 0 && frheader.channel != 1) {
ws_debug("FlexRay supports only two channels.");
}
/* Measurement Header */
if (frheader.channel == 0) {
tmpbuf[0] = BLF_FLEXRAYDATA_FRAME;
} else {
tmpbuf[0] = BLF_FLEXRAYDATA_FRAME | BLF_FLEXRAYDATA_CHANNEL_B;
}
/* Error Flags */
tmpbuf[1] = 0;
/* Frame Header */
tmpbuf[2] = ((0x0700 & frheader.frameId) >> 8);
if ((frheader.frameState & BLF_FLEXRAYMESSAGE_STATE_PPI) == BLF_FLEXRAYMESSAGE_STATE_PPI) {
tmpbuf[2] |= BLF_DLT_FLEXRAY_PPI;
}
if ((frheader.frameState & BLF_FLEXRAYMESSAGE_STATE_SFI) == BLF_FLEXRAYMESSAGE_STATE_SFI) {
tmpbuf[2] |= BLF_DLT_FLEXRAY_SFI;
}
if ((frheader.frameState & BLF_FLEXRAYMESSAGE_STATE_NFI) != BLF_FLEXRAYMESSAGE_STATE_NFI) {
/* NFI needs to be inversed !? */
tmpbuf[2] |= BLF_DLT_FLEXRAY_NFI;
}
if ((frheader.frameState & BLF_FLEXRAYMESSAGE_STATE_STFI) == BLF_FLEXRAYMESSAGE_STATE_STFI) {
tmpbuf[2] |= BLF_DLT_FLEXRAY_STFI;
}
tmpbuf[3] = 0x00ff & frheader.frameId;
tmpbuf[4] = (0xfe & frheader.length) | ((frheader.headerCrc & 0x0400) >> 10);
tmpbuf[5] = (0x03fc & frheader.headerCrc) >> 2;
tmpbuf[6] = ((0x0003 & frheader.headerCrc) << 6) | (0x3f & frheader.cycle);
ws_buffer_assure_space(params->buf, sizeof(tmpbuf) + payload_length_valid);
ws_buffer_append(params->buf, tmpbuf, sizeof(tmpbuf));
caplen = sizeof(tmpbuf) + payload_length_valid;
len = sizeof(tmpbuf) + payload_length;
if (payload_length_valid > 0 && !blf_read_bytes(params, data_start + sizeof(frheader), ws_buffer_end_ptr(params->buf), payload_length_valid, err, err_info)) {
ws_debug("copying flexray payload failed");
return FALSE;
}
params->buf->first_free += payload_length_valid;
blf_init_rec(params, timestamp, WTAP_ENCAP_FLEXRAY, frheader.channel, caplen, len);
blf_add_direction_option(params, frheader.dir);
return TRUE;
}
static gboolean
blf_read_flexrayrcvmessageex(blf_params_t *params, int *err, gchar **err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp, gboolean ext) {
blf_flexrayrcvmessage_t frheader;
guint16 payload_length;
guint16 payload_length_valid;
guint8 tmpbuf[7];
gint frheadersize = sizeof(frheader);
guint caplen, len;
if (ext) {
frheadersize += 40;
}
if ((gint64)object_length < (data_start - block_start) + frheadersize) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: %s: not enough bytes for flexrayheader in object",
ext ? "FLEXRAY_RCVMESSAGE_EX" : "FLEXRAY_RCVMESSAGE");
ws_debug("not enough bytes for flexrayheader in object");
return FALSE;
}
if (!blf_read_bytes(params, data_start, &frheader, sizeof(frheader), err, err_info)) {
ws_debug("not enough bytes for flexrayheader header in file");
return FALSE;
}
fix_endianness_blf_flexrayrcvmessage(&frheader);
if (!ext) {
frheader.dir &= 0xff;
frheader.cycle &= 0xff;
}
payload_length = frheader.payloadLength;
payload_length_valid = frheader.payloadLengthValid;
if ((frheader.payloadLength & 0x01) == 0x01) {
ws_debug("reading odd length in FlexRay!?");
}
if (payload_length_valid > object_length - (data_start - block_start) - frheadersize) {
ws_debug("shortening FlexRay payload because buffer is too short!");
payload_length_valid = (guint8)(object_length - (data_start - block_start) - frheadersize);
}
/* Measurement Header */
/* TODO: It seems that this format support both channels at the same time!? */
if (frheader.channelMask == BLF_FLEXRAYRCVMSG_CHANNELMASK_A) {
tmpbuf[0] = BLF_FLEXRAYDATA_FRAME;
} else {
tmpbuf[0] = BLF_FLEXRAYDATA_FRAME | BLF_FLEXRAYDATA_CHANNEL_B;
}
/* Error Flags */
tmpbuf[1] = 0;
/* Frame Header */
tmpbuf[2] = ((0x0700 & frheader.frameId) >> 8);
if ((frheader.data & BLF_FLEXRAYRCVMSG_DATA_FLAG_PAYLOAD_PREAM) == BLF_FLEXRAYRCVMSG_DATA_FLAG_PAYLOAD_PREAM) {
tmpbuf[2] |= BLF_DLT_FLEXRAY_PPI;
}
if ((frheader.data & BLF_FLEXRAYRCVMSG_DATA_FLAG_SYNC) == BLF_FLEXRAYRCVMSG_DATA_FLAG_SYNC) {
tmpbuf[2] |= BLF_DLT_FLEXRAY_SFI;
}
if ((frheader.data & BLF_FLEXRAYRCVMSG_DATA_FLAG_NULL_FRAME) != BLF_FLEXRAYRCVMSG_DATA_FLAG_NULL_FRAME) {
/* NFI needs to be inversed !? */
tmpbuf[2] |= BLF_DLT_FLEXRAY_NFI;
}
if ((frheader.data & BLF_FLEXRAYRCVMSG_DATA_FLAG_STARTUP) == BLF_FLEXRAYRCVMSG_DATA_FLAG_STARTUP) {
tmpbuf[2] |= BLF_DLT_FLEXRAY_STFI;
}
tmpbuf[3] = 0x00ff & frheader.frameId;
tmpbuf[4] = (0xfe & frheader.payloadLength) | ((frheader.headerCrc1 & 0x0400) >> 10);
tmpbuf[5] = (0x03fc & frheader.headerCrc1) >> 2;
tmpbuf[6] = ((0x0003 & frheader.headerCrc1) << 6) | (0x3f & frheader.cycle);
ws_buffer_assure_space(params->buf, sizeof(tmpbuf) + payload_length_valid);
ws_buffer_append(params->buf, tmpbuf, sizeof(tmpbuf));
caplen = sizeof(tmpbuf) + payload_length_valid;
len = sizeof(tmpbuf) + payload_length;
if (payload_length_valid > 0 && !blf_read_bytes(params, data_start + frheadersize, ws_buffer_end_ptr(params->buf), payload_length_valid, err, err_info)) {
ws_debug("copying flexray payload failed");
return FALSE;
}
params->buf->first_free += payload_length_valid;
blf_init_rec(params, timestamp, WTAP_ENCAP_FLEXRAY, frheader.channelMask, caplen, len);
blf_add_direction_option(params, frheader.dir);
return TRUE;
}
static gboolean
blf_read_linmessage(blf_params_t *params, int *err, gchar **err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp) {
blf_linmessage_t linheader;
blf_linmessage_trailer_t lintrailer;
guint8 payload_length;
guint8 payload_length_valid;
guint caplen, len;
if (object_length < (data_start - block_start) + (int)sizeof(linheader)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: LIN_MESSAGE: not enough bytes for linmessage header in object");
ws_debug("not enough bytes for linmessage header in object");
return FALSE;
}
if (!blf_read_bytes(params, data_start, &linheader, sizeof(linheader), err, err_info)) {
ws_debug("not enough bytes for linmessage header in file");
return FALSE;
}
fix_endianness_blf_linmessage(&linheader);
if (linheader.dlc > 15) {
linheader.dlc = 15;
}
payload_length = linheader.dlc;
payload_length_valid = payload_length;
if (payload_length_valid > object_length - (data_start - block_start)) {
ws_debug("shortening LIN payload because buffer is too short!");
payload_length_valid = (guint8)(object_length - (data_start - block_start));
}
guint8 tmpbuf[8];
tmpbuf[0] = 1; /* message format rev = 1 */
tmpbuf[1] = 0; /* reserved */
tmpbuf[2] = 0; /* reserved */
tmpbuf[3] = 0; /* reserved */
tmpbuf[4] = (linheader.dlc << 4) | 0; /* dlc (4bit) | type (2bit) | checksum type (2bit) */
tmpbuf[5] = linheader.id;
tmpbuf[6] = 0; /* checksum */
tmpbuf[7] = 0; /* errors */
ws_buffer_assure_space(params->buf, sizeof(tmpbuf) + payload_length_valid);
ws_buffer_append(params->buf, tmpbuf, sizeof(tmpbuf));
caplen = sizeof(tmpbuf) + payload_length_valid;
len = sizeof(tmpbuf) + payload_length;
if (payload_length_valid > 0 && !blf_read_bytes(params, data_start + 4, ws_buffer_end_ptr(params->buf), payload_length_valid, err, err_info)) {
ws_debug("copying can payload failed");
return FALSE;
}
params->buf->first_free += payload_length_valid;
if (object_length < (data_start - block_start) + (int)sizeof(linheader) + payload_length_valid + (int)sizeof(lintrailer)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: LIN_MESSAGE: not enough bytes for linmessage trailer");
ws_debug("not enough bytes for linmessage trailer");
return FALSE;
}
if (!blf_read_bytes(params, data_start + sizeof(linheader) + payload_length_valid, &lintrailer, sizeof(lintrailer), err, err_info)) {
ws_debug("not enough bytes for linmessage trailer in file");
return FALSE;
}
fix_endianness_blf_linmessage_trailer(&lintrailer);
/* we are not using it right now since the CRC is too big to convert */
blf_init_rec(params, timestamp, WTAP_ENCAP_LIN, linheader.channel, caplen, len);
blf_add_direction_option(params, lintrailer.dir);
return TRUE;
}
static int
blf_read_apptextmessage(blf_params_t *params, int *err, gchar **err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp _U_) {
blf_apptext_t apptextheader;
if (object_length < (data_start - block_start) + (int)sizeof(apptextheader)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: APP_TEXT: not enough bytes for apptext header in object");
ws_debug("not enough bytes for apptext header in object");
return BLF_APPTEXT_FAILED;
}
if (!blf_read_bytes(params, data_start, &apptextheader, sizeof(apptextheader), err, err_info)) {
ws_debug("not enough bytes for apptext header in file");
return BLF_APPTEXT_FAILED;
}
fix_endianness_blf_apptext_header(&apptextheader);
/* Add an extra byte for a terminating '\0' */
gchar* text = g_try_malloc((gsize)apptextheader.textLength + 1);
if (!blf_read_bytes(params, data_start + sizeof(apptextheader), text, apptextheader.textLength, err, err_info)) {
ws_debug("not enough bytes for apptext text in file");
g_free(text);
return BLF_APPTEXT_FAILED;
}
text[apptextheader.textLength] = '\0'; /* Here's the '\0' */
switch (apptextheader.source) {
case BLF_APPTEXT_CHANNEL:
{
/* returns a NULL terminated array of NULL terminates strings */
gchar** tokens = g_strsplit_set(text, ";", -1);
if (tokens == NULL || tokens[0] == NULL || tokens[1] == NULL) {
if (tokens != NULL) {
g_strfreev(tokens);
}
g_free(text);
return BLF_APPTEXT_CHANNEL;
}
guint32 channel = (apptextheader.reservedAppText1 >> 8) & 0xff;
int pkt_encap;
switch ((apptextheader.reservedAppText1 >> 16) & 0xff) {
case BLF_BUSTYPE_CAN:
pkt_encap = WTAP_ENCAP_SOCKETCAN;
break;
case BLF_BUSTYPE_FLEXRAY:
pkt_encap = WTAP_ENCAP_FLEXRAY;
break;
case BLF_BUSTYPE_LIN:
pkt_encap = WTAP_ENCAP_LIN;
break;
case BLF_BUSTYPE_ETHERNET:
pkt_encap = WTAP_ENCAP_ETHERNET;
break;
case BLF_BUSTYPE_WLAN:
pkt_encap = WTAP_ENCAP_IEEE_802_11;
break;
default:
pkt_encap = 0xffffffff;
}
/* we use lookup to create interface, if not existing yet */
blf_lookup_interface(params, pkt_encap, channel, tokens[1]);
g_strfreev(tokens);
g_free(text);
return BLF_APPTEXT_CHANNEL;
break;
}
case BLF_APPTEXT_METADATA:
case BLF_APPTEXT_COMMENT:
if (apptextheader.textLength < 5) {
/* Arbitary lengt chosen */
g_free(text);
return BLF_APPTEXT_CHANNEL; /* Cheat - no block to write */
}
wtap_buffer_append_epdu_string(params->buf, EXP_PDU_TAG_DISSECTOR_NAME, "data-text-lines");
wtap_buffer_append_epdu_string(params->buf, EXP_PDU_TAG_COL_PROT_TEXT, "BLF App text");
if (apptextheader.source == BLF_APPTEXT_METADATA) {
wtap_buffer_append_epdu_string(params->buf, EXP_PDU_TAG_COL_INFO_TEXT, "Metadata");
} else {
wtap_buffer_append_epdu_string(params->buf, EXP_PDU_TAG_COL_INFO_TEXT, "Comment");
}
wtap_buffer_append_epdu_end(params->buf);
ws_buffer_assure_space(params->buf, apptextheader.textLength + 1);
ws_buffer_append(params->buf, text, apptextheader.textLength + 1);
/* We'll write this as a WS UPPER PDU packet with a text blob */
blf_init_rec(params, timestamp, WTAP_ENCAP_WIRESHARK_UPPER_PDU, 0, (guint32)ws_buffer_length(params->buf), (guint32)ws_buffer_length(params->buf));
g_free(text);
return apptextheader.source;
default:
return BLF_APPTEXT_CHANNEL; /* Cheat - no block to write */;
break;
}
return BLF_APPTEXT_CHANNEL; /* Cheat - no block to write */
}
static gboolean
blf_read_ethernet_status(blf_params_t* params, int* err, gchar** err_info, gint64 block_start, gint64 data_start, gint64 object_length, guint64 timestamp) {
blf_ethernet_status_t ethernet_status_header;
guint8 tmpbuf[16];
if (object_length < (data_start - block_start) + (int)sizeof(ethernet_status_header)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("blf: ETHERNET_STATUS: not enough bytes for apptext header in object");
ws_debug("not enough bytes for apptext header in object");
return FALSE;
}
if (!blf_read_bytes(params, data_start, ðernet_status_header, sizeof(ethernet_status_header), err, err_info)) {
ws_debug("not enough bytes for ethernet_status_header header in file");
return FALSE;
}
fix_endianness_blf_ethernet_status_header(ðernet_status_header);
tmpbuf[0] = (ethernet_status_header.channel & 0xff00) >> 8;
tmpbuf[1] = (ethernet_status_header.channel & 0x00ff);
tmpbuf[2] = (ethernet_status_header.flags & 0xff00) >> 8;
tmpbuf[3] = (ethernet_status_header.flags & 0x00ff);
tmpbuf[4] = (ethernet_status_header.linkStatus);
tmpbuf[5] = (ethernet_status_header.ethernetPhy);
tmpbuf[6] = (ethernet_status_header.duplex);
tmpbuf[7] = (ethernet_status_header.mdi);
tmpbuf[8] = (ethernet_status_header.connector);
tmpbuf[9] = (ethernet_status_header.clockMode);
tmpbuf[10] = (ethernet_status_header.pairs);
tmpbuf[11] = (ethernet_status_header.hardwareChannel);
tmpbuf[12] = (ethernet_status_header.bitrate & 0xff000000) >> 24;
tmpbuf[13] = (ethernet_status_header.bitrate & 0x00ff0000) >> 16;
tmpbuf[14] = (ethernet_status_header.bitrate & 0x0000ff00) >> 8;
tmpbuf[15] = (ethernet_status_header.bitrate & 0x000000ff);
wtap_buffer_append_epdu_string(params->buf, EXP_PDU_TAG_DISSECTOR_NAME, "blf-ethernetstatus-obj");
wtap_buffer_append_epdu_end(params->buf);
ws_buffer_assure_space(params->buf, sizeof(ethernet_status_header));
ws_buffer_append(params->buf, tmpbuf, (gsize)16);
/* We'll write this as a WS UPPER PDU packet with a data blob */
blf_init_rec(params, timestamp, WTAP_ENCAP_WIRESHARK_UPPER_PDU, ethernet_status_header.channel, (guint32)ws_buffer_length(params->buf), (guint32)ws_buffer_length(params->buf));
return TRUE;
}
static gboolean
blf_read_block(blf_params_t *params, gint64 start_pos, int *err, gchar **err_info) {
blf_blockheader_t header;
blf_logobjectheader_t logheader;
blf_logobjectheader2_t logheader2;
blf_logobjectheader3_t logheader3;
guint64 timestamp;
while (1) {
/* Find Object */
/* Resetting buffer */
params->buf->first_free = params->buf->start;
while (1) {
if (!blf_read_bytes_or_eof(params, start_pos, &header, sizeof header, err, err_info)) {
ws_debug("not enough bytes for block header or unsupported file");
if (*err == WTAP_ERR_SHORT_READ) {
/* we have found the end that is not a short read therefore. */
*err = 0;
g_free(*err_info);
}
return FALSE;
}
fix_endianness_blf_blockheader(&header);
if (memcmp(header.magic, blf_obj_magic, sizeof(blf_obj_magic))) {
ws_debug("object magic is not LOBJ (pos: 0x%" PRIx64 ")", start_pos);
} else {
break;
}
/* we are moving back and try again but 1 byte later */
/* TODO: better understand how this paddings works... */
start_pos++;
}
params->blf_data->start_of_last_obj = start_pos;
switch (header.header_type) {
case BLF_HEADER_TYPE_DEFAULT:
if (!blf_read_log_object_header(params, err, err_info, start_pos + sizeof(blf_blockheader_t), start_pos + header.header_length, &logheader)) {
return FALSE;
}
timestamp = blf_timestamp_to_ns(logheader.flags, logheader.object_timestamp) + params->blf_data->start_offset_ns;
break;
case BLF_HEADER_TYPE_2:
if (!blf_read_log_object_header2(params, err, err_info, start_pos + sizeof(blf_blockheader_t), start_pos + header.header_length, &logheader2)) {
return FALSE;
}
timestamp = blf_timestamp_to_ns(logheader2.flags, logheader2.object_timestamp) + params->blf_data->start_offset_ns;
break;
case BLF_HEADER_TYPE_3:
if (!blf_read_log_object_header3(params, err, err_info, start_pos + sizeof(blf_blockheader_t), start_pos + header.header_length, &logheader3)) {
return FALSE;
}
timestamp = blf_timestamp_to_ns(logheader3.flags, logheader3.object_timestamp) + params->blf_data->start_offset_ns;
break;
default:
*err = WTAP_ERR_UNSUPPORTED;
*err_info = ws_strdup_printf("blf: unknown header type %u", header.header_type);
ws_debug("unknown header type");
return FALSE;
}
/* already making sure that we start after this object next time. */
params->blf_data->current_real_seek_pos = start_pos + MAX(MAX(16, header.object_length), header.header_length);
switch (header.object_type) {
case BLF_OBJTYPE_LOG_CONTAINER:
*err = WTAP_ERR_UNSUPPORTED;
*err_info = ws_strdup_printf("blf: log container in log container not supported");
ws_debug("log container in log container not supported");
return FALSE;
break;
case BLF_OBJTYPE_ETHERNET_FRAME:
return blf_read_ethernetframe(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp);
break;
case BLF_OBJTYPE_ETHERNET_FRAME_EX:
return blf_read_ethernetframe_ext(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp);
break;
case BLF_OBJTYPE_WLAN_FRAME:
return blf_read_wlanframe(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp);
break;
case BLF_OBJTYPE_CAN_MESSAGE:
return blf_read_canmessage(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp, FALSE);
break;
case BLF_OBJTYPE_CAN_ERROR:
return blf_read_canerror(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp);
break;
case BLF_OBJTYPE_CAN_MESSAGE2:
return blf_read_canmessage(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp, TRUE);
break;
case BLF_OBJTYPE_CAN_ERROR_EXT:
return blf_read_canerrorext(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp);
break;
case BLF_OBJTYPE_CAN_FD_MESSAGE:
return blf_read_canfdmessage(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp);
break;
case BLF_OBJTYPE_CAN_FD_MESSAGE_64:
return blf_read_canfdmessage64(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp);
break;
case BLF_OBJTYPE_CAN_FD_ERROR_64:
return blf_read_canfderror64(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp);
break;
case BLF_OBJTYPE_FLEXRAY_DATA:
return blf_read_flexraydata(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp);
break;
case BLF_OBJTYPE_FLEXRAY_MESSAGE:
return blf_read_flexraymessage(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp);
break;
case BLF_OBJTYPE_FLEXRAY_RCVMESSAGE:
return blf_read_flexrayrcvmessageex(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp, FALSE);
break;
case BLF_OBJTYPE_FLEXRAY_RCVMESSAGE_EX:
return blf_read_flexrayrcvmessageex(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp, TRUE);
break;
case BLF_OBJTYPE_LIN_MESSAGE:
return blf_read_linmessage(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp);
break;
case BLF_OBJTYPE_APP_TEXT:
{
int result = blf_read_apptextmessage(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp);
switch (result) {
case BLF_APPTEXT_FAILED:
return FALSE;
case BLF_APPTEXT_METADATA:
return TRUE;
case BLF_APPTEXT_COMMENT:
return TRUE;
case BLF_APPTEXT_CHANNEL:
default:
/* we do not return since there is no packet to show here */
start_pos += MAX(MAX(16, header.object_length), header.header_length);
}
}
break;
case BLF_OBJTYPE_ETHERNET_STATUS:
return blf_read_ethernet_status(params, err, err_info, start_pos, start_pos + header.header_length, header.object_length, timestamp);
break;
default:
ws_debug("unknown object type 0x%04x", header.object_type);
start_pos += MAX(MAX(16, header.object_length), header.header_length);
}
}
return TRUE;
}
static gboolean blf_read(wtap *wth, wtap_rec *rec, Buffer *buf, int *err, gchar **err_info, gint64 *data_offset) {
blf_params_t blf_tmp;
blf_tmp.wth = wth;
blf_tmp.fh = wth->fh;
blf_tmp.rec = rec;
blf_tmp.buf = buf;
blf_tmp.blf_data = (blf_t *)wth->priv;
if (!blf_read_block(&blf_tmp, blf_tmp.blf_data->current_real_seek_pos, err, err_info)) {
return FALSE;
}
*data_offset = blf_tmp.blf_data->start_of_last_obj;
return TRUE;
}
static gboolean blf_seek_read(wtap *wth, gint64 seek_off, wtap_rec *rec, Buffer *buf, int *err, gchar **err_info) {
blf_params_t blf_tmp;
blf_tmp.wth = wth;
blf_tmp.fh = wth->random_fh;
blf_tmp.rec = rec;
blf_tmp.buf = buf;
blf_tmp.blf_data = (blf_t *)wth->priv;
if (!blf_read_block(&blf_tmp, seek_off, err, err_info)) {
ws_debug("couldn't read packet block (err=%d).", *err);
return FALSE;
}
return TRUE;
}
static void blf_close(wtap *wth) {
blf_t *blf = (blf_t *)wth->priv;
if (blf != NULL && blf->log_containers != NULL) {
for (guint i = 0; i < blf->log_containers->len; i++) {
blf_log_container_t *log_container = &g_array_index(blf->log_containers, blf_log_container_t, i);
if (log_container->real_data != NULL) {
g_free(log_container->real_data);
}
}
g_array_free(blf->log_containers, TRUE);
blf->log_containers = NULL;
}
if (blf != NULL && blf->channel_to_iface_ht != NULL) {
g_hash_table_destroy(blf->channel_to_iface_ht);
blf->channel_to_iface_ht = NULL;
}
/* TODO: do we need to reverse the wtap_add_idb? how? */
return;
}
wtap_open_return_val
blf_open(wtap *wth, int *err, gchar **err_info) {
blf_fileheader_t header;
blf_t *blf;
blf_params_t params;
ws_debug("opening file");
if (!wtap_read_bytes_or_eof(wth->fh, &header, sizeof header, err, err_info)) {
ws_debug("wtap_read_bytes_or_eof() failed, err = %d.", *err);
if (*err == 0 || *err == WTAP_ERR_SHORT_READ) {
/*
* Short read or EOF.
*
* We're reading this as part of an open, so
* the file is too short to be a blf file.
*/
*err = 0;
g_free(*err_info);
*err_info = NULL;
return WTAP_OPEN_NOT_MINE;
}
return WTAP_OPEN_ERROR;
}
fix_endianness_blf_fileheader(&header);
if (memcmp(header.magic, blf_magic, sizeof(blf_magic))) {
return WTAP_OPEN_NOT_MINE;
}
/* This seems to be an BLF! */
/* skip unknown part of header */
file_seek(wth->fh, header.header_length, SEEK_SET, err);
struct tm timestamp;
timestamp.tm_year = (header.start_date.year > 1970) ? header.start_date.year - 1900 : 70;
timestamp.tm_mon = header.start_date.month -1;
timestamp.tm_mday = header.start_date.day;
timestamp.tm_hour = header.start_date.hour;
timestamp.tm_min = header.start_date.mins;
timestamp.tm_sec = header.start_date.sec;
timestamp.tm_isdst = -1;
/* Prepare our private context. */
blf = g_new(blf_t, 1);
blf->log_containers = NULL;
blf->current_log_container = 0;
blf->current_real_seek_pos = 0;
blf->start_offset_ns = 1000 * 1000 * 1000 * (guint64)mktime(×tamp);
blf->start_offset_ns += 1000 * 1000 * header.start_date.ms;
blf->channel_to_iface_ht = g_hash_table_new_full(g_int64_hash, g_int64_equal, &blf_free_key, &blf_free_channel_to_iface_entry);
blf->next_interface_id = 0;
/* embed in params */
params.blf_data = blf;
params.buf = NULL;
params.fh = wth->fh;
params.rec = NULL;
params.wth = wth;
params.blf_data->current_real_seek_pos = 0;
/* lets check out the layout of all log containers */
blf_scan_file_for_logcontainers(¶ms);
wth->priv = (void *)blf;
wth->file_encap = WTAP_ENCAP_UNKNOWN;
wth->snapshot_length = 0;
wth->file_tsprec = WTAP_TSPREC_UNKNOWN;
wth->subtype_read = blf_read;
wth->subtype_seek_read = blf_seek_read;
wth->subtype_close = blf_close;
wth->file_type_subtype = blf_file_type_subtype;
return WTAP_OPEN_MINE;
}
/* Options for interface blocks. */
static const struct supported_option_type interface_block_options_supported[] = {
/* No comments, just an interface name. */
{ OPT_IDB_NAME, ONE_OPTION_SUPPORTED }
};
static const struct supported_block_type blf_blocks_supported[] = {
{ WTAP_BLOCK_PACKET, MULTIPLE_BLOCKS_SUPPORTED, NO_OPTIONS_SUPPORTED },
{ WTAP_BLOCK_IF_ID_AND_INFO, MULTIPLE_BLOCKS_SUPPORTED, OPTION_TYPES_SUPPORTED(interface_block_options_supported) },
};
static const struct file_type_subtype_info blf_info = {
"Vector Informatik Binary Logging Format (BLF) logfile", "blf", "blf", NULL,
FALSE, BLOCKS_SUPPORTED(blf_blocks_supported),
NULL, NULL, NULL
};
void register_blf(void)
{
blf_file_type_subtype = wtap_register_file_type_subtype(&blf_info);
/*
* Register name for backwards compatibility with the
* wtap_filetypes table in Lua.
*/
wtap_register_backwards_compatibility_lua_name("BLF", blf_file_type_subtype);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/ |
C/C++ | wireshark/wiretap/blf.h | /** @file
*
* Binary Log File (BLF) file format from Vector Informatik decoder
* for the Wiretap library.
*
* Copyright (c) 2021-2022 by Dr. Lars Voelker <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/*
* The following was used as a reference for the file format:
* https://bitbucket.org/tobylorenz/vector_blf
* The repo above includes multiple examples files as well.
*/
#ifndef __W_BLF_H__
#define __W_BLF_H__
#include "wtap.h"
#include <epan/value_string.h>
wtap_open_return_val blf_open(wtap *wth, int *err, gchar **err_info);
#define BLF_HEADER_TYPE_DEFAULT 1
#define BLF_HEADER_TYPE_2 2
#define BLF_HEADER_TYPE_3 3
#define BLF_COMPRESSION_NONE 0
#define BLF_COMPRESSION_ZLIB 2
#define BLF_TIMESTAMP_RESOLUTION_10US 1
#define BLF_TIMESTAMP_RESOLUTION_1NS 2
typedef struct blf_date {
guint16 year;
guint16 month;
guint16 dayofweek;
guint16 day;
guint16 hour;
guint16 mins;
guint16 sec;
guint16 ms;
} blf_date_t;
/* BLF Header */
typedef struct blf_fileheader {
guint8 magic[4];
guint32 header_length;
guint8 applications[4];
guint8 api[4];
guint64 len_compressed;
guint64 len_uncompressed;
guint32 obj_count;
guint32 obj_read;
blf_date_t start_date;
blf_date_t end_date;
guint32 length3;
} blf_fileheader_t;
typedef struct blf_blockheader {
guint8 magic[4];
guint16 header_length; /* length of header starting with magic */
guint16 header_type; /* header format ? */
guint32 object_length; /* complete length including header */
guint32 object_type;
} blf_blockheader_t;
typedef struct blf_logcontainerheader {
guint16 compression_method; /* 0 uncompressed, 2 zlib */
guint16 res1;
guint32 res2;
guint32 uncompressed_size;
guint32 res4;
} blf_logcontainerheader_t;
typedef struct blf_logobjectheader {
guint32 flags;
guint16 client_index;
guint16 object_version;
guint64 object_timestamp;
} blf_logobjectheader_t;
#define BLF_TS_STATUS_ORIG_TS_VALID 0x01
#define BLF_TS_STATUS_SW_TS 0x02
#define BLF_TS_STATUS_PROTO_SPECIFIC 0x10
typedef struct blf_logobjectheader2 {
guint32 flags;
guint8 timestamp_status;
guint8 res1;
guint16 object_version;
guint64 object_timestamp;
guint64 original_timestamp;
} blf_logobjectheader2_t;
typedef struct blf_logobjectheader3 {
guint32 flags;
guint16 static_size;
guint16 object_version;
guint64 object_timestamp;
} blf_logobjectheader3_t;
#define BLF_DIR_RX 0
#define BLF_DIR_TX 1
#define BLF_DIR_TX_RQ 2
typedef struct blf_ethernetframeheader {
guint8 src_addr[6];
guint16 channel;
guint8 dst_addr[6];
guint16 direction;
guint16 ethtype;
guint16 tpid;
guint16 tci;
guint16 payloadlength;
guint64 res;
} blf_ethernetframeheader_t;
typedef struct blf_ethernetframeheader_ex {
guint16 struct_length;
guint16 flags;
guint16 channel;
guint16 hw_channel;
guint64 frame_duration;
guint32 frame_checksum;
guint16 direction;
guint16 frame_length;
guint32 frame_handle;
guint32 error;
} blf_ethernetframeheader_ex_t;
typedef struct blf_wlanframeheader {
guint16 channel;
guint16 flags;
guint8 direction;
guint8 radio_channel;
guint16 signal_strength;
guint16 signal_quality;
guint16 frame_length;
guint32 res;
} blf_wlanframeheader_t;
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/CanMessage.h */
/* shared for CAN message and CAN message2 and CANFD message */
#define BLF_CANMESSAGE_FLAG_TX 0x01
#define BLF_CANMESSAGE_FLAG_NERR 0x20
#define BLF_CANMESSAGE_FLAG_WU 0x40
#define BLF_CANMESSAGE_FLAG_RTR 0x80
/* shared for CAN message and CAN message2*/
typedef struct blf_canmessage {
guint16 channel;
guint8 flags;
guint8 dlc;
guint32 id;
} blf_canmessage_t;
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/CanMessage2.h */
typedef struct blf_canmessage2_trailer {
guint32 frameLength_in_ns;
guint8 bitCount;
guint8 reserved1;
guint16 reserved2;
} blf_canmessage2_trailer_t;
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/CanFdMessage.h */
/* EDL 0: CAN, 1: CAN-FD*/
#define BLF_CANFDMESSAGE_CANFDFLAG_EDL 0x01
#define BLF_CANFDMESSAGE_CANFDFLAG_BRS 0x02
#define BLF_CANFDMESSAGE_CANFDFLAG_ESI 0x04
typedef struct blf_canfdmessage {
guint16 channel;
guint8 flags;
guint8 dlc;
guint32 id;
guint32 frameLength_in_ns;
guint8 arbitration_bit_count;
guint8 canfdflags;
guint8 validDataBytes;
guint8 reservedCanFdMessage1;
guint32 reservedCanFdMessage2;
/* DATA */
/* guint32 reservedCanFdMessage3 */
} blf_canfdmessage_t;
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/CanFdMessage64.h */
#define BLF_CANFDMESSAGE64_FLAG_NERR 0x000004
#define BLF_CANFDMESSAGE64_FLAG_HIGH_VOLT_WAKE_UP 0x000008
#define BLF_CANFDMESSAGE64_FLAG_REMOTE_FRAME 0x000010
#define BLF_CANFDMESSAGE64_FLAG_TX_ACK 0x000040
#define BLF_CANFDMESSAGE64_FLAG_TX_REQ 0x000080
#define BLF_CANFDMESSAGE64_FLAG_SRR 0x000200
#define BLF_CANFDMESSAGE64_FLAG_R0 0x000400
#define BLF_CANFDMESSAGE64_FLAG_R1 0x000800
/* EDL 0: CAN, 1: CAN-FD*/
#define BLF_CANFDMESSAGE64_FLAG_EDL 0x001000
#define BLF_CANFDMESSAGE64_FLAG_BRS 0x002000
#define BLF_CANFDMESSAGE64_FLAG_ESI 0x004000
#define BLF_CANFDMESSAGE64_FLAG_BURST 0x200000
typedef struct blf_canfdmessage64 {
guint8 channel;
guint8 dlc;
guint8 validDataBytes;
guint8 txCount;
guint32 id;
guint32 frameLength_in_ns;
guint32 flags;
guint32 btrCfgArb;
guint32 btrCfgData;
guint32 timeOffsetBrsNs;
guint32 timeOffsetCrcDelNs;
guint16 bitCount;
guint8 dir;
guint8 extDataOffset;
guint32 crc;
} blf_canfdmessage64_t;
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/CanErrorFrame.h */
typedef struct blf_canerror {
guint16 channel;
guint16 length;
} blf_canerror_t;
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/CanErrorFrameExt.h */
#define BLF_CANERROREXT_FLAG_SJA 0x01
#define BLF_CANERROREXT_FLAG_CANCORE 0x02
#define BLF_CANERROREXT_EXTECC_TX 0x1000
#define BLF_CANERROREXT_EXTECC_NOT_ACK 0x2000
#define BLF_CANERROREXT_ECC_MEANING_BIT_ERROR 0x0
#define BLF_CANERROREXT_ECC_MEANING_FORM_ERROR 0x1
#define BLF_CANERROREXT_ECC_MEANING_STUFF_ERROR 0x2
#define BLF_CANERROREXT_ECC_MEANING_OTHER_ERROR 0x3
#define BLF_CANERROREXT_ECC_MEANING_CRC_ERROR 0x4
#define BLF_CANERROREXT_ECC_MEANING_ACKDEL_ERROR 0x5
#define BLF_CANERROREXT_ECC_MEANING_OTHER_ERROR2 0x6
#define BLF_CANERROREXT_ECC_MEANING_NACK_ERROR 0x7
#define BLF_CANERROREXT_ECC_MEANING_OVERLOAD 0x8
#define BLF_CANERROREXT_ECC_FDF_BIT_ERROR 0x9
typedef struct blf_canerrorext {
guint16 channel;
guint16 length;
guint32 flags;
guint8 ecc;
guint8 position;
guint8 dlc;
guint8 reserved1;
guint32 frameLength_in_ns;
guint32 id;
guint16 errorCodeExt;
guint16 reserved2;
} blf_canerrorext_t;
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/CanFdErrorFrame64.h */
typedef struct blf_canfderror64 {
guint8 channel;
guint8 dlc;
guint8 validDataBytes;
guint8 ecc;
guint16 flags;
guint16 errorCodeExt;
guint16 extFlags;
guint8 extDataOffset;
guint8 reserved1;
guint32 id;
guint32 frameLength_in_ns;
guint32 btrCfgArb;
guint32 btrCfgData;
guint32 timeOffsetBrsNs;
guint32 timeOffsetCrcDelNs;
guint32 crc;
guint16 errorPosition;
guint16 reserved2;
} blf_canfderror64_t;
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/FlexRayData.h */
#define BLF_FLEXRAYDATA_FRAME 0x01
#define BLF_FLEXRAYDATA_CHANNEL_B 0x80
typedef struct blf_flexraydata {
guint16 channel;
guint8 mux;
guint8 len;
guint16 messageId;
guint16 crc;
guint8 dir;
guint8 reservedFlexRayData1;
guint16 reservedFlexRayData2;
} blf_flexraydata_t;
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/FlexRayV6Message.h */
#define BLF_FLEXRAYMESSAGE_DIR_RX 0x01
#define BLF_FLEXRAYMESSAGE_DIR_TX 0x02
#define BLF_FLEXRAYMESSAGE_DIR_TX_REQ 0x04
#define BLF_FLEXRAYMESSAGE_STATE_PPI 0x01
#define BLF_FLEXRAYMESSAGE_STATE_SFI 0x02
#define BLF_FLEXRAYMESSAGE_STATE_RES_BIT2 0x04
#define BLF_FLEXRAYMESSAGE_STATE_NFI 0x08
#define BLF_FLEXRAYMESSAGE_STATE_STFI 0x10
#define BLF_FLEXRAYMESSAGE_STATE_FORMAT 0xe0
#define BLF_FLEXRAYMESSAGE_HEADER_BIT_NM 0x01
#define BLF_FLEXRAYMESSAGE_HEADER_BIT_SYNC 0x02
#define BLF_FLEXRAYMESSAGE_HEADER_BIT_RES 0x04
#define BLF_DLT_FLEXRAY_STFI 0x08
#define BLF_DLT_FLEXRAY_SFI 0x10
#define BLF_DLT_FLEXRAY_NFI 0x20
#define BLF_DLT_FLEXRAY_PPI 0x40
typedef struct blf_flexraymessage {
guint16 channel;
guint8 dir; /* Flags: 0 RX, 1 TX, 2 TX Req, 3 internal, 4 internal*/
guint8 lowTime;
guint32 fpgaTick;
guint32 fpgaTickOverflow;
guint32 clientIndexFlexRayV6Message;
guint32 clusterTime;
guint16 frameId;
guint16 headerCrc;
guint16 frameState;
guint8 length;
guint8 cycle;
guint8 headerBitMask;
guint8 reservedFlexRayV6Message1;
guint16 reservedFlexRayV6Message2;
} blf_flexraymessage_t;
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/FlexRayVFrReceiveMsg.h */
#define BLF_FLEXRAYRCVMSG_DIR_RX 0x01
#define BLF_FLEXRAYRCVMSG_DIR_TX 0x02
#define BLF_FLEXRAYRCVMSG_DIR_TX_REQ 0x04
#define BLF_FLEXRAYRCVMSG_CHANNELMASK_RES 0x00
#define BLF_FLEXRAYRCVMSG_CHANNELMASK_A 0x01
#define BLF_FLEXRAYRCVMSG_CHANNELMASK_B 0x02
#define BLF_FLEXRAYRCVMSG_CHANNELMASK_AB 0x03
#define BLF_FLEXRAYRCVMSG_DATA_FLAG_NULL_FRAME 0x00000001
#define BLF_FLEXRAYRCVMSG_DATA_FLAG_VALID_DATA 0x00000002
#define BLF_FLEXRAYRCVMSG_DATA_FLAG_SYNC 0x00000004
#define BLF_FLEXRAYRCVMSG_DATA_FLAG_STARTUP 0x00000008
#define BLF_FLEXRAYRCVMSG_DATA_FLAG_PAYLOAD_PREAM 0x00000010
#define BLF_FLEXRAYRCVMSG_DATA_FLAG_RES_20 0x00000020
#define BLF_FLEXRAYRCVMSG_DATA_FLAG_ERROR 0x00000040
#define BLF_FLEXRAYRCVMSG_DATA_FLAG_RES_80 0x00000080
typedef struct blf_flexrayrcvmessage {
guint16 channel;
guint16 version;
guint16 channelMask; /* 0 res, 1 A, 2 B, 3 A+B */
guint16 dir; /* 0 RX, 1 TX, 2 TX Req, 3 internal, 4 internal*/ /* high byte reserved! */
guint32 clientIndex;
guint32 clusterNo;
guint16 frameId;
guint16 headerCrc1;
guint16 headerCrc2;
guint16 payloadLength;
guint16 payloadLengthValid;
guint16 cycle; /* high byte reserved! */
guint32 tag;
guint32 data;
guint32 frameFlags;
guint32 appParameter;
/* if ext, skip 40 bytes */
/* payload bytes */
/* guint16 res3 */
/* guint32 res4 */
} blf_flexrayrcvmessage_t;
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/FlexRayVFrReceiveMsgEx.h */
/* defines see above BLF_FLEXRAYRCVMSG_* */
typedef struct blf_flexrayrcvmessageex {
guint16 channel;
guint16 version;
guint16 channelMask; /* 0 res, 1 A, 2 B, 3 A+B */
guint16 dir; /* 0 RX, 1 TX, 2 TX Req, 3 internal, 4 internal*/
guint32 clientIndex;
guint32 clusterNo;
guint16 frameId;
guint16 headerCrc1;
guint16 headerCrc2;
guint16 payloadLength;
guint16 payloadLengthValid;
guint16 cycle;
guint32 tag;
guint32 data;
guint32 frameFlags;
guint32 appParameter;
guint32 frameCRC;
guint32 frameLengthInNs;
guint16 frameId1;
guint16 pduOffset;
guint16 blfLogMask;
guint16 res1;
guint32 res2;
guint32 res3;
guint32 res4;
guint32 res5;
guint32 res6;
guint32 res7;
/* payload bytes */
} blf_flexrayrcvmessageex_t;
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/LinMessage.h */
typedef struct blf_linmessage {
guint16 channel;
guint8 id;
guint8 dlc;
} blf_linmessage_t;
typedef struct blf_linmessage_trailer {
guint8 fsmId;
guint8 fsmState;
guint8 headerTime;
guint8 fullTime;
guint16 crc;
guint8 dir; /* 0 RX, 1 TX Receipt, 2 TX Req */
guint8 res1;
/* This field is optional and skipping does not hurt us.
guint32 res2;
*/
} blf_linmessage_trailer_t;
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/AppText.h */
typedef struct blf_apptext {
guint32 source;
guint32 reservedAppText1;
guint32 textLength;
guint32 reservedAppText2;
} blf_apptext_t;
#define BLF_APPTEXT_COMMENT 0x00000000
#define BLF_APPTEXT_CHANNEL 0x00000001
#define BLF_APPTEXT_METADATA 0x00000002
#define BLF_APPTEXT_FAILED 0x000000FF
#define BLF_BUSTYPE_CAN 1
#define BLF_BUSTYPE_LIN 5
#define BLF_BUSTYPE_MOST 6
#define BLF_BUSTYPE_FLEXRAY 7
#define BLF_BUSTYPE_J1708 9
#define BLF_BUSTYPE_ETHERNET 11
#define BLF_BUSTYPE_WLAN 13
#define BLF_BUSTYPE_AFDX 14
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/EthernetStatus.h */
typedef struct blf_ethernet_status {
uint16_t channel;
uint16_t flags;
uint8_t linkStatus;
uint8_t ethernetPhy;
uint8_t duplex;
uint8_t mdi;
uint8_t connector;
uint8_t clockMode;
uint8_t pairs;
uint8_t hardwareChannel;
uint32_t bitrate;
} blf_ethernet_status_t;
/* see https://bitbucket.org/tobylorenz/vector_blf/src/master/src/Vector/BLF/ObjectHeaderBase.h */
#define BLF_OBJTYPE_UNKNOWN 0
#define BLF_OBJTYPE_CAN_MESSAGE 1
#define BLF_OBJTYPE_CAN_ERROR 2
#define BLF_OBJTYPE_CAN_OVERLOAD 3
#define BLF_OBJTYPE_CAN_STATISTIC 4
#define BLF_OBJTYPE_APP_TRIGGER 5
#define BLF_OBJTYPE_ENV_INTEGER 6
#define BLF_OBJTYPE_ENV_DOUBLE 7
#define BLF_OBJTYPE_ENV_STRING 8
#define BLF_OBJTYPE_ENV_DATA 9
#define BLF_OBJTYPE_LOG_CONTAINER 10
#define BLF_OBJTYPE_LIN_MESSAGE 11
#define BLF_OBJTYPE_LIN_CRC_ERROR 12
#define BLF_OBJTYPE_LIN_DLC_INFO 13
#define BLF_OBJTYPE_LIN_RCV_ERROR 14
#define BLF_OBJTYPE_LIN_SND_ERROR 15
#define BLF_OBJTYPE_LIN_SLV_TIMEOUT 16
#define BLF_OBJTYPE_LIN_SCHED_MODCH 17
#define BLF_OBJTYPE_LIN_SYN_ERROR 18
#define BLF_OBJTYPE_LIN_BAUDRATE 19
#define BLF_OBJTYPE_LIN_SLEEP 20
#define BLF_OBJTYPE_LIN_WAKEUP 21
#define BLF_OBJTYPE_MOST_SPY 22
#define BLF_OBJTYPE_MOST_CTRL 23
#define BLF_OBJTYPE_MOST_LIGHTLOCK 24
#define BLF_OBJTYPE_MOST_STATISTIC 25
#define BLF_OBJTYPE_FLEXRAY_DATA 29
#define BLF_OBJTYPE_FLEXRAY_SYNC 30
#define BLF_OBJTYPE_CAN_DRIVER_ERROR 31
#define BLF_OBJTYPE_MOST_PKT 32
#define BLF_OBJTYPE_MOST_PKT2 33
#define BLF_OBJTYPE_MOST_HWMODE 34
#define BLF_OBJTYPE_MOST_REG 35
#define BLF_OBJTYPE_MOST_GENREG 36
#define BLF_OBJTYPE_MOST_NETSTATE 37
#define BLF_OBJTYPE_MOST_DATALOST 38
#define BLF_OBJTYPE_MOST_TRIGGER 39
#define BLF_OBJTYPE_FLEXRAY_CYCLE 40
#define BLF_OBJTYPE_FLEXRAY_MESSAGE 41
#define BLF_OBJTYPE_LIN_CHECKSUM_INFO 42
#define BLF_OBJTYPE_LIN_SPIKE_EVENT 43
#define BLF_OBJTYPE_CAN_DRIVER_SYNC 44
#define BLF_OBJTYPE_FLEXRAY_STATUS 45
#define BLF_OBJTYPE_GPS_EVENT 46
#define BLF_OBJTYPE_FLEXRAY_ERROR 47
#define BLF_OBJTYPE_FLEXRAY_STATUS2 48
#define BLF_OBJTYPE_FLEXRAY_STARTCYCLE 49
#define BLF_OBJTYPE_FLEXRAY_RCVMESSAGE 50
#define BLF_OBJTYPE_REALTIMECLOCK 51
#define BLF_OBJTYPE_LIN_STATISTIC 54
#define BLF_OBJTYPE_J1708_MESSAGE 55
#define BLF_OBJTYPE_J1708_VIRTUAL_MSG 56
#define BLF_OBJTYPE_LIN_MESSAGE2 57
#define BLF_OBJTYPE_LIN_SND_ERROR2 58
#define BLF_OBJTYPE_LIN_SYN_ERROR2 59
#define BLF_OBJTYPE_LIN_CRC_ERROR2 60
#define BLF_OBJTYPE_LIN_RCV_ERROR2 61
#define BLF_OBJTYPE_LIN_WAKEUP2 62
#define BLF_OBJTYPE_LIN_SPIKE_EVENT2 63
#define BLF_OBJTYPE_LIN_LONG_DOM_SIG 64
#define BLF_OBJTYPE_APP_TEXT 65
#define BLF_OBJTYPE_FLEXRAY_RCVMESSAGE_EX 66
#define BLF_OBJTYPE_MOST_STATISTICEX 67
#define BLF_OBJTYPE_MOST_TXLIGHT 68
#define BLF_OBJTYPE_MOST_ALLOCTAB 69
#define BLF_OBJTYPE_MOST_STRESS 70
#define BLF_OBJTYPE_ETHERNET_FRAME 71
#define BLF_OBJTYPE_SYS_VARIABLE 72
#define BLF_OBJTYPE_CAN_ERROR_EXT 73
#define BLF_OBJTYPE_CAN_DRIVER_ERROR_EXT 74
#define BLF_OBJTYPE_LIN_LONG_DOM_SIG2 75
#define BLF_OBJTYPE_MOST_150_MESSAGE 76
#define BLF_OBJTYPE_MOST_150_PKT 77
#define BLF_OBJTYPE_MOST_ETHERNET_PKT 78
#define BLF_OBJTYPE_MOST_150_MESSAGE_FRAGMENT 79
#define BLF_OBJTYPE_MOST_150_PKT_FRAGMENT 80
#define BLF_OBJTYPE_MOST_ETHERNET_PKT_FRAGMENT 81
#define BLF_OBJTYPE_MOST_SYSTEM_EVENT 82
#define BLF_OBJTYPE_MOST_150_ALLOCTAB 83
#define BLF_OBJTYPE_MOST_50_MESSAGE 84
#define BLF_OBJTYPE_MOST_50_PKT 85
#define BLF_OBJTYPE_CAN_MESSAGE2 86
#define BLF_OBJTYPE_LIN_UNEXPECTED_WAKEUP 87
#define BLF_OBJTYPE_LIN_SHORT_OR_SLOW_RESPONSE 88
#define BLF_OBJTYPE_LIN_DISTURBANCE_EVENT 89
#define BLF_OBJTYPE_SERIAL_EVENT 90
#define BLF_OBJTYPE_OVERRUN_ERROR 91
#define BLF_OBJTYPE_EVENT_COMMENT 92
#define BLF_OBJTYPE_WLAN_FRAME 93
#define BLF_OBJTYPE_WLAN_STATISTIC 94
#define BLF_OBJTYPE_MOST_ECL 95
#define BLF_OBJTYPE_GLOBAL_MARKER 96
#define BLF_OBJTYPE_AFDX_FRAME 97
#define BLF_OBJTYPE_AFDX_STATISTIC 98
#define BLF_OBJTYPE_KLINE_STATUSEVENT 99
#define BLF_OBJTYPE_CAN_FD_MESSAGE 100
#define BLF_OBJTYPE_CAN_FD_MESSAGE_64 101
#define BLF_OBJTYPE_ETHERNET_RX_ERROR 102
#define BLF_OBJTYPE_ETHERNET_STATUS 103
#define BLF_OBJTYPE_CAN_FD_ERROR_64 104
#define BLF_OBJTYPE_AFDX_STATUS 106
#define BLF_OBJTYPE_AFDX_BUS_STATISTIC 107
#define BLF_OBJTYPE_AFDX_ERROR_EVENT 109
#define BLF_OBJTYPE_A429_ERROR 110
#define BLF_OBJTYPE_A429_STATUS 111
#define BLF_OBJTYPE_A429_BUS_STATISTIC 112
#define BLF_OBJTYPE_A429_MESSAGE 113
#define BLF_OBJTYPE_ETHERNET_STATISTIC 114
#define BLF_OBJTYPE_TEST_STRUCTURE 118
#define BLF_OBJTYPE_DIAG_REQUEST_INTERPRETATION 119
#define BLF_OBJTYPE_ETHERNET_FRAME_EX 120
#define BLF_OBJTYPE_ETHERNET_FRAME_FORWARDED 121
#define BLF_OBJTYPE_ETHERNET_ERROR_EX 122
#define BLF_OBJTYPE_ETHERNET_ERROR_FORWARDED 123
#define BLF_OBJTYPE_FUNCTION_BUS 124
#define BLF_OBJTYPE_DATA_LOST_BEGIN 125
#define BLF_OBJTYPE_DATA_LOST_END 126
#define BLF_OBJTYPE_WATER_MARK_EVENT 127
#define BLF_OBJTYPE_TRIGGER_CONDITION 128
#define BLF_OBJTYPE_CAN_SETTING_CHANGED 129
#define BLF_OBJTYPE_DISTRIBUTED_OBJECT_MEMBER 130
#define BLF_OBJTYPE_ATTRIBUTE_EVENT 131
#endif
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/ |
C | wireshark/wiretap/btsnoop.c | /* btsnoop.c
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <string.h>
#include "wtap-int.h"
#include "file_wrappers.h"
#include "btsnoop.h"
/*
* Symbian's btsnoop format is derived from Sun's snoop format.
* See RFC 1761 for a description of the "snoop" file format.
* See
*
* https://gitlab.com/wireshark/wireshark/uploads/6d44fa94c164b58516e8577f44a6ccdc/btmodified_rfc1761.txt
*
* for a description of the btsnoop format.
*/
/* Magic number in "btsnoop" files. */
static const char btsnoop_magic[] = {
'b', 't', 's', 'n', 'o', 'o', 'p', '\0'
};
/* "btsnoop" file header (minus magic number). */
struct btsnoop_hdr {
guint32 version; /* version number (should be 1) */
guint32 datalink; /* datalink type */
};
/* "btsnoop" record header. */
struct btsnooprec_hdr {
guint32 orig_len; /* actual length of packet */
guint32 incl_len; /* number of octets captured in file */
guint32 flags; /* packet flags */
guint32 cum_drops; /* cumulative number of dropped packets */
gint64 ts_usec; /* timestamp microseconds */
};
/* H1 is unframed data with the packet type encoded in the flags field of capture header */
/* It can be used for any datalink by placing logging above the datalink layer of HCI */
#define KHciLoggerDatalinkTypeH1 1001
/* H4 is the serial HCI with packet type encoded in the first byte of each packet */
#define KHciLoggerDatalinkTypeH4 1002
/* CSR's PPP derived bluecore serial protocol - in practice we log in H1 format after deframing */
#define KHciLoggerDatalinkTypeBCSP 1003
/* H5 is the official three wire serial protocol derived from BCSP*/
#define KHciLoggerDatalinkTypeH5 1004
/* Linux Monitor */
#define KHciLoggerDatalinkLinuxMonitor 2001
/* BlueZ 5 Simulator */
#define KHciLoggerDatalinkBlueZ5Simulator 2002
#define KHciLoggerHostToController 0
#define KHciLoggerControllerToHost 0x00000001
#define KHciLoggerACLDataFrame 0
#define KHciLoggerCommandOrEvent 0x00000002
static const gint64 KUnixTimeBase = G_GINT64_CONSTANT(0x00dcddb30f2f8000); /* offset from symbian - unix time */
static gboolean btsnoop_read(wtap *wth, wtap_rec *rec, Buffer *buf,
int *err, gchar **err_info, gint64 *offset);
static gboolean btsnoop_seek_read(wtap *wth, gint64 seek_off,
wtap_rec *rec, Buffer *buf, int *err, gchar **err_info);
static gboolean btsnoop_read_record(wtap *wth, FILE_T fh,
wtap_rec *rec, Buffer *buf, int *err, gchar **err_info);
static int btsnoop_file_type_subtype = -1;
void register_btsnoop(void);
wtap_open_return_val btsnoop_open(wtap *wth, int *err, gchar **err_info)
{
char magic[sizeof btsnoop_magic];
struct btsnoop_hdr hdr;
int file_encap=WTAP_ENCAP_UNKNOWN;
/* Read in the string that should be at the start of a "btsnoop" file */
if (!wtap_read_bytes(wth->fh, magic, sizeof magic, err, err_info)) {
if (*err != WTAP_ERR_SHORT_READ)
return WTAP_OPEN_ERROR;
return WTAP_OPEN_NOT_MINE;
}
if (memcmp(magic, btsnoop_magic, sizeof btsnoop_magic) != 0) {
return WTAP_OPEN_NOT_MINE;
}
/* Read the rest of the header. */
if (!wtap_read_bytes(wth->fh, &hdr, sizeof hdr, err, err_info))
return WTAP_OPEN_ERROR;
/*
* Make sure it's a version we support.
*/
hdr.version = g_ntohl(hdr.version);
if (hdr.version != 1) {
*err = WTAP_ERR_UNSUPPORTED;
*err_info = ws_strdup_printf("btsnoop: version %u unsupported", hdr.version);
return WTAP_OPEN_ERROR;
}
hdr.datalink = g_ntohl(hdr.datalink);
switch (hdr.datalink) {
case KHciLoggerDatalinkTypeH1:
file_encap=WTAP_ENCAP_BLUETOOTH_HCI;
break;
case KHciLoggerDatalinkTypeH4:
file_encap=WTAP_ENCAP_BLUETOOTH_H4_WITH_PHDR;
break;
case KHciLoggerDatalinkTypeBCSP:
*err = WTAP_ERR_UNSUPPORTED;
*err_info = g_strdup("btsnoop: BCSP capture logs unsupported");
return WTAP_OPEN_ERROR;
case KHciLoggerDatalinkTypeH5:
*err = WTAP_ERR_UNSUPPORTED;
*err_info = g_strdup("btsnoop: H5 capture logs unsupported");
return WTAP_OPEN_ERROR;
case KHciLoggerDatalinkLinuxMonitor:
file_encap=WTAP_ENCAP_BLUETOOTH_LINUX_MONITOR;
break;
case KHciLoggerDatalinkBlueZ5Simulator:
*err = WTAP_ERR_UNSUPPORTED;
*err_info = g_strdup("btsnoop: BlueZ 5 Simulator capture logs unsupported");
return WTAP_OPEN_ERROR;
default:
*err = WTAP_ERR_UNSUPPORTED;
*err_info = ws_strdup_printf("btsnoop: datalink type %u unknown or unsupported", hdr.datalink);
return WTAP_OPEN_ERROR;
}
wth->subtype_read = btsnoop_read;
wth->subtype_seek_read = btsnoop_seek_read;
wth->file_encap = file_encap;
wth->snapshot_length = 0; /* not available in header */
wth->file_tsprec = WTAP_TSPREC_USEC;
wth->file_type_subtype = btsnoop_file_type_subtype;
/*
* Add an IDB; we don't know how many interfaces were
* involved, so we just say one interface, about which
* we only know the link-layer type, snapshot length,
* and time stamp resolution.
*/
wtap_add_generated_idb(wth);
return WTAP_OPEN_MINE;
}
static gboolean btsnoop_read(wtap *wth, wtap_rec *rec, Buffer *buf,
int *err, gchar **err_info, gint64 *offset)
{
*offset = file_tell(wth->fh);
return btsnoop_read_record(wth, wth->fh, rec, buf, err, err_info);
}
static gboolean btsnoop_seek_read(wtap *wth, gint64 seek_off,
wtap_rec *rec, Buffer *buf, int *err, gchar **err_info)
{
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
return FALSE;
return btsnoop_read_record(wth, wth->random_fh, rec, buf, err, err_info);
}
static gboolean btsnoop_read_record(wtap *wth, FILE_T fh,
wtap_rec *rec, Buffer *buf, int *err, gchar **err_info)
{
struct btsnooprec_hdr hdr;
guint32 packet_size;
guint32 flags;
guint32 orig_size;
gint64 ts;
/* Read record header. */
if (!wtap_read_bytes_or_eof(fh, &hdr, sizeof hdr, err, err_info))
return FALSE;
packet_size = g_ntohl(hdr.incl_len);
orig_size = g_ntohl(hdr.orig_len);
flags = g_ntohl(hdr.flags);
if (packet_size > WTAP_MAX_PACKET_SIZE_STANDARD) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = ws_strdup_printf("btsnoop: File has %u-byte packet, bigger than maximum of %u",
packet_size, WTAP_MAX_PACKET_SIZE_STANDARD);
return FALSE;
}
ts = GINT64_FROM_BE(hdr.ts_usec);
ts -= KUnixTimeBase;
rec->rec_type = REC_TYPE_PACKET;
rec->block = wtap_block_create(WTAP_BLOCK_PACKET);
rec->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
rec->ts.secs = (guint)(ts / 1000000);
rec->ts.nsecs = (guint)((ts % 1000000) * 1000);
rec->rec_header.packet_header.caplen = packet_size;
rec->rec_header.packet_header.len = orig_size;
if(wth->file_encap == WTAP_ENCAP_BLUETOOTH_H4_WITH_PHDR)
{
rec->rec_header.packet_header.pseudo_header.p2p.sent = (flags & KHciLoggerControllerToHost) ? FALSE : TRUE;
} else if(wth->file_encap == WTAP_ENCAP_BLUETOOTH_HCI) {
rec->rec_header.packet_header.pseudo_header.bthci.sent = (flags & KHciLoggerControllerToHost) ? FALSE : TRUE;
if(flags & KHciLoggerCommandOrEvent)
{
if(rec->rec_header.packet_header.pseudo_header.bthci.sent)
{
rec->rec_header.packet_header.pseudo_header.bthci.channel = BTHCI_CHANNEL_COMMAND;
}
else
{
rec->rec_header.packet_header.pseudo_header.bthci.channel = BTHCI_CHANNEL_EVENT;
}
}
else
{
rec->rec_header.packet_header.pseudo_header.bthci.channel = BTHCI_CHANNEL_ACL;
}
} else if (wth->file_encap == WTAP_ENCAP_BLUETOOTH_LINUX_MONITOR) {
rec->rec_header.packet_header.pseudo_header.btmon.opcode = flags & 0xFFFF;
rec->rec_header.packet_header.pseudo_header.btmon.adapter_id = flags >> 16;
}
/* Read packet data. */
return wtap_read_packet_bytes(fh, buf, rec->rec_header.packet_header.caplen, err, err_info);
}
/* Returns 0 if we could write the specified encapsulation type,
an error indication otherwise. */
static int btsnoop_dump_can_write_encap(int encap)
{
/* Per-packet encapsulations aren't supported. */
if (encap == WTAP_ENCAP_PER_PACKET)
return WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED;
/*
* XXX - for now we only support WTAP_ENCAP_BLUETOOTH_HCI,
* WTAP_ENCAP_BLUETOOTH_H4_WITH_PHDR, and
* WTAP_ENCAP_BLUETOOTH_LINUX_MONITOR.
*/
if (encap != WTAP_ENCAP_BLUETOOTH_HCI &&
encap != WTAP_ENCAP_BLUETOOTH_H4_WITH_PHDR &&
encap != WTAP_ENCAP_BLUETOOTH_LINUX_MONITOR)
return WTAP_ERR_UNWRITABLE_ENCAP;
return 0;
}
static gboolean btsnoop_dump(wtap_dumper *wdh,
const wtap_rec *rec,
const guint8 *pd, int *err, gchar **err_info)
{
const union wtap_pseudo_header *pseudo_header = &rec->rec_header.packet_header.pseudo_header;
struct btsnooprec_hdr rec_hdr;
guint32 flags;
gint64 nsecs;
gint64 ts_usec;
/* We can only write packet records. */
if (rec->rec_type != REC_TYPE_PACKET) {
*err = WTAP_ERR_UNWRITABLE_REC_TYPE;
return FALSE;
}
/*
* Make sure this packet doesn't have a link-layer type that
* differs from the one for the file.
*/
if (wdh->file_encap != rec->rec_header.packet_header.pkt_encap) {
*err = WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED;
return FALSE;
}
/* Don't write out anything bigger than we can read. */
if (rec->rec_header.packet_header.caplen > WTAP_MAX_PACKET_SIZE_STANDARD) {
*err = WTAP_ERR_PACKET_TOO_LARGE;
return FALSE;
}
rec_hdr.incl_len = GUINT32_TO_BE(rec->rec_header.packet_header.caplen);
rec_hdr.orig_len = GUINT32_TO_BE(rec->rec_header.packet_header.len);
switch (wdh->file_encap) {
case WTAP_ENCAP_BLUETOOTH_HCI:
switch (pseudo_header->bthci.channel) {
case BTHCI_CHANNEL_COMMAND:
if (!pseudo_header->bthci.sent) {
*err = WTAP_ERR_UNWRITABLE_REC_DATA;
*err_info = ws_strdup_printf("btsnoop: Command channel, sent FALSE");
return FALSE;
}
flags = KHciLoggerCommandOrEvent|KHciLoggerHostToController;
break;
case BTHCI_CHANNEL_EVENT:
if (pseudo_header->bthci.sent) {
*err = WTAP_ERR_UNWRITABLE_REC_DATA;
*err_info = ws_strdup_printf("btsnoop: Event channel, sent TRUE");
return FALSE;
}
flags = KHciLoggerCommandOrEvent|KHciLoggerControllerToHost;
break;
case BTHCI_CHANNEL_ACL:
if (pseudo_header->bthci.sent)
flags = KHciLoggerACLDataFrame|KHciLoggerHostToController;
else
flags = KHciLoggerACLDataFrame|KHciLoggerControllerToHost;
break;
default:
*err = WTAP_ERR_UNWRITABLE_REC_DATA;
*err_info = ws_strdup_printf("btsnoop: Unknown channel %u",
pseudo_header->bthci.channel);
return FALSE;
}
break;
case WTAP_ENCAP_BLUETOOTH_H4_WITH_PHDR:
if (pseudo_header->p2p.sent)
flags = KHciLoggerHostToController;
else
flags = KHciLoggerControllerToHost;
if (rec->rec_header.packet_header.caplen >= 1 &&
(pd[0] == 0x01 || pd[0] == 0x04))
flags |= KHciLoggerCommandOrEvent;
break;
case WTAP_ENCAP_BLUETOOTH_LINUX_MONITOR:
flags = (pseudo_header->btmon.adapter_id << 16) | pseudo_header->btmon.opcode;
break;
default:
/* We should never get here - our open routine should only get
called for the types above. */
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("btsnoop: invalid encapsulation %u",
wdh->file_encap);
return FALSE;
}
rec_hdr.flags = GUINT32_TO_BE(flags);
rec_hdr.cum_drops = GUINT32_TO_BE(0);
nsecs = rec->ts.nsecs;
ts_usec = ((gint64) rec->ts.secs * 1000000) + (nsecs / 1000);
ts_usec += KUnixTimeBase;
rec_hdr.ts_usec = GINT64_TO_BE(ts_usec);
if (!wtap_dump_file_write(wdh, &rec_hdr, sizeof rec_hdr, err))
return FALSE;
if (!wtap_dump_file_write(wdh, pd, rec->rec_header.packet_header.caplen, err))
return FALSE;
return TRUE;
}
/* Returns TRUE on success, FALSE on failure; sets "*err" to an error code on
failure */
static gboolean btsnoop_dump_open(wtap_dumper *wdh, int *err, gchar **err_info _U_)
{
struct btsnoop_hdr file_hdr;
guint32 datalink;
/* This is a btsnoop file */
wdh->subtype_write = btsnoop_dump;
switch (wdh->file_encap) {
case WTAP_ENCAP_BLUETOOTH_HCI:
datalink = KHciLoggerDatalinkTypeH1;
break;
case WTAP_ENCAP_BLUETOOTH_H4_WITH_PHDR:
datalink = KHciLoggerDatalinkTypeH4;
break;
case WTAP_ENCAP_BLUETOOTH_LINUX_MONITOR:
datalink = KHciLoggerDatalinkLinuxMonitor;
break;
default:
/* We should never get here - our open routine should only get
called for the types above. */
*err = WTAP_ERR_INTERNAL;
*err_info = ws_strdup_printf("btsnoop: invalid encapsulation %u",
wdh->file_encap);
return FALSE;
}
/* Write the file header. */
if (!wtap_dump_file_write(wdh, btsnoop_magic, sizeof btsnoop_magic, err))
return FALSE;
/* current "btsnoop" format is 1 */
file_hdr.version = GUINT32_TO_BE(1);
/* HCI type encoded in first byte */
file_hdr.datalink = GUINT32_TO_BE(datalink);
if (!wtap_dump_file_write(wdh, &file_hdr, sizeof file_hdr, err))
return FALSE;
return TRUE;
}
static const struct supported_block_type btsnoop_blocks_supported[] = {
/*
* We support packet blocks, with no comments or other options.
*/
{ WTAP_BLOCK_PACKET, MULTIPLE_BLOCKS_SUPPORTED, NO_OPTIONS_SUPPORTED }
};
static const struct file_type_subtype_info btsnoop_info = {
"Symbian OS btsnoop", "btsnoop", "log", NULL,
FALSE, BLOCKS_SUPPORTED(btsnoop_blocks_supported),
btsnoop_dump_can_write_encap, btsnoop_dump_open, NULL
};
void register_btsnoop(void)
{
btsnoop_file_type_subtype = wtap_register_file_type_subtype(&btsnoop_info);
/*
* Register name for backwards compatibility with the
* wtap_filetypes table in Lua.
*/
wtap_register_backwards_compatibility_lua_name("BTSNOOP",
btsnoop_file_type_subtype);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/ |
C/C++ | wireshark/wiretap/btsnoop.h | /** @file
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __W_BTSNOOP_H__
#define __W_BTSNOOP_H__
#include <glib.h>
#include "ws_symbol_export.h"
wtap_open_return_val btsnoop_open(wtap *wth, int *err, gchar **err_info);
#endif |
C | wireshark/wiretap/busmaster.c | /* busmaster.c
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* Support for Busmaster log file format
* Copyright (c) 2019 by Maksim Salau <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <wtap-int.h>
#include <file_wrappers.h>
#include <epan/dissectors/packet-socketcan.h>
#include <wsutil/exported_pdu_tlvs.h>
#include "busmaster.h"
#include "busmaster_priv.h"
#include <inttypes.h>
#include <string.h>
#include <errno.h>
static void
busmaster_close(wtap *wth);
static gboolean
busmaster_read(wtap *wth, wtap_rec *rec, Buffer *buf,
int *err, gchar **err_info,
gint64 *data_offset);
static gboolean
busmaster_seek_read(wtap *wth, gint64 seek_off,
wtap_rec *rec, Buffer *buf,
int *err, gchar **err_info);
static int busmaster_file_type_subtype = -1;
void register_busmaster(void);
/*
* See
*
* http://rbei-etas.github.io/busmaster/
*
* for the BUSMASTER software.
*/
static gboolean
busmaster_gen_packet(wtap_rec *rec, Buffer *buf,
const busmaster_priv_t *priv_entry, const msg_t *msg,
int *err, gchar **err_info)
{
time_t secs = 0;
guint32 nsecs = 0;
gboolean has_ts = FALSE;
gboolean is_fd = (msg->type == MSG_TYPE_STD_FD)
|| (msg->type == MSG_TYPE_EXT_FD);
gboolean is_eff = (msg->type == MSG_TYPE_EXT)
|| (msg->type == MSG_TYPE_EXT_RTR)
|| (msg->type == MSG_TYPE_EXT_FD);
gboolean is_rtr = (msg->type == MSG_TYPE_STD_RTR)
|| (msg->type == MSG_TYPE_EXT_RTR);
gboolean is_err = (msg->type == MSG_TYPE_ERR);
if (!priv_entry)
{
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("Header is missing");
return FALSE;
}
/* Generate Exported PDU tags for the packet info */
ws_buffer_clean(buf);
if (is_fd)
{
wtap_buffer_append_epdu_string(buf, EXP_PDU_TAG_DISSECTOR_NAME, "canfd");
}
else
{
wtap_buffer_append_epdu_string(buf, EXP_PDU_TAG_DISSECTOR_NAME, "can-hostendian");
}
wtap_buffer_append_epdu_end(buf);
if (is_fd)
{
canfd_frame_t canfd_frame = {0};
canfd_frame.can_id = (msg->id & (is_eff ? CAN_EFF_MASK : CAN_SFF_MASK)) |
(is_eff ? CAN_EFF_FLAG : 0) |
(is_err ? CAN_ERR_FLAG : 0);
canfd_frame.flags = 0;
canfd_frame.len = msg->data.length;
memcpy(canfd_frame.data,
msg->data.data,
MIN(msg->data.length, sizeof(canfd_frame.data)));
ws_buffer_append(buf,
(guint8 *)&canfd_frame,
sizeof(canfd_frame));
}
else
{
can_frame_t can_frame = {0};
can_frame.can_id = (msg->id & (is_eff ? CAN_EFF_MASK : CAN_SFF_MASK)) |
(is_rtr ? CAN_RTR_FLAG : 0) |
(is_eff ? CAN_EFF_FLAG : 0) |
(is_err ? CAN_ERR_FLAG : 0);
can_frame.can_dlc = msg->data.length;
memcpy(can_frame.data,
msg->data.data,
MIN(msg->data.length, sizeof(can_frame.data)));
ws_buffer_append(buf,
(guint8 *)&can_frame,
sizeof(can_frame));
}
if (priv_entry->time_mode == TIME_MODE_SYSTEM)
{
struct tm tm;
tm.tm_year = priv_entry->start_date.year - 1900;
tm.tm_mon = priv_entry->start_date.month - 1;
tm.tm_mday = priv_entry->start_date.day;
tm.tm_hour = msg->timestamp.hours;
tm.tm_min = msg->timestamp.minutes;
tm.tm_sec = msg->timestamp.seconds;
tm.tm_isdst = -1;
secs = mktime(&tm);
nsecs = msg->timestamp.micros * 1000u;
has_ts = TRUE;
}
else if (priv_entry->time_mode == TIME_MODE_ABSOLUTE)
{
struct tm tm;
guint32 micros;
tm.tm_year = priv_entry->start_date.year - 1900;
tm.tm_mon = priv_entry->start_date.month - 1;
tm.tm_mday = priv_entry->start_date.day;
tm.tm_hour = priv_entry->start_time.hours;
tm.tm_min = priv_entry->start_time.minutes;
tm.tm_sec = priv_entry->start_time.seconds;
tm.tm_isdst = -1;
secs = mktime(&tm);
secs += msg->timestamp.hours * 3600;
secs += msg->timestamp.minutes * 60;
secs += msg->timestamp.seconds;
micros = priv_entry->start_time.micros + msg->timestamp.micros;
if (micros >= 1000000u)
{
micros -= 1000000u;
secs += 1;
}
nsecs = micros * 1000u;
has_ts = TRUE;
}
rec->rec_type = REC_TYPE_PACKET;
rec->block = wtap_block_create(WTAP_BLOCK_PACKET);
rec->presence_flags = has_ts ? WTAP_HAS_TS : 0;
rec->ts.secs = secs;
rec->ts.nsecs = nsecs;
rec->rec_header.packet_header.caplen = (guint32)ws_buffer_length(buf);
rec->rec_header.packet_header.len = (guint32)ws_buffer_length(buf);
return TRUE;
}
static log_entry_type_t
busmaster_parse(FILE_T fh, busmaster_state_t *state, int *err, char **err_info)
{
gboolean ok;
gint64 seek_off;
busmaster_debug_printf("%s: Running busmaster file decoder\n", G_STRFUNC);
state->fh = fh;
do
{
if (file_eof(fh))
return LOG_ENTRY_EOF;
seek_off = file_tell(fh);
busmaster_debug_printf("%s: Starting parser at offset %" PRIi64 "\n",
G_STRFUNC, seek_off);
state->file_bytes_read = 0;
ok = run_busmaster_parser(state, err, err_info);
/* Rewind the file to the offset we have finished parsing */
busmaster_debug_printf("%s: Rewinding to offset %" PRIi64 "\n",
G_STRFUNC, seek_off + state->file_bytes_read);
if (file_seek(fh, seek_off + state->file_bytes_read, SEEK_SET, err) == -1)
{
g_free(*err_info);
*err = errno;
*err_info = g_strdup(g_strerror(errno));
return LOG_ENTRY_ERROR;
}
}
while (ok && state->entry_type == LOG_ENTRY_NONE);
if (!ok)
return LOG_ENTRY_ERROR;
busmaster_debug_printf("%s: Success\n", G_STRFUNC);
return state->entry_type;
}
wtap_open_return_val
busmaster_open(wtap *wth, int *err, char **err_info)
{
busmaster_state_t state = {0};
log_entry_type_t entry;
busmaster_debug_printf("%s: Trying to open with busmaster log reader\n",
G_STRFUNC);
/* Rewind to the beginning */
if (file_seek(wth->fh, 0, SEEK_SET, err) == -1)
return WTAP_OPEN_ERROR;
entry = busmaster_parse(wth->fh, &state, err, err_info);
g_free(*err_info);
*err_info = NULL;
*err = 0;
if (entry != LOG_ENTRY_HEADER)
return WTAP_OPEN_NOT_MINE;
/* Rewind to the beginning, so busmaster_read may read from the very beginning */
if (file_seek(wth->fh, 0, SEEK_SET, err) == -1)
return WTAP_OPEN_ERROR;
busmaster_debug_printf("%s: That's a busmaster log\n", G_STRFUNC);
wth->priv = NULL;
wth->subtype_close = busmaster_close;
wth->subtype_read = busmaster_read;
wth->subtype_seek_read = busmaster_seek_read;
wth->file_type_subtype = busmaster_file_type_subtype;
wth->file_encap = WTAP_ENCAP_WIRESHARK_UPPER_PDU;
wth->file_tsprec = WTAP_TSPREC_USEC;
return WTAP_OPEN_MINE;
}
static void
busmaster_close(wtap *wth)
{
busmaster_debug_printf("%s\n", G_STRFUNC);
g_slist_free_full((GSList *)wth->priv, g_free);
wth->priv = NULL;
}
static busmaster_priv_t *
busmaster_find_priv_entry(void *priv, gint64 offset)
{
GSList *list;
for (list = (GSList *)priv; list; list = g_slist_next(list))
{
busmaster_priv_t *entry = (busmaster_priv_t *)list->data;
if (((entry->file_end_offset == -1)
&& (g_slist_next(list) == NULL))
|| ((offset >= entry->file_start_offset)
&& (offset <= entry->file_end_offset)))
{
return entry;
}
}
return NULL;
}
static gboolean
busmaster_read(wtap *wth, wtap_rec *rec, Buffer *buf, int *err, gchar **err_info,
gint64 *data_offset)
{
log_entry_type_t entry;
busmaster_state_t state;
busmaster_priv_t *priv_entry;
gboolean is_msg = FALSE;
gboolean is_ok = TRUE;
while (!is_msg && is_ok)
{
busmaster_debug_printf("%s: offset = %" PRIi64 "\n",
G_STRFUNC, file_tell(wth->fh));
if (file_eof(wth->fh))
{
busmaster_debug_printf("%s: End of file detected, nothing to do here\n",
G_STRFUNC);
*err = 0;
*err_info = NULL;
return FALSE;
}
*data_offset = file_tell(wth->fh);
priv_entry = busmaster_find_priv_entry(wth->priv, *data_offset);
memset(&state, 0, sizeof(state));
if (priv_entry)
state.header = *priv_entry;
entry = busmaster_parse(wth->fh, &state, err, err_info);
busmaster_debug_printf("%s: analyzing output\n", G_STRFUNC);
switch (entry)
{
case LOG_ENTRY_EMPTY:
break;
case LOG_ENTRY_FOOTER_AND_HEADER:
case LOG_ENTRY_FOOTER:
priv_entry = (busmaster_priv_t *)g_slist_last((GSList *)wth->priv)->data;
if (!priv_entry)
{
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("Header is missing");
return FALSE;
}
priv_entry->file_end_offset = *data_offset;
if (entry == LOG_ENTRY_FOOTER)
break;
/* fall-through */
case LOG_ENTRY_HEADER:
if (state.header.protocol != PROTOCOL_CAN &&
state.header.protocol != PROTOCOL_J1939)
{
*err = WTAP_ERR_UNSUPPORTED;
*err_info = g_strdup("Unsupported protocol type");
return FALSE;
}
if (wth->priv)
{
/* Check that the previous section has a footer */
priv_entry = (busmaster_priv_t *)g_slist_last((GSList *)wth->priv)->data;
if (priv_entry && priv_entry->file_end_offset == -1)
{
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("Footer is missing");
return FALSE;
}
}
/* Start a new section */
priv_entry = g_new(busmaster_priv_t, 1);
priv_entry[0] = state.header;
priv_entry->file_start_offset = file_tell(wth->fh);
priv_entry->file_end_offset = -1;
wth->priv = g_slist_append((GSList *)wth->priv, priv_entry);
break;
case LOG_ENTRY_MSG:
is_msg = TRUE;
priv_entry = busmaster_find_priv_entry(wth->priv, *data_offset);
is_ok = busmaster_gen_packet(rec, buf, priv_entry, &state.msg, err, err_info);
break;
case LOG_ENTRY_EOF:
case LOG_ENTRY_ERROR:
case LOG_ENTRY_NONE:
default:
is_ok = FALSE;
break;
}
}
busmaster_debug_printf("%s: stopped at offset %" PRIi64 " with entry %d\n",
G_STRFUNC, file_tell(wth->fh), entry);
return is_ok;
}
static gboolean
busmaster_seek_read(wtap *wth, gint64 seek_off, wtap_rec *rec,
Buffer *buf, int *err, gchar **err_info)
{
busmaster_priv_t *priv_entry;
busmaster_state_t state = {0};
log_entry_type_t entry;
busmaster_debug_printf("%s: offset = %" PRIi64 "\n", G_STRFUNC, seek_off);
priv_entry = busmaster_find_priv_entry(wth->priv, seek_off);
if (!priv_entry)
{
busmaster_debug_printf("%s: analyzing output\n", G_STRFUNC);
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("Malformed header");
return FALSE;
}
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
return FALSE;
state.header = *priv_entry;
entry = busmaster_parse(wth->random_fh, &state, err, err_info);
busmaster_debug_printf("%s: analyzing output\n", G_STRFUNC);
if (entry == LOG_ENTRY_ERROR || entry == LOG_ENTRY_NONE)
return FALSE;
if (entry != LOG_ENTRY_MSG)
{
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("Failed to read a frame");
return FALSE;
}
return busmaster_gen_packet(rec, buf, priv_entry, &state.msg, err, err_info);
}
static const struct supported_block_type busmaster_blocks_supported[] = {
/*
* We support packet blocks, with no comments or other options.
*/
{ WTAP_BLOCK_PACKET, MULTIPLE_BLOCKS_SUPPORTED, NO_OPTIONS_SUPPORTED }
};
static const struct file_type_subtype_info busmaster_info = {
"BUSMASTER log file", "busmaster", "log", NULL,
FALSE, BLOCKS_SUPPORTED(busmaster_blocks_supported),
NULL, NULL, NULL
};
void register_busmaster(void)
{
busmaster_file_type_subtype = wtap_register_file_type_subtype(&busmaster_info);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/ |
C/C++ | wireshark/wiretap/busmaster.h | /** @file
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* Support for Busmaster log file format
* Copyright (c) 2019 by Maksim Salau <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef BUSMASTER_H__
#define BUSMASTER_H__
#include <wiretap/wtap.h>
wtap_open_return_val
busmaster_open(wtap *wth, int *err, char **err_info);
#endif /* BUSMASTER_H__ */ |
wireshark/wiretap/busmaster_parser.lemon | %include {
/* busmaster_parser.lemon
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* Support for Busmaster log file format
* Copyright (c) 2019 by Maksim Salau <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <assert.h>
#include <string.h>
#include <wireshark.h>
#include <wiretap/file_wrappers.h>
#include "busmaster_priv.h"
extern void *BusmasterParserAlloc(void *(*mallocProc)(size_t));
extern void BusmasterParser(void *yyp, int yymajor, token_t yyminor, busmaster_state_t *state);
extern void BusmasterParserFree(void *p, void (*freeProc)(void*));
#if defined(BUSMASTER_DEBUG) || defined(BUSMASTER_PARSER_TRACE)
extern void BusmasterParserTrace(FILE *TraceFILE, char *zTracePrompt);
#undef NDEBUG
#endif
static void merge_msg_data(msg_data_t *dst, const msg_data_t *a, const msg_data_t *b)
{
dst->length = a->length + b->length;
memcpy(&dst->data[0], &a->data[0], a->length);
memcpy(&dst->data[a->length], &b->data[0], b->length);
}
DIAG_OFF_LEMON()
} /* end of %include */
%code {
DIAG_ON_LEMON()
}
%name BusmasterParser
%token_prefix TOKEN_
%token_type { token_t }
%token_destructor
{
(void)state;
(void)yypParser;
(void)yypminor;
}
%extra_argument { busmaster_state_t* state }
%syntax_error
{
(void)yypParser;
(void)yyminor;
#ifdef BUSMASTER_DEBUG
const int n = sizeof(yyTokenName) / sizeof(yyTokenName[0]);
busmaster_debug_printf("%s: got token: %s\n", G_STRFUNC, yyTokenName[yymajor]);
for (int i = 0; i < n; ++i) {
int a = yy_find_shift_action((YYCODETYPE)i, yypParser->yytos->stateno);
if (a < YYNSTATE + YYNRULE) {
busmaster_debug_printf("%s: possible token: %s\n", G_STRFUNC, yyTokenName[i]);
}
}
#endif
g_free(state->parse_error);
state->entry_type = LOG_ENTRY_ERROR;
state->parse_error = ws_strdup_printf("Syntax Error");
busmaster_debug_printf("%s: Syntax Error\n", G_STRFUNC);
}
%parse_failure
{
g_free(state->parse_error);
state->entry_type = LOG_ENTRY_ERROR;
state->parse_error = g_strdup("Parse Error");
busmaster_debug_printf("%s: Parse Error\n", G_STRFUNC);
}
%stack_overflow
{
g_free(state->parse_error);
state->entry_type = LOG_ENTRY_ERROR;
state->parse_error = g_strdup("Parser stack overflow");
busmaster_debug_printf("%s: Parser stack overflow\n", G_STRFUNC);
}
%type msg_time { msg_time_t }
%type msg_type { msg_type_t }
%type err_msg_type { msg_type_t }
%type msg_length { guint }
%type msg_id { guint32 }
%type ref_date { msg_date_t }
%type ref_time { msg_time_t }
%type start_time { msg_date_time_t }
%type byte { guint8 }
%type data { msg_data_t }
%type data0 { msg_data_t }
%type data1 { msg_data_t }
%type data2 { msg_data_t }
%type data3 { msg_data_t }
%type data4 { msg_data_t }
%type data5 { msg_data_t }
%type data6 { msg_data_t }
%type data7 { msg_data_t }
%type data8 { msg_data_t }
%type data12 { msg_data_t }
%type data16 { msg_data_t }
%type data20 { msg_data_t }
%type data24 { msg_data_t }
%type data32 { msg_data_t }
%type data48 { msg_data_t }
%type data64 { msg_data_t }
%nonassoc INVALID_CHAR .
%nonassoc INVALID_NUMBER .
%start_symbol entry
entry ::= empty_line .
entry ::= footer_and_header .
entry ::= header .
entry ::= footer .
entry ::= msg .
entry ::= err_msg .
entry ::= j1939_msg .
empty_line ::= .
{
busmaster_debug_printf("%s: EMPTY\n", G_STRFUNC);
state->entry_type = LOG_ENTRY_EMPTY;
}
footer_and_header ::= footer ENDL header .
{
busmaster_debug_printf("%s: FOOTER AND HEADER\n", G_STRFUNC);
state->entry_type = LOG_ENTRY_FOOTER_AND_HEADER;
}
header ::= version ENDL maybe_lines
PROTOCOL_TYPE(P) ENDL maybe_lines
START_SESSION ENDL maybe_lines
start_time(S) ENDL maybe_lines
DATA_MODE(D) ENDL maybe_lines
TIME_MODE(T) ENDL anything .
{
busmaster_debug_printf("%s: HEADER\n", G_STRFUNC);
state->entry_type = LOG_ENTRY_HEADER;
state->header.start_date = S.date;
state->header.start_time = S.time;
state->header.protocol = (protocol_type_t)P.v0;
state->header.data_mode = (data_mode_t)D.v0;
state->header.time_mode = (time_mode_t)T.v0;
}
version ::= HEADER_VER maybe_chars .
maybe_chars ::= .
maybe_chars ::= maybe_chars HEADER_CHAR .
maybe_lines ::= .
maybe_lines ::= maybe_lines maybe_chars ENDL .
anything ::= .
anything ::= anything HEADER_CHAR .
anything ::= anything ENDL .
start_time(R) ::= START_TIME ref_date(D) ref_time(T) .
{
R.date = D;
R.time = T;
}
footer ::= end_time ENDL STOP_SESSION .
{
busmaster_debug_printf("%s: FOOTER\n", G_STRFUNC);
state->entry_type = LOG_ENTRY_FOOTER;
}
end_time ::= END_TIME ref_date ref_time .
/* <Time><Tx/Rx><Channel><CAN ID><Type><DLC><DataBytes> */
msg ::= msg_time(msg_time) MSG_DIR INT msg_id(msg_id) msg_type(msg_type) msg_length(msg_length) data(msg_data) .
{
msg_t msg;
/* DLC is always in DEC mode, thus we need to fix the value
* if it was read initially as HEX. */
if (state->header.data_mode == DATA_MODE_HEX)
{
msg_length = (msg_length / 16) * 10 + (msg_length % 16);
}
/* Fix data in RTR frames. Data may not be present,
* but length field is set. */
if (msg_type == MSG_TYPE_STD_RTR ||
msg_type == MSG_TYPE_EXT_RTR)
{
memset(&msg_data, 0, sizeof(msg_data));
msg_data.length = msg_length;
}
msg.timestamp = msg_time;
msg.id = msg_id;
msg.type = msg_type;
msg.data = msg_data;
busmaster_debug_printf("%s: MSG\n", G_STRFUNC);
state->msg = msg;
state->entry_type = LOG_ENTRY_MSG;
}
/* <Time><Tx/Rx><Channel><CAN ID><Type><Text> */
err_msg ::= msg_time(msg_time) MSG_DIR INT INT err_msg_type(msg_type) .
{
msg_t msg;
msg.timestamp = msg_time;
msg.id = 0;
msg.type = msg_type;
msg.data.length = CAN_MAX_DLEN;
memset(msg.data.data, 0, sizeof(msg.data.data));
busmaster_debug_printf("%s: ERR MSG\n", G_STRFUNC);
state->msg = msg;
state->entry_type = LOG_ENTRY_MSG;
}
/* <Time><Channel><CAN ID><PGN><Type><Source Node><Destination Node><Priority><Tx/Rx><DLC><DataBytes> */
j1939_msg ::= msg_time(msg_time) INT msg_id(msg_id) INT J1939_MSG_TYPE INT INT INT MSG_DIR msg_length data(msg_data) .
{
msg_t msg;
msg.timestamp = msg_time;
msg.id = msg_id;
msg.type = MSG_TYPE_EXT;
msg.data = msg_data;
busmaster_debug_printf("%s: J1939 MSG\n", G_STRFUNC);
state->msg = msg;
state->entry_type = LOG_ENTRY_MSG;
}
ref_date(R) ::= INT(D) COLON INT(M) COLON INT(Y) .
{
R.year = (guint)Y.v0;
R.month = (guint)M.v0;
R.day = (guint)D.v0;
}
ref_time(R) ::= INT(H) COLON INT(M) COLON INT(S) COLON INT(U) .
{
R.hours = (guint)H.v0;
R.minutes = (guint)M.v0;
R.seconds = (guint)S.v0;
R.micros = (guint)U.v0 * 1000;
}
msg_time(R) ::= MSG_TIME(M) .
{
R.hours = (guint)M.v0;
R.minutes = (guint)M.v1;
R.seconds = (guint)M.v2;
R.micros = (guint)M.v3 * 100;
}
msg_id(R) ::= INT(V) .
{
R = (guint)V.v0;
}
msg_length(R) ::= INT(V) .
{
R = (guint)V.v0;
}
msg_type(R) ::= MSG_TYPE(V) .
{
R = (msg_type_t)V.v0;
}
err_msg_type(R) ::= ERR_MSG_TYPE(V) .
{
R = (msg_type_t)V.v0;
}
data(R) ::= data0(A) . { R = A; }
data(R) ::= data1(A) . { R = A; }
data(R) ::= data2(A) . { R = A; }
data(R) ::= data3(A) . { R = A; }
data(R) ::= data4(A) . { R = A; }
data(R) ::= data5(A) . { R = A; }
data(R) ::= data6(A) . { R = A; }
data(R) ::= data7(A) . { R = A; }
data(R) ::= data8(A) . { R = A; }
data(R) ::= data12(A) . { R = A; }
data(R) ::= data16(A) . { R = A; }
data(R) ::= data20(A) . { R = A; }
data(R) ::= data24(A) . { R = A; }
data(R) ::= data32(A) . { R = A; }
data(R) ::= data48(A) . { R = A; }
data(R) ::= data64(A) . { R = A; }
byte(R) ::= INT(A) .
{
R = (guint8)A.v0;
}
data0(R) ::= .
{
R.length = 0;
}
data1(R) ::= byte(A) .
{
R.length = 1;
R.data[0] = A;
}
data2(R) ::= byte(A) byte(B) .
{
R.length = 2;
R.data[0] = A;
R.data[1] = B;
}
data3(R) ::= byte(A) byte(B) byte(C) .
{
R.length = 3;
R.data[0] = A;
R.data[1] = B;
R.data[2] = C;
}
data4(R) ::= byte(A) byte(B) byte(C) byte(D) .
{
R.length = 4;
R.data[0] = A;
R.data[1] = B;
R.data[2] = C;
R.data[3] = D;
}
data5(R) ::= data4(A) data1(B) . { merge_msg_data(&R, &A, &B); }
data6(R) ::= data4(A) data2(B) . { merge_msg_data(&R, &A, &B); }
data7(R) ::= data4(A) data3(B) . { merge_msg_data(&R, &A, &B); }
data8(R) ::= data4(A) data4(B) . { merge_msg_data(&R, &A, &B); }
data12(R) ::= data8(A) data4(B) . { merge_msg_data(&R, &A, &B); }
data16(R) ::= data8(A) data8(B) . { merge_msg_data(&R, &A, &B); }
data20(R) ::= data16(A) data4(B) . { merge_msg_data(&R, &A, &B); }
data24(R) ::= data16(A) data8(B) . { merge_msg_data(&R, &A, &B); }
data32(R) ::= data16(A) data16(B) . { merge_msg_data(&R, &A, &B); }
data48(R) ::= data32(A) data16(B) . { merge_msg_data(&R, &A, &B); }
data64(R) ::= data32(A) data32(B) . { merge_msg_data(&R, &A, &B); }
%code {
#include "busmaster_scanner_lex.h"
#include "busmaster_parser.h"
gboolean
run_busmaster_parser(busmaster_state_t *state,
int *err, gchar **err_info)
{
int lex_code;
yyscan_t scanner;
void *parser;
state->entry_type = LOG_ENTRY_NONE;
state->parse_error = NULL;
state->err = 0;
state->err_info = NULL;
if (busmaster_lex_init_extra(state, &scanner) != 0)
{
*err = errno;
*err_info = g_strdup(g_strerror(errno));
return FALSE;
}
parser = BusmasterParserAlloc(g_malloc);
#ifdef BUSMASTER_PARSER_TRACE
BusmasterParserTrace(stdout, "BusmasterParser >> ");
#endif
busmaster_debug_printf("%s: Starting parsing of the line\n", G_STRFUNC);
do
{
lex_code = busmaster_lex(scanner);
#ifdef BUSMASTER_DEBUG
if (lex_code)
busmaster_debug_printf("%s: Feeding %s '%s'\n",
G_STRFUNC, yyTokenName[lex_code],
busmaster_get_text(scanner));
else
busmaster_debug_printf("%s: Feeding %s\n",
G_STRFUNC, yyTokenName[lex_code]);
#endif
BusmasterParser(parser, lex_code, state->token, state);
if (state->err || state->err_info || state->parse_error)
break;
}
while (lex_code);
busmaster_debug_printf("%s: Done (%d)\n", G_STRFUNC, lex_code);
BusmasterParserFree(parser, g_free);
busmaster_lex_destroy(scanner);
if (state->err || state->err_info || state->parse_error)
{
if (state->err_info)
{
*err_info = state->err_info;
g_free(state->parse_error);
}
else
{
*err_info = state->parse_error;
}
if (state->err)
*err = state->err;
else
*err = WTAP_ERR_BAD_FILE;
return FALSE;
}
return TRUE;
}
} |
|
C/C++ | wireshark/wiretap/busmaster_priv.h | /** @file
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* Support for Busmaster log file format
* Copyright (c) 2019 by Maksim Salau <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef BUSMASTER_PRIV_H__
#define BUSMASTER_PRIV_H__
#include <gmodule.h>
#include <wiretap/wtap.h>
#include <wiretap/socketcan.h>
//#define BUSMASTER_DEBUG
//#define BUSMASTER_PARSER_TRACE
typedef enum {
LOG_ENTRY_ERROR = -1,
LOG_ENTRY_NONE = 0,
LOG_ENTRY_EMPTY,
LOG_ENTRY_HEADER,
LOG_ENTRY_FOOTER,
LOG_ENTRY_FOOTER_AND_HEADER,
LOG_ENTRY_MSG,
LOG_ENTRY_EOF,
} log_entry_type_t;
typedef enum {
PROTOCOL_UNKNOWN = 0,
PROTOCOL_CAN,
PROTOCOL_LIN,
PROTOCOL_J1939,
} protocol_type_t;
typedef enum {
DATA_MODE_UNKNOWN = 0,
DATA_MODE_HEX,
DATA_MODE_DEC,
} data_mode_t;
typedef enum {
TIME_MODE_UNKNOWN = 0,
TIME_MODE_ABSOLUTE,
TIME_MODE_SYSTEM,
TIME_MODE_RELATIVE,
} time_mode_t;
typedef enum {
MSG_TYPE_STD,
MSG_TYPE_EXT,
MSG_TYPE_STD_RTR,
MSG_TYPE_EXT_RTR,
MSG_TYPE_STD_FD,
MSG_TYPE_EXT_FD,
MSG_TYPE_ERR,
} msg_type_t;
typedef struct {
guint year;
guint month;
guint day;
} msg_date_t;
typedef struct {
guint hours;
guint minutes;
guint seconds;
guint micros;
} msg_time_t;
typedef struct {
msg_date_t date;
msg_time_t time;
} msg_date_time_t;
typedef struct {
guint length;
guint8 data[CANFD_MAX_DLEN];
} msg_data_t;
typedef struct {
msg_time_t timestamp;
msg_type_t type;
guint32 id;
msg_data_t data;
} msg_t;
typedef struct {
gint64 v0;
gint64 v1;
gint64 v2;
gint64 v3;
} token_t;
typedef struct {
gint64 file_start_offset;
gint64 file_end_offset;
protocol_type_t protocol;
data_mode_t data_mode;
time_mode_t time_mode;
msg_date_t start_date;
msg_time_t start_time;
} busmaster_priv_t;
typedef struct {
FILE_T fh;
gint64 file_bytes_read;
gchar *parse_error;
int err;
gchar *err_info;
token_t token;
log_entry_type_t entry_type;
busmaster_priv_t header;
msg_t msg;
} busmaster_state_t;
gboolean
run_busmaster_parser(busmaster_state_t *state,
int *err, gchar **err_info);
#ifdef BUSMASTER_DEBUG
#include <stdio.h>
#define busmaster_debug_printf(...) printf(__VA_ARGS__)
#else
#define busmaster_debug_printf(...) (void)0
#endif
#endif /* BUSMASTER_PRIV_H__ */ |
wireshark/wiretap/busmaster_scanner.l | /* busmaster_scanner.l
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* Support for Busmaster log file format
* Copyright (c) 2019 by Maksim Salau <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
%top {
/* Include this before everything else, for various large-file definitions */
#include "config.h"
#include <wireshark.h>
}
%option noyywrap
%option noinput
%option nounput
%option batch
%option never-interactive
%option nodefault
%option prefix="busmaster_"
%option reentrant
%option extra-type="busmaster_state_t *"
%option noyy_scan_buffer
%option noyy_scan_bytes
%option noyy_scan_string
/*
* We have to override the memory allocators so that we don't get
* "unused argument" warnings from the yyscanner argument (which
* we don't use, as we have a global memory allocator).
*
* We provide, as macros, our own versions of the routines generated by Flex,
* which just call malloc()/realloc()/free() (as the Flex versions do),
* discarding the extra argument.
*/
%option noyyalloc
%option noyyrealloc
%option noyyfree
%{
#include <ws_diag_control.h>
#include <wiretap/file_wrappers.h>
#include "busmaster_parser.h"
#include "busmaster_priv.h"
#ifndef HAVE_UNISTD_H
#define YY_NO_UNISTD_H
#endif
static int busmaster_yyinput(void *buf, unsigned int length, busmaster_state_t *state)
{
int ret = file_read(buf, length, state->fh);
if (ret < 0)
{
state->err = file_error(state->fh, &state->err_info);
return YY_NULL;
}
return ret;
}
#define YY_INPUT(buf, result, max_size) \
do { (result) = busmaster_yyinput((buf), (max_size), yyextra); } while (0)
/* Count bytes read. This is required in order to rewind the file
* to the beginning of the next packet, since flex reads more bytes
* before executing the action that does yyterminate(). */
#define YY_USER_ACTION do { yyextra->file_bytes_read += yyleng; } while (0);
/*
* Sleazy hack to suppress compiler warnings in yy_fatal_error().
*/
#define YY_EXIT_FAILURE ((void)yyscanner, 2)
/*
* Macros for the allocators, to discard the extra argument.
*/
#define busmaster_alloc(size, yyscanner) (void *)malloc(size)
#define busmaster_realloc(ptr, size, yyscanner) (void *)realloc((char *)(ptr), (size))
#define busmaster_free(ptr, yyscanner) free((char *)(ptr))
DIAG_OFF_FLEX()
%}
SPC [ \t]+
ENDL [\r\n][ \t\r\n]*
INT [0-9]+
NUM (0x)?[0-9A-Fa-f]+
%x HEADER TIME
%x HEADER_CHANNELS HEADER_DB_FILES
%%
<*>{SPC} ;
<INITIAL>{ENDL} { yyterminate(); };
<HEADER,TIME>{ENDL} { YY_FATAL_ERROR("Unterminated header statement"); }
"***" { BEGIN(HEADER); }
<HEADER,TIME>"***"{ENDL}"***" { BEGIN(HEADER); return TOKEN_ENDL; }
<HEADER>"***"{ENDL} { BEGIN(INITIAL); yyterminate(); }
<HEADER>"BUSMASTER" { return TOKEN_HEADER_VER; }
<HEADER>"PROTOCOL CAN" { yyextra->token.v0 = PROTOCOL_CAN; return TOKEN_PROTOCOL_TYPE; }
<HEADER>"PROTOCOL J1939" { yyextra->token.v0 = PROTOCOL_J1939; return TOKEN_PROTOCOL_TYPE; }
<HEADER>"PROTOCOL LIN" { yyextra->token.v0 = PROTOCOL_LIN; return TOKEN_PROTOCOL_TYPE; }
<HEADER>"START DATE AND TIME" { BEGIN(TIME); return TOKEN_START_TIME; }
<HEADER>"END DATE AND TIME" { BEGIN(TIME); return TOKEN_END_TIME; }
<HEADER>"DEC" { yyextra->token.v0 = DATA_MODE_DEC; return TOKEN_DATA_MODE; }
<HEADER>"HEX" { yyextra->token.v0 = DATA_MODE_HEX; return TOKEN_DATA_MODE; }
<HEADER>"ABSOLUTE MODE" { yyextra->token.v0 = TIME_MODE_ABSOLUTE; return TOKEN_TIME_MODE; }
<HEADER>"SYSTEM MODE" { yyextra->token.v0 = TIME_MODE_SYSTEM; return TOKEN_TIME_MODE; }
<HEADER>"RELATIVE MODE" { yyextra->token.v0 = TIME_MODE_RELATIVE; return TOKEN_TIME_MODE; }
<HEADER>"[START LOGGING SESSION]" { return TOKEN_START_SESSION; }
<HEADER>"[STOP LOGGING SESSION]" { return TOKEN_STOP_SESSION; }
<HEADER>"START CHANNEL BAUD RATE***" { BEGIN(HEADER_CHANNELS); }
<HEADER>"START DATABASE FILES (DBF/DBC)***" { BEGIN(HEADER_DB_FILES); }
<HEADER>. { return TOKEN_HEADER_CHAR; }
<HEADER_CHANNELS>"***END CHANNEL BAUD RATE***"{ENDL}"***" { BEGIN(HEADER); }
<HEADER_CHANNELS>.+ ;
<HEADER_CHANNELS>{ENDL} ;
<HEADER_DB_FILES>"***END DATABASE FILES (DBF/DBC)***"{ENDL}"***" { BEGIN(HEADER); }
<HEADER_DB_FILES>"***END OF DATABASE FILES (DBF/DBC)***"{ENDL}"***" { BEGIN(HEADER); }
<HEADER_DB_FILES>.+ ;
<HEADER_DB_FILES>{ENDL} ;
<TIME>{INT} { yyextra->token.v0 = strtoul(yytext, NULL, 10); return TOKEN_INT; }
<TIME>: { return TOKEN_COLON; }
<TIME>. { return TOKEN_INVALID_CHAR; }
<INITIAL>{INT}:{INT}:{INT}:{INT} {
char *endp;
char *strp;
yyextra->token.v0 = strtoul(yytext, &endp, 10);
if (*endp != ':' || endp == yytext)
return TOKEN_INVALID_NUMBER;
strp = endp + 1;
yyextra->token.v1 = strtoul(strp, &endp, 10);
if (*endp != ':' || endp == strp)
return TOKEN_INVALID_NUMBER;
strp = endp + 1;
yyextra->token.v2 = strtoul(strp, &endp, 10);
if (*endp != ':' || endp == strp)
return TOKEN_INVALID_NUMBER;
strp = endp + 1;
yyextra->token.v3 = strtoul(strp, &endp, 10);
if (*endp != '\0' || endp == strp)
return TOKEN_INVALID_NUMBER;
return TOKEN_MSG_TIME;
}
<INITIAL>{NUM} {
char *endp;
if (yyextra->header.data_mode == DATA_MODE_HEX)
yyextra->token.v0 = strtoul(yytext, &endp, 16);
else if (yyextra->header.data_mode == DATA_MODE_DEC)
yyextra->token.v0 = strtoul(yytext, &endp, 10);
else
return TOKEN_INVALID_NUMBER;
if (*endp != '\0' || endp == yytext)
return TOKEN_INVALID_NUMBER;
return TOKEN_INT;
}
<INITIAL>[RT]x { return TOKEN_MSG_DIR; }
<INITIAL>s { yyextra->token.v0 = MSG_TYPE_STD; return TOKEN_MSG_TYPE; }
<INITIAL>sr { yyextra->token.v0 = MSG_TYPE_STD_RTR; return TOKEN_MSG_TYPE; }
<INITIAL>x { yyextra->token.v0 = MSG_TYPE_EXT; return TOKEN_MSG_TYPE; }
<INITIAL>xr { yyextra->token.v0 = MSG_TYPE_EXT_RTR; return TOKEN_MSG_TYPE; }
<INITIAL>s-fd { yyextra->token.v0 = MSG_TYPE_STD_FD; return TOKEN_MSG_TYPE; }
<INITIAL>x-fd { yyextra->token.v0 = MSG_TYPE_EXT_FD; return TOKEN_MSG_TYPE; }
<INITIAL>ERR.* { yyextra->token.v0 = MSG_TYPE_ERR; return TOKEN_ERR_MSG_TYPE; }
<INITIAL>("NONE"|"CMD"|"RQST"|"DATA"|"BROADCAST"|"ACK"|"GRP_FUNC"|"ACL"|"RQST_ACL"|"CA"|"BAM"|"RTS"|"CTS"|"EOM"|"CON_ABORT"|"TPDT") {
return TOKEN_J1939_MSG_TYPE;
}
<INITIAL>. { return TOKEN_INVALID_CHAR; }
%%
DIAG_ON_FLEX() |
|
C | wireshark/wiretap/camins.c | /* camins.c
*
* File format support for Rabbit Labs CAM Inspector files
* Copyright (c) 2013 by Martin Kaiser <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/* CAM Inspector is a commercial log tool for DVB-CI
it stores recorded packets between a CI module and a DVB receiver,
using a proprietary file format
a CAM Inspector file consists of 16bit blocks
the first byte contains payload data,
the second byte contains a "transaction type"
we currently support the following transaction types
0x20 == data transfer from CI module to host
0x22 == host reads the lower byte of the size register
0x23 == host reads the higher byte of the size register
0x2A == host writes the lower byte of the size register
0x2B == host writes the higher byte of the size register
0x28 == data transfer from host to CI module
using these transaction types, we can identify and assemble data transfers
from the host to the CAM and vice versa
a host->module data transfer will use the following transactions
one 0x2A and one 0x2B transaction to write the 16bit size
<size> 0x28 transactions to transfer one byte at a time
this will be assembled into one packet
the module->host transfer is similar
a CAM Inspector file uses a 44-bit time counter to keep track of the
time. the counter is in units of 1us. a timestamp block in the file
updates a part of the global time counter. a timestamp contains a 2-bit
relative position within the time counter and an 11-bit value for
this position.
error handling
when we run into an error while assembling a data transfer, the
primary goal is to recover so that we can handle the next transfer
correctly (all files I used for testing contained errors where
apparently the logging hardware missed some bytes)
*/
#include "config.h"
#include <glib.h>
#include <string.h>
#include "wtap-int.h"
#include "file_wrappers.h"
#include "camins.h"
#define TRANS_CAM_HOST 0x20
#define TRANS_READ_SIZE_LOW 0x22
#define TRANS_READ_SIZE_HIGH 0x23
#define TRANS_HOST_CAM 0x28
#define TRANS_WRITE_SIZE_LOW 0x2A
#define TRANS_WRITE_SIZE_HIGH 0x2B
#define IS_TRANS_SIZE(x) \
((x)==TRANS_WRITE_SIZE_LOW || (x)==TRANS_WRITE_SIZE_HIGH || \
(x)==TRANS_READ_SIZE_LOW || (x)==TRANS_READ_SIZE_HIGH)
/* a block contains a timestamp if the upper three bits are 0 */
#define IS_TIMESTAMP(x) (((x) & 0xE0) == 0x00)
/* a timestamp consists of a 2-bit position, followed by an 11-bit value. */
#define TS_VALUE_SHIFT 11
#define TS_POS_MASK (0x3 << TS_VALUE_SHIFT)
#define TS_VALUE_MASK G_GUINT64_CONSTANT((1 << TS_VALUE_SHIFT) - 1)
typedef enum {
SIZE_HAVE_NONE,
SIZE_HAVE_LOW,
SIZE_HAVE_HIGH,
SIZE_HAVE_ALL
} size_read_t;
#define RESET_STAT_VALS \
{ \
*dat_trans_type = 0x00; \
*dat_len = 0x00; \
size_stat = SIZE_HAVE_NONE; \
}
#define SIZE_ADD_LOW \
{ size_stat = (size_stat==SIZE_HAVE_HIGH ? SIZE_HAVE_ALL : SIZE_HAVE_LOW); }
#define SIZE_ADD_HIGH \
{ size_stat = (size_stat==SIZE_HAVE_LOW ? SIZE_HAVE_ALL : SIZE_HAVE_HIGH); }
/* PCAP DVB-CI pseudo-header, see https://www.kaiser.cx/pcap-dvbci.html */
#define DVB_CI_PSEUDO_HDR_VER 0
#define DVB_CI_PSEUDO_HDR_LEN 4
#define DVB_CI_PSEUDO_HDR_CAM_TO_HOST 0xFF
#define DVB_CI_PSEUDO_HDR_HOST_TO_CAM 0xFE
/* Maximum number of bytes to read before making a heuristic decision
* of whether this is our file type or not. Arbitrary. */
#define CAMINS_BYTES_TO_CHECK 0x3FFFFFFFU
static int camins_file_type_subtype = -1;
void register_camins(void);
/* Detect a camins file by looking at the blocks that access the 16bit
size register. The matching blocks to access the upper and lower 8bit
must be no further than 5 blocks apart.
A file may have errors that affect the size blocks. Therefore, we
read CAMINS_BYTES_TO_CHECK bytes and require that we have many more
valid pairs than errors. */
static wtap_open_return_val detect_camins_file(FILE_T fh)
{
int err;
gchar *err_info;
guint8 block[2];
guint8 search_block = 0;
guint8 gap_count = 0;
guint32 valid_pairs = 0, invalid_pairs = 0;
guint64 read_bytes = 0;
while (wtap_read_bytes(fh, block, sizeof(block), &err, &err_info)) {
if (search_block != 0) {
/* We're searching for a matching block to complete the pair. */
if (block[1] == search_block) {
/* We found it */
valid_pairs++;
search_block = 0;
}
else {
/* We didn't find it. */
gap_count++;
if (gap_count > 5) {
/* Give up the search, we have no pair. */
invalid_pairs++;
search_block = 0;
}
}
}
else {
/* We're not searching for a matching block at the moment.
If we see a size read/write block of one type, the matching
block is the other type and we can start searching. */
if (block[1] == TRANS_READ_SIZE_LOW) {
search_block = TRANS_READ_SIZE_HIGH;
gap_count = 0;
}
else if (block[1] == TRANS_READ_SIZE_HIGH) {
search_block = TRANS_READ_SIZE_LOW;
gap_count = 0;
}
else if (block[1] == TRANS_WRITE_SIZE_LOW) {
search_block = TRANS_WRITE_SIZE_HIGH;
gap_count = 0;
}
else if (block[1] == TRANS_WRITE_SIZE_HIGH) {
search_block = TRANS_WRITE_SIZE_LOW;
gap_count = 0;
}
}
read_bytes += sizeof(block);
if (read_bytes > CAMINS_BYTES_TO_CHECK) {
err = 0;
break;
}
}
if ((err != 0) && (err != WTAP_ERR_SHORT_READ)) {
/* A real read error. */
return WTAP_OPEN_ERROR;
}
/* For valid_pairs == invalid_pairs == 0, this isn't a camins file.
Don't change > into >= */
if (valid_pairs > 10 * invalid_pairs)
return WTAP_OPEN_MINE;
return WTAP_OPEN_NOT_MINE;
}
/* update the current time counter with infos from a timestamp block */
static void process_timestamp(guint16 timestamp, guint64 *time_us)
{
guint8 pos, shift;
guint64 val;
if (!time_us)
return;
val = timestamp & TS_VALUE_MASK;
pos = (timestamp & TS_POS_MASK) >> TS_VALUE_SHIFT;
shift = TS_VALUE_SHIFT * pos;
*time_us &= ~(TS_VALUE_MASK << shift);
*time_us |= (val << shift);
}
/* find the transaction type for the data bytes of the next packet
and the number of data bytes in that packet
the fd is moved such that it can be used in a subsequent call
to retrieve the data
if requested by the caller, we increment the time counter as we
walk through the file */
static gboolean
find_next_pkt_info(FILE_T fh,
guint8 *dat_trans_type, /* transaction type used for the data bytes */
guint16 *dat_len, /* the number of data bytes in the packet */
guint64 *time_us,
int *err, gchar **err_info)
{
guint8 block[2];
size_read_t size_stat;
if (!dat_trans_type || !dat_len)
return FALSE;
RESET_STAT_VALS;
do {
if (!wtap_read_bytes_or_eof(fh, block, sizeof(block), err, err_info)) {
RESET_STAT_VALS;
return FALSE;
}
/* our strategy is to continue reading until we have a high and a
low size byte for the same direction, duplicates or spurious data
bytes are ignored */
switch (block[1]) {
case TRANS_READ_SIZE_LOW:
if (*dat_trans_type != TRANS_CAM_HOST)
RESET_STAT_VALS;
*dat_trans_type = TRANS_CAM_HOST;
*dat_len |= block[0];
SIZE_ADD_LOW;
break;
case TRANS_READ_SIZE_HIGH:
if (*dat_trans_type != TRANS_CAM_HOST)
RESET_STAT_VALS;
*dat_trans_type = TRANS_CAM_HOST;
*dat_len |= (block[0] << 8);
SIZE_ADD_HIGH;
break;
case TRANS_WRITE_SIZE_LOW:
if (*dat_trans_type != TRANS_HOST_CAM)
RESET_STAT_VALS;
*dat_trans_type = TRANS_HOST_CAM;
*dat_len |= block[0];
SIZE_ADD_LOW;
break;
case TRANS_WRITE_SIZE_HIGH:
if (*dat_trans_type != TRANS_HOST_CAM)
RESET_STAT_VALS;
*dat_trans_type = TRANS_HOST_CAM;
*dat_len |= (block[0] << 8);
SIZE_ADD_HIGH;
break;
default:
if (IS_TIMESTAMP(block[1]))
process_timestamp(pletoh16(block), time_us);
break;
}
} while (size_stat != SIZE_HAVE_ALL);
return TRUE;
}
/* buffer allocated by the caller, must be long enough to hold
dat_len bytes, ... */
static gint
read_packet_data(FILE_T fh, guint8 dat_trans_type, guint8 *buf, guint16 dat_len,
guint64 *time_us, int *err, gchar **err_info)
{
guint8 *p;
guint8 block[2];
guint16 bytes_count = 0;
if (!buf)
return -1;
/* we're not checking for end-of-file here, we read as many bytes as
we can get (up to dat_len) and return those
end-of-file will be detected when we search for the next packet */
p = buf;
while (bytes_count < dat_len) {
if (!wtap_read_bytes_or_eof(fh, block, sizeof(block), err, err_info))
break;
if (block[1] == dat_trans_type) {
*p++ = block[0];
bytes_count++;
}
else if (IS_TIMESTAMP(block[1])) {
process_timestamp(pletoh16(block), time_us);
}
else if (IS_TRANS_SIZE(block[1])) {
/* go back before the size transaction block
the next packet should be able to pick up this block */
if (-1 == file_seek(fh, -(gint64)sizeof(block), SEEK_CUR, err))
return -1;
break;
}
}
return bytes_count;
}
/* create a DVB-CI pseudo header
return its length or -1 for error */
static gint
create_pseudo_hdr(guint8 *buf, guint8 dat_trans_type, guint16 dat_len,
gchar **err_info)
{
buf[0] = DVB_CI_PSEUDO_HDR_VER;
if (dat_trans_type==TRANS_CAM_HOST)
buf[1] = DVB_CI_PSEUDO_HDR_CAM_TO_HOST;
else if (dat_trans_type==TRANS_HOST_CAM)
buf[1] = DVB_CI_PSEUDO_HDR_HOST_TO_CAM;
else {
*err_info = ws_strdup_printf("camins: invalid dat_trans_type %u", dat_trans_type);
return -1;
}
buf[2] = (dat_len>>8) & 0xFF;
buf[3] = dat_len & 0xFF;
return DVB_CI_PSEUDO_HDR_LEN;
}
static gboolean
camins_read_packet(FILE_T fh, wtap_rec *rec, Buffer *buf,
guint64 *time_us, int *err, gchar **err_info)
{
guint8 dat_trans_type;
guint16 dat_len;
guint8 *p;
gint offset, bytes_read;
if (!find_next_pkt_info(
fh, &dat_trans_type, &dat_len, time_us, err, err_info))
return FALSE;
/*
* The maximum value of length is 65535, which, even after
* DVB_CI_PSEUDO_HDR_LEN is added to it, is less than
* WTAP_MAX_PACKET_SIZE_STANDARD will ever be, so we don't need to check
* it.
*/
ws_buffer_assure_space(buf, DVB_CI_PSEUDO_HDR_LEN+dat_len);
p = ws_buffer_start_ptr(buf);
offset = create_pseudo_hdr(p, dat_trans_type, dat_len, err_info);
if (offset<0) {
/* shouldn't happen, all invalid packets must be detected by
find_next_pkt_info() */
*err = WTAP_ERR_INTERNAL;
/* create_pseudo_hdr() set err_info appropriately */
return FALSE;
}
bytes_read = read_packet_data(fh, dat_trans_type,
&p[offset], dat_len, time_us, err, err_info);
/* 0<=bytes_read<=dat_len is very likely a corrupted packet
we let the dissector handle this */
if (bytes_read < 0)
return FALSE;
offset += bytes_read;
rec->rec_type = REC_TYPE_PACKET;
rec->block = wtap_block_create(WTAP_BLOCK_PACKET);
rec->presence_flags = 0; /* we may or may not have a time stamp */
rec->rec_header.packet_header.pkt_encap = WTAP_ENCAP_DVBCI;
if (time_us) {
rec->presence_flags = WTAP_HAS_TS;
rec->ts.secs = (time_t)(*time_us / (1000 * 1000));
rec->ts.nsecs = (int)(*time_us % (1000 *1000) * 1000);
}
rec->rec_header.packet_header.caplen = offset;
rec->rec_header.packet_header.len = offset;
return TRUE;
}
static gboolean
camins_read(wtap *wth, wtap_rec *rec, Buffer *buf, int *err,
gchar **err_info, gint64 *data_offset)
{
*data_offset = file_tell(wth->fh);
return camins_read_packet(wth->fh, rec, buf, (guint64 *)(wth->priv),
err, err_info);
}
static gboolean
camins_seek_read(wtap *wth, gint64 seek_off, wtap_rec *rec, Buffer *buf,
int *err, gchar **err_info)
{
if (-1 == file_seek(wth->random_fh, seek_off, SEEK_SET, err))
return FALSE;
return camins_read_packet(wth->random_fh, rec, buf, NULL, err, err_info);
}
wtap_open_return_val camins_open(wtap *wth, int *err, gchar **err_info _U_)
{
wtap_open_return_val status;
status = detect_camins_file(wth->fh);
if (status != WTAP_OPEN_MINE) {
/* A read error or a failed heuristic. */
return status;
}
/* rewind the fh so we re-read from the beginning */
if (-1 == file_seek(wth->fh, 0, SEEK_SET, err))
return WTAP_OPEN_ERROR;
wth->file_encap = WTAP_ENCAP_DVBCI;
wth->snapshot_length = 0;
wth->file_tsprec = WTAP_TSPREC_USEC;
/* wth->priv stores a pointer to the global time counter. we update
it as we go through the file sequentially. */
wth->priv = g_new0(guint64, 1);
wth->subtype_read = camins_read;
wth->subtype_seek_read = camins_seek_read;
wth->file_type_subtype = camins_file_type_subtype;
*err = 0;
/*
* Add an IDB; we don't know how many interfaces were
* involved, so we just say one interface, about which
* we only know the link-layer type, snapshot length,
* and time stamp resolution.
*/
wtap_add_generated_idb(wth);
return WTAP_OPEN_MINE;
}
static const struct supported_block_type camins_blocks_supported[] = {
/*
* We support packet blocks, with no comments or other options.
*/
{ WTAP_BLOCK_PACKET, MULTIPLE_BLOCKS_SUPPORTED, NO_OPTIONS_SUPPORTED }
};
static const struct file_type_subtype_info camins_info = {
"CAM Inspector file", "camins", "camins", NULL,
FALSE, BLOCKS_SUPPORTED(camins_blocks_supported),
NULL, NULL, NULL
};
void register_camins(void)
{
camins_file_type_subtype = wtap_register_file_type_subtype(&camins_info);
/*
* Register name for backwards compatibility with the
* wtap_filetypes table in Lua.
*/
wtap_register_backwards_compatibility_lua_name("CAMINS",
camins_file_type_subtype);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/ |
C/C++ | wireshark/wiretap/camins.h | /** @file
*
* File format support for Rabbit Labs CAM Inspector files
* Copyright (c) 2013 by Martin Kaiser <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef _CAMINS_H
#define _CAMINS_H
#include <glib.h>
#include <wiretap/wtap.h>
wtap_open_return_val camins_open(wtap *wth, int *err, gchar **err_info _U_);
#endif /* _CAMINS_H */ |
C | wireshark/wiretap/candump.c | /* candump.c
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* Support for candump log file format
* Copyright (c) 2019 by Maksim Salau <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <config.h>
#include <wtap-int.h>
#include <file_wrappers.h>
#include <wsutil/exported_pdu_tlvs.h>
#include <string.h>
#include <inttypes.h>
#include <errno.h>
#include "candump.h"
#include "candump_priv.h"
static gboolean candump_read(wtap *wth, wtap_rec *rec, Buffer *buf,
int *err, gchar **err_info,
gint64 *data_offset);
static gboolean candump_seek_read(wtap *wth, gint64 seek_off,
wtap_rec *rec, Buffer *buf,
int *err, gchar **err_info);
static int candump_file_type_subtype = -1;
void register_candump(void);
/*
* This is written by the candump utility on Linux.
*/
static gboolean
candump_write_packet(wtap_rec *rec, Buffer *buf, const msg_t *msg, int *err,
gchar **err_info)
{
/* Generate Exported PDU tags for the packet info */
ws_buffer_clean(buf);
if (msg->is_fd)
{
wtap_buffer_append_epdu_string(buf, EXP_PDU_TAG_DISSECTOR_NAME, "canfd");
}
else
{
wtap_buffer_append_epdu_string(buf, EXP_PDU_TAG_DISSECTOR_NAME, "can-hostendian");
}
wtap_buffer_append_epdu_end(buf);
if (msg->is_fd)
{
canfd_frame_t canfd_frame = {0};
/*
* There's a maximum of CANFD_MAX_DLEN bytes in a CAN-FD frame.
*/
if (msg->data.length > CANFD_MAX_DLEN) {
*err = WTAP_ERR_BAD_FILE;
if (err_info != NULL) {
*err_info = ws_strdup_printf("candump: File has %u-byte CAN FD packet, bigger than maximum of %u",
msg->data.length, CANFD_MAX_DLEN);
}
return FALSE;
}
canfd_frame.can_id = msg->id;
canfd_frame.flags = msg->flags;
canfd_frame.len = msg->data.length;
memcpy(canfd_frame.data, msg->data.data, msg->data.length);
ws_buffer_append(buf, (guint8 *)&canfd_frame, sizeof(canfd_frame));
}
else
{
can_frame_t can_frame = {0};
/*
* There's a maximum of CAN_MAX_DLEN bytes in a CAN frame.
*/
if (msg->data.length > CAN_MAX_DLEN) {
*err = WTAP_ERR_BAD_FILE;
if (err_info != NULL) {
*err_info = ws_strdup_printf("candump: File has %u-byte CAN packet, bigger than maximum of %u",
msg->data.length, CAN_MAX_DLEN);
}
return FALSE;
}
can_frame.can_id = msg->id;
can_frame.can_dlc = msg->data.length;
memcpy(can_frame.data, msg->data.data, msg->data.length);
ws_buffer_append(buf, (guint8 *)&can_frame, sizeof(can_frame));
}
rec->rec_type = REC_TYPE_PACKET;
rec->block = wtap_block_create(WTAP_BLOCK_PACKET);
rec->presence_flags = WTAP_HAS_TS;
rec->ts = msg->ts;
rec->tsprec = WTAP_TSPREC_USEC;
rec->rec_header.packet_header.caplen = (guint32)ws_buffer_length(buf);
rec->rec_header.packet_header.len = (guint32)ws_buffer_length(buf);
return TRUE;
}
static gboolean
candump_parse(FILE_T fh, msg_t *msg, gint64 *offset, int *err, char **err_info)
{
candump_state_t state = {0};
gboolean ok;
gint64 seek_off;
#ifdef CANDUMP_DEBUG
candump_debug_printf("%s: Trying candump file decoder\n", G_STRFUNC);
#endif
state.fh = fh;
do
{
if (file_eof(fh))
return FALSE;
seek_off = file_tell(fh);
#ifdef CANDUMP_DEBUG
candump_debug_printf("%s: Starting parser at offset %" PRIi64 "\n", G_STRFUNC, seek_off);
#endif
state.file_bytes_read = 0;
ok = run_candump_parser(&state, err, err_info);
/* Rewind the file to the offset we have finished parsing */
if (file_seek(fh, seek_off + state.file_bytes_read, SEEK_SET, err) == -1)
{
g_free(*err_info);
*err = errno;
*err_info = g_strdup(g_strerror(errno));
return FALSE;
}
}
while (ok && !state.is_msg_valid);
if (!ok)
return FALSE;
#ifdef CANDUMP_DEBUG
candump_debug_printf("%s: Success\n", G_STRFUNC);
#endif
if (offset)
*offset = seek_off;
if (msg)
*msg = state.msg;
return TRUE;
}
wtap_open_return_val
candump_open(wtap *wth, int *err, char **err_info)
{
if (!candump_parse(wth->fh, NULL, NULL, err, err_info))
{
g_free(*err_info);
*err = 0;
*err_info = NULL;
return WTAP_OPEN_NOT_MINE;
}
#ifdef CANDUMP_DEBUG
candump_debug_printf("%s: This is our file\n", G_STRFUNC);
#endif
if (file_seek(wth->fh, 0, SEEK_SET, err) == -1)
{
*err = errno;
*err_info = g_strdup(g_strerror(errno));
return WTAP_OPEN_ERROR;
}
wth->priv = NULL;
wth->file_type_subtype = candump_file_type_subtype;
wth->file_encap = WTAP_ENCAP_WIRESHARK_UPPER_PDU;
wth->file_tsprec = WTAP_TSPREC_USEC;
wth->subtype_read = candump_read;
wth->subtype_seek_read = candump_seek_read;
return WTAP_OPEN_MINE;
}
static gboolean
candump_read(wtap *wth, wtap_rec *rec, Buffer *buf, int *err, gchar **err_info,
gint64 *data_offset)
{
msg_t msg;
#ifdef CANDUMP_DEBUG
candump_debug_printf("%s: Try reading at offset %" PRIi64 "\n", G_STRFUNC, file_tell(wth->fh));
#endif
if (!candump_parse(wth->fh, &msg, data_offset, err, err_info))
return FALSE;
#ifdef CANDUMP_DEBUG
candump_debug_printf("%s: Stopped at offset %" PRIi64 "\n", G_STRFUNC, file_tell(wth->fh));
#endif
return candump_write_packet(rec, buf, &msg, err, err_info);
}
static gboolean
candump_seek_read(wtap *wth , gint64 seek_off, wtap_rec *rec,
Buffer *buf, int *err, gchar **err_info)
{
msg_t msg;
#ifdef CANDUMP_DEBUG
candump_debug_printf("%s: Read at offset %" PRIi64 "\n", G_STRFUNC, seek_off);
#endif
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
{
*err = errno;
*err_info = g_strdup(g_strerror(errno));
return FALSE;
}
if (!candump_parse(wth->random_fh, &msg, NULL, err, err_info))
return FALSE;
return candump_write_packet(rec, buf, &msg, err, err_info);
}
static const struct supported_block_type candump_blocks_supported[] = {
/*
* We support packet blocks, with no comments or other options.
*/
{ WTAP_BLOCK_PACKET, MULTIPLE_BLOCKS_SUPPORTED, NO_OPTIONS_SUPPORTED }
};
static const struct file_type_subtype_info candump_info = {
"Linux candump file", "candump", NULL, NULL,
FALSE, BLOCKS_SUPPORTED(candump_blocks_supported),
NULL, NULL, NULL
};
void register_candump(void)
{
candump_file_type_subtype = wtap_register_file_type_subtype(&candump_info);
}
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/ |
C/C++ | wireshark/wiretap/candump.h | /** @file
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <[email protected]>
*
* Support for candump log file format
* Copyright (c) 2019 by Maksim Salau <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef CANDUMP_H__
#define CANDUMP_H__
#include <wiretap/wtap.h>
wtap_open_return_val
candump_open(wtap *wth, int *err, char **err_info);
#endif /* CANDUMP_H__ */ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.