language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
C++ | wireshark/ui/qt/manuf_dialog.cpp | /*
* manuf_dialog.c
*
* 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 "manuf_dialog.h"
#include <ui_manuf_dialog.h>
#include <cstdio>
#include <cstdint>
#include <QComboBox>
#include <QStandardItemModel>
#include <QPushButton>
#include <QRegularExpression>
#include <QClipboard>
#include <QAction>
#include <QButtonGroup>
#include <QCheckBox>
#include "main_application.h"
#include <epan/manuf.h>
#include <epan/strutil.h>
#include <wsutil/regex.h>
#include <utils/qt_ui_utils.h>
#define PLACEHOLDER_SEARCH_ADDR "Search address"
#define PLACEHOLDER_SEARCH_NAME "Search name"
ManufDialog::ManufDialog(QWidget &parent, CaptureFile &cf) :
WiresharkDialog(parent, cf),
ui(new Ui::ManufDialog)
{
ui->setupUi(this);
loadGeometry();
model_ = new ManufTableModel(this);
proxy_model_ = new ManufSortFilterProxyModel(this);
proxy_model_->setSourceModel(model_);
ui->manufTableView->setModel(proxy_model_);
ui->manufTableView->setContextMenuPolicy(Qt::ActionsContextMenu);
ui->manufTableView->setColumnHidden(ManufTableModel::COL_SHORT_NAME, true);
QAction *select_action = new QAction(tr("Select all"));
connect(select_action, &QAction::triggered, ui->manufTableView, &QTableView::selectAll);
ui->manufTableView->addAction(select_action);
QAction *copy_action = new QAction(tr("Copy"));
connect(copy_action, &QAction::triggered, this, &ManufDialog::copyToClipboard);
ui->manufTableView->addAction(copy_action);
QPushButton *find_button = ui->buttonBox->addButton(tr("Find"), QDialogButtonBox::ActionRole);
find_button->setDefault(true);
connect(find_button, &QPushButton::clicked, this, &ManufDialog::on_editingFinished);
QPushButton *clear_button = ui->buttonBox->addButton(tr("Clear"), QDialogButtonBox::ActionRole);
connect(clear_button, &QPushButton::clicked, this, &ManufDialog::clearFilter);
QPushButton *copy_button = ui->buttonBox->addButton(tr("Copy"), QDialogButtonBox::ApplyRole);
connect(copy_button, &QPushButton::clicked, this, &ManufDialog::copyToClipboard);
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
connect(ui->radioButtonGroup, &QButtonGroup::buttonClicked, this, &ManufDialog::on_searchToggled);
connect(ui->radioButtonGroup, &QButtonGroup::buttonClicked, this, &ManufDialog::on_editingFinished);
#else
connect(ui->radioButtonGroup, QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), this, &ManufDialog::on_searchToggled);
connect(ui->radioButtonGroup, QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), this, &ManufDialog::on_editingFinished);
#endif
connect(ui->checkShortNameButton, &QCheckBox::stateChanged, this, &ManufDialog::on_shortNameStateChanged);
ui->manufLineEdit->setPlaceholderText(tr(PLACEHOLDER_SEARCH_ADDR));
ui->hintLabel->clear();
}
ManufDialog::~ManufDialog()
{
delete ui;
}
void ManufDialog::searchVendor(QString &text)
{
QRegularExpression name_re;
name_re = QRegularExpression(text, QRegularExpression::CaseInsensitiveOption);
if (!name_re.isValid()) {
ui->hintLabel->setText(QString("<small><i>Invalid regular expression: %1</i></small>").arg(name_re.errorString()));
return;
}
proxy_model_->setFilterName(name_re);
ui->hintLabel->setText(QString("<small><i>Found %1 matches for \"%2\"</i></small>").arg(proxy_model_->rowCount()).arg(text));
}
static QByteArray convertMacAddressToByteArray(const QString &bytesString)
{
GByteArray *bytes = g_byte_array_new();
if (!hex_str_to_bytes(qUtf8Printable(bytesString), bytes, FALSE)
|| bytes->len == 0 || bytes->len > 6) {
g_byte_array_free(bytes, TRUE);
return QByteArray();
}
/* Mask out multicast/locally administered flags. */
bytes->data[0] &= 0xFC;
return gbytearray_free_to_qbytearray(bytes);
}
QString convertToMacAddress(const QByteArray& byteArray) {
QString macAddress;
for (int i = 0; i < byteArray.size(); ++i) {
macAddress += QString("%1").arg(static_cast<quint8>(byteArray[i]), 2, 16, QChar('0'));
if (i != byteArray.size() - 1) {
macAddress += ":";
}
}
return macAddress.toUpper();
}
void ManufDialog::searchPrefix(QString &text)
{
QByteArray addr;
addr = convertMacAddressToByteArray(text);
if (addr.isEmpty()) {
ui->hintLabel->setText(QString("<small><i>\"%1\" is not a valid MAC address</i></small>").arg(text));
return;
}
proxy_model_->setFilterAddress(addr);
ui->hintLabel->setText(QString("<small><i>Found %1 matches for \"%2\"</i></small>").arg(proxy_model_->rowCount()).arg(convertToMacAddress(addr)));
}
void ManufDialog::on_searchToggled(void)
{
if (ui->ouiRadioButton->isChecked())
ui->manufLineEdit->setPlaceholderText(tr(PLACEHOLDER_SEARCH_ADDR));
else if (ui->vendorRadioButton->isChecked())
ui->manufLineEdit->setPlaceholderText(tr(PLACEHOLDER_SEARCH_NAME));
else
ws_assert_not_reached();
}
void ManufDialog::on_editingFinished(void)
{
QString text = ui->manufLineEdit->text();
if (text.isEmpty())
return;
if (ui->ouiRadioButton->isChecked())
searchPrefix(text);
else if (ui->vendorRadioButton->isChecked())
searchVendor(text);
else
ws_assert_not_reached();
}
void ManufDialog::on_shortNameStateChanged(int state)
{
ui->manufTableView->setColumnHidden(ManufTableModel::COL_SHORT_NAME, state ? false : true);
}
void ManufDialog::clearFilter()
{
proxy_model_->clearFilter();
ui->manufLineEdit->clear();
ui->hintLabel->clear();
}
void ManufDialog::copyToClipboard() {
QModelIndexList selectedIndexes = ui->manufTableView->selectionModel()->selectedIndexes();
std::sort(selectedIndexes.begin(), selectedIndexes.end(), [](const QModelIndex &a, const QModelIndex &b) {
return a.row() < b.row() || (a.row() == b.row() && a.column() < b.column());
});
QAbstractItemModel *model = ui->manufTableView->model();
QString copiedData;
int previousRow = -1;
for (const QModelIndex& selectedIndex : selectedIndexes) {
// If the row changed, add a newline character
if (selectedIndex.row() != previousRow) {
if (!copiedData.isEmpty()) {
copiedData += "\n";
}
previousRow = selectedIndex.row();
}
else {
// If not the first column in the row, add a tab character
copiedData += "\t";
}
// Add the cell data to the string
copiedData += model->data(selectedIndex).toString();
}
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(copiedData);
} |
C/C++ | wireshark/ui/qt/manuf_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 MANUF_DIALOG_H
#define MANUF_DIALOG_H
#include <wireshark_dialog.h>
#include <models/manuf_table_model.h>
namespace Ui {
class ManufDialog;
}
class ManufDialog : public WiresharkDialog
{
Q_OBJECT
public:
explicit ManufDialog(QWidget &parent, CaptureFile &cf);
~ManufDialog();
private slots:
void on_searchToggled(void);
void on_editingFinished(void);
void on_shortNameStateChanged(int state);
void copyToClipboard(void);
void clearFilter(void);
private:
void searchPrefix(QString &text);
void searchVendor(QString &text);
Ui::ManufDialog *ui;
ManufTableModel *model_;
ManufSortFilterProxyModel *proxy_model_;
};
#endif // MANUF_DIALOG_H |
User Interface | wireshark/ui/qt/manuf_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ManufDialog</class>
<widget class="QDialog" name="ManufDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>503</width>
<height>394</height>
</rect>
</property>
<property name="windowTitle">
<string>MAC Address Blocks</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="1" column="0">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QRadioButton" name="ouiRadioButton">
<property name="toolTip">
<string>Search MAC address or address prefix. Special purpose bits are masked.</string>
</property>
<property name="text">
<string>MAC Address</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
<attribute name="buttonGroup">
<string notr="true">radioButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="vendorRadioButton">
<property name="toolTip">
<string>Search vendor name using a case-insentitive regular expression.</string>
</property>
<property name="text">
<string>Vendor Name</string>
</property>
<attribute name="buttonGroup">
<string notr="true">radioButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkShortNameButton">
<property name="toolTip">
<string>Show short name column.</string>
</property>
<property name="text">
<string>Short name</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item row="3" column="0">
<widget class="QLabel" name="hintLabel">
<property name="text">
<string notr="true"><small><i>A hint.</i></small></string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLineEdit" name="manufLineEdit"/>
</item>
<item row="2" column="0">
<widget class="QTableView" name="manufTableView">
<attribute name="horizontalHeaderDefaultSectionSize">
<number>140</number>
</attribute>
<attribute name="horizontalHeaderStretchLastSection">
<bool>true</bool>
</attribute>
</widget>
</item>
<item row="4" column="0">
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Close</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>ManufDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>ManufDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
<buttongroups>
<buttongroup name="radioButtonGroup"/>
</buttongroups>
</ui> |
C++ | wireshark/ui/qt/module_preferences_scroll_area.cpp | /* module_preferences_scroll_area.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "module_preferences_scroll_area.h"
#include <ui_module_preferences_scroll_area.h>
#include <ui/qt/widgets/syntax_line_edit.h>
#include "ui/qt/widgets/wireshark_file_dialog.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include "uat_dialog.h"
#include "main_application.h"
#include "ui/qt/main_window.h"
#include <ui/qt/utils/variant_pointer.h>
#include <epan/prefs-int.h>
#include <wsutil/utf8_entities.h>
#include <QAbstractButton>
#include <QButtonGroup>
#include <QCheckBox>
#include <QComboBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMainWindow>
#include <QPushButton>
#include <QRadioButton>
#include <QScrollBar>
#include <QSpacerItem>
#include <QRegularExpression>
const char *pref_prop_ = "pref_ptr";
// Escape our ampersands so that Qt won't try to interpret them as
// mnemonics.
static const QString title_to_shortcut(const char *title) {
QString shortcut_str(title);
shortcut_str.replace('&', "&&");
return shortcut_str;
}
typedef struct
{
QVBoxLayout *layout;
QString moduleName;
} prefSearchData;
extern "C" {
// Callbacks prefs routines
/* Add a single preference to the QVBoxLayout of a preference page */
static guint
pref_show(pref_t *pref, gpointer user_data)
{
prefSearchData * data = static_cast<prefSearchData *>(user_data);
if (!pref || !data) return 0;
QVBoxLayout *vb = data->layout;
// Convert the pref description from plain text to rich text.
QString description = html_escape(prefs_get_description(pref));
QString name = QString("%1.%2").arg(data->moduleName).arg(prefs_get_name(pref));
description.replace('\n', "<br/>");
QString tooltip = QString("<span>%1</span><br/><br/>%2").arg(description).arg(name);
switch (prefs_get_type(pref)) {
case PREF_UINT:
case PREF_DECODE_AS_UINT:
{
QHBoxLayout *hb = new QHBoxLayout();
QLabel *label = new QLabel(prefs_get_title(pref));
label->setToolTip(tooltip);
hb->addWidget(label);
QLineEdit *uint_le = new QLineEdit();
uint_le->setToolTip(tooltip);
uint_le->setProperty(pref_prop_, VariantPointer<pref_t>::asQVariant(pref));
uint_le->setMinimumWidth(uint_le->fontMetrics().height() * 8);
hb->addWidget(uint_le);
hb->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Minimum));
vb->addLayout(hb);
break;
}
case PREF_BOOL:
{
QCheckBox *bool_cb = new QCheckBox(title_to_shortcut(prefs_get_title(pref)));
bool_cb->setToolTip(tooltip);
bool_cb->setProperty(pref_prop_, VariantPointer<pref_t>::asQVariant(pref));
vb->addWidget(bool_cb);
break;
}
case PREF_ENUM:
{
const enum_val_t *ev;
ev = prefs_get_enumvals(pref);
if (!ev || !ev->description)
return 0;
if (prefs_get_enum_radiobuttons(pref)) {
QLabel *label = new QLabel(prefs_get_title(pref));
label->setToolTip(tooltip);
vb->addWidget(label);
QButtonGroup *enum_bg = new QButtonGroup(vb);
while (ev->description) {
QRadioButton *enum_rb = new QRadioButton(title_to_shortcut(ev->description));
enum_rb->setToolTip(tooltip);
QStyleOption style_opt;
enum_rb->setProperty(pref_prop_, VariantPointer<pref_t>::asQVariant(pref));
enum_rb->setStyleSheet(QString(
"QRadioButton {"
" margin-left: %1px;"
"}"
)
.arg(enum_rb->style()->subElementRect(QStyle::SE_CheckBoxContents, &style_opt).left()));
enum_bg->addButton(enum_rb, ev->value);
vb->addWidget(enum_rb);
ev++;
}
} else {
QHBoxLayout *hb = new QHBoxLayout();
QComboBox *enum_cb = new QComboBox();
enum_cb->setToolTip(tooltip);
enum_cb->setProperty(pref_prop_, VariantPointer<pref_t>::asQVariant(pref));
for (ev = prefs_get_enumvals(pref); ev && ev->description; ev++) {
enum_cb->addItem(ev->description, QVariant(ev->value));
}
QLabel * lbl = new QLabel(prefs_get_title(pref));
lbl->setToolTip(tooltip);
hb->addWidget(lbl);
hb->addWidget(enum_cb);
hb->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Minimum));
vb->addLayout(hb);
}
break;
}
case PREF_STRING:
{
QHBoxLayout *hb = new QHBoxLayout();
QLabel *label = new QLabel(prefs_get_title(pref));
label->setToolTip(tooltip);
hb->addWidget(label);
QLineEdit *string_le = new QLineEdit();
string_le->setToolTip(tooltip);
string_le->setProperty(pref_prop_, VariantPointer<pref_t>::asQVariant(pref));
string_le->setMinimumWidth(string_le->fontMetrics().height() * 20);
hb->addWidget(string_le);
hb->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Minimum));
vb->addLayout(hb);
break;
}
case PREF_PASSWORD:
{
QHBoxLayout *hb = new QHBoxLayout();
QLabel *label = new QLabel(prefs_get_title(pref));
label->setToolTip(tooltip);
hb->addWidget(label);
QLineEdit *string_le = new QLineEdit();
string_le->setToolTip(tooltip);
string_le->setProperty(pref_prop_, VariantPointer<pref_t>::asQVariant(pref));
string_le->setMinimumWidth(string_le->fontMetrics().height() * 20);
string_le->setEchoMode(QLineEdit::PasswordEchoOnEdit);
hb->addWidget(string_le);
hb->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Minimum));
vb->addLayout(hb);
break;
}
case PREF_DECODE_AS_RANGE:
case PREF_RANGE:
{
QHBoxLayout *hb = new QHBoxLayout();
QLabel *label = new QLabel(prefs_get_title(pref));
label->setToolTip(tooltip);
hb->addWidget(label);
SyntaxLineEdit *range_se = new SyntaxLineEdit();
range_se->setToolTip(tooltip);
range_se->setProperty(pref_prop_, VariantPointer<pref_t>::asQVariant(pref));
range_se->setMinimumWidth(range_se->fontMetrics().height() * 20);
hb->addWidget(range_se);
hb->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Minimum));
vb->addLayout(hb);
break;
}
case PREF_STATIC_TEXT:
{
QLabel *label = new QLabel(prefs_get_title(pref));
label->setToolTip(tooltip);
label->setWordWrap(true);
vb->addWidget(label);
break;
}
case PREF_UAT:
{
QHBoxLayout *hb = new QHBoxLayout();
QLabel *label = new QLabel(prefs_get_title(pref));
label->setToolTip(tooltip);
hb->addWidget(label);
QPushButton *uat_pb = new QPushButton(QObject::tr("Edit…"));
uat_pb->setToolTip(tooltip);
uat_pb->setProperty(pref_prop_, VariantPointer<pref_t>::asQVariant(pref));
hb->addWidget(uat_pb);
hb->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Minimum));
vb->addLayout(hb);
break;
}
case PREF_SAVE_FILENAME:
case PREF_OPEN_FILENAME:
case PREF_DIRNAME:
{
QLabel *label = new QLabel(prefs_get_title(pref));
label->setToolTip(tooltip);
vb->addWidget(label);
QHBoxLayout *hb = new QHBoxLayout();
QLineEdit *path_le = new QLineEdit();
path_le->setToolTip(tooltip);
QStyleOption style_opt;
path_le->setProperty(pref_prop_, VariantPointer<pref_t>::asQVariant(pref));
path_le->setMinimumWidth(path_le->fontMetrics().height() * 20);
path_le->setStyleSheet(QString(
"QLineEdit {"
" margin-left: %1px;"
"}"
)
.arg(path_le->style()->subElementRect(QStyle::SE_CheckBoxContents, &style_opt).left()));
hb->addWidget(path_le);
QPushButton *path_pb = new QPushButton(QObject::tr("Browse…"));
path_pb->setProperty(pref_prop_, VariantPointer<pref_t>::asQVariant(pref));
hb->addWidget(path_pb);
hb->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Minimum));
vb->addLayout(hb);
break;
}
case PREF_COLOR:
{
// XXX - Not needed yet. When it is needed we can add a label + QFrame which pops up a
// color picker similar to the Font and Colors prefs.
break;
}
case PREF_PROTO_TCP_SNDAMB_ENUM:
{
const enum_val_t *ev;
ev = prefs_get_enumvals(pref);
if (!ev || !ev->description)
return 0;
if (prefs_get_enum_radiobuttons(pref)) {
QLabel *label = new QLabel(prefs_get_title(pref));
label->setToolTip(tooltip);
vb->addWidget(label);
QButtonGroup *enum_bg = new QButtonGroup(vb);
while (ev->description) {
QRadioButton *enum_rb = new QRadioButton(title_to_shortcut(ev->description));
enum_rb->setToolTip(tooltip);
QStyleOption style_opt;
enum_rb->setProperty(pref_prop_, VariantPointer<pref_t>::asQVariant(pref));
enum_rb->setStyleSheet(QString(
"QRadioButton {"
" margin-left: %1px;"
"}"
)
.arg(enum_rb->style()->subElementRect(QStyle::SE_CheckBoxContents, &style_opt).left()));
enum_bg->addButton(enum_rb, ev->value);
vb->addWidget(enum_rb);
ev++;
}
} else {
QHBoxLayout *hb = new QHBoxLayout();
QComboBox *enum_cb = new QComboBox();
enum_cb->setToolTip(tooltip);
enum_cb->setProperty(pref_prop_, VariantPointer<pref_t>::asQVariant(pref));
for (ev = prefs_get_enumvals(pref); ev && ev->description; ev++) {
enum_cb->addItem(ev->description, QVariant(ev->value));
}
QLabel * lbl = new QLabel(prefs_get_title(pref));
lbl->setToolTip(tooltip);
hb->addWidget(lbl);
hb->addWidget(enum_cb);
hb->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Minimum));
vb->addLayout(hb);
}
break;
}
default:
break;
}
return 0;
}
} // extern "C"
ModulePreferencesScrollArea::ModulePreferencesScrollArea(module_t *module, QWidget *parent) :
QScrollArea(parent),
ui(new Ui::ModulePreferencesScrollArea),
module_(module)
{
ui->setupUi(this);
if (!module) return;
/* Show the preference's description at the top of the page */
QFont font;
font.setBold(TRUE);
QLabel *label = new QLabel(module->description);
label->setFont(font);
ui->verticalLayout->addWidget(label);
prefSearchData * searchData = new prefSearchData;
searchData->layout = ui->verticalLayout;
searchData->moduleName = module->name;
/* Add items for each of the preferences */
prefs_pref_foreach(module, pref_show, (gpointer) searchData);
foreach (QLineEdit *le, findChildren<QLineEdit *>()) {
pref_t *pref = VariantPointer<pref_t>::asPtr(le->property(pref_prop_));
if (!pref) continue;
switch (prefs_get_type(pref)) {
case PREF_DECODE_AS_UINT:
connect(le, &QLineEdit::textEdited, this, &ModulePreferencesScrollArea::uintLineEditTextEdited);
break;
case PREF_UINT:
connect(le, &QLineEdit::textEdited, this, &ModulePreferencesScrollArea::uintLineEditTextEdited);
break;
case PREF_STRING:
case PREF_SAVE_FILENAME:
case PREF_OPEN_FILENAME:
case PREF_DIRNAME:
case PREF_PASSWORD:
connect(le, &QLineEdit::textEdited, this, &ModulePreferencesScrollArea::stringLineEditTextEdited);
break;
case PREF_RANGE:
case PREF_DECODE_AS_RANGE:
connect(le, &QLineEdit::textEdited, this, &ModulePreferencesScrollArea::rangeSyntaxLineEditTextEdited);
break;
default:
break;
}
}
foreach (QCheckBox *cb, findChildren<QCheckBox *>()) {
pref_t *pref = VariantPointer<pref_t>::asPtr(cb->property(pref_prop_));
if (!pref) continue;
if (prefs_get_type(pref) == PREF_BOOL) {
connect(cb, &QCheckBox::toggled, this, &ModulePreferencesScrollArea::boolCheckBoxToggled);
}
}
foreach (QRadioButton *rb, findChildren<QRadioButton *>()) {
pref_t *pref = VariantPointer<pref_t>::asPtr(rb->property(pref_prop_));
if (!pref) continue;
if (prefs_get_type(pref) == PREF_ENUM && prefs_get_enum_radiobuttons(pref)) {
connect(rb, &QRadioButton::toggled, this, &ModulePreferencesScrollArea::enumRadioButtonToggled);
}
}
foreach (QComboBox *combo, findChildren<QComboBox *>()) {
pref_t *pref = VariantPointer<pref_t>::asPtr(combo->property(pref_prop_));
if (!pref) continue;
if (prefs_get_type(pref) == PREF_ENUM && !prefs_get_enum_radiobuttons(pref)) {
connect(combo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this, &ModulePreferencesScrollArea::enumComboBoxCurrentIndexChanged);
}
}
foreach (QComboBox *combo, findChildren<QComboBox *>()) {
pref_t *pref = VariantPointer<pref_t>::asPtr(combo->property(pref_prop_));
if (!pref) continue;
if (prefs_get_type(pref) == PREF_PROTO_TCP_SNDAMB_ENUM && !prefs_get_enum_radiobuttons(pref)) {
connect(combo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this, &ModulePreferencesScrollArea::enumComboBoxCurrentIndexChanged_PROTO_TCP);
}
}
foreach (QPushButton *pb, findChildren<QPushButton *>()) {
pref_t *pref = VariantPointer<pref_t>::asPtr(pb->property(pref_prop_));
if (!pref) continue;
switch (prefs_get_type(pref)) {
case PREF_UAT:
connect(pb, &QPushButton::clicked, this, &ModulePreferencesScrollArea::uatPushButtonClicked);
break;
case PREF_SAVE_FILENAME:
connect(pb, &QPushButton::clicked, this, &ModulePreferencesScrollArea::saveFilenamePushButtonClicked);
break;
case PREF_OPEN_FILENAME:
connect(pb, &QPushButton::clicked, this, &ModulePreferencesScrollArea::openFilenamePushButtonClicked);
break;
case PREF_DIRNAME:
connect(pb, &QPushButton::clicked, this, &ModulePreferencesScrollArea::dirnamePushButtonClicked);
break;
}
}
ui->verticalLayout->addSpacerItem(new QSpacerItem(10, 1, QSizePolicy::Minimum, QSizePolicy::Expanding));
}
ModulePreferencesScrollArea::~ModulePreferencesScrollArea()
{
delete ui;
}
void ModulePreferencesScrollArea::showEvent(QShowEvent *)
{
updateWidgets();
}
void ModulePreferencesScrollArea::resizeEvent(QResizeEvent *evt)
{
QScrollArea::resizeEvent(evt);
if (verticalScrollBar()->isVisible()) {
setFrameStyle(QFrame::StyledPanel);
} else {
setFrameStyle(QFrame::NoFrame);
}
}
void ModulePreferencesScrollArea::updateWidgets()
{
foreach (QLineEdit *le, findChildren<QLineEdit *>()) {
pref_t *pref = VariantPointer<pref_t>::asPtr(le->property(pref_prop_));
if (!pref) continue;
le->setText(gchar_free_to_qstring(prefs_pref_to_str(pref, pref_stashed)).remove(QRegularExpression("\n\t")));
}
foreach (QCheckBox *cb, findChildren<QCheckBox *>()) {
pref_t *pref = VariantPointer<pref_t>::asPtr(cb->property(pref_prop_));
if (!pref) continue;
if (prefs_get_type(pref) == PREF_BOOL) {
cb->setChecked(prefs_get_bool_value(pref, pref_stashed));
}
}
foreach (QRadioButton *enum_rb, findChildren<QRadioButton *>()) {
pref_t *pref = VariantPointer<pref_t>::asPtr(enum_rb->property(pref_prop_));
if (!pref) continue;
QButtonGroup *enum_bg = enum_rb->group();
if (!enum_bg) continue;
if (prefs_get_type(pref) == PREF_ENUM && prefs_get_enum_radiobuttons(pref)) {
if (prefs_get_enum_value(pref, pref_stashed) == enum_bg->id(enum_rb)) {
enum_rb->setChecked(true);
}
}
}
foreach (QComboBox *enum_cb, findChildren<QComboBox *>()) {
pref_t *pref = VariantPointer<pref_t>::asPtr(enum_cb->property(pref_prop_));
if (!pref) continue;
if (prefs_get_type(pref) == PREF_ENUM && !prefs_get_enum_radiobuttons(pref)) {
for (int i = 0; i < enum_cb->count(); i++) {
if (prefs_get_enum_value(pref, pref_stashed) == enum_cb->itemData(i).toInt()) {
enum_cb->setCurrentIndex(i);
}
}
}
if (prefs_get_type(pref) == PREF_PROTO_TCP_SNDAMB_ENUM && !prefs_get_enum_radiobuttons(pref)) {
MainWindow* topWidget = dynamic_cast<MainWindow*> (mainApp->mainWindow());
/* Ensure there is one unique or multiple selections. See issue 18642 */
if (topWidget->hasSelection() || topWidget->hasUniqueSelection()) {
frame_data * fdata = topWidget->frameDataForRow((topWidget->selectedRows()).at(0));
enum_cb->setCurrentIndex(fdata->tcp_snd_manual_analysis);
}
}
}
}
void ModulePreferencesScrollArea::uintLineEditTextEdited(const QString &new_str)
{
QLineEdit *uint_le = qobject_cast<QLineEdit*>(sender());
if (!uint_le) return;
pref_t *pref = VariantPointer<pref_t>::asPtr(uint_le->property(pref_prop_));
if (!pref) return;
bool ok;
uint new_uint = new_str.toUInt(&ok, 0);
if (ok) {
prefs_set_uint_value(pref, new_uint, pref_stashed);
}
}
void ModulePreferencesScrollArea::boolCheckBoxToggled(bool checked)
{
QCheckBox *bool_cb = qobject_cast<QCheckBox*>(sender());
if (!bool_cb) return;
pref_t *pref = VariantPointer<pref_t>::asPtr(bool_cb->property(pref_prop_));
if (!pref) return;
prefs_set_bool_value(pref, checked, pref_stashed);
}
void ModulePreferencesScrollArea::enumRadioButtonToggled(bool checked)
{
if (!checked) return;
QRadioButton *enum_rb = qobject_cast<QRadioButton*>(sender());
if (!enum_rb) return;
QButtonGroup *enum_bg = enum_rb->group();
if (!enum_bg) return;
pref_t *pref = VariantPointer<pref_t>::asPtr(enum_rb->property(pref_prop_));
if (!pref) return;
if (enum_bg->checkedId() >= 0) {
prefs_set_enum_value(pref, enum_bg->checkedId(), pref_stashed);
}
}
void ModulePreferencesScrollArea::enumComboBoxCurrentIndexChanged(int index)
{
QComboBox *enum_cb = qobject_cast<QComboBox*>(sender());
if (!enum_cb) return;
pref_t *pref = VariantPointer<pref_t>::asPtr(enum_cb->property(pref_prop_));
if (!pref) return;
prefs_set_enum_value(pref, enum_cb->itemData(index).toInt(), pref_stashed);
}
void ModulePreferencesScrollArea::stringLineEditTextEdited(const QString &new_str)
{
QLineEdit *string_le = qobject_cast<QLineEdit*>(sender());
if (!string_le) return;
pref_t *pref = VariantPointer<pref_t>::asPtr(string_le->property(pref_prop_));
if (!pref) return;
prefs_set_string_value(pref, new_str.toStdString().c_str(), pref_stashed);
}
void ModulePreferencesScrollArea::rangeSyntaxLineEditTextEdited(const QString &new_str)
{
SyntaxLineEdit *range_se = qobject_cast<SyntaxLineEdit*>(sender());
if (!range_se) return;
pref_t *pref = VariantPointer<pref_t>::asPtr(range_se->property(pref_prop_));
if (!pref) return;
if (prefs_set_stashed_range_value(pref, new_str.toUtf8().constData())) {
if (new_str.isEmpty()) {
range_se->setSyntaxState(SyntaxLineEdit::Empty);
} else {
range_se->setSyntaxState(SyntaxLineEdit::Valid);
}
} else {
range_se->setSyntaxState(SyntaxLineEdit::Invalid);
}
}
void ModulePreferencesScrollArea::uatPushButtonClicked()
{
QPushButton *uat_pb = qobject_cast<QPushButton*>(sender());
if (!uat_pb) return;
pref_t *pref = VariantPointer<pref_t>::asPtr(uat_pb->property(pref_prop_));
if (!pref) return;
UatDialog *uat_dlg = new UatDialog(this, prefs_get_uat_value(pref));
uat_dlg->setWindowModality(Qt::ApplicationModal);
uat_dlg->setAttribute(Qt::WA_DeleteOnClose);
uat_dlg->show();
}
void ModulePreferencesScrollArea::saveFilenamePushButtonClicked()
{
QPushButton *filename_pb = qobject_cast<QPushButton*>(sender());
if (!filename_pb) return;
pref_t *pref = VariantPointer<pref_t>::asPtr(filename_pb->property(pref_prop_));
if (!pref) return;
QString filename = WiresharkFileDialog::getSaveFileName(this, mainApp->windowTitleString(prefs_get_title(pref)),
prefs_get_string_value(pref, pref_stashed));
if (!filename.isEmpty()) {
prefs_set_string_value(pref, QDir::toNativeSeparators(filename).toStdString().c_str(), pref_stashed);
updateWidgets();
}
}
void ModulePreferencesScrollArea::openFilenamePushButtonClicked()
{
QPushButton *filename_pb = qobject_cast<QPushButton*>(sender());
if (!filename_pb) return;
pref_t *pref = VariantPointer<pref_t>::asPtr(filename_pb->property(pref_prop_));
if (!pref) return;
QString filename = WiresharkFileDialog::getOpenFileName(this, mainApp->windowTitleString(prefs_get_title(pref)),
prefs_get_string_value(pref, pref_stashed));
if (!filename.isEmpty()) {
prefs_set_string_value(pref, QDir::toNativeSeparators(filename).toStdString().c_str(), pref_stashed);
updateWidgets();
}
}
void ModulePreferencesScrollArea::dirnamePushButtonClicked()
{
QPushButton *dirname_pb = qobject_cast<QPushButton*>(sender());
if (!dirname_pb) return;
pref_t *pref = VariantPointer<pref_t>::asPtr(dirname_pb->property(pref_prop_));
if (!pref) return;
QString dirname = WiresharkFileDialog::getExistingDirectory(this, mainApp->windowTitleString(prefs_get_title(pref)),
prefs_get_string_value(pref, pref_stashed));
if (!dirname.isEmpty()) {
prefs_set_string_value(pref, QDir::toNativeSeparators(dirname).toStdString().c_str(), pref_stashed);
updateWidgets();
}
}
/*
* Dedicated event handling for TCP SEQ Analysis overriding.
*/
void ModulePreferencesScrollArea::enumComboBoxCurrentIndexChanged_PROTO_TCP(int index)
{
QComboBox *enum_cb = qobject_cast<QComboBox*>(sender());
if (!enum_cb) return;
pref_t *pref = VariantPointer<pref_t>::asPtr(enum_cb->property(pref_prop_));
if (!pref) return;
MainWindow* topWidget = dynamic_cast<MainWindow*> (mainApp->mainWindow());
// method 1 : apply to one single packet
/* frame_data * fdata = topWidget->frameDataForRow((topWidget->selectedRows()).at(0));
fdata->tcp_snd_manual_analysis = enum_cb->itemData(index).toInt();*/
// method 2 : we can leverage the functionality by allowing multiple selections
QList<int> rows = topWidget->selectedRows();
foreach (int row, rows) {
frame_data * fdata = topWidget->frameDataForRow(row);
fdata->tcp_snd_manual_analysis = enum_cb->itemData(index).toInt();
}
prefs_set_enum_value(pref, enum_cb->itemData(index).toInt(), pref_current);
//prefs_set_enum_value(pref, enum_cb->itemData(index).toInt(), pref_stashed);
updateWidgets();
} |
C/C++ | wireshark/ui/qt/module_preferences_scroll_area.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef MODULE_PREFERENCES_SCROLL_AREA_H
#define MODULE_PREFERENCES_SCROLL_AREA_H
#include <config.h>
#include <glib.h>
#include <epan/prefs.h>
#include <epan/prefs-int.h>
#include <QScrollArea>
namespace Ui {
class ModulePreferencesScrollArea;
}
class ModulePreferencesScrollArea : public QScrollArea
{
Q_OBJECT
public:
explicit ModulePreferencesScrollArea(module_t *module, QWidget *parent = 0);
~ModulePreferencesScrollArea();
const QString name() const { return QString(module_->name); }
protected:
void showEvent(QShowEvent *);
void resizeEvent(QResizeEvent *evt);
private:
Ui::ModulePreferencesScrollArea *ui;
module_t *module_;
void updateWidgets();
private slots:
void uintLineEditTextEdited(const QString &new_str);
void boolCheckBoxToggled(bool checked);
void enumRadioButtonToggled(bool checked);
void enumComboBoxCurrentIndexChanged(int index);
void stringLineEditTextEdited(const QString &new_str);
void rangeSyntaxLineEditTextEdited(const QString &new_str);
void uatPushButtonClicked();
void saveFilenamePushButtonClicked();
void openFilenamePushButtonClicked();
void dirnamePushButtonClicked();
void enumComboBoxCurrentIndexChanged_PROTO_TCP(int index);
};
#endif // MODULE_PREFERENCES_SCROLL_AREA_H |
User Interface | wireshark/ui/qt/module_preferences_scroll_area.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ModulePreferencesScrollArea</class>
<widget class="QScrollArea" name="ModulePreferencesScrollArea">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>ScrollArea</string>
</property>
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Plain</enum>
</property>
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="widgetResizable">
<bool>true</bool>
</property>
<widget class="QWidget" name="scrollAreaWidgetContents">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout"/>
</widget>
</widget>
<connections/>
</ui> |
C++ | wireshark/ui/qt/mtp3_summary_dialog.cpp | /* mtp3_summary_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "mtp3_summary_dialog.h"
#include <ui_mtp3_summary_dialog.h>
#include "config.h"
#include <glib.h>
#include <epan/tap.h>
#include <epan/dissectors/packet-mtp3.h>
#include "wsutil/utf8_entities.h"
#include "ui/capture_globals.h"
#include "ui/simple_dialog.h"
#include "ui/summary.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include <QTextStream>
typedef struct _mtp3_stat_si_code_t {
int num_msus;
int size;
} mtp3_stat_si_code_t;
typedef struct _mtp3_stat_t {
mtp3_addr_pc_t addr_opc;
mtp3_addr_pc_t addr_dpc;
mtp3_stat_si_code_t mtp3_si_code[MTP3_NUM_SI_CODE];
} mtp3_stat_t;
#define MTP3_MAX_NUM_OPC_DPC 50
static mtp3_stat_t mtp3_stat[MTP3_MAX_NUM_OPC_DPC];
static size_t mtp3_num_used;
Mtp3SummaryDialog::Mtp3SummaryDialog(QWidget &parent, CaptureFile &capture_file) :
WiresharkDialog(parent, capture_file),
ui(new Ui::Mtp3SummaryDialog)
{
ui->setupUi(this);
setWindowSubtitle(tr("MTP3 Summary"));
updateWidgets();
}
Mtp3SummaryDialog::~Mtp3SummaryDialog()
{
delete ui;
}
QString Mtp3SummaryDialog::summaryToHtml()
{
summary_tally summary;
memset(&summary, 0, sizeof(summary_tally));
QString section_tmpl;
QString table_begin, table_end;
QString table_row_begin, table_ul_row_begin, table_row_end;
QString table_vheader_tmpl, table_hheader15_tmpl, table_hheader25_tmpl;
QString table_data_tmpl;
section_tmpl = "<p><strong>%1</strong></p>\n";
table_begin = "<p><table>\n";
table_end = "</table></p>\n";
table_row_begin = "<tr>\n";
table_ul_row_begin = "<tr style=\"border-bottom: 1px solid gray;\">\n";
table_row_end = "</tr>\n";
table_vheader_tmpl = "<td width=\"50%\">%1:</td>"; // <th align="left"> looked odd
table_hheader15_tmpl = "<td width=\"15%\"><u>%1</u></td>";
table_hheader25_tmpl = "<td width=\"25%\"><u>%1</u></td>";
table_data_tmpl = "<td>%1</td>";
if (cap_file_.isValid()) {
/* initial computations */
summary_fill_in(cap_file_.capFile(), &summary);
#ifdef HAVE_LIBPCAP
summary_fill_in_capture(cap_file_.capFile(), &global_capture_opts, &summary);
#endif
}
QString summary_str;
QTextStream out(&summary_str);
// File Section
out << section_tmpl.arg(tr("File"));
out << table_begin;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Name"))
<< table_data_tmpl.arg(summary.filename)
<< table_row_end;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Length"))
<< table_data_tmpl.arg(file_size_to_qstring(summary.file_length))
<< table_row_end;
QString format_str = wtap_file_type_subtype_description(summary.file_type);
const char *compression_type_description = wtap_compression_type_description(summary.compression_type);
if (compression_type_description != NULL) {
format_str += QString(" (%1)").arg(compression_type_description);
}
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Format"))
<< table_data_tmpl.arg(format_str)
<< table_row_end;
if (summary.snap != 0) {
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Snapshot length"))
<< table_data_tmpl.arg(summary.snap)
<< table_row_end;
}
out << table_end;
// Data Section
out << section_tmpl.arg(tr("Data"));
out << table_begin;
if (summary.packet_count_ts == summary.packet_count &&
summary.packet_count >= 1)
{
// start time
out << table_row_begin
<< table_vheader_tmpl.arg(tr("First packet"))
<< table_data_tmpl.arg(time_t_to_qstring((time_t)summary.start_time))
<< table_row_end;
// stop time
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Last packet"))
<< table_data_tmpl.arg(time_t_to_qstring((time_t)summary.stop_time))
<< table_row_end;
// elapsed seconds (capture duration)
if (summary.packet_count_ts > 1)
{
/* elapsed seconds */
QString elapsed_str;
unsigned int elapsed_time = (unsigned int)summary.elapsed_time;
if (elapsed_time/86400)
{
elapsed_str = QString("%1 days ").arg(elapsed_time / 86400);
}
elapsed_str += QString("%1:%2:%3")
.arg(elapsed_time % 86400 / 3600, 2, 10, QChar('0'))
.arg(elapsed_time % 3600 / 60, 2, 10, QChar('0'))
.arg(elapsed_time % 60, 2, 10, QChar('0'));
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Elapsed"))
<< table_data_tmpl.arg(elapsed_str)
<< table_row_end;
}
}
// count
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Packets"))
<< table_data_tmpl.arg(summary.packet_count)
<< table_row_end;
out << table_end;
QString n_a = UTF8_EM_DASH;
int total_msus = 0;
int total_bytes = 0;
double seconds = summary.stop_time - summary.start_time;
// SI Section
out << section_tmpl.arg(tr("Service Indicator (SI) Totals"));
out << table_begin;
out << table_row_begin
<< table_hheader25_tmpl.arg(tr("SI"))
<< table_hheader15_tmpl.arg(tr("MSUs"))
<< table_hheader15_tmpl.arg(tr("MSUs/s"))
<< table_hheader15_tmpl.arg(tr("Bytes"))
<< table_hheader15_tmpl.arg(tr("Bytes/MSU"))
<< table_hheader15_tmpl.arg(tr("Bytes/s"))
<< table_row_end;
for (size_t ws_si_code = 0; ws_si_code < MTP3_NUM_SI_CODE; ws_si_code++) {
int si_msus = 0;
int si_bytes = 0;
QString msus_s_str = n_a;
QString bytes_msu_str = n_a;
QString bytes_s_str = n_a;
for (size_t stat_idx = 0; stat_idx < mtp3_num_used; stat_idx++) {
si_msus += mtp3_stat[stat_idx].mtp3_si_code[ws_si_code].num_msus;
si_bytes += mtp3_stat[stat_idx].mtp3_si_code[ws_si_code].size;
}
total_msus += si_msus;
total_bytes += si_bytes;
if (seconds > 0) {
msus_s_str = QString("%1").arg(si_msus / seconds, 1, 'f', 1);
bytes_s_str = QString("%1").arg(si_bytes / seconds, 1, 'f', 1);
}
if (si_msus > 0) {
bytes_msu_str = QString("%1").arg((double) si_bytes / si_msus, 1, 'f', 1);
}
out << table_row_begin
<< table_data_tmpl.arg(mtp3_service_indicator_code_short_vals[ws_si_code].strptr)
<< table_data_tmpl.arg(si_msus)
<< table_data_tmpl.arg(msus_s_str)
<< table_data_tmpl.arg(si_bytes)
<< table_data_tmpl.arg(bytes_msu_str)
<< table_data_tmpl.arg(bytes_s_str)
<< table_row_end;
}
out << table_end;
// Totals Section
QString total_msus_s_str = n_a;
QString total_bytes_msu_str = n_a;
QString total_bytes_s_str = n_a;
if (seconds > 0) {
total_msus_s_str = QString("%1").arg(total_msus / seconds, 1, 'f', 1);
total_bytes_s_str = QString("%1").arg(total_bytes / seconds, 1, 'f', 1);
}
if (total_msus > 0) {
total_bytes_msu_str = QString("%1").arg((double) total_bytes / total_msus, 1, 'f', 1);
}
out << section_tmpl.arg(tr("Totals"));
out << table_begin;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Total MSUs"))
<< table_data_tmpl.arg(total_msus)
<< table_row_end;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("MSUs/s"))
<< table_data_tmpl.arg(total_msus_s_str)
<< table_row_end;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Total Bytes"))
<< table_data_tmpl.arg(total_bytes)
<< table_row_end;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Average Bytes/MSU"))
<< table_data_tmpl.arg(total_bytes_msu_str)
<< table_row_end;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Average Bytes/s"))
<< table_data_tmpl.arg(total_bytes_s_str)
<< table_row_end;
out << table_end;
return summary_str;
}
void Mtp3SummaryDialog::updateWidgets()
{
ui->summaryTextEdit->setHtml(summaryToHtml());
WiresharkDialog::updateWidgets();
}
extern "C" {
void register_tap_listener_qt_mtp3_summary(void);
static void
mtp3_summary_reset(
void *tapdata)
{
mtp3_stat_t (*stat_p)[MTP3_MAX_NUM_OPC_DPC] = (mtp3_stat_t(*)[MTP3_MAX_NUM_OPC_DPC])tapdata;
mtp3_num_used = 0;
memset(stat_p, 0, MTP3_MAX_NUM_OPC_DPC * sizeof(mtp3_stat_t));
}
static tap_packet_status
mtp3_summary_packet(
void *tapdata,
packet_info *,
epan_dissect_t *,
const void *data,
tap_flags_t)
{
mtp3_stat_t (*stat_p)[MTP3_MAX_NUM_OPC_DPC] = (mtp3_stat_t(*)[MTP3_MAX_NUM_OPC_DPC])tapdata;
const mtp3_tap_rec_t *data_p = (const mtp3_tap_rec_t *)data;
size_t i;
if (data_p->mtp3_si_code >= MTP3_NUM_SI_CODE)
{
/*
* we thought this si_code was not used ?
* is MTP3_NUM_SI_CODE out of date ?
* XXX - if this is an error, report it and return TAP_PACKET_FAILED.
*/
return(TAP_PACKET_DONT_REDRAW);
}
/*
* look for opc/dpc pair
*/
i = 0;
while (i < mtp3_num_used)
{
if (memcmp(&data_p->addr_opc, &(*stat_p)[i].addr_opc, sizeof(mtp3_addr_pc_t)) == 0)
{
if (memcmp(&data_p->addr_dpc, &(*stat_p)[i].addr_dpc, sizeof(mtp3_addr_pc_t)) == 0)
{
break;
}
}
i++;
}
if (i == mtp3_num_used)
{
if (mtp3_num_used == MTP3_MAX_NUM_OPC_DPC)
{
/*
* too many
* XXX - report an error and return TAP_PACKET_FAILED?
*/
return(TAP_PACKET_DONT_REDRAW);
}
mtp3_num_used++;
}
(*stat_p)[i].addr_opc = data_p->addr_opc;
(*stat_p)[i].addr_dpc = data_p->addr_dpc;
(*stat_p)[i].mtp3_si_code[data_p->mtp3_si_code].num_msus++;
(*stat_p)[i].mtp3_si_code[data_p->mtp3_si_code].size += data_p->size;
return(TAP_PACKET_REDRAW);
}
void
register_tap_listener_qt_mtp3_summary(void)
{
GString *err_p;
memset((void *) &mtp3_stat, 0, sizeof(mtp3_stat));
err_p =
register_tap_listener("mtp3", &mtp3_stat, NULL, 0,
mtp3_summary_reset,
mtp3_summary_packet,
NULL,
NULL);
if (err_p != NULL)
{
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err_p->str);
g_string_free(err_p, TRUE);
exit(1);
}
}
} // extern "C" |
C/C++ | wireshark/ui/qt/mtp3_summary_dialog.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef MTP3_SUMMARY_DIALOG_H
#define MTP3_SUMMARY_DIALOG_H
#include "wireshark_dialog.h"
namespace Ui {
class Mtp3SummaryDialog;
}
class Mtp3SummaryDialog : public WiresharkDialog
{
Q_OBJECT
public:
explicit Mtp3SummaryDialog(QWidget &parent, CaptureFile& capture_file);
~Mtp3SummaryDialog();
private:
Ui::Mtp3SummaryDialog *ui;
QString summaryToHtml();
private slots:
void updateWidgets();
};
#endif // MTP3_SUMMARY_DIALOG_H |
User Interface | wireshark/ui/qt/mtp3_summary_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Mtp3SummaryDialog</class>
<widget class="QDialog" name="Mtp3SummaryDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>640</width>
<height>420</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTextEdit" name="summaryTextEdit">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Close</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>Mtp3SummaryDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>Mtp3SummaryDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/multicast_statistics_dialog.cpp | /* multicast_statistics_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "multicast_statistics_dialog.h"
#include <QFormLayout>
#include <QLabel>
#include <QPushButton>
#include <QTreeWidget>
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/widgets/syntax_line_edit.h>
#include "ui/simple_dialog.h"
#include <file.h>
#include "main_application.h"
enum {
col_src_addr_,
col_src_port_,
col_dst_addr_,
col_dst_port_,
col_packets_,
col_packets_s_,
col_avg_bw_,
col_max_bw_,
col_max_burst_,
col_burst_alarms_,
col_max_buffers_,
col_buffer_alarms_
};
enum {
mcast_table_type_ = 1000
};
class MulticastStatTreeWidgetItem : public QTreeWidgetItem
{
public:
MulticastStatTreeWidgetItem(QTreeWidget *parent) :
QTreeWidgetItem (parent, mcast_table_type_)
{
clear_address(&src_addr_);
clear_address(&dst_addr_);
src_port_ = 0;
dst_port_ = 0;
num_packets_ = 0;
avg_pps_ = 0;
avg_bw_ = 0;
max_bw_ = 0;
top_burst_size_ = 0;
num_bursts_ = 0;
top_buff_usage_ = 0;
num_buff_alarms_ = 0;
}
void updateStreamInfo(const mcast_stream_info_t *stream_info) {
copy_address(&src_addr_, &stream_info->src_addr);
src_port_ = stream_info->src_port;
copy_address(&dst_addr_, &stream_info->dest_addr);
dst_port_ = stream_info->dest_port;
num_packets_ = stream_info->npackets;
avg_pps_ = stream_info->apackets;
avg_bw_ = stream_info->average_bw;
max_bw_ = stream_info->element.maxbw;
top_burst_size_ = stream_info->element.topburstsize;
num_bursts_ = stream_info->element.numbursts;
top_buff_usage_ = stream_info->element.topbuffusage;
num_buff_alarms_ = stream_info->element.numbuffalarms;
draw();
}
void draw() {
setText(col_src_addr_, address_to_qstring(&src_addr_));
setText(col_src_port_, QString::number(src_port_));
setText(col_dst_addr_, address_to_qstring(&dst_addr_));
setText(col_dst_port_, QString::number(dst_port_));
setText(col_packets_, QString::number(num_packets_));
setText(col_packets_s_, QString::number(avg_pps_, 'f', 2));
setText(col_avg_bw_, bits_s_to_qstring(avg_bw_));
setText(col_max_bw_, bits_s_to_qstring(max_bw_));
setText(col_max_burst_, QString("%1 / %2ms").arg(top_burst_size_).arg(mcast_stream_burstint));
setText(col_burst_alarms_, QString::number(num_bursts_));
setText(col_max_buffers_, bits_s_to_qstring(top_buff_usage_));
setText(col_buffer_alarms_, QString::number(num_buff_alarms_));
}
bool operator< (const QTreeWidgetItem &other) const
{
if (other.type() != mcast_table_type_) return QTreeWidgetItem::operator< (other);
const MulticastStatTreeWidgetItem *other_row = static_cast<const MulticastStatTreeWidgetItem *>(&other);
switch (treeWidget()->sortColumn()) {
case col_src_addr_:
return cmp_address(&src_addr_, &other_row->src_addr_) < 0;
case col_src_port_:
return src_port_ < other_row->src_port_;
case col_dst_addr_:
return cmp_address(&dst_addr_, &other_row->dst_addr_) < 0;
case col_dst_port_:
return dst_port_ < other_row->dst_port_;
case col_packets_:
return num_packets_ < other_row->num_packets_;
case col_packets_s_:
return avg_pps_ < other_row->avg_pps_;
case col_avg_bw_:
return avg_bw_ < other_row->avg_bw_;
case col_max_bw_:
return max_bw_ < other_row->max_bw_;
case col_max_burst_:
return top_burst_size_ < other_row->top_burst_size_;
case col_burst_alarms_:
return num_bursts_ < other_row->num_bursts_;
case col_max_buffers_:
return top_buff_usage_ < other_row->top_buff_usage_;
case col_buffer_alarms_:
return num_buff_alarms_ < other_row->num_buff_alarms_;
default:
break;
}
return QTreeWidgetItem::operator< (other);
}
QList<QVariant> rowData() {
return QList<QVariant>()
<< address_to_qstring(&src_addr_) << src_port_
<< address_to_qstring(&dst_addr_) << dst_port_
<< num_packets_ << avg_pps_
<< avg_bw_ << max_bw_
<< top_burst_size_ << num_bursts_
<< top_buff_usage_ << num_buff_alarms_;
}
const QString filterExpression() {
QString ip_version;
if (src_addr_.type == AT_IPv6) ip_version = "v6";
const QString filter_expr = QString("(ip%1.src==%2 && udp.srcport==%3 && ip%1.dst==%4 && udp.dstport==%5)")
.arg(ip_version)
.arg(address_to_qstring(&src_addr_))
.arg(src_port_)
.arg(address_to_qstring(&dst_addr_))
.arg(dst_port_);
return filter_expr;
}
private:
address src_addr_;
guint16 src_port_;
address dst_addr_;
guint16 dst_port_;
unsigned num_packets_;
double avg_pps_;
double avg_bw_;
double max_bw_;
int top_burst_size_;
int num_bursts_;
int top_buff_usage_;
int num_buff_alarms_;
};
MulticastStatisticsDialog::MulticastStatisticsDialog(QWidget &parent, CaptureFile &cf, const char *filter) :
TapParameterDialog(parent, cf)
{
setWindowSubtitle(tr("UDP Multicast Streams"));
loadGeometry(parent.width() * 4 / 5, parent.height() * 3 / 4, "MulticastStatisticsDialog");
tapinfo_ = new mcaststream_tapinfo_t();
tapinfo_->user_data = this;
tapinfo_->tap_reset = tapReset;
tapinfo_->tap_draw = tapDraw;
QStringList header_names = QStringList()
<< tr("Source Address") << tr("Source Port")
<< tr("Destination Address") << tr("Destination Port")
<< tr("Packets") << tr("Packets/s")
<< tr("Avg BW (bps)") << tr("Max BW (bps)")
<< tr("Max Burst") << tr("Burst Alarms")
<< tr("Max Buffers (B)") << tr("Buffer Alarms");
statsTreeWidget()->setHeaderLabels(header_names);
for (int col = 0; col < statsTreeWidget()->columnCount(); col++) {
if (col == col_src_addr_ || col == col_dst_addr_) continue;
statsTreeWidget()->headerItem()->setTextAlignment(col, Qt::AlignRight);
}
burst_measurement_interval_le_ = new SyntaxLineEdit(this);
burst_alarm_threshold_le_ = new SyntaxLineEdit(this);
buffer_alarm_threshold_le_ = new SyntaxLineEdit(this);
stream_empty_speed_le_ = new SyntaxLineEdit(this);
total_empty_speed_le_ = new SyntaxLineEdit(this);
int filter_layout_idx = verticalLayout()->indexOf(filterLayout()->widget());
QGridLayout *param_grid = new QGridLayout();
int one_em = fontMetrics().height();
verticalLayout()->insertLayout(filter_layout_idx, param_grid);
// Label | LineEdit | | Label | LineEdit | | Label | LineEdit
// 0 1 2 3 4 5 6 7
param_grid->setColumnMinimumWidth(2, one_em * 2);
param_grid->setColumnStretch(2, 1);
param_grid->setColumnMinimumWidth(5, one_em * 2);
param_grid->setColumnStretch(5, 1);
param_grid->addWidget(new QLabel(tr("Burst measurement interval (ms):")), 0, 0, Qt::AlignRight);
param_grid->addWidget(burst_measurement_interval_le_, 0, 1);
param_grid->addWidget(new QLabel(tr("Burst alarm threshold (packets):")), 0, 3, Qt::AlignRight);
param_grid->addWidget(burst_alarm_threshold_le_, 0, 4);
param_grid->addWidget(new QLabel(tr("Buffer alarm threshold (B):")), 0, 6, Qt::AlignRight);
param_grid->addWidget(buffer_alarm_threshold_le_, 0, 7);
param_grid->addWidget(new QLabel(tr("Stream empty speed (Kb/s):")), 1, 0, Qt::AlignRight);
param_grid->addWidget(stream_empty_speed_le_, 1, 1);
param_grid->addWidget(new QLabel(tr("Total empty speed (Kb/s):")), 1, 3, Qt::AlignRight);
param_grid->addWidget(total_empty_speed_le_, 1, 4);
burst_measurement_interval_le_->setText(QString::number(mcast_stream_burstint));
burst_alarm_threshold_le_->setText(QString::number(mcast_stream_trigger));
buffer_alarm_threshold_le_->setText(QString::number(mcast_stream_bufferalarm));
stream_empty_speed_le_->setText(QString::number(mcast_stream_emptyspeed));
total_empty_speed_le_->setText(QString::number(mcast_stream_cumulemptyspeed));
line_edits_ = QList<QWidget *>()
<< burst_measurement_interval_le_ << burst_alarm_threshold_le_
<< buffer_alarm_threshold_le_ << stream_empty_speed_le_
<< total_empty_speed_le_;
foreach (QWidget *w, line_edits_) {
QLineEdit *line_edit = qobject_cast<QLineEdit *>(w);
line_edit->setMinimumWidth(one_em * 5);
connect(line_edit, &QLineEdit::textEdited, this, &MulticastStatisticsDialog::updateWidgets);
}
addFilterActions();
if (filter) {
setDisplayFilter(filter);
}
connect(this, &MulticastStatisticsDialog::updateFilter,
this, &MulticastStatisticsDialog::updateMulticastParameters);
/* Register the tap listener */
GString * error_string = register_tap_listener_mcast_stream(tapinfo_);
if (error_string != NULL) {
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
"%s", error_string->str);
g_string_free(error_string, TRUE);
exit(1);
}
updateWidgets();
}
MulticastStatisticsDialog::~MulticastStatisticsDialog()
{
/* Remove the stream tap listener */
remove_tap_listener_mcast_stream(tapinfo_);
/* Clean up memory used by stream tap */
mcaststream_reset(tapinfo_);
delete tapinfo_;
}
void MulticastStatisticsDialog::tapReset(mcaststream_tapinfo_t *tapinfo)
{
MulticastStatisticsDialog *ms_dlg = dynamic_cast<MulticastStatisticsDialog *>((MulticastStatisticsDialog*)tapinfo->user_data);
if (!ms_dlg || !ms_dlg->statsTreeWidget()) return;
ms_dlg->statsTreeWidget()->clear();
}
void MulticastStatisticsDialog::tapDraw(mcaststream_tapinfo_t *tapinfo)
{
MulticastStatisticsDialog *ms_dlg = dynamic_cast<MulticastStatisticsDialog *>((MulticastStatisticsDialog*)tapinfo->user_data);
if (!ms_dlg || !ms_dlg->statsTreeWidget()) return;
//Clear the tree because the list always starts from the beginning
ms_dlg->statsTreeWidget()->clear();
// Add missing rows and update stats
int cur_row = 0;
for (GList *cur = g_list_first(tapinfo->strinfo_list); cur; cur = gxx_list_next(cur)) {
mcast_stream_info_t *stream_info = gxx_list_data(mcast_stream_info_t *, cur);
if (!stream_info) continue;
MulticastStatTreeWidgetItem *ms_ti;
QTreeWidgetItem *ti = ms_dlg->statsTreeWidget()->topLevelItem(cur_row);
if (!ti) {
ms_ti = new MulticastStatTreeWidgetItem(ms_dlg->statsTreeWidget());
for (int col = 0; col < ms_dlg->statsTreeWidget()->columnCount(); col++) {
if (col == col_src_addr_ || col == col_dst_addr_) continue;
ms_ti->setTextAlignment(col, Qt::AlignRight);
}
} else {
ms_ti = static_cast<MulticastStatTreeWidgetItem *>(ti);
}
ms_ti->updateStreamInfo(stream_info);
cur_row++;
}
}
QList<QVariant> MulticastStatisticsDialog::treeItemData(QTreeWidgetItem *ti) const
{
MulticastStatTreeWidgetItem *ms_ti = dynamic_cast<MulticastStatTreeWidgetItem*>(ti);
if (ms_ti) {
return ms_ti->rowData();
}
else {
return QList<QVariant>();
}
}
const QString MulticastStatisticsDialog::filterExpression()
{
QString filter_expr;
if (statsTreeWidget()->selectedItems().count() > 0) {
QTreeWidgetItem *ti = statsTreeWidget()->selectedItems()[0];
MulticastStatTreeWidgetItem *ms_ti = static_cast<MulticastStatTreeWidgetItem *>(ti);
filter_expr = ms_ti->filterExpression();
}
return filter_expr;
}
void MulticastStatisticsDialog::updateWidgets()
{
QString hint;
bool enable_apply = true;
bool enable_edits = cap_file_.isValid();
bool ok = false;
int param;
param = burst_measurement_interval_le_->text().toUInt(&ok);
if (!ok || param < 1 || param > 1000) {
hint += tr("The burst interval must be between 1 and 1000. ");
enable_apply = false;
burst_measurement_interval_le_->setSyntaxState(SyntaxLineEdit::Invalid);
} else {
burst_measurement_interval_le_->setSyntaxState(SyntaxLineEdit::Valid);
}
param = burst_alarm_threshold_le_->text().toInt(&ok);
if (!ok || param < 1) {
hint += tr("The burst alarm threshold isn't valid. ");
enable_apply = false;
burst_alarm_threshold_le_->setSyntaxState(SyntaxLineEdit::Invalid);
} else {
burst_alarm_threshold_le_->setSyntaxState(SyntaxLineEdit::Valid);
}
param = buffer_alarm_threshold_le_->text().toInt(&ok);
if (!ok || param < 1) {
hint += tr("The buffer alarm threshold isn't valid. ");
enable_apply = false;
buffer_alarm_threshold_le_->setSyntaxState(SyntaxLineEdit::Invalid);
} else {
buffer_alarm_threshold_le_->setSyntaxState(SyntaxLineEdit::Valid);
}
param = stream_empty_speed_le_->text().toInt(&ok);
if (!ok || param < 1 || param > 10000000) {
hint += tr("The stream empty speed should be between 1 and 10000000. ");
enable_apply = false;
stream_empty_speed_le_->setSyntaxState(SyntaxLineEdit::Invalid);
} else {
stream_empty_speed_le_->setSyntaxState(SyntaxLineEdit::Valid);
}
param = total_empty_speed_le_->text().toInt(&ok);
if (!ok || param < 1 || param > 10000000) {
hint += tr("The total empty speed should be between 1 and 10000000. ");
enable_apply = false;
total_empty_speed_le_->setSyntaxState(SyntaxLineEdit::Invalid);
} else {
total_empty_speed_le_->setSyntaxState(SyntaxLineEdit::Valid);
}
foreach (QWidget *line_edit, line_edits_) {
line_edit->setEnabled(enable_edits);
}
applyFilterButton()->setEnabled(enable_apply);
if (hint.isEmpty() && tapinfo_->allstreams) {
const QString stats = tr("%1 streams, avg bw: %2bps, max bw: %3bps, max burst: %4 / %5ms, max buffer: %6B")
.arg(statsTreeWidget()->topLevelItemCount())
.arg(bits_s_to_qstring(tapinfo_->allstreams->average_bw))
.arg(bits_s_to_qstring(tapinfo_->allstreams->element.maxbw))
.arg(tapinfo_->allstreams->element.topburstsize)
.arg(mcast_stream_burstint)
.arg(bits_s_to_qstring(tapinfo_->allstreams->element.topbuffusage));
hint.append(stats);
}
hint.prepend("<small><i>");
hint.append("</i></small>");
setHint(hint);
TapParameterDialog::updateWidgets();
}
void MulticastStatisticsDialog::updateMulticastParameters()
{
bool ok = false;
int param;
param = burst_measurement_interval_le_->text().toUInt(&ok);
if (ok && param > 0 && param <= 1000) {
mcast_stream_burstint = (guint16) param;
}
param = burst_alarm_threshold_le_->text().toInt(&ok);
if (ok) {
mcast_stream_trigger = param;
}
param = buffer_alarm_threshold_le_->text().toInt(&ok);
if (ok && param > 0) {
mcast_stream_bufferalarm = param;
}
param = stream_empty_speed_le_->text().toInt(&ok);
if (ok && param > 0 && param <= 10000000) {
mcast_stream_emptyspeed = param;
}
param = total_empty_speed_le_->text().toInt(&ok);
if (ok && param > 0 && param <= 10000000) {
mcast_stream_cumulemptyspeed = param;
}
}
void MulticastStatisticsDialog::fillTree()
{
QList<QWidget *> disable_widgets = QList<QWidget *>()
<< line_edits_ << displayFilterLineEdit() << applyFilterButton();
foreach (QWidget *w, disable_widgets) w->setEnabled(false);
rescan();
foreach (QWidget *w, disable_widgets) w->setEnabled(true);
for (int col = 0; col < statsTreeWidget()->columnCount() - 1; col++) {
statsTreeWidget()->resizeColumnToContents(col);
}
updateWidgets();
}
void MulticastStatisticsDialog::rescan()
{
gboolean was_registered = tapinfo_->is_registered;
if (!tapinfo_->is_registered)
register_tap_listener_mcast_stream(tapinfo_);
cf_retap_packets(cap_file_.capFile());
if (!was_registered)
remove_tap_listener_mcast_stream(tapinfo_);
tapDraw(tapinfo_);
}
void MulticastStatisticsDialog::captureFileClosing()
{
/* Remove the stream tap listener */
remove_tap_listener_mcast_stream(tapinfo_);
WiresharkDialog::captureFileClosing();
}
// Stat command + args
static void
multicast_statistics_init(const char *args, void*) {
QStringList args_l = QString(args).split(',');
QByteArray filter;
if (args_l.length() > 2) {
filter = QStringList(args_l.mid(2)).join(",").toUtf8();
}
mainApp->emitStatCommandSignal("MulticastStatistics", filter.constData(), NULL);
}
static stat_tap_ui multicast_statistics_ui = {
REGISTER_STAT_GROUP_GENERIC,
NULL,
"multicast,stat",
multicast_statistics_init,
0,
NULL
};
extern "C" {
void register_tap_listener_qt_multicast_statistics(void);
void
register_tap_listener_qt_multicast_statistics(void)
{
register_stat_tap_ui(&multicast_statistics_ui, NULL);
}
} |
C/C++ | wireshark/ui/qt/multicast_statistics_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 MULTICASTSTATISTICSDIALOG_H
#define MULTICASTSTATISTICSDIALOG_H
#include "tap_parameter_dialog.h"
#include "ui/mcast_stream.h"
class SyntaxLineEdit;
class MulticastStatisticsDialog : public TapParameterDialog
{
Q_OBJECT
public:
MulticastStatisticsDialog(QWidget &parent, CaptureFile &cf, const char *filter = NULL);
~MulticastStatisticsDialog();
protected:
void captureFileClosing();
private:
struct _mcaststream_tapinfo *tapinfo_;
SyntaxLineEdit *burst_measurement_interval_le_;
SyntaxLineEdit *burst_alarm_threshold_le_;
SyntaxLineEdit *buffer_alarm_threshold_le_;
SyntaxLineEdit *stream_empty_speed_le_;
SyntaxLineEdit *total_empty_speed_le_;
QList<QWidget *> line_edits_;
// Callbacks for register_tap_listener
static void tapReset(mcaststream_tapinfo_t *tapinfo);
static void tapDraw(mcaststream_tapinfo_t *tapinfo);
void rescan();
virtual QList<QVariant> treeItemData(QTreeWidgetItem *ti) const;
virtual const QString filterExpression();
private slots:
void updateWidgets();
void updateMulticastParameters();
virtual void fillTree();
};
#endif // MULTICASTSTATISTICSDIALOG_H |
C++ | wireshark/ui/qt/packet_comment_dialog.cpp | /* packet_comment_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "packet_comment_dialog.h"
#include <ui_packet_comment_dialog.h>
#include "main_application.h"
PacketCommentDialog::PacketCommentDialog(bool isEdit, QWidget *parent, QString comment) :
GeometryStateDialog(parent),
pc_ui_(new Ui::PacketCommentDialog)
{
QString title = isEdit
? tr("Edit Packet Comment")
: tr("Add Packet Comment");
pc_ui_->setupUi(this);
loadGeometry();
setWindowTitle(mainApp->windowTitleString(title));
pc_ui_->commentTextEdit->setPlainText(comment);
}
PacketCommentDialog::~PacketCommentDialog()
{
delete pc_ui_;
}
QString PacketCommentDialog::text()
{
return pc_ui_->commentTextEdit->toPlainText();
}
void PacketCommentDialog::on_buttonBox_helpRequested()
{
// mainApp->helpTopicAction(HELP_PACKET_COMMENT_DIALOG);
} |
C/C++ | wireshark/ui/qt/packet_comment_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 PACKET_COMMENT_DIALOG_H
#define PACKET_COMMENT_DIALOG_H
#include <glib.h>
#include "geometry_state_dialog.h"
namespace Ui {
class PacketCommentDialog;
}
class PacketCommentDialog : public GeometryStateDialog
{
Q_OBJECT
public:
explicit PacketCommentDialog(bool isEdit, QWidget *parent = 0, QString comment = QString());
~PacketCommentDialog();
QString text();
private slots:
void on_buttonBox_helpRequested();
private:
Ui::PacketCommentDialog *pc_ui_;
};
#endif // PACKET_COMMENT_DIALOG_H |
User Interface | wireshark/ui/qt/packet_comment_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>PacketCommentDialog</class>
<widget class="QDialog" name="PacketCommentDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="modal">
<bool>true</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QPlainTextEdit" name="commentTextEdit"/>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Help|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>PacketCommentDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>PacketCommentDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/packet_diagram.cpp | /* packet_diagram.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "packet_diagram.h"
#include "math.h"
#include "epan/epan.h"
#include "epan/epan_dissect.h"
#include "wsutil/utf8_entities.h"
#include "main_application.h"
#include "ui/qt/main_window.h"
#include "ui/qt/capture_file_dialog.h"
#include "ui/qt/utils/proto_node.h"
#include "ui/qt/utils/variant_pointer.h"
#include "ui/recent.h"
#include <QClipboard>
#include <QContextMenuEvent>
#include <QGraphicsItem>
#include <QMenu>
#include <QStyleOptionGraphicsItem>
#if defined(QT_SVG_LIB) && 0
#include <QBuffer>
#include <QMimeData>
#include <QSvgGenerator>
#endif
// Item offsets and lengths
//#define DEBUG_PACKET_DIAGRAM 1
#ifdef DEBUG_PACKET_DIAGRAM
#include <QDebug>
#endif
// "rems" are root em widths, aka the regular font height, similar to rems in CSS.
class DiagramLayout {
public:
DiagramLayout() :
bits_per_row_(32),
small_font_rems_(0.75),
bit_width_rems_(1.0),
padding_rems_(0.5),
span_mark_offset_rems_(0.2)
{
setFont(mainApp->font());
}
void setFont(QFont font) {
regular_font_ = font;
small_font_ = font;
small_font_.setPointSize(regular_font_.pointSize() * small_font_rems_);
QFontMetrics fm(regular_font_);
root_em_ = fm.height();
}
void setShowFields(bool show_fields = false) { recent.gui_packet_diagram_field_values = show_fields; }
int bitsPerRow() const { return bits_per_row_; }
const QFont regularFont() const { return regular_font_; }
const QFont smallFont() const { return small_font_; }
int bitWidth() const { return root_em_ * bit_width_rems_; }
int lineHeight() const { return root_em_; }
int hPadding() const { return root_em_ * padding_rems_; }
int vPadding() const { return root_em_ * padding_rems_; }
int spanMarkOffset() const { return root_em_ * span_mark_offset_rems_; }
int rowHeight() const {
int rows = recent.gui_packet_diagram_field_values ? 2 : 1;
return ((lineHeight() * rows) + (vPadding() * 2));
}
bool showFields() const { return recent.gui_packet_diagram_field_values; }
private:
int bits_per_row_;
double small_font_rems_;
double bit_width_rems_;
double padding_rems_;
double span_mark_offset_rems_; // XXX Make this padding_rems_ / 2 instead?
QFont regular_font_;
QFont small_font_;
int root_em_;
};
class FieldInformationGraphicsItem : public QGraphicsPolygonItem
{
public:
FieldInformationGraphicsItem(field_info *fi, int start_bit, int fi_length, const DiagramLayout *layout, QGraphicsItem *parent = nullptr) :
QGraphicsPolygonItem(QPolygonF(), parent),
finfo_(new FieldInformation(fi)),
representation_("Unknown"),
start_bit_(start_bit),
layout_(layout),
collapsed_len_(fi_length),
collapsed_row_(-1)
{
Q_ASSERT(layout_);
for (int idx = 0; idx < NumSpanMarks; idx++) {
span_marks_[idx] = new QGraphicsLineItem(this);
span_marks_[idx]->hide();
}
int bits_per_row = layout_->bitsPerRow();
int row1_start = start_bit_ % bits_per_row;
int bits_remain = fi_length;
int row1_bits = bits_remain;
if (bits_remain + row1_start > bits_per_row) {
row1_bits = bits_per_row - row1_start;
bits_remain -= row1_bits;
if (row1_start == 0 && bits_remain >= bits_per_row) {
// Collapse first row
bits_remain %= bits_per_row;
collapsed_row_ = 0;
}
} else {
bits_remain = 0;
}
int row2_bits = bits_remain;
if (bits_remain > bits_per_row) {
row2_bits = bits_per_row;
bits_remain -= bits_per_row;
if (bits_remain > bits_per_row) {
// Collapse second row
bits_remain %= bits_per_row;
collapsed_row_ = 1;
}
} else {
bits_remain = 0;
}
int row3_bits = bits_remain;
collapsed_len_ = row1_bits + row2_bits + row3_bits;
QRectF rr1, rr2, rr3;
QRectF row_rect = QRectF(row1_start, 0, row1_bits, 1);
unit_shape_ = QPolygonF(row_rect);
rr1 = row_rect;
unit_tr_ = row_rect;
if (row2_bits > 0) {
row_rect = QRectF(0, 1, row2_bits, 1);
unit_shape_ = unit_shape_.united(QPolygonF(row_rect));
rr2 = row_rect;
if (row2_bits > row1_bits) {
unit_tr_ = row_rect;
}
if (row3_bits > 0) {
row_rect = QRectF(0, 2, row3_bits, 1);
unit_shape_ = unit_shape_.united(QPolygonF(row_rect));
rr3 = row_rect;
}
QPainterPath pp;
pp.addPolygon(unit_shape_);
unit_shape_ = pp.simplified().toFillPolygon();
}
updateLayout();
if (finfo_->isValid()) {
setToolTip(QString("%1 (%2) = %3")
.arg(finfo_->headerInfo().name)
.arg(finfo_->headerInfo().abbreviation)
.arg(finfo_->toString()));
setData(Qt::UserRole, VariantPointer<field_info>::asQVariant(finfo_->fieldInfo()));
representation_ = fi->rep->representation;
} else {
setToolTip(QObject::tr("Gap in dissection"));
}
}
~FieldInformationGraphicsItem()
{
delete finfo_;
}
int collapsedLength() { return collapsed_len_; }
void setPos(qreal x, qreal y) {
QGraphicsPolygonItem::setPos(x, y);
updateLayout();
}
int maxLeftY() {
qreal rel_len = (start_bit_ % layout_->bitsPerRow()) + collapsed_len_;
QPointF pt = mapToParent(QPointF(0, ceil(rel_len / layout_->bitsPerRow()) * layout_->rowHeight()));
return pt.y();
}
int maxRightY() {
qreal rel_len = (start_bit_ % layout_->bitsPerRow()) + collapsed_len_;
QPointF pt = mapToParent(QPointF(0, floor(rel_len / layout_->bitsPerRow()) * layout_->rowHeight()));
return pt.y();
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) {
painter->setPen(Qt::NoPen);
painter->save();
if (!finfo_->isValid()) {
QBrush brush = QBrush(option->palette.text().color(), Qt::BDiagPattern);
painter->setBrush(brush);
} else if (isSelected()) {
painter->setBrush(option->palette.highlight().color());
}
painter->drawPolygon(polygon());
painter->restore();
// Lower and inner right borders
painter->setPen(option->palette.text().color());
QPolygonF shape = polygon();
for (int idx = 1; idx < unit_shape_.size(); idx++) {
QPointF u_start = unit_shape_[idx - 1];
QPointF u_end = unit_shape_[idx];
QPointF start, end;
bool draw_line = false;
if (u_start.y() > 0 && u_start.y() == u_end.y()) {
draw_line = true;
} else if (u_start.x() > 0 && u_start.x() < layout_->bitsPerRow() && u_start.x() == u_end.x()) {
draw_line = true;
}
if (draw_line) {
start = shape[idx - 1];
end = shape[idx];
painter->drawLine(start, end);
}
}
if (!finfo_->isValid()) {
return;
}
// Field label(s)
QString label;
if (finfo_->headerInfo().type == FT_NONE) {
label = representation_;
} else {
label = finfo_->headerInfo().name;
}
paintLabel(painter, label, scaled_tr_);
if (layout_->showFields()) {
label = finfo_->toString();
paintLabel(painter, label, scaled_tr_.adjusted(0, scaled_tr_.height(), 0, scaled_tr_.height()));
}
}
private:
enum SpanMark {
TopLeft,
BottomLeft,
TopRight,
BottomRight,
NumSpanMarks
};
FieldInformation *finfo_;
QString representation_;
int start_bit_;
const DiagramLayout *layout_;
int collapsed_len_;
int collapsed_row_;
QPolygonF unit_shape_;
QRectF unit_tr_;
QRectF scaled_tr_;
QGraphicsLineItem *span_marks_[NumSpanMarks];
void updateLayout() {
QTransform xform;
xform.scale(layout_->bitWidth(), layout_->rowHeight());
setPolygon(xform.map(unit_shape_));
scaled_tr_ = xform.mapRect(unit_tr_);
scaled_tr_.adjust(layout_->hPadding(), layout_->vPadding(), -layout_->hPadding(), -layout_->vPadding());
scaled_tr_.setHeight(layout_->lineHeight());
// Collapsed / span marks
for (int idx = 0; idx < NumSpanMarks; idx++) {
span_marks_[idx]->hide();
}
if (collapsed_row_ >= 0) {
QRectF bounding_rect = polygon().boundingRect();
qreal center_y = bounding_rect.top() + (layout_->rowHeight() * collapsed_row_) + (layout_->rowHeight() / 2);
qreal mark_w = layout_->bitWidth() / 3; // Each mark side to center
QLineF span_l = QLineF(-mark_w, mark_w / 2, mark_w, -mark_w / 2);
for (int idx = 0; idx < NumSpanMarks; idx++) {
QPointF center;
switch (idx) {
case TopLeft:
center = QPointF(bounding_rect.left(), center_y - layout_->spanMarkOffset());
break;
case BottomLeft:
center = QPointF(bounding_rect.left(), center_y + layout_->spanMarkOffset());
break;
case TopRight:
center = QPointF(bounding_rect.right(), center_y - layout_->spanMarkOffset());
break;
case BottomRight:
center = QPointF(bounding_rect.right(), center_y + layout_->spanMarkOffset());
break;
}
span_marks_[idx]->setLine(span_l.translated(center));
span_marks_[idx]->setZValue(zValue() - 0.1);
span_marks_[idx]->show();
}
}
}
void paintLabel(QPainter *painter, QString label, QRectF label_rect) {
QFontMetrics fm = QFontMetrics(layout_->regularFont());
painter->setFont(layout_->regularFont());
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
int label_w = fm.horizontalAdvance(label);
#else
int label_w = fm.width(label);
#endif
if (label_w > label_rect.width()) {
painter->setFont(layout_->smallFont());
fm = QFontMetrics(layout_->smallFont());
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
label_w = fm.horizontalAdvance(label);
#else
label_w = fm.width(label);
#endif
if (label_w > label_rect.width()) {
// XXX Use parent+ItemClipsChildrenToShape or setScale instead?
label = fm.elidedText(label, Qt::ElideRight, label_rect.width());
}
}
painter->drawText(label_rect, Qt::AlignCenter, label);
}
};
PacketDiagram::PacketDiagram(QWidget *parent) :
QGraphicsView(parent),
layout_(new DiagramLayout),
cap_file_(nullptr),
root_node_(nullptr),
selected_field_(nullptr),
y_pos_(0)
{
setAccessibleName(tr("Packet diagram"));
setRenderHint(QPainter::Antialiasing);
// XXX Move to setMonospaceFont similar to ProtoTree
layout_->setFont(font());
connect(mainApp, &MainApplication::appInitialized, this, &PacketDiagram::connectToMainWindow);
connect(mainApp, &MainApplication::zoomRegularFont, this, &PacketDiagram::setFont);
resetScene();
}
PacketDiagram::~PacketDiagram()
{
delete layout_;
}
void PacketDiagram::setRootNode(proto_node *root_node)
{
// As https://doc.qt.io/qt-5/qgraphicsscene.html#clear says, this
// "Removes and deletes all items from the scene, but otherwise leaves
// the state of the scene unchanged."
// This means that the scene rect grows but doesn't shrink, which is
// useful in our case because it gives us a cheap way to retain our
// scroll position between packets.
scene()->clear();
selected_field_ = nullptr;
y_pos_ = 0;
root_node_ = root_node;
if (!isVisible() || !root_node) {
return;
}
ProtoNode parent_node(root_node_);
if (!parent_node.isValid()) {
return;
}
ProtoNode::ChildIterator kids = parent_node.children();
while (kids.element().isValid())
{
proto_node *tl_node = kids.element().protoNode();
kids.next();
// Exclude all ("Frame") and nothing
if (tl_node->finfo->start == 0 && tl_node->finfo->length == (int) tvb_captured_length(cap_file_->edt->tvb)) {
continue;
}
if (tl_node->finfo->length < 1) {
continue;
}
addDiagram(tl_node);
}
}
void PacketDiagram::clear()
{
setRootNode(nullptr);
}
void PacketDiagram::setCaptureFile(capture_file *cf)
{
// For use by the main view, set the capture file which will later have a
// dissection (EDT) ready.
// The packet dialog sets a fixed EDT context and MUST NOT use this.
cap_file_ = cf;
if (!cf) {
resetScene();
}
}
void PacketDiagram::setFont(const QFont &font)
{
layout_->setFont(font);
resetScene(false);
}
void PacketDiagram::selectedFieldChanged(FieldInformation *finfo)
{
setSelectedField(finfo ? finfo->fieldInfo() : nullptr);
}
void PacketDiagram::selectedFrameChanged(QList<int> frames)
{
if (frames.count() == 1 && cap_file_ && cap_file_->edt && cap_file_->edt->tree) {
setRootNode(cap_file_->edt->tree);
} else {
// Clear the proto tree contents as they have become invalid.
setRootNode(nullptr);
}
}
bool PacketDiagram::event(QEvent *event)
{
switch (event->type()) {
case QEvent::ApplicationPaletteChange:
resetScene(false);
break;
default:
break;
}
return QGraphicsView::event(event);
}
void PacketDiagram::contextMenuEvent(QContextMenuEvent *event)
{
if (!event) {
return;
}
QAction *action;
QMenu *ctx_menu = new QMenu(this);
ctx_menu->setAttribute(Qt::WA_DeleteOnClose);
action = ctx_menu->addAction(tr("Show Field Values"));
action->setCheckable(true);
action->setChecked(layout_->showFields());
connect(action, &QAction::toggled, this, &PacketDiagram::showFieldsToggled);
ctx_menu->addSeparator();
action = ctx_menu->addAction(tr("Save Diagram As…"));
connect(action, &QAction::triggered, this, &PacketDiagram::saveAsTriggered);
action = ctx_menu->addAction(tr("Copy as Raster Image"));
connect(action, &QAction::triggered, this, &PacketDiagram::copyAsRasterTriggered);
#if defined(QT_SVG_LIB) && !defined(Q_OS_MAC)
action = ctx_menu->addAction(tr("…as SVG"));
connect(action, &QAction::triggered, this, &PacketDiagram::copyAsSvgTriggered);
#endif
ctx_menu->popup(event->globalPos());
}
void PacketDiagram::connectToMainWindow()
{
MainWindow *main_window = qobject_cast<MainWindow *>(mainApp->mainWindow());
if (!main_window) {
return;
}
connect(main_window, &MainWindow::setCaptureFile, this, &PacketDiagram::setCaptureFile);
connect(main_window, &MainWindow::fieldSelected, this, &PacketDiagram::selectedFieldChanged);
connect(main_window, &MainWindow::framesSelected, this, &PacketDiagram::selectedFrameChanged);
connect(this, &PacketDiagram::fieldSelected, main_window, &MainWindow::fieldSelected);
}
void PacketDiagram::sceneSelectionChanged()
{
field_info *sel_fi = nullptr;
if (! scene()->selectedItems().isEmpty()) {
sel_fi = VariantPointer<field_info>::asPtr(scene()->selectedItems().first()->data(Qt::UserRole));
}
if (sel_fi) {
FieldInformation finfo(sel_fi, this);
emit fieldSelected(&finfo);
} else {
emit fieldSelected(nullptr);
}
}
void PacketDiagram::resetScene(bool reset_root)
{
// As noted in setRootNode, scene()->clear() doesn't clear everything.
// Do a "hard" clear, which resets our various rects and scroll position.
if (scene()) {
delete scene();
}
viewport()->update();
QGraphicsScene *new_scene = new QGraphicsScene();
setScene(new_scene);
connect(new_scene, &QGraphicsScene::selectionChanged, this, &PacketDiagram::sceneSelectionChanged);
setRootNode(reset_root ? nullptr : root_node_);
}
struct DiagramItemSpan {
field_info *finfo;
int start_bit;
int length;
};
void PacketDiagram::addDiagram(proto_node *tl_node)
{
QGraphicsItem *item;
QGraphicsSimpleTextItem *t_item;
int bits_per_row = layout_->bitsPerRow();
int bit_width = layout_->bitWidth();
int diag_w = bit_width * layout_->bitsPerRow();
qreal x = layout_->hPadding();
// Title
t_item = scene()->addSimpleText(tl_node->finfo->hfinfo->name);
t_item->setFont(layout_->regularFont());
t_item->setPos(0, y_pos_);
y_pos_ += layout_->lineHeight() + (bit_width / 4);
int border_top = y_pos_;
// Bit scale + tick marks
QList<int> tick_nums;
for (int tn = 0 ; tn < layout_->bitsPerRow(); tn += 16) {
tick_nums << tn << tn + 15;
}
qreal y_bottom = y_pos_ + bit_width;
QGraphicsItem *tl_item = scene()->addLine(x, y_bottom, x + diag_w, y_bottom);
QFontMetrics sfm = QFontMetrics(layout_->smallFont());
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
int space_w = sfm.horizontalAdvance(' ');
#else
int space_w = sfm.width(' ');
#endif
#ifdef Q_OS_WIN
// t_item->boundingRect() has a pixel of space on the left on my (gcc)
// Windows VM.
int tl_adjust = 1;
#else
int tl_adjust = 0;
#endif
for (int tick_n = 0; tick_n < bits_per_row; tick_n++) {
x = layout_->hPadding() + (tick_n * bit_width);
qreal y_top = y_pos_ + (tick_n % 8 == 0 ? 0 : bit_width / 2);
if (tick_n > 0) {
scene()->addLine(x, y_top, x, y_bottom);
}
if (tick_nums.contains(tick_n)) {
t_item = scene()->addSimpleText(QString::number(tick_n));
t_item->setFont(layout_->smallFont());
if (tick_n % 2 == 0) {
t_item->setPos(x + space_w - tl_adjust, y_pos_);
} else {
t_item->setPos(x + bit_width - space_w - t_item->boundingRect().width() - tl_adjust, y_pos_);
}
// Does the placement above look funny on your system? Try
// uncommenting the lines below.
// QGraphicsRectItem *br_item = scene()->addRect(t_item->boundingRect(), QPen(palette().highlight().color()));
// br_item->setPos(t_item->pos());
}
}
y_pos_ = y_bottom;
x = layout_->hPadding();
// Collect our top-level fields
int last_start_bit = -1;
int max_l_y = y_bottom;
QList<DiagramItemSpan>item_spans;
for (proto_item *cur_item = tl_node->first_child; cur_item; cur_item = cur_item->next) {
if (proto_item_is_generated(cur_item) || proto_item_is_hidden(cur_item)) {
continue;
}
field_info *fi = cur_item->finfo;
int start_bit = ((fi->start - tl_node->finfo->start) * 8) + FI_GET_BITS_OFFSET(fi);
int length = FI_GET_BITS_SIZE(fi) ? FI_GET_BITS_SIZE(fi) : fi->length * 8;
if (start_bit <= last_start_bit || length <= 0) {
#ifdef DEBUG_PACKET_DIAGRAM
qDebug() << "Skipping item" << fi->hfinfo->abbrev << start_bit << last_start_bit << length;
#endif
continue;
}
last_start_bit = start_bit;
if (item_spans.size() > 0) {
DiagramItemSpan prev_span = item_spans.last();
// Get rid of overlaps.
if (prev_span.start_bit + prev_span.length > start_bit) {
#ifdef DEBUG_PACKET_DIAGRAM
qDebug() << "Resized prev" << prev_span.finfo->hfinfo->abbrev << prev_span.start_bit << prev_span.length << "->" << start_bit - prev_span.start_bit;
#endif
prev_span.length = start_bit - prev_span.start_bit;
}
if (prev_span.length < 1) {
#ifdef DEBUG_PACKET_DIAGRAM
qDebug() << "Removed prev" << prev_span.finfo->hfinfo->abbrev << prev_span.start_bit << prev_span.length;
item_spans.removeLast();
if (item_spans.size() < 1) {
continue;
}
prev_span = item_spans.last();
#endif
}
// Fill in gaps.
if (prev_span.start_bit + prev_span.length < start_bit) {
#ifdef DEBUG_PACKET_DIAGRAM
qDebug() << "Adding gap" << prev_span.finfo->hfinfo->abbrev << prev_span.start_bit << prev_span.length << start_bit;
#endif
int gap_start = prev_span.start_bit + prev_span.length;
DiagramItemSpan gap_span = { nullptr, gap_start, start_bit - gap_start };
item_spans << gap_span;
}
}
DiagramItemSpan item_span = { cur_item->finfo, start_bit, length };
item_spans << item_span;
}
qreal z_value = tl_item->zValue();
int start_bit = 0;
for (int idx = 0; idx < item_spans.size(); idx++) {
DiagramItemSpan *item_span = &item_spans[idx];
int y_off = (start_bit / bits_per_row) * layout_->rowHeight();
// Stack each item behind the previous one.
z_value -= .01;
FieldInformationGraphicsItem *fi_item = new FieldInformationGraphicsItem(item_span->finfo, start_bit, item_span->length, layout_);
start_bit += fi_item->collapsedLength();
fi_item->setPos(x, y_bottom + y_off);
fi_item->setFlag(QGraphicsItem::ItemIsSelectable);
fi_item->setAcceptedMouseButtons(Qt::LeftButton);
fi_item->setZValue(z_value);
scene()->addItem(fi_item);
y_pos_ = fi_item->maxRightY();
max_l_y = fi_item->maxLeftY();
}
// Left & right borders
scene()->addLine(x, border_top, x, max_l_y);
scene()->addLine(x + diag_w, border_top, x + diag_w, y_pos_);
// Inter-diagram margin
y_pos_ = max_l_y + bit_width;
// Set the proper color. Needed for dark mode on macOS + Qt 5.15.0 at least, possibly other cases.
foreach (item, scene()->items()) {
QGraphicsSimpleTextItem *t_item = qgraphicsitem_cast<QGraphicsSimpleTextItem *>(item);
if (t_item) {
t_item->setBrush(palette().text().color());
}
QGraphicsLineItem *l_item = qgraphicsitem_cast<QGraphicsLineItem *>(item);
if (l_item) {
l_item->setPen(palette().text().color());
}
}
}
void PacketDiagram::setSelectedField(field_info *fi)
{
QSignalBlocker blocker(this);
FieldInformationGraphicsItem *fi_item;
foreach (QGraphicsItem *item, scene()->items()) {
if (item->isSelected()) {
item->setSelected(false);
}
if (fi && VariantPointer<field_info>::asPtr(item->data(Qt::UserRole)) == fi) {
fi_item = qgraphicsitem_cast<FieldInformationGraphicsItem *>(item);
if (fi_item) {
fi_item->setSelected(true);
}
}
}
}
QImage PacketDiagram::exportToImage()
{
// Create a hi-res 2x scaled image.
int scale = 2;
QRect rr = QRect(0, 0, sceneRect().size().width() * scale, sceneRect().size().height() * scale);
QImage raster_diagram = QImage(rr.size(), QImage::Format_ARGB32);
QPainter raster_painter(&raster_diagram);
raster_painter.setRenderHint(QPainter::Antialiasing);
raster_painter.fillRect(rr, palette().base().color());
scene()->render(&raster_painter);
raster_painter.end();
return raster_diagram;
}
#if defined(QT_SVG_LIB) && 0
QByteArray PacketDiagram::exportToSvg()
{
QRect sr = QRect(0, 0, sceneRect().size().width(), sceneRect().size().height());
QBuffer svg_buf;
QSvgGenerator svg_diagram;
svg_diagram.setSize(sr.size());
svg_diagram.setViewBox(sr);
svg_diagram.setOutputDevice(&svg_buf);
QPainter svg_painter(&svg_diagram);
svg_painter.fillRect(sr, palette().base().color());
scene()->render(&svg_painter);
svg_painter.end();
return svg_buf.buffer();
}
#endif
void PacketDiagram::showFieldsToggled(bool checked)
{
layout_->setShowFields(checked);
setRootNode(root_node_);
/* Viewport needs to be update to avoid residues being shown */
viewport()->update();
}
// XXX - We have similar code in tcp_stream_dialog and io_graph_dialog. Should this be a common routine?
void PacketDiagram::saveAsTriggered()
{
QString file_name, extension;
QDir path(mainApp->lastOpenDir());
QString png_filter = tr("Portable Network Graphics (*.png)");
QString bmp_filter = tr("Windows Bitmap (*.bmp)");
// Gaze upon my beautiful graph with lossy artifacts!
QString jpeg_filter = tr("JPEG File Interchange Format (*.jpeg *.jpg)");
QStringList fl = QStringList() << png_filter << bmp_filter << jpeg_filter;
#if defined(QT_SVG_LIB) && 0
QString svg_filter = tr("Scalable Vector Graphics (*.svg)");
fl << svg_filter;
#endif
QString filter = fl.join(";;");
file_name = WiresharkFileDialog::getSaveFileName(this, mainApp->windowTitleString(tr("Save Graph As…")),
path.canonicalPath(), filter, &extension);
if (file_name.length() > 0) {
bool save_ok = false;
if (extension.compare(png_filter) == 0) {
QImage raster_diagram = exportToImage();
save_ok = raster_diagram.save(file_name, "PNG");
} else if (extension.compare(bmp_filter) == 0) {
QImage raster_diagram = exportToImage();
save_ok = raster_diagram.save(file_name, "BMP");
} else if (extension.compare(jpeg_filter) == 0) {
QImage raster_diagram = exportToImage();
save_ok = raster_diagram.save(file_name, "JPG");
}
#if defined(QT_SVG_LIB) && 0
else if (extension.compare(svg_filter) == 0) {
QByteArray svg_diagram = exportToSvg();
QFile file(file_name);
if (file.open(QIODevice::WriteOnly)) {
save_ok = file.write(svg_diagram) > 0;
file.close();
}
}
#endif
// else error dialog?
if (save_ok) {
mainApp->setLastOpenDirFromFilename(file_name);
}
}
}
void PacketDiagram::copyAsRasterTriggered()
{
QImage raster_diagram = exportToImage();
mainApp->clipboard()->setImage(raster_diagram);
}
#if defined(QT_SVG_LIB) && !defined(Q_OS_MAC) && 0
void PacketDiagram::copyAsSvgTriggered()
{
QByteArray svg_ba = exportToSvg();
// XXX It looks like we have to use/subclass QMacPasteboardMime in
// order for this to work on macOS.
// It might be easier to just do "Save As" instead.
QMimeData *md = new QMimeData();
md->setData("image/svg+xml", svg_buf);
mainApp->clipboard()->setMimeData(md);
}
#endif |
C/C++ | wireshark/ui/qt/packet_diagram.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PACKET_DIAGRAM_H
#define PACKET_DIAGRAM_H
#include <config.h>
#include <epan/proto.h>
#include "cfile.h"
#include <ui/qt/utils/field_information.h>
#include <QGraphicsView>
class DiagramLayout;
class PacketDiagram : public QGraphicsView
{
Q_OBJECT
public:
PacketDiagram(QWidget *parent = nullptr);
~PacketDiagram();
void setRootNode(proto_node *root_node);
void clear();
signals:
void fieldSelected(FieldInformation *);
public slots:
void setCaptureFile(capture_file *cf);
void setFont(const QFont &font);
void selectedFieldChanged(FieldInformation *finfo);
void selectedFrameChanged(QList<int> frames);
protected:
virtual bool event(QEvent *event) override;
virtual void contextMenuEvent(QContextMenuEvent *event) override;
private slots:
void connectToMainWindow();
void sceneSelectionChanged();
private:
void resetScene(bool reset_root = true);
void addDiagram(proto_node *tl_node);
void setSelectedField(field_info *fi);
QImage exportToImage();
#if defined(QT_SVG_LIB) && 0
QByteArray exportToSvg();
#endif
void showFieldsToggled(bool checked);
void saveAsTriggered();
void copyAsRasterTriggered();
#if defined(QT_SVG_LIB) && !defined(Q_OS_MAC) && 0
void copyAsSvgTriggered();
#endif
DiagramLayout *layout_;
capture_file *cap_file_;
proto_node *root_node_;
field_info *selected_field_;
int y_pos_;
};
#endif // PACKET_DIAGRAM_H |
C++ | wireshark/ui/qt/packet_dialog.cpp | /* packet_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "packet_dialog.h"
#include <ui_packet_dialog.h>
#include "file.h"
#include "epan/column.h"
#include "epan/ftypes/ftypes.h"
#include "epan/prefs.h"
#include "ui/preference_utils.h"
#include "frame_tvbuff.h"
#include <wsutil/utf8_entities.h>
#include "byte_view_tab.h"
#include "proto_tree.h"
#include "main_application.h"
#include <ui/qt/utils/field_information.h>
#include <QTreeWidgetItemIterator>
// To do:
// - Copy over experimental packet editing code.
// - Fix ElidedText width.
PacketDialog::PacketDialog(QWidget &parent, CaptureFile &cf, frame_data *fdata) :
WiresharkDialog(parent, cf),
ui(new Ui::PacketDialog),
proto_tree_(NULL),
byte_view_tab_(NULL)
{
ui->setupUi(this);
loadGeometry(parent.width() * 4 / 5, parent.height() * 4 / 5);
ui->hintLabel->setSmallText();
wtap_rec_init(&rec_);
ws_buffer_init(&buf_, 1514);
edt_.session = NULL;
edt_.tvb = NULL;
edt_.tree = NULL;
memset(&edt_.pi, 0x0, sizeof(edt_.pi));
setWindowSubtitle(tr("Packet %1").arg(fdata->num));
if (!cf_read_record(cap_file_.capFile(), fdata, &rec_, &buf_)) {
reject();
return;
}
/* proto tree, visible. We need a proto tree if there are custom columns */
epan_dissect_init(&edt_, cap_file_.capFile()->epan, TRUE, TRUE);
col_custom_prime_edt(&edt_, &(cap_file_.capFile()->cinfo));
epan_dissect_run(&edt_, cap_file_.capFile()->cd_t, &rec_,
frame_tvbuff_new_buffer(&cap_file_.capFile()->provider, fdata, &buf_),
fdata, &(cap_file_.capFile()->cinfo));
epan_dissect_fill_in_columns(&edt_, TRUE, TRUE);
proto_tree_ = new ProtoTree(ui->packetSplitter, &edt_);
// Do not call proto_tree_->setCaptureFile, ProtoTree only needs the
// dissection context.
proto_tree_->setRootNode(edt_.tree);
byte_view_tab_ = new ByteViewTab(ui->packetSplitter, &edt_);
byte_view_tab_->setCaptureFile(cap_file_.capFile());
byte_view_tab_->selectedFrameChanged(QList<int>() << 0);
ui->packetSplitter->setStretchFactor(1, 0);
QStringList col_parts;
for (int i = 0; i < cap_file_.capFile()->cinfo.num_cols; ++i) {
// ElidedLabel doesn't support rich text / HTML
col_parts << QString("%1: %2")
.arg(get_column_title(i))
.arg(get_column_text(&cap_file_.capFile()->cinfo, i));
}
col_info_ = col_parts.join(" " UTF8_MIDDLE_DOT " ");
ui->hintLabel->setText(col_info_);
/* Handle preference value correctly */
Qt::CheckState state = Qt::Checked;
if (!prefs.gui_packet_details_show_byteview) {
state = Qt::Unchecked;
byte_view_tab_->setVisible(false);
}
ui->chkShowByteView->setCheckState(state);
connect(mainApp, SIGNAL(zoomMonospaceFont(QFont)),
proto_tree_, SLOT(setMonospaceFont(QFont)));
connect(byte_view_tab_, SIGNAL(fieldSelected(FieldInformation *)),
proto_tree_, SLOT(selectedFieldChanged(FieldInformation *)));
connect(proto_tree_, SIGNAL(fieldSelected(FieldInformation *)),
byte_view_tab_, SLOT(selectedFieldChanged(FieldInformation *)));
connect(byte_view_tab_, SIGNAL(fieldHighlight(FieldInformation *)),
this, SLOT(setHintText(FieldInformation *)));
connect(byte_view_tab_, &ByteViewTab::fieldSelected,
this, &PacketDialog::setHintTextSelected);
connect(proto_tree_, &ProtoTree::fieldSelected,
this, &PacketDialog::setHintTextSelected);
connect(proto_tree_, SIGNAL(showProtocolPreferences(QString)),
this, SIGNAL(showProtocolPreferences(QString)));
connect(proto_tree_, SIGNAL(editProtocolPreference(preference*,pref_module*)),
this, SIGNAL(editProtocolPreference(preference*,pref_module*)));
connect(ui->chkShowByteView, &QCheckBox::stateChanged, this, &PacketDialog::viewVisibilityStateChanged);
}
PacketDialog::~PacketDialog()
{
delete ui;
epan_dissect_cleanup(&edt_);
wtap_rec_cleanup(&rec_);
ws_buffer_free(&buf_);
}
void PacketDialog::captureFileClosing()
{
QString closed_title = tr("[%1 closed] " UTF8_MIDDLE_DOT " %2")
.arg(cap_file_.fileName())
.arg(col_info_);
ui->hintLabel->setText(closed_title);
byte_view_tab_->captureFileClosing();
WiresharkDialog::captureFileClosing();
}
void PacketDialog::on_buttonBox_helpRequested()
{
mainApp->helpTopicAction(HELP_NEW_PACKET_DIALOG);
}
void PacketDialog::setHintText(FieldInformation * finfo)
{
QString hint;
if (finfo)
{
FieldInformation::Position pos = finfo->position();
QString field_str;
if (pos.length < 2) {
hint = QString(tr("Byte %1")).arg(pos.start);
} else {
hint = QString(tr("Bytes %1-%2")).arg(pos.start).arg(pos.start + pos.length - 1);
}
hint += QString(": %1 (%2)")
.arg(finfo->headerInfo().name)
.arg(finfo->headerInfo().abbreviation);
}
else {
hint = col_info_;
}
ui->hintLabel->setText(hint);
}
void PacketDialog::setHintTextSelected(FieldInformation* finfo)
{
QString hint;
if (finfo)
{
FieldInformation::HeaderInfo hInfo = finfo->headerInfo();
if (hInfo.isValid)
{
if (hInfo.description.length() > 0) {
hint.append(hInfo.description);
}
else {
hint.append(hInfo.name);
}
}
if (!hint.isEmpty()) {
int finfo_length;
if (hInfo.isValid)
hint.append(" (" + hInfo.abbreviation + ")");
finfo_length = finfo->position().length + finfo->appendix().length;
if (finfo_length > 0) {
hint.append(", " + tr("%Ln byte(s)", "", finfo_length));
}
}
}
else {
hint = col_info_;
}
ui->hintLabel->setText(hint);
}
void PacketDialog::viewVisibilityStateChanged(int state)
{
byte_view_tab_->setVisible(state == Qt::Checked);
prefs.gui_packet_details_show_byteview = (state == Qt::Checked ? TRUE : FALSE);
prefs_main_write();
} |
C/C++ | wireshark/ui/qt/packet_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 PACKET_DIALOG_H
#define PACKET_DIALOG_H
#include "wireshark_dialog.h"
#include "epan/epan_dissect.h"
#include "wiretap/wtap.h"
#include "wsutil/buffer.h"
#include <ui/qt/utils/field_information.h>
class ByteViewTab;
class ProtoTree;
namespace Ui {
class PacketDialog;
}
class PacketDialog : public WiresharkDialog
{
Q_OBJECT
public:
explicit PacketDialog(QWidget &parent, CaptureFile &cf, frame_data *fdata);
~PacketDialog();
protected:
void captureFileClosing();
signals:
void showProtocolPreferences(const QString module_name);
void editProtocolPreference(struct preference *pref, struct pref_module *module);
private slots:
void on_buttonBox_helpRequested();
void viewVisibilityStateChanged(int);
void setHintText(FieldInformation *);
void setHintTextSelected(FieldInformation*);
private:
Ui::PacketDialog *ui;
QString col_info_;
ProtoTree *proto_tree_;
ByteViewTab *byte_view_tab_;
wtap_rec rec_;
Buffer buf_;
epan_dissect_t edt_;
};
#endif // PACKET_DIALOG_H |
User Interface | wireshark/ui/qt/packet_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>PacketDialog</class>
<widget class="QDialog" name="PacketDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>641</width>
<height>450</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout" stretch="1,0,0">
<item>
<widget class="QSplitter" name="packetSplitter">
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
</widget>
</item>
<item>
<widget class="ElidedLabel" name="hintLabel">
<property name="text">
<string><small><i></i></small></string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkShowByteView">
<property name="text">
<string>Show packet bytes</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Close|QDialogButtonBox::Help</set>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>ElidedLabel</class>
<extends>QLabel</extends>
<header>widgets/elided_label.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>PacketDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>PacketDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/packet_format_group_box.cpp | /* packet_format_group_box.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "packet_format_group_box.h"
#include <ui_packet_format_group_box.h>
#include <epan/print.h>
#include <QStyle>
#include <QStyleOption>
PacketFormatGroupBox::PacketFormatGroupBox(QWidget *parent) :
QGroupBox(parent),
pf_ui_(new Ui::PacketFormatGroupBox)
{
pf_ui_->setupUi(this);
setFlat(true);
QStyleOption style_opt;
int cb_label_offset = pf_ui_->detailsCheckBox->style()->subElementRect(QStyle::SE_CheckBoxContents, &style_opt).left();
// Indent the checkbox under the "Packet summary" checkbox
pf_ui_->includeColumnHeadingsCheckBox->setStyleSheet(QString(
"QCheckBox {"
" padding-left: %1px;"
"}"
).arg(cb_label_offset));
// Indent the radio buttons under the "Packet details" checkbox
pf_ui_->allCollapsedButton->setStyleSheet(QString(
"QRadioButton {"
" padding-left: %1px;"
"}"
).arg(cb_label_offset));
pf_ui_->asDisplayedButton->setStyleSheet(QString(
"QRadioButton {"
" padding-left: %1px;"
"}"
).arg(cb_label_offset));
pf_ui_->allExpandedButton->setStyleSheet(QString(
"QRadioButton {"
" padding-left: %1px;"
"}"
).arg(cb_label_offset));
// Indent the checkbox under the "Bytes" checkbox
pf_ui_->includeDataSourcesCheckBox->setStyleSheet(QString(
"QCheckBox {"
" padding-left: %1px;"
"}"
).arg(cb_label_offset));
}
PacketFormatGroupBox::~PacketFormatGroupBox()
{
delete pf_ui_;
}
bool PacketFormatGroupBox::summaryEnabled()
{
return pf_ui_->summaryCheckBox->isChecked();
}
bool PacketFormatGroupBox::detailsEnabled()
{
return pf_ui_->detailsCheckBox->isChecked();
}
bool PacketFormatGroupBox::bytesEnabled()
{
return pf_ui_->bytesCheckBox->isChecked();
}
bool PacketFormatGroupBox::includeColumnHeadingsEnabled()
{
return pf_ui_->includeColumnHeadingsCheckBox->isChecked();
}
bool PacketFormatGroupBox::allCollapsedEnabled()
{
return pf_ui_->allCollapsedButton->isChecked();
}
bool PacketFormatGroupBox::asDisplayedEnabled()
{
return pf_ui_->asDisplayedButton->isChecked();
}
bool PacketFormatGroupBox::allExpandedEnabled()
{
return pf_ui_->allExpandedButton->isChecked();
}
uint PacketFormatGroupBox::getHexdumpOptions()
{
return pf_ui_->includeDataSourcesCheckBox->isChecked() ? HEXDUMP_SOURCE_MULTI : HEXDUMP_SOURCE_PRIMARY;
}
void PacketFormatGroupBox::on_summaryCheckBox_toggled(bool checked)
{
pf_ui_->includeColumnHeadingsCheckBox->setEnabled(checked);
emit formatChanged();
}
void PacketFormatGroupBox::on_detailsCheckBox_toggled(bool checked)
{
pf_ui_->allCollapsedButton->setEnabled(checked);
pf_ui_->asDisplayedButton->setEnabled(checked);
pf_ui_->allExpandedButton->setEnabled(checked);
emit formatChanged();
}
void PacketFormatGroupBox::on_bytesCheckBox_toggled(bool checked)
{
pf_ui_->includeDataSourcesCheckBox->setEnabled(checked);
emit formatChanged();
}
void PacketFormatGroupBox::on_includeColumnHeadingsCheckBox_toggled(bool)
{
emit formatChanged();
}
void PacketFormatGroupBox::on_allCollapsedButton_toggled(bool checked)
{
if (checked) emit formatChanged();
}
void PacketFormatGroupBox::on_asDisplayedButton_toggled(bool checked)
{
if (checked) emit formatChanged();
}
void PacketFormatGroupBox::on_allExpandedButton_toggled(bool checked)
{
if (checked) emit formatChanged();
}
void PacketFormatGroupBox::on_includeDataSourcesCheckBox_toggled(bool)
{
emit formatChanged();
} |
C/C++ | wireshark/ui/qt/packet_format_group_box.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PACKET_FORMAT_GROUP_BOX_H
#define PACKET_FORMAT_GROUP_BOX_H
#include <QGroupBox>
namespace Ui {
class PacketFormatGroupBox;
}
class PacketFormatGroupBox : public QGroupBox
{
Q_OBJECT
public:
explicit PacketFormatGroupBox(QWidget *parent = 0);
~PacketFormatGroupBox();
bool summaryEnabled();
bool detailsEnabled();
bool bytesEnabled();
bool includeColumnHeadingsEnabled();
bool allCollapsedEnabled();
bool asDisplayedEnabled();
bool allExpandedEnabled();
uint getHexdumpOptions();
signals:
void formatChanged();
private slots:
void on_summaryCheckBox_toggled(bool checked);
void on_detailsCheckBox_toggled(bool checked);
void on_bytesCheckBox_toggled(bool checked);
void on_includeColumnHeadingsCheckBox_toggled(bool checked);
void on_allCollapsedButton_toggled(bool checked);
void on_asDisplayedButton_toggled(bool checked);
void on_allExpandedButton_toggled(bool checked);
void on_includeDataSourcesCheckBox_toggled(bool checked);
private:
Ui::PacketFormatGroupBox *pf_ui_;
};
#endif // PACKET_FORMAT_GROUP_BOX_H |
User Interface | wireshark/ui/qt/packet_format_group_box.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>PacketFormatGroupBox</class>
<widget class="QGroupBox" name="PacketFormatGroupBox">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>199</height>
</rect>
</property>
<property name="windowTitle">
<string>GroupBox</string>
</property>
<property name="title">
<string>Packet Format</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QCheckBox" name="summaryCheckBox">
<property name="toolTip">
<string><html><head/><body><p>Packet summary lines similar to the packet list</p></body></html></string>
</property>
<property name="text">
<string>Summary line</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="includeColumnHeadingsCheckBox">
<property name="text">
<string>Include column headings</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="detailsCheckBox">
<property name="toolTip">
<string><html><head/><body><p>Packet details similar to the protocol tree</p></body></html></string>
</property>
<property name="text">
<string>Details:</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="allCollapsedButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="toolTip">
<string><html><head/><body><p>Export only top-level packet detail items</p></body></html></string>
</property>
<property name="text">
<string>All co&llapsed</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="asDisplayedButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="toolTip">
<string><html><head/><body><p>Expand and collapse packet details as they are currently displayed.</p></body></html></string>
</property>
<property name="text">
<string>As displa&yed</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="allExpandedButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="toolTip">
<string><html><head/><body><p>Export all packet detail items</p></body></html></string>
</property>
<property name="text">
<string>All e&xpanded</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="bytesCheckBox">
<property name="toolTip">
<string><html><head/><body><p>Export a hexdump of the packet data similar to the packet bytes view</p></body></html></string>
</property>
<property name="text">
<string>Bytes</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="includeDataSourcesCheckBox">
<property name="text">
<string>Include secondary data sources</string>
</property>
<property name="toolTip">
<string><html><head/><body><p>Generate hexdumps for secondary data sources like reassembled or decrypted buffers in addition to the frame</p></body></html></string>
</property>
<property name="checked">
<bool>true</bool>
</property>
<property name="enabled">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</widget>
<connections/>
</ui> |
C++ | wireshark/ui/qt/packet_list.cpp | /* packet_list.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/packet_list.h>
#include "config.h"
#include <glib.h>
#include "file.h"
#include <epan/epan.h>
#include <epan/epan_dissect.h>
#include <epan/column.h>
#include <epan/expert.h>
#include <epan/ipproto.h>
#include <epan/packet.h>
#include <epan/prefs.h>
#include <epan/proto.h>
#include "ui/main_statusbar.h"
#include "ui/packet_list_utils.h"
#include "ui/preference_utils.h"
#include "ui/recent.h"
#include "ui/recent_utils.h"
#include "ui/ws_ui_util.h"
#include "ui/simple_dialog.h"
#include <wsutil/utf8_entities.h>
#include "ui/util.h"
#include "wiretap/wtap_opttypes.h"
#include "wsutil/str_util.h"
#include <wsutil/wslog.h>
#include <epan/color_filters.h>
#include "frame_tvbuff.h"
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/widgets/overlay_scroll_bar.h>
#include "proto_tree.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
#include <ui/qt/utils/data_printer.h>
#include <ui/qt/utils/frame_information.h>
#include <ui/qt/utils/variant_pointer.h>
#include <ui/qt/models/pref_models.h>
#include <ui/qt/widgets/packet_list_header.h>
#include <ui/qt/utils/wireshark_mime_data.h>
#include <ui/qt/widgets/drag_label.h>
#include <ui/qt/filter_action.h>
#include <ui/qt/follow_stream_action.h>
#include <ui/qt/decode_as_dialog.h>
#include <ui/qt/wireshark_main_window.h>
#include <QAction>
#include <QActionGroup>
#include <QClipboard>
#include <QContextMenuEvent>
#include <QtCore/qmath.h>
#include <QElapsedTimer>
#include <QFontMetrics>
#include <QHeaderView>
#include <QMessageBox>
#include <QPainter>
#include <QScreen>
#include <QScrollBar>
#include <QTabWidget>
#include <QTextEdit>
#include <QTimerEvent>
#include <QTreeWidget>
#include <QWindow>
#include <QJsonObject>
#include <QJsonDocument>
#ifdef Q_OS_WIN
#include "wsutil/file_util.h"
#include <QSysInfo>
#include <uxtheme.h>
#endif
// To do:
// - Fix "apply as filter" behavior.
// - Add colorize conversation.
// - Use a timer to trigger automatic scrolling.
// If we ever add the ability to open multiple capture files we might be
// able to use something like QMap<capture_file *, PacketList *> to match
// capture files against packet lists and models.
static PacketList *gbl_cur_packet_list = NULL;
const int max_comments_to_fetch_ = 20000000; // Arbitrary
const int overlay_update_interval_ = 100; // 250; // Milliseconds.
/*
* Given a frame_data structure, scroll to and select the row in the
* packet list corresponding to that frame. If there is no such
* row, return FALSE, otherwise return TRUE.
*/
gboolean
packet_list_select_row_from_data(frame_data *fdata_needle)
{
if (! gbl_cur_packet_list || ! gbl_cur_packet_list->model())
return FALSE;
PacketListModel * model = qobject_cast<PacketListModel *>(gbl_cur_packet_list->model());
if (! model)
return FALSE;
model->flushVisibleRows();
int row = -1;
if (!fdata_needle)
row = 0;
else
row = model->visibleIndexOf(fdata_needle);
if (row >= 0) {
/* Calling ClearAndSelect with setCurrentIndex clears the "current"
* item, but doesn't clear the "selected" item. We want to clear
* the "selected" item as well so that selectionChanged() will be
* emitted in order to force an update of the packet details and
* packet bytes after a search.
*/
gbl_cur_packet_list->selectionModel()->clearSelection();
gbl_cur_packet_list->selectionModel()->setCurrentIndex(model->index(row, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
gbl_cur_packet_list->scrollTo(gbl_cur_packet_list->currentIndex(), PacketList::PositionAtCenter);
return TRUE;
}
return FALSE;
}
void
packet_list_clear(void)
{
if (gbl_cur_packet_list) {
gbl_cur_packet_list->clear();
}
}
void
packet_list_freeze(void)
{
if (gbl_cur_packet_list) {
gbl_cur_packet_list->freeze();
}
}
void
packet_list_thaw(void)
{
if (gbl_cur_packet_list) {
gbl_cur_packet_list->thaw();
}
packets_bar_update();
}
/* Redraw the packet list *and* currently-selected detail */
void
packet_list_queue_draw(void)
{
if (gbl_cur_packet_list)
gbl_cur_packet_list->redrawVisiblePackets();
}
void
packet_list_recent_write_all(FILE *rf) {
if (!gbl_cur_packet_list)
return;
gbl_cur_packet_list->writeRecent(rf);
}
gboolean
packet_list_multi_select_active(void)
{
if (gbl_cur_packet_list) {
return gbl_cur_packet_list->multiSelectActive();
}
return FALSE;
}
#define MIN_COL_WIDTH_STR "MMMMMM"
PacketList::PacketList(QWidget *parent) :
QTreeView(parent),
proto_tree_(NULL),
cap_file_(NULL),
ctx_column_(-1),
overlay_timer_id_(0),
create_near_overlay_(true),
create_far_overlay_(true),
mouse_pressed_at_(QModelIndex()),
capture_in_progress_(false),
tail_at_end_(0),
columns_changed_(false),
set_column_visibility_(false),
frozen_current_row_(QModelIndex()),
frozen_selected_rows_(QModelIndexList()),
cur_history_(-1),
in_history_(false),
finfo_array(NULL)
{
setItemsExpandable(false);
setRootIsDecorated(false);
setSortingEnabled(prefs.gui_packet_list_sortable);
setUniformRowHeights(true);
setAccessibleName("Packet list");
proto_prefs_menus_.setTitle(tr("Protocol Preferences"));
packet_list_header_ = new PacketListHeader(header()->orientation());
connect(packet_list_header_, &PacketListHeader::resetColumnWidth, this, &PacketList::setRecentColumnWidth);
connect(packet_list_header_, &PacketListHeader::updatePackets, this, &PacketList::updatePackets);
connect(packet_list_header_, &PacketListHeader::showColumnPreferences, this, &PacketList::showProtocolPreferences);
connect(packet_list_header_, &PacketListHeader::editColumn, this, &PacketList::editColumn);
connect(packet_list_header_, &PacketListHeader::columnsChanged, this, &PacketList::columnsChanged);
setHeader(packet_list_header_);
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
header()->setFirstSectionMovable(true);
#endif
setSelectionMode(QAbstractItemView::ExtendedSelection);
// Shrink down to a small but nonzero size in the main splitter.
int one_em = fontMetrics().height();
setMinimumSize(one_em, one_em);
overlay_sb_ = new OverlayScrollBar(Qt::Vertical, this);
setVerticalScrollBar(overlay_sb_);
header()->setSortIndicator(-1, Qt::AscendingOrder);
packet_list_model_ = new PacketListModel(this, cap_file_);
setModel(packet_list_model_);
Q_ASSERT(gbl_cur_packet_list == Q_NULLPTR);
gbl_cur_packet_list = this;
connect(packet_list_model_, SIGNAL(goToPacket(int)), this, SLOT(goToPacket(int)));
connect(packet_list_model_, SIGNAL(itemHeightChanged(const QModelIndex&)), this, SLOT(updateRowHeights(const QModelIndex&)));
connect(mainApp, SIGNAL(addressResolutionChanged()), this, SLOT(redrawVisiblePacketsDontSelectCurrent()));
connect(mainApp, SIGNAL(columnDataChanged()), this, SLOT(redrawVisiblePacketsDontSelectCurrent()));
connect(mainApp, &MainApplication::preferencesChanged, this, [=]() {
/* The pref is a uint but QCache maxCost is a signed int (/
* qsizetype in Qt 6). Note that QAbstractItemModel row numbers
* are ints, not unsigned ints, so we're limited to INT_MAX
* rows anyway.
*/
PacketListRecord::setMaxCache(prefs.gui_packet_list_cached_rows_max > INT_MAX ? INT_MAX : prefs.gui_packet_list_cached_rows_max);
if ((bool) (prefs.gui_packet_list_sortable) != isSortingEnabled()) {
setSortingEnabled(prefs.gui_packet_list_sortable);
}
});
connect(header(), SIGNAL(sectionResized(int,int,int)),
this, SLOT(sectionResized(int,int,int)));
connect(header(), SIGNAL(sectionMoved(int,int,int)),
this, SLOT(sectionMoved(int,int,int)));
connect(verticalScrollBar(), SIGNAL(actionTriggered(int)), this, SLOT(vScrollBarActionTriggered(int)));
}
PacketList::~PacketList()
{
if (finfo_array)
{
g_ptr_array_free(finfo_array, TRUE);
}
}
void PacketList::colorsChanged()
{
const QString c_active = "active";
const QString c_inactive = "!active";
QString flat_style_format =
"QTreeView::item:selected:%1 {"
" color: %2;"
" background-color: %3;"
"}";
QString gradient_style_format =
"QTreeView::item:selected:%1 {"
" color: %2;"
" background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1 stop: 0 %4, stop: 0.5 %3, stop: 1 %4);"
"}";
QString hover_style;
#if !defined(Q_OS_WIN)
hover_style = QString(
"QTreeView:item:hover {"
" background-color: %1;"
" color: palette(text);"
"}").arg(ColorUtils::hoverBackground().name(QColor::HexArgb));
#endif
QString active_style = QString();
QString inactive_style = QString();
if (prefs.gui_active_style == COLOR_STYLE_DEFAULT) {
// ACTIVE = Default
} else if (prefs.gui_active_style == COLOR_STYLE_FLAT) {
// ACTIVE = Flat
QColor foreground = ColorUtils::fromColorT(prefs.gui_active_fg);
QColor background = ColorUtils::fromColorT(prefs.gui_active_bg);
active_style = flat_style_format.arg(
c_active,
foreground.name(),
background.name());
} else if (prefs.gui_active_style == COLOR_STYLE_GRADIENT) {
// ACTIVE = Gradient
QColor foreground = ColorUtils::fromColorT(prefs.gui_active_fg);
QColor background1 = ColorUtils::fromColorT(prefs.gui_active_bg);
QColor background2 = QColor::fromRgb(ColorUtils::alphaBlend(foreground, background1, COLOR_STYLE_ALPHA));
active_style = gradient_style_format.arg(
c_active,
foreground.name(),
background1.name(),
background2.name());
}
// INACTIVE style sheet settings
if (prefs.gui_inactive_style == COLOR_STYLE_DEFAULT) {
// INACTIVE = Default
} else if (prefs.gui_inactive_style == COLOR_STYLE_FLAT) {
// INACTIVE = Flat
QColor foreground = ColorUtils::fromColorT(prefs.gui_inactive_fg);
QColor background = ColorUtils::fromColorT(prefs.gui_inactive_bg);
inactive_style = flat_style_format.arg(
c_inactive,
foreground.name(),
background.name());
} else if (prefs.gui_inactive_style == COLOR_STYLE_GRADIENT) {
// INACTIVE = Gradient
QColor foreground = ColorUtils::fromColorT(prefs.gui_inactive_fg);
QColor background1 = ColorUtils::fromColorT(prefs.gui_inactive_bg);
QColor background2 = QColor::fromRgb(ColorUtils::alphaBlend(foreground, background1, COLOR_STYLE_ALPHA));
inactive_style = gradient_style_format.arg(
c_inactive,
foreground.name(),
background1.name(),
background2.name());
}
// Set the style sheet
if(prefs.gui_packet_list_hover_style) {
setStyleSheet(active_style + inactive_style + hover_style);
} else {
setStyleSheet(active_style + inactive_style);
}
}
QString PacketList::joinSummaryRow(QStringList col_parts, int row, SummaryCopyType type)
{
QString copy_text;
switch (type) {
case CopyAsCSV:
copy_text = "\"";
copy_text += col_parts.join("\",\"");
copy_text += "\"";
break;
case CopyAsYAML:
copy_text = "----\n";
copy_text += QString("# Packet %1 from %2\n").arg(row).arg(cap_file_->filename);
copy_text += "- ";
copy_text += col_parts.join("\n- ");
copy_text += "\n";
break;
case CopyAsText:
default:
copy_text = col_parts.join("\t");
}
return copy_text;
}
void PacketList::drawRow (QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QTreeView::drawRow(painter, option, index);
if (prefs.gui_packet_list_separator) {
QRect rect = visualRect(index);
painter->setPen(QColor(Qt::white));
painter->drawLine(0, rect.y() + rect.height() - 1, width(), rect.y() + rect.height() - 1);
}
}
void PacketList::setProtoTree (ProtoTree *proto_tree) {
proto_tree_ = proto_tree;
connect(proto_tree_, SIGNAL(goToPacket(int)), this, SLOT(goToPacket(int)));
connect(proto_tree_, SIGNAL(relatedFrame(int,ft_framenum_type_t)),
&related_packet_delegate_, SLOT(addRelatedFrame(int,ft_framenum_type_t)));
}
bool PacketList::uniqueSelectActive()
{
return selectionModel()->selectedRows(0).count() == 1 ? true : false;
}
bool PacketList::multiSelectActive()
{
return selectionModel()->selectedRows(0).count() > 1 ? true : false;
}
QList<int> PacketList::selectedRows(bool useFrameNum)
{
QList<int> rows;
if (selectionModel() && selectionModel()->hasSelection())
{
foreach (QModelIndex idx, selectionModel()->selectedRows(0))
{
if (idx.isValid())
{
if (! useFrameNum)
rows << idx.row();
else if (useFrameNum)
{
frame_data * frame = getFDataForRow(idx.row());
if (frame)
rows << frame->num;
}
}
}
}
else if (currentIndex().isValid())
{
//
// XXX - will we ever have a current index but not a selection
// model?
//
if (! useFrameNum)
rows << currentIndex().row();
else
{
frame_data *frame = getFDataForRow(currentIndex().row());
if (frame)
rows << frame->num;
}
}
return rows;
}
void PacketList::selectionChanged (const QItemSelection & selected, const QItemSelection & deselected)
{
QTreeView::selectionChanged(selected, deselected);
if (!cap_file_) return;
int row = -1;
static bool multiSelect = false;
if (selectionModel())
{
QModelIndexList selRows = selectionModel()->selectedRows(0);
if (selRows.count() > 1)
{
QList<int> rows;
foreach (QModelIndex idx, selRows)
{
if (idx.isValid())
rows << idx.row();
}
emit framesSelected(rows);
emit fieldSelected(0);
cf_unselect_packet(cap_file_);
/* We have to repaint the content while changing state, as some delegates react to multi-select */
if (! multiSelect)
{
related_packet_delegate_.clear();
viewport()->update();
}
multiSelect = true;
return;
}
else if (selRows.count() > 0 && selRows.at(0).isValid())
{
multiSelect = false;
row = selRows.at(0).row();
}
/* Handling empty selection */
if (selRows.count() <= 0)
{
/* Nothing selected, but multiSelect is still active */
if (multiSelect)
{
multiSelect = false;
if (currentIndex().isValid())
{
selectionModel()->select(currentIndex(), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
return;
}
}
/* Nothing selected, so in WS <= 3.0 nothing was indicated as well */
else if (currentIndex().isValid())
{
setCurrentIndex(QModelIndex());
}
}
}
if (row < 0 || !packet_list_model_)
cf_unselect_packet(cap_file_);
else {
frame_data * fdata = packet_list_model_->getRowFdata(row);
cf_select_packet(cap_file_, fdata);
}
if (!in_history_ && cap_file_->current_frame) {
cur_history_++;
selection_history_.resize(cur_history_);
selection_history_.append(cap_file_->current_frame->num);
}
in_history_ = false;
related_packet_delegate_.clear();
// The previous dissection state has been invalidated by cf_select_packet
// above, receivers must clear the previous state and apply the updated one.
emit framesSelected(QList<int>() << row);
if (!cap_file_->edt) {
viewport()->update();
emit fieldSelected(0);
return;
}
if (cap_file_->edt->tree) {
packet_info *pi = &cap_file_->edt->pi;
related_packet_delegate_.setCurrentFrame(pi->num);
conversation_t *conv = find_conversation_pinfo(pi, 0);
if (conv) {
related_packet_delegate_.setConversation(conv);
}
viewport()->update();
}
if (cap_file_->search_in_progress) {
field_info *fi = NULL;
if (cap_file_->string && cap_file_->decode_data) {
// The tree where the target string matched one of the labels was discarded in
// match_protocol_tree() so we have to search again in the latest tree.
fi = cf_find_string_protocol_tree(cap_file_, cap_file_->edt->tree);
} else if (cap_file_->search_pos != 0) {
// Find the finfo that corresponds to our byte.
fi = proto_find_field_from_offset(cap_file_->edt->tree, cap_file_->search_pos,
cap_file_->edt->tvb);
}
if (fi) {
FieldInformation finfo(fi, this);
emit fieldSelected(&finfo);
} else {
emit fieldSelected(0);
}
} else if (proto_tree_) {
proto_tree_->restoreSelectedField();
}
}
void PacketList::contextMenuEvent(QContextMenuEvent *event)
{
const char *module_name = NULL;
proto_prefs_menus_.clear();
if (finfo_array)
{
g_ptr_array_free(finfo_array, TRUE);
finfo_array = NULL;
}
if (cap_file_ && cap_file_->edt && cap_file_->edt->tree) {
finfo_array = proto_all_finfos(cap_file_->edt->tree);
QList<QString> added_proto_prefs;
for (guint i = 0; i < finfo_array->len; i++) {
field_info *fi = (field_info *)g_ptr_array_index (finfo_array, i);
header_field_info *hfinfo = fi->hfinfo;
if (prefs_is_registered_protocol(hfinfo->abbrev)) {
if (hfinfo->parent == -1) {
module_name = hfinfo->abbrev;
} else {
module_name = proto_registrar_get_abbrev(hfinfo->parent);
}
if (added_proto_prefs.contains(module_name)) {
continue;
}
ProtocolPreferencesMenu *proto_prefs_menu = new ProtocolPreferencesMenu(hfinfo->name, module_name, &proto_prefs_menus_);
connect(proto_prefs_menu, SIGNAL(showProtocolPreferences(QString)),
this, SIGNAL(showProtocolPreferences(QString)));
connect(proto_prefs_menu, SIGNAL(editProtocolPreference(preference*,pref_module*)),
this, SIGNAL(editProtocolPreference(preference*,pref_module*)));
proto_prefs_menus_.addMenu(proto_prefs_menu);
added_proto_prefs << module_name;
}
}
}
QModelIndex ctxIndex = indexAt(event->pos());
if (selectionModel() && selectionModel()->selectedRows(0).count() > 1)
selectionModel()->select(ctxIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
// frameData will be owned by one of the submenus, see below.
FrameInformation * frameData =
new FrameInformation(new CaptureFile(this, cap_file_), packet_list_model_->getRowFdata(ctxIndex.row()));
QMenu * ctx_menu = new QMenu(this);
ctx_menu->setAttribute(Qt::WA_DeleteOnClose);
// XXX We might want to reimplement setParent() and fill in the context
// menu there.
ctx_menu->addAction(window()->findChild<QAction *>("actionEditMarkPacket"));
ctx_menu->addAction(window()->findChild<QAction *>("actionEditIgnorePacket"));
ctx_menu->addAction(window()->findChild<QAction *>("actionEditSetTimeReference"));
ctx_menu->addAction(window()->findChild<QAction *>("actionEditTimeShift"));
ctx_menu->addMenu(window()->findChild<QMenu *>("menuPacketComment"));
ctx_menu->addSeparator();
// Code for custom context menus from Lua's register_packet_menu()
MainWindow * mainWindow = qobject_cast<MainWindow *>(mainApp->mainWindow());
if (cap_file_ && cap_file_->edt && cap_file_->edt->tree && mainWindow) {
bool insertedPacketMenu = mainWindow->addPacketMenus(ctx_menu, finfo_array);
if (insertedPacketMenu) {
ctx_menu->addSeparator();
}
}
ctx_menu->addAction(window()->findChild<QAction *>("actionViewEditResolvedName"));
ctx_menu->addSeparator();
QString selectedfilter = getFilterFromRowAndColumn(currentIndex());
if (! hasFocus() && cap_file_ && cap_file_->finfo_selected) {
char *tmp_field = proto_construct_match_selected_string(cap_file_->finfo_selected, cap_file_->edt);
selectedfilter = QString(tmp_field);
wmem_free(NULL, tmp_field);
}
bool have_filter_expr = !selectedfilter.isEmpty();
ctx_menu->addMenu(FilterAction::createFilterMenu(FilterAction::ActionApply, selectedfilter, have_filter_expr, ctx_menu));
ctx_menu->addMenu(FilterAction::createFilterMenu(FilterAction::ActionPrepare, selectedfilter, have_filter_expr, ctx_menu));
const char *conv_menu_name = "menuConversationFilter";
QMenu * main_menu_item = window()->findChild<QMenu *>(conv_menu_name);
conv_menu_.setTitle(main_menu_item->title());
conv_menu_.setObjectName(conv_menu_name);
ctx_menu->addMenu(&conv_menu_);
const char *colorize_menu_name = "menuColorizeConversation";
main_menu_item = window()->findChild<QMenu *>(colorize_menu_name);
colorize_menu_.setTitle(main_menu_item->title());
colorize_menu_.setObjectName(colorize_menu_name);
ctx_menu->addMenu(&colorize_menu_);
QMenu * submenu;
main_menu_item = window()->findChild<QMenu *>("menuSCTP");
if (main_menu_item) {
submenu = new QMenu(main_menu_item->title(), ctx_menu);
ctx_menu->addMenu(submenu);
submenu->addAction(window()->findChild<QAction *>("actionSCTPAnalyseThisAssociation"));
submenu->addAction(window()->findChild<QAction *>("actionSCTPShowAllAssociations"));
submenu->addAction(window()->findChild<QAction *>("actionSCTPFilterThisAssociation"));
}
main_menu_item = window()->findChild<QMenu *>("menuFollow");
if (main_menu_item) {
submenu = new QMenu(main_menu_item->title(), ctx_menu);
ctx_menu->addMenu(submenu);
foreach (FollowStreamAction *follow_action, main_menu_item->findChildren<FollowStreamAction *>()) {
/* XXX: We could, like the prefs above, walk the protocols/layers
* and add the follow actions in the order they appear in the packet.
*/
if (follow_action->isEnabled()) {
submenu->addAction(follow_action);
}
}
}
ctx_menu->addSeparator();
main_menu_item = window()->findChild<QMenu *>("menuEditCopy");
submenu = new QMenu(main_menu_item->title(), ctx_menu);
ctx_menu->addMenu(submenu);
QAction * action = submenu->addAction(tr("Summary as Text"));
action->setData(CopyAsText);
connect(action, SIGNAL(triggered()), this, SLOT(copySummary()));
action = submenu->addAction(tr("…as CSV"));
action->setData(CopyAsCSV);
connect(action, SIGNAL(triggered()), this, SLOT(copySummary()));
action = submenu->addAction(tr("…as YAML"));
action->setData(CopyAsYAML);
connect(action, SIGNAL(triggered()), this, SLOT(copySummary()));
submenu->addSeparator();
submenu->addAction(window()->findChild<QAction *>("actionEditCopyAsFilter"));
submenu->addSeparator();
QActionGroup * copyEntries = DataPrinter::copyActions(this, frameData);
submenu->addActions(copyEntries->actions());
copyEntries->setParent(submenu);
frameData->setParent(submenu);
ctx_menu->addSeparator();
ctx_menu->addMenu(&proto_prefs_menus_);
action = ctx_menu->addAction(tr("Decode As…"));
action->setProperty("create_new", QVariant(true));
connect(action, &QAction::triggered, this, &PacketList::ctxDecodeAsDialog);
// "Print" not ported intentionally
action = window()->findChild<QAction *>("actionViewShowPacketInNewWindow");
ctx_menu->addAction(action);
// Set menu sensitivity for the current column and set action data.
if (frameData)
emit framesSelected(QList<int>() << frameData->frameNum());
else
emit framesSelected(QList<int>());
ctx_menu->popup(event->globalPos());
}
void PacketList::ctxDecodeAsDialog()
{
QAction *da_action = qobject_cast<QAction*>(sender());
if (! da_action)
return;
bool create_new = da_action->property("create_new").toBool();
DecodeAsDialog *da_dialog = new DecodeAsDialog(this, cap_file_, create_new);
connect(da_dialog, SIGNAL(destroyed(QObject*)), mainApp, SLOT(flushAppSignals()));
da_dialog->setWindowModality(Qt::ApplicationModal);
da_dialog->setAttribute(Qt::WA_DeleteOnClose);
da_dialog->show();
}
void PacketList::timerEvent(QTimerEvent *event)
{
if (event->timerId() == overlay_timer_id_) {
if (!capture_in_progress_) {
if (create_near_overlay_) drawNearOverlay();
if (create_far_overlay_) drawFarOverlay();
}
} else {
QTreeView::timerEvent(event);
}
}
void PacketList::paintEvent(QPaintEvent *event)
{
// XXX This is overkill, but there are quite a few events that
// require a new overlay, e.g. page up/down, scrolling, column
// resizing, etc.
create_near_overlay_ = true;
QTreeView::paintEvent(event);
}
void PacketList::mousePressEvent (QMouseEvent *event)
{
setAutoScroll(false);
QTreeView::mousePressEvent(event);
setAutoScroll(true);
QModelIndex curIndex = indexAt(event->pos());
mouse_pressed_at_ = curIndex;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
bool midButton = (event->buttons() & Qt::MiddleButton) == Qt::MiddleButton;
#else
bool midButton = (event->buttons() & Qt::MidButton) == Qt::MidButton;
#endif
if (midButton && cap_file_ && packet_list_model_)
{
packet_list_model_->toggleFrameMark(QModelIndexList() << curIndex);
// Make sure the packet list's frame.marked related field text is updated.
redrawVisiblePackets();
create_far_overlay_ = true;
packets_bar_update();
}
}
void PacketList::mouseReleaseEvent(QMouseEvent *event) {
QTreeView::mouseReleaseEvent(event);
mouse_pressed_at_ = QModelIndex();
}
void PacketList::mouseMoveEvent (QMouseEvent *event)
{
QModelIndex curIndex = indexAt(event->pos());
if (event->buttons() & Qt::LeftButton && curIndex.isValid() && curIndex == mouse_pressed_at_)
{
ctx_column_ = curIndex.column();
QMimeData * mimeData = new QMimeData();
QWidget * content = nullptr;
QString filter = getFilterFromRowAndColumn(curIndex);
QList<int> rows = selectedRows();
if (rows.count() > 1)
{
QStringList content;
foreach (int row, rows)
{
QModelIndex idx = model()->index(row, 0);
if (! idx.isValid())
continue;
QString entry = createSummaryText(idx, CopyAsText);
content << entry;
}
if (content.count() > 0)
mimeData->setText(content.join("\n"));
}
else if (! filter.isEmpty())
{
QString abbrev;
QString name = model()->headerData(curIndex.column(), header()->orientation()).toString();
if (! filter.isEmpty())
{
abbrev = filter.left(filter.indexOf(' '));
}
else
{
filter = model()->data(curIndex).toString().toLower();
abbrev = filter;
}
mimeData->setText(filter);
QJsonObject filterData;
filterData["filter"] = filter;
filterData["name"] = abbrev;
filterData["description"] = name;
mimeData->setData(WiresharkMimeData::DisplayFilterMimeType, QJsonDocument(filterData).toJson());
content = new DragLabel(QString("%1\n%2").arg(name, abbrev), this);
}
else
{
QString text = model()->data(curIndex).toString();
if (! text.isEmpty())
mimeData->setText(text);
}
if (mimeData->hasText() || mimeData->hasFormat(WiresharkMimeData::DisplayFilterMimeType))
{
QDrag * drag = new QDrag(this);
drag->setMimeData(mimeData);
if (content)
{
qreal dpr = window()->windowHandle()->devicePixelRatio();
QPixmap pixmap= QPixmap(content->size() * dpr);
pixmap.setDevicePixelRatio(dpr);
content->render(&pixmap);
drag->setPixmap(pixmap);
}
drag->exec(Qt::CopyAction);
}
else
{
delete mimeData;
}
}
}
void PacketList::keyPressEvent(QKeyEvent *event)
{
bool handled = false;
// If scrolling up/down, want to preserve horizontal scroll extent.
if (event->key() == Qt::Key_Down || event->key() == Qt::Key_Up ||
event->key() == Qt::Key_PageDown || event->key() == Qt::Key_PageUp ||
event->key() == Qt::Key_End || event->key() == Qt::Key_Home )
{
// XXX: Why allow jumping to the left if the first column is current?
if (currentIndex().isValid() && currentIndex().column() > 0) {
int pos = horizontalScrollBar()->value();
QTreeView::keyPressEvent(event);
horizontalScrollBar()->setValue(pos);
handled = true;
}
}
if (!handled)
QTreeView::keyPressEvent(event);
if (event->matches(QKeySequence::Copy))
{
QStringList content;
if (model() && selectionModel() && selectionModel()->hasSelection())
{
QList<int> rows;
QModelIndexList selRows = selectionModel()->selectedRows(0);
foreach(QModelIndex row, selRows)
rows.append(row.row());
foreach(int row, rows)
{
QModelIndex idx = model()->index(row, 0);
if (! idx.isValid())
continue;
QString entry = createSummaryText(idx, CopyAsText);
content << entry;
}
}
if (content.count() > 0)
mainApp->clipboard()->setText(content.join('\n'), QClipboard::Clipboard);
}
}
void PacketList::resizeEvent(QResizeEvent *event)
{
create_near_overlay_ = true;
create_far_overlay_ = true;
QTreeView::resizeEvent(event);
}
void PacketList::setColumnVisibility()
{
set_column_visibility_ = true;
for (int i = 0; i < prefs.num_cols; i++) {
setColumnHidden(i, get_column_visible(i) ? false : true);
}
set_column_visibility_ = false;
}
int PacketList::sizeHintForColumn(int column) const
{
int size_hint = 0;
// This is a bit hacky but Qt does a fine job of column sizing and
// reimplementing QTreeView::sizeHintForColumn seems like a worse idea.
if (itemDelegateForColumn(column)) {
QStyleOptionViewItem option;
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
initViewItemOption(&option);
#else
option = viewOptions();
#endif
// In my (gcc) testing this results in correct behavior on Windows but adds extra space
// on macOS and Linux. We might want to add Q_OS_... #ifdefs accordingly.
size_hint = itemDelegateForColumn(column)->sizeHint(option, QModelIndex()).width();
}
size_hint += QTreeView::sizeHintForColumn(column); // Decoration padding
return size_hint;
}
void PacketList::setRecentColumnWidth(int col)
{
int col_width = recent_get_column_width(col);
if (col_width < 1) {
int fmt = get_column_format(col);
const char *long_str = get_column_width_string(fmt, col);
QFontMetrics fm = QFontMetrics(mainApp->monospaceFont());
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
if (long_str) {
col_width = fm.horizontalAdvance(long_str);
} else {
col_width = fm.horizontalAdvance(MIN_COL_WIDTH_STR);
}
#else
if (long_str) {
col_width = fm.width(long_str);
} else {
col_width = fm.width(MIN_COL_WIDTH_STR);
}
#endif
// Custom delegate padding
if (itemDelegateForColumn(col)) {
QStyleOptionViewItem option;
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
initViewItemOption(&option);
#else
option = viewOptions();
#endif
col_width += itemDelegateForColumn(col)->sizeHint(option, QModelIndex()).width();
}
}
setColumnWidth(col, col_width);
}
void PacketList::drawCurrentPacket()
{
QModelIndex current_index = currentIndex();
if (selectionModel() && current_index.isValid()) {
selectionModel()->clearSelection();
selectionModel()->setCurrentIndex(current_index, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
}
}
// Redraw the packet list and detail. Re-selects the current packet (causes
// the UI to scroll to that packet).
// Called from many places.
void PacketList::redrawVisiblePackets() {
redrawVisiblePacketsDontSelectCurrent();
drawCurrentPacket();
}
// Redraw the packet list and detail.
// Does not scroll back to the selected packet.
void PacketList::redrawVisiblePacketsDontSelectCurrent() {
packet_list_model_->invalidateAllColumnStrings();
}
void PacketList::resetColumns()
{
packet_list_model_->resetColumns();
}
// Return true if we have a visible packet further along in the history.
bool PacketList::haveNextHistory(bool update_cur)
{
if (selection_history_.size() < 1 || cur_history_ >= selection_history_.size() - 1) {
return false;
}
for (int i = cur_history_ + 1; i < selection_history_.size(); i++) {
if (packet_list_model_->packetNumberToRow(selection_history_.at(i)) >= 0) {
if (update_cur) {
cur_history_ = i;
}
return true;
}
}
return false;
}
// Return true if we have a visible packet back in the history.
bool PacketList::havePreviousHistory(bool update_cur)
{
if (selection_history_.size() < 1 || cur_history_ < 1) {
return false;
}
for (int i = cur_history_ - 1; i >= 0; i--) {
if (packet_list_model_->packetNumberToRow(selection_history_.at(i)) >= 0) {
if (update_cur) {
cur_history_ = i;
}
return true;
}
}
return false;
}
frame_data *PacketList::getFDataForRow(int row) const
{
return packet_list_model_->getRowFdata(row);
}
// prefs.col_list has changed.
void PacketList::columnsChanged()
{
columns_changed_ = true;
column_register_fields();
mainApp->emitAppSignal(MainApplication::FieldsChanged);
if (!cap_file_) {
// Keep columns_changed_ = true until we load a capture file.
return;
}
prefs.num_cols = g_list_length(prefs.col_list);
col_cleanup(&cap_file_->cinfo);
build_column_format_array(&cap_file_->cinfo, prefs.num_cols, FALSE);
create_far_overlay_ = true;
resetColumns();
applyRecentColumnWidths();
setColumnVisibility();
columns_changed_ = false;
}
// Fields have changed, update custom columns
void PacketList::fieldsChanged(capture_file *cf)
{
prefs.num_cols = g_list_length(prefs.col_list);
col_cleanup(&cf->cinfo);
build_column_format_array(&cf->cinfo, prefs.num_cols, FALSE);
resetColumns();
}
// Column widths should
// - Load from recent when we load a new profile (including at starting up).
// - Reapply when changing columns.
// - Persist across freezes and thaws.
// - Persist across file closing and opening.
// - Save to recent when we save our profile (including shutting down).
// - Not be affected by the behavior of stretchLastSection. (XXX: We
// still save the stretched value to recent, sectionResized doesn't
// distinguish between a resize from being stretched and a manual change.)
void PacketList::applyRecentColumnWidths()
{
// Either we've just started up or a profile has changed. Read
// the recent settings, apply them, and save the header state.
for (int col = 0; col < prefs.num_cols; col++) {
// The column must be shown before setting column width.
// Visibility will be updated in setColumnVisibility().
setColumnHidden(col, false);
setRecentColumnWidth(col);
}
column_state_ = header()->saveState();
}
void PacketList::preferencesChanged()
{
// Update color style changes
colorsChanged();
// Related packet delegate
if (prefs.gui_packet_list_show_related) {
setItemDelegateForColumn(0, &related_packet_delegate_);
} else {
setItemDelegateForColumn(0, 0);
}
// Intelligent scroll bar (minimap)
if (prefs.gui_packet_list_show_minimap) {
if (overlay_timer_id_ == 0) {
overlay_timer_id_ = startTimer(overlay_update_interval_);
}
} else {
if (overlay_timer_id_ != 0) {
killTimer(overlay_timer_id_);
overlay_timer_id_ = 0;
}
}
// Elide mode.
// This sets the mode for the entire view. If we want to make this setting
// per-column we'll either have to generalize RelatedPacketDelegate so that
// we can set it for entire rows or create another delegate.
Qt::TextElideMode elide_mode = Qt::ElideRight;
switch (prefs.gui_packet_list_elide_mode) {
case ELIDE_LEFT:
elide_mode = Qt::ElideLeft;
break;
case ELIDE_MIDDLE:
elide_mode = Qt::ElideMiddle;
break;
case ELIDE_NONE:
elide_mode = Qt::ElideNone;
break;
default:
break;
}
setTextElideMode(elide_mode);
}
void PacketList::freezePacketList(bool changing_profile)
{
changing_profile_ = changing_profile;
freeze(true);
}
void PacketList::recolorPackets()
{
packet_list_model_->resetColorized();
redrawVisiblePackets();
}
// Enable autoscroll.
void PacketList::setVerticalAutoScroll(bool enabled)
{
tail_at_end_ = enabled;
if (enabled && capture_in_progress_) {
scrollToBottom();
}
}
// Called when we finish reading, reloading, rescanning, and retapping
// packets.
void PacketList::captureFileReadFinished()
{
packet_list_model_->flushVisibleRows();
packet_list_model_->dissectIdle(true);
// Invalidating the column strings picks up and request/response
// tracking changes. We might just want to call it from flushVisibleRows.
packet_list_model_->invalidateAllColumnStrings();
// Sort *after* invalidating the column strings
if (isSortingEnabled()) {
sortByColumn(header()->sortIndicatorSection(), header()->sortIndicatorOrder());
}
}
bool PacketList::freeze(bool keep_current_frame)
{
if (!cap_file_ || model() == Q_NULLPTR) {
// No capture file or already frozen
return false;
}
frame_data *current_frame = cap_file_->current_frame;
column_state_ = header()->saveState();
setHeaderHidden(true);
frozen_current_row_ = currentIndex();
frozen_selected_rows_ = selectionModel()->selectedRows();
selectionModel()->clear();
setModel(Q_NULLPTR);
// It looks like GTK+ sends a cursor-changed signal at this point but Qt doesn't
// call selectionChanged.
related_packet_delegate_.clear();
if (keep_current_frame) {
cap_file_->current_frame = current_frame;
}
/* Clears packet list as well as byteview */
emit framesSelected(QList<int>());
return true;
}
bool PacketList::thaw(bool restore_selection)
{
if (!cap_file_ || model() != Q_NULLPTR) {
// No capture file or not frozen
return false;
}
setHeaderHidden(false);
// Note that if we have a current sort status set in the header,
// this will automatically try to sort the model (we don't want
// that to happen if we're in the middle of reading the file).
setModel(packet_list_model_);
if (changing_profile_) {
// When changing profile the new recent settings must be applied to the columns.
applyRecentColumnWidths();
setColumnVisibility();
changing_profile_ = false;
} else {
// Resetting the model resets our column widths so we restore them here.
// We don't reapply the recent settings because the user could have
// resized the columns manually since they were initially loaded.
header()->restoreState(column_state_);
}
if (restore_selection && frozen_selected_rows_.length() > 0 && selectionModel()) {
/* This updates our selection, which redissects the current packet,
* which is needed when we're called from MainWindow::layoutPanes.
* Also, this resets all ProtoTree and ByteView data */
clearSelection();
setCurrentIndex(frozen_current_row_);
foreach (QModelIndex idx, frozen_selected_rows_) {
selectionModel()->select(idx, QItemSelectionModel::Select | QItemSelectionModel::Rows);
}
scrollTo(currentIndex(), PositionAtCenter);
}
frozen_current_row_ = QModelIndex();
frozen_selected_rows_ = QModelIndexList();
return true;
}
void PacketList::clear() {
related_packet_delegate_.clear();
selectionModel()->clear();
packet_list_model_->clear();
proto_tree_->clear();
selection_history_.clear();
cur_history_ = -1;
in_history_ = false;
QImage overlay;
overlay_sb_->setNearOverlayImage(overlay);
overlay_sb_->setMarkedPacketImage(overlay);
create_near_overlay_ = true;
create_far_overlay_ = true;
}
void PacketList::writeRecent(FILE *rf) {
gint col, width, col_fmt;
gchar xalign;
fprintf (rf, "%s:\n", RECENT_KEY_COL_WIDTH);
for (col = 0; col < prefs.num_cols; col++) {
if (col > 0) {
fprintf (rf, ",\n");
}
col_fmt = get_column_format(col);
if (col_fmt == COL_CUSTOM) {
fprintf (rf, " \"%%Cus:%s\",", get_column_custom_fields(col));
} else {
fprintf (rf, " %s,", col_format_to_string(col_fmt));
}
width = recent_get_column_width (col);
xalign = recent_get_column_xalign (col);
fprintf (rf, " %d", width);
if (xalign != COLUMN_XALIGN_DEFAULT) {
fprintf (rf, ":%c", xalign);
}
}
fprintf (rf, "\n");
}
bool PacketList::contextMenuActive()
{
return ctx_column_ >= 0 ? true : false;
}
QString PacketList::getFilterFromRowAndColumn(QModelIndex idx)
{
frame_data *fdata;
QString filter;
if (! idx.isValid())
return filter;
int row = idx.row();
int column = idx.column();
if (!cap_file_ || !packet_list_model_ || column < 0 || column >= cap_file_->cinfo.num_cols)
return filter;
fdata = packet_list_model_->getRowFdata(row);
if (fdata != NULL) {
epan_dissect_t edt;
wtap_rec rec; /* Record metadata */
Buffer buf; /* Record data */
wtap_rec_init(&rec);
ws_buffer_init(&buf, 1514);
if (!cf_read_record(cap_file_, fdata, &rec, &buf)) {
wtap_rec_cleanup(&rec);
ws_buffer_free(&buf);
return filter; /* error reading the record */
}
/* proto tree, visible. We need a proto tree if there's custom columns */
epan_dissect_init(&edt, cap_file_->epan, have_custom_cols(&cap_file_->cinfo), FALSE);
col_custom_prime_edt(&edt, &cap_file_->cinfo);
epan_dissect_run(&edt, cap_file_->cd_t, &rec,
frame_tvbuff_new_buffer(&cap_file_->provider, fdata, &buf),
fdata, &cap_file_->cinfo);
if (cap_file_->cinfo.columns[column].col_fmt == COL_CUSTOM) {
filter.append(gchar_free_to_qstring(col_custom_get_filter(&edt, &cap_file_->cinfo, column)));
} else {
/* We don't need to fill in the custom columns, as we get their
* filters above.
*/
col_fill_in(&edt.pi, TRUE, TRUE);
if (strlen(cap_file_->cinfo.col_expr.col_expr[column]) != 0 &&
strlen(cap_file_->cinfo.col_expr.col_expr_val[column]) != 0) {
gboolean is_string_value = FALSE;
header_field_info *hfi = proto_registrar_get_byname(cap_file_->cinfo.col_expr.col_expr[column]);
if (hfi && hfi->type == FT_STRING) {
/* Could be an address type such as usb.src which must be quoted. */
is_string_value = TRUE;
}
if (filter.isEmpty()) {
if (is_string_value) {
filter.append(QString("%1 == \"%2\"")
.arg(cap_file_->cinfo.col_expr.col_expr[column])
.arg(cap_file_->cinfo.col_expr.col_expr_val[column]));
} else {
filter.append(QString("%1 == %2")
.arg(cap_file_->cinfo.col_expr.col_expr[column])
.arg(cap_file_->cinfo.col_expr.col_expr_val[column]));
}
}
}
}
epan_dissect_cleanup(&edt);
wtap_rec_cleanup(&rec);
ws_buffer_free(&buf);
}
return filter;
}
void PacketList::resetColorized()
{
packet_list_model_->resetColorized();
update();
}
QString PacketList::getPacketComment(guint c_number)
{
int row = currentIndex().row();
const frame_data *fdata;
char *pkt_comment;
wtap_opttype_return_val result;
QString ret_val = NULL;
if (!cap_file_ || !packet_list_model_) return NULL;
fdata = packet_list_model_->getRowFdata(row);
if (!fdata) return NULL;
wtap_block_t pkt_block = cf_get_packet_block(cap_file_, fdata);
result = wtap_block_get_nth_string_option_value(pkt_block, OPT_COMMENT, c_number, &pkt_comment);
if (result == WTAP_OPTTYPE_SUCCESS) {
ret_val = QString(pkt_comment);
}
wtap_block_unref(pkt_block);
return ret_val;
}
void PacketList::addPacketComment(QString new_comment)
{
if (!cap_file_ || !packet_list_model_) return;
if (new_comment.isEmpty()) return;
QByteArray ba = new_comment.toUtf8();
/*
* Make sure this would fit in a pcapng option.
*
* XXX - 65535 is the maximum size for an option in pcapng;
* what if another capture file format supports larger
* comments?
*/
if (ba.size() > 65535) {
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
"That comment is too large to save in a capture file.");
return;
}
if (selectionModel() && selectionModel()->hasSelection()) {
packet_list_model_->addFrameComment(selectionModel()->selectedRows(), ba);
drawCurrentPacket();
}
}
void PacketList::setPacketComment(guint c_number, QString new_comment)
{
QModelIndex curIndex = currentIndex();
if (!cap_file_ || !packet_list_model_) return;
QByteArray ba = new_comment.toUtf8();
/*
* Make sure this would fit in a pcapng option.
*
* XXX - 65535 is the maximum size for an option in pcapng;
* what if another capture file format supports larger
* comments?
*/
if (ba.size() > 65535) {
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
"That comment is too large to save in a capture file.");
return;
}
packet_list_model_->setFrameComment(curIndex, ba, c_number);
drawCurrentPacket();
}
QString PacketList::allPacketComments()
{
guint32 framenum;
frame_data *fdata;
QString buf_str;
if (!cap_file_) return buf_str;
for (framenum = 1; framenum <= cap_file_->count ; framenum++) {
fdata = frame_data_sequence_find(cap_file_->provider.frames, framenum);
wtap_block_t pkt_block = cf_get_packet_block(cap_file_, fdata);
if (pkt_block) {
guint n_comments = wtap_block_count_option(pkt_block, OPT_COMMENT);
for (guint i = 0; i < n_comments; i++) {
char *comment_text;
if (WTAP_OPTTYPE_SUCCESS == wtap_block_get_nth_string_option_value(pkt_block, OPT_COMMENT, i, &comment_text)) {
buf_str.append(QString(tr("Frame %1: %2\n\n")).arg(framenum).arg(comment_text));
if (buf_str.length() > max_comments_to_fetch_) {
buf_str.append(QString(tr("[ Comment text exceeds %1. Stopping. ]"))
.arg(format_size(max_comments_to_fetch_, FORMAT_SIZE_UNIT_BYTES, FORMAT_SIZE_PREFIX_SI)));
return buf_str;
}
}
}
}
}
return buf_str;
}
void PacketList::deleteCommentsFromPackets()
{
if (!cap_file_ || !packet_list_model_) return;
if (selectionModel() && selectionModel()->hasSelection()) {
packet_list_model_->deleteFrameComments(selectionModel()->selectedRows());
drawCurrentPacket();
}
}
void PacketList::deleteAllPacketComments()
{
if (!cap_file_ || !packet_list_model_) return;
packet_list_model_->deleteAllFrameComments();
drawCurrentPacket();
}
// Slots
void PacketList::setCaptureFile(capture_file *cf)
{
cap_file_ = cf;
packet_list_model_->setCaptureFile(cf);
if (cf) {
if (columns_changed_) {
columnsChanged();
} else {
// Restore columns widths and visibility.
header()->restoreState(column_state_);
setColumnVisibility();
}
}
create_near_overlay_ = true;
changing_profile_ = false;
sortByColumn(-1, Qt::AscendingOrder);
}
void PacketList::setMonospaceFont(const QFont &mono_font)
{
setFont(mono_font);
header()->setFont(mainApp->font());
}
void PacketList::goNextPacket(void)
{
if (QApplication::keyboardModifiers() & Qt::AltModifier) {
// Alt+toolbar
goNextHistoryPacket();
return;
}
if (selectionModel()->hasSelection()) {
selectionModel()->setCurrentIndex(moveCursor(MoveDown, Qt::NoModifier), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
} else {
// First visible packet.
selectionModel()->setCurrentIndex(indexAt(viewport()->rect().topLeft()), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}
scrollViewChanged(false);
}
void PacketList::goPreviousPacket(void)
{
if (QApplication::keyboardModifiers() & Qt::AltModifier) {
// Alt+toolbar
goPreviousHistoryPacket();
return;
}
if (selectionModel()->hasSelection()) {
selectionModel()->setCurrentIndex(moveCursor(MoveUp, Qt::NoModifier), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
} else {
// Last visible packet.
QModelIndex last_idx = indexAt(viewport()->rect().bottomLeft());
if (last_idx.isValid()) {
selectionModel()->setCurrentIndex(last_idx, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
} else {
goLastPacket();
}
}
scrollViewChanged(false);
}
void PacketList::goFirstPacket(void) {
if (packet_list_model_->rowCount() < 1) return;
selectionModel()->setCurrentIndex(packet_list_model_->index(0, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
scrollTo(currentIndex());
scrollViewChanged(false);
}
void PacketList::goLastPacket(void) {
if (packet_list_model_->rowCount() < 1) return;
selectionModel()->setCurrentIndex(packet_list_model_->index(packet_list_model_->rowCount() - 1, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
scrollTo(currentIndex());
scrollViewChanged(false);
}
// XXX We can jump to the wrong packet if a display filter is applied
void PacketList::goToPacket(int packet, int hf_id)
{
if (!cf_goto_frame(cap_file_, packet))
return;
int row = packet_list_model_->packetNumberToRow(packet);
if (row >= 0) {
selectionModel()->setCurrentIndex(packet_list_model_->index(row, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
scrollTo(currentIndex(), PositionAtCenter);
proto_tree_->goToHfid(hf_id);
}
scrollViewChanged(false);
}
void PacketList::goNextHistoryPacket()
{
if (haveNextHistory(true)) {
in_history_ = true;
goToPacket(selection_history_.at(cur_history_));
in_history_ = false;
}
}
void PacketList::goPreviousHistoryPacket()
{
if (havePreviousHistory(true)) {
in_history_ = true;
goToPacket(selection_history_.at(cur_history_));
in_history_ = false;
}
}
void PacketList::markFrame()
{
if (!cap_file_ || !packet_list_model_) return;
QModelIndexList frames;
if (selectionModel() && selectionModel()->hasSelection())
{
QModelIndexList selRows = selectionModel()->selectedRows(0);
foreach (QModelIndex idx, selRows)
{
if (idx.isValid())
{
frames << idx;
}
}
}
else
frames << currentIndex();
packet_list_model_->toggleFrameMark(frames);
// Make sure the packet list's frame.marked related field text is updated.
redrawVisiblePackets();
create_far_overlay_ = true;
packets_bar_update();
}
void PacketList::markAllDisplayedFrames(bool set)
{
if (!cap_file_ || !packet_list_model_) return;
packet_list_model_->setDisplayedFrameMark(set);
// Make sure the packet list's frame.marked related field text is updated.
redrawVisiblePackets();
create_far_overlay_ = true;
packets_bar_update();
}
void PacketList::ignoreFrame()
{
if (!cap_file_ || !packet_list_model_) return;
QModelIndexList frames;
if (selectionModel() && selectionModel()->hasSelection())
{
foreach (QModelIndex idx, selectionModel()->selectedRows(0))
{
if (idx.isValid())
{
frames << idx;
}
}
}
else
frames << currentIndex();
packet_list_model_->toggleFrameIgnore(frames);
create_far_overlay_ = true;
int sb_val = verticalScrollBar()->value(); // Surely there's a better way to keep our position?
setUpdatesEnabled(false);
emit packetDissectionChanged();
setUpdatesEnabled(true);
verticalScrollBar()->setValue(sb_val);
}
void PacketList::ignoreAllDisplayedFrames(bool set)
{
if (!cap_file_ || !packet_list_model_) return;
packet_list_model_->setDisplayedFrameIgnore(set);
create_far_overlay_ = true;
emit packetDissectionChanged();
}
void PacketList::setTimeReference()
{
if (!cap_file_ || !packet_list_model_) return;
packet_list_model_->toggleFrameRefTime(currentIndex());
create_far_overlay_ = true;
}
void PacketList::unsetAllTimeReferences()
{
if (!cap_file_ || !packet_list_model_) return;
packet_list_model_->unsetAllFrameRefTime();
create_far_overlay_ = true;
}
void PacketList::applyTimeShift()
{
packet_list_model_->resetColumns();
redrawVisiblePackets();
emit packetDissectionChanged();
}
void PacketList::updatePackets(bool redraw)
{
if (redraw) {
packet_list_model_->resetColumns();
redrawVisiblePackets();
} else {
update();
}
}
void PacketList::columnVisibilityTriggered()
{
QAction *ha = qobject_cast<QAction*>(sender());
if (!ha) return;
int col = ha->data().toInt();
set_column_visible(col, ha->isChecked());
setColumnVisibility();
if (ha->isChecked()) {
setRecentColumnWidth(col);
}
prefs_main_write();
}
void PacketList::sectionResized(int col, int, int new_width)
{
if (isVisible() && !columns_changed_ && !set_column_visibility_ && new_width > 0) {
// Column 1 gets an invalid value (32 on macOS) when we're not yet
// visible.
//
// Don't set column width when columns changed or setting column
// visibility because we may get a sectionReized() from QTreeView
// with values from a old columns layout.
//
// Don't set column width when hiding a column.
recent_set_column_width(col, new_width);
}
}
// The user moved a column. Make sure prefs.col_list, the column format
// array, and the header's visual and logical indices all agree.
// gtk/packet_list.c:column_dnd_changed_cb
void PacketList::sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex)
{
GList *new_col_list = NULL;
QList<int> saved_sizes;
int sort_idx;
// Since we undo the move below, these should always stay in sync.
// Otherwise the order of columns can be unexpected after drag and drop.
if (logicalIndex != oldVisualIndex) {
ws_warning("Column moved from an unexpected state (%d, %d, %d)",
logicalIndex, oldVisualIndex, newVisualIndex);
}
// Remember which column should be sorted. Use the visual index since this
// points to the current GUI state rather than the outdated column order
// (indicated by the logical index).
sort_idx = header()->sortIndicatorSection();
if (sort_idx != -1) {
sort_idx = header()->visualIndex(sort_idx);
}
// Build a new column list based on the header's logical order.
for (int vis_idx = 0; vis_idx < header()->count(); vis_idx++) {
int log_idx = header()->logicalIndex(vis_idx);
saved_sizes << header()->sectionSize(log_idx);
void *pref_data = g_list_nth_data(prefs.col_list, log_idx);
if (!pref_data) continue;
new_col_list = g_list_append(new_col_list, pref_data);
}
// Undo move to ensure that the logical indices map to the visual indices,
// otherwise the column order is changed twice (once via the modified
// col_list, once because of the visual/logical index mismatch).
disconnect(header(), SIGNAL(sectionMoved(int,int,int)),
this, SLOT(sectionMoved(int,int,int)));
header()->moveSection(newVisualIndex, oldVisualIndex);
connect(header(), SIGNAL(sectionMoved(int,int,int)),
this, SLOT(sectionMoved(int,int,int)));
// Clear and rebuild our (and the header's) model. There doesn't appear
// to be another way to reset the logical index.
freeze();
g_list_free(prefs.col_list);
prefs.col_list = new_col_list;
thaw(true);
for (int i = 0; i < saved_sizes.length(); i++) {
if (saved_sizes[i] < 1) continue;
header()->resizeSection(i, saved_sizes[i]);
}
prefs_main_write();
mainApp->emitAppSignal(MainApplication::ColumnsChanged);
// If the column with the sort indicator got shifted, mark the new column
// after updating the columns contents (via ColumnsChanged) to ensure that
// the columns are sorted using the intended column contents.
int left_col = MIN(oldVisualIndex, newVisualIndex);
int right_col = MAX(oldVisualIndex, newVisualIndex);
if (left_col <= sort_idx && sort_idx <= right_col) {
header()->setSortIndicator(sort_idx, header()->sortIndicatorOrder());
}
}
void PacketList::updateRowHeights(const QModelIndex &ih_index)
{
QStyleOptionViewItem option;
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
initViewItemOption(&option);
#else
option = viewOptions();
#endif
int max_height = 0;
// One of our columns increased the maximum row height. Find out which one.
for (int col = 0; col < packet_list_model_->columnCount(); col++) {
QSize size_hint = itemDelegate()->sizeHint(option, packet_list_model_->index(ih_index.row(), col));
max_height = qMax(max_height, size_hint.height());
}
if (max_height > 0) {
packet_list_model_->setMaximumRowHeight(max_height);
}
}
QString PacketList::createSummaryText(QModelIndex idx, SummaryCopyType type)
{
if (! idx.isValid())
return "";
QStringList col_parts;
int row = idx.row();
for (int col = 0; col < packet_list_model_->columnCount(); col++) {
if (get_column_visible(col)) {
col_parts << packet_list_model_->data(packet_list_model_->index(row, col), Qt::DisplayRole).toString();
}
}
return joinSummaryRow(col_parts, row, type);
}
QString PacketList::createHeaderSummaryText(SummaryCopyType type)
{
QStringList col_parts;
for (int col = 0; col < packet_list_model_->columnCount(); ++col)
{
if (get_column_visible(col)) {
col_parts << packet_list_model_->headerData(col, Qt::Orientation::Horizontal, Qt::DisplayRole).toString();
}
}
return joinSummaryRow(col_parts, 0, type);
}
void PacketList::copySummary()
{
if (!currentIndex().isValid()) return;
QAction *ca = qobject_cast<QAction*>(sender());
if (!ca) return;
QVariant type = ca->data();
if (! type.canConvert<SummaryCopyType>())
return;
SummaryCopyType copy_type = type.value<SummaryCopyType>();
QString copy_text = createSummaryText(currentIndex(), copy_type);
mainApp->clipboard()->setText(copy_text);
}
// We need to tell when the user has scrolled the packet list, either to
// the end or anywhere other than the end.
void PacketList::vScrollBarActionTriggered(int)
{
// If we're scrolling with a mouse wheel or trackpad sliderPosition can end up
// past the end.
tail_at_end_ = (overlay_sb_->sliderPosition() >= overlay_sb_->maximum());
scrollViewChanged(tail_at_end_);
}
void PacketList::scrollViewChanged(bool at_end)
{
if (capture_in_progress_) {
// We want to start auto scrolling when the user scrolls to (or past)
// the end only if recent.capture_auto_scroll is set.
// We want to stop autoscrolling if the user scrolls up or uses
// Go to Packet regardless of the preference setting.
if (recent.capture_auto_scroll || !at_end) {
emit packetListScrolled(at_end);
}
}
}
// Goal: Overlay the packet list scroll bar with the colors of all of the
// packets.
// Try 1: Average packet colors in each scroll bar raster line. This has
// two problems: It's easy to wash out colors and we dissect every packet.
// Try 2: Color across a 5000 or 10000 packet window. We still end up washing
// out colors.
// Try 3: One packet per vertical scroll bar pixel. This seems to work best
// but has the smallest window.
// Try 4: Use a multiple of the scroll bar heigh and scale the image down
// using Qt::SmoothTransformation. This gives us more packets per raster
// line.
// Odd (prime?) numbers resulted in fewer scaling artifacts. A multiplier
// of 9 washed out colors a little too much.
//const int height_multiplier_ = 7;
void PacketList::drawNearOverlay()
{
if (create_near_overlay_) {
create_near_overlay_ = false;
}
if (!cap_file_ || cap_file_->state != FILE_READ_DONE) return;
if (!prefs.gui_packet_list_show_minimap) return;
qreal dp_ratio = overlay_sb_->devicePixelRatio();
int o_height = overlay_sb_->height() * dp_ratio;
int o_rows = qMin(packet_list_model_->rowCount(), o_height);
QFontMetricsF fmf(mainApp->font());
int o_width = ((static_cast<int>(fmf.height())) * 2 * dp_ratio) + 2; // 2ems + 1-pixel border on either side.
if (recent.packet_list_colorize && o_rows > 0) {
QImage overlay(o_width, o_height, QImage::Format_ARGB32_Premultiplied);
QPainter painter(&overlay);
overlay.fill(Qt::transparent);
int cur_line = 0;
int start = 0;
if (packet_list_model_->rowCount() > o_height && overlay_sb_->maximum() > 0) {
start += ((double) overlay_sb_->value() / overlay_sb_->maximum()) * (packet_list_model_->rowCount() - o_rows);
}
int end = start + o_rows;
for (int row = start; row < end; row++) {
packet_list_model_->ensureRowColorized(row);
frame_data *fdata = packet_list_model_->getRowFdata(row);
const color_t *bgcolor = NULL;
if (fdata->color_filter) {
const color_filter_t *color_filter = (const color_filter_t *) fdata->color_filter;
bgcolor = &color_filter->bg_color;
}
int next_line = (row - start + 1) * o_height / o_rows;
if (bgcolor) {
QColor color(ColorUtils::fromColorT(bgcolor));
painter.fillRect(0, cur_line, o_width, next_line - cur_line, color);
}
cur_line = next_line;
}
// If the selected packet is in the overlay set selected_pos
// accordingly. Otherwise, pin it to either the top or bottom.
QList<int> positions;
if (selectionModel()->hasSelection()) {
QModelIndexList selRows = selectionModel()->selectedRows(0);
int last_row = -1;
int last_pos = -1;
foreach (QModelIndex idx, selRows)
{
int selected_pos = -1;
int sel_row = idx.row();
if (sel_row < start) {
selected_pos = 0;
} else if (sel_row >= end) {
selected_pos = overlay.height() - 1;
} else {
selected_pos = (sel_row - start) * o_height / o_rows;
}
/* Due to the difference in the display height, we sometimes get empty positions
* inbetween consecutive valid rows. If those are detected, they are signaled as
* being selected as well */
if (last_pos >= 0 && selected_pos > (last_pos + 1) && (last_row + 1) == sel_row)
{
for (int pos = (last_pos + 1); pos < selected_pos; pos++)
{
if (! positions.contains(pos))
positions << pos;
}
}
else if (selected_pos != -1 && ! positions.contains(selected_pos))
positions << selected_pos;
last_row = sel_row;
last_pos = selected_pos;
}
}
overlay_sb_->setNearOverlayImage(overlay, packet_list_model_->rowCount(), start, end, positions, (o_height / o_rows));
} else {
QImage overlay;
overlay_sb_->setNearOverlayImage(overlay);
}
}
void PacketList::drawFarOverlay()
{
if (create_far_overlay_) {
create_far_overlay_ = false;
}
if (!cap_file_ || cap_file_->state != FILE_READ_DONE) return;
if (!prefs.gui_packet_list_show_minimap) return;
QSize groove_size = overlay_sb_->grooveRect().size();
qreal dp_ratio = overlay_sb_->devicePixelRatio();
groove_size *= dp_ratio;
int o_width = groove_size.width();
int o_height = groove_size.height();
int pl_rows = packet_list_model_->rowCount();
QImage overlay(o_width, o_height, QImage::Format_ARGB32_Premultiplied);
bool have_marked_image = false;
// If only there were references from popular culture about getting into
// some sort of groove.
if (!overlay.isNull() && recent.packet_list_colorize && pl_rows > 0) {
QPainter painter(&overlay);
// Draw text-colored tick marks on a transparent background.
// Hopefully no themes use the text color for the groove color.
overlay.fill(Qt::transparent);
QColor tick_color = palette().text().color();
tick_color.setAlphaF(0.3f);
painter.setPen(tick_color);
for (int row = 0; row < pl_rows; row++) {
frame_data *fdata = packet_list_model_->getRowFdata(row);
if (fdata->marked || fdata->ref_time || fdata->ignored) {
int new_line = row * o_height / pl_rows;
int tick_width = o_width / 3;
// Marked or ignored: left side, time refs: right side.
// XXX Draw ignored ticks in the middle?
int x1 = fdata->ref_time ? o_width - tick_width : 1;
int x2 = fdata->ref_time ? o_width - 1 : tick_width;
painter.drawLine(x1, new_line, x2, new_line);
have_marked_image = true;
}
}
if (have_marked_image) {
overlay_sb_->setMarkedPacketImage(overlay);
return;
}
}
if (!have_marked_image) {
QImage null_overlay;
overlay_sb_->setMarkedPacketImage(null_overlay);
}
}
// Auto scroll if:
// - We are capturing
// - actionGoAutoScroll in the main UI is checked.
// actionGoAutoScroll in the main UI:
// - Is set to the value of recent.capture_auto_scroll when beginning a capture
// - Can be triggered manually by the user
// - Is turned on if the last user-set vertical scrollbar position is at the
// end and recent.capture_auto_scroll is enabled
// - Is turned off if the last user-set vertical scrollbar is not at the end,
// or if one of the Go to Packet actions is used (XXX: Should keyboard
// navigation in keyPressEvent turn it off for similar reasons?)
void PacketList::rowsInserted(const QModelIndex &parent, int start, int end)
{
QTreeView::rowsInserted(parent, start, end);
if (capture_in_progress_ && tail_at_end_) {
scrollToBottom();
}
}
void PacketList::resizeAllColumns(bool onlyTimeFormatted)
{
if (!cap_file_ || cap_file_->state == FILE_CLOSED || cap_file_->state == FILE_READ_PENDING)
return;
for (int col = 0; col < cap_file_->cinfo.num_cols; col++) {
if (! onlyTimeFormatted || col_has_time_fmt(&cap_file_->cinfo, col)) {
resizeColumnToContents(col);
}
}
} |
C/C++ | wireshark/ui/qt/packet_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 PACKET_LIST_H
#define PACKET_LIST_H
#include "byte_view_tab.h"
#include <ui/qt/models/packet_list_model.h>
#include "proto_tree.h"
#include "protocol_preferences_menu.h"
#include <ui/qt/models/related_packet_delegate.h>
#include <ui/qt/utils/field_information.h>
#include <QMenu>
#include <QTime>
#include <QTreeView>
#include <QPainter>
class PacketListHeader;
class OverlayScrollBar;
class QAction;
class QTimerEvent;
//
// XXX - Wireshark supports up to 2^32-1 packets in a capture, but
// row numbers in a QAbstractItemModel are ints, not unsigned ints,
// so we can only have 2^31-1 rows on ILP32, LP64, and LLP64 platforms.
// Does that mean we're permanently stuck at a maximum of 2^31-1 packets
// per capture?
//
class PacketList : public QTreeView
{
Q_OBJECT
public:
explicit PacketList(QWidget *parent = 0);
~PacketList();
enum SummaryCopyType {
CopyAsText,
CopyAsCSV,
CopyAsYAML
};
Q_ENUM(SummaryCopyType)
QMenu *conversationMenu() { return &conv_menu_; }
QMenu *colorizeMenu() { return &colorize_menu_; }
void setProtoTree(ProtoTree *proto_tree);
/** Disable and clear the packet list.
*
* @param keep_current_frame If true, keep the selected frame.
* Disable packet list widget updates, clear the detail and byte views,
* and disconnect the model.
*/
bool freeze(bool keep_current_frame = false);
/** Enable and restore the packet list.
*
* Enable packet list widget updates and reconnect the model.
*
* @param restore_selection If true, redissect the previously selected
* packet. This includes filling in the detail and byte views.
*/
bool thaw(bool restore_selection = false);
void clear();
void writeRecent(FILE *rf);
bool contextMenuActive();
QString getFilterFromRowAndColumn(QModelIndex idx);
void resetColorized();
QString getPacketComment(guint c_number);
void addPacketComment(QString new_comment);
void setPacketComment(guint c_number, QString new_comment);
QString allPacketComments();
void deleteCommentsFromPackets();
void deleteAllPacketComments();
void setVerticalAutoScroll(bool enabled = true);
void setCaptureInProgress(bool in_progress = false, bool auto_scroll = true) { capture_in_progress_ = in_progress; tail_at_end_ = in_progress && auto_scroll; }
void captureFileReadFinished();
void resetColumns();
bool haveNextHistory(bool update_cur = false);
bool havePreviousHistory(bool update_cur = false);
frame_data * getFDataForRow(int row) const;
bool uniqueSelectActive();
bool multiSelectActive();
QList<int> selectedRows(bool useFrameNum = false);
QString createSummaryText(QModelIndex idx, SummaryCopyType type);
QString createHeaderSummaryText(SummaryCopyType type);
void resizeAllColumns(bool onlyTimeFormatted = false);
protected:
void selectionChanged(const QItemSelection & selected, const QItemSelection & deselected) override;
virtual void contextMenuEvent(QContextMenuEvent *event) override;
void timerEvent(QTimerEvent *event) override;
void paintEvent(QPaintEvent *event) override;
virtual void mousePressEvent (QMouseEvent *event) override;
virtual void mouseReleaseEvent (QMouseEvent *event) override;
virtual void mouseMoveEvent (QMouseEvent *event) override;
virtual void resizeEvent(QResizeEvent *event) override;
virtual void keyPressEvent(QKeyEvent *event) override;
protected slots:
void rowsInserted(const QModelIndex &parent, int start, int end) override;
virtual void drawRow(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const override;
private:
PacketListModel *packet_list_model_;
PacketListHeader * packet_list_header_;
ProtoTree *proto_tree_;
capture_file *cap_file_;
QMenu conv_menu_;
QMenu colorize_menu_;
QMenu proto_prefs_menus_;
int ctx_column_;
QByteArray column_state_;
OverlayScrollBar *overlay_sb_;
int overlay_timer_id_;
bool create_near_overlay_;
bool create_far_overlay_;
QVector<QRgb> overlay_colors_;
bool changing_profile_;
QModelIndex mouse_pressed_at_;
RelatedPacketDelegate related_packet_delegate_;
QAction *show_hide_separator_;
QList<QAction *>show_hide_actions_;
bool capture_in_progress_;
bool tail_at_end_;
bool columns_changed_;
bool set_column_visibility_;
QModelIndex frozen_current_row_;
QModelIndexList frozen_selected_rows_;
QVector<int> selection_history_;
int cur_history_;
bool in_history_;
GPtrArray *finfo_array; // Packet data from the last selected packet entry
void setFrameReftime(gboolean set, frame_data *fdata);
void setColumnVisibility();
int sizeHintForColumn(int column) const override;
void setRecentColumnWidth(int column);
void drawCurrentPacket();
void applyRecentColumnWidths();
void scrollViewChanged(bool at_end);
void colorsChanged();
QString joinSummaryRow(QStringList col_parts, int row, SummaryCopyType type);
signals:
void packetDissectionChanged();
void showColumnPreferences(QString pane_name);
void editColumn(int column);
void packetListScrolled(bool at_end);
void showProtocolPreferences(const QString module_name);
void editProtocolPreference(struct preference *pref, struct pref_module *module);
void framesSelected(QList<int>);
void fieldSelected(FieldInformation *);
public slots:
void setCaptureFile(capture_file *cf);
void setMonospaceFont(const QFont &mono_font);
void goNextPacket();
void goPreviousPacket();
void goFirstPacket();
void goLastPacket();
void goToPacket(int packet, int hf_id = -1);
void goNextHistoryPacket();
void goPreviousHistoryPacket();
void markFrame();
void markAllDisplayedFrames(bool set);
void ignoreFrame();
void ignoreAllDisplayedFrames(bool set);
void setTimeReference();
void unsetAllTimeReferences();
void applyTimeShift();
void recolorPackets();
void redrawVisiblePackets();
void redrawVisiblePacketsDontSelectCurrent();
void columnsChanged();
void fieldsChanged(capture_file *cf);
void preferencesChanged();
void freezePacketList(bool changing_profile);
private slots:
void columnVisibilityTriggered();
void sectionResized(int col, int, int new_width);
void sectionMoved(int, int, int);
void updateRowHeights(const QModelIndex &ih_index);
void copySummary();
void vScrollBarActionTriggered(int);
void drawFarOverlay();
void drawNearOverlay();
void updatePackets(bool redraw);
void ctxDecodeAsDialog();
};
#endif // PACKET_LIST_H |
C++ | wireshark/ui/qt/packet_range_group_box.cpp | /* packet_range_group_box.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "packet_range_group_box.h"
#include <ui_packet_range_group_box.h>
#include <wsutil/ws_assert.h>
PacketRangeGroupBox::PacketRangeGroupBox(QWidget *parent) :
QGroupBox(parent),
pr_ui_(new Ui::PacketRangeGroupBox),
range_(NULL),
syntax_state_(SyntaxLineEdit::Empty)
{
pr_ui_->setupUi(this);
setFlat(true);
pr_ui_->displayedButton->setChecked(true);
pr_ui_->allButton->setChecked(true);
}
PacketRangeGroupBox::~PacketRangeGroupBox()
{
delete pr_ui_;
}
void PacketRangeGroupBox::initRange(packet_range_t *range, QString selRange) {
if (!range) return;
range_ = nullptr;
// Set this before setting range_ so that on_dependedCheckBox_toggled
// doesn't trigger an extra updateCounts().
// (We could instead manually connect and disconnect signals and slots
// after getting a range, instead of checking for range_ in all the
// slots.)
pr_ui_->dependedCheckBox->setChecked(range->include_dependents);
range_ = range;
if (range_->process_filtered) {
pr_ui_->displayedButton->setChecked(true);
} else {
pr_ui_->capturedButton->setChecked(true);
}
if (selRange.length() > 0)
packet_range_convert_selection_str(range_, selRange.toUtf8().constData());
if (range_->user_range) {
char* tmp_str = range_convert_range(NULL, range_->user_range);
pr_ui_->rangeLineEdit->setText(tmp_str);
wmem_free(NULL, tmp_str);
}
updateCounts();
}
bool PacketRangeGroupBox::isValid() {
if (pr_ui_->rangeButton->isChecked() && syntax_state_ != SyntaxLineEdit::Empty) {
return false;
}
return true;
}
void PacketRangeGroupBox::updateCounts() {
SyntaxLineEdit::SyntaxState orig_ss = syntax_state_;
bool displayed_checked = pr_ui_->displayedButton->isChecked();
bool can_select;
bool selected_packets;
int ignored_cnt = 0, displayed_ignored_cnt = 0;
int depended_cnt = 0, displayed_depended_cnt = 0;
int label_count;
if (!range_ || !range_->cf) return;
if (range_->displayed_cnt != 0) {
pr_ui_->displayedButton->setEnabled(true);
} else {
displayed_checked = false;
pr_ui_->capturedButton->setChecked(true);
pr_ui_->displayedButton->setEnabled(false);
}
// All / Captured
pr_ui_->allCapturedLabel->setEnabled(!displayed_checked);
label_count = range_->cf->count;
if (range_->remove_ignored) {
label_count -= range_->ignored_cnt;
}
pr_ui_->allCapturedLabel->setText(QString("%1").arg(label_count));
// All / Displayed
pr_ui_->allDisplayedLabel->setEnabled(displayed_checked);
if (range_->include_dependents) {
label_count = range_->displayed_plus_dependents_cnt;
} else {
label_count = range_->displayed_cnt;
}
if (range_->remove_ignored) {
label_count -= range_->displayed_ignored_cnt;
}
pr_ui_->allDisplayedLabel->setText(QString("%1").arg(label_count));
// Selected / Captured + Displayed
can_select = (range_->selection_range_cnt > 0 || range_->displayed_selection_range_cnt > 0);
if (can_select) {
pr_ui_->selectedButton->setEnabled(true);
pr_ui_->selectedCapturedLabel->setEnabled(!displayed_checked);
pr_ui_->selectedDisplayedLabel->setEnabled(displayed_checked);
if (range_->include_dependents) {
pr_ui_->selectedCapturedLabel->setText(QString::number(range_->selected_plus_depends_cnt));
pr_ui_->selectedDisplayedLabel->setText(QString::number(range_->displayed_selected_plus_depends_cnt));
} else {
pr_ui_->selectedCapturedLabel->setText(QString::number(range_->selection_range_cnt));
pr_ui_->selectedDisplayedLabel->setText(QString::number(range_->displayed_selection_range_cnt));
}
} else {
if (range_->process == range_process_selected) {
pr_ui_->allButton->setChecked(true);
}
pr_ui_->selectedButton->setEnabled(false);
pr_ui_->selectedCapturedLabel->setEnabled(false);
pr_ui_->selectedDisplayedLabel->setEnabled(false);
pr_ui_->selectedCapturedLabel->setText("0");
pr_ui_->selectedDisplayedLabel->setText("0");
}
// Marked / Captured + Displayed
if (displayed_checked) {
selected_packets = (range_->displayed_marked_cnt != 0);
} else {
selected_packets = (range_->cf->marked_count > 0);
}
if (selected_packets) {
pr_ui_->markedButton->setEnabled(true);
pr_ui_->markedCapturedLabel->setEnabled(!displayed_checked);
pr_ui_->markedDisplayedLabel->setEnabled(displayed_checked);
} else {
if (range_->process == range_process_marked) {
pr_ui_->allButton->setChecked(true);
}
pr_ui_->markedButton->setEnabled(false);
pr_ui_->markedCapturedLabel->setEnabled(false);
pr_ui_->markedDisplayedLabel->setEnabled(false);
}
if (range_->include_dependents) {
label_count = range_->marked_plus_depends_cnt;
} else {
label_count = range_->cf->marked_count;
}
if (range_->remove_ignored) {
label_count -= range_->ignored_marked_cnt;
}
pr_ui_->markedCapturedLabel->setText(QString("%1").arg(label_count));
if (range_->include_dependents) {
label_count = range_->displayed_marked_plus_depends_cnt;
} else {
label_count = range_->displayed_marked_cnt;
}
if (range_->remove_ignored) {
label_count -= range_->displayed_ignored_marked_cnt;
}
pr_ui_->markedDisplayedLabel->setText(QString("%1").arg(label_count));
// First to last marked / Captured + Displayed
if (displayed_checked) {
selected_packets = (range_->displayed_mark_range_cnt != 0);
} else {
selected_packets = (range_->mark_range_cnt != 0);
}
if (selected_packets) {
pr_ui_->ftlMarkedButton->setEnabled(true);
pr_ui_->ftlCapturedLabel->setEnabled(!displayed_checked);
pr_ui_->ftlDisplayedLabel->setEnabled(displayed_checked);
} else {
if (range_->process == range_process_marked_range) {
pr_ui_->allButton->setChecked(true);
}
pr_ui_->ftlMarkedButton->setEnabled(false);
pr_ui_->ftlCapturedLabel->setEnabled(false);
pr_ui_->ftlDisplayedLabel->setEnabled(false);
}
if (range_->include_dependents) {
label_count = range_->mark_range_plus_depends_cnt;
} else {
label_count = range_->mark_range_cnt;
}
if (range_->remove_ignored) {
label_count -= range_->ignored_mark_range_cnt;
}
pr_ui_->ftlCapturedLabel->setText(QString("%1").arg(label_count));
if (range_->include_dependents) {
label_count = range_->displayed_mark_range_plus_depends_cnt;
} else {
label_count = range_->displayed_mark_range_cnt;
}
if (range_->remove_ignored) {
label_count -= range_->displayed_ignored_mark_range_cnt;
}
pr_ui_->ftlDisplayedLabel->setText(QString("%1").arg(label_count));
// User specified / Captured + Displayed
pr_ui_->rangeButton->setEnabled(true);
pr_ui_->rangeCapturedLabel->setEnabled(!displayed_checked);
pr_ui_->rangeDisplayedLabel->setEnabled(displayed_checked);
packet_range_convert_str(range_, pr_ui_->rangeLineEdit->text().toUtf8().constData());
switch (packet_range_check(range_)) {
case CVT_NO_ERROR:
if (range_->include_dependents) {
label_count = range_->user_range_plus_depends_cnt;
} else {
label_count = range_->user_range_cnt;
}
if (range_->remove_ignored) {
label_count -= range_->ignored_user_range_cnt;
}
pr_ui_->rangeCapturedLabel->setText(QString("%1").arg(label_count));
if (range_->include_dependents) {
label_count = range_->displayed_user_range_plus_depends_cnt;
} else {
label_count = range_->displayed_user_range_cnt;
}
if (range_->remove_ignored) {
label_count -= range_->displayed_ignored_user_range_cnt;
}
pr_ui_->rangeDisplayedLabel->setText(QString("%1").arg(label_count));
syntax_state_ = SyntaxLineEdit::Empty;
break;
case CVT_SYNTAX_ERROR:
pr_ui_->rangeCapturedLabel->setText("<small><i>Bad range</i></small>");
pr_ui_->rangeDisplayedLabel->setText("-");
syntax_state_ = SyntaxLineEdit::Invalid;
break;
case CVT_NUMBER_TOO_BIG:
pr_ui_->rangeCapturedLabel->setText("<small><i>Number too large</i></small>");
pr_ui_->rangeDisplayedLabel->setText("-");
syntax_state_ = SyntaxLineEdit::Invalid;
break;
default:
ws_assert_not_reached();
return;
}
// Ignored
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();
}
if (displayed_checked)
selected_packets = (displayed_ignored_cnt != 0);
else
selected_packets = (ignored_cnt != 0);
if (selected_packets) {
pr_ui_->ignoredCheckBox->setEnabled(true);
pr_ui_->ignoredCapturedLabel->setEnabled(!displayed_checked);
pr_ui_->ignoredDisplayedLabel->setEnabled(displayed_checked);
} else {
pr_ui_->ignoredCheckBox->setEnabled(false);
pr_ui_->ignoredCapturedLabel->setEnabled(false);
pr_ui_->ignoredDisplayedLabel->setEnabled(false);
}
pr_ui_->ignoredCapturedLabel->setText(QString("%1").arg(ignored_cnt));
pr_ui_->ignoredDisplayedLabel->setText(QString("%1").arg(displayed_ignored_cnt));
// Depended upon / Displayed + Captured
switch(range_->process) {
case(range_process_all):
depended_cnt = 0;
displayed_depended_cnt = range_->displayed_plus_dependents_cnt - range_->displayed_cnt;
break;
case(range_process_selected):
depended_cnt = range_->selected_plus_depends_cnt - range_->selection_range_cnt;
displayed_depended_cnt = range_->displayed_selected_plus_depends_cnt - range_->displayed_selection_range_cnt;
break;
case(range_process_marked):
depended_cnt = range_->marked_plus_depends_cnt - range_->cf->marked_count;
displayed_depended_cnt = range_->displayed_marked_plus_depends_cnt - range_->displayed_marked_cnt;
break;
case(range_process_marked_range):
depended_cnt = range_->mark_range_plus_depends_cnt - range_->mark_range_cnt;
displayed_depended_cnt = range_->displayed_mark_range_plus_depends_cnt - range_->displayed_mark_range_cnt;
break;
case(range_process_user_range):
depended_cnt = range_->user_range_plus_depends_cnt - range_->user_range_cnt;
displayed_depended_cnt = range_->displayed_user_range_plus_depends_cnt - range_->displayed_user_range_cnt;
break;
default:
depended_cnt = 0;
displayed_depended_cnt = 0;
break;
}
if (displayed_checked) {
selected_packets = (displayed_depended_cnt != 0);
} else {
selected_packets = (depended_cnt != 0);
}
if (selected_packets) {
pr_ui_->dependedCheckBox->setEnabled(true);
pr_ui_->dependedCapturedLabel->setEnabled(!displayed_checked);
pr_ui_->dependedDisplayedLabel->setEnabled(displayed_checked);
} else {
pr_ui_->dependedCheckBox->setEnabled(false);
pr_ui_->dependedCapturedLabel->setEnabled(false);
pr_ui_->dependedDisplayedLabel->setEnabled(false);
}
pr_ui_->dependedCapturedLabel->setText(QString("%1").arg(depended_cnt));
pr_ui_->dependedDisplayedLabel->setText(QString("%1").arg(displayed_depended_cnt));
if (orig_ss != syntax_state_) {
pr_ui_->rangeLineEdit->setSyntaxState(syntax_state_);
emit validityChanged(isValid());
}
emit rangeChanged();
}
// Slots
void PacketRangeGroupBox::on_rangeLineEdit_textChanged(const QString &)
{
if (!pr_ui_->rangeButton->isChecked()) {
pr_ui_->rangeButton->setChecked(true);
} else {
updateCounts();
}
}
void PacketRangeGroupBox::processButtonToggled(bool checked, packet_range_e process) {
if (checked && range_) {
range_->process = process;
}
updateCounts();
}
void PacketRangeGroupBox::on_allButton_toggled(bool checked)
{
processButtonToggled(checked, range_process_all);
}
void PacketRangeGroupBox::on_selectedButton_toggled(bool checked)
{
processButtonToggled(checked, range_process_selected);
}
void PacketRangeGroupBox::on_markedButton_toggled(bool checked)
{
processButtonToggled(checked, range_process_marked);
}
void PacketRangeGroupBox::on_ftlMarkedButton_toggled(bool checked)
{
processButtonToggled(checked, range_process_marked_range);
}
void PacketRangeGroupBox::on_rangeButton_toggled(bool checked)
{
processButtonToggled(checked, range_process_user_range);
}
void PacketRangeGroupBox::on_capturedButton_toggled(bool checked)
{
if (checked) {
if (range_) range_->process_filtered = FALSE;
updateCounts();
}
}
void PacketRangeGroupBox::on_displayedButton_toggled(bool checked)
{
if (checked) {
if (range_) range_->process_filtered = TRUE;
updateCounts();
}
}
void PacketRangeGroupBox::on_ignoredCheckBox_toggled(bool checked)
{
if (range_) range_->remove_ignored = checked ? TRUE : FALSE;
updateCounts();
}
void PacketRangeGroupBox::on_dependedCheckBox_toggled(bool checked)
{
if (range_) {
range_->include_dependents = checked ? TRUE : FALSE;
updateCounts();
}
} |
C/C++ | wireshark/ui/qt/packet_range_group_box.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PACKET_RANGE_GROUP_BOX_H
#define PACKET_RANGE_GROUP_BOX_H
#include <config.h>
#include <glib.h>
#include <ui/packet_range.h>
#include <ui/qt/widgets/syntax_line_edit.h>
#include <QGroupBox>
namespace Ui {
class PacketRangeGroupBox;
}
/**
* UI element for controlling a range selection. The range provided in
* "initRange" is not owned by this class but will be modified.
*/
class PacketRangeGroupBox : public QGroupBox
{
Q_OBJECT
public:
explicit PacketRangeGroupBox(QWidget *parent = 0);
~PacketRangeGroupBox();
void initRange(packet_range_t *range, QString selRange = QString());
bool isValid();
signals:
void validityChanged(bool is_valid);
void rangeChanged();
private:
void updateCounts();
void processButtonToggled(bool checked, packet_range_e process);
Ui::PacketRangeGroupBox *pr_ui_;
packet_range_t *range_;
SyntaxLineEdit::SyntaxState syntax_state_;
private slots:
void on_rangeLineEdit_textChanged(const QString &range_str);
void on_allButton_toggled(bool checked);
void on_selectedButton_toggled(bool checked);
void on_markedButton_toggled(bool checked);
void on_ftlMarkedButton_toggled(bool checked);
void on_rangeButton_toggled(bool checked);
void on_capturedButton_toggled(bool checked);
void on_displayedButton_toggled(bool checked);
void on_ignoredCheckBox_toggled(bool checked);
void on_dependedCheckBox_toggled(bool checked);
};
#endif // PACKET_RANGE_GROUP_BOX_H |
User Interface | wireshark/ui/qt/packet_range_group_box.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>PacketRangeGroupBox</class>
<widget class="QGroupBox" name="PacketRangeGroupBox">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>454</width>
<height>241</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<property name="title">
<string>Packet Range</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="2" column="3">
<widget class="QLabel" name="selectedDisplayedLabel">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="0" column="3">
<widget class="QRadioButton" name="displayedButton">
<property name="text">
<string>Displayed</string>
</property>
<property name="checkable">
<bool>true</bool>
</property>
<attribute name="buttonGroup">
<string notr="true">capturedDisplayedButtonGroup</string>
</attribute>
</widget>
</item>
<item row="1" column="2">
<widget class="QLabel" name="allCapturedLabel">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="3" column="0" colspan="2">
<widget class="QRadioButton" name="markedButton">
<property name="text">
<string>&Marked packets only</string>
</property>
<attribute name="buttonGroup">
<string notr="true">packetSelectionButtonGroup</string>
</attribute>
</widget>
</item>
<item row="5" column="0">
<widget class="QRadioButton" name="rangeButton">
<property name="text">
<string>&Range:</string>
</property>
<attribute name="buttonGroup">
<string notr="true">packetSelectionButtonGroup</string>
</attribute>
</widget>
</item>
<item row="5" column="3">
<widget class="QLabel" name="rangeDisplayedLabel">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="7" column="0" colspan="2">
<widget class="QCheckBox" name="ignoredCheckBox">
<property name="text">
<string>Remove &ignored packets</string>
</property>
</widget>
</item>
<item row="8" column="0" colspan="2">
<widget class="QCheckBox" name="dependedCheckBox">
<property name="text">
<string>Include &depended upon packets</string>
</property>
<property name="toolTip">
<string>Also include packets depended upon, such as those used to reassemble displayed packets</string>
</property>
</widget>
</item>
<item row="3" column="3">
<widget class="QLabel" name="markedDisplayedLabel">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="4" column="0" colspan="2">
<widget class="QRadioButton" name="ftlMarkedButton">
<property name="text">
<string>First &to last marked</string>
</property>
<attribute name="buttonGroup">
<string notr="true">packetSelectionButtonGroup</string>
</attribute>
</widget>
</item>
<item row="2" column="2">
<widget class="QLabel" name="selectedCapturedLabel">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="1" column="0" colspan="2">
<widget class="QRadioButton" name="allButton">
<property name="text">
<string>&All packets</string>
</property>
<attribute name="buttonGroup">
<string notr="true">packetSelectionButtonGroup</string>
</attribute>
</widget>
</item>
<item row="4" column="2">
<widget class="QLabel" name="ftlCapturedLabel">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="1" column="3">
<widget class="QLabel" name="allDisplayedLabel">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="5" column="2">
<widget class="QLabel" name="rangeCapturedLabel">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="2" column="0" colspan="2">
<widget class="QRadioButton" name="selectedButton">
<property name="text">
<string>&Selected packets only</string>
</property>
<attribute name="buttonGroup">
<string notr="true">packetSelectionButtonGroup</string>
</attribute>
</widget>
</item>
<item row="0" column="2">
<widget class="QRadioButton" name="capturedButton">
<property name="text">
<string>Captured</string>
</property>
<property name="checkable">
<bool>true</bool>
</property>
<attribute name="buttonGroup">
<string notr="true">capturedDisplayedButtonGroup</string>
</attribute>
</widget>
</item>
<item row="3" column="2">
<widget class="QLabel" name="markedCapturedLabel">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="0" column="0">
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>63</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="5" column="1">
<widget class="SyntaxLineEdit" name="rangeLineEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item row="4" column="3">
<widget class="QLabel" name="ftlDisplayedLabel">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="7" column="2">
<widget class="QLabel" name="ignoredCapturedLabel">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="7" column="3">
<widget class="QLabel" name="ignoredDisplayedLabel">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="8" column="2">
<widget class="QLabel" name="dependedCapturedLabel">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="8" column="3">
<widget class="QLabel" name="dependedDisplayedLabel">
<property name="text">
<string>-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>SyntaxLineEdit</class>
<extends>QLineEdit</extends>
<header>widgets/syntax_line_edit.h</header>
</customwidget>
</customwidgets>
<connections/>
<buttongroups>
<buttongroup name="packetSelectionButtonGroup"/>
<buttongroup name="capturedDisplayedButtonGroup"/>
</buttongroups>
</ui> |
C++ | wireshark/ui/qt/preferences_dialog.cpp | /* preferences_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "preferences_dialog.h"
#include <ui_preferences_dialog.h>
#include "module_preferences_scroll_area.h"
#include <epan/prefs.h>
#include <epan/prefs-int.h>
#include <epan/decode_as.h>
#include <ui/language.h>
#include <ui/preference_utils.h>
#include <cfile.h>
#include <ui/commandline.h>
#include <ui/simple_dialog.h>
#include <ui/recent.h>
#include <main_window.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
extern "C" {
// Callbacks prefs routines
static guint
module_prefs_unstash(module_t *module, gpointer data)
{
gboolean *must_redissect_p = static_cast<gboolean *>(data);
pref_unstash_data_t unstashed_data;
unstashed_data.handle_decode_as = TRUE;
module->prefs_changed_flags = 0; /* assume none of them changed */
for (GList *pref_l = module->prefs; pref_l && pref_l->data; pref_l = gxx_list_next(pref_l)) {
pref_t *pref = gxx_list_data(pref_t *, pref_l);
if (prefs_get_type(pref) == PREF_OBSOLETE || prefs_get_type(pref) == PREF_STATIC_TEXT) continue;
unstashed_data.module = module;
pref_unstash(pref, &unstashed_data);
commandline_options_drop(module->name, prefs_get_name(pref));
}
/* If any of them changed, indicate that we must redissect and refilter
the current capture (if we have one), as the preference change
could cause packets to be dissected differently. */
*must_redissect_p |= module->prefs_changed_flags;
if (prefs_module_has_submodules(module))
return prefs_modules_foreach_submodules(module, module_prefs_unstash, data);
return 0; /* Keep unstashing. */
}
static guint
module_prefs_clean_stash(module_t *module, gpointer)
{
for (GList *pref_l = module->prefs; pref_l && pref_l->data; pref_l = gxx_list_next(pref_l)) {
pref_t *pref = gxx_list_data(pref_t *, pref_l);
if (prefs_get_type(pref) == PREF_OBSOLETE || prefs_get_type(pref) == PREF_STATIC_TEXT) continue;
pref_clean_stash(pref, Q_NULLPTR);
}
if (prefs_module_has_submodules(module))
return prefs_modules_foreach_submodules(module, module_prefs_clean_stash, Q_NULLPTR);
return 0; /* Keep cleaning modules */
}
} // extern "C"
// Preference tree items
const int APPEARANCE_ITEM = 0;
//placeholder key to keep dynamically loaded preferences
static const char* MODULES_NAME = "Modules";
PreferencesDialog::PreferencesDialog(QWidget *parent) :
GeometryStateDialog(parent),
pd_ui_(new Ui::PreferencesDialog),
model_(this),
advancedPrefsModel_(this),
advancedPrefsDelegate_(this),
modulePrefsModel_(this)
{
advancedPrefsModel_.setSourceModel(&model_);
modulePrefsModel_.setSourceModel(&model_);
saved_capture_no_extcap_ = prefs.capture_no_extcap;
// Some classes depend on pref_ptr_to_pref_ so this MUST be called after
// model_.populate().
pd_ui_->setupUi(this);
loadGeometry();
setWindowTitle(mainApp->windowTitleString(tr("Preferences")));
pd_ui_->advancedView->setModel(&advancedPrefsModel_);
pd_ui_->advancedView->setItemDelegate(&advancedPrefsDelegate_);
advancedPrefsModel_.setFirstColumnSpanned(pd_ui_->advancedView);
pd_ui_->prefsView->setModel(&modulePrefsModel_);
pd_ui_->splitter->setStretchFactor(0, 1);
pd_ui_->splitter->setStretchFactor(1, 5);
pd_ui_->prefsView->sortByColumn(ModulePrefsModel::colName, Qt::AscendingOrder);
//Set the Appearance leaf to expanded
pd_ui_->prefsView->setExpanded(modulePrefsModel_.index(APPEARANCE_ITEM, 0), true);
// PreferencesPane, prefsView, and stackedWidget must all correspond to each other.
prefs_pane_to_item_[PrefsModel::typeToString(PrefsModel::Appearance)] = pd_ui_->appearanceFrame;
prefs_pane_to_item_[PrefsModel::typeToString(PrefsModel::Layout)] = pd_ui_->layoutFrame;
prefs_pane_to_item_[PrefsModel::typeToString(PrefsModel::Columns)] = pd_ui_->columnFrame;
prefs_pane_to_item_[PrefsModel::typeToString(PrefsModel::FontAndColors)] = pd_ui_->fontandcolorFrame;
prefs_pane_to_item_[PrefsModel::typeToString(PrefsModel::Capture)] = pd_ui_->captureFrame;
prefs_pane_to_item_[PrefsModel::typeToString(PrefsModel::Expert)] = pd_ui_->expertFrame;
prefs_pane_to_item_[PrefsModel::typeToString(PrefsModel::FilterButtons)] = pd_ui_->filterExpressonsFrame;
prefs_pane_to_item_[PrefsModel::typeToString(PrefsModel::RSAKeys)] = pd_ui_->rsaKeysFrame;
prefs_pane_to_item_[PrefsModel::typeToString(PrefsModel::Advanced)] = pd_ui_->advancedFrame;
prefs_pane_to_item_[MODULES_NAME] = NULL;
pd_ui_->filterExpressonsFrame->setUat(uat_get_table_by_name("Display expressions"));
pd_ui_->expertFrame->setUat(uat_get_table_by_name("Expert Info Severity Level Configuration"));
connect(pd_ui_->prefsView, &PrefModuleTreeView::goToPane, this, &PreferencesDialog::selectPane);
/* Create a single-shot timer for debouncing calls to
* updateSearchLineEdit() */
searchLineEditTimer = new QTimer(this);
searchLineEditTimer->setSingleShot(true);
connect(searchLineEditTimer, &QTimer::timeout, this, &PreferencesDialog::updateSearchLineEdit);
}
PreferencesDialog::~PreferencesDialog()
{
delete pd_ui_;
delete searchLineEditTimer;
prefs_modules_foreach_submodules(NULL, module_prefs_clean_stash, NULL);
}
void PreferencesDialog::setPane(const QString module_name)
{
pd_ui_->prefsView->setPane(module_name);
}
void PreferencesDialog::showEvent(QShowEvent *)
{
QStyleOption style_opt;
int new_prefs_tree_width = pd_ui_->prefsView->style()->subElementRect(QStyle::SE_TreeViewDisclosureItem, &style_opt).left();
QList<int> sizes = pd_ui_->splitter->sizes();
#ifdef Q_OS_WIN
new_prefs_tree_width *= 2;
#endif
pd_ui_->prefsView->resizeColumnToContents(ModulePrefsModel::colName);
new_prefs_tree_width += pd_ui_->prefsView->columnWidth(ModulePrefsModel::colName);
pd_ui_->prefsView->setMinimumWidth(new_prefs_tree_width);
sizes[1] += sizes[0] - new_prefs_tree_width;
sizes[0] = new_prefs_tree_width;
pd_ui_->splitter->setSizes(sizes);
pd_ui_->splitter->setStretchFactor(0, 1);
pd_ui_->advancedView->expandAll();
pd_ui_->advancedView->setSortingEnabled(true);
pd_ui_->advancedView->sortByColumn(AdvancedPrefsModel::colName, Qt::AscendingOrder);
int one_em = fontMetrics().height();
pd_ui_->advancedView->setColumnWidth(AdvancedPrefsModel::colName, one_em * 12); // Don't let long items widen things too much
pd_ui_->advancedView->resizeColumnToContents(AdvancedPrefsModel::colStatus);
pd_ui_->advancedView->resizeColumnToContents(AdvancedPrefsModel::colType);
pd_ui_->advancedView->setColumnWidth(AdvancedPrefsModel::colValue, one_em * 30);
}
void PreferencesDialog::selectPane(QString pane)
{
if (prefs_pane_to_item_.contains(pane)) {
pd_ui_->stackedWidget->setCurrentWidget(prefs_pane_to_item_[pane]);
} else {
//If not found in prefs_pane_to_item_, it must be an individual module
module_t* module = prefs_find_module(pane.toStdString().c_str());
if (module != NULL) {
QWidget* moduleWindow = prefs_pane_to_item_[MODULES_NAME];
if (moduleWindow != NULL) {
pd_ui_->stackedWidget->removeWidget(moduleWindow);
delete moduleWindow;
}
moduleWindow = new ModulePreferencesScrollArea(module);
prefs_pane_to_item_[MODULES_NAME] = moduleWindow;
pd_ui_->stackedWidget->addWidget(moduleWindow);
pd_ui_->stackedWidget->setCurrentWidget(moduleWindow);
}
}
}
void PreferencesDialog::updateSearchLineEdit()
{
advancedPrefsModel_.setFilter(searchLineEditText);
/* If items are filtered out, then filtered back in, the tree remains collapsed
Force an expansion */
pd_ui_->advancedView->expandAll();
}
void PreferencesDialog::on_advancedSearchLineEdit_textEdited(const QString &text)
{
/* As running pd_ui_->advancedView->expandAll() takes a noticeable amount
* of time and so would introduce significant lag while typing a string
* into the Search box, we instead debounce the call to
* updateSearchLineEdit(), so that it doesn't run until a set amount of
* time has elapsed with no updates to the Search field.
*
* If the user types something before the timer elapses, the timer restarts
* the countdown.
*/
searchLineEditText = text;
guint gui_debounce_timer = prefs_get_uint_value("gui", "debounce.timer");
searchLineEditTimer->start(gui_debounce_timer);
}
void PreferencesDialog::on_buttonBox_accepted()
{
gchar* err = NULL;
unsigned int redissect_flags = 0;
// XXX - We should validate preferences as the user changes them, not here.
// XXX - We're also too enthusiastic about setting must_redissect.
prefs_modules_foreach_submodules(NULL, module_prefs_unstash, (gpointer)&redissect_flags);
if (redissect_flags & PREF_EFFECT_GUI_LAYOUT) {
// Layout type changed, reset sizes
recent.gui_geometry_main_upper_pane = 0;
recent.gui_geometry_main_lower_pane = 0;
}
pd_ui_->columnFrame->unstash();
pd_ui_->filterExpressonsFrame->acceptChanges();
pd_ui_->expertFrame->acceptChanges();
#ifdef HAVE_LIBGNUTLS
pd_ui_->rsaKeysFrame->acceptChanges();
#endif
//Filter expressions don't affect dissection, so there is no need to
//send any events to that effect. However, the app needs to know
//about any button changes.
mainApp->emitAppSignal(MainApplication::FilterExpressionsChanged);
prefs_main_write();
if (save_decode_as_entries(&err) < 0)
{
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err);
g_free(err);
}
write_language_prefs();
mainApp->loadLanguage(QString(language));
#ifdef HAVE_AIRPCAP
/*
* Load the Wireshark decryption keys (just set) and save
* the changes to the adapters' registry
*/
//airpcap_load_decryption_keys(airpcap_if_list);
#endif
// gtk/prefs_dlg.c:prefs_main_apply_all
/*
* Apply the protocol preferences first - "gui_prefs_apply()" could
* cause redissection, and we have to make sure the protocol
* preference changes have been fully applied.
*/
prefs_apply_all();
/* Fill in capture options with values from the preferences */
prefs_to_capture_opts();
#ifdef HAVE_AIRPCAP
// prefs_airpcap_update();
#endif
mainApp->setMonospaceFont(prefs.gui_font_name);
if (redissect_flags & PREF_EFFECT_FIELDS) {
mainApp->queueAppSignal(MainApplication::FieldsChanged);
}
if (redissect_flags & PREF_EFFECT_DISSECTION) {
// Freeze the packet list early to avoid updating column data before doing a
// full redissection. The packet list will be thawed when redissection is done.
mainApp->queueAppSignal(MainApplication::FreezePacketList);
/* Redissect all the packets, and re-evaluate the display filter. */
mainApp->queueAppSignal(MainApplication::PacketDissectionChanged);
}
mainApp->queueAppSignal(MainApplication::PreferencesChanged);
if (redissect_flags & PREF_EFFECT_GUI_LAYOUT) {
mainApp->queueAppSignal(MainApplication::RecentPreferencesRead);
}
if (prefs.capture_no_extcap != saved_capture_no_extcap_)
mainApp->refreshLocalInterfaces();
}
void PreferencesDialog::on_buttonBox_rejected()
{
//handle frames that don't have their own OK/Cancel "buttons"
pd_ui_->filterExpressonsFrame->rejectChanges();
pd_ui_->expertFrame->rejectChanges();
#ifdef HAVE_LIBGNUTLS
pd_ui_->rsaKeysFrame->rejectChanges();
#endif
}
void PreferencesDialog::on_buttonBox_helpRequested()
{
mainApp->helpTopicAction(HELP_PREFERENCES_DIALOG);
} |
C/C++ | wireshark/ui/qt/preferences_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 PREFERENCES_DIALOG_H
#define PREFERENCES_DIALOG_H
#include <config.h>
#include <epan/prefs.h>
#include <ui/qt/models/pref_models.h>
#include <ui/qt/models/pref_delegate.h>
#include "geometry_state_dialog.h"
class QComboBox;
namespace Ui {
class PreferencesDialog;
}
class PreferencesDialog : public GeometryStateDialog
{
Q_OBJECT
public:
explicit PreferencesDialog(QWidget *parent = 0);
~PreferencesDialog();
/**
* Show the preference pane corresponding to the a preference module name.
* @param module_name A preference module name, e.g. the "name" parameter passed
* to prefs_register_module or a protocol name.
*/
void setPane(const QString module_name);
protected:
void showEvent(QShowEvent *evt);
private:
Ui::PreferencesDialog *pd_ui_;
QHash<QString, QWidget*> prefs_pane_to_item_;
PrefsModel model_;
AdvancedPrefsModel advancedPrefsModel_;
AdvancedPrefDelegate advancedPrefsDelegate_;
ModulePrefsModel modulePrefsModel_;
gboolean saved_capture_no_extcap_;
QTimer *searchLineEditTimer;
QString searchLineEditText;
private slots:
void selectPane(QString pane);
void on_advancedSearchLineEdit_textEdited(const QString &search_re);
void on_buttonBox_accepted();
void on_buttonBox_rejected();
void on_buttonBox_helpRequested();
/**
* Update search results from the advancedSearchLineEdit field
*
* This is performed separately from on_advancedSearchLineEdit_textEdited
* to support debouncing.
*/
void updateSearchLineEdit();
};
#endif // PREFERENCES_DIALOG_H |
User Interface | wireshark/ui/qt/preferences_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>PreferencesDialog</class>
<widget class="QDialog" name="PreferencesDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>680</width>
<height>475</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<widget class="PrefModuleTreeView" name="prefsView">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="uniformRowHeights">
<bool>true</bool>
</property>
<property name="headerHidden">
<bool>true</bool>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
</widget>
<widget class="QStackedWidget" name="stackedWidget">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="currentIndex">
<number>6</number>
</property>
<widget class="MainWindowPreferencesFrame" name="appearanceFrame"/>
<widget class="LayoutPreferencesFrame" name="layoutFrame"/>
<widget class="ColumnPreferencesFrame" name="columnFrame"/>
<widget class="FontColorPreferencesFrame" name="fontandcolorFrame"/>
<widget class="CapturePreferencesFrame" name="captureFrame"/>
<widget class="UatFrame" name="expertFrame"/>
<widget class="UatFrame" name="filterExpressonsFrame"/>
<widget class="RsaKeysFrame" name="rsaKeysFrame"/>
<widget class="QFrame" name="advancedFrame">
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Search:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="advancedSearchLineEdit"/>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="QTreeView" name="advancedView">
<property name="indentation">
<number>0</number>
</property>
<property name="uniformRowHeights">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Help|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>MainWindowPreferencesFrame</class>
<extends>QFrame</extends>
<header>main_window_preferences_frame.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>LayoutPreferencesFrame</class>
<extends>QFrame</extends>
<header>layout_preferences_frame.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>ColumnPreferencesFrame</class>
<extends>QFrame</extends>
<header>column_preferences_frame.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>FontColorPreferencesFrame</class>
<extends>QFrame</extends>
<header>font_color_preferences_frame.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>CapturePreferencesFrame</class>
<extends>QFrame</extends>
<header>capture_preferences_frame.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>UatFrame</class>
<extends>QFrame</extends>
<header>uat_frame.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>PrefModuleTreeView</class>
<extends>QTreeView</extends>
<header>widgets/pref_module_view.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>RsaKeysFrame</class>
<extends>QFrame</extends>
<header>rsa_keys_frame.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>PreferencesDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>PreferencesDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/preference_editor_frame.cpp | /* preference_editor_frame.h
*
* 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/prefs-int.h>
#include <epan/decode_as.h>
#include <ui/preference_utils.h>
#include <ui/simple_dialog.h>
#include "preference_editor_frame.h"
#include <ui_preference_editor_frame.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/widgets/wireshark_file_dialog.h>
#include <wsutil/utf8_entities.h>
#include "main_application.h"
#include <QPushButton>
#include <QKeyEvent>
#include <QRegularExpression>
PreferenceEditorFrame::PreferenceEditorFrame(QWidget *parent) :
AccordionFrame(parent),
ui(new Ui::PreferenceEditorFrame),
module_(NULL),
pref_(NULL),
new_uint_(0),
new_str_(""),
new_range_(NULL)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
foreach (QWidget *w, findChildren<QWidget *>()) {
w->setAttribute(Qt::WA_MacSmallSize, true);
}
#endif
connect(ui->preferenceBrowseButton, &QPushButton::clicked, this, &PreferenceEditorFrame::browsePushButtonClicked);
}
PreferenceEditorFrame::~PreferenceEditorFrame()
{
delete ui;
}
void PreferenceEditorFrame::editPreference(preference *pref, pref_module *module)
{
pref_ = pref;
module_ = module;
if (!pref || !module) {
hide();
return;
}
ui->modulePreferencesToolButton->setText(tr("Open %1 preferences…").arg(module_->title));
pref_stash(pref_, NULL);
ui->preferenceTitleLabel->setText(QString("%1:").arg(prefs_get_title(pref)));
// Convert the pref description from plain text to rich text.
QString description = html_escape(prefs_get_description(pref));
description.replace('\n', "<br>");
QString tooltip = QString("<span>%1</span>").arg(description);
ui->preferenceTitleLabel->setToolTip(tooltip);
ui->preferenceLineEdit->setToolTip(tooltip);
ui->preferenceLineEdit->clear();
ui->preferenceLineEdit->setSyntaxState(SyntaxLineEdit::Empty);
disconnect(ui->preferenceLineEdit, 0, 0, 0);
bool show = false;
bool browse_button = false;
switch (prefs_get_type(pref_)) {
case PREF_UINT:
case PREF_DECODE_AS_UINT:
connect(ui->preferenceLineEdit, &SyntaxLineEdit::textChanged,
this, &PreferenceEditorFrame::uintLineEditTextEdited);
show = true;
break;
case PREF_SAVE_FILENAME:
case PREF_OPEN_FILENAME:
case PREF_DIRNAME:
browse_button = true;
// Fallthrough
case PREF_STRING:
case PREF_PASSWORD:
connect(ui->preferenceLineEdit, &SyntaxLineEdit::textChanged,
this, &PreferenceEditorFrame::stringLineEditTextEdited);
show = true;
break;
case PREF_RANGE:
case PREF_DECODE_AS_RANGE:
connect(ui->preferenceLineEdit, &SyntaxLineEdit::textChanged,
this, &PreferenceEditorFrame::rangeLineEditTextEdited);
show = true;
break;
default:
break;
}
if (show) {
ui->preferenceLineEdit->setText(gchar_free_to_qstring(prefs_pref_to_str(pref_, pref_stashed)).remove(QRegularExpression("\n\t")));
ui->preferenceBrowseButton->setHidden(!browse_button);
animatedShow();
}
}
void PreferenceEditorFrame::uintLineEditTextEdited(const QString &new_str)
{
if (new_str.isEmpty()) {
new_uint_ = prefs_get_uint_value_real(pref_, pref_stashed);
ui->preferenceLineEdit->setSyntaxState(SyntaxLineEdit::Empty);
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
return;
}
bool ok;
uint new_uint = new_str.toUInt(&ok, 0);
if (ok) {
new_uint_ = new_uint;
ui->preferenceLineEdit->setSyntaxState(SyntaxLineEdit::Valid);
} else {
new_uint_ = prefs_get_uint_value_real(pref_, pref_stashed);
ui->preferenceLineEdit->setSyntaxState(SyntaxLineEdit::Invalid);
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ok);
}
void PreferenceEditorFrame::stringLineEditTextEdited(const QString &new_str)
{
new_str_ = new_str;
}
void PreferenceEditorFrame::browsePushButtonClicked()
{
QString caption = mainApp->windowTitleString(prefs_get_title(pref_));
QString dir = prefs_get_string_value(pref_, pref_stashed);
QString filename;
switch (prefs_get_type(pref_)) {
case PREF_SAVE_FILENAME:
filename = WiresharkFileDialog::getSaveFileName(this, caption, dir);
break;
case PREF_OPEN_FILENAME:
filename = WiresharkFileDialog::getOpenFileName(this, caption, dir);
break;
case PREF_DIRNAME:
filename = WiresharkFileDialog::getExistingDirectory(this, caption, dir);
break;
}
if (!filename.isEmpty()) {
ui->preferenceLineEdit->setText(filename);
}
}
void PreferenceEditorFrame::rangeLineEditTextEdited(const QString &new_str)
{
range_t *new_range = NULL;
convert_ret_t ret = range_convert_str(NULL, &new_range, new_str.toUtf8().constData(), prefs_get_max_value(pref_));
wmem_free(NULL, new_range_);
new_range_ = new_range;
if (ret == CVT_NO_ERROR) {
if (new_str.isEmpty()) {
ui->preferenceLineEdit->setSyntaxState(SyntaxLineEdit::Empty);
} else {
ui->preferenceLineEdit->setSyntaxState(SyntaxLineEdit::Valid);
}
} else {
ui->preferenceLineEdit->setSyntaxState(SyntaxLineEdit::Invalid);
}
}
void PreferenceEditorFrame::showEvent(QShowEvent *event)
{
ui->preferenceLineEdit->setFocus();
ui->preferenceLineEdit->selectAll();
AccordionFrame::showEvent(event);
}
void PreferenceEditorFrame::on_modulePreferencesToolButton_clicked()
{
if (module_) {
emit showProtocolPreferences(module_->name);
}
on_buttonBox_rejected();
}
void PreferenceEditorFrame::on_preferenceLineEdit_returnPressed()
{
if (ui->buttonBox->button(QDialogButtonBox::Ok)->isEnabled()) {
on_buttonBox_accepted();
}
}
void PreferenceEditorFrame::on_buttonBox_accepted()
{
unsigned int changed_flags = 0;
unsigned int apply = 0;
switch(prefs_get_type(pref_)) {
case PREF_UINT:
case PREF_DECODE_AS_UINT:
apply = prefs_set_uint_value(pref_, new_uint_, pref_stashed);
break;
case PREF_STRING:
case PREF_SAVE_FILENAME:
case PREF_OPEN_FILENAME:
case PREF_DIRNAME:
apply = prefs_set_string_value(pref_, new_str_.toStdString().c_str(), pref_stashed);
break;
case PREF_PASSWORD:
apply = prefs_set_password_value(pref_, new_str_.toStdString().c_str(), pref_stashed);
break;
case PREF_RANGE:
case PREF_DECODE_AS_RANGE:
apply = prefs_set_range_value(pref_, new_range_, pref_stashed);
break;
default:
break;
}
if (apply && module_) {
changed_flags = module_->prefs_changed_flags;
pref_unstash_data_t unstashed_data;
unstashed_data.module = module_;
unstashed_data.handle_decode_as = TRUE;
pref_unstash(pref_, &unstashed_data);
prefs_apply(module_);
prefs_main_write();
gchar* err = NULL;
if (save_decode_as_entries(&err) < 0)
{
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err);
g_free(err);
}
}
on_buttonBox_rejected();
// Emit signals once UI is hidden
if (apply) {
if (changed_flags & PREF_EFFECT_FIELDS) {
mainApp->emitAppSignal(MainApplication::FieldsChanged);
}
mainApp->emitAppSignal(MainApplication::PacketDissectionChanged);
mainApp->emitAppSignal(MainApplication::PreferencesChanged);
}
}
void PreferenceEditorFrame::on_buttonBox_rejected()
{
pref_ = NULL;
module_ = NULL;
wmem_free(NULL, new_range_);
new_range_ = NULL;
animatedHide();
}
void PreferenceEditorFrame::keyPressEvent(QKeyEvent *event)
{
if (event->modifiers() == Qt::NoModifier) {
if (event->key() == Qt::Key_Escape) {
on_buttonBox_rejected();
} else if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
if (ui->buttonBox->button(QDialogButtonBox::Ok)->isEnabled()) {
on_buttonBox_accepted();
} else if (ui->preferenceLineEdit->syntaxState() == SyntaxLineEdit::Invalid) {
mainApp->pushStatus(MainApplication::FilterSyntax, tr("Invalid value."));
}
}
}
AccordionFrame::keyPressEvent(event);
} |
C/C++ | wireshark/ui/qt/preference_editor_frame.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PREFERENCE_EDITOR_FRAME_H
#define PREFERENCE_EDITOR_FRAME_H
#include "accordion_frame.h"
struct pref_module;
struct preference;
struct epan_range;
namespace Ui {
class PreferenceEditorFrame;
}
class PreferenceEditorFrame : public AccordionFrame
{
Q_OBJECT
public:
explicit PreferenceEditorFrame(QWidget *parent = 0);
~PreferenceEditorFrame();
public slots:
void editPreference(struct preference *pref = NULL, struct pref_module *module = NULL);
signals:
void showProtocolPreferences(const QString module_name);
protected:
virtual void showEvent(QShowEvent *event);
virtual void keyPressEvent(QKeyEvent *event);
private slots:
// Similar to ModulePreferencesScrollArea
void uintLineEditTextEdited(const QString &new_str);
void stringLineEditTextEdited(const QString &new_str);
void rangeLineEditTextEdited(const QString &new_str);
void browsePushButtonClicked();
void on_modulePreferencesToolButton_clicked();
void on_preferenceLineEdit_returnPressed();
void on_buttonBox_accepted();
void on_buttonBox_rejected();
private:
Ui::PreferenceEditorFrame *ui;
struct pref_module *module_;
struct preference *pref_;
unsigned int new_uint_;
QString new_str_;
struct epan_range *new_range_;
};
#endif // PREFERENCE_EDITOR_FRAME_H |
User Interface | wireshark/ui/qt/preference_editor_frame.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>PreferenceEditorFrame</class>
<widget class="AccordionFrame" name="PreferenceEditorFrame">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>458</width>
<height>34</height>
</rect>
</property>
<property name="windowTitle">
<string>Frame</string>
</property>
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Plain</enum>
</property>
<layout class="QHBoxLayout" name="horizontalLayout" stretch="0,1,0,0,0,0">
<property name="topMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QToolButton" name="modulePreferencesToolButton">
<property name="text">
<string>…</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>81</width>
<height>5</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="preferenceTitleLabel">
<property name="text">
<string>a preference</string>
</property>
</widget>
</item>
<item>
<widget class="SyntaxLineEdit" name="preferenceLineEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="preferenceBrowseButton">
<property name="text">
<string>Browse…</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>13</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>27</height>
</size>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>AccordionFrame</class>
<extends>QFrame</extends>
<header>accordion_frame.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>SyntaxLineEdit</class>
<extends>QLineEdit</extends>
<header>widgets/syntax_line_edit.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui> |
C++ | wireshark/ui/qt/print_dialog.cpp | /* print_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "print_dialog.h"
#include <ui_print_dialog.h>
#include <wsutil/utf8_entities.h>
#ifdef Q_OS_WIN
#include <windows.h>
#include "ui/packet_range.h"
#include "ui/win32/file_dlg_win32.h"
#endif
#include <QPrintDialog>
#include <QPageSetupDialog>
#include <QPainter>
#include <QPaintEngine>
#include <QKeyEvent>
#include <QMessageBox>
#include "main_application.h"
extern "C" {
// Page element callbacks
static gboolean
print_preamble_pd(print_stream_t *self, gchar *, const char *)
{
if (!self) return FALSE;
PrintDialog *print_dlg = static_cast<PrintDialog *>(self->data);
if (!print_dlg) return FALSE;
return print_dlg->printHeader();
}
static gboolean
print_line_pd(print_stream_t *self, int indent, const char *line)
{
if (!self) return FALSE;
PrintDialog *print_dlg = static_cast<PrintDialog *>(self->data);
if (!print_dlg) return FALSE;
return print_dlg->printLine(indent, line);
}
static gboolean
new_page_pd(print_stream_t *self)
{
if (!self) return FALSE;
PrintDialog *print_dlg = static_cast<PrintDialog *>(self->data);
if (!print_dlg) return FALSE;
return print_dlg->printHeader();
}
} // extern "C"
PrintDialog::PrintDialog(QWidget *parent, capture_file *cf, QString selRange) :
QDialog(parent),
pd_ui_(new Ui::PrintDialog),
cur_printer_(NULL),
cur_painter_(NULL),
preview_(new QPrintPreviewWidget(&printer_)),
print_bt_(new QPushButton(tr("&Print…"))),
cap_file_(cf),
page_pos_(0),
in_preview_(FALSE)
{
Q_ASSERT(cf);
pd_ui_->setupUi(this);
setWindowTitle(mainApp->windowTitleString(tr("Print")));
pd_ui_->previewLayout->insertWidget(0, preview_, Qt::AlignTop);
preview_->setMinimumWidth(preview_->height() / 2);
preview_->setToolTip(pd_ui_->zoomLabel->toolTip());
// XXX Make these configurable
header_font_.setFamily("Times");
header_font_.setPointSizeF(header_font_.pointSizeF() * 0.8);
packet_font_ = mainApp->monospaceFont();
packet_font_.setPointSizeF(packet_font_.pointSizeF() * 0.8);
memset(&print_args_, 0, sizeof(print_args_));
memset(&stream_ops_, 0, sizeof(stream_ops_));
/* Init the export range */
packet_range_init(&print_args_.range, cap_file_);
/* Default to displayed packets */
print_args_.range.process_filtered = TRUE;
stream_ops_.print_preamble = print_preamble_pd;
stream_ops_.print_line = print_line_pd;
stream_ops_.new_page = new_page_pd;
stream_.data = this;
stream_.ops = &stream_ops_;
print_args_.stream = &stream_;
gchar *display_basename = g_filename_display_basename(cap_file_->filename);
printer_.setDocName(display_basename);
g_free(display_basename);
pd_ui_->rangeGroupBox->initRange(&print_args_.range, selRange);
pd_ui_->buttonBox->addButton(print_bt_, QDialogButtonBox::ActionRole);
pd_ui_->buttonBox->addButton(tr("Page &Setup…"), QDialogButtonBox::ResetRole);
print_bt_->setDefault(true);
connect(preview_, SIGNAL(paintRequested(QPrinter*)), this, SLOT(paintPreview(QPrinter*)));
connect(pd_ui_->rangeGroupBox, SIGNAL(rangeChanged()),
this, SLOT(checkValidity()));
connect(pd_ui_->formatGroupBox, SIGNAL(formatChanged()),
this, SLOT(checkValidity()));
connect(pd_ui_->formFeedCheckBox, SIGNAL(toggled(bool)),
preview_, SLOT(updatePreview()));
connect(pd_ui_->bannerCheckBox, SIGNAL(toggled(bool)),
preview_, SLOT(updatePreview()));
checkValidity();
}
PrintDialog::~PrintDialog()
{
packet_range_cleanup(&print_args_.range);
delete pd_ui_;
}
gboolean PrintDialog::printHeader()
{
if (!cap_file_ || !cap_file_->filename || !cur_printer_ || !cur_painter_) return FALSE;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
int page_top = cur_printer_->pageLayout().paintRectPixels(cur_printer_->resolution()).top();
#else
int page_top = cur_printer_->pageRect().top();
#endif
if (page_pos_ > page_top) {
if (in_preview_) {
// When generating a preview, only generate the first page;
// if we're past the first page, stop the printing process.
return FALSE;
}
// Second and subsequent pages only
cur_printer_->newPage();
page_pos_ = page_top;
}
if (pd_ui_->bannerCheckBox->isChecked()) {
QString banner = QString(tr("%1 %2 total packets, %3 shown"))
.arg(cap_file_->filename)
.arg(cap_file_->count)
.arg(cap_file_->displayed_count);
cur_painter_->setFont(header_font_);
cur_painter_->drawText(0, page_top, banner);
}
page_pos_ += cur_painter_->fontMetrics().height();
cur_painter_->setFont(packet_font_);
return TRUE;
}
gboolean PrintDialog::printLine(int indent, const char *line)
{
QRect out_rect, page_rect;
QString out_line;
if (!line || !cur_printer_ || !cur_painter_) return FALSE;
/* Prepare the tabs for printing, depending on tree level */
out_line.fill(' ', indent * 4);
out_line += line;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
page_rect = cur_printer_->pageLayout().paintRectPixels(cur_printer_->resolution());
#else
page_rect = cur_printer_->pageRect();
#endif
out_rect = cur_painter_->boundingRect(page_rect, Qt::TextWordWrap, out_line);
if (page_rect.height() < page_pos_ + out_rect.height()) {
//
// We're past the end of the page, so this line will be on
// the next page.
//
if (in_preview_) {
// When generating a preview, only generate the first page;
// if we're past the first page, stop the printing process.
return FALSE;
}
if (*line == '\0') {
// This is an empty line, so it's a separator; no need to
// waste space printing it at the top of a page, as the
// page break suffices as a separator.
return TRUE;
}
printHeader();
}
out_rect.translate(0, page_pos_);
cur_painter_->drawText(out_rect, Qt::TextWordWrap, out_line);
page_pos_ += out_rect.height();
return TRUE;
}
// Protected
void PrintDialog::keyPressEvent(QKeyEvent *event)
{
// XXX - This differs from the main window but matches other applications (e.g. Mozilla and Safari)
switch(event->key()) {
case Qt::Key_Minus:
case Qt::Key_Underscore: // Shifted minus on U.S. keyboards
preview_->zoomOut();
break;
case Qt::Key_Plus:
case Qt::Key_Equal: // Unshifted plus on U.S. keyboards
preview_->zoomIn();
break;
case Qt::Key_0:
case Qt::Key_ParenRight: // Shifted 0 on U.S. keyboards
// fitInView doesn't grow (at least in Qt 4.8.2) so make sure it shrinks.
preview_->setUpdatesEnabled(false);
preview_->setZoomFactor(1.0);
preview_->fitInView();
preview_->setUpdatesEnabled(true);
break;
}
QDialog::keyPressEvent(event);
}
// Private
void PrintDialog::printPackets(QPrinter *printer, bool in_preview)
{
QPainter painter;
if (!printer) return;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
page_pos_ = printer->pageLayout().paintRectPixels(printer->resolution()).top();
#else
page_pos_ = printer->pageRect().top();
#endif
in_preview_ = in_preview;
/* Fill in our print args */
print_args_.format = PR_FMT_TEXT;
print_args_.print_summary = pd_ui_->formatGroupBox->summaryEnabled();
print_args_.print_col_headings = pd_ui_->formatGroupBox->includeColumnHeadingsEnabled();
print_args_.print_hex = pd_ui_->formatGroupBox->bytesEnabled();
print_args_.hexdump_options = pd_ui_->formatGroupBox->getHexdumpOptions();
print_args_.print_formfeed = pd_ui_->formFeedCheckBox->isChecked();
print_args_.print_dissections = print_dissections_none;
if (pd_ui_->formatGroupBox->detailsEnabled()) {
if (pd_ui_->formatGroupBox->allCollapsedEnabled())
print_args_.print_dissections = print_dissections_collapsed;
else if (pd_ui_->formatGroupBox->asDisplayedEnabled())
print_args_.print_dissections = print_dissections_as_displayed;
else if (pd_ui_->formatGroupBox->allExpandedEnabled())
print_args_.print_dissections = print_dissections_expanded;
}
// This should be identical to printer_. However, the QPrintPreviewWidget docs
// tell us to draw on the printer handed to us by the paintRequested() signal.
cur_printer_ = printer;
cur_painter_ = &painter;
if (!painter.begin(printer)) {
QMessageBox::warning(this, tr("Print Error"),
QString(tr("Unable to print to %1.")).arg(printer_.printerName()),
QMessageBox::Ok);
close();
}
// Don't show a progress bar if we're previewing; if it takes a
// significant amount of time to generate a preview of the first
// page, We Have A Real Problem
cf_print_packets(cap_file_, &print_args_, in_preview ? FALSE : TRUE);
cur_printer_ = NULL;
cur_painter_ = NULL;
painter.end();
}
void PrintDialog::paintPreview(QPrinter *printer)
{
printPackets(printer, true);
}
void PrintDialog::checkValidity()
{
bool enable = true;
if (!pd_ui_->rangeGroupBox->isValid()) enable = false;
if (!pd_ui_->formatGroupBox->summaryEnabled() &&
!pd_ui_->formatGroupBox->detailsEnabled() &&
!pd_ui_->formatGroupBox->bytesEnabled())
{
enable = false;
}
print_bt_->setEnabled(enable);
preview_->updatePreview();
}
void PrintDialog::on_buttonBox_helpRequested()
{
mainApp->helpTopicAction(HELP_PRINT_DIALOG);
}
void PrintDialog::on_buttonBox_clicked(QAbstractButton *button)
{
QPrintDialog *print_dlg;
QPageSetupDialog *ps_dlg;
#ifdef Q_OS_WIN
HANDLE da_ctx;
#endif
switch (pd_ui_->buttonBox->buttonRole(button)) {
case QDialogButtonBox::ActionRole:
int result;
#ifdef Q_OS_WIN
da_ctx = set_thread_per_monitor_v2_awareness();
#endif
print_dlg = new QPrintDialog(&printer_, this);
result = print_dlg->exec();
#ifdef Q_OS_WIN
revert_thread_per_monitor_v2_awareness(da_ctx);
#endif
if (result == QDialog::Accepted) {
printPackets(&printer_, false);
done(result);
}
break;
case QDialogButtonBox::ResetRole:
#ifdef Q_OS_WIN
da_ctx = set_thread_per_monitor_v2_awareness();
#endif
ps_dlg = new QPageSetupDialog(&printer_, this);
ps_dlg->exec();
#ifdef Q_OS_WIN
revert_thread_per_monitor_v2_awareness(da_ctx);
#endif
preview_->updatePreview();
break;
default: // Help, Cancel
break;
}
} |
C/C++ | wireshark/ui/qt/print_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 PRINT_DIALOG_H
#define PRINT_DIALOG_H
#include <config.h>
#include <glib.h>
#include "file.h"
#include <QDialog>
#include <QPrinter>
#include <QPrintPreviewWidget>
#include <QPushButton>
namespace Ui {
class PrintDialog;
}
class PrintDialog : public QDialog
{
Q_OBJECT
public:
explicit PrintDialog(QWidget *parent = 0, capture_file *cf = NULL, QString selRange = QString());
~PrintDialog();
gboolean printHeader();
gboolean printLine(int indent, const char *line);
protected:
virtual void keyPressEvent(QKeyEvent *event) override;
private:
Ui::PrintDialog *pd_ui_;
QPrinter printer_;
QPrinter *cur_printer_;
QPainter *cur_painter_;
QPrintPreviewWidget *preview_;
QPushButton *print_bt_;
QFont header_font_;
QFont packet_font_;
public:
capture_file *cap_file_;
private:
print_args_t print_args_;
print_stream_ops_t stream_ops_;
print_stream_t stream_;
int page_pos_;
bool in_preview_;
void printPackets(QPrinter *printer = NULL, bool in_preview = false);
private slots:
void paintPreview(QPrinter *printer);
void checkValidity();
void on_buttonBox_helpRequested();
void on_buttonBox_clicked(QAbstractButton *button);
};
#endif // PRINT_DIALOG_H |
User Interface | wireshark/ui/qt/print_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>PrintDialog</class>
<widget class="QDialog" name="PrintDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>496</width>
<height>328</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="previewLayout">
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="PacketFormatGroupBox" name="formatGroupBox">
<property name="title">
<string>Packet Format</string>
</property>
<property name="alignment">
<set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="formFeedCheckBox">
<property name="text">
<string>Print each packet on a new page</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="bannerCheckBox">
<property name="toolTip">
<string><html><head/><body><p>Print capture file information on each page</p></body></html></string>
</property>
<property name="text">
<string>Capture information header</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>118</width>
<height>28</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="zoomLabel">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string><html><head/><body><p>Use the &quot;+&quot; and &quot;-&quot; keys to zoom the preview in and out. Use the &quot;0&quot; key to reset the zoom level.</p></body></html></string>
</property>
<property name="text">
<string><html><head/><body><p><span style=" font-size:small; font-style:italic;">+ and - zoom, 0 resets</span></p></body></html></string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item>
<widget class="PacketRangeGroupBox" name="rangeGroupBox">
<property name="title">
<string>Packet Range</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Help</set>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>PacketRangeGroupBox</class>
<extends>QGroupBox</extends>
<header>packet_range_group_box.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>PacketFormatGroupBox</class>
<extends>QGroupBox</extends>
<header>packet_format_group_box.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>PrintDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>PrintDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/profile_dialog.cpp | /* profile_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 <glib.h>
#include "wsutil/filesystem.h"
#include "wsutil/utf8_entities.h"
#include "epan/prefs.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include "ui/profile.h"
#include "ui/recent.h"
#include "ui/last_open_dir.h"
#include <ui/qt/utils/variant_pointer.h>
#include <ui/qt/models/profile_model.h>
#include "profile_dialog.h"
#include <ui_profile_dialog.h>
#include "main_application.h"
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/simple_dialog.h>
#include <QBrush>
#include <QDir>
#include <QFont>
#include <QMessageBox>
#include <QPushButton>
#include <QTreeWidgetItem>
#include <QUrl>
#include <QComboBox>
#include <QLineEdit>
#include <QFileDialog>
#include <QStandardPaths>
#include <QKeyEvent>
#include <QMenu>
#include <QMessageBox>
#define PROFILE_EXPORT_PROPERTY "export"
#define PROFILE_EXPORT_ALL "all"
#define PROFILE_EXPORT_SELECTED "selected"
ProfileDialog::ProfileDialog(QWidget *parent) :
GeometryStateDialog(parent),
pd_ui_(new Ui::ProfileDialog),
ok_button_(Q_NULLPTR),
import_button_(Q_NULLPTR),
model_(Q_NULLPTR),
sort_model_(Q_NULLPTR)
{
pd_ui_->setupUi(this);
loadGeometry();
setWindowTitle(mainApp->windowTitleString(tr("Configuration Profiles")));
ok_button_ = pd_ui_->buttonBox->button(QDialogButtonBox::Ok);
// XXX - Use NSImageNameAddTemplate and NSImageNameRemoveTemplate to set stock
// icons on macOS.
// Are there equivalent stock icons on Windows?
pd_ui_->newToolButton->setStockIcon("list-add");
pd_ui_->deleteToolButton->setStockIcon("list-remove");
pd_ui_->copyToolButton->setStockIcon("list-copy");
#ifdef Q_OS_MAC
pd_ui_->newToolButton->setAttribute(Qt::WA_MacSmallSize, true);
pd_ui_->deleteToolButton->setAttribute(Qt::WA_MacSmallSize, true);
pd_ui_->copyToolButton->setAttribute(Qt::WA_MacSmallSize, true);
pd_ui_->hintLabel->setAttribute(Qt::WA_MacSmallSize, true);
#endif
import_button_ = pd_ui_->buttonBox->addButton(tr("Import", "noun"), QDialogButtonBox::ActionRole);
#ifdef HAVE_MINIZIP
export_button_ = pd_ui_->buttonBox->addButton(tr("Export", "noun"), QDialogButtonBox::ActionRole);
QMenu * importMenu = new QMenu(import_button_);
QAction * entry = importMenu->addAction(tr("From Zip File..."));
connect(entry, &QAction::triggered, this, &ProfileDialog::importFromZip, Qt::QueuedConnection);
entry = importMenu->addAction(tr("From Directory..."));
connect(entry, &QAction::triggered, this, &ProfileDialog::importFromDirectory, Qt::QueuedConnection);
import_button_->setMenu(importMenu);
QMenu * exportMenu = new QMenu(export_button_);
export_selected_entry_ = exportMenu->addAction(tr("%Ln Selected Personal Profile(s)...", "", 0));
export_selected_entry_->setProperty(PROFILE_EXPORT_PROPERTY, PROFILE_EXPORT_SELECTED);
connect(export_selected_entry_, &QAction::triggered, this, &ProfileDialog::exportProfiles, Qt::QueuedConnection);
entry = exportMenu->addAction(tr("All Personal Profiles..."));
entry->setProperty(PROFILE_EXPORT_PROPERTY, PROFILE_EXPORT_ALL);
connect(entry, &QAction::triggered, this, &ProfileDialog::exportProfiles, Qt::QueuedConnection);
export_button_->setMenu(exportMenu);
#else
connect(import_button_, &QPushButton::clicked, this, &ProfileDialog::importFromDirectory);
#endif
resetTreeView();
/* Select the row for the currently selected profile or the first row if non is selected*/
selectProfile();
pd_ui_->cmbProfileTypes->addItems(ProfileSortModel::filterTypes());
connect (pd_ui_->cmbProfileTypes, &QComboBox::currentTextChanged,
this, &ProfileDialog::filterChanged);
connect (pd_ui_->lineProfileFilter, &QLineEdit::textChanged,
this, &ProfileDialog::filterChanged);
currentItemChanged();
pd_ui_->profileTreeView->setFocus();
}
ProfileDialog::~ProfileDialog()
{
delete pd_ui_;
empty_profile_list (TRUE);
}
void ProfileDialog::keyPressEvent(QKeyEvent *evt)
{
if (pd_ui_->lineProfileFilter->hasFocus() && (evt->key() == Qt::Key_Enter || evt->key() == Qt::Key_Return))
return;
QDialog::keyPressEvent(evt);
}
void ProfileDialog::selectProfile(QString profile)
{
if (profile.isEmpty())
profile = QString(get_profile_name());
int row = model_->findByName(profile);
QModelIndex idx = sort_model_->mapFromSource(model_->index(row, ProfileModel::COL_NAME));
if (idx.isValid())
pd_ui_->profileTreeView->selectRow(idx.row());
}
int ProfileDialog::execAction(ProfileDialog::ProfileAction profile_action)
{
int ret = QDialog::Accepted;
QModelIndex item;
switch (profile_action) {
case ShowProfiles:
ret = exec();
break;
case NewProfile:
on_newToolButton_clicked();
ret = exec();
break;
case ImportZipProfile:
#ifdef HAVE_MINIZIP
importFromZip();
#endif
break;
case ImportDirProfile:
importFromDirectory();
break;
case ExportSingleProfile:
#ifdef HAVE_MINIZIP
exportProfiles();
#endif
break;
case ExportAllProfiles:
#ifdef HAVE_MINIZIP
exportProfiles(true);
#endif
break;
case EditCurrentProfile:
item = pd_ui_->profileTreeView->currentIndex();
if (item.isValid()) {
pd_ui_->profileTreeView->edit(item);
}
ret = exec();
break;
case DeleteCurrentProfile:
if (delete_current_profile()) {
mainApp->setConfigurationProfile (Q_NULLPTR);
}
break;
}
return ret;
}
QModelIndexList ProfileDialog::selectedProfiles()
{
QModelIndexList profiles;
foreach (QModelIndex idx, pd_ui_->profileTreeView->selectionModel()->selectedIndexes())
{
QModelIndex temp = sort_model_->mapToSource(idx);
if (! temp.isValid() || profiles.contains(temp) || temp.column() != ProfileModel::COL_NAME)
continue;
profiles << temp;
}
return profiles;
}
void ProfileDialog::selectionChanged()
{
if (selectedProfiles().count() == 0)
pd_ui_->profileTreeView->selectRow(0);
updateWidgets();
}
void ProfileDialog::updateWidgets()
{
bool enable_del = true;
bool enable_ok = true;
bool multiple = false;
bool enable_import = true;
int user_profiles = 0;
QString msg;
QModelIndex index = sort_model_->mapToSource(pd_ui_->profileTreeView->currentIndex());
QModelIndexList profiles = selectedProfiles();
/* Ensure that the index is always the name column */
if (index.column() != ProfileModel::COL_NAME)
index = index.sibling(index.row(), ProfileModel::COL_NAME);
/* check if more than one viable profile is selected, and inform the sorting model */
if (profiles.count() > 1)
multiple = true;
/* Check if user profiles have been selected and allow export if it is so */
for (int cnt = 0; cnt < profiles.count(); cnt++)
{
if (! profiles[cnt].data(ProfileModel::DATA_IS_GLOBAL).toBool() && ! profiles[cnt].data(ProfileModel::DATA_IS_DEFAULT).toBool())
user_profiles++;
}
if (model_->changesPending())
{
enable_import = false;
msg = tr("An import of profiles is not allowed, while changes are pending");
}
else if (model_->importPending())
{
enable_import = false;
msg = tr("An import is pending to be saved. Additional imports are not allowed");
}
import_button_->setToolTip(msg);
import_button_->setEnabled(enable_import);
#ifdef HAVE_MINIZIP
bool contains_user = false;
bool enable_export = false;
if (user_profiles > 0)
contains_user = true;
/* enable export if no changes are pending */
if (! model_->changesPending())
enable_export = true;
export_button_->setEnabled(enable_export);
if (! enable_export)
{
if (! contains_user)
export_button_->setToolTip(tr("An export of profiles is only allowed for personal profiles"));
else
export_button_->setToolTip(tr("An export of profiles is not allowed, while changes are pending"));
}
export_selected_entry_->setVisible(contains_user);
#endif
/* if the current profile is default with reset pending or a global one, deactivate delete */
if (! multiple)
{
if (index.isValid())
{
if (index.data(ProfileModel::DATA_IS_GLOBAL).toBool())
enable_del = false;
else if (index.data(ProfileModel::DATA_IS_DEFAULT).toBool() && model_->resetDefault())
enable_del = false;
}
else if (! index.isValid())
enable_del = false;
}
QString hintUrl;
msg.clear();
if (multiple)
{
/* multiple profiles are being selected, copy is no longer allowed */
pd_ui_->copyToolButton->setEnabled(false);
msg = tr("%Ln Selected Personal Profile(s)...", "", user_profiles);
pd_ui_->hintLabel->setText(msg);
#ifdef HAVE_MINIZIP
export_selected_entry_->setText(msg);
#endif
}
else
{
/* if only one profile is selected, display it's path in the hint label and activate link (if allowed) */
if (index.isValid())
{
QString temp = index.data(ProfileModel::DATA_PATH).toString();
if (index.data(ProfileModel::DATA_PATH_IS_NOT_DESCRIPTION).toBool() && QFileInfo(temp).isDir())
hintUrl = QUrl::fromLocalFile(temp).toString();
pd_ui_->hintLabel->setText(temp);
pd_ui_->hintLabel->setToolTip(index.data(Qt::ToolTipRole).toString());
if (! index.data(ProfileModel::DATA_IS_GLOBAL).toBool() && ! index.data(ProfileModel::DATA_IS_DEFAULT).toBool())
msg = tr("%Ln Selected Personal Profile(s)...", "", 1);
}
pd_ui_->copyToolButton->setEnabled(true);
#ifdef HAVE_MINIZIP
export_selected_entry_->setText(msg);
#endif
}
/* Ensure, that the ok button is disabled, if an invalid name is used or if duplicate global profiles exist */
if (model_ && model_->rowCount() > 0)
{
msg.clear();
for (int row = 0; row < model_->rowCount() && enable_ok; row++)
{
QModelIndex idx = model_->index(row, ProfileModel::COL_NAME);
QString name = idx.data().toString();
if (! ProfileModel::checkNameValidity(name, &msg))
{
if (idx == index || selectedProfiles().contains(idx))
{
hintUrl.clear();
pd_ui_->hintLabel->setText(msg);
}
enable_ok = false;
continue;
}
if (model_->checkInvalid(idx) || (! idx.data(ProfileModel::DATA_IS_GLOBAL).toBool() && model_->checkIfDeleted(idx)) )
{
if (idx == index)
hintUrl.clear();
enable_ok = false;
continue;
}
if (idx != index && idx.data().toString().compare(index.data().toString()) == 0)
{
if (idx.data(ProfileModel::DATA_IS_GLOBAL).toBool() == index.data(ProfileModel::DATA_IS_GLOBAL).toBool())
enable_ok = false;
}
QList<int> rows = model_->findAllByNameAndVisibility(name, idx.data(ProfileModel::DATA_IS_GLOBAL).toBool());
if (rows.count() > 1)
enable_ok = false;
}
if (enable_ok && ! model_->checkIfDeleted(index) && index.data(ProfileModel::DATA_STATUS).toInt() == PROF_STAT_CHANGED)
hintUrl.clear();
}
pd_ui_->hintLabel->setUrl(hintUrl);
/* ensure the name column is resized to it's content */
pd_ui_->profileTreeView->resizeColumnToContents(ProfileModel::COL_NAME);
pd_ui_->deleteToolButton->setEnabled(enable_del);
ok_button_->setEnabled(enable_ok);
}
void ProfileDialog::currentItemChanged(const QModelIndex &, const QModelIndex &)
{
updateWidgets();
}
void ProfileDialog::on_newToolButton_clicked()
{
pd_ui_->lineProfileFilter->setText("");
pd_ui_->cmbProfileTypes->setCurrentIndex(ProfileSortModel::AllProfiles);
sort_model_->setFilterString();
QModelIndex ridx = sort_model_->mapFromSource(model_->addNewProfile(tr("New profile")));
if (ridx.isValid())
{
pd_ui_->profileTreeView->setCurrentIndex(ridx);
pd_ui_->profileTreeView->scrollTo(ridx);
pd_ui_->profileTreeView->edit(ridx);
currentItemChanged();
}
else
updateWidgets();
}
void ProfileDialog::on_deleteToolButton_clicked()
{
QModelIndexList profiles = selectedProfiles();
if (profiles.count() <= 0)
return;
model_->deleteEntries(profiles);
bool isGlobal = model_->activeProfile().data(ProfileModel::DATA_IS_GLOBAL).toBool();
int row = model_->findByName(model_->activeProfile().data().toString());
/* If the active profile is deleted, the default is selected next */
if (row < 0)
row = 0;
QModelIndex newIdx = sort_model_->mapFromSource(model_->index(row, 0));
if (newIdx.data(ProfileModel::DATA_IS_GLOBAL).toBool() != isGlobal)
newIdx = sort_model_->mapFromSource(model_->index(0, 0));
pd_ui_->profileTreeView->setCurrentIndex(newIdx);
updateWidgets();
}
void ProfileDialog::on_copyToolButton_clicked()
{
QModelIndexList profiles = selectedProfiles();
if (profiles.count() > 1)
return;
pd_ui_->lineProfileFilter->setText("");
pd_ui_->cmbProfileTypes->setCurrentIndex(ProfileSortModel::AllProfiles);
sort_model_->setFilterString();
QModelIndex current = pd_ui_->profileTreeView->currentIndex();
if (current.column() != ProfileModel::COL_NAME)
current = current.sibling(current.row(), ProfileModel::COL_NAME);
QModelIndex source = sort_model_->mapToSource(current);
QModelIndex ridx = model_->duplicateEntry(source);
if (ridx.isValid())
{
pd_ui_->profileTreeView->setCurrentIndex(sort_model_->mapFromSource(ridx));
pd_ui_->profileTreeView->scrollTo(sort_model_->mapFromSource(ridx));
pd_ui_->profileTreeView->edit(sort_model_->mapFromSource(ridx));
currentItemChanged();
}
else
updateWidgets();
}
void ProfileDialog::on_buttonBox_accepted()
{
bool write_recent = true;
bool item_data_removed = false;
QModelIndex index = sort_model_->mapToSource(pd_ui_->profileTreeView->currentIndex());
pd_ui_->buttonBox->setFocus();
QModelIndexList profiles = selectedProfiles();
if (profiles.count() <= 0)
index = QModelIndex();
QModelIndex default_item = sort_model_->mapFromSource(model_->index(0, ProfileModel::COL_NAME));
if (index.isValid() && index.column() != ProfileModel::COL_NAME)
index = index.sibling(index.row(), ProfileModel::COL_NAME);
if (default_item.data(ProfileModel::DATA_STATUS).toInt() == PROF_STAT_DEFAULT && model_->resetDefault())
{
// Reset Default profile.
GList *fl_entry = model_->at(0);
remove_from_profile_list(fl_entry);
// Don't write recent file if leaving the Default profile after this has been reset.
write_recent = !is_default_profile();
// Don't fetch profile data if removed.
item_data_removed = (index.row() == 0);
}
if (write_recent) {
/* Get the current geometry, before writing it to disk */
mainApp->emitAppSignal(MainApplication::ProfileChanging);
/* Write recent file for current profile now because
* the profile may be renamed in apply_profile_changes() */
write_profile_recent();
}
gchar * err_msg = Q_NULLPTR;
if ((err_msg = apply_profile_changes()) != Q_NULLPTR) {
QMessageBox::critical(this, tr("Profile Error"),
err_msg,
QMessageBox::Ok);
g_free(err_msg);
model_->doResetModel();
return;
}
model_->doResetModel();
QString profileName;
if (! index.isValid() && model_->lastSetRow() >= 0)
{
QModelIndex original = model_->index(model_->lastSetRow(), ProfileModel::COL_NAME);
index = sort_model_->mapFromSource(original);
}
/* If multiple profiles are selected, do not change the selected profile */
if (index.isValid() && ! item_data_removed && profiles.count() <= 1)
{
profileName = model_->data(index).toString();
}
if (profileName.length() > 0 && model_->findByName(profileName) >= 0) {
// The new profile exists, change.
mainApp->setConfigurationProfile (profileName.toUtf8().constData(), FALSE);
} else if (!model_->activeProfile().isValid()) {
// The new profile does not exist, and the previous profile has
// been deleted. Change to the default profile.
mainApp->setConfigurationProfile (Q_NULLPTR, FALSE);
}
}
void ProfileDialog::on_buttonBox_rejected()
{
QString msg;
if (! model_->clearImported(&msg))
QMessageBox::critical(this, tr("Error"), msg);
}
void ProfileDialog::on_buttonBox_helpRequested()
{
mainApp->helpTopicAction(HELP_CONFIG_PROFILES_DIALOG);
}
void ProfileDialog::dataChanged(const QModelIndex &)
{
pd_ui_->lineProfileFilter->setText("");
pd_ui_->cmbProfileTypes->setCurrentIndex(ProfileSortModel::AllProfiles);
pd_ui_->profileTreeView->setFocus();
if (model_->lastSetRow() >= 0)
{
QModelIndex original = model_->index(model_->lastSetRow(), ProfileModel::COL_NAME);
pd_ui_->profileTreeView->setCurrentIndex(sort_model_->mapFromSource(original));
pd_ui_->profileTreeView->selectRow(sort_model_->mapFromSource(original).row());
}
updateWidgets();
}
void ProfileDialog::filterChanged(const QString &text)
{
if (qobject_cast<QComboBox *>(sender()))
{
QComboBox * cmb = qobject_cast<QComboBox *>(sender());
sort_model_->setFilterType(static_cast<ProfileSortModel::FilterType>(cmb->currentIndex()));
}
else if (qobject_cast<QLineEdit *>(sender()))
sort_model_->setFilterString(text);
pd_ui_->profileTreeView->resizeColumnToContents(ProfileModel::COL_NAME);
QModelIndex active = sort_model_->mapFromSource(model_->activeProfile());
if (active.isValid())
pd_ui_->profileTreeView->setCurrentIndex(active);
}
#ifdef HAVE_MINIZIP
void ProfileDialog::exportProfiles(bool exportAllPersonalProfiles)
{
QAction * action = qobject_cast<QAction *>(sender());
if (action && action->property(PROFILE_EXPORT_PROPERTY).isValid())
exportAllPersonalProfiles = action->property(PROFILE_EXPORT_PROPERTY).toString().compare(PROFILE_EXPORT_ALL) == 0;
QModelIndexList items;
int skipped = 0;
if (! exportAllPersonalProfiles)
{
foreach (QModelIndex idx, selectedProfiles())
{
QModelIndex baseIdx = sort_model_->index(idx.row(), ProfileModel::COL_NAME);
if (! baseIdx.data(ProfileModel::DATA_IS_GLOBAL).toBool() && ! baseIdx.data(ProfileModel::DATA_IS_DEFAULT).toBool())
items << sort_model_->mapToSource(baseIdx);
else
skipped++;
}
}
else if (exportAllPersonalProfiles)
{
for (int cnt = 0; cnt < sort_model_->rowCount(); cnt++)
{
QModelIndex idx = sort_model_->index(cnt, ProfileModel::COL_NAME);
if (! idx.data(ProfileModel::DATA_IS_GLOBAL).toBool() && ! idx.data(ProfileModel::DATA_IS_DEFAULT).toBool())
items << sort_model_->mapToSource(idx);
}
}
if (items.count() == 0)
{
QString msg = tr("No profiles found for export");
if (skipped > 0)
msg.append(tr(", %Ln profile(s) skipped", "", skipped));
QMessageBox::critical(this, tr("Exporting profiles"), msg);
return;
}
QString zipFile = QFileDialog::getSaveFileName(this, tr("Select zip file for export"), lastOpenDir(), tr("Zip File (*.zip)"));
if (zipFile.length() > 0)
{
QFileInfo fi(zipFile);
if (fi.suffix().length() == 0 || fi.suffix().toLower().compare("zip") != 0)
zipFile += ".zip";
QString err;
if (model_->exportProfiles(zipFile, items, &err))
{
QString msg = tr("%Ln profile(s) exported", "", static_cast<int>(items.count()));
if (skipped > 0)
msg.append(tr(", %Ln profile(s) skipped", "", skipped));
QMessageBox::information(this, tr("Exporting profiles"), msg);
QFileInfo zip(zipFile);
storeLastDir(zip.absolutePath());
}
else
{
QString msg = tr("An error has occurred while exporting profiles");
if (err.length() > 0)
msg.append(QString("\n\n%1: %3").arg(tr("Error")).arg(err));
QMessageBox::critical(this, tr("Exporting profiles"), msg);
}
}
}
void ProfileDialog::importFromZip()
{
QString zipFile = QFileDialog::getOpenFileName(this, tr("Select zip file for import"), lastOpenDir(), tr("Zip File (*.zip)"));
QFileInfo fi(zipFile);
if (! fi.exists())
return;
int skipped = 0;
QStringList import;
int count = model_->importProfilesFromZip(zipFile, &skipped, &import);
finishImport(fi, count, skipped, import);
}
#endif
void ProfileDialog::importFromDirectory()
{
QString importDir = QFileDialog::getExistingDirectory(this, tr("Select directory for import"), lastOpenDir());
QFileInfo fi(importDir);
if (! fi.isDir())
return;
int skipped = 0;
QStringList import;
int count = model_->importProfilesFromDir(importDir, &skipped, false, &import);
finishImport(fi, count, skipped, import);
}
void ProfileDialog::finishImport(QFileInfo fi, int count, int skipped, QStringList import)
{
QString msg;
QMessageBox::Icon icon;
if (count == 0 && skipped == 0)
{
icon = QMessageBox::Warning;
msg = tr("No profiles found for import in %1").arg(fi.fileName());
}
else
{
icon = QMessageBox::Information;
msg = tr("%Ln profile(s) imported", "", count);
if (skipped > 0)
msg.append(tr(", %Ln profile(s) skipped", "", skipped));
}
QMessageBox msgBox(icon, tr("Importing profiles"), msg, QMessageBox::Ok, this);
msgBox.exec();
storeLastDir(fi.absolutePath());
if (count > 0)
{
import.sort();
resetTreeView();
model_->markAsImported(import);
int rowFirstImported = model_->findByName(import.at(0));
QModelIndex idx = sort_model_->mapFromSource(model_->index(rowFirstImported, ProfileModel::COL_NAME));
pd_ui_->profileTreeView->selectRow(idx.isValid() ? idx.row() : 0);
}
updateWidgets();
}
void ProfileDialog::resetTreeView()
{
if (model_)
{
pd_ui_->profileTreeView->setModel(Q_NULLPTR);
sort_model_->setSourceModel(Q_NULLPTR);
model_->disconnect();
if (pd_ui_->profileTreeView->selectionModel())
pd_ui_->profileTreeView->selectionModel()->disconnect();
delete sort_model_;
delete model_;
}
model_ = new ProfileModel(pd_ui_->profileTreeView);
sort_model_ = new ProfileSortModel(pd_ui_->profileTreeView);
sort_model_->setSourceModel(model_);
pd_ui_->profileTreeView->setModel(sort_model_);
connect(model_, &ProfileModel::itemChanged, this, &ProfileDialog::dataChanged, Qt::QueuedConnection);
QItemSelectionModel *selModel = pd_ui_->profileTreeView->selectionModel();
connect(selModel, &QItemSelectionModel::currentChanged,
this, &ProfileDialog::currentItemChanged, Qt::QueuedConnection);
connect(selModel, &QItemSelectionModel::selectionChanged,
this, &ProfileDialog::selectionChanged);
selectionChanged();
if (sort_model_->columnCount() <= 1)
pd_ui_->profileTreeView->header()->hide();
else
{
pd_ui_->profileTreeView->header()->setStretchLastSection(false);
pd_ui_->profileTreeView->header()->setSectionResizeMode(ProfileModel::COL_NAME, QHeaderView::Stretch);
}
} |
C/C++ | wireshark/ui/qt/profile_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 PROFILE_DIALOG_H
#define PROFILE_DIALOG_H
#include "config.h"
#include <ui/qt/geometry_state_dialog.h>
#include <ui/qt/models/profile_model.h>
#include <ui/qt/widgets/profile_tree_view.h>
#include <QPushButton>
#include <QTreeWidgetItem>
namespace Ui {
class ProfileDialog;
}
class ProfileDialog : public GeometryStateDialog
{
Q_OBJECT
public:
enum ProfileAction {
ShowProfiles, NewProfile, ImportZipProfile, ImportDirProfile,
ExportSingleProfile, ExportAllProfiles, EditCurrentProfile, DeleteCurrentProfile
};
explicit ProfileDialog(QWidget *parent = Q_NULLPTR);
~ProfileDialog();
int execAction(ProfileAction profile_action);
/**
* @brief Select the profile with the given name.
*
* If the profile name is empty, the currently selected profile will be choosen instead.
* If the choosen profile is invalid, the first row will be choosen.
*
* @param profile the name of the profile to be selected
*/
void selectProfile(QString profile = QString());
protected:
virtual void keyPressEvent(QKeyEvent *event);
private:
Ui::ProfileDialog *pd_ui_;
QPushButton *ok_button_;
QPushButton *import_button_;
#ifdef HAVE_MINIZIP
QPushButton *export_button_;
QAction *export_selected_entry_;
#endif
ProfileModel *model_;
ProfileSortModel *sort_model_;
void updateWidgets();
void resetTreeView();
void finishImport(QFileInfo fi, int count, int skipped, QStringList import);
private slots:
void currentItemChanged(const QModelIndex & c = QModelIndex(), const QModelIndex & p = QModelIndex());
#ifdef HAVE_MINIZIP
void exportProfiles(bool exportAllPersonalProfiles = false);
void importFromZip();
#endif
void importFromDirectory();
void on_newToolButton_clicked();
void on_deleteToolButton_clicked();
void on_copyToolButton_clicked();
void on_buttonBox_accepted();
void on_buttonBox_rejected();
void on_buttonBox_helpRequested();
void dataChanged(const QModelIndex &);
void filterChanged(const QString &);
void selectionChanged();
QModelIndexList selectedProfiles();
// QWidget interface
};
#endif // PROFILE_DIALOG_H |
User Interface | wireshark/ui/qt/profile_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ProfileDialog</class>
<widget class="QDialog" name="ProfileDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>570</width>
<height>400</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLineEdit" name="lineProfileFilter">
<property name="placeholderText">
<string>Search for profile …</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="cmbProfileTypes"/>
</item>
</layout>
</item>
<item>
<widget class="ProfileTreeView" name="profileTreeView">
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="uniformRowHeights">
<bool>true</bool>
</property>
<property name="itemsExpandable">
<bool>false</bool>
</property>
<property name="sortingEnabled">
<bool>false</bool>
</property>
<property name="headerHidden">
<bool>false</bool>
</property>
<property name="expandsOnDoubleClick">
<bool>false</bool>
</property>
<attribute name="headerVisible">
<bool>true</bool>
</attribute>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0,0,0,0">
<item>
<widget class="StockIconToolButton" name="newToolButton">
<property name="toolTip">
<string>Create a new profile using default settings.</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset>
<normaloff>:/stock/plus-8.png</normaloff>:/stock/plus-8.png</iconset>
</property>
</widget>
</item>
<item>
<widget class="StockIconToolButton" name="deleteToolButton">
<property name="toolTip">
<string><html><head/><body><p>Remove this profile. System provided profiles cannot be removed. The default profile will be reset upon deletion.</p></body></html></string>
</property>
<property name="icon">
<iconset>
<normaloff>:/stock/minus-8.png</normaloff>:/stock/minus-8.png</iconset>
</property>
</widget>
</item>
<item>
<widget class="StockIconToolButton" name="copyToolButton">
<property name="toolTip">
<string>Copy this profile.</string>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset>
<normaloff>:/stock/copy-8.png</normaloff>:/stock/copy-8.png</iconset>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="ElidedLabel" name="hintLabel">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string/>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Help|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>StockIconToolButton</class>
<extends>QToolButton</extends>
<header>widgets/stock_icon_tool_button.h</header>
</customwidget>
<customwidget>
<class>ProfileTreeView</class>
<extends>QTreeView</extends>
<header>widgets/profile_tree_view.h</header>
</customwidget>
<customwidget>
<class>ElidedLabel</class>
<extends>QLabel</extends>
<header>widgets/elided_label.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>ProfileDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>ProfileDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/progress_frame.cpp | /* progress_frame.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 "progress_frame.h"
#include <ui_progress_frame.h>
#include "ui/progress_dlg.h"
#include <QDialogButtonBox>
#include <QGraphicsOpacityEffect>
#include <QBoxLayout>
#include <QPropertyAnimation>
#include <ui/qt/widgets/stock_icon_tool_button.h>
#include "main_application.h"
// To do:
// - Add an NSProgressIndicator to the dock icon on macOS.
// - Start adding the progress bar to dialogs.
// - Don't complain so loudly when the user stops a capture.
progdlg_t *
create_progress_dlg(gpointer top_level_window, const gchar *task_title, const gchar *item_title,
gboolean terminate_is_stop, gboolean *stop_flag) {
ProgressFrame *pf;
QWidget *main_window;
if (!top_level_window) {
return nullptr;
}
main_window = qobject_cast<QWidget *>((QObject *)top_level_window);
if (!main_window) {
return nullptr;
}
pf = main_window->findChild<ProgressFrame *>();
if (!pf) {
return nullptr;
}
QString title = task_title;
if (item_title && strlen(item_title) > 0) {
title.append(" ").append(item_title);
}
return pf->showProgress(title, true, terminate_is_stop, stop_flag, 0);
}
progdlg_t *
delayed_create_progress_dlg(gpointer top_level_window, const gchar *task_title, const gchar *item_title,
gboolean terminate_is_stop, gboolean *stop_flag,
gfloat progress)
{
progdlg_t *progress_dialog = create_progress_dlg(top_level_window, task_title, item_title, terminate_is_stop, stop_flag);
update_progress_dlg(progress_dialog, progress, item_title);
return progress_dialog;
}
/*
* Update the progress information of the progress bar box.
*/
void
update_progress_dlg(progdlg_t *dlg, gfloat percentage, const gchar *)
{
if (!dlg) return;
dlg->progress_frame->setValue((int)(percentage * 100));
/*
* Flush out the update and process any input events.
*/
MainApplication::processEvents();
}
/*
* Destroy the progress bar.
*/
void
destroy_progress_dlg(progdlg_t *dlg)
{
dlg->progress_frame->hide();
}
ProgressFrame::ProgressFrame(QWidget *parent) :
QFrame(parent),
ui(new Ui::ProgressFrame)
, terminate_is_stop_(false)
, stop_flag_(nullptr)
, show_timer_(-1)
, effect_(nullptr)
, animation_(nullptr)
#ifdef QWINTASKBARPROGRESS_H
, update_taskbar_(false)
, taskbar_progress_(NULL)
#endif
{
ui->setupUi(this);
progress_dialog_.progress_frame = this;
progress_dialog_.top_level_window = window();
#ifdef Q_OS_MAC
ui->label->setAttribute(Qt::WA_MacSmallSize, true);
#endif
ui->label->setStyleSheet(QString(
"QLabel {"
" background: transparent;"
"}"));
ui->progressBar->setStyleSheet(QString(
"QProgressBar {"
" max-width: 20em;"
" min-height: 0.5em;"
" max-height: 1em;"
" border-bottom: 0px;"
" border-top: 0px;"
" background: transparent;"
"}"));
ui->stopButton->setStockIcon("x-filter-clear");
ui->stopButton->setIconSize(QSize(14, 14));
ui->stopButton->setStyleSheet(
"QToolButton {"
" border: none;"
" background: transparent;" // Disables platform style on Windows.
" padding: 0px;"
" margin: 0px;"
" min-height: 0.8em;"
" max-height: 1em;"
" min-width: 0.8em;"
" max-width: 1em;"
"}"
);
effect_ = new QGraphicsOpacityEffect(this);
animation_ = new QPropertyAnimation(effect_, "opacity", this);
connect(this, SIGNAL(showRequested(bool,bool,gboolean*)),
this, SLOT(show(bool,bool,gboolean*)));
hide();
}
ProgressFrame::~ProgressFrame()
{
delete ui;
}
struct progdlg *ProgressFrame::showProgress(const QString &title, bool animate, bool terminate_is_stop, gboolean *stop_flag, int value)
{
setMaximumValue(100);
ui->progressBar->setValue(value);
QString elided_title = title;
int max_w = fontMetrics().height() * 20; // em-widths, arbitrary
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
int title_w = fontMetrics().horizontalAdvance(title);
#else
int title_w = fontMetrics().width(title);
#endif
if (title_w > max_w) {
elided_title = fontMetrics().elidedText(title, Qt::ElideRight, max_w);
}
// If we're in the main status bar, should we push this as a status message instead?
ui->label->setText(elided_title);
emit showRequested(animate, terminate_is_stop, stop_flag);
return &progress_dialog_;
}
progdlg *ProgressFrame::showBusy(bool animate, bool terminate_is_stop, gboolean *stop_flag)
{
setMaximumValue(0);
emit showRequested(animate, terminate_is_stop, stop_flag);
return &progress_dialog_;
}
void ProgressFrame::addToButtonBox(QDialogButtonBox *button_box, QObject *main_window)
{
// We have a ProgressFrame in the main status bar which is controlled
// from the capture file and other parts of the application via
// create_progress_dlg and delayed_create_progress_dlg.
// Create a new ProgressFrame and pair it with the main instance.
ProgressFrame *main_progress_frame = main_window->findChild<ProgressFrame *>();
if (!button_box || !main_progress_frame) return;
QBoxLayout *layout = qobject_cast<QBoxLayout *>(button_box->layout());
if (!layout) return;
ProgressFrame *progress_frame = new ProgressFrame(button_box);
// Insert ourselves after the first spacer we find, otherwise the
// far right of the button box.
int idx = layout->count();
for (int i = 0; i < layout->count(); i++) {
if (layout->itemAt(i)->spacerItem()) {
idx = i + 1;
break;
}
}
layout->insertWidget(idx, progress_frame);
int one_em = progress_frame->fontMetrics().height();
progress_frame->setMaximumWidth(one_em * 8);
connect(main_progress_frame, SIGNAL(showRequested(bool,bool,gboolean*)),
progress_frame, SLOT(show(bool,bool,gboolean*)));
connect(main_progress_frame, SIGNAL(maximumValueChanged(int)),
progress_frame, SLOT(setMaximumValue(int)));
connect(main_progress_frame, SIGNAL(valueChanged(int)),
progress_frame, SLOT(setValue(int)));
connect(main_progress_frame, SIGNAL(setHidden()),
progress_frame, SLOT(hide()));
connect(progress_frame, SIGNAL(stopLoading()),
main_progress_frame, SIGNAL(stopLoading()));
}
void ProgressFrame::captureFileClosing()
{
// Hide any paired ProgressFrames and disconnect from them.
emit setHidden();
disconnect(SIGNAL(showRequested(bool,bool,gboolean*)));
disconnect(SIGNAL(maximumValueChanged(int)));
disconnect(SIGNAL(valueChanged(int)));
connect(this, SIGNAL(showRequested(bool,bool,gboolean*)),
this, SLOT(show(bool,bool,gboolean*)));
}
void ProgressFrame::setValue(int value)
{
ui->progressBar->setValue(value);
emit valueChanged(value);
}
void ProgressFrame::timerEvent(QTimerEvent *event)
{
if (event->timerId() == show_timer_) {
killTimer(show_timer_);
show_timer_ = -1;
this->setGraphicsEffect(effect_);
animation_->setDuration(200);
animation_->setStartValue(0.1);
animation_->setEndValue(1.0);
animation_->setEasingCurve(QEasingCurve::InOutQuad);
animation_->start();
QFrame::show();
} else {
QFrame::timerEvent(event);
}
}
void ProgressFrame::hide()
{
show_timer_ = -1;
emit setHidden();
QFrame::hide();
#ifdef QWINTASKBARPROGRESS_H
if (taskbar_progress_) {
disconnect(this, SIGNAL(valueChanged(int)), taskbar_progress_, SLOT(setValue(int)));
taskbar_progress_->reset();
taskbar_progress_->hide();
}
#endif
}
void ProgressFrame::on_stopButton_clicked()
{
emit stopLoading();
}
const int show_delay_ = 150; // ms
void ProgressFrame::show(bool animate, bool terminate_is_stop, gboolean *stop_flag)
{
terminate_is_stop_ = terminate_is_stop;
stop_flag_ = stop_flag;
if (stop_flag) {
ui->stopButton->show();
} else {
ui->stopButton->hide();
}
if (animate) {
show_timer_ = startTimer(show_delay_);
} else {
QFrame::show();
}
#ifdef QWINTASKBARPROGRESS_H
// windowHandle() is picky about returning a non-NULL value so we check it
// each time.
if (update_taskbar_ && !taskbar_progress_ && window()->windowHandle()) {
QWinTaskbarButton *taskbar_button = new QWinTaskbarButton(this);
if (taskbar_button) {
taskbar_button->setWindow(window()->windowHandle());
taskbar_progress_ = taskbar_button->progress();
}
}
if (taskbar_progress_) {
taskbar_progress_->show();
taskbar_progress_->reset();
connect(this, SIGNAL(valueChanged(int)), taskbar_progress_, SLOT(setValue(int)));
}
#endif
}
void ProgressFrame::setMaximumValue(int value)
{
ui->progressBar->setMaximum(value);
emit maximumValueChanged(value);
} |
C/C++ | wireshark/ui/qt/progress_frame.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PROGRESS_FRAME_H
#define PROGRESS_FRAME_H
#include <glib.h>
#include <QFrame>
namespace Ui {
class ProgressFrame;
}
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && defined(Q_OS_WIN)
#include <QWinTaskbarButton>
#include <QWinTaskbarProgress>
#endif
class ProgressFrame;
class QDialogButtonBox;
class QElapsedTimer;
class QGraphicsOpacityEffect;
class QPropertyAnimation;
// Define the structure describing a progress dialog.
struct progdlg {
ProgressFrame *progress_frame; // This progress frame
QWidget *top_level_window; // Progress frame's main window
};
class ProgressFrame : public QFrame
{
Q_OBJECT
public:
explicit ProgressFrame(QWidget *parent = 0);
~ProgressFrame();
#ifdef QWINTASKBARPROGRESS_H
void enableTaskbarUpdates(bool enable = true) { update_taskbar_ = enable; }
#endif
static void addToButtonBox(QDialogButtonBox *button_box, QObject *main_window);
void captureFileClosing();
public slots:
struct progdlg *showProgress(const QString &title, bool animate, bool terminate_is_stop, gboolean *stop_flag, int value = 0);
struct progdlg *showBusy(bool animate, bool terminate_is_stop, gboolean *stop_flag);
void setValue(int value);
void hide();
signals:
void showRequested(bool animate, bool terminate_is_stop, gboolean *stop_flag);
void valueChanged(int value);
void maximumValueChanged(int value);
void setHidden();
void stopLoading();
protected:
void timerEvent(QTimerEvent *event);
private:
Ui::ProgressFrame *ui;
struct progdlg progress_dialog_;
QString message_;
QString status_;
bool terminate_is_stop_;
gboolean *stop_flag_;
int show_timer_;
QGraphicsOpacityEffect *effect_;
QPropertyAnimation *animation_;
#ifdef QWINTASKBARPROGRESS_H
bool update_taskbar_;
QWinTaskbarProgress *taskbar_progress_;
#endif
private slots:
void on_stopButton_clicked();
void show(bool animate, bool terminate_is_stop, gboolean *stop_flag);
void setMaximumValue(int value);
};
#endif // PROGRESS_FRAME_H |
User Interface | wireshark/ui/qt/progress_frame.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ProgressFrame</class>
<widget class="QFrame" name="ProgressFrame">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>210</width>
<height>38</height>
</rect>
</property>
<property name="windowTitle">
<string>Frame</string>
</property>
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<property name="lineWidth">
<number>0</number>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="sizeConstraint">
<enum>QLayout::SetMinimumSize</enum>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Loading</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>
<item>
<widget class="StockIconToolButton" name="stopButton">
<property name="text">
<string/>
</property>
<property name="iconSize">
<size>
<width>12</width>
<height>12</height>
</size>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>StockIconToolButton</class>
<extends>QToolButton</extends>
<header>widgets/stock_icon_tool_button.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui> |
C++ | wireshark/ui/qt/protocol_hierarchy_dialog.cpp | /* protocol_hierarchy_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "protocol_hierarchy_dialog.h"
#include <ui_protocol_hierarchy_dialog.h>
#include "cfile.h"
#include "ui/proto_hier_stats.h"
#include <ui/qt/utils/variant_pointer.h>
#include <wsutil/utf8_entities.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
#include <epan/proto.h>
#include <epan/disabled_protos.h>
#include <QClipboard>
#include <QPushButton>
#include <QTextStream>
#include <QTreeWidgetItemIterator>
/*
* @file Protocol Hierarchy Statistics dialog
*
* Displays tree of protocols with various statistics
* Allows filtering on tree items
*/
// To do:
// - Make "Copy as YAML" output a tree?
// - Add time series data to ph_stats_node_t and draw sparklines.
const int protocol_col_ = 0;
const int pct_packets_col_ = 1;
const int packets_col_ = 2;
const int pct_bytes_col_ = 3;
const int bytes_col_ = 4;
const int bandwidth_col_ = 5;
const int end_packets_col_ = 6;
const int end_bytes_col_ = 7;
const int end_bandwidth_col_ = 8;
const int pdus_col_ = 9;
struct addTreeNodeData {
QSet<QString> *protos;
QTreeWidgetItem *widget;
};
class ProtocolHierarchyTreeWidgetItem : public QTreeWidgetItem
{
public:
ProtocolHierarchyTreeWidgetItem(QTreeWidgetItem *parent, ph_stats_node_t& ph_stats_node) :
QTreeWidgetItem(parent),
total_packets_(ph_stats_node.num_pkts_total),
total_pdus_(ph_stats_node.num_pdus_total),
last_packets_(ph_stats_node.num_pkts_last),
total_bytes_(ph_stats_node.num_bytes_total),
last_bytes_(ph_stats_node.num_bytes_last),
percent_packets_(0),
percent_bytes_(0),
bits_s_(0.0),
end_bits_s_(0.0)
{
filter_name_ = ph_stats_node.hfinfo->abbrev;
if (!parent) return;
ph_stats_t *ph_stats = VariantPointer<ph_stats_t>::asPtr(parent->treeWidget()->invisibleRootItem()->data(0, Qt::UserRole));
if (!ph_stats || ph_stats->tot_packets < 1) return;
percent_packets_ = total_packets_ * 100.0 / ph_stats->tot_packets;
percent_bytes_ = total_bytes_ * 100.0 / ph_stats->tot_bytes;
double seconds = ph_stats->last_time - ph_stats->first_time;
if (seconds > 0.0) {
bits_s_ = total_bytes_ * 8.0 / seconds;
end_bits_s_ = last_bytes_ * 8.0 / seconds;
}
setText(protocol_col_, ph_stats_node.hfinfo->name);
setToolTip(protocol_col_, QString("%1").arg(ph_stats_node.hfinfo->abbrev));
setData(pct_packets_col_, Qt::UserRole, percent_packets_);
setText(packets_col_, QString::number(total_packets_));
setData(pct_bytes_col_, Qt::UserRole, percent_bytes_);
setText(bytes_col_, QString::number(total_bytes_));
setText(bandwidth_col_, seconds > 0.0 ? bits_s_to_qstring(bits_s_) : UTF8_EM_DASH);
setText(end_packets_col_, QString::number(last_packets_));
setText(end_bytes_col_, QString::number(last_bytes_));
setText(end_bandwidth_col_, seconds > 0.0 ? bits_s_to_qstring(end_bits_s_) : UTF8_EM_DASH);
setText(pdus_col_, QString::number(total_pdus_));
}
// Return a QString, int, double, or invalid QVariant representing the raw column data.
QVariant colData(int col) const {
switch(col) {
case protocol_col_:
return text(col);
case (pct_packets_col_):
return percent_packets_;
case (packets_col_):
return total_packets_;
case (pct_bytes_col_):
return percent_bytes_;
case (bytes_col_):
return total_bytes_;
case (bandwidth_col_):
return bits_s_;
case (end_packets_col_):
return last_packets_;
case (end_bytes_col_):
return last_bytes_;
case (end_bandwidth_col_):
return end_bits_s_;
case (pdus_col_):
return total_pdus_;
default:
break;
}
return QVariant();
}
bool operator< (const QTreeWidgetItem &other) const
{
const ProtocolHierarchyTreeWidgetItem &other_phtwi = dynamic_cast<const ProtocolHierarchyTreeWidgetItem&>(other);
switch (treeWidget()->sortColumn()) {
case pct_packets_col_:
return percent_packets_ < other_phtwi.percent_packets_;
case packets_col_:
return total_packets_ < other_phtwi.total_packets_;
case pct_bytes_col_:
return percent_packets_ < other_phtwi.percent_packets_;
case bytes_col_:
return total_bytes_ < other_phtwi.total_bytes_;
case bandwidth_col_:
return bits_s_ < other_phtwi.bits_s_;
case end_packets_col_:
return last_packets_ < other_phtwi.last_packets_;
case end_bytes_col_:
return last_bytes_ < other_phtwi.last_bytes_;
case end_bandwidth_col_:
return end_bits_s_ < other_phtwi.end_bits_s_;
case pdus_col_:
return total_pdus_ < other_phtwi.total_pdus_;
default:
break;
}
// Fall back to string comparison
return QTreeWidgetItem::operator <(other);
}
const QString filterName(void) { return filter_name_; }
private:
QString filter_name_;
unsigned total_packets_;
unsigned total_pdus_;
unsigned last_packets_;
unsigned total_bytes_;
unsigned last_bytes_;
double percent_packets_;
double percent_bytes_;
double bits_s_;
double end_bits_s_;
};
ProtocolHierarchyDialog::ProtocolHierarchyDialog(QWidget &parent, CaptureFile &cf) :
WiresharkDialog(parent, cf),
ui(new Ui::ProtocolHierarchyDialog)
{
ui->setupUi(this);
loadGeometry(parent.width() * 4 / 5, parent.height() * 4 / 5);
setWindowSubtitle(tr("Protocol Hierarchy Statistics"));
ui->hierStatsTreeWidget->setItemDelegateForColumn(pct_packets_col_, &percent_bar_delegate_);
ui->hierStatsTreeWidget->setItemDelegateForColumn(pct_bytes_col_, &percent_bar_delegate_);
ph_stats_t *ph_stats = ph_stats_new(cap_file_.capFile());
if (ph_stats) {
ui->hierStatsTreeWidget->invisibleRootItem()->setData(0, Qt::UserRole, VariantPointer<ph_stats_t>::asQVariant(ph_stats));
addTreeNodeData atnd { &used_protos_, ui->hierStatsTreeWidget->invisibleRootItem() };
g_node_children_foreach(ph_stats->stats_tree, G_TRAVERSE_ALL, addTreeNode, (void *)&atnd);
ph_stats_free(ph_stats);
}
ui->hierStatsTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->hierStatsTreeWidget, SIGNAL(customContextMenuRequested(QPoint)),
SLOT(showProtoHierMenu(QPoint)));
ui->hierStatsTreeWidget->setSortingEnabled(true);
ui->hierStatsTreeWidget->expandAll();
for (int i = 0; i < ui->hierStatsTreeWidget->columnCount(); i++) {
ui->hierStatsTreeWidget->resizeColumnToContents(i);
}
QMenu *submenu;
FilterAction::Action cur_action = FilterAction::ActionApply;
submenu = ctx_menu_.addMenu(FilterAction::actionName(cur_action));
foreach (FilterAction::ActionType at, FilterAction::actionTypes()) {
FilterAction *fa = new FilterAction(submenu, cur_action, at);
submenu->addAction(fa);
connect(fa, SIGNAL(triggered()), this, SLOT(filterActionTriggered()));
}
cur_action = FilterAction::ActionPrepare;
submenu = ctx_menu_.addMenu(FilterAction::actionName(cur_action));
foreach (FilterAction::ActionType at, FilterAction::actionTypes()) {
FilterAction *fa = new FilterAction(submenu, cur_action, at);
submenu->addAction(fa);
connect(fa, SIGNAL(triggered()), this, SLOT(filterActionTriggered()));
}
FilterAction *fa = new FilterAction(&ctx_menu_, FilterAction::ActionFind);
ctx_menu_.addAction(fa);
connect(fa, SIGNAL(triggered()), this, SLOT(filterActionTriggered()));
fa = new FilterAction(&ctx_menu_, FilterAction::ActionColorize);
ctx_menu_.addAction(fa);
connect(fa, SIGNAL(triggered()), this, SLOT(filterActionTriggered()));
ctx_menu_.addSeparator();
ctx_menu_.addAction(ui->actionCopyAsCsv);
ctx_menu_.addAction(ui->actionCopyAsYaml);
QPushButton *copy_button = ui->buttonBox->addButton(tr("Copy"), QDialogButtonBox::ApplyRole);
QMenu *copy_menu = new QMenu(copy_button);
QAction *ca;
ca = copy_menu->addAction(tr("as CSV"));
ca->setToolTip(ui->actionCopyAsCsv->toolTip());
connect(ca, &QAction::triggered, this, &ProtocolHierarchyDialog::on_actionCopyAsCsv_triggered);
ca = copy_menu->addAction(tr("as YAML"));
ca->setToolTip(ui->actionCopyAsYaml->toolTip());
connect(ca, &QAction::triggered, this, &ProtocolHierarchyDialog::on_actionCopyAsYaml_triggered);
copy_button->setMenu(copy_menu);
connect(ca, SIGNAL(triggered()), this, SLOT(on_actionCopyAsYaml_triggered()));
ca = copy_menu->addAction(tr("protocol short names"));
ca->setToolTip(ui->actionCopyProtoList->toolTip());
connect(ca, SIGNAL(triggered()), this, SLOT(on_actionCopyProtoList_triggered()));
copy_button->setMenu(copy_menu);
QPushButton *protos_button = ui->buttonBox->addButton(tr("Protocols"), QDialogButtonBox::ApplyRole);
QMenu *protos_menu = new QMenu(protos_button);
proto_disable_ = protos_menu->addAction(tr("Disable unused"));
proto_disable_->setToolTip(ui->actionDisableProtos->toolTip());
connect(proto_disable_, SIGNAL(triggered()), this, SLOT(on_actionDisableProtos_triggered()));
proto_revert_ = protos_menu->addAction(tr("Revert changes"));
proto_revert_->setToolTip(ui->actionRevertProtos->toolTip());
connect(proto_revert_, SIGNAL(triggered()), this, SLOT(on_actionRevertProtos_triggered()));
protos_button->setMenu(protos_menu);
QPushButton *close_bt = ui->buttonBox->button(QDialogButtonBox::Close);
if (close_bt) {
close_bt->setDefault(true);
}
display_filter_ = cap_file_.capFile()->dfilter;
updateWidgets();
}
ProtocolHierarchyDialog::~ProtocolHierarchyDialog()
{
delete ui;
}
void ProtocolHierarchyDialog::showProtoHierMenu(QPoint pos)
{
bool enable = ui->hierStatsTreeWidget->currentItem() != NULL && !file_closed_ ? true : false;
foreach (QMenu *submenu, ctx_menu_.findChildren<QMenu*>()) {
submenu->setEnabled(enable);
}
foreach (QAction *action, ctx_menu_.actions()) {
if (action != ui->actionCopyAsCsv && action != ui->actionCopyAsYaml) {
action->setEnabled(enable);
}
}
ctx_menu_.popup(ui->hierStatsTreeWidget->viewport()->mapToGlobal(pos));
}
void ProtocolHierarchyDialog::filterActionTriggered()
{
ProtocolHierarchyTreeWidgetItem *phti = static_cast<ProtocolHierarchyTreeWidgetItem *>(ui->hierStatsTreeWidget->currentItem());
FilterAction *fa = qobject_cast<FilterAction *>(QObject::sender());
if (!fa || !phti) {
return;
}
QString filter_name(phti->filterName());
emit filterAction(filter_name, fa->action(), fa->actionType());
}
void ProtocolHierarchyDialog::addTreeNode(GNode *node, gpointer data)
{
ph_stats_node_t *stats = (ph_stats_node_t *)node->data;
if (!stats) return;
addTreeNodeData *atndp = (addTreeNodeData *)data;
QTreeWidgetItem *parent_ti = atndp->widget;
if (!parent_ti) return;
atndp->protos->insert(QString(stats->hfinfo->abbrev));
ProtocolHierarchyTreeWidgetItem *phti = new ProtocolHierarchyTreeWidgetItem(parent_ti, *stats);
addTreeNodeData atnd { atndp->protos, phti };
g_node_children_foreach(node, G_TRAVERSE_ALL, addTreeNode, (void *)&atnd);
}
void ProtocolHierarchyDialog::updateWidgets()
{
QString hint = "<small><i>";
if (display_filter_.isEmpty()) {
hint += tr("No display filter.");
} else {
hint += tr("Display filter: %1").arg(display_filter_);
}
hint += "</i></small>";
ui->hintLabel->setText(hint);
proto_revert_->setEnabled(enabled_protos_unsaved_changes());
WiresharkDialog::updateWidgets();
}
QList<QVariant> ProtocolHierarchyDialog::protoHierRowData(QTreeWidgetItem *item) const
{
QList<QVariant> row_data;
for (int col = 0; col < ui->hierStatsTreeWidget->columnCount(); col++) {
if (!item) {
row_data << ui->hierStatsTreeWidget->headerItem()->text(col);
} else {
ProtocolHierarchyTreeWidgetItem *phti = static_cast<ProtocolHierarchyTreeWidgetItem*>(item);
if (phti) {
row_data << phti->colData(col);
}
}
}
return row_data;
}
void ProtocolHierarchyDialog::on_actionCopyAsCsv_triggered()
{
QString csv;
QTextStream stream(&csv, QIODevice::Text);
QTreeWidgetItemIterator iter(ui->hierStatsTreeWidget);
bool first = true;
while (*iter) {
QStringList separated_value;
QTreeWidgetItem *item = first ? NULL : (*iter);
foreach (QVariant v, protoHierRowData(item)) {
if (!v.isValid()) {
separated_value << "\"\"";
} else if (v.userType() == QMetaType::QString) {
separated_value << QString("\"%1\"").arg(v.toString());
} else {
separated_value << v.toString();
}
}
stream << separated_value.join(",") << '\n';
if (!first) ++iter;
first = false;
}
mainApp->clipboard()->setText(stream.readAll());
}
void ProtocolHierarchyDialog::on_actionCopyAsYaml_triggered()
{
QString yaml;
QTextStream stream(&yaml, QIODevice::Text);
QTreeWidgetItemIterator iter(ui->hierStatsTreeWidget);
bool first = true;
stream << "---" << '\n';
while (*iter) {
QTreeWidgetItem *item = first ? NULL : (*iter);
stream << "-" << '\n';
foreach (QVariant v, protoHierRowData(item)) {
stream << " - " << v.toString() << '\n';
}
if (!first) ++iter;
first = false;
}
mainApp->clipboard()->setText(stream.readAll());
}
void ProtocolHierarchyDialog::on_actionCopyProtoList_triggered()
{
QString plist;
QTextStream stream(&plist, QIODevice::Text);
bool first = true;
QSetIterator<QString> iter(used_protos_);
while (iter.hasNext()) {
if (!first) stream << ',';
stream << iter.next();
first = false;
}
mainApp->clipboard()->setText(stream.readAll());
}
void ProtocolHierarchyDialog::on_actionDisableProtos_triggered()
{
proto_disable_all();
QSetIterator<QString> iter(used_protos_);
while (iter.hasNext()) {
proto_enable_proto_by_name(iter.next().toStdString().c_str());
}
/* Note that we aren't saving the changes here; they only apply
* to the current dissection.
* (Though if the user goes to the Enabled Protocols dialog and
* makes changes, these changes as well as the user's will be saved.)
*/
proto_revert_->setEnabled(enabled_protos_unsaved_changes());
QString hint = "<small><i>"
+ tr("Unused protocols have been disabled.")
+ "</i></small>";
ui->hintLabel->setText(hint);
// If we've done everything right, nothing should change.
//wsApp->emitAppSignal(WiresharkApplication::PacketDissectionChanged);
}
void ProtocolHierarchyDialog::on_actionRevertProtos_triggered()
{
proto_reenable_all();
read_enabled_and_disabled_lists();
proto_revert_->setEnabled(enabled_protos_unsaved_changes());
QString hint = "<small><i>"
+ tr("Protocol changes have been reverted.")
+ "</i></small>";
ui->hintLabel->setText(hint);
// If we've done everything right, nothing should change.
//wsApp->emitAppSignal(WiresharkApplication::PacketDissectionChanged);
}
void ProtocolHierarchyDialog::on_buttonBox_helpRequested()
{
mainApp->helpTopicAction(HELP_STATS_PROTO_HIERARCHY_DIALOG);
} |
C/C++ | wireshark/ui/qt/protocol_hierarchy_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 PROTOCOL_HIERARCHY_DIALOG_H
#define PROTOCOL_HIERARCHY_DIALOG_H
#include <QMenu>
#include <QSet>
#include "filter_action.h"
#include <ui/qt/models/percent_bar_delegate.h>
#include "wireshark_dialog.h"
class QPushButton;
class QTreeWidgetItem;
namespace Ui {
class ProtocolHierarchyDialog;
}
class ProtocolHierarchyDialog : public WiresharkDialog
{
Q_OBJECT
public:
explicit ProtocolHierarchyDialog(QWidget &parent, CaptureFile &cf);
~ProtocolHierarchyDialog();
signals:
void filterAction(QString filter, FilterAction::Action action, FilterAction::ActionType type);
private slots:
void showProtoHierMenu(QPoint pos);
void filterActionTriggered();
void on_actionCopyAsCsv_triggered();
void on_actionCopyAsYaml_triggered();
void on_actionCopyProtoList_triggered();
void on_actionDisableProtos_triggered();
void on_actionRevertProtos_triggered();
void on_buttonBox_helpRequested();
private:
Ui::ProtocolHierarchyDialog *ui;
QAction *proto_disable_;
QAction *proto_revert_;
QMenu ctx_menu_;
PercentBarDelegate percent_bar_delegate_;
QString display_filter_;
QSet<QString> used_protos_;
// Callback for g_node_children_foreach
static void addTreeNode(GNode *node, gpointer data);
void updateWidgets();
QList<QVariant> protoHierRowData(QTreeWidgetItem *item) const;
};
#endif // PROTOCOL_HIERARCHY_DIALOG_H |
User Interface | wireshark/ui/qt/protocol_hierarchy_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ProtocolHierarchyDialog</class>
<widget class="QDialog" name="ProtocolHierarchyDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>620</width>
<height>480</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTreeWidget" name="hierStatsTreeWidget">
<property name="uniformRowHeights">
<bool>true</bool>
</property>
<attribute name="headerDefaultSectionSize">
<number>50</number>
</attribute>
<attribute name="headerShowSortIndicator" stdset="0">
<bool>false</bool>
</attribute>
<column>
<property name="text">
<string>Protocol</string>
</property>
</column>
<column>
<property name="text">
<string>Percent Packets</string>
</property>
</column>
<column>
<property name="text">
<string>Packets</string>
</property>
</column>
<column>
<property name="text">
<string>Percent Bytes</string>
</property>
</column>
<column>
<property name="text">
<string>Bytes</string>
</property>
</column>
<column>
<property name="text">
<string>Bits/s</string>
</property>
</column>
<column>
<property name="text">
<string>End Packets</string>
</property>
</column>
<column>
<property name="text">
<string>End Bytes</string>
</property>
</column>
<column>
<property name="text">
<string>End Bits/s</string>
</property>
</column>
<column>
<property name="text">
<string>PDUs</string>
</property>
</column>
</widget>
</item>
<item>
<widget class="QLabel" name="hintLabel">
<property name="text">
<string><small><i>A hint.</i></small></string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Close|QDialogButtonBox::Help</set>
</property>
</widget>
</item>
</layout>
<action name="actionCopyAsCsv">
<property name="text">
<string>Copy as CSV</string>
</property>
<property name="toolTip">
<string>Copy stream list as CSV.</string>
</property>
</action>
<action name="actionCopyAsYaml">
<property name="text">
<string>Copy as YAML</string>
</property>
<property name="toolTip">
<string>Copy stream list as YAML.</string>
</property>
</action>
<action name="actionCopyProtoList">
<property name="text">
<string>Copy short names</string>
</property>
<property name="toolTip">
<string>Copy short protocol names in use.</string>
</property>
</action>
<action name="actionDisableProtos">
<property name="text">
<string>Disable unused protocols</string>
</property>
<property name="toolTip">
<string>Disable all protocols but those listed.</string>
</property>
</action>
<action name="actionRevertProtos">
<property name="text">
<string>Re-enable unused protocols</string>
</property>
<property name="toolTip">
<string>Re-enable protocols that were disabled in this dialog.</string>
</property>
</action>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>ProtocolHierarchyDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>ProtocolHierarchyDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/protocol_preferences_menu.cpp | /* protocol_preferences_menu.h
*
* 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/prefs-int.h>
#include <epan/proto.h>
#include <cfile.h>
#include <ui/commandline.h>
#include <ui/preference_utils.h>
#include <wsutil/utf8_entities.h>
#include "protocol_preferences_menu.h"
#include <ui/qt/models/enabled_protocols_model.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "uat_dialog.h"
#include "main_application.h"
#include "main_window.h"
#include <QActionGroup>
#include <QMainWindow>
// To do:
// - Elide really long items?
// - Handle color prefs.
class BoolPreferenceAction : public QAction
{
public:
BoolPreferenceAction(pref_t *pref, QObject *parent=0) :
QAction(parent),
pref_(pref)
{
setText(prefs_get_title(pref_));
setCheckable(true);
setChecked(prefs_get_bool_value(pref_, pref_current));
}
unsigned int setBoolValue() {
return prefs_set_bool_value(pref_, isChecked(), pref_current);
}
pref_t *getPref() { return pref_; }
private:
pref_t *pref_;
};
class EnumPreferenceAction : public QAction
{
public:
EnumPreferenceAction(pref_t *pref, const char *title, int enumval, QActionGroup *ag, QObject *parent=0) :
QAction(parent),
pref_(pref),
enumval_(enumval)
{
setText(title);
setActionGroup(ag);
setCheckable(true);
}
unsigned int setEnumValue() {
return prefs_set_enum_value(pref_, enumval_, pref_current);
}
pref_t *getPref() { return pref_; }
private:
pref_t *pref_;
int enumval_;
};
class EnumCustomTCPOverridePreferenceAction : public QAction
{
public:
EnumCustomTCPOverridePreferenceAction(pref_t *pref, const char *title, int enumval, QActionGroup *ag, QObject *parent=0) :
QAction(parent),
pref_(pref),
enumval_(enumval)
{
setText(title);
setActionGroup(ag);
setCheckable(true);
}
unsigned int setEnumValue() {
return prefs_set_enum_value(pref_, enumval_, pref_current);
}
int getEnumValue() { return enumval_; }
pref_t *getPref() { return pref_; }
private:
pref_t *pref_;
int enumval_;
};
class UatPreferenceAction : public QAction
{
public:
UatPreferenceAction(pref_t *pref, QObject *parent=0) :
QAction(parent),
pref_(pref)
{
setText(QString("%1" UTF8_HORIZONTAL_ELLIPSIS).arg(prefs_get_title(pref_)));
}
void showUatDialog() {
UatDialog *uat_dlg = new UatDialog(qobject_cast<QWidget*>(parent()), prefs_get_uat_value(pref_));
connect(uat_dlg, SIGNAL(destroyed(QObject*)), mainApp, SLOT(flushAppSignals()));
uat_dlg->setWindowModality(Qt::ApplicationModal);
uat_dlg->setAttribute(Qt::WA_DeleteOnClose);
uat_dlg->show();
}
pref_t *getPref() { return pref_; }
private:
pref_t *pref_;
};
// Preference requires an external editor (PreferenceEditorFrame)
class EditorPreferenceAction : public QAction
{
public:
EditorPreferenceAction(pref_t *pref, QObject *parent=0) :
QAction(parent),
pref_(pref)
{
QString title = prefs_get_title(pref_);
title.append(QString(": %1" UTF8_HORIZONTAL_ELLIPSIS).arg(gchar_free_to_qstring(prefs_pref_to_str(pref_, pref_current))));
setText(title);
}
pref_t *pref() { return pref_; }
private:
pref_t *pref_;
};
extern "C" {
// Preference callback
static guint
add_prefs_menu_item(pref_t *pref, gpointer menu_ptr)
{
ProtocolPreferencesMenu *pp_menu = static_cast<ProtocolPreferencesMenu *>(menu_ptr);
if (!pp_menu) return 1;
pp_menu->addMenuItem(pref);
return 0;
}
}
ProtocolPreferencesMenu::ProtocolPreferencesMenu()
{
setTitle(tr("Protocol Preferences"));
setModule(NULL);
}
ProtocolPreferencesMenu::ProtocolPreferencesMenu(const QString &title, const QString &module_name, QWidget *parent) :
QMenu(title, parent)
{
setModule(module_name);
}
void ProtocolPreferencesMenu::setModule(const QString module_name)
{
QAction *action;
int proto_id = -1;
if (!module_name.isEmpty()) {
proto_id = proto_get_id_by_filter_name(module_name.toUtf8().constData());
}
clear();
module_name_.clear();
module_ = NULL;
protocol_ = find_protocol_by_id(proto_id);
const QString long_name = proto_get_protocol_long_name(protocol_);
const QString short_name = proto_get_protocol_short_name(protocol_);
if (module_name.isEmpty() || proto_id < 0 || !protocol_) {
action = addAction(tr("No protocol preferences available"));
action->setDisabled(true);
return;
}
QAction *disable_action = new QAction(tr("Disable %1").arg(short_name), this);
connect(disable_action, SIGNAL(triggered(bool)), this, SLOT(disableProtocolTriggered()));
disable_action->setDisabled(!proto_can_toggle_protocol(proto_id));
module_ = prefs_find_module(module_name.toUtf8().constData());
if (!module_ || !prefs_is_registered_protocol(module_name.toUtf8().constData())) {
action = addAction(tr("%1 has no preferences").arg(long_name));
action->setDisabled(true);
addSeparator();
addAction(disable_action);
return;
}
module_name_ = module_name;
action = addAction(tr("Open %1 preferences…").arg(long_name));
if (module_->use_gui) {
action->setData(QString(module_name));
connect(action, SIGNAL(triggered(bool)), this, SLOT(modulePreferencesTriggered()));
} else {
action->setDisabled(true);
}
addSeparator();
prefs_pref_foreach(module_, add_prefs_menu_item, this);
if (!actions().last()->isSeparator()) {
addSeparator();
}
addAction(disable_action);
}
void ProtocolPreferencesMenu::addMenuItem(preference *pref)
{
switch (prefs_get_type(pref)) {
case PREF_BOOL:
{
BoolPreferenceAction *bpa = new BoolPreferenceAction(pref, this);
addAction(bpa);
connect(bpa, SIGNAL(triggered(bool)), this, SLOT(boolPreferenceTriggered()));
break;
}
case PREF_ENUM:
{
QMenu *enum_menu = addMenu(prefs_get_title(pref));
const enum_val_t *enum_valp = prefs_get_enumvals(pref);
if (enum_valp && enum_valp->name) {
QActionGroup *ag = new QActionGroup(this);
while (enum_valp->name) {
EnumPreferenceAction *epa = new EnumPreferenceAction(pref, enum_valp->description, enum_valp->value, ag, this);
if (prefs_get_enum_value(pref, pref_current) == enum_valp->value) {
epa->setChecked(true);
}
enum_menu->addAction(epa);
connect(epa, SIGNAL(triggered(bool)), this, SLOT(enumPreferenceTriggered()));
enum_valp++;
}
}
break;
}
case PREF_UINT:
case PREF_STRING:
case PREF_SAVE_FILENAME:
case PREF_OPEN_FILENAME:
case PREF_DIRNAME:
case PREF_RANGE:
case PREF_DECODE_AS_UINT:
case PREF_DECODE_AS_RANGE:
case PREF_PASSWORD:
{
EditorPreferenceAction *epa = new EditorPreferenceAction(pref, this);
addAction(epa);
connect(epa, SIGNAL(triggered(bool)), this, SLOT(editorPreferenceTriggered()));
break;
}
case PREF_UAT:
{
UatPreferenceAction *upa = new UatPreferenceAction(pref, this);
addAction(upa);
connect(upa, SIGNAL(triggered(bool)), this, SLOT(uatPreferenceTriggered()));
break;
}
case PREF_CUSTOM:
case PREF_STATIC_TEXT:
case PREF_OBSOLETE:
break;
case PREF_PROTO_TCP_SNDAMB_ENUM:
{
int override_id = -1;
/* ensure we have access to MainWindow, and indirectly to the selection */
if (mainApp) {
QWidget * mainWin = mainApp->mainWindow();
if (qobject_cast<MainWindow *>(mainWin)) {
frame_data * fdata = qobject_cast<MainWindow *>(mainWin)->frameDataForRow((qobject_cast<MainWindow *>(mainWin)->selectedRows()).at(0));
if(fdata) {
override_id = fdata->tcp_snd_manual_analysis;
}
}
}
if (override_id != -1) {
QMenu *enum_menu = addMenu(prefs_get_title(pref));
const enum_val_t *enum_valp = prefs_get_enumvals(pref);
if (enum_valp && enum_valp->name) {
QActionGroup *ag = new QActionGroup(this);
while (enum_valp->name) {
EnumCustomTCPOverridePreferenceAction *epa = new EnumCustomTCPOverridePreferenceAction(pref, enum_valp->description, enum_valp->value, ag, this);
if (override_id>=0) {
if(override_id==enum_valp->value)
epa->setChecked(true);
}
else {
if(enum_valp->value == 0)
epa->setChecked(true);
}
enum_menu->addAction(epa);
connect(epa, SIGNAL(triggered(bool)), this, SLOT(enumCustomTCPOverridePreferenceTriggered()));
enum_valp++;
}
}
}
break;
}
default:
// A type we currently don't handle. Just open the prefs dialog.
QString title = QString("%1" UTF8_HORIZONTAL_ELLIPSIS).arg(prefs_get_title(pref));
QAction *mpa = addAction(title);
connect(mpa, SIGNAL(triggered(bool)), this, SLOT(modulePreferencesTriggered()));
break;
}
}
void ProtocolPreferencesMenu::disableProtocolTriggered()
{
EnabledProtocolsModel::disableProtocol(protocol_);
}
void ProtocolPreferencesMenu::modulePreferencesTriggered()
{
if (!module_name_.isEmpty()) {
emit showProtocolPreferences(module_name_);
}
}
void ProtocolPreferencesMenu::editorPreferenceTriggered()
{
EditorPreferenceAction *epa = static_cast<EditorPreferenceAction *>(QObject::sender());
if (!epa) return;
if (epa->pref() && module_) {
emit editProtocolPreference(epa->pref(), module_);
}
}
void ProtocolPreferencesMenu::boolPreferenceTriggered()
{
BoolPreferenceAction *bpa = static_cast<BoolPreferenceAction *>(QObject::sender());
if (!bpa) return;
module_->prefs_changed_flags |= bpa->setBoolValue();
unsigned int changed_flags = module_->prefs_changed_flags;
prefs_apply(module_);
prefs_main_write();
commandline_options_drop(module_->name, prefs_get_name(bpa->getPref()));
if (changed_flags & PREF_EFFECT_FIELDS) {
mainApp->emitAppSignal(MainApplication::FieldsChanged);
}
/* Protocol preference changes almost always affect dissection,
so don't bother checking flags */
mainApp->emitAppSignal(MainApplication::PacketDissectionChanged);
}
void ProtocolPreferencesMenu::enumPreferenceTriggered()
{
EnumPreferenceAction *epa = static_cast<EnumPreferenceAction *>(QObject::sender());
if (!epa) return;
unsigned int changed_flags = epa->setEnumValue();
if (changed_flags) { // Changed
module_->prefs_changed_flags |= changed_flags;
prefs_apply(module_);
prefs_main_write();
commandline_options_drop(module_->name, prefs_get_name(epa->getPref()));
if (changed_flags & PREF_EFFECT_FIELDS) {
mainApp->emitAppSignal(MainApplication::FieldsChanged);
}
/* Protocol preference changes almost always affect dissection,
so don't bother checking flags */
mainApp->emitAppSignal(MainApplication::PacketDissectionChanged);
}
}
void ProtocolPreferencesMenu::enumCustomTCPOverridePreferenceTriggered()
{
EnumCustomTCPOverridePreferenceAction *epa = static_cast<EnumCustomTCPOverridePreferenceAction *>(QObject::sender());
if (!epa) return;
/* ensure we have access to MainWindow, and indirectly to the selection */
if (mainApp) {
QWidget * mainWin = mainApp->mainWindow();
if (qobject_cast<MainWindow *>(mainWin)) {
frame_data * fdata = qobject_cast<MainWindow *>(mainWin)->frameDataForRow((qobject_cast<MainWindow *>(mainWin)->selectedRows()).at(0));
if(!fdata)
return;
if (fdata->tcp_snd_manual_analysis != epa->getEnumValue()) { // Changed
fdata->tcp_snd_manual_analysis = epa->getEnumValue();
/* Protocol preference changes almost always affect dissection,
so don't bother checking flags */
mainApp->emitAppSignal(MainApplication::FieldsChanged);
mainApp->emitAppSignal(MainApplication::PacketDissectionChanged);
}
}
}
}
void ProtocolPreferencesMenu::uatPreferenceTriggered()
{
UatPreferenceAction *upa = static_cast<UatPreferenceAction *>(QObject::sender());
if (!upa) return;
upa->showUatDialog();
} |
C/C++ | wireshark/ui/qt/protocol_preferences_menu.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __PROTOCOL_PREFERENCES_MENU_H__
#define __PROTOCOL_PREFERENCES_MENU_H__
#include <QMenu>
struct _protocol;
struct pref_module;
struct preference;
class ProtocolPreferencesMenu : public QMenu
{
Q_OBJECT
public:
ProtocolPreferencesMenu();
ProtocolPreferencesMenu(const QString &title, const QString &module_name, QWidget *parent = nullptr);
void setModule(const QString module_name);
void addMenuItem(struct preference *pref);
signals:
void showProtocolPreferences(const QString module_name);
void editProtocolPreference(struct preference *pref, struct pref_module *module);
private:
QString module_name_;
struct pref_module *module_;
struct _protocol *protocol_;
private slots:
void disableProtocolTriggered();
void modulePreferencesTriggered();
void editorPreferenceTriggered();
void boolPreferenceTriggered();
void enumPreferenceTriggered();
void uatPreferenceTriggered();
void enumCustomTCPOverridePreferenceTriggered();
};
#endif // __PROTOCOL_PREFERENCES_MENU_H__ |
C++ | wireshark/ui/qt/proto_tree.cpp | /* proto_tree.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/proto_tree.h>
#include <ui/qt/models/proto_tree_model.h>
#include <epan/ftypes/ftypes.h>
#include <epan/prefs.h>
#include <epan/epan.h>
#include <epan/epan_dissect.h>
#include <cfile.h>
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/utils/variant_pointer.h>
#include <ui/qt/utils/wireshark_mime_data.h>
#include <ui/qt/widgets/drag_label.h>
#include <ui/qt/widgets/wireshark_file_dialog.h>
#include <ui/qt/show_packet_bytes_dialog.h>
#include <ui/qt/filter_action.h>
#include <ui/qt/follow_stream_action.h>
#include <ui/all_files_wildcard.h>
#include <ui/alert_box.h>
#include <ui/urls.h>
#include "main_application.h"
#include <QApplication>
#include <QContextMenuEvent>
#include <QDesktopServices>
#include <QHeaderView>
#include <QItemSelectionModel>
#include <QScrollBar>
#include <QStack>
#include <QUrl>
#include <QClipboard>
#include <QWindow>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
// To do:
// - Fix "apply as filter" behavior.
ProtoTree::ProtoTree(QWidget *parent, epan_dissect_t *edt_fixed) :
QTreeView(parent),
proto_tree_model_(new ProtoTreeModel(this)),
column_resize_timer_(0),
cap_file_(NULL),
edt_(edt_fixed)
{
setAccessibleName(tr("Packet details"));
// Leave the uniformRowHeights property as-is (false) since items might
// have multiple lines (e.g. packet comments). If this slows things down
// too much we should add a custom delegate which handles SizeHintRole
// similar to PacketListModel::data.
setHeaderHidden(true);
#if !defined(Q_OS_WIN)
setStyleSheet(QString(
"QTreeView:item:hover {"
" background-color: %1;"
" color: palette(text);"
"}").arg(ColorUtils::hoverBackground().name(QColor::HexArgb)));
#endif
// Shrink down to a small but nonzero size in the main splitter.
int one_em = fontMetrics().height();
setMinimumSize(one_em, one_em);
setModel(proto_tree_model_);
connect(this, SIGNAL(expanded(QModelIndex)), this, SLOT(syncExpanded(QModelIndex)));
connect(this, SIGNAL(collapsed(QModelIndex)), this, SLOT(syncCollapsed(QModelIndex)));
connect(this, SIGNAL(clicked(QModelIndex)),
this, SLOT(itemClicked(QModelIndex)));
connect(this, SIGNAL(doubleClicked(QModelIndex)),
this, SLOT(itemDoubleClicked(QModelIndex)));
connect(&proto_prefs_menu_, SIGNAL(showProtocolPreferences(QString)),
this, SIGNAL(showProtocolPreferences(QString)));
connect(&proto_prefs_menu_, SIGNAL(editProtocolPreference(preference*,pref_module*)),
this, SIGNAL(editProtocolPreference(preference*,pref_module*)));
// resizeColumnToContents checks 1000 items by default. The user might
// have scrolled to an area with a different width at this point.
connect(verticalScrollBar(), SIGNAL(sliderReleased()),
this, SLOT(updateContentWidth()));
connect(mainApp, SIGNAL(appInitialized()), this, SLOT(connectToMainWindow()));
viewport()->installEventFilter(this);
}
void ProtoTree::clear() {
proto_tree_model_->setRootNode(NULL);
updateContentWidth();
}
void ProtoTree::connectToMainWindow()
{
if (mainApp->mainWindow())
{
connect(mainApp->mainWindow(), SIGNAL(fieldSelected(FieldInformation *)),
this, SLOT(selectedFieldChanged(FieldInformation *)));
connect(mainApp->mainWindow(), SIGNAL(framesSelected(QList<int>)),
this, SLOT(selectedFrameChanged(QList<int>)));
}
}
void ProtoTree::ctxCopyVisibleItems()
{
bool selected_tree = false;
QAction * send = qobject_cast<QAction *>(sender());
if (send && send->property("selected_tree").isValid())
selected_tree = true;
QString clip;
if (selected_tree && selectionModel()->hasSelection())
clip = toString(selectionModel()->selectedIndexes().first());
else
clip = toString();
if (clip.length() > 0)
mainApp->clipboard()->setText(clip);
}
void ProtoTree::ctxCopyAsFilter()
{
QModelIndex idx = selectionModel()->selectedIndexes().first();
FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(idx));
if (finfo.isValid())
{
epan_dissect_t *edt = cap_file_ ? cap_file_->edt : edt_;
char *field_filter = proto_construct_match_selected_string(finfo.fieldInfo(), edt);
QString filter(field_filter);
wmem_free(Q_NULLPTR, field_filter);
if (filter.length() > 0)
mainApp->clipboard()->setText(filter);
}
}
void ProtoTree::ctxCopySelectedInfo()
{
int val = -1;
QString clip;
QAction * send = qobject_cast<QAction *>(sender());
if (send && send->property("field_type").isValid())
val = send->property("field_type").toInt();
QModelIndex idx = selectionModel()->selectedIndexes().first();
FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(idx));
if (! finfo.isValid())
return;
switch (val)
{
case ProtoTree::Name:
clip.append(finfo.headerInfo().abbreviation);
break;
case ProtoTree::Description:
clip = idx.data(Qt::DisplayRole).toString();
break;
case ProtoTree::Value:
{
epan_dissect_t *edt = cap_file_ ? cap_file_->edt : edt_;
gchar* field_str = get_node_field_value(finfo.fieldInfo(), edt);
clip.append(field_str);
g_free(field_str);
}
break;
default:
break;
}
if (clip.length() > 0)
mainApp->clipboard()->setText(clip);
}
void ProtoTree::ctxOpenUrlWiki()
{
QUrl url;
bool is_field_reference = false;
QAction * send = qobject_cast<QAction *>(sender());
if (send && send->property("field_reference").isValid())
is_field_reference = send->property("field_reference").toBool();
QModelIndex idx = selectionModel()->selectedIndexes().first();
FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(idx));
int field_id = finfo.headerInfo().id;
if (!proto_registrar_is_protocol(field_id) && (field_id != hf_text_only)) {
field_id = proto_registrar_get_parent(field_id);
}
const QString proto_abbrev = proto_registrar_get_abbrev(field_id);
if (! is_field_reference)
{
int ret = QMessageBox::question(this, mainApp->windowTitleString(tr("Wiki Page for %1").arg(proto_abbrev)),
tr("<p>The Wireshark Wiki is maintained by the community.</p>"
"<p>The page you are about to load might be wonderful, "
"incomplete, wrong, or nonexistent.</p>"
"<p>Proceed to the wiki?</p>"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if (ret != QMessageBox::Yes) return;
url = QString(WS_WIKI_URL("%1")).arg(proto_abbrev);
}
else
{
if (field_id != hf_text_only) {
url = QString(WS_DOCS_URL "dfref/%1/%2")
.arg(proto_abbrev[0])
.arg(proto_abbrev);
} else {
QMessageBox::information(this, tr("Not a field or protocol"),
tr("No field reference available for text labels."),
QMessageBox::Ok);
}
}
QDesktopServices::openUrl(url);
}
void ProtoTree::contextMenuEvent(QContextMenuEvent *event)
{
QModelIndex index = indexAt(event->pos());
if (! index.isValid())
return;
// We're in a PacketDialog
bool buildForDialog = false;
if (! window()->findChild<QAction *>("actionViewExpandSubtrees"))
buildForDialog = true;
QMenu * ctx_menu = new QMenu(this);
ctx_menu->setAttribute(Qt::WA_DeleteOnClose);
ctx_menu->setProperty("toolTipsVisible", QVariant::fromValue(true));
QMenu *main_menu_item, *submenu;
QAction *action;
bool have_subtree = false;
FieldInformation *finfo = new FieldInformation(proto_tree_model_->protoNodeFromIndex(index), ctx_menu);
field_info * fi = finfo->fieldInfo();
bool is_selected = false;
epan_dissect_t *edt = cap_file_ ? cap_file_->edt : edt_;
if (cap_file_ && cap_file_->finfo_selected == fi)
is_selected = true;
else if (! window()->findChild<QAction *>("actionViewExpandSubtrees"))
is_selected = true;
if (is_selected)
{
if (fi && fi->tree_type != -1) {
have_subtree = true;
}
}
action = ctx_menu->addAction(tr("Expand Subtrees"), this, SLOT(expandSubtrees()));
action->setEnabled(have_subtree);
action = ctx_menu->addAction(tr("Collapse Subtrees"), this, SLOT(collapseSubtrees()));
action->setEnabled(have_subtree);
ctx_menu->addAction(tr("Expand All"), this, SLOT(expandAll()));
ctx_menu->addAction(tr("Collapse All"), this, SLOT(collapseAll()));
ctx_menu->addSeparator();
if (! buildForDialog)
{
action = window()->findChild<QAction *>("actionAnalyzeApplyAsColumn");
ctx_menu->addAction(action);
ctx_menu->addSeparator();
}
char * selectedfilter = proto_construct_match_selected_string(finfo->fieldInfo(), edt);
bool can_match_selected = proto_can_match_selected(finfo->fieldInfo(), edt);
ctx_menu->addMenu(FilterAction::createFilterMenu(FilterAction::ActionApply, selectedfilter, can_match_selected, ctx_menu));
ctx_menu->addMenu(FilterAction::createFilterMenu(FilterAction::ActionPrepare, selectedfilter, can_match_selected, ctx_menu));
if (selectedfilter)
wmem_free(Q_NULLPTR, selectedfilter);
if (! buildForDialog)
{
QMenu *main_conv_menu = window()->findChild<QMenu *>("menuConversationFilter");
conv_menu_.setTitle(main_conv_menu->title());
conv_menu_.clear();
foreach (QAction *action, main_conv_menu->actions()) {
conv_menu_.addAction(action);
}
ctx_menu->addMenu(&conv_menu_);
colorize_menu_.setTitle(tr("Colorize with Filter"));
ctx_menu->addMenu(&colorize_menu_);
/* XXX: Should we just get a Follow action (if it exists) for the currently
* selected field info, similar to preferences and filters?
*/
main_menu_item = window()->findChild<QMenu *>("menuFollow");
if (main_menu_item) {
submenu = new QMenu(main_menu_item->title(), ctx_menu);
ctx_menu->addMenu(submenu);
foreach (FollowStreamAction *follow_action, main_menu_item->findChildren<FollowStreamAction *>()) {
if (follow_action->isEnabled()) {
submenu->addAction(follow_action);
}
}
}
ctx_menu->addSeparator();
}
submenu = ctx_menu->addMenu(tr("Copy"));
submenu->addAction(tr("All Visible Items"), this, SLOT(ctxCopyVisibleItems()));
action = submenu->addAction(tr("All Visible Selected Tree Items"), this, SLOT(ctxCopyVisibleItems()));
action->setProperty("selected_tree", QVariant::fromValue(true));
action = submenu->addAction(tr("Description"), this, SLOT(ctxCopySelectedInfo()));
action->setProperty("field_type", ProtoTree::Description);
action = submenu->addAction(tr("Field Name"), this, SLOT(ctxCopySelectedInfo()));
action->setProperty("field_type", ProtoTree::Name);
action = submenu->addAction(tr("Value"), this, SLOT(ctxCopySelectedInfo()));
action->setProperty("field_type", ProtoTree::Value);
submenu->addSeparator();
submenu->addAction(tr("As Filter"), this, SLOT(ctxCopyAsFilter()));
submenu->addSeparator();
QActionGroup * copyEntries = DataPrinter::copyActions(this, finfo);
submenu->addActions(copyEntries->actions());
ctx_menu->addSeparator();
if (! buildForDialog)
{
action = window()->findChild<QAction *>("actionAnalyzeShowPacketBytes");
ctx_menu->addAction(action);
action = window()->findChild<QAction *>("actionFileExportPacketBytes");
ctx_menu->addAction(action);
ctx_menu->addSeparator();
}
int field_id = finfo->headerInfo().id;
action = ctx_menu->addAction(tr("Wiki Protocol Page"), this, SLOT(ctxOpenUrlWiki()));
action->setProperty("toolTip", QString(WS_WIKI_URL("Protocols/%1")).arg(proto_registrar_get_abbrev(field_id)));
action = ctx_menu->addAction(tr("Filter Field Reference"), this, SLOT(ctxOpenUrlWiki()));
action->setProperty("field_reference", QVariant::fromValue(true));
if (field_id != hf_text_only) {
action->setEnabled(true);
const QString proto_abbrev = proto_registrar_get_abbrev(field_id);
action->setProperty("toolTip", QString(WS_DOCS_URL "dfref/%1/%2")
.arg(proto_abbrev[0])
.arg(proto_abbrev));
}
else {
action->setEnabled(false);
action->setProperty("toolTip", tr("No field reference available for text labels."));
}
ctx_menu->addMenu(&proto_prefs_menu_);
ctx_menu->addSeparator();
if (! buildForDialog)
{
QAction *decode_as_ = window()->findChild<QAction *>("actionAnalyzeDecodeAs");
ctx_menu->addAction(decode_as_);
decode_as_->setProperty("create_new", QVariant::fromValue(true));
ctx_menu->addAction(window()->findChild<QAction *>("actionGoGoToLinkedPacket"));
ctx_menu->addAction(window()->findChild<QAction *>("actionContextShowLinkedPacketInNewWindow"));
}
// The "text only" header field will not give preferences for the selected protocol.
// Use parent in this case.
ProtoNode *node = proto_tree_model_->protoNodeFromIndex(index);
while (node && node->isValid() && node->protoNode()->finfo && node->protoNode()->finfo->hfinfo && node->protoNode()->finfo->hfinfo->id == hf_text_only) {
node = node->parentNode();
}
FieldInformation pref_finfo(node);
proto_prefs_menu_.setModule(pref_finfo.moduleName());
ctx_menu->popup(event->globalPos());
}
void ProtoTree::timerEvent(QTimerEvent *event)
{
if (event->timerId() == column_resize_timer_) {
killTimer(column_resize_timer_);
column_resize_timer_ = 0;
resizeColumnToContents(0);
} else {
QTreeView::timerEvent(event);
}
}
// resizeColumnToContents checks 1000 items by default. The user might
// have scrolled to an area with a different width at this point.
void ProtoTree::keyReleaseEvent(QKeyEvent *event)
{
if (event->isAutoRepeat()) return;
switch(event->key()) {
case Qt::Key_Up:
case Qt::Key_Down:
case Qt::Key_PageUp:
case Qt::Key_PageDown:
case Qt::Key_Home:
case Qt::Key_End:
updateContentWidth();
break;
default:
break;
}
}
void ProtoTree::updateContentWidth()
{
if (column_resize_timer_ == 0) {
column_resize_timer_ = startTimer(0);
}
}
void ProtoTree::setMonospaceFont(const QFont &mono_font)
{
setFont(mono_font);
update();
}
void ProtoTree::foreachTreeNode(proto_node *node, gpointer proto_tree_ptr)
{
ProtoTree *tree_view = static_cast<ProtoTree *>(proto_tree_ptr);
ProtoTreeModel *model = qobject_cast<ProtoTreeModel *>(tree_view->model());
if (!tree_view || !model) {
return;
}
// Related frames - there might be hidden FT_FRAMENUM nodes, so do this
// for each proto_node and not just the ProtoNodes in the model
if (node->finfo->hfinfo->type == FT_FRAMENUM) {
ft_framenum_type_t framenum_type = (ft_framenum_type_t)GPOINTER_TO_INT(node->finfo->hfinfo->strings);
tree_view->emitRelatedFrame(fvalue_get_uinteger(node->finfo->value), framenum_type);
}
proto_tree_children_foreach(node, foreachTreeNode, proto_tree_ptr);
}
void ProtoTree::foreachExpand(const QModelIndex &index = QModelIndex()) {
// Restore expanded state. (Note QModelIndex() refers to the root node)
int children = proto_tree_model_->rowCount(index);
QModelIndex childIndex;
for (int child = 0; child < children; child++) {
childIndex = proto_tree_model_->index(child, 0, index);
if (childIndex.isValid()) {
ProtoNode *node = proto_tree_model_->protoNodeFromIndex(childIndex);
if (node && node->isValid() && tree_expanded(node->protoNode()->finfo->tree_type)) {
expand(childIndex);
}
foreachExpand(childIndex);
}
}
}
// setRootNode sets the new contents for the protocol tree and subsequently
// restores the previously expanded state.
void ProtoTree::setRootNode(proto_node *root_node) {
// We track item expansion using proto.c:tree_is_expanded.
// Replace any existing (possibly invalidated) proto tree by the new tree.
// The expanded state will be reset as well and will be re-expanded below.
proto_tree_model_->setRootNode(root_node);
disconnect(this, SIGNAL(expanded(QModelIndex)), this, SLOT(syncExpanded(QModelIndex)));
proto_tree_children_foreach(root_node, foreachTreeNode, this);
foreachExpand();
connect(this, SIGNAL(expanded(QModelIndex)), this, SLOT(syncExpanded(QModelIndex)));
updateContentWidth();
}
void ProtoTree::emitRelatedFrame(int related_frame, ft_framenum_type_t framenum_type)
{
emit relatedFrame(related_frame, framenum_type);
}
void ProtoTree::autoScrollTo(const QModelIndex &index)
{
selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
if (!index.isValid()) {
return;
}
// ensure item is visible (expanding its parents as needed).
scrollTo(index);
}
// XXX We select the first match, which might not be the desired item.
void ProtoTree::goToHfid(int hfid)
{
QModelIndex index = proto_tree_model_->findFirstHfid(hfid);
autoScrollTo(index);
}
void ProtoTree::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
QTreeView::selectionChanged(selected, deselected);
if (selected.isEmpty()) {
emit fieldSelected(0);
return;
}
QModelIndex index = selected.indexes().first();
saveSelectedField(index);
// Find and highlight the protocol bytes. select above won't call
// selectionChanged if the current and selected indexes are the same
// so we do this here.
FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(index), this);
if (finfo.isValid()) {
QModelIndex parent = index;
while (parent.isValid() && parent.parent().isValid()) {
parent = parent.parent();
}
if (parent.isValid()) {
FieldInformation parent_finfo(proto_tree_model_->protoNodeFromIndex(parent));
finfo.setParentField(parent_finfo.fieldInfo());
}
emit fieldSelected(&finfo);
}
}
void ProtoTree::syncExpanded(const QModelIndex &index) {
FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(index));
if (!finfo.isValid()) return;
/*
* Nodes with "finfo->tree_type" of -1 have no ett_ value, and
* are thus presumably leaf nodes and cannot be expanded.
*/
if (finfo.treeType() != -1) {
tree_expanded_set(finfo.treeType(), TRUE);
}
}
void ProtoTree::syncCollapsed(const QModelIndex &index) {
FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(index));
if (!finfo.isValid()) return;
/*
* Nodes with "finfo->tree_type" of -1 have no ett_ value, and
* are thus presumably leaf nodes and cannot be collapsed.
*/
if (finfo.treeType() != -1) {
tree_expanded_set(finfo.treeType(), FALSE);
}
}
void ProtoTree::expandSubtrees()
{
if (!selectionModel()->hasSelection()) return;
QStack<QModelIndex> index_stack;
index_stack.push(selectionModel()->selectedIndexes().first());
while (!index_stack.isEmpty()) {
QModelIndex index = index_stack.pop();
expand(index);
int row_count = proto_tree_model_->rowCount(index);
for (int row = row_count - 1; row >= 0; row--) {
QModelIndex child = proto_tree_model_->index(row, 0, index);
if (proto_tree_model_->hasChildren(child)) {
index_stack.push(child);
}
}
}
updateContentWidth();
}
void ProtoTree::collapseSubtrees()
{
if (!selectionModel()->hasSelection()) return;
QStack<QModelIndex> index_stack;
index_stack.push(selectionModel()->selectedIndexes().first());
while (!index_stack.isEmpty()) {
QModelIndex index = index_stack.pop();
collapse(index);
int row_count = proto_tree_model_->rowCount(index);
for (int row = row_count - 1; row >= 0; row--) {
QModelIndex child = proto_tree_model_->index(row, 0, index);
if (proto_tree_model_->hasChildren(child)) {
index_stack.push(child);
}
}
}
updateContentWidth();
}
void ProtoTree::expandAll()
{
for (int i = 0; i < num_tree_types; i++) {
tree_expanded_set(i, TRUE);
}
QTreeView::expandAll();
updateContentWidth();
}
void ProtoTree::collapseAll()
{
for (int i = 0; i < num_tree_types; i++) {
tree_expanded_set(i, FALSE);
}
QTreeView::collapseAll();
updateContentWidth();
}
void ProtoTree::itemClicked(const QModelIndex &index)
{
if (selectionModel()->selectedIndexes().isEmpty()) {
emit fieldSelected(0);
} else if (index == selectionModel()->selectedIndexes().first()) {
FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(index));
if (finfo.isValid()) {
emit fieldSelected(&finfo);
}
}
}
void ProtoTree::itemDoubleClicked(const QModelIndex &index)
{
FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(index));
if (!finfo.isValid()) return;
if (finfo.headerInfo().type == FT_FRAMENUM) {
if (QApplication::queryKeyboardModifiers() & Qt::ShiftModifier) {
emit openPacketInNewWindow(true);
} else {
mainApp->gotoFrame(fvalue_get_uinteger(finfo.fieldInfo()->value));
}
} else {
QString url = finfo.url();
if (!url.isEmpty()) {
QApplication::clipboard()->setText(url);
QString push_msg = tr("Copied ") + url;
mainApp->pushStatus(MainApplication::TemporaryStatus, push_msg);
}
}
}
void ProtoTree::selectedFrameChanged(QList<int> frames)
{
if (frames.count() == 1 && cap_file_ && cap_file_->edt && cap_file_->edt->tree) {
setRootNode(cap_file_->edt->tree);
} else {
// Clear the proto tree contents as they have become invalid.
proto_tree_model_->setRootNode(NULL);
}
}
// Select a field and bring it into view. Intended to be called by external
// components (such as the byte view).
void ProtoTree::selectedFieldChanged(FieldInformation *finfo)
{
if (finfo && finfo->parent() == this) {
// We only want inbound signals.
return;
}
QModelIndex index = proto_tree_model_->findFieldInformation(finfo);
setUpdatesEnabled(false);
// The new finfo might match the current index. Clear our selection
// so that we force a fresh item selection, so that fieldSelected
// will in turn be emitted.
selectionModel()->clearSelection();
autoScrollTo(index);
setUpdatesEnabled(true);
}
// Remember the currently focussed field based on:
// - current hf_id (obviously)
// - parent items (to avoid selecting a text item in a different tree)
// - the row of each item
void ProtoTree::saveSelectedField(QModelIndex &index)
{
selected_hfid_path_.clear();
QModelIndex save_index = index;
while (save_index.isValid()) {
FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(save_index));
if (!finfo.isValid()) break;
selected_hfid_path_.prepend(QPair<int,int>(save_index.row(), finfo.headerInfo().id));
save_index = save_index.parent();
}
}
// Try to focus a tree item which was previously also visible
void ProtoTree::restoreSelectedField()
{
if (selected_hfid_path_.isEmpty()) return;
QModelIndex cur_index = QModelIndex();
QPair<int,int> path_entry;
foreach (path_entry, selected_hfid_path_) {
int row = path_entry.first;
int hf_id = path_entry.second;
cur_index = proto_tree_model_->index(row, 0, cur_index);
FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(cur_index));
if (!finfo.isValid() || finfo.headerInfo().id != hf_id) {
// Did not find the selected hfid path in the selected packet
cur_index = QModelIndex();
emit fieldSelected(0);
break;
}
}
autoScrollTo(cur_index);
}
QString ProtoTree::traverseTree(const QModelIndex & travTree, int identLevel) const
{
QString result = "";
if (travTree.isValid())
{
result.append(QString(" ").repeated(identLevel));
result.append(travTree.data().toString());
result.append("\n");
/* if the element is expanded, we traverse one level down */
if (isExpanded(travTree))
{
int children = proto_tree_model_->rowCount(travTree);
identLevel++;
for (int child = 0; child < children; child++)
result += traverseTree(proto_tree_model_->index(child, 0, travTree), identLevel);
}
}
return result;
}
QString ProtoTree::toString(const QModelIndex &start_idx) const
{
QString tree_string = "";
if (start_idx.isValid())
tree_string = traverseTree(start_idx, 0);
else
{
int children = proto_tree_model_->rowCount();
for (int child = 0; child < children; child++)
tree_string += traverseTree(proto_tree_model_->index(child, 0, QModelIndex()), 0);
}
return tree_string;
}
void ProtoTree::setCaptureFile(capture_file *cf)
{
// For use by the main view, set the capture file which will later have a
// dissection (EDT) ready.
// The packet dialog sets a fixed EDT context and MUST NOT use this.
Q_ASSERT(edt_ == NULL);
cap_file_ = cf;
}
bool ProtoTree::eventFilter(QObject * obj, QEvent * event)
{
if (event->type() != QEvent::MouseButtonPress && event->type() != QEvent::MouseMove)
return QTreeView::eventFilter(obj, event);
/* Mouse was over scrollbar, ignoring */
if (qobject_cast<QScrollBar *>(obj))
return QTreeView::eventFilter(obj, event);
if (event->type() == QEvent::MouseButtonPress)
{
QMouseEvent * ev = (QMouseEvent *)event;
if (ev->buttons() & Qt::LeftButton)
drag_start_position_ = ev->pos();
}
else if (event->type() == QEvent::MouseMove)
{
QMouseEvent * ev = (QMouseEvent *)event;
if ((ev->buttons() & Qt::LeftButton) && (ev->pos() - drag_start_position_).manhattanLength()
> QApplication::startDragDistance())
{
QModelIndex idx = indexAt(drag_start_position_);
FieldInformation finfo(proto_tree_model_->protoNodeFromIndex(idx));
if (finfo.isValid())
{
/* Hack to prevent QItemSelection taking the item which has been dragged over at start
* of drag-drop operation. selectionModel()->blockSignals could have done the trick, but
* it does not take in a QTreeWidget (maybe View) */
emit fieldSelected(&finfo);
selectionModel()->select(idx, QItemSelectionModel::ClearAndSelect);
epan_dissect_t *edt = cap_file_ ? cap_file_->edt : edt_;
char *field_filter = proto_construct_match_selected_string(finfo.fieldInfo(), edt);
QString filter(field_filter);
wmem_free(NULL, field_filter);
if (filter.length() > 0)
{
QJsonObject filterData;
filterData["filter"] = filter;
filterData["name"] = finfo.headerInfo().abbreviation;
filterData["description"] = finfo.headerInfo().name;
QMimeData * mimeData = new QMimeData();
mimeData->setData(WiresharkMimeData::DisplayFilterMimeType, QJsonDocument(filterData).toJson());
mimeData->setText(toString(idx));
QDrag * drag = new QDrag(this);
drag->setMimeData(mimeData);
QString lblTxt = QString("%1\n%2").arg(finfo.headerInfo().name, filter);
DragLabel * content = new DragLabel(lblTxt, this);
qreal dpr = window()->windowHandle()->devicePixelRatio();
QPixmap pixmap(content->size() * dpr);
pixmap.setDevicePixelRatio(dpr);
content->render(&pixmap);
drag->setPixmap(pixmap);
drag->exec(Qt::CopyAction);
return true;
}
}
}
}
return QTreeView::eventFilter(obj, event);
}
QModelIndex ProtoTree::moveCursor(QAbstractItemView::CursorAction cursorAction, Qt::KeyboardModifiers modifiers)
{
if (cursorAction == MoveLeft && selectionModel()->hasSelection()) {
QModelIndex cur_idx = selectionModel()->selectedIndexes().first();
QModelIndex parent = cur_idx.parent();
if (!isExpanded(cur_idx) && parent.isValid() && parent != rootIndex()) {
return parent;
}
}
return QTreeView::moveCursor(cursorAction, modifiers);
} |
C/C++ | wireshark/ui/qt/proto_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 PROTO_TREE_H
#define PROTO_TREE_H
#include <config.h>
#include <epan/proto.h>
#include "cfile.h"
#include "protocol_preferences_menu.h"
#include <ui/qt/utils/field_information.h>
#include <QTreeView>
#include <QMenu>
class ProtoTreeModel;
class ProtoNode;
class ProtoTree : public QTreeView
{
Q_OBJECT
public:
explicit ProtoTree(QWidget *parent = 0, epan_dissect_t *edt_fixed = 0);
QMenu *colorizeMenu() { return &colorize_menu_; }
void setRootNode(proto_node *root_node);
void emitRelatedFrame(int related_frame, ft_framenum_type_t framenum_type = FT_FRAMENUM_NONE);
void autoScrollTo(const QModelIndex &index);
void goToHfid(int hfid);
void clear();
void restoreSelectedField();
QString toString(const QModelIndex &start_idx = QModelIndex()) const;
protected:
enum {
Name = 0,
Description,
Value
};
virtual void contextMenuEvent(QContextMenuEvent *event);
virtual void timerEvent(QTimerEvent *event);
virtual void keyReleaseEvent(QKeyEvent *event);
virtual bool eventFilter(QObject * obj, QEvent * ev);
virtual QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers);
QString traverseTree(const QModelIndex & rootNode, int identLevel = 0) const;
private:
ProtoTreeModel *proto_tree_model_;
QMenu conv_menu_;
QMenu colorize_menu_;
ProtocolPreferencesMenu proto_prefs_menu_;
QList<QAction *> copy_actions_;
int column_resize_timer_;
QList<QPair<int,int> > selected_hfid_path_; // row, hfinfo
QPoint drag_start_position_;
capture_file *cap_file_;
epan_dissect_t *edt_;
void saveSelectedField(QModelIndex &index);
static void foreachTreeNode(proto_node *node, gpointer proto_tree_ptr);
void foreachExpand(const QModelIndex &index);
signals:
void fieldSelected(FieldInformation *);
void openPacketInNewWindow(bool);
void goToPacket(int);
void relatedFrame(int, ft_framenum_type_t);
void showProtocolPreferences(const QString module_name);
void editProtocolPreference(struct preference *pref, struct pref_module *module);
public slots:
/* Set the capture file */
void setCaptureFile(capture_file *cf);
void setMonospaceFont(const QFont &mono_font);
void syncExpanded(const QModelIndex & index);
void syncCollapsed(const QModelIndex & index);
void expandSubtrees();
void collapseSubtrees();
void expandAll();
void collapseAll();
void itemClicked(const QModelIndex & index);
void itemDoubleClicked(const QModelIndex & index);
void selectedFieldChanged(FieldInformation *);
void selectedFrameChanged(QList<int>);
protected slots:
void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
#if 0
void ctxShowPacketBytes();
void ctxExportPacketBytes();
#endif
void ctxCopyVisibleItems();
void ctxCopyAsFilter();
void ctxCopySelectedInfo();
void ctxOpenUrlWiki();
private slots:
void updateContentWidth();
void connectToMainWindow();
};
#endif // PROTO_TREE_H |
Text | wireshark/ui/qt/qt6-migration-links.txt | https://doc.qt.io/qt-5/qtmac-obsolete.html
https://doc.qt.io/qt-6/extras-changes-qt6.html
https://doc.qt.io/qt-6/modulechanges.html
https://doc.qt.io/qt-6/cmake-qt5-and-qt6-compatibility.html
https://www.qt.io/blog/porting-from-qt-5-to-qt-6-using-qt5compat-library
https://dangelog.wordpress.com/2012/04/07/qregularexpression/
https://doc.qt.io/qt-6/qtcore-changes-qt6.html#regular-expression-classes
https://doc.qt.io/qt-6/qtmodules.html
https://doc.qt.io/qt-6/whatsnew60.html |
C++ | wireshark/ui/qt/recent_file_status.cpp | /* recent_file_status.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "recent_file_status.h"
RecentFileStatus::RecentFileStatus(const QString filename, QObject *parent) :
QObject(parent),
// Force a deep copy.
filename_(QString::fromStdU16String(filename.toStdU16String()))
{
// We're a QObject, which means that we emit a destroyed signal,
// which might happen at the wrong time when automatic deletion is
// enabled. This will trigger an assert in debug builds (bug 14279).
setAutoDelete(false);
// Qt::QueuedConnection creates a copy of our argument list. This
// squelches what appears to be a ThreadSanitizer false positive.
connect(this, SIGNAL(statusFound(QString, qint64, bool)),
parent, SLOT(itemStatusFinished(QString, qint64, bool)), Qt::QueuedConnection);
}
void RecentFileStatus::run() {
fileinfo_.setFile(filename_);
if (fileinfo_.isFile() && fileinfo_.isReadable()) {
emit statusFound(filename_, fileinfo_.size(), true);
} else {
emit statusFound(filename_, 0, false);
}
deleteLater();
} |
C/C++ | wireshark/ui/qt/recent_file_status.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef RECENT_FILE_STATUS_H
#define RECENT_FILE_STATUS_H
#include <QRunnable>
#include <QFileInfo>
class RecentFileStatus : public QObject, public QRunnable
{
Q_OBJECT
public:
RecentFileStatus(const QString filename, QObject *parent);
protected:
void run();
private:
const QString filename_;
QFileInfo fileinfo_;
signals:
void statusFound(const QString filename = QString(), qint64 size = 0, bool accessible = false);
};
#endif // RECENT_FILE_STATUS_H |
C++ | wireshark/ui/qt/remote_capture_dialog.cpp | /* remote_capture_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
// XXX This shouldn't exist. These controls should be in ManageInterfacesDialog instead.
#include "config.h"
#ifdef HAVE_PCAP_REMOTE
#include <glib.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "ui/capture_globals.h"
#include "remote_capture_dialog.h"
#include <ui_remote_capture_dialog.h>
#include "capture_opts.h"
#include "capture/capture-pcap-util.h"
#include "ui/capture_ui_utils.h"
#include "epan/prefs.h"
#include "epan/to_str.h"
#include "ui/ws_ui_util.h"
#include "ui/recent.h"
#include <QMessageBox>
RemoteCaptureDialog::RemoteCaptureDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::RemoteCaptureDialog)
{
ui->setupUi(this);
fillComboBox();
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(apply_remote()));
connect(this, SIGNAL(remoteAdded(GList *, remote_options*)), parent, SIGNAL(remoteAdded(GList *, remote_options*)));
connect(ui->hostCombo, &QComboBox::currentTextChanged, this, &RemoteCaptureDialog::hostChanged);
}
RemoteCaptureDialog::~RemoteCaptureDialog()
{
delete ui;
}
void RemoteCaptureDialog::hostChanged(const QString host)
{
if (!host.compare(tr("Clear list"))) {
recent_free_remote_host_list();
ui->hostCombo->clear();
} else {
struct remote_host *rh = recent_get_remote_host(host.toUtf8().constData());
if (rh) {
ui->portText->setText(QString(rh->remote_port));
if (rh->auth_type == CAPTURE_AUTH_NULL) {
ui->nullAuth->setChecked(true);
} else {
ui->pwAuth->setChecked(true);
}
}
}
}
static void fillBox(gpointer key, gpointer, gpointer user_data)
{
QComboBox *cb = (QComboBox *)user_data;
cb->addItem(QString((gchar*)key));
}
void RemoteCaptureDialog::fillComboBox()
{
int remote_host_list_size;
ui->hostCombo->addItem(QString(""));
remote_host_list_size = recent_get_remote_host_list_size();
if (remote_host_list_size > 0) {
recent_remote_host_list_foreach(fillBox, ui->hostCombo);
ui->hostCombo->insertSeparator(remote_host_list_size+1);
ui->hostCombo->addItem(QString(tr("Clear list")));
}
}
void RemoteCaptureDialog::apply_remote()
{
int err;
gchar *err_str;
remote_options global_remote_opts;
QString host = ui->hostCombo->currentText();
global_remote_opts.src_type = CAPTURE_IFREMOTE;
global_remote_opts.remote_host_opts.remote_host = qstring_strdup(host);
QString port = ui->portText->text();
global_remote_opts.remote_host_opts.remote_port = qstring_strdup(port);
if (ui->pwAuth->isChecked()) {
global_remote_opts.remote_host_opts.auth_type = CAPTURE_AUTH_PWD;
} else {
global_remote_opts.remote_host_opts.auth_type = CAPTURE_AUTH_NULL;
}
QString user = ui->userText->text();
global_remote_opts.remote_host_opts.auth_username = qstring_strdup(user);
QString pw = ui->pwText->text();
global_remote_opts.remote_host_opts.auth_password = qstring_strdup(pw);
global_remote_opts.remote_host_opts.datatx_udp = FALSE;
global_remote_opts.remote_host_opts.nocap_rpcap = TRUE;
global_remote_opts.remote_host_opts.nocap_local = FALSE;
#ifdef HAVE_PCAP_SETSAMPLING
global_remote_opts.sampling_method = CAPTURE_SAMP_NONE;
global_remote_opts.sampling_param = 0;
#endif
GList *rlist = get_remote_interface_list(global_remote_opts.remote_host_opts.remote_host,
global_remote_opts.remote_host_opts.remote_port,
global_remote_opts.remote_host_opts.auth_type,
global_remote_opts.remote_host_opts.auth_username,
global_remote_opts.remote_host_opts.auth_password,
&err, &err_str);
if (rlist == NULL) {
if (err == 0)
QMessageBox::warning(this, tr("Error"), tr("No remote interfaces found."));
else if (err == CANT_GET_INTERFACE_LIST)
QMessageBox::critical(this, tr("Error"), err_str);
else if (err == DONT_HAVE_PCAP)
QMessageBox::critical(this, tr("Error"), tr("PCAP not found"));
else
QMessageBox::critical(this, tr("Error"), "Unknown error");
return;
}
if (ui->hostCombo->count() == 0) {
ui->hostCombo->addItem("");
ui->hostCombo->addItem(host);
ui->hostCombo->insertSeparator(2);
ui->hostCombo->addItem(QString(tr("Clear list")));
} else {
ui->hostCombo->insertItem(0, host);
}
struct remote_host *rh = recent_get_remote_host(host.toUtf8().constData());
if (!rh) {
rh = (struct remote_host *)g_malloc (sizeof (*rh));
rh->r_host = qstring_strdup(host);
rh->remote_port = qstring_strdup(port);
rh->auth_type = global_remote_opts.remote_host_opts.auth_type;
rh->auth_password = g_strdup("");
rh->auth_username = g_strdup("");
recent_add_remote_host(global_remote_opts.remote_host_opts.remote_host, rh);
}
emit remoteAdded(rlist, &global_remote_opts);
}
void RemoteCaptureDialog::on_pwAuth_toggled(bool checked)
{
if (checked) {
ui->userLabel->setEnabled(true);
ui->userText->setEnabled(true);
ui->pwLabel->setEnabled(true);
ui->pwText->setEnabled(true);
}
}
void RemoteCaptureDialog::on_nullAuth_toggled(bool checked)
{
if (checked) {
ui->userLabel->setEnabled(false);
ui->userText->setEnabled(false);
ui->pwLabel->setEnabled(false);
ui->pwText->setEnabled(false);
}
}
#endif /* HAVE_PCAP_REMOTE */ |
C/C++ | wireshark/ui/qt/remote_capture_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 REMOTE_CAPTURE_DIALOG_H
#define REMOTE_CAPTURE_DIALOG_H
#include <config.h>
#ifdef HAVE_PCAP_REMOTE
#include <QDialog>
#include <glib.h>
#include "capture_opts.h"
namespace Ui {
class RemoteCaptureDialog;
}
class RemoteCaptureDialog : public QDialog
{
Q_OBJECT
public:
explicit RemoteCaptureDialog(QWidget *parent = 0);
~RemoteCaptureDialog();
signals:
void remoteAdded(GList *rlist, remote_options *roptions);
private slots:
void on_pwAuth_toggled(bool checked);
void on_nullAuth_toggled(bool checked);
void apply_remote();
void hostChanged(const QString host);
private:
Ui::RemoteCaptureDialog *ui;
void fillComboBox();
};
#endif
#endif // REMOTE_CAPTURE_DIALOG_H |
User Interface | wireshark/ui/qt/remote_capture_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>RemoteCaptureDialog</class>
<widget class="QDialog" name="RemoteCaptureDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>233</width>
<height>256</height>
</rect>
</property>
<property name="windowTitle">
<string>Remote Interface</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<layout class="QFormLayout" name="formLayout_2">
<property name="fieldGrowthPolicy">
<enum>QFormLayout::AllNonFixedFieldsGrow</enum>
</property>
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Host:</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QComboBox" name="hostCombo">
<property name="editable">
<bool>true</bool>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>Port:</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="portText"/>
</item>
</layout>
</item>
<item>
<widget class="QFrame" name="frame">
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Plain</enum>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>Authentication</string>
</property>
</widget>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QRadioButton" name="nullAuth">
<property name="text">
<string>Null authentication</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pwAuth">
<property name="text">
<string>Password authentication</string>
</property>
</widget>
</item>
<item>
<layout class="QFormLayout" name="formLayout">
<item row="0" column="0">
<widget class="QLabel" name="userLabel">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Username:</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="userText">
<property name="enabled">
<bool>false</bool>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="pwLabel">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Password:</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="pwText">
<property name="enabled">
<bool>false</bool>
</property>
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>RemoteCaptureDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>RemoteCaptureDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/remote_settings_dialog.cpp | /* remote_settings_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
// XXX This shouldn't exist. These controls should be in ManageInterfacesDialog instead.
#include "config.h"
#ifdef HAVE_PCAP_REMOTE
#include "remote_settings_dialog.h"
#include <ui_remote_settings_dialog.h>
RemoteSettingsDialog::RemoteSettingsDialog(QWidget *parent, interface_t *iface) :
QDialog(parent),
ui(new Ui::RemoteSettingsDialog)
{
ui->setupUi(this);
mydevice.name = g_strdup(iface->name);
ui->rpcapBox->setCheckState(iface->remote_opts.remote_host_opts.nocap_rpcap?Qt::Checked:Qt::Unchecked);
ui->udpBox->setCheckState(iface->remote_opts.remote_host_opts.datatx_udp?Qt::Checked:Qt::Unchecked);
#ifdef HAVE_PCAP_SETSAMPLING
switch (iface->remote_opts.sampling_method)
{
case CAPTURE_SAMP_NONE:
ui->sampleNone->setChecked(true);
break;
case CAPTURE_SAMP_BY_COUNT:
ui->samplePkt->setChecked(true);
ui->spinPkt->setValue(iface->remote_opts.sampling_param);
break;
case CAPTURE_SAMP_BY_TIMER:
ui->sampleTime->setChecked(true);
ui->spinTime->setValue(iface->remote_opts.sampling_param);
break;
}
#else
ui->sampleLabel->setVisible(false);
ui->sampleNone->setVisible(false);
ui->samplePkt->setVisible(false);
ui->sampleTime->setVisible(false);
ui->spinPkt->setVisible(false);
ui->spinTime->setVisible(false);
ui->pktLabel->setVisible(false);
ui->timeLabel->setVisible(false);
resize(width(), height() - ui->sampleLabel->height() - 3 * ui->sampleNone->height());
#endif
connect(this, SIGNAL(remoteSettingsChanged(interface_t *)), parent, SIGNAL(remoteSettingsChanged(interface_t *)));
}
RemoteSettingsDialog::~RemoteSettingsDialog()
{
delete ui;
}
void RemoteSettingsDialog::on_buttonBox_accepted()
{
mydevice.remote_opts.remote_host_opts.nocap_rpcap = (ui->rpcapBox->checkState()==Qt::Checked)?true:false;
mydevice.remote_opts.remote_host_opts.datatx_udp = (ui->udpBox->checkState()==Qt::Checked)?true:false;
#ifdef HAVE_PCAP_SETSAMPLING
if (ui->sampleNone->isChecked()) {
mydevice.remote_opts.sampling_method = CAPTURE_SAMP_NONE;
mydevice.remote_opts.sampling_param = 0;
} else if (ui->samplePkt->isChecked()) {
mydevice.remote_opts.sampling_method = CAPTURE_SAMP_BY_COUNT;
mydevice.remote_opts.sampling_param = ui->spinPkt->value();
} else {
mydevice.remote_opts.sampling_method = CAPTURE_SAMP_BY_TIMER;
mydevice.remote_opts.sampling_param = ui->spinTime->value();
}
#endif
emit remoteSettingsChanged(&mydevice);
}
#endif |
C/C++ | wireshark/ui/qt/remote_settings_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 REMOTE_SETTINGS_DIALOG_H
#define REMOTE_SETTINGS_DIALOG_H
#include <config.h>
#ifdef HAVE_PCAP_REMOTE
#include <QDialog>
#include "capture_opts.h"
namespace Ui {
class RemoteSettingsDialog;
}
class RemoteSettingsDialog : public QDialog
{
Q_OBJECT
public:
explicit RemoteSettingsDialog(QWidget *parent = 0, interface_t *iface = NULL);
~RemoteSettingsDialog();
signals:
void remoteSettingsChanged(interface_t *iface);
private slots:
void on_buttonBox_accepted();
private:
Ui::RemoteSettingsDialog *ui;
interface_t mydevice;
};
#endif
#endif // REMOTE_SETTINGS_DIALOG_H |
User Interface | wireshark/ui/qt/remote_settings_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>RemoteSettingsDialog</class>
<widget class="QDialog" name="RemoteSettingsDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>231</width>
<height>229</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Remote Capture Settings</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="sizeConstraint">
<enum>QLayout::SetMinimumSize</enum>
</property>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Capture Options</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="rpcapBox">
<property name="text">
<string>Do not capture own RPCAP traffic</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="udpBox">
<property name="text">
<string>Use UDP for data transfer</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="sampleLabel">
<property name="text">
<string>Sampling Options</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="sampleNone">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>None</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QRadioButton" name="samplePkt">
<property name="text">
<string>1 of</string>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="spinPkt">
<property name="maximum">
<number>1000000</number>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="pktLabel">
<property name="text">
<string>packets</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QRadioButton" name="sampleTime">
<property name="text">
<string>1 every </string>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="spinTime">
<property name="maximum">
<number>1000000</number>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="timeLabel">
<property name="text">
<string>milliseconds</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>RemoteSettingsDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>RemoteSettingsDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/resolved_addresses_dialog.cpp | /* resolved_addresses_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "resolved_addresses_dialog.h"
#include <ui_resolved_addresses_dialog.h>
#include "config.h"
#include <glib.h>
#include "file.h"
#include "epan/addr_resolv.h"
#include <wiretap/wtap.h>
#include <QMenu>
#include <QPushButton>
#include <QTextCursor>
#include <QSortFilterProxyModel>
#include "capture_file.h"
#include "main_application.h"
#include <ui/qt/models/astringlist_list_model.h>
#include <ui/qt/models/resolved_addresses_models.h>
const QString no_entries_ = QObject::tr("No entries.");
const QString entry_count_ = QObject::tr("%1 entries.");
ResolvedAddressesDialog::ResolvedAddressesDialog(QWidget *parent, QString captureFile, wtap* wth) :
GeometryStateDialog(parent),
ui(new Ui::ResolvedAddressesDialog),
file_name_(tr("[no file]"))
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose, true);
QStringList title_parts = QStringList() << tr("Resolved Addresses");
if (!captureFile.isEmpty()) {
file_name_ = captureFile;
title_parts << file_name_;
}
setWindowTitle(mainApp->windowTitleString(title_parts));
ui->plainTextEdit->setFont(mainApp->monospaceFont());
ui->plainTextEdit->setReadOnly(true);
ui->plainTextEdit->setWordWrapMode(QTextOption::NoWrap);
if (wth) {
// might return null
wtap_block_t nrb_hdr;
/*
* XXX - support multiple NRBs.
*/
nrb_hdr = wtap_file_get_nrb(wth);
if (nrb_hdr != NULL) {
char *str;
/*
* XXX - support multiple comments.
*/
if (wtap_block_get_nth_string_option_value(nrb_hdr, OPT_COMMENT, 0, &str) == WTAP_OPTTYPE_SUCCESS) {
comment_ = str;
}
}
}
fillBlocks();
ethSortModel = new AStringListListSortFilterProxyModel(this);
ethTypeModel = new AStringListListSortFilterProxyModel(this);
EthernetAddressModel * ethModel = new EthernetAddressModel(this);
ethSortModel->setSourceModel(ethModel);
ethSortModel->setColumnsToFilter(QList<int>() << 1 << 2);
ethSortModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
ethTypeModel->setSourceModel(ethSortModel);
ethTypeModel->setColumnToFilter(0);
ethTypeModel->setColumnToHide(0);
ui->tblAddresses->setModel(ethTypeModel);
ui->tblAddresses->resizeColumnsToContents();
ui->tblAddresses->horizontalHeader()->setStretchLastSection(true);
ui->tblAddresses->sortByColumn(1, Qt::AscendingOrder);
ui->cmbDataType->addItems(ethModel->filterValues());
portSortModel = new AStringListListSortFilterProxyModel(this);
portTypeModel = new AStringListListSortFilterProxyModel(this);
PortsModel * portModel = new PortsModel(this);
portSortModel->setSourceModel(portModel);
portSortModel->setColumnAsNumeric(1);
portSortModel->setColumnsToFilter(QList<int>() << 0 << 1);
portSortModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
portTypeModel->setSourceModel(portSortModel);
portTypeModel->setColumnToFilter(2);
portTypeModel->setColumnAsNumeric(1);
ui->tblPorts->setModel(portTypeModel);
ui->tblPorts->resizeColumnsToContents();
ui->tblPorts->horizontalHeader()->setStretchLastSection(true);
ui->tblPorts->sortByColumn(1, Qt::AscendingOrder);
ui->cmbPortFilterType->addItems(portModel->filterValues());
}
ResolvedAddressesDialog::~ResolvedAddressesDialog()
{
delete ui;
}
void ResolvedAddressesDialog::on_cmbDataType_currentIndexChanged(int index)
{
if (! ethSortModel)
return;
QString filter = ui->cmbDataType->itemText(index);
if (index == 0)
{
filter.clear();
ethTypeModel->setFilterType(AStringListListSortFilterProxyModel::FilterNone, 0);
}
else
ethTypeModel->setFilterType(AStringListListSortFilterProxyModel::FilterByEquivalent, 0);
ethTypeModel->setFilter(filter);
}
void ResolvedAddressesDialog::on_txtSearchFilter_textChanged(QString)
{
QString filter = ui->txtSearchFilter->text();
if (!ethSortModel || (!filter.isEmpty() && filter.length() < 3))
return;
ethSortModel->setFilter(filter);
}
void ResolvedAddressesDialog::on_cmbPortFilterType_currentIndexChanged(int index)
{
if (! portSortModel)
return;
QString filter = ui->cmbPortFilterType->itemText(index);
if (index == 0)
{
filter.clear();
portTypeModel->setFilterType(AStringListListSortFilterProxyModel::FilterNone, 2);
}
else
portTypeModel->setFilterType(AStringListListSortFilterProxyModel::FilterByEquivalent, 2);
portTypeModel->setFilter(filter);
}
void ResolvedAddressesDialog::on_txtPortFilter_textChanged(QString val)
{
if (! portSortModel)
return;
portSortModel->setFilter(val);
}
void ResolvedAddressesDialog::changeEvent(QEvent *event)
{
if (0 != event)
{
switch (event->type())
{
case QEvent::LanguageChange:
ui->retranslateUi(this);
fillBlocks();
break;
default:
break;
}
}
QDialog::changeEvent(event);
}
void ResolvedAddressesDialog::fillBlocks()
{
setUpdatesEnabled(false);
ui->plainTextEdit->clear();
QString lines;
ui->plainTextEdit->appendPlainText(tr("# Resolved addresses found in %1").arg(file_name_));
if (ui->actionComment->isChecked()) {
lines = "\n";
lines.append(tr("# Comments\n#\n# "));
if (!comment_.isEmpty()) {
lines.append("\n\n");
lines.append(comment_);
lines.append("\n");
} else {
lines.append(no_entries_);
}
ui->plainTextEdit->appendPlainText(lines);
}
ui->plainTextEdit->moveCursor(QTextCursor::Start);
setUpdatesEnabled(true);
} |
C/C++ | wireshark/ui/qt/resolved_addresses_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 RESOLVED_ADDRESSES_DIALOG_H
#define RESOLVED_ADDRESSES_DIALOG_H
#include "geometry_state_dialog.h"
#include <wiretap/wtap.h>
class CaptureFile;
class AStringListListSortFilterProxyModel;
namespace Ui {
class ResolvedAddressesDialog;
}
class ResolvedAddressesDialog : public GeometryStateDialog
{
Q_OBJECT
public:
explicit ResolvedAddressesDialog(QWidget *parent, QString captureFile, wtap* wth);
~ResolvedAddressesDialog();
protected slots:
void on_cmbDataType_currentIndexChanged(int index);
void on_txtSearchFilter_textChanged(QString text);
void on_cmbPortFilterType_currentIndexChanged(int index);
void on_txtPortFilter_textChanged(QString text);
void changeEvent(QEvent* event);
private:
Ui::ResolvedAddressesDialog *ui;
QString file_name_;
QString comment_;
AStringListListSortFilterProxyModel * ethSortModel;
AStringListListSortFilterProxyModel * ethTypeModel;
AStringListListSortFilterProxyModel * portSortModel;
AStringListListSortFilterProxyModel * portTypeModel;
void fillBlocks();
};
#endif // RESOLVED_ADDRESSES_DIALOG_H |
User Interface | wireshark/ui/qt/resolved_addresses_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ResolvedAddressesDialog</class>
<widget class="QDialog" name="ResolvedAddressesDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>620</width>
<height>450</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<attribute name="title">
<string>Hosts</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLineEdit" name="txtSearchFilter">
<property name="placeholderText">
<string>Search for entry (min 3 characters)</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="cmbDataType"/>
</item>
</layout>
</item>
<item>
<widget class="QTableView" name="tblAddresses">
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
<attribute name="horizontalHeaderShowSortIndicator" stdset="0">
<bool>true</bool>
</attribute>
<attribute name="verticalHeaderVisible">
<bool>false</bool>
</attribute>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="tab_3">
<attribute name="title">
<string>Ports</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLineEdit" name="txtPortFilter">
<property name="placeholderText">
<string>Search for port or name</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="cmbPortFilterType"/>
</item>
</layout>
</item>
<item>
<widget class="QTableView" name="tblPorts">
<property name="sortingEnabled">
<bool>true</bool>
</property>
<attribute name="verticalHeaderVisible">
<bool>false</bool>
</attribute>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="tab_2">
<attribute name="title">
<string>Capture File Comments</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<widget class="QPlainTextEdit" name="plainTextEdit"/>
</item>
</layout>
</widget>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Close</set>
</property>
</widget>
</item>
</layout>
<action name="actionComment">
<property name="checkable">
<bool>true</bool>
</property>
<property name="checked">
<bool>true</bool>
</property>
<property name="text">
<string>Comment</string>
</property>
<property name="toolTip">
<string>Show the comment.</string>
</property>
</action>
<action name="actionIPv4HashTable">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>IPv4 Hash Table</string>
</property>
<property name="toolTip">
<string>Show the IPv4 hash table entries.</string>
</property>
</action>
<action name="actionIPv6HashTable">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>IPv6 Hash Table</string>
</property>
<property name="toolTip">
<string>Show the IPv6 hash table entries.</string>
</property>
</action>
<action name="actionShowAll">
<property name="text">
<string>Show All</string>
</property>
<property name="toolTip">
<string>Show all address types.</string>
</property>
</action>
<action name="actionHideAll">
<property name="text">
<string>Hide All</string>
</property>
<property name="toolTip">
<string>Hide all address types.</string>
</property>
</action>
<action name="actionAddressesHosts">
<property name="checkable">
<bool>true</bool>
</property>
<property name="checked">
<bool>true</bool>
</property>
<property name="text">
<string>IPv4 and IPv6 Addresses (hosts)</string>
</property>
<property name="toolTip">
<string>Show resolved IPv4 and IPv6 host names in "hosts" format.</string>
</property>
</action>
<action name="actionPortNames">
<property name="checkable">
<bool>true</bool>
</property>
<property name="checked">
<bool>true</bool>
</property>
<property name="text">
<string>Port names (services)</string>
</property>
<property name="toolTip">
<string>Show resolved port names in "services" format.</string>
</property>
</action>
<action name="actionEthernetAddresses">
<property name="checkable">
<bool>true</bool>
</property>
<property name="checked">
<bool>true</bool>
</property>
<property name="text">
<string>Ethernet Addresses</string>
</property>
<property name="toolTip">
<string>Show resolved Ethernet addresses in "ethers" format.</string>
</property>
</action>
<action name="actionEthernetWKA">
<property name="checkable">
<bool>true</bool>
</property>
<property name="checked">
<bool>true</bool>
</property>
<property name="text">
<string>Ethernet Well-Known Addresses</string>
</property>
<property name="toolTip">
<string>Show well-known Ethernet addresses in "ethers" format.</string>
</property>
</action>
<action name="actionEthernetManufacturers">
<property name="checkable">
<bool>true</bool>
</property>
<property name="checked">
<bool>true</bool>
</property>
<property name="text">
<string>Ethernet Manufacturers</string>
</property>
<property name="toolTip">
<string>Show Ethernet manufacturers in "ethers" format.</string>
</property>
</action>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>ResolvedAddressesDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>ResolvedAddressesDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/response_time_delay_dialog.cpp | /* response_time_delay_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "response_time_delay_dialog.h"
#include "file.h"
#include "epan/proto.h"
#include "epan/rtd_table.h"
#include <QTreeWidget>
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
static QHash<const QString, register_rtd_t *> cfg_str_to_rtd_;
extern "C" {
static void
rtd_init(const char *args, void*) {
QStringList args_l = QString(args).split(',');
if (args_l.length() > 1) {
QString rtd = QString("%1,%2").arg(args_l[0]).arg(args_l[1]);
QString filter;
if (args_l.length() > 2) {
filter = QStringList(args_l.mid(2)).join(",");
}
mainApp->emitTapParameterSignal(rtd, filter, NULL);
}
}
}
bool register_response_time_delay_tables(const void *, void *value, void*)
{
register_rtd_t *rtd = (register_rtd_t*)value;
const char* short_name = proto_get_protocol_short_name(find_protocol_by_id(get_rtd_proto_id(rtd)));
char *cfg_abbr = rtd_table_get_tap_string(rtd);
cfg_str_to_rtd_[cfg_abbr] = rtd;
TapParameterDialog::registerDialog(
short_name,
cfg_abbr,
REGISTER_STAT_GROUP_RESPONSE_TIME,
rtd_init,
ResponseTimeDelayDialog::createRtdDialog);
g_free(cfg_abbr);
return FALSE;
}
enum {
col_type_,
col_messages_,
col_min_srt_,
col_max_srt_,
col_avg_srt_,
col_min_frame_,
col_max_frame_,
col_open_requests,
col_discarded_responses_,
col_repeated_requests_,
col_repeated_responses_
};
enum {
rtd_table_type_ = 1000,
rtd_time_stat_type_
};
class RtdTimeStatTreeWidgetItem : public QTreeWidgetItem
{
public:
RtdTimeStatTreeWidgetItem(QTreeWidget *parent, const QString type, const rtd_timestat *timestat) :
QTreeWidgetItem (parent, rtd_time_stat_type_),
type_(type),
timestat_(timestat)
{
setText(col_type_, type_);
setHidden(true);
}
void draw() {
setText(col_messages_, QString::number(timestat_->rtd->num));
setText(col_min_srt_, QString::number(nstime_to_sec(×tat_->rtd->min), 'f', 6));
setText(col_max_srt_, QString::number(nstime_to_sec(×tat_->rtd->max), 'f', 6));
setText(col_avg_srt_, QString::number(get_average(×tat_->rtd->tot, timestat_->rtd->num) / 1000.0, 'f', 6));
setText(col_min_frame_, QString::number(timestat_->rtd->min_num));
setText(col_max_frame_, QString::number(timestat_->rtd->max_num));
setText(col_open_requests, QString::number(timestat_->open_req_num));
setText(col_discarded_responses_, QString::number(timestat_->disc_rsp_num));
setText(col_repeated_requests_, QString::number(timestat_->req_dup_num));
setText(col_repeated_responses_, QString::number(timestat_->rsp_dup_num));
setHidden(timestat_->rtd->num < 1);
}
bool operator< (const QTreeWidgetItem &other) const
{
if (other.type() != rtd_time_stat_type_) return QTreeWidgetItem::operator< (other);
const RtdTimeStatTreeWidgetItem *other_row = static_cast<const RtdTimeStatTreeWidgetItem *>(&other);
switch (treeWidget()->sortColumn()) {
case col_messages_:
return timestat_->rtd->num < other_row->timestat_->rtd->num;
case col_min_srt_:
return nstime_cmp(×tat_->rtd->min, &other_row->timestat_->rtd->min) < 0;
case col_max_srt_:
return nstime_cmp(×tat_->rtd->max, &other_row->timestat_->rtd->max) < 0;
case col_avg_srt_:
{
double our_avg = get_average(×tat_->rtd->tot, timestat_->rtd->num);
double other_avg = get_average(&other_row->timestat_->rtd->tot, other_row->timestat_->rtd->num);
return our_avg < other_avg;
}
case col_min_frame_:
return timestat_->rtd->min_num < other_row->timestat_->rtd->min_num;
case col_max_frame_:
return timestat_->rtd->max_num < other_row->timestat_->rtd->max_num;
case col_open_requests:
return timestat_->open_req_num < other_row->timestat_->open_req_num;
case col_discarded_responses_:
return timestat_->disc_rsp_num < other_row->timestat_->disc_rsp_num;
case col_repeated_requests_:
return timestat_->req_dup_num < other_row->timestat_->req_dup_num;
case col_repeated_responses_:
return timestat_->rsp_dup_num < other_row->timestat_->rsp_dup_num;
default:
break;
}
return QTreeWidgetItem::operator< (other);
}
QList<QVariant> rowData() {
return QList<QVariant>() << type_ << timestat_->rtd->num
<< nstime_to_sec(×tat_->rtd->min) << nstime_to_sec(×tat_->rtd->max)
<< get_average(×tat_->rtd->tot, timestat_->rtd->num) / 1000.0
<< timestat_->rtd->min_num << timestat_->rtd->max_num
<< timestat_->open_req_num << timestat_->disc_rsp_num
<< timestat_->req_dup_num << timestat_->rsp_dup_num;
}
private:
const QString type_;
const rtd_timestat *timestat_;
};
ResponseTimeDelayDialog::ResponseTimeDelayDialog(QWidget &parent, CaptureFile &cf, register_rtd *rtd, const QString filter, int help_topic) :
TapParameterDialog(parent, cf, help_topic),
rtd_(rtd)
{
QString subtitle = tr("%1 Response Time Delay Statistics")
.arg(proto_get_protocol_short_name(find_protocol_by_id(get_rtd_proto_id(rtd))));
setWindowSubtitle(subtitle);
loadGeometry(0, 0, "ResponseTimeDelayDialog");
QStringList header_names = QStringList()
<< tr("Type") << tr("Messages")
<< tr("Min SRT") << tr("Max SRT") << tr("Avg SRT")
<< tr("Min in Frame") << tr("Max in Frame")
<< tr("Open Requests") << tr("Discarded Responses")
<< tr("Repeated Requests") << tr("Repeated Responses");
statsTreeWidget()->setHeaderLabels(header_names);
for (int col = 0; col < statsTreeWidget()->columnCount(); col++) {
if (col == col_type_) continue;
statsTreeWidget()->headerItem()->setTextAlignment(col, Qt::AlignRight);
}
if (!filter.isEmpty()) {
setDisplayFilter(filter);
}
}
TapParameterDialog *ResponseTimeDelayDialog::createRtdDialog(QWidget &parent, const QString cfg_str, const QString filter, CaptureFile &cf)
{
if (!cfg_str_to_rtd_.contains(cfg_str)) {
// XXX MessageBox?
return NULL;
}
register_rtd_t *rtd = cfg_str_to_rtd_[cfg_str];
return new ResponseTimeDelayDialog(parent, cf, rtd, filter);
}
void ResponseTimeDelayDialog::addRtdTable(const _rtd_stat_table *rtd_table)
{
for (unsigned i = 0; i < rtd_table->num_rtds; i++) {
const QString type = val_to_qstring(i, get_rtd_value_string(rtd_), "Other (%d)");
new RtdTimeStatTreeWidgetItem(statsTreeWidget(), type, &rtd_table->time_stats[i]);
}
}
void ResponseTimeDelayDialog::tapReset(void *rtdd_ptr)
{
rtd_data_t *rtdd = (rtd_data_t*) rtdd_ptr;
ResponseTimeDelayDialog *rtd_dlg = static_cast<ResponseTimeDelayDialog *>(rtdd->user_data);
if (!rtd_dlg) return;
reset_rtd_table(&rtdd->stat_table);
rtd_dlg->statsTreeWidget()->clear();
rtd_dlg->addRtdTable(&rtdd->stat_table);
}
void ResponseTimeDelayDialog::tapDraw(void *rtdd_ptr)
{
rtd_data_t *rtdd = (rtd_data_t*) rtdd_ptr;
ResponseTimeDelayDialog *rtd_dlg = static_cast<ResponseTimeDelayDialog *>(rtdd->user_data);
if (!rtd_dlg || !rtd_dlg->statsTreeWidget()) return;
QTreeWidgetItemIterator it(rtd_dlg->statsTreeWidget());
while (*it) {
if ((*it)->type() == rtd_time_stat_type_) {
RtdTimeStatTreeWidgetItem *rtd_ts_ti = static_cast<RtdTimeStatTreeWidgetItem *>((*it));
rtd_ts_ti->draw();
}
++it;
}
for (int i = 0; i < rtd_dlg->statsTreeWidget()->columnCount() - 1; i++) {
rtd_dlg->statsTreeWidget()->resizeColumnToContents(i);
}
}
void ResponseTimeDelayDialog::fillTree()
{
rtd_data_t rtd_data;
memset (&rtd_data, 0, sizeof(rtd_data));
rtd_table_dissector_init(rtd_, &rtd_data.stat_table, NULL, NULL);
rtd_data.user_data = this;
QByteArray display_filter = displayFilter().toUtf8();
if (!registerTapListener(get_rtd_tap_listener_name(rtd_),
&rtd_data,
display_filter.constData(),
0,
tapReset,
get_rtd_packet_func(rtd_),
tapDraw)) {
free_rtd_table(&rtd_data.stat_table);
reject(); // XXX Stay open instead?
return;
}
statsTreeWidget()->setSortingEnabled(false);
cap_file_.retapPackets();
tapDraw(&rtd_data);
statsTreeWidget()->sortItems(col_type_, Qt::AscendingOrder);
statsTreeWidget()->setSortingEnabled(true);
removeTapListeners();
free_rtd_table(&rtd_data.stat_table);
}
QList<QVariant> ResponseTimeDelayDialog::treeItemData(QTreeWidgetItem *ti) const
{
QList<QVariant> tid;
if (ti->type() == rtd_time_stat_type_) {
RtdTimeStatTreeWidgetItem *rtd_ts_ti = static_cast<RtdTimeStatTreeWidgetItem *>(ti);
tid << rtd_ts_ti->rowData();
}
return tid;
} |
C/C++ | wireshark/ui/qt/response_time_delay_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 __RESPONSE_TIME_DELAY_DIALOG_H__
#define __RESPONSE_TIME_DELAY_DIALOG_H__
#include "tap_parameter_dialog.h"
struct _rtd_stat_table;
class ResponseTimeDelayDialog : public TapParameterDialog
{
Q_OBJECT
public:
ResponseTimeDelayDialog(QWidget &parent, CaptureFile &cf, struct register_rtd *rtd, const QString filter, int help_topic = 0);
static TapParameterDialog *createRtdDialog(QWidget &parent, const QString cfg_str, const QString filter, CaptureFile &cf);
protected:
/** Add a response time delay table.
*
* @param rtd_table The table to add.
*/
// gtk:service_response_table.h:init_srt_table
void addRtdTable(const struct _rtd_stat_table *rtd_table);
private:
struct register_rtd *rtd_;
// Callbacks for register_tap_listener
static void tapReset(void *rtdd_ptr);
static void tapDraw(void *rtdd_ptr);
virtual QList<QVariant> treeItemData(QTreeWidgetItem *ti) const;
private slots:
virtual void fillTree();
};
/** Register function to register dissectors that support RTD for Qt.
*
* @param key is unused
* @param value register_rtd_t* representing dissetor RTD table
* @param userdata is unused
*/
bool register_response_time_delay_tables(const void *key, void *value, void *userdata);
#endif // __RESPONSE_TIME_DELAY_DIALOG_H__ |
C++ | wireshark/ui/qt/rpc_service_response_time_dialog.cpp | /* rpc_service_response_time_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
// warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4267)
#endif
#include "rpc_service_response_time_dialog.h"
#include <algorithm>
#include <stdio.h>
#include <epan/dissectors/packet-dcerpc.h>
#include <epan/dissectors/packet-rpc.h>
#include <epan/guid-utils.h>
#include <epan/srt_table.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <QComboBox>
#include <QHBoxLayout>
#include <QLabel>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// To do:
// - Don't assume that the user knows what programs+versions are in the
// capture. I.e. combine this dialog with the ONC-RPC Programs dialog,
// with two lists: programs on top, procedures on the bottom.
// - Allow the display of multiple programs and versions.
// - Expose the DCE-RPC UUIDs and ONC-RPC program numbers e.g. in an extra
// column.
// - Make the version in the command-line args optional?
extern "C" {
static void
dce_rpc_add_program(gpointer key_ptr, gpointer value_ptr, gpointer rsrtd_ptr)
{
RpcServiceResponseTimeDialog *rsrt_dlg = dynamic_cast<RpcServiceResponseTimeDialog *>((RpcServiceResponseTimeDialog *)rsrtd_ptr);
if (!rsrt_dlg) return;
guid_key *key = (guid_key *)key_ptr;
dcerpc_uuid_value *value = (dcerpc_uuid_value *)value_ptr;
rsrt_dlg->addDceRpcProgram(key, value);
}
static void
dce_rpc_find_versions(gpointer key_ptr, gpointer, gpointer rsrtd_ptr)
{
RpcServiceResponseTimeDialog *rsrt_dlg = dynamic_cast<RpcServiceResponseTimeDialog *>((RpcServiceResponseTimeDialog *)rsrtd_ptr);
if (!rsrt_dlg) return;
guid_key *key = (guid_key *)key_ptr;
rsrt_dlg->addDceRpcProgramVersion(key);
}
static void
onc_rpc_add_program(gpointer prog_ptr, gpointer value_ptr, gpointer rsrtd_ptr)
{
RpcServiceResponseTimeDialog *rsrt_dlg = dynamic_cast<RpcServiceResponseTimeDialog *>((RpcServiceResponseTimeDialog *)rsrtd_ptr);
if (!rsrt_dlg) return;
guint32 program = GPOINTER_TO_UINT(prog_ptr);
rpc_prog_info_value *value = (rpc_prog_info_value *) value_ptr;
rsrt_dlg->addOncRpcProgram(program, value);
}
static void
onc_rpc_find_versions(const gchar *, ftenum_t , gpointer rpik_ptr, gpointer, gpointer rsrtd_ptr)
{
RpcServiceResponseTimeDialog *rsrt_dlg = dynamic_cast<RpcServiceResponseTimeDialog *>((RpcServiceResponseTimeDialog *)rsrtd_ptr);
if (!rsrt_dlg) return;
rpc_proc_info_key *rpik = (rpc_proc_info_key *)rpik_ptr;
rsrt_dlg->addOncRpcProgramVersion(rpik->prog, rpik->vers);
}
static void
onc_rpc_count_procedures(const gchar *, ftenum_t , gpointer rpik_ptr, gpointer, gpointer rsrtd_ptr)
{
RpcServiceResponseTimeDialog *rsrt_dlg = dynamic_cast<RpcServiceResponseTimeDialog *>((RpcServiceResponseTimeDialog *)rsrtd_ptr);
if (!rsrt_dlg) return;
rpc_proc_info_key *rpik = (rpc_proc_info_key *)rpik_ptr;
rsrt_dlg->updateOncRpcProcedureCount(rpik->prog, rpik->vers, rpik->proc);
}
} // extern "C"
RpcServiceResponseTimeDialog::RpcServiceResponseTimeDialog(QWidget &parent, CaptureFile &cf, struct register_srt *srt, RpcFamily dlg_type, const QString filter) :
ServiceResponseTimeDialog(parent, cf, srt, filter),
dlg_type_(dlg_type)
{
setRetapOnShow(false);
setHint(tr("<small><i>Select a program and version and enter a filter if desired, then press Apply.</i></small>"));
QHBoxLayout *filter_layout = filterLayout();
program_combo_ = new QComboBox(this);
version_combo_ = new QComboBox(this);
filter_layout->insertStretch(0, 1);
filter_layout->insertWidget(0, version_combo_);
filter_layout->insertWidget(0, new QLabel(tr("Version:")));
filter_layout->insertWidget(0, program_combo_);
filter_layout->insertWidget(0, new QLabel(tr("Program:")));
if (dlg_type == DceRpc) {
setWindowSubtitle(tr("DCE-RPC Service Response Times"));
g_hash_table_foreach(dcerpc_uuids, dce_rpc_add_program, this);
// This is a loooooong list. The GTK+ UI addresses this by making
// the program combo a tree instead of a list. We might want to add a
// full-height list to the left of the stats tree instead.
QStringList programs = dce_name_to_uuid_key_.keys();
std::sort(programs.begin(), programs.end(), qStringCaseLessThan);
connect(program_combo_, SIGNAL(currentTextChanged(const QString)),
this, SLOT(dceRpcProgramChanged(const QString)));
program_combo_->addItems(programs);
} else {
setWindowSubtitle(tr("ONC-RPC Service Response Times"));
g_hash_table_foreach(rpc_progs, onc_rpc_add_program, this);
QStringList programs = onc_name_to_program_.keys();
std::sort(programs.begin(), programs.end(), qStringCaseLessThan);
connect(program_combo_, SIGNAL(currentTextChanged(const QString)),
this, SLOT(oncRpcProgramChanged(const QString)));
program_combo_->addItems(programs);
}
}
TapParameterDialog *RpcServiceResponseTimeDialog::createDceRpcSrtDialog(QWidget &parent, const QString, const QString opt_arg, CaptureFile &cf)
{
QString filter;
bool have_args = false;
QString program_name;
e_guid_t uuid;
int version = 0;
// dcerpc,srt,<uuid>,<major version>.<minor version>[,<filter>]
QStringList args_l = QString(opt_arg).split(',');
if (args_l.length() > 1) {
// XXX Switch to QUuid.
unsigned d1, d2, d3, d4_0, d4_1, d4_2, d4_3, d4_4, d4_5, d4_6, d4_7;
if (sscanf(args_l[0].toUtf8().constData(),
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
&d1, &d2, &d3,
&d4_0, &d4_1, &d4_2, &d4_3, &d4_4, &d4_5, &d4_6, &d4_7) == 11) {
uuid.data1 = d1;
uuid.data2 = d2;
uuid.data3 = d3;
uuid.data4[0] = d4_0;
uuid.data4[1] = d4_1;
uuid.data4[2] = d4_2;
uuid.data4[3] = d4_3;
uuid.data4[4] = d4_4;
uuid.data4[5] = d4_5;
uuid.data4[6] = d4_6;
uuid.data4[7] = d4_7;
} else {
program_name = args_l[0];
}
version = args_l[1].split('.')[0].toInt();
if (args_l.length() > 2) {
filter = QStringList(args_l.mid(2)).join(",");
}
have_args = true;
}
RpcServiceResponseTimeDialog *dce_rpc_dlg = new RpcServiceResponseTimeDialog(parent, cf, get_srt_table_by_name("dcerpc"), DceRpc, filter);
if (have_args) {
if (program_name.isEmpty()) {
dce_rpc_dlg->setDceRpcUuidAndVersion(&uuid, version);
} else {
dce_rpc_dlg->setRpcNameAndVersion(program_name, version);
}
}
// Else the GTK+ UI throws an error.
return dce_rpc_dlg;
}
TapParameterDialog *RpcServiceResponseTimeDialog::createOncRpcSrtDialog(QWidget &parent, const QString, const QString opt_arg, CaptureFile &cf)
{
QString filter;
bool have_args = false;
QString program_name;
int program_num = 0;
int version = 0;
// rpc,srt,<program>,<version>[,<filter>
QStringList args_l = QString(opt_arg).split(',');
if (args_l.length() > 1) {
bool ok = false;
program_num = args_l[0].toInt(&ok);
if (!ok) {
program_name = args_l[0];
}
version = args_l[1].toInt();
if (args_l.length() > 2) {
filter = QStringList(args_l.mid(2)).join(",");
}
have_args = true;
}
RpcServiceResponseTimeDialog *onc_rpc_dlg = new RpcServiceResponseTimeDialog(parent, cf, get_srt_table_by_name("rpc"), OncRpc, filter);
if (have_args) {
if (program_name.isEmpty()) {
onc_rpc_dlg->setOncRpcProgramAndVersion(program_num, version);
} else {
onc_rpc_dlg->setRpcNameAndVersion(program_name, version);
}
}
// Else the GTK+ UI throws an error.
return onc_rpc_dlg;
}
void RpcServiceResponseTimeDialog::addDceRpcProgram(_guid_key *key, _dcerpc_uuid_value *value)
{
dce_name_to_uuid_key_.insert(value->name, key);
}
void RpcServiceResponseTimeDialog::addDceRpcProgramVersion(_guid_key *key)
{
if (guid_cmp(&(dce_name_to_uuid_key_[program_combo_->currentText()]->guid), &(key->guid))) return;
versions_ << key->ver;
std::sort(versions_.begin(), versions_.end());
}
void RpcServiceResponseTimeDialog::addOncRpcProgram(guint32 program, _rpc_prog_info_value *value)
{
onc_name_to_program_.insert(value->progname, program);
}
void RpcServiceResponseTimeDialog::addOncRpcProgramVersion(guint32 program, guint32 version)
{
if (onc_name_to_program_[program_combo_->currentText()] != program) return;
if (versions_.isEmpty()) {
versions_ << version;
return;
}
while (version < versions_.first()) {
versions_.prepend(versions_.first() - 1);
}
while (version > versions_.last()) {
versions_.append(versions_.last() + 1);
}
}
void RpcServiceResponseTimeDialog::updateOncRpcProcedureCount(guint32 program, guint32 version, int procedure)
{
if (onc_name_to_program_[program_combo_->currentText()] != program) return;
if (version_combo_->itemData(version_combo_->currentIndex()).toUInt() != version) return;
if (procedure > onc_rpc_num_procedures_) onc_rpc_num_procedures_ = procedure;
}
void RpcServiceResponseTimeDialog::setDceRpcUuidAndVersion(_e_guid_t *uuid, int version)
{
bool found = false;
for (int pi = 0; pi < program_combo_->count(); pi++) {
if (guid_cmp(uuid, &(dce_name_to_uuid_key_[program_combo_->itemText(pi)]->guid)) == 0) {
program_combo_->setCurrentIndex(pi);
for (int vi = 0; vi < version_combo_->count(); vi++) {
if (version == (int) version_combo_->itemData(vi).toUInt()) {
version_combo_->setCurrentIndex(vi);
found = true;
break;
}
}
break;
}
}
if (found) fillTree();
}
void RpcServiceResponseTimeDialog::setOncRpcProgramAndVersion(int program, int version)
{
bool found = false;
for (int pi = 0; pi < program_combo_->count(); pi++) {
if (program == (int) onc_name_to_program_[program_combo_->itemText(pi)]) {
program_combo_->setCurrentIndex(pi);
for (int vi = 0; vi < version_combo_->count(); vi++) {
if (version == (int) version_combo_->itemData(vi).toUInt()) {
version_combo_->setCurrentIndex(vi);
found = true;
break;
}
}
break;
}
}
if (found) fillTree();
}
void RpcServiceResponseTimeDialog::setRpcNameAndVersion(const QString &program_name, int version)
{
bool found = false;
for (int pi = 0; pi < program_combo_->count(); pi++) {
if (program_name.compare(program_combo_->itemText(pi), Qt::CaseInsensitive) == 0) {
program_combo_->setCurrentIndex(pi);
for (int vi = 0; vi < version_combo_->count(); vi++) {
if (version == (int) version_combo_->itemData(vi).toUInt()) {
version_combo_->setCurrentIndex(vi);
found = true;
break;
}
}
break;
}
}
if (found) fillTree();
}
void RpcServiceResponseTimeDialog::dceRpcProgramChanged(const QString &program_name)
{
clearVersionCombo();
if (!dce_name_to_uuid_key_.contains(program_name)) return;
g_hash_table_foreach(dcerpc_uuids, dce_rpc_find_versions, this);
fillVersionCombo();
}
void RpcServiceResponseTimeDialog::oncRpcProgramChanged(const QString &program_name)
{
clearVersionCombo();
if (!onc_name_to_program_.contains(program_name)) return;
dissector_table_foreach ("rpc.call", onc_rpc_find_versions, this);
dissector_table_foreach ("rpc.reply", onc_rpc_find_versions, this);
fillVersionCombo();
}
void RpcServiceResponseTimeDialog::clearVersionCombo()
{
version_combo_->clear();
versions_.clear();
}
void RpcServiceResponseTimeDialog::fillVersionCombo()
{
foreach (unsigned version, versions_) {
version_combo_->addItem(QString::number(version), version);
}
if (versions_.count() > 0) {
// Select the highest-numbered version.
version_combo_->setCurrentIndex(static_cast<int>(versions_.count()) - 1);
}
}
void RpcServiceResponseTimeDialog::provideParameterData()
{
void *tap_data = NULL;
const QString program_name = program_combo_->currentText();
guint32 max_procs = 0;
switch (dlg_type_) {
case DceRpc:
{
if (!dce_name_to_uuid_key_.contains(program_name)) return;
guid_key *dkey = dce_name_to_uuid_key_[program_name];
guint16 version = (guint16) version_combo_->itemData(version_combo_->currentIndex()).toUInt();
dcerpc_sub_dissector *procs = dcerpc_get_proto_sub_dissector(&(dkey->guid), version);
if (!procs) return;
dcerpcstat_tap_data_t *dtap_data = g_new0(dcerpcstat_tap_data_t, 1);
dtap_data->uuid = dkey->guid;
dtap_data->ver = version;
dtap_data->prog = dcerpc_get_proto_name(&dtap_data->uuid, dtap_data->ver);
for (int i = 0; procs[i].name; i++) {
if (procs[i].num > max_procs) max_procs = procs[i].num;
}
dtap_data->num_procedures = max_procs + 1;
tap_data = dtap_data;
break;
}
case OncRpc:
{
if (!onc_name_to_program_.contains(program_name)) return;
rpcstat_tap_data_t *otap_data = g_new0(rpcstat_tap_data_t, 1);
otap_data->program = onc_name_to_program_[program_name];
otap_data->prog = rpc_prog_name(otap_data->program);
otap_data->version = (guint32) version_combo_->itemData(version_combo_->currentIndex()).toUInt();
onc_rpc_num_procedures_ = -1;
dissector_table_foreach ("rpc.call", onc_rpc_count_procedures, this);
dissector_table_foreach ("rpc.reply", onc_rpc_count_procedures, this);
otap_data->num_procedures = onc_rpc_num_procedures_ + 1;
tap_data = otap_data;
break;
}
}
set_srt_table_param_data(srt_, tap_data);
} |
C/C++ | wireshark/ui/qt/rpc_service_response_time_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 __RPC_SERVICE_RESPONSE_TIME_DIALOG_H__
#define __RPC_SERVICE_RESPONSE_TIME_DIALOG_H__
#include "service_response_time_dialog.h"
class QComboBox;
struct _guid_key;
struct _dcerpc_uuid_value;
struct _e_guid_t;
struct _rpc_prog_info_value;
class RpcServiceResponseTimeDialog : public ServiceResponseTimeDialog
{
Q_OBJECT
public:
enum RpcFamily {
DceRpc,
OncRpc
};
RpcServiceResponseTimeDialog(QWidget &parent, CaptureFile &cf, struct register_srt *srt, RpcFamily dlg_type, const QString filter);
static TapParameterDialog *createDceRpcSrtDialog(QWidget &parent, const QString, const QString opt_arg, CaptureFile &cf);
static TapParameterDialog *createOncRpcSrtDialog(QWidget &parent, const QString, const QString opt_arg, CaptureFile &cf);
void addDceRpcProgram(_guid_key *key, struct _dcerpc_uuid_value *value);
void addDceRpcProgramVersion(_guid_key *key);
void addOncRpcProgram(guint32 program, struct _rpc_prog_info_value *value);
void addOncRpcProgramVersion(guint32 program, guint32 version);
void updateOncRpcProcedureCount(guint32 program, guint32 version, int procedure);
void setDceRpcUuidAndVersion(struct _e_guid_t *uuid, int version);
void setOncRpcProgramAndVersion(int program, int version);
void setRpcNameAndVersion(const QString &program_name, int version);
protected:
virtual void provideParameterData();
public slots:
void dceRpcProgramChanged(const QString &program_name);
void oncRpcProgramChanged(const QString &program_name);
private:
RpcFamily dlg_type_;
QComboBox *program_combo_;
QComboBox *version_combo_;
QList<unsigned> versions_;
// DCE-RPC
QMap<QString, struct _guid_key *> dce_name_to_uuid_key_;
// ONC-RPC
QMap<QString, guint32> onc_name_to_program_;
int onc_rpc_num_procedures_;
void clearVersionCombo();
void fillVersionCombo();
};
#endif // __RPC_SERVICE_RESPONSE_TIME_DIALOG_H__ |
C++ | wireshark/ui/qt/rsa_keys_frame.cpp | /* rsa_keys_frame.cpp
*
* Copyright 2019 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 <config.h>
#include "rsa_keys_frame.h"
#include <ui_rsa_keys_frame.h>
#include "ui/qt/widgets/wireshark_file_dialog.h"
#include <wsutil/report_message.h>
#include <QMessageBox>
#include <ui/all_files_wildcard.h>
#include <epan/secrets.h>
#include <QInputDialog>
#ifdef HAVE_LIBGNUTLS
RsaKeysFrame::RsaKeysFrame(QWidget *parent) :
QFrame(parent),
ui(new Ui::RsaKeysFrame),
rsa_keys_model_(0),
pkcs11_libs_model_(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
ui->addFileButton->setAttribute(Qt::WA_MacSmallSize, true);
ui->addItemButton->setAttribute(Qt::WA_MacSmallSize, true);
ui->deleteItemButton->setAttribute(Qt::WA_MacSmallSize, true);
ui->addLibraryButton->setAttribute(Qt::WA_MacSmallSize, true);
ui->deleteLibraryButton->setAttribute(Qt::WA_MacSmallSize, true);
#endif
#ifdef HAVE_GNUTLS_PKCS11
pkcs11_libs_model_ = new UatModel(this, "PKCS #11 Provider Libraries");
ui->libsView->setModel(pkcs11_libs_model_);
connect(ui->libsView->selectionModel(), &QItemSelectionModel::currentChanged,
this, &RsaKeysFrame::libCurrentChanged);
#else
ui->addLibraryButton->setEnabled(false);
#endif
rsa_keys_model_ = new UatModel(this, "RSA Private Keys");
ui->keysView->setModel(rsa_keys_model_);
connect(ui->keysView->selectionModel(), &QItemSelectionModel::currentChanged,
this, &RsaKeysFrame::keyCurrentChanged);
}
#else /* ! HAVE_LIBGNUTLS */
RsaKeysFrame::RsaKeysFrame(QWidget *parent) : QFrame(parent) { }
#endif /* ! HAVE_LIBGNUTLS */
#ifdef HAVE_LIBGNUTLS
RsaKeysFrame::~RsaKeysFrame()
{
delete ui;
}
gboolean RsaKeysFrame::verifyKey(const char *uri, const char *password, gboolean *need_password, QString &error)
{
char *error_c = NULL;
gboolean key_ok = secrets_verify_key(qPrintable(uri), qPrintable(password), need_password, &error_c);
error = error_c ? error_c : "";
g_free(error_c);
return key_ok;
}
void RsaKeysFrame::addKey(const QString &uri, const QString &password)
{
// Create a new UAT entry with the given URI and PIN/password.
int row = rsa_keys_model_->rowCount();
rsa_keys_model_->insertRows(row, 1);
rsa_keys_model_->setData(rsa_keys_model_->index(row, 0), uri);
rsa_keys_model_->setData(rsa_keys_model_->index(row, 1), password);
ui->keysView->setCurrentIndex(rsa_keys_model_->index(row, 0));
}
void RsaKeysFrame::keyCurrentChanged(const QModelIndex ¤t, const QModelIndex & /* previous */)
{
ui->deleteItemButton->setEnabled(current.isValid());
}
void RsaKeysFrame::on_addItemButton_clicked()
{
GSList *keys_list = secrets_get_available_keys();
QStringList keys;
if (keys_list) {
for (GSList *uri = keys_list; uri; uri = uri->next) {
keys << (char *)uri->data;
}
g_slist_free_full(keys_list, g_free);
}
// Remove duplicates (keys that have already been added)
for (int row = rsa_keys_model_->rowCount() - 1; row >= 0; --row) {
QString item = rsa_keys_model_->data(rsa_keys_model_->index(row, 0)).toString();
keys.removeAll(item);
}
if (keys.isEmpty()) {
QMessageBox::information(this, tr("Add PKCS #11 token or key"),
tr("No new PKCS #11 tokens or keys found, consider adding a PKCS #11 provider."),
QMessageBox::Ok);
return;
}
bool ok;
QString item = QInputDialog::getItem(this,
tr("Select a new PKCS #11 token or key"),
tr("PKCS #11 token or key"), keys, 0, false, &ok);
if (!ok || item.isEmpty()) {
return;
}
// Validate the token, is a PIN needed?
gboolean key_ok = false, needs_pin = true;
QString error;
if (!item.startsWith("pkcs11:")) {
// For keys other than pkcs11, try to verify the key without password.
// (The PIN must always be prompted for PKCS #11 tokens, otherwise it is
// possible that an already unlocked token will not trigger a prompt).
key_ok = verifyKey(qPrintable(item), NULL, &needs_pin, error);
}
QString pin;
while (!key_ok && needs_pin) {
// A PIN is possibly needed, prompt for one.
QString msg;
if (!error.isEmpty()) {
msg = error + "\n";
error.clear();
}
msg += tr("Enter PIN or password for %1 (it will be stored unencrypted)");
pin = QInputDialog::getText(this, tr("Enter PIN or password for key"),
msg.arg(item), QLineEdit::Password, "", &ok);
if (!ok) {
return;
}
key_ok = verifyKey(qPrintable(item), qPrintable(pin), NULL, error);
}
if (!key_ok) {
QMessageBox::warning(this,
tr("Add PKCS #11 token or key"),
tr("Key could not be added: %1").arg(item),
QMessageBox::Ok);
return;
}
addKey(item, pin);
}
void RsaKeysFrame::on_addFileButton_clicked()
{
QString filter =
tr("RSA private key (*.pem *.p12 *.pfx *.key);;All Files (" ALL_FILES_WILDCARD ")");
QString file = WiresharkFileDialog::getOpenFileName(this,
tr("Select RSA private key file"), "", filter);
if (file.isEmpty()) {
return;
}
// Try to load the key as unencrypted key file. If any errors occur, assume
// an encrypted key file and prompt for a password.
QString password, error;
gboolean key_ok = secrets_verify_key(qPrintable(file), NULL, NULL, NULL);
while (!key_ok) {
QString msg;
if (!error.isEmpty()) {
msg = error + "\n";
error.clear();
}
msg += QString("Enter the password to open %1").arg(file);
bool ok;
password = QInputDialog::getText(this, tr("Select RSA private key file"), msg,
QLineEdit::Password, "", &ok);
if (!ok) {
return;
}
key_ok = verifyKey(qPrintable(file), qPrintable(password), NULL, error);
}
addKey(file, password);
}
void RsaKeysFrame::on_deleteItemButton_clicked()
{
const QModelIndex ¤t = ui->keysView->currentIndex();
if (rsa_keys_model_ && current.isValid()) {
rsa_keys_model_->removeRows(current.row(), 1);
}
}
void RsaKeysFrame::acceptChanges()
{
// Save keys list mutations. The PKCS #11 provider list was already saved.
QString error;
if (rsa_keys_model_->applyChanges(error) && !error.isEmpty()) {
report_failure("%s", qPrintable(error));
}
}
void RsaKeysFrame::rejectChanges()
{
// Revert keys list mutations. The PKCS #11 provider list was already saved.
QString error;
if (rsa_keys_model_->revertChanges(error) && !error.isEmpty()) {
report_failure("%s", qPrintable(error));
}
}
void RsaKeysFrame::libCurrentChanged(const QModelIndex ¤t, const QModelIndex & /* previous */)
{
ui->deleteLibraryButton->setEnabled(current.isValid());
}
void RsaKeysFrame::on_addLibraryButton_clicked()
{
if (!pkcs11_libs_model_) return;
#ifdef Q_OS_WIN
QString filter(tr("Libraries (*.dll)"));
#else
QString filter(tr("Libraries (*.so)"));
#endif
QString file = WiresharkFileDialog::getOpenFileName(this, tr("Select PKCS #11 Provider Library"), "", filter);
if (file.isEmpty()) {
return;
}
int row = pkcs11_libs_model_->rowCount();
pkcs11_libs_model_->insertRows(row, 1);
pkcs11_libs_model_->setData(pkcs11_libs_model_->index(row, 0), file);
ui->libsView->setCurrentIndex(pkcs11_libs_model_->index(row, 0));
// As the libraries affect the availability of PKCS #11 tokens, we will
// immediately apply changes without waiting for the OK button to be
// activated.
QString error;
if (pkcs11_libs_model_->applyChanges(error) && error.isEmpty()) {
report_failure("%s", qPrintable(error));
}
}
void RsaKeysFrame::on_deleteLibraryButton_clicked()
{
if (!pkcs11_libs_model_) return;
const QModelIndex ¤t = ui->libsView->currentIndex();
if (!current.isValid()) {
return;
}
QString file = pkcs11_libs_model_->data(current, 0).toString();
pkcs11_libs_model_->removeRows(current.row(), 1);
// Due to technical limitations of GnuTLS, libraries cannot be unloaded or
// disabled once loaded. Inform the user of this caveat.
QMessageBox::information(this, tr("Changes will apply after a restart"),
tr("PKCS #11 provider %1 will be removed after the next restart.").arg(file),
QMessageBox::Ok);
// Make sure the UAT is actually saved to file.
QString error;
if (pkcs11_libs_model_->applyChanges(error) && error.isEmpty()) {
report_failure("%s", qPrintable(error));
}
}
#endif /* HAVE_LIBGNUTLS */ |
C/C++ | wireshark/ui/qt/rsa_keys_frame.h | /** @file
*
* Copyright 2019 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 RSA_KEYS_FRAME_H
#define RSA_KEYS_FRAME_H
#include <config.h>
#include <QFrame>
#include <ui/qt/models/uat_model.h>
namespace Ui {
class RsaKeysFrame;
}
class RsaKeysFrame : public QFrame
{
Q_OBJECT
public:
explicit RsaKeysFrame(QWidget *parent = NULL);
#ifdef HAVE_LIBGNUTLS
~RsaKeysFrame();
void acceptChanges();
void rejectChanges();
private:
Ui::RsaKeysFrame *ui;
UatModel *rsa_keys_model_;
UatModel *pkcs11_libs_model_;
gboolean verifyKey(const char *uri, const char *password, gboolean *need_password, QString &error);
void addKey(const QString &uri, const QString &password);
private slots:
void keyCurrentChanged(const QModelIndex ¤t, const QModelIndex &previous);
void on_addFileButton_clicked();
void on_addItemButton_clicked();
void on_deleteItemButton_clicked();
void libCurrentChanged(const QModelIndex ¤t, const QModelIndex &previous);
void on_addLibraryButton_clicked();
void on_deleteLibraryButton_clicked();
#endif /* HAVE_LIBGNUTLS */
};
#endif /* RSA_KEYS_FRAME_H */ |
User Interface | wireshark/ui/qt/rsa_keys_frame.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>RsaKeysFrame</class>
<widget class="QFrame" name="RsaKeysFrame">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QGroupBox" name="groupBox">
<property name="title">
<string>RSA Keys</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QLabel" name="keysLabel">
<property name="text">
<string>RSA private keys are loaded from a file or PKCS #11 token.</string>
</property>
</widget>
</item>
<item>
<widget class="QListView" name="keysView"/>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="addFileButton">
<property name="text">
<string>Add new keyfile…</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="addItemButton">
<property name="text">
<string>Add new token…</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="deleteItemButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Remove key</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="libsLabel">
<property name="text">
<string>PKCS #11 provider libraries.</string>
</property>
</widget>
</item>
<item>
<widget class="QListView" name="libsView">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>54</height>
</size>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QPushButton" name="addLibraryButton">
<property name="text">
<string>Add new provider…</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="deleteLibraryButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Remove provider</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui> |
C++ | wireshark/ui/qt/rtp_analysis_dialog.cpp | /* rtp_analysis_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "rtp_analysis_dialog.h"
#include <ui_rtp_analysis_dialog.h>
#include "file.h"
#include "frame_tvbuff.h"
#include "epan/epan_dissect.h"
#include <epan/addr_resolv.h>
#include "epan/rtp_pt.h"
#include "epan/dfilter/dfilter.h"
#include "epan/dissectors/packet-rtp.h"
#include <ui/rtp_media.h>
#include "ui/help_url.h"
#include "ui/simple_dialog.h"
#include <wsutil/utf8_entities.h>
#include <wsutil/g711.h>
#include <wsutil/pint.h>
#include <QMessageBox>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QToolButton>
#include <QWidget>
#include <QCheckBox>
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "rtp_player_dialog.h"
#include <ui/qt/utils/stock_icon.h>
#include "main_application.h"
#include "ui/qt/widgets/wireshark_file_dialog.h"
/*
* @file RTP stream analysis dialog
*
* Displays forward and reverse RTP streams and graphs each stream
*/
// To do:
// - Progress bar for tapping and saving.
// - Add a refresh button and/or action.
// - Fixup output file names.
// - Add a graph title and legend when saving?
enum {
packet_col_,
sequence_col_,
delta_col_,
jitter_col_,
skew_col_,
bandwidth_col_,
marker_col_,
status_col_
};
static const QRgb color_cn_ = 0xbfbfff;
static const QRgb color_rtp_warn_ = 0xffdbbf;
static const QRgb color_pt_event_ = 0xefffff;
enum { rtp_analysis_type_ = 1000 };
class RtpAnalysisTreeWidgetItem : public QTreeWidgetItem
{
public:
RtpAnalysisTreeWidgetItem(QTreeWidget *tree, tap_rtp_stat_t *statinfo, packet_info *pinfo, const struct _rtp_info *rtpinfo) :
QTreeWidgetItem(tree, rtp_analysis_type_)
{
frame_num_ = pinfo->num;
sequence_num_ = rtpinfo->info_seq_num;
pkt_len_ = pinfo->fd->pkt_len;
flags_ = statinfo->flags;
if (flags_ & STAT_FLAG_FIRST) {
delta_ = 0.0;
jitter_ = 0.0;
skew_ = 0.0;
} else {
delta_ = statinfo->delta;
jitter_ = statinfo->jitter;
skew_ = statinfo->skew;
}
bandwidth_ = statinfo->bandwidth;
marker_ = rtpinfo->info_marker_set ? true : false;
ok_ = false;
QColor bg_color = QColor();
QString status;
if (statinfo->pt == PT_CN) {
status = "Comfort noise (PT=13, RFC 3389)";
bg_color = color_cn_;
} else if (statinfo->pt == PT_CN_OLD) {
status = "Comfort noise (PT=19, reserved)";
bg_color = color_cn_;
} else if (statinfo->flags & STAT_FLAG_WRONG_SEQ) {
status = "Wrong sequence number";
bg_color = ColorUtils::expert_color_error;
} else if (statinfo->flags & STAT_FLAG_DUP_PKT) {
status = "Suspected duplicate (MAC address) only delta time calculated";
bg_color = color_rtp_warn_;
} else if (statinfo->flags & STAT_FLAG_REG_PT_CHANGE) {
status = QString("Payload changed to PT=%1").arg(statinfo->pt);
if (statinfo->flags & STAT_FLAG_PT_T_EVENT) {
status.append(" telephone/event");
}
bg_color = color_rtp_warn_;
} else if (statinfo->flags & STAT_FLAG_WRONG_TIMESTAMP) {
status = "Incorrect timestamp";
/* color = COLOR_WARNING; */
bg_color = color_rtp_warn_;
} else if ((statinfo->flags & STAT_FLAG_PT_CHANGE)
&& !(statinfo->flags & STAT_FLAG_FIRST)
&& !(statinfo->flags & STAT_FLAG_PT_CN)
&& (statinfo->flags & STAT_FLAG_FOLLOW_PT_CN)
&& !(statinfo->flags & STAT_FLAG_MARKER)) {
status = "Marker missing?";
bg_color = color_rtp_warn_;
} else if (statinfo->flags & STAT_FLAG_PT_T_EVENT) {
status = QString("PT=%1 telephone/event").arg(statinfo->pt);
/* XXX add color? */
bg_color = color_pt_event_;
} else {
if (statinfo->flags & STAT_FLAG_MARKER) {
bg_color = color_rtp_warn_;
}
}
if (status.isEmpty()) {
ok_ = true;
status = UTF8_CHECK_MARK;
}
setText(packet_col_, QString::number(frame_num_));
setText(sequence_col_, QString::number(sequence_num_));
setText(delta_col_, QString::number(delta_, 'f', prefs.gui_decimal_places3));
setText(jitter_col_, QString::number(jitter_, 'f', prefs.gui_decimal_places3));
setText(skew_col_, QString::number(skew_, 'f', prefs.gui_decimal_places3));
setText(bandwidth_col_, QString::number(bandwidth_, 'f', prefs.gui_decimal_places1));
if (marker_) {
setText(marker_col_, UTF8_BULLET);
}
setText(status_col_, status);
setTextAlignment(packet_col_, Qt::AlignRight);
setTextAlignment(sequence_col_, Qt::AlignRight);
setTextAlignment(delta_col_, Qt::AlignRight);
setTextAlignment(jitter_col_, Qt::AlignRight);
setTextAlignment(skew_col_, Qt::AlignRight);
setTextAlignment(bandwidth_col_, Qt::AlignRight);
setTextAlignment(marker_col_, Qt::AlignCenter);
if (bg_color.isValid()) {
for (int col = 0; col < columnCount(); col++) {
setBackground(col, bg_color);
setForeground(col, ColorUtils::expert_color_foreground);
}
}
}
uint32_t frameNum() { return frame_num_; }
bool frameStatus() { return ok_; }
QList<QVariant> rowData() {
QString marker_str;
QString status_str = ok_ ? "OK" : text(status_col_);
if (marker_) marker_str = "SET";
return QList<QVariant>()
<< frame_num_ << sequence_num_ << delta_ << jitter_ << skew_ << bandwidth_
<< marker_str << status_str;
}
bool operator< (const QTreeWidgetItem &other) const
{
if (other.type() != rtp_analysis_type_) return QTreeWidgetItem::operator< (other);
const RtpAnalysisTreeWidgetItem *other_row = static_cast<const RtpAnalysisTreeWidgetItem *>(&other);
switch (treeWidget()->sortColumn()) {
case (packet_col_):
return frame_num_ < other_row->frame_num_;
break;
case (sequence_col_):
return sequence_num_ < other_row->sequence_num_;
break;
case (delta_col_):
return delta_ < other_row->delta_;
break;
case (jitter_col_):
return jitter_ < other_row->jitter_;
break;
case (skew_col_):
return skew_ < other_row->skew_;
break;
case (bandwidth_col_):
return bandwidth_ < other_row->bandwidth_;
break;
default:
break;
}
// Fall back to string comparison
return QTreeWidgetItem::operator <(other);
}
private:
uint32_t frame_num_;
uint32_t sequence_num_;
uint32_t pkt_len_;
uint32_t flags_;
double delta_;
double jitter_;
double skew_;
double bandwidth_;
bool marker_;
bool ok_;
};
enum {
fwd_jitter_graph_,
fwd_diff_graph_,
fwd_delta_graph_,
rev_jitter_graph_,
rev_diff_graph_,
rev_delta_graph_,
num_graphs_
};
RtpAnalysisDialog *RtpAnalysisDialog::pinstance_{nullptr};
std::mutex RtpAnalysisDialog::init_mutex_;
std::mutex RtpAnalysisDialog::run_mutex_;
RtpAnalysisDialog *RtpAnalysisDialog::openRtpAnalysisDialog(QWidget &parent, CaptureFile &cf, QObject *packet_list)
{
std::lock_guard<std::mutex> lock(init_mutex_);
if (pinstance_ == nullptr)
{
pinstance_ = new RtpAnalysisDialog(parent, cf);
connect(pinstance_, SIGNAL(goToPacket(int)),
packet_list, SLOT(goToPacket(int)));
}
return pinstance_;
}
RtpAnalysisDialog::RtpAnalysisDialog(QWidget &parent, CaptureFile &cf) :
WiresharkDialog(parent, cf),
ui(new Ui::RtpAnalysisDialog),
tab_seq(0)
{
ui->setupUi(this);
loadGeometry(parent.width() * 4 / 5, parent.height() * 4 / 5);
setWindowSubtitle(tr("RTP Stream Analysis"));
// Used when tab contains IPs
//ui->tabWidget->setStyleSheet("QTabBar::tab { height: 7ex; }");
ui->tabWidget->tabBar()->setTabsClosable(true);
ui->progressFrame->hide();
stream_ctx_menu_.addAction(ui->actionGoToPacket);
stream_ctx_menu_.addAction(ui->actionNextProblem);
set_action_shortcuts_visible_in_context_menu(stream_ctx_menu_.actions());
connect(ui->streamGraph, SIGNAL(mousePress(QMouseEvent*)),
this, SLOT(graphClicked(QMouseEvent*)));
graph_ctx_menu_.addAction(ui->actionSaveGraph);
ui->streamGraph->xAxis->setLabel("Arrival Time");
ui->streamGraph->yAxis->setLabel("Value (ms)");
QPushButton *prepare_button = ui->buttonBox->addButton(ui->actionPrepareButton->text(), QDialogButtonBox::ActionRole);
prepare_button->setToolTip(ui->actionPrepareButton->toolTip());
prepare_button->setMenu(ui->menuPrepareFilter);
player_button_ = RtpPlayerDialog::addPlayerButton(ui->buttonBox, this);
QPushButton *export_btn = ui->buttonBox->addButton(ui->actionExportButton->text(), QDialogButtonBox::ActionRole);
export_btn->setToolTip(ui->actionExportButton->toolTip());
QMenu *save_menu = new QMenu(export_btn);
save_menu->addAction(ui->actionSaveOneCsv);
save_menu->addAction(ui->actionSaveAllCsv);
save_menu->addSeparator();
save_menu->addAction(ui->actionSaveGraph);
export_btn->setMenu(save_menu);
connect(ui->tabWidget, SIGNAL(currentChanged(int)),
this, SLOT(updateWidgets()));
connect(ui->tabWidget->tabBar(), SIGNAL(tabCloseRequested(int)),
this, SLOT(closeTab(int)));
connect(this, SIGNAL(updateFilter(QString, bool)),
&parent, SLOT(filterPackets(QString, bool)));
connect(this, SIGNAL(rtpPlayerDialogReplaceRtpStreams(QVector<rtpstream_id_t *>)),
&parent, SLOT(rtpPlayerDialogReplaceRtpStreams(QVector<rtpstream_id_t *>)));
connect(this, SIGNAL(rtpPlayerDialogAddRtpStreams(QVector<rtpstream_id_t *>)),
&parent, SLOT(rtpPlayerDialogAddRtpStreams(QVector<rtpstream_id_t *>)));
connect(this, SIGNAL(rtpPlayerDialogRemoveRtpStreams(QVector<rtpstream_id_t *>)),
&parent, SLOT(rtpPlayerDialogRemoveRtpStreams(QVector<rtpstream_id_t *>)));
updateWidgets();
updateStatistics();
}
RtpAnalysisDialog::~RtpAnalysisDialog()
{
std::lock_guard<std::mutex> lock(init_mutex_);
if (pinstance_ != nullptr) {
delete ui;
for(int i=0; i<tabs_.count(); i++) {
deleteTabInfo(tabs_[i]);
g_free(tabs_[i]);
}
pinstance_ = nullptr;
}
}
void RtpAnalysisDialog::deleteTabInfo(tab_info_t *tab_info)
{
delete tab_info->time_vals;
delete tab_info->jitter_vals;
delete tab_info->diff_vals;
delete tab_info->delta_vals;
delete tab_info->tab_name;
// tab_info->tree_widget was deleted by ui
// tab_info->statistics_label was deleted by ui
rtpstream_info_free_data(&tab_info->stream);
}
int RtpAnalysisDialog::addTabUI(tab_info_t *new_tab)
{
int new_tab_no;
rtpstream_info_calc_t s_calc;
rtpstream_info_calculate(&new_tab->stream, &s_calc);
new_tab->tab_name = new QString(QString("%1:%2 " UTF8_RIGHTWARDS_ARROW "\n%3:%4\n(%5)")
.arg(s_calc.src_addr_str)
.arg(s_calc.src_port)
.arg(s_calc.dst_addr_str)
.arg(s_calc.dst_port)
.arg(int_to_qstring(s_calc.ssrc, 8, 16)));
rtpstream_info_calc_free(&s_calc);
QWidget *tab = new QWidget();
tab->setProperty("tab_data", QVariant::fromValue((void *)new_tab));
QHBoxLayout *horizontalLayout = new QHBoxLayout(tab);
QVBoxLayout *verticalLayout = new QVBoxLayout();
new_tab->statistics_label = new QLabel();
//new_tab->statistics_label->setStyleSheet("QLabel { color : blue; }");
new_tab->statistics_label->setTextFormat(Qt::RichText);
new_tab->statistics_label->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
verticalLayout->addWidget(new_tab->statistics_label);
QSpacerItem *verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout->addItem(verticalSpacer);
horizontalLayout->addLayout(verticalLayout);
new_tab->tree_widget = new QTreeWidget();
new_tab->tree_widget->setRootIsDecorated(false);
new_tab->tree_widget->setUniformRowHeights(true);
new_tab->tree_widget->setItemsExpandable(false);
new_tab->tree_widget->setSortingEnabled(true);
new_tab->tree_widget->setExpandsOnDoubleClick(false);
new_tab->tree_widget->installEventFilter(this);
new_tab->tree_widget->setContextMenuPolicy(Qt::CustomContextMenu);
new_tab->tree_widget->header()->setSortIndicator(0, Qt::AscendingOrder);
connect(new_tab->tree_widget, SIGNAL(customContextMenuRequested(QPoint)),
SLOT(showStreamMenu(QPoint)));
connect(new_tab->tree_widget, SIGNAL(itemSelectionChanged()),
this, SLOT(updateWidgets()));
QTreeWidgetItem *ti = new_tab->tree_widget->headerItem();
ti->setText(packet_col_, tr("Packet"));
ti->setText(sequence_col_, tr("Sequence"));
ti->setText(delta_col_, tr("Delta (ms)"));
ti->setText(jitter_col_, tr("Jitter (ms)"));
ti->setText(skew_col_, tr("Skew"));
ti->setText(bandwidth_col_, tr("Bandwidth"));
ti->setText(marker_col_, tr("Marker"));
ti->setText(status_col_, tr("Status"));
QColor color = ColorUtils::graphColor(tab_seq++);
ui->tabWidget->setUpdatesEnabled(false);
horizontalLayout->addWidget(new_tab->tree_widget);
new_tab_no = ui->tabWidget->count() - 1;
// Used when tab contains IPs
//ui->tabWidget->insertTab(new_tab_no, tab, *new_tab->tab_name);
ui->tabWidget->insertTab(new_tab_no, tab, QString(tr("Stream %1")).arg(tab_seq - 1));
ui->tabWidget->tabBar()->setTabTextColor(new_tab_no, color);
ui->tabWidget->tabBar()->setTabToolTip(new_tab_no, *new_tab->tab_name);
ui->tabWidget->setUpdatesEnabled(true);
QPen pen = QPen(color);
QCPScatterStyle jitter_shape;
QCPScatterStyle diff_shape;
QCPScatterStyle delta_shape;
jitter_shape.setShape(QCPScatterStyle::ssCircle);
//jitter_shape.setSize(5);
diff_shape.setShape(QCPScatterStyle::ssCross);
//diff_shape.setSize(5);
delta_shape.setShape(QCPScatterStyle::ssTriangle);
//delta_shape.setSize(5);
new_tab->jitter_graph = ui->streamGraph->addGraph();
new_tab->diff_graph = ui->streamGraph->addGraph();
new_tab->delta_graph = ui->streamGraph->addGraph();
new_tab->jitter_graph->setPen(pen);
new_tab->diff_graph->setPen(pen);
new_tab->delta_graph->setPen(pen);
new_tab->jitter_graph->setScatterStyle(jitter_shape);
new_tab->diff_graph->setScatterStyle(diff_shape);
new_tab->delta_graph->setScatterStyle(delta_shape);
new_tab->graphHorizontalLayout = new QHBoxLayout();
new_tab->stream_checkbox = new QCheckBox(tr("Stream %1").arg(tab_seq - 1), ui->graphTab);
new_tab->stream_checkbox->setChecked(true);
new_tab->stream_checkbox->setIcon(StockIcon::colorIcon(color.rgb(), QPalette::Text));
new_tab->graphHorizontalLayout->addWidget(new_tab->stream_checkbox);
new_tab->graphHorizontalLayout->addItem(new QSpacerItem(10, 5, QSizePolicy::Expanding, QSizePolicy::Minimum));
connect(new_tab->stream_checkbox, SIGNAL(stateChanged(int)),
this, SLOT(rowCheckboxChanged(int)));
new_tab->jitter_checkbox = new QCheckBox(tr("Stream %1 Jitter").arg(tab_seq - 1), ui->graphTab);
new_tab->jitter_checkbox->setChecked(true);
new_tab->jitter_checkbox->setIcon(StockIcon::colorIconCircle(color.rgb(), QPalette::Text));
new_tab->graphHorizontalLayout->addWidget(new_tab->jitter_checkbox);
new_tab->graphHorizontalLayout->addItem(new QSpacerItem(10, 5, QSizePolicy::Expanding, QSizePolicy::Minimum));
connect(new_tab->jitter_checkbox, SIGNAL(stateChanged(int)),
this, SLOT(singleCheckboxChanged(int)));
new_tab->diff_checkbox = new QCheckBox(tr("Stream %1 Difference").arg(tab_seq - 1), ui->graphTab);
new_tab->diff_checkbox->setChecked(true);
new_tab->diff_checkbox->setIcon(StockIcon::colorIconCross(color.rgb(), QPalette::Text));
new_tab->graphHorizontalLayout->addWidget(new_tab->diff_checkbox);
new_tab->graphHorizontalLayout->addItem(new QSpacerItem(10, 5, QSizePolicy::Expanding, QSizePolicy::Minimum));
connect(new_tab->diff_checkbox, SIGNAL(stateChanged(int)),
this, SLOT(singleCheckboxChanged(int)));
new_tab->delta_checkbox = new QCheckBox(tr("Stream %1 Delta").arg(tab_seq - 1), ui->graphTab);
new_tab->delta_checkbox->setChecked(true);
new_tab->delta_checkbox->setIcon(StockIcon::colorIconTriangle(color.rgb(), QPalette::Text));
new_tab->graphHorizontalLayout->addWidget(new_tab->delta_checkbox);
new_tab->graphHorizontalLayout->addItem(new QSpacerItem(10, 5, QSizePolicy::Expanding, QSizePolicy::Minimum));
connect(new_tab->delta_checkbox, SIGNAL(stateChanged(int)),
this, SLOT(singleCheckboxChanged(int)));
new_tab->graphHorizontalLayout->setStretch(6, 1);
ui->layout->addLayout(new_tab->graphHorizontalLayout);
return new_tab_no;
}
// Handles all row checkBoxes
void RtpAnalysisDialog::rowCheckboxChanged(int checked)
{
QObject *obj = sender();
// Find correct tab data
for(int i=0; i<tabs_.count(); i++) {
tab_info_t *tab = tabs_[i];
if (obj == tab->stream_checkbox) {
// Set new state for all checkboxes on row
Qt::CheckState new_state;
if (checked) {
new_state = Qt::Checked;
} else {
new_state = Qt::Unchecked;
}
tab->jitter_checkbox->setCheckState(new_state);
tab->diff_checkbox->setCheckState(new_state);
tab->delta_checkbox->setCheckState(new_state);
break;
}
}
}
// Handles all single CheckBoxes
void RtpAnalysisDialog::singleCheckboxChanged(int checked)
{
QObject *obj = sender();
// Find correct tab data
for(int i=0; i<tabs_.count(); i++) {
tab_info_t *tab = tabs_[i];
if (obj == tab->jitter_checkbox) {
tab->jitter_graph->setVisible(checked);
updateGraph();
break;
} else if (obj == tab->diff_checkbox) {
tab->diff_graph->setVisible(checked);
updateGraph();
break;
} else if (obj == tab->delta_checkbox) {
tab->delta_graph->setVisible(checked);
updateGraph();
break;
}
}
}
void RtpAnalysisDialog::updateWidgets()
{
bool enable_tab = false;
bool enable_nav = false;
QString hint = err_str_;
if ((!file_closed_) &&
(tabs_.count() > 0)) {
enable_tab = true;
}
if ((!file_closed_) &&
(tabs_.count() > 0) &&
(ui->tabWidget->currentIndex() < (ui->tabWidget->count()-1))) {
enable_nav = true;
}
ui->actionGoToPacket->setEnabled(enable_nav);
ui->actionNextProblem->setEnabled(enable_nav);
if (enable_nav) {
hint.append(tr(" %1 streams, ").arg(tabs_.count() - 1));
hint.append(tr(" G: Go to packet, N: Next problem packet"));
}
ui->actionExportButton->setEnabled(enable_tab);
ui->actionSaveOneCsv->setEnabled(enable_nav);
ui->actionSaveAllCsv->setEnabled(enable_tab);
ui->actionSaveGraph->setEnabled(enable_tab);
ui->actionPrepareFilterOne->setEnabled(enable_nav);
ui->actionPrepareFilterAll->setEnabled(enable_tab);
#if defined(QT_MULTIMEDIA_LIB)
player_button_->setEnabled(enable_tab);
#endif
ui->tabWidget->setEnabled(enable_tab);
hint.prepend("<small><i>");
hint.append("</i></small>");
ui->hintLabel->setText(hint);
WiresharkDialog::updateWidgets();
}
void RtpAnalysisDialog::on_actionGoToPacket_triggered()
{
tab_info_t *tab_data = getTabInfoForCurrentTab();
if (!tab_data) return;
QTreeWidget *cur_tree = tab_data->tree_widget;
if (!cur_tree || cur_tree->selectedItems().length() < 1) return;
QTreeWidgetItem *ti = cur_tree->selectedItems()[0];
if (ti->type() != rtp_analysis_type_) return;
RtpAnalysisTreeWidgetItem *ra_ti = dynamic_cast<RtpAnalysisTreeWidgetItem *>((RtpAnalysisTreeWidgetItem *)ti);
emit goToPacket(ra_ti->frameNum());
}
void RtpAnalysisDialog::on_actionNextProblem_triggered()
{
tab_info_t *tab_data = getTabInfoForCurrentTab();
if (!tab_data) return;
QTreeWidget *cur_tree = tab_data->tree_widget;
if (!cur_tree || cur_tree->topLevelItemCount() < 2) return;
// Choose convenience over correctness.
if (cur_tree->selectedItems().length() < 1) {
cur_tree->setCurrentItem(cur_tree->topLevelItem(0));
}
QTreeWidgetItem *sel_ti = cur_tree->selectedItems()[0];
if (sel_ti->type() != rtp_analysis_type_) return;
QTreeWidgetItem *test_ti = cur_tree->itemBelow(sel_ti);
if (!test_ti) test_ti = cur_tree->topLevelItem(0);
while (test_ti != sel_ti) {
RtpAnalysisTreeWidgetItem *ra_ti = dynamic_cast<RtpAnalysisTreeWidgetItem *>((RtpAnalysisTreeWidgetItem *)test_ti);
if (!ra_ti->frameStatus()) {
cur_tree->setCurrentItem(ra_ti);
break;
}
test_ti = cur_tree->itemBelow(test_ti);
if (!test_ti) test_ti = cur_tree->topLevelItem(0);
}
}
void RtpAnalysisDialog::on_actionSaveOneCsv_triggered()
{
saveCsv(dir_one_);
}
void RtpAnalysisDialog::on_actionSaveAllCsv_triggered()
{
saveCsv(dir_all_);
}
void RtpAnalysisDialog::on_actionSaveGraph_triggered()
{
ui->tabWidget->setCurrentWidget(ui->graphTab);
QString file_name, extension;
QDir path(mainApp->lastOpenDir());
QString pdf_filter = tr("Portable Document Format (*.pdf)");
QString png_filter = tr("Portable Network Graphics (*.png)");
QString bmp_filter = tr("Windows Bitmap (*.bmp)");
// Gaze upon my beautiful graph with lossy artifacts!
QString jpeg_filter = tr("JPEG File Interchange Format (*.jpeg *.jpg)");
QString filter = QString("%1;;%2;;%3;;%4")
.arg(pdf_filter)
.arg(png_filter)
.arg(bmp_filter)
.arg(jpeg_filter);
QString save_file = path.canonicalPath();
if (!file_closed_) {
save_file += QString("/%1").arg(cap_file_.fileBaseName());
}
file_name = WiresharkFileDialog::getSaveFileName(this, mainApp->windowTitleString(tr("Save Graph As…")),
save_file, filter, &extension);
if (!file_name.isEmpty()) {
bool save_ok = false;
// https://www.qcustomplot.com/index.php/support/forum/63
// ui->streamGraph->legend->setVisible(true);
if (extension.compare(pdf_filter) == 0) {
save_ok = ui->streamGraph->savePdf(file_name);
} else if (extension.compare(png_filter) == 0) {
save_ok = ui->streamGraph->savePng(file_name);
} else if (extension.compare(bmp_filter) == 0) {
save_ok = ui->streamGraph->saveBmp(file_name);
} else if (extension.compare(jpeg_filter) == 0) {
save_ok = ui->streamGraph->saveJpg(file_name);
}
// ui->streamGraph->legend->setVisible(false);
// else error dialog?
if (save_ok) {
mainApp->setLastOpenDirFromFilename(file_name);
}
}
}
void RtpAnalysisDialog::on_buttonBox_helpRequested()
{
mainApp->helpTopicAction(HELP_TELEPHONY_RTP_ANALYSIS_DIALOG);
}
void RtpAnalysisDialog::tapReset(void *tapinfo_ptr)
{
RtpAnalysisDialog *rtp_analysis_dialog = dynamic_cast<RtpAnalysisDialog *>((RtpAnalysisDialog*)tapinfo_ptr);
if (!rtp_analysis_dialog) return;
rtp_analysis_dialog->resetStatistics();
}
tap_packet_status RtpAnalysisDialog::tapPacket(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *, const void *rtpinfo_ptr, tap_flags_t)
{
RtpAnalysisDialog *rtp_analysis_dialog = dynamic_cast<RtpAnalysisDialog *>((RtpAnalysisDialog*)tapinfo_ptr);
if (!rtp_analysis_dialog) return TAP_PACKET_DONT_REDRAW;
const struct _rtp_info *rtpinfo = (const struct _rtp_info *)rtpinfo_ptr;
if (!rtpinfo) return TAP_PACKET_DONT_REDRAW;
/* we ignore packets that are not displayed */
if (pinfo->fd->passed_dfilter == 0)
return TAP_PACKET_DONT_REDRAW;
/* also ignore RTP Version != 2 */
else if (rtpinfo->info_version != 2)
return TAP_PACKET_DONT_REDRAW;
/* is it the forward direction? */
else {
// Search tab in hash key, if there are multiple tabs with same hash
QList<tab_info_t *> tabs = rtp_analysis_dialog->tab_hash_.values(pinfo_rtp_info_to_hash(pinfo, rtpinfo));
for (int i = 0; i < tabs.size(); i++) {
tab_info_t *tab = tabs.at(i);
if (rtpstream_id_equal_pinfo_rtp_info(&tab->stream.id, pinfo, rtpinfo)) {
rtp_analysis_dialog->addPacket(tab, pinfo, rtpinfo);
break;
}
}
}
return TAP_PACKET_DONT_REDRAW;
}
void RtpAnalysisDialog::tapDraw(void *tapinfo_ptr)
{
RtpAnalysisDialog *rtp_analysis_dialog = dynamic_cast<RtpAnalysisDialog *>((RtpAnalysisDialog*)tapinfo_ptr);
if (!rtp_analysis_dialog) return;
rtp_analysis_dialog->updateStatistics();
}
void RtpAnalysisDialog::resetStatistics()
{
for(int i=0; i<tabs_.count(); i++) {
tab_info_t *tab = tabs_[i];
memset(&tab->stream.rtp_stats, 0, sizeof(tab->stream.rtp_stats));
tab->stream.rtp_stats.first_packet = true;
tab->stream.rtp_stats.reg_pt = PT_UNDEFINED;
tab->time_vals->clear();
tab->jitter_vals->clear();
tab->diff_vals->clear();
tab->delta_vals->clear();
tab->tree_widget->clear();
}
for (int i = 0; i < ui->streamGraph->graphCount(); i++) {
ui->streamGraph->graph(i)->data()->clear();
}
}
void RtpAnalysisDialog::addPacket(tab_info_t *tab, packet_info *pinfo, const _rtp_info *rtpinfo)
{
rtpstream_info_analyse_process(&tab->stream, pinfo, rtpinfo);
new RtpAnalysisTreeWidgetItem(tab->tree_widget, &tab->stream.rtp_stats, pinfo, rtpinfo);
tab->time_vals->append(tab->stream.rtp_stats.time / 1000);
tab->jitter_vals->append(tab->stream.rtp_stats.jitter);
tab->diff_vals->append(tab->stream.rtp_stats.diff);
tab->delta_vals->append(tab->stream.rtp_stats.delta);
}
void RtpAnalysisDialog::updateStatistics()
{
for(int i=0; i<tabs_.count(); i++) {
rtpstream_info_t *stream = &tabs_[i]->stream;
rtpstream_info_calc_t s_calc;
rtpstream_info_calculate(stream, &s_calc);
QString stats_tables = "<html><head><style>td{vertical-align:bottom;}</style></head><body>\n";
stats_tables += "<h4>Stream</h4>\n";
stats_tables += QString("<p>%1:%2 " UTF8_RIGHTWARDS_ARROW)
.arg(s_calc.src_addr_str)
.arg(s_calc.src_port);
stats_tables += QString("<br>%1:%2</p>\n")
.arg(s_calc.dst_addr_str)
.arg(s_calc.dst_port);
stats_tables += "<p><table>\n";
stats_tables += QString("<tr><th align=\"left\">SSRC</th><td>%1</td></tr>")
.arg(int_to_qstring(s_calc.ssrc, 8, 16));
stats_tables += QString("<tr><th align=\"left\">Max Delta</th><td>%1 ms @ %2</td></tr>")
.arg(s_calc.max_delta, 0, 'f', prefs.gui_decimal_places3)
.arg(s_calc.last_packet_num);
stats_tables += QString("<tr><th align=\"left\">Max Jitter</th><td>%1 ms</td></tr>")
.arg(s_calc.max_jitter, 0, 'f', prefs.gui_decimal_places3);
stats_tables += QString("<tr><th align=\"left\">Mean Jitter</th><td>%1 ms</td></tr>")
.arg(s_calc.mean_jitter, 0, 'f', prefs.gui_decimal_places3);
stats_tables += QString("<tr><th align=\"left\">Max Skew</th><td>%1 ms</td></tr>")
.arg(s_calc.max_skew, 0, 'f', prefs.gui_decimal_places3);
stats_tables += QString("<tr><th align=\"left\">RTP Packets</th><td>%1</td></tr>")
.arg(s_calc.total_nr);
stats_tables += QString("<tr><th align=\"left\">Expected</th><td>%1</td></tr>")
.arg(s_calc.packet_expected);
stats_tables += QString("<tr><th align=\"left\">Lost</th><td>%1 (%2 %)</td></tr>")
.arg(s_calc.lost_num).arg(s_calc.lost_perc, 0, 'f', prefs.gui_decimal_places1);
stats_tables += QString("<tr><th align=\"left\">Seq Errs</th><td>%1</td></tr>")
.arg(s_calc.sequence_err);
stats_tables += QString("<tr><th align=\"left\">Start at</th><td>%1 s @ %2</td></tr>")
.arg(s_calc.start_time_ms, 0, 'f', 6)
.arg(s_calc.first_packet_num);
stats_tables += QString("<tr><th align=\"left\">Duration</th><td>%1 s</td></tr>")
.arg(s_calc.duration_ms, 0, 'f', prefs.gui_decimal_places1);
stats_tables += QString("<tr><th align=\"left\">Clock Drift</th><td>%1 ms</td></tr>")
.arg(s_calc.clock_drift_ms, 0, 'f', 0);
stats_tables += QString("<tr><th align=\"left\">Freq Drift</th><td>%1 Hz (%2 %)</td></tr>") // XXX Terminology?
.arg(s_calc.freq_drift_hz, 0, 'f', 0).arg(s_calc.freq_drift_perc, 0, 'f', 2);
rtpstream_info_calc_free(&s_calc);
stats_tables += "</table></p>\n";
tabs_[i]->statistics_label->setText(stats_tables);
for (int col = 0; col < tabs_[i]->tree_widget->columnCount() - 1; col++) {
tabs_[i]->tree_widget->resizeColumnToContents(col);
}
tabs_[i]->jitter_graph->setData(*tabs_[i]->time_vals, *tabs_[i]->jitter_vals);
tabs_[i]->diff_graph->setData(*tabs_[i]->time_vals, *tabs_[i]->diff_vals);
tabs_[i]->delta_graph->setData(*tabs_[i]->time_vals, *tabs_[i]->delta_vals);
}
updateGraph();
updateWidgets();
}
void RtpAnalysisDialog::updateGraph()
{
for (int i = 0; i < ui->streamGraph->graphCount(); i++) {
if (ui->streamGraph->graph(i)->visible()) {
ui->streamGraph->graph(i)->rescaleAxes(i > 0);
}
}
ui->streamGraph->replot();
}
QVector<rtpstream_id_t *>RtpAnalysisDialog::getSelectedRtpIds()
{
QVector<rtpstream_id_t *> stream_ids;
for(int i=0; i < tabs_.count(); i++) {
stream_ids << &(tabs_[i]->stream.id);
}
return stream_ids;
}
void RtpAnalysisDialog::rtpPlayerReplace()
{
if (tabs_.count() < 1) return;
emit rtpPlayerDialogReplaceRtpStreams(getSelectedRtpIds());
}
void RtpAnalysisDialog::rtpPlayerAdd()
{
if (tabs_.count() < 1) return;
emit rtpPlayerDialogAddRtpStreams(getSelectedRtpIds());
}
void RtpAnalysisDialog::rtpPlayerRemove()
{
if (tabs_.count() < 1) return;
emit rtpPlayerDialogRemoveRtpStreams(getSelectedRtpIds());
}
void RtpAnalysisDialog::saveCsvHeader(QFile *save_file, QTreeWidget *tree)
{
QList<QVariant> row_data;
QStringList values;
for (int col = 0; col < tree->columnCount(); col++) {
row_data << tree->headerItem()->text(col);
}
foreach (QVariant v, row_data) {
if (!v.isValid()) {
values << "\"\"";
} else if (v.userType() == QMetaType::QString) {
values << QString("\"%1\"").arg(v.toString());
} else {
values << v.toString();
}
}
save_file->write(values.join(",").toUtf8());
save_file->write("\n");
}
void RtpAnalysisDialog::saveCsvData(QFile *save_file, QTreeWidget *tree)
{
for (int row = 0; row < tree->topLevelItemCount(); row++) {
QTreeWidgetItem *ti = tree->topLevelItem(row);
if (ti->type() != rtp_analysis_type_) continue;
RtpAnalysisTreeWidgetItem *ra_ti = dynamic_cast<RtpAnalysisTreeWidgetItem *>((RtpAnalysisTreeWidgetItem *)ti);
QStringList values;
foreach (QVariant v, ra_ti->rowData()) {
if (!v.isValid()) {
values << "\"\"";
} else if (v.userType() == QMetaType::QString) {
values << QString("\"%1\"").arg(v.toString());
} else {
values << v.toString();
}
}
save_file->write(values.join(",").toUtf8());
save_file->write("\n");
}
}
// XXX The GTK+ UI saves the length and timestamp.
void RtpAnalysisDialog::saveCsv(RtpAnalysisDialog::StreamDirection direction)
{
QString caption;
switch (direction) {
case dir_one_:
caption = tr("Save one stream CSV");
break;
case dir_all_:
default:
caption = tr("Save all stream's CSV");
break;
}
QString file_path = WiresharkFileDialog::getSaveFileName(
this, caption, mainApp->lastOpenDir().absoluteFilePath("RTP Packet Data.csv"),
tr("Comma-separated values (*.csv)"));
if (file_path.isEmpty()) return;
QFile save_file(file_path);
save_file.open(QFile::WriteOnly);
switch (direction) {
case dir_one_:
{
tab_info_t *tab_data = getTabInfoForCurrentTab();
if (tab_data) {
saveCsvHeader(&save_file, tab_data->tree_widget);
QString n = QString(*tab_data->tab_name);
n.replace("\n"," ");
save_file.write("\"");
save_file.write(n.toUtf8());
save_file.write("\"\n");
saveCsvData(&save_file, tab_data->tree_widget);
}
}
break;
case dir_all_:
default:
if (tabs_.count() > 0) {
saveCsvHeader(&save_file, tabs_[0]->tree_widget);
}
for(int i=0; i<tabs_.count(); i++) {
QString n = QString(*tabs_[i]->tab_name);
n.replace("\n"," ");
save_file.write("\"");
save_file.write(n.toUtf8());
save_file.write("\"\n");
saveCsvData(&save_file, tabs_[i]->tree_widget);
save_file.write("\n");
}
break;
}
}
bool RtpAnalysisDialog::eventFilter(QObject *, QEvent *event)
{
if (event->type() != QEvent::KeyPress) return false;
QKeyEvent *kevt = static_cast<QKeyEvent *>(event);
switch(kevt->key()) {
case Qt::Key_G:
on_actionGoToPacket_triggered();
return true;
case Qt::Key_N:
on_actionNextProblem_triggered();
return true;
default:
break;
}
return false;
}
void RtpAnalysisDialog::graphClicked(QMouseEvent *event)
{
updateWidgets();
if (event->button() == Qt::RightButton) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
graph_ctx_menu_.popup(event->globalPosition().toPoint());
#else
graph_ctx_menu_.popup(event->globalPos());
#endif
}
}
void RtpAnalysisDialog::clearLayout(QLayout *layout)
{
if (layout) {
QLayoutItem *item;
//the key point here is that the layout items are stored inside the layout in a stack
while((item = layout->takeAt(0)) != 0) {
if (item->widget()) {
layout->removeWidget(item->widget());
delete item->widget();
}
delete item;
}
}
}
void RtpAnalysisDialog::closeTab(int index)
{
// Do not close last tab with graph
if (index != tabs_.count()) {
QWidget *remove_tab = qobject_cast<QWidget *>(ui->tabWidget->widget(index));
tab_info_t *tab = tabs_[index];
tab_hash_.remove(rtpstream_to_hash(&tab->stream), tab);
tabs_.remove(index);
ui->tabWidget->removeTab(index);
ui->streamGraph->removeGraph(tab->jitter_graph);
ui->streamGraph->removeGraph(tab->diff_graph);
ui->streamGraph->removeGraph(tab->delta_graph);
clearLayout(tab->graphHorizontalLayout);
delete remove_tab;
deleteTabInfo(tab);
g_free(tab);
updateGraph();
}
}
void RtpAnalysisDialog::showStreamMenu(QPoint pos)
{
tab_info_t *tab_data = getTabInfoForCurrentTab();
if (!tab_data) return;
QTreeWidget *cur_tree = tab_data->tree_widget;
if (!cur_tree) return;
updateWidgets();
stream_ctx_menu_.popup(cur_tree->viewport()->mapToGlobal(pos));
}
void RtpAnalysisDialog::replaceRtpStreams(QVector<rtpstream_id_t *> stream_ids)
{
std::unique_lock<std::mutex> lock(run_mutex_, std::try_to_lock);
if (lock.owns_lock()) {
// Delete existing tabs (from last to first)
if (tabs_.count() > 0) {
for(int i = static_cast<int>(tabs_.count()); i>0; i--) {
closeTab(i-1);
}
}
addRtpStreamsPrivate(stream_ids);
} else {
ws_warning("replaceRtpStreams was called while other thread locked it. Current call is ignored, try it later.");
}
}
void RtpAnalysisDialog::addRtpStreams(QVector<rtpstream_id_t *> stream_ids)
{
std::unique_lock<std::mutex> lock(run_mutex_, std::try_to_lock);
if (lock.owns_lock()) {
addRtpStreamsPrivate(stream_ids);
} else {
ws_warning("addRtpStreams was called while other thread locked it. Current call is ignored, try it later.");
}
}
void RtpAnalysisDialog::addRtpStreamsPrivate(QVector<rtpstream_id_t *> stream_ids)
{
int first_tab_no = -1;
setUpdatesEnabled(false);
foreach(rtpstream_id_t *id, stream_ids) {
bool found = false;
QList<tab_info_t *> tabs = tab_hash_.values(rtpstream_id_to_hash(id));
for (int i = 0; i < tabs.size(); i++) {
tab_info_t *tab = tabs.at(i);
if (rtpstream_id_equal(&tab->stream.id, id, RTPSTREAM_ID_EQUAL_SSRC)) {
found = true;
break;
}
}
if (!found) {
int cur_tab_no;
tab_info_t *new_tab = g_new0(tab_info_t, 1);
rtpstream_id_copy(id, &(new_tab->stream.id));
new_tab->time_vals = new QVector<double>();
new_tab->jitter_vals = new QVector<double>();
new_tab->diff_vals = new QVector<double>();
new_tab->delta_vals = new QVector<double>();
tabs_ << new_tab;
cur_tab_no = addTabUI(new_tab);
tab_hash_.insert(rtpstream_id_to_hash(id), new_tab);
if (first_tab_no == -1) {
first_tab_no = cur_tab_no;
}
}
}
if (first_tab_no != -1) {
ui->tabWidget->setCurrentIndex(first_tab_no);
}
setUpdatesEnabled(true);
registerTapListener("rtp", this, NULL, 0, tapReset, tapPacket, tapDraw);
cap_file_.retapPackets();
updateStatistics();
removeTapListeners();
updateGraph();
}
void RtpAnalysisDialog::removeRtpStreams(QVector<rtpstream_id_t *> stream_ids)
{
std::unique_lock<std::mutex> lock(run_mutex_, std::try_to_lock);
if (lock.owns_lock()) {
setUpdatesEnabled(false);
foreach(rtpstream_id_t *id, stream_ids) {
QList<tab_info_t *> tabs = tab_hash_.values(rtpstream_id_to_hash(id));
for (int i = 0; i < tabs.size(); i++) {
tab_info_t *tab = tabs.at(i);
if (rtpstream_id_equal(&tab->stream.id, id, RTPSTREAM_ID_EQUAL_SSRC)) {
closeTab(static_cast<int>(tabs_.indexOf(tab)));
}
}
}
setUpdatesEnabled(true);
updateGraph();
} else {
ws_warning("removeRtpStreams was called while other thread locked it. Current call is ignored, try it later.");
}
}
tab_info_t *RtpAnalysisDialog::getTabInfoForCurrentTab()
{
tab_info_t *tab_data;
if (file_closed_) return NULL;
QWidget *cur_tab = qobject_cast<QWidget *>(ui->tabWidget->currentWidget());
if (!cur_tab) return NULL;
tab_data = static_cast<tab_info_t *>(cur_tab->property("tab_data").value<void*>());
return tab_data;
}
QToolButton *RtpAnalysisDialog::addAnalyzeButton(QDialogButtonBox *button_box, QDialog *dialog)
{
if (!button_box) return NULL;
QAction *ca;
QToolButton *analysis_button = new QToolButton();
button_box->addButton(analysis_button, QDialogButtonBox::ActionRole);
analysis_button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
analysis_button->setPopupMode(QToolButton::MenuButtonPopup);
ca = new QAction(tr("&Analyze"), analysis_button);
ca->setToolTip(tr("Open the analysis window for the selected stream(s)"));
connect(ca, SIGNAL(triggered()), dialog, SLOT(rtpAnalysisReplace()));
analysis_button->setDefaultAction(ca);
// Overrides text striping of shortcut undercode in QAction
analysis_button->setText(ca->text());
QMenu *button_menu = new QMenu(analysis_button);
button_menu->setToolTipsVisible(true);
ca = button_menu->addAction(tr("&Set List"));
ca->setToolTip(tr("Replace existing list in RTP Analysis Dialog with new one"));
connect(ca, SIGNAL(triggered()), dialog, SLOT(rtpAnalysisReplace()));
ca = button_menu->addAction(tr("&Add to List"));
ca->setToolTip(tr("Add new set to existing list in RTP Analysis Dialog"));
connect(ca, SIGNAL(triggered()), dialog, SLOT(rtpAnalysisAdd()));
ca = button_menu->addAction(tr("&Remove from List"));
ca->setToolTip(tr("Remove selected streams from list in RTP Analysis Dialog"));
connect(ca, SIGNAL(triggered()), dialog, SLOT(rtpAnalysisRemove()));
analysis_button->setMenu(button_menu);
return analysis_button;
}
void RtpAnalysisDialog::on_actionPrepareFilterOne_triggered()
{
if ((ui->tabWidget->currentIndex() < (ui->tabWidget->count()-1))) {
QVector<rtpstream_id_t *> ids;
ids << &(tabs_[ui->tabWidget->currentIndex()]->stream.id);
QString filter = make_filter_based_on_rtpstream_id(ids);
if (filter.length() > 0) {
emit updateFilter(filter);
}
}
}
void RtpAnalysisDialog::on_actionPrepareFilterAll_triggered()
{
QVector<rtpstream_id_t *>ids = getSelectedRtpIds();
QString filter = make_filter_based_on_rtpstream_id(ids);
if (filter.length() > 0) {
emit updateFilter(filter);
}
} |
C/C++ | wireshark/ui/qt/rtp_analysis_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 RTP_ANALYSIS_DIALOG_H
#define RTP_ANALYSIS_DIALOG_H
#include <config.h>
#include <glib.h>
#include <mutex>
#include "epan/address.h"
#include "ui/rtp_stream.h"
#include "ui/tap-rtp-common.h"
#include "ui/tap-rtp-analysis.h"
#include <QMenu>
#include <QTreeWidget>
#include <QLabel>
#include <QFile>
#include <QCheckBox>
#include <QHBoxLayout>
#include <QToolButton>
#include "wireshark_dialog.h"
namespace Ui {
class RtpAnalysisDialog;
}
class QCPGraph;
class QTemporaryFile;
class QDialogButtonBox;
typedef struct {
rtpstream_info_t stream;
QVector<double> *time_vals;
QVector<double> *jitter_vals;
QVector<double> *diff_vals;
QVector<double> *delta_vals;
QTreeWidget *tree_widget;
QLabel *statistics_label;
QString *tab_name;
QCPGraph *jitter_graph;
QCPGraph *diff_graph;
QCPGraph *delta_graph;
QHBoxLayout *graphHorizontalLayout;
QCheckBox *stream_checkbox;
QCheckBox *jitter_checkbox;
QCheckBox *diff_checkbox;
QCheckBox *delta_checkbox;
} tab_info_t;
// Singleton by https://refactoring.guru/design-patterns/singleton/cpp/example#example-1
class RtpAnalysisDialog : public WiresharkDialog
{
Q_OBJECT
public:
/**
* Returns singleton
*/
static RtpAnalysisDialog *openRtpAnalysisDialog(QWidget &parent, CaptureFile &cf, QObject *packet_list);
/**
* Should not be clonnable and assignable
*/
RtpAnalysisDialog(RtpAnalysisDialog &other) = delete;
void operator=(const RtpAnalysisDialog &) = delete;
/**
* @brief Common routine to add a "Analyze" button to a QDialogButtonBox.
* @param button_box Caller's QDialogButtonBox.
* @return The new "Analyze" button.
*/
static QToolButton *addAnalyzeButton(QDialogButtonBox *button_box, QDialog *dialog);
/** Replace/Add/Remove an RTP streams to analyse.
* Requires array of rtpstream_id_t.
*
* @param stream_ids structs with rtpstream_id
*/
void replaceRtpStreams(QVector<rtpstream_id_t *> stream_ids);
void addRtpStreams(QVector<rtpstream_id_t *> stream_ids);
void removeRtpStreams(QVector<rtpstream_id_t *> stream_ids);
signals:
void goToPacket(int packet_num);
void rtpPlayerDialogReplaceRtpStreams(QVector<rtpstream_id_t *> stream_ids);
void rtpPlayerDialogAddRtpStreams(QVector<rtpstream_id_t *> stream_ids);
void rtpPlayerDialogRemoveRtpStreams(QVector<rtpstream_id_t *> stream_ids);
void updateFilter(QString filter, bool force = false);
public slots:
void rtpPlayerReplace();
void rtpPlayerAdd();
void rtpPlayerRemove();
protected slots:
virtual void updateWidgets();
protected:
explicit RtpAnalysisDialog(QWidget &parent, CaptureFile &cf);
~RtpAnalysisDialog();
private slots:
void on_actionGoToPacket_triggered();
void on_actionNextProblem_triggered();
void on_actionSaveOneCsv_triggered();
void on_actionSaveAllCsv_triggered();
void on_actionSaveGraph_triggered();
void on_buttonBox_helpRequested();
void showStreamMenu(QPoint pos);
void graphClicked(QMouseEvent *event);
void closeTab(int index);
void rowCheckboxChanged(int checked);
void singleCheckboxChanged(int checked);
void on_actionPrepareFilterOne_triggered();
void on_actionPrepareFilterAll_triggered();
private:
static RtpAnalysisDialog *pinstance_;
static std::mutex init_mutex_;
static std::mutex run_mutex_;
Ui::RtpAnalysisDialog *ui;
enum StreamDirection { dir_all_, dir_one_ };
int tab_seq;
QVector<tab_info_t *> tabs_;
QMultiHash<guint, tab_info_t *> tab_hash_;
QToolButton *player_button_;
// Graph data for QCustomPlot
QList<QCPGraph *>graphs_;
QString err_str_;
QMenu stream_ctx_menu_;
QMenu graph_ctx_menu_;
// Tap callbacks
static void tapReset(void *tapinfo_ptr);
static tap_packet_status tapPacket(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *, const void *rtpinfo_ptr, tap_flags_t flags);
static void tapDraw(void *tapinfo_ptr);
void resetStatistics();
void addPacket(tab_info_t *tab, packet_info *pinfo, const struct _rtp_info *rtpinfo);
void updateStatistics();
void updateGraph();
void saveCsvHeader(QFile *save_file, QTreeWidget *tree);
void saveCsvData(QFile *save_file, QTreeWidget *tree);
void saveCsv(StreamDirection direction);
bool eventFilter(QObject*, QEvent* event);
QVector<rtpstream_id_t *>getSelectedRtpIds();
int addTabUI(tab_info_t *new_tab);
tab_info_t *getTabInfoForCurrentTab();
void deleteTabInfo(tab_info_t *tab_info);
void clearLayout(QLayout *layout);
void addRtpStreamsPrivate(QVector<rtpstream_id_t *> stream_ids);
};
#endif // RTP_ANALYSIS_DIALOG_H |
User Interface | wireshark/ui/qt/rtp_analysis_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>RtpAnalysisDialog</class>
<widget class="QDialog" name="RtpAnalysisDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>650</width>
<height>475</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="graphTab">
<attribute name="title">
<string>Graph</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_2" stretch="1,0">
<item>
<widget class="QCustomPlot" name="streamGraph" native="true"/>
</item>
<item>
<widget class="QScrollArea" name="scrollarea">
<property name="minimumSize">
<size>
<width>0</width>
<height>200</height>
</size>
</property>
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="widgetResizable">
<bool>true</bool>
</property>
<widget class="QWidget" name="qwidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>606</width>
<height>298</height>
</rect>
</property>
<layout class="QVBoxLayout" name="layout"/>
</widget>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2" stretch="1,0">
<item>
<widget class="QLabel" name="hintLabel">
<property name="text">
<string><small><i>A hint.</i></small></string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="ProgressFrame" name="progressFrame">
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Plain</enum>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Close|QDialogButtonBox::Help</set>
</property>
</widget>
</item>
</layout>
<action name="actionExportButton">
<property name="text">
<string>&Export</string>
</property>
<property name="toolTip">
<string>Open export menu</string>
</property>
</action>
<action name="actionSaveCsv">
<property name="text">
<string>CSV</string>
</property>
<property name="toolTip">
<string>Save tables as CSV.</string>
</property>
</action>
<action name="actionSaveOneCsv">
<property name="text">
<string>Current Tab Stream CSV</string>
</property>
<property name="toolTip">
<string>Save the table on the current tab as CSV.</string>
</property>
</action>
<action name="actionSaveAllCsv">
<property name="text">
<string>All Tab Streams CSV</string>
</property>
<property name="toolTip">
<string>Save the table from all tabs as CSV.</string>
</property>
</action>
<action name="actionSaveGraph">
<property name="text">
<string>Save Graph</string>
</property>
<property name="toolTip">
<string>Save the graph image.</string>
</property>
</action>
<action name="actionGoToPacket">
<property name="text">
<string>Go to Packet</string>
</property>
<property name="toolTip">
<string>Select the corresponding packet in the packet list.</string>
</property>
<property name="shortcut">
<string>G</string>
</property>
</action>
<action name="actionNextProblem">
<property name="text">
<string>Next Problem Packet</string>
</property>
<property name="toolTip">
<string>Go to the next problem packet</string>
</property>
<property name="shortcut">
<string>N</string>
</property>
</action>
<action name="actionPrepareButton">
<property name="text">
<string>Prepare &Filter</string>
</property>
<property name="toolTip">
<string>Prepare a filter matching the selected stream(s).</string>
</property>
</action>
<widget class="QMenu" name="menuPrepareFilter">
<property name="title">
<string>Prepare &Filter</string>
</property>
<property name="toolTipsVisible">
<bool>true</bool>
</property>
<addaction name="actionPrepareFilterOne"/>
<addaction name="actionPrepareFilterAll"/>
</widget>
<action name="actionPrepareFilterOne">
<property name="text">
<string>&Current Tab</string>
</property>
<property name="toolTip">
<string>Prepare a filter matching current tab.</string>
</property>
</action>
<action name="actionPrepareFilterAll">
<property name="text">
<string>&All Tabs</string>
</property>
<property name="toolTip">
<string>Prepare a filter matching all tabs.</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>QCustomPlot</class>
<extends>QWidget</extends>
<header>widgets/qcustomplot.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>ProgressFrame</class>
<extends>QFrame</extends>
<header>progress_frame.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>RtpAnalysisDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>RtpAnalysisDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/rtp_audio_stream.cpp | /* rtp_audio_frame.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "rtp_audio_stream.h"
#ifdef QT_MULTIMEDIA_LIB
#include <speex/speex_resampler.h>
#include <epan/rtp_pt.h>
#include <epan/to_str.h>
#include <epan/dissectors/packet-rtp.h>
#include <ui/rtp_media.h>
#include <ui/rtp_stream.h>
#include <ui/tap-rtp-common.h>
#include <wsutil/nstime.h>
#include <ui/qt/utils/rtp_audio_routing_filter.h>
#include <ui/qt/utils/rtp_audio_file.h>
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
#include <QAudioDevice>
#include <QAudioSink>
#endif
#include <QAudioFormat>
#include <QAudioOutput>
#include <QVariant>
#include <QTimer>
// To do:
// - Only allow one rtpstream_info_t per RtpAudioStream?
static const spx_int16_t visual_sample_rate_ = 1000;
RtpAudioStream::RtpAudioStream(QObject *parent, rtpstream_id_t *id, bool stereo_required) :
QObject(parent)
, first_packet_(true)
, decoders_hash_(rtp_decoder_hash_table_new())
, global_start_rel_time_(0.0)
, start_abs_offset_(0.0)
, start_rel_time_(0.0)
, stop_rel_time_(0.0)
, stereo_required_(stereo_required)
, first_sample_rate_(0)
, audio_out_rate_(0)
, audio_requested_out_rate_(0)
, max_sample_val_(1)
, max_sample_val_used_(1)
, color_(0)
, jitter_buffer_size_(50)
, timing_mode_(RtpAudioStream::JitterBuffer)
, start_play_time_(0)
, audio_output_(NULL)
{
rtpstream_id_copy(id, &id_);
memset(&rtpstream_, 0, sizeof(rtpstream_));
rtpstream_id_copy(&id_, &rtpstream_.id);
// Rates will be set later, we just init visual resampler
visual_resampler_ = speex_resampler_init(1, visual_sample_rate_,
visual_sample_rate_, SPEEX_RESAMPLER_QUALITY_MIN, NULL);
try {
// RtpAudioFile is ready for writing Frames
audio_file_ = new RtpAudioFile(prefs.gui_rtp_player_use_disk1, prefs.gui_rtp_player_use_disk2);
} catch (...) {
speex_resampler_destroy(visual_resampler_);
rtpstream_info_free_data(&rtpstream_);
rtpstream_id_free(&id_);
throw -1;
}
// RTP_STREAM_DEBUG("Writing to %s", tempname.toUtf8().constData());
}
RtpAudioStream::~RtpAudioStream()
{
for (int i = 0; i < rtp_packets_.size(); i++) {
rtp_packet_t *rtp_packet = rtp_packets_[i];
g_free(rtp_packet->info);
g_free(rtp_packet->payload_data);
g_free(rtp_packet);
}
g_hash_table_destroy(decoders_hash_);
speex_resampler_destroy(visual_resampler_);
rtpstream_info_free_data(&rtpstream_);
rtpstream_id_free(&id_);
if (audio_file_) delete audio_file_;
// temp_file_ is released by audio_output_
if (audio_output_) delete audio_output_;
}
bool RtpAudioStream::isMatch(const rtpstream_id_t *id) const
{
if (id
&& rtpstream_id_equal(&id_, id, RTPSTREAM_ID_EQUAL_SSRC))
return true;
return false;
}
bool RtpAudioStream::isMatch(const _packet_info *pinfo, const _rtp_info *rtp_info) const
{
if (pinfo && rtp_info
&& rtpstream_id_equal_pinfo_rtp_info(&id_, pinfo, rtp_info))
return true;
return false;
}
void RtpAudioStream::addRtpPacket(const struct _packet_info *pinfo, const struct _rtp_info *rtp_info)
{
if (!rtp_info) return;
if (first_packet_) {
rtpstream_info_analyse_init(&rtpstream_, pinfo, rtp_info);
first_packet_ = false;
}
rtpstream_info_analyse_process(&rtpstream_, pinfo, rtp_info);
rtp_packet_t *rtp_packet = g_new0(rtp_packet_t, 1);
rtp_packet->info = (struct _rtp_info *) g_memdup2(rtp_info, sizeof(struct _rtp_info));
if (rtp_info->info_all_data_present && (rtp_info->info_payload_len != 0)) {
rtp_packet->payload_data = (guint8 *) g_memdup2(&(rtp_info->info_data[rtp_info->info_payload_offset]),
rtp_info->info_payload_len);
}
if (rtp_packets_.size() < 1) { // First packet
start_abs_offset_ = nstime_to_sec(&pinfo->abs_ts) - start_rel_time_;
start_rel_time_ = stop_rel_time_ = nstime_to_sec(&pinfo->rel_ts);
}
rtp_packet->frame_num = pinfo->num;
rtp_packet->arrive_offset = nstime_to_sec(&pinfo->rel_ts) - start_rel_time_;
rtp_packets_ << rtp_packet;
}
void RtpAudioStream::clearPackets()
{
for (int i = 0; i < rtp_packets_.size(); i++) {
rtp_packet_t *rtp_packet = rtp_packets_[i];
g_free(rtp_packet->info);
g_free(rtp_packet->payload_data);
g_free(rtp_packet);
}
rtp_packets_.clear();
rtpstream_info_free_data(&rtpstream_);
memset(&rtpstream_, 0, sizeof(rtpstream_));
rtpstream_id_copy(&id_, &rtpstream_.id);
first_packet_ = true;
}
void RtpAudioStream::reset(double global_start_time)
{
global_start_rel_time_ = global_start_time;
stop_rel_time_ = start_rel_time_;
audio_out_rate_ = 0;
max_sample_val_ = 1;
packet_timestamps_.clear();
visual_samples_.clear();
out_of_seq_timestamps_.clear();
jitter_drop_timestamps_.clear();
}
AudioRouting RtpAudioStream::getAudioRouting()
{
return audio_routing_;
}
void RtpAudioStream::setAudioRouting(AudioRouting audio_routing)
{
audio_routing_ = audio_routing;
}
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
void RtpAudioStream::decode(QAudioDevice out_device)
#else
void RtpAudioStream::decode(QAudioDeviceInfo out_device)
#endif
{
if (rtp_packets_.size() < 1) return;
audio_file_->setFrameWriteStage();
decodeAudio(out_device);
// Skip silence at begin of the stream
audio_file_->setFrameReadStage(prepend_samples_);
speex_resampler_reset_mem(visual_resampler_);
decodeVisual();
audio_file_->setDataReadStage();
}
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
quint32 RtpAudioStream::calculateAudioOutRate(QAudioDevice out_device, unsigned int sample_rate, unsigned int requested_out_rate)
#else
quint32 RtpAudioStream::calculateAudioOutRate(QAudioDeviceInfo out_device, unsigned int sample_rate, unsigned int requested_out_rate)
#endif
{
quint32 out_rate;
// Use the first non-zero rate we find. Ajust it to match
// our audio hardware.
QAudioFormat format;
format.setSampleRate(sample_rate);
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
// Must match rtp_media.h.
format.setSampleFormat(QAudioFormat::Int16);
#else
format.setSampleSize(SAMPLE_BYTES * 8); // bits
format.setSampleType(QAudioFormat::SignedInt);
#endif
if (stereo_required_) {
format.setChannelCount(2);
} else {
format.setChannelCount(1);
}
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
format.setCodec("audio/pcm");
#endif
if (!out_device.isNull() &&
!out_device.isFormatSupported(format) &&
(requested_out_rate == 0)
) {
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
out_rate = out_device.preferredFormat().sampleRate();
#else
out_rate = out_device.nearestFormat(format).sampleRate();
#endif
} else {
if ((requested_out_rate != 0) &&
(requested_out_rate != sample_rate)
) {
out_rate = requested_out_rate;
} else {
out_rate = sample_rate;
}
}
RTP_STREAM_DEBUG("Audio sample rate is %u", out_rate);
return out_rate;
}
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
void RtpAudioStream::decodeAudio(QAudioDevice out_device)
#else
void RtpAudioStream::decodeAudio(QAudioDeviceInfo out_device)
#endif
{
// XXX This is more messy than it should be.
gint32 resample_buff_bytes = 0x1000;
SAMPLE *resample_buff = (SAMPLE *) g_malloc(resample_buff_bytes);
char *write_buff = NULL;
qint64 write_bytes = 0;
unsigned int channels = 0;
unsigned int sample_rate = 0;
guint32 last_sequence = 0;
guint32 last_sequence_w = 0; // Last sequence number we wrote data
double rtp_time_prev = 0.0;
double arrive_time_prev = 0.0;
double pack_period = 0.0;
double start_time = 0.0;
double start_rtp_time = 0.0;
guint64 start_timestamp = 0;
size_t decoded_bytes_prev = 0;
unsigned int audio_resampler_input_rate = 0;
struct SpeexResamplerState_ *audio_resampler = NULL;
for (int cur_packet = 0; cur_packet < rtp_packets_.size(); cur_packet++) {
SAMPLE *decode_buff = NULL;
// TODO: Update a progress bar here.
rtp_packet_t *rtp_packet = rtp_packets_[cur_packet];
stop_rel_time_ = start_rel_time_ + rtp_packet->arrive_offset;
QString payload_name;
if (rtp_packet->info->info_payload_type_str) {
payload_name = rtp_packet->info->info_payload_type_str;
} else {
payload_name = try_val_to_str_ext(rtp_packet->info->info_payload_type, &rtp_payload_type_short_vals_ext);
}
if (!payload_name.isEmpty()) {
payload_names_ << payload_name;
}
if (cur_packet < 1) { // First packet
start_timestamp = rtp_packet->info->info_extended_timestamp;
start_rtp_time = 0;
rtp_time_prev = 0;
last_sequence = rtp_packet->info->info_extended_seq_num - 1;
}
size_t decoded_bytes = decode_rtp_packet(rtp_packet, &decode_buff, decoders_hash_, &channels, &sample_rate);
// XXX: We don't actually *do* anything with channels, and just treat
// everything as if it were mono
unsigned rtp_clock_rate = sample_rate;
if (rtp_packet->info->info_payload_type == PT_G722) {
// G.722 sample rate is 16kHz, but RTP clock rate is 8kHz
// for historic reasons.
rtp_clock_rate = 8000;
}
// Length 2 for PT_PCM mean silence packet probably, ignore
if (decoded_bytes == 0 || sample_rate == 0 ||
((rtp_packet->info->info_payload_type == PT_PCMU ||
rtp_packet->info->info_payload_type == PT_PCMA
) && (decoded_bytes == 2)
)
) {
// We didn't decode anything. Clean up and prep for
// the next packet.
last_sequence = rtp_packet->info->info_extended_seq_num;
g_free(decode_buff);
continue;
}
if (audio_out_rate_ == 0) {
first_sample_rate_ = sample_rate;
// We calculate audio_out_rate just for first sample_rate.
// All later are just resampled to it.
// Side effect: it creates and initiates resampler if needed
audio_out_rate_ = calculateAudioOutRate(out_device, sample_rate, audio_requested_out_rate_);
// Calculate count of prepend samples for the stream
// The earliest stream starts at 0.
// Note: Order of operations and separation to two formulas is
// important.
// When joined, calculated incorrectly - probably caused by
// conversions between int/double
prepend_samples_ = (start_rel_time_ - global_start_rel_time_) * sample_rate;
prepend_samples_ = prepend_samples_ * audio_out_rate_ / sample_rate;
// Prepend silence to match our sibling streams.
if ((prepend_samples_ > 0) && (audio_out_rate_ != 0)) {
audio_file_->frameWriteSilence(rtp_packet->frame_num, prepend_samples_);
}
}
if (rtp_packet->info->info_extended_seq_num != last_sequence+1) {
out_of_seq_timestamps_.append(stop_rel_time_);
}
last_sequence = rtp_packet->info->info_extended_seq_num;
double rtp_time = (double)(rtp_packet->info->info_extended_timestamp-start_timestamp)/rtp_clock_rate - start_rtp_time;
double arrive_time;
if (timing_mode_ == RtpTimestamp) {
arrive_time = rtp_time;
} else {
arrive_time = rtp_packet->arrive_offset - start_time;
}
double diff = qAbs(arrive_time - rtp_time);
if (diff*1000 > jitter_buffer_size_ && timing_mode_ != Uninterrupted) {
// rtp_player.c:628
jitter_drop_timestamps_.append(stop_rel_time_);
RTP_STREAM_DEBUG("Packet drop by jitter buffer exceeded %f > %d", diff*1000, jitter_buffer_size_);
/* if there was a silence period (more than two packetization
* period) resync the source */
if ((rtp_time - rtp_time_prev) > pack_period*2) {
qint64 silence_samples;
RTP_STREAM_DEBUG("Resync...");
silence_samples = (qint64)((arrive_time - arrive_time_prev)*sample_rate - decoded_bytes_prev / SAMPLE_BYTES);
silence_samples = silence_samples * audio_out_rate_ / sample_rate;
silence_timestamps_.append(stop_rel_time_);
// Timestamp shift can make silence calculation negative
if ((silence_samples > 0) && (audio_out_rate_ != 0)) {
audio_file_->frameWriteSilence(rtp_packet->frame_num, silence_samples);
}
decoded_bytes_prev = 0;
start_timestamp = rtp_packet->info->info_extended_timestamp;
start_rtp_time = 0;
start_time = rtp_packet->arrive_offset;
rtp_time_prev = 0;
}
} else {
// rtp_player.c:664
/* Add silence if it is necessary */
qint64 silence_samples;
if (timing_mode_ == Uninterrupted) {
silence_samples = 0;
} else {
silence_samples = (int)((rtp_time - rtp_time_prev)*sample_rate - decoded_bytes_prev / SAMPLE_BYTES);
silence_samples = silence_samples * audio_out_rate_ / sample_rate;
}
if (silence_samples != 0) {
wrong_timestamp_timestamps_.append(stop_rel_time_);
}
if (silence_samples > 0) {
silence_timestamps_.append(stop_rel_time_);
if ((silence_samples > 0) && (audio_out_rate_ != 0)) {
audio_file_->frameWriteSilence(rtp_packet->frame_num, silence_samples);
}
}
// XXX rtp_player.c:696 adds audio here.
rtp_time_prev = rtp_time;
pack_period = (double) decoded_bytes / SAMPLE_BYTES / sample_rate;
decoded_bytes_prev = decoded_bytes;
arrive_time_prev = arrive_time;
}
// Prepare samples to write
write_buff = (char *) decode_buff;
write_bytes = decoded_bytes;
if (audio_out_rate_ != sample_rate) {
// Resample the audio to match output rate.
// Buffer is in SAMPLEs
spx_uint32_t in_len = (spx_uint32_t) (write_bytes / SAMPLE_BYTES);
// Output is audio_out_rate_/sample_rate bigger than input
spx_uint32_t out_len = (spx_uint32_t) ((guint64)in_len * audio_out_rate_ / sample_rate);
resample_buff = resizeBufferIfNeeded(resample_buff, &resample_buff_bytes, out_len * SAMPLE_BYTES);
if (audio_resampler &&
sample_rate != audio_resampler_input_rate
) {
// Clear old resampler because input rate changed
speex_resampler_destroy(audio_resampler);
audio_resampler_input_rate = 0;
audio_resampler = NULL;
}
if (!audio_resampler) {
audio_resampler_input_rate = sample_rate;
audio_resampler = speex_resampler_init(1, sample_rate, audio_out_rate_, 10, NULL);
RTP_STREAM_DEBUG("Started resampling from %u to (out) %u Hz.", sample_rate, audio_out_rate_);
}
speex_resampler_process_int(audio_resampler, 0, decode_buff, &in_len, resample_buff, &out_len);
write_buff = (char *) resample_buff;
write_bytes = out_len * SAMPLE_BYTES;
}
// We should write only newer data to avoid duplicates in replay
if (last_sequence_w < last_sequence) {
// Write the decoded, possibly-resampled audio to our temp file.
audio_file_->frameWriteSamples(rtp_packet->frame_num, write_buff, write_bytes);
last_sequence_w = last_sequence;
}
g_free(decode_buff);
}
g_free(resample_buff);
if (audio_resampler) speex_resampler_destroy(audio_resampler);
}
// We preallocate buffer, 320 samples is enough for most scenarios
#define VISUAL_BUFF_LEN (320)
#define VISUAL_BUFF_BYTES (SAMPLE_BYTES * VISUAL_BUFF_LEN)
void RtpAudioStream::decodeVisual()
{
spx_uint32_t read_len = 0;
gint32 read_buff_bytes = VISUAL_BUFF_BYTES;
SAMPLE *read_buff = (SAMPLE *) g_malloc(read_buff_bytes);
gint32 resample_buff_bytes = VISUAL_BUFF_BYTES;
SAMPLE *resample_buff = (SAMPLE *) g_malloc(resample_buff_bytes);
unsigned int sample_no = 0;
spx_uint32_t out_len;
guint32 frame_num;
rtp_frame_type type;
speex_resampler_set_rate(visual_resampler_, audio_out_rate_, visual_sample_rate_);
// Loop over every frame record
// readFrameSamples() maintains size of buffer for us
while (audio_file_->readFrameSamples(&read_buff_bytes, &read_buff, &read_len, &frame_num, &type)) {
out_len = (spx_uint32_t)(((guint64)read_len * visual_sample_rate_ ) / audio_out_rate_);
if (type == RTP_FRAME_AUDIO) {
// We resample only audio samples
resample_buff = resizeBufferIfNeeded(resample_buff, &resample_buff_bytes, out_len * SAMPLE_BYTES);
// Resample
speex_resampler_process_int(visual_resampler_, 0, read_buff, &read_len, resample_buff, &out_len);
// Create timestamp and visual sample
for (unsigned i = 0; i < out_len; i++) {
double time = start_rel_time_ + (double) sample_no / visual_sample_rate_;
packet_timestamps_[time] = frame_num;
if (qAbs(resample_buff[i]) > max_sample_val_) max_sample_val_ = qAbs(resample_buff[i]);
visual_samples_.append(resample_buff[i]);
sample_no++;
}
} else {
// Insert end of line mark
double time = start_rel_time_ + (double) sample_no / visual_sample_rate_;
packet_timestamps_[time] = frame_num;
visual_samples_.append(SAMPLE_NaN);
sample_no += out_len;
}
}
max_sample_val_used_ = max_sample_val_;
g_free(resample_buff);
g_free(read_buff);
}
const QStringList RtpAudioStream::payloadNames() const
{
QStringList payload_names = payload_names_.values();
payload_names.sort();
return payload_names;
}
const QVector<double> RtpAudioStream::visualTimestamps(bool relative)
{
QVector<double> ts_keys = packet_timestamps_.keys().toVector();
if (relative) return ts_keys;
QVector<double> adj_timestamps;
for (int i = 0; i < ts_keys.size(); i++) {
adj_timestamps.append(ts_keys[i] + start_abs_offset_ - start_rel_time_);
}
return adj_timestamps;
}
// Scale the height of the waveform to global scale (max_sample_val_used_)
// and adjust its Y offset so that they overlap slightly (stack_offset_).
static const double stack_offset_ = G_MAXINT16 / 3;
const QVector<double> RtpAudioStream::visualSamples(int y_offset)
{
QVector<double> adj_samples;
double scaled_offset = y_offset * stack_offset_;
for (int i = 0; i < visual_samples_.size(); i++) {
if (SAMPLE_NaN != visual_samples_[i]) {
adj_samples.append(((double)visual_samples_[i] * G_MAXINT16 / max_sample_val_used_) + scaled_offset);
} else {
// Convert to break in graph line
adj_samples.append(qQNaN());
}
}
return adj_samples;
}
const QVector<double> RtpAudioStream::outOfSequenceTimestamps(bool relative)
{
if (relative) return out_of_seq_timestamps_;
QVector<double> adj_timestamps;
for (int i = 0; i < out_of_seq_timestamps_.size(); i++) {
adj_timestamps.append(out_of_seq_timestamps_[i] + start_abs_offset_ - start_rel_time_);
}
return adj_timestamps;
}
const QVector<double> RtpAudioStream::outOfSequenceSamples(int y_offset)
{
QVector<double> adj_samples;
double scaled_offset = y_offset * stack_offset_; // XXX Should be different for seq, jitter, wrong & silence
for (int i = 0; i < out_of_seq_timestamps_.size(); i++) {
adj_samples.append(scaled_offset);
}
return adj_samples;
}
const QVector<double> RtpAudioStream::jitterDroppedTimestamps(bool relative)
{
if (relative) return jitter_drop_timestamps_;
QVector<double> adj_timestamps;
for (int i = 0; i < jitter_drop_timestamps_.size(); i++) {
adj_timestamps.append(jitter_drop_timestamps_[i] + start_abs_offset_ - start_rel_time_);
}
return adj_timestamps;
}
const QVector<double> RtpAudioStream::jitterDroppedSamples(int y_offset)
{
QVector<double> adj_samples;
double scaled_offset = y_offset * stack_offset_; // XXX Should be different for seq, jitter, wrong & silence
for (int i = 0; i < jitter_drop_timestamps_.size(); i++) {
adj_samples.append(scaled_offset);
}
return adj_samples;
}
const QVector<double> RtpAudioStream::wrongTimestampTimestamps(bool relative)
{
if (relative) return wrong_timestamp_timestamps_;
QVector<double> adj_timestamps;
for (int i = 0; i < wrong_timestamp_timestamps_.size(); i++) {
adj_timestamps.append(wrong_timestamp_timestamps_[i] + start_abs_offset_ - start_rel_time_);
}
return adj_timestamps;
}
const QVector<double> RtpAudioStream::wrongTimestampSamples(int y_offset)
{
QVector<double> adj_samples;
double scaled_offset = y_offset * stack_offset_; // XXX Should be different for seq, jitter, wrong & silence
for (int i = 0; i < wrong_timestamp_timestamps_.size(); i++) {
adj_samples.append(scaled_offset);
}
return adj_samples;
}
const QVector<double> RtpAudioStream::insertedSilenceTimestamps(bool relative)
{
if (relative) return silence_timestamps_;
QVector<double> adj_timestamps;
for (int i = 0; i < silence_timestamps_.size(); i++) {
adj_timestamps.append(silence_timestamps_[i] + start_abs_offset_ - start_rel_time_);
}
return adj_timestamps;
}
const QVector<double> RtpAudioStream::insertedSilenceSamples(int y_offset)
{
QVector<double> adj_samples;
double scaled_offset = y_offset * stack_offset_; // XXX Should be different for seq, jitter, wrong & silence
for (int i = 0; i < silence_timestamps_.size(); i++) {
adj_samples.append(scaled_offset);
}
return adj_samples;
}
quint32 RtpAudioStream::nearestPacket(double timestamp, bool is_relative)
{
if (packet_timestamps_.size() < 1) return 0;
if (!is_relative) timestamp -= start_abs_offset_;
QMap<double, quint32>::iterator it = packet_timestamps_.lowerBound(timestamp);
if (it == packet_timestamps_.end()) return 0;
return it.value();
}
QAudio::State RtpAudioStream::outputState() const
{
if (!audio_output_) return QAudio::IdleState;
return audio_output_->state();
}
const QString RtpAudioStream::formatDescription(const QAudioFormat &format)
{
QString fmt_descr = QString("%1 Hz, ").arg(format.sampleRate());
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
switch (format.sampleFormat()) {
case QAudioFormat::UInt8:
fmt_descr += "UInt8";
break;
case QAudioFormat::Int16:
fmt_descr += "Int16";
break;
case QAudioFormat::Int32:
fmt_descr += "Int32";
break;
case QAudioFormat::Float:
fmt_descr += "Float";
break;
default:
fmt_descr += "Unknown";
break;
}
#else
switch (format.sampleType()) {
case QAudioFormat::SignedInt:
fmt_descr += "Int";
fmt_descr += QString::number(format.sampleSize());
fmt_descr += format.byteOrder() == QAudioFormat::BigEndian ? "BE" : "LE";
break;
case QAudioFormat::UnSignedInt:
fmt_descr += "UInt";
fmt_descr += QString::number(format.sampleSize());
fmt_descr += format.byteOrder() == QAudioFormat::BigEndian ? "BE" : "LE";
break;
case QAudioFormat::Float:
fmt_descr += "Float";
break;
default:
fmt_descr += "Unknown";
break;
}
#endif
return fmt_descr;
}
QString RtpAudioStream::getIDAsQString()
{
gchar *src_addr_str = address_to_display(NULL, &id_.src_addr);
gchar *dst_addr_str = address_to_display(NULL, &id_.dst_addr);
QString str = QString("%1:%2 - %3:%4 %5")
.arg(src_addr_str)
.arg(id_.src_port)
.arg(dst_addr_str)
.arg(id_.dst_port)
.arg(QString("0x%1").arg(id_.ssrc, 0, 16));
wmem_free(NULL, src_addr_str);
wmem_free(NULL, dst_addr_str);
return str;
}
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
bool RtpAudioStream::prepareForPlay(QAudioDevice out_device)
#else
bool RtpAudioStream::prepareForPlay(QAudioDeviceInfo out_device)
#endif
{
qint64 start_pos;
qint64 size;
if (audio_routing_.isMuted())
return false;
if (audio_output_)
return false;
if (audio_out_rate_ == 0) {
/* It is observed, but is not an error
QString error = tr("RTP stream (%1) is empty or codec is unsupported.")
.arg(getIDAsQString());
emit playbackError(error);
*/
return false;
}
QAudioFormat format;
format.setSampleRate(audio_out_rate_);
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
// Must match rtp_media.h.
format.setSampleFormat(QAudioFormat::Int16);
#else
format.setSampleSize(SAMPLE_BYTES * 8); // bits
format.setSampleType(QAudioFormat::SignedInt);
#endif
if (stereo_required_) {
format.setChannelCount(2);
} else {
format.setChannelCount(1);
}
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
format.setCodec("audio/pcm");
#endif
// RTP_STREAM_DEBUG("playing %s %d samples @ %u Hz",
// sample_file_->fileName().toUtf8().constData(),
// (int) sample_file_->size(), audio_out_rate_);
if (!out_device.isFormatSupported(format)) {
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
QString playback_error = tr("%1 does not support PCM at %2. Preferred format is %3")
.arg(out_device.description(), formatDescription(format), formatDescription(out_device.preferredFormat()));
#else
QString playback_error = tr("%1 does not support PCM at %2. Preferred format is %3")
.arg(out_device.deviceName())
.arg(formatDescription(format))
.arg(formatDescription(out_device.nearestFormat(format)));
#endif
emit playbackError(playback_error);
}
start_pos = (qint64)(start_play_time_ * SAMPLE_BYTES * audio_out_rate_);
// Round to SAMPLE_BYTES boundary
start_pos = (start_pos / SAMPLE_BYTES) * SAMPLE_BYTES;
size = audio_file_->sampleFileSize();
if (stereo_required_) {
// There is 2x more samples for stereo
start_pos *= 2;
size *= 2;
}
if (start_pos < size) {
audio_file_->setDataReadStage();
temp_file_ = new AudioRoutingFilter(audio_file_, stereo_required_, audio_routing_);
temp_file_->seek(start_pos);
if (audio_output_) delete audio_output_;
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
audio_output_ = new QAudioSink(out_device, format, this);
connect(audio_output_, &QAudioSink::stateChanged, this, &RtpAudioStream::outputStateChanged);
#else
audio_output_ = new QAudioOutput(out_device, format, this);
connect(audio_output_, &QAudioOutput::stateChanged, this, &RtpAudioStream::outputStateChanged);
#endif
return true;
} else {
// Report stopped audio if start position is later than stream ends
outputStateChanged(QAudio::StoppedState);
return false;
}
return false;
}
void RtpAudioStream::startPlaying()
{
// On Win32/Qt 6.x start() returns, but state() is QAudio::StoppedState even
// everything is OK
audio_output_->start(temp_file_);
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
// Bug is related to Qt 4.x and probably for 5.x, but not for 6.x
// QTBUG-6548 StoppedState is not always emitted on error, force a cleanup
// in case playback fails immediately.
if (audio_output_ && audio_output_->state() == QAudio::StoppedState) {
outputStateChanged(QAudio::StoppedState);
}
#endif
}
void RtpAudioStream::pausePlaying()
{
if (audio_routing_.isMuted())
return;
if (audio_output_) {
if (QAudio::ActiveState == audio_output_->state()) {
audio_output_->suspend();
} else if (QAudio::SuspendedState == audio_output_->state()) {
audio_output_->resume();
}
}
}
void RtpAudioStream::stopPlaying()
{
if (audio_routing_.isMuted())
return;
if (audio_output_) {
if (audio_output_->state() == QAudio::StoppedState) {
// Looks like "delayed" QTBUG-6548
// It may happen that stream is stopped, but no signal emited
// Probably triggered by some issue in sound system which is not
// handled by Qt correctly
outputStateChanged(QAudio::StoppedState);
} else {
audio_output_->stop();
}
}
}
void RtpAudioStream::seekPlaying(qint64 samples _U_)
{
if (audio_routing_.isMuted())
return;
if (audio_output_) {
audio_output_->suspend();
audio_file_->seekSample(samples);
audio_output_->resume();
}
}
void RtpAudioStream::outputStateChanged(QAudio::State new_state)
{
if (!audio_output_) return;
// On some platforms including macOS and Windows, the stateChanged signal
// is emitted while a QMutexLocker is active. As a result we shouldn't
// delete audio_output_ here.
switch (new_state) {
case QAudio::StoppedState:
{
// RTP_STREAM_DEBUG("stopped %f", audio_output_->processedUSecs() / 100000.0);
// Detach from parent (RtpAudioStream) to prevent deleteLater
// from being run during destruction of this class.
QAudio::Error error = audio_output_->error();
audio_output_->setParent(0);
audio_output_->disconnect();
audio_output_->deleteLater();
audio_output_ = NULL;
emit finishedPlaying(this, error);
break;
}
case QAudio::IdleState:
// Workaround for Qt behaving on some platforms with some soundcards:
// When ->stop() is called from outputStateChanged(),
// internalQMutexLock is locked and application hangs.
// We can stop the stream later.
QTimer::singleShot(0, this, SLOT(delayedStopStream()));
break;
default:
break;
}
}
void RtpAudioStream::delayedStopStream()
{
audio_output_->stop();
}
SAMPLE *RtpAudioStream::resizeBufferIfNeeded(SAMPLE *buff, gint32 *buff_bytes, qint64 requested_size)
{
if (requested_size > *buff_bytes) {
while ((requested_size > *buff_bytes))
*buff_bytes *= 2;
buff = (SAMPLE *) g_realloc(buff, *buff_bytes);
}
return buff;
}
void RtpAudioStream::seekSample(qint64 samples)
{
audio_file_->seekSample(samples);
}
qint64 RtpAudioStream::readSample(SAMPLE *sample)
{
return audio_file_->readSample(sample);
}
bool RtpAudioStream::savePayload(QIODevice *file)
{
for (int cur_packet = 0; cur_packet < rtp_packets_.size(); cur_packet++) {
// TODO: Update a progress bar here.
rtp_packet_t *rtp_packet = rtp_packets_[cur_packet];
if ((rtp_packet->info->info_payload_type != PT_CN) &&
(rtp_packet->info->info_payload_type != PT_CN_OLD)) {
// All other payloads
int64_t nchars;
if (rtp_packet->payload_data && (rtp_packet->info->info_payload_len > 0)) {
nchars = file->write((char *)rtp_packet->payload_data, rtp_packet->info->info_payload_len);
if (nchars != rtp_packet->info->info_payload_len) {
return false;
}
}
}
}
return true;
}
#endif // QT_MULTIMEDIA_LIB |
C/C++ | wireshark/ui/qt/rtp_audio_stream.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef RTPAUDIOSTREAM_H
#define RTPAUDIOSTREAM_H
#include "config.h"
#ifdef QT_MULTIMEDIA_LIB
#include <glib.h>
#include <epan/address.h>
#include <ui/rtp_stream.h>
#include <ui/qt/utils/rtp_audio_routing.h>
#include <ui/qt/utils/rtp_audio_file.h>
#include <ui/rtp_media.h>
#include <QAudio>
#include <QColor>
#include <QMap>
#include <QObject>
#include <QSet>
#include <QVector>
#include <QIODevice>
#include <QAudioOutput>
class QAudioFormat;
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
class QAudioSink;
#else
class QAudioOutput;
#endif
class QIODevice;
class RtpAudioStream : public QObject
{
Q_OBJECT
public:
enum TimingMode { JitterBuffer, RtpTimestamp, Uninterrupted };
explicit RtpAudioStream(QObject *parent, rtpstream_id_t *id, bool stereo_required);
~RtpAudioStream();
bool isMatch(const rtpstream_id_t *id) const;
bool isMatch(const struct _packet_info *pinfo, const struct _rtp_info *rtp_info) const;
void addRtpPacket(const struct _packet_info *pinfo, const struct _rtp_info *rtp_info);
void clearPackets();
void reset(double global_start_time);
AudioRouting getAudioRouting();
void setAudioRouting(AudioRouting audio_routing);
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
void decode(QAudioDevice out_device);
#else
void decode(QAudioDeviceInfo out_device);
#endif
double startRelTime() const { return start_rel_time_; }
double stopRelTime() const { return stop_rel_time_; }
unsigned sampleRate() const { return first_sample_rate_; }
unsigned playRate() const { return audio_out_rate_; }
void setRequestedPlayRate(unsigned new_rate) { audio_requested_out_rate_ = new_rate; }
const QStringList payloadNames() const;
/**
* @brief Return a list of visual timestamps.
* @return A set of timestamps suitable for passing to QCPGraph::setData.
*/
const QVector<double> visualTimestamps(bool relative = true);
/**
* @brief Return a list of visual samples. There will be fewer visual samples
* per second (1000) than the actual audio.
* @param y_offset Y axis offset to be used for stacking graphs.
* @return A set of values suitable for passing to QCPGraph::setData.
*/
const QVector<double> visualSamples(int y_offset = 0);
/**
* @brief Return a list of out-of-sequence timestamps.
* @return A set of timestamps suitable for passing to QCPGraph::setData.
*/
const QVector<double> outOfSequenceTimestamps(bool relative = true);
int outOfSequence() { return static_cast<int>(out_of_seq_timestamps_.size()); }
/**
* @brief Return a list of out-of-sequence samples. Y value is constant.
* @param y_offset Y axis offset to be used for stacking graphs.
* @return A set of values suitable for passing to QCPGraph::setData.
*/
const QVector<double> outOfSequenceSamples(int y_offset = 0);
/**
* @brief Return a list of jitter dropped timestamps.
* @return A set of timestamps suitable for passing to QCPGraph::setData.
*/
const QVector<double> jitterDroppedTimestamps(bool relative = true);
int jitterDropped() { return static_cast<int>(jitter_drop_timestamps_.size()); }
/**
* @brief Return a list of jitter dropped samples. Y value is constant.
* @param y_offset Y axis offset to be used for stacking graphs.
* @return A set of values suitable for passing to QCPGraph::setData.
*/
const QVector<double> jitterDroppedSamples(int y_offset = 0);
/**
* @brief Return a list of wrong timestamps.
* @return A set of timestamps suitable for passing to QCPGraph::setData.
*/
const QVector<double> wrongTimestampTimestamps(bool relative = true);
int wrongTimestamps() { return static_cast<int>(wrong_timestamp_timestamps_.size()); }
/**
* @brief Return a list of wrong timestamp samples. Y value is constant.
* @param y_offset Y axis offset to be used for stacking graphs.
* @return A set of values suitable for passing to QCPGraph::setData.
*/
const QVector<double> wrongTimestampSamples(int y_offset = 0);
/**
* @brief Return a list of inserted silence timestamps.
* @return A set of timestamps suitable for passing to QCPGraph::setData.
*/
const QVector<double> insertedSilenceTimestamps(bool relative = true);
int insertedSilences() { return static_cast<int>(silence_timestamps_.size()); }
/**
* @brief Return a list of wrong timestamp samples. Y value is constant.
* @param y_offset Y axis offset to be used for stacking graphs.
* @return A set of values suitable for passing to QCPGraph::setData.
*/
const QVector<double> insertedSilenceSamples(int y_offset = 0);
quint32 nearestPacket(double timestamp, bool is_relative = true);
QRgb color() { return color_; }
void setColor(QRgb color) { color_ = color; }
QAudio::State outputState() const;
void setJitterBufferSize(int jitter_buffer_size) { jitter_buffer_size_ = jitter_buffer_size; }
void setTimingMode(TimingMode timing_mode) { timing_mode_ = timing_mode; }
void setStartPlayTime(double start_play_time) { start_play_time_ = start_play_time; }
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
bool prepareForPlay(QAudioDevice out_device);
#else
bool prepareForPlay(QAudioDeviceInfo out_device);
#endif
void startPlaying();
void pausePlaying();
void stopPlaying();
void seekPlaying(qint64 samples);
void setStereoRequired(bool stereo_required) { stereo_required_ = stereo_required; }
qint16 getMaxSampleValue() { return max_sample_val_; }
void setMaxSampleValue(gint16 max_sample_val) { max_sample_val_used_ = max_sample_val; }
void seekSample(qint64 samples);
qint64 readSample(SAMPLE *sample);
qint64 getLeadSilenceSamples() { return prepend_samples_; }
qint64 getTotalSamples() { return (audio_file_->getTotalSamples()); }
qint64 getEndOfSilenceSample() { return (audio_file_->getEndOfSilenceSample()); }
double getEndOfSilenceTime() { return (double)getEndOfSilenceSample() / (double)playRate(); }
qint64 convertTimeToSamples(double time) { return (qint64)(time * playRate()); }
bool savePayload(QIODevice *file);
guint getHash() { return rtpstream_id_to_hash(&(id_)); }
rtpstream_id_t *getID() { return &(id_); }
QString getIDAsQString();
rtpstream_info_t *getStreamInfo() { return &rtpstream_; }
signals:
void processedSecs(double secs);
void playbackError(const QString error_msg);
void finishedPlaying(RtpAudioStream *stream, QAudio::Error error);
private:
// Used to identify unique streams.
// The GTK+ UI also uses the call number + current channel.
rtpstream_id_t id_;
rtpstream_info_t rtpstream_;
bool first_packet_;
QVector<struct _rtp_packet *>rtp_packets_;
RtpAudioFile *audio_file_; // Stores waveform samples in sparse file
QIODevice *temp_file_;
struct _GHashTable *decoders_hash_;
double global_start_rel_time_;
double start_abs_offset_;
double start_rel_time_;
double stop_rel_time_;
qint64 prepend_samples_; // Count of silence samples at begin of the stream to align with other streams
AudioRouting audio_routing_;
bool stereo_required_;
quint32 first_sample_rate_;
quint32 audio_out_rate_;
quint32 audio_requested_out_rate_;
QSet<QString> payload_names_;
struct SpeexResamplerState_ *visual_resampler_;
QMap<double, quint32> packet_timestamps_;
QVector<qint16> visual_samples_;
QVector<double> out_of_seq_timestamps_;
QVector<double> jitter_drop_timestamps_;
QVector<double> wrong_timestamp_timestamps_;
QVector<double> silence_timestamps_;
qint16 max_sample_val_;
qint16 max_sample_val_used_;
QRgb color_;
int jitter_buffer_size_;
TimingMode timing_mode_;
double start_play_time_;
const QString formatDescription(const QAudioFormat & format);
QString currentOutputDevice();
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
QAudioSink *audio_output_;
void decodeAudio(QAudioDevice out_device);
quint32 calculateAudioOutRate(QAudioDevice out_device, unsigned int sample_rate, unsigned int requested_out_rate);
#else
QAudioOutput *audio_output_;
void decodeAudio(QAudioDeviceInfo out_device);
quint32 calculateAudioOutRate(QAudioDeviceInfo out_device, unsigned int sample_rate, unsigned int requested_out_rate);
#endif
void decodeVisual();
SAMPLE *resizeBufferIfNeeded(SAMPLE *buff, gint32 *buff_bytes, qint64 requested_size);
private slots:
void outputStateChanged(QAudio::State new_state);
void delayedStopStream();
};
#endif // QT_MULTIMEDIA_LIB
#endif // RTPAUDIOSTREAM_H |
C++ | wireshark/ui/qt/rtp_player_dialog.cpp | /* rtp_player_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 <ui/rtp_media.h>
#include <ui/tap-rtp-common.h>
#include "rtp_player_dialog.h"
#include <ui_rtp_player_dialog.h>
#include "epan/epan_dissect.h"
#include "file.h"
#include "frame_tvbuff.h"
#include "rtp_analysis_dialog.h"
#ifdef QT_MULTIMEDIA_LIB
#include <epan/dissectors/packet-rtp.h>
#include <epan/to_str.h>
#include <wsutil/report_message.h>
#include <wsutil/utf8_entities.h>
#include <wsutil/pint.h>
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/widgets/qcustomplot.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "rtp_audio_stream.h"
#include <ui/qt/utils/tango_colors.h>
#include <widgets/rtp_audio_graph.h>
#include "main_application.h"
#include "ui/qt/widgets/wireshark_file_dialog.h"
#include <QAudio>
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
#include <algorithm>
#include <QAudioDevice>
#include <QAudioSink>
#include <QMediaDevices>
#else
#include <QAudioDeviceInfo>
#endif
#include <QFrame>
#include <QMenu>
#include <QVBoxLayout>
#include <QTimer>
#include <QAudioFormat>
#include <QAudioOutput>
#include <ui/qt/utils/rtp_audio_silence_generator.h>
#endif // QT_MULTIMEDIA_LIB
#include <QPushButton>
#include <QToolButton>
#include <ui/qt/utils/stock_icon.h>
#include "main_application.h"
// To do:
// - Threaded decoding?
// Current and former RTP player bugs. Many have attachments that can be usef for testing.
// Bug 3368 - The timestamp line in a RTP or RTCP packet display's "Not Representable"
// Bug 3952 - VoIP Call RTP Player: audio played is corrupted when RFC2833 packets are present
// Bug 4960 - RTP Player: Audio and visual feedback get rapidly out of sync
// Bug 5527 - Adding arbitrary value to x-axis RTP player
// Bug 7935 - Wrong Timestamps in RTP Player-Decode
// Bug 8007 - UI gets confused on playing decoded audio in rtp_player
// Bug 9007 - Switching SSRC values in RTP stream
// Bug 10613 - RTP audio player crashes
// Bug 11125 - RTP Player does not show progress in selected stream in Window 7
// Bug 11409 - Wireshark crashes when using RTP player
// Bug 12166 - RTP audio player crashes
// In some places we match by conv/call number, in others we match by first frame.
enum {
channel_col_,
src_addr_col_,
src_port_col_,
dst_addr_col_,
dst_port_col_,
ssrc_col_,
first_pkt_col_,
num_pkts_col_,
time_span_col_,
sample_rate_col_,
play_rate_col_,
payload_col_,
stream_data_col_ = src_addr_col_, // RtpAudioStream
graph_audio_data_col_ = src_port_col_, // QCPGraph (wave)
graph_sequence_data_col_ = dst_addr_col_, // QCPGraph (sequence)
graph_jitter_data_col_ = dst_port_col_, // QCPGraph (jitter)
graph_timestamp_data_col_ = ssrc_col_, // QCPGraph (timestamp)
// first_pkt_col_ is skipped, it is used for real data
graph_silence_data_col_ = num_pkts_col_, // QCPGraph (silence)
};
class RtpPlayerTreeWidgetItem : public QTreeWidgetItem
{
public:
RtpPlayerTreeWidgetItem(QTreeWidget *tree) :
QTreeWidgetItem(tree)
{
}
bool operator< (const QTreeWidgetItem &other) const
{
// Handle numeric sorting
switch (treeWidget()->sortColumn()) {
case src_port_col_:
case dst_port_col_:
case num_pkts_col_:
case sample_rate_col_:
return text(treeWidget()->sortColumn()).toInt() < other.text(treeWidget()->sortColumn()).toInt();
case play_rate_col_:
return text(treeWidget()->sortColumn()).toInt() < other.text(treeWidget()->sortColumn()).toInt();
case first_pkt_col_:
int v1;
int v2;
v1 = data(first_pkt_col_, Qt::UserRole).toInt();
v2 = other.data(first_pkt_col_, Qt::UserRole).toInt();
return v1 < v2;
default:
// Fall back to string comparison
return QTreeWidgetItem::operator <(other);
break;
}
}
};
RtpPlayerDialog *RtpPlayerDialog::pinstance_{nullptr};
std::mutex RtpPlayerDialog::init_mutex_;
std::mutex RtpPlayerDialog::run_mutex_;
RtpPlayerDialog *RtpPlayerDialog::openRtpPlayerDialog(QWidget &parent, CaptureFile &cf, QObject *packet_list, bool capture_running)
{
std::lock_guard<std::mutex> lock(init_mutex_);
if (pinstance_ == nullptr)
{
pinstance_ = new RtpPlayerDialog(parent, cf, capture_running);
connect(pinstance_, SIGNAL(goToPacket(int)),
packet_list, SLOT(goToPacket(int)));
}
return pinstance_;
}
RtpPlayerDialog::RtpPlayerDialog(QWidget &parent, CaptureFile &cf, bool capture_running _U_) :
WiresharkDialog(parent, cf)
#ifdef QT_MULTIMEDIA_LIB
, ui(new Ui::RtpPlayerDialog)
, first_stream_rel_start_time_(0.0)
, first_stream_abs_start_time_(0.0)
, first_stream_rel_stop_time_(0.0)
, streams_length_(0.0)
, start_marker_time_(0.0)
, number_ticker_(new QCPAxisTicker)
, datetime_ticker_(new QCPAxisTickerDateTime)
, stereo_available_(false)
, marker_stream_(0)
, marker_stream_requested_out_rate_(0)
, last_ti_(0)
, listener_removed_(true)
, block_redraw_(false)
, lock_ui_(0)
, read_capture_enabled_(capture_running)
, silence_skipped_time_(0.0)
#endif // QT_MULTIMEDIA_LIB
{
ui->setupUi(this);
loadGeometry(parent.width(), parent.height());
setWindowTitle(mainApp->windowTitleString(tr("RTP Player")));
ui->streamTreeWidget->installEventFilter(this);
ui->audioPlot->installEventFilter(this);
installEventFilter(this);
#ifdef QT_MULTIMEDIA_LIB
ui->splitter->setStretchFactor(0, 3);
ui->splitter->setStretchFactor(1, 1);
ui->streamTreeWidget->sortByColumn(first_pkt_col_, Qt::AscendingOrder);
graph_ctx_menu_ = new QMenu(this);
graph_ctx_menu_->addAction(ui->actionZoomIn);
graph_ctx_menu_->addAction(ui->actionZoomOut);
graph_ctx_menu_->addAction(ui->actionReset);
graph_ctx_menu_->addSeparator();
graph_ctx_menu_->addAction(ui->actionMoveRight10);
graph_ctx_menu_->addAction(ui->actionMoveLeft10);
graph_ctx_menu_->addAction(ui->actionMoveRight1);
graph_ctx_menu_->addAction(ui->actionMoveLeft1);
graph_ctx_menu_->addSeparator();
graph_ctx_menu_->addAction(ui->actionGoToPacket);
graph_ctx_menu_->addAction(ui->actionGoToSetupPacketPlot);
set_action_shortcuts_visible_in_context_menu(graph_ctx_menu_->actions());
ui->streamTreeWidget->setMouseTracking(true);
connect(ui->streamTreeWidget, &QTreeWidget::itemEntered, this, &RtpPlayerDialog::itemEntered);
connect(ui->audioPlot, &QCustomPlot::mouseMove, this, &RtpPlayerDialog::mouseMovePlot);
connect(ui->audioPlot, &QCustomPlot::mousePress, this, &RtpPlayerDialog::graphClicked);
connect(ui->audioPlot, &QCustomPlot::mouseDoubleClick, this, &RtpPlayerDialog::graphDoubleClicked);
connect(ui->audioPlot, &QCustomPlot::plottableClick, this, &RtpPlayerDialog::plotClicked);
cur_play_pos_ = new QCPItemStraightLine(ui->audioPlot);
cur_play_pos_->setVisible(false);
start_marker_pos_ = new QCPItemStraightLine(ui->audioPlot);
start_marker_pos_->setPen(QPen(Qt::green,4));
setStartPlayMarker(0);
drawStartPlayMarker();
start_marker_pos_->setVisible(true);
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
notify_timer_.setInterval(100); // ~15 fps
connect(¬ify_timer_, &QTimer::timeout, this, &RtpPlayerDialog::outputNotify);
#endif
datetime_ticker_->setDateTimeFormat("yyyy-MM-dd\nhh:mm:ss.zzz");
ui->audioPlot->xAxis->setNumberFormat("gb");
ui->audioPlot->xAxis->setNumberPrecision(3);
ui->audioPlot->xAxis->setTicker(datetime_ticker_);
ui->audioPlot->yAxis->setVisible(false);
ui->playButton->setIcon(StockIcon("media-playback-start"));
ui->playButton->setEnabled(false);
ui->pauseButton->setIcon(StockIcon("media-playback-pause"));
ui->pauseButton->setCheckable(true);
ui->pauseButton->setVisible(false);
ui->stopButton->setIcon(StockIcon("media-playback-stop"));
ui->stopButton->setEnabled(false);
ui->skipSilenceButton->setIcon(StockIcon("media-seek-forward"));
ui->skipSilenceButton->setCheckable(true);
ui->skipSilenceButton->setEnabled(false);
read_btn_ = ui->buttonBox->addButton(ui->actionReadCapture->text(), QDialogButtonBox::ActionRole);
read_btn_->setToolTip(ui->actionReadCapture->toolTip());
read_btn_->setEnabled(false);
connect(read_btn_, &QPushButton::pressed, this, &RtpPlayerDialog::on_actionReadCapture_triggered);
inaudible_btn_ = new QToolButton();
ui->buttonBox->addButton(inaudible_btn_, QDialogButtonBox::ActionRole);
inaudible_btn_->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
inaudible_btn_->setPopupMode(QToolButton::MenuButtonPopup);
connect(ui->actionInaudibleButton, &QAction::triggered, this, &RtpPlayerDialog::on_actionSelectInaudible_triggered);
inaudible_btn_->setDefaultAction(ui->actionInaudibleButton);
// Overrides text striping of shortcut undercode in QAction
inaudible_btn_->setText(ui->actionInaudibleButton->text());
inaudible_btn_->setEnabled(false);
inaudible_btn_->setMenu(ui->menuInaudible);
analyze_btn_ = RtpAnalysisDialog::addAnalyzeButton(ui->buttonBox, this);
prepare_btn_ = ui->buttonBox->addButton(ui->actionPrepareFilter->text(), QDialogButtonBox::ActionRole);
prepare_btn_->setToolTip(ui->actionPrepareFilter->toolTip());
connect(prepare_btn_, &QPushButton::pressed, this, &RtpPlayerDialog::on_actionPrepareFilter_triggered);
export_btn_ = ui->buttonBox->addButton(ui->actionExportButton->text(), QDialogButtonBox::ActionRole);
export_btn_->setToolTip(ui->actionExportButton->toolTip());
export_btn_->setEnabled(false);
export_btn_->setMenu(ui->menuExport);
// Ordered, unique device names starting with the system default
QMap<QString, bool> out_device_map; // true == default device
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
out_device_map.insert(QMediaDevices::defaultAudioOutput().description(), true);
foreach (QAudioDevice out_device, QMediaDevices::audioOutputs()) {
if (!out_device_map.contains(out_device.description())) {
out_device_map.insert(out_device.description(), false);
}
}
#else
out_device_map.insert(QAudioDeviceInfo::defaultOutputDevice().deviceName(), true);
foreach (QAudioDeviceInfo out_device, QAudioDeviceInfo::availableDevices(QAudio::AudioOutput)) {
if (!out_device_map.contains(out_device.deviceName())) {
out_device_map.insert(out_device.deviceName(), false);
}
}
#endif
ui->outputDeviceComboBox->blockSignals(true);
foreach (QString out_name, out_device_map.keys()) {
ui->outputDeviceComboBox->addItem(out_name);
if (out_device_map.value(out_name)) {
ui->outputDeviceComboBox->setCurrentIndex(ui->outputDeviceComboBox->count() - 1);
}
}
if (ui->outputDeviceComboBox->count() < 1) {
ui->outputDeviceComboBox->setEnabled(false);
ui->playButton->setEnabled(false);
ui->pauseButton->setEnabled(false);
ui->stopButton->setEnabled(false);
ui->skipSilenceButton->setEnabled(false);
ui->minSilenceSpinBox->setEnabled(false);
ui->outputDeviceComboBox->addItem(tr("No devices available"));
ui->outputAudioRate->setEnabled(false);
} else {
stereo_available_ = isStereoAvailable();
fillAudioRateMenu();
}
ui->outputDeviceComboBox->blockSignals(false);
ui->audioPlot->setMouseTracking(true);
ui->audioPlot->setEnabled(true);
ui->audioPlot->setInteractions(
QCP::iRangeDrag |
QCP::iRangeZoom
);
graph_ctx_menu_->addSeparator();
list_ctx_menu_ = new QMenu(this);
list_ctx_menu_->addAction(ui->actionPlay);
graph_ctx_menu_->addAction(ui->actionPlay);
list_ctx_menu_->addAction(ui->actionStop);
graph_ctx_menu_->addAction(ui->actionStop);
list_ctx_menu_->addMenu(ui->menuSelect);
graph_ctx_menu_->addMenu(ui->menuSelect);
list_ctx_menu_->addMenu(ui->menuAudioRouting);
graph_ctx_menu_->addMenu(ui->menuAudioRouting);
list_ctx_menu_->addAction(ui->actionRemoveStream);
graph_ctx_menu_->addAction(ui->actionRemoveStream);
list_ctx_menu_->addAction(ui->actionGoToSetupPacketTree);
set_action_shortcuts_visible_in_context_menu(list_ctx_menu_->actions());
connect(&cap_file_, &CaptureFile::captureEvent, this, &RtpPlayerDialog::captureEvent);
connect(this, SIGNAL(updateFilter(QString, bool)),
&parent, SLOT(filterPackets(QString, bool)));
connect(this, SIGNAL(rtpAnalysisDialogReplaceRtpStreams(QVector<rtpstream_id_t *>)),
&parent, SLOT(rtpAnalysisDialogReplaceRtpStreams(QVector<rtpstream_id_t *>)));
connect(this, SIGNAL(rtpAnalysisDialogAddRtpStreams(QVector<rtpstream_id_t *>)),
&parent, SLOT(rtpAnalysisDialogAddRtpStreams(QVector<rtpstream_id_t *>)));
connect(this, SIGNAL(rtpAnalysisDialogRemoveRtpStreams(QVector<rtpstream_id_t *>)),
&parent, SLOT(rtpAnalysisDialogRemoveRtpStreams(QVector<rtpstream_id_t *>)));
#endif // QT_MULTIMEDIA_LIB
}
// _U_ is used when no QT_MULTIMEDIA_LIB is available
QToolButton *RtpPlayerDialog::addPlayerButton(QDialogButtonBox *button_box, QDialog *dialog _U_)
{
if (!button_box) return NULL;
QAction *ca;
QToolButton *player_button = new QToolButton();
button_box->addButton(player_button, QDialogButtonBox::ActionRole);
player_button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
player_button->setPopupMode(QToolButton::MenuButtonPopup);
ca = new QAction(tr("&Play Streams"), player_button);
ca->setToolTip(tr("Open RTP player dialog"));
ca->setIcon(StockIcon("media-playback-start"));
connect(ca, SIGNAL(triggered()), dialog, SLOT(rtpPlayerReplace()));
player_button->setDefaultAction(ca);
// Overrides text striping of shortcut undercode in QAction
player_button->setText(ca->text());
#if defined(QT_MULTIMEDIA_LIB)
QMenu *button_menu = new QMenu(player_button);
button_menu->setToolTipsVisible(true);
ca = button_menu->addAction(tr("&Set playlist"));
ca->setToolTip(tr("Replace existing playlist in RTP Player with new one"));
connect(ca, SIGNAL(triggered()), dialog, SLOT(rtpPlayerReplace()));
ca = button_menu->addAction(tr("&Add to playlist"));
ca->setToolTip(tr("Add new set to existing playlist in RTP Player"));
connect(ca, SIGNAL(triggered()), dialog, SLOT(rtpPlayerAdd()));
ca = button_menu->addAction(tr("&Remove from playlist"));
ca->setToolTip(tr("Remove selected streams from playlist in RTP Player"));
connect(ca, SIGNAL(triggered()), dialog, SLOT(rtpPlayerRemove()));
player_button->setMenu(button_menu);
#else
player_button->setEnabled(false);
player_button->setText(tr("No Audio"));
#endif
return player_button;
}
#ifdef QT_MULTIMEDIA_LIB
RtpPlayerDialog::~RtpPlayerDialog()
{
std::lock_guard<std::mutex> lock(init_mutex_);
if (pinstance_ != nullptr) {
cleanupMarkerStream();
for (int row = 0; row < ui->streamTreeWidget->topLevelItemCount(); row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
if (audio_stream)
delete audio_stream;
}
delete ui;
pinstance_ = nullptr;
}
}
void RtpPlayerDialog::accept()
{
if (!listener_removed_) {
remove_tap_listener(this);
listener_removed_ = true;
}
int row_count = ui->streamTreeWidget->topLevelItemCount();
// Stop all streams before the dialogs are closed.
for (int row = 0; row < row_count; row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
audio_stream->stopPlaying();
}
WiresharkDialog::accept();
}
void RtpPlayerDialog::reject()
{
RtpPlayerDialog::accept();
}
void RtpPlayerDialog::retapPackets()
{
if (!listener_removed_) {
// Retap is running, nothing better we can do
return;
}
lockUI();
ui->hintLabel->setText("<i><small>" + tr("Decoding streams...") + "</i></small>");
mainApp->processEvents();
// Clear packets from existing streams before retap
for (int row = 0; row < ui->streamTreeWidget->topLevelItemCount(); row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioStream *row_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
row_stream->clearPackets();
}
// destroyCheck is protection againts destroying dialog during recap.
// It stores dialog pointer in data() and if dialog destroyed, it
// returns null
QPointer<RtpPlayerDialog> destroyCheck=this;
GString *error_string;
listener_removed_ = false;
error_string = register_tap_listener("rtp", this, NULL, 0, NULL, tapPacket, NULL, NULL);
if (error_string) {
report_failure("RTP Player - tap registration failed: %s", error_string->str);
g_string_free(error_string, TRUE);
unlockUI();
return;
}
cap_file_.retapPackets();
// Check if dialog exists still
if (destroyCheck.data()) {
if (!listener_removed_) {
remove_tap_listener(this);
listener_removed_ = true;
}
fillTappedColumns();
rescanPackets(true);
}
unlockUI();
}
void RtpPlayerDialog::rescanPackets(bool rescale_axes)
{
lockUI();
// Show information for a user - it can last long time...
playback_error_.clear();
ui->hintLabel->setText("<i><small>" + tr("Decoding streams...") + "</i></small>");
mainApp->processEvents();
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
QAudioDevice cur_out_device = getCurrentDeviceInfo();
#else
QAudioDeviceInfo cur_out_device = getCurrentDeviceInfo();
#endif
int row_count = ui->streamTreeWidget->topLevelItemCount();
// Reset stream values
for (int row = 0; row < row_count; row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
audio_stream->setStereoRequired(stereo_available_);
audio_stream->reset(first_stream_rel_start_time_);
audio_stream->setJitterBufferSize((int) ui->jitterSpinBox->value());
RtpAudioStream::TimingMode timing_mode = RtpAudioStream::JitterBuffer;
switch (ui->timingComboBox->currentIndex()) {
case RtpAudioStream::RtpTimestamp:
timing_mode = RtpAudioStream::RtpTimestamp;
break;
case RtpAudioStream::Uninterrupted:
timing_mode = RtpAudioStream::Uninterrupted;
break;
default:
break;
}
audio_stream->setTimingMode(timing_mode);
//if (!cur_out_device.isNull()) {
audio_stream->decode(cur_out_device);
//}
}
for (int col = 0; col < ui->streamTreeWidget->columnCount() - 1; col++) {
ui->streamTreeWidget->resizeColumnToContents(col);
}
createPlot(rescale_axes);
updateWidgets();
unlockUI();
}
void RtpPlayerDialog::createPlot(bool rescale_axes)
{
bool legend_out_of_sequence = false;
bool legend_jitter_dropped = false;
bool legend_wrong_timestamps = false;
bool legend_inserted_silences = false;
bool relative_timestamps = !ui->todCheckBox->isChecked();
int row_count = ui->streamTreeWidget->topLevelItemCount();
gint16 total_max_sample_value = 1;
ui->audioPlot->clearGraphs();
if (relative_timestamps) {
ui->audioPlot->xAxis->setTicker(number_ticker_);
} else {
ui->audioPlot->xAxis->setTicker(datetime_ticker_);
}
// Calculate common Y scale for graphs
for (int row = 0; row < row_count; row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
gint16 max_sample_value = audio_stream->getMaxSampleValue();
if (max_sample_value > total_max_sample_value) {
total_max_sample_value = max_sample_value;
}
}
// Clear existing graphs
for (int row = 0; row < row_count; row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
int y_offset = row_count - row - 1;
AudioRouting audio_routing = audio_stream->getAudioRouting();
ti->setData(graph_audio_data_col_, Qt::UserRole, QVariant());
ti->setData(graph_sequence_data_col_, Qt::UserRole, QVariant());
ti->setData(graph_jitter_data_col_, Qt::UserRole, QVariant());
ti->setData(graph_timestamp_data_col_, Qt::UserRole, QVariant());
ti->setData(graph_silence_data_col_, Qt::UserRole, QVariant());
// Set common scale
audio_stream->setMaxSampleValue(total_max_sample_value);
// Waveform
RtpAudioGraph *audio_graph = new RtpAudioGraph(ui->audioPlot, audio_stream->color());
audio_graph->setMuted(audio_routing.isMuted());
audio_graph->setData(audio_stream->visualTimestamps(relative_timestamps), audio_stream->visualSamples(y_offset));
ti->setData(graph_audio_data_col_, Qt::UserRole, QVariant::fromValue<RtpAudioGraph *>(audio_graph));
//RTP_STREAM_DEBUG("Plotting %s, %d samples", ti->text(src_addr_col_).toUtf8().constData(), audio_graph->wave->data()->size());
QString span_str;
if (ui->todCheckBox->isChecked()) {
QDateTime date_time1 = QDateTime::fromMSecsSinceEpoch((audio_stream->startRelTime() + first_stream_abs_start_time_ - audio_stream->startRelTime()) * 1000.0);
QDateTime date_time2 = QDateTime::fromMSecsSinceEpoch((audio_stream->stopRelTime() + first_stream_abs_start_time_ - audio_stream->startRelTime()) * 1000.0);
QString time_str1 = date_time1.toString("yyyy-MM-dd hh:mm:ss.zzz");
QString time_str2 = date_time2.toString("yyyy-MM-dd hh:mm:ss.zzz");
span_str = QString("%1 - %2 (%3)")
.arg(time_str1)
.arg(time_str2)
.arg(QString::number(audio_stream->stopRelTime() - audio_stream->startRelTime(), 'f', prefs.gui_decimal_places1));
} else {
span_str = QString("%1 - %2 (%3)")
.arg(QString::number(audio_stream->startRelTime(), 'f', prefs.gui_decimal_places1))
.arg(QString::number(audio_stream->stopRelTime(), 'f', prefs.gui_decimal_places1))
.arg(QString::number(audio_stream->stopRelTime() - audio_stream->startRelTime(), 'f', prefs.gui_decimal_places1));
}
ti->setText(time_span_col_, span_str);
ti->setText(sample_rate_col_, QString::number(audio_stream->sampleRate()));
ti->setText(play_rate_col_, QString::number(audio_stream->playRate()));
ti->setText(payload_col_, audio_stream->payloadNames().join(", "));
if (audio_stream->outOfSequence() > 0) {
// Sequence numbers
QCPGraph *seq_graph = ui->audioPlot->addGraph();
seq_graph->setLineStyle(QCPGraph::lsNone);
seq_graph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssSquare, tango_aluminium_6, Qt::white, mainApp->font().pointSize())); // Arbitrary
seq_graph->setSelectable(QCP::stNone);
seq_graph->setData(audio_stream->outOfSequenceTimestamps(relative_timestamps), audio_stream->outOfSequenceSamples(y_offset));
ti->setData(graph_sequence_data_col_, Qt::UserRole, QVariant::fromValue<QCPGraph *>(seq_graph));
if (legend_out_of_sequence) {
seq_graph->removeFromLegend();
} else {
seq_graph->setName(tr("Out of Sequence"));
legend_out_of_sequence = true;
}
}
if (audio_stream->jitterDropped() > 0) {
// Jitter drops
QCPGraph *seq_graph = ui->audioPlot->addGraph();
seq_graph->setLineStyle(QCPGraph::lsNone);
seq_graph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, tango_scarlet_red_5, Qt::white, mainApp->font().pointSize())); // Arbitrary
seq_graph->setSelectable(QCP::stNone);
seq_graph->setData(audio_stream->jitterDroppedTimestamps(relative_timestamps), audio_stream->jitterDroppedSamples(y_offset));
ti->setData(graph_jitter_data_col_, Qt::UserRole, QVariant::fromValue<QCPGraph *>(seq_graph));
if (legend_jitter_dropped) {
seq_graph->removeFromLegend();
} else {
seq_graph->setName(tr("Jitter Drops"));
legend_jitter_dropped = true;
}
}
if (audio_stream->wrongTimestamps() > 0) {
// Wrong timestamps
QCPGraph *seq_graph = ui->audioPlot->addGraph();
seq_graph->setLineStyle(QCPGraph::lsNone);
seq_graph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDiamond, tango_sky_blue_5, Qt::white, mainApp->font().pointSize())); // Arbitrary
seq_graph->setSelectable(QCP::stNone);
seq_graph->setData(audio_stream->wrongTimestampTimestamps(relative_timestamps), audio_stream->wrongTimestampSamples(y_offset));
ti->setData(graph_timestamp_data_col_, Qt::UserRole, QVariant::fromValue<QCPGraph *>(seq_graph));
if (legend_wrong_timestamps) {
seq_graph->removeFromLegend();
} else {
seq_graph->setName(tr("Wrong Timestamps"));
legend_wrong_timestamps = true;
}
}
if (audio_stream->insertedSilences() > 0) {
// Inserted silence
QCPGraph *seq_graph = ui->audioPlot->addGraph();
seq_graph->setLineStyle(QCPGraph::lsNone);
seq_graph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssTriangle, tango_butter_5, Qt::white, mainApp->font().pointSize())); // Arbitrary
seq_graph->setSelectable(QCP::stNone);
seq_graph->setData(audio_stream->insertedSilenceTimestamps(relative_timestamps), audio_stream->insertedSilenceSamples(y_offset));
ti->setData(graph_silence_data_col_, Qt::UserRole, QVariant::fromValue<QCPGraph *>(seq_graph));
if (legend_inserted_silences) {
seq_graph->removeFromLegend();
} else {
seq_graph->setName(tr("Inserted Silence"));
legend_inserted_silences = true;
}
}
}
ui->audioPlot->legend->setVisible(legend_out_of_sequence || legend_jitter_dropped || legend_wrong_timestamps || legend_inserted_silences);
ui->audioPlot->replot();
if (rescale_axes) resetXAxis();
}
void RtpPlayerDialog::fillTappedColumns()
{
// true just for first stream
bool is_first = true;
// Get all rows, immutable list. Later changes in rows migth reorder them
QList<QTreeWidgetItem *> items = ui->streamTreeWidget->findItems(
QString("*"), Qt::MatchWrap | Qt::MatchWildcard | Qt::MatchRecursive);
// Update rows by calculated values, it might reorder them in view...
foreach(QTreeWidgetItem *ti, items) {
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
if (audio_stream) {
rtpstream_info_t *rtpstream = audio_stream->getStreamInfo();
// 0xFFFFFFFF mean no setup frame
// first_packet_num == setup_frame_number happens, when
// rtp_udp is active or Decode as was used
if ((rtpstream->setup_frame_number == 0xFFFFFFFF) ||
(rtpstream->rtp_stats.first_packet_num == rtpstream->setup_frame_number)
) {
int packet = rtpstream->rtp_stats.first_packet_num;
ti->setText(first_pkt_col_, QString("RTP %1").arg(packet));
ti->setData(first_pkt_col_, Qt::UserRole, QVariant(packet));
} else {
int packet = rtpstream->setup_frame_number;
ti->setText(first_pkt_col_, QString("SETUP %1").arg(rtpstream->setup_frame_number));
ti->setData(first_pkt_col_, Qt::UserRole, QVariant(packet));
}
ti->setText(num_pkts_col_, QString::number(rtpstream->packet_count));
updateStartStopTime(rtpstream, is_first);
is_first = false;
}
}
setMarkers();
}
void RtpPlayerDialog::addSingleRtpStream(rtpstream_id_t *id)
{
bool found = false;
AudioRouting audio_routing = AudioRouting(AUDIO_UNMUTED, channel_mono);
if (!id) return;
// Find the RTP streams associated with this conversation.
// gtk/rtp_player.c:mark_rtp_stream_to_play does this differently.
QList<RtpAudioStream *> streams = stream_hash_.values(rtpstream_id_to_hash(id));
for (int i = 0; i < streams.size(); i++) {
RtpAudioStream *row_stream = streams.at(i);
if (row_stream->isMatch(id)) {
found = true;
break;
}
}
if (found) {
return;
}
try {
int tli_count = ui->streamTreeWidget->topLevelItemCount();
RtpAudioStream *audio_stream = new RtpAudioStream(this, id, stereo_available_);
audio_stream->setColor(ColorUtils::graphColor(tli_count));
QTreeWidgetItem *ti = new RtpPlayerTreeWidgetItem(ui->streamTreeWidget);
stream_hash_.insert(rtpstream_id_to_hash(id), audio_stream);
ti->setText(src_addr_col_, address_to_qstring(&(id->src_addr)));
ti->setText(src_port_col_, QString::number(id->src_port));
ti->setText(dst_addr_col_, address_to_qstring(&(id->dst_addr)));
ti->setText(dst_port_col_, QString::number(id->dst_port));
ti->setText(ssrc_col_, int_to_qstring(id->ssrc, 8, 16));
// Calculated items are updated after every retapPackets()
ti->setData(stream_data_col_, Qt::UserRole, QVariant::fromValue(audio_stream));
if (stereo_available_) {
if (tli_count%2) {
audio_routing.setChannel(channel_stereo_right);
} else {
audio_routing.setChannel(channel_stereo_left);
}
} else {
audio_routing.setChannel(channel_mono);
}
ti->setToolTip(channel_col_, QString(tr("Double click on cell to change audio routing")));
formatAudioRouting(ti, audio_routing);
audio_stream->setAudioRouting(audio_routing);
for (int col = 0; col < ui->streamTreeWidget->columnCount(); col++) {
QBrush fgBrush = ti->foreground(col);
fgBrush.setColor(audio_stream->color());
fgBrush.setStyle(Qt::SolidPattern);
ti->setForeground(col, fgBrush);
}
connect(audio_stream, &RtpAudioStream::finishedPlaying, this, &RtpPlayerDialog::playFinished);
connect(audio_stream, &RtpAudioStream::playbackError, this, &RtpPlayerDialog::setPlaybackError);
} catch (...) {
qWarning() << "Stream ignored, try to add fewer streams to playlist";
}
RTP_STREAM_DEBUG("adding stream %d to layout",
ui->streamTreeWidget->topLevelItemCount());
}
void RtpPlayerDialog::lockUI()
{
if (0 == lock_ui_++) {
if (playing_streams_.count() > 0) {
on_stopButton_clicked();
}
setEnabled(false);
}
}
void RtpPlayerDialog::unlockUI()
{
if (--lock_ui_ == 0) {
setEnabled(true);
}
}
void RtpPlayerDialog::replaceRtpStreams(QVector<rtpstream_id_t *> stream_ids)
{
std::unique_lock<std::mutex> lock(run_mutex_, std::try_to_lock);
if (lock.owns_lock()) {
lockUI();
// Delete all existing rows
if (last_ti_) {
highlightItem(last_ti_, false);
last_ti_ = NULL;
}
for (int row = ui->streamTreeWidget->topLevelItemCount() - 1; row >= 0; row--) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
removeRow(ti);
}
// Add all new streams
for (int i=0; i < stream_ids.size(); i++) {
addSingleRtpStream(stream_ids[i]);
}
setMarkers();
unlockUI();
#ifdef QT_MULTIMEDIA_LIB
QTimer::singleShot(0, this, SLOT(retapPackets()));
#endif
} else {
ws_warning("replaceRtpStreams was called while other thread locked it. Current call is ignored, try it later.");
}
}
void RtpPlayerDialog::addRtpStreams(QVector<rtpstream_id_t *> stream_ids)
{
std::unique_lock<std::mutex> lock(run_mutex_, std::try_to_lock);
if (lock.owns_lock()) {
lockUI();
int tli_count = ui->streamTreeWidget->topLevelItemCount();
// Add new streams
for (int i=0; i < stream_ids.size(); i++) {
addSingleRtpStream(stream_ids[i]);
}
if (tli_count == 0) {
setMarkers();
}
unlockUI();
#ifdef QT_MULTIMEDIA_LIB
QTimer::singleShot(0, this, SLOT(retapPackets()));
#endif
} else {
ws_warning("addRtpStreams was called while other thread locked it. Current call is ignored, try it later.");
}
}
void RtpPlayerDialog::removeRtpStreams(QVector<rtpstream_id_t *> stream_ids)
{
std::unique_lock<std::mutex> lock(run_mutex_, std::try_to_lock);
if (lock.owns_lock()) {
lockUI();
int tli_count = ui->streamTreeWidget->topLevelItemCount();
for (int i=0; i < stream_ids.size(); i++) {
for (int row = 0; row < tli_count; row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioStream *row_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
if (row_stream->isMatch(stream_ids[i])) {
removeRow(ti);
tli_count--;
break;
}
}
}
updateGraphs();
updateWidgets();
unlockUI();
} else {
ws_warning("removeRtpStreams was called while other thread locked it. Current call is ignored, try it later.");
}
}
void RtpPlayerDialog::setMarkers()
{
setStartPlayMarker(0);
drawStartPlayMarker();
}
void RtpPlayerDialog::showEvent(QShowEvent *)
{
QList<int> split_sizes = ui->splitter->sizes();
int tot_size = split_sizes[0] + split_sizes[1];
int plot_size = tot_size * 3 / 4;
split_sizes.clear();
split_sizes << plot_size << tot_size - plot_size;
ui->splitter->setSizes(split_sizes);
}
bool RtpPlayerDialog::eventFilter(QObject *, QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent &keyEvent = static_cast<QKeyEvent&>(*event);
int pan_secs = keyEvent.modifiers() & Qt::ShiftModifier ? 1 : 10;
switch(keyEvent.key()) {
case Qt::Key_Minus:
case Qt::Key_Underscore: // Shifted minus on U.S. keyboards
case Qt::Key_O: // GTK+
case Qt::Key_R:
on_actionZoomOut_triggered();
return true;
case Qt::Key_Plus:
case Qt::Key_Equal: // Unshifted plus on U.S. keyboards
case Qt::Key_I: // GTK+
if (keyEvent.modifiers() == Qt::ControlModifier) {
// Ctrl+I
on_actionSelectInvert_triggered();
return true;
} else {
// I
on_actionZoomIn_triggered();
return true;
}
break;
case Qt::Key_Right:
case Qt::Key_L:
panXAxis(pan_secs);
return true;
case Qt::Key_Left:
case Qt::Key_H:
panXAxis(-1 * pan_secs);
return true;
case Qt::Key_0:
case Qt::Key_ParenRight: // Shifted 0 on U.S. keyboards
on_actionReset_triggered();
return true;
case Qt::Key_G:
if (keyEvent.modifiers() == Qt::ShiftModifier) {
// Goto SETUP frame, use correct call based on caller
QPoint pos1 = ui->audioPlot->mapFromGlobal(QCursor::pos());
QPoint pos2 = ui->streamTreeWidget->mapFromGlobal(QCursor::pos());
if (ui->audioPlot->rect().contains(pos1)) {
// audio plot, by mouse coords
on_actionGoToSetupPacketPlot_triggered();
} else if (ui->streamTreeWidget->rect().contains(pos2)) {
// packet tree, by cursor
on_actionGoToSetupPacketTree_triggered();
}
return true;
} else {
on_actionGoToPacket_triggered();
return true;
}
case Qt::Key_A:
if (keyEvent.modifiers() == Qt::ControlModifier) {
// Ctrl+A
on_actionSelectAll_triggered();
return true;
} else if (keyEvent.modifiers() == (Qt::ShiftModifier | Qt::ControlModifier)) {
// Ctrl+Shift+A
on_actionSelectNone_triggered();
return true;
}
break;
case Qt::Key_M:
if (keyEvent.modifiers() == Qt::ShiftModifier) {
on_actionAudioRoutingUnmute_triggered();
return true;
} else if (keyEvent.modifiers() == Qt::ControlModifier) {
on_actionAudioRoutingMuteInvert_triggered();
return true;
} else {
on_actionAudioRoutingMute_triggered();
return true;
}
case Qt::Key_Delete:
on_actionRemoveStream_triggered();
return true;
case Qt::Key_X:
if (keyEvent.modifiers() == Qt::ControlModifier) {
// Ctrl+X
on_actionRemoveStream_triggered();
return true;
}
break;
case Qt::Key_Down:
case Qt::Key_Up:
case Qt::Key_PageUp:
case Qt::Key_PageDown:
case Qt::Key_Home:
case Qt::Key_End:
// Route keys to QTreeWidget
ui->streamTreeWidget->setFocus();
break;
case Qt::Key_P:
if (keyEvent.modifiers() == Qt::NoModifier) {
on_actionPlay_triggered();
return true;
}
break;
case Qt::Key_S:
on_actionStop_triggered();
return true;
case Qt::Key_N:
if (keyEvent.modifiers() == Qt::ShiftModifier) {
// Shift+N
on_actionDeselectInaudible_triggered();
return true;
} else {
on_actionSelectInaudible_triggered();
return true;
}
break;
}
}
return false;
}
void RtpPlayerDialog::contextMenuEvent(QContextMenuEvent *event)
{
list_ctx_menu_->popup(event->globalPos());
}
void RtpPlayerDialog::updateWidgets()
{
bool enable_play = true;
bool enable_pause = false;
bool enable_stop = false;
bool enable_timing = true;
int count = ui->streamTreeWidget->topLevelItemCount();
qsizetype selected = ui->streamTreeWidget->selectedItems().count();
if (count < 1) {
enable_play = false;
ui->skipSilenceButton->setEnabled(false);
ui->minSilenceSpinBox->setEnabled(false);
} else {
ui->skipSilenceButton->setEnabled(true);
ui->minSilenceSpinBox->setEnabled(true);
}
for (int row = 0; row < ui->streamTreeWidget->topLevelItemCount(); row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
if (audio_stream->outputState() != QAudio::IdleState) {
enable_play = false;
enable_pause = true;
enable_stop = true;
enable_timing = false;
}
}
ui->actionAudioRoutingP->setVisible(!stereo_available_);
ui->actionAudioRoutingL->setVisible(stereo_available_);
ui->actionAudioRoutingLR->setVisible(stereo_available_);
ui->actionAudioRoutingR->setVisible(stereo_available_);
ui->playButton->setEnabled(enable_play);
if (enable_play) {
ui->playButton->setVisible(true);
ui->pauseButton->setVisible(false);
} else if (enable_pause) {
ui->playButton->setVisible(false);
ui->pauseButton->setVisible(true);
}
ui->outputDeviceComboBox->setEnabled(enable_play);
ui->outputAudioRate->setEnabled(enable_play);
ui->pauseButton->setEnabled(enable_pause);
ui->stopButton->setEnabled(enable_stop);
ui->actionStop->setEnabled(enable_stop);
cur_play_pos_->setVisible(enable_stop);
ui->jitterSpinBox->setEnabled(enable_timing);
ui->timingComboBox->setEnabled(enable_timing);
ui->todCheckBox->setEnabled(enable_timing);
read_btn_->setEnabled(read_capture_enabled_);
inaudible_btn_->setEnabled(count > 0);
analyze_btn_->setEnabled(selected > 0);
prepare_btn_->setEnabled(selected > 0);
updateHintLabel();
ui->audioPlot->replot();
}
void RtpPlayerDialog::handleItemHighlight(QTreeWidgetItem *ti, bool scroll)
{
if (ti) {
if (ti != last_ti_) {
if (last_ti_) {
highlightItem(last_ti_, false);
}
highlightItem(ti, true);
if (scroll)
ui->streamTreeWidget->scrollToItem(ti, QAbstractItemView::EnsureVisible);
ui->audioPlot->replot();
last_ti_ = ti;
}
} else {
if (last_ti_) {
highlightItem(last_ti_, false);
ui->audioPlot->replot();
last_ti_ = NULL;
}
}
}
void RtpPlayerDialog::highlightItem(QTreeWidgetItem *ti, bool highlight)
{
QFont font;
RtpAudioGraph *audio_graph;
font.setBold(highlight);
for(int i=0; i<ui->streamTreeWidget->columnCount(); i++) {
ti->setFont(i, font);
}
audio_graph = ti->data(graph_audio_data_col_, Qt::UserRole).value<RtpAudioGraph*>();
if (audio_graph) {
audio_graph->setHighlight(highlight);
}
}
void RtpPlayerDialog::itemEntered(QTreeWidgetItem *item, int column _U_)
{
handleItemHighlight(item, false);
}
void RtpPlayerDialog::mouseMovePlot(QMouseEvent *event)
{
updateHintLabel();
QTreeWidgetItem *ti = findItemByCoords(event->pos());
handleItemHighlight(ti, true);
}
void RtpPlayerDialog::graphClicked(QMouseEvent *event)
{
updateWidgets();
if (event->button() == Qt::RightButton) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
graph_ctx_menu_->popup(event->globalPosition().toPoint());
#else
graph_ctx_menu_->popup(event->globalPos());
#endif
}
}
void RtpPlayerDialog::graphDoubleClicked(QMouseEvent *event)
{
updateWidgets();
if (event->button() == Qt::LeftButton) {
// Move start play line
double ts = ui->audioPlot->xAxis->pixelToCoord(event->pos().x());
setStartPlayMarker(ts);
drawStartPlayMarker();
ui->audioPlot->replot();
}
}
void RtpPlayerDialog::plotClicked(QCPAbstractPlottable *plottable _U_, int dataIndex _U_, QMouseEvent *event)
{
// Delivered plottable very often points to different element than a mouse
// so we find right one by mouse coordinates
QTreeWidgetItem *ti = findItemByCoords(event->pos());
if (ti) {
if (event->modifiers() == Qt::NoModifier) {
ti->setSelected(true);
} else if (event->modifiers() == Qt::ControlModifier) {
ti->setSelected(!ti->isSelected());
}
}
}
QTreeWidgetItem *RtpPlayerDialog::findItemByCoords(QPoint point)
{
QCPAbstractPlottable *plottable=ui->audioPlot->plottableAt(point);
if (plottable) {
return findItem(plottable);
}
return NULL;
}
QTreeWidgetItem *RtpPlayerDialog::findItem(QCPAbstractPlottable *plottable)
{
for (int row = 0; row < ui->streamTreeWidget->topLevelItemCount(); row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioGraph *audio_graph = ti->data(graph_audio_data_col_, Qt::UserRole).value<RtpAudioGraph*>();
if (audio_graph && audio_graph->isMyPlottable(plottable)) {
return ti;
}
}
return NULL;
}
void RtpPlayerDialog::updateHintLabel()
{
int packet_num = getHoveredPacket();
QString hint = "<small><i>";
double start_pos = getStartPlayMarker();
int row_count = ui->streamTreeWidget->topLevelItemCount();
qsizetype selected = ui->streamTreeWidget->selectedItems().count();
int not_muted = 0;
hint += tr("%1 streams").arg(row_count);
if (row_count > 0) {
if (selected > 0) {
hint += tr(", %1 selected").arg(selected);
}
for (int row = 0; row < row_count; row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
if (audio_stream && (!audio_stream->getAudioRouting().isMuted())) {
not_muted++;
}
}
hint += tr(", %1 not muted").arg(not_muted);
}
if (packet_num == 0) {
hint += tr(", start: %1. Double click on graph to set start of playback.")
.arg(getFormatedTime(start_pos));
} else if (packet_num > 0) {
hint += tr(", start: %1, cursor: %2. Press \"G\" to go to packet %3. Double click on graph to set start of playback.")
.arg(getFormatedTime(start_pos))
.arg(getFormatedHoveredTime())
.arg(packet_num);
}
if (!playback_error_.isEmpty()) {
hint += " <font color=\"red\">";
hint += playback_error_;
hint += " </font>";
}
hint += "</i></small>";
ui->hintLabel->setText(hint);
}
void RtpPlayerDialog::resetXAxis()
{
QCustomPlot *ap = ui->audioPlot;
double pixel_pad = 10.0; // per side
ap->rescaleAxes(true);
double axis_pixels = ap->xAxis->axisRect()->width();
ap->xAxis->scaleRange((axis_pixels + (pixel_pad * 2)) / axis_pixels, ap->xAxis->range().center());
axis_pixels = ap->yAxis->axisRect()->height();
ap->yAxis->scaleRange((axis_pixels + (pixel_pad * 2)) / axis_pixels, ap->yAxis->range().center());
ap->replot();
}
void RtpPlayerDialog::updateGraphs()
{
QCustomPlot *ap = ui->audioPlot;
// Create new plots, just existing ones
createPlot(false);
// Rescale Y axis
double pixel_pad = 10.0; // per side
double axis_pixels = ap->yAxis->axisRect()->height();
ap->yAxis->rescale(true);
ap->yAxis->scaleRange((axis_pixels + (pixel_pad * 2)) / axis_pixels, ap->yAxis->range().center());
ap->replot();
}
void RtpPlayerDialog::playFinished(RtpAudioStream *stream, QAudio::Error error)
{
if ((error != QAudio::NoError) && (error != QAudio::UnderrunError)) {
setPlaybackError(tr("Playback of stream %1 failed!")
.arg(stream->getIDAsQString())
);
}
playing_streams_.removeOne(stream);
if (playing_streams_.isEmpty()) {
marker_stream_->stop();
updateWidgets();
}
}
void RtpPlayerDialog::setPlayPosition(double secs)
{
double cur_secs = cur_play_pos_->point1->key();
if (ui->todCheckBox->isChecked()) {
secs += first_stream_abs_start_time_;
} else {
secs += first_stream_rel_start_time_;
}
if (secs > cur_secs) {
cur_play_pos_->point1->setCoords(secs, 0.0);
cur_play_pos_->point2->setCoords(secs, 1.0);
ui->audioPlot->replot();
}
}
void RtpPlayerDialog::setPlaybackError(const QString playback_error)
{
playback_error_ = playback_error;
updateHintLabel();
}
tap_packet_status RtpPlayerDialog::tapPacket(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *, const void *rtpinfo_ptr, tap_flags_t)
{
RtpPlayerDialog *rtp_player_dialog = dynamic_cast<RtpPlayerDialog *>((RtpPlayerDialog*)tapinfo_ptr);
if (!rtp_player_dialog) return TAP_PACKET_DONT_REDRAW;
const struct _rtp_info *rtpinfo = (const struct _rtp_info *)rtpinfo_ptr;
if (!rtpinfo) return TAP_PACKET_DONT_REDRAW;
/* ignore RTP Version != 2 */
if (rtpinfo->info_version != 2)
return TAP_PACKET_DONT_REDRAW;
rtp_player_dialog->addPacket(pinfo, rtpinfo);
return TAP_PACKET_DONT_REDRAW;
}
void RtpPlayerDialog::addPacket(packet_info *pinfo, const _rtp_info *rtpinfo)
{
// Search stream in hash key, if there are multiple streams with same hash
QList<RtpAudioStream *> streams = stream_hash_.values(pinfo_rtp_info_to_hash(pinfo, rtpinfo));
for (int i = 0; i < streams.size(); i++) {
RtpAudioStream *row_stream = streams.at(i);
if (row_stream->isMatch(pinfo, rtpinfo)) {
row_stream->addRtpPacket(pinfo, rtpinfo);
break;
}
}
// qDebug() << "=ap no match!" << address_to_qstring(&pinfo->src) << address_to_qstring(&pinfo->dst);
}
void RtpPlayerDialog::zoomXAxis(bool in)
{
QCustomPlot *ap = ui->audioPlot;
double h_factor = ap->axisRect()->rangeZoomFactor(Qt::Horizontal);
if (!in) {
h_factor = pow(h_factor, -1);
}
ap->xAxis->scaleRange(h_factor, ap->xAxis->range().center());
ap->replot();
}
// XXX I tried using seconds but pixels make more sense at varying zoom
// levels.
void RtpPlayerDialog::panXAxis(int x_pixels)
{
QCustomPlot *ap = ui->audioPlot;
double h_pan;
h_pan = ap->xAxis->range().size() * x_pixels / ap->xAxis->axisRect()->width();
if (x_pixels) {
ap->xAxis->moveRange(h_pan);
ap->replot();
}
}
void RtpPlayerDialog::on_playButton_clicked()
{
double start_time;
QList<RtpAudioStream *> streams_to_start;
ui->hintLabel->setText("<i><small>" + tr("Preparing to play...") + "</i></small>");
mainApp->processEvents();
ui->pauseButton->setChecked(false);
// Protect start time against move of marker during the play
start_marker_time_play_ = start_marker_time_;
silence_skipped_time_ = 0.0;
cur_play_pos_->point1->setCoords(start_marker_time_play_, 0.0);
cur_play_pos_->point2->setCoords(start_marker_time_play_, 1.0);
cur_play_pos_->setVisible(true);
playback_error_.clear();
if (ui->todCheckBox->isChecked()) {
start_time = start_marker_time_play_;
} else {
start_time = start_marker_time_play_ - first_stream_rel_start_time_;
}
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
QAudioDevice cur_out_device = getCurrentDeviceInfo();
#else
QAudioDeviceInfo cur_out_device = getCurrentDeviceInfo();
#endif
playing_streams_.clear();
int row_count = ui->streamTreeWidget->topLevelItemCount();
for (int row = 0; row < row_count; row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
// All streams starts at first_stream_rel_start_time_
audio_stream->setStartPlayTime(start_time);
if (audio_stream->prepareForPlay(cur_out_device)) {
playing_streams_ << audio_stream;
}
}
// Prepare silent stream for progress marker
if (!marker_stream_) {
marker_stream_ = getSilenceAudioOutput();
} else {
marker_stream_->stop();
}
// Start progress marker and then audio streams
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
notify_timer_start_diff_ = -1;
#endif
marker_stream_->start(new AudioSilenceGenerator(marker_stream_));
// It may happen that stream play is finished before all others are started
// therefore we do not use playing_streams_ there, but separate temporarly
// list. It avoids access element/remove element race condition.
streams_to_start = playing_streams_;
for( int i = 0; i<streams_to_start.count(); ++i ) {
streams_to_start[i]->startPlaying();
}
updateWidgets();
}
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
QAudioDevice RtpPlayerDialog::getCurrentDeviceInfo()
{
QAudioDevice cur_out_device = QMediaDevices::defaultAudioOutput();
QString cur_out_name = currentOutputDeviceName();
foreach (QAudioDevice out_device, QMediaDevices::audioOutputs()) {
if (cur_out_name == out_device.description()) {
cur_out_device = out_device;
}
}
return cur_out_device;
}
void RtpPlayerDialog::sinkStateChanged()
{
if (marker_stream_->state() == QAudio::ActiveState) {
notify_timer_.start();
} else {
notify_timer_.stop();
}
}
#else
QAudioDeviceInfo RtpPlayerDialog::getCurrentDeviceInfo()
{
QAudioDeviceInfo cur_out_device = QAudioDeviceInfo::defaultOutputDevice();
QString cur_out_name = currentOutputDeviceName();
foreach (QAudioDeviceInfo out_device, QAudioDeviceInfo::availableDevices(QAudio::AudioOutput)) {
if (cur_out_name == out_device.deviceName()) {
cur_out_device = out_device;
}
}
return cur_out_device;
}
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
QAudioSink *RtpPlayerDialog::getSilenceAudioOutput()
{
QAudioDevice cur_out_device = getCurrentDeviceInfo();
QAudioFormat format;
if (marker_stream_requested_out_rate_ > 0) {
format.setSampleRate(marker_stream_requested_out_rate_);
} else {
format.setSampleRate(8000);
}
// Must match rtp_media.h.
format.setSampleFormat(QAudioFormat::Int16);
format.setChannelCount(1);
if (!cur_out_device.isFormatSupported(format)) {
format = cur_out_device.preferredFormat();
}
QAudioSink *sink = new QAudioSink(cur_out_device, format, this);
connect(sink, &QAudioSink::stateChanged, this, &RtpPlayerDialog::sinkStateChanged);
return sink;
}
#else
QAudioOutput *RtpPlayerDialog::getSilenceAudioOutput()
{
QAudioOutput *o;
QAudioDeviceInfo cur_out_device = getCurrentDeviceInfo();
QAudioFormat format;
if (marker_stream_requested_out_rate_ > 0) {
format.setSampleRate(marker_stream_requested_out_rate_);
} else {
format.setSampleRate(8000);
}
format.setSampleSize(SAMPLE_BYTES * 8); // bits
format.setSampleType(QAudioFormat::SignedInt);
format.setChannelCount(1);
format.setCodec("audio/pcm");
if (!cur_out_device.isFormatSupported(format)) {
format = cur_out_device.nearestFormat(format);
}
o = new QAudioOutput(cur_out_device, format, this);
o->setNotifyInterval(100); // ~15 fps
connect(o, &QAudioOutput::notify, this, &RtpPlayerDialog::outputNotify);
return o;
}
#endif
void RtpPlayerDialog::outputNotify()
{
double new_current_pos = 0.0;
double current_pos = 0.0;
qint64 usecs = marker_stream_->processedUSecs();
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
// First notify can show end of buffer, not play point so we have
// remember the shift
if ( -1 == notify_timer_start_diff_ || 0 == notify_timer_start_diff_) {
notify_timer_start_diff_ = usecs;
}
usecs -= notify_timer_start_diff_;
#endif
double secs = usecs / 1000000.0;
if (ui->skipSilenceButton->isChecked()) {
// We should check whether we can skip some silence
// We must calculate in time domain as every stream can use different
// play rate
double min_silence = playing_streams_[0]->getEndOfSilenceTime();
for( int i = 1; i<playing_streams_.count(); ++i ) {
qint64 cur_silence = playing_streams_[i]->getEndOfSilenceTime();
if (cur_silence < min_silence) {
min_silence = cur_silence;
}
}
if (min_silence > 0.0) {
double silence_duration;
// Calculate silence duration we can skip
new_current_pos = first_stream_rel_start_time_ + min_silence;
if (ui->todCheckBox->isChecked()) {
current_pos = secs + start_marker_time_play_ + first_stream_rel_start_time_;
} else {
current_pos = secs + start_marker_time_play_;
}
silence_duration = new_current_pos - current_pos;
if (silence_duration >= ui->minSilenceSpinBox->value()) {
// Skip silence gap and update cursor difference
for( int i = 0; i<playing_streams_.count(); ++i ) {
// Convert silence from time domain to samples
qint64 skip_samples = playing_streams_[i]->convertTimeToSamples(min_silence);
playing_streams_[i]->seekPlaying(skip_samples);
}
silence_skipped_time_ = silence_duration;
}
}
}
// Calculate new cursor position
if (ui->todCheckBox->isChecked()) {
secs += start_marker_time_play_;
secs += silence_skipped_time_;
} else {
secs += start_marker_time_play_;
secs -= first_stream_rel_start_time_;
secs += silence_skipped_time_;
}
setPlayPosition(secs);
}
void RtpPlayerDialog::on_pauseButton_clicked()
{
for( int i = 0; i<playing_streams_.count(); ++i ) {
playing_streams_[i]->pausePlaying();
}
if (ui->pauseButton->isChecked()) {
marker_stream_->suspend();
} else {
marker_stream_->resume();
}
updateWidgets();
}
void RtpPlayerDialog::on_stopButton_clicked()
{
// We need copy of list because items will be removed during stopPlaying()
QList<RtpAudioStream *> ps=QList<RtpAudioStream *>(playing_streams_);
for( int i = 0; i<ps.count(); ++i ) {
ps[i]->stopPlaying();
}
marker_stream_->stop();
cur_play_pos_->setVisible(false);
updateWidgets();
}
void RtpPlayerDialog::on_actionReset_triggered()
{
resetXAxis();
}
void RtpPlayerDialog::on_actionZoomIn_triggered()
{
zoomXAxis(true);
}
void RtpPlayerDialog::on_actionZoomOut_triggered()
{
zoomXAxis(false);
}
void RtpPlayerDialog::on_actionMoveLeft10_triggered()
{
panXAxis(-10);
}
void RtpPlayerDialog::on_actionMoveRight10_triggered()
{
panXAxis(10);
}
void RtpPlayerDialog::on_actionMoveLeft1_triggered()
{
panXAxis(-1);
}
void RtpPlayerDialog::on_actionMoveRight1_triggered()
{
panXAxis(1);
}
void RtpPlayerDialog::on_actionGoToPacket_triggered()
{
int packet_num = getHoveredPacket();
if (packet_num > 0) emit goToPacket(packet_num);
}
void RtpPlayerDialog::handleGoToSetupPacket(QTreeWidgetItem *ti)
{
if (ti) {
bool ok;
int packet_num = ti->data(first_pkt_col_, Qt::UserRole).toInt(&ok);
if (ok) {
emit goToPacket(packet_num);
}
}
}
void RtpPlayerDialog::on_actionGoToSetupPacketPlot_triggered()
{
QPoint pos = ui->audioPlot->mapFromGlobal(QCursor::pos());
handleGoToSetupPacket(findItemByCoords(pos));
}
void RtpPlayerDialog::on_actionGoToSetupPacketTree_triggered()
{
handleGoToSetupPacket(last_ti_);
}
// Make waveform graphs selectable and update the treewidget selection accordingly.
void RtpPlayerDialog::on_streamTreeWidget_itemSelectionChanged()
{
for (int row = 0; row < ui->streamTreeWidget->topLevelItemCount(); row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioGraph *audio_graph = ti->data(graph_audio_data_col_, Qt::UserRole).value<RtpAudioGraph*>();
if (audio_graph) {
audio_graph->setSelected(ti->isSelected());
}
}
qsizetype selected = ui->streamTreeWidget->selectedItems().count();
if (selected == 0) {
analyze_btn_->setEnabled(false);
prepare_btn_->setEnabled(false);
export_btn_->setEnabled(false);
} else if (selected == 1) {
analyze_btn_->setEnabled(true);
prepare_btn_->setEnabled(true);
export_btn_->setEnabled(true);
ui->actionSavePayload->setEnabled(true);
} else {
analyze_btn_->setEnabled(true);
prepare_btn_->setEnabled(true);
export_btn_->setEnabled(true);
ui->actionSavePayload->setEnabled(false);
}
if (!block_redraw_) {
ui->audioPlot->replot();
updateHintLabel();
}
}
// Change channel audio routing if double clicked channel column
void RtpPlayerDialog::on_streamTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, const int column)
{
if (column == channel_col_) {
RtpAudioStream *audio_stream = item->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
if (!audio_stream)
return;
AudioRouting audio_routing = audio_stream->getAudioRouting();
audio_routing = audio_routing.getNextChannel(stereo_available_);
changeAudioRoutingOnItem(item, audio_routing);
}
updateHintLabel();
}
void RtpPlayerDialog::removeRow(QTreeWidgetItem *ti)
{
if (last_ti_ && (last_ti_ == ti)) {
highlightItem(last_ti_, false);
last_ti_ = NULL;
}
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
if (audio_stream) {
stream_hash_.remove(audio_stream->getHash(), audio_stream);
ti->setData(stream_data_col_, Qt::UserRole, QVariant());
delete audio_stream;
}
RtpAudioGraph *audio_graph = ti->data(graph_audio_data_col_, Qt::UserRole).value<RtpAudioGraph*>();
if (audio_graph) {
ti->setData(graph_audio_data_col_, Qt::UserRole, QVariant());
audio_graph->remove(ui->audioPlot);
}
QCPGraph *graph;
graph = ti->data(graph_sequence_data_col_, Qt::UserRole).value<QCPGraph*>();
if (graph) {
ti->setData(graph_sequence_data_col_, Qt::UserRole, QVariant());
ui->audioPlot->removeGraph(graph);
}
graph = ti->data(graph_jitter_data_col_, Qt::UserRole).value<QCPGraph*>();
if (graph) {
ti->setData(graph_jitter_data_col_, Qt::UserRole, QVariant());
ui->audioPlot->removeGraph(graph);
}
graph = ti->data(graph_timestamp_data_col_, Qt::UserRole).value<QCPGraph*>();
if (graph) {
ti->setData(graph_timestamp_data_col_, Qt::UserRole, QVariant());
ui->audioPlot->removeGraph(graph);
}
graph = ti->data(graph_silence_data_col_, Qt::UserRole).value<QCPGraph*>();
if (graph) {
ti->setData(graph_silence_data_col_, Qt::UserRole, QVariant());
ui->audioPlot->removeGraph(graph);
}
delete ti;
}
void RtpPlayerDialog::on_actionRemoveStream_triggered()
{
lockUI();
QList<QTreeWidgetItem *> items = ui->streamTreeWidget->selectedItems();
block_redraw_ = true;
for(int i = static_cast<int>(items.count()) - 1; i>=0; i-- ) {
removeRow(items[i]);
}
block_redraw_ = false;
// TODO: Recalculate legend
// - Graphs used for legend could be removed above and we must add new
// - If no legend is required, it should be removed
// Redraw existing waveforms and rescale Y axis
updateGraphs();
updateWidgets();
unlockUI();
}
// If called with channel_any, just muted flag should be changed
void RtpPlayerDialog::changeAudioRoutingOnItem(QTreeWidgetItem *ti, AudioRouting new_audio_routing)
{
if (!ti)
return;
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
if (!audio_stream)
return;
AudioRouting audio_routing = audio_stream->getAudioRouting();
audio_routing.mergeAudioRouting(new_audio_routing);
formatAudioRouting(ti, audio_routing);
audio_stream->setAudioRouting(audio_routing);
RtpAudioGraph *audio_graph = ti->data(graph_audio_data_col_, Qt::UserRole).value<RtpAudioGraph*>();
if (audio_graph) {
audio_graph->setSelected(ti->isSelected());
audio_graph->setMuted(audio_routing.isMuted());
if (!block_redraw_) {
ui->audioPlot->replot();
}
}
}
// Find current item and apply change on it
void RtpPlayerDialog::changeAudioRouting(AudioRouting new_audio_routing)
{
lockUI();
QList<QTreeWidgetItem *> items = ui->streamTreeWidget->selectedItems();
block_redraw_ = true;
for(int i = 0; i<items.count(); i++ ) {
QTreeWidgetItem *ti = items[i];
changeAudioRoutingOnItem(ti, new_audio_routing);
}
block_redraw_ = false;
ui->audioPlot->replot();
updateHintLabel();
unlockUI();
}
// Invert mute/unmute on item
void RtpPlayerDialog::invertAudioMutingOnItem(QTreeWidgetItem *ti)
{
if (!ti)
return;
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
if (!audio_stream)
return;
AudioRouting audio_routing = audio_stream->getAudioRouting();
// Invert muting
if (audio_routing.isMuted()) {
changeAudioRoutingOnItem(ti, AudioRouting(AUDIO_UNMUTED, channel_any));
} else {
changeAudioRoutingOnItem(ti, AudioRouting(AUDIO_MUTED, channel_any));
}
}
void RtpPlayerDialog::on_actionAudioRoutingP_triggered()
{
changeAudioRouting(AudioRouting(AUDIO_UNMUTED, channel_mono));
}
void RtpPlayerDialog::on_actionAudioRoutingL_triggered()
{
changeAudioRouting(AudioRouting(AUDIO_UNMUTED, channel_stereo_left));
}
void RtpPlayerDialog::on_actionAudioRoutingLR_triggered()
{
changeAudioRouting(AudioRouting(AUDIO_UNMUTED, channel_stereo_both));
}
void RtpPlayerDialog::on_actionAudioRoutingR_triggered()
{
changeAudioRouting(AudioRouting(AUDIO_UNMUTED, channel_stereo_right));
}
void RtpPlayerDialog::on_actionAudioRoutingMute_triggered()
{
changeAudioRouting(AudioRouting(AUDIO_MUTED, channel_any));
}
void RtpPlayerDialog::on_actionAudioRoutingUnmute_triggered()
{
changeAudioRouting(AudioRouting(AUDIO_UNMUTED, channel_any));
}
void RtpPlayerDialog::on_actionAudioRoutingMuteInvert_triggered()
{
lockUI();
QList<QTreeWidgetItem *> items = ui->streamTreeWidget->selectedItems();
block_redraw_ = true;
for(int i = 0; i<items.count(); i++ ) {
QTreeWidgetItem *ti = items[i];
invertAudioMutingOnItem(ti);
}
block_redraw_ = false;
ui->audioPlot->replot();
updateHintLabel();
unlockUI();
}
const QString RtpPlayerDialog::getFormatedTime(double f_time)
{
QString time_str;
if (ui->todCheckBox->isChecked()) {
QDateTime date_time = QDateTime::fromMSecsSinceEpoch(f_time * 1000.0);
time_str = date_time.toString("yyyy-MM-dd hh:mm:ss.zzz");
} else {
time_str = QString::number(f_time, 'f', 6);
time_str += " s";
}
return time_str;
}
const QString RtpPlayerDialog::getFormatedHoveredTime()
{
QPoint pos = ui->audioPlot->mapFromGlobal(QCursor::pos());
QTreeWidgetItem *ti = findItemByCoords(pos);
if (!ti) return tr("Unknown");
double ts = ui->audioPlot->xAxis->pixelToCoord(pos.x());
return getFormatedTime(ts);
}
int RtpPlayerDialog::getHoveredPacket()
{
QPoint pos = ui->audioPlot->mapFromGlobal(QCursor::pos());
QTreeWidgetItem *ti = findItemByCoords(pos);
if (!ti) return 0;
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
double ts = ui->audioPlot->xAxis->pixelToCoord(pos.x());
return audio_stream->nearestPacket(ts, !ui->todCheckBox->isChecked());
}
// Used by RtpAudioStreams to initialize QAudioOutput. We could alternatively
// pass the corresponding QAudioDeviceInfo directly.
QString RtpPlayerDialog::currentOutputDeviceName()
{
return ui->outputDeviceComboBox->currentText();
}
void RtpPlayerDialog::fillAudioRateMenu()
{
ui->outputAudioRate->blockSignals(true);
ui->outputAudioRate->clear();
ui->outputAudioRate->addItem(tr("Automatic"));
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
// XXX QAudioDevice doesn't provide supportedSampleRates(). Fake it with
// what's available.
QAudioDevice cur_out_device = getCurrentDeviceInfo();
QSet<int>sample_rates;
if (!cur_out_device.isNull()) {
sample_rates.insert(cur_out_device.preferredFormat().sampleRate());
// Add 8000 if supported
if ((cur_out_device.minimumSampleRate() <= 8000) &&
(8000 <= cur_out_device.maximumSampleRate())
) {
sample_rates.insert(8000);
}
// Add 16000 if supported
if ((cur_out_device.minimumSampleRate() <= 16000) &&
(16000 <= cur_out_device.maximumSampleRate())
) {
sample_rates.insert(16000);
}
// Add 44100 if supported
if ((cur_out_device.minimumSampleRate() <= 44100) &&
(44100 <= cur_out_device.maximumSampleRate())
) {
sample_rates.insert(44100);
}
}
// Sort values
QList<int> sorter = sample_rates.values();
std::sort(sorter.begin(), sorter.end());
// Insert rates to the list
for (auto rate : sorter) {
ui->outputAudioRate->addItem(QString::number(rate));
}
#else
QAudioDeviceInfo cur_out_device = getCurrentDeviceInfo();
if (!cur_out_device.isNull()) {
foreach (int rate, cur_out_device.supportedSampleRates()) {
ui->outputAudioRate->addItem(QString::number(rate));
}
}
#endif
ui->outputAudioRate->blockSignals(false);
}
void RtpPlayerDialog::cleanupMarkerStream()
{
if (marker_stream_) {
marker_stream_->stop();
delete marker_stream_;
marker_stream_ = NULL;
}
}
void RtpPlayerDialog::on_outputDeviceComboBox_currentTextChanged(const QString &)
{
lockUI();
stereo_available_ = isStereoAvailable();
for (int row = 0; row < ui->streamTreeWidget->topLevelItemCount(); row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
if (!audio_stream)
continue;
changeAudioRoutingOnItem(ti, audio_stream->getAudioRouting().convert(stereo_available_));
}
marker_stream_requested_out_rate_ = 0;
cleanupMarkerStream();
fillAudioRateMenu();
rescanPackets();
unlockUI();
}
void RtpPlayerDialog::on_outputAudioRate_currentTextChanged(const QString & rate_string)
{
lockUI();
// Any unconvertable string is converted to 0 => used as Automatic rate
unsigned selected_rate = rate_string.toInt();
for (int row = 0; row < ui->streamTreeWidget->topLevelItemCount(); row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
if (!audio_stream)
continue;
audio_stream->setRequestedPlayRate(selected_rate);
}
marker_stream_requested_out_rate_ = selected_rate;
cleanupMarkerStream();
rescanPackets();
unlockUI();
}
void RtpPlayerDialog::on_jitterSpinBox_valueChanged(double)
{
rescanPackets();
}
void RtpPlayerDialog::on_timingComboBox_currentIndexChanged(int)
{
rescanPackets();
}
void RtpPlayerDialog::on_todCheckBox_toggled(bool)
{
QCPAxis *x_axis = ui->audioPlot->xAxis;
double move;
// Create plot with new tod settings
createPlot();
// Move view to same place as was shown before the change
if (ui->todCheckBox->isChecked()) {
// rel -> abs
// based on abs time of first sample
setStartPlayMarker(first_stream_abs_start_time_ + start_marker_time_ - first_stream_rel_start_time_);
move = first_stream_abs_start_time_ - first_stream_rel_start_time_;
} else {
// abs -> rel
// based on 0s
setStartPlayMarker(first_stream_rel_start_time_ + start_marker_time_);
move = - first_stream_abs_start_time_ + first_stream_rel_start_time_;
}
x_axis->moveRange(move);
drawStartPlayMarker();
ui->audioPlot->replot();
}
void RtpPlayerDialog::on_buttonBox_helpRequested()
{
mainApp->helpTopicAction(HELP_TELEPHONY_RTP_PLAYER_DIALOG);
}
double RtpPlayerDialog::getStartPlayMarker()
{
double start_pos;
if (ui->todCheckBox->isChecked()) {
start_pos = start_marker_time_ + first_stream_abs_start_time_;
} else {
start_pos = start_marker_time_;
}
return start_pos;
}
void RtpPlayerDialog::drawStartPlayMarker()
{
double pos = getStartPlayMarker();
start_marker_pos_->point1->setCoords(pos, 0.0);
start_marker_pos_->point2->setCoords(pos, 1.0);
updateHintLabel();
}
void RtpPlayerDialog::setStartPlayMarker(double new_time)
{
if (ui->todCheckBox->isChecked()) {
new_time = qBound(first_stream_abs_start_time_, new_time, first_stream_abs_start_time_ + streams_length_);
// start_play_time is relative, we must calculate it
start_marker_time_ = new_time - first_stream_abs_start_time_;
} else {
new_time = qBound(first_stream_rel_start_time_, new_time, first_stream_rel_start_time_ + streams_length_);
start_marker_time_ = new_time;
}
}
void RtpPlayerDialog::updateStartStopTime(rtpstream_info_t *rtpstream, bool is_first)
{
// Calculate start time of first last packet of last stream
double stream_rel_start_time = nstime_to_sec(&rtpstream->start_rel_time);
double stream_abs_start_time = nstime_to_sec(&rtpstream->start_abs_time);
double stream_rel_stop_time = nstime_to_sec(&rtpstream->stop_rel_time);
if (is_first) {
// Take start/stop time for first stream
first_stream_rel_start_time_ = stream_rel_start_time;
first_stream_abs_start_time_ = stream_abs_start_time;
first_stream_rel_stop_time_ = stream_rel_stop_time;
} else {
// Calculate min/max for start/stop time for other streams
first_stream_rel_start_time_ = qMin(first_stream_rel_start_time_, stream_rel_start_time);
first_stream_abs_start_time_ = qMin(first_stream_abs_start_time_, stream_abs_start_time);
first_stream_rel_stop_time_ = qMax(first_stream_rel_stop_time_, stream_rel_stop_time);
}
streams_length_ = first_stream_rel_stop_time_ - first_stream_rel_start_time_;
}
void RtpPlayerDialog::formatAudioRouting(QTreeWidgetItem *ti, AudioRouting audio_routing)
{
ti->setText(channel_col_, tr(audio_routing.formatAudioRoutingToString()));
}
bool RtpPlayerDialog::isStereoAvailable()
{
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
QAudioDevice cur_out_device = getCurrentDeviceInfo();
if (cur_out_device.maximumChannelCount() > 1) {
return true;
}
#else
QAudioDeviceInfo cur_out_device = getCurrentDeviceInfo();
foreach(int count, cur_out_device.supportedChannelCounts()) {
if (count > 1) {
return true;
}
}
#endif
return false;
}
void RtpPlayerDialog::invertSelection()
{
block_redraw_ = true;
ui->streamTreeWidget->blockSignals(true);
for (int row = 0; row < ui->streamTreeWidget->topLevelItemCount(); row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
ti->setSelected(!ti->isSelected());
}
ui->streamTreeWidget->blockSignals(false);
block_redraw_ = false;
ui->audioPlot->replot();
updateHintLabel();
}
void RtpPlayerDialog::on_actionSelectAll_triggered()
{
ui->streamTreeWidget->selectAll();
updateHintLabel();
}
void RtpPlayerDialog::on_actionSelectInvert_triggered()
{
invertSelection();
updateHintLabel();
}
void RtpPlayerDialog::on_actionSelectNone_triggered()
{
ui->streamTreeWidget->clearSelection();
updateHintLabel();
}
void RtpPlayerDialog::on_actionPlay_triggered()
{
if (ui->playButton->isEnabled()) {
ui->playButton->animateClick();
} else if (ui->pauseButton->isEnabled()) {
ui->pauseButton->animateClick();
}
}
void RtpPlayerDialog::on_actionStop_triggered()
{
if (ui->stopButton->isEnabled()) {
ui->stopButton->animateClick();
}
}
qint64 RtpPlayerDialog::saveAudioHeaderAU(QFile *save_file, quint32 channels, unsigned audio_rate)
{
uint8_t pd[4];
int64_t nchars;
/* https://pubs.opengroup.org/external/auformat.html */
/* First we write the .au header. All values in the header are
* 4-byte big-endian values, so we use pntoh32() to copy them
* to a 4-byte buffer, in big-endian order, and then write out
* the buffer. */
/* the magic word 0x2e736e64 == .snd */
phton32(pd, 0x2e736e64);
nchars = save_file->write((const char *)pd, 4);
if (nchars != 4) {
return -1;
}
/* header offset == 24 bytes */
phton32(pd, 24);
nchars = save_file->write((const char *)pd, 4);
if (nchars != 4) {
return -1;
}
/* total length; it is permitted to set this to 0xffffffff */
phton32(pd, 0xffffffff);
nchars = save_file->write((const char *)pd, 4);
if (nchars != 4) {
return -1;
}
/* encoding format == 16-bit linear PCM */
phton32(pd, 3);
nchars = save_file->write((const char *)pd, 4);
if (nchars != 4) {
return -1;
}
/* sample rate [Hz] */
phton32(pd, audio_rate);
nchars = save_file->write((const char *)pd, 4);
if (nchars != 4) {
return -1;
}
/* channels */
phton32(pd, channels);
nchars = save_file->write((const char *)pd, 4);
if (nchars != 4) {
return -1;
}
return save_file->pos();
}
qint64 RtpPlayerDialog::saveAudioHeaderWAV(QFile *save_file, quint32 channels, unsigned audio_rate, qint64 samples)
{
uint8_t pd[4];
int64_t nchars;
gint32 subchunk2Size;
gint32 data32;
gint16 data16;
subchunk2Size = sizeof(SAMPLE) * channels * (gint32)samples;
/* http://soundfile.sapp.org/doc/WaveFormat/ */
/* RIFF header, ChunkID 0x52494646 == RIFF */
phton32(pd, 0x52494646);
nchars = save_file->write((const char *)pd, 4);
if (nchars != 4) {
return -1;
}
/* RIFF header, ChunkSize */
data32 = 36 + subchunk2Size;
nchars = save_file->write((const char *)&data32, 4);
if (nchars != 4) {
return -1;
}
/* RIFF header, Format 0x57415645 == WAVE */
phton32(pd, 0x57415645);
nchars = save_file->write((const char *)pd, 4);
if (nchars != 4) {
return -1;
}
/* WAVE fmt header, Subchunk1ID 0x666d7420 == 'fmt ' */
phton32(pd, 0x666d7420);
nchars = save_file->write((const char *)pd, 4);
if (nchars != 4) {
return -1;
}
/* WAVE fmt header, Subchunk1Size */
data32 = 16;
nchars = save_file->write((const char *)&data32, 4);
if (nchars != 4) {
return -1;
}
/* WAVE fmt header, AudioFormat 1 == PCM */
data16 = 1;
nchars = save_file->write((const char *)&data16, 2);
if (nchars != 2) {
return -1;
}
/* WAVE fmt header, NumChannels */
data16 = channels;
nchars = save_file->write((const char *)&data16, 2);
if (nchars != 2) {
return -1;
}
/* WAVE fmt header, SampleRate */
data32 = audio_rate;
nchars = save_file->write((const char *)&data32, 4);
if (nchars != 4) {
return -1;
}
/* WAVE fmt header, ByteRate */
data32 = audio_rate * channels * sizeof(SAMPLE);
nchars = save_file->write((const char *)&data32, 4);
if (nchars != 4) {
return -1;
}
/* WAVE fmt header, BlockAlign */
data16 = channels * (gint16)sizeof(SAMPLE);
nchars = save_file->write((const char *)&data16, 2);
if (nchars != 2) {
return -1;
}
/* WAVE fmt header, BitsPerSample */
data16 = (gint16)sizeof(SAMPLE) * 8;
nchars = save_file->write((const char *)&data16, 2);
if (nchars != 2) {
return -1;
}
/* WAVE data header, Subchunk2ID 0x64617461 == 'data' */
phton32(pd, 0x64617461);
nchars = save_file->write((const char *)pd, 4);
if (nchars != 4) {
return -1;
}
/* WAVE data header, Subchunk2Size */
data32 = subchunk2Size;
nchars = save_file->write((const char *)&data32, 4);
if (nchars != 4) {
return -1;
}
/* Now we are ready for saving data */
return save_file->pos();
}
bool RtpPlayerDialog::writeAudioSilenceSamples(QFile *out_file, qint64 samples, int stream_count)
{
uint8_t pd[2];
phton16(pd, 0x0000);
for(int s=0; s < stream_count; s++) {
for(qint64 i=0; i < samples; i++) {
if (sizeof(SAMPLE) != out_file->write((char *)&pd, sizeof(SAMPLE))) {
return false;
}
}
}
return true;
}
bool RtpPlayerDialog::writeAudioStreamsSamples(QFile *out_file, QVector<RtpAudioStream *> streams, bool swap_bytes)
{
SAMPLE sample;
uint8_t pd[2];
// Did we read something in last cycle?
bool read = true;
while (read) {
read = false;
// Loop over all streams, read one sample from each, write to output
foreach(RtpAudioStream *audio_stream, streams) {
if (sizeof(sample) == audio_stream->readSample(&sample)) {
if (swap_bytes) {
// same as phton16(), but more clear in compare
// to else branch
pd[0] = (guint8)(sample >> 8);
pd[1] = (guint8)(sample >> 0);
} else {
// just copy
pd[1] = (guint8)(sample >> 8);
pd[0] = (guint8)(sample >> 0);
}
read = true;
} else {
// for 0x0000 doesn't matter on order
phton16(pd, 0x0000);
}
if (sizeof(sample) != out_file->write((char *)&pd, sizeof(sample))) {
return false;
}
}
}
return true;
}
save_audio_t RtpPlayerDialog::selectFileAudioFormatAndName(QString *file_path)
{
QString ext_filter = "";
QString ext_filter_wav = tr("WAV (*.wav)");
QString ext_filter_au = tr("Sun Audio (*.au)");
ext_filter.append(ext_filter_wav);
ext_filter.append(";;");
ext_filter.append(ext_filter_au);
QString sel_filter;
*file_path = WiresharkFileDialog::getSaveFileName(
this, tr("Save audio"), mainApp->lastOpenDir().absoluteFilePath(""),
ext_filter, &sel_filter);
if (file_path->isEmpty()) return save_audio_none;
save_audio_t save_format = save_audio_none;
if (0 == QString::compare(sel_filter, ext_filter_au)) {
save_format = save_audio_au;
} else if (0 == QString::compare(sel_filter, ext_filter_wav)) {
save_format = save_audio_wav;
}
return save_format;
}
save_payload_t RtpPlayerDialog::selectFilePayloadFormatAndName(QString *file_path)
{
QString ext_filter = "";
QString ext_filter_raw = tr("Raw (*.raw)");
ext_filter.append(ext_filter_raw);
QString sel_filter;
*file_path = WiresharkFileDialog::getSaveFileName(
this, tr("Save payload"), mainApp->lastOpenDir().absoluteFilePath(""),
ext_filter, &sel_filter);
if (file_path->isEmpty()) return save_payload_none;
save_payload_t save_format = save_payload_none;
if (0 == QString::compare(sel_filter, ext_filter_raw)) {
save_format = save_payload_data;
}
return save_format;
}
QVector<rtpstream_id_t *>RtpPlayerDialog::getSelectedRtpStreamIDs()
{
QList<QTreeWidgetItem *> items = ui->streamTreeWidget->selectedItems();
QVector<rtpstream_id_t *> ids;
if (items.count() > 0) {
foreach(QTreeWidgetItem *ti, items) {
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
if (audio_stream) {
ids << audio_stream->getID();
}
}
}
return ids;
}
QVector<RtpAudioStream *>RtpPlayerDialog::getSelectedAudibleNonmutedAudioStreams()
{
QList<QTreeWidgetItem *> items = ui->streamTreeWidget->selectedItems();
QVector<RtpAudioStream *> streams;
if (items.count() > 0) {
foreach(QTreeWidgetItem *ti, items) {
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
// Ignore muted streams and streams with no audio
if (audio_stream &&
!audio_stream->getAudioRouting().isMuted() &&
(audio_stream->sampleRate()>0)
) {
streams << audio_stream;
}
}
}
return streams;
}
void RtpPlayerDialog::saveAudio(save_mode_t save_mode)
{
qint64 minSilenceSamples;
qint64 startSample;
qint64 lead_silence_samples;
qint64 maxSample;
QString path;
QVector<RtpAudioStream *>streams;
streams = getSelectedAudibleNonmutedAudioStreams();
if (streams.count() < 1) {
QMessageBox::warning(this, tr("Warning"), tr("No stream selected or none of selected streams provide audio"));
return;
}
unsigned save_audio_rate = streams[0]->playRate();
// Check whether all streams use same audio rate
foreach(RtpAudioStream *audio_stream, streams) {
if (save_audio_rate != audio_stream->playRate()) {
QMessageBox::warning(this, tr("Error"), tr("All selected streams must use same play rate. Manual set of Output Audio Rate might help."));
return;
}
}
save_audio_t format = selectFileAudioFormatAndName(&path);
if (format == save_audio_none) return;
// Use start silence and length of first stream
minSilenceSamples = streams[0]->getLeadSilenceSamples();
maxSample = streams[0]->getTotalSamples();
// Find shortest start silence and longest stream
foreach(RtpAudioStream *audio_stream, streams) {
if (minSilenceSamples > audio_stream->getLeadSilenceSamples()) {
minSilenceSamples = audio_stream->getLeadSilenceSamples();
}
if (maxSample < audio_stream->getTotalSamples()) {
maxSample = audio_stream->getTotalSamples();
}
}
switch (save_mode) {
case save_mode_from_cursor:
if (ui->todCheckBox->isChecked()) {
startSample = start_marker_time_ * save_audio_rate;
} else {
startSample = (start_marker_time_ - first_stream_rel_start_time_) * save_audio_rate;
}
lead_silence_samples = 0;
break;
case save_mode_sync_stream:
// Skip start of first stream, no lead silence
startSample = minSilenceSamples;
lead_silence_samples = 0;
break;
case save_mode_sync_file:
default:
// Full first stream, lead silence
startSample = 0;
lead_silence_samples = first_stream_rel_start_time_ * save_audio_rate;
break;
}
QVector<RtpAudioStream *>temp = QVector<RtpAudioStream *>(streams);
// Remove streams shorter than startSample and
// seek to correct start for longer ones
foreach(RtpAudioStream *audio_stream, temp) {
if (startSample > audio_stream->getTotalSamples()) {
streams.removeAll(audio_stream);
} else {
audio_stream->seekSample(startSample);
}
}
if (streams.count() < 1) {
QMessageBox::warning(this, tr("Warning"), tr("No streams are suitable for save"));
return;
}
QFile file(path);
file.open(QIODevice::WriteOnly);
if (!file.isOpen() || (file.error() != QFile::NoError)) {
QMessageBox::warning(this, tr("Warning"), tr("Save failed!"));
} else {
switch (format) {
case save_audio_au:
if (-1 == saveAudioHeaderAU(&file, static_cast<quint32>(streams.count()), save_audio_rate)) {
QMessageBox::warning(this, tr("Error"), tr("Can't write header of AU file"));
return;
}
if (lead_silence_samples > 0) {
if (!writeAudioSilenceSamples(&file, lead_silence_samples, static_cast<int>(streams.count()))) {
QMessageBox::warning(this, tr("Warning"), tr("Save failed!"));
}
}
if (!writeAudioStreamsSamples(&file, streams, true)) {
QMessageBox::warning(this, tr("Warning"), tr("Save failed!"));
}
break;
case save_audio_wav:
if (-1 == saveAudioHeaderWAV(&file, static_cast<quint32>(streams.count()), save_audio_rate, (maxSample - startSample) + lead_silence_samples)) {
QMessageBox::warning(this, tr("Error"), tr("Can't write header of WAV file"));
return;
}
if (lead_silence_samples > 0) {
if (!writeAudioSilenceSamples(&file, lead_silence_samples, static_cast<int>(streams.count()))) {
QMessageBox::warning(this, tr("Warning"), tr("Save failed!"));
}
}
if (!writeAudioStreamsSamples(&file, streams, false)) {
QMessageBox::warning(this, tr("Warning"), tr("Save failed!"));
}
break;
case save_audio_none:
break;
}
}
file.close();
}
void RtpPlayerDialog::savePayload()
{
QString path;
QList<QTreeWidgetItem *> items;
RtpAudioStream *audio_stream = NULL;
items = ui->streamTreeWidget->selectedItems();
foreach(QTreeWidgetItem *ti, items) {
audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
if (audio_stream)
break;
}
if (items.count() != 1 || !audio_stream) {
QMessageBox::warning(this, tr("Warning"), tr("Payload save works with just one audio stream."));
return;
}
save_payload_t format = selectFilePayloadFormatAndName(&path);
if (format == save_payload_none) return;
QFile file(path);
file.open(QIODevice::WriteOnly);
if (!file.isOpen() || (file.error() != QFile::NoError)) {
QMessageBox::warning(this, tr("Warning"), tr("Save failed!"));
} else if (!audio_stream->savePayload(&file)) {
QMessageBox::warning(this, tr("Warning"), tr("Save failed!"));
}
file.close();
}
void RtpPlayerDialog::on_actionSaveAudioFromCursor_triggered()
{
saveAudio(save_mode_from_cursor);
}
void RtpPlayerDialog::on_actionSaveAudioSyncStream_triggered()
{
saveAudio(save_mode_sync_stream);
}
void RtpPlayerDialog::on_actionSaveAudioSyncFile_triggered()
{
saveAudio(save_mode_sync_file);
}
void RtpPlayerDialog::on_actionSavePayload_triggered()
{
savePayload();
}
void RtpPlayerDialog::selectInaudible(bool select)
{
block_redraw_ = true;
ui->streamTreeWidget->blockSignals(true);
for (int row = 0; row < ui->streamTreeWidget->topLevelItemCount(); row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
RtpAudioStream *audio_stream = ti->data(stream_data_col_, Qt::UserRole).value<RtpAudioStream*>();
// Streams with no audio
if (audio_stream && (audio_stream->sampleRate()==0)) {
ti->setSelected(select);
}
}
ui->streamTreeWidget->blockSignals(false);
block_redraw_ = false;
ui->audioPlot->replot();
updateHintLabel();
}
void RtpPlayerDialog::on_actionSelectInaudible_triggered()
{
selectInaudible(true);
}
void RtpPlayerDialog::on_actionDeselectInaudible_triggered()
{
selectInaudible(false);
}
void RtpPlayerDialog::on_actionPrepareFilter_triggered()
{
QVector<rtpstream_id_t *> ids = getSelectedRtpStreamIDs();
QString filter = make_filter_based_on_rtpstream_id(ids);
if (filter.length() > 0) {
emit updateFilter(filter);
}
}
void RtpPlayerDialog::rtpAnalysisReplace()
{
if (ui->streamTreeWidget->selectedItems().count() < 1) return;
emit rtpAnalysisDialogReplaceRtpStreams(getSelectedRtpStreamIDs());
}
void RtpPlayerDialog::rtpAnalysisAdd()
{
if (ui->streamTreeWidget->selectedItems().count() < 1) return;
emit rtpAnalysisDialogAddRtpStreams(getSelectedRtpStreamIDs());
}
void RtpPlayerDialog::rtpAnalysisRemove()
{
if (ui->streamTreeWidget->selectedItems().count() < 1) return;
emit rtpAnalysisDialogRemoveRtpStreams(getSelectedRtpStreamIDs());
}
void RtpPlayerDialog::on_actionReadCapture_triggered()
{
#ifdef QT_MULTIMEDIA_LIB
QTimer::singleShot(0, this, SLOT(retapPackets()));
#endif
}
// _U_ is used for case w have no LIBPCAP
void RtpPlayerDialog::captureEvent(CaptureEvent e _U_)
{
#ifdef HAVE_LIBPCAP
bool new_read_capture_enabled = false;
bool found = false;
if ((e.captureContext() & CaptureEvent::Capture) &&
(e.eventType() == CaptureEvent::Prepared)
) {
new_read_capture_enabled = true;
found = true;
} else if ((e.captureContext() & CaptureEvent::Capture) &&
(e.eventType() == CaptureEvent::Finished)
) {
new_read_capture_enabled = false;
found = true;
}
if (found) {
bool retap = false;
if (read_capture_enabled_ && !new_read_capture_enabled) {
// Capturing ended, automatically refresh data
retap = true;
}
read_capture_enabled_ = new_read_capture_enabled;
updateWidgets();
if (retap) {
QTimer::singleShot(0, this, SLOT(retapPackets()));
}
}
#endif
}
#endif // QT_MULTIMEDIA_LIB |
C/C++ | wireshark/ui/qt/rtp_player_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 RTP_PLAYER_DIALOG_H
#define RTP_PLAYER_DIALOG_H
#include "config.h"
#include <glib.h>
#include <mutex>
#include "ui/rtp_stream.h"
#include "wireshark_dialog.h"
#include "rtp_audio_stream.h"
#include <QWidget>
#include <QMap>
#include <QMultiHash>
#include <QTreeWidgetItem>
#include <QMetaType>
#include <ui/qt/widgets/qcustomplot.h>
#ifdef QT_MULTIMEDIA_LIB
# if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
# include <QAudioDevice>
# else
# include <QAudioDeviceInfo>
# endif
#endif
namespace Ui {
class RtpPlayerDialog;
}
class QCPItemStraightLine;
class QDialogButtonBox;
class QMenu;
class RtpAudioStream;
class QCPAxisTicker;
class QCPAxisTickerDateTime;
typedef enum {
save_audio_none,
save_audio_au,
save_audio_wav
} save_audio_t;
typedef enum {
save_payload_none,
save_payload_data
} save_payload_t;
typedef enum {
save_mode_from_cursor,
save_mode_sync_stream,
save_mode_sync_file
} save_mode_t;
// Singleton by https://refactoring.guru/design-patterns/singleton/cpp/example#example-1
class RtpPlayerDialog : public WiresharkDialog
{
Q_OBJECT
#ifdef QT_MULTIMEDIA_LIB
Q_PROPERTY(QString currentOutputDeviceName READ currentOutputDeviceName)
#endif
public:
/**
* Returns singleton
*/
static RtpPlayerDialog *openRtpPlayerDialog(QWidget &parent, CaptureFile &cf, QObject *packet_list, bool capture_running);
/**
* Should not be clonnable and assignable
*/
RtpPlayerDialog(RtpPlayerDialog &other) = delete;
void operator=(const RtpPlayerDialog &) = delete;
/**
* @brief Common routine to add a "Play call" button to a QDialogButtonBox.
* @param button_box Caller's QDialogButtonBox.
* @return The new "Play call" button.
*/
static QToolButton *addPlayerButton(QDialogButtonBox *button_box, QDialog *dialog);
#ifdef QT_MULTIMEDIA_LIB
void accept();
void reject();
void setMarkers();
/** Replace/Add/Remove an RTP streams to play.
* Requires array of rtpstream_info_t.
* Each item must have filled items: src_addr, src_port, dest_addr,
* dest_port, ssrc, packet_count, setup_frame_number, and start_rel_time.
*
* @param stream_ids struct with rtpstream info
*/
void replaceRtpStreams(QVector<rtpstream_id_t *> stream_ids);
void addRtpStreams(QVector<rtpstream_id_t *> stream_ids);
void removeRtpStreams(QVector<rtpstream_id_t *> stream_ids);
signals:
// Tells the packet list to redraw. An alternative might be to add a
// cf_packet_marked callback to file.[ch] but that's synchronous and
// might incur too much overhead.
void packetsMarked();
void updateFilter(QString filter, bool force = false);
void goToPacket(int packet_num);
void rtpAnalysisDialogReplaceRtpStreams(QVector<rtpstream_id_t *> stream_infos);
void rtpAnalysisDialogAddRtpStreams(QVector<rtpstream_id_t *> stream_infos);
void rtpAnalysisDialogRemoveRtpStreams(QVector<rtpstream_id_t *> stream_infos);
public slots:
void rtpAnalysisReplace();
void rtpAnalysisAdd();
void rtpAnalysisRemove();
#endif
protected:
explicit RtpPlayerDialog(QWidget &parent, CaptureFile &cf, bool capture_running);
#ifdef QT_MULTIMEDIA_LIB
~RtpPlayerDialog();
virtual void showEvent(QShowEvent *);
void contextMenuEvent(QContextMenuEvent *event);
bool eventFilter(QObject *obj, QEvent *event);
private slots:
/** Retap the capture file, reading RTP packets that match the
* streams added using ::addRtpStream.
*/
void retapPackets();
void captureEvent(CaptureEvent e);
/** Clear, decode, and redraw each stream.
*/
void rescanPackets(bool rescale_axes = false);
void createPlot(bool rescale_axes = false);
void updateWidgets();
void itemEntered(QTreeWidgetItem *item, int column);
void mouseMovePlot(QMouseEvent *event);
void graphClicked(QMouseEvent *event);
void graphDoubleClicked(QMouseEvent *event);
void plotClicked(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event);
void updateHintLabel();
void resetXAxis();
void updateGraphs();
void playFinished(RtpAudioStream *stream, QAudio::Error error);
void setPlayPosition(double secs);
void setPlaybackError(const QString playback_error);
void changeAudioRoutingOnItem(QTreeWidgetItem *ti, AudioRouting new_audio_routing);
void changeAudioRouting(AudioRouting new_audio_routing);
void invertAudioMutingOnItem(QTreeWidgetItem *ti);
void on_playButton_clicked();
void on_pauseButton_clicked();
void on_stopButton_clicked();
void on_actionReset_triggered();
void on_actionZoomIn_triggered();
void on_actionZoomOut_triggered();
void on_actionMoveLeft10_triggered();
void on_actionMoveRight10_triggered();
void on_actionMoveLeft1_triggered();
void on_actionMoveRight1_triggered();
void on_actionGoToPacket_triggered();
void on_actionGoToSetupPacketPlot_triggered();
void on_actionGoToSetupPacketTree_triggered();
void on_actionRemoveStream_triggered();
void on_actionAudioRoutingP_triggered();
void on_actionAudioRoutingL_triggered();
void on_actionAudioRoutingLR_triggered();
void on_actionAudioRoutingR_triggered();
void on_actionAudioRoutingMute_triggered();
void on_actionAudioRoutingUnmute_triggered();
void on_actionAudioRoutingMuteInvert_triggered();
void on_streamTreeWidget_itemSelectionChanged();
void on_streamTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, const int column);
void on_outputDeviceComboBox_currentTextChanged(const QString &);
void on_outputAudioRate_currentTextChanged(const QString &);
void on_jitterSpinBox_valueChanged(double);
void on_timingComboBox_currentIndexChanged(int);
void on_todCheckBox_toggled(bool checked);
void on_buttonBox_helpRequested();
void on_actionSelectAll_triggered();
void on_actionSelectInvert_triggered();
void on_actionSelectNone_triggered();
void outputNotify();
void on_actionPlay_triggered();
void on_actionStop_triggered();
void on_actionSaveAudioFromCursor_triggered();
void on_actionSaveAudioSyncStream_triggered();
void on_actionSaveAudioSyncFile_triggered();
void on_actionSavePayload_triggered();
void on_actionSelectInaudible_triggered();
void on_actionDeselectInaudible_triggered();
void on_actionPrepareFilter_triggered();
void on_actionReadCapture_triggered();
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
void sinkStateChanged();
#endif
#endif
private:
static RtpPlayerDialog *pinstance_;
static std::mutex init_mutex_;
static std::mutex run_mutex_;
#ifdef QT_MULTIMEDIA_LIB
Ui::RtpPlayerDialog *ui;
QMenu *graph_ctx_menu_;
QMenu *list_ctx_menu_;
double first_stream_rel_start_time_; // Relative start time of first stream
double first_stream_abs_start_time_; // Absolute start time of first stream
double first_stream_rel_stop_time_; // Relative end time of first stream (ued for streams_length_ calculation
double streams_length_; // Difference between start of first stream and end of last stream
double start_marker_time_; // Always relative time to start of the capture
double start_marker_time_play_; // Copy when play started
QCPItemStraightLine *cur_play_pos_;
QCPItemStraightLine *start_marker_pos_;
QString playback_error_;
QSharedPointer<QCPAxisTicker> number_ticker_;
QSharedPointer<QCPAxisTickerDateTime> datetime_ticker_;
bool stereo_available_;
QList<RtpAudioStream *> playing_streams_;
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
QAudioSink *marker_stream_;
QTimer notify_timer_;
qint64 notify_timer_start_diff_; // Used to shift play cursor to correct place
#else
QAudioOutput *marker_stream_;
#endif
quint32 marker_stream_requested_out_rate_;
QTreeWidgetItem *last_ti_;
bool listener_removed_;
QPushButton *read_btn_;
QToolButton *inaudible_btn_;
QToolButton *analyze_btn_;
QPushButton *prepare_btn_;
QPushButton *export_btn_;
QMultiHash<guint, RtpAudioStream *> stream_hash_;
bool block_redraw_;
int lock_ui_;
bool read_capture_enabled_;
double silence_skipped_time_;
// const QString streamKey(const rtpstream_info_t *rtpstream);
// const QString streamKey(const packet_info *pinfo, const struct _rtp_info *rtpinfo);
// Tap callbacks
// static void tapReset(void *tapinfo_ptr);
static tap_packet_status tapPacket(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *, const void *rtpinfo_ptr, tap_flags_t flags);
static void tapDraw(void *tapinfo_ptr);
void addPacket(packet_info *pinfo, const struct _rtp_info *rtpinfo);
void zoomXAxis(bool in);
void panXAxis(int x_pixels);
const QString getFormatedTime(double f_time);
const QString getFormatedHoveredTime();
int getHoveredPacket();
QString currentOutputDeviceName();
double getStartPlayMarker();
void drawStartPlayMarker();
void setStartPlayMarker(double new_time);
void updateStartStopTime(rtpstream_info_t *rtpstream, bool is_first);
void formatAudioRouting(QTreeWidgetItem *ti, AudioRouting audio_routing);
bool isStereoAvailable();
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
QAudioSink *getSilenceAudioOutput();
QAudioDevice getCurrentDeviceInfo();
#else
QAudioOutput *getSilenceAudioOutput();
QAudioDeviceInfo getCurrentDeviceInfo();
#endif
QTreeWidgetItem *findItemByCoords(QPoint point);
QTreeWidgetItem *findItem(QCPAbstractPlottable *plottable);
void handleItemHighlight(QTreeWidgetItem *ti, bool scroll);
void highlightItem(QTreeWidgetItem *ti, bool highlight);
void invertSelection();
void handleGoToSetupPacket(QTreeWidgetItem *ti);
void addSingleRtpStream(rtpstream_id_t *id);
void removeRow(QTreeWidgetItem *ti);
void fillAudioRateMenu();
void cleanupMarkerStream();
qint64 saveAudioHeaderAU(QFile *save_file, quint32 channels, unsigned audio_rate);
qint64 saveAudioHeaderWAV(QFile *save_file, quint32 channels, unsigned audio_rate, qint64 samples);
bool writeAudioSilenceSamples(QFile *out_file, qint64 samples, int stream_count);
bool writeAudioStreamsSamples(QFile *out_file, QVector<RtpAudioStream *> streams, bool swap_bytes);
save_audio_t selectFileAudioFormatAndName(QString *file_path);
save_payload_t selectFilePayloadFormatAndName(QString *file_path);
QVector<RtpAudioStream *>getSelectedAudibleNonmutedAudioStreams();
void saveAudio(save_mode_t save_mode);
void savePayload();
void lockUI();
void unlockUI();
void selectInaudible(bool select);
QVector<rtpstream_id_t *>getSelectedRtpStreamIDs();
void fillTappedColumns();
#else // QT_MULTIMEDIA_LIB
private:
Ui::RtpPlayerDialog *ui;
#endif // QT_MULTIMEDIA_LIB
};
#endif // RTP_PLAYER_DIALOG_H |
User Interface | wireshark/ui/qt/rtp_player_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>RtpPlayerDialog</class>
<widget class="QDialog" name="RtpPlayerDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>750</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>RTP Player</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<widget class="QCustomPlot" name="audioPlot" native="true"/>
<widget class="QTreeWidget" name="streamTreeWidget">
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="uniformRowHeights">
<bool>true</bool>
</property>
<property name="itemsExpandable">
<bool>false</bool>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
<property name="expandsOnDoubleClick">
<bool>false</bool>
</property>
<column>
<property name="text">
<string>Play</string>
</property>
<property name="toolTip">
<string>Double click to change audio routing</string>
</property>
</column>
<column>
<property name="text">
<string>Source Address</string>
</property>
</column>
<column>
<property name="text">
<string>Source Port</string>
</property>
</column>
<column>
<property name="text">
<string>Destination Address</string>
</property>
</column>
<column>
<property name="text">
<string>Destination Port</string>
</property>
</column>
<column>
<property name="text">
<string>SSRC</string>
</property>
</column>
<column>
<property name="text">
<string>Setup Frame</string>
</property>
</column>
<column>
<property name="text">
<string>Packets</string>
</property>
</column>
<column>
<property name="text">
<string>Time Span (s)</string>
</property>
</column>
<column>
<property name="text">
<string>SR (Hz)</string>
</property>
<property name="toolTip">
<string>Sample rate of codec</string>
</property>
</column>
<column>
<property name="text">
<string>PR (Hz)</string>
</property>
<property name="toolTip">
<string>Play rate of decoded audio (depends e. g. on selected sound card)</string>
</property>
</column>
<column>
<property name="text">
<string>Payloads</string>
</property>
</column>
</widget>
</widget>
</item>
<item>
<widget class="QLabel" name="hintLabel">
<property name="text">
<string><small><i>No audio</i></small></string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0,0,0,0,0,0,0,0,0,0,1,0,0">
<item>
<widget class="QToolButton" name="playButton">
<property name="text">
<string/>
</property>
<property name="toolTip">
<string>Start playback of all unmuted streams</string>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="pauseButton">
<property name="text">
<string/>
</property>
<property name="toolTip">
<string>Pause/unpause playback</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_4">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Fixed</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>10</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QToolButton" name="stopButton">
<property name="text">
<string/>
</property>
<property name="toolTip">
<string>Stop playback</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Fixed</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>10</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QToolButton" name="skipSilenceButton">
<property name="text">
<string/>
</property>
<property name="toolTip">
<string>Enable/disable skipping of silence during playback</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_7">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Fixed</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>10</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Min silence:</string>
</property>
</widget>
</item>
<item>
<widget class="QDoubleSpinBox" name="minSilenceSpinBox">
<property name="toolTip">
<string>Minimum silence duration to skip in seconds</string>
</property>
<property name="decimals">
<number>0</number>
</property>
<property name="minimum">
<double>1.000000000000000</double>
</property>
<property name="singleStep">
<double>1.000000000000000</double>
</property>
<property name="value">
<double>2.000000000000000</double>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_8">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Fixed</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>10</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>Output Device:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="outputDeviceComboBox"/>
</item>
<item>
<spacer name="horizontalSpacer_6">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Fixed</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>10</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="label_4">
<property name="text">
<string>Output Audio Rate:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="outputAudioRate"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2" stretch="0,0,0,0,0,0,0,1">
<item>
<widget class="QLabel" name="label_1">
<property name="text">
<string>Jitter Buffer:</string>
</property>
</widget>
</item>
<item>
<widget class="QDoubleSpinBox" name="jitterSpinBox">
<property name="toolTip">
<string>The simulated jitter buffer in milliseconds.</string>
</property>
<property name="decimals">
<number>0</number>
</property>
<property name="maximum">
<double>500.000000000000000</double>
</property>
<property name="singleStep">
<double>5.000000000000000</double>
</property>
<property name="value">
<double>50.000000000000000</double>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>10</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Playback Timing:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="timingComboBox">
<property name="toolTip">
<string><strong>Jitter Buffer</strong>: Use jitter buffer to simulate the RTP stream as heard by the end user.
<br/>
<strong>RTP Timestamp</strong>: Use RTP Timestamp instead of the arriving packet time. This will not reproduce the RTP stream as the user heard it, but is useful when the RTP is being tunneled and the original packet timing is missing.
<br/>
<strong>Uninterrupted Mode</strong>: Ignore the RTP Timestamp. Play the stream as it is completed. This is useful when the RTP timestamp is missing.</string>
</property>
<item>
<property name="text">
<string>Jitter Buffer</string>
</property>
</item>
<item>
<property name="text">
<string>RTP Timestamp</string>
</property>
</item>
<item>
<property name="text">
<string>Uninterrupted Mode</string>
</property>
</item>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>10</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QCheckBox" name="todCheckBox">
<property name="toolTip">
<string><html><head/><body><p>View the timestamps as time of day (checked) or seconds since beginning of capture (unchecked).</p></body></html></string>
</property>
<property name="text">
<string>Time of Day</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_5">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>48</width>
<height>24</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Close|QDialogButtonBox::Help</set>
</property>
</widget>
</item>
</layout>
<action name="actionExportButton">
<property name="text">
<string>&Export</string>
</property>
<property name="toolTip">
<string>Export audio of all unmuted selected channels or export payload of one channel.</string>
</property>
</action>
<widget class="QMenu" name="menuExport">
<property name="title">
<string>&Export</string>
</property>
<property name="toolTipsVisible">
<bool>true</bool>
</property>
<addaction name="actionSaveAudioFromCursor"/>
<addaction name="actionSaveAudioSyncStream"/>
<addaction name="actionSaveAudioSyncFile"/>
<addaction name="separator"/>
<addaction name="actionSavePayload"/>
</widget>
<action name="actionSaveAudioFromCursor">
<property name="text">
<string>From &cursor</string>
</property>
<property name="toolTip">
<string>Save audio data started at the cursor</string>
</property>
</action>
<action name="actionSaveAudioSyncStream">
<property name="text">
<string>&Stream Synchronized Audio</string>
</property>
<property name="toolTip">
<string>Save audio data synchronized to start of the earliest stream.</string>
</property>
</action>
<action name="actionSaveAudioSyncFile">
<property name="text">
<string>&File Synchronized Audio</string>
</property>
<property name="toolTip">
<string>Save audio data synchronized to start of the capture file.</string>
</property>
</action>
<action name="actionSavePayload">
<property name="text">
<string>&Payload</string>
</property>
<property name="toolTip">
<string>Save RTP payload of selected stream.</string>
</property>
</action>
<action name="actionReset">
<property name="text">
<string>Reset Graph</string>
</property>
<property name="toolTip">
<string>Reset the graph to its initial state.</string>
</property>
<property name="shortcut">
<string notr="true">0</string>
</property>
</action>
<action name="actionZoomIn">
<property name="text">
<string>Zoom In</string>
</property>
<property name="toolTip">
<string>Zoom In</string>
</property>
<property name="shortcut">
<string notr="true">+</string>
</property>
</action>
<action name="actionZoomOut">
<property name="text">
<string>Zoom Out</string>
</property>
<property name="toolTip">
<string>Zoom Out</string>
</property>
<property name="shortcut">
<string notr="true">-</string>
</property>
</action>
<action name="actionMoveLeft10">
<property name="text">
<string>Move Left 10 Pixels</string>
</property>
<property name="toolTip">
<string>Move Left 10 Pixels</string>
</property>
<property name="shortcut">
<string notr="true">Left</string>
</property>
</action>
<action name="actionMoveRight10">
<property name="text">
<string>Move Right 10 Pixels</string>
</property>
<property name="toolTip">
<string>Move Right 10 Pixels</string>
</property>
<property name="shortcut">
<string notr="true">Right</string>
</property>
</action>
<action name="actionMoveLeft1">
<property name="text">
<string>Move Left 1 Pixels</string>
</property>
<property name="toolTip">
<string>Move Left 1 Pixels</string>
</property>
<property name="shortcut">
<string notr="true">Shift+Left</string>
</property>
</action>
<action name="actionMoveRight1">
<property name="text">
<string>Move Right 1 Pixels</string>
</property>
<property name="toolTip">
<string>Move Right 1 Pixels</string>
</property>
<property name="shortcut">
<string notr="true">Shift+Right</string>
</property>
</action>
<action name="actionGoToPacket">
<property name="text">
<string>Go To Packet Under Cursor</string>
</property>
<property name="toolTip">
<string>Go to packet currently under the cursor</string>
</property>
<property name="shortcut">
<string notr="true">G</string>
</property>
</action>
<action name="actionGoToSetupPacketPlot">
<property name="text">
<string>Go To Setup Packet</string>
</property>
<property name="toolTip">
<string>Go to setup packet of stream currently under the cursor</string>
</property>
<property name="shortcut">
<string notr="true">Shift+G</string>
</property>
</action>
<action name="actionGoToSetupPacketTree">
<property name="text">
<string>Go To Setup Packet</string>
</property>
<property name="toolTip">
<string>Go to setup packet of stream currently under the cursor</string>
</property>
<property name="shortcut">
<string notr="true">Shift+G</string>
</property>
</action>
<widget class="QMenu" name="menuAudioRouting">
<property name="title">
<string>Audio Routing</string>
</property>
<property name="toolTipsVisible">
<bool>true</bool>
</property>
<addaction name="actionAudioRoutingMute"/>
<addaction name="actionAudioRoutingUnmute"/>
<addaction name="actionAudioRoutingMuteInvert"/>
<addaction name="actionAudioRoutingP"/>
<addaction name="actionAudioRoutingL"/>
<addaction name="actionAudioRoutingLR"/>
<addaction name="actionAudioRoutingR"/>
</widget>
<action name="actionAudioRoutingMute">
<property name="text">
<string>Mute</string>
</property>
<property name="toolTip">
<string>Mute selected streams</string>
</property>
<property name="shortcut">
<string notr="true">M</string>
</property>
</action>
<action name="actionAudioRoutingUnmute">
<property name="text">
<string>Unmute</string>
</property>
<property name="toolTip">
<string>Unmute selected streams</string>
</property>
<property name="shortcut">
<string notr="true">Shift+M</string>
</property>
</action>
<action name="actionAudioRoutingMuteInvert">
<property name="text">
<string>Invert Muting</string>
</property>
<property name="toolTip">
<string>Invert muting of selected streams</string>
</property>
<property name="shortcut">
<string notr="true">Ctrl+M</string>
</property>
</action>
<action name="actionAudioRoutingP">
<property name="text">
<string>Play</string>
</property>
<property name="toolTip">
<string>Play the stream</string>
</property>
</action>
<action name="actionAudioRoutingL">
<property name="text">
<string>To Left</string>
</property>
<property name="toolTip">
<string>Route audio to left channel of selected streams</string>
</property>
</action>
<action name="actionAudioRoutingLR">
<property name="text">
<string>Left + Right</string>
</property>
<property name="toolTip">
<string>Route audio to left and right channel of selected streams</string>
</property>
</action>
<action name="actionAudioRoutingR">
<property name="text">
<string>To Right</string>
</property>
<property name="toolTip">
<string>Route audio to right channel of selected streams</string>
</property>
</action>
<action name="actionRemoveStream">
<property name="text">
<string>Remove Streams</string>
</property>
<property name="toolTip">
<string>Remove selected streams from the list</string>
</property>
<property name="shortcut">
<string notr="true">Delete</string>
</property>
</action>
<widget class="QMenu" name="menuSelect">
<property name="title">
<string>Select</string>
</property>
<property name="toolTipsVisible">
<bool>true</bool>
</property>
<addaction name="actionSelectAll"/>
<addaction name="actionSelectNone"/>
<addaction name="actionSelectInvert"/>
</widget>
<action name="actionSelectAll">
<property name="text">
<string>All</string>
</property>
<property name="toolTip">
<string>Select all</string>
</property>
<property name="shortcut">
<string notr="true">Ctrl+A</string>
</property>
</action>
<action name="actionSelectNone">
<property name="text">
<string>None</string>
</property>
<property name="toolTip">
<string>Clear selection</string>
</property>
<property name="shortcut">
<string notr="true">Ctrl+Shift+A</string>
</property>
</action>
<action name="actionSelectInvert">
<property name="text">
<string>Invert</string>
</property>
<property name="toolTip">
<string>Invert selection</string>
</property>
<property name="shortcut">
<string notr="true">Ctrl+I</string>
</property>
</action>
<action name="actionPlay">
<property name="text">
<string>Play/Pause</string>
</property>
<property name="toolTip">
<string>Start playing or pause playing</string>
</property>
<property name="shortcut">
<string notr="true">P</string>
</property>
</action>
<action name="actionStop">
<property name="text">
<string>Stop</string>
</property>
<property name="toolTip">
<string>Stop playing</string>
</property>
<property name="shortcut">
<string notr="true">S</string>
</property>
</action>
<action name="actionInaudibleButton">
<property name="text">
<string>I&naudible streams</string>
</property>
<property name="toolTip">
<string>Select/Deselect inaudible streams</string>
</property>
</action>
<widget class="QMenu" name="menuInaudible">
<property name="title">
<string>Inaudible streams</string>
</property>
<property name="toolTipsVisible">
<bool>true</bool>
</property>
<addaction name="actionSelectInaudible"/>
<addaction name="actionDeselectInaudible"/>
</widget>
<action name="actionSelectInaudible">
<property name="text">
<string>&Select</string>
</property>
<property name="toolTip">
<string>Select inaudible streams</string>
</property>
<property name="shortcut">
<string notr="true">N</string>
</property>
</action>
<action name="actionDeselectInaudible">
<property name="text">
<string>&Deselect</string>
</property>
<property name="toolTip">
<string>Deselect inaudible streams</string>
</property>
<property name="shortcut">
<string notr="true">Shift+N</string>
</property>
</action>
<action name="actionPrepareFilter">
<property name="text">
<string>Prepare &Filter</string>
</property>
<property name="toolTip">
<string>Prepare a filter matching the selected stream(s).</string>
</property>
</action>
<action name="actionReadCapture">
<property name="text">
<string>R&efresh streams</string>
</property>
<property name="toolTip">
<string>Read captured packets from capture in progress to player</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>QCustomPlot</class>
<extends>QWidget</extends>
<header>widgets/qcustomplot.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>RtpPlayerDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>RtpPlayerDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/rtp_stream_dialog.cpp | /* rtp_stream_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "rtp_stream_dialog.h"
#include <ui_rtp_stream_dialog.h>
#include "file.h"
#include "epan/addr_resolv.h"
#include <epan/rtp_pt.h>
#include <wsutil/utf8_entities.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "rtp_analysis_dialog.h"
#include "progress_frame.h"
#include "main_application.h"
#include "ui/qt/widgets/wireshark_file_dialog.h"
#include <QAction>
#include <QClipboard>
#include <QKeyEvent>
#include <QPushButton>
#include <QTextStream>
#include <QTreeWidgetItem>
#include <QTreeWidgetItemIterator>
#include <QDateTime>
#include <ui/qt/utils/color_utils.h>
/*
* @file RTP stream dialog
*
* Displays a list of RTP streams with the following information:
* - UDP 4-tuple
* - SSRC
* - Payload type
* - Stats: Packets, lost, max delta, max jitter, mean jitter
* - Problems
*
* Finds reverse streams
* "Save As" rtpdump
* Mark packets
* Go to the setup frame
* Prepare filter
* Copy As CSV and YAML
* Analyze
*/
// To do:
// - Add more statistics to the hint text (e.g. lost packets).
// - Add more statistics to the main list (e.g. stream duration)
const int src_addr_col_ = 0;
const int src_port_col_ = 1;
const int dst_addr_col_ = 2;
const int dst_port_col_ = 3;
const int ssrc_col_ = 4;
const int start_time_col_ = 5;
const int duration_col_ = 6;
const int payload_col_ = 7;
const int packets_col_ = 8;
const int lost_col_ = 9;
const int min_delta_col_ = 10;
const int mean_delta_col_ = 11;
const int max_delta_col_ = 12;
const int min_jitter_col_ = 13;
const int mean_jitter_col_ = 14;
const int max_jitter_col_ = 15;
const int status_col_ = 16;
const int ssrc_fmt_col_ = 17;
const int lost_perc_col_ = 18;
enum { rtp_stream_type_ = 1000 };
bool operator==(rtpstream_id_t const& a, rtpstream_id_t const& b);
class RtpStreamTreeWidgetItem : public QTreeWidgetItem
{
public:
RtpStreamTreeWidgetItem(QTreeWidget *tree, rtpstream_info_t *stream_info) :
QTreeWidgetItem(tree, rtp_stream_type_),
stream_info_(stream_info),
tod_(0)
{
drawData();
}
rtpstream_info_t *streamInfo() const { return stream_info_; }
void drawData() {
rtpstream_info_calc_t calc;
if (!stream_info_) {
return;
}
rtpstream_info_calculate(stream_info_, &calc);
setText(src_addr_col_, calc.src_addr_str);
setText(src_port_col_, QString::number(calc.src_port));
setText(dst_addr_col_, calc.dst_addr_str);
setText(dst_port_col_, QString::number(calc.dst_port));
setText(ssrc_col_, QString("0x%1").arg(calc.ssrc, 0, 16));
if (tod_) {
QDateTime abs_dt = QDateTime::fromMSecsSinceEpoch(nstime_to_msec(&stream_info_->start_fd->abs_ts));
setText(start_time_col_, QString("%1")
.arg(abs_dt.toString("yyyy-MM-dd hh:mm:ss.zzz")));
} else {
setText(start_time_col_, QString::number(calc.start_time_ms, 'f', 6));
}
setText(duration_col_, QString::number(calc.duration_ms, 'f', prefs.gui_decimal_places1));
setText(payload_col_, calc.all_payload_type_names);
setText(packets_col_, QString::number(calc.packet_count));
setText(lost_col_, QObject::tr("%1 (%L2%)").arg(calc.lost_num).arg(QString::number(calc.lost_perc, 'f', 1)));
setText(min_delta_col_, QString::number(calc.min_delta, 'f', prefs.gui_decimal_places3)); // This is RTP. Do we need nanoseconds?
setText(mean_delta_col_, QString::number(calc.mean_delta, 'f', prefs.gui_decimal_places3)); // This is RTP. Do we need nanoseconds?
setText(max_delta_col_, QString::number(calc.max_delta, 'f', prefs.gui_decimal_places3)); // This is RTP. Do we need nanoseconds?
setText(min_jitter_col_, QString::number(calc.min_jitter, 'f', prefs.gui_decimal_places3));
setText(mean_jitter_col_, QString::number(calc.mean_jitter, 'f', prefs.gui_decimal_places3));
setText(max_jitter_col_, QString::number(calc.max_jitter, 'f', prefs.gui_decimal_places3));
if (calc.problem) {
setText(status_col_, UTF8_BULLET);
setTextAlignment(status_col_, Qt::AlignCenter);
QColor bgColor(ColorUtils::warningBackground());
QColor textColor(QApplication::palette().text().color());
for (int i = 0; i < columnCount(); i++) {
QBrush bgBrush = background(i);
bgBrush.setColor(bgColor);
bgBrush.setStyle(Qt::SolidPattern);
setBackground(i, bgBrush);
QBrush fgBrush = foreground(i);
fgBrush.setColor(textColor);
fgBrush.setStyle(Qt::SolidPattern);
setForeground(i, fgBrush);
}
}
rtpstream_info_calc_free(&calc);
}
// Return a QString, int, double, or invalid QVariant representing the raw column data.
QVariant colData(int col) const {
rtpstream_info_calc_t calc;
if (!stream_info_) {
return QVariant();
}
QVariant ret;
rtpstream_info_calculate(stream_info_, &calc);
switch(col) {
case src_addr_col_:
ret = QVariant(text(col));
break;
case src_port_col_:
ret = calc.src_port;
break;
case dst_addr_col_:
ret = text(col);
break;
case dst_port_col_:
ret = calc.dst_port;
break;
case ssrc_col_:
ret = calc.ssrc;
break;
case start_time_col_:
ret = calc.start_time_ms;
break;
case duration_col_:
ret = calc.duration_ms;
break;
case payload_col_:
ret = text(col);
break;
case packets_col_:
ret = calc.packet_count;
break;
case lost_col_:
ret = calc.lost_num;
break;
case min_delta_col_:
ret = calc.min_delta;
break;
case mean_delta_col_:
ret = calc.mean_delta;
break;
case max_delta_col_:
ret = calc.max_delta;
break;
case min_jitter_col_:
ret = calc.min_jitter;
break;
case mean_jitter_col_:
ret = calc.mean_jitter;
break;
case max_jitter_col_:
ret = calc.max_jitter;
break;
case status_col_:
ret = calc.problem ? "Problem" : "";
break;
case ssrc_fmt_col_:
ret = QString("0x%1").arg(calc.ssrc, 0, 16);
break;
case lost_perc_col_:
ret = QString::number(calc.lost_perc, 'f', prefs.gui_decimal_places1);
break;
default:
ret = QVariant();
break;
}
rtpstream_info_calc_free(&calc);
return ret;
}
bool operator< (const QTreeWidgetItem &other) const
{
rtpstream_info_calc_t calc1;
rtpstream_info_calc_t calc2;
bool ret;
if (other.type() != rtp_stream_type_) return QTreeWidgetItem::operator <(other);
const RtpStreamTreeWidgetItem &other_rstwi = dynamic_cast<const RtpStreamTreeWidgetItem&>(other);
switch (treeWidget()->sortColumn()) {
case src_addr_col_:
return cmp_address(&(stream_info_->id.src_addr), &(other_rstwi.stream_info_->id.src_addr)) < 0;
case src_port_col_:
return stream_info_->id.src_port < other_rstwi.stream_info_->id.src_port;
case dst_addr_col_:
return cmp_address(&(stream_info_->id.dst_addr), &(other_rstwi.stream_info_->id.dst_addr)) < 0;
case dst_port_col_:
return stream_info_->id.dst_port < other_rstwi.stream_info_->id.dst_port;
case ssrc_col_:
return stream_info_->id.ssrc < other_rstwi.stream_info_->id.ssrc;
case start_time_col_:
rtpstream_info_calculate(stream_info_, &calc1);
rtpstream_info_calculate(other_rstwi.stream_info_, &calc2);
ret = calc1.start_time_ms < calc2.start_time_ms;
rtpstream_info_calc_free(&calc1);
rtpstream_info_calc_free(&calc2);
return ret;
case duration_col_:
rtpstream_info_calculate(stream_info_, &calc1);
rtpstream_info_calculate(other_rstwi.stream_info_, &calc2);
ret = calc1.duration_ms < calc2.duration_ms;
rtpstream_info_calc_free(&calc1);
rtpstream_info_calc_free(&calc2);
return ret;
case payload_col_:
return g_strcmp0(stream_info_->all_payload_type_names, other_rstwi.stream_info_->all_payload_type_names);
case packets_col_:
return stream_info_->packet_count < other_rstwi.stream_info_->packet_count;
case lost_col_:
rtpstream_info_calculate(stream_info_, &calc1);
rtpstream_info_calculate(other_rstwi.stream_info_, &calc2);
/* XXX: Should this sort on the total number or the percentage?
* lost_num is displayed first and lost_perc in parenthesis,
* so let's use the total number.
*/
ret = calc1.lost_num < calc2.lost_num;
rtpstream_info_calc_free(&calc1);
rtpstream_info_calc_free(&calc2);
return ret;
break;
case min_delta_col_:
return stream_info_->rtp_stats.min_delta < other_rstwi.stream_info_->rtp_stats.min_delta;
case mean_delta_col_:
return stream_info_->rtp_stats.mean_delta < other_rstwi.stream_info_->rtp_stats.mean_delta;
case max_delta_col_:
return stream_info_->rtp_stats.max_delta < other_rstwi.stream_info_->rtp_stats.max_delta;
case min_jitter_col_:
return stream_info_->rtp_stats.min_jitter < other_rstwi.stream_info_->rtp_stats.min_jitter;
case mean_jitter_col_:
return stream_info_->rtp_stats.mean_jitter < other_rstwi.stream_info_->rtp_stats.mean_jitter;
case max_jitter_col_:
return stream_info_->rtp_stats.max_jitter < other_rstwi.stream_info_->rtp_stats.max_jitter;
default:
break;
}
// Fall back to string comparison
return QTreeWidgetItem::operator <(other);
}
void setTOD(gboolean tod)
{
tod_ = tod;
}
private:
rtpstream_info_t *stream_info_;
gboolean tod_;
};
RtpStreamDialog *RtpStreamDialog::pinstance_{nullptr};
std::mutex RtpStreamDialog::mutex_;
RtpStreamDialog *RtpStreamDialog::openRtpStreamDialog(QWidget &parent, CaptureFile &cf, QObject *packet_list)
{
std::lock_guard<std::mutex> lock(mutex_);
if (pinstance_ == nullptr)
{
pinstance_ = new RtpStreamDialog(parent, cf);
connect(pinstance_, SIGNAL(packetsMarked()),
packet_list, SLOT(redrawVisiblePackets()));
connect(pinstance_, SIGNAL(goToPacket(int)),
packet_list, SLOT(goToPacket(int)));
}
return pinstance_;
}
RtpStreamDialog::RtpStreamDialog(QWidget &parent, CaptureFile &cf) :
WiresharkDialog(parent, cf),
ui(new Ui::RtpStreamDialog),
need_redraw_(false)
{
ui->setupUi(this);
loadGeometry(parent.width() * 4 / 5, parent.height() * 2 / 3);
setWindowSubtitle(tr("RTP Streams"));
ui->streamTreeWidget->installEventFilter(this);
ctx_menu_.addMenu(ui->menuSelect);
ctx_menu_.addMenu(ui->menuFindReverse);
ctx_menu_.addAction(ui->actionGoToSetup);
ctx_menu_.addAction(ui->actionMarkPackets);
ctx_menu_.addAction(ui->actionPrepareFilter);
ctx_menu_.addAction(ui->actionExportAsRtpDump);
ctx_menu_.addAction(ui->actionCopyAsCsv);
ctx_menu_.addAction(ui->actionCopyAsYaml);
ctx_menu_.addAction(ui->actionAnalyze);
set_action_shortcuts_visible_in_context_menu(ctx_menu_.actions());
ui->streamTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
ui->streamTreeWidget->header()->setSortIndicator(0, Qt::AscendingOrder);
connect(ui->streamTreeWidget, SIGNAL(customContextMenuRequested(QPoint)),
SLOT(showStreamMenu(QPoint)));
find_reverse_button_ = new QToolButton();
ui->buttonBox->addButton(find_reverse_button_, QDialogButtonBox::ActionRole);
find_reverse_button_->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
find_reverse_button_->setPopupMode(QToolButton::MenuButtonPopup);
connect(ui->actionFindReverse, &QAction::triggered, this, &RtpStreamDialog::on_actionFindReverseNormal_triggered);
find_reverse_button_->setDefaultAction(ui->actionFindReverse);
// Overrides text striping of shortcut undercode in QAction
find_reverse_button_->setText(ui->actionFindReverseNormal->text());
find_reverse_button_->setMenu(ui->menuFindReverse);
analyze_button_ = RtpAnalysisDialog::addAnalyzeButton(ui->buttonBox, this);
prepare_button_ = ui->buttonBox->addButton(ui->actionPrepareFilter->text(), QDialogButtonBox::ActionRole);
prepare_button_->setToolTip(ui->actionPrepareFilter->toolTip());
connect(prepare_button_, &QPushButton::pressed, this, &RtpStreamDialog::on_actionPrepareFilter_triggered);
player_button_ = RtpPlayerDialog::addPlayerButton(ui->buttonBox, this);
copy_button_ = ui->buttonBox->addButton(ui->actionCopyButton->text(), QDialogButtonBox::ActionRole);
copy_button_->setToolTip(ui->actionCopyButton->toolTip());
export_button_ = ui->buttonBox->addButton(ui->actionExportAsRtpDump->text(), QDialogButtonBox::ActionRole);
export_button_->setToolTip(ui->actionExportAsRtpDump->toolTip());
connect(export_button_, &QPushButton::pressed, this, &RtpStreamDialog::on_actionExportAsRtpDump_triggered);
QMenu *copy_menu = new QMenu(copy_button_);
QAction *ca;
ca = copy_menu->addAction(tr("as CSV"));
ca->setToolTip(ui->actionCopyAsCsv->toolTip());
connect(ca, &QAction::triggered, this, &RtpStreamDialog::on_actionCopyAsCsv_triggered);
ca = copy_menu->addAction(tr("as YAML"));
ca->setToolTip(ui->actionCopyAsYaml->toolTip());
connect(ca, &QAction::triggered, this, &RtpStreamDialog::on_actionCopyAsYaml_triggered);
copy_button_->setMenu(copy_menu);
connect(&cap_file_, SIGNAL(captureEvent(CaptureEvent)),
this, SLOT(captureEvent(CaptureEvent)));
/* Register the tap listener */
memset(&tapinfo_, 0, sizeof(rtpstream_tapinfo_t));
tapinfo_.tap_reset = tapReset;
tapinfo_.tap_draw = tapDraw;
tapinfo_.tap_mark_packet = tapMarkPacket;
tapinfo_.tap_data = this;
tapinfo_.mode = TAP_ANALYSE;
register_tap_listener_rtpstream(&tapinfo_, NULL, show_tap_registration_error);
if (cap_file_.isValid() && cap_file_.capFile()->dfilter) {
// Activate display filter checking
tapinfo_.apply_display_filter = true;
ui->displayFilterCheckBox->setChecked(true);
}
connect(ui->displayFilterCheckBox, &QCheckBox::toggled,
this, &RtpStreamDialog::displayFilterCheckBoxToggled);
connect(this, SIGNAL(updateFilter(QString, bool)),
&parent, SLOT(filterPackets(QString, bool)));
connect(&parent, SIGNAL(displayFilterSuccess(bool)),
this, SLOT(displayFilterSuccess(bool)));
connect(this, SIGNAL(rtpPlayerDialogReplaceRtpStreams(QVector<rtpstream_id_t *>)),
&parent, SLOT(rtpPlayerDialogReplaceRtpStreams(QVector<rtpstream_id_t *>)));
connect(this, SIGNAL(rtpPlayerDialogAddRtpStreams(QVector<rtpstream_id_t *>)),
&parent, SLOT(rtpPlayerDialogAddRtpStreams(QVector<rtpstream_id_t *>)));
connect(this, SIGNAL(rtpPlayerDialogRemoveRtpStreams(QVector<rtpstream_id_t *>)),
&parent, SLOT(rtpPlayerDialogRemoveRtpStreams(QVector<rtpstream_id_t *>)));
connect(this, SIGNAL(rtpAnalysisDialogReplaceRtpStreams(QVector<rtpstream_id_t *>)),
&parent, SLOT(rtpAnalysisDialogReplaceRtpStreams(QVector<rtpstream_id_t *>)));
connect(this, SIGNAL(rtpAnalysisDialogAddRtpStreams(QVector<rtpstream_id_t *>)),
&parent, SLOT(rtpAnalysisDialogAddRtpStreams(QVector<rtpstream_id_t *>)));
connect(this, SIGNAL(rtpAnalysisDialogRemoveRtpStreams(QVector<rtpstream_id_t *>)),
&parent, SLOT(rtpAnalysisDialogRemoveRtpStreams(QVector<rtpstream_id_t *>)));
ProgressFrame::addToButtonBox(ui->buttonBox, &parent);
updateWidgets();
if (cap_file_.isValid()) {
cap_file_.delayedRetapPackets();
}
}
RtpStreamDialog::~RtpStreamDialog()
{
std::lock_guard<std::mutex> lock(mutex_);
freeLastSelected();
delete ui;
rtpstream_reset(&tapinfo_);
remove_tap_listener_rtpstream(&tapinfo_);
pinstance_ = nullptr;
}
void RtpStreamDialog::setRtpStreamSelection(rtpstream_id_t *id, bool state)
{
QTreeWidgetItemIterator iter(ui->streamTreeWidget);
while (*iter) {
RtpStreamTreeWidgetItem *rsti = static_cast<RtpStreamTreeWidgetItem*>(*iter);
rtpstream_info_t *stream_info = rsti->streamInfo();
if (stream_info) {
if (rtpstream_id_equal(id,&stream_info->id,RTPSTREAM_ID_EQUAL_SSRC)) {
(*iter)->setSelected(state);
}
}
++iter;
}
}
void RtpStreamDialog::selectRtpStream(QVector<rtpstream_id_t *> stream_ids)
{
std::lock_guard<std::mutex> lock(mutex_);
foreach(rtpstream_id_t *id, stream_ids) {
setRtpStreamSelection(id, true);
}
}
void RtpStreamDialog::deselectRtpStream(QVector<rtpstream_id_t *> stream_ids)
{
std::lock_guard<std::mutex> lock(mutex_);
foreach(rtpstream_id_t *id, stream_ids) {
setRtpStreamSelection(id, false);
}
}
bool RtpStreamDialog::eventFilter(QObject *, QEvent *event)
{
if (ui->streamTreeWidget->hasFocus() && event->type() == QEvent::KeyPress) {
QKeyEvent &keyEvent = static_cast<QKeyEvent&>(*event);
switch(keyEvent.key()) {
case Qt::Key_G:
on_actionGoToSetup_triggered();
return true;
case Qt::Key_M:
on_actionMarkPackets_triggered();
return true;
case Qt::Key_P:
on_actionPrepareFilter_triggered();
return true;
case Qt::Key_R:
if (keyEvent.modifiers() == Qt::ShiftModifier) {
on_actionFindReversePair_triggered();
} else if (keyEvent.modifiers() == Qt::ControlModifier) {
on_actionFindReverseSingle_triggered();
} else {
on_actionFindReverseNormal_triggered();
}
return true;
case Qt::Key_I:
if (keyEvent.modifiers() == Qt::ControlModifier) {
// Ctrl+I
on_actionSelectInvert_triggered();
return true;
}
break;
case Qt::Key_A:
if (keyEvent.modifiers() == Qt::ControlModifier) {
// Ctrl+A
on_actionSelectAll_triggered();
return true;
} else if (keyEvent.modifiers() == (Qt::ShiftModifier | Qt::ControlModifier)) {
// Ctrl+Shift+A
on_actionSelectNone_triggered();
return true;
} else if (keyEvent.modifiers() == Qt::NoModifier) {
on_actionAnalyze_triggered();
}
break;
default:
break;
}
}
return false;
}
void RtpStreamDialog::captureEvent(CaptureEvent e)
{
if (e.captureContext() == CaptureEvent::Retap)
{
switch (e.eventType())
{
case CaptureEvent::Started:
ui->displayFilterCheckBox->setEnabled(false);
break;
case CaptureEvent::Finished:
ui->displayFilterCheckBox->setEnabled(true);
break;
default:
break;
}
}
}
void RtpStreamDialog::tapReset(rtpstream_tapinfo_t *tapinfo)
{
RtpStreamDialog *rtp_stream_dialog = dynamic_cast<RtpStreamDialog *>((RtpStreamDialog *)tapinfo->tap_data);
if (rtp_stream_dialog) {
rtp_stream_dialog->freeLastSelected();
/* Copy currently selected rtpstream_ids */
QTreeWidgetItemIterator iter(rtp_stream_dialog->ui->streamTreeWidget);
rtpstream_id_t selected_id;
while (*iter) {
RtpStreamTreeWidgetItem *rsti = static_cast<RtpStreamTreeWidgetItem*>(*iter);
rtpstream_info_t *stream_info = rsti->streamInfo();
if ((*iter)->isSelected()) {
/* QList.append() does a member by member copy, so allocate new
* addresses. rtpstream_id_copy() overwrites all struct members.
*/
rtpstream_id_copy(&stream_info->id, &selected_id);
rtp_stream_dialog->last_selected_.append(selected_id);
}
++iter;
}
/* invalidate items which refer to old strinfo_list items. */
rtp_stream_dialog->ui->streamTreeWidget->clear();
}
}
void RtpStreamDialog::tapDraw(rtpstream_tapinfo_t *tapinfo)
{
RtpStreamDialog *rtp_stream_dialog = dynamic_cast<RtpStreamDialog *>((RtpStreamDialog *)tapinfo->tap_data);
if (rtp_stream_dialog) {
rtp_stream_dialog->updateStreams();
}
}
void RtpStreamDialog::tapMarkPacket(rtpstream_tapinfo_t *tapinfo, frame_data *fd)
{
if (!tapinfo) return;
RtpStreamDialog *rtp_stream_dialog = dynamic_cast<RtpStreamDialog *>((RtpStreamDialog *)tapinfo->tap_data);
if (rtp_stream_dialog) {
cf_mark_frame(rtp_stream_dialog->cap_file_.capFile(), fd);
rtp_stream_dialog->need_redraw_ = true;
}
}
/* Operator == for rtpstream_id_t */
bool operator==(rtpstream_id_t const& a, rtpstream_id_t const& b)
{
return rtpstream_id_equal(&a, &b, RTPSTREAM_ID_EQUAL_SSRC);
}
void RtpStreamDialog::updateStreams()
{
// string_list is reverse ordered, so we must add
// just first "to_insert_count" of streams
GList *cur_stream = g_list_first(tapinfo_.strinfo_list);
guint tap_len = g_list_length(tapinfo_.strinfo_list);
guint tree_len = static_cast<guint>(ui->streamTreeWidget->topLevelItemCount());
guint to_insert_count = tap_len - tree_len;
// Add any missing items
while (cur_stream && cur_stream->data && to_insert_count) {
rtpstream_info_t *stream_info = gxx_list_data(rtpstream_info_t*, cur_stream);
RtpStreamTreeWidgetItem *rsti = new RtpStreamTreeWidgetItem(ui->streamTreeWidget, stream_info);
cur_stream = gxx_list_next(cur_stream);
to_insert_count--;
// Check if item was selected last time. If so, select it
if (-1 != last_selected_.indexOf(stream_info->id)) {
rsti->setSelected(true);
}
}
// Recalculate values
QTreeWidgetItemIterator iter(ui->streamTreeWidget);
while (*iter) {
RtpStreamTreeWidgetItem *rsti = static_cast<RtpStreamTreeWidgetItem*>(*iter);
rsti->drawData();
++iter;
}
// Resize columns
for (int i = 0; i < ui->streamTreeWidget->columnCount(); i++) {
ui->streamTreeWidget->resizeColumnToContents(i);
}
ui->streamTreeWidget->setSortingEnabled(true);
updateWidgets();
if (need_redraw_) {
emit packetsMarked();
need_redraw_ = false;
}
}
void RtpStreamDialog::updateWidgets()
{
bool selected = ui->streamTreeWidget->selectedItems().count() > 0;
QString hint = "<small><i>";
hint += tr("%1 streams").arg(ui->streamTreeWidget->topLevelItemCount());
if (selected) {
int tot_packets = 0;
foreach(QTreeWidgetItem *ti, ui->streamTreeWidget->selectedItems()) {
RtpStreamTreeWidgetItem *rsti = static_cast<RtpStreamTreeWidgetItem*>(ti);
if (rsti->streamInfo()) {
tot_packets += rsti->streamInfo()->packet_count;
}
}
hint += tr(", %1 selected, %2 total packets")
.arg(ui->streamTreeWidget->selectedItems().count())
.arg(tot_packets);
}
hint += ". Right-click for more options.";
hint += "</i></small>";
ui->hintLabel->setText(hint);
bool enable = selected && !file_closed_;
bool has_data = ui->streamTreeWidget->topLevelItemCount() > 0;
find_reverse_button_->setEnabled(has_data);
prepare_button_->setEnabled(enable);
export_button_->setEnabled(enable);
copy_button_->setEnabled(has_data);
analyze_button_->setEnabled(enable);
ui->actionFindReverseNormal->setEnabled(enable);
ui->actionFindReversePair->setEnabled(has_data);
ui->actionFindReverseSingle->setEnabled(has_data);
ui->actionGoToSetup->setEnabled(enable);
ui->actionMarkPackets->setEnabled(enable);
ui->actionPrepareFilter->setEnabled(enable);
ui->actionExportAsRtpDump->setEnabled(enable);
ui->actionCopyAsCsv->setEnabled(has_data);
ui->actionCopyAsYaml->setEnabled(has_data);
ui->actionAnalyze->setEnabled(enable);
#if defined(QT_MULTIMEDIA_LIB)
player_button_->setEnabled(enable);
#endif
WiresharkDialog::updateWidgets();
}
QList<QVariant> RtpStreamDialog::streamRowData(int row) const
{
QList<QVariant> row_data;
if (row >= ui->streamTreeWidget->topLevelItemCount()) {
return row_data;
}
for (int col = 0; col < ui->streamTreeWidget->columnCount(); col++) {
if (row < 0) {
row_data << ui->streamTreeWidget->headerItem()->text(col);
} else {
RtpStreamTreeWidgetItem *rsti = static_cast<RtpStreamTreeWidgetItem*>(ui->streamTreeWidget->topLevelItem(row));
if (rsti) {
row_data << rsti->colData(col);
}
}
}
// Add additional columns to export
if (row < 0) {
row_data << QString("SSRC formatted");
row_data << QString("Lost percentage");
} else {
RtpStreamTreeWidgetItem *rsti = static_cast<RtpStreamTreeWidgetItem*>(ui->streamTreeWidget->topLevelItem(row));
if (rsti) {
row_data << rsti->colData(ssrc_fmt_col_);
row_data << rsti->colData(lost_perc_col_);
}
}
return row_data;
}
void RtpStreamDialog::freeLastSelected()
{
/* Free old IDs */
for(int i=0; i<last_selected_.length(); i++) {
rtpstream_id_t id = last_selected_.at(i);
rtpstream_id_free(&id);
}
/* Clear list and reuse it */
last_selected_.clear();
}
void RtpStreamDialog::captureFileClosing()
{
remove_tap_listener_rtpstream(&tapinfo_);
WiresharkDialog::captureFileClosing();
}
void RtpStreamDialog::captureFileClosed()
{
ui->todCheckBox->setEnabled(false);
ui->displayFilterCheckBox->setEnabled(false);
WiresharkDialog::captureFileClosed();
}
void RtpStreamDialog::showStreamMenu(QPoint pos)
{
ui->actionGoToSetup->setEnabled(!file_closed_);
ui->actionMarkPackets->setEnabled(!file_closed_);
ui->actionPrepareFilter->setEnabled(!file_closed_);
ui->actionExportAsRtpDump->setEnabled(!file_closed_);
ui->actionAnalyze->setEnabled(!file_closed_);
ctx_menu_.popup(ui->streamTreeWidget->viewport()->mapToGlobal(pos));
}
void RtpStreamDialog::on_actionCopyAsCsv_triggered()
{
QString csv;
QTextStream stream(&csv, QIODevice::Text);
for (int row = -1; row < ui->streamTreeWidget->topLevelItemCount(); row++) {
QStringList rdsl;
foreach (QVariant v, streamRowData(row)) {
if (!v.isValid()) {
rdsl << "\"\"";
} else if (v.userType() == QMetaType::QString) {
rdsl << QString("\"%1\"").arg(v.toString());
} else {
rdsl << v.toString();
}
}
stream << rdsl.join(",") << '\n';
}
mainApp->clipboard()->setText(stream.readAll());
}
void RtpStreamDialog::on_actionCopyAsYaml_triggered()
{
QString yaml;
QTextStream stream(&yaml, QIODevice::Text);
stream << "---" << '\n';
for (int row = -1; row < ui->streamTreeWidget->topLevelItemCount(); row ++) {
stream << "-" << '\n';
foreach (QVariant v, streamRowData(row)) {
stream << " - " << v.toString() << '\n';
}
}
mainApp->clipboard()->setText(stream.readAll());
}
void RtpStreamDialog::on_actionExportAsRtpDump_triggered()
{
if (file_closed_ || ui->streamTreeWidget->selectedItems().count() < 1) return;
// XXX If the user selected multiple frames is this the one we actually want?
QTreeWidgetItem *ti = ui->streamTreeWidget->selectedItems()[0];
RtpStreamTreeWidgetItem *rsti = static_cast<RtpStreamTreeWidgetItem*>(ti);
rtpstream_info_t *stream_info = rsti->streamInfo();
if (stream_info) {
QString file_name;
QDir path(mainApp->lastOpenDir());
QString save_file = path.canonicalPath() + "/" + cap_file_.fileBaseName();
QString extension;
file_name = WiresharkFileDialog::getSaveFileName(this, mainApp->windowTitleString(tr("Save RTPDump As…")),
save_file, "RTPDump Format (*.rtp)", &extension);
if (file_name.length() > 0) {
gchar *dest_file = qstring_strdup(file_name);
gboolean save_ok = rtpstream_save(&tapinfo_, cap_file_.capFile(), stream_info, dest_file);
g_free(dest_file);
// else error dialog?
if (save_ok) {
mainApp->setLastOpenDirFromFilename(file_name);
}
}
}
}
// Search for reverse stream of every selected stream
void RtpStreamDialog::on_actionFindReverseNormal_triggered()
{
if (ui->streamTreeWidget->selectedItems().count() < 1) return;
ui->streamTreeWidget->blockSignals(true);
// Traverse all items and if stream is selected, search reverse from
// current position till last item (NxN/2)
for (int fwd_row = 0; fwd_row < ui->streamTreeWidget->topLevelItemCount(); fwd_row++) {
RtpStreamTreeWidgetItem *fwd_rsti = static_cast<RtpStreamTreeWidgetItem*>(ui->streamTreeWidget->topLevelItem(fwd_row));
rtpstream_info_t *fwd_stream = fwd_rsti->streamInfo();
if (fwd_stream && fwd_rsti->isSelected()) {
for (int rev_row = fwd_row + 1; rev_row < ui->streamTreeWidget->topLevelItemCount(); rev_row++) {
RtpStreamTreeWidgetItem *rev_rsti = static_cast<RtpStreamTreeWidgetItem*>(ui->streamTreeWidget->topLevelItem(rev_row));
rtpstream_info_t *rev_stream = rev_rsti->streamInfo();
if (rev_stream && rtpstream_info_is_reverse(fwd_stream, rev_stream)) {
rev_rsti->setSelected(true);
break;
}
}
}
}
ui->streamTreeWidget->blockSignals(false);
updateWidgets();
}
// Select all pairs of forward/reverse streams
void RtpStreamDialog::on_actionFindReversePair_triggered()
{
ui->streamTreeWidget->blockSignals(true);
ui->streamTreeWidget->clearSelection();
// Traverse all items and search reverse from current position till last
// item (NxN/2)
for (int fwd_row = 0; fwd_row < ui->streamTreeWidget->topLevelItemCount(); fwd_row++) {
RtpStreamTreeWidgetItem *fwd_rsti = static_cast<RtpStreamTreeWidgetItem*>(ui->streamTreeWidget->topLevelItem(fwd_row));
rtpstream_info_t *fwd_stream = fwd_rsti->streamInfo();
if (fwd_stream) {
for (int rev_row = fwd_row + 1; rev_row < ui->streamTreeWidget->topLevelItemCount(); rev_row++) {
RtpStreamTreeWidgetItem *rev_rsti = static_cast<RtpStreamTreeWidgetItem*>(ui->streamTreeWidget->topLevelItem(rev_row));
rtpstream_info_t *rev_stream = rev_rsti->streamInfo();
if (rev_stream && rtpstream_info_is_reverse(fwd_stream, rev_stream)) {
fwd_rsti->setSelected(true);
rev_rsti->setSelected(true);
break;
}
}
}
}
ui->streamTreeWidget->blockSignals(false);
updateWidgets();
}
// Select all streams which don't have reverse stream
void RtpStreamDialog::on_actionFindReverseSingle_triggered()
{
ui->streamTreeWidget->blockSignals(true);
ui->streamTreeWidget->selectAll();
// Traverse all items and search reverse from current position till last
// item (NxN/2)
for (int fwd_row = 0; fwd_row < ui->streamTreeWidget->topLevelItemCount(); fwd_row++) {
RtpStreamTreeWidgetItem *fwd_rsti = static_cast<RtpStreamTreeWidgetItem*>(ui->streamTreeWidget->topLevelItem(fwd_row));
rtpstream_info_t *fwd_stream = fwd_rsti->streamInfo();
if (fwd_stream) {
for (int rev_row = fwd_row + 1; rev_row < ui->streamTreeWidget->topLevelItemCount(); rev_row++) {
RtpStreamTreeWidgetItem *rev_rsti = static_cast<RtpStreamTreeWidgetItem*>(ui->streamTreeWidget->topLevelItem(rev_row));
rtpstream_info_t *rev_stream = rev_rsti->streamInfo();
if (rev_stream && rtpstream_info_is_reverse(fwd_stream, rev_stream)) {
fwd_rsti->setSelected(false);
rev_rsti->setSelected(false);
break;
}
}
}
}
ui->streamTreeWidget->blockSignals(false);
updateWidgets();
}
void RtpStreamDialog::on_actionGoToSetup_triggered()
{
if (ui->streamTreeWidget->selectedItems().count() < 1) return;
// XXX If the user selected multiple frames is this the one we actually want?
QTreeWidgetItem *ti = ui->streamTreeWidget->selectedItems()[0];
RtpStreamTreeWidgetItem *rsti = static_cast<RtpStreamTreeWidgetItem*>(ti);
rtpstream_info_t *stream_info = rsti->streamInfo();
if (stream_info) {
emit goToPacket(stream_info->setup_frame_number);
}
}
void RtpStreamDialog::on_actionMarkPackets_triggered()
{
if (ui->streamTreeWidget->selectedItems().count() < 1) return;
rtpstream_info_t *stream_a, *stream_b = NULL;
QTreeWidgetItem *ti = ui->streamTreeWidget->selectedItems()[0];
RtpStreamTreeWidgetItem *rsti = static_cast<RtpStreamTreeWidgetItem*>(ti);
stream_a = rsti->streamInfo();
if (ui->streamTreeWidget->selectedItems().count() > 1) {
ti = ui->streamTreeWidget->selectedItems()[1];
rsti = static_cast<RtpStreamTreeWidgetItem*>(ti);
stream_b = rsti->streamInfo();
}
if (stream_a == NULL && stream_b == NULL) return;
// XXX Mark the setup frame as well?
need_redraw_ = false;
rtpstream_mark(&tapinfo_, cap_file_.capFile(), stream_a, stream_b);
updateWidgets();
}
void RtpStreamDialog::on_actionPrepareFilter_triggered()
{
QVector<rtpstream_id_t *> ids = getSelectedRtpIds();
QString filter = make_filter_based_on_rtpstream_id(ids);
if (filter.length() > 0) {
remove_tap_listener_rtpstream(&tapinfo_);
emit updateFilter(filter);
}
}
void RtpStreamDialog::on_streamTreeWidget_itemSelectionChanged()
{
updateWidgets();
}
void RtpStreamDialog::on_buttonBox_helpRequested()
{
mainApp->helpTopicAction(HELP_TELEPHONY_RTP_STREAMS_DIALOG);
}
void RtpStreamDialog::displayFilterCheckBoxToggled(bool checked)
{
if (!cap_file_.isValid()) {
return;
}
tapinfo_.apply_display_filter = checked;
cap_file_.retapPackets();
}
void RtpStreamDialog::on_todCheckBox_toggled(bool checked)
{
QTreeWidgetItemIterator iter(ui->streamTreeWidget);
while (*iter) {
RtpStreamTreeWidgetItem *rsti = static_cast<RtpStreamTreeWidgetItem*>(*iter);
rsti->setTOD(checked);
rsti->drawData();
++iter;
}
ui->streamTreeWidget->resizeColumnToContents(start_time_col_);
}
void RtpStreamDialog::on_actionSelectAll_triggered()
{
ui->streamTreeWidget->selectAll();
}
void RtpStreamDialog::on_actionSelectInvert_triggered()
{
invertSelection();
}
void RtpStreamDialog::on_actionSelectNone_triggered()
{
ui->streamTreeWidget->clearSelection();
}
QVector<rtpstream_id_t *>RtpStreamDialog::getSelectedRtpIds()
{
// Gather up our selected streams...
QVector<rtpstream_id_t *> stream_ids;
foreach(QTreeWidgetItem *ti, ui->streamTreeWidget->selectedItems()) {
RtpStreamTreeWidgetItem *rsti = static_cast<RtpStreamTreeWidgetItem*>(ti);
rtpstream_info_t *selected_stream = rsti->streamInfo();
if (selected_stream) {
stream_ids << &(selected_stream->id);
}
}
return stream_ids;
}
void RtpStreamDialog::rtpPlayerReplace()
{
if (ui->streamTreeWidget->selectedItems().count() < 1) return;
emit rtpPlayerDialogReplaceRtpStreams(getSelectedRtpIds());
}
void RtpStreamDialog::rtpPlayerAdd()
{
if (ui->streamTreeWidget->selectedItems().count() < 1) return;
emit rtpPlayerDialogAddRtpStreams(getSelectedRtpIds());
}
void RtpStreamDialog::rtpPlayerRemove()
{
if (ui->streamTreeWidget->selectedItems().count() < 1) return;
emit rtpPlayerDialogRemoveRtpStreams(getSelectedRtpIds());
}
void RtpStreamDialog::rtpAnalysisReplace()
{
if (ui->streamTreeWidget->selectedItems().count() < 1) return;
emit rtpAnalysisDialogReplaceRtpStreams(getSelectedRtpIds());
}
void RtpStreamDialog::rtpAnalysisAdd()
{
if (ui->streamTreeWidget->selectedItems().count() < 1) return;
emit rtpAnalysisDialogAddRtpStreams(getSelectedRtpIds());
}
void RtpStreamDialog::rtpAnalysisRemove()
{
if (ui->streamTreeWidget->selectedItems().count() < 1) return;
emit rtpAnalysisDialogRemoveRtpStreams(getSelectedRtpIds());
}
void RtpStreamDialog::displayFilterSuccess(bool success)
{
if (success && ui->displayFilterCheckBox->isChecked()) {
cap_file_.retapPackets();
}
}
void RtpStreamDialog::invertSelection()
{
ui->streamTreeWidget->blockSignals(true);
for (int row = 0; row < ui->streamTreeWidget->topLevelItemCount(); row++) {
QTreeWidgetItem *ti = ui->streamTreeWidget->topLevelItem(row);
ti->setSelected(!ti->isSelected());
}
ui->streamTreeWidget->blockSignals(false);
updateWidgets();
}
void RtpStreamDialog::on_actionAnalyze_triggered()
{
RtpStreamDialog::rtpAnalysisAdd();
} |
C/C++ | wireshark/ui/qt/rtp_stream_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 RTP_STREAM_DIALOG_H
#define RTP_STREAM_DIALOG_H
#include "wireshark_dialog.h"
#include <mutex>
#include "ui/rtp_stream.h"
#include "rtp_player_dialog.h"
#include <QToolButton>
#include <QMenu>
namespace Ui {
class RtpStreamDialog;
}
// Singleton by https://refactoring.guru/design-patterns/singleton/cpp/example#example-1
class RtpStreamDialog : public WiresharkDialog
{
Q_OBJECT
public:
/**
* Returns singleton
*/
static RtpStreamDialog *openRtpStreamDialog(QWidget &parent, CaptureFile &cf, QObject *packet_list);
/**
* Should not be clonnable and assignable
*/
RtpStreamDialog(RtpStreamDialog &other) = delete;
void operator=(const RtpStreamDialog &) = delete;
// Caller must provide ids which are immutable to recap
void selectRtpStream(QVector<rtpstream_id_t *> stream_ids);
// Caller must provide ids which are immutable to recap
void deselectRtpStream(QVector<rtpstream_id_t *> stream_ids);
signals:
// Tells the packet list to redraw. An alternative might be to add a
// cf_packet_marked callback to file.[ch] but that's synchronous and
// might incur too much overhead.
void packetsMarked();
void updateFilter(QString filter, bool force = false);
void goToPacket(int packet_num);
void rtpPlayerDialogReplaceRtpStreams(QVector<rtpstream_id_t *> stream_ids);
void rtpPlayerDialogAddRtpStreams(QVector<rtpstream_id_t *> stream_ids);
void rtpPlayerDialogRemoveRtpStreams(QVector<rtpstream_id_t *> stream_ids);
void rtpAnalysisDialogReplaceRtpStreams(QVector<rtpstream_id_t *> stream_infos);
void rtpAnalysisDialogAddRtpStreams(QVector<rtpstream_id_t *> stream_infos);
void rtpAnalysisDialogRemoveRtpStreams(QVector<rtpstream_id_t *> stream_infos);
public slots:
void displayFilterSuccess(bool success);
void rtpPlayerReplace();
void rtpPlayerAdd();
void rtpPlayerRemove();
void rtpAnalysisReplace();
void rtpAnalysisAdd();
void rtpAnalysisRemove();
protected:
explicit RtpStreamDialog(QWidget &parent, CaptureFile &cf);
~RtpStreamDialog();
bool eventFilter(QObject *obj, QEvent *event);
void captureFileClosing();
void captureFileClosed();
private:
static RtpStreamDialog *pinstance_;
static std::mutex mutex_;
Ui::RtpStreamDialog *ui;
rtpstream_tapinfo_t tapinfo_;
QToolButton *find_reverse_button_;
QPushButton *prepare_button_;
QPushButton *export_button_;
QPushButton *copy_button_;
QToolButton *analyze_button_;
QToolButton *player_button_;
QMenu ctx_menu_;
bool need_redraw_;
QList<rtpstream_id_t> last_selected_;
static void tapReset(rtpstream_tapinfo_t *tapinfo);
static void tapDraw(rtpstream_tapinfo_t *tapinfo);
static void tapMarkPacket(rtpstream_tapinfo_t *tapinfo, frame_data *fd);
void updateStreams();
void updateWidgets();
void showPlayer();
void setRtpStreamSelection(rtpstream_id_t *id, bool state);
QList<QVariant> streamRowData(int row) const;
void freeLastSelected();
void invertSelection();
QVector<rtpstream_id_t *>getSelectedRtpIds();
private slots:
void showStreamMenu(QPoint pos);
void on_actionCopyAsCsv_triggered();
void on_actionCopyAsYaml_triggered();
void on_actionFindReverseNormal_triggered();
void on_actionFindReversePair_triggered();
void on_actionFindReverseSingle_triggered();
void on_actionGoToSetup_triggered();
void on_actionMarkPackets_triggered();
void on_actionPrepareFilter_triggered();
void on_streamTreeWidget_itemSelectionChanged();
void on_buttonBox_helpRequested();
void on_actionExportAsRtpDump_triggered();
void captureEvent(CaptureEvent e);
void displayFilterCheckBoxToggled(bool checked);
void on_todCheckBox_toggled(bool checked);
void on_actionSelectAll_triggered();
void on_actionSelectInvert_triggered();
void on_actionSelectNone_triggered();
void on_actionAnalyze_triggered();
};
#endif // RTP_STREAM_DIALOG_H |
User Interface | wireshark/ui/qt/rtp_stream_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>RtpStreamDialog</class>
<widget class="QDialog" name="RtpStreamDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>600</width>
<height>460</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTreeWidget" name="streamTreeWidget">
<property name="selectionMode">
<enum>QAbstractItemView::MultiSelection</enum>
</property>
<property name="textElideMode">
<enum>Qt::ElideMiddle</enum>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="uniformRowHeights">
<bool>true</bool>
</property>
<property name="itemsExpandable">
<bool>false</bool>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
<property name="expandsOnDoubleClick">
<bool>false</bool>
</property>
<attribute name="headerDefaultSectionSize">
<number>50</number>
</attribute>
<column>
<property name="text">
<string>Source Address</string>
</property>
</column>
<column>
<property name="text">
<string>Source Port</string>
</property>
</column>
<column>
<property name="text">
<string>Destination Address</string>
</property>
</column>
<column>
<property name="text">
<string>Destination Port</string>
</property>
</column>
<column>
<property name="text">
<string>SSRC</string>
</property>
</column>
<column>
<property name="text">
<string>Start Time</string>
</property>
</column>
<column>
<property name="text">
<string>Duration</string>
</property>
</column>
<column>
<property name="text">
<string>Payload</string>
</property>
</column>
<column>
<property name="text">
<string>Packets</string>
</property>
</column>
<column>
<property name="text">
<string>Lost</string>
</property>
</column>
<column>
<property name="text">
<string>Min Delta (ms)</string>
</property>
</column>
<column>
<property name="text">
<string>Mean Delta (ms)</string>
</property>
</column>
<column>
<property name="text">
<string>Max Delta (ms)</string>
</property>
</column>
<column>
<property name="text">
<string>Min Jitter</string>
</property>
</column>
<column>
<property name="text">
<string>Mean Jitter</string>
</property>
</column>
<column>
<property name="text">
<string>Max Jitter</string>
</property>
</column>
<column>
<property name="text">
<string>Status</string>
</property>
</column>
</widget>
</item>
<item>
<widget class="QLabel" name="hintLabel">
<property name="text">
<string><small><i>A hint.</i></small></string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QCheckBox" name="displayFilterCheckBox">
<property name="toolTip">
<string><html><head/><body><p>Only show conversations matching the current display filter</p></body></html></string>
</property>
<property name="text">
<string>Limit to display filter</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="todCheckBox">
<property name="text">
<string>Time of Day</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Close|QDialogButtonBox::Help</set>
</property>
</widget>
</item>
</layout>
<action name="actionFindReverse">
<property name="text">
<string>Find &Reverse</string>
</property>
<property name="toolTip">
<string>All forward/reverse stream actions</string>
</property>
</action>
<action name="actionFindReverseNormal">
<property name="text">
<string>Find &Reverse</string>
</property>
<property name="toolTip">
<string>Find the reverse stream matching the selected forward stream.</string>
</property>
<property name="shortcut">
<string>R</string>
</property>
</action>
<action name="actionFindReversePair">
<property name="text">
<string>Find All &Pairs</string>
</property>
<property name="toolTip">
<string>Select all streams which are paired in forward/reverse relation</string>
</property>
<property name="shortcut">
<string>Shift+R</string>
</property>
</action>
<action name="actionFindReverseSingle">
<property name="text">
<string>Find Only &Singles</string>
</property>
<property name="toolTip">
<string>Find all streams which don't have paired reverse stream</string>
</property>
<property name="shortcut">
<string>Ctrl+R</string>
</property>
</action>
<widget class="QMenu" name="menuFindReverse">
<property name="title">
<string>Find &Reverse</string>
</property>
<property name="toolTipsVisible">
<bool>true</bool>
</property>
<addaction name="actionFindReverseNormal"/>
<addaction name="actionFindReversePair"/>
<addaction name="actionFindReverseSingle"/>
</widget>
<action name="actionMarkPackets">
<property name="text">
<string>Mark Packets</string>
</property>
<property name="toolTip">
<string>Mark the packets of the selected stream(s).</string>
</property>
<property name="shortcut">
<string>M</string>
</property>
</action>
<widget class="QMenu" name="menuSelect">
<property name="title">
<string>Select</string>
</property>
<property name="toolTipsVisible">
<bool>true</bool>
</property>
<addaction name="actionSelectAll"/>
<addaction name="actionSelectNone"/>
<addaction name="actionSelectInvert"/>
</widget>
<action name="actionSelectAll">
<property name="text">
<string>All</string>
</property>
<property name="toolTip">
<string>Select all</string>
</property>
<property name="shortcut">
<string notr="true">Ctrl+A</string>
</property>
</action>
<action name="actionSelectNone">
<property name="text">
<string>None</string>
</property>
<property name="toolTip">
<string>Clear selection</string>
</property>
<property name="shortcut">
<string notr="true">Ctrl+Shift+A</string>
</property>
</action>
<action name="actionSelectInvert">
<property name="text">
<string>Invert</string>
</property>
<property name="toolTip">
<string>Invert selection</string>
</property>
<property name="shortcut">
<string notr="true">Ctrl+I</string>
</property>
</action>
<action name="actionGoToSetup">
<property name="text">
<string>Go To Setup</string>
</property>
<property name="toolTip">
<string>Go to the setup packet for this stream.</string>
</property>
<property name="shortcut">
<string>G</string>
</property>
</action>
<action name="actionPrepareFilter">
<property name="text">
<string>Prepare &Filter</string>
</property>
<property name="toolTip">
<string>Prepare a filter matching the selected stream(s).</string>
</property>
<property name="shortcut">
<string>P</string>
</property>
</action>
<action name="actionExportAsRtpDump">
<property name="text">
<string>&Export</string>
</property>
<property name="toolTip">
<string>Export the stream payload as rtpdump</string>
</property>
<property name="shortcut">
<string>E</string>
</property>
</action>
<action name="actionAnalyze">
<property name="text">
<string>&Analyze</string>
</property>
<property name="toolTip">
<string>Open the analysis window for the selected stream(s) and add it to it</string>
</property>
<property name="shortcut">
<string>A</string>
</property>
</action>
<action name="actionCopyButton">
<property name="text">
<string>Cop&y</string>
</property>
<property name="toolTip">
<string>Open copy menu</string>
</property>
</action>
<action name="actionCopyAsCsv">
<property name="text">
<string>Copy as CSV</string>
</property>
<property name="toolTip">
<string>Copy stream list as CSV.</string>
</property>
</action>
<action name="actionCopyAsYaml">
<property name="text">
<string>Copy as YAML</string>
</property>
<property name="toolTip">
<string>Copy stream list as YAML.</string>
</property>
</action>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>RtpStreamDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>RtpStreamDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/scsi_service_response_time_dialog.cpp | /* scsi_service_response_time_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "scsi_service_response_time_dialog.h"
#include <algorithm>
#include <stdio.h>
#include <epan/srt_table.h>
#include <epan/conversation.h>
#include <epan/dissectors/packet-scsi.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <QComboBox>
#include <QHBoxLayout>
#include <QLabel>
ScsiServiceResponseTimeDialog::ScsiServiceResponseTimeDialog(QWidget &parent, CaptureFile &cf, struct register_srt *srt, const QString filter) :
ServiceResponseTimeDialog(parent, cf, srt, filter)
{
setRetapOnShow(false);
setHint(tr("<small><i>Select a command and enter a filter if desired, then press Apply.</i></small>"));
QHBoxLayout *filter_layout = filterLayout();
command_combo_ = new QComboBox(this);
filter_layout->insertStretch(0, 1);
filter_layout->insertWidget(0, command_combo_);
filter_layout->insertWidget(0, new QLabel(tr("Command:")));
setWindowSubtitle(tr("SCSI Service Response Times"));
QStringList commands;
commands << "SBC (disk)" << "SSC (tape)" << "MMC (cd/dvd)" << "SMC (tape robot)" << "OSD (object based)";
command_combo_->addItems(commands);
}
TapParameterDialog *ScsiServiceResponseTimeDialog::createScsiSrtDialog(QWidget &parent, const QString, const QString opt_arg, CaptureFile &cf)
{
QString filter;
bool have_args = false;
QString command;
// rpc,srt,scsi,command[,<filter>
QStringList args_l = QString(opt_arg).split(',');
if (args_l.length() > 0) {
command = args_l[0];
if (args_l.length() > 1) {
filter = QStringList(args_l.mid(1)).join(",");
}
have_args = true;
}
ScsiServiceResponseTimeDialog *scsi_dlg = new ScsiServiceResponseTimeDialog(parent, cf, get_srt_table_by_name("scsi"), filter);
if (have_args) {
if (!command.isEmpty()) {
scsi_dlg->setScsiCommand(command.toInt());
}
}
return scsi_dlg;
}
void ScsiServiceResponseTimeDialog::setScsiCommand(int command)
{
command_combo_->setCurrentIndex(command);
fillTree();
}
void ScsiServiceResponseTimeDialog::provideParameterData()
{
char* err;
QString command;
command = QString(",%1").arg(command_combo_->currentIndex());
scsistat_param(srt_, command.toStdString().c_str(), &err);
} |
C/C++ | wireshark/ui/qt/scsi_service_response_time_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 __SCSI_SERVICE_RESPONSE_TIME_DIALOG_H__
#define __SCSI_SERVICE_RESPONSE_TIME_DIALOG_H__
#include "service_response_time_dialog.h"
class QComboBox;
class ScsiServiceResponseTimeDialog : public ServiceResponseTimeDialog
{
Q_OBJECT
public:
ScsiServiceResponseTimeDialog(QWidget &parent, CaptureFile &cf, struct register_srt *srt, const QString filter);
static TapParameterDialog *createScsiSrtDialog(QWidget &parent, const QString, const QString opt_arg, CaptureFile &cf);
void setScsiCommand(int command);
protected:
virtual void provideParameterData();
private:
QComboBox *command_combo_;
};
#endif // __SCSI_SERVICE_RESPONSE_TIME_DIALOG_H__ |
C++ | wireshark/ui/qt/sctp_all_assocs_dialog.cpp | /* sctp_all_assocs_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "sctp_all_assocs_dialog.h"
#include <ui_sctp_all_assocs_dialog.h>
#include "sctp_assoc_analyse_dialog.h"
#include <ui/qt/utils/qt_ui_utils.h>
//#include "main_application.h"
#include "file.h"
#include "ui/qt/main_window.h"
#include <QWidget>
#include <QDir>
#include <QPushButton>
//#include <QDebug>
SCTPAllAssocsDialog::SCTPAllAssocsDialog(QWidget *parent, capture_file *cf) :
QDialog(parent),
ui(new Ui::SCTPAllAssocsDialog),
cap_file_(cf)
{
ui->setupUi(this);
Qt::WindowFlags flags = Qt::Window | Qt::WindowSystemMenuHint
| Qt::WindowMinimizeButtonHint
| Qt::WindowMaximizeButtonHint
| Qt::WindowCloseButtonHint;
this->setWindowFlags(flags);
fillTable();
}
SCTPAllAssocsDialog::~SCTPAllAssocsDialog()
{
delete ui;
}
void SCTPAllAssocsDialog::fillTable()
{
const sctp_allassocs_info_t *sctp_assocs;
GList *list;
const sctp_assoc_info_t* assinfo;
int numAssocs;
ui->assocList->setColumnHidden(0, true);
ui->assocList->setColumnWidth(1, 85);
ui->assocList->setColumnWidth(2, 85);
ui->assocList->setColumnWidth(3, 150);
ui->assocList->setColumnWidth(4, 150);
sctp_assocs = sctp_stat_get_info();
if (sctp_assocs->is_registered == FALSE) {
register_tap_listener_sctp_stat();
/* (redissect all packets) */
cf_retap_packets(cap_file_);
}
numAssocs = 0;
ui->assocList->setRowCount(static_cast<int>(g_list_length(sctp_assocs->assoc_info_list)));
list = g_list_first(sctp_assocs->assoc_info_list);
while (list) {
assinfo = gxx_list_data(const sctp_assoc_info_t*, list);
ui->assocList->setItem(numAssocs, 0, new QTableWidgetItem(QString("%1").arg(assinfo->assoc_id)));
ui->assocList->setItem(numAssocs, 1, new QTableWidgetItem(QString("%1").arg(assinfo->port1)));
ui->assocList->setItem(numAssocs, 2, new QTableWidgetItem(QString("%1").arg(assinfo->port2)));
ui->assocList->setItem(numAssocs, 3, new QTableWidgetItem(QString("%1").arg(assinfo->n_packets)));
ui->assocList->setItem(numAssocs, 4, new QTableWidgetItem(QString("%1").arg(assinfo->n_data_chunks)));
ui->assocList->setItem(numAssocs, 5, new QTableWidgetItem(QString("%1").arg(assinfo->n_data_bytes)));
list = gxx_list_next(list);
numAssocs++;
}
ui->analyseButton->setEnabled(false);
ui->setFilterButton->setEnabled(false);
connect(ui->assocList, SIGNAL(itemSelectionChanged()), this, SLOT(getSelectedItem()));
}
void SCTPAllAssocsDialog::getSelectedItem()
{
ui->analyseButton->setEnabled(true);
ui->setFilterButton->setEnabled(true);
ui->analyseButton->setFocus(Qt::OtherFocusReason);
selected_assoc_id = ui->assocList->item(ui->assocList->selectedItems().at(0)->row(), 0)->data(0).toInt();
}
void SCTPAllAssocsDialog::on_analyseButton_clicked()
{
const sctp_assoc_info_t* selected_assoc = SCTPAssocAnalyseDialog::findAssoc(this, selected_assoc_id);
if (!selected_assoc) return;
SCTPAssocAnalyseDialog *sctp_analyse = new SCTPAssocAnalyseDialog(this, selected_assoc, cap_file_);
connect(sctp_analyse, SIGNAL(filterPackets(QString&,bool)),
parent(), SLOT(filterPackets(QString&,bool)));
if (sctp_analyse->isMinimized() == true)
{
sctp_analyse->showNormal();
}
else
{
sctp_analyse->show();
}
sctp_analyse->raise();
sctp_analyse->activateWindow();
}
void SCTPAllAssocsDialog::on_setFilterButton_clicked()
{
QString newFilter = QString("sctp.assoc_index==%1").arg(selected_assoc_id);
emit filterPackets(newFilter, false);
} |
C/C++ | wireshark/ui/qt/sctp_all_assocs_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 SCTP_ALL_ASSOCS_DIALOG_H
#define SCTP_ALL_ASSOCS_DIALOG_H
#include <config.h>
#include <glib.h>
#include <file.h>
#include <epan/dissectors/packet-sctp.h>
#include "ui/tap-sctp-analysis.h"
#include <QDialog>
#include <QObject>
namespace Ui {
class SCTPAllAssocsDialog;
}
class SCTPAllAssocsDialog : public QDialog
{
Q_OBJECT
public:
explicit SCTPAllAssocsDialog(QWidget *parent = 0, capture_file *cf = NULL);
~SCTPAllAssocsDialog();
void fillTable();
public slots:
void setCaptureFile(capture_file *cf) { cap_file_ = cf; }
private slots:
void on_analyseButton_clicked();
void on_setFilterButton_clicked();
void getSelectedItem();
private:
Ui::SCTPAllAssocsDialog *ui;
capture_file *cap_file_;
guint16 selected_assoc_id;
signals:
void filterPackets(QString new_filter, bool force);
};
#endif // SCTP_ALL_ASSOCS_DIALOG_H |
User Interface | wireshark/ui/qt/sctp_all_assocs_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SCTPAllAssocsDialog</class>
<widget class="QDialog" name="SCTPAllAssocsDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>827</width>
<height>546</height>
</rect>
</property>
<property name="windowTitle">
<string>Wireshark - SCTP Associations</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTableWidget" name="assocList">
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<property name="showDropIndicator" stdset="0">
<bool>false</bool>
</property>
<property name="dragDropOverwriteMode">
<bool>false</bool>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::SingleSelection</enum>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectRows</enum>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
<property name="wordWrap">
<bool>false</bool>
</property>
<property name="rowCount">
<number>2</number>
</property>
<property name="columnCount">
<number>6</number>
</property>
<attribute name="horizontalHeaderMinimumSectionSize">
<number>50</number>
</attribute>
<attribute name="horizontalHeaderDefaultSectionSize">
<number>120</number>
</attribute>
<attribute name="horizontalHeaderStretchLastSection">
<bool>true</bool>
</attribute>
<row/>
<row/>
<column>
<property name="text">
<string>ID</string>
</property>
</column>
<column>
<property name="text">
<string>Port 1</string>
</property>
</column>
<column>
<property name="text">
<string>Port 2</string>
</property>
</column>
<column>
<property name="text">
<string>Number of Packets</string>
</property>
</column>
<column>
<property name="text">
<string>Number of DATA Chunks</string>
</property>
</column>
<column>
<property name="text">
<string>Number of Bytes</string>
</property>
</column>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout"/>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QPushButton" name="setFilterButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="focusPolicy">
<enum>Qt::ClickFocus</enum>
</property>
<property name="text">
<string>Filter Selected Association</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="analyseButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="focusPolicy">
<enum>Qt::ClickFocus</enum>
</property>
<property name="text">
<string>Analyze</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>10</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Close</set>
</property>
</widget>
</item>
</layout>
</item>
</layout>
<action name="actionReset">
<property name="text">
<string>Reset Graph</string>
</property>
<property name="toolTip">
<string>Reset the graph to its initial state.</string>
</property>
<property name="shortcut">
<string>0</string>
</property>
</action>
<action name="actionZoomIn">
<property name="text">
<string>Zoom In</string>
</property>
<property name="toolTip">
<string>Zoom In</string>
</property>
<property name="shortcut">
<string>+</string>
</property>
</action>
<action name="actionZoomOut">
<property name="text">
<string>Zoom Out</string>
</property>
<property name="toolTip">
<string>Zoom Out</string>
</property>
<property name="shortcut">
<string>-</string>
</property>
</action>
<action name="actionMoveUp10">
<property name="text">
<string>Move Up 10 Pixels</string>
</property>
<property name="toolTip">
<string>Move Up 10 Pixels</string>
</property>
<property name="shortcut">
<string>Up</string>
</property>
</action>
<action name="actionMoveLeft10">
<property name="text">
<string>Move Left 10 Pixels</string>
</property>
<property name="toolTip">
<string>Move Left 10 Pixels</string>
</property>
<property name="shortcut">
<string>Left</string>
</property>
</action>
<action name="actionMoveRight10">
<property name="text">
<string>Move Right 10 Pixels</string>
</property>
<property name="toolTip">
<string>Move Right 10 Pixels</string>
</property>
<property name="shortcut">
<string>Right</string>
</property>
</action>
<action name="actionMoveDown10">
<property name="text">
<string>Move Down 10 Pixels</string>
</property>
<property name="toolTip">
<string>Move Down 10 Pixels</string>
</property>
<property name="shortcut">
<string>Down</string>
</property>
</action>
<action name="actionMoveUp1">
<property name="text">
<string>Move Up 1 Pixel</string>
</property>
<property name="toolTip">
<string>Move Up 1 Pixel</string>
</property>
<property name="shortcut">
<string>Shift+Up</string>
</property>
</action>
<action name="actionMoveLeft1">
<property name="text">
<string>Move Left 1 Pixel</string>
</property>
<property name="toolTip">
<string>Move Left 1 Pixel</string>
</property>
<property name="shortcut">
<string>Shift+Left</string>
</property>
</action>
<action name="actionMoveRight1">
<property name="text">
<string>Move Right 1 Pixel</string>
</property>
<property name="toolTip">
<string>Move Right 1 Pixel</string>
</property>
<property name="shortcut">
<string>Shift+Right</string>
</property>
</action>
<action name="actionMoveDown1">
<property name="text">
<string>Move Down 1 Pixel</string>
</property>
<property name="toolTip">
<string>Move Down 1 Pixel</string>
</property>
<property name="shortcut">
<string>Shift+Down</string>
</property>
</action>
<action name="actionNextStream">
<property name="text">
<string>Next Stream</string>
</property>
<property name="toolTip">
<string>Go to the next stream in the capture</string>
</property>
<property name="shortcut">
<string>PgUp</string>
</property>
</action>
<action name="actionPreviousStream">
<property name="text">
<string>Previous Stream</string>
</property>
<property name="toolTip">
<string>Go to the previous stream in the capture</string>
</property>
<property name="shortcut">
<string>PgDown</string>
</property>
</action>
<action name="actionSwitchDirection">
<property name="text">
<string>Switch Direction</string>
</property>
<property name="toolTip">
<string>Switch direction (swap TCP endpoints)</string>
</property>
<property name="shortcut">
<string>D</string>
</property>
</action>
<action name="actionGoToPacket">
<property name="text">
<string>Go To Packet Under Cursor</string>
</property>
<property name="toolTip">
<string>Go to packet currently under the cursor</string>
</property>
<property name="shortcut">
<string>G</string>
</property>
</action>
<action name="actionDragZoom">
<property name="text">
<string>Drag / Zoom</string>
</property>
<property name="toolTip">
<string>Toggle mouse drag / zoom behavior</string>
</property>
<property name="shortcut">
<string>Z</string>
</property>
</action>
<action name="actionToggleSequenceNumbers">
<property name="text">
<string>Relative / Absolute Sequence Numbers</string>
</property>
<property name="toolTip">
<string>Toggle relative / absolute sequence numbers</string>
</property>
<property name="shortcut">
<string>S</string>
</property>
</action>
<action name="actionToggleTimeOrigin">
<property name="text">
<string>Capture / Session Time Origin</string>
</property>
<property name="toolTip">
<string>Toggle capture / session time origin</string>
</property>
<property name="shortcut">
<string>T</string>
</property>
</action>
<action name="actionCrosshairs">
<property name="text">
<string>Crosshairs</string>
</property>
<property name="toolTip">
<string>Toggle crosshairs</string>
</property>
<property name="shortcut">
<string>Space</string>
</property>
</action>
<action name="actionRoundTripTime">
<property name="text">
<string>Round Trip Time</string>
</property>
<property name="toolTip">
<string>Switch to the Round Trip Time graph</string>
</property>
<property name="shortcut">
<string>1</string>
</property>
</action>
<action name="actionThroughput">
<property name="text">
<string>Throughput</string>
</property>
<property name="toolTip">
<string>Switch to the Throughput graph</string>
</property>
<property name="shortcut">
<string>2</string>
</property>
</action>
<action name="actionStevens">
<property name="text">
<string>Time / Sequence (Stevens)</string>
</property>
<property name="toolTip">
<string>Switch to the Stevens-style Time / Sequence graph</string>
</property>
<property name="shortcut">
<string>3</string>
</property>
</action>
<action name="actionWindowScaling">
<property name="text">
<string>Window Scaling</string>
</property>
<property name="toolTip">
<string>Switch to the Window Scaling graph</string>
</property>
<property name="shortcut">
<string>5</string>
</property>
</action>
<action name="actionTcptrace">
<property name="text">
<string>Time / Sequence (tcptrace)</string>
</property>
<property name="toolTip">
<string>Switch to the tcptrace-style Time / Sequence graph</string>
</property>
<property name="shortcut">
<string>4</string>
</property>
</action>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>clicked(QAbstractButton*)</signal>
<receiver>SCTPAllAssocsDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>644</x>
<y>274</y>
</hint>
<hint type="destinationlabel">
<x>659</x>
<y>322</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/sctp_assoc_analyse_dialog.cpp | /* sctp_assoc_analyse_dialog.cpp
*
* Copyright 2021 Thomas Dreibholz <dreibh [AT] iem.uni-due.de>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "epan/to_str.h"
#include "sctp_assoc_analyse_dialog.h"
#include <ui_sctp_assoc_analyse_dialog.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "sctp_graph_dialog.h"
#include "sctp_graph_arwnd_dialog.h"
#include "sctp_graph_byte_dialog.h"
#include "sctp_chunk_statistics_dialog.h"
SCTPAssocAnalyseDialog::SCTPAssocAnalyseDialog(QWidget *parent, const sctp_assoc_info_t *assoc,
capture_file *cf) :
QDialog(parent),
ui(new Ui::SCTPAssocAnalyseDialog),
cap_file_(cf)
{
Q_ASSERT(assoc);
selected_assoc_id = assoc->assoc_id;
ui->setupUi(this);
ui->SCTPAssocAnalyseTab->setCurrentWidget(ui->Statistics);
Qt::WindowFlags flags = Qt::Window | Qt::WindowSystemMenuHint
| Qt::WindowMinimizeButtonHint
| Qt::WindowCloseButtonHint;
this->setWindowFlags(flags);
this->setWindowTitle(QString(tr("SCTP Analyse Association: %1 Port1 %2 Port2 %3"))
.arg(gchar_free_to_qstring(cf_get_display_name(cap_file_))).arg(assoc->port1).arg(assoc->port2));
fillTabs(assoc);
}
SCTPAssocAnalyseDialog::~SCTPAssocAnalyseDialog()
{
delete ui;
}
const sctp_assoc_info_t* SCTPAssocAnalyseDialog::findAssocForPacket(capture_file* cf)
{
frame_data *fdata;
GList *list, *framelist;
const sctp_assoc_info_t *assoc;
bool frame_found = false;
fdata = cf->current_frame;
if (sctp_stat_get_info()->is_registered == FALSE) {
register_tap_listener_sctp_stat();
/* (redissect all packets) */
cf_retap_packets(cf);
}
list = g_list_first(sctp_stat_get_info()->assoc_info_list);
while (list) {
assoc = gxx_list_data(const sctp_assoc_info_t*, list);
framelist = g_list_first(assoc->frame_numbers);
guint32 fn;
while (framelist) {
fn = GPOINTER_TO_UINT(framelist->data);
if (fn == fdata->num) {
frame_found = TRUE;
break;
}
framelist = gxx_list_next(framelist);
}
if (frame_found) {
return assoc;
} else {
list = gxx_list_next(list);
}
}
if (!frame_found) {
QMessageBox msgBox;
msgBox.setText(tr("No Association found for this packet."));
msgBox.exec();
}
return Q_NULLPTR;
}
const _sctp_assoc_info* SCTPAssocAnalyseDialog::findAssoc(QWidget *parent, guint16 assoc_id)
{
const sctp_assoc_info_t* result = get_sctp_assoc_info(assoc_id);
if (result) return result;
QMessageBox::warning(parent, tr("Warning"), tr("Could not find SCTP Association with id: %1")
.arg(assoc_id));
return NULL;
}
void SCTPAssocAnalyseDialog::fillTabs(const sctp_assoc_info_t* selected_assoc)
{
Q_ASSERT(selected_assoc);
/* Statistics Tab */
ui->checksumLabel->setText(selected_assoc->checksum_type);
ui->data12Label->setText(QString("%1").arg(selected_assoc->n_data_chunks_ep1));
ui->bytes12Label->setText(QString("%1").arg(selected_assoc->n_data_bytes_ep1));
ui->data21Label->setText(QString("%1").arg(selected_assoc->n_data_chunks_ep2));
ui->bytes21Label->setText(QString("%1").arg(selected_assoc->n_data_bytes_ep2));
/* Tab Endpoint 1 */
if (selected_assoc->init)
ui->labelEP1->setText(QString(tr("Complete list of IP addresses from INIT Chunk:")));
else if ((selected_assoc->initack) && (selected_assoc->initack_dir == 1))
ui->labelEP1->setText(QString(tr("Complete list of IP addresses from INIT_ACK Chunk:")));
else
ui->labelEP1->setText(QString(tr("List of Used IP Addresses")));
if (selected_assoc->addr1 != Q_NULLPTR) {
GList *list;
list = g_list_first(selected_assoc->addr1);
while (list) {
address *store;
store = gxx_list_data(address *, list);
if (store->type != AT_NONE) {
if ((store->type == AT_IPv4) || (store->type == AT_IPv6)) {
ui->listWidgetEP1->addItem(address_to_qstring(store));
}
}
list = gxx_list_next(list);
}
} else {
return;
}
ui->label_221->setText(QString("%1").arg(selected_assoc->port1));
ui->label_222->setText(QString("0x%1").arg(selected_assoc->verification_tag1, 0, 16));
if ((selected_assoc->init) ||
((selected_assoc->initack) && (selected_assoc->initack_dir == 1))) {
ui->label_213->setText(QString(tr("Requested Number of Inbound Streams:")));
ui->label_223->setText(QString("%1").arg(selected_assoc->instream1));
ui->label_214->setText(QString(tr("Minimum Number of Inbound Streams:")));
ui->label_224->setText(QString("%1").arg(((selected_assoc->instream1 > selected_assoc->outstream2) ?
selected_assoc->outstream2 : selected_assoc->instream1)));
ui->label_215->setText(QString(tr("Provided Number of Outbound Streams:")));
ui->label_225->setText(QString("%1").arg(selected_assoc->outstream1));
ui->label_216->setText(QString(tr("Minimum Number of Outbound Streams:")));
ui->label_226->setText(QString("%1").arg(((selected_assoc->outstream1 > selected_assoc->instream2) ?
selected_assoc->instream2 : selected_assoc->outstream1)));
} else {
ui->label_213->setText(QString(tr("Used Number of Inbound Streams:")));
ui->label_223->setText(QString("%1").arg(selected_assoc->instream1));
ui->label_214->setText(QString(tr("Used Number of Outbound Streams:")));
ui->label_224->setText(QString("%1").arg(selected_assoc->outstream1));
ui->label_215->setText(QString(""));
ui->label_225->setText(QString(""));
ui->label_216->setText(QString(""));
ui->label_226->setText(QString(""));
}
/* Tab Endpoint 2 */
if ((selected_assoc->initack) && (selected_assoc->initack_dir == 2))
ui->labelEP2->setText(QString(tr("Complete list of IP addresses from INIT_ACK Chunk:")));
else
ui->labelEP2->setText(QString(tr("List of Used IP Addresses")));
if (selected_assoc->addr2 != Q_NULLPTR) {
GList *list;
list = g_list_first(selected_assoc->addr2);
while (list) {
address *store;
store = gxx_list_data(address *, list);
if (store->type != AT_NONE) {
if ((store->type == AT_IPv4) || (store->type == AT_IPv6)) {
ui->listWidgetEP2->addItem(address_to_qstring(store));
}
}
list = gxx_list_next(list);
}
} else {
return;
}
ui->label_321->setText(QString("%1").arg(selected_assoc->port2));
ui->label_322->setText(QString("0x%1").arg(selected_assoc->verification_tag2, 0, 16));
if (selected_assoc->initack) {
ui->label_313->setText(QString(tr("Requested Number of Inbound Streams:")));
ui->label_323->setText(QString("%1").arg(selected_assoc->instream2));
ui->label_314->setText(QString(tr("Minimum Number of Inbound Streams:")));
ui->label_324->setText(QString("%1").arg(((selected_assoc->instream2 > selected_assoc->outstream1) ?
selected_assoc->outstream1 : selected_assoc->instream2)));
ui->label_315->setText(QString(tr("Provided Number of Outbound Streams:")));
ui->label_325->setText(QString("%1").arg(selected_assoc->outstream2));
ui->label_316->setText(QString(tr("Minimum Number of Outbound Streams:")));
ui->label_326->setText(QString("%1").arg(((selected_assoc->outstream2 > selected_assoc->instream1) ?
selected_assoc->instream1 : selected_assoc->outstream2)));
} else {
ui->label_313->setText(QString(tr("Used Number of Inbound Streams:")));
ui->label_323->setText(QString("%1").arg(selected_assoc->instream2));
ui->label_314->setText(QString(tr("Used Number of Outbound Streams:")));
ui->label_324->setText(QString("%1").arg(selected_assoc->outstream2));
ui->label_315->setText(QString(""));
ui->label_325->setText(QString(""));
ui->label_316->setText(QString(""));
ui->label_326->setText(QString(""));
}
}
void SCTPAssocAnalyseDialog::openGraphDialog(int direction)
{
const sctp_assoc_info_t* selected_assoc = SCTPAssocAnalyseDialog::findAssoc(this, selected_assoc_id);
if (!selected_assoc) return;
SCTPGraphDialog *sctp_dialog = new SCTPGraphDialog(this, selected_assoc, cap_file_, direction);
if (sctp_dialog->isMinimized() == true) {
sctp_dialog->showNormal();
} else {
sctp_dialog->show();
}
sctp_dialog->raise();
sctp_dialog->activateWindow();
}
void SCTPAssocAnalyseDialog::on_GraphTSN_2_clicked()
{
openGraphDialog(2);
}
void SCTPAssocAnalyseDialog::on_GraphTSN_1_clicked()
{
openGraphDialog(1);
}
void SCTPAssocAnalyseDialog::on_chunkStatisticsButton_clicked()
{
const sctp_assoc_info_t* selected_assoc = SCTPAssocAnalyseDialog::findAssoc(this, selected_assoc_id);
if (!selected_assoc) return;
SCTPChunkStatisticsDialog *sctp_dialog = new SCTPChunkStatisticsDialog(this, selected_assoc, cap_file_);
if (sctp_dialog->isMinimized() == true) {
sctp_dialog->showNormal();
} else {
sctp_dialog->show();
}
sctp_dialog->raise();
sctp_dialog->activateWindow();
}
void SCTPAssocAnalyseDialog::on_setFilterButton_clicked()
{
QString newFilter = QString("sctp.assoc_index==%1").arg(selected_assoc_id);
emit filterPackets(newFilter, false);
}
void SCTPAssocAnalyseDialog::openGraphByteDialog(int direction)
{
const sctp_assoc_info_t* selected_assoc = SCTPAssocAnalyseDialog::findAssoc(this, selected_assoc_id);
if (!selected_assoc) return;
SCTPGraphByteDialog *sctp_dialog = new SCTPGraphByteDialog(this, selected_assoc, cap_file_, direction);
if (sctp_dialog->isMinimized() == true) {
sctp_dialog->showNormal();
} else {
sctp_dialog->show();
}
sctp_dialog->raise();
sctp_dialog->activateWindow();
}
void SCTPAssocAnalyseDialog::on_GraphBytes_1_clicked()
{
openGraphByteDialog(1);
}
void SCTPAssocAnalyseDialog::on_GraphBytes_2_clicked()
{
openGraphByteDialog(2);
}
void SCTPAssocAnalyseDialog::openGraphArwndDialog(int direction)
{
const sctp_assoc_info_t* selected_assoc = SCTPAssocAnalyseDialog::findAssoc(this, selected_assoc_id);
if (!selected_assoc) return;
SCTPGraphArwndDialog *sctp_dialog = new SCTPGraphArwndDialog(this, selected_assoc, cap_file_, direction);
if (sctp_dialog->isMinimized() == true) {
sctp_dialog->showNormal();
} else {
sctp_dialog->show();
}
sctp_dialog->raise();
sctp_dialog->activateWindow();
}
void SCTPAssocAnalyseDialog::on_GraphArwnd_1_clicked()
{
openGraphArwndDialog(1);
}
void SCTPAssocAnalyseDialog::on_GraphArwnd_2_clicked()
{
openGraphArwndDialog(2);
} |
C/C++ | wireshark/ui/qt/sctp_assoc_analyse_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 SCTP_ASSOC_ANALYSE_DIALOG_H
#define SCTP_ASSOC_ANALYSE_DIALOG_H
#include <config.h>
#include <glib.h>
#include <file.h>
#include <epan/dissectors/packet-sctp.h>
#include "sctp_all_assocs_dialog.h"
#include <QDialog>
#include <QTabWidget>
#include <QObject>
#include <QGridLayout>
#include <QMessageBox>
namespace Ui {
class SCTPAssocAnalyseDialog;
}
struct _sctp_assoc_info;
class SCTPAssocAnalyseDialog : public QDialog
{
Q_OBJECT
public:
explicit SCTPAssocAnalyseDialog(QWidget *parent = 0, const _sctp_assoc_info *assoc = NULL,
capture_file *cf = NULL);
~SCTPAssocAnalyseDialog();
void fillTabs(const _sctp_assoc_info* selected_assoc);
static const _sctp_assoc_info* findAssocForPacket(capture_file* cf);
static const _sctp_assoc_info* findAssoc(QWidget *parent, guint16 assoc_id);
public slots:
void setCaptureFile(capture_file *cf) { cap_file_ = cf; }
private slots:
void on_GraphTSN_2_clicked();
void on_GraphTSN_1_clicked();
void on_chunkStatisticsButton_clicked();
void on_setFilterButton_clicked();
void on_GraphBytes_1_clicked();
void on_GraphBytes_2_clicked();
void on_GraphArwnd_1_clicked();
void on_GraphArwnd_2_clicked();
private:
Ui::SCTPAssocAnalyseDialog *ui;
guint16 selected_assoc_id;
capture_file *cap_file_;
void openGraphDialog(int direction);
void openGraphByteDialog(int direction);
void openGraphArwndDialog(int direction);
signals:
void filterPackets(QString new_filter, bool force);
};
#endif // SCTP_ASSOC_ANALYSE_DIALOG_H |
User Interface | wireshark/ui/qt/sctp_assoc_analyse_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SCTPAssocAnalyseDialog</class>
<widget class="QDialog" name="SCTPAssocAnalyseDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>826</width>
<height>672</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Wireshark - Analyse Association</string>
</property>
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<widget class="QTabWidget" name="SCTPAssocAnalyseTab">
<property name="geometry">
<rect>
<x>5</x>
<y>10</y>
<width>821</width>
<height>661</height>
</rect>
</property>
<property name="windowTitle">
<string>TabWidget</string>
</property>
<property name="currentIndex">
<number>2</number>
</property>
<widget class="QWidget" name="Statistics">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<attribute name="title">
<string>Statistics</string>
</attribute>
<widget class="QWidget" name="gridLayoutWidget_3">
<property name="geometry">
<rect>
<x>20</x>
<y>40</y>
<width>781</width>
<height>231</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout_3">
<item row="2" column="0">
<widget class="QLabel" name="label_13">
<property name="text">
<string>Number of Data Bytes from EP1 to EP2:</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QLabel" name="data21Label">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="label_18">
<property name="text">
<string>Number of Data Bytes from EP2 to EP1: </string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label_15">
<property name="text">
<string>Checksum Type:</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLabel" name="bytes12Label">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QLabel" name="bytes21Label">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLabel" name="data12Label">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="label_17">
<property name="text">
<string>Number of Data Chunks from EP2 to EP1: </string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLabel" name="checksumLabel">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_16">
<property name="text">
<string>Number of Data Chunks from EP1 to EP2: </string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="gridLayoutWidget_4">
<property name="geometry">
<rect>
<x>10</x>
<y>540</y>
<width>791</width>
<height>55</height>
</rect>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="setFilterButton">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Filter Association</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="chunkStatisticsButton">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Chunk Statistics</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Close</string>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<widget class="QWidget" name="Endpoint_1">
<attribute name="title">
<string>Endpoint 1</string>
</attribute>
<widget class="QLabel" name="labelEP1">
<property name="geometry">
<rect>
<x>10</x>
<y>10</y>
<width>791</width>
<height>41</height>
</rect>
</property>
<property name="text">
<string>Complete List of IP addresses from INIT Chunk:</string>
</property>
</widget>
<widget class="QWidget" name="gridLayoutWidget">
<property name="geometry">
<rect>
<x>10</x>
<y>210</y>
<width>791</width>
<height>301</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="5" column="1">
<widget class="QLabel" name="label_226">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QLabel" name="label_224">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLabel" name="label_222">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QLabel" name="label_216">
<property name="text">
<string>Minimum Number of Outbound Streams:</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="label_215">
<property name="text">
<string>Provided Number of Outbound Streams:</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="label_214">
<property name="text">
<string>Minimum Number of Inbound Streams:</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_212">
<property name="text">
<string>Sent Verification Tag:</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QLabel" name="label_225">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label_211">
<property name="text">
<string>Port:</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLabel" name="label_223">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLabel" name="label_221">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="label_213">
<property name="text">
<string>Requested Number of Inbound Streams:</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QListWidget" name="listWidgetEP1">
<property name="geometry">
<rect>
<x>10</x>
<y>60</y>
<width>791</width>
<height>141</height>
</rect>
</property>
</widget>
<widget class="QWidget" name="gridLayoutWidget_5">
<property name="geometry">
<rect>
<x>10</x>
<y>540</y>
<width>791</width>
<height>55</height>
</rect>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QPushButton" name="GraphBytes_1">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Graph Bytes</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="GraphTSN_1">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Graph TSN</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="GraphArwnd_1">
<property name="text">
<string>Graph Arwnd</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_2">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Close</string>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<widget class="QWidget" name="Endpoint_2">
<attribute name="title">
<string>Endpoint 2</string>
</attribute>
<widget class="QWidget" name="gridLayoutWidget_2">
<property name="geometry">
<rect>
<x>10</x>
<y>210</y>
<width>791</width>
<height>301</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="2" column="0">
<widget class="QLabel" name="label_313">
<property name="text">
<string>Requested Number of Inbound Streams:</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QLabel" name="label_324">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLabel" name="label_321">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_312">
<property name="text">
<string>Sent Verification Tag:</string>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QLabel" name="label_316">
<property name="text">
<string>Minimum Number of Outbound Streams:</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label_311">
<property name="text">
<string>Port:</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="label_314">
<property name="text">
<string>Minimum Number of Inbound Streams:</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLabel" name="label_322">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLabel" name="label_323">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QLabel" name="label_326">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="label_315">
<property name="text">
<string>Provided Number of Outbound Streams:</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QLabel" name="label_325">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QLabel" name="labelEP2">
<property name="geometry">
<rect>
<x>10</x>
<y>10</y>
<width>791</width>
<height>41</height>
</rect>
</property>
<property name="text">
<string>Complete List of IP addresses from INIT_ACK Chunk:</string>
</property>
</widget>
<widget class="QListWidget" name="listWidgetEP2">
<property name="geometry">
<rect>
<x>10</x>
<y>60</y>
<width>791</width>
<height>141</height>
</rect>
</property>
</widget>
<widget class="QWidget" name="horizontalLayoutWidget">
<property name="geometry">
<rect>
<x>10</x>
<y>540</y>
<width>791</width>
<height>55</height>
</rect>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QPushButton" name="GraphBytes_2">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Graph Bytes</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="GraphTSN_2">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Graph TSN</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="GraphArwnd_2">
<property name="text">
<string>Graph Arwnd</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_3">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Close</string>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</widget>
</widget>
<resources/>
<connections>
<connection>
<sender>pushButton_2</sender>
<signal>clicked()</signal>
<receiver>SCTPAssocAnalyseDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>471</x>
<y>365</y>
</hint>
<hint type="destinationlabel">
<x>475</x>
<y>384</y>
</hint>
</hints>
</connection>
<connection>
<sender>pushButton</sender>
<signal>clicked()</signal>
<receiver>SCTPAssocAnalyseDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>494</x>
<y>361</y>
</hint>
<hint type="destinationlabel">
<x>523</x>
<y>433</y>
</hint>
</hints>
</connection>
<connection>
<sender>pushButton_3</sender>
<signal>clicked()</signal>
<receiver>SCTPAssocAnalyseDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>502</x>
<y>362</y>
</hint>
<hint type="destinationlabel">
<x>520</x>
<y>459</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/sctp_chunk_statistics_dialog.cpp | /* sctp_chunk_statistics_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "sctp_chunk_statistics_dialog.h"
#include "sctp_assoc_analyse_dialog.h"
#include <ui_sctp_chunk_statistics_dialog.h>
#include "uat_dialog.h"
#include <wsutil/strtoi.h>
#include <wsutil/wslog.h>
#include "ui/tap-sctp-analysis.h"
#include <ui/qt/utils/qt_ui_utils.h>
SCTPChunkStatisticsDialog::SCTPChunkStatisticsDialog(QWidget *parent, const sctp_assoc_info_t *assoc,
capture_file *cf) :
QDialog(parent),
ui(new Ui::SCTPChunkStatisticsDialog),
cap_file_(cf)
{
Q_ASSERT(assoc);
selected_assoc_id = assoc->assoc_id;
ui->setupUi(this);
Qt::WindowFlags flags = Qt::Window | Qt::WindowSystemMenuHint
| Qt::WindowMinimizeButtonHint
| Qt::WindowMaximizeButtonHint
| Qt::WindowCloseButtonHint;
this->setWindowFlags(flags);
ui->tableWidget->verticalHeader()->setSectionsClickable(true);
ui->tableWidget->verticalHeader()->setSectionsMovable(true);
ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
this->setWindowTitle(QString(tr("SCTP Chunk Statistics: %1 Port1 %2 Port2 %3"))
.arg(gchar_free_to_qstring(cf_get_display_name(cap_file_)))
.arg(assoc->port1).arg(assoc->port2));
// connect(ui->tableWidget->verticalHeader(), &QHeaderView::sectionMoved, this, &SCTPChunkStatisticsDialog::on_sectionMoved);
ctx_menu_.addAction(ui->actionHideChunkType);
ctx_menu_.addAction(ui->actionChunkTypePreferences);
ctx_menu_.addAction(ui->actionShowAllChunkTypes);
initializeChunkMap();
fillTable(false, assoc);
}
SCTPChunkStatisticsDialog::~SCTPChunkStatisticsDialog()
{
delete ui;
}
void SCTPChunkStatisticsDialog::initializeChunkMap()
{
struct chunkTypes temp;
gchar buf[16];
for (int i = 0; i < 256; i++) {
temp.id = i;
temp.row = i;
snprintf(buf, sizeof buf, "%d", i);
(void) g_strlcpy(temp.name, val_to_str_const(i, chunk_type_values, "NA"), sizeof temp.name);
if (strcmp(temp.name, "NA") == 0) {
temp.hide = 1;
(void) g_strlcpy(temp.name, buf, sizeof temp.name);
} else {
temp.hide = 0;
}
chunks.insert(i, temp);
}
}
void SCTPChunkStatisticsDialog::fillTable(bool all, const sctp_assoc_info_t *selected_assoc)
{
if (!selected_assoc) {
selected_assoc = SCTPAssocAnalyseDialog::findAssoc(this, selected_assoc_id);
if (!selected_assoc) return;
}
FILE* fp = NULL;
pref_t *pref = prefs_find_preference(prefs_find_module("sctp"),"statistics_chunk_types");
if (!pref) {
ws_log(LOG_DOMAIN_QTUI, LOG_LEVEL_ERROR, "Can't find preference sctp/statistics_chunk_types");
return;
}
uat_t *uat = prefs_get_uat_value(pref);
gchar* fname = uat_get_actual_filename(uat,TRUE);
bool init = false;
if (!fname) {
init = true;
} else {
fp = ws_fopen(fname,"r");
if (!fp) {
if (errno == ENOENT) {
init = true;
} else {
ws_log(LOG_DOMAIN_QTUI, LOG_LEVEL_ERROR, "Can't open %s: %s", fname, g_strerror(errno));
return;
}
}
}
g_free (fname);
if (init || all) {
int i, j = 0;
for (i = 0; i < chunks.size(); i++) {
if (!chunks.value(i).hide) {
ui->tableWidget->setRowCount(ui->tableWidget->rowCount()+1);
ui->tableWidget->setVerticalHeaderItem(j, new QTableWidgetItem(QString("%1").arg(chunks.value(i).name)));
ui->tableWidget->setItem(j,0, new QTableWidgetItem(QString("%1").arg(selected_assoc->chunk_count[chunks.value(i).id])));
ui->tableWidget->setItem(j,1, new QTableWidgetItem(QString("%1").arg(selected_assoc->ep1_chunk_count[chunks.value(i).id])));
ui->tableWidget->setItem(j,2, new QTableWidgetItem(QString("%1").arg(selected_assoc->ep2_chunk_count[chunks.value(i).id])));
j++;
}
}
for (i = 0; i < chunks.size(); i++) {
if (chunks.value(i).hide) {
ui->tableWidget->setRowCount(ui->tableWidget->rowCount()+1);
ui->tableWidget->setVerticalHeaderItem(j, new QTableWidgetItem(QString("%1").arg(chunks.value(i).name)));
ui->tableWidget->setItem(j,0, new QTableWidgetItem(QString("%1").arg(selected_assoc->chunk_count[chunks.value(i).id])));
ui->tableWidget->setItem(j,1, new QTableWidgetItem(QString("%1").arg(selected_assoc->ep1_chunk_count[chunks.value(i).id])));
ui->tableWidget->setItem(j,2, new QTableWidgetItem(QString("%1").arg(selected_assoc->ep2_chunk_count[chunks.value(i).id])));
ui->tableWidget->hideRow(j);
j++;
}
}
} else {
char line[100];
char *token, id[5];
int i = 0, j = 0;
struct chunkTypes temp;
while (fgets(line, (int)sizeof line, fp)) {
if (line[0] == '#')
continue;
token = strtok(line, ",");
if (!token)
continue;
/* Get rid of the quotation marks */
QString ch = QString(token).mid(1, (int)strlen(token)-2);
(void) g_strlcpy(id, qPrintable(ch), sizeof id);
if (!ws_strtoi32(id, NULL, &temp.id))
continue;
temp.hide = 0;
temp.name[0] = '\0';
while (token != NULL) {
token = strtok(NULL, ",");
if (token) {
if ((strstr(token, "Hide"))) {
temp.hide = 1;
} else if ((strstr(token, "Show"))) {
temp.hide = 0;
} else {
QString ch2 = QString(token).mid(1, (int)strlen(token)-2);
(void) g_strlcpy(temp.name, qPrintable(ch2), sizeof temp.name);
}
}
}
if (!temp.hide) {
ui->tableWidget->setRowCount(ui->tableWidget->rowCount()+1);
ui->tableWidget->setVerticalHeaderItem(j, new QTableWidgetItem(QString("%1").arg(temp.name)));
ui->tableWidget->setItem(j,0, new QTableWidgetItem(QString("%1").arg(selected_assoc->chunk_count[temp.id])));
ui->tableWidget->setItem(j,1, new QTableWidgetItem(QString("%1").arg(selected_assoc->ep1_chunk_count[temp.id])));
ui->tableWidget->setItem(j,2, new QTableWidgetItem(QString("%1").arg(selected_assoc->ep2_chunk_count[temp.id])));
j++;
}
chunks.insert(i, temp);
i++;
}
j = ui->tableWidget->rowCount();
for (i = 0; i < chunks.size(); i++) {
if (chunks.value(i).hide) {
ui->tableWidget->setRowCount(ui->tableWidget->rowCount()+1);
ui->tableWidget->setVerticalHeaderItem(j, new QTableWidgetItem(QString("%1").arg(chunks.value(i).name)));
ui->tableWidget->setItem(j,0, new QTableWidgetItem(QString("%1").arg(selected_assoc->chunk_count[chunks.value(i).id])));
ui->tableWidget->setItem(j,1, new QTableWidgetItem(QString("%1").arg(selected_assoc->ep1_chunk_count[chunks.value(i).id])));
ui->tableWidget->setItem(j,2, new QTableWidgetItem(QString("%1").arg(selected_assoc->ep2_chunk_count[chunks.value(i).id])));
ui->tableWidget->hideRow(j);
j++;
}
}
}
if (fp)
fclose(fp);
}
void SCTPChunkStatisticsDialog::contextMenuEvent(QContextMenuEvent * event)
{
selected_point = event->pos();
QTableWidgetItem *item = ui->tableWidget->itemAt(selected_point.x(), selected_point.y()-60);
if (item) {
ctx_menu_.popup(event->globalPos());
}
}
void SCTPChunkStatisticsDialog::on_pushButton_clicked()
{
FILE* fp;
pref_t *pref = prefs_find_preference(prefs_find_module("sctp"),"statistics_chunk_types");
if (!pref) {
ws_log(LOG_DOMAIN_QTUI, LOG_LEVEL_ERROR, "Can't find preference sctp/statistics_chunk_types");
return;
}
uat_t *uat = prefs_get_uat_value(pref);
gchar* fname = uat_get_actual_filename(uat,TRUE);
if (!fname) {
return;
}
fp = ws_fopen(fname,"w");
if (!fp && errno == ENOENT) {
gchar *pf_dir_path = NULL;
if (create_persconffile_dir(&pf_dir_path) != 0) {
g_free (pf_dir_path);
return;
}
fp = ws_fopen(fname,"w");
}
if (!fp) {
return;
}
g_free (fname);
fprintf(fp,"# This file is automatically generated, DO NOT MODIFY.\n");
char str[40];
struct chunkTypes tempChunk;
for (int i = 0; i < chunks.size(); i++) {
tempChunk = chunks.value(i);
snprintf(str, sizeof str, "\"%d\",\"%s\",\"%s\"\n", tempChunk.id, tempChunk.name, tempChunk.hide==0?"Show":"Hide");
fputs(str, fp);
void *rec = g_malloc0(uat->record_size);
uat_add_record(uat, rec, TRUE);
if (uat->free_cb) {
uat->free_cb(rec);
}
g_free(rec);
}
fclose(fp);
}
/*void SCTPChunkStatisticsDialog::on_sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex)
{
}*/
void SCTPChunkStatisticsDialog::on_actionHideChunkType_triggered()
{
int row;
QTableWidgetItem *itemPoint = ui->tableWidget->itemAt(selected_point.x(), selected_point.y()-60);
if (itemPoint) {
row = itemPoint->row();
ui->tableWidget->hideRow(row);
QTableWidgetItem *item = ui->tableWidget->verticalHeaderItem(row);
QMap<int, struct chunkTypes>::iterator iter;
for (iter = chunks.begin(); iter != chunks.end(); ++iter) {
if (strcmp(iter.value().name, item->text().toUtf8().constData()) == 0) {
iter.value().hide = true;
break;
}
}
}
}
void SCTPChunkStatisticsDialog::on_actionChunkTypePreferences_triggered()
{
gchar* err = NULL;
pref_t *pref = prefs_find_preference(prefs_find_module("sctp"),"statistics_chunk_types");
if (!pref) {
ws_log(LOG_DOMAIN_QTUI, LOG_LEVEL_ERROR, "Can't find preference sctp/statistics_chunk_types");
return;
}
uat_t *uat = prefs_get_uat_value(pref);
uat_clear(uat);
if (!uat_load(uat, NULL, &err)) {
/* XXX - report this through the GUI */
ws_log(LOG_DOMAIN_QTUI, LOG_LEVEL_WARNING, "Error loading table '%s': %s", uat->name, err);
g_free(err);
}
UatDialog *uatdialog = new UatDialog(this, uat);
uatdialog->exec();
// Emitting PacketDissectionChanged directly from a QDialog can cause
// problems on macOS.
mainApp->flushAppSignals();
ui->tableWidget->clear();
ui->tableWidget->setRowCount(0);
ui->tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem(QString(tr("Association"))));
ui->tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem(QString(tr("Endpoint 1"))));
ui->tableWidget->setHorizontalHeaderItem(2, new QTableWidgetItem(QString(tr("Endpoint 2"))));
fillTable();
}
void SCTPChunkStatisticsDialog::on_actionShowAllChunkTypes_triggered()
{
ui->tableWidget->clear();
ui->tableWidget->setRowCount(0);
ui->tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem(QString(tr("Association"))));
ui->tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem(QString(tr("Endpoint 1"))));
ui->tableWidget->setHorizontalHeaderItem(2, new QTableWidgetItem(QString(tr("Endpoint 2"))));
initializeChunkMap();
fillTable(true);
} |
C/C++ | wireshark/ui/qt/sctp_chunk_statistics_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 SCTP_CHUNK_STATISTICS_DIALOG_H
#define SCTP_CHUNK_STATISTICS_DIALOG_H
#include <config.h>
#include <glib.h>
#include <file.h>
#include <wsutil/file_util.h>
#include <epan/dissectors/packet-sctp.h>
#include "epan/packet.h"
#include "epan/value_string.h"
#include <epan/prefs.h>
#include <epan/uat-int.h>
#include <epan/prefs-int.h>
#include <wsutil/filesystem.h>
#include "wireshark_application.h"
#include <QTableWidgetItem>
#include <QDialog>
#include <QMenu>
#include <QContextMenuEvent>
namespace Ui {
class SCTPChunkStatisticsDialog;
}
struct _sctp_assoc_info;
class SCTPChunkStatisticsDialog : public QDialog
{
Q_OBJECT
public:
explicit SCTPChunkStatisticsDialog(QWidget *parent = 0, const _sctp_assoc_info *assoc = NULL, capture_file *cf = NULL);
~SCTPChunkStatisticsDialog();
public slots:
void setCaptureFile(capture_file *cf) { cap_file_ = cf; }
private slots:
// void on_sectionClicked(int row);
// void on_sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex);
void on_pushButton_clicked();
void on_actionHideChunkType_triggered();
void on_actionChunkTypePreferences_triggered();
void contextMenuEvent(QContextMenuEvent * event);
void on_actionShowAllChunkTypes_triggered();
signals:
// void sectionClicked(int);
// void sectionMoved(int, int, int);
private:
Ui::SCTPChunkStatisticsDialog *ui;
guint16 selected_assoc_id;
capture_file *cap_file_;
QMenu ctx_menu_;
QPoint selected_point;
struct chunkTypes {
int row;
int id;
int hide;
char name[30];
};
QMap<int, struct chunkTypes> chunks, tempChunks;
void initializeChunkMap();
void fillTable(bool all = false, const _sctp_assoc_info *selected_assoc = NULL);
};
#endif // SCTP_CHUNK_STATISTICS_DIALOG_H |
User Interface | wireshark/ui/qt/sctp_chunk_statistics_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SCTPChunkStatisticsDialog</class>
<widget class="QDialog" name="SCTPChunkStatisticsDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>830</width>
<height>673</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="geometry">
<rect>
<x>510</x>
<y>610</y>
<width>311</width>
<height>51</height>
</rect>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Close</set>
</property>
</widget>
<widget class="QTableWidget" name="tableWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>10</y>
<width>831</width>
<height>591</height>
</rect>
</property>
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::SingleSelection</enum>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectRows</enum>
</property>
<property name="rowCount">
<number>0</number>
</property>
<attribute name="horizontalHeaderCascadingSectionResizes">
<bool>false</bool>
</attribute>
<attribute name="horizontalHeaderStretchLastSection">
<bool>true</bool>
</attribute>
<attribute name="verticalHeaderCascadingSectionResizes">
<bool>false</bool>
</attribute>
<column>
<property name="text">
<string>Association</string>
</property>
</column>
<column>
<property name="text">
<string>Endpoint 1</string>
</property>
</column>
<column>
<property name="text">
<string>Endpoint 2</string>
</property>
</column>
</widget>
<widget class="QPushButton" name="pushButton">
<property name="geometry">
<rect>
<x>0</x>
<y>610</y>
<width>381</width>
<height>51</height>
</rect>
</property>
<property name="text">
<string>Save Chunk Type Order</string>
</property>
</widget>
<action name="actionHideChunkType">
<property name="text">
<string>Hide Chunk Type</string>
</property>
<property name="toolTip">
<string>Remove the chunk type from the table</string>
</property>
</action>
<action name="actionChunkTypePreferences">
<property name="text">
<string>Chunk Type Preferences</string>
</property>
<property name="toolTip">
<string>Go to the chunk type preferences dialog to show or hide other chunk types</string>
</property>
</action>
<action name="actionShowAllChunkTypes">
<property name="text">
<string>Show All Registered Chunk Types</string>
</property>
<property name="toolTip">
<string>Show all chunk types with defined names</string>
</property>
</action>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>clicked(QAbstractButton*)</signal>
<receiver>SCTPChunkStatisticsDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>456</x>
<y>483</y>
</hint>
<hint type="destinationlabel">
<x>445</x>
<y>563</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>clicked(QAbstractButton*)</signal>
<receiver>SCTPChunkStatisticsDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>357</x>
<y>486</y>
</hint>
<hint type="destinationlabel">
<x>355</x>
<y>542</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/sctp_graph_arwnd_dialog.cpp | /* sctp_graph_arwnd_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "sctp_graph_arwnd_dialog.h"
#include <ui_sctp_graph_arwnd_dialog.h>
#include "sctp_assoc_analyse_dialog.h"
#include <file.h>
#include <math.h>
#include <epan/dissectors/packet-sctp.h>
#include "epan/packet.h"
#include "ui/tap-sctp-analysis.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/widgets/qcustomplot.h>
#include "sctp_graph_dialog.h"
SCTPGraphArwndDialog::SCTPGraphArwndDialog(QWidget *parent, const sctp_assoc_info_t *assoc,
_capture_file *cf, int dir) :
QDialog(parent),
ui(new Ui::SCTPGraphArwndDialog),
cap_file_(cf),
frame_num(0),
direction(dir),
startArwnd(0)
{
Q_ASSERT(assoc);
selected_assoc_id = assoc->assoc_id;
ui->setupUi(this);
Qt::WindowFlags flags = Qt::Window | Qt::WindowSystemMenuHint
| Qt::WindowMinimizeButtonHint
| Qt::WindowMaximizeButtonHint
| Qt::WindowCloseButtonHint;
this->setWindowFlags(flags);
this->setWindowTitle(QString(tr("SCTP Data and Adv. Rec. Window over Time: %1 Port1 %2 Port2 %3"))
.arg(gchar_free_to_qstring(cf_get_display_name(cap_file_))).arg(assoc->port1).arg(assoc->port2));
if ((direction == 1 && assoc->n_array_tsn1 == 0) || (direction == 2 && assoc->n_array_tsn2 == 0)) {
QMessageBox msgBox;
msgBox.setText(tr("No Data Chunks sent"));
msgBox.exec();
return;
} else {
drawGraph(assoc);
}
}
SCTPGraphArwndDialog::~SCTPGraphArwndDialog()
{
delete ui;
}
void SCTPGraphArwndDialog::drawArwndGraph(const sctp_assoc_info_t *selected_assoc)
{
GList *listSACK = Q_NULLPTR, *tlist;
struct sack_chunk_header *sack_header;
struct nr_sack_chunk_header *nr_sack_header;
tsn_t *tsn;
guint8 type;
guint32 arwnd=0;
if (direction == 1) {
listSACK = g_list_last(selected_assoc->sack1);
startArwnd = selected_assoc->arwnd2;
} else {
listSACK = g_list_last(selected_assoc->sack2);
startArwnd = selected_assoc->arwnd1;
}
bool detect_max_arwnd = (startArwnd == 0) ? true : false;
while (listSACK) {
tsn = gxx_list_data(tsn_t*, listSACK);
tlist = g_list_first(tsn->tsns);
while (tlist) {
type = gxx_list_data(struct chunk_header *, tlist)->type;
if (type == SCTP_SACK_CHUNK_ID) {
sack_header = gxx_list_data(struct sack_chunk_header *, tlist);
arwnd = g_ntohl(sack_header->a_rwnd);
} else if (type == SCTP_NR_SACK_CHUNK_ID) {
nr_sack_header = gxx_list_data(struct nr_sack_chunk_header *, tlist);
arwnd = g_ntohl(nr_sack_header->a_rwnd);
}
if (detect_max_arwnd && startArwnd < arwnd) {
startArwnd = arwnd;
}
ya.append(arwnd);
xa.append(tsn->secs + tsn->usecs/1000000.0);
fa.append(tsn->frame_number);
tlist = gxx_list_next(tlist);
}
listSACK = gxx_list_previous(listSACK);
}
QCPScatterStyle myScatter;
myScatter.setShape(QCPScatterStyle::ssCircle);
myScatter.setSize(3);
// create graph and assign data to it:
// Add Arwnd graph
if (xa.size() > 0) {
QCPGraph *gr = ui->sctpPlot->addGraph(ui->sctpPlot->xAxis, ui->sctpPlot->yAxis);
gr->setName(QString(tr("Arwnd")));
myScatter.setPen(QPen(Qt::red));
myScatter.setBrush(Qt::red);
ui->sctpPlot->graph(0)->setScatterStyle(myScatter);
ui->sctpPlot->graph(0)->setLineStyle(QCPGraph::lsNone);
ui->sctpPlot->graph(0)->setData(xa, ya);
}
ui->sctpPlot->xAxis->setLabel(tr("time [secs]"));
ui->sctpPlot->yAxis->setLabel(tr("Advertised Receiver Window [Bytes]"));
// set axes ranges, so we see all data:
QCPRange myXArwndRange(0, (selected_assoc->max_secs+1));
// QCPRange myXArwndRange(0, 1);
QCPRange myYArwndRange(0, startArwnd);
ui->sctpPlot->xAxis->setRange(myXArwndRange);
ui->sctpPlot->yAxis->setRange(myYArwndRange);
}
void SCTPGraphArwndDialog::drawGraph(const sctp_assoc_info_t *selected_assoc)
{
ui->sctpPlot->clearGraphs();
drawArwndGraph(selected_assoc);
ui->sctpPlot->setInteractions(QCP::iRangeZoom | QCP::iRangeDrag | QCP::iSelectPlottables);
ui->sctpPlot->axisRect(0)->setRangeZoomAxes(ui->sctpPlot->xAxis, ui->sctpPlot->yAxis);
ui->sctpPlot->axisRect(0)->setRangeZoom(Qt::Horizontal);
connect(ui->sctpPlot, &QCustomPlot::plottableClick, this, &SCTPGraphArwndDialog::graphClicked);
ui->sctpPlot->replot();
}
void SCTPGraphArwndDialog::on_pushButton_4_clicked()
{
const sctp_assoc_info_t* selected_assoc = SCTPAssocAnalyseDialog::findAssoc(this, selected_assoc_id);
if (!selected_assoc) return;
ui->sctpPlot->xAxis->setRange(selected_assoc->min_secs+selected_assoc->min_usecs/1000000.0, selected_assoc->max_secs+selected_assoc->max_usecs/1000000.0);
ui->sctpPlot->yAxis->setRange(0, startArwnd);
ui->sctpPlot->replot();
}
void SCTPGraphArwndDialog::graphClicked(QCPAbstractPlottable* plottable, int, QMouseEvent* event)
{
if (plottable->name().contains("Arwnd", Qt::CaseInsensitive)) {
double times = ui->sctpPlot->xAxis->pixelToCoord(event->pos().x());
int i=0;
for (i = 0; i < xa.size(); i++) {
if (times <= xa.value(i)) {
frame_num = fa.at(i);
break;
}
}
if (cap_file_ && frame_num > 0) {
cf_goto_frame(cap_file_, frame_num);
}
ui->hintLabel->setText(QString(tr("<small><i>Graph %1: a_rwnd=%2 Time=%3 secs </i></small>"))
.arg(plottable->name())
.arg(ya.value(i))
.arg(xa.value(i)));
}
}
void SCTPGraphArwndDialog::on_saveButton_clicked()
{
SCTPGraphDialog::save_graph(this, ui->sctpPlot);
} |
C/C++ | wireshark/ui/qt/sctp_graph_arwnd_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 SCTP_GRAPH_ARWND_DIALOG_H
#define SCTP_GRAPH_ARWND_DIALOG_H
#include <config.h>
#include <glib.h>
#include "cfile.h"
#include <QDialog>
namespace Ui {
class SCTPGraphArwndDialog;
}
class QCPAbstractPlottable;
struct _sctp_assoc_info;
class SCTPGraphArwndDialog : public QDialog
{
Q_OBJECT
public:
explicit SCTPGraphArwndDialog(QWidget *parent = 0, const _sctp_assoc_info *assoc = NULL,
capture_file *cf = NULL, int dir = 0);
~SCTPGraphArwndDialog();
public slots:
void setCaptureFile(capture_file *cf) { cap_file_ = cf; }
private slots:
void on_pushButton_4_clicked();
void graphClicked(QCPAbstractPlottable* plottable, int, QMouseEvent* event);
void on_saveButton_clicked();
private:
Ui::SCTPGraphArwndDialog *ui;
guint16 selected_assoc_id;
capture_file *cap_file_;
int frame_num;
int direction;
guint32 startArwnd;
QVector<double> xa, ya;
QVector<guint32> fa;
// QVector<QString> typeStrings;
void drawGraph(const _sctp_assoc_info *selected_assoc);
void drawArwndGraph(const _sctp_assoc_info *selected_assoc);
};
#endif // SCTP_GRAPH_DIALOG_H |
User Interface | wireshark/ui/qt/sctp_graph_arwnd_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SCTPGraphArwndDialog</class>
<widget class="QDialog" name="SCTPGraphArwndDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>826</width>
<height>546</height>
</rect>
</property>
<property name="windowTitle">
<string>SCTP Graph</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QCustomPlot" name="sctpPlot" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="hintLabel">
<property name="text">
<string><html><head/><body><p><br/></p></body></html></string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="pushButton_4">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Reset to full size</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="saveButton">
<property name="text">
<string>Save Graph</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>428</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Close</set>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
<action name="actionGoToPacket">
<property name="text">
<string>goToPacket</string>
</property>
<property name="toolTip">
<string>Go to Packet</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>QCustomPlot</class>
<extends>QWidget</extends>
<header>widgets/qcustomplot.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>clicked(QAbstractButton*)</signal>
<receiver>SCTPGraphArwndDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>706</x>
<y>530</y>
</hint>
<hint type="destinationlabel">
<x>703</x>
<y>574</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/sctp_graph_byte_dialog.cpp | /* sctp_graph_byte_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "sctp_graph_byte_dialog.h"
#include <ui_sctp_graph_byte_dialog.h>
#include <file.h>
#include <math.h>
#include <epan/dissectors/packet-sctp.h>
#include "epan/packet.h"
#include "ui/tap-sctp-analysis.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/widgets/qcustomplot.h>
#include "sctp_graph_dialog.h"
#include "sctp_assoc_analyse_dialog.h"
SCTPGraphByteDialog::SCTPGraphByteDialog(QWidget *parent, const sctp_assoc_info_t *assoc,
capture_file *cf, int dir) :
QDialog(parent),
ui(new Ui::SCTPGraphByteDialog),
cap_file_(cf),
frame_num(0),
direction(dir)
{
Q_ASSERT(assoc);
selected_assoc_id = assoc->assoc_id;
ui->setupUi(this);
Qt::WindowFlags flags = Qt::Window | Qt::WindowSystemMenuHint
| Qt::WindowMinimizeButtonHint
| Qt::WindowMaximizeButtonHint
| Qt::WindowCloseButtonHint;
this->setWindowFlags(flags);
this->setWindowTitle(QString(tr("SCTP Data and Adv. Rec. Window over Time: %1 Port1 %2 Port2 %3"))
.arg(gchar_free_to_qstring(cf_get_display_name(cap_file_))).arg(assoc->port1).arg(assoc->port2));
if ((direction == 1 && assoc->n_array_tsn1 == 0) || (direction == 2 && assoc->n_array_tsn2 == 0)) {
QMessageBox msgBox;
msgBox.setText(tr("No Data Chunks sent"));
msgBox.exec();
return;
} else {
drawGraph();
}
}
SCTPGraphByteDialog::~SCTPGraphByteDialog()
{
delete ui;
}
void SCTPGraphByteDialog::drawBytesGraph(const sctp_assoc_info_t *selected_assoc)
{
GList *listTSN = Q_NULLPTR, *tlist = Q_NULLPTR;
tsn_t *tsn = Q_NULLPTR;
guint8 type;
guint32 maxBytes;
guint64 sumBytes = 0;
if (direction == 1) {
maxBytes = selected_assoc->n_data_bytes_ep1;
listTSN = g_list_last(selected_assoc->tsn1);
} else {
maxBytes = selected_assoc->n_data_bytes_ep2;
listTSN = g_list_last(selected_assoc->tsn2);
}
while (listTSN) {
tsn = gxx_list_data(tsn_t*, listTSN);
tlist = g_list_first(tsn->tsns);
guint16 length;
while (tlist)
{
type = gxx_list_data(struct chunk_header *, tlist)->type;
if (type == SCTP_DATA_CHUNK_ID || type == SCTP_I_DATA_CHUNK_ID) {
length = g_ntohs(gxx_list_data(struct data_chunk_header *, tlist)->length);
if (type == SCTP_DATA_CHUNK_ID)
length -= DATA_CHUNK_HEADER_LENGTH;
else
length -= I_DATA_CHUNK_HEADER_LENGTH;
sumBytes += length;
yb.append(sumBytes);
xb.append(tsn->secs + tsn->usecs/1000000.0);
fb.append(tsn->frame_number);
}
tlist = gxx_list_next(tlist);
}
listTSN = gxx_list_previous(listTSN);
}
QCPScatterStyle myScatter;
myScatter.setShape(QCPScatterStyle::ssCircle);
myScatter.setSize(3);
// create graph and assign data to it:
// Add Bytes graph
if (xb.size() > 0) {
QCPGraph *gr = ui->sctpPlot->addGraph(ui->sctpPlot->xAxis, ui->sctpPlot->yAxis);
gr->setName(QString(tr("Bytes")));
myScatter.setPen(QPen(Qt::red));
myScatter.setBrush(Qt::red);
ui->sctpPlot->graph(0)->setScatterStyle(myScatter);
ui->sctpPlot->graph(0)->setLineStyle(QCPGraph::lsNone);
ui->sctpPlot->graph(0)->setData(xb, yb);
}
ui->sctpPlot->xAxis->setLabel(tr("time [secs]"));
ui->sctpPlot->yAxis->setLabel(tr("Received Bytes"));
// set axes ranges, so we see all data:
QCPRange myXByteRange(0, (selected_assoc->max_secs+1));
QCPRange myYByteRange(0, maxBytes);
ui->sctpPlot->xAxis->setRange(myXByteRange);
ui->sctpPlot->yAxis->setRange(myYByteRange);
}
void SCTPGraphByteDialog::drawGraph()
{
const sctp_assoc_info_t* selected_assoc = SCTPAssocAnalyseDialog::findAssoc(this, selected_assoc_id);
if (!selected_assoc) return;
ui->sctpPlot->clearGraphs();
drawBytesGraph(selected_assoc);
ui->sctpPlot->setInteractions(QCP::iRangeZoom | QCP::iRangeDrag | QCP::iSelectPlottables);
connect(ui->sctpPlot, &QCustomPlot::plottableClick, this, &SCTPGraphByteDialog::graphClicked);
ui->sctpPlot->replot();
}
void SCTPGraphByteDialog::on_pushButton_4_clicked()
{
const sctp_assoc_info_t* selected_assoc = SCTPAssocAnalyseDialog::findAssoc(this, selected_assoc_id);
if (!selected_assoc) return;
ui->sctpPlot->xAxis->setRange(selected_assoc->min_secs+selected_assoc->min_usecs/1000000.0, selected_assoc->max_secs+selected_assoc->max_usecs/1000000.0);
if (direction == 1) {
ui->sctpPlot->yAxis->setRange(0, selected_assoc->n_data_bytes_ep1);
} else {
ui->sctpPlot->yAxis->setRange(0, selected_assoc->n_data_bytes_ep2);
}
ui->sctpPlot->replot();
}
void SCTPGraphByteDialog::graphClicked(QCPAbstractPlottable* plottable, int, QMouseEvent* event)
{
if (plottable->name().contains(tr("Bytes"), Qt::CaseInsensitive)) {
double bytes = ui->sctpPlot->yAxis->pixelToCoord(event->pos().y());
int i;
for (i = 0; i < yb.size(); i++) {
if (bytes <= yb.value(i)) {
frame_num = fb.at(i);
break;
}
}
if (cap_file_ && frame_num > 0) {
cf_goto_frame(cap_file_, frame_num);
}
ui->hintLabel->setText(QString(tr("<small><i>Graph %1: Received bytes=%2 Time=%3 secs </i></small>"))
.arg(plottable->name())
.arg(yb.value(i))
.arg(xb.value(i)));
}
}
void SCTPGraphByteDialog::on_saveButton_clicked()
{
SCTPGraphDialog::save_graph(this, ui->sctpPlot);
} |
C/C++ | wireshark/ui/qt/sctp_graph_byte_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 SCTP_GRAPH_BYTE_DIALOG_H
#define SCTP_GRAPH_BYTE_DIALOG_H
#include <config.h>
#include <glib.h>
#include "cfile.h"
#include <QDialog>
namespace Ui {
class SCTPGraphByteDialog;
}
class QCPAbstractPlottable;
struct _sctp_assoc_info;
class SCTPGraphByteDialog : public QDialog
{
Q_OBJECT
public:
explicit SCTPGraphByteDialog(QWidget *parent = 0, const _sctp_assoc_info *assoc = NULL,
capture_file *cf = NULL, int dir = 0);
~SCTPGraphByteDialog();
public slots:
void setCaptureFile(capture_file *cf) { cap_file_ = cf; }
private slots:
void on_pushButton_4_clicked();
void graphClicked(QCPAbstractPlottable* plottable, int, QMouseEvent* event);
void on_saveButton_clicked();
private:
Ui::SCTPGraphByteDialog *ui;
guint16 selected_assoc_id;
capture_file *cap_file_;
int frame_num;
int direction;
QVector<double> xb, yb;
QVector<guint32> fb;
void drawGraph();
void drawBytesGraph(const _sctp_assoc_info *selected_assoc);
};
#endif // SCTP_GRAPH_DIALOG_H |
User Interface | wireshark/ui/qt/sctp_graph_byte_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SCTPGraphByteDialog</class>
<widget class="QDialog" name="SCTPGraphByteDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>987</width>
<height>546</height>
</rect>
</property>
<property name="windowTitle">
<string>SCTP Graph</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QCustomPlot" name="sctpPlot" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="hintLabel">
<property name="text">
<string><html><head/><body><p><br/></p></body></html></string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="pushButton_4">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Reset to full size</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="saveButton">
<property name="text">
<string>Save Graph</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>428</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Close</set>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
<action name="actionGoToPacket">
<property name="text">
<string>goToPacket</string>
</property>
<property name="toolTip">
<string>Go to Packet</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>QCustomPlot</class>
<extends>QWidget</extends>
<header>widgets/qcustomplot.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>clicked(QAbstractButton*)</signal>
<receiver>SCTPGraphByteDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>706</x>
<y>530</y>
</hint>
<hint type="destinationlabel">
<x>703</x>
<y>574</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/sctp_graph_dialog.cpp | /* sctp_graph_dialog.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 "sctp_graph_dialog.h"
#include <ui_sctp_graph_dialog.h>
#include "sctp_assoc_analyse_dialog.h"
#include <file.h>
#include <math.h>
#include <epan/dissectors/packet-sctp.h>
#include "epan/packet.h"
#include "ui/tap-sctp-analysis.h"
#include <QMessageBox>
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/widgets/qcustomplot.h>
#include "ui/qt/widgets/wireshark_file_dialog.h"
#include "main_application.h"
SCTPGraphDialog::SCTPGraphDialog(QWidget *parent, const sctp_assoc_info_t *assoc,
capture_file *cf, int dir) :
QDialog(parent),
ui(new Ui::SCTPGraphDialog),
cap_file_(cf),
frame_num(0),
direction(dir),
relative(false),
type(1)
{
Q_ASSERT(assoc);
selected_assoc_id = assoc->assoc_id;
ui->setupUi(this);
Qt::WindowFlags flags = Qt::Window | Qt::WindowSystemMenuHint
| Qt::WindowMinimizeButtonHint
| Qt::WindowMaximizeButtonHint
| Qt::WindowCloseButtonHint;
this->setWindowFlags(flags);
this->setWindowTitle(QString(tr("SCTP TSNs and SACKs over Time: %1 Port1 %2 Port2 %3"))
.arg(gchar_free_to_qstring(cf_get_display_name(cap_file_))).arg(assoc->port1).arg(assoc->port2));
if ((direction == 1 && assoc->n_array_tsn1 == 0) || (direction == 2 && assoc->n_array_tsn2 == 0)) {
QMessageBox msgBox;
msgBox.setText(tr("No Data Chunks sent"));
msgBox.exec();
return;
} else {
drawGraph(assoc);
}
}
SCTPGraphDialog::~SCTPGraphDialog()
{
delete ui;
}
void SCTPGraphDialog::drawNRSACKGraph(const sctp_assoc_info_t* selected_assoc)
{
tsn_t *sack = Q_NULLPTR;
GList *list = Q_NULLPTR, *tlist = Q_NULLPTR;
guint16 gap_start=0, gap_end=0, i, numberOf_gaps, numberOf_nr_gaps;
guint8 type;
guint32 tsnumber, j = 0, min_tsn, rel = 0;
struct nr_sack_chunk_header *nr_sack_header = Q_NULLPTR;
struct gaps *nr_gap = Q_NULLPTR;
/* This holds the sum of gap acks and nr gap acks */
guint16 total_gaps = 0;
if (direction == 1) {
list = g_list_last(selected_assoc->sack1);
min_tsn = selected_assoc->min_tsn1;
} else {
list = g_list_last(selected_assoc->sack2);
min_tsn = selected_assoc->min_tsn2;
}
if (relative) {
rel = min_tsn;
}
while (list) {
sack = gxx_list_data(tsn_t*, list);
tlist = g_list_first(sack->tsns);
while (tlist) {
type = gxx_list_data(struct chunk_header *, tlist)->type;
if (type == SCTP_NR_SACK_CHUNK_ID) {
nr_sack_header = gxx_list_data(struct nr_sack_chunk_header *, tlist);
numberOf_nr_gaps=g_ntohs(nr_sack_header->nr_of_nr_gaps);
numberOf_gaps=g_ntohs(nr_sack_header->nr_of_gaps);
tsnumber = g_ntohl(nr_sack_header->cum_tsn_ack);
total_gaps = numberOf_gaps + numberOf_nr_gaps;
/* If the number of nr_gaps is greater than 0 */
if (total_gaps > 0) {
nr_gap = &nr_sack_header->gaps[0];
for (i = 0; i < total_gaps; i++) {
gap_start = g_ntohs(nr_gap->start);
gap_end = g_ntohs(nr_gap->end);
for (j = gap_start; j <= gap_end; j++) {
if (i >= numberOf_gaps) {
yn.append(j + tsnumber - rel);
xn.append(sack->secs + sack->usecs/1000000.0);
fn.append(sack->frame_number);
} else {
yg.append(j + tsnumber - rel);
xg.append(sack->secs + sack->usecs/1000000.0);
fg.append(sack->frame_number);
}
}
if (i < total_gaps-1)
nr_gap++;
}
if (tsnumber>=min_tsn) {
ys.append(j + tsnumber - rel);
xs.append(sack->secs + sack->usecs/1000000.0);
fs.append(sack->frame_number);
}
}
}
tlist = gxx_list_next(tlist);
}
list = gxx_list_previous(list);
}
}
void SCTPGraphDialog::drawSACKGraph(const sctp_assoc_info_t* selected_assoc)
{
GList *listSACK = Q_NULLPTR, *tlist = Q_NULLPTR;
guint16 gap_start=0, gap_end=0, nr, dup_nr;
struct sack_chunk_header *sack_header = Q_NULLPTR;
struct gaps *gap = Q_NULLPTR;
tsn_t *tsn = Q_NULLPTR;
guint8 type;
guint32 tsnumber=0, rel = 0;
guint32 minTSN;
guint32 *dup_list = Q_NULLPTR;
int i, j;
if (direction == 1) {
minTSN = selected_assoc->min_tsn1;
listSACK = g_list_last(selected_assoc->sack1);
} else {
minTSN = selected_assoc->min_tsn2;
listSACK = g_list_last(selected_assoc->sack2);
}
if (relative) {
rel = minTSN;
}
while (listSACK) {
tsn = gxx_list_data(tsn_t*, listSACK);
tlist = g_list_first(tsn->tsns);
while (tlist) {
type = gxx_list_data(struct chunk_header *, tlist)->type;
if (type == SCTP_SACK_CHUNK_ID) {
sack_header = gxx_list_data(struct sack_chunk_header *, tlist);
nr=g_ntohs(sack_header->nr_of_gaps);
tsnumber = g_ntohl(sack_header->cum_tsn_ack);
dup_nr=g_ntohs(sack_header->nr_of_dups);
if (nr>0) { // Gap Reports green
gap = &sack_header->gaps[0];
for (i=0;i<nr; i++) {
gap_start=g_ntohs(gap->start);
gap_end = g_ntohs(gap->end);
for (j=gap_start; j<=gap_end; j++) {
yg.append(j + tsnumber - rel);
xg.append(tsn->secs + tsn->usecs/1000000.0);
fg.append(tsn->frame_number);
}
if (i < nr-1)
gap++;
}
}
if (tsnumber>=minTSN) { // CumTSNAck red
ys.append(tsnumber - rel);
xs.append(tsn->secs + tsn->usecs/1000000.0);
fs.append(tsn->frame_number);
}
if (dup_nr > 0) { // Duplicates cyan
dup_list = &sack_header->a_rwnd + 2 + nr;
for (i = 0; i < dup_nr; i++) {
tsnumber = g_ntohl(dup_list[i]);
if (tsnumber >= minTSN) {
yd.append(tsnumber - rel);
xd.append(tsn->secs + tsn->usecs/1000000.0);
fd.append(tsn->frame_number);
}
}
}
}
tlist = gxx_list_next(tlist);
}
listSACK = gxx_list_previous(listSACK);
}
QCPScatterStyle myScatter;
myScatter.setShape(QCPScatterStyle::ssCircle);
myScatter.setSize(3);
int graphcount = ui->sctpPlot->graphCount();
// create graph and assign data to it:
// Add SACK graph
if (xs.size() > 0) {
QCPGraph *gr = ui->sctpPlot->addGraph();
gr->setName(QString("SACK"));
myScatter.setPen(QPen(Qt::red));
myScatter.setBrush(Qt::red);
ui->sctpPlot->graph(graphcount)->setScatterStyle(myScatter);
ui->sctpPlot->graph(graphcount)->setLineStyle(QCPGraph::lsNone);
ui->sctpPlot->graph(graphcount)->setData(xs, ys);
typeStrings.insert(graphcount, QString(tr("CumTSNAck")));
graphcount++;
}
// Add Gap Acks
if (xg.size() > 0) {
QCPGraph *gr = ui->sctpPlot->addGraph();
gr->setName(QString("GAP"));
myScatter.setPen(QPen(Qt::green));
myScatter.setBrush(Qt::green);
ui->sctpPlot->graph(graphcount)->setScatterStyle(myScatter);
ui->sctpPlot->graph(graphcount)->setLineStyle(QCPGraph::lsNone);
ui->sctpPlot->graph(graphcount)->setData(xg, yg);
typeStrings.insert(graphcount, QString(tr("Gap Ack")));
graphcount++;
}
// Add NR Gap Acks
if (xn.size() > 0) {
QCPGraph *gr = ui->sctpPlot->addGraph();
gr->setName(QString("NR_GAP"));
myScatter.setPen(QPen(Qt::blue));
myScatter.setBrush(Qt::blue);
ui->sctpPlot->graph(graphcount)->setScatterStyle(myScatter);
ui->sctpPlot->graph(graphcount)->setLineStyle(QCPGraph::lsNone);
ui->sctpPlot->graph(graphcount)->setData(xn, yn);
typeStrings.insert(graphcount, QString(tr("NR Gap Ack")));
graphcount++;
}
// Add Duplicates
if (xd.size() > 0) {
QCPGraph *gr = ui->sctpPlot->addGraph();
gr->setName(QString("DUP"));
myScatter.setPen(QPen(Qt::cyan));
myScatter.setBrush(Qt::cyan);
ui->sctpPlot->graph(graphcount)->setScatterStyle(myScatter);
ui->sctpPlot->graph(graphcount)->setLineStyle(QCPGraph::lsNone);
ui->sctpPlot->graph(graphcount)->setData(xd, yd);
typeStrings.insert(graphcount, QString(tr("Duplicate Ack")));
}
}
void SCTPGraphDialog::drawTSNGraph(const sctp_assoc_info_t* selected_assoc)
{
GList *listTSN = Q_NULLPTR,*tlist = Q_NULLPTR;
tsn_t *tsn = Q_NULLPTR;
guint8 type;
guint32 tsnumber=0, rel = 0, minTSN;
if (direction == 1) {
listTSN = g_list_last(selected_assoc->tsn1);
minTSN = selected_assoc->min_tsn1;
} else {
listTSN = g_list_last(selected_assoc->tsn2);
minTSN = selected_assoc->min_tsn2;
}
if (relative) {
rel = minTSN;
}
while (listTSN) {
tsn = gxx_list_data(tsn_t*, listTSN);
tlist = g_list_first(tsn->tsns);
while (tlist)
{
type = gxx_list_data(struct chunk_header *, tlist)->type;
if (type == SCTP_DATA_CHUNK_ID || type == SCTP_I_DATA_CHUNK_ID || type == SCTP_FORWARD_TSN_CHUNK_ID) {
tsnumber = g_ntohl(gxx_list_data(struct data_chunk_header *, tlist)->tsn);
yt.append(tsnumber - rel);
xt.append(tsn->secs + tsn->usecs/1000000.0);
ft.append(tsn->frame_number);
}
tlist = gxx_list_next(tlist);
}
listTSN = gxx_list_previous(listTSN);
}
QCPScatterStyle myScatter;
myScatter.setShape(QCPScatterStyle::ssCircle);
myScatter.setSize(3);
int graphcount = ui->sctpPlot->graphCount();
// create graph and assign data to it:
// Add TSN graph
if (xt.size() > 0) {
QCPGraph *gr = ui->sctpPlot->addGraph();
gr->setName(QString("TSN"));
myScatter.setPen(QPen(Qt::black));
myScatter.setBrush(Qt::black);
ui->sctpPlot->graph(graphcount)->setScatterStyle(myScatter);
ui->sctpPlot->graph(graphcount)->setLineStyle(QCPGraph::lsNone);
ui->sctpPlot->graph(graphcount)->setData(xt, yt);
typeStrings.insert(graphcount, QString(tr("TSN")));
}
}
void SCTPGraphDialog::drawGraph(const sctp_assoc_info_t* selected_assoc)
{
if (!selected_assoc) {
selected_assoc = SCTPAssocAnalyseDialog::findAssoc(this, selected_assoc_id);
if (!selected_assoc) return;
}
guint32 maxTSN, minTSN;
if (direction == 1) {
maxTSN = selected_assoc->max_tsn1;
minTSN = selected_assoc->min_tsn1;
} else {
maxTSN = selected_assoc->max_tsn2;
minTSN = selected_assoc->min_tsn2;
}
ui->sctpPlot->clearGraphs();
xt.clear();
yt.clear();
xs.clear();
ys.clear();
xg.clear();
yg.clear();
xd.clear();
yd.clear();
xn.clear();
yn.clear();
ft.clear();
fs.clear();
fg.clear();
fd.clear();
fn.clear();
typeStrings.clear();
switch (type) {
case 1:
drawSACKGraph(selected_assoc);
drawNRSACKGraph(selected_assoc);
break;
case 2:
drawTSNGraph(selected_assoc);
break;
case 3:
drawTSNGraph(selected_assoc);
drawSACKGraph(selected_assoc);
drawNRSACKGraph(selected_assoc);
break;
default:
drawTSNGraph(selected_assoc);
drawSACKGraph(selected_assoc);
drawNRSACKGraph(selected_assoc);
break;
}
// give the axes some labels:
ui->sctpPlot->xAxis->setLabel(tr("time [secs]"));
ui->sctpPlot->yAxis->setLabel(tr("TSNs"));
ui->sctpPlot->setInteractions(QCP::iRangeZoom | QCP::iRangeDrag | QCP::iSelectPlottables);
connect(ui->sctpPlot, &QCustomPlot::plottableClick, this, &SCTPGraphDialog::graphClicked);
// set axes ranges, so we see all data:
QCPRange myXRange(selected_assoc->min_secs, (selected_assoc->max_secs+1));
if (relative) {
QCPRange myYRange(0, maxTSN - minTSN + 1);
ui->sctpPlot->yAxis->setRange(myYRange);
} else {
QCPRange myYRange(minTSN, maxTSN + 1);
ui->sctpPlot->yAxis->setRange(myYRange);
}
ui->sctpPlot->xAxis->setRange(myXRange);
ui->sctpPlot->replot();
}
void SCTPGraphDialog::on_pushButton_clicked()
{
type = 1;
drawGraph();
}
void SCTPGraphDialog::on_pushButton_2_clicked()
{
type = 2;
drawGraph();
}
void SCTPGraphDialog::on_pushButton_3_clicked()
{
type = 3;
drawGraph();
}
void SCTPGraphDialog::on_pushButton_4_clicked()
{
const sctp_assoc_info_t* selected_assoc = SCTPAssocAnalyseDialog::findAssoc(this, selected_assoc_id);
if (!selected_assoc) return;
ui->sctpPlot->xAxis->setRange(selected_assoc->min_secs, selected_assoc->max_secs+1);
if (relative) {
if (direction == 1) {
ui->sctpPlot->yAxis->setRange(0, selected_assoc->max_tsn1 - selected_assoc->min_tsn1);
} else {
ui->sctpPlot->yAxis->setRange(0, selected_assoc->max_tsn2 - selected_assoc->min_tsn2);
}
} else {
if (direction == 1) {
ui->sctpPlot->yAxis->setRange(selected_assoc->min_tsn1, selected_assoc->max_tsn1);
} else {
ui->sctpPlot->yAxis->setRange(selected_assoc->min_tsn2, selected_assoc->max_tsn2);
}
}
ui->sctpPlot->replot();
}
void SCTPGraphDialog::graphClicked(QCPAbstractPlottable* plottable, int, QMouseEvent* event)
{
frame_num = 0;
int i=0;
double times = ui->sctpPlot->xAxis->pixelToCoord(event->pos().x());
if (plottable->name().contains("TSN", Qt::CaseInsensitive)) {
for (i = 0; i < xt.size(); i++) {
if (times <= xt.value(i)) {
frame_num = ft.at(i);
break;
}
}
} else if (plottable->name().contains("SACK", Qt::CaseInsensitive)) {
for (i = 0; i < xs.size(); i++) {
if (times <= xs.value(i)) {
frame_num = fs.at(i);
break;
}
}
} else if (plottable->name().contains("DUP", Qt::CaseInsensitive)) {
for (i = 0; i < xd.size(); i++) {
if (times <= xd.value(i)) {
frame_num = fd.at(i);
break;
}
}
} else if (plottable->name().contains("NR_GAP", Qt::CaseInsensitive)) {
for (i = 0; i < xn.size(); i++) {
if (times <= xn.value(i)) {
frame_num = fn.at(i);
break;
}
}
} else if (plottable->name().contains("GAP", Qt::CaseInsensitive)) {
for (i = 0; i < xs.size(); i++) {
if (times <= xs.value(i)) {
frame_num = fs.at(i);
break;
}
}
}
if (cap_file_ && frame_num > 0) {
cf_goto_frame(cap_file_, frame_num);
}
ui->hintLabel->setText(QString(tr("<small><i>%1: %2 Time: %3 secs </i></small>"))
.arg(plottable->name())
.arg(floor(ui->sctpPlot->yAxis->pixelToCoord(event->pos().y()) + 0.5))
.arg(ui->sctpPlot->xAxis->pixelToCoord(event->pos().x())));
}
void SCTPGraphDialog::save_graph(QDialog *dlg, QCustomPlot *plot)
{
QString file_name, extension;
QDir path(mainApp->lastOpenDir());
QString pdf_filter = tr("Portable Document Format (*.pdf)");
QString png_filter = tr("Portable Network Graphics (*.png)");
QString bmp_filter = tr("Windows Bitmap (*.bmp)");
// Gaze upon my beautiful graph with lossy artifacts!
QString jpeg_filter = tr("JPEG File Interchange Format (*.jpeg *.jpg)");
QString filter = QString("%1;;%2;;%3;;%4")
.arg(pdf_filter)
.arg(png_filter)
.arg(bmp_filter)
.arg(jpeg_filter);
file_name = WiresharkFileDialog::getSaveFileName(dlg, mainApp->windowTitleString(tr("Save Graph As…")),
path.canonicalPath(), filter, &extension);
if (file_name.length() > 0) {
bool save_ok = false;
if (extension.compare(pdf_filter) == 0) {
save_ok = plot->savePdf(file_name);
} else if (extension.compare(png_filter) == 0) {
save_ok = plot->savePng(file_name);
} else if (extension.compare(bmp_filter) == 0) {
save_ok = plot->saveBmp(file_name);
} else if (extension.compare(jpeg_filter) == 0) {
save_ok = plot->saveJpg(file_name);
}
// else error dialog?
if (save_ok) {
mainApp->setLastOpenDirFromFilename(file_name);
}
}
}
void SCTPGraphDialog::on_saveButton_clicked()
{
save_graph(this, ui->sctpPlot);
}
void SCTPGraphDialog::on_relativeTsn_stateChanged(int arg1)
{
relative = arg1;
drawGraph();
} |
C/C++ | wireshark/ui/qt/sctp_graph_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 SCTP_GRAPH_DIALOG_H
#define SCTP_GRAPH_DIALOG_H
#include <config.h>
#include <glib.h>
#include "cfile.h"
#include <QDialog>
namespace Ui {
class SCTPGraphDialog;
}
class QCPAbstractPlottable;
class QCustomPlot;
struct _sctp_assoc_info;
struct chunk_header {
guint8 type;
guint8 flags;
guint16 length;
};
struct data_chunk_header {
guint8 type;
guint8 flags;
guint16 length;
guint32 tsn;
guint16 sid;
guint16 ssn;
guint32 ppi;
};
struct gaps {
guint16 start;
guint16 end;
};
struct sack_chunk_header {
guint8 type;
guint8 flags;
guint16 length;
guint32 cum_tsn_ack;
guint32 a_rwnd;
guint16 nr_of_gaps;
guint16 nr_of_dups;
struct gaps gaps[1];
};
struct nr_sack_chunk_header {
guint8 type;
guint8 flags;
guint16 length;
guint32 cum_tsn_ack;
guint32 a_rwnd;
guint16 nr_of_gaps;
guint16 nr_of_nr_gaps;
guint16 nr_of_dups;
guint16 reserved;
struct gaps gaps[1];
};
class SCTPGraphDialog : public QDialog
{
Q_OBJECT
public:
explicit SCTPGraphDialog(QWidget *parent = 0, const _sctp_assoc_info *assoc = NULL,
capture_file *cf = NULL, int dir = 0);
~SCTPGraphDialog();
static void save_graph(QDialog *dlg, QCustomPlot *plot);
public slots:
void setCaptureFile(capture_file *cf) { cap_file_ = cf; }
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
void on_pushButton_4_clicked();
void graphClicked(QCPAbstractPlottable* plottable, int, QMouseEvent* event);
void on_saveButton_clicked();
void on_relativeTsn_stateChanged(int arg1);
private:
Ui::SCTPGraphDialog *ui;
guint16 selected_assoc_id;
capture_file *cap_file_;
int frame_num;
int direction;
QVector<double> xt, yt, xs, ys, xg, yg, xd, yd, xn, yn;
QVector<guint32> ft, fs, fg, fd, fn;
QVector<QString> typeStrings;
bool relative;
int type;
void drawGraph(const _sctp_assoc_info* selected_assoc = NULL);
void drawTSNGraph(const _sctp_assoc_info* selected_assoc);
void drawSACKGraph(const _sctp_assoc_info* selected_assoc);
void drawNRSACKGraph(const _sctp_assoc_info* selected_assoc);
};
#endif // SCTP_GRAPH_DIALOG_H |
User Interface | wireshark/ui/qt/sctp_graph_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SCTPGraphDialog</class>
<widget class="QDialog" name="SCTPGraphDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>546</height>
</rect>
</property>
<property name="windowTitle">
<string>SCTP Graph</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QCustomPlot" name="sctpPlot" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item alignment="Qt::AlignLeft">
<widget class="QLabel" name="hintLabel">
<property name="minimumSize">
<size>
<width>300</width>
<height>0</height>
</size>
</property>
</widget>
</item>
<item alignment="Qt::AlignRight">
<widget class="QCheckBox" name="relativeTsn">
<property name="text">
<string>Relative TSNs</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QPushButton" name="pushButton">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Only SACKs</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_2">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Only TSNs</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_3">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Show both</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_4">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="text">
<string>Reset to full size</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="saveButton">
<property name="text">
<string>Save Graph</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Close</set>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
<action name="actionGoToPacket">
<property name="text">
<string>goToPacket</string>
</property>
<property name="toolTip">
<string>Go to Packet</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>QCustomPlot</class>
<extends>QWidget</extends>
<header>widgets/qcustomplot.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>clicked(QAbstractButton*)</signal>
<receiver>SCTPGraphDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>706</x>
<y>530</y>
</hint>
<hint type="destinationlabel">
<x>703</x>
<y>574</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | wireshark/ui/qt/search_frame.cpp | /* search_frame.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "search_frame.h"
#include <ui_search_frame.h>
#include "file.h"
#include "ui/recent.h"
#include <epan/proto.h>
#include <epan/strutil.h>
#include <wsutil/utf8_entities.h>
#include <wsutil/regex.h>
#include "main_application.h"
#include <QKeyEvent>
#include <QCheckBox>
enum {
in_packet_list_,
in_proto_tree_,
in_bytes_
};
enum {
df_search_,
hex_search_,
string_search_,
regex_search_
};
enum {
narrow_and_wide_chars_,
narrow_chars_,
wide_chars_
};
SearchFrame::SearchFrame(QWidget *parent) :
AccordionFrame(parent),
sf_ui_(new Ui::SearchFrame),
cap_file_(nullptr),
regex_(nullptr)
{
sf_ui_->setupUi(this);
#ifdef Q_OS_MAC
foreach (QWidget *w, findChildren<QWidget *>()) {
w->setAttribute(Qt::WA_MacSmallSize, true);
}
#endif
applyRecentSearchSettings();
updateWidgets();
}
SearchFrame::~SearchFrame()
{
if (regex_) {
ws_regex_free(regex_);
}
delete sf_ui_;
}
void SearchFrame::animatedShow()
{
AccordionFrame::animatedShow();
sf_ui_->searchLineEdit->setFocus();
}
void SearchFrame::findNext()
{
if (!cap_file_) return;
cap_file_->dir = SD_FORWARD;
if (isHidden()) {
animatedShow();
return;
}
on_findButton_clicked();
}
void SearchFrame::findPrevious()
{
if (!cap_file_) return;
cap_file_->dir = SD_BACKWARD;
if (isHidden()) {
animatedShow();
return;
}
on_findButton_clicked();
}
void SearchFrame::setFocus()
{
sf_ui_->searchLineEdit->setFocus();
sf_ui_->searchLineEdit->selectAll();
cap_file_->dir = SD_FORWARD;
}
void SearchFrame::setCaptureFile(capture_file *cf)
{
cap_file_ = cf;
if (!cf && isVisible()) {
animatedHide();
}
updateWidgets();
}
void SearchFrame::findFrameWithFilter(QString &filter)
{
animatedShow();
sf_ui_->searchLineEdit->setText(filter);
sf_ui_->searchLineEdit->setCursorPosition(0);
sf_ui_->searchTypeComboBox->setCurrentIndex(df_search_);
updateWidgets();
on_findButton_clicked();
}
void SearchFrame::keyPressEvent(QKeyEvent *event)
{
if (event->modifiers() == Qt::NoModifier) {
if (event->key() == Qt::Key_Escape) {
on_cancelButton_clicked();
} else if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
on_findButton_clicked();
}
}
AccordionFrame::keyPressEvent(event);
}
bool SearchFrame::regexCompile()
{
unsigned flags = 0;
if (!sf_ui_->caseCheckBox->isChecked()) {
flags |= WS_REGEX_CASELESS;
}
if (regex_) {
ws_regex_free(regex_);
}
if (sf_ui_->searchLineEdit->text().isEmpty()) {
regex_ = nullptr;
return false;
}
char *errmsg = nullptr;
regex_ = ws_regex_compile_ex(sf_ui_->searchLineEdit->text().toUtf8().constData(), -1,
&errmsg, flags);
if (errmsg != nullptr) {
regex_error_ = errmsg;
}
return regex_ ? true : false;
}
void SearchFrame::applyRecentSearchSettings()
{
int search_in_idx = in_packet_list_;
int char_encoding_idx = narrow_and_wide_chars_;
int search_type_idx = df_search_;
switch (recent.gui_search_in) {
case SEARCH_IN_PACKET_LIST:
search_in_idx = in_packet_list_;
break;
case SEARCH_IN_PACKET_DETAILS:
search_in_idx = in_proto_tree_;
break;
case SEARCH_IN_PACKET_BYTES:
search_in_idx = in_bytes_;
break;
default:
break;
}
switch (recent.gui_search_char_set) {
case SEARCH_CHAR_SET_NARROW_AND_WIDE:
char_encoding_idx = narrow_and_wide_chars_;
break;
case SEARCH_CHAR_SET_NARROW:
char_encoding_idx = narrow_chars_;
break;
case SEARCH_CHAR_SET_WIDE:
char_encoding_idx = wide_chars_;
break;
default:
break;
}
switch (recent.gui_search_type) {
case SEARCH_TYPE_DISPLAY_FILTER:
search_type_idx = df_search_;
break;
case SEARCH_TYPE_HEX_VALUE:
search_type_idx = hex_search_;
break;
case SEARCH_TYPE_STRING:
search_type_idx = string_search_;
break;
case SEARCH_TYPE_REGEX:
search_type_idx = regex_search_;
break;
default:
break;
}
sf_ui_->searchInComboBox->setCurrentIndex(search_in_idx);
sf_ui_->charEncodingComboBox->setCurrentIndex(char_encoding_idx);
sf_ui_->caseCheckBox->setChecked(recent.gui_search_case_sensitive);
sf_ui_->searchTypeComboBox->setCurrentIndex(search_type_idx);
}
void SearchFrame::updateWidgets()
{
if (cap_file_) {
setEnabled(true);
} else {
setEnabled(false);
return;
}
int search_type = sf_ui_->searchTypeComboBox->currentIndex();
sf_ui_->searchInComboBox->setEnabled(search_type == string_search_ || search_type == regex_search_);
sf_ui_->caseCheckBox->setEnabled(search_type == string_search_ || search_type == regex_search_);
sf_ui_->charEncodingComboBox->setEnabled(search_type == string_search_);
switch (search_type) {
case df_search_:
sf_ui_->searchLineEdit->checkDisplayFilter(sf_ui_->searchLineEdit->text());
break;
case hex_search_:
if (sf_ui_->searchLineEdit->text().isEmpty()) {
sf_ui_->searchLineEdit->setSyntaxState(SyntaxLineEdit::Invalid);
} else {
guint8 *bytes;
size_t nbytes;
bytes = convert_string_to_hex(sf_ui_->searchLineEdit->text().toUtf8().constData(), &nbytes);
if (bytes == nullptr)
sf_ui_->searchLineEdit->setSyntaxState(SyntaxLineEdit::Invalid);
else {
g_free(bytes);
sf_ui_->searchLineEdit->setSyntaxState(SyntaxLineEdit::Valid);
}
}
break;
case string_search_:
if (sf_ui_->searchLineEdit->text().isEmpty()) {
sf_ui_->searchLineEdit->setSyntaxState(SyntaxLineEdit::Invalid);
} else {
sf_ui_->searchLineEdit->setSyntaxState(SyntaxLineEdit::Valid);
}
break;
case regex_search_:
if (regexCompile()) {
sf_ui_->searchLineEdit->setSyntaxState(SyntaxLineEdit::Valid);
} else {
sf_ui_->searchLineEdit->setSyntaxState(SyntaxLineEdit::Invalid);
}
break;
default:
// currentIndex is probably -1. Nothing is selected or list is empty.
return;
}
if (sf_ui_->searchLineEdit->text().isEmpty() || sf_ui_->searchLineEdit->syntaxState() == SyntaxLineEdit::Invalid) {
sf_ui_->findButton->setEnabled(false);
} else {
sf_ui_->findButton->setEnabled(true);
}
}
void SearchFrame::on_searchInComboBox_currentIndexChanged(int idx)
{
switch (idx) {
case in_packet_list_:
recent.gui_search_in = SEARCH_IN_PACKET_LIST;
break;
case in_proto_tree_:
recent.gui_search_in = SEARCH_IN_PACKET_DETAILS;
break;
case in_bytes_:
recent.gui_search_in = SEARCH_IN_PACKET_BYTES;
break;
default:
break;
}
}
void SearchFrame::on_charEncodingComboBox_currentIndexChanged(int idx)
{
switch (idx) {
case narrow_and_wide_chars_:
recent.gui_search_char_set = SEARCH_CHAR_SET_NARROW_AND_WIDE;
break;
case narrow_chars_:
recent.gui_search_char_set = SEARCH_CHAR_SET_NARROW;
break;
case wide_chars_:
recent.gui_search_char_set = SEARCH_CHAR_SET_WIDE;
break;
default:
break;
}
}
void SearchFrame::on_caseCheckBox_toggled(bool checked)
{
recent.gui_search_case_sensitive = checked;
regexCompile();
}
void SearchFrame::on_searchTypeComboBox_currentIndexChanged(int idx)
{
switch (idx) {
case df_search_:
recent.gui_search_type = SEARCH_TYPE_DISPLAY_FILTER;
break;
case hex_search_:
recent.gui_search_type = SEARCH_TYPE_HEX_VALUE;
break;
case string_search_:
recent.gui_search_type = SEARCH_TYPE_STRING;
break;
case regex_search_:
recent.gui_search_type = SEARCH_TYPE_REGEX;
break;
default:
break;
}
// Enable completion only for display filter search.
sf_ui_->searchLineEdit->allowCompletion(idx == df_search_);
if (idx == df_search_) {
sf_ui_->searchLineEdit->checkFilter();
} else {
sf_ui_->searchLineEdit->setToolTip(QString());
mainApp->popStatus(MainApplication::FilterSyntax);
}
updateWidgets();
}
void SearchFrame::on_searchLineEdit_textChanged(const QString &)
{
updateWidgets();
}
void SearchFrame::on_findButton_clicked()
{
guint8 *bytes = nullptr;
size_t nbytes = 0;
char *string = nullptr;
dfilter_t *dfp = nullptr;
gboolean found_packet = FALSE;
QString err_string;
if (!cap_file_) {
return;
}
cap_file_->hex = FALSE;
cap_file_->string = FALSE;
cap_file_->case_type = FALSE;
cap_file_->regex = nullptr;
cap_file_->packet_data = FALSE;
cap_file_->decode_data = FALSE;
cap_file_->summary_data = FALSE;
cap_file_->scs_type = SCS_NARROW_AND_WIDE;
int search_type = sf_ui_->searchTypeComboBox->currentIndex();
switch (search_type) {
case df_search_:
if (!dfilter_compile(sf_ui_->searchLineEdit->text().toUtf8().constData(), &dfp, nullptr)) {
err_string = tr("Invalid filter.");
goto search_done;
}
if (dfp == nullptr) {
err_string = tr("That filter doesn't test anything.");
goto search_done;
}
break;
case hex_search_:
bytes = convert_string_to_hex(sf_ui_->searchLineEdit->text().toUtf8().constData(), &nbytes);
if (bytes == nullptr) {
err_string = tr("That's not a valid hex string.");
goto search_done;
}
cap_file_->hex = TRUE;
break;
case string_search_:
case regex_search_:
if (sf_ui_->searchLineEdit->text().isEmpty()) {
err_string = tr("You didn't specify any text for which to search.");
goto search_done;
}
cap_file_->string = TRUE;
cap_file_->case_type = sf_ui_->caseCheckBox->isChecked() ? FALSE : TRUE;
cap_file_->regex = (search_type == regex_search_ ? regex_ : nullptr);
switch (sf_ui_->charEncodingComboBox->currentIndex()) {
case narrow_and_wide_chars_:
cap_file_->scs_type = SCS_NARROW_AND_WIDE;
break;
case narrow_chars_:
cap_file_->scs_type = SCS_NARROW;
break;
case wide_chars_:
cap_file_->scs_type = SCS_WIDE;
break;
default:
err_string = tr("No valid character set selected. Please report this to the development team.");
goto search_done;
}
string = convert_string_case(sf_ui_->searchLineEdit->text().toUtf8().constData(), cap_file_->case_type);
break;
default:
err_string = tr("No valid search type selected. Please report this to the development team.");
goto search_done;
}
switch (sf_ui_->searchInComboBox->currentIndex()) {
case in_packet_list_:
cap_file_->summary_data = TRUE;
break;
case in_proto_tree_:
cap_file_->decode_data = TRUE;
break;
case in_bytes_:
cap_file_->packet_data = TRUE;
break;
default:
err_string = tr("No valid search area selected. Please report this to the development team.");
goto search_done;
}
g_free(cap_file_->sfilter);
cap_file_->sfilter = g_strdup(sf_ui_->searchLineEdit->text().toUtf8().constData());
mainApp->popStatus(MainApplication::FileStatus);
mainApp->pushStatus(MainApplication::FileStatus, tr("Searching for %1…").arg(sf_ui_->searchLineEdit->text()));
if (cap_file_->hex) {
/* Hex value in packet data */
found_packet = cf_find_packet_data(cap_file_, bytes, nbytes, cap_file_->dir);
g_free(bytes);
if (!found_packet) {
/* We didn't find a packet */
err_string = tr("No packet contained those bytes.");
goto search_done;
}
} else if (cap_file_->string) {
if (search_type == regex_search_ && !cap_file_->regex) {
err_string = regex_error_;
goto search_done;
}
if (cap_file_->summary_data) {
/* String in the Info column of the summary line */
found_packet = cf_find_packet_summary_line(cap_file_, string, cap_file_->dir);
g_free(string);
if (!found_packet) {
err_string = tr("No packet contained that string in its Info column.");
goto search_done;
}
} else if (cap_file_->decode_data) {
/* String in the protocol tree headings */
found_packet = cf_find_packet_protocol_tree(cap_file_, string, cap_file_->dir);
g_free(string);
if (!found_packet) {
err_string = tr("No packet contained that string in its dissected display.");
goto search_done;
}
} else if (cap_file_->packet_data && string) {
/* String in the ASCII-converted packet data */
found_packet = cf_find_packet_data(cap_file_, (guint8 *) string, strlen(string), cap_file_->dir);
g_free(string);
if (!found_packet) {
err_string = tr("No packet contained that string in its converted data.");
goto search_done;
}
}
} else {
/* Search via display filter */
found_packet = cf_find_packet_dfilter(cap_file_, dfp, cap_file_->dir);
dfilter_free(dfp);
if (!found_packet) {
err_string = tr("No packet matched that filter.");
g_free(bytes);
goto search_done;
}
}
search_done:
mainApp->popStatus(MainApplication::FileStatus);
if (!err_string.isEmpty()) {
mainApp->pushStatus(MainApplication::FilterSyntax, err_string);
}
}
void SearchFrame::on_cancelButton_clicked()
{
mainApp->popStatus(MainApplication::FilterSyntax);
animatedHide();
}
void SearchFrame::changeEvent(QEvent* event)
{
if (event)
{
switch (event->type())
{
case QEvent::LanguageChange:
sf_ui_->retranslateUi(this);
break;
default:
break;
}
}
AccordionFrame::changeEvent(event);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.