language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
C++ | wireshark/ui/qt/extcap_argument.cpp | /* extcap_argument.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <extcap_argument.h>
#include <QObject>
#include <QWidget>
#include <QLabel>
#include <QLineEdit>
#include <QDateTimeEdit>
#include <QIntValidator>
#include <QDoubleValidator>
#include <QCheckBox>
#include <QButtonGroup>
#include <QBoxLayout>
#include <QRadioButton>
#include <QComboBox>
#include <QPushButton>
#include <QMargins>
#include <QVariant>
#include <QAbstractItemModel>
#include <QStringList>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QItemSelectionModel>
#include <QRegularExpression>
#include <glib.h>
#include <extcap.h>
#include <epan/prefs.h>
#include <epan/prefs-int.h>
#include <wsutil/wslog.h>
#include <ui/qt/utils/color_utils.h>
#include <extcap_parser.h>
#include <extcap_argument_file.h>
#include <extcap_argument_multiselect.h>
#include <ui/qt/extcap_options_dialog.h>
ExtArgTimestamp::ExtArgTimestamp(extcap_arg * argument, QObject * parent) :
ExtcapArgument(argument, parent), tsBox(0) {}
QWidget * ExtArgTimestamp::createEditor(QWidget * parent)
{
QString text = defaultValue();
if (_argument->pref_valptr && strlen(*_argument->pref_valptr))
{
QString storeValue(*_argument->pref_valptr);
text = storeValue.trimmed();
}
ts = QDateTime::fromSecsSinceEpoch(text.toInt());
tsBox = new QDateTimeEdit(ts, parent);
tsBox->setDisplayFormat(QLocale::system().dateTimeFormat());
tsBox->setCalendarPopup(true);
tsBox->setAutoFillBackground(true);
if (_argument->tooltip != NULL)
tsBox->setToolTip(QString().fromUtf8(_argument->tooltip));
connect(tsBox, SIGNAL(dateTimeChanged(QDateTime)), SLOT(onDateTimeChanged(QDateTime)));
return tsBox;
}
void ExtArgTimestamp::onDateTimeChanged(QDateTime t)
{
ts = t;
emit valueChanged();
}
QString ExtArgTimestamp::defaultValue()
{
return QString::number(QDateTime::currentDateTime().toSecsSinceEpoch());
}
bool ExtArgTimestamp::isValid()
{
bool valid = true;
if (value().length() == 0 && isRequired())
valid = false;
return valid;
}
QString ExtArgTimestamp::value()
{
return QString::number(ts.toSecsSinceEpoch());
}
QString ExtArgTimestamp::prefValue()
{
return value();
}
bool ExtArgTimestamp::isSetDefaultValueSupported()
{
return TRUE;
}
void ExtArgTimestamp::setDefaultValue()
{
QDateTime t;
t = QDateTime::fromSecsSinceEpoch(defaultValue().toInt());
tsBox->setDateTime(t);
}
ExtArgSelector::ExtArgSelector(extcap_arg * argument, QObject * parent) :
ExtcapArgument(argument, parent), boxSelection(0) {}
QWidget * ExtArgSelector::createEditor(QWidget * parent)
{
QWidget * editor = new QWidget(parent);
QHBoxLayout * layout = new QHBoxLayout();
QMargins margins = layout->contentsMargins();
layout->setContentsMargins(0, margins.top(), 0, margins.bottom());
boxSelection = new QComboBox(parent);
boxSelection->setToolTip(QString().fromUtf8(_argument->tooltip));
layout->addWidget(boxSelection);
if (values.length() > 0)
{
ExtcapValueList::const_iterator iter = values.constBegin();
while (iter != values.constEnd())
{
boxSelection->addItem((*iter).value(), (*iter).call());
++iter;
}
}
setDefaultValue();
if (reload())
{
QString btnText(tr("Reload data"));
if (_argument->placeholder)
btnText = QString(_argument->placeholder);
QPushButton * reloadButton = new QPushButton(btnText, editor);
layout->addWidget(reloadButton);
reloadButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred);
boxSelection->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
connect(reloadButton, SIGNAL(clicked()), this, SLOT(onReloadTriggered()));
}
connect (boxSelection, SIGNAL(currentIndexChanged(int)), SLOT(onIntChanged(int)));
editor->setLayout(layout);
return editor;
}
void ExtArgSelector::onReloadTriggered()
{
int counter = 0;
int selected = -1;
QString call = boxSelection->currentData().toString();
const char *prefval = (_argument->pref_valptr && strlen(*_argument->pref_valptr)) ? *_argument->pref_valptr : NULL;
QString stored(prefval ? prefval : "");
if (call != stored)
stored = call;
if (reloadValues() && values.length() > 0)
{
boxSelection->clear();
ExtcapValueList::const_iterator iter = values.constBegin();
while (iter != values.constEnd())
{
boxSelection->addItem((*iter).value(), (*iter).call());
if (stored.compare((*iter).call()) == 0)
selected = counter;
else if ((*iter).isDefault() && selected == -1)
selected = counter;
counter++;
++iter;
}
if (selected > -1 && selected < boxSelection->count())
boxSelection->setCurrentIndex(selected);
}
}
bool ExtArgSelector::isValid()
{
bool valid = true;
if (value().length() == 0 && isRequired())
valid = false;
if (boxSelection)
{
QString lblInvalidColor = ColorUtils::fromColorT(prefs.gui_text_invalid).name();
QString cmbBoxStyle("QComboBox { background-color: %1; } ");
boxSelection->setStyleSheet(cmbBoxStyle.arg(valid ? QString("") : lblInvalidColor));
}
return valid;
}
QString ExtArgSelector::value()
{
if (boxSelection == 0)
return QString();
QVariant data = boxSelection->currentData();
return data.toString();
}
bool ExtArgSelector::isSetDefaultValueSupported()
{
return TRUE;
}
void ExtArgSelector::setDefaultValue()
{
int counter = 0;
int selected = -1;
const char *prefval = (_argument->pref_valptr && strlen(*_argument->pref_valptr)) ? *_argument->pref_valptr : NULL;
QString stored(prefval ? prefval : "");
if (values.length() > 0)
{
ExtcapValueList::const_iterator iter = values.constBegin();
while (iter != values.constEnd())
{
if (!prefval && (*iter).isDefault())
selected = counter;
else if (prefval && stored.compare((*iter).call()) == 0)
selected = counter;
counter++;
++iter;
}
if (selected > -1 && selected < boxSelection->count())
boxSelection->setCurrentIndex(selected);
}
}
ExtArgEditSelector::ExtArgEditSelector(extcap_arg * argument, QObject * parent) :
ExtArgSelector(argument, parent) {}
QWidget * ExtArgEditSelector::createEditor(QWidget * parent)
{
QWidget *editor = ExtArgSelector::createEditor(parent);
boxSelection->setEditable(true);
boxSelection->setInsertPolicy(QComboBox::NoInsert);
return editor;
}
QString ExtArgEditSelector::value()
{
if (boxSelection == nullptr) {
return QString();
}
if (boxSelection->currentIndex() > -1) {
return ExtArgSelector::value();
}
return boxSelection->currentText();
}
void ExtArgEditSelector::setDefaultValue()
{
ExtArgSelector::setDefaultValue();
if (boxSelection == nullptr) {
return;
}
const char *prefval = (_argument->pref_valptr && strlen(*_argument->pref_valptr)) ? *_argument->pref_valptr : NULL;
QString stored(prefval ? prefval : "");
QVariant data = boxSelection->currentData();
if (data.toString() != stored) {
// createEditor may not have been called at this point?
boxSelection->setEditable(true);
boxSelection->setInsertPolicy(QComboBox::NoInsert);
boxSelection->setEditText(stored);
}
}
ExtArgRadio::ExtArgRadio(extcap_arg * argument, QObject * parent) :
ExtcapArgument(argument, parent), selectorGroup(0), callStrings(0) {}
QWidget * ExtArgRadio::createEditor(QWidget * parent)
{
int count = 0;
selectorGroup = new QButtonGroup(parent);
QWidget * radioButtons = new QWidget;
QVBoxLayout * vrLayout = new QVBoxLayout();
QMargins margins = vrLayout->contentsMargins();
vrLayout->setContentsMargins(0, 0, 0, margins.bottom());
if (callStrings != 0)
delete callStrings;
callStrings = new QList<QString>();
if (values.length() > 0)
{
ExtcapValueList::const_iterator iter = values.constBegin();
while (iter != values.constEnd())
{
QRadioButton * radio = new QRadioButton((*iter).value());
QString callString = (*iter).call();
callStrings->append(callString);
connect(radio, SIGNAL(clicked(bool)), SLOT(onBoolChanged(bool)));
selectorGroup->addButton(radio, count);
vrLayout->addWidget(radio);
count++;
++iter;
}
}
setDefaultValue();
radioButtons->setLayout(vrLayout);
return radioButtons;
}
QString ExtArgRadio::value()
{
int idx = 0;
if (selectorGroup == 0 || callStrings == 0)
return QString();
idx = selectorGroup->checkedId();
if (idx > -1 && callStrings->length() > idx)
return callStrings->at(idx);
return QString();
}
bool ExtArgRadio::isValid()
{
bool valid = true;
int idx = 0;
if (isRequired())
{
if (selectorGroup == 0 || callStrings == 0)
valid = false;
else
{
idx = selectorGroup->checkedId();
if (idx == -1 || callStrings->length() <= idx)
valid = false;
}
}
/* If nothing is selected, but a selection is required, the only thing that
* can be marked is the label */
QString lblInvalidColor = ColorUtils::fromColorT(prefs.gui_text_invalid).name();
_label->setStyleSheet (label_style.arg(valid ? QString("") : lblInvalidColor));
return valid;
}
bool ExtArgRadio::isSetDefaultValueSupported()
{
return TRUE;
}
void ExtArgRadio::setDefaultValue()
{
int counter = 0;
int selected = 0;
const char *prefval = (_argument->pref_valptr && strlen(*_argument->pref_valptr)) ? *_argument->pref_valptr : NULL;
QString stored(prefval ? prefval : "");
if (values.length() > 0)
{
ExtcapValueList::const_iterator iter = values.constBegin();
while (iter != values.constEnd())
{
if (!prefval && (*iter).isDefault())
selected = counter;
else if (prefval && stored.compare((*iter).call()) == 0)
selected = counter;
counter++;
++iter;
}
((QRadioButton*)(selectorGroup->button(selected)))->setChecked(true);
}
}
ExtArgBool::ExtArgBool(extcap_arg * argument, QObject * parent) :
ExtcapArgument(argument, parent), boolBox(0) {}
QWidget * ExtArgBool::createLabel(QWidget * parent)
{
return new QWidget(parent);
}
QWidget * ExtArgBool::createEditor(QWidget * parent)
{
bool state = defaultBool();
boolBox = new QCheckBox(QString().fromUtf8(_argument->display), parent);
if (_argument->tooltip != NULL)
boolBox->setToolTip(QString().fromUtf8(_argument->tooltip));
const char *prefval = (_argument->pref_valptr && strlen(*_argument->pref_valptr)) ? *_argument->pref_valptr : NULL;
if (prefval)
{
QRegularExpression regexp(EXTCAP_BOOLEAN_REGEX);
QRegularExpressionMatch match = regexp.match(QString(prefval[0]));
bool savedstate = match.hasMatch();
if (savedstate != state)
state = savedstate;
}
boolBox->setCheckState(state ? Qt::Checked : Qt::Unchecked);
connect (boolBox, SIGNAL(stateChanged(int)), SLOT(onIntChanged(int)));
return boolBox;
}
QString ExtArgBool::call()
{
if (boolBox == NULL)
return QString("");
if (_argument->arg_type == EXTCAP_ARG_BOOLEAN)
return ExtcapArgument::call();
return QString(boolBox->checkState() == Qt::Checked ? _argument->call : "");
}
QString ExtArgBool::value()
{
if (boolBox == NULL || _argument->arg_type == EXTCAP_ARG_BOOLFLAG)
return QString();
return QString(boolBox->checkState() == Qt::Checked ? "true" : "false");
}
QString ExtArgBool::prefValue()
{
if (boolBox == NULL)
return QString("false");
return QString(boolBox->checkState() == Qt::Checked ? "true" : "false");
}
bool ExtArgBool::isValid()
{
/* A bool is always valid, but the base function checks on string length,
* which will fail with boolflags */
return true;
}
bool ExtArgBool::defaultBool()
{
bool result = false;
if (_argument)
{
if (extcap_complex_get_bool(_argument->default_complex) == (gboolean)TRUE)
result = true;
}
return result;
}
QString ExtArgBool::defaultValue()
{
return defaultBool() ? QString("true") : QString("false");
}
bool ExtArgBool::isSetDefaultValueSupported()
{
return TRUE;
}
void ExtArgBool::setDefaultValue()
{
boolBox->setCheckState(defaultBool() ? Qt::Checked : Qt::Unchecked);
}
ExtArgText::ExtArgText(extcap_arg * argument, QObject * parent) :
ExtcapArgument(argument, parent), textBox(0)
{
}
QWidget * ExtArgText::createEditor(QWidget * parent)
{
QString text = defaultValue();
/* Prefs can contain empty string. We accept it. */
if (_argument->pref_valptr && (*_argument->pref_valptr))
{
QString storeValue(*_argument->pref_valptr);
text = storeValue.trimmed();
}
textBox = new QLineEdit(text, parent);
if (_argument->tooltip != NULL)
textBox->setToolTip(QString().fromUtf8(_argument->tooltip));
if (_argument->placeholder != NULL)
textBox->setPlaceholderText(QString().fromUtf8(_argument->placeholder));
if (_argument->arg_type == EXTCAP_ARG_PASSWORD)
textBox->setEchoMode(QLineEdit::PasswordEchoOnEdit);
connect(textBox , SIGNAL(textChanged(QString)), SLOT(onStringChanged(QString)));
return textBox;
}
QString ExtArgText::value()
{
if (textBox == 0)
return QString();
return textBox->text();
}
bool ExtArgText::isValid()
{
bool valid = true;
if (isRequired() && value().length() == 0)
valid = false;
/* Does the validator, if any, consider the value valid?
*
* If it considers it an "intermediate" value, rather than an "invalid"
* value, the user will be able to transfer the input focus to another
* widget, and, as long as all widgets have values for which isValid()
* is true, they wil be able to click the "Start" button.
*
* For QIntValidator(), used for integral fields with minimum and
* maximum values, a value that's larger than the maximum but has
* the same number of digits as the maximum is "intermediate" rather
* than "invalid", so the user will be able to cause that value to
* be passed to the extcap module; see bug 16510.
*
* So we explicitly call the hasAcceptableInput() method on the
* text box; that returns false if the value is not "valid", and
* that includes "intermediate" values.
*
* This way, 1) non-colorblind users are informed that the value
* is invalid by the text box background being red (perhaps the
* user isn't fully colorblind, or perhaps the background is a
* noticeably different grayscale), and 2) the user won't be able
* to start the capture until they fix the problem.
*
* XXX - it might be nice to have some way of indicating to the
* user what the problem is with the value - alert box? Tooltip? */
if (!textBox->hasAcceptableInput())
valid = false;
/* validation should only be checked if there is a value. if the argument
* must be present (isRequired) the check above will handle that */
if (valid && _argument->regexp != NULL && value().length() > 0)
{
QString regexp = QString().fromUtf8(_argument->regexp);
if (regexp.length() > 0)
{
QRegularExpression expr(regexp, QRegularExpression::UseUnicodePropertiesOption);
if (! expr.isValid() || ! expr.match(value()).hasMatch())
valid = false;
}
}
QString lblInvalidColor = ColorUtils::fromColorT(prefs.gui_text_invalid).name();
QString txtStyle("QLineEdit { background-color: %1; } ");
textBox->setStyleSheet(txtStyle.arg(valid ? QString("") : lblInvalidColor));
return valid;
}
bool ExtArgText::isSetDefaultValueSupported()
{
return TRUE;
}
void ExtArgText::setDefaultValue()
{
textBox->setText(defaultValue());
}
ExtArgNumber::ExtArgNumber(extcap_arg * argument, QObject * parent) :
ExtArgText(argument, parent) {}
QWidget * ExtArgNumber::createEditor(QWidget * parent)
{
QString text = defaultValue();
if (_argument->pref_valptr && strlen(*_argument->pref_valptr))
{
QString storeValue(*_argument->pref_valptr);
text = storeValue;
}
textBox = (QLineEdit *)ExtArgText::createEditor(parent);
textBox->disconnect(SIGNAL(textChanged(QString)));
if (_argument->arg_type == EXTCAP_ARG_INTEGER || _argument->arg_type == EXTCAP_ARG_UNSIGNED)
{
QIntValidator * textValidator = new QIntValidator(parent);
if (_argument->range_start != NULL)
{
int val = 0;
if (_argument->arg_type == EXTCAP_ARG_INTEGER)
val = extcap_complex_get_int(_argument->range_start);
else if (_argument->arg_type == EXTCAP_ARG_UNSIGNED)
{
guint tmp = extcap_complex_get_uint(_argument->range_start);
if (tmp > G_MAXINT)
{
ws_log(LOG_DOMAIN_CAPTURE, LOG_LEVEL_DEBUG, "Defined value for range_start of %s exceeds valid integer range", _argument->call);
val = G_MAXINT;
}
else
val = (gint)tmp;
}
textValidator->setBottom(val);
}
if (_argument->arg_type == EXTCAP_ARG_UNSIGNED && textValidator->bottom() < 0)
{
ws_log(LOG_DOMAIN_CAPTURE, LOG_LEVEL_DEBUG, "%s sets negative bottom range for unsigned value, setting to 0", _argument->call);
textValidator->setBottom(0);
}
if (_argument->range_end != NULL)
{
int val = 0;
if (_argument->arg_type == EXTCAP_ARG_INTEGER)
val = extcap_complex_get_int(_argument->range_end);
else if (_argument->arg_type == EXTCAP_ARG_UNSIGNED)
{
guint tmp = extcap_complex_get_uint(_argument->range_end);
if (tmp > G_MAXINT)
{
ws_log(LOG_DOMAIN_CAPTURE, LOG_LEVEL_DEBUG, "Defined value for range_end of %s exceeds valid integer range", _argument->call);
val = G_MAXINT;
}
else
val = (gint)tmp;
}
textValidator->setTop(val);
}
textBox->setValidator(textValidator);
}
else if (_argument->arg_type == EXTCAP_ARG_DOUBLE)
{
QDoubleValidator * textValidator = new QDoubleValidator(parent);
if (_argument->range_start != NULL)
textValidator->setBottom(extcap_complex_get_double(_argument->range_start));
if (_argument->range_end != NULL)
textValidator->setTop(extcap_complex_get_double(_argument->range_end));
textBox->setValidator(textValidator);
}
textBox->setText(text.trimmed());
connect(textBox, SIGNAL(textChanged(QString)), SLOT(onStringChanged(QString)));
return textBox;
}
QString ExtArgNumber::defaultValue()
{
QString result;
if (_argument != 0)
{
if (_argument->arg_type == EXTCAP_ARG_DOUBLE)
result = QString::number(extcap_complex_get_double(_argument->default_complex));
else if (_argument->arg_type == EXTCAP_ARG_INTEGER)
result = QString::number(extcap_complex_get_int(_argument->default_complex));
else if (_argument->arg_type == EXTCAP_ARG_UNSIGNED)
result = QString::number(extcap_complex_get_uint(_argument->default_complex));
else if (_argument->arg_type == EXTCAP_ARG_LONG)
result = QString::number(extcap_complex_get_long(_argument->default_complex));
else
{
QString defValue = ExtcapArgument::defaultValue();
result = defValue.length() > 0 ? defValue : QString();
}
}
return result;
}
ExtcapValue::~ExtcapValue() {}
void ExtcapValue::setChildren(ExtcapValueList children)
{
ExtcapValueList::iterator iter = children.begin();
while (iter != children.end())
{
(*iter)._depth = _depth + 1;
++iter;
}
_children.append(children);
}
ExtcapArgument::ExtcapArgument(QObject *parent) :
QObject(parent), _argument(0), _label(0), _number(0),
label_style(QString("QLabel { color: %1; }"))
{
}
ExtcapArgument::ExtcapArgument(extcap_arg * argument, QObject *parent) :
QObject(parent), _argument(argument), _label(0),
label_style(QString("QLabel { color: %1; }"))
{
_number = argument->arg_num;
if (_argument->values != 0)
{
ExtcapValueList elements = loadValues(QString(""));
if (elements.length() > 0)
values.append(elements);
}
}
ExtcapArgument::ExtcapArgument(const ExtcapArgument &obj) :
QObject(obj.parent()), _argument(obj._argument), _label(0),
label_style(QString("QLabel { color: %1; }"))
{
_number = obj._argument->arg_num;
if (_argument->values != 0)
{
ExtcapValueList elements = loadValues(QString(""));
if (elements.length() > 0)
values.append(elements);
}
}
ExtcapValueList ExtcapArgument::loadValues(QString parent)
{
if (_argument == 0 || _argument->values == 0)
return ExtcapValueList();
GList * walker = 0;
extcap_value * v;
ExtcapValueList elements;
for (walker = g_list_first((GList *)(_argument->values)); walker != NULL ; walker = walker->next)
{
v = (extcap_value *) walker->data;
if (v == NULL || v->display == NULL || v->call == NULL)
break;
QString valParent = QString().fromUtf8(v->parent);
if (parent.compare(valParent) == 0)
{
QString display = QString().fromUtf8(v->display);
QString call = QString().fromUtf8(v->call);
ExtcapValue element = ExtcapValue(display, call,
v->enabled == (gboolean)TRUE, v->is_default == (gboolean)TRUE);
if (!call.isEmpty())
element.setChildren(this->loadValues(call));
elements.append(element);
}
}
return elements;
}
bool ExtcapArgument::reloadValues()
{
if (! qobject_cast<ExtcapOptionsDialog*> (parent()) )
return false;
ExtcapOptionsDialog * dialog = qobject_cast<ExtcapOptionsDialog*>(parent());
ExtcapValueList list = dialog->loadValuesFor(_argument->arg_num, _argument->call);
if (list.size() > 0)
{
values.clear();
values << list;
return true;
}
return false;
}
ExtcapArgument::~ExtcapArgument() {
}
QWidget * ExtcapArgument::createLabel(QWidget * parent)
{
if (_argument == 0 || _argument->display == 0)
return 0;
QString lblInvalidColor = ColorUtils::fromColorT(prefs.gui_text_invalid).name();
QString text = QString().fromUtf8(_argument->display);
if (_label == 0)
_label = new QLabel(text, parent);
else
_label->setText(text);
_label->setProperty("isRequired", QString(isRequired() ? "true" : "false"));
_label->setStyleSheet (label_style.arg(QString("")));
if (_argument->tooltip != 0)
_label->setToolTip(QString().fromUtf8(_argument->tooltip));
return (QWidget *)_label;
}
QWidget * ExtcapArgument::createEditor(QWidget *)
{
return 0;
}
QString ExtcapArgument::call()
{
return QString(_argument->call);
}
QString ExtcapArgument::value()
{
return QString();
}
QString ExtcapArgument::prefValue()
{
return value();
}
void ExtcapArgument::resetValue()
{
if (_argument->pref_valptr) {
g_free(*_argument->pref_valptr);
*_argument->pref_valptr = g_strdup("");
}
}
bool ExtcapArgument::isValid()
{
/* Unrequired arguments are always valid, except if validity checks fail,
* which must be checked in an derived class, not here */
if (! isRequired())
return true;
return value().length() > 0;
}
QString ExtcapArgument::defaultValue()
{
if (_argument != 0 && _argument->default_complex != 0)
{
gchar * str = extcap_get_complex_as_string(_argument->default_complex);
if (str != 0)
return QString(str);
}
return QString();
}
QString ExtcapArgument::group() const
{
if (_argument != 0 && _argument->group != 0)
return QString(_argument->group);
return QString();
}
int ExtcapArgument::argNr() const
{
return _number;
}
QString ExtcapArgument::prefKey(const QString & device_name)
{
struct preference * pref = NULL;
if (_argument == 0 || ! _argument->save)
return QString();
pref = extcap_pref_for_argument(device_name.toStdString().c_str(), _argument);
if (pref != NULL)
return QString(prefs_get_name(pref));
return QString();
}
bool ExtcapArgument::isRequired()
{
if (_argument != NULL)
return _argument->is_required;
return FALSE;
}
bool ExtcapArgument::reload()
{
if (_argument != NULL)
return _argument->reload;
return false;
}
bool ExtcapArgument::fileExists()
{
if (_argument != NULL)
return _argument->fileexists;
return FALSE;
}
bool ExtcapArgument::isDefault()
{
if (value().compare(defaultValue()) == 0)
return true;
return false;
}
ExtcapArgument * ExtcapArgument::create(extcap_arg * argument, QObject *parent)
{
if (argument == 0 || argument->display == 0)
return 0;
ExtcapArgument * result = 0;
if (argument->arg_type == EXTCAP_ARG_STRING || argument->arg_type == EXTCAP_ARG_PASSWORD)
result = new ExtArgText(argument, parent);
else if (argument->arg_type == EXTCAP_ARG_INTEGER || argument->arg_type == EXTCAP_ARG_LONG ||
argument->arg_type == EXTCAP_ARG_UNSIGNED || argument->arg_type == EXTCAP_ARG_DOUBLE)
result = new ExtArgNumber(argument, parent);
else if (argument->arg_type == EXTCAP_ARG_BOOLEAN || argument->arg_type == EXTCAP_ARG_BOOLFLAG)
result = new ExtArgBool(argument, parent);
else if (argument->arg_type == EXTCAP_ARG_SELECTOR)
result = new ExtArgSelector(argument, parent);
else if (argument->arg_type == EXTCAP_ARG_EDIT_SELECTOR)
result = new ExtArgEditSelector(argument, parent);
else if (argument->arg_type == EXTCAP_ARG_RADIO)
result = new ExtArgRadio(argument, parent);
else if (argument->arg_type == EXTCAP_ARG_FILESELECT)
result = new ExtcapArgumentFileSelection(argument, parent);
else if (argument->arg_type == EXTCAP_ARG_MULTICHECK)
result = new ExtArgMultiSelect(argument, parent);
else if (argument->arg_type == EXTCAP_ARG_TIMESTAMP)
result = new ExtArgTimestamp(argument, parent);
else
{
/* For everything else, we just print the label */
result = new ExtcapArgument(argument, parent);
}
return result;
}
/* The following is a necessity, because Q_Object does not do well with multiple inheritances */
void ExtcapArgument::onStringChanged(QString)
{
emit valueChanged();
}
void ExtcapArgument::onIntChanged(int)
{
if (isValid())
emit valueChanged();
}
void ExtcapArgument::onBoolChanged(bool)
{
emit valueChanged();
}
bool ExtcapArgument::isSetDefaultValueSupported()
{
return FALSE;
}
void ExtcapArgument::setDefaultValue()
{
} |
C/C++ | wireshark/ui/qt/extcap_argument.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef UI_QT_EXTCAP_ARGUMENT_H_
#define UI_QT_EXTCAP_ARGUMENT_H_
#include <QObject>
#include <QWidget>
#include <QLabel>
#include <QVariant>
#include <QList>
#include <QLineEdit>
#include <QComboBox>
#include <QButtonGroup>
#include <QCheckBox>
#include <QDateTime>
#include <extcap_parser.h>
#define EXTCAP_GUI_BLANK_LABEL "QLabel { color : ; }"
#define EXTCAP_GUI_ERROR_LABEL "QLabel { color : red; }"
class ExtcapValue;
typedef QList<ExtcapValue> ExtcapValueList;
class ExtcapValue
{
public:
ExtcapValue(QString value, QString call, bool enabled, bool isDefault) :
_value(value), _call(call), _enabled(enabled),
_isDefault(isDefault), _depth(0) {}
virtual ~ExtcapValue();
void setChildren(ExtcapValueList children);
ExtcapValueList children()
{
if (_children.length() == 0)
return ExtcapValueList();
return _children;
}
QString value() const { return _value; }
const QString call() const { return _call; }
bool enabled() const { return _enabled; }
bool isDefault() const { return _isDefault; }
int depth() { return _depth; }
private:
QString _value;
QString _call;
bool _enabled;
bool _isDefault;
int _depth;
ExtcapValueList _children;
};
class ExtcapArgument: public QObject
{
Q_OBJECT
public:
ExtcapArgument(QObject *parent = Q_NULLPTR);
ExtcapArgument(extcap_arg * argument, QObject *parent = Q_NULLPTR);
ExtcapArgument(const ExtcapArgument &obj);
virtual ~ExtcapArgument();
virtual QWidget * createLabel(QWidget * parent = 0);
virtual QWidget * createEditor(QWidget * parent = 0);
virtual extcap_arg * argument() { return _argument; }
virtual QString call();
virtual QString value();
virtual QString defaultValue();
bool isDefault();
virtual bool isValid();
bool isRequired();
bool reload();
QString prefKey(const QString & device_name);
virtual QString prefValue();
void resetValue();
virtual QString group() const;
virtual int argNr() const;
static ExtcapArgument * create(extcap_arg * argument = Q_NULLPTR, QObject * parent = Q_NULLPTR);
virtual bool isSetDefaultValueSupported();
public Q_SLOTS:
virtual void setDefaultValue();
Q_SIGNALS:
void valueChanged();
protected:
bool fileExists();
ExtcapValueList loadValues(QString parent);
bool reloadValues();
ExtcapValueList values;
extcap_arg * _argument;
QLabel * _label;
int _number;
const QString label_style;
private Q_SLOTS:
void onStringChanged(QString);
void onIntChanged(int);
void onBoolChanged(bool);
};
class ExtArgText : public ExtcapArgument
{
Q_OBJECT
public:
ExtArgText(extcap_arg * argument, QObject *parent = Q_NULLPTR);
virtual QWidget * createEditor(QWidget * parent);
virtual QString value();
virtual bool isValid();
virtual bool isSetDefaultValueSupported();
public Q_SLOTS:
virtual void setDefaultValue();
protected:
QLineEdit * textBox;
};
class ExtArgNumber : public ExtArgText
{
Q_OBJECT
public:
ExtArgNumber(extcap_arg * argument, QObject *parent = Q_NULLPTR);
virtual QWidget * createEditor(QWidget * parent);
virtual QString defaultValue();
};
class ExtArgSelector : public ExtcapArgument
{
Q_OBJECT
public:
ExtArgSelector(extcap_arg * argument, QObject *parent = Q_NULLPTR);
virtual QWidget * createEditor(QWidget * parent);
virtual QString value();
virtual bool isValid();
virtual bool isSetDefaultValueSupported();
public Q_SLOTS:
virtual void setDefaultValue();
protected:
QComboBox * boxSelection;
private Q_SLOTS:
void onReloadTriggered();
};
class ExtArgEditSelector : public ExtArgSelector
{
Q_OBJECT
public:
ExtArgEditSelector(extcap_arg * argument, QObject *parent = Q_NULLPTR);
virtual QWidget * createEditor(QWidget * parent);
virtual QString value();
public Q_SLOTS:
virtual void setDefaultValue();
};
class ExtArgRadio : public ExtcapArgument
{
Q_OBJECT
public:
ExtArgRadio(extcap_arg * argument, QObject *parent = Q_NULLPTR);
virtual QWidget * createEditor(QWidget * parent);
virtual QString value();
virtual bool isValid();
virtual bool isSetDefaultValueSupported();
public Q_SLOTS:
virtual void setDefaultValue();
private:
QButtonGroup * selectorGroup;
QList<QString> * callStrings;
};
class ExtArgBool : public ExtcapArgument
{
Q_OBJECT
public:
ExtArgBool(extcap_arg * argument, QObject *parent = Q_NULLPTR);
virtual QWidget * createLabel(QWidget * parent);
virtual QWidget * createEditor(QWidget * parent);
virtual QString call();
virtual QString value();
virtual bool isValid();
virtual QString defaultValue();
virtual QString prefValue();
virtual bool isSetDefaultValueSupported();
public Q_SLOTS:
virtual void setDefaultValue();
private:
QCheckBox * boolBox;
bool defaultBool();
};
class ExtArgTimestamp : public ExtcapArgument
{
Q_OBJECT
public:
ExtArgTimestamp(extcap_arg * argument, QObject *parent = Q_NULLPTR);
virtual QWidget * createEditor(QWidget * parent);
virtual bool isValid();
virtual QString defaultValue();
virtual QString value();
virtual QString prefValue();
virtual bool isSetDefaultValueSupported();
public Q_SLOTS:
virtual void setDefaultValue();
private Q_SLOTS:
void onDateTimeChanged(QDateTime);
private:
QDateTime ts;
QDateTimeEdit *tsBox;
};
#endif /* UI_QT_EXTCAP_ARGUMENT_H_ */ |
C++ | wireshark/ui/qt/extcap_argument_file.cpp | /* extcap_argument_file.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <extcap_argument.h>
#include <extcap_argument_file.h>
#include <wsutil/utf8_entities.h>
#include "ui/qt/widgets/wireshark_file_dialog.h"
#include <QObject>
#include <QWidget>
#include <QLabel>
#include <QLineEdit>
#include <QBoxLayout>
#include <QPushButton>
#include <QDir>
#include <QFileInfo>
#include <QVariant>
#include <epan/prefs.h>
#include <ui/qt/utils/color_utils.h>
#include <ui/all_files_wildcard.h>
#include <extcap_parser.h>
ExtcapArgumentFileSelection::ExtcapArgumentFileSelection (extcap_arg * argument, QObject *parent) :
ExtcapArgument(argument, parent), textBox(0)
{
}
ExtcapArgumentFileSelection::~ExtcapArgumentFileSelection()
{
if (textBox != NULL)
delete textBox;
}
QWidget * ExtcapArgumentFileSelection::createEditor(QWidget * parent)
{
QString text = defaultValue();
QString buttonText(UTF8_HORIZONTAL_ELLIPSIS);
QString buttonClearText(tr("Clear"));
QWidget * fileWidget = new QWidget(parent);
QHBoxLayout * editLayout = new QHBoxLayout();
QMargins margins = editLayout->contentsMargins();
editLayout->setContentsMargins(0, 0, 0, margins.bottom());
fileWidget->setContentsMargins(margins.left(), margins.right(), 0, margins.bottom());
QPushButton * buttonSelect = new QPushButton(buttonText, fileWidget);
QPushButton * buttonClear = new QPushButton(buttonClearText, fileWidget);
textBox = new QLineEdit(text, parent);
textBox->setReadOnly(true);
/* Value is empty if no file is selected */
const char *prefval = (_argument->pref_valptr && (*_argument->pref_valptr)) ? *_argument->pref_valptr : NULL;
if (prefval)
{
QString storeValue(prefval);
if (storeValue.length() > 0 && storeValue.compare(text) != 0)
text = storeValue.trimmed();
}
textBox->setText(text);
if (_argument->tooltip != NULL)
{
textBox->setToolTip(QString().fromUtf8(_argument->tooltip));
buttonSelect->setToolTip(QString().fromUtf8(_argument->tooltip));
}
connect(buttonSelect, &QPushButton::clicked, this, &ExtcapArgumentFileSelection::openFileDialog);
connect(buttonClear, &QPushButton::clicked, this, &ExtcapArgumentFileSelection::clearFilename);
editLayout->addWidget(textBox);
editLayout->addWidget(buttonSelect);
editLayout->addWidget(buttonClear);
fileWidget->setLayout(editLayout);
return fileWidget;
}
QString ExtcapArgumentFileSelection::value()
{
if (textBox == 0)
return QString();
return textBox->text();
}
/* opens the file dialog */
void ExtcapArgumentFileSelection::openFileDialog()
{
QString filename = textBox->text();
QDir workingDir = QDir::currentPath();
if (QFileInfo(filename).exists())
workingDir = QFileInfo(filename).dir();
QString fileExt(tr("All Files (" ALL_FILES_WILDCARD ")"));
if (_argument->fileextension != NULL)
{
QString givenExt = QString().fromUtf8(_argument->fileextension);
if (givenExt.length() != 0)
fileExt.prepend(";;").prepend(givenExt);
}
if (fileExists())
{
/* UI should check that the file exists */
filename = WiresharkFileDialog::getOpenFileName((QWidget*)(textBox->parent()),
QString().fromUtf8(_argument->display) + " " + tr("Open File"),
workingDir.absolutePath(), fileExt);
}
else
{
/* File might or might not exist. Actual overwrite handling is extcap specific
* (e.g. boolflag argument if user wants to always overwrite the file)
*/
filename = WiresharkFileDialog::getSaveFileName((QWidget*)(textBox->parent()),
QString().fromUtf8(_argument->display) + " " + tr("Select File"),
workingDir.absolutePath(), fileExt, nullptr, QFileDialog::Option::DontConfirmOverwrite);
}
if (! filename.isEmpty() && (! fileExists() || QFileInfo(filename).exists()))
{
textBox->setText(filename);
emit valueChanged();
}
}
void ExtcapArgumentFileSelection::clearFilename()
{
textBox->clear();
emit valueChanged();
}
bool ExtcapArgumentFileSelection::isValid()
{
bool valid = false;
if (textBox->text().length() > 0)
{
if (_argument->fileexists)
valid = QFileInfo(textBox->text()).exists();
else
valid = true;
}
else if (! isRequired())
valid = true;
QString lblInvalidColor = ColorUtils::fromColorT(prefs.gui_text_invalid).name();
QString txtStyle("QLineEdit { background-color: %1; } ");
textBox->setStyleSheet(txtStyle.arg(valid ? QString("") : lblInvalidColor));
return valid;
}
void ExtcapArgumentFileSelection::setDefaultValue()
{
clearFilename();
} |
C/C++ | wireshark/ui/qt/extcap_argument_file.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef UI_QT_EXTCAP_ARGUMENT_FILE_H_
#define UI_QT_EXTCAP_ARGUMENT_FILE_H_
#include <QObject>
#include <QWidget>
#include <QLineEdit>
#include <extcap_parser.h>
#include <extcap_argument.h>
class ExtcapArgumentFileSelection : public ExtcapArgument
{
Q_OBJECT
public:
ExtcapArgumentFileSelection(extcap_arg * argument, QObject * parent = Q_NULLPTR);
virtual ~ExtcapArgumentFileSelection();
virtual QWidget * createEditor(QWidget * parent);
virtual QString value();
virtual bool isValid();
virtual void setDefaultValue();
protected:
QLineEdit * textBox;
private slots:
/* opens the file dialog */
void openFileDialog();
/* clears previously entered filename */
void clearFilename();
};
#endif /* UI_QT_EXTCAP_ARGUMENT_FILE_H_ */ |
C++ | wireshark/ui/qt/extcap_argument_multiselect.cpp | /* extcap_argument_multiselect.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <extcap_argument.h>
#include <extcap_argument_file.h>
#include <wsutil/utf8_entities.h>
#include <QObject>
#include <QWidget>
#include <QLabel>
#include <QLineEdit>
#include <QBoxLayout>
#include <QPushButton>
#include <QVariant>
#include <epan/prefs.h>
#include <ui/qt/utils/color_utils.h>
#include <extcap_parser.h>
#include <extcap_argument_multiselect.h>
ExtArgMultiSelect::ExtArgMultiSelect(extcap_arg * argument, QObject *parent) :
ExtcapArgument(argument, parent), treeView(0), viewModel(0) {}
ExtArgMultiSelect::~ExtArgMultiSelect()
{
if (treeView != 0)
delete treeView;
if (viewModel != 0)
delete viewModel;
}
QList<QStandardItem *> ExtArgMultiSelect::valueWalker(ExtcapValueList list, QStringList &defaults)
{
ExtcapValueList::iterator iter = list.begin();
QList<QStandardItem *> items;
while (iter != list.end())
{
QStandardItem * item = new QStandardItem((*iter).value());
if ((*iter).enabled() == false)
{
item->setCheckable(false);
}
else
{
item->setCheckable(true);
}
item->setData((*iter).call(), Qt::UserRole);
if ((*iter).isDefault())
defaults << (*iter).call();
item->setSelectable(false);
item->setEditable(false);
QList<QStandardItem *> childs = valueWalker((*iter).children(), defaults);
if (childs.length() > 0)
item->appendRows(childs);
items << item;
++iter;
}
return items;
}
void ExtArgMultiSelect::checkItemsWalker(QStandardItem * item, QStringList defaults)
{
QModelIndexList results;
QModelIndex index;
if (item->hasChildren())
{
for (int row = 0; row < item->rowCount(); row++)
{
QStandardItem * child = item->child(row);
if (child != 0)
{
checkItemsWalker(child, defaults);
}
}
}
QString data = item->data(Qt::UserRole).toString();
if (defaults.contains(data))
{
item->setCheckState(Qt::Checked);
index = item->index();
while (index.isValid())
{
treeView->setExpanded(index, true);
index = index.parent();
}
} else if (item->isCheckable()) {
item->setCheckState(Qt::Unchecked);
}
}
QWidget * ExtArgMultiSelect::createEditor(QWidget * parent)
{
QStringList checked;
QList<QStandardItem *> items = valueWalker(values, checked);
if (items.length() == 0)
return new QWidget();
/* Value can be empty if no items are checked */
if (_argument->pref_valptr && (*_argument->pref_valptr))
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
checked = QString(*_argument->pref_valptr).split(",", Qt::SkipEmptyParts);
#else
checked = QString(*_argument->pref_valptr).split(",", QString::SkipEmptyParts);
#endif
}
viewModel = new QStandardItemModel();
QList<QStandardItem *>::const_iterator iter = items.constBegin();
while (iter != items.constEnd())
{
((QStandardItemModel *)viewModel)->appendRow((*iter));
++iter;
}
treeView = new QTreeView(parent);
treeView->setModel(viewModel);
/* Shows at minimum 6 entries at most desktops */
treeView->setMinimumHeight(100);
treeView->setHeaderHidden(true);
treeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
for (int row = 0; row < viewModel->rowCount(); row++)
checkItemsWalker(((QStandardItemModel*)viewModel)->item(row), checked);
connect (viewModel,
SIGNAL(itemChanged(QStandardItem *)),
SLOT(itemChanged(QStandardItem *)));
return treeView;
}
QString ExtArgMultiSelect::value()
{
if (viewModel == 0)
return QString();
QStringList result;
QModelIndexList checked = viewModel->match(viewModel->index(0, 0), Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchExactly | Qt::MatchRecursive);
if (checked.size() <= 0)
return QString();
QModelIndexList::const_iterator iter = checked.constBegin();
while (iter != checked.constEnd())
{
QModelIndex index = (QModelIndex)(*iter);
result << viewModel->data(index, Qt::UserRole).toString();
++iter;
}
return result.join(QString(','));
}
void ExtArgMultiSelect::itemChanged(QStandardItem *)
{
emit valueChanged();
}
bool ExtArgMultiSelect::isValid()
{
bool valid = true;
if (isRequired())
{
if (viewModel == 0)
valid = false;
else
{
QModelIndexList checked = viewModel->match(viewModel->index(0, 0), Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchExactly | Qt::MatchRecursive);
if (checked.size() <= 0)
valid = false;
}
}
QString lblInvalidColor = ColorUtils::fromColorT(prefs.gui_text_invalid).name();
QString txtStyle("QTreeView { background-color: %1; } ");
if (viewModel != 0)
treeView->setStyleSheet(txtStyle.arg(valid ? QString("") : lblInvalidColor));
return valid;
}
QString ExtArgMultiSelect::defaultValue()
{
QStringList checked;
QList<QStandardItem *> items = valueWalker(values, checked);
return checked.join(QString(','));
}
bool ExtArgMultiSelect::isSetDefaultValueSupported()
{
return TRUE;
}
void ExtArgMultiSelect::setDefaultValue()
{
QStringList checked;
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
checked = defaultValue().split(",", Qt::SkipEmptyParts);
#else
checked = defaultValue().split(",", QString::SkipEmptyParts);
#endif
for (int row = 0; row < viewModel->rowCount(); row++)
checkItemsWalker(((QStandardItemModel*)viewModel)->item(row), checked);
} |
C/C++ | wireshark/ui/qt/extcap_argument_multiselect.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef UI_QT_EXTCAP_ARGUMENT_MULTISELECT_H_
#define UI_QT_EXTCAP_ARGUMENT_MULTISELECT_H_
#include <QObject>
#include <QWidget>
#include <QStandardItem>
#include <QTreeView>
#include <QAbstractItemModel>
#include <QItemSelection>
#include <extcap_parser.h>
#include <extcap_argument.h>
class ExtArgMultiSelect : public ExtcapArgument
{
Q_OBJECT
public:
ExtArgMultiSelect(extcap_arg * argument, QObject *parent = Q_NULLPTR);
virtual ~ExtArgMultiSelect();
virtual QString value();
virtual bool isValid();
virtual QString defaultValue();
virtual bool isSetDefaultValueSupported();
public Q_SLOTS:
virtual void setDefaultValue();
protected:
virtual QList<QStandardItem *> valueWalker(ExtcapValueList list, QStringList &defaults);
void checkItemsWalker(QStandardItem * item, QStringList defaults);
virtual QWidget * createEditor(QWidget * parent);
private Q_SLOTS:
void itemChanged(QStandardItem *);
private:
QTreeView * treeView;
QAbstractItemModel * viewModel;
};
#endif /* UI_QT_EXTCAP_ARGUMENT_MULTISELECT_H_ */ |
C++ | wireshark/ui/qt/extcap_options_dialog.cpp | /* extcap_options_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 <extcap_options_dialog.h>
#include <ui_extcap_options_dialog.h>
#include <main_application.h>
#include <QMessageBox>
#include <QHash>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QGridLayout>
#include <QUrl>
#include <QDesktopServices>
#include <QTabWidget>
#include "ringbuffer.h"
#include "ui/capture_ui_utils.h"
#include "ui/capture_globals.h"
#include "ui/iface_lists.h"
#include "ui/last_open_dir.h"
#include "ui/ws_ui_util.h"
#include "ui/util.h"
#include <wsutil/utf8_entities.h>
#include <cstdio>
#include <epan/addr_resolv.h>
#include <wsutil/filesystem.h>
#include <extcap.h>
#include <extcap_parser.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <epan/prefs.h>
#include <ui/preference_utils.h>
#include <ui/qt/main_application.h>
#include <ui/qt/utils/stock_icon.h>
#include <ui/qt/utils/variant_pointer.h>
#include <ui/qt/extcap_argument.h>
#include <ui/qt/extcap_argument_file.h>
#include <ui/qt/extcap_argument_multiselect.h>
ExtcapOptionsDialog::ExtcapOptionsDialog(bool startCaptureOnClose, QWidget *parent) :
QDialog(parent),
ui(new Ui::ExtcapOptionsDialog),
device_name(""),
device_idx(0),
defaultValueIcon_(StockIcon("x-reset"))
{
ui->setupUi(this);
setWindowTitle(mainApp->windowTitleString(tr("Interface Options")));
ui->checkSaveOnStart->setCheckState(prefs.extcap_save_on_start ? Qt::Checked : Qt::Unchecked);
if (startCaptureOnClose) {
ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Start"));
} else {
ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Save"));
}
}
ExtcapOptionsDialog * ExtcapOptionsDialog::createForDevice(QString &dev_name, bool startCaptureOnClose, QWidget *parent)
{
interface_t *device;
ExtcapOptionsDialog * resultDialog = NULL;
bool dev_found = false;
guint if_idx;
if (dev_name.length() == 0)
return NULL;
for (if_idx = 0; if_idx < global_capture_opts.all_ifaces->len; if_idx++)
{
device = &g_array_index(global_capture_opts.all_ifaces, interface_t, if_idx);
if (dev_name.compare(QString(device->name)) == 0 && device->if_info.type == IF_EXTCAP)
{
dev_found = true;
break;
}
}
if (! dev_found)
return NULL;
resultDialog = new ExtcapOptionsDialog(startCaptureOnClose, parent);
resultDialog->device_name = QString(dev_name);
resultDialog->device_idx = if_idx;
resultDialog->setWindowTitle(mainApp->windowTitleString(tr("Interface Options") + ": " + device->display_name));
resultDialog->updateWidgets();
/* mark required fields */
resultDialog->anyValueChanged();
return resultDialog;
}
ExtcapOptionsDialog::~ExtcapOptionsDialog()
{
delete ui;
}
void ExtcapOptionsDialog::on_buttonBox_accepted()
{
if (saveOptionToCaptureInfo()) {
/* Starting a new capture with those values */
prefs.extcap_save_on_start = ui->checkSaveOnStart->checkState() == Qt::Checked;
if (prefs.extcap_save_on_start)
storeValues();
accept();
}
}
void ExtcapOptionsDialog::anyValueChanged()
{
bool allowStart = true;
ExtcapArgumentList::const_iterator iter;
/* All arguments are being iterated, to ensure, that any error handling catches all arguments */
for (iter = extcapArguments.constBegin(); iter != extcapArguments.constEnd(); ++iter)
{
/* The dynamic casts are necessary, because we come here using the Signal/Slot system
* of Qt, and -in short- Q_OBJECT classes cannot be multiple inherited. Another possibility
* would be to use Q_INTERFACE, but this causes way more nightmares, and we really just
* need here an explicit cast for the check functionality */
if (dynamic_cast<ExtArgBool *>((*iter)) != NULL)
{
if (! ((ExtArgBool *)*iter)->isValid())
allowStart = false;
}
else if (dynamic_cast<ExtArgRadio *>((*iter)) != NULL)
{
if (! ((ExtArgRadio *)*iter)->isValid())
allowStart = false;
}
else if (dynamic_cast<ExtArgSelector *>((*iter)) != NULL)
{
if (! ((ExtArgSelector *)*iter)->isValid())
allowStart = false;
}
else if (dynamic_cast<ExtArgMultiSelect *>((*iter)) != NULL)
{
if (! ((ExtArgMultiSelect *)*iter)->isValid())
allowStart = false;
}
else if (dynamic_cast<ExtcapArgumentFileSelection *>((*iter)) != NULL)
{
if (! ((ExtcapArgumentFileSelection *)*iter)->isValid())
allowStart = false;
}
else if (dynamic_cast<ExtArgNumber *>((*iter)) != NULL)
{
if (! ((ExtArgNumber *)*iter)->isValid())
allowStart = false;
}
else if (dynamic_cast<ExtArgText *>((*iter)) != NULL)
{
if (! ((ExtArgText *)*iter)->isValid())
allowStart = false;
}
else if (dynamic_cast<ExtArgTimestamp *>((*iter)) != NULL)
{
if (! ((ExtArgTimestamp *)*iter)->isValid())
allowStart = false;
}
else
if (! (*iter)->isValid())
allowStart = false;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(allowStart);
}
void ExtcapOptionsDialog::loadArguments()
{
GList * arguments = Q_NULLPTR, * walker = Q_NULLPTR, * item = Q_NULLPTR;
ExtcapArgument * argument = Q_NULLPTR;
if (device_name.length() == 0 )
return;
extcapArguments.clear();
arguments = g_list_first(extcap_get_if_configuration(device_name.toUtf8().constData()));
ExtcapArgumentList required;
ExtcapArgumentList optional;
walker = arguments;
while (walker != Q_NULLPTR)
{
item = g_list_first(gxx_list_data(GList *, walker));
while (item != Q_NULLPTR)
{
argument = ExtcapArgument::create(gxx_list_data(extcap_arg *, item), this);
if (argument != Q_NULLPTR)
{
if (argument->isRequired())
required << argument;
else
optional << argument;
}
item = item->next;
}
walker = gxx_list_next(walker);
}
if (required.length() > 0)
extcapArguments << required;
if (optional.length() > 0)
extcapArguments << optional;
/* argument items are now owned by ExtcapArgument. Only free the lists */
extcap_free_if_configuration(arguments, FALSE);
}
void ExtcapOptionsDialog::updateWidgets()
{
QWidget * lblWidget = NULL, *editWidget = NULL;
ExtcapArgument * argument = NULL;
bool allowStart = true;
unsigned int counter = 0;
if (device_name.length() == 0 )
return;
/* find existing layout */
if (ui->verticalLayout->children().count() > 0)
{
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
QWidget * item = ui->verticalLayout->itemAt(0)->widget();
if (item)
{
ui->verticalLayout->removeItem(ui->verticalLayout->itemAt(0));
delete item;
}
}
QHash<QString, QWidget *> layouts;
/* Load all extcap arguments */
loadArguments();
/* exit if no arguments have been found. This is a precaution, it should
* never happen, that this dialog get's called without any arguments */
if (extcapArguments.count() == 0)
{
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
return;
}
ui->checkSaveOnStart->setText(tr("Save parameter(s) on capture start", "", static_cast<int>(extcapArguments.count())));
QStringList groupKeys;
QString defaultKeyName(tr("Default"));
/* QMap sorts keys, therefore the groups are sorted by appearance */
QMap<int, QString> groups;
/* Look for all necessary tabs */
ExtcapArgumentList::iterator iter = extcapArguments.begin();
while (iter != extcapArguments.end())
{
argument = (ExtcapArgument *)(*iter);
QString groupKey = argument->group();
if (groupKey.length() > 0)
{
if (! groups.values().contains(groupKey))
groups.insert(argument->argNr(), groupKey);
}
else if (! groups.keys().contains(0))
{
groups.insert(0, defaultKeyName);
groupKey = defaultKeyName;
}
if (! layouts.keys().contains(groupKey))
{
QWidget * tabWidget = new QWidget(this);
QGridLayout * tabLayout = new QGridLayout(tabWidget);
tabWidget->setLayout(tabLayout);
layouts.insert(groupKey, tabWidget);
}
++iter;
}
groupKeys << groups.values();
/* Iterate over all arguments and do the following:
* 1. create the label for each element
* 2. create an editor for each element
* 3. add both to the layout for the tab widget
*/
iter = extcapArguments.begin();
while (iter != extcapArguments.end())
{
argument = (ExtcapArgument *)(*iter);
QString groupKey = defaultKeyName;
if (argument->group().length() > 0)
groupKey = argument->group();
/* Skip non-assigned group keys, this happens if the configuration of the extcap is faulty */
if (! layouts.keys().contains(groupKey))
{
++iter;
continue;
}
QGridLayout * layout = ((QGridLayout *)layouts[groupKey]->layout());
lblWidget = argument->createLabel((QWidget *)this);
if (lblWidget != NULL)
{
layout->addWidget(lblWidget, counter, 0, Qt::AlignVCenter);
editWidget = argument->createEditor((QWidget *) this);
if (editWidget != NULL)
{
editWidget->setProperty("extcap", VariantPointer<ExtcapArgument>::asQVariant(argument));
layout->addWidget(editWidget, counter, 1, Qt::AlignVCenter);
if (argument->isSetDefaultValueSupported())
{
QPushButton *button = new QPushButton(defaultValueIcon_,"");
button->setToolTip(tr("Restore default value of the item"));
layout->addWidget(button, counter, 2, Qt::AlignVCenter);
connect(button, SIGNAL(clicked()), argument, SLOT(setDefaultValue()));
}
}
if (argument->isRequired() && ! argument->isValid())
allowStart = false;
connect(argument, &ExtcapArgument::valueChanged, this, &ExtcapOptionsDialog::anyValueChanged);
counter++;
}
++iter;
}
if (counter > 0)
{
setStyleSheet ("QLabel[isRequired=\"true\"] { font-weight: bold; } ");
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(allowStart);
QWidget * mainWidget = Q_NULLPTR;
/* We should never display the dialog, if no settings are present */
Q_ASSERT(layouts.count() > 0);
if (layouts.count() > 1)
{
QTabWidget * tabs = new QTabWidget(this);
foreach (QString key, groupKeys)
{
layouts[key]->layout()->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding));
tabs->addTab(layouts[key], key);
}
tabs->setCurrentIndex(0);
mainWidget = tabs;
}
else if (layouts.count() == 1)
mainWidget = layouts[layouts.keys().at(0)];
ui->verticalLayout->addWidget(mainWidget);
ui->verticalLayout->addSpacerItem(new QSpacerItem(20, 100, QSizePolicy::Minimum, QSizePolicy::Expanding));
}
else
{
QList<QString> keys = layouts.keys();
foreach (QString key, keys)
delete(layouts[key]);
}
}
// Not sure why we have to do this manually.
void ExtcapOptionsDialog::on_buttonBox_rejected()
{
reject();
}
void ExtcapOptionsDialog::on_buttonBox_helpRequested()
{
interface_t *device;
QString interface_help = NULL;
device = &g_array_index(global_capture_opts.all_ifaces, interface_t, device_idx);
interface_help = QString(extcap_get_help_for_ifname(device->name));
/* The extcap interface didn't provide an help. Let's go with the default */
if (interface_help.isEmpty()) {
mainApp->helpTopicAction(HELP_EXTCAP_OPTIONS_DIALOG);
return;
}
QUrl help_url(interface_help);
/* Check the existence for a local file */
if (help_url.isLocalFile()) {
QString local_path = help_url.toLocalFile();
QFileInfo help_file(local_path);
if (!help_file.exists()) {
QMessageBox::warning(this, tr("Extcap Help cannot be found"),
QString(tr("The help for the extcap interface %1 cannot be found. Given file: %2"))
.arg(device->name).arg(QDir::toNativeSeparators(local_path)),
QMessageBox::Ok);
return;
}
}
/* We have an actual url or an existing local file. Let's open it. */
QDesktopServices::openUrl(help_url);
}
bool ExtcapOptionsDialog::saveOptionToCaptureInfo()
{
GHashTable * ret_args;
interface_t *device;
device = &g_array_index(global_capture_opts.all_ifaces, interface_t, device_idx);
ret_args = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
ExtcapArgumentList::const_iterator iter;
for (iter = extcapArguments.constBegin(); iter != extcapArguments.constEnd(); ++iter)
{
QString call = (*iter)->call();
QString value = (*iter)->value();
QString prefValue = (*iter)->prefValue();
if ((*iter)->argument()->arg_type != EXTCAP_ARG_BOOLFLAG && value.length() == 0)
continue;
if (call.length() <= 0) {
/* BOOLFLAG was cleared, make its value empty */
if ((*iter)->argument()->arg_type == EXTCAP_ARG_BOOLFLAG) {
*(*iter)->argument()->pref_valptr[0] = 0;
}
continue;
}
if (value.compare((*iter)->defaultValue()) == 0) {
extcap_arg *arg = (*iter)->argument();
// If previous value is not default, set it to default value
if (arg->default_complex != NULL && arg->default_complex->_val != NULL) {
g_free(*arg->pref_valptr);
*arg->pref_valptr = g_strdup(arg->default_complex->_val);
} else {
// Set empty value if there is no default value
*arg->pref_valptr[0] = 0;
}
continue;
}
gchar * call_string = qstring_strdup(call);
gchar * value_string = NULL;
if (value.length() > 0)
value_string = qstring_strdup(value);
g_hash_table_insert(ret_args, call_string, value_string);
// For current value we need strdup even it is empty
value_string = qstring_strdup(prefValue);
// Update current value with new value
// We use prefValue because for bool/boolflag it returns value
// even it is false
g_free(*(*iter)->argument()->pref_valptr);
*(*iter)->argument()->pref_valptr = value_string;
}
if (device->external_cap_args_settings != NULL)
g_hash_table_unref(device->external_cap_args_settings);
device->external_cap_args_settings = ret_args;
return true;
}
void ExtcapOptionsDialog::on_buttonBox_clicked(QAbstractButton *button)
{
/* Only the save button has the ActionRole */
if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::ResetRole)
resetValues();
}
void ExtcapOptionsDialog::resetValues()
{
int count = ui->verticalLayout->count();
if (count > 0)
{
QList<QLayout *> layouts;
/* Find all layouts */
if (qobject_cast<QTabWidget *>(ui->verticalLayout->itemAt(0)->widget()))
{
QTabWidget * tabs = qobject_cast<QTabWidget *>(ui->verticalLayout->itemAt(0)->widget());
for (int cnt = 0; cnt < tabs->count(); cnt++)
{
layouts.append(tabs->widget(cnt)->layout());
}
}
else
layouts.append(ui->verticalLayout->itemAt(0)->layout());
/* Loop over all layouts */
for (int cnt = 0; cnt < layouts.count(); cnt++)
{
QGridLayout * layout = qobject_cast<QGridLayout *>(layouts.at(cnt));
if (! layout)
continue;
/* Loop over all widgets in column 1 on layout */
for (int row = 0; row < layout->rowCount(); row++)
{
QWidget * child = Q_NULLPTR;
if (layout->itemAtPosition(row, 1))
child = qobject_cast<QWidget *>(layout->itemAtPosition(row, 1)->widget());
if (child)
{
/* Don't need labels, the edit widget contains the extcapargument property value */
ExtcapArgument * arg = 0;
QVariant prop = child->property("extcap");
if (prop.isValid())
{
arg = VariantPointer<ExtcapArgument>::asPtr(prop);
/* value<> can fail */
if (arg)
{
arg->setDefaultValue();
}
}
}
}
}
/* Values are stored when dialog is commited, just check validity*/
anyValueChanged();
}
}
GHashTable *ExtcapOptionsDialog::getArgumentSettings(bool useCallsAsKey, bool includeEmptyValues)
{
GHashTable * entries = g_hash_table_new(g_str_hash, g_str_equal);
ExtcapArgumentList::const_iterator iter;
QString value;
/* All arguments are being iterated, to ensure, that any error handling catches all arguments */
for (iter = extcapArguments.constBegin(); iter != extcapArguments.constEnd(); ++iter)
{
ExtcapArgument * argument = (ExtcapArgument *)(*iter);
bool isBoolflag = false;
/* The dynamic casts are necessary, because we come here using the Signal/Slot system
* of Qt, and -in short- Q_OBJECT classes cannot be multiple inherited. Another possibility
* would be to use Q_INTERFACE, but this causes way more nightmares, and we really just
* need here an explicit cast for the check functionality */
if (dynamic_cast<ExtArgBool *>((*iter)) != NULL)
{
value = ((ExtArgBool *)*iter)->prefValue();
// For boolflag there should be no value
if ((*iter)->argument()->arg_type != EXTCAP_ARG_BOOLFLAG)
isBoolflag = true;
}
else if (dynamic_cast<ExtArgRadio *>((*iter)) != NULL)
{
value = ((ExtArgRadio *)*iter)->prefValue();
}
else if (dynamic_cast<ExtArgSelector *>((*iter)) != NULL)
{
value = ((ExtArgSelector *)*iter)->prefValue();
}
else if (dynamic_cast<ExtArgMultiSelect *>((*iter)) != NULL)
{
value = ((ExtArgMultiSelect *)*iter)->prefValue();
}
else if (dynamic_cast<ExtcapArgumentFileSelection *>((*iter)) != NULL)
{
value = ((ExtcapArgumentFileSelection *)*iter)->prefValue();
}
else if (dynamic_cast<ExtArgNumber *>((*iter)) != NULL)
{
value = ((ExtArgNumber *)*iter)->prefValue();
}
else if (dynamic_cast<ExtArgText *>((*iter)) != NULL)
{
value = ((ExtArgText *)*iter)->prefValue();
}
else if (dynamic_cast<ExtArgTimestamp *>((*iter)) != NULL)
{
value = ((ExtArgTimestamp *)*iter)->prefValue();
}
else
value = (*iter)->prefValue();
QString key = argument->prefKey(device_name);
if (useCallsAsKey)
key = argument->call();
if ((key.length() > 0) && (includeEmptyValues || isBoolflag || value.length() > 0) )
{
gchar * val = qstring_strdup(value);
g_hash_table_insert(entries, qstring_strdup(key), val);
}
}
return entries;
}
void ExtcapOptionsDialog::storeValues()
{
GHashTable * entries = getArgumentSettings();
if (g_hash_table_size(entries) > 0)
{
if (prefs_store_ext_multiple("extcap", entries))
mainApp->emitAppSignal(MainApplication::PreferencesChanged);
}
}
ExtcapValueList ExtcapOptionsDialog::loadValuesFor(int argNum, QString argumentName, QString parent)
{
ExtcapValueList elements;
GList * walker = 0, * values = 0;
extcap_value * v;
QList<QWidget *> children = findChildren<QWidget *>();
foreach (QWidget * child, children)
child->setEnabled(false);
QString argcall = argumentName;
if (argcall.startsWith("--"))
argcall = argcall.right(argcall.size()-2);
GHashTable * entries = getArgumentSettings(true, false);
values = extcap_get_if_configuration_values(this->device_name.toStdString().c_str(), argcall.toStdString().c_str(), entries);
for (walker = g_list_first((GList *)(values)); walker != NULL ; walker = walker->next)
{
v = (extcap_value *) walker->data;
if (v == NULL || v->display == NULL || v->call == NULL)
break;
/* Only accept values for this argument */
if (v->arg_num != argNum)
break;
QString valParent = QString().fromUtf8(v->parent);
if (parent.compare(valParent) == 0)
{
QString display = QString().fromUtf8(v->display);
QString call = QString().fromUtf8(v->call);
ExtcapValue element = ExtcapValue(display, call,
v->enabled == (gboolean)TRUE, v->is_default == (gboolean)TRUE);
#if 0
/* TODO: Disabled due to wrong parent handling. It leads to an infinite loop for now. To implement this properly, other things
will be needed, like new arguments for setting the parent in the call to the extcap utility*/
if (!call.isEmpty())
element.setChildren(this->loadValuesFor(argumentName, call));
#endif
elements.append(element);
}
}
foreach (QWidget * child, children)
child->setEnabled(true);
return elements;
} |
C/C++ | wireshark/ui/qt/extcap_options_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 EXTCAP_OPTIONS_DIALOG_H
#define EXTCAP_OPTIONS_DIALOG_H
#include <config.h>
#include <QWidget>
#include <QDialog>
#include <QPushButton>
#include <QList>
#include "ui/qt/extcap_argument.h"
#include <extcap.h>
#include <extcap_parser.h>
namespace Ui {
class ExtcapOptionsDialog;
}
typedef QList<ExtcapArgument *> ExtcapArgumentList;
class ExtcapOptionsDialog : public QDialog
{
Q_OBJECT
public:
~ExtcapOptionsDialog();
static ExtcapOptionsDialog * createForDevice(QString &device_name, bool startCaptureOnClose, QWidget *parent = 0);
ExtcapValueList loadValuesFor(int argNum, QString call, QString parent = "");
private Q_SLOTS:
void on_buttonBox_accepted();
void on_buttonBox_rejected();
void on_buttonBox_clicked(QAbstractButton *button);
void on_buttonBox_helpRequested();
void updateWidgets();
void anyValueChanged();
private:
explicit ExtcapOptionsDialog(bool startCaptureOnClose, QWidget *parent = 0);
Ui::ExtcapOptionsDialog *ui;
QString device_name;
guint device_idx;
QIcon defaultValueIcon_;
ExtcapArgumentList extcapArguments;
void loadArguments();
bool saveOptionToCaptureInfo();
GHashTable * getArgumentSettings(bool useCallsAsKey = false, bool includeEmptyValues = true);
void storeValues();
void resetValues();
};
#endif // EXTCAP_OPTIONS_DIALOG_H |
User Interface | wireshark/ui/qt/extcap_options_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ExtcapOptionsDialog</class>
<widget class="QDialog" name="ExtcapOptionsDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>600</width>
<height>92</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>600</width>
<height>0</height>
</size>
</property>
<layout class="QVBoxLayout" name="verticalLayout_12">
<item>
<layout class="QVBoxLayout" name="verticalLayout"/>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkSaveOnStart">
<property name="text">
<string>Save parameter(s) on capture start</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="standardButtons">
<set>QDialogButtonBox::Close|QDialogButtonBox::Help|QDialogButtonBox::Ok|QDialogButtonBox::RestoreDefaults</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui> |
C++ | wireshark/ui/qt/file_set_dialog.cpp | /* fileset_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 "file.h"
#include "fileset.h"
#include "ui/help_url.h"
#include <wsutil/str_util.h>
#include "file_set_dialog.h"
#include <ui_file_set_dialog.h>
#include "models/fileset_entry_model.h"
#include "main_application.h"
#include <QDialogButtonBox>
#include <QPushButton>
#include <QDateTime>
#include <QFontMetrics>
#include <QFont>
#include <QUrl>
// To do:
// - We might want to rename this to FilesetDialog / fileset_dialog.{cpp,h}.
void
fileset_dlg_begin_add_file(void *window) {
FileSetDialog *fs_dlg = static_cast<FileSetDialog *>(window);
if (fs_dlg) fs_dlg->beginAddFile();
}
/* This file is a part of the current file set. Add it to our model. */
void
fileset_dlg_add_file(fileset_entry *entry, void *window) {
FileSetDialog *fs_dlg = static_cast<FileSetDialog *>(window);
if (fs_dlg) fs_dlg->addFile(entry);
}
void
fileset_dlg_end_add_file(void *window) {
FileSetDialog *fs_dlg = static_cast<FileSetDialog *>(window);
if (fs_dlg) fs_dlg->endAddFile();
}
FileSetDialog::FileSetDialog(QWidget *parent) :
GeometryStateDialog(parent),
fs_ui_(new Ui::FileSetDialog),
fileset_entry_model_(new FilesetEntryModel(this)),
close_button_(NULL)
{
fs_ui_->setupUi(this);
loadGeometry ();
fs_ui_->fileSetTree->setModel(fileset_entry_model_);
fs_ui_->fileSetTree->setFocus();
close_button_ = fs_ui_->buttonBox->button(QDialogButtonBox::Close);
connect(fs_ui_->fileSetTree->selectionModel(), &QItemSelectionModel::selectionChanged,
this, &FileSetDialog::selectionChanged);
beginAddFile();
addFile();
endAddFile();
}
FileSetDialog::~FileSetDialog()
{
fileset_entry_model_->clear();
delete fs_ui_;
}
/* a new capture file was opened, browse the dir and look for files matching the given file set */
void FileSetDialog::fileOpened(const capture_file *cf) {
if (!cf) return;
fileset_entry_model_->clear();
fileset_add_dir(cf->filename, this);
}
/* the capture file was closed */
void FileSetDialog::fileClosed() {
fileset_entry_model_->clear();
}
void FileSetDialog::addFile(fileset_entry *entry) {
if (!entry) return;
if (entry->current) {
cur_idx_ = fileset_entry_model_->entryCount();
}
fileset_entry_model_->appendEntry(entry);
}
void FileSetDialog::beginAddFile()
{
cur_idx_ = -1;
setWindowTitle(mainApp->windowTitleString(tr("No files in Set")));
fs_ui_->directoryLabel->setText(tr("No capture loaded"));
fs_ui_->directoryLabel->setEnabled(false);
}
void FileSetDialog::endAddFile()
{
if (fileset_entry_model_->entryCount() > 0) {
setWindowTitle(mainApp->windowTitleString(tr("%Ln File(s) in Set", "",
fileset_entry_model_->entryCount())));
}
QString dir_name = fileset_get_dirname();
fs_ui_->directoryLabel->setText(dir_name);
fs_ui_->directoryLabel->setUrl(QUrl::fromLocalFile(dir_name).toString());
fs_ui_->directoryLabel->setEnabled(true);
if (cur_idx_ >= 0) {
fs_ui_->fileSetTree->setCurrentIndex(fileset_entry_model_->index(cur_idx_, 0));
}
for (int col = 0; col < 4; col++) {
fs_ui_->fileSetTree->resizeColumnToContents(col);
}
if (close_button_)
close_button_->setEnabled(true);
}
void FileSetDialog::selectionChanged(const QItemSelection &selected, const QItemSelection &)
{
const fileset_entry *entry = fileset_entry_model_->getRowEntry(selected.first().top());
if (!entry || entry->current)
return;
QString new_cf_path = entry->fullname;
if (new_cf_path.length() > 0) {
emit fileSetOpenCaptureFile(new_cf_path);
}
}
void FileSetDialog::on_buttonBox_helpRequested()
{
mainApp->helpTopicAction(HELP_FILESET_DIALOG);
} |
C/C++ | wireshark/ui/qt/file_set_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 FILE_SET_DIALOG_H
#define FILE_SET_DIALOG_H
#include <config.h>
#include <glib.h>
#include "file.h"
#include "fileset.h"
#include "geometry_state_dialog.h"
#include <QItemSelection>
namespace Ui {
class FileSetDialog;
}
class FilesetEntryModel;
class FileSetDialog : public GeometryStateDialog
{
Q_OBJECT
public:
explicit FileSetDialog(QWidget *parent = 0);
~FileSetDialog();
void fileOpened(const capture_file *cf);
void fileClosed();
void addFile(fileset_entry *entry = NULL);
void beginAddFile();
void endAddFile();
signals:
void fileSetOpenCaptureFile(QString);
private slots:
void selectionChanged(const QItemSelection &selected, const QItemSelection &);
void on_buttonBox_helpRequested();
private:
Ui::FileSetDialog *fs_ui_;
FilesetEntryModel *fileset_entry_model_;
QPushButton *close_button_;
int cur_idx_;
};
#endif // FILE_SET_DIALOG_H |
User Interface | wireshark/ui/qt/file_set_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FileSetDialog</class>
<widget class="QDialog" name="FileSetDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>750</width>
<height>450</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<property name="sizeGripEnabled">
<bool>true</bool>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<layout class="QFormLayout" name="formLayout">
<property name="fieldGrowthPolicy">
<enum>QFormLayout::FieldsStayAtSizeHint</enum>
</property>
<item row="1" column="0" colspan="2">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Directory:</string>
</property>
</widget>
</item>
<item>
<widget class="ElidedLabel" name="directoryLabel">
<property name="sizePolicy">
<sizepolicy hsizetype="Ignored" vsizetype="Preferred">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string/>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse|Qt::TextBrowserInteraction|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
</layout>
</item>
<item row="2" column="0" colspan="2">
<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>
<item row="0" column="0" colspan="2">
<widget class="QTreeView" name="fileSetTree">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
<property name="textElideMode">
<enum>Qt::ElideLeft</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="expandsOnDoubleClick">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</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>FileSetDialog</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>FileSetDialog</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/filter_action.cpp | /* filter_action.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "filter_action.h"
#include <ui/qt/main_application.h>
#include <ui/qt/main_window.h>
#include <QClipboard>
#include <QMenu>
FilterAction::FilterAction(QObject *parent, FilterAction::Action action, FilterAction::ActionType type, QString actionName) :
QAction(parent),
action_(action),
type_(type),
actionName_(actionName)
{
setText(actionName);
}
FilterAction::FilterAction(QObject *parent, FilterAction::Action action, FilterAction::ActionType type, FilterAction::ActionDirection direction) :
QAction(parent),
action_(action),
type_(type),
direction_(direction)
{
setText(actionDirectionName(direction));
}
FilterAction::FilterAction(QObject *parent, FilterAction::Action action, FilterAction::ActionType type) :
QAction(parent),
action_(action),
type_(type),
direction_(ActionDirectionAToAny)
{
setText(actionTypeName(type));
}
FilterAction::FilterAction(QObject *parent, FilterAction::Action action) :
QAction(parent),
action_(action),
type_(ActionTypePlain),
direction_(ActionDirectionAToAny)
{
setText(actionName(action));
}
const QList<FilterAction::Action> FilterAction::actions() {
static const QList<Action> actions_ = QList<Action>()
<< ActionApply
<< ActionPrepare
<< ActionFind
<< ActionColorize
<< ActionWebLookup
<< ActionCopy;
return actions_;
}
const QString FilterAction::actionName(Action action) {
switch (action) {
case ActionApply:
return QObject::tr("Apply as Filter");
break;
case ActionPrepare:
return QObject::tr("Prepare as Filter");
break;
case ActionFind:
return QObject::tr("Find");
break;
case ActionColorize:
return QObject::tr("Colorize");
break;
case ActionWebLookup:
return QObject::tr("Look Up");
break;
case ActionCopy:
return QObject::tr("Copy");
break;
default:
return QObject::tr("UNKNOWN");
break;
}
}
const QList<FilterAction::ActionType> FilterAction::actionTypes(Action filter_action)
{
static const QList<ActionType> action_types_ = QList<ActionType>()
<< ActionTypePlain
<< ActionTypeNot
<< ActionTypeAnd
<< ActionTypeOr
<< ActionTypeAndNot
<< ActionTypeOrNot;
static const QList<ActionType> simple_action_types_ = QList<ActionType>()
<< ActionTypePlain
<< ActionTypeNot;
switch (filter_action) {
case ActionFind:
case ActionColorize:
return simple_action_types_;
default:
break;
}
return action_types_;
}
const QString FilterAction::actionTypeName(ActionType type) {
switch (type) {
case ActionTypePlain:
return QObject::tr("Selected");
break;
case ActionTypeNot:
return QObject::tr("Not Selected");
break;
case ActionTypeAnd:
return QObject::tr("…and Selected");
break;
case ActionTypeOr:
return QObject::tr("…or Selected");
break;
case ActionTypeAndNot:
return QObject::tr("…and not Selected");
break;
case ActionTypeOrNot:
return QObject::tr("…or not Selected");
break;
default:
return QObject::tr("UNKNOWN");
break;
}
}
const QList<FilterAction::ActionDirection> FilterAction::actionDirections()
{
static const QList<FilterAction::ActionDirection> action_directions_ = QList<ActionDirection>()
<< ActionDirectionAToFromB
<< ActionDirectionAToB
<< ActionDirectionAFromB
<< ActionDirectionAToFromAny
<< ActionDirectionAToAny
<< ActionDirectionAFromAny
<< ActionDirectionAnyToFromB
<< ActionDirectionAnyToB
<< ActionDirectionAnyFromB;
return action_directions_;
}
const QString FilterAction::actionDirectionName(ActionDirection direction) {
switch (direction) {
case ActionDirectionAToFromB:
return QObject::tr("A " UTF8_LEFT_RIGHT_ARROW " B");
break;
case ActionDirectionAToB:
return QObject::tr("A " UTF8_RIGHTWARDS_ARROW " B");
break;
case ActionDirectionAFromB:
return QObject::tr("B " UTF8_RIGHTWARDS_ARROW " A");
break;
case ActionDirectionAToFromAny:
return QObject::tr("A " UTF8_LEFT_RIGHT_ARROW " Any");
break;
case ActionDirectionAToAny:
return QObject::tr("A " UTF8_RIGHTWARDS_ARROW " Any");
break;
case ActionDirectionAFromAny:
return QObject::tr("Any " UTF8_RIGHTWARDS_ARROW " A");
break;
case ActionDirectionAnyToFromB:
return QObject::tr("Any " UTF8_LEFT_RIGHT_ARROW " B");
break;
case ActionDirectionAnyToB:
return QObject::tr("Any " UTF8_RIGHTWARDS_ARROW " B");
break;
case ActionDirectionAnyFromB:
return QObject::tr("B " UTF8_RIGHTWARDS_ARROW " Any");
break;
default:
return QObject::tr("UNKNOWN");
break;
}
}
QActionGroup * FilterAction::createFilterGroup(QString filter, bool prepare, bool enabled, QWidget * parent)
{
if (filter.isEmpty())
enabled = false;
bool filterEmpty = false;
if (mainApp)
{
QWidget * mainWin = mainApp->mainWindow();
if (qobject_cast<MainWindow *>(mainWin))
filterEmpty = qobject_cast<MainWindow *>(mainWin)->getFilter().isEmpty();
}
FilterAction * filterAction = new FilterAction(parent, prepare ? FilterAction::ActionPrepare : FilterAction::ActionApply);
QActionGroup * group = new QActionGroup(parent);
group->setProperty("filter", filter);
group->setProperty("filterAction", prepare ? FilterAction::ActionPrepare : FilterAction::ActionApply);
QAction * action = group->addAction(tr("Selected"));
action->setProperty("filterType", FilterAction::ActionTypePlain);
action = group->addAction(tr("Not Selected"));
action->setProperty("filterType", FilterAction::ActionTypeNot);
action = group->addAction(tr("…and Selected"));
action->setProperty("filterType", FilterAction::ActionTypeAnd);
action->setEnabled(!filterEmpty);
action = group->addAction(tr("…or Selected"));
action->setProperty("filterType", FilterAction::ActionTypeOr);
action->setEnabled(!filterEmpty);
action = group->addAction(tr("…and not Selected"));
action->setProperty("filterType", FilterAction::ActionTypeAndNot);
action->setEnabled(!filterEmpty);
action = group->addAction(tr("…or not Selected"));
action->setProperty("filterType", FilterAction::ActionTypeOrNot);
action->setEnabled(!filterEmpty);
group->setEnabled(enabled);
if (! filter.isEmpty())
connect(group, &QActionGroup::triggered, filterAction, &FilterAction::groupTriggered);
return group;
}
QMenu * FilterAction::createFilterMenu(FilterAction::Action act, QString filter, bool enabled, QWidget * par)
{
QString title = (act == FilterAction::ActionApply) ? QObject::tr("Apply as Filter") : QObject::tr("Prepare as Filter");
bool prepare = (act == FilterAction::ActionApply) ? false : true;
QMenu * submenu = new QMenu(title, par);
if (filter.length() > 0)
{
int one_em = submenu->fontMetrics().height();
QString prep_text = QString("%1: %2").arg(title).arg(filter);
prep_text = submenu->fontMetrics().elidedText(prep_text, Qt::ElideRight, one_em * 40);
QAction * comment = submenu->addAction(prep_text);
comment->setEnabled(false);
submenu->addSeparator();
}
QActionGroup * group = FilterAction::createFilterGroup(filter, prepare, enabled, par);
submenu->addActions(group->actions());
return submenu;
}
void FilterAction::groupTriggered(QAction * action)
{
if (action && mainApp)
{
if (action->property("filterType").canConvert<FilterAction::ActionType>() &&
sender()->property("filterAction").canConvert<FilterAction::Action>())
{
FilterAction::Action act = sender()->property("filterAction").value<FilterAction::Action>();
FilterAction::ActionType type = action->property("filterType").value<FilterAction::ActionType>();
QString filter = sender()->property("filter").toString();
QWidget * mainWin = mainApp->mainWindow();
if (qobject_cast<MainWindow *>(mainWin))
{
MainWindow * mw = qobject_cast<MainWindow *>(mainWin);
mw->setDisplayFilter(filter, act, type);
}
}
}
}
QAction * FilterAction::copyFilterAction(QString filter, QWidget *par)
{
FilterAction * filterAction = new FilterAction(par, ActionCopy);
QAction * action = new QAction(QObject::tr("Copy"), par);
action->setProperty("filter", QVariant::fromValue(filter));
connect(action, &QAction::triggered, filterAction, &FilterAction::copyActionTriggered);
if (filter.isEmpty())
action->setEnabled(false);
return action;
}
void FilterAction::copyActionTriggered()
{
QAction * sendAction = qobject_cast<QAction *>(sender());
if (! sendAction)
return;
QString filter = sendAction->property("filter").toString();
if (filter.length() > 0)
mainApp->clipboard()->setText(filter);
} |
C/C++ | wireshark/ui/qt/filter_action.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/* Derived from gtk/filter_utils.h */
#ifndef FILTER_ACTION_H
#define FILTER_ACTION_H
#include <wsutil/utf8_entities.h>
#include <QAction>
#include <QActionGroup>
class FilterAction : public QAction
{
Q_OBJECT
public:
/* Filter actions */
enum Action {
ActionApply,
ActionColorize,
ActionCopy,
ActionFind,
ActionPrepare,
ActionWebLookup
};
Q_ENUM(Action)
/* Action type - says what to do with the filter */
enum ActionType {
ActionTypePlain,
ActionTypeNot,
ActionTypeAnd,
ActionTypeOr,
ActionTypeAndNot,
ActionTypeOrNot
};
Q_ENUM(ActionType)
/* Action direction */
enum ActionDirection {
ActionDirectionAToFromB,
ActionDirectionAToB,
ActionDirectionAFromB,
ActionDirectionAToFromAny,
ActionDirectionAToAny,
ActionDirectionAFromAny,
ActionDirectionAnyToFromB,
ActionDirectionAnyToB,
ActionDirectionAnyFromB
};
explicit FilterAction(QObject *parent, Action action, ActionType type, QString actionName);
explicit FilterAction(QObject *parent, Action action, ActionType type, ActionDirection direction);
explicit FilterAction(QObject *parent, Action action, ActionType type);
explicit FilterAction(QObject *parent, Action action);
Action action() { return action_; }
static const QList<Action> actions();
static const QString actionName(Action action);
ActionType actionType() { return type_; }
static const QList<ActionType> actionTypes(Action filter_action = ActionApply);
static const QString actionTypeName(ActionType type);
ActionDirection actionDirection() { return direction_; }
static const QList<ActionDirection> actionDirections();
static const QString actionDirectionName(ActionDirection direction);
static QActionGroup * createFilterGroup(QString filter, bool prepare, bool enabled, QWidget * parent);
static QMenu * createFilterMenu(FilterAction::Action act, QString filter, bool enabled, QWidget * parent);
static QAction * copyFilterAction(QString filter, QWidget *par);
signals:
public slots:
private:
Action action_;
ActionType type_;
ActionDirection direction_;
QString actionName_;
private slots:
void groupTriggered(QAction *);
void copyActionTriggered();
};
#endif // FILTER_ACTION_H |
C++ | wireshark/ui/qt/filter_dialog.cpp | /* filter_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/filter_files.h>
#include <wsutil/filesystem.h>
#include "filter_dialog.h"
#include <ui_filter_dialog.h>
#include <QMessageBox>
#include <QThread>
#include <QUrl>
#include <QSortFilterProxyModel>
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/widgets/capture_filter_edit.h>
#include <ui/qt/widgets/display_filter_edit.h>
#include "main_application.h"
FilterDialog::FilterDialog(QWidget *parent, FilterType filter_type, QString new_filter_) :
GeometryStateDialog(parent),
ui(new Ui::FilterDialog),
filter_type_(filter_type),
filter_tree_delegate_(new FilterTreeDelegate(this, filter_type))
{
ui->setupUi(this);
if (parent) loadGeometry(parent->width() * 2 / 3, parent->height() * 2 / 3);
setWindowIcon(mainApp->normalIcon());
ui->newToolButton->setStockIcon("list-add");
ui->deleteToolButton->setStockIcon("list-remove");
ui->copyToolButton->setStockIcon("list-copy");
#ifdef Q_OS_MAC
ui->newToolButton->setAttribute(Qt::WA_MacSmallSize, true);
ui->deleteToolButton->setAttribute(Qt::WA_MacSmallSize, true);
ui->copyToolButton->setAttribute(Qt::WA_MacSmallSize, true);
ui->pathLabel->setAttribute(Qt::WA_MacSmallSize, true);
#endif
#if 0
ui->filterTreeWidget->setDragEnabled(true);
ui->filterTreeWidget->viewport()->setAcceptDrops(true);
ui->filterTreeWidget->setDropIndicatorShown(true);
ui->filterTreeWidget->setDragDropMode(QAbstractItemView::InternalMove);
#endif
ui->filterTreeView->setDragEnabled(true);
ui->filterTreeView->setAcceptDrops(true);
ui->filterTreeView->setDropIndicatorShown(true);
const gchar * filename = NULL;
QString newFilterText;
if (filter_type == CaptureFilter) {
setWindowTitle(mainApp->windowTitleString(tr("Capture Filters")));
filename = CFILTER_FILE_NAME;
newFilterText = tr("New capture filter");
model_ = new FilterListModel(FilterListModel::Capture, this);
} else {
setWindowTitle(mainApp->windowTitleString(tr("Display Filters")));
filename = DFILTER_FILE_NAME;
newFilterText = tr("New display filter");
model_ = new FilterListModel(FilterListModel::Display, this);
}
if (new_filter_.length() > 0)
model_->addFilter(newFilterText, new_filter_);
ui->filterTreeView->setModel(model_);
ui->filterTreeView->setItemDelegate(new FilterTreeDelegate(this, filter_type));
ui->filterTreeView->resizeColumnToContents(FilterListModel::ColumnName);
connect(ui->filterTreeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &FilterDialog::selectionChanged);
QString abs_path = gchar_free_to_qstring(get_persconffile_path(filename, TRUE));
if (file_exists(abs_path.toUtf8().constData())) {
ui->pathLabel->setText(abs_path);
ui->pathLabel->setUrl(QUrl::fromLocalFile(abs_path).toString());
ui->pathLabel->setToolTip(tr("Open ") + filename);
ui->pathLabel->setEnabled(true);
}
}
FilterDialog::~FilterDialog()
{
delete ui;
}
void FilterDialog::addFilter(QString name, QString filter, bool start_editing)
{
if (model_)
{
QModelIndex idx = model_->addFilter(name, filter);
if (start_editing)
ui->filterTreeView->edit(idx);
}
}
void FilterDialog::updateWidgets()
{
if (! ui->filterTreeView->selectionModel())
return;
qsizetype num_selected = ui->filterTreeView->selectionModel()->selectedRows().count();
ui->copyToolButton->setEnabled(num_selected == 1);
ui->deleteToolButton->setEnabled(num_selected > 0);
}
void FilterDialog::selectionChanged(const QItemSelection &/*selected*/, const QItemSelection &/*deselected*/)
{
updateWidgets();
}
void FilterDialog::on_newToolButton_clicked()
{
QString name;
QString filter;
if (filter_type_ == CaptureFilter) {
//: This text is automatically filled in when a new filter is created
name = tr("New capture filter");
filter = "ip host host.example.com";
} else {
//: This text is automatically filled in when a new filter is created
name = tr("New display filter");
filter = "ip.host == host.example.com";
}
addFilter(name, filter, true);
}
void FilterDialog::on_deleteToolButton_clicked()
{
QModelIndexList selected = ui->filterTreeView->selectionModel()->selectedRows();
QList<int> rows;
foreach (QModelIndex idx, selected)
{
if (idx.isValid() && ! rows.contains(idx.row()))
{
rows << idx.row();
model_->removeFilter(idx);
}
}
}
void FilterDialog::on_copyToolButton_clicked()
{
QModelIndexList selected = ui->filterTreeView->selectionModel()->selectedRows();
if (selected.count() <= 0)
return;
int rowNr = selected.at(0).row();
QModelIndex row = selected.at(0).sibling(rowNr, FilterListModel::ColumnName);
addFilter(row.data().toString(), row.sibling(rowNr, FilterListModel::ColumnExpression).data().toString(), true);
}
void FilterDialog::on_buttonBox_accepted()
{
model_->saveList();
if (filter_type_ == CaptureFilter) {
mainApp->emitAppSignal(MainApplication::CaptureFilterListChanged);
} else {
mainApp->emitAppSignal(MainApplication::DisplayFilterListChanged);
}
}
void FilterDialog::on_buttonBox_helpRequested()
{
if (filter_type_ == CaptureFilter) {
mainApp->helpTopicAction(HELP_CAPTURE_FILTERS_DIALOG);
} else {
mainApp->helpTopicAction(HELP_DISPLAY_FILTERS_DIALOG);
}
}
//
// FilterTreeDelegate
// Delegate for editing capture and display filters.
//
FilterTreeDelegate::FilterTreeDelegate(QObject *parent, FilterDialog::FilterType filter_type) :
QStyledItemDelegate(parent),
filter_type_(filter_type)
{}
QWidget *FilterTreeDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QWidget * w = Q_NULLPTR;
if (index.column() != FilterListModel::ColumnExpression) {
w = QStyledItemDelegate::createEditor(parent, option, index);
}
else
{
if (filter_type_ == FilterDialog::CaptureFilter) {
w = new CaptureFilterEdit(parent, true);
} else {
w = new DisplayFilterEdit(parent, DisplayFilterToEnter);
}
}
if (qobject_cast<QLineEdit *>(w) && index.column() == FilterListModel::ColumnName)
qobject_cast<QLineEdit *>(w)->setValidator(new FilterValidator());
return w;
}
void FilterTreeDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
if (! editor || ! index.isValid())
return;
QStyledItemDelegate::setEditorData(editor, index);
if (qobject_cast<QLineEdit *>(editor))
qobject_cast<QLineEdit *>(editor)->setText(index.data().toString());
}
QValidator::State FilterValidator::validate(QString & input, int & /*pos*/) const
{
/* Making this a list to be able to easily add additional values in the future */
QStringList invalidKeys = QStringList() << "\"";
if (input.length() <= 0)
return QValidator::Intermediate;
foreach (QString key, invalidKeys)
if (input.indexOf(key) >= 0)
return QValidator::Invalid;
return QValidator::Acceptable;
} |
C/C++ | wireshark/ui/qt/filter_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 FILTER_DIALOG_H
#define FILTER_DIALOG_H
#include "geometry_state_dialog.h"
#include <ui/qt/models/filter_list_model.h>
#include <QStyledItemDelegate>
#include <QValidator>
class QItemSelection;
class FilterTreeDelegate;
namespace Ui {
class FilterDialog;
}
class FilterDialog : public GeometryStateDialog
{
Q_OBJECT
public:
enum FilterType { CaptureFilter, DisplayFilter };
explicit FilterDialog(QWidget *parent = 0, FilterType filter_type = CaptureFilter, const QString new_filter = QString());
~FilterDialog();
private:
Ui::FilterDialog *ui;
FilterListModel * model_;
enum FilterType filter_type_;
FilterTreeDelegate *filter_tree_delegate_;
void addFilter(QString name, QString filter, bool start_editing = false);
private slots:
void updateWidgets();
void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
void on_newToolButton_clicked();
void on_deleteToolButton_clicked();
void on_copyToolButton_clicked();
void on_buttonBox_accepted();
void on_buttonBox_helpRequested();
};
//
// FilterTreeDelegate
// Delegate for editing capture and display filters.
//
class FilterTreeDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
FilterTreeDelegate(QObject *parent, FilterDialog::FilterType filter_type);
virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
virtual void setEditorData(QWidget *editor, const QModelIndex &index) const override;
private:
FilterDialog::FilterType filter_type_;
};
class FilterValidator : public QValidator
{
public:
virtual QValidator::State validate(QString & input, int & pos) const override;
};
#endif // FILTER_DIALOG_H |
User Interface | wireshark/ui/qt/filter_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FilterDialog</class>
<widget class="QDialog" name="FilterDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>584</width>
<height>390</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTreeView" name="filterTreeView">
<property name="dragDropMode">
<enum>QAbstractItemView::DragDrop</enum>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
<attribute name="headerShowSortIndicator" stdset="0">
<bool>true</bool>
</attribute>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0,0,0,1">
<item>
<widget class="StockIconToolButton" name="newToolButton">
<property name="toolTip">
<string>Create a new filter.</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<widget class="StockIconToolButton" name="deleteToolButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Remove this filter.</string>
</property>
</widget>
</item>
<item>
<widget class="StockIconToolButton" name="copyToolButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Copy this filter.</string>
</property>
<property name="text">
<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="ElidedLabel" name="pathLabel">
<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>ElidedLabel</class>
<extends>QLabel</extends>
<header>widgets/elided_label.h</header>
</customwidget>
<customwidget>
<class>StockIconToolButton</class>
<extends>QToolButton</extends>
<header>widgets/stock_icon_tool_button.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>FilterDialog</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>FilterDialog</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/filter_expression_frame.cpp | /* filter_expression_frame.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "filter_expression_frame.h"
#include <ui_filter_expression_frame.h>
#include <epan/filter_expressions.h>
#include <ui/preference_utils.h>
#include <ui/qt/models/uat_model.h>
#include <ui/qt/models/pref_models.h>
#include <ui/qt/main_application.h>
#include <QPushButton>
#include <QKeyEvent>
// To do:
// - Add the ability to edit current expressions.
FilterExpressionFrame::FilterExpressionFrame(QWidget *parent) :
AccordionFrame(parent),
ui(new Ui::FilterExpressionFrame)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
foreach (QWidget *w, findChildren<QWidget *>()) {
w->setAttribute(Qt::WA_MacSmallSize, true);
}
#endif
editExpression_ = -1;
updateWidgets();
}
FilterExpressionFrame::~FilterExpressionFrame()
{
delete ui;
}
void FilterExpressionFrame::addExpression(const QString filter_text)
{
if (isVisible()) {
on_buttonBox_rejected();
return;
}
editExpression_ = -1;
ui->displayFilterLineEdit->setText(filter_text);
if (! isVisible())
animatedShow();
}
void FilterExpressionFrame::editExpression(int exprIdx)
{
if (isVisible())
{
ui->labelLineEdit->clear();
ui->displayFilterLineEdit->clear();
ui->commentLineEdit->clear();
editExpression_ = -1;
}
UatModel * uatModel = new UatModel(this, "Display expressions");
if (! uatModel->index(exprIdx, 1).isValid())
return;
editExpression_ = exprIdx;
ui->labelLineEdit->setText(uatModel->data(uatModel->index(exprIdx, 1), Qt::DisplayRole).toString());
ui->displayFilterLineEdit->setText(uatModel->data(uatModel->index(exprIdx, 2), Qt::DisplayRole).toString());
ui->commentLineEdit->setText(uatModel->data(uatModel->index(exprIdx, 3), Qt::DisplayRole).toString());
delete(uatModel);
if (! isVisible())
animatedShow();
}
void FilterExpressionFrame::showEvent(QShowEvent *event)
{
ui->labelLineEdit->setFocus();
ui->labelLineEdit->selectAll();
AccordionFrame::showEvent(event);
}
void FilterExpressionFrame::updateWidgets()
{
bool ok_enable = true;
if (ui->labelLineEdit->text().isEmpty() ||
((ui->displayFilterLineEdit->syntaxState() != SyntaxLineEdit::Valid) &&
(ui->displayFilterLineEdit->syntaxState() != SyntaxLineEdit::Deprecated)))
ok_enable = false;
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ok_enable);
}
void FilterExpressionFrame::on_filterExpressionPreferencesPushButton_clicked()
{
on_buttonBox_rejected();
emit showPreferencesDialog(PrefsModel::typeToString(PrefsModel::FilterButtons));
}
void FilterExpressionFrame::on_labelLineEdit_textChanged(const QString)
{
updateWidgets();
}
void FilterExpressionFrame::on_displayFilterLineEdit_textChanged(const QString)
{
updateWidgets();
}
void FilterExpressionFrame::on_buttonBox_accepted()
{
QByteArray label_ba = ui->labelLineEdit->text().toUtf8();
QByteArray expr_ba = ui->displayFilterLineEdit->text().toUtf8();
QByteArray comment_ba = ui->commentLineEdit->text().toUtf8();
if (ui->labelLineEdit->text().length() == 0 || ui->displayFilterLineEdit->text().length() == 0)
return;
if (! ui->displayFilterLineEdit->checkFilter())
return;
if (editExpression_ >= 0)
{
UatModel * uatModel = new UatModel(this, "Display expressions");
if (! uatModel->index(editExpression_, 1).isValid())
return;
uatModel->setData(uatModel->index(editExpression_, 1), QVariant::fromValue(label_ba));
uatModel->setData(uatModel->index(editExpression_, 2), QVariant::fromValue(expr_ba));
uatModel->setData(uatModel->index(editExpression_, 3), QVariant::fromValue(comment_ba));
}
else
{
filter_expression_new(label_ba.constData(), expr_ba.constData(), comment_ba.constData(), TRUE);
}
save_migrated_uat("Display expressions", &prefs.filter_expressions_old);
on_buttonBox_rejected();
emit filterExpressionsChanged();
}
void FilterExpressionFrame::on_buttonBox_rejected()
{
ui->labelLineEdit->clear();
ui->displayFilterLineEdit->clear();
ui->commentLineEdit->clear();
editExpression_ = -1;
animatedHide();
}
void FilterExpressionFrame::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->labelLineEdit->text().length() == 0) {
mainApp->pushStatus(MainApplication::FilterSyntax, tr("Missing label."));
} else if (ui->displayFilterLineEdit->syntaxState() == SyntaxLineEdit::Empty) {
mainApp->pushStatus(MainApplication::FilterSyntax, tr("Missing filter expression."));
} else if (ui->displayFilterLineEdit->syntaxState() != SyntaxLineEdit::Valid) {
mainApp->pushStatus(MainApplication::FilterSyntax, tr("Invalid filter expression."));
}
}
}
AccordionFrame::keyPressEvent(event);
} |
C/C++ | wireshark/ui/qt/filter_expression_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 FILTER_EXPRESSION_FRAME_H
#define FILTER_EXPRESSION_FRAME_H
#include "accordion_frame.h"
namespace Ui {
class FilterExpressionFrame;
}
class FilterExpressionFrame : public AccordionFrame
{
Q_OBJECT
public:
explicit FilterExpressionFrame(QWidget *parent = 0);
~FilterExpressionFrame();
void addExpression(const QString filter_text);
void editExpression(int exprIdx);
signals:
void showPreferencesDialog(QString pane_name);
void filterExpressionsChanged();
protected:
virtual void showEvent(QShowEvent *event);
virtual void keyPressEvent(QKeyEvent *event);
private:
Ui::FilterExpressionFrame *ui;
int editExpression_;
private slots:
void updateWidgets();
void on_filterExpressionPreferencesPushButton_clicked();
void on_labelLineEdit_textChanged(const QString);
void on_displayFilterLineEdit_textChanged(const QString);
void on_buttonBox_accepted();
void on_buttonBox_rejected();
};
#endif // FILTER_EXPRESSION_FRAME_H |
User Interface | wireshark/ui/qt/filter_expression_frame.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FilterExpressionFrame</class>
<widget class="AccordionFrame" name="FilterExpressionFrame">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>796</width>
<height>82</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>82</height>
</size>
</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_5">
<item>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QToolButton" name="filterExpressionPreferencesPushButton">
<property name="text">
<string>Filter Buttons Preferences…</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>5</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="labelLabel">
<property name="text">
<string>Label:</string>
</property>
</widget>
</item>
<item>
<widget class="SyntaxLineEdit" name="labelLineEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>80</width>
<height>0</height>
</size>
</property>
<property name="placeholderText">
<string>Enter a description for the filter button</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="filterLabel">
<property name="text">
<string>Filter:</string>
</property>
</widget>
</item>
<item>
<widget class="DisplayFilterEdit" name="displayFilterLineEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>80</width>
<height>0</height>
</size>
</property>
<property name="placeholderText">
<string>Enter a filter expression to be applied</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="commentLabel">
<property name="text">
<string>Comment:</string>
</property>
</widget>
</item>
<item>
<widget class="SyntaxLineEdit" name="commentLineEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>1</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>80</width>
<height>0</height>
</size>
</property>
<property name="placeholderText">
<string>Enter a comment for the filter button</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</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>
<customwidget>
<class>DisplayFilterEdit</class>
<extends>QLineEdit</extends>
<header>widgets/display_filter_edit.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui> |
C++ | wireshark/ui/qt/firewall_rules_dialog.cpp | /* firewall_rules_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 "firewall_rules_dialog.h"
#include <ui_firewall_rules_dialog.h>
#include "epan/packet_info.h"
#include "epan/to_str.h"
#include "ui/all_files_wildcard.h"
#include "ui/firewall_rules.h"
#include "ui/help_url.h"
#include "wsutil/file_util.h"
#include "wsutil/utf8_entities.h"
#include "main_application.h"
#include "ui/qt/widgets/wireshark_file_dialog.h"
#include <QClipboard>
#include <QMessageBox>
#include <QPushButton>
#include <QTextCursor>
// XXX As described in bug 2482, some of the generated rules don't
// make sense. We could generate rules for every conceivable use case,
// but that would add complexity. We could also add controls to let
// users fine-tune rule output, but that would also add complexity.
FirewallRulesDialog::FirewallRulesDialog(QWidget &parent, CaptureFile &cf) :
WiresharkDialog(parent, cf),
ui(new Ui::FirewallRulesDialog),
prod_(0)
{
ui->setupUi(this);
setWindowSubtitle(tr("Firewall ACL Rules"));
ui->buttonBox->button(QDialogButtonBox::Apply)->setText(tr("Copy"));
file_name_ = cf.fileName(); // XXX Add extension?
packet_num_ = cf.packetInfo()->num;
packet_info *pinfo = cf.packetInfo();
copy_address(&dl_src_, &(pinfo->dl_src));
copy_address(&dl_dst_, &(pinfo->dl_dst));
copy_address(&net_src_, &(pinfo->net_src));
copy_address(&net_dst_, &(pinfo->net_dst));
ptype_ = pinfo->ptype;
src_port_ = pinfo->srcport;
dst_port_ = pinfo->destport;
int nf_item = 0;
for (size_t prod = 0; prod < firewall_product_count(); prod++) {
QString prod_name = firewall_product_name(prod);
// Default to Netfilter since it's likely the most popular.
if (prod_name.contains("Netfilter")) nf_item = ui->productComboBox->count();
ui->productComboBox->addItem(prod_name);
}
ui->productComboBox->setCurrentIndex(nf_item);
ui->buttonBox->button(QDialogButtonBox::Close)->setDefault(true);
}
FirewallRulesDialog::~FirewallRulesDialog()
{
delete ui;
}
void FirewallRulesDialog::updateWidgets()
{
WiresharkDialog::updateWidgets();
QString comment_pfx = firewall_product_comment_prefix(prod_);
QString rule_hint = firewall_product_rule_hint(prod_);
QString rule_line;
rule_line = QString("%1 %2 rules for %3, packet %4.")
.arg(comment_pfx)
.arg(firewall_product_name(prod_))
.arg(file_name_)
.arg(packet_num_);
if (!rule_hint.isEmpty()) rule_line += " " + rule_hint;
ui->textBrowser->clear();
ui->textBrowser->append(rule_line);
syntax_func v4_func = firewall_product_ipv4_func(prod_);
syntax_func port_func = firewall_product_port_func(prod_);
syntax_func v4_port_func = firewall_product_ipv4_port_func(prod_);
syntax_func mac_func = firewall_product_mac_func(prod_);
if (v4_func && net_src_.type == AT_IPv4) {
addRule(tr("IPv4 source address."), v4_func, &net_src_, src_port_);
addRule(tr("IPv4 destination address."), v4_func, &net_dst_, dst_port_);
}
if (port_func && (ptype_ == PT_TCP || ptype_ == PT_UDP)) {
addRule(tr("Source port."), port_func, &net_src_, src_port_);
addRule(tr("Destination port."), port_func, &net_dst_, dst_port_);
}
if (v4_port_func && net_src_.type == AT_IPv4 &&
(ptype_ == PT_TCP || ptype_ == PT_UDP)) {
addRule(tr("IPv4 source address and port."), v4_port_func, &net_src_, src_port_);
addRule(tr("IPv4 destination address and port."), v4_port_func, &net_dst_, dst_port_);
}
if (mac_func && dl_src_.type == AT_ETHER) {
addRule(tr("MAC source address."), mac_func, &dl_src_, src_port_);
addRule(tr("MAC destination address."), mac_func, &dl_dst_, dst_port_);
}
ui->textBrowser->moveCursor(QTextCursor::Start);
ui->inboundCheckBox->setEnabled(firewall_product_does_inbound(prod_));
}
#define ADDR_BUF_LEN 200
void FirewallRulesDialog::addRule(QString description, syntax_func rule_func, address *addr, guint32 port)
{
if (!rule_func) return;
char addr_buf[ADDR_BUF_LEN];
QString comment_pfx = firewall_product_comment_prefix(prod_);
GString *rule_str = g_string_new("");
gboolean inbound = ui->inboundCheckBox->isChecked();
gboolean deny = ui->denyCheckBox->isChecked();
address_to_str_buf(addr, addr_buf, ADDR_BUF_LEN);
rule_func(rule_str, addr_buf, port, ptype_, inbound, deny);
ui->textBrowser->append(QString());
QString comment_line = comment_pfx + " " + description;
ui->textBrowser->append(comment_line);
ui->textBrowser->append(rule_str->str);
g_string_free(rule_str, TRUE);
}
void FirewallRulesDialog::on_productComboBox_currentIndexChanged(int new_idx)
{
prod_ = (size_t) new_idx;
updateWidgets();
}
void FirewallRulesDialog::on_inboundCheckBox_toggled(bool)
{
updateWidgets();
}
void FirewallRulesDialog::on_denyCheckBox_toggled(bool)
{
updateWidgets();
}
void FirewallRulesDialog::on_buttonBox_clicked(QAbstractButton *button)
{
if (button == ui->buttonBox->button(QDialogButtonBox::Save)) {
QString save_title = QString("Save %1 rules as" UTF8_HORIZONTAL_ELLIPSIS)
.arg(firewall_product_name(prod_));
QByteArray file_name = WiresharkFileDialog::getSaveFileName(this,
save_title,
mainApp->lastOpenDir().canonicalPath(),
tr("Text file (*.txt);;All Files (" ALL_FILES_WILDCARD ")")
).toUtf8();
if (file_name.length() > 0) {
QFile save_file(file_name);
QByteArray rule_text = ui->textBrowser->toPlainText().toUtf8();
save_file.open(QIODevice::WriteOnly);
save_file.write(rule_text);
save_file.close();
if (save_file.error() != QFile::NoError) {
QMessageBox::warning(this, tr("Warning"), tr("Unable to save %1").arg(save_file.fileName()));
return;
}
/* Save the directory name for future file dialogs. */
mainApp->setLastOpenDirFromFilename(file_name);
}
} else if (button == ui->buttonBox->button(QDialogButtonBox::Apply)) {
if (ui->textBrowser->textCursor().hasSelection()) {
ui->textBrowser->copy();
} else {
mainApp->clipboard()->setText(ui->textBrowser->toPlainText());
}
}
}
void FirewallRulesDialog::on_buttonBox_helpRequested()
{
mainApp->helpTopicAction(HELP_FIREWALL_DIALOG);
} |
C/C++ | wireshark/ui/qt/firewall_rules_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 FIREWALL_RULES_DIALOG_H
#define FIREWALL_RULES_DIALOG_H
#include "epan/address.h"
#include <wireshark_dialog.h>
namespace Ui {
class FirewallRulesDialog;
}
class QAbstractButton;
typedef void (*syntax_func)(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
class FirewallRulesDialog : public WiresharkDialog
{
Q_OBJECT
public:
explicit FirewallRulesDialog(QWidget &parent, CaptureFile &cf);
~FirewallRulesDialog();
private slots:
void on_productComboBox_currentIndexChanged(int new_idx);
void on_inboundCheckBox_toggled(bool);
void on_denyCheckBox_toggled(bool);
void on_buttonBox_helpRequested();
void on_buttonBox_clicked(QAbstractButton *button);
private:
Ui::FirewallRulesDialog *ui;
QString file_name_;
int packet_num_;
size_t prod_;
address dl_src_;
address dl_dst_;
address net_src_;
address net_dst_;
port_type ptype_;
guint32 src_port_;
guint32 dst_port_;
void updateWidgets();
void addRule(QString description, syntax_func rule_func, address *addr, guint32 port);
};
#endif // FIREWALL_RULES_DIALOG_H |
User Interface | wireshark/ui/qt/firewall_rules_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FirewallRulesDialog</class>
<widget class="QDialog" name="FirewallRulesDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>650</width>
<height>450</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTextBrowser" name="textBrowser"/>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0,1,0,0,0">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Create rules for</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="productComboBox"/>
</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="QCheckBox" name="inboundCheckBox">
<property name="text">
<string>Inbound</string>
</property>
<property name="checked">
<bool>true</bool>
</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>5</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QCheckBox" name="denyCheckBox">
<property name="text">
<string>Deny</string>
</property>
<property name="checked">
<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::Apply|QDialogButtonBox::Close|QDialogButtonBox::Help|QDialogButtonBox::Save</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>FirewallRulesDialog</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>FirewallRulesDialog</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/follow_stream_action.cpp | /* follow_stream_action.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <config.h>
#include <glib.h>
#include <epan/packet_info.h>
#include <epan/proto_data.h>
#include <epan/packet.h>
#include "follow_stream_action.h"
#include <QMenu>
#include <ui/qt/utils/qt_ui_utils.h>
FollowStreamAction::FollowStreamAction(QObject *parent, register_follow_t *follow) :
QAction(parent),
follow_(follow)
{
if (follow_) {
setText(QString(tr("%1 Stream").arg(proto_get_protocol_short_name(find_protocol_by_id(get_follow_proto_id(follow))))));
}
} |
C/C++ | wireshark/ui/qt/follow_stream_action.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef FOLLOWSTREAMACTION_H
#define FOLLOWSTREAMACTION_H
#include "config.h"
#include <glib.h>
#include <epan/packet_info.h>
#include <epan/follow.h>
#include <QAction>
#include <ui/qt/capture_file.h>
// Actions for "Follow Stream" menu items.
class FollowStreamAction : public QAction
{
Q_OBJECT
public:
FollowStreamAction(QObject *parent, register_follow_t *follow = NULL);
register_follow_t* follow() const {return follow_;}
int protoId() const {return get_follow_proto_id(follow_);}
const char* filterName() const {return proto_get_protocol_filter_name(get_follow_proto_id(follow_));}
private:
register_follow_t *follow_;
};
#endif // FOLLOWSTREAMACTION_H |
C++ | wireshark/ui/qt/follow_stream_dialog.cpp | /* follow_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 "follow_stream_dialog.h"
#include <ui_follow_stream_dialog.h>
#include "main_application.h"
#include "main_window.h"
#include "frame_tvbuff.h"
#include "epan/follow.h"
#include "epan/prefs.h"
#include "epan/addr_resolv.h"
#include "epan/charsets.h"
#include "epan/epan_dissect.h"
#include "epan/tap.h"
#include "ui/alert_box.h"
#include "ui/simple_dialog.h"
#include <ui/recent.h>
#include <wsutil/utf8_entities.h>
#include <wsutil/ws_assert.h>
#include "wsutil/file_util.h"
#include "wsutil/str_util.h"
#include "ws_symbol_export.h"
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "progress_frame.h"
#include "ui/qt/widgets/wireshark_file_dialog.h"
#include <QElapsedTimer>
#include <QKeyEvent>
#include <QMessageBox>
#include <QMutex>
#include <QPrintDialog>
#include <QPrinter>
#include <QScrollBar>
#include <QTextCodec>
// To do:
// - Show text while tapping.
// - Instead of calling QMessageBox, display the error message in the text
// box and disable the appropriate controls.
// - Add a progress bar and connect captureCaptureUpdateContinue to it
// - User's Guide documents the "Raw" type as "same as ASCII, but saving binary
// data". However it currently displays hex-encoded data.
// Matches SplashOverlay.
static int info_update_freq_ = 100;
// Handle the loop breaking notification properly
static QMutex loop_break_mutex;
// Indicates that a Follow Stream is currently running
static gboolean isReadRunning;
FollowStreamDialog::FollowStreamDialog(QWidget &parent, CaptureFile &cf, int proto_id) :
WiresharkDialog(parent, cf),
ui(new Ui::FollowStreamDialog),
b_find_(NULL),
follower_(NULL),
truncated_(false),
client_buffer_count_(0),
server_buffer_count_(0),
client_packet_count_(0),
server_packet_count_(0),
last_packet_(0),
last_from_server_(0),
turns_(0),
use_regex_find_(false),
terminating_(false),
previous_sub_stream_num_(0)
{
ui->setupUi(this);
loadGeometry(parent.width() * 2 / 3, parent.height());
ui->streamNumberSpinBox->setStyleSheet("QSpinBox { min-width: 2em; }");
ui->subStreamNumberSpinBox->setStyleSheet("QSpinBox { min-width: 2em; }");
follower_ = get_follow_by_proto_id(proto_id);
if (follower_ == NULL) {
ws_assert_not_reached();
}
memset(&follow_info_, 0, sizeof(follow_info_));
follow_info_.show_stream = BOTH_HOSTS;
follow_info_.substream_id = SUBSTREAM_UNUSED;
ui->teStreamContent->installEventFilter(this);
connect(ui->leFind, SIGNAL(useRegexFind(bool)), this, SLOT(useRegexFind(bool)));
QComboBox *cbcs = ui->cbCharset;
cbcs->blockSignals(true);
cbcs->addItem(tr("ASCII"), SHOW_ASCII);
cbcs->addItem(tr("C Arrays"), SHOW_CARRAY);
cbcs->addItem(tr("EBCDIC"), SHOW_EBCDIC);
cbcs->addItem(tr("Hex Dump"), SHOW_HEXDUMP);
cbcs->addItem(tr("Raw"), SHOW_RAW);
// UTF-8 is guaranteed to exist as a QTextCodec
cbcs->addItem(tr("UTF-8"), SHOW_CODEC);
cbcs->addItem(tr("YAML"), SHOW_YAML);
cbcs->setCurrentIndex(static_cast<int>(recent.gui_follow_show));
cbcs->blockSignals(false);
b_filter_out_ = ui->buttonBox->addButton(tr("Filter Out This Stream"), QDialogButtonBox::ActionRole);
connect(b_filter_out_, SIGNAL(clicked()), this, SLOT(filterOut()));
b_print_ = ui->buttonBox->addButton(tr("Print"), QDialogButtonBox::ActionRole);
connect(b_print_, SIGNAL(clicked()), this, SLOT(printStream()));
b_save_ = ui->buttonBox->addButton(tr("Save as…"), QDialogButtonBox::ActionRole);
connect(b_save_, SIGNAL(clicked()), this, SLOT(saveAs()));
b_back_ = ui->buttonBox->addButton(tr("Back"), QDialogButtonBox::ActionRole);
connect(b_back_, SIGNAL(clicked()), this, SLOT(backButton()));
ProgressFrame::addToButtonBox(ui->buttonBox, &parent);
connect(ui->buttonBox, SIGNAL(helpRequested()), this, SLOT(helpButton()));
connect(ui->teStreamContent, SIGNAL(mouseMovedToTextCursorPosition(int)),
this, SLOT(fillHintLabel(int)));
connect(ui->teStreamContent, SIGNAL(mouseClickedOnTextCursorPosition(int)),
this, SLOT(goToPacketForTextPos(int)));
fillHintLabel(-1);
}
FollowStreamDialog::~FollowStreamDialog()
{
delete ui;
resetStream(); // Frees payload
}
void FollowStreamDialog::addCodecs(const QMap<QString, QTextCodec *> &codecMap)
{
// Make the combobox respect max visible items?
//ui->cbCharset->setStyleSheet("QComboBox { combobox-popup: 0;}");
ui->cbCharset->insertSeparator(ui->cbCharset->count());
for (const auto &codec : qAsConst(codecMap)) {
// This is already in the menu and handled separately
if (codec->name() != "US-ASCII" && codec->name() != "UTF-8")
ui->cbCharset->addItem(tr(codec->name()), SHOW_CODEC);
}
}
void FollowStreamDialog::printStream()
{
#ifndef QT_NO_PRINTER
QPrinter printer(QPrinter::HighResolution);
QPrintDialog dialog(&printer, this);
if (dialog.exec() == QDialog::Accepted)
ui->teStreamContent->print(&printer);
#endif
}
void FollowStreamDialog::fillHintLabel(int text_pos)
{
QString hint;
int pkt = -1;
if (text_pos >= 0) {
QMap<int, guint32>::iterator it = text_pos_to_packet_.upperBound(text_pos);
if (it != text_pos_to_packet_.end()) {
pkt = it.value();
}
}
if (pkt > 0) {
hint = QString(tr("Packet %1. ")).arg(pkt);
}
hint += tr("%Ln <span style=\"color: %1; background-color:%2\">client</span> pkt(s), ", "", client_packet_count_)
.arg(ColorUtils::fromColorT(prefs.st_client_fg).name())
.arg(ColorUtils::fromColorT(prefs.st_client_bg).name())
+ tr("%Ln <span style=\"color: %1; background-color:%2\">server</span> pkt(s), ", "", server_packet_count_)
.arg(ColorUtils::fromColorT(prefs.st_server_fg).name())
.arg(ColorUtils::fromColorT(prefs.st_server_bg).name())
+ tr("%Ln turn(s).", "", turns_);
if (pkt > 0) {
hint.append(QString(tr(" Click to select.")));
}
hint.prepend("<small><i>");
hint.append("</i></small>");
ui->hintLabel->setText(hint);
}
void FollowStreamDialog::goToPacketForTextPos(int text_pos)
{
int pkt = -1;
if (file_closed_) {
return;
}
if (text_pos >= 0) {
QMap<int, guint32>::iterator it = text_pos_to_packet_.upperBound(text_pos);
if (it != text_pos_to_packet_.end()) {
pkt = it.value();
}
}
if (pkt > 0) {
emit goToPacket(pkt);
}
}
void FollowStreamDialog::updateWidgets(bool follow_in_progress)
{
bool enable = !follow_in_progress;
if (file_closed_) {
ui->teStreamContent->setEnabled(true);
enable = false;
}
ui->cbDirections->setEnabled(enable);
ui->cbCharset->setEnabled(enable);
ui->streamNumberSpinBox->setEnabled(enable);
if (get_follow_sub_stream_id_func(follower_) != NULL) {
ui->subStreamNumberSpinBox->setEnabled(enable);
}
ui->leFind->setEnabled(enable);
ui->bFind->setEnabled(enable);
b_filter_out_->setEnabled(enable);
b_print_->setEnabled(enable);
b_save_->setEnabled(enable);
WiresharkDialog::updateWidgets();
}
void FollowStreamDialog::useRegexFind(bool use_regex)
{
use_regex_find_ = use_regex;
if (use_regex_find_)
ui->lFind->setText(tr("Regex Find:"));
else
ui->lFind->setText(tr("Find:"));
}
void FollowStreamDialog::findText(bool go_back)
{
if (ui->leFind->text().isEmpty()) return;
bool found;
if (use_regex_find_) {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))
QRegularExpression regex(ui->leFind->text(), QRegularExpression::UseUnicodePropertiesOption);
#else
QRegExp regex(ui->leFind->text());
#endif
found = ui->teStreamContent->find(regex);
} else {
found = ui->teStreamContent->find(ui->leFind->text());
}
if (found) {
ui->teStreamContent->setFocus();
} else if (go_back) {
ui->teStreamContent->moveCursor(QTextCursor::Start);
findText(false);
}
}
void FollowStreamDialog::saveAs()
{
QString file_name = WiresharkFileDialog::getSaveFileName(this, mainApp->windowTitleString(tr("Save Stream Content As…")));
if (file_name.isEmpty()) {
return;
}
QFile file(file_name);
if (!file.open(QIODevice::WriteOnly)) {
open_failure_alert_box(file_name.toUtf8().constData(), errno, TRUE);
return;
}
// Unconditionally save data as UTF-8 (even if data is decoded otherwise).
QByteArray bytes = ui->teStreamContent->toPlainText().toUtf8();
if (recent.gui_follow_show == SHOW_RAW) {
// The "Raw" format is currently displayed as hex data and needs to be
// converted to binary data.
bytes = QByteArray::fromHex(bytes);
}
QDataStream out(&file);
out.writeRawData(bytes.constData(), static_cast<int>(bytes.size()));
}
void FollowStreamDialog::helpButton()
{
mainApp->helpTopicAction(HELP_FOLLOW_STREAM_DIALOG);
}
void FollowStreamDialog::backButton()
{
if (terminating_)
return;
output_filter_ = previous_filter_;
close();
}
void FollowStreamDialog::filterOut()
{
if (terminating_)
return;
output_filter_ = filter_out_filter_;
close();
}
void FollowStreamDialog::close()
{
terminating_ = true;
// Update filter - Use:
// previous_filter if 'Close' (passed in follow() method)
// filter_out_filter_ if 'Filter Out This Stream' (built by appending !current_stream to previous_filter)
// leave filter alone if window closed. (current stream)
emit updateFilter(output_filter_, TRUE);
WiresharkDialog::close();
}
void FollowStreamDialog::on_cbDirections_currentIndexChanged(int idx)
{
switch(idx)
{
case 0 :
follow_info_.show_stream = BOTH_HOSTS;
break;
case 1 :
follow_info_.show_stream = FROM_SERVER;
break;
case 2 :
follow_info_.show_stream = FROM_CLIENT;
break;
default:
return;
}
readStream();
}
void FollowStreamDialog::on_cbCharset_currentIndexChanged(int idx)
{
if (idx < 0) return;
recent.gui_follow_show = static_cast<follow_show_type>(ui->cbCharset->itemData(idx).toInt());
readStream();
}
void FollowStreamDialog::on_bFind_clicked()
{
findText();
}
void FollowStreamDialog::on_leFind_returnPressed()
{
findText();
}
void FollowStreamDialog::on_streamNumberSpinBox_valueChanged(int stream_num)
{
if (file_closed_) return;
int sub_stream_num = 0;
ui->subStreamNumberSpinBox->blockSignals(true);
sub_stream_num = ui->subStreamNumberSpinBox->value();
ui->subStreamNumberSpinBox->blockSignals(false);
gboolean ok;
if (ui->subStreamNumberSpinBox->isVisible()) {
/* We need to find a suitable sub stream for the new stream */
follow_sub_stream_id_func sub_stream_func;
sub_stream_func = get_follow_sub_stream_id_func(follower_);
if (sub_stream_func == NULL) {
// Should not happen, this field is only visible for suitable protocols.
return;
}
guint sub_stream_num_new = static_cast<guint>(sub_stream_num);
if (sub_stream_num < 0) {
// Stream ID 0 should always exist as it is used for control messages.
// XXX: That is only guaranteed for HTTP2. For example, in QUIC,
// stream ID 0 is a normal stream used by the first standard client-
// initiated bidirectional stream (if it exists, and it might not)
// and we might have a stream (connection) but only the CRYPTO
// stream, which does not have a (sub) stream ID.
// What should we do if there is a stream with no substream to
// follow? Right now the substream spinbox is left active and
// the user can change the value to no effect.
sub_stream_num_new = 0;
ok = TRUE;
} else {
ok = sub_stream_func(static_cast<guint>(stream_num), sub_stream_num_new, FALSE, &sub_stream_num_new);
if (!ok) {
ok = sub_stream_func(static_cast<guint>(stream_num), sub_stream_num_new, TRUE, &sub_stream_num_new);
}
}
sub_stream_num = static_cast<gint>(sub_stream_num_new);
} else {
/* XXX: For HTTP and TLS, we use the TCP stream index, and really should
* return false if the TCP stream doesn't have HTTP or TLS. (Or we could
* switch to having separate HTTP and TLS stream numbers.)
*/
ok = true;
}
if (stream_num >= 0 && ok) {
follow(previous_filter_, true, stream_num, sub_stream_num);
previous_sub_stream_num_ = sub_stream_num;
}
}
void FollowStreamDialog::on_subStreamNumberSpinBox_valueChanged(int sub_stream_num)
{
if (file_closed_) return;
int stream_num = 0;
ui->streamNumberSpinBox->blockSignals(true);
stream_num = ui->streamNumberSpinBox->value();
ui->streamNumberSpinBox->blockSignals(false);
follow_sub_stream_id_func sub_stream_func;
sub_stream_func = get_follow_sub_stream_id_func(follower_);
if (sub_stream_func == NULL) {
// Should not happen, this field is only visible for suitable protocols.
return;
}
guint sub_stream_num_new = static_cast<guint>(sub_stream_num);
gboolean ok;
/* previous_sub_stream_num_ is a hack to track which buttons was pressed without event handling */
if (sub_stream_num < 0) {
// Stream ID 0 should always exist as it is used for control messages.
// XXX: That is only guaranteed for HTTP2, see above.
sub_stream_num_new = 0;
ok = TRUE;
} else if (previous_sub_stream_num_ < sub_stream_num) {
ok = sub_stream_func(static_cast<guint>(stream_num), sub_stream_num_new, FALSE, &sub_stream_num_new);
} else {
ok = sub_stream_func(static_cast<guint>(stream_num), sub_stream_num_new, TRUE, &sub_stream_num_new);
}
sub_stream_num = static_cast<gint>(sub_stream_num_new);
if (ok) {
follow(previous_filter_, true, stream_num, sub_stream_num);
previous_sub_stream_num_ = sub_stream_num;
}
}
void FollowStreamDialog::on_buttonBox_rejected()
{
// Ignore the close button if FollowStreamDialog::close() is running.
if (terminating_)
return;
WiresharkDialog::reject();
}
void FollowStreamDialog::removeStreamControls()
{
ui->horizontalLayout->removeItem(ui->streamNumberSpacer);
ui->streamNumberLabel->setVisible(false);
ui->streamNumberSpinBox->setVisible(false);
ui->subStreamNumberLabel->setVisible(false);
ui->subStreamNumberSpinBox->setVisible(false);
}
void FollowStreamDialog::resetStream()
{
GList *cur;
follow_record_t *follow_record;
filter_out_filter_.clear();
text_pos_to_packet_.clear();
if (!data_out_filename_.isEmpty()) {
ws_unlink(data_out_filename_.toUtf8().constData());
}
for (cur = follow_info_.payload; cur; cur = gxx_list_next(cur)) {
follow_record = gxx_list_data(follow_record_t *, cur);
if (follow_record->data) {
g_byte_array_free(follow_record->data, TRUE);
}
g_free(follow_record);
}
g_list_free(follow_info_.payload);
//Only TCP stream uses fragments
for (cur = follow_info_.fragments[0]; cur; cur = gxx_list_next(cur)) {
follow_record = gxx_list_data(follow_record_t *, cur);
if (follow_record->data) {
g_byte_array_free(follow_record->data, TRUE);
}
g_free(follow_record);
}
follow_info_.fragments[0] = Q_NULLPTR;
for (cur = follow_info_.fragments[1]; cur; cur = gxx_list_next(cur)) {
follow_record = gxx_list_data(follow_record_t *, cur);
if (follow_record->data) {
g_byte_array_free(follow_record->data, TRUE);
}
g_free(follow_record);
}
follow_info_.fragments[1] = Q_NULLPTR;
free_address(&follow_info_.client_ip);
free_address(&follow_info_.server_ip);
follow_info_.payload = Q_NULLPTR;
follow_info_.client_port = 0;
}
frs_return_t
FollowStreamDialog::readStream()
{
// interrupt any reading already running
loop_break_mutex.lock();
isReadRunning = FALSE;
loop_break_mutex.unlock();
ui->teStreamContent->clear();
text_pos_to_packet_.clear();
switch (recent.gui_follow_show) {
case SHOW_CARRAY:
case SHOW_HEXDUMP:
case SHOW_YAML:
/* We control the width and insert line breaks in these formats. */
ui->teStreamContent->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
break;
default:
/* Everything else might have extremely long lines without whitespace,
* (SHOW_RAW almost surely so), and QTextEdit is O(N^2) trying
* to search for word boundaries on long lines when adding text.
*/
ui->teStreamContent->setWordWrapMode(QTextOption::WrapAnywhere);
}
truncated_ = false;
frs_return_t ret;
client_buffer_count_ = 0;
server_buffer_count_ = 0;
client_packet_count_ = 0;
server_packet_count_ = 0;
last_packet_ = 0;
turns_ = 0;
if (follower_) {
ret = readFollowStream();
} else {
ret = (frs_return_t)0;
ws_assert_not_reached();
}
ui->teStreamContent->moveCursor(QTextCursor::Start);
return ret;
}
void
FollowStreamDialog::followStream()
{
readStream();
}
const int FollowStreamDialog::max_document_length_ = 500 * 1000 * 1000; // Just a guess
void FollowStreamDialog::addText(QString text, gboolean is_from_server, guint32 packet_num, gboolean colorize)
{
if (truncated_) {
return;
}
int char_count = ui->teStreamContent->document()->characterCount();
if (char_count + text.length() > max_document_length_) {
text.truncate(max_document_length_ - char_count);
truncated_ = true;
}
setUpdatesEnabled(false);
int cur_pos = ui->teStreamContent->verticalScrollBar()->value();
ui->teStreamContent->moveCursor(QTextCursor::End);
QTextCharFormat tcf = ui->teStreamContent->currentCharFormat();
if (!colorize) {
tcf.setBackground(palette().window().color());
tcf.setForeground(palette().windowText().color());
} else if (is_from_server) {
tcf.setForeground(ColorUtils::fromColorT(prefs.st_server_fg));
tcf.setBackground(ColorUtils::fromColorT(prefs.st_server_bg));
} else {
tcf.setForeground(ColorUtils::fromColorT(prefs.st_client_fg));
tcf.setBackground(ColorUtils::fromColorT(prefs.st_client_bg));
}
ui->teStreamContent->setCurrentCharFormat(tcf);
ui->teStreamContent->insertPlainText(text);
text_pos_to_packet_[ui->teStreamContent->textCursor().anchor()] = packet_num;
if (truncated_) {
tcf = ui->teStreamContent->currentCharFormat();
tcf.setBackground(palette().window().color());
tcf.setForeground(palette().windowText().color());
ui->teStreamContent->insertPlainText("\n" + tr("[Stream output truncated]"));
ui->teStreamContent->moveCursor(QTextCursor::End);
} else {
ui->teStreamContent->verticalScrollBar()->setValue(cur_pos);
}
setUpdatesEnabled(true);
}
// The following keyboard shortcuts should work (although
// they may not work consistently depending on focus):
// / (slash), Ctrl-F - Focus and highlight the search box
// Ctrl-G, Ctrl-N, F3 - Find next
// Should we make it so that typing any text starts searching?
bool FollowStreamDialog::eventFilter(QObject *, QEvent *event)
{
if (ui->teStreamContent->hasFocus() && event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->matches(QKeySequence::SelectAll) || keyEvent->matches(QKeySequence::Copy)
|| keyEvent->text().isEmpty()) {
return false;
}
ui->leFind->setFocus();
if (keyEvent->matches(QKeySequence::Find)) {
return true;
} else if (keyEvent->matches(QKeySequence::FindNext)) {
findText();
return true;
}
}
return false;
}
void FollowStreamDialog::keyPressEvent(QKeyEvent *event)
{
if (ui->leFind->hasFocus()) {
if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
findText();
return;
}
} else {
if (event->key() == Qt::Key_Slash || event->matches(QKeySequence::Find)) {
ui->leFind->setFocus();
ui->leFind->selectAll();
}
return;
}
if (event->key() == Qt::Key_F3 || (event->key() == Qt::Key_N && event->modifiers() & Qt::ControlModifier)) {
findText();
return;
}
QDialog::keyPressEvent(event);
}
static inline void sanitize_buffer(char *buffer, size_t nchars) {
for (size_t i = 0; i < nchars; i++) {
if (buffer[i] == '\n' || buffer[i] == '\r' || buffer[i] == '\t')
continue;
if (! g_ascii_isprint((guchar)buffer[i])) {
buffer[i] = '.';
}
}
}
frs_return_t
FollowStreamDialog::showBuffer(char *buffer, size_t nchars, gboolean is_from_server, guint32 packet_num,
nstime_t abs_ts, guint32 *global_pos)
{
gchar initbuf[256];
guint32 current_pos;
static const gchar hexchars[16] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
switch (recent.gui_follow_show) {
case SHOW_EBCDIC:
{
/* If our native arch is ASCII, call: */
EBCDIC_to_ASCII((guint8*)buffer, (guint) nchars);
sanitize_buffer(buffer, nchars);
QByteArray ba = QByteArray(buffer, (int)nchars);
addText(ba, is_from_server, packet_num);
break;
}
case SHOW_ASCII:
{
/* If our native arch is EBCDIC, call:
* ASCII_TO_EBCDIC(buffer, nchars);
*/
sanitize_buffer(buffer, nchars);
QByteArray ba = QByteArray(buffer, (int)nchars);
addText(ba, is_from_server, packet_num);
break;
}
case SHOW_CODEC:
{
// This assumes that multibyte characters don't span packets in the
// stream. To handle that case properly (which might occur with fixed
// block sizes, e.g. transferring over TFTP, we would need to create
// two stateful QTextDecoders, one for each direction, presumably in
// on_cbCharset_currentIndexChanged()
QTextCodec *codec = QTextCodec::codecForName(ui->cbCharset->currentText().toUtf8());
QByteArray ba = QByteArray(buffer, (int)nchars);
QString decoded = codec->toUnicode(ba);
addText(decoded, is_from_server, packet_num);
break;
}
case SHOW_HEXDUMP:
current_pos = 0;
while (current_pos < nchars) {
gchar hexbuf[256];
int i;
gchar *cur = hexbuf, *ascii_start;
/* is_from_server indentation : put 4 spaces at the
* beginning of the string */
/* XXX - We might want to prepend each line with "C" or "S" instead. */
if (is_from_server && follow_info_.show_stream == BOTH_HOSTS) {
memset(cur, ' ', 4);
cur += 4;
}
cur += snprintf(cur, 20, "%08X ", *global_pos);
/* 49 is space consumed by hex chars */
ascii_start = cur + 49 + 2;
for (i = 0; i < 16 && current_pos + i < nchars; i++) {
*cur++ =
hexchars[(buffer[current_pos + i] & 0xf0) >> 4];
*cur++ =
hexchars[buffer[current_pos + i] & 0x0f];
*cur++ = ' ';
if (i == 7)
*cur++ = ' ';
}
/* Fill it up if column isn't complete */
while (cur < ascii_start)
*cur++ = ' ';
/* Now dump bytes as text */
for (i = 0; i < 16 && current_pos + i < nchars; i++) {
*cur++ =
(g_ascii_isprint((guchar)buffer[current_pos + i]) ?
buffer[current_pos + i] : '.');
if (i == 7) {
*cur++ = ' ';
}
}
current_pos += i;
(*global_pos) += i;
*cur++ = '\n';
*cur = 0;
addText(hexbuf, is_from_server, packet_num);
}
break;
case SHOW_CARRAY:
current_pos = 0;
snprintf(initbuf, sizeof(initbuf), "char peer%d_%d[] = { /* Packet %u */\n",
is_from_server ? 1 : 0,
is_from_server ? server_buffer_count_++ : client_buffer_count_++,
packet_num);
addText(initbuf, is_from_server, packet_num);
while (current_pos < nchars) {
gchar hexbuf[256];
int i, cur;
cur = 0;
for (i = 0; i < 8 && current_pos + i < nchars; i++) {
/* Prepend entries with "0x" */
hexbuf[cur++] = '0';
hexbuf[cur++] = 'x';
hexbuf[cur++] =
hexchars[(buffer[current_pos + i] & 0xf0) >> 4];
hexbuf[cur++] =
hexchars[buffer[current_pos + i] & 0x0f];
/* Delimit array entries with a comma */
if (current_pos + i + 1 < nchars)
hexbuf[cur++] = ',';
hexbuf[cur++] = ' ';
}
/* Terminate the array if we are at the end */
if (current_pos + i == nchars) {
hexbuf[cur++] = '}';
hexbuf[cur++] = ';';
}
current_pos += i;
(*global_pos) += i;
hexbuf[cur++] = '\n';
hexbuf[cur] = 0;
addText(hexbuf, is_from_server, packet_num);
}
break;
case SHOW_YAML:
{
QString yaml_text;
const int base64_raw_len = 57; // Encodes to 76 bytes, common in RFCs
current_pos = 0;
if (last_packet_ == 0) {
// Header with general info about peers
const char *hostname0 = address_to_name(&follow_info_.client_ip);
const char *hostname1 = address_to_name(&follow_info_.server_ip);
char *port0 = get_follow_port_to_display(follower_)(NULL, follow_info_.client_port);
char *port1 = get_follow_port_to_display(follower_)(NULL, follow_info_.server_port);
addText("peers:\n", false, 0, false);
addText(QString(
" - peer: 0\n"
" host: %1\n"
" port: %2\n")
.arg(hostname0)
.arg(port0), false, 0);
addText(QString(
" - peer: 1\n"
" host: %1\n"
" port: %2\n")
.arg(hostname1)
.arg(port1), true, 0);
wmem_free(NULL, port0);
wmem_free(NULL, port1);
addText("packets:\n", false, 0, false);
}
if (packet_num != last_packet_) {
yaml_text.append(QString(" - packet: %1\n")
.arg(packet_num));
yaml_text.append(QString(" peer: %1\n")
.arg(is_from_server ? 1 : 0));
yaml_text.append(QString(" index: %1\n")
.arg(is_from_server ? server_buffer_count_++ : client_buffer_count_++));
yaml_text.append(QString(" timestamp: %1.%2\n")
.arg(abs_ts.secs)
.arg(abs_ts.nsecs, 9, 10, QChar('0')));
yaml_text.append(QString(" data: !!binary |\n"));
}
while (current_pos < nchars) {
int len = current_pos + base64_raw_len < nchars ? base64_raw_len : (int) nchars - current_pos;
QByteArray base64_data(&buffer[current_pos], len);
/* XXX: GCC 12.1 has a bogus stringop-overread warning using the Qt
* conversions from QByteArray to QString at -O2 and higher due to
* computing a branch that will never be taken.
*/
#if WS_IS_AT_LEAST_GNUC_VERSION(12,1)
DIAG_OFF(stringop-overread)
#endif
yaml_text += " " + base64_data.toBase64() + "\n";
#if WS_IS_AT_LEAST_GNUC_VERSION(12,1)
DIAG_ON(stringop-overread)
#endif
current_pos += len;
(*global_pos) += len;
}
addText(yaml_text, is_from_server, packet_num);
break;
}
case SHOW_RAW:
{
QByteArray ba = QByteArray(buffer, (int)nchars).toHex();
ba += '\n';
addText(ba, is_from_server, packet_num);
break;
}
}
if (last_packet_ == 0) {
last_from_server_ = is_from_server;
}
if (packet_num != last_packet_) {
last_packet_ = packet_num;
if (is_from_server) {
server_packet_count_++;
} else {
client_packet_count_++;
}
if (last_from_server_ != is_from_server) {
last_from_server_ = is_from_server;
turns_++;
}
}
return FRS_OK;
}
bool FollowStreamDialog::follow(QString previous_filter, bool use_stream_index, guint stream_num, guint sub_stream_num)
{
QString follow_filter;
const char *hostname0 = NULL, *hostname1 = NULL;
char *port0 = NULL, *port1 = NULL;
QString server_to_client_string;
QString client_to_server_string;
QString both_directions_string;
gboolean is_follower = FALSE;
int stream_count;
follow_stream_count_func stream_count_func = NULL;
resetStream();
if (file_closed_)
{
QMessageBox::warning(this, tr("No capture file."), tr("Please make sure you have a capture file opened."));
return false;
}
if (!use_stream_index) {
if (cap_file_.capFile()->edt == NULL)
{
QMessageBox::warning(this, tr("Error following stream."), tr("Capture file invalid."));
return false;
}
is_follower = proto_is_frame_protocol(cap_file_.capFile()->edt->pi.layers, proto_get_protocol_filter_name(get_follow_proto_id(follower_)));
if (!is_follower) {
QMessageBox::warning(this, tr("Error following stream."), tr("Please make sure you have a %1 packet selected.").arg
(proto_get_protocol_short_name(find_protocol_by_id(get_follow_proto_id(follower_)))));
return false;
}
}
follow_reset_stream(&follow_info_);
/* Create a new filter that matches all packets in the TCP stream,
and set the display filter entry accordingly */
if (use_stream_index) {
follow_filter = gchar_free_to_qstring(get_follow_index_func(follower_)(stream_num, sub_stream_num));
} else {
follow_filter = gchar_free_to_qstring(get_follow_conv_func(follower_)(cap_file_.capFile()->edt, &cap_file_.capFile()->edt->pi, &stream_num, &sub_stream_num));
}
if (follow_filter.isEmpty()) {
// XXX: This error probably has to do with tunneling (#18231), where
// the addresses or ports changed after the TCP or UDP layer.
// (The appropriate layer must be present, or else the GUI
// doesn't allow the option to be selected.)
QMessageBox::warning(this,
tr("Error creating filter for this stream."),
tr("%1 stream not found on the selected packet.").arg(proto_get_protocol_short_name(find_protocol_by_id(get_follow_proto_id(follower_)))));
return false;
}
previous_filter_ = previous_filter;
/* append the negation */
if (!previous_filter.isEmpty()) {
filter_out_filter_ = QString("%1 and !(%2)")
.arg(previous_filter).arg(follow_filter);
}
else
{
filter_out_filter_ = QString("!(%1)").arg(follow_filter);
}
follow_info_.substream_id = sub_stream_num;
/* data will be passed via tap callback*/
if (!registerTapListener(get_follow_tap_string(follower_), &follow_info_,
follow_filter.toUtf8().constData(),
0, NULL, get_follow_tap_handler(follower_), NULL)) {
return false;
}
stream_count_func = get_follow_stream_count_func(follower_);
if (stream_count_func == NULL) {
removeStreamControls();
} else {
stream_count = stream_count_func();
ui->streamNumberSpinBox->blockSignals(true);
ui->streamNumberSpinBox->setMaximum(stream_count-1);
ui->streamNumberSpinBox->setValue(stream_num);
ui->streamNumberSpinBox->blockSignals(false);
ui->streamNumberSpinBox->setToolTip(tr("%Ln total stream(s).", "", stream_count));
ui->streamNumberLabel->setToolTip(ui->streamNumberSpinBox->toolTip());
}
follow_sub_stream_id_func sub_stream_func;
sub_stream_func = get_follow_sub_stream_id_func(follower_);
if (sub_stream_func != NULL) {
guint substream_max_id = 0;
sub_stream_func(static_cast<guint>(stream_num), G_MAXINT32, TRUE, &substream_max_id);
stream_count = static_cast<gint>(substream_max_id);
ui->subStreamNumberSpinBox->blockSignals(true);
ui->subStreamNumberSpinBox->setEnabled(true);
ui->subStreamNumberSpinBox->setMaximum(stream_count);
ui->subStreamNumberSpinBox->setValue(sub_stream_num);
ui->subStreamNumberSpinBox->blockSignals(false);
ui->subStreamNumberSpinBox->setToolTip(tr("Max sub stream ID for the selected stream: %Ln", "", stream_count));
ui->subStreamNumberSpinBox->setToolTip(ui->subStreamNumberSpinBox->toolTip());
ui->subStreamNumberSpinBox->setVisible(true);
ui->subStreamNumberLabel->setVisible(true);
} else {
/* disable substream spin box for protocols without substreams */
ui->subStreamNumberSpinBox->blockSignals(true);
ui->subStreamNumberSpinBox->setEnabled(false);
ui->subStreamNumberSpinBox->setValue(0);
ui->subStreamNumberSpinBox->setKeyboardTracking(false);
ui->subStreamNumberSpinBox->blockSignals(false);
ui->subStreamNumberSpinBox->setVisible(false);
ui->subStreamNumberLabel->setVisible(false);
}
beginRetapPackets();
updateWidgets(true);
/* Run the display filter so it goes in effect - even if it's the
same as the previous display filter. */
emit updateFilter(follow_filter, TRUE);
removeTapListeners();
hostname0 = address_to_name(&follow_info_.client_ip);
hostname1 = address_to_name(&follow_info_.server_ip);
port0 = get_follow_port_to_display(follower_)(NULL, follow_info_.client_port);
port1 = get_follow_port_to_display(follower_)(NULL, follow_info_.server_port);
server_to_client_string =
QString("%1:%2 %3 %4:%5 (%6)")
.arg(hostname0).arg(port0)
.arg(UTF8_RIGHTWARDS_ARROW)
.arg(hostname1).arg(port1)
.arg(gchar_free_to_qstring(format_size(
follow_info_.bytes_written[0],
FORMAT_SIZE_UNIT_BYTES, FORMAT_SIZE_PREFIX_SI)));
client_to_server_string =
QString("%1:%2 %3 %4:%5 (%6)")
.arg(hostname1).arg(port1)
.arg(UTF8_RIGHTWARDS_ARROW)
.arg(hostname0).arg(port0)
.arg(gchar_free_to_qstring(format_size(
follow_info_.bytes_written[1],
FORMAT_SIZE_UNIT_BYTES, FORMAT_SIZE_PREFIX_SI)));
wmem_free(NULL, port0);
wmem_free(NULL, port1);
both_directions_string = tr("Entire conversation (%1)")
.arg(gchar_free_to_qstring(format_size(
follow_info_.bytes_written[0] + follow_info_.bytes_written[1],
FORMAT_SIZE_UNIT_BYTES, FORMAT_SIZE_PREFIX_SI)));
setWindowSubtitle(tr("Follow %1 Stream (%2)").arg(proto_get_protocol_short_name(find_protocol_by_id(get_follow_proto_id(follower_))))
.arg(follow_filter));
ui->cbDirections->blockSignals(true);
ui->cbDirections->clear();
ui->cbDirections->addItem(both_directions_string);
ui->cbDirections->addItem(client_to_server_string);
ui->cbDirections->addItem(server_to_client_string);
ui->cbDirections->blockSignals(false);
followStream();
fillHintLabel(-1);
updateWidgets(false);
endRetapPackets();
if (prefs.restore_filter_after_following_stream) {
emit updateFilter(previous_filter_, TRUE);
}
return true;
}
void FollowStreamDialog::captureFileClosed()
{
QString tooltip = tr("File closed.");
ui->streamNumberSpinBox->setToolTip(tooltip);
ui->streamNumberLabel->setToolTip(tooltip);
WiresharkDialog::captureFileClosed();
}
/*
* XXX - the routine pointed to by "print_line_fcn_p" doesn't get handed lines,
* it gets handed bufferfuls. That's fine for "follow_write_raw()"
* and "follow_add_to_gtk_text()", but, as "follow_print_text()" calls
* the "print_line()" routine from "print.c", and as that routine might
* genuinely expect to be handed a line (if, for example, it's using
* some OS or desktop environment's printing API, and that API expects
* to be handed lines), "follow_print_text()" should probably accumulate
* lines in a buffer and hand them "print_line()". (If there's a
* complete line in a buffer - i.e., there's nothing of the line in
* the previous buffer or the next buffer - it can just hand that to
* "print_line()" after filtering out non-printables, as an
* optimization.)
*
* This might or might not be the reason why C arrays display
* correctly but get extra blank lines very other line when printed.
*/
frs_return_t
FollowStreamDialog::readFollowStream()
{
guint32 global_client_pos = 0, global_server_pos = 0;
guint32 *global_pos;
gboolean skip;
GList* cur;
frs_return_t frs_return;
follow_record_t *follow_record;
QElapsedTimer elapsed_timer;
elapsed_timer.start();
loop_break_mutex.lock();
isReadRunning = TRUE;
loop_break_mutex.unlock();
for (cur = g_list_last(follow_info_.payload); cur; cur = g_list_previous(cur)) {
if (dialogClosed() || !isReadRunning) break;
follow_record = (follow_record_t *)cur->data;
skip = FALSE;
if (!follow_record->is_server) {
global_pos = &global_client_pos;
if (follow_info_.show_stream == FROM_SERVER) {
skip = TRUE;
}
} else {
global_pos = &global_server_pos;
if (follow_info_.show_stream == FROM_CLIENT) {
skip = TRUE;
}
}
QByteArray buffer;
if (!skip) {
// We want a deep copy.
buffer.clear();
buffer.append((const char *) follow_record->data->data,
follow_record->data->len);
frs_return = showBuffer(
buffer.data(),
follow_record->data->len,
follow_record->is_server,
follow_record->packet_num,
follow_record->abs_ts,
global_pos);
if (frs_return == FRS_PRINT_ERROR)
return frs_return;
if (elapsed_timer.elapsed() > info_update_freq_) {
fillHintLabel(ui->teStreamContent->textCursor().position());
mainApp->processEvents();
elapsed_timer.start();
}
}
}
loop_break_mutex.lock();
isReadRunning = FALSE;
loop_break_mutex.unlock();
return FRS_OK;
} |
C/C++ | wireshark/ui/qt/follow_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 FOLLOW_STREAM_DIALOG_H
#define FOLLOW_STREAM_DIALOG_H
#include <config.h>
#include <glib.h>
#include <stdio.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "file.h"
#include "epan/follow.h"
#include "wireshark_dialog.h"
#include <QFile>
#include <QMap>
#include <QPushButton>
#include <QTextCodec>
namespace Ui {
class FollowStreamDialog;
}
class FollowStreamDialog : public WiresharkDialog
{
Q_OBJECT
public:
explicit FollowStreamDialog(QWidget &parent, CaptureFile &cf, int proto_id);
~FollowStreamDialog();
void addCodecs(const QMap<QString, QTextCodec *> &codecMap);
bool follow(QString previous_filter = QString(), bool use_stream_index = false, guint stream_num = 0, guint sub_stream_num = 0);
protected:
bool eventFilter(QObject *obj, QEvent *event);
void keyPressEvent(QKeyEvent *event);
void captureFileClosed();
private slots:
void on_cbCharset_currentIndexChanged(int idx);
void on_cbDirections_currentIndexChanged(int idx);
void on_bFind_clicked();
void on_leFind_returnPressed();
void helpButton();
void backButton();
void close();
void filterOut();
void useRegexFind(bool use_regex);
void findText(bool go_back = true);
void saveAs();
void printStream();
void fillHintLabel(int text_pos);
void goToPacketForTextPos(int text_pos);
void on_streamNumberSpinBox_valueChanged(int stream_num);
void on_subStreamNumberSpinBox_valueChanged(int sub_stream_num);
void on_buttonBox_rejected();
signals:
void updateFilter(QString filter, bool force);
void goToPacket(int packet_num);
private:
void removeStreamControls();
void resetStream(void);
void updateWidgets(bool follow_in_progress);
void updateWidgets() { updateWidgets(false); } // Needed for WiresharkDialog?
frs_return_t
showBuffer(char *buffer, size_t nchars, gboolean is_from_server,
guint32 packet_num, nstime_t abs_ts, guint32 *global_pos);
frs_return_t readStream();
frs_return_t readFollowStream();
frs_return_t readSslStream();
void followStream();
void addText(QString text, gboolean is_from_server, guint32 packet_num, gboolean colorize = true);
Ui::FollowStreamDialog *ui;
QPushButton *b_filter_out_;
QPushButton *b_find_;
QPushButton *b_print_;
QPushButton *b_save_;
QPushButton *b_back_;
follow_info_t follow_info_;
register_follow_t* follower_;
QString data_out_filename_;
static const int max_document_length_;
bool truncated_;
QString previous_filter_;
QString filter_out_filter_;
QString output_filter_;
int client_buffer_count_;
int server_buffer_count_;
int client_packet_count_;
int server_packet_count_;
guint32 last_packet_;
gboolean last_from_server_;
int turns_;
QMap<int,guint32> text_pos_to_packet_;
bool use_regex_find_;
bool terminating_;
int previous_sub_stream_num_;
};
#endif // FOLLOW_STREAM_DIALOG_H |
User Interface | wireshark/ui/qt/follow_stream_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FollowStreamDialog</class>
<widget class="QDialog" name="FollowStreamDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>609</width>
<height>600</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Follow Stream</string>
</property>
<property name="sizeGripEnabled">
<bool>true</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="FollowStreamText" name="teStreamContent">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="hintLabel">
<property name="text">
<string>Hint.</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0,0,0,1,0,0,0,0">
<item>
<widget class="QComboBox" name="cbDirections">
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContents</enum>
</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="QLabel" name="label">
<property name="text">
<string>Show data as</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="cbCharset">
<property name="currentIndex">
<number>-1</number>
</property>
</widget>
</item>
<item>
<spacer name="streamNumberSpacer">
<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="QLabel" name="streamNumberLabel">
<property name="text">
<string>Stream</string>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="streamNumberSpinBox"/>
</item>
<item>
<widget class="QLabel" name="subStreamNumberLabel">
<property name="text">
<string>Substream</string>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="subStreamNumberSpinBox"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2" stretch="0,1,0">
<item>
<widget class="QLabel" name="lFind">
<property name="text">
<string>Find:</string>
</property>
</widget>
</item>
<item>
<widget class="FindLineEdit" name="leFind"/>
</item>
<item>
<widget class="QPushButton" name="bFind">
<property name="text">
<string>Find &Next</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="standardButtons">
<set>QDialogButtonBox::Close|QDialogButtonBox::Help</set>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>FollowStreamText</class>
<extends>QTextEdit</extends>
<header>widgets/follow_stream_text.h</header>
</customwidget>
<customwidget>
<class>FindLineEdit</class>
<extends>QLineEdit</extends>
<header>widgets/find_line_edit.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui> |
C++ | wireshark/ui/qt/font_color_preferences_frame.cpp | /* font_color_preferences_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 <ui/qt/utils/qt_ui_utils.h>
#include "font_color_preferences_frame.h"
#include <ui/qt/models/pref_models.h>
#include <ui_font_color_preferences_frame.h>
#include <ui/qt/utils/color_utils.h>
#include "main_application.h"
#include <functional>
#include <QFontDialog>
#include <QColorDialog>
#include <epan/prefs-int.h>
//: These are pangrams. Feel free to replace with nonsense text that spans your alphabet.
//: https://en.wikipedia.org/wiki/Pangram
static const char *font_pangrams_[] = {
QT_TRANSLATE_NOOP("FontColorPreferencesFrame", "Example GIF query packets have jumbo window sizes"),
QT_TRANSLATE_NOOP("FontColorPreferencesFrame", "Lazy badgers move unique waxy jellyfish packets")
};
const int num_font_pangrams_ = (sizeof font_pangrams_ / sizeof font_pangrams_[0]);
FontColorPreferencesFrame::FontColorPreferencesFrame(QWidget *parent) :
QFrame(parent),
ui(new Ui::FontColorPreferencesFrame)
{
ui->setupUi(this);
pref_qt_gui_font_name_ = prefFromPrefPtr(&prefs.gui_font_name);
pref_active_fg_ = prefFromPrefPtr(&prefs.gui_active_fg);
pref_active_bg_ = prefFromPrefPtr(&prefs.gui_active_bg);
pref_active_style_ = prefFromPrefPtr(&prefs.gui_active_style);
pref_inactive_fg_ = prefFromPrefPtr(&prefs.gui_inactive_fg);
pref_inactive_bg_ = prefFromPrefPtr(&prefs.gui_inactive_bg);
pref_inactive_style_ = prefFromPrefPtr(&prefs.gui_inactive_style);
pref_marked_fg_ = prefFromPrefPtr(&prefs.gui_marked_fg);
pref_marked_bg_ = prefFromPrefPtr(&prefs.gui_marked_bg);
pref_ignored_fg_ = prefFromPrefPtr(&prefs.gui_ignored_fg);
pref_ignored_bg_ = prefFromPrefPtr(&prefs.gui_ignored_bg);
pref_client_fg_ = prefFromPrefPtr(&prefs.st_client_fg);
pref_client_bg_ = prefFromPrefPtr(&prefs.st_client_bg);
pref_server_fg_ = prefFromPrefPtr(&prefs.st_server_fg);
pref_server_bg_ = prefFromPrefPtr(&prefs.st_server_bg);
pref_valid_bg_ = prefFromPrefPtr(&prefs.gui_text_valid);
pref_invalid_bg_ = prefFromPrefPtr(&prefs.gui_text_invalid);
pref_deprecated_bg_ = prefFromPrefPtr(&prefs.gui_text_deprecated);
cur_font_.fromString(prefs_get_string_value(pref_qt_gui_font_name_, pref_stashed));
}
FontColorPreferencesFrame::~FontColorPreferencesFrame()
{
delete ui;
}
void FontColorPreferencesFrame::showEvent(QShowEvent *)
{
GRand *rand_state = g_rand_new();
QString pangram = QString(font_pangrams_[g_rand_int_range(rand_state, 0, num_font_pangrams_)]) + " 0123456789";
ui->fontSampleLineEdit->setText(pangram);
ui->fontSampleLineEdit->setCursorPosition(0);
ui->fontSampleLineEdit->setMinimumWidth(mainApp->monospaceTextSize(pangram.toUtf8().constData()) + mainApp->monospaceTextSize(" "));
g_rand_free(rand_state);
updateWidgets();
}
void FontColorPreferencesFrame::updateWidgets()
{
gint colorstyle;
QColor foreground;
QColor background1;
QColor background2;
QPalette default_pal;
int margin = style()->pixelMetric(QStyle::PM_LayoutLeftMargin);
ui->fontPushButton->setText(
cur_font_.family() + " " + cur_font_.styleName() + " " +
QString::number(cur_font_.pointSizeF(), 'f', 1));
ui->fontSampleLineEdit->setFont(cur_font_);
QString line_edit_ss = QString("QLineEdit { margin-left: %1px; }").arg(margin);
ui->fontSampleLineEdit->setStyleSheet(line_edit_ss);
QString color_button_ss =
"QPushButton {"
" border: 1px solid palette(Dark);"
" background-color: %1;"
" margin-left: %2px;"
"}";
QString sample_text_ss =
"QLineEdit {"
" color: %1;"
" background-color: %2;"
"}";
QString sample_text_ex_ss =
"QLineEdit {"
" color: %1;"
" background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1 stop: 0 %3, stop: 0.5 %2, stop: 1 %3);"
"}";
//
// Sample active selected item
//
colorstyle = prefs_get_enum_value(pref_active_style_, pref_stashed);
// Make foreground and background colors
switch (colorstyle)
{
case COLOR_STYLE_DEFAULT:
default_pal = QApplication::palette();
default_pal.setCurrentColorGroup(QPalette::Active);
foreground = default_pal.highlightedText().color();
background1 = default_pal.highlight().color();
background2 = default_pal.highlight().color();
break;
case COLOR_STYLE_FLAT:
foreground = ColorUtils::fromColorT(prefs_get_color_value(pref_active_fg_, pref_stashed));
background1 = ColorUtils::fromColorT(prefs_get_color_value(pref_active_bg_, pref_stashed));
background2 = ColorUtils::fromColorT(prefs_get_color_value(pref_active_bg_, pref_stashed));
break;
case COLOR_STYLE_GRADIENT:
foreground = ColorUtils::fromColorT(prefs_get_color_value(pref_active_fg_, pref_stashed));
background1 = ColorUtils::fromColorT(prefs_get_color_value(pref_active_bg_, pref_stashed));
background2 = QColor::fromRgb(ColorUtils::alphaBlend(foreground, background1, COLOR_STYLE_ALPHA));
break;
}
ui->activeFGPushButton->setStyleSheet(color_button_ss.arg(foreground.name()).arg(margin));
ui->activeBGPushButton->setStyleSheet(color_button_ss.arg(background1.name()).arg(0));
ui->activeSampleLineEdit->setStyleSheet(sample_text_ex_ss.arg(
foreground.name(),
background1.name(),
background2.name()));
ui->activeSampleLineEdit->setFont(cur_font_);
ui->activeStyleComboBox->setCurrentIndex(prefs_get_enum_value(pref_active_style_, pref_stashed));
// Show or hide the widgets
ui->activeFGPushButton->setVisible(colorstyle != COLOR_STYLE_DEFAULT);
ui->activeBGPushButton->setVisible(colorstyle != COLOR_STYLE_DEFAULT);
//
// Sample inactive selected item
//
colorstyle = prefs_get_enum_value(pref_inactive_style_, pref_stashed);
// Make foreground and background colors
switch (colorstyle)
{
case COLOR_STYLE_DEFAULT:
default_pal = QApplication::palette();
default_pal.setCurrentColorGroup(QPalette::Inactive);
foreground = default_pal.highlightedText().color();
background1 = default_pal.highlight().color();
background2 = default_pal.highlight().color();
break;
case COLOR_STYLE_FLAT:
foreground = ColorUtils::fromColorT(prefs_get_color_value(pref_inactive_fg_, pref_stashed));
background1 = ColorUtils::fromColorT(prefs_get_color_value(pref_inactive_bg_, pref_stashed));
background2 = ColorUtils::fromColorT(prefs_get_color_value(pref_inactive_bg_, pref_stashed));
break;
case COLOR_STYLE_GRADIENT:
foreground = ColorUtils::fromColorT(prefs_get_color_value(pref_inactive_fg_, pref_stashed));
background1 = ColorUtils::fromColorT(prefs_get_color_value(pref_inactive_bg_, pref_stashed));
background2 = QColor::fromRgb(ColorUtils::alphaBlend(foreground, background1, COLOR_STYLE_ALPHA));
break;
}
ui->inactiveFGPushButton->setStyleSheet(color_button_ss.arg(foreground.name()).arg(margin));
ui->inactiveBGPushButton->setStyleSheet(color_button_ss.arg(background1.name()).arg(0));
ui->inactiveSampleLineEdit->setStyleSheet(sample_text_ex_ss.arg(
foreground.name(),
background1.name(),
background2.name()));
ui->inactiveSampleLineEdit->setFont(cur_font_);
ui->inactiveStyleComboBox->setCurrentIndex(prefs_get_enum_value(pref_inactive_style_, pref_stashed));
// Show or hide the widgets
ui->inactiveFGPushButton->setVisible(colorstyle != COLOR_STYLE_DEFAULT);
ui->inactiveBGPushButton->setVisible(colorstyle != COLOR_STYLE_DEFAULT);
//
// Sample marked packet text
//
ui->markedFGPushButton->setStyleSheet(color_button_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_marked_fg_, pref_stashed)).name())
.arg(margin));
ui->markedBGPushButton->setStyleSheet(color_button_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_marked_bg_, pref_stashed)).name())
.arg(0));
ui->markedSampleLineEdit->setStyleSheet(sample_text_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_marked_fg_, pref_stashed)).name(),
ColorUtils::fromColorT(prefs_get_color_value(pref_marked_bg_, pref_stashed)).name()));
ui->markedSampleLineEdit->setFont(cur_font_);
//
// Sample ignored packet text
//
ui->ignoredFGPushButton->setStyleSheet(color_button_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_ignored_fg_, pref_stashed)).name())
.arg(margin));
ui->ignoredBGPushButton->setStyleSheet(color_button_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_ignored_bg_, pref_stashed)).name())
.arg(0));
ui->ignoredSampleLineEdit->setStyleSheet(sample_text_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_ignored_fg_, pref_stashed)).name(),
ColorUtils::fromColorT(prefs_get_color_value(pref_ignored_bg_, pref_stashed)).name()));
ui->ignoredSampleLineEdit->setFont(cur_font_);
//
// Sample "Follow Stream" client text
//
ui->clientFGPushButton->setStyleSheet(color_button_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_client_fg_, pref_stashed)).name())
.arg(margin));
ui->clientBGPushButton->setStyleSheet(color_button_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_client_bg_, pref_stashed)).name())
.arg(0));
ui->clientSampleLineEdit->setStyleSheet(sample_text_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_client_fg_, pref_stashed)).name(),
ColorUtils::fromColorT(prefs_get_color_value(pref_client_bg_, pref_stashed)).name()));
ui->clientSampleLineEdit->setFont(cur_font_);
//
// Sample "Follow Stream" server text
//
ui->serverFGPushButton->setStyleSheet(color_button_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_server_fg_, pref_stashed)).name())
.arg(margin));
ui->serverBGPushButton->setStyleSheet(color_button_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_server_bg_, pref_stashed)).name())
.arg(0));
ui->serverSampleLineEdit->setStyleSheet(sample_text_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_server_fg_, pref_stashed)).name(),
ColorUtils::fromColorT(prefs_get_color_value(pref_server_bg_, pref_stashed)).name()));
ui->serverSampleLineEdit->setFont(cur_font_);
//
// Sample valid filter
//
QColor ss_bg = ColorUtils::fromColorT(prefs_get_color_value(pref_valid_bg_, pref_stashed));
ui->validFilterBGPushButton->setStyleSheet(color_button_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_valid_bg_, pref_stashed)).name())
.arg(0));
ui->validFilterSampleLineEdit->setStyleSheet(sample_text_ss.arg(
ColorUtils::contrastingTextColor(ss_bg).name(),
ss_bg.name()));
//
// Sample invalid filter
//
ss_bg = ColorUtils::fromColorT(prefs_get_color_value(pref_invalid_bg_, pref_stashed));
ui->invalidFilterBGPushButton->setStyleSheet(color_button_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_invalid_bg_, pref_stashed)).name())
.arg(0));
ui->invalidFilterSampleLineEdit->setStyleSheet(sample_text_ss.arg(
ColorUtils::contrastingTextColor(ss_bg).name(),
ss_bg.name()));
//
// Sample warning filter
//
ss_bg = ColorUtils::fromColorT(prefs_get_color_value(pref_deprecated_bg_, pref_stashed));
ui->deprecatedFilterBGPushButton->setStyleSheet(color_button_ss.arg(
ColorUtils::fromColorT(prefs_get_color_value(pref_deprecated_bg_, pref_stashed)).name())
.arg(0));
ui->deprecatedFilterSampleLineEdit->setStyleSheet(sample_text_ss.arg(
ColorUtils::contrastingTextColor(ss_bg).name(),
ss_bg.name()));
}
void FontColorPreferencesFrame::changeColor(pref_t *pref)
{
QColorDialog *color_dlg = new QColorDialog();
color_t* color = prefs_get_color_value(pref, pref_stashed);
color_dlg->setCurrentColor(QColor(
color->red >> 8,
color->green >> 8,
color->blue >> 8
));
connect(color_dlg, &QColorDialog::colorSelected, std::bind(&FontColorPreferencesFrame::colorChanged, this, pref, std::placeholders::_1));
color_dlg->setWindowModality(Qt::ApplicationModal);
color_dlg->setAttribute(Qt::WA_DeleteOnClose);
color_dlg->show();
}
void FontColorPreferencesFrame::colorChanged(pref_t *pref, const QColor &cc)
{
color_t new_color;
new_color.red = cc.red() << 8 | cc.red();
new_color.green = cc.green() << 8 | cc.green();
new_color.blue = cc.blue() << 8 | cc.blue();
prefs_set_color_value(pref, new_color, pref_stashed);
updateWidgets();
}
void FontColorPreferencesFrame::on_fontPushButton_clicked()
{
bool ok;
QFont new_font = QFontDialog::getFont(&ok, cur_font_, this, mainApp->windowTitleString(tr("Font")));
if (ok) {
prefs_set_string_value(pref_qt_gui_font_name_, new_font.toString().toStdString().c_str(), pref_stashed);
cur_font_ = new_font;
updateWidgets();
}
}
void FontColorPreferencesFrame::on_activeFGPushButton_clicked()
{
changeColor(pref_active_fg_);
}
void FontColorPreferencesFrame::on_activeBGPushButton_clicked()
{
changeColor(pref_active_bg_);
}
void FontColorPreferencesFrame::on_activeStyleComboBox_currentIndexChanged(int index)
{
prefs_set_enum_value(pref_active_style_, index, pref_stashed);
updateWidgets();
}
void FontColorPreferencesFrame::on_inactiveFGPushButton_clicked()
{
changeColor(pref_inactive_fg_);
}
void FontColorPreferencesFrame::on_inactiveBGPushButton_clicked()
{
changeColor(pref_inactive_bg_);
}
void FontColorPreferencesFrame::on_inactiveStyleComboBox_currentIndexChanged(int index)
{
prefs_set_enum_value(pref_inactive_style_, index, pref_stashed);
updateWidgets();
}
void FontColorPreferencesFrame::on_markedFGPushButton_clicked()
{
changeColor(pref_marked_fg_);
}
void FontColorPreferencesFrame::on_markedBGPushButton_clicked()
{
changeColor(pref_marked_bg_);
}
void FontColorPreferencesFrame::on_ignoredFGPushButton_clicked()
{
changeColor(pref_ignored_fg_);
}
void FontColorPreferencesFrame::on_ignoredBGPushButton_clicked()
{
changeColor(pref_ignored_bg_);
}
void FontColorPreferencesFrame::on_clientFGPushButton_clicked()
{
changeColor(pref_client_fg_);
}
void FontColorPreferencesFrame::on_clientBGPushButton_clicked()
{
changeColor(pref_client_bg_);
}
void FontColorPreferencesFrame::on_serverFGPushButton_clicked()
{
changeColor(pref_server_fg_);
}
void FontColorPreferencesFrame::on_serverBGPushButton_clicked()
{
changeColor(pref_server_bg_);
}
void FontColorPreferencesFrame::on_validFilterBGPushButton_clicked()
{
changeColor(pref_valid_bg_);
}
void FontColorPreferencesFrame::on_invalidFilterBGPushButton_clicked()
{
changeColor(pref_invalid_bg_);
}
void FontColorPreferencesFrame::on_deprecatedFilterBGPushButton_clicked()
{
changeColor(pref_deprecated_bg_);
} |
C/C++ | wireshark/ui/qt/font_color_preferences_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 FONT_COLOR_PREFERENCES_FRAME_H
#define FONT_COLOR_PREFERENCES_FRAME_H
#include <QFrame>
#include <QFont>
#include <epan/prefs.h>
namespace Ui {
class FontColorPreferencesFrame;
}
class FontColorPreferencesFrame : public QFrame
{
Q_OBJECT
public:
explicit FontColorPreferencesFrame(QWidget *parent = 0);
~FontColorPreferencesFrame();
protected:
void showEvent(QShowEvent *evt);
private:
Ui::FontColorPreferencesFrame *ui;
pref_t *pref_qt_gui_font_name_;
pref_t *pref_active_fg_;
pref_t *pref_active_bg_;
pref_t *pref_active_style_;
pref_t *pref_inactive_fg_;
pref_t *pref_inactive_bg_;
pref_t *pref_inactive_style_;
pref_t *pref_marked_fg_;
pref_t *pref_marked_bg_;
pref_t *pref_ignored_fg_;
pref_t *pref_ignored_bg_;
pref_t *pref_client_fg_;
pref_t *pref_client_bg_;
pref_t *pref_server_fg_;
pref_t *pref_server_bg_;
pref_t *pref_valid_bg_;
pref_t *pref_invalid_bg_;
pref_t *pref_deprecated_bg_;
QFont cur_font_;
void updateWidgets();
void changeColor(pref_t *pref);
private slots:
void colorChanged(pref_t *pref, const QColor &cc);
void on_fontPushButton_clicked();
void on_activeFGPushButton_clicked();
void on_activeBGPushButton_clicked();
void on_activeStyleComboBox_currentIndexChanged(int index);
void on_inactiveFGPushButton_clicked();
void on_inactiveBGPushButton_clicked();
void on_inactiveStyleComboBox_currentIndexChanged(int index);
void on_markedFGPushButton_clicked();
void on_markedBGPushButton_clicked();
void on_ignoredFGPushButton_clicked();
void on_ignoredBGPushButton_clicked();
void on_clientFGPushButton_clicked();
void on_clientBGPushButton_clicked();
void on_serverFGPushButton_clicked();
void on_serverBGPushButton_clicked();
void on_validFilterBGPushButton_clicked();
void on_invalidFilterBGPushButton_clicked();
void on_deprecatedFilterBGPushButton_clicked();
};
#endif // FONT_COLOR_PREFERENCES_FRAME_H |
User Interface | wireshark/ui/qt/font_color_preferences_frame.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FontColorPreferencesFrame</class>
<widget class="QFrame" name="FontColorPreferencesFrame">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>540</width>
<height>390</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>540</width>
<height>390</height>
</size>
</property>
<property name="windowTitle">
<string>Frame</string>
</property>
<property name="lineWidth">
<number>0</number>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Main window font:</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="fontPushButton">
<property name="text">
<string>Select Font</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="QLineEdit" name="fontSampleLineEdit">
<property name="text">
<string/>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>Colors:</string>
</property>
</widget>
</item>
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QPushButton" name="activeFGPushButton">
<property name="enabled">
<bool>true</bool>
</property>
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QPushButton" name="activeBGPushButton">
<property name="enabled">
<bool>true</bool>
</property>
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
</widget>
</item>
<item row="0" column="2">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLineEdit" name="activeSampleLineEdit">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>Sample active selected item</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Style:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="activeStyleComboBox">
<item>
<property name="text">
<string>System Default</string>
</property>
</item>
<item>
<property name="text">
<string>Solid</string>
</property>
</item>
<item>
<property name="text">
<string>Gradient</string>
</property>
</item>
</widget>
</item>
</layout>
</item>
<item row="1" column="0">
<widget class="QPushButton" name="inactiveFGPushButton">
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="inactiveBGPushButton">
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="1" column="2">
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLineEdit" name="inactiveSampleLineEdit">
<property name="text">
<string>Sample inactive selected item</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_4">
<property name="text">
<string>Style:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="inactiveStyleComboBox">
<item>
<property name="text">
<string>System Default</string>
</property>
</item>
<item>
<property name="text">
<string>Solid</string>
</property>
</item>
<item>
<property name="text">
<string>Gradient</string>
</property>
</item>
</widget>
</item>
</layout>
</item>
<item row="2" column="0">
<widget class="QPushButton" name="markedFGPushButton">
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QPushButton" name="markedBGPushButton">
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item row="2" column="2">
<widget class="QLineEdit" name="markedSampleLineEdit">
<property name="text">
<string>Sample marked packet text</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QPushButton" name="ignoredFGPushButton">
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QPushButton" name="ignoredBGPushButton">
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item row="3" column="2">
<widget class="QLineEdit" name="ignoredSampleLineEdit">
<property name="text">
<string>Sample ignored packet text</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QPushButton" name="clientFGPushButton">
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QPushButton" name="clientBGPushButton">
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item row="4" column="2">
<widget class="QLineEdit" name="clientSampleLineEdit">
<property name="text">
<string>Sample "Follow Stream" client text</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QPushButton" name="serverFGPushButton">
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QPushButton" name="serverBGPushButton">
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item row="5" column="2">
<widget class="QLineEdit" name="serverSampleLineEdit">
<property name="text">
<string>Sample "Follow Stream" server text</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item row="6" column="1">
<widget class="QPushButton" name="validFilterBGPushButton">
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item row="6" column="2">
<widget class="QLineEdit" name="validFilterSampleLineEdit">
<property name="text">
<string>Sample valid filter</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item row="7" column="1">
<widget class="QPushButton" name="invalidFilterBGPushButton">
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item row="7" column="2">
<widget class="QLineEdit" name="invalidFilterSampleLineEdit">
<property name="text">
<string>Sample invalid filter</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item row="8" column="1">
<widget class="QPushButton" name="deprecatedFilterBGPushButton">
<property name="styleSheet">
<string notr="true">QPushButton { border: 1px solid palette(Dark); }</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item row="8" column="2">
<widget class="QLineEdit" name="deprecatedFilterSampleLineEdit">
<property name="text">
<string>Sample warning filter</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>178</width>
<height>13</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui> |
C++ | wireshark/ui/qt/funnel_statistics.cpp | /* funnel_statistics.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <glib.h>
#include "epan/color_filters.h"
#include "file.h"
#include "epan/funnel.h"
#include "epan/prefs.h"
#include <wsutil/wslog.h>
#include "ui/progress_dlg.h"
#include "ui/simple_dialog.h"
#include <ui/qt/main_window.h>
#include <ui/qt/io_console_dialog.h>
#include "funnel_statistics.h"
#include "funnel_string_dialog.h"
#include "funnel_text_dialog.h"
#include <QAction>
#include <QClipboard>
#include <QDebug>
#include <QDesktopServices>
#include <QMenu>
#include <QUrl>
#include "main_application.h"
// To do:
// - Handle menu paths. Do we create a new path (GTK+) or use the base element?
// - Add a FunnelGraphDialog class?
extern "C" {
static struct _funnel_text_window_t* text_window_new(funnel_ops_id_t *ops_id, const char* title);
static void string_dialog_new(funnel_ops_id_t *ops_id, const gchar* title, const gchar** field_names, const gchar** field_values, funnel_dlg_cb_t dialog_cb, void* dialog_cb_data, funnel_dlg_cb_data_free_t dialog_cb_data_free);
static void funnel_statistics_retap_packets(funnel_ops_id_t *ops_id);
static void funnel_statistics_copy_to_clipboard(GString *text);
static const gchar *funnel_statistics_get_filter(funnel_ops_id_t *ops_id);
static void funnel_statistics_set_filter(funnel_ops_id_t *ops_id, const char* filter_string);
static gchar* funnel_statistics_get_color_filter_slot(guint8 filter_num);
static void funnel_statistics_set_color_filter_slot(guint8 filter_num, const gchar* filter_string);
static gboolean funnel_statistics_open_file(funnel_ops_id_t *ops_id, const char* fname, const char* filter, char**);
static void funnel_statistics_reload_packets(funnel_ops_id_t *ops_id);
static void funnel_statistics_redissect_packets(funnel_ops_id_t *ops_id);
static void funnel_statistics_reload_lua_plugins(funnel_ops_id_t *ops_id);
static void funnel_statistics_apply_filter(funnel_ops_id_t *ops_id);
static gboolean browser_open_url(const gchar *url);
static void browser_open_data_file(const gchar *filename);
static struct progdlg *progress_window_new(funnel_ops_id_t *ops_id, const gchar* title, const gchar* task, gboolean terminate_is_stop, gboolean *stop_flag);
static void progress_window_update(struct progdlg *progress_dialog, float percentage, const gchar* status);
static void progress_window_destroy(struct progdlg *progress_dialog);
}
FunnelAction::FunnelAction(QObject *parent) :
QAction(parent)
{
}
FunnelAction::FunnelAction(QString title, funnel_menu_callback callback, gpointer callback_data, gboolean retap, QObject *parent = nullptr) :
QAction(parent),
title_(title),
callback_(callback),
callback_data_(callback_data),
retap_(retap)
{
// Use "&&" to get a real ampersand in the menu item.
title.replace('&', "&&");
setText(title);
setObjectName(FunnelStatistics::actionName());
packetRequiredFields_ = QSet<QString>();
}
FunnelAction::FunnelAction(QString title, funnel_packet_menu_callback callback, gpointer callback_data, gboolean retap, const char *packet_required_fields, QObject *parent = nullptr) :
QAction(parent),
title_(title),
callback_data_(callback_data),
retap_(retap),
packetCallback_(callback),
packetRequiredFields_(QSet<QString>())
{
// Use "&&" to get a real ampersand in the menu item.
title.replace('&', "&&");
QStringList menuComponents = title.split(QString("/"));
// Set the menu's text to the rightmost component, set the path to being everything to the left:
setText("(empty)");
packetSubmenu_ = "";
if (!menuComponents.isEmpty())
{
setText(menuComponents.last());
menuComponents.removeLast();
packetSubmenu_ = menuComponents.join("/");
}
setObjectName(FunnelStatistics::actionName());
setPacketRequiredFields(packet_required_fields);
}
FunnelAction::~FunnelAction(){
}
funnel_menu_callback FunnelAction::callback() const {
return callback_;
}
QString FunnelAction::title() const {
return title_;
}
void FunnelAction::triggerCallback() {
if (callback_) {
callback_(callback_data_);
}
}
void FunnelAction::setPacketCallback(funnel_packet_menu_callback packet_callback) {
packetCallback_ = packet_callback;
}
void FunnelAction::setPacketRequiredFields(const char *required_fields_str) {
packetRequiredFields_.clear();
// If multiple fields are required to be present, they're split by commas
// Also remove leading and trailing spaces, in case someone writes
// "http, dns" instead of "http,dns"
QString requiredFieldsJoined = QString(required_fields_str);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
QStringList requiredFieldsSplit = requiredFieldsJoined.split(",", Qt::SkipEmptyParts);
#else
QStringList requiredFieldsSplit = requiredFieldsJoined.split(",", QString::SkipEmptyParts);
#endif
foreach (QString requiredField, requiredFieldsSplit) {
QString trimmedFieldName = requiredField.trimmed();
if (! trimmedFieldName.isEmpty()) {
packetRequiredFields_.insert(trimmedFieldName);
}
}
}
const QSet<QString> FunnelAction::getPacketRequiredFields() {
return packetRequiredFields_;
}
void FunnelAction::setPacketData(GPtrArray* finfos) {
packetData_ = finfos;
}
void FunnelAction::addToMenu(QMenu * ctx_menu, QHash<QString, QMenu *> menuTextToMenus) {
QString submenusText = this->getPacketSubmenus();
if (submenusText.isEmpty()) {
ctx_menu->addAction(this);
} else {
// If the action has a submenu, ensure that the
// the full submenu chain exists:
QStringList menuComponents = submenusText.split("/");
QString menuSubComponentsStringPrior = NULL;
for (int menuIndex=0; menuIndex < menuComponents.size(); menuIndex++) {
QStringList menuSubComponents = menuComponents.mid(0, menuIndex+1);
QString menuSubComponentsString = menuSubComponents.join("/");
if (!menuTextToMenus.contains(menuSubComponentsString)) {
// Create a new menu object under the prior object
QMenu *previousSubmenu = menuTextToMenus.value(menuSubComponentsStringPrior);
QMenu *submenu = previousSubmenu->addMenu(menuComponents.at(menuIndex));
menuTextToMenus.insert(menuSubComponentsString, submenu);
}
menuSubComponentsStringPrior = menuSubComponentsString;
}
// Then add the action to the relevant submenu
QMenu *parentMenu = menuTextToMenus.value(submenusText);
parentMenu->addAction(this);
}
}
void FunnelAction::triggerPacketCallback() {
if (packetCallback_) {
packetCallback_(callback_data_, packetData_);
}
}
bool FunnelAction::retap() {
if (retap_) return true;
return false;
}
QString FunnelAction::getPacketSubmenus() {
return packetSubmenu_;
}
FunnelConsoleAction::FunnelConsoleAction(QString name,
funnel_console_eval_cb_t eval_cb,
funnel_console_open_cb_t open_cb,
funnel_console_close_cb_t close_cb,
void *callback_data, QObject *parent = nullptr) :
FunnelAction(parent),
eval_cb_(eval_cb),
open_cb_(open_cb),
close_cb_(close_cb),
callback_data_(callback_data)
{
// Use "&&" to get a real ampersand in the menu item.
QString title = QString("%1 Console").arg(name).replace('&', "&&");
setText(title);
setObjectName(FunnelStatistics::actionName());
}
FunnelConsoleAction::~FunnelConsoleAction()
{
}
void FunnelConsoleAction::triggerCallback() {
IOConsoleDialog *dialog = new IOConsoleDialog(*qobject_cast<QWidget *>(parent()),
this->text(),
eval_cb_, open_cb_, close_cb_, callback_data_);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
static QHash<int, QList<FunnelAction *> > funnel_actions_;
const QString FunnelStatistics::action_name_ = "FunnelStatisticsAction";
static gboolean menus_registered = FALSE;
struct _funnel_ops_id_t {
FunnelStatistics *funnel_statistics;
};
FunnelStatistics::FunnelStatistics(QObject *parent, CaptureFile &cf) :
QObject(parent),
capture_file_(cf),
prepared_filter_(QString())
{
funnel_ops_ = new(struct _funnel_ops_t);
memset(funnel_ops_, 0, sizeof(struct _funnel_ops_t));
funnel_ops_id_ = new(struct _funnel_ops_id_t);
funnel_ops_id_->funnel_statistics = this;
funnel_ops_->ops_id = funnel_ops_id_;
funnel_ops_->new_text_window = text_window_new;
funnel_ops_->set_text = text_window_set_text;
funnel_ops_->append_text = text_window_append;
funnel_ops_->prepend_text = text_window_prepend;
funnel_ops_->clear_text = text_window_clear;
funnel_ops_->get_text = text_window_get_text;
funnel_ops_->set_close_cb = text_window_set_close_cb;
funnel_ops_->set_editable = text_window_set_editable;
funnel_ops_->destroy_text_window = text_window_destroy;
funnel_ops_->add_button = text_window_add_button;
funnel_ops_->new_dialog = string_dialog_new;
funnel_ops_->close_dialogs = string_dialogs_close;
funnel_ops_->retap_packets = funnel_statistics_retap_packets;
funnel_ops_->copy_to_clipboard = funnel_statistics_copy_to_clipboard;
funnel_ops_->get_filter = funnel_statistics_get_filter;
funnel_ops_->set_filter = funnel_statistics_set_filter;
funnel_ops_->get_color_filter_slot = funnel_statistics_get_color_filter_slot;
funnel_ops_->set_color_filter_slot = funnel_statistics_set_color_filter_slot;
funnel_ops_->open_file = funnel_statistics_open_file;
funnel_ops_->reload_packets = funnel_statistics_reload_packets;
funnel_ops_->redissect_packets = funnel_statistics_redissect_packets;
funnel_ops_->reload_lua_plugins = funnel_statistics_reload_lua_plugins;
funnel_ops_->apply_filter = funnel_statistics_apply_filter;
funnel_ops_->browser_open_url = browser_open_url;
funnel_ops_->browser_open_data_file = browser_open_data_file;
funnel_ops_->new_progress_window = progress_window_new;
funnel_ops_->update_progress = progress_window_update;
funnel_ops_->destroy_progress_window = progress_window_destroy;
funnel_set_funnel_ops(funnel_ops_);
}
FunnelStatistics::~FunnelStatistics()
{
// At this point we're probably closing the program and will shortly
// call epan_cleanup, which calls ProgDlg__gc and TextWindow__gc.
// They in turn depend on funnel_ops_ being valid.
memset(funnel_ops_id_, 0, sizeof(struct _funnel_ops_id_t));
memset(funnel_ops_, 0, sizeof(struct _funnel_ops_t));
// delete(funnel_ops_id_);
// delete(funnel_ops_);
}
void FunnelStatistics::retapPackets()
{
capture_file_.retapPackets();
}
struct progdlg *FunnelStatistics::progressDialogNew(const gchar *task_title, const gchar *item_title, gboolean terminate_is_stop, gboolean *stop_flag)
{
return create_progress_dlg(parent(), task_title, item_title, terminate_is_stop, stop_flag);
}
const char *FunnelStatistics::displayFilter()
{
return display_filter_.constData();
}
void FunnelStatistics::emitSetDisplayFilter(const QString filter)
{
prepared_filter_ = filter;
emit setDisplayFilter(filter, FilterAction::ActionPrepare, FilterAction::ActionTypePlain);
}
void FunnelStatistics::reloadPackets()
{
capture_file_.reload();
}
void FunnelStatistics::redissectPackets()
{
// This will trigger a packet redissection.
mainApp->emitAppSignal(MainApplication::PacketDissectionChanged);
}
void FunnelStatistics::reloadLuaPlugins()
{
mainApp->reloadLuaPluginsDelayed();
}
void FunnelStatistics::emitApplyDisplayFilter()
{
emit setDisplayFilter(prepared_filter_, FilterAction::ActionApply, FilterAction::ActionTypePlain);
}
void FunnelStatistics::emitOpenCaptureFile(QString cf_path, QString filter)
{
emit openCaptureFile(cf_path, filter);
}
void FunnelStatistics::funnelActionTriggered()
{
FunnelAction *funnel_action = dynamic_cast<FunnelAction *>(sender());
if (!funnel_action) return;
funnel_action->triggerCallback();
}
void FunnelStatistics::displayFilterTextChanged(const QString &filter)
{
display_filter_ = filter.toUtf8();
}
struct _funnel_text_window_t* text_window_new(funnel_ops_id_t *ops_id, const char* title)
{
return FunnelTextDialog::textWindowNew(qobject_cast<QWidget *>(ops_id->funnel_statistics->parent()), title);
}
void string_dialog_new(funnel_ops_id_t *ops_id, const gchar* title, const gchar** field_names, const gchar** field_values, funnel_dlg_cb_t dialog_cb, void* dialog_cb_data, funnel_dlg_cb_data_free_t dialog_cb_data_free)
{
QList<QPair<QString, QString>> field_list;
for (int i = 0; field_names[i]; i++) {
QPair<QString, QString> field = QPair<QString, QString>(QString(field_names[i]), QString(""));
if (field_values != NULL && field_values[i])
{
field.second = QString(field_values[i]);
}
field_list << field;
}
FunnelStringDialog::stringDialogNew(qobject_cast<QWidget *>(ops_id->funnel_statistics->parent()), title, field_list, dialog_cb, dialog_cb_data, dialog_cb_data_free);
}
void funnel_statistics_retap_packets(funnel_ops_id_t *ops_id) {
if (!ops_id || !ops_id->funnel_statistics) return;
ops_id->funnel_statistics->retapPackets();
}
void funnel_statistics_copy_to_clipboard(GString *text) {
mainApp->clipboard()->setText(text->str);
}
const gchar *funnel_statistics_get_filter(funnel_ops_id_t *ops_id) {
if (!ops_id || !ops_id->funnel_statistics) return nullptr;
return ops_id->funnel_statistics->displayFilter();
}
void funnel_statistics_set_filter(funnel_ops_id_t *ops_id, const char* filter_string) {
if (!ops_id || !ops_id->funnel_statistics) return;
ops_id->funnel_statistics->emitSetDisplayFilter(filter_string);
}
gchar* funnel_statistics_get_color_filter_slot(guint8 filter_num) {
return color_filters_get_tmp(filter_num);
}
void funnel_statistics_set_color_filter_slot(guint8 filter_num, const gchar* filter_string) {
gchar *err_msg = nullptr;
if (!color_filters_set_tmp(filter_num, filter_string, FALSE, &err_msg)) {
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err_msg);
g_free(err_msg);
}
}
gboolean funnel_statistics_open_file(funnel_ops_id_t *ops_id, const char* fname, const char* filter, char**) {
// XXX We need to return a proper error value. We should probably move
// MainWindow::openCaptureFile to CaptureFile and add error handling
// there.
if (!ops_id || !ops_id->funnel_statistics) return FALSE;
QString cf_name(fname);
QString cf_filter(filter);
ops_id->funnel_statistics->emitOpenCaptureFile(cf_name, cf_filter);
return TRUE;
}
void funnel_statistics_reload_packets(funnel_ops_id_t *ops_id) {
if (!ops_id || !ops_id->funnel_statistics) return;
ops_id->funnel_statistics->reloadPackets();
}
void funnel_statistics_redissect_packets(funnel_ops_id_t *ops_id) {
if (!ops_id || !ops_id->funnel_statistics) return;
ops_id->funnel_statistics->redissectPackets();
}
void funnel_statistics_reload_lua_plugins(funnel_ops_id_t *ops_id) {
if (!ops_id || !ops_id->funnel_statistics) return;
ops_id->funnel_statistics->reloadLuaPlugins();
}
void funnel_statistics_apply_filter(funnel_ops_id_t *ops_id) {
if (!ops_id || !ops_id->funnel_statistics) return;
ops_id->funnel_statistics->emitApplyDisplayFilter();
}
gboolean browser_open_url(const gchar *url) {
return QDesktopServices::openUrl(QUrl(url)) ? TRUE : FALSE;
}
void browser_open_data_file(const gchar *filename) {
QDesktopServices::openUrl(QUrl::fromLocalFile(filename));
}
struct progdlg *progress_window_new(funnel_ops_id_t *ops_id, const gchar* task_title, const gchar* item_title, gboolean terminate_is_stop, gboolean *stop_flag) {
if (!ops_id || !ops_id->funnel_statistics) return nullptr;
return ops_id->funnel_statistics->progressDialogNew(task_title, item_title, terminate_is_stop, stop_flag);
}
void progress_window_update(struct progdlg *progress_dialog, float percentage, const gchar* status) {
update_progress_dlg(progress_dialog, percentage, status);
}
void progress_window_destroy(progdlg *progress_dialog) {
destroy_progress_dlg(progress_dialog);
}
extern "C" {
void register_tap_listener_qt_funnel(void);
static void register_menu_cb(const char *name,
register_stat_group_t group,
funnel_menu_callback callback,
gpointer callback_data,
gboolean retap)
{
FunnelAction *funnel_action = new FunnelAction(name, callback, callback_data, retap, mainApp);
if (menus_registered) {
mainApp->appendDynamicMenuGroupItem(group, funnel_action);
} else {
mainApp->addDynamicMenuGroupItem(group, funnel_action);
}
if (!funnel_actions_.contains(group)) {
funnel_actions_[group] = QList<FunnelAction *>();
}
funnel_actions_[group] << funnel_action;
}
/*
* Callback used to register packet menus in the GUI.
*
* Creates a new FunnelAction with the Lua
* callback and stores it in the Wireshark GUI with
* appendPacketMenu() so it can be retrieved when
* the packet's context menu is open.
*
* @param name packet menu item's name
* @param required_fields fields required to be present for the packet menu to be displayed
* @param callback function called when the menu item is invoked. The function must take one argument and return nothing.
* @param callback_data Lua state for the callback function
* @param retap whether or not to rescan all packets
*/
static void register_packet_menu_cb(const char *name,
const char *required_fields,
funnel_packet_menu_callback callback,
gpointer callback_data,
gboolean retap)
{
FunnelAction *funnel_action = new FunnelAction(name, callback, callback_data, retap, required_fields, mainApp);
MainWindow * mainwindow = qobject_cast<MainWindow *>(mainApp->mainWindow());
if (mainwindow) {
mainwindow->appendPacketMenu(funnel_action);
}
}
static void deregister_menu_cb(funnel_menu_callback callback)
{
foreach (int group, funnel_actions_.keys()) {
QList<FunnelAction *>::iterator it = funnel_actions_[group].begin();
while (it != funnel_actions_[group].end()) {
FunnelAction *funnel_action = *it;
if (funnel_action->callback() == callback) {
// Must set back to title to find the correct sub-menu in Tools
funnel_action->setText(funnel_action->title());
mainApp->removeDynamicMenuGroupItem(group, funnel_action);
it = funnel_actions_[group].erase(it);
} else {
++it;
}
}
}
}
void
register_tap_listener_qt_funnel(void)
{
funnel_register_all_menus(register_menu_cb);
funnel_statistics_load_console_menus();
menus_registered = TRUE;
}
void
funnel_statistics_reload_menus(void)
{
funnel_reload_menus(deregister_menu_cb, register_menu_cb);
funnel_statistics_load_packet_menus();
}
/**
* Returns whether the packet menus have been modified since they were last registered
*
* @return TRUE if the packet menus were modified since the last registration
*/
gboolean
funnel_statistics_packet_menus_modified(void)
{
return funnel_packet_menus_modified();
}
/*
* Loads all registered_packet_menus into the
* Wireshark GUI.
*/
void
funnel_statistics_load_packet_menus(void)
{
funnel_register_all_packet_menus(register_packet_menu_cb);
}
static void register_console_menu_cb(const char *name,
funnel_console_eval_cb_t eval_cb,
funnel_console_open_cb_t open_cb,
funnel_console_close_cb_t close_cb,
void *callback_data)
{
FunnelConsoleAction *funnel_action = new FunnelConsoleAction(name, eval_cb,
open_cb,
close_cb,
callback_data,
mainApp);
if (menus_registered) {
mainApp->appendDynamicMenuGroupItem(REGISTER_TOOLS_GROUP_UNSORTED, funnel_action);
} else {
mainApp->addDynamicMenuGroupItem(REGISTER_TOOLS_GROUP_UNSORTED, funnel_action);
}
if (!funnel_actions_.contains(REGISTER_TOOLS_GROUP_UNSORTED)) {
funnel_actions_[REGISTER_TOOLS_GROUP_UNSORTED] = QList<FunnelAction *>();
}
funnel_actions_[REGISTER_TOOLS_GROUP_UNSORTED] << funnel_action;
}
/*
* Loads all registered console menus into the
* Wireshark GUI.
*/
void
funnel_statistics_load_console_menus(void)
{
funnel_register_all_console_menus(register_console_menu_cb);
}
} // extern "C" |
C/C++ | wireshark/ui/qt/funnel_statistics.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef FUNNELSTATISTICS_H
#define FUNNELSTATISTICS_H
#include <QObject>
#include <QAction>
#include <QSet>
#include <epan/funnel.h>
#include "capture_file.h"
#include <ui/qt/filter_action.h>
struct _funnel_ops_t;
struct progdlg;
/**
* Signature of function that can be called from a custom packet menu entry
*/
typedef void (* funnel_packet_menu_callback)(gpointer, GPtrArray*);
class FunnelStatistics : public QObject
{
Q_OBJECT
public:
explicit FunnelStatistics(QObject *parent, CaptureFile &cf);
~FunnelStatistics();
void retapPackets();
struct progdlg *progressDialogNew(const gchar *task_title, const gchar *item_title, gboolean terminate_is_stop, gboolean *stop_flag);
const char *displayFilter();
void emitSetDisplayFilter(const QString filter);
void reloadPackets();
void redissectPackets();
void reloadLuaPlugins();
void emitApplyDisplayFilter();
void emitOpenCaptureFile(QString cf_path, QString filter);
static const QString &actionName() { return action_name_; }
signals:
void openCaptureFile(QString cf_path, QString filter);
void setDisplayFilter(QString filter, FilterAction::Action action, FilterAction::ActionType filterType);
public slots:
void funnelActionTriggered();
void displayFilterTextChanged(const QString &filter);
private:
static const QString action_name_;
struct _funnel_ops_t *funnel_ops_;
struct _funnel_ops_id_t *funnel_ops_id_;
CaptureFile &capture_file_;
QByteArray display_filter_;
QString prepared_filter_;
};
class FunnelAction : public QAction
{
Q_OBJECT
public:
FunnelAction(QObject *parent = nullptr);
FunnelAction(QString title, funnel_menu_callback callback, gpointer callback_data, gboolean retap, QObject *parent);
FunnelAction(QString title, funnel_packet_menu_callback callback, gpointer callback_data, gboolean retap, const char *packet_required_fields, QObject *parent);
~FunnelAction();
funnel_menu_callback callback() const;
QString title() const;
virtual void triggerCallback();
void setPacketCallback(funnel_packet_menu_callback packet_callback);
void setPacketData(GPtrArray* finfos);
void addToMenu(QMenu * ctx_menu, QHash<QString, QMenu *> menuTextToMenus);
void setPacketRequiredFields(const char *required_fields_str);
const QSet<QString> getPacketRequiredFields();
bool retap();
QString getPacketSubmenus();
public slots:
void triggerPacketCallback();
private:
QString title_;
QString packetSubmenu_;
funnel_menu_callback callback_;
gpointer callback_data_;
gboolean retap_;
funnel_packet_menu_callback packetCallback_;
GPtrArray* packetData_;
QSet<QString> packetRequiredFields_;
};
class FunnelConsoleAction : public FunnelAction
{
Q_OBJECT
public:
FunnelConsoleAction(QString name, funnel_console_eval_cb_t eval_cb,
funnel_console_open_cb_t open_cb,
funnel_console_close_cb_t close_cb,
void *callback_data, QObject *parent);
~FunnelConsoleAction();
virtual void triggerCallback();
private:
QString title_;
funnel_console_eval_cb_t eval_cb_;
funnel_console_open_cb_t open_cb_;
funnel_console_close_cb_t close_cb_;
void *callback_data_;
};
extern "C" {
void funnel_statistics_reload_menus(void);
void funnel_statistics_load_packet_menus(void);
void funnel_statistics_load_console_menus(void);
gboolean funnel_statistics_packet_menus_modified(void);
} // extern "C"
#endif // FUNNELSTATISTICS_H |
C++ | wireshark/ui/qt/funnel_string_dialog.cpp | /* funnel_string_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "funnel_string_dialog.h"
#include <ui_funnel_string_dialog.h>
#include <QLabel>
#include <QLineEdit>
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
// Helper object used for sending close signal to open dialogs from a C function
static FunnelStringDialogHelper dialog_helper_;
const int min_edit_width_ = 20; // em widths
FunnelStringDialog::FunnelStringDialog(QWidget *parent, const QString title, const QList<QPair<QString, QString>> field_list, funnel_dlg_cb_t dialog_cb, void* dialog_cb_data, funnel_dlg_cb_data_free_t dialog_data_free_cb) :
QDialog(parent),
ui(new Ui::FunnelStringDialog),
dialog_cb_(dialog_cb),
dialog_cb_data_(dialog_cb_data),
dialog_cb_data_free_(dialog_data_free_cb)
{
ui->setupUi(this);
setWindowTitle(mainApp->windowTitleString(title));
int one_em = fontMetrics().height();
int row = 0;
QPair<QString, QString> field;
foreach(field, field_list) {
QLabel* field_label = new QLabel(field.first, this);
ui->stringGridLayout->addWidget(field_label, row, 0);
QLineEdit* field_edit = new QLineEdit(this);
field_edit->setText(field.second);
field_edit->setMinimumWidth(one_em * min_edit_width_);
field_edits_ << field_edit;
ui->stringGridLayout->addWidget(field_edit, row, 1);
row++;
}
}
FunnelStringDialog::~FunnelStringDialog()
{
if (dialog_cb_data_free_) {
dialog_cb_data_free_(dialog_cb_data_);
}
delete ui;
}
void FunnelStringDialog::accept()
{
QDialog::accept();
disconnect();
deleteLater();
}
void FunnelStringDialog::reject()
{
QDialog::reject();
disconnect();
deleteLater();
}
void FunnelStringDialog::on_buttonBox_accepted()
{
if (!dialog_cb_) return;
GPtrArray* returns = g_ptr_array_new();
foreach (QLineEdit *field_edit, field_edits_) {
g_ptr_array_add(returns, qstring_strdup(field_edit->text()));
}
g_ptr_array_add(returns, NULL);
gchar **user_input = (gchar **)g_ptr_array_free(returns, FALSE);
dialog_cb_(user_input, dialog_cb_data_);
}
void FunnelStringDialog::stringDialogNew(QWidget *parent, const QString title, QList<QPair<QString, QString>> field_list, funnel_dlg_cb_t dialog_cb, void* dialog_cb_data, funnel_dlg_cb_data_free_t dialog_cb_data_free)
{
FunnelStringDialog* fsd = new FunnelStringDialog(parent, title, field_list, dialog_cb, dialog_cb_data, dialog_cb_data_free);
connect(&dialog_helper_, &FunnelStringDialogHelper::closeDialogs, fsd, &FunnelStringDialog::close);
fsd->show();
}
void FunnelStringDialogHelper::emitCloseDialogs()
{
emit closeDialogs();
}
void string_dialogs_close(void)
{
dialog_helper_.emitCloseDialogs();
} |
C/C++ | wireshark/ui/qt/funnel_string_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 FUNNEL_STRING_DIALOG_H
#define FUNNEL_STRING_DIALOG_H
#include <glib.h>
#include "epan/funnel.h"
#include <QDialog>
class QLineEdit;
namespace Ui {
class FunnelStringDialog;
class FunnelStringDialogHelper;
}
class FunnelStringDialog : public QDialog
{
Q_OBJECT
public:
explicit FunnelStringDialog(QWidget *parent, const QString title, const QList<QPair<QString, QString>> field_list, funnel_dlg_cb_t dialog_cb, void* dialog_cb_data, funnel_dlg_cb_data_free_t dialog_data_free_cb);
~FunnelStringDialog();
// Funnel ops
static void stringDialogNew(QWidget *parent, const QString title, const QList<QPair<QString, QString>> field_list, funnel_dlg_cb_t dialog_cb, void* dialog_cb_data, funnel_dlg_cb_data_free_t dialog_cb_data_free);
void accept();
void reject();
private slots:
void on_buttonBox_accepted();
private:
Ui::FunnelStringDialog *ui;
funnel_dlg_cb_t dialog_cb_;
void *dialog_cb_data_;
funnel_dlg_cb_data_free_t dialog_cb_data_free_;
QList<QLineEdit *> field_edits_;
};
class FunnelStringDialogHelper : public QObject
{
Q_OBJECT
public slots:
void emitCloseDialogs();
signals:
void closeDialogs();
};
extern "C" {
void string_dialogs_close(void);
}
#endif // FUNNEL_STRING_DIALOG_H |
User Interface | wireshark/ui/qt/funnel_string_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FunnelStringDialog</class>
<widget class="QDialog" name="FunnelStringDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>176</width>
<height>66</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QGridLayout" name="stringGridLayout"/>
</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>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>FunnelStringDialog</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>FunnelStringDialog</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/funnel_text_dialog.cpp | /* funnel_text_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "funnel_text_dialog.h"
#include <ui_funnel_text_dialog.h>
#include <QPushButton>
#include <QRegularExpression>
#include <QTextCharFormat>
#include <QTextCursor>
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
// To do:
// - Add "Find next" to highlighting.
// - Add rich text support?
// - Zoom text?
static QHash<QObject *, funnel_bt_t*> text_button_to_funnel_button_;
FunnelTextDialog::FunnelTextDialog(QWidget *parent, const QString &title) :
GeometryStateDialog(parent),
ui(new Ui::FunnelTextDialog),
close_cb_(NULL),
close_cb_data_(NULL)
{
ui->setupUi(this);
if (!title.isEmpty()) {
loadGeometry(0, 0, QString("Funnel %1").arg(title));
}
setWindowTitle(mainApp->windowTitleString(title));
funnel_text_window_.funnel_text_dialog = this;
ui->textEdit->setFont(mainApp->monospaceFont());
ui->textEdit->setReadOnly(true);
ui->textEdit->setAcceptRichText(false);
}
FunnelTextDialog::~FunnelTextDialog()
{
delete ui;
}
void FunnelTextDialog::reject()
{
QDialog::reject();
if (close_cb_) {
close_cb_(close_cb_data_);
}
QHash<QObject *, funnel_bt_t*>::iterator i;
for (i = text_button_to_funnel_button_.begin(); i != text_button_to_funnel_button_.end(); ++i) {
funnel_bt_t *funnel_button = i.value();
if (funnel_button->free_data_fcn) {
funnel_button->free_data_fcn(funnel_button->data);
}
if (funnel_button->free_fcn) {
funnel_button->free_fcn(funnel_button);
}
}
text_button_to_funnel_button_.clear();
disconnect();
deleteLater();
}
struct _funnel_text_window_t *FunnelTextDialog::textWindowNew(QWidget *parent, const QString title)
{
FunnelTextDialog *ftd = new FunnelTextDialog(parent, title);
ftd->show();
return &ftd->funnel_text_window_;
}
void FunnelTextDialog::setText(const QString text)
{
ui->textEdit->setText(text);
}
void FunnelTextDialog::appendText(const QString text)
{
ui->textEdit->moveCursor(QTextCursor::End);
ui->textEdit->insertPlainText(text);
}
void FunnelTextDialog::prependText(const QString text)
{
ui->textEdit->moveCursor(QTextCursor::Start);
ui->textEdit->insertPlainText(text);
}
void FunnelTextDialog::clearText()
{
ui->textEdit->clear();
}
const char *FunnelTextDialog::getText()
{
return qstring_strdup(ui->textEdit->toPlainText());
}
void FunnelTextDialog::setCloseCallback(text_win_close_cb_t close_cb, void *close_cb_data)
{
close_cb_ = close_cb;
close_cb_data_ = close_cb_data;
}
void FunnelTextDialog::setTextEditable(gboolean editable)
{
ui->textEdit->setReadOnly(!editable);
}
void FunnelTextDialog::addButton(funnel_bt_t *funnel_button, QString label)
{
// Use "&&" to get a real ampersand in the button.
label.replace('&', "&&");
QPushButton *button = new QPushButton(label);
ui->buttonBox->addButton(button, QDialogButtonBox::ActionRole);
text_button_to_funnel_button_[button] = funnel_button;
connect(button, &QPushButton::clicked, this, &FunnelTextDialog::buttonClicked);
}
void FunnelTextDialog::buttonClicked()
{
if (text_button_to_funnel_button_.contains(sender())) {
funnel_bt_t *funnel_button = text_button_to_funnel_button_[sender()];
if (funnel_button) {
funnel_button->func(&funnel_text_window_, funnel_button->data);
}
}
}
void FunnelTextDialog::on_findLineEdit_textChanged(const QString &pattern)
{
QRegularExpression re(pattern, QRegularExpression::CaseInsensitiveOption |
QRegularExpression::UseUnicodePropertiesOption);
QTextCharFormat plain_fmt, highlight_fmt;
highlight_fmt.setBackground(Qt::yellow);
QTextCursor csr(ui->textEdit->document());
int position = csr.position();
setUpdatesEnabled(false);
// Reset highlighting
csr.movePosition(QTextCursor::Start);
csr.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
csr.setCharFormat(plain_fmt);
// Apply new highlighting
if (!pattern.isEmpty() && re.isValid()) {
QRegularExpressionMatchIterator iter = re.globalMatch(ui->textEdit->toPlainText());
while (iter.hasNext()) {
QRegularExpressionMatch match = iter.next();
csr.setPosition(static_cast<int>(match.capturedStart()), QTextCursor::MoveAnchor);
csr.setPosition(static_cast<int>(match.capturedEnd()), QTextCursor::KeepAnchor);
csr.setCharFormat(highlight_fmt);
}
}
// Restore cursor and anchor
csr.setPosition(position, QTextCursor::MoveAnchor);
setUpdatesEnabled(true);
}
void text_window_set_text(funnel_text_window_t *ftw, const char* text)
{
if (ftw) {
ftw->funnel_text_dialog->setText(text);
}
}
void text_window_append(funnel_text_window_t* ftw, const char* text)
{
if (ftw) {
ftw->funnel_text_dialog->appendText(text);
}
}
void text_window_prepend(funnel_text_window_t *ftw, const char* text)
{
if (ftw) {
ftw->funnel_text_dialog->prependText(text);
}
}
void text_window_clear(funnel_text_window_t* ftw)
{
if (ftw) {
ftw->funnel_text_dialog->clearText();
}
}
const char *text_window_get_text(funnel_text_window_t *ftw)
{
if (ftw) {
return ftw->funnel_text_dialog->getText();
}
return NULL;
}
void text_window_set_close_cb(funnel_text_window_t *ftw, text_win_close_cb_t close_cb, void *close_cb_data)
{
if (ftw) {
ftw->funnel_text_dialog->setCloseCallback(close_cb, close_cb_data);
}
}
void text_window_set_editable(funnel_text_window_t *ftw, gboolean editable)
{
if (ftw) {
ftw->funnel_text_dialog->setTextEditable(editable);
}
}
void text_window_destroy(funnel_text_window_t *ftw)
{
if (ftw) {
ftw->funnel_text_dialog->close();
}
}
void text_window_add_button(funnel_text_window_t *ftw, funnel_bt_t *funnel_button, const char *label)
{
if (ftw) {
ftw->funnel_text_dialog->addButton(funnel_button, label);
}
} |
C/C++ | wireshark/ui/qt/funnel_text_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 FUNNEL_TEXT_DIALOG_H
#define FUNNEL_TEXT_DIALOG_H
#include <glib.h>
#include "epan/funnel.h"
#include "geometry_state_dialog.h"
#include <QDialog>
namespace Ui {
class FunnelTextDialog;
}
class FunnelTextDialog;
struct _funnel_text_window_t {
FunnelTextDialog* funnel_text_dialog;
};
class FunnelTextDialog : public GeometryStateDialog
{
Q_OBJECT
public:
explicit FunnelTextDialog(QWidget *parent, const QString &title = QString());
~FunnelTextDialog();
void reject();
// Funnel ops
static struct _funnel_text_window_t *textWindowNew(QWidget *parent, const QString title);
void setText(const QString text);
void appendText(const QString text);
void prependText(const QString text);
void clearText();
const char *getText();
void setCloseCallback(text_win_close_cb_t close_cb, void* close_cb_data);
void setTextEditable(gboolean editable);
void addButton(funnel_bt_t *button_cb, QString label);
private slots:
void buttonClicked();
void on_findLineEdit_textChanged(const QString &pattern);
private:
Ui::FunnelTextDialog *ui;
struct _funnel_text_window_t funnel_text_window_;
text_win_close_cb_t close_cb_;
void *close_cb_data_;
};
extern "C" {
void text_window_set_text(funnel_text_window_t* ftw, const char* text);
void text_window_append(funnel_text_window_t *ftw, const char* text);
void text_window_prepend(funnel_text_window_t* ftw, const char* text);
void text_window_clear(funnel_text_window_t *ftw);
const char *text_window_get_text(funnel_text_window_t* ftw);
void text_window_set_close_cb(funnel_text_window_t *ftw, text_win_close_cb_t close_cb, void* close_cb_data);
void text_window_set_editable(funnel_text_window_t* ftw, gboolean editable);
void text_window_destroy(funnel_text_window_t* ftw);
void text_window_add_button(funnel_text_window_t* ftw, funnel_bt_t* funnel_button, const char* label);
}
#endif // FUNNEL_TEXT_DIALOG_H |
User Interface | wireshark/ui/qt/funnel_text_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FunnelTextDialog</class>
<widget class="QDialog" name="FunnelTextDialog">
<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">
<item>
<widget class="QTextEdit" name="textEdit"/>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label">
<property name="toolTip">
<string><html><head/><body><p>Enter some text or a regular expression. It will be highlighted above.</p></body></html></string>
</property>
<property name="text">
<string>Highlight:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="findLineEdit">
<property name="toolTip">
<string><html><head/><body><p>Enter some text or a regular expression. It will be highlighted above.</p></body></html></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::Close</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>FunnelTextDialog</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>FunnelTextDialog</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/geometry_state_dialog.cpp | /* geometry_state_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "geometry_state_dialog.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include "ui/recent.h"
#include "ui/ws_ui_util.h"
GeometryStateDialog::~GeometryStateDialog()
{
saveGeometry();
}
void GeometryStateDialog::loadGeometry(int width, int height, const QString &dialog_name)
{
window_geometry_t geom;
dialog_name_ = dialog_name.isEmpty() ? objectName() : dialog_name;
if (!dialog_name_.isEmpty() && window_geom_load(dialog_name_.toUtf8().constData(), &geom)) {
QRect recent_geom(geom.x, geom.y, geom.width, geom.height);
// Check if the dialog is visible on any screen
if (rect_on_screen(recent_geom)) {
move(recent_geom.topLeft());
resize(recent_geom.size());
} else {
// Not visible, move within a reasonable area and try size only
recent_geom.moveTopLeft(QPoint(50, 50));
if (rect_on_screen(recent_geom)) {
resize(recent_geom.size());
} else if (width > 0 && height > 0) {
// We're not visible on any screens, use defaults
resize(width, height);
}
}
if (geom.maximized) {
showFullScreen();
}
} else if (width > 0 && height > 0) {
// No saved geometry found, use defaults
resize(width, height);
}
}
void GeometryStateDialog::saveGeometry()
{
if (dialog_name_.isEmpty())
return;
window_geometry_t geom;
geom.key = NULL;
geom.set_pos = TRUE;
geom.x = pos().x();
geom.y = pos().y();
geom.set_size = TRUE;
geom.width = size().width();
geom.height = size().height();
geom.set_maximized = TRUE;
geom.maximized = isFullScreen();
window_geom_save(dialog_name_.toUtf8().constData(), &geom);
} |
C/C++ | wireshark/ui/qt/geometry_state_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 GEOMETRY_STATE_DIALOG_H
#define GEOMETRY_STATE_DIALOG_H
#include <QDialog>
class GeometryStateDialog : public QDialog
{
public:
// As discussed in change 7072, QDialogs have different minimize and "on
// top" behaviors depending on their parents, flags, and platforms.
//
// W = Windows, L = Linux (and other non-macOS UN*Xes), X = macOS
//
// QDialog(parent)
//
// W,L: Always on top, no minimize button.
// X: Independent, no minimize button.
//
// QDialog(parent, Qt::Window)
//
// W: Always on top, minimize button. Minimizes to a small title bar
// attached to the taskbar and not the taskbar itself. (The GTK+
// UI used to do this.)
// L: Always on top, minimize button.
// X: Independent, minimize button.
//
// QDialog(NULL)
//
// W, L, X: Independent, no minimize button.
//
// QDialog(NULL, Qt::Window)
//
// W, L, X: Independent, minimize button.
//
// Additionally, maximized, parent-less dialogs can close to a black screen
// on macOS: https://gitlab.com/wireshark/wireshark/-/issues/12544
//
// Pass in the parent on macOS and NULL elsewhere so that we have an
// independent window that un-maximizes correctly.
#ifdef Q_OS_MAC
explicit GeometryStateDialog(QWidget *parent, Qt::WindowFlags f = Qt::WindowFlags()) : QDialog(parent, f) {}
#else
explicit GeometryStateDialog(QWidget *, Qt::WindowFlags f = Qt::WindowFlags()) : QDialog(NULL, f) {}
#endif
~GeometryStateDialog();
protected:
void loadGeometry(int width = 0, int height = 0, const QString &dialog_name = QString());
private:
void saveGeometry();
QString dialog_name_;
};
#endif // GEOMETRY_STATE_DIALOG_H |
C++ | wireshark/ui/qt/glib_mainloop_on_qeventloop.cpp | /** @file
*
* Copyright 2022 Tomasz Mon <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <QTimer>
#include "glib_mainloop_on_qeventloop.h"
GLibPoller::GLibPoller(GMainContext *context) :
mutex_(), dispatched_(),
ctx_(context), priority_(0),
fds_(g_new(GPollFD, 1)), allocated_fds_(1), nfds_(0)
{
g_main_context_ref(ctx_);
}
GLibPoller::~GLibPoller()
{
g_main_context_unref(ctx_);
g_free(fds_);
}
void GLibPoller::run()
{
gint timeout;
mutex_.lock();
while (!isInterruptionRequested())
{
while (!g_main_context_acquire(ctx_))
{
/* In normal circumstances context is acquired right away */
}
g_main_context_prepare(ctx_, &priority_);
while ((nfds_ = g_main_context_query(ctx_, priority_, &timeout, fds_,
allocated_fds_)) > allocated_fds_)
{
g_free(fds_);
fds_ = g_new(GPollFD, nfds_);
allocated_fds_ = nfds_;
}
/* Blocking g_poll() call is the reason for separate polling thread */
g_poll(fds_, nfds_, timeout);
g_main_context_release(ctx_);
/* Polling has finished, dispatch events (if any) in main thread so we
* don't have to worry about concurrency issues in GLib callbacks.
*/
emit polled();
/* Wait for the main thread to finish dispatching before next poll */
dispatched_.wait(&mutex_);
}
mutex_.unlock();
}
GLibMainloopOnQEventLoop::GLibMainloopOnQEventLoop(QObject *parent) :
QObject(parent),
poller_(g_main_context_default())
{
connect(&poller_, &GLibPoller::polled,
this, &GLibMainloopOnQEventLoop::checkAndDispatch);
poller_.setObjectName("GLibPoller");
poller_.start();
}
GLibMainloopOnQEventLoop::~GLibMainloopOnQEventLoop()
{
poller_.requestInterruption();
/* Wakeup poller thread in case it is blocked on g_poll(). Wakeup does not
* cause any problem if poller thread is already waiting on dispatched wait
* condition.
*/
g_main_context_wakeup(poller_.ctx_);
/* Wakeup poller thread without actually dispatching */
poller_.mutex_.lock();
poller_.dispatched_.wakeOne();
poller_.mutex_.unlock();
/* Poller thread will quit, wait for it to avoid warning */
poller_.wait();
}
void GLibMainloopOnQEventLoop::checkAndDispatch()
{
poller_.mutex_.lock();
while (!g_main_context_acquire(poller_.ctx_))
{
/* In normal circumstances context is acquired right away */
}
if (g_main_depth() > 0)
{
/* This should not happen, but if it does warn about nested event loops
* so the issue can be fixed before the harm is done. To identify root
* cause, put breakpoint here and take backtrace when it hits. Look for
* calls to exec() and processEvents() functions. Refactor the code so
* it does not spin additional event loops.
*
* Ignoring this warning will lead to very strange and hard to debug
* problems in the future.
*/
qWarning("Nested GLib event loop detected");
}
if (g_main_context_check(poller_.ctx_, poller_.priority_,
poller_.fds_, poller_.nfds_))
{
g_main_context_dispatch(poller_.ctx_);
}
g_main_context_release(poller_.ctx_);
/* Start next iteration in GLibPoller thread */
poller_.dispatched_.wakeOne();
poller_.mutex_.unlock();
}
void GLibMainloopOnQEventLoop::setup(QObject *parent)
{
/* Schedule event loop action so we can check if Qt runs GLib mainloop */
QTimer::singleShot(0, [parent]() {
if (g_main_depth() == 0)
{
/* Not running inside GLib mainloop, actually setup */
new GLibMainloopOnQEventLoop(parent);
}
});
} |
C/C++ | wireshark/ui/qt/glib_mainloop_on_qeventloop.h | /** @file
*
* Copyright 2022 Tomasz Mon <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef GLIB_MAINLOOP_ON_QEVENTLOOP_H
#define GLIB_MAINLOOP_ON_QEVENTLOOP_H
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <glib.h>
class GLibPoller : public QThread
{
Q_OBJECT
protected:
explicit GLibPoller(GMainContext *context);
~GLibPoller();
void run() override;
QMutex mutex_;
QWaitCondition dispatched_;
GMainContext *ctx_;
gint priority_;
GPollFD *fds_;
gint allocated_fds_, nfds_;
signals:
void polled(void);
friend class GLibMainloopOnQEventLoop;
};
class GLibMainloopOnQEventLoop : public QObject
{
Q_OBJECT
protected:
explicit GLibMainloopOnQEventLoop(QObject *parent);
~GLibMainloopOnQEventLoop();
protected slots:
void checkAndDispatch();
public:
static void setup(QObject *parent);
protected:
GLibPoller poller_;
};
#endif /* GLIB_MAINLOOP_ON_QEVENTLOOP_H */ |
Text | wireshark/ui/qt/gpl-template.txt | /* <filename>.c
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/ |
C++ | wireshark/ui/qt/gsm_map_summary_dialog.cpp | /* gsm_map_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 "gsm_map_summary_dialog.h"
#include <ui_gsm_map_summary_dialog.h>
#include "config.h"
#include <glib.h>
#include "ui/summary.h"
#include <epan/packet.h>
#include <epan/tap.h>
#include <epan/asn1.h>
#include <epan/dissectors/packet-gsm_map.h>
#include "wsutil/utf8_entities.h"
#include "ui/capture_globals.h"
#include "ui/simple_dialog.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
#include <QTextStream>
/** Gsm map statistic data */
typedef struct _gsm_map_stat_t {
int opr_code[GSM_MAP_MAX_NUM_OPR_CODES];
int size[GSM_MAP_MAX_NUM_OPR_CODES];
int opr_code_rr[GSM_MAP_MAX_NUM_OPR_CODES];
int size_rr[GSM_MAP_MAX_NUM_OPR_CODES];
} gsm_map_stat_t;
gsm_map_stat_t gsm_map_stat;
GsmMapSummaryDialog::GsmMapSummaryDialog(QWidget &parent, CaptureFile &capture_file) :
WiresharkDialog(parent, capture_file),
ui(new Ui::GsmMapSummaryDialog)
{
ui->setupUi(this);
setWindowSubtitle(tr("GSM MAP Summary"));
updateWidgets();
}
GsmMapSummaryDialog::~GsmMapSummaryDialog()
{
delete ui;
}
// Copied from capture_file_properties_dialog.cpp
QString GsmMapSummaryDialog::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;
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_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;
QString invoke_rate_str, result_rate_str, total_rate_str;
QString invoke_avg_size_str, result_avg_size_str, total_avg_size_str;
// Message averages
invoke_rate_str = result_rate_str = total_rate_str = n_a;
invoke_avg_size_str = result_avg_size_str = total_avg_size_str = n_a;
double seconds = summary.stop_time - summary.start_time;
int invoke_count = 0, invoke_bytes = 0;
int result_count = 0, result_bytes = 0;
for (int i = 0; i < GSM_MAP_MAX_NUM_OPR_CODES; i++) {
invoke_count += gsm_map_stat.opr_code[i];
invoke_bytes += gsm_map_stat.size[i];
}
for (int i = 0; i < GSM_MAP_MAX_NUM_OPR_CODES; i++) {
result_count += gsm_map_stat.opr_code_rr[i];
result_bytes += gsm_map_stat.size_rr[i];
}
int total_count = invoke_count + result_count;
int total_bytes = invoke_bytes + result_bytes;
/*
* We must have no un-time-stamped packets (i.e., the number of
* time-stamped packets must be the same as the number of packets),
* and at least two time-stamped packets, in order for the elapsed
* time to be valid.
*/
if (summary.packet_count_ts > 1 && seconds > 0.0) {
/* Total number of invokes per second */
invoke_rate_str = QString("%1").arg(invoke_count / seconds, 1, 'f', 1);
result_rate_str = QString("%1").arg(result_count / seconds, 1, 'f', 1);
total_rate_str = QString("%1").arg((total_count) / seconds, 1, 'f', 1);
}
/* Average message sizes */
if (invoke_count > 0) {
invoke_avg_size_str = QString("%1").arg((double) invoke_bytes / invoke_count, 1, 'f', 1);
}
if (result_count > 0) {
result_avg_size_str = QString("%1").arg((double) result_bytes / result_count, 1, 'f', 1);
}
if (total_count > 0) {
total_avg_size_str = QString("%1").arg((double) total_bytes / total_count, 1, 'f', 1);
}
// Invoke Section
out << section_tmpl.arg(tr("Invokes"));
out << table_begin;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Total number of Invokes"))
<< table_data_tmpl.arg(invoke_count)
<< table_row_end;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Average number of Invokes per second"))
<< table_data_tmpl.arg(invoke_rate_str)
<< table_row_end;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Total number of bytes for Invokes"))
<< table_data_tmpl.arg(invoke_bytes)
<< table_row_end;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Average number of bytes per Invoke"))
<< table_data_tmpl.arg(invoke_avg_size_str)
<< table_row_end;
out << table_end;
// Return Result Section
out << section_tmpl.arg(tr("Return Results"));
out << table_begin;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Total number of Return Results"))
<< table_data_tmpl.arg(result_count)
<< table_row_end;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Average number of Return Results per second"))
<< table_data_tmpl.arg(result_rate_str)
<< table_row_end;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Total number of bytes for Return Results"))
<< table_data_tmpl.arg(result_bytes)
<< table_row_end;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Average number of bytes per Return Result"))
<< table_data_tmpl.arg(result_avg_size_str)
<< table_row_end;
out << table_end;
// Total Section
out << section_tmpl.arg(tr("Totals"));
out << table_begin;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Total number of GSM MAP messages"))
<< table_data_tmpl.arg(total_count)
<< table_row_end;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Average number of GSM MAP messages per second"))
<< table_data_tmpl.arg(total_rate_str)
<< table_row_end;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Total number of bytes for GSM MAP messages"))
<< table_data_tmpl.arg(total_bytes)
<< table_row_end;
out << table_row_begin
<< table_vheader_tmpl.arg(tr("Average number of bytes per GSM MAP message"))
<< table_data_tmpl.arg(total_avg_size_str)
<< table_row_end;
out << table_end;
return summary_str;
}
void GsmMapSummaryDialog::updateWidgets()
{
// QPushButton *refresh_bt = ui->buttonBox->button(QDialogButtonBox::Reset);
// QPushButton *save_bt = ui->buttonBox->button(QDialogButtonBox::Save);
// if (file_closed_) {
// if (refresh_bt) {
// refresh_bt->setEnabled(false);
// }
// ui->commentsTextEdit->setReadOnly(true);
// if (save_bt) {
// save_bt->setEnabled(false);
// }
// return;
// }
ui->summaryTextEdit->setHtml(summaryToHtml());
WiresharkDialog::updateWidgets();
}
extern "C" {
void register_tap_listener_qt_gsm_map_summary(void);
static void
gsm_map_summary_reset(void *tapdata)
{
gsm_map_stat_t *gm_stat = (gsm_map_stat_t *)tapdata;
memset(gm_stat, 0, sizeof(gsm_map_stat_t));
}
static tap_packet_status
gsm_map_summary_packet(void *tapdata, packet_info *, epan_dissect_t *, const void *gmtr_ptr, tap_flags_t flags _U_)
{
gsm_map_stat_t *gm_stat = (gsm_map_stat_t *)tapdata;
const gsm_map_tap_rec_t *gm_tap_rec = (const gsm_map_tap_rec_t *)gmtr_ptr;
if (gm_tap_rec->invoke)
{
gm_stat->opr_code[gm_tap_rec->opcode]++;
gm_stat->size[gm_tap_rec->opcode] += gm_tap_rec->size;
}
else
{
gm_stat->opr_code_rr[gm_tap_rec->opcode]++;
gm_stat->size_rr[gm_tap_rec->opcode] += gm_tap_rec->size;
}
return(TAP_PACKET_DONT_REDRAW); /* We have no draw callback */
}
void
register_tap_listener_qt_gsm_map_summary(void)
{
GString *err_p;
memset((void *) &gsm_map_stat, 0, sizeof(gsm_map_stat_t));
err_p =
register_tap_listener("gsm_map", &gsm_map_stat, NULL, 0,
gsm_map_summary_reset,
gsm_map_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/gsm_map_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 GSM_MAP_SUMMARY_DIALOG_H
#define GSM_MAP_SUMMARY_DIALOG_H
#include "wireshark_dialog.h"
namespace Ui {
class GsmMapSummaryDialog;
}
class GsmMapSummaryDialog : public WiresharkDialog
{
Q_OBJECT
public:
explicit GsmMapSummaryDialog(QWidget &parent, CaptureFile& capture_file);
~GsmMapSummaryDialog();
private:
Ui::GsmMapSummaryDialog *ui;
QString summaryToHtml();
private slots:
void updateWidgets();
};
#endif // GSM_MAP_SUMMARY_DIALOG_H |
User Interface | wireshark/ui/qt/gsm_map_summary_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>GsmMapSummaryDialog</class>
<widget class="QDialog" name="GsmMapSummaryDialog">
<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>GsmMapSummaryDialog</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>GsmMapSummaryDialog</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/iax2_analysis_dialog.cpp | /* iax2_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 "iax2_analysis_dialog.h"
#include <ui_iax2_analysis_dialog.h>
#include "file.h"
#include "frame_tvbuff.h"
#include <epan/epan_dissect.h>
#include <epan/rtp_pt.h>
#include <epan/dfilter/dfilter.h>
#include <epan/dissectors/packet-iax2.h>
#include "ui/help_url.h"
#ifdef IAX2_RTP_STREAM_CHECK
#include "ui/rtp_stream.h"
#endif
#include <wsutil/utf8_entities.h>
#include <wsutil/g711.h>
#include <wsutil/pint.h>
#include <QMessageBox>
#include <QPushButton>
#include <QTemporaryFile>
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/utils/qt_ui_utils.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_,
delta_col_,
jitter_col_,
bandwidth_col_,
status_col_,
length_col_
};
static const QRgb color_rtp_warn_ = 0xffdbbf;
enum { iax2_analysis_type_ = 1000 };
class Iax2AnalysisTreeWidgetItem : public QTreeWidgetItem
{
public:
Iax2AnalysisTreeWidgetItem(QTreeWidget *tree, tap_iax2_stat_t *statinfo, packet_info *pinfo) :
QTreeWidgetItem(tree, iax2_analysis_type_),
frame_num_(pinfo->num),
pkt_len_(pinfo->fd->pkt_len),
flags_(statinfo->flags),
bandwidth_(statinfo->bandwidth),
ok_(false)
{
if (flags_ & STAT_FLAG_FIRST) {
delta_ = 0.0;
jitter_ = 0.0;
} else {
delta_ = statinfo->delta;
jitter_ = statinfo->jitter;
}
QColor bg_color = QColor();
QString status;
if (statinfo->flags & STAT_FLAG_WRONG_SEQ) {
status = QObject::tr("Wrong sequence number");
bg_color = ColorUtils::expert_color_error;
} else if (statinfo->flags & STAT_FLAG_REG_PT_CHANGE) {
status = QObject::tr("Payload changed to PT=%1").arg(statinfo->pt);
bg_color = color_rtp_warn_;
} else if (statinfo->flags & STAT_FLAG_WRONG_TIMESTAMP) {
status = QObject::tr("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 = QObject::tr("Marker missing?");
bg_color = color_rtp_warn_;
} 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(delta_col_, QString::number(delta_, 'f', 2));
setText(jitter_col_, QString::number(jitter_, 'f', 2));
setText(bandwidth_col_, QString::number(bandwidth_, 'f', 2));
setText(status_col_, status);
setText(length_col_, QString::number(pkt_len_));
setTextAlignment(packet_col_, Qt::AlignRight);
setTextAlignment(delta_col_, Qt::AlignRight);
setTextAlignment(jitter_col_, Qt::AlignRight);
setTextAlignment(bandwidth_col_, Qt::AlignRight);
setTextAlignment(length_col_, Qt::AlignRight);
if (bg_color.isValid()) {
for (int col = 0; col < columnCount(); col++) {
setBackground(col, bg_color);
setForeground(col, ColorUtils::expert_color_foreground);
}
}
}
guint32 frameNum() { return frame_num_; }
bool frameStatus() { return ok_; }
QList<QVariant> rowData() {
QString status_str = ok_ ? "OK" : text(status_col_);
return QList<QVariant>()
<< frame_num_ << delta_ << jitter_ << bandwidth_
<< status_str << pkt_len_;
}
bool operator< (const QTreeWidgetItem &other) const
{
if (other.type() != iax2_analysis_type_) return QTreeWidgetItem::operator< (other);
const Iax2AnalysisTreeWidgetItem *other_row = static_cast<const Iax2AnalysisTreeWidgetItem *>(&other);
switch (treeWidget()->sortColumn()) {
case (packet_col_):
return frame_num_ < other_row->frame_num_;
break;
case (delta_col_):
return delta_ < other_row->delta_;
break;
case (jitter_col_):
return jitter_ < other_row->jitter_;
break;
case (bandwidth_col_):
return bandwidth_ < other_row->bandwidth_;
break;
case (length_col_):
return pkt_len_ < other_row->pkt_len_;
break;
default:
break;
}
// Fall back to string comparison
return QTreeWidgetItem::operator <(other);
}
private:
guint32 frame_num_;
guint32 pkt_len_;
guint32 flags_;
double delta_;
double jitter_;
double bandwidth_;
bool ok_;
};
enum {
fwd_jitter_graph_,
fwd_diff_graph_,
rev_jitter_graph_,
rev_diff_graph_,
num_graphs_
};
Iax2AnalysisDialog::Iax2AnalysisDialog(QWidget &parent, CaptureFile &cf) :
WiresharkDialog(parent, cf),
ui(new Ui::Iax2AnalysisDialog),
save_payload_error_(TAP_IAX2_NO_ERROR)
{
ui->setupUi(this);
loadGeometry(parent.width() * 4 / 5, parent.height() * 4 / 5);
setWindowSubtitle(tr("IAX2 Stream Analysis"));
ui->progressFrame->hide();
stream_ctx_menu_.addAction(ui->actionGoToPacket);
stream_ctx_menu_.addAction(ui->actionNextProblem);
stream_ctx_menu_.addSeparator();
stream_ctx_menu_.addAction(ui->actionSaveAudio);
stream_ctx_menu_.addAction(ui->actionSaveForwardAudio);
stream_ctx_menu_.addAction(ui->actionSaveReverseAudio);
stream_ctx_menu_.addSeparator();
stream_ctx_menu_.addAction(ui->actionSaveCsv);
stream_ctx_menu_.addAction(ui->actionSaveForwardCsv);
stream_ctx_menu_.addAction(ui->actionSaveReverseCsv);
stream_ctx_menu_.addSeparator();
stream_ctx_menu_.addAction(ui->actionSaveGraph);
set_action_shortcuts_visible_in_context_menu(stream_ctx_menu_.actions());
ui->forwardTreeWidget->installEventFilter(this);
ui->forwardTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->forwardTreeWidget, SIGNAL(customContextMenuRequested(QPoint)),
SLOT(showStreamMenu(QPoint)));
ui->reverseTreeWidget->installEventFilter(this);
ui->reverseTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->reverseTreeWidget, SIGNAL(customContextMenuRequested(QPoint)),
SLOT(showStreamMenu(QPoint)));
connect(ui->streamGraph, SIGNAL(mousePress(QMouseEvent*)),
this, SLOT(graphClicked(QMouseEvent*)));
graph_ctx_menu_.addAction(ui->actionSaveGraph);
QStringList header_labels;
for (int i = 0; i < ui->forwardTreeWidget->columnCount(); i++) {
header_labels << ui->forwardTreeWidget->headerItem()->text(i);
}
ui->reverseTreeWidget->setHeaderLabels(header_labels);
memset(&fwd_id_, 0, sizeof(fwd_id_));
memset(&rev_id_, 0, sizeof(rev_id_));
QList<QCheckBox *> graph_cbs = QList<QCheckBox *>()
<< ui->fJitterCheckBox << ui->fDiffCheckBox
<< ui->rJitterCheckBox << ui->rDiffCheckBox;
for (int i = 0; i < num_graphs_; i++) {
QCPGraph *graph = ui->streamGraph->addGraph();
graph->setPen(QPen(ColorUtils::graphColor(i)));
graph->setName(graph_cbs[i]->text());
graphs_ << graph;
graph_cbs[i]->setChecked(true);
graph_cbs[i]->setIcon(StockIcon::colorIcon(ColorUtils::graphColor(i), QPalette::Text));
}
ui->streamGraph->xAxis->setLabel("Arrival Time");
ui->streamGraph->yAxis->setLabel("Value (ms)");
// We keep our temp files open for the lifetime of the dialog. The GTK+
// UI opens and closes at various points.
QString tempname = QString("%1/wireshark_iax2_f").arg(QDir::tempPath());
fwd_tempfile_ = new QTemporaryFile(tempname, this);
fwd_tempfile_->open();
tempname = QString("%1/wireshark_iax2_r").arg(QDir::tempPath());
rev_tempfile_ = new QTemporaryFile(tempname, this);
rev_tempfile_->open();
if (fwd_tempfile_->error() != QFile::NoError || rev_tempfile_->error() != QFile::NoError) {
err_str_ = tr("Unable to save RTP data.");
ui->actionSaveAudio->setEnabled(false);
ui->actionSaveForwardAudio->setEnabled(false);
ui->actionSaveReverseAudio->setEnabled(false);
}
QPushButton *save_bt = ui->buttonBox->button(QDialogButtonBox::Save);
QMenu *save_menu = new QMenu(save_bt);
save_menu->addAction(ui->actionSaveAudio);
save_menu->addAction(ui->actionSaveForwardAudio);
save_menu->addAction(ui->actionSaveReverseAudio);
save_menu->addSeparator();
save_menu->addAction(ui->actionSaveCsv);
save_menu->addAction(ui->actionSaveForwardCsv);
save_menu->addAction(ui->actionSaveReverseCsv);
save_menu->addSeparator();
save_menu->addAction(ui->actionSaveGraph);
save_bt->setMenu(save_menu);
ui->buttonBox->button(QDialogButtonBox::Close)->setDefault(true);
resetStatistics();
updateStatistics(); // Initialize stats if an error occurs
#if 0
/* Only accept Voice or MiniPacket packets */
const gchar filter_text[] = "iax2.call && (ip || ipv6)";
#else
const gchar filter_text[] = "iax2 && (ip || ipv6)";
#endif
dfilter_t *sfcode;
df_error_t *df_err;
/* Try to compile the filter. */
if (!dfilter_compile(filter_text, &sfcode, &df_err)) {
err_str_ = QString(df_err->msg);
df_error_free(&df_err);
updateWidgets();
return;
}
if (!cap_file_.capFile() || !cap_file_.capFile()->current_frame) {
dfilter_free(sfcode);
err_str_ = tr("Please select an IAX2 packet.");
save_payload_error_ = TAP_IAX2_NO_PACKET_SELECTED;
updateWidgets();
return;
}
if (!cf_read_current_record(cap_file_.capFile())) close();
frame_data *fdata = cap_file_.capFile()->current_frame;
epan_dissect_t edt;
epan_dissect_init(&edt, cap_file_.capFile()->epan, TRUE, FALSE);
epan_dissect_prime_with_dfilter(&edt, sfcode);
epan_dissect_run(&edt, cap_file_.capFile()->cd_t, &cap_file_.capFile()->rec,
frame_tvbuff_new_buffer(&cap_file_.capFile()->provider, fdata, &cap_file_.capFile()->buf),
fdata, NULL);
// This shouldn't happen (the menu item should be disabled) but check anyway
if (!dfilter_apply_edt(sfcode, &edt)) {
epan_dissect_cleanup(&edt);
dfilter_free(sfcode);
err_str_ = tr("Please select an IAX2 packet.");
save_payload_error_ = TAP_IAX2_NO_PACKET_SELECTED;
updateWidgets();
return;
}
dfilter_free(sfcode);
/* ok, it is a IAX2 frame, so let's get the ip and port values */
rtpstream_id_copy_pinfo(&(edt.pi),&(fwd_id_),FALSE);
/* assume the inverse ip/port combination for the reverse direction */
rtpstream_id_copy_pinfo(&(edt.pi),&(rev_id_),TRUE);
epan_dissect_cleanup(&edt);
#ifdef IAX2_RTP_STREAM_CHECK
rtpstream_tapinfo_t tapinfo;
/* Register the tap listener */
rtpstream_info_init(&tapinfo);
tapinfo.tap_data = this;
tapinfo.mode = TAP_ANALYSE;
// register_tap_listener_rtpstream(&tapinfo, NULL);
/* Scan for RTP streams (redissect all packets) */
rtpstream_scan(&tapinfo, cap_file_.capFile(), Q_NULLPTR);
int num_streams = 0;
// TODO: Not used
//GList *filtered_list = NULL;
for (GList *strinfo_list = g_list_first(tapinfo.strinfo_list); strinfo_list; strinfo_list = gxx_list_next(strinfo_list)) {
rtpstream_info_t * strinfo = gxx_list_data(rtpstream_info_t*, strinfo_list);
if (rtpstream_id_equal(&(strinfo->id), &(fwd_id_),RTPSTREAM_ID_EQUAL_NONE))
{
++num_streams;
// TODO: Not used
//filtered_list = g_list_prepend(filtered_list, strinfo);
}
if (rtpstream_id_equal(&(strinfo->id), &(rev_id_),RTPSTREAM_ID_EQUAL_NONE))
{
++num_streams;
// TODO: Not used
//filtered_list = g_list_append(filtered_list, strinfo);
}
rtpstream_info_free_data(strinfo);
g_free(list->data);
}
g_list_free(tapinfo->strinfo_list);
if (num_streams > 1) {
// Open the RTP streams dialog.
}
#endif
connect(ui->tabWidget, SIGNAL(currentChanged(int)),
this, SLOT(updateWidgets()));
connect(ui->forwardTreeWidget, SIGNAL(itemSelectionChanged()),
this, SLOT(updateWidgets()));
connect(ui->reverseTreeWidget, SIGNAL(itemSelectionChanged()),
this, SLOT(updateWidgets()));
updateWidgets();
registerTapListener("IAX2", this, Q_NULLPTR, 0, tapReset, tapPacket, tapDraw);
cap_file_.retapPackets();
removeTapListeners();
updateStatistics();
}
Iax2AnalysisDialog::~Iax2AnalysisDialog()
{
delete ui;
// remove_tap_listener_rtpstream(&tapinfo);
delete fwd_tempfile_;
delete rev_tempfile_;
}
void Iax2AnalysisDialog::updateWidgets()
{
bool enable_tab = false;
QString hint = err_str_;
if (hint.isEmpty() || save_payload_error_ != TAP_IAX2_NO_ERROR) {
/* We cannot save the payload but can still display the widget
or save CSV data */
enable_tab = true;
}
bool enable_nav = false;
if (!file_closed_
&& ((ui->tabWidget->currentWidget() == ui->forwardTreeWidget
&& ui->forwardTreeWidget->selectedItems().length() > 0)
|| (ui->tabWidget->currentWidget() == ui->reverseTreeWidget
&& ui->reverseTreeWidget->selectedItems().length() > 0))) {
enable_nav = true;
}
ui->actionGoToPacket->setEnabled(enable_nav);
ui->actionNextProblem->setEnabled(enable_nav);
if (enable_nav) {
hint.append(tr(" G: Go to packet, N: Next problem packet"));
}
bool enable_save_fwd_audio = fwd_tempfile_->isOpen() && (save_payload_error_ == TAP_IAX2_NO_ERROR);
bool enable_save_rev_audio = rev_tempfile_->isOpen() && (save_payload_error_ == TAP_IAX2_NO_ERROR);
ui->actionSaveAudio->setEnabled(enable_save_fwd_audio && enable_save_rev_audio);
ui->actionSaveForwardAudio->setEnabled(enable_save_fwd_audio);
ui->actionSaveReverseAudio->setEnabled(enable_save_rev_audio);
bool enable_save_fwd_csv = ui->forwardTreeWidget->topLevelItemCount() > 0;
bool enable_save_rev_csv = ui->reverseTreeWidget->topLevelItemCount() > 0;
ui->actionSaveCsv->setEnabled(enable_save_fwd_csv && enable_save_rev_csv);
ui->actionSaveForwardCsv->setEnabled(enable_save_fwd_csv);
ui->actionSaveReverseCsv->setEnabled(enable_save_rev_csv);
ui->tabWidget->setEnabled(enable_tab);
hint.prepend("<small><i>");
hint.append("</i></small>");
ui->hintLabel->setText(hint);
WiresharkDialog::updateWidgets();
}
void Iax2AnalysisDialog::on_actionGoToPacket_triggered()
{
if (file_closed_) return;
QTreeWidget *cur_tree = qobject_cast<QTreeWidget *>(ui->tabWidget->currentWidget());
if (!cur_tree || cur_tree->selectedItems().length() < 1) return;
QTreeWidgetItem *ti = cur_tree->selectedItems()[0];
if (ti->type() != iax2_analysis_type_) return;
Iax2AnalysisTreeWidgetItem *ra_ti = dynamic_cast<Iax2AnalysisTreeWidgetItem *>((Iax2AnalysisTreeWidgetItem *)ti);
emit goToPacket(ra_ti->frameNum());
}
void Iax2AnalysisDialog::on_actionNextProblem_triggered()
{
QTreeWidget *cur_tree = qobject_cast<QTreeWidget *>(ui->tabWidget->currentWidget());
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() != iax2_analysis_type_) return;
QTreeWidgetItem *test_ti = cur_tree->itemBelow(sel_ti);
while (test_ti != sel_ti) {
if (!test_ti) test_ti = cur_tree->topLevelItem(0);
Iax2AnalysisTreeWidgetItem *ra_ti = dynamic_cast<Iax2AnalysisTreeWidgetItem *>((Iax2AnalysisTreeWidgetItem *)test_ti);
if (!ra_ti->frameStatus()) {
cur_tree->setCurrentItem(ra_ti);
break;
}
test_ti = cur_tree->itemBelow(test_ti);
}
}
void Iax2AnalysisDialog::on_fJitterCheckBox_toggled(bool checked)
{
ui->streamGraph->graph(fwd_jitter_graph_)->setVisible(checked);
updateGraph();
}
void Iax2AnalysisDialog::on_fDiffCheckBox_toggled(bool checked)
{
ui->streamGraph->graph(fwd_diff_graph_)->setVisible(checked);
updateGraph();
}
void Iax2AnalysisDialog::on_rJitterCheckBox_toggled(bool checked)
{
ui->streamGraph->graph(rev_jitter_graph_)->setVisible(checked);
updateGraph();
}
void Iax2AnalysisDialog::on_rDiffCheckBox_toggled(bool checked)
{
ui->streamGraph->graph(rev_diff_graph_)->setVisible(checked);
updateGraph();
}
void Iax2AnalysisDialog::on_actionSaveAudio_triggered()
{
saveAudio(dir_both_);
}
void Iax2AnalysisDialog::on_actionSaveForwardAudio_triggered()
{
saveAudio(dir_forward_);
}
void Iax2AnalysisDialog::on_actionSaveReverseAudio_triggered()
{
saveAudio(dir_reverse_);
}
void Iax2AnalysisDialog::on_actionSaveCsv_triggered()
{
saveCsv(dir_both_);
}
void Iax2AnalysisDialog::on_actionSaveForwardCsv_triggered()
{
saveCsv(dir_forward_);
}
void Iax2AnalysisDialog::on_actionSaveReverseCsv_triggered()
{
saveCsv(dir_reverse_);
}
void Iax2AnalysisDialog::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 Iax2AnalysisDialog::on_buttonBox_helpRequested()
{
mainApp->helpTopicAction(HELP_IAX2_ANALYSIS_DIALOG);
}
void Iax2AnalysisDialog::tapReset(void *tapinfoptr)
{
Iax2AnalysisDialog *iax2_analysis_dialog = dynamic_cast<Iax2AnalysisDialog *>((Iax2AnalysisDialog*)tapinfoptr);
if (!iax2_analysis_dialog) return;
iax2_analysis_dialog->resetStatistics();
}
tap_packet_status Iax2AnalysisDialog::tapPacket(void *tapinfoptr, packet_info *pinfo, struct epan_dissect *, const void *iax2info_ptr, tap_flags_t)
{
Iax2AnalysisDialog *iax2_analysis_dialog = dynamic_cast<Iax2AnalysisDialog *>((Iax2AnalysisDialog*)tapinfoptr);
if (!iax2_analysis_dialog) return TAP_PACKET_DONT_REDRAW;
const iax2_info_t *iax2info = (const iax2_info_t *)iax2info_ptr;
if (!iax2info) return TAP_PACKET_DONT_REDRAW;
/* we ignore packets that are not displayed */
if (pinfo->fd->passed_dfilter == 0)
return TAP_PACKET_DONT_REDRAW;
/* we ignore packets that carry no data */
if (iax2info->payload_len < 1)
return TAP_PACKET_DONT_REDRAW;
/* is it the forward direction? */
else if ((cmp_address(&(iax2_analysis_dialog->fwd_id_.src_addr), &(pinfo->src)) == 0)
&& (iax2_analysis_dialog->fwd_id_.src_port == pinfo->srcport)
&& (cmp_address(&(iax2_analysis_dialog->fwd_id_.dst_addr), &(pinfo->dst)) == 0)
&& (iax2_analysis_dialog->fwd_id_.dst_port == pinfo->destport)) {
iax2_analysis_dialog->addPacket(true, pinfo, iax2info);
}
/* is it the reversed direction? */
else if ((cmp_address(&(iax2_analysis_dialog->rev_id_.src_addr), &(pinfo->src)) == 0)
&& (iax2_analysis_dialog->rev_id_.src_port == pinfo->srcport)
&& (cmp_address(&(iax2_analysis_dialog->rev_id_.dst_addr), &(pinfo->dst)) == 0)
&& (iax2_analysis_dialog->rev_id_.dst_port == pinfo->destport)) {
iax2_analysis_dialog->addPacket(false, pinfo, iax2info);
}
return TAP_PACKET_DONT_REDRAW;
}
void Iax2AnalysisDialog::tapDraw(void *tapinfoptr)
{
Iax2AnalysisDialog *iax2_analysis_dialog = dynamic_cast<Iax2AnalysisDialog *>((Iax2AnalysisDialog*)tapinfoptr);
if (!iax2_analysis_dialog) return;
iax2_analysis_dialog->updateStatistics();
}
void Iax2AnalysisDialog::resetStatistics()
{
memset(&fwd_statinfo_, 0, sizeof(fwd_statinfo_));
memset(&rev_statinfo_, 0, sizeof(rev_statinfo_));
fwd_statinfo_.first_packet = TRUE;
rev_statinfo_.first_packet = TRUE;
fwd_statinfo_.reg_pt = PT_UNDEFINED;
rev_statinfo_.reg_pt = PT_UNDEFINED;
ui->forwardTreeWidget->clear();
ui->reverseTreeWidget->clear();
for (int i = 0; i < ui->streamGraph->graphCount(); i++) {
ui->streamGraph->graph(i)->data()->clear();
}
fwd_time_vals_.clear();
fwd_jitter_vals_.clear();
fwd_diff_vals_.clear();
rev_time_vals_.clear();
rev_jitter_vals_.clear();
rev_diff_vals_.clear();
fwd_tempfile_->resize(0);
rev_tempfile_->resize(0);
}
void Iax2AnalysisDialog::addPacket(bool forward, packet_info *pinfo, const struct _iax2_info_t *iax2info)
{
/* add this RTP for future listening using the RTP Player*/
// add_rtp_packet(rtpinfo, pinfo);
if (forward) {
iax2_packet_analyse(&fwd_statinfo_, pinfo, iax2info);
new Iax2AnalysisTreeWidgetItem(ui->forwardTreeWidget, &fwd_statinfo_, pinfo);
fwd_time_vals_.append((fwd_statinfo_.time));
fwd_jitter_vals_.append(fwd_statinfo_.jitter * 1000);
fwd_diff_vals_.append(fwd_statinfo_.diff * 1000);
savePayload(fwd_tempfile_, pinfo, iax2info);
} else {
iax2_packet_analyse(&rev_statinfo_, pinfo, iax2info);
new Iax2AnalysisTreeWidgetItem(ui->reverseTreeWidget, &rev_statinfo_, pinfo);
rev_time_vals_.append((rev_statinfo_.time));
rev_jitter_vals_.append(rev_statinfo_.jitter * 1000);
rev_diff_vals_.append(rev_statinfo_.diff * 1000);
savePayload(rev_tempfile_, pinfo, iax2info);
}
}
// iax2_analysis.c:rtp_packet_save_payload
const guint8 silence_pcmu_ = 0xff;
const guint8 silence_pcma_ = 0x55;
void Iax2AnalysisDialog::savePayload(QTemporaryFile *tmpfile, packet_info *pinfo, const struct _iax2_info_t *iax2info)
{
/* Is this the first packet we got in this direction? */
// if (statinfo->flags & STAT_FLAG_FIRST) {
// if (saveinfo->fp == NULL) {
// saveinfo->saved = FALSE;
// saveinfo->error_type = TAP_RTP_FILE_OPEN_ERROR;
// } else {
// saveinfo->saved = TRUE;
// }
// }
/* Save the voice information */
/* If there was already an error, we quit */
if (!tmpfile->isOpen() || tmpfile->error() != QFile::NoError) return;
/* Quit if the captured length and packet length aren't equal.
*/
if (pinfo->fd->pkt_len != pinfo->fd->cap_len) {
tmpfile->close();
err_str_ = tr("Can't save in a file: Wrong length of captured packets.");
save_payload_error_ = TAP_IAX2_WRONG_LENGTH;
return;
}
if (iax2info->payload_len > 0) {
const char *data = (const char *) iax2info->payload_data;
qint64 nchars;
nchars = tmpfile->write(data, iax2info->payload_len);
if (nchars != (iax2info->payload_len)) {
/* Write error or short write */
err_str_ = tr("Can't save in a file: File I/O problem.");
save_payload_error_ = TAP_IAX2_FILE_IO_ERROR;
tmpfile->close();
return;
}
return;
}
return;
}
void Iax2AnalysisDialog::updateStatistics()
{
double f_duration = fwd_statinfo_.time - fwd_statinfo_.start_time; // s
double r_duration = rev_statinfo_.time - rev_statinfo_.start_time;
#if 0 // Marked as "TODO" in tap-iax2-analysis.c:128
unsigned int f_expected = fwd_statinfo_.stop_seq_nr - fwd_statinfo_.start_seq_nr + 1;
unsigned int r_expected = rev_statinfo_.stop_seq_nr - rev_statinfo_.start_seq_nr + 1;
int f_lost = f_expected - fwd_statinfo_.total_nr;
int r_lost = r_expected - rev_statinfo_.total_nr;
double f_perc, r_perc;
if (f_expected) {
f_perc = (double)(f_lost*100)/(double)f_expected;
} else {
f_perc = 0;
}
if (r_expected) {
r_perc = (double)(r_lost*100)/(double)r_expected;
} else {
r_perc = 0;
}
#endif
QString stats_tables = "<html><head></head><body>\n";
stats_tables += QString("<p>%1:%2 " UTF8_LEFT_RIGHT_ARROW)
.arg(address_to_qstring(&fwd_id_.src_addr, true))
.arg(fwd_id_.src_port);
stats_tables += QString("<br>%1:%2</p>\n")
.arg(address_to_qstring(&fwd_id_.dst_addr, true))
.arg(fwd_id_.dst_port);
stats_tables += "<h4>Forward</h4>\n";
stats_tables += "<p><table>\n";
stats_tables += QString("<tr><th align=\"left\">Max Delta</th><td>%1 ms @ %2</td></tr>")
.arg(fwd_statinfo_.max_delta, 0, 'f', 2)
.arg(fwd_statinfo_.max_nr);
stats_tables += QString("<tr><th align=\"left\">Max Jitter</th><td>%1 ms</tr>")
.arg(fwd_statinfo_.max_jitter, 0, 'f', 2);
stats_tables += QString("<tr><th align=\"left\">Mean Jitter</th><td>%1 ms</tr>")
.arg(fwd_statinfo_.mean_jitter, 0, 'f', 2);
stats_tables += QString("<tr><th align=\"left\">IAX2 Packets</th><td>%1</tr>")
.arg(fwd_statinfo_.total_nr);
#if 0
stats_tables += QString("<tr><th align=\"left\">Expected</th><td>%1</tr>")
.arg(f_expected);
stats_tables += QString("<tr><th align=\"left\">Lost</th><td>%1 (%2 %)</tr>")
.arg(f_lost).arg(f_perc, 0, 'f', 2);
stats_tables += QString("<tr><th align=\"left\">Seq Errs</th><td>%1</tr>")
.arg(fwd_statinfo_.sequence);
#endif
stats_tables += QString("<tr><th align=\"left\">Duration</th><td>%1 s</tr>")
.arg(f_duration, 0, 'f', 2);
stats_tables += "</table></p>\n";
stats_tables += "<h4>Reverse</h4>\n";
stats_tables += "<p><table>\n";
stats_tables += QString("<tr><th align=\"left\">Max Delta</th><td>%1 ms @ %2</td></tr>")
.arg(rev_statinfo_.max_delta, 0, 'f', 2)
.arg(rev_statinfo_.max_nr);
stats_tables += QString("<tr><th align=\"left\">Max Jitter</th><td>%1 ms</tr>")
.arg(rev_statinfo_.max_jitter, 0, 'f', 2);
stats_tables += QString("<tr><th align=\"left\">Mean Jitter</th><td>%1 ms</tr>")
.arg(rev_statinfo_.mean_jitter, 0, 'f', 2);
stats_tables += QString("<tr><th align=\"left\">IAX2 Packets</th><td>%1</tr>")
.arg(rev_statinfo_.total_nr);
#if 0
stats_tables += QString("<tr><th align=\"left\">Expected</th><td>%1</tr>")
.arg(r_expected);
stats_tables += QString("<tr><th align=\"left\">Lost</th><td>%1 (%2 %)</tr>")
.arg(r_lost).arg(r_perc, 0, 'f', 2);
stats_tables += QString("<tr><th align=\"left\">Seq Errs</th><td>%1</tr>")
.arg(rev_statinfo_.sequence);
#endif
stats_tables += QString("<tr><th align=\"left\">Duration</th><td>%1 s</tr>")
.arg(r_duration, 0, 'f', 2);
stats_tables += "</table></p></body>\n";
ui->statisticsLabel->setText(stats_tables);
for (int col = 0; col < ui->forwardTreeWidget->columnCount() - 1; col++) {
ui->forwardTreeWidget->resizeColumnToContents(col);
ui->reverseTreeWidget->resizeColumnToContents(col);
}
graphs_[fwd_jitter_graph_]->setData(fwd_time_vals_, fwd_jitter_vals_);
graphs_[fwd_diff_graph_]->setData(fwd_time_vals_, fwd_diff_vals_);
graphs_[rev_jitter_graph_]->setData(rev_time_vals_, rev_jitter_vals_);
graphs_[rev_diff_graph_]->setData(rev_time_vals_, rev_diff_vals_);
updateGraph();
updateWidgets();
}
void Iax2AnalysisDialog::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();
}
// iax2_analysis.c:copy_file
enum { save_audio_none_, save_audio_au_, save_audio_raw_ };
void Iax2AnalysisDialog::saveAudio(Iax2AnalysisDialog::StreamDirection direction)
{
if (!fwd_tempfile_->isOpen() || !rev_tempfile_->isOpen()) return;
QString caption;
switch (direction) {
case dir_forward_:
caption = tr("Save forward stream audio");
break;
case dir_reverse_:
caption = tr("Save reverse stream audio");
break;
case dir_both_:
default:
caption = tr("Save audio");
break;
}
QString ext_filter = tr("Sun Audio (*.au)");
if (direction != dir_both_) {
ext_filter.append(tr(";;Raw (*.raw)"));
}
QString sel_filter;
QString file_path = WiresharkFileDialog::getSaveFileName(
this, caption, mainApp->lastOpenDir().absoluteFilePath("Saved RTP Audio.au"),
ext_filter, &sel_filter);
if (file_path.isEmpty()) return;
int save_format = save_audio_none_;
if (file_path.endsWith(".au")) {
save_format = save_audio_au_;
} else if (file_path.endsWith(".raw")) {
save_format = save_audio_raw_;
}
if (save_format == save_audio_none_) {
QMessageBox::warning(this, tr("Warning"), tr("Unable to save in that format"));
return;
}
QFile save_file(file_path);
gint16 sample;
guint8 pd[4];
gboolean stop_flag = FALSE;
qint64 nchars;
save_file.open(QIODevice::WriteOnly);
fwd_tempfile_->seek(0);
rev_tempfile_->seek(0);
if (save_file.error() != QFile::NoError) {
QMessageBox::warning(this, tr("Warning"), tr("Unable to save %1").arg(save_file.fileName()));
return;
}
ui->hintLabel->setText(tr("Saving %1…").arg(save_file.fileName()));
ui->progressFrame->showProgress(tr("Analyzing IAX2"), true, true, &stop_flag);
if (save_format == save_audio_au_) { /* au format; 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)
goto copy_file_err;
/* header offset == 24 bytes */
phton32(pd, 24);
nchars = save_file.write((const char *)pd, 4);
if (nchars != 4)
goto copy_file_err;
/* total length; it is permitted to set this to 0xffffffff */
phton32(pd, 0xffffffff);
nchars = save_file.write((const char *)pd, 4);
if (nchars != 4)
goto copy_file_err;
/* encoding format == 16-bit linear PCM */
phton32(pd, 3);
nchars = save_file.write((const char *)pd, 4);
if (nchars != 4)
goto copy_file_err;
/* sample rate == 8000 Hz */
phton32(pd, 8000);
nchars = save_file.write((const char *)pd, 4);
if (nchars != 4)
goto copy_file_err;
/* channels == 1 */
phton32(pd, 1);
nchars = save_file.write((const char *)pd, 4);
if (nchars != 4)
goto copy_file_err;
switch (direction) {
/* Only forward direction */
case dir_forward_:
{
char f_rawvalue;
while (fwd_tempfile_->getChar(&f_rawvalue)) {
if (stop_flag) {
break;
}
ui->progressFrame->setValue(int(fwd_tempfile_->pos() * 100 / fwd_tempfile_->size()));
if (fwd_statinfo_.pt == PT_PCMU) {
sample = ulaw2linear((unsigned char)f_rawvalue);
phton16(pd, sample);
} else if (fwd_statinfo_.pt == PT_PCMA) {
sample = alaw2linear((unsigned char)f_rawvalue);
phton16(pd, sample);
} else {
goto copy_file_err;
}
nchars = save_file.write((const char *)pd, 2);
if (nchars < 2) {
goto copy_file_err;
}
}
break;
}
/* Only reverse direction */
case dir_reverse_:
{
char r_rawvalue;
while (rev_tempfile_->getChar(&r_rawvalue)) {
if (stop_flag) {
break;
}
ui->progressFrame->setValue(int(rev_tempfile_->pos() * 100 / rev_tempfile_->size()));
if (rev_statinfo_.pt == PT_PCMU) {
sample = ulaw2linear((unsigned char)r_rawvalue);
phton16(pd, sample);
} else if (rev_statinfo_.pt == PT_PCMA) {
sample = alaw2linear((unsigned char)r_rawvalue);
phton16(pd, sample);
} else {
goto copy_file_err;
}
nchars = save_file.write((const char *)pd, 2);
if (nchars < 2) {
goto copy_file_err;
}
}
break;
}
/* Both directions */
case dir_both_:
{
char f_rawvalue, r_rawvalue;
guint32 f_write_silence = 0;
guint32 r_write_silence = 0;
/* since conversation in one way can start later than in the other one,
* we have to write some silence information for one channel */
if (fwd_statinfo_.start_time > rev_statinfo_.start_time) {
f_write_silence = (guint32)
((fwd_statinfo_.start_time - rev_statinfo_.start_time)
* (8000/1000));
} else if (fwd_statinfo_.start_time < rev_statinfo_.start_time) {
r_write_silence = (guint32)
((rev_statinfo_.start_time - fwd_statinfo_.start_time)
* (8000/1000));
}
for (;;) {
if (stop_flag) {
break;
}
int fwd_pct = int(fwd_tempfile_->pos() * 100 / fwd_tempfile_->size());
int rev_pct = int(rev_tempfile_->pos() * 100 / rev_tempfile_->size());
ui->progressFrame->setValue(qMin(fwd_pct, rev_pct));
if (f_write_silence > 0) {
rev_tempfile_->getChar(&r_rawvalue);
switch (fwd_statinfo_.reg_pt) {
case PT_PCMU:
f_rawvalue = silence_pcmu_;
break;
case PT_PCMA:
f_rawvalue = silence_pcma_;
break;
default:
f_rawvalue = 0;
break;
}
f_write_silence--;
} else if (r_write_silence > 0) {
fwd_tempfile_->getChar(&f_rawvalue);
switch (rev_statinfo_.reg_pt) {
case PT_PCMU:
r_rawvalue = silence_pcmu_;
break;
case PT_PCMA:
r_rawvalue = silence_pcma_;
break;
default:
r_rawvalue = 0;
break;
}
r_write_silence--;
} else {
fwd_tempfile_->getChar(&f_rawvalue);
rev_tempfile_->getChar(&r_rawvalue);
}
if (fwd_tempfile_->atEnd() && rev_tempfile_->atEnd())
break;
if ((fwd_statinfo_.pt == PT_PCMU)
&& (rev_statinfo_.pt == PT_PCMU)) {
sample = (ulaw2linear((unsigned char)r_rawvalue)
+ ulaw2linear((unsigned char)f_rawvalue)) / 2;
phton16(pd, sample);
}
else if ((fwd_statinfo_.pt == PT_PCMA)
&& (rev_statinfo_.pt == PT_PCMA)) {
sample = (alaw2linear((unsigned char)r_rawvalue)
+ alaw2linear((unsigned char)f_rawvalue)) / 2;
phton16(pd, sample);
} else {
goto copy_file_err;
}
nchars = save_file.write((const char *)pd, 2);
if (nchars < 2) {
goto copy_file_err;
}
}
}
}
} else if (save_format == save_audio_raw_) { /* raw format */
QFile *tempfile;
int progress_pct;
switch (direction) {
/* Only forward direction */
case dir_forward_: {
progress_pct = int(fwd_tempfile_->pos() * 100 / fwd_tempfile_->size());
tempfile = fwd_tempfile_;
break;
}
/* only reversed direction */
case dir_reverse_: {
progress_pct = int(rev_tempfile_->pos() * 100 / rev_tempfile_->size());
tempfile = rev_tempfile_;
break;
}
default: {
goto copy_file_err;
}
}
qsizetype chunk_size = 65536;
/* XXX how do you just copy the file? */
while (chunk_size > 0) {
if (stop_flag)
break;
QByteArray bytes = tempfile->read(chunk_size);
ui->progressFrame->setValue(progress_pct);
if (!save_file.write(bytes)) {
goto copy_file_err;
}
chunk_size = bytes.length();
}
}
copy_file_err:
ui->progressFrame->hide();
updateWidgets();
return;
}
// XXX The GTK+ UI saves the length and timestamp.
void Iax2AnalysisDialog::saveCsv(Iax2AnalysisDialog::StreamDirection direction)
{
QString caption;
switch (direction) {
case dir_forward_:
caption = tr("Save forward stream CSV");
break;
case dir_reverse_:
caption = tr("Save reverse stream CSV");
break;
case dir_both_:
default:
caption = tr("Save 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);
if (direction == dir_forward_ || direction == dir_both_) {
save_file.write("Forward\n");
for (int row = 0; row < ui->forwardTreeWidget->topLevelItemCount(); row++) {
QTreeWidgetItem *ti = ui->forwardTreeWidget->topLevelItem(row);
if (ti->type() != iax2_analysis_type_) continue;
Iax2AnalysisTreeWidgetItem *ra_ti = dynamic_cast<Iax2AnalysisTreeWidgetItem *>((Iax2AnalysisTreeWidgetItem *)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");
}
}
if (direction == dir_both_) {
save_file.write("\n");
}
if (direction == dir_reverse_ || direction == dir_both_) {
save_file.write("Reverse\n");
for (int row = 0; row < ui->reverseTreeWidget->topLevelItemCount(); row++) {
QTreeWidgetItem *ti = ui->reverseTreeWidget->topLevelItem(row);
if (ti->type() != iax2_analysis_type_) continue;
Iax2AnalysisTreeWidgetItem *ra_ti = dynamic_cast<Iax2AnalysisTreeWidgetItem *>((Iax2AnalysisTreeWidgetItem *)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");
}
}
}
bool Iax2AnalysisDialog::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 Iax2AnalysisDialog::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 Iax2AnalysisDialog::showStreamMenu(QPoint pos)
{
QTreeWidget *cur_tree = qobject_cast<QTreeWidget *>(ui->tabWidget->currentWidget());
if (!cur_tree) return;
updateWidgets();
stream_ctx_menu_.popup(cur_tree->viewport()->mapToGlobal(pos));
} |
C/C++ | wireshark/ui/qt/iax2_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 IAX2_ANALYSIS_DIALOG_H
#define IAX2_ANALYSIS_DIALOG_H
// The GTK+ UI checks for multiple RTP streams, and if found opens the RTP
// stream dialog. That seems to violate the principle of least surprise.
// Migrate the code but disable it.
// #define IAX2_RTP_STREAM_CHECK
#include <config.h>
#include <glib.h>
#include <epan/address.h>
#include "ui/tap-iax2-analysis.h"
#include "ui/rtp_stream_id.h"
#include <QAbstractButton>
#include <QMenu>
#include "wireshark_dialog.h"
namespace Ui {
class Iax2AnalysisDialog;
}
class QCPGraph;
class QTemporaryFile;
typedef enum {
TAP_IAX2_NO_ERROR,
TAP_IAX2_NO_PACKET_SELECTED,
TAP_IAX2_WRONG_LENGTH,
TAP_IAX2_FILE_IO_ERROR
} iax2_error_type_t;
class Iax2AnalysisDialog : public WiresharkDialog
{
Q_OBJECT
public:
explicit Iax2AnalysisDialog(QWidget &parent, CaptureFile &cf);
~Iax2AnalysisDialog();
signals:
void goToPacket(int packet_num);
protected slots:
virtual void updateWidgets();
private slots:
void on_actionGoToPacket_triggered();
void on_actionNextProblem_triggered();
void on_fJitterCheckBox_toggled(bool checked);
void on_fDiffCheckBox_toggled(bool checked);
void on_rJitterCheckBox_toggled(bool checked);
void on_rDiffCheckBox_toggled(bool checked);
void on_actionSaveAudio_triggered();
void on_actionSaveForwardAudio_triggered();
void on_actionSaveReverseAudio_triggered();
void on_actionSaveCsv_triggered();
void on_actionSaveForwardCsv_triggered();
void on_actionSaveReverseCsv_triggered();
void on_actionSaveGraph_triggered();
void on_buttonBox_helpRequested();
void showStreamMenu(QPoint pos);
void graphClicked(QMouseEvent *event);
private:
Ui::Iax2AnalysisDialog *ui;
enum StreamDirection { dir_both_, dir_forward_, dir_reverse_ };
rtpstream_id_t fwd_id_;
rtpstream_id_t rev_id_;
tap_iax2_stat_t fwd_statinfo_;
tap_iax2_stat_t rev_statinfo_;
QTemporaryFile *fwd_tempfile_;
QTemporaryFile *rev_tempfile_;
// Graph data for QCustomPlot
QList<QCPGraph *>graphs_;
QVector<double> fwd_time_vals_;
QVector<double> fwd_jitter_vals_;
QVector<double> fwd_diff_vals_;
QVector<double> rev_time_vals_;
QVector<double> rev_jitter_vals_;
QVector<double> rev_diff_vals_;
QString err_str_;
iax2_error_type_t save_payload_error_;
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, struct epan_dissect *, const void *iax2info_ptr, tap_flags_t flags);
static void tapDraw(void *tapinfo_ptr);
void resetStatistics();
void addPacket(bool forward, packet_info *pinfo, const struct _iax2_info_t *iax2info);
void savePayload(QTemporaryFile *tmpfile, packet_info *pinfo, const struct _iax2_info_t *iax2info);
void updateStatistics();
void updateGraph();
void saveAudio(StreamDirection direction);
void saveCsv(StreamDirection direction);
#if 0
guint32 processNode(proto_node *ptree_node, header_field_info *hfinformation, const gchar* proto_field, bool *ok);
guint32 getIntFromProtoTree(proto_tree *protocol_tree, const gchar *proto_name, const gchar *proto_field, bool *ok);
#endif
bool eventFilter(QObject*, QEvent* event);
};
#endif // IAX2_ANALYSIS_DIALOG_H |
User Interface | wireshark/ui/qt/iax2_analysis_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Iax2AnalysisDialog</class>
<widget class="QDialog" name="Iax2AnalysisDialog">
<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>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="statisticsLabel">
<property name="text">
<string><html><head/><body><p><span style=" font-size:medium; font-weight:600;">Forward</span></p><p><span style=" font-size:medium; font-weight:600;">Reverse</span></p></body></html></string>
</property>
<property name="textFormat">
<enum>Qt::RichText</enum>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QTreeWidget" name="forwardTreeWidget">
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="itemsExpandable">
<bool>false</bool>
</property>
<property name="expandsOnDoubleClick">
<bool>false</bool>
</property>
<attribute name="title">
<string>Forward</string>
</attribute>
<column>
<property name="text">
<string>Packet</string>
</property>
</column>
<column>
<property name="text">
<string>Delta (ms)</string>
</property>
</column>
<column>
<property name="text">
<string>Jitter (ms)</string>
</property>
</column>
<column>
<property name="text">
<string>Bandwidth</string>
</property>
</column>
<column>
<property name="text">
<string>Status</string>
</property>
</column>
<column>
<property name="text">
<string>Length</string>
</property>
</column>
</widget>
<widget class="QTreeWidget" name="reverseTreeWidget">
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="itemsExpandable">
<bool>false</bool>
</property>
<attribute name="title">
<string>Reverse</string>
</attribute>
<column>
<property name="text">
<string notr="true">1</string>
</property>
</column>
</widget>
<widget class="QWidget" name="graphTab">
<attribute name="title">
<string>Graph</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_2" stretch="1,0,0">
<item>
<widget class="QCustomPlot" name="streamGraph" native="true"/>
</item>
<item>
<layout class="QHBoxLayout" name="forwardHorizontalLayout" stretch="0,0,0,1">
<item>
<widget class="QCheckBox" name="fJitterCheckBox">
<property name="toolTip">
<string><html><head/><body><p>Show or hide forward jitter values.</p></body></html></string>
</property>
<property name="text">
<string>Forward Jitter</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>10</width>
<height>5</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QCheckBox" name="fDiffCheckBox">
<property name="toolTip">
<string><html><head/><body><p>Show or hide forward difference values.</p></body></html></string>
</property>
<property name="text">
<string>Forward Difference</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>10</width>
<height>5</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="reverseHorizontalLayout" stretch="0,0,0,1">
<item>
<widget class="QCheckBox" name="rJitterCheckBox">
<property name="toolTip">
<string><html><head/><body><p>Show or hide reverse jitter values.</p></body></html></string>
</property>
<property name="text">
<string>Reverse Jitter</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_4">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>10</width>
<height>5</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QCheckBox" name="rDiffCheckBox">
<property name="toolTip">
<string><html><head/><body><p>Show or hide reverse difference values.</p></body></html></string>
</property>
<property name="text">
<string>Reverse Difference</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>5</height>
</size>
</property>
</spacer>
</item>
</layout>
</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|QDialogButtonBox::Save</set>
</property>
</widget>
</item>
</layout>
<action name="actionSaveAudio">
<property name="text">
<string>Audio</string>
</property>
<property name="toolTip">
<string>Save the audio data for both channels.</string>
</property>
</action>
<action name="actionSaveForwardAudio">
<property name="text">
<string>Forward Stream Audio</string>
</property>
<property name="toolTip">
<string>Save the forward stream audio data.</string>
</property>
</action>
<action name="actionSaveReverseAudio">
<property name="text">
<string>Reverse Stream Audio</string>
</property>
<property name="toolTip">
<string>Save the reverse stream audio data.</string>
</property>
</action>
<action name="actionSaveCsv">
<property name="text">
<string>CSV</string>
</property>
<property name="toolTip">
<string>Save both tables as CSV.</string>
</property>
</action>
<action name="actionSaveForwardCsv">
<property name="text">
<string>Forward Stream CSV</string>
</property>
<property name="toolTip">
<string>Save the forward table as CSV.</string>
</property>
</action>
<action name="actionSaveReverseCsv">
<property name="text">
<string>Reverse Stream CSV</string>
</property>
<property name="toolTip">
<string>Save the reverse table 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>
</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>Iax2AnalysisDialog</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>Iax2AnalysisDialog</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/import_text_dialog.cpp | /* import_text_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 "import_text_dialog.h"
#include "wiretap/wtap.h"
#include "wiretap/pcap-encap.h"
#include <epan/prefs.h>
#include "ui/text_import_scanner.h"
#include "ui/last_open_dir.h"
#include "ui/alert_box.h"
#include "ui/help_url.h"
#include "ui/capture_globals.h"
#include "file.h"
#include "wsutil/file_util.h"
#include "wsutil/inet_addr.h"
#include "wsutil/time_util.h"
#include "wsutil/tempfile.h"
#include "wsutil/filesystem.h"
#include <ui_import_text_dialog.h>
#include "main_application.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include "ui/qt/widgets/wireshark_file_dialog.h"
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QFile>
#define HINT_BEGIN "<small><i>"
#define HINT_END "</i></small>"
#define HTML_LT "<"
#define HTML_GT ">"
static const QString default_regex_hint = ImportTextDialog::tr("Supported fields are data, dir, time, seqno");
static const QString missing_data_hint = ImportTextDialog::tr("Missing capturing group data (use (?" HTML_LT "data" HTML_GT "(...)) )");
#define SETTINGS_FILE "import_hexdump.json"
ImportTextDialog::ImportTextDialog(QWidget *parent) :
QDialog(parent),
ti_ui_(new Ui::ImportTextDialog),
import_info_(),
file_ok_(false),
timestamp_format_ok_(true),
regex_ok_(false),
re_has_dir_(false),
in_indication_ok_(false),
out_indication_ok_(false),
re_has_time_(false),
ether_type_ok_(true),
proto_ok_(true),
source_addr_ok_(true),
dest_addr_ok_(true),
source_port_ok_(true),
dest_port_ok_(true),
tag_ok_(true),
ppi_ok_(true),
payload_ok_(true),
max_len_ok_(true)
{
int encap;
int i;
int file_type_subtype;
ti_ui_->setupUi(this);
setWindowTitle(mainApp->windowTitleString(tr("Import From Hex Dump")));
memset(&import_info_, 0, sizeof(import_info_));
import_button_ = ti_ui_->buttonBox->button(QDialogButtonBox::Open);
import_button_->setText(tr("Import"));
import_button_->setEnabled(false);
ti_ui_->regexHintLabel->setSmallText(true);
#ifdef Q_OS_MAC
// The grid layout squishes each line edit otherwise.
int le_height = ti_ui_->textFileLineEdit->sizeHint().height();
ti_ui_->ethertypeLineEdit->setMinimumHeight(le_height);
ti_ui_->protocolLineEdit->setMinimumHeight(le_height);
ti_ui_->sourceAddressLineEdit->setMinimumHeight(le_height);
ti_ui_->destinationAddressLineEdit->setMinimumHeight(le_height);
ti_ui_->sourcePortLineEdit->setMinimumHeight(le_height);
ti_ui_->destinationPortLineEdit->setMinimumHeight(le_height);
ti_ui_->tagLineEdit->setMinimumHeight(le_height);
ti_ui_->ppiLineEdit->setMinimumHeight(le_height);
#endif
on_timestampFormatLineEdit_textChanged(ti_ui_->timestampFormatLineEdit->text());
encap_buttons = new QButtonGroup(this);
for (i = 0; i < ti_ui_->headerGridLayout->count(); i++) {
QRadioButton *rb = qobject_cast<QRadioButton *>(ti_ui_->headerGridLayout->itemAt(i)->widget());
if (rb) encap_buttons->addButton(rb);
}
/* There are two QButtonGroup::buttonToggled signals from Qt 5.2-5.15 with
* different parameters. This breaks connectSlotsByName, which only finds
* the deprecated one that doesn't exist in Qt 6. So we have to connect it
* manually, and avoid naming the slot in the normal way.
*/
connect(encap_buttons, SIGNAL(buttonToggled(QAbstractButton*, bool)), this, SLOT(encap_buttonsToggled(QAbstractButton*, bool)));
/* fill the IP version combobox */
ti_ui_->ipVersionComboBox->addItem("IPv4", QVariant(4));
ti_ui_->ipVersionComboBox->addItem("IPv6", QVariant(6));
/* fill the data encoding dropdown in regex tab*/
struct {
const char* name;
enum data_encoding id;
} encodings[] = {
{"Plain hex", ENCODING_PLAIN_HEX},
{"Plain oct", ENCODING_PLAIN_OCT},
{"Plain bin", ENCODING_PLAIN_BIN},
{"Base 64", ENCODING_BASE64}
};
for (i = 0; i < (int) (sizeof(encodings) / sizeof(encodings[0])); ++i) {
ti_ui_->dataEncodingComboBox->addItem(encodings[i].name, QVariant(encodings[i].id));
}
/*
* Scan all Wiretap encapsulation types.
*
* XXX - this "knows" that WTAP_ENCAP_ETHERNET is the first encapsulation
* type, skipping the special non-types WTAP_ENCAP_PER_PACKET and
* WTAP_ENCAP_UNKNOWN. We need a better way to express the notion
* of "for (all encapsulation types)".
*/
import_info_.encapsulation = WTAP_ENCAP_ETHERNET;
file_type_subtype = wtap_pcapng_file_type_subtype();
for (encap = import_info_.encapsulation; encap < wtap_get_num_encap_types(); encap++)
{
/* Check if we can write to a pcapng file
*
* Exclude wtap encapsulations that require a pseudo header,
* because we won't setup one from the text we import and
* wiretap doesn't allow us to write 'raw' frames
*/
if (wtap_dump_can_write_encap(file_type_subtype, encap) &&
!wtap_encap_requires_phdr(encap)) {
const char *name;
/* If it has got a name */
if ((name = wtap_encap_description(encap)))
{
ti_ui_->encapComboBox->addItem(name, QVariant(encap));
}
}
}
ti_ui_->encapComboBox->model()->sort(0);
/* fill the dissector combo box */
GList* dissector_names = get_dissector_names();
for (GList* l = dissector_names; l != NULL; l = l->next) {
const char* name = (const char*) l->data;
ti_ui_->dissectorComboBox->addItem(name, QVariant(name));
}
ti_ui_->dissectorComboBox->model()->sort(0);
g_list_free(dissector_names);
ti_ui_->regexHintLabel->setText(default_regex_hint);
applyDialogSettings();
updateImportButtonState();
}
ImportTextDialog::~ImportTextDialog()
{
storeDialogSettings();
delete ti_ui_;
}
void ImportTextDialog::loadSettingsFile()
{
QFileInfo fileInfo(gchar_free_to_qstring(get_profile_dir(get_profile_name(), FALSE)), QString(SETTINGS_FILE));
QFile loadFile(fileInfo.filePath());
if (!fileInfo.exists() || !fileInfo.isFile()) {
return;
}
if (loadFile.open(QIODevice::ReadOnly)) {
QByteArray loadData = loadFile.readAll();
QJsonDocument document = QJsonDocument::fromJson(loadData);
settings = document.object().toVariantMap();
}
}
void ImportTextDialog::saveSettingsFile()
{
QFileInfo fileInfo(gchar_free_to_qstring(get_profile_dir(get_profile_name(), FALSE)), QString(SETTINGS_FILE));
QFile saveFile(fileInfo.filePath());
if (fileInfo.exists() && !fileInfo.isFile()) {
return;
}
if (saveFile.open(QIODevice::WriteOnly)) {
QJsonDocument document = QJsonDocument::fromVariant(settings);
QByteArray saveData = document.toJson();
saveFile.write(saveData);
}
}
void ImportTextDialog::applyDialogSettings()
{
loadSettingsFile();
// Hex Dump
QString offsetType = settings["hexdump.offsets"].toString();
if (offsetType == "hex") {
ti_ui_->hexOffsetButton->setChecked(true);
} else if (offsetType == "dec") {
ti_ui_->decimalOffsetButton->setChecked(true);
} else if (offsetType == "oct") {
ti_ui_->octalOffsetButton->setChecked(true);
} else if (offsetType == "none") {
ti_ui_->noOffsetButton->setChecked(true);
}
ti_ui_->directionIndicationCheckBox->setChecked(settings["hexdump.hasDirection"].toBool());
ti_ui_->asciiIdentificationCheckBox->setChecked(settings["hexdump.identifyAscii"].toBool());
// Regular Expression
ti_ui_->regexTextEdit->setText(settings["regex.format"].toString());
QString encoding = settings["regex.encoding"].toString();
if (encoding == "plainHex") {
ti_ui_->dataEncodingComboBox->setCurrentIndex(0);
} else if (encoding == "plainOct") {
ti_ui_->dataEncodingComboBox->setCurrentIndex(1);
} else if (encoding == "plainBin") {
ti_ui_->dataEncodingComboBox->setCurrentIndex(2);
} else if (encoding == "base64") {
ti_ui_->dataEncodingComboBox->setCurrentIndex(3);
}
ti_ui_->dirInIndicationLineEdit->setText(settings["regex.inIndication"].toString());
ti_ui_->dirOutIndicationLineEdit->setText(settings["regex.outIndication"].toString());
// Import info
ti_ui_->timestampFormatLineEdit->setText(settings["timestampFormat"].toString());
const char *name = wtap_encap_description(settings["encapsulation"].toInt());
ti_ui_->encapComboBox->setCurrentText(name);
QString dummyHeader = settings["dummyHeader"].toString();
if (dummyHeader == "ethernet") {
ti_ui_->ethernetButton->setChecked(true);
} else if (dummyHeader == "ipv4") {
ti_ui_->ipv4Button->setChecked(true);
} else if (dummyHeader == "udp") {
ti_ui_->udpButton->setChecked(true);
} else if (dummyHeader == "tcp") {
ti_ui_->tcpButton->setChecked(true);
} else if (dummyHeader == "sctp") {
ti_ui_->sctpButton->setChecked(true);
} else if (dummyHeader == "sctpData") {
ti_ui_->sctpDataButton->setChecked(true);
} else if (dummyHeader == "exportPDU") {
ti_ui_->exportPduButton->setChecked(true);
} else if (dummyHeader == "none") {
ti_ui_->noDummyButton->setChecked(true);
}
if (settings["ipVersion"].toUInt() == 6) {
ti_ui_->ipVersionComboBox->setCurrentIndex(1);
} else {
ti_ui_->ipVersionComboBox->setCurrentIndex(0);
}
ti_ui_->ethertypeLineEdit->setText(settings["ethertype"].toString());
ti_ui_->protocolLineEdit->setText(settings["ipProtocol"].toString());
ti_ui_->sourceAddressLineEdit->setText(settings["sourceAddress"].toString());
ti_ui_->destinationAddressLineEdit->setText(settings["destinationAddress"].toString());
ti_ui_->sourcePortLineEdit->setText(settings["sourcePort"].toString());
ti_ui_->destinationPortLineEdit->setText(settings["destinationPort"].toString());
ti_ui_->tagLineEdit->setText(settings["sctpTag"].toString());
ti_ui_->ppiLineEdit->setText(settings["sctpPPI"].toString());
if (settings.contains("pduPayload")) {
ti_ui_->dissectorComboBox->setCurrentText(settings["pduPayload"].toString());
} else {
// Default to the data dissector when not previously set
ti_ui_->dissectorComboBox->setCurrentText("data");
}
ti_ui_->interfaceLineEdit->setText(settings["interfaceName"].toString());
ti_ui_->maxLengthLineEdit->setText(settings["maxFrameLength"].toString());
// Select mode tab last to enableFieldWidgets()
QString mode(settings["mode"].toString());
int modeIndex = (mode == "regex") ? 1 : 0;
ti_ui_->modeTabWidget->setCurrentIndex(modeIndex);
on_modeTabWidget_currentChanged(modeIndex);
}
void ImportTextDialog::storeDialogSettings()
{
int modeIndex = ti_ui_->modeTabWidget->currentIndex();
if (modeIndex == 0) {
settings["mode"] = "hexdump";
} else {
settings["mode"] = "regex";
}
// Hex Dump
if (ti_ui_->hexOffsetButton->isChecked()) {
settings["hexdump.offsets"] = "hex";
} else if (ti_ui_->decimalOffsetButton->isChecked()) {
settings["hexdump.offsets"] = "dec";
} else if (ti_ui_->octalOffsetButton->isChecked()) {
settings["hexdump.offsets"] = "oct";
} else {
settings["hexdump.offsets"] = "none";
}
settings["hexdump.hasDirection"] = ti_ui_->directionIndicationCheckBox->isChecked();
settings["hexdump.identifyAscii"] = ti_ui_->asciiIdentificationCheckBox->isChecked();
// Regular Expression
settings["regex.format"] = ti_ui_->regexTextEdit->toPlainText();
QVariant encodingVal = ti_ui_->dataEncodingComboBox->itemData(ti_ui_->dataEncodingComboBox->currentIndex());
if (encodingVal.isValid()) {
enum data_encoding encoding = (enum data_encoding) encodingVal.toUInt();
switch (encoding) {
case ENCODING_PLAIN_HEX:
settings["regex.encoding"] = "plainHex";
break;
case ENCODING_PLAIN_OCT:
settings["regex.encoding"] = "plainOct";
break;
case ENCODING_PLAIN_BIN:
settings["regex.encoding"] = "plainBin";
break;
case ENCODING_BASE64:
settings["regex.encoding"] = "base64";
break;
}
} else {
settings["regex.encoding"] = "plainHex";
}
settings["regex.inIndication"] = ti_ui_->dirInIndicationLineEdit->text();
settings["regex.outIndication"] = ti_ui_->dirOutIndicationLineEdit->text();
// Import info
settings["timestampFormat"] = ti_ui_->timestampFormatLineEdit->text();
QVariant encapVal = ti_ui_->encapComboBox->itemData(ti_ui_->encapComboBox->currentIndex());
if (encapVal.isValid()) {
settings["encapsulation"] = encapVal.toUInt();
} else {
settings["encapsulation"] = WTAP_ENCAP_ETHERNET;
}
if (ti_ui_->ethernetButton->isChecked()) {
settings["dummyHeader"] = "ethernet";
} else if (ti_ui_->ipv4Button->isChecked()) {
settings["dummyHeader"] = "ipv4";
} else if (ti_ui_->udpButton->isChecked()) {
settings["dummyHeader"] = "udp";
} else if (ti_ui_->tcpButton->isChecked()) {
settings["dummyHeader"] = "tcp";
} else if (ti_ui_->sctpButton->isChecked()) {
settings["dummyHeader"] = "sctp";
} else if (ti_ui_->sctpDataButton->isChecked()) {
settings["dummyHeader"] = "sctpData";
} else if (ti_ui_->exportPduButton->isChecked()) {
settings["dummyHeader"] = "exportPDU";
} else {
settings["dummyHeader"] = "none";
}
settings["ipVersion"] = ti_ui_->ipVersionComboBox->currentData().toUInt();
settings["ethertype"] = ti_ui_->ethertypeLineEdit->text();
settings["ipProtocol"] = ti_ui_->protocolLineEdit->text();
settings["sourceAddress"] = ti_ui_->sourceAddressLineEdit->text();
settings["destinationAddress"] = ti_ui_->destinationAddressLineEdit->text();
settings["sourcePort"] = ti_ui_->sourcePortLineEdit->text();
settings["destinationPort"] = ti_ui_->destinationPortLineEdit->text();
settings["sctpTag"] = ti_ui_->tagLineEdit->text();
settings["sctpPPI"] = ti_ui_->ppiLineEdit->text();
settings["pduPayload"] = ti_ui_->dissectorComboBox->currentData().toString();
settings["interfaceName"] = ti_ui_->interfaceLineEdit->text();
settings["maxFrameLength"] = ti_ui_->maxLengthLineEdit->text();
saveSettingsFile();
}
QString &ImportTextDialog::capfileName() {
return capfile_name_;
}
int ImportTextDialog::exec() {
QVariant encap_val;
char* tmp;
GError* gerror = NULL;
int err;
gchar *err_info;
wtap_dump_params params;
int file_type_subtype;
QString interface_name;
QDialog::exec();
if (result() != QDialog::Accepted) {
return result();
}
/* from here on the cleanup labels are used to free allocated resources in
* reverse order.
* naming is cleanup_<step_where_something_failed>
* Don't Declare new variables from here on
*/
import_info_.import_text_filename = qstring_strdup(ti_ui_->textFileLineEdit->text());
import_info_.timestamp_format = qstring_strdup(ti_ui_->timestampFormatLineEdit->text());
if (strlen(import_info_.timestamp_format) == 0) {
g_free((gpointer) import_info_.timestamp_format);
import_info_.timestamp_format = NULL;
}
switch (import_info_.mode) {
default: /* should never happen */
setResult(QDialog::Rejected);
return QDialog::Rejected;
case TEXT_IMPORT_HEXDUMP:
import_info_.hexdump.import_text_FILE = ws_fopen(import_info_.import_text_filename, "rb");
if (!import_info_.hexdump.import_text_FILE) {
open_failure_alert_box(import_info_.import_text_filename, errno, FALSE);
setResult(QDialog::Rejected);
goto cleanup_mode;
}
import_info_.hexdump.offset_type =
ti_ui_->hexOffsetButton->isChecked() ? OFFSET_HEX :
ti_ui_->decimalOffsetButton->isChecked() ? OFFSET_DEC :
ti_ui_->octalOffsetButton->isChecked() ? OFFSET_OCT :
OFFSET_NONE;
break;
case TEXT_IMPORT_REGEX:
import_info_.regex.import_text_GMappedFile = g_mapped_file_new(import_info_.import_text_filename, true, &gerror);
if (gerror) {
open_failure_alert_box(import_info_.import_text_filename, gerror->code, FALSE);
g_error_free(gerror);
setResult(QDialog::Rejected);
goto cleanup_mode;
}
tmp = qstring_strdup(ti_ui_->regexTextEdit->toPlainText());
import_info_.regex.format = g_regex_new(tmp, (GRegexCompileFlags) (G_REGEX_DUPNAMES | G_REGEX_OPTIMIZE | G_REGEX_MULTILINE), G_REGEX_MATCH_NOTEMPTY, &gerror);
g_free(tmp);
if (re_has_dir_) {
import_info_.regex.in_indication = qstring_strdup(ti_ui_->dirInIndicationLineEdit->text());
import_info_.regex.out_indication = qstring_strdup(ti_ui_->dirOutIndicationLineEdit->text());
} else {
import_info_.regex.in_indication = NULL;
import_info_.regex.out_indication = NULL;
}
break;
}
encap_val = ti_ui_->encapComboBox->itemData(ti_ui_->encapComboBox->currentIndex());
import_info_.dummy_header_type = HEADER_NONE;
if (encap_val.isValid() && (encap_buttons->checkedButton()->isEnabled())
&& !ti_ui_->noDummyButton->isChecked()) {
// Inputs were validated in the on_xxx_textChanged slots.
if (ti_ui_->ethernetButton->isChecked()) {
import_info_.dummy_header_type = HEADER_ETH;
} else if (ti_ui_->ipv4Button->isChecked()) {
import_info_.dummy_header_type = HEADER_IPV4;
} else if (ti_ui_->udpButton->isChecked()) {
import_info_.dummy_header_type = HEADER_UDP;
} else if (ti_ui_->tcpButton->isChecked()) {
import_info_.dummy_header_type = HEADER_TCP;
} else if (ti_ui_->sctpButton->isChecked()) {
import_info_.dummy_header_type = HEADER_SCTP;
} else if (ti_ui_->sctpDataButton->isChecked()) {
import_info_.dummy_header_type = HEADER_SCTP_DATA;
} else if (ti_ui_->exportPduButton->isChecked()) {
import_info_.dummy_header_type = HEADER_EXPORT_PDU;
}
}
if (import_info_.max_frame_length == 0) {
import_info_.max_frame_length = WTAP_MAX_PACKET_SIZE_STANDARD;
}
import_info_.payload = qstring_strdup(ti_ui_->dissectorComboBox->currentData().toString());
capfile_name_.clear();
wtap_dump_params_init(¶ms, NULL);
params.encap = import_info_.encapsulation;
params.snaplen = import_info_.max_frame_length;
params.tsprec = WTAP_TSPREC_NSEC; /* XXX - support other precisions? */
/* Write a pcapng temporary file */
file_type_subtype = wtap_pcapng_file_type_subtype();
if (ti_ui_->interfaceLineEdit->text().length()) {
interface_name = ti_ui_->interfaceLineEdit->text();
} else {
interface_name = ti_ui_->interfaceLineEdit->placeholderText();
}
text_import_pre_open(¶ms, file_type_subtype, import_info_.import_text_filename, interface_name.toUtf8().constData());
/* Use a random name for the temporary import buffer */
import_info_.wdh = wtap_dump_open_tempfile(global_capture_opts.temp_dir, &tmp, "import", file_type_subtype, WTAP_UNCOMPRESSED, ¶ms, &err, &err_info);
capfile_name_.append(tmp ? tmp : "temporary file");
import_info_.output_filename = tmp;
if (import_info_.wdh == NULL) {
cfile_dump_open_failure_alert_box(capfile_name_.toUtf8().constData(), err, err_info, file_type_subtype);
setResult(QDialog::Rejected);
goto cleanup_wtap;
}
err = text_import(&import_info_);
if (err != 0) {
failure_alert_box("Import failed");
setResult(QDialog::Rejected);
goto cleanup;
}
cleanup: /* free in reverse order of allocation */
if (!wtap_dump_close(import_info_.wdh, NULL, &err, &err_info))
{
cfile_close_failure_alert_box(capfile_name_.toUtf8().constData(), err, err_info);
}
cleanup_wtap:
/* g_free checks for null */
wtap_free_idb_info(params.idb_inf);
wtap_dump_params_cleanup(¶ms);
g_free(tmp);
g_free((gpointer) import_info_.payload);
switch (import_info_.mode) {
case TEXT_IMPORT_HEXDUMP:
fclose(import_info_.hexdump.import_text_FILE);
break;
case TEXT_IMPORT_REGEX:
g_mapped_file_unref(import_info_.regex.import_text_GMappedFile);
g_regex_unref((GRegex*) import_info_.regex.format);
g_free((gpointer) import_info_.regex.in_indication);
g_free((gpointer) import_info_.regex.out_indication);
break;
}
cleanup_mode:
g_free((gpointer) import_info_.import_text_filename);
g_free((gpointer) import_info_.timestamp_format);
return result();
}
/*******************************************************************************
* General Input
*/
void ImportTextDialog::updateImportButtonState()
{
/* XXX: This requires even buttons that aren't being used to have valid
* entries (addresses, ports, etc.) Fixing that can mean changing the
* encapsulation type in order to enable the line edits, which is a little
* awkward for the user.
*/
if (file_ok_ && timestamp_format_ok_ && ether_type_ok_ &&
proto_ok_ && source_addr_ok_ && dest_addr_ok_ &&
source_port_ok_ && dest_port_ok_ &&
tag_ok_ && ppi_ok_ && payload_ok_ && max_len_ok_ &&
(
(
import_info_.mode == TEXT_IMPORT_REGEX && regex_ok_ &&
(!re_has_dir_ || (in_indication_ok_ && out_indication_ok_))
) || (
import_info_.mode == TEXT_IMPORT_HEXDUMP
)
)
) {
import_button_->setEnabled(true);
} else {
import_button_->setEnabled(false);
}
}
void ImportTextDialog::on_textFileLineEdit_textChanged(const QString &file_name)
{
QFile text_file(file_name);
if (file_name.length() > 0 && text_file.open(QIODevice::ReadOnly)) {
file_ok_ = true;
text_file.close();
} else {
file_ok_ = false;
}
updateImportButtonState();
}
void ImportTextDialog::on_textFileBrowseButton_clicked()
{
QString open_dir;
if (ti_ui_->textFileLineEdit->text().length() > 0) {
open_dir = ti_ui_->textFileLineEdit->text();
} else {
switch (prefs.gui_fileopen_style) {
case FO_STYLE_LAST_OPENED:
/* The user has specified that we should start out in the last directory
we looked in. If we've already opened a file, use its containing
directory, if we could determine it, as the directory, otherwise
use the "last opened" directory saved in the preferences file if
there was one. */
/* This is now the default behaviour in file_selection_new() */
open_dir = get_last_open_dir();
break;
case FO_STYLE_SPECIFIED:
/* The user has specified that we should always start out in a
specified directory; if they've specified that directory,
start out by showing the files in that dir. */
if (prefs.gui_fileopen_dir[0] != '\0')
open_dir = prefs.gui_fileopen_dir;
break;
}
}
QString file_name = WiresharkFileDialog::getOpenFileName(this, mainApp->windowTitleString(tr("Import Text File")), open_dir);
ti_ui_->textFileLineEdit->setText(file_name);
}
bool ImportTextDialog::checkDateTimeFormat(const QString &time_format)
{
/* nonstandard is f for fractions of seconds */
const QString valid_code = "aAbBcdDFfHIjmMpsSTUwWxXyYzZ%";
int idx = 0;
int ret = false;
/* XXX: Temporary(?) hack to allow ISO format time, a checkbox is
* probably better */
if (time_format == "ISO") {
ret = true;
} else while ((idx = static_cast<int>(time_format.indexOf("%", idx))) != -1) {
idx++;
if ((idx == time_format.size()) || !valid_code.contains(time_format[idx])) {
return false;
}
idx++;
ret = true;
}
return ret;
}
void ImportTextDialog::on_timestampFormatLineEdit_textChanged(const QString &time_format)
{
if (time_format.length() > 0) {
if (checkDateTimeFormat(time_format)) {
struct timespec timenow;
struct tm *cur_tm;
struct tm fallback;
char time_str[100];
QString timefmt = QString(time_format);
ws_clock_get_realtime(&timenow);
/* On windows strftime/wcsftime does not support %s yet, this works on all OSs */
timefmt.replace(QString("%s"), QString::number(timenow.tv_sec));
/* subsecond example as usec */
timefmt.replace(QString("%f"), QString("%1").arg(timenow.tv_nsec, 6, 10, QChar('0')));
cur_tm = localtime(&timenow.tv_sec);
if (cur_tm == NULL) {
memset(&fallback, 0, sizeof(fallback));
cur_tm = &fallback;
}
strftime(time_str, sizeof time_str, timefmt.toUtf8(), cur_tm);
ti_ui_->timestampExampleLabel->setText(QString(tr(HINT_BEGIN "Example: %1" HINT_END)).arg(QString(time_str).toHtmlEscaped()));
timestamp_format_ok_ = true;
}
else {
ti_ui_->timestampExampleLabel->setText(tr(HINT_BEGIN "(Wrong date format)" HINT_END));
timestamp_format_ok_ = false;
}
} else {
ti_ui_->timestampExampleLabel->setText(tr(HINT_BEGIN "(No format will be applied)" HINT_END));
timestamp_format_ok_ = true;
}
updateImportButtonState();
}
void ImportTextDialog::on_modeTabWidget_currentChanged(int index) {
switch (index) {
default:
ti_ui_->modeTabWidget->setCurrentIndex(0);
/* fall through */
case 0: /* these numbers depend on the UI */
import_info_.mode = TEXT_IMPORT_HEXDUMP;
memset(&import_info_.hexdump, 0, sizeof(import_info_.hexdump));
on_directionIndicationCheckBox_toggled(ti_ui_->directionIndicationCheckBox->isChecked());
on_asciiIdentificationCheckBox_toggled(ti_ui_->asciiIdentificationCheckBox->isChecked());
enableFieldWidgets(false, true);
break;
case 1:
import_info_.mode = TEXT_IMPORT_REGEX;
memset(&import_info_.regex, 0, sizeof(import_info_.regex));
on_dataEncodingComboBox_currentIndexChanged(ti_ui_->dataEncodingComboBox->currentIndex());
enableFieldWidgets(re_has_dir_, re_has_time_);
break;
}
on_textFileLineEdit_textChanged(ti_ui_->textFileLineEdit->text());
}
/*******************************************************************************
* Hex Dump Tab
*/
void ImportTextDialog::on_noOffsetButton_toggled(bool checked)
{
if (checked) {
ti_ui_->noOffsetLabel->setText("(only one packet will be created)");
} else {
ti_ui_->noOffsetLabel->setText("");
}
}
void ImportTextDialog::on_directionIndicationCheckBox_toggled(bool checked)
{
import_info_.hexdump.has_direction = checked;
}
void ImportTextDialog::on_asciiIdentificationCheckBox_toggled(bool checked)
{
import_info_.hexdump.identify_ascii = checked;
}
/*******************************************************************************
* Regex Tab
*/
void ImportTextDialog::on_regexTextEdit_textChanged()
{
gchar* regex_gchar_p = qstring_strdup(ti_ui_->regexTextEdit->toPlainText());;
GError* gerror = NULL;
/* TODO: Use GLib's c++ interface or enable C++ int to enum casting
* because the flags are declared as enum, so we can't pass 0 like
* the specification recommends. These options don't hurt.
*/
GRegex* regex = g_regex_new(regex_gchar_p, G_REGEX_DUPNAMES, G_REGEX_MATCH_NOTEMPTY, &gerror);
if (gerror) {
regex_ok_ = false;
ti_ui_->regexHintLabel->setText(QString(gerror->message).toHtmlEscaped());
g_error_free(gerror);
} else {
regex_ok_ = 0 <= g_regex_get_string_number(regex, "data");
if (regex_ok_)
ti_ui_->regexHintLabel->setText(default_regex_hint);
else
ti_ui_->regexHintLabel->setText(missing_data_hint);
re_has_dir_ = 0 <= g_regex_get_string_number(regex, "dir");
re_has_time_ = 0 <= g_regex_get_string_number(regex, "time");
//re_has_seqno = 0 <= g_regex_get_string_number(regex, "seqno");
g_regex_unref(regex);
}
g_free(regex_gchar_p);
enableFieldWidgets(re_has_dir_, re_has_time_);
updateImportButtonState();
}
void ImportTextDialog::enableFieldWidgets(bool enable_direction_input, bool enable_time_input) {
ti_ui_->dirIndicationLabel->setEnabled(enable_direction_input);
ti_ui_->dirInIndicationLineEdit->setEnabled(enable_direction_input);
ti_ui_->dirOutIndicationLineEdit->setEnabled(enable_direction_input);
ti_ui_->timestampLabel->setEnabled(enable_time_input);
ti_ui_->timestampFormatLineEdit->setEnabled(enable_time_input);
ti_ui_->timestampExampleLabel->setEnabled(enable_time_input);
}
void ImportTextDialog::on_dataEncodingComboBox_currentIndexChanged(int index)
{
QVariant val = ti_ui_->dataEncodingComboBox->itemData(index);
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
if (val.canConvert<int>())
#else
if (val != QVariant::Invalid)
#endif
{
// data_encoding_ok = true;
import_info_.regex.encoding = (enum data_encoding) val.toUInt();
switch (import_info_.regex.encoding) {
case ENCODING_PLAIN_HEX:
ti_ui_->encodingRegexExample->setText(HINT_BEGIN "(?" HTML_LT "data" HTML_GT "[0-9a-fA-F:\\s]+)" HINT_END);
break;
case ENCODING_PLAIN_BIN:
ti_ui_->encodingRegexExample->setText(HINT_BEGIN "(?" HTML_LT "data" HTML_GT "[0-1\\s]+)" HINT_END);
break;
case ENCODING_PLAIN_OCT:
ti_ui_->encodingRegexExample->setText(HINT_BEGIN "(?" HTML_LT "data" HTML_GT "[0-8:\\s]+)" HINT_END);
break;
case ENCODING_BASE64:
ti_ui_->encodingRegexExample->setText(HINT_BEGIN "(?" HTML_LT "data" HTML_GT "[0-9a-zA-Z+\\/\\s]+=*)" HINT_END);
break;
default:
ti_ui_->encodingRegexExample->setText(HINT_BEGIN HTML_LT "no example" HTML_GT HINT_END);
break;
}
/* for some reason this breaks when changing the text */
ti_ui_->encodingRegexExample->setTextInteractionFlags(Qt::TextSelectableByMouse);
}
updateImportButtonState();
}
void ImportTextDialog::on_dirInIndicationLineEdit_textChanged(const QString &in_indication)
{
in_indication_ok_ = in_indication.length() > 0;
updateImportButtonState();
}
void ImportTextDialog::on_dirOutIndicationLineEdit_textChanged(const QString &out_indication)
{
out_indication_ok_ = out_indication.length() > 0;
updateImportButtonState();
}
/*******************************************************************************
* Encapsulation input
*/
void ImportTextDialog::enableHeaderWidgets(uint encapsulation) {
bool ethertype = false;
bool ipv4_proto = false;
bool ip_address = false;
bool port = false;
bool sctp_tag = false;
bool sctp_ppi = false;
bool export_pdu = false;
bool enable_ethernet_buttons = (encapsulation == WTAP_ENCAP_ETHERNET);
bool enable_ip_buttons = (encapsulation == WTAP_ENCAP_RAW_IP || encapsulation == WTAP_ENCAP_RAW_IP4 || encapsulation == WTAP_ENCAP_RAW_IP6);
bool enable_export_pdu_buttons = (encapsulation == WTAP_ENCAP_WIRESHARK_UPPER_PDU);
if (enable_ethernet_buttons) {
if (ti_ui_->ethernetButton->isChecked()) {
ethertype = true;
on_ethertypeLineEdit_textChanged(ti_ui_->ethertypeLineEdit->text());
}
enable_ip_buttons = true;
}
if (enable_ip_buttons) {
if (ti_ui_->ipv4Button->isChecked()) {
ipv4_proto = true;
ip_address = true;
on_protocolLineEdit_textChanged(ti_ui_->protocolLineEdit->text());
} else if (ti_ui_->udpButton->isChecked() || ti_ui_->tcpButton->isChecked()) {
ip_address = true;
port = true;
on_sourcePortLineEdit_textChanged(ti_ui_->sourcePortLineEdit->text());
on_destinationPortLineEdit_textChanged(ti_ui_->destinationPortLineEdit->text());
} else if (ti_ui_->sctpButton->isChecked()) {
ip_address = true;
port = true;
sctp_tag = true;
on_sourcePortLineEdit_textChanged(ti_ui_->sourcePortLineEdit->text());
on_destinationPortLineEdit_textChanged(ti_ui_->destinationPortLineEdit->text());
on_tagLineEdit_textChanged(ti_ui_->tagLineEdit->text());
}
if (ti_ui_->sctpDataButton->isChecked()) {
ip_address = true;
port = true;
sctp_ppi = true;
on_sourcePortLineEdit_textChanged(ti_ui_->sourcePortLineEdit->text());
on_destinationPortLineEdit_textChanged(ti_ui_->destinationPortLineEdit->text());
on_ppiLineEdit_textChanged(ti_ui_->ppiLineEdit->text());
}
}
if (enable_export_pdu_buttons) {
if (ti_ui_->exportPduButton->isChecked()) {
export_pdu = true;
}
}
foreach (auto &&rb, encap_buttons->buttons()) {
rb->setEnabled(enable_ip_buttons);
}
ti_ui_->ethernetButton->setEnabled(enable_ethernet_buttons);
ti_ui_->exportPduButton->setEnabled(enable_export_pdu_buttons);
ti_ui_->noDummyButton->setEnabled(enable_export_pdu_buttons || enable_ip_buttons);
ti_ui_->ethertypeLabel->setEnabled(ethertype);
ti_ui_->ethertypeLineEdit->setEnabled(ethertype);
ti_ui_->protocolLabel->setEnabled(ipv4_proto);
ti_ui_->protocolLineEdit->setEnabled(ipv4_proto);
ti_ui_->ipVersionLabel->setEnabled(ip_address);
if (encapsulation == WTAP_ENCAP_RAW_IP4) {
ti_ui_->ipVersionComboBox->setEnabled(false);
ti_ui_->ipVersionComboBox->setCurrentIndex(0);
} else if (encapsulation == WTAP_ENCAP_RAW_IP6) {
ti_ui_->ipVersionComboBox->setEnabled(false);
ti_ui_->ipVersionComboBox->setCurrentIndex(1);
} else {
ti_ui_->ipVersionComboBox->setEnabled(ip_address);
}
ti_ui_->sourceAddressLabel->setEnabled(ip_address);
ti_ui_->sourceAddressLineEdit->setEnabled(ip_address);
ti_ui_->destinationAddressLabel->setEnabled(ip_address);
ti_ui_->destinationAddressLineEdit->setEnabled(ip_address);
ti_ui_->sourcePortLabel->setEnabled(port);
ti_ui_->sourcePortLineEdit->setEnabled(port);
ti_ui_->destinationPortLabel->setEnabled(port);
ti_ui_->destinationPortLineEdit->setEnabled(port);
ti_ui_->tagLabel->setEnabled(sctp_tag);
ti_ui_->tagLineEdit->setEnabled(sctp_tag);
ti_ui_->ppiLabel->setEnabled(sctp_ppi);
ti_ui_->ppiLineEdit->setEnabled(sctp_ppi);
ti_ui_->payloadLabel->setEnabled(export_pdu);
ti_ui_->dissectorComboBox->setEnabled(export_pdu);
if (ti_ui_->noDummyButton->isEnabled() && !(encap_buttons->checkedButton()->isEnabled())) {
ti_ui_->noDummyButton->toggle();
}
}
void ImportTextDialog::on_encapComboBox_currentIndexChanged(int index)
{
QVariant val = ti_ui_->encapComboBox->itemData(index);
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
if (val.canConvert<int>())
#else
if (val != QVariant::Invalid)
#endif
{
import_info_.encapsulation = val.toUInt();
} else {
import_info_.encapsulation = WTAP_ENCAP_UNKNOWN;
}
enableHeaderWidgets(import_info_.encapsulation);
}
void ImportTextDialog::encap_buttonsToggled(QAbstractButton *button _U_, bool checked)
{
if (checked) enableHeaderWidgets(import_info_.encapsulation);
}
void ImportTextDialog::on_ipVersionComboBox_currentIndexChanged(int index)
{
import_info_.ipv6 = (index == 1) ? 1 : 0;
on_sourceAddressLineEdit_textChanged(ti_ui_->sourceAddressLineEdit->text());
on_destinationAddressLineEdit_textChanged(ti_ui_->destinationAddressLineEdit->text());
}
void ImportTextDialog::check_line_edit(SyntaxLineEdit *le, bool &ok_enabled, const QString &num_str, int base, guint max_val, bool is_short, guint *val_ptr) {
bool conv_ok;
SyntaxLineEdit::SyntaxState syntax_state = SyntaxLineEdit::Empty;
if (!le || !val_ptr)
return;
ok_enabled = true;
if (num_str.length() < 1) {
*val_ptr = 0;
} else {
if (is_short) {
*val_ptr = num_str.toUShort(&conv_ok, base);
} else {
*val_ptr = (guint)num_str.toULong(&conv_ok, base);
}
if (conv_ok && *val_ptr <= max_val) {
syntax_state = SyntaxLineEdit::Valid;
} else {
syntax_state = SyntaxLineEdit::Invalid;
ok_enabled = false;
}
}
le->setSyntaxState(syntax_state);
updateImportButtonState();
}
void ImportTextDialog::checkAddress(SyntaxLineEdit *le, bool &ok_enabled, const QString &addr_str, ws_in4_addr *val_ptr) {
bool conv_ok;
SyntaxLineEdit::SyntaxState syntax_state = SyntaxLineEdit::Empty;
if (!le || !val_ptr)
return;
ok_enabled = true;
if (addr_str.length() < 1) {
*val_ptr = 0;
} else {
conv_ok = ws_inet_pton4(addr_str.toUtf8().data(), (ws_in4_addr*)val_ptr);
if (conv_ok) {
syntax_state= SyntaxLineEdit::Valid;
} else {
syntax_state = SyntaxLineEdit::Invalid;
ok_enabled = false;
}
}
le->setSyntaxState(syntax_state);
updateImportButtonState();
}
void ImportTextDialog::checkIPv6Address(SyntaxLineEdit *le, bool &ok_enabled, const QString &addr_str, ws_in6_addr *val_ptr) {
bool conv_ok;
SyntaxLineEdit::SyntaxState syntax_state = SyntaxLineEdit::Empty;
if (!le || !val_ptr)
return;
ok_enabled = true;
if (addr_str.length() < 1) {
*val_ptr = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};
} else {
conv_ok = ws_inet_pton6(addr_str.toUtf8().data(), (ws_in6_addr*)val_ptr);
if (conv_ok) {
syntax_state= SyntaxLineEdit::Valid;
} else {
syntax_state = SyntaxLineEdit::Invalid;
ok_enabled = false;
}
}
le->setSyntaxState(syntax_state);
updateImportButtonState();
}
void ImportTextDialog::on_ethertypeLineEdit_textChanged(const QString ðertype_str)
{
check_line_edit(ti_ui_->ethertypeLineEdit, ether_type_ok_, ethertype_str, 16, 0xffff, true, &import_info_.pid);
}
void ImportTextDialog::on_protocolLineEdit_textChanged(const QString &protocol_str)
{
check_line_edit(ti_ui_->protocolLineEdit, proto_ok_, protocol_str, 10, 0xff, true, &import_info_.protocol);
}
void ImportTextDialog::on_sourceAddressLineEdit_textChanged(const QString &source_addr_str)
{
if (ti_ui_->ipVersionComboBox->currentIndex() == 1) {
checkIPv6Address(ti_ui_->sourceAddressLineEdit, source_addr_ok_, source_addr_str, &import_info_.ip_src_addr.ipv6);
} else {
checkAddress(ti_ui_->sourceAddressLineEdit, source_addr_ok_, source_addr_str, &import_info_.ip_src_addr.ipv4);
}
}
void ImportTextDialog::on_destinationAddressLineEdit_textChanged(const QString &destination_addr_str)
{
if (ti_ui_->ipVersionComboBox->currentIndex() == 1) {
checkIPv6Address(ti_ui_->destinationAddressLineEdit, dest_addr_ok_, destination_addr_str, &import_info_.ip_dest_addr.ipv6);
} else {
checkAddress(ti_ui_->destinationAddressLineEdit, dest_addr_ok_, destination_addr_str, &import_info_.ip_dest_addr.ipv4);
}
}
void ImportTextDialog::on_sourcePortLineEdit_textChanged(const QString &source_port_str)
{
check_line_edit(ti_ui_->sourcePortLineEdit, source_port_ok_, source_port_str, 10, 0xffff, true, &import_info_.src_port);
}
void ImportTextDialog::on_destinationPortLineEdit_textChanged(const QString &destination_port_str)
{
check_line_edit(ti_ui_->destinationPortLineEdit, dest_port_ok_, destination_port_str, 10, 0xffff, true, &import_info_.dst_port);
}
void ImportTextDialog::on_tagLineEdit_textChanged(const QString &tag_str)
{
check_line_edit(ti_ui_->tagLineEdit, tag_ok_, tag_str, 10, 0xffffffff, false, &import_info_.tag);
}
void ImportTextDialog::on_ppiLineEdit_textChanged(const QString &ppi_str)
{
check_line_edit(ti_ui_->ppiLineEdit, ppi_ok_, ppi_str, 10, 0xffffffff, false, &import_info_.ppi);
}
/*******************************************************************************
* Footer
*/
void ImportTextDialog::on_maxLengthLineEdit_textChanged(const QString &max_frame_len_str)
{
check_line_edit(ti_ui_->maxLengthLineEdit, max_len_ok_, max_frame_len_str, 10, WTAP_MAX_PACKET_SIZE_STANDARD, true, &import_info_.max_frame_length);
}
void ImportTextDialog::on_buttonBox_helpRequested()
{
mainApp->helpTopicAction(HELP_IMPORT_DIALOG);
} |
C/C++ | wireshark/ui/qt/import_text_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 IMPORT_TEXT_DIALOG_H
#define IMPORT_TEXT_DIALOG_H
#include <config.h>
#include <stdio.h>
#include <glib.h>
#include "ui/text_import.h"
#include <ui/qt/widgets/syntax_line_edit.h>
#include <QDialog>
#include <QPushButton>
#include <QRadioButton>
#include <QButtonGroup>
namespace Ui {
class ImportTextDialog;
}
class ImportTextDialog : public QDialog
{
Q_OBJECT
public:
explicit ImportTextDialog(QWidget *parent = 0);
~ImportTextDialog();
QString &capfileName();
private:
void enableHeaderWidgets(uint encapsulation = WTAP_ENCAP_ETHERNET);
/* regex fields */
void enableFieldWidgets(bool enable_direction_input = true, bool enable_time_input = true);
void check_line_edit(SyntaxLineEdit *le, bool &ok_enable, const QString &num_str, int base, guint max_val, bool is_short, guint *val_ptr);
void checkAddress(SyntaxLineEdit *le, bool &ok_enable, const QString &addr_str, ws_in4_addr *val_ptr);
void checkIPv6Address(SyntaxLineEdit *le, bool &ok_enable, const QString &addr_str, ws_in6_addr *val_ptr);
bool checkDateTimeFormat(const QString &time_format);
void loadSettingsFile();
void saveSettingsFile();
void applyDialogSettings();
void storeDialogSettings();
void updateImportButtonState();
Ui::ImportTextDialog *ti_ui_;
QVariantMap settings;
QPushButton *import_button_;
QButtonGroup *encap_buttons;
text_import_info_t import_info_;
QString capfile_name_;
bool file_ok_;
bool timestamp_format_ok_;
/* Regex input */
bool regex_ok_;
bool re_has_dir_;
bool in_indication_ok_;
bool out_indication_ok_;
bool re_has_time_;
bool ether_type_ok_;
bool proto_ok_;
bool source_addr_ok_;
bool dest_addr_ok_;
bool source_port_ok_;
bool dest_port_ok_;
bool tag_ok_;
bool ppi_ok_;
bool payload_ok_;
bool max_len_ok_;
public slots:
int exec();
private slots:
void on_textFileBrowseButton_clicked();
void on_textFileLineEdit_textChanged(const QString &arg1);
void on_modeTabWidget_currentChanged(int index);
void on_timestampFormatLineEdit_textChanged(const QString &arg1);
/* Hex Dump input */
void on_noOffsetButton_toggled(bool checked);
void on_directionIndicationCheckBox_toggled(bool checked);
void on_asciiIdentificationCheckBox_toggled(bool checked);
/* Regex input */
void on_regexTextEdit_textChanged();
void on_dataEncodingComboBox_currentIndexChanged(int index);
void on_dirInIndicationLineEdit_textChanged(const QString &arg1);
void on_dirOutIndicationLineEdit_textChanged(const QString &arg1);
/* Encapsulation input */
void on_encapComboBox_currentIndexChanged(int index);
void encap_buttonsToggled(QAbstractButton *button, bool checked);
void on_ipVersionComboBox_currentIndexChanged(int index);
void on_ethertypeLineEdit_textChanged(const QString ðertype_str);
void on_protocolLineEdit_textChanged(const QString &protocol_str);
void on_sourceAddressLineEdit_textChanged(const QString &source_addr_str);
void on_destinationAddressLineEdit_textChanged(const QString &destination_addr_str);
void on_sourcePortLineEdit_textChanged(const QString &source_port_str);
void on_destinationPortLineEdit_textChanged(const QString &destination_port_str);
void on_tagLineEdit_textChanged(const QString &tag_str);
void on_ppiLineEdit_textChanged(const QString &ppi_str);
/* Footer input */
void on_maxLengthLineEdit_textChanged(const QString &max_frame_len_str);
void on_buttonBox_helpRequested();
};
#endif // IMPORT_TEXT_DIALOG_H |
User Interface | wireshark/ui/qt/import_text_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ImportTextDialog</class>
<widget class="QDialog" name="ImportTextDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>562</width>
<height>832</height>
</rect>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>1000</height>
</size>
</property>
<property name="sizeGripEnabled">
<bool>true</bool>
</property>
<property name="modal">
<bool>true</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>File:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="textFileLineEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="toolTip">
<string>Set name of text file to import</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="textFileBrowseButton">
<property name="toolTip">
<string>Browse for text file to import</string>
</property>
<property name="text">
<string>Browse…</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QTabWidget" name="modeTabWidget">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<attribute name="title">
<string>Hex Dump</string>
</attribute>
<attribute name="toolTip">
<string>Import a standard hex dump as exported by Wireshark</string>
</attribute>
<layout class="QHBoxLayout" name="horizontalLayout_7">
<item>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<layout class="QGridLayout" name="gridLayout_2">
<property name="verticalSpacing">
<number>1</number>
</property>
<item row="2" column="1">
<widget class="QRadioButton" name="octalOffsetButton">
<property name="toolTip">
<string>Offsets in the text file are in octal notation</string>
</property>
<property name="text">
<string>Octal</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>Offsets:</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QRadioButton" name="hexOffsetButton">
<property name="toolTip">
<string>Offsets in the text file are in hexadecimal notation</string>
</property>
<property name="text">
<string>Hexadecimal</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QRadioButton" name="decimalOffsetButton">
<property name="toolTip">
<string>Offsets in the text file are in decimal notation</string>
</property>
<property name="text">
<string>Decimal</string>
</property>
</widget>
</item>
<item row="0" column="2" rowspan="4">
<spacer name="horizontalSpacer_2">
<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 row="3" column="1">
<widget class="QRadioButton" name="noOffsetButton">
<property name="toolTip">
<string>The text file has no offset</string>
</property>
<property name="text">
<string>None</string>
</property>
</widget>
</item>
<item row="3" column="2">
<widget class="QLabel" name="noOffsetLabel">
<property name="font">
<font>
<italic>false</italic>
</font>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_5" stretch="0,0,0">
<item>
<widget class="QLabel" name="directionIndicationLabel">
<property name="toolTip">
<string>Whether or not the file contains information indicating the direction (inbound or outbound) of the packet.</string>
</property>
<property name="text">
<string>Direction indication:</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="directionIndicationCheckBox">
<property name="toolTip">
<string>Whether or not the file contains information indicating the direction (inbound or outbound) of the packet.</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_5">
<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>
<layout class="QHBoxLayout" name="asciiLayout" stretch="0,0,0">
<item>
<widget class="QLabel" name="asciiIdentificationLabel">
<property name="toolTip">
<string><html><head/><body><p>Whether to do extra processing detecting the start of the ASCII representation at the end of a hex+ASCII line even if it looks like hex bytes.</p><p>Do not enable if the hex dump does not contain ASCII.</p></body></html></string>
</property>
<property name="text">
<string>ASCII identification:</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="asciiIdentificationCheckBox">
<property name="toolTip">
<string><html><head/><body><p>Whether to do extra processing detecting the start of the ASCII representation at the end of a hex+ASCII line even if it looks like hex bytes.</p><p>Do not enable if the hex dump does not contain ASCII.</p></body></html></string>
</property>
</widget>
</item>
<item>
<spacer name="asciiSpacer">
<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>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QWidget" name="tab_2">
<attribute name="title">
<string>Regular Expression</string>
</attribute>
<attribute name="toolTip">
<string>Import a file formatted according to a custom regular expression</string>
</attribute>
<layout class="QHBoxLayout" name="horizontalLayout_10">
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label_6">
<property name="text">
<string>Packet format regular expression</string>
</property>
</widget>
</item>
<item>
<widget class="QTextEdit" name="regexTextEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="sizeIncrement">
<size>
<width>1</width>
<height>1</height>
</size>
</property>
<property name="baseSize">
<size>
<width>100</width>
<height>100</height>
</size>
</property>
<property name="toolTip">
<string><html><head/><body><p>Perl compatible regular expression capturing a single packet in the file with named groups identifieing data to import. Anchors ^ and $ also match before/after newlines </p><p>Required is only a data group, also supported are time, dir and seqno.</p><p>Regex flags: DUPNAMES, MULTILINE and NOEMPTY</p></body></html></string>
</property>
<property name="lineWidth">
<number>24</number>
</property>
<property name="acceptRichText">
<bool>false</bool>
</property>
<property name="placeholderText">
<string notr="true">^(?<dir>(<|>))\s*(?<time>(\d\d\:){2}\d\d)\s+(?<seqno>\d{5})\s+(?<data>[0-9a-fA-F]*)$\s+</string>
</property>
</widget>
</item>
<item>
<widget class="ElidedLabel" name="regexHintLabel">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>This is regexHintLabel, it will be set to default_regex_hint</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_8" stretch="0,0,0,0,0">
<property name="sizeConstraint">
<enum>QLayout::SetDefaultConstraint</enum>
</property>
<item>
<widget class="QLabel" name="label_7">
<property name="text">
<string>Data encoding:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="dataEncodingComboBox">
<property name="toolTip">
<string>How data is encoded</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string><small><i>recommended regex:</small></i></string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="encodingRegexExample">
<property name="text">
<string>encodingRegexExample</string>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_7">
<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>
<layout class="QHBoxLayout" name="horizontalLayout_6" stretch="0,0,0,0">
<item>
<widget class="QLabel" name="dirIndicationLabel">
<property name="toolTip">
<string/>
</property>
<property name="text">
<string>Direction indication:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="dirInIndicationLineEdit">
<property name="baseSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="toolTip">
<string>List of characters indicating incoming packets</string>
</property>
<property name="maxLength">
<number>6</number>
</property>
<property name="placeholderText">
<string>iI<</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="dirOutIndicationLineEdit">
<property name="enabled">
<bool>true</bool>
</property>
<property name="toolTip">
<string>List of characters indicating outgoing packets</string>
</property>
<property name="placeholderText">
<string>oO></string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_6">
<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>
</layout>
</item>
</layout>
</widget>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_9" stretch="0,0,0,0">
<item>
<widget class="QLabel" name="timestampLabel">
<property name="toolTip">
<string>The format in which to parse timestamps in the text file (e.g. %H:%M:%S.). Format specifiers are based on strptime(3)</string>
</property>
<property name="text">
<string>Timestamp format:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="timestampFormatLineEdit">
<property name="toolTip">
<string><html><head/><body><p>The format in which to parse timestamps in the text file (e.g. %H:%M:%S.%f).</p><p>Format specifiers are based on strptime(3) with the addition of %f for second fractions. The precision of %f is determined from its length.</p></body></html></string>
</property>
<property name="placeholderText">
<string>%H:%M:%S.%f</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="timestampExampleLabel">
<property name="text">
<string>timestampExampleLabel</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_8">
<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="QGroupBox" name="groupBox_2">
<property name="title">
<string>Encapsulation</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
<layout class="QFormLayout" name="formLayout">
<property name="fieldGrowthPolicy">
<enum>QFormLayout::FieldsStayAtSizeHint</enum>
</property>
<item row="0" column="0" colspan="2">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label_4">
<property name="text">
<string>Encapsulation Type:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="encapComboBox">
<property name="toolTip">
<string>Encapsulation type of the frames in the import capture file</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_3">
<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="1" column="0" colspan="2">
<layout class="QGridLayout" name="headerGridLayout">
<property name="verticalSpacing">
<number>1</number>
</property>
<item row="0" column="0" colspan="3">
<widget class="QRadioButton" name="noDummyButton">
<property name="toolTip">
<string>Leave frames unchanged</string>
</property>
<property name="text">
<string>No dummy header</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item row="0" column="3" rowspan="8">
<spacer name="horizontalSpacer_4">
<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 row="1" column="0">
<widget class="QRadioButton" name="ethernetButton">
<property name="toolTip">
<string>Prefix each frame with an Ethernet header</string>
</property>
<property name="text">
<string>Ethernet</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QRadioButton" name="ipv4Button">
<property name="toolTip">
<string>Prefix each frame with an Ethernet and IP header</string>
</property>
<property name="text">
<string>IP</string>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QRadioButton" name="udpButton">
<property name="toolTip">
<string>Prefix each frame with an Ethernet, IP and UDP header</string>
</property>
<property name="text">
<string>UDP</string>
</property>
</widget>
</item>
<item row="6" column="0">
<widget class="QRadioButton" name="tcpButton">
<property name="toolTip">
<string>Prefix each frame with an Ethernet, IP and TCP header</string>
</property>
<property name="text">
<string>TCP</string>
</property>
</widget>
</item>
<item row="7" column="0">
<widget class="QRadioButton" name="sctpButton">
<property name="toolTip">
<string>Prefix each frame with an Ethernet, IP and SCTP header</string>
</property>
<property name="text">
<string>SCTP</string>
</property>
</widget>
</item>
<item row="8" column="0">
<widget class="QRadioButton" name="sctpDataButton">
<property name="toolTip">
<string>Prefix each frame with an Ethernet, IP and SCTP (DATA) header</string>
</property>
<property name="text">
<string>SCTP (Data)</string>
</property>
</widget>
</item>
<item row="9" column="0">
<widget class="QRadioButton" name="exportPduButton">
<property name="text">
<string>ExportPDU</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLabel" name="ethertypeLabel">
<property name="text">
<string>Ethertype (hex):</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLabel" name="protocolLabel">
<property name="text">
<string>Protocol (dec):</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QLabel" name="sourceAddressLabel">
<property name="text">
<string>Source address:</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QLabel" name="destinationAddressLabel">
<property name="text">
<string>Destination address:</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QLabel" name="sourcePortLabel">
<property name="text">
<string>Source port:</string>
</property>
</widget>
</item>
<item row="6" column="1">
<widget class="QLabel" name="destinationPortLabel">
<property name="text">
<string>Destination port:</string>
</property>
</widget>
</item>
<item row="7" column="1">
<widget class="QLabel" name="tagLabel">
<property name="text">
<string>Tag:</string>
</property>
</widget>
</item>
<item row="8" column="1">
<widget class="QLabel" name="ppiLabel">
<property name="text">
<string>PPI:</string>
</property>
</widget>
</item>
<item row="9" column="1">
<widget class="QLabel" name="payloadLabel">
<property name="text">
<string>Dissector</string>
</property>
</widget>
</item>
<item row="1" column="2">
<widget class="SyntaxLineEdit" name="ethertypeLineEdit">
<property name="toolTip">
<string>The Ethertype value of each frame</string>
</property>
<property name="cursorPosition">
<number>0</number>
</property>
</widget>
</item>
<item row="2" column="2">
<widget class="SyntaxLineEdit" name="protocolLineEdit">
<property name="toolTip">
<string>The IP protocol ID for each frame</string>
</property>
</widget>
</item>
<item row="3" column="2" colspan="3">
<widget class="SyntaxLineEdit" name="sourceAddressLineEdit">
<property name="toolTip">
<string>The IP source address for each frame</string>
</property>
</widget>
</item>
<item row="4" column="2" colspan="3">
<widget class="SyntaxLineEdit" name="destinationAddressLineEdit">
<property name="toolTip">
<string>The IP destination address for each frame</string>
</property>
</widget>
</item>
<item row="5" column="2">
<widget class="SyntaxLineEdit" name="sourcePortLineEdit">
<property name="toolTip">
<string>The UDP, TCP or SCTP source port for each frame</string>
</property>
</widget>
</item>
<item row="6" column="2">
<widget class="SyntaxLineEdit" name="destinationPortLineEdit">
<property name="toolTip">
<string>The UDP, TCP or SCTP destination port for each frame</string>
</property>
</widget>
</item>
<item row="7" column="2">
<widget class="SyntaxLineEdit" name="tagLineEdit">
<property name="toolTip">
<string>The SCTP verification tag for each frame</string>
</property>
</widget>
</item>
<item row="8" column="2">
<widget class="SyntaxLineEdit" name="ppiLineEdit">
<property name="toolTip">
<string>The SCTP DATA payload protocol identifier for each frame</string>
</property>
</widget>
</item>
<item row="9" column="2" colspan="3">
<widget class="QComboBox" name="dissectorComboBox">
<property name="toolTip">
<string>The dissector to use for each frame</string>
</property>
</widget>
</item>
<item row="2" column="3">
<widget class="QLabel" name="ipVersionLabel">
<property name="text">
<string>IP version:</string>
</property>
</widget>
</item>
<item row="2" column="4">
<widget class="QComboBox" name="ipVersionComboBox">
<property name="toolTip">
<string>The IP Version to use for the dummy IP header</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="interfaceLayout">
<item>
<widget class="QLabel" name="interfaceLabel">
<property name="text">
<string>Interface name:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="interfaceLineEdit">
<property name="toolTip">
<string>The name of the interface to write to the import capture file</string>
</property>
<property name="placeholderText">
<string>Fake IF, Import from Hex Dump</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="maxLengthLayout">
<item>
<widget class="QLabel" name="maxLengthLabel">
<property name="text">
<string>Maximum frame length:</string>
</property>
</widget>
</item>
<item>
<widget class="SyntaxLineEdit" name="maxLengthLineEdit">
<property name="toolTip">
<string>The maximum size of the frames to write to the import capture file (max 256kiB)</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</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::Open</set>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>ElidedLabel</class>
<extends>QLabel</extends>
<header>widgets/elided_label.h</header>
</customwidget>
<customwidget>
<class>SyntaxLineEdit</class>
<extends>QLineEdit</extends>
<header>widgets/syntax_line_edit.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>ImportTextDialog</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>ImportTextDialog</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/interface_frame.cpp | /* interface_frame.cpp
* Display of interfaces, including their respective data, and the
* capability to filter interfaces by type
*
* 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_interface_frame.h>
#include "capture/capture_ifinfo.h"
#ifdef Q_OS_WIN
#include "capture/capture-wpcap.h"
#endif
#include "ui/qt/interface_frame.h"
#include <ui/qt/simple_dialog.h>
#include <ui/qt/main_application.h>
#include <ui/qt/models/interface_tree_model.h>
#include <ui/qt/models/sparkline_delegate.h>
#include <ui/qt/utils/color_utils.h>
#include "extcap.h"
#include <ui/recent.h>
#include "capture_opts.h"
#include "ui/capture_globals.h"
#include <wsutil/utf8_entities.h>
#include <QDesktopServices>
#include <QFrame>
#include <QHBoxLayout>
#include <QItemSelection>
#include <QLabel>
#include <QPushButton>
#include <QUrl>
#include <epan/prefs.h>
#define BTN_IFTYPE_PROPERTY "ifType"
#ifdef HAVE_LIBPCAP
const int stat_update_interval_ = 1000; // ms
#endif
const char *no_capture_link = "#no_capture";
InterfaceFrame::InterfaceFrame(QWidget * parent)
: QFrame(parent),
ui(new Ui::InterfaceFrame)
, proxy_model_(Q_NULLPTR)
, source_model_(Q_NULLPTR)
, info_model_(this)
#ifdef HAVE_LIBPCAP
,stat_timer_(NULL)
#endif // HAVE_LIBPCAP
{
ui->setupUi(this);
setStyleSheet(QString(
"QFrame {"
" border: 0;"
"}"
"QTreeView {"
" border: 0;"
"}"
));
ui->warningLabel->hide();
#ifdef Q_OS_MAC
ui->interfaceTree->setAttribute(Qt::WA_MacShowFocusRect, false);
#endif
/* TODO: There must be a better way to do this */
ifTypeDescription.insert(IF_WIRED, tr("Wired"));
ifTypeDescription.insert(IF_AIRPCAP, tr("AirPCAP"));
ifTypeDescription.insert(IF_PIPE, tr("Pipe"));
ifTypeDescription.insert(IF_STDIN, tr("STDIN"));
ifTypeDescription.insert(IF_BLUETOOTH, tr("Bluetooth"));
ifTypeDescription.insert(IF_WIRELESS, tr("Wireless"));
ifTypeDescription.insert(IF_DIALUP, tr("Dial-Up"));
ifTypeDescription.insert(IF_USB, tr("USB"));
ifTypeDescription.insert(IF_EXTCAP, tr("External Capture"));
ifTypeDescription.insert(IF_VIRTUAL, tr ("Virtual"));
QList<InterfaceTreeColumns> columns;
columns.append(IFTREE_COL_EXTCAP);
columns.append(IFTREE_COL_DISPLAY_NAME);
columns.append(IFTREE_COL_STATS);
proxy_model_.setColumns(columns);
proxy_model_.setStoreOnChange(true);
proxy_model_.setSortByActivity(true);
proxy_model_.setSourceModel(&source_model_);
info_model_.setSourceModel(&proxy_model_);
info_model_.setColumn(static_cast<int>(columns.indexOf(IFTREE_COL_STATS)));
ui->interfaceTree->setModel(&info_model_);
ui->interfaceTree->setSortingEnabled(true);
ui->interfaceTree->setItemDelegateForColumn(proxy_model_.mapSourceToColumn(IFTREE_COL_STATS), new SparkLineDelegate(this));
ui->interfaceTree->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->interfaceTree, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint)));
connect(mainApp, SIGNAL(appInitialized()), this, SLOT(interfaceListChanged()));
connect(mainApp, SIGNAL(localInterfaceListChanged()), this, SLOT(interfaceListChanged()));
connect(ui->interfaceTree->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
this, SLOT(interfaceTreeSelectionChanged(const QItemSelection &, const QItemSelection &)));
}
InterfaceFrame::~InterfaceFrame()
{
delete ui;
}
QMenu * InterfaceFrame::getSelectionMenu()
{
QMenu * contextMenu = new QMenu(this);
QList<int> typesDisplayed = proxy_model_.typesDisplayed();
QMap<int, QString>::const_iterator it = ifTypeDescription.constBegin();
while (it != ifTypeDescription.constEnd())
{
int ifType = it.key();
if (typesDisplayed.contains(ifType))
{
QAction *endp_action = new QAction(it.value(), this);
endp_action->setData(QVariant::fromValue(ifType));
endp_action->setCheckable(true);
endp_action->setChecked(proxy_model_.isInterfaceTypeShown(ifType));
connect(endp_action, SIGNAL(triggered()), this, SLOT(triggeredIfTypeButton()));
contextMenu->addAction(endp_action);
}
++it;
}
#ifdef HAVE_PCAP_REMOTE
if (proxy_model_.remoteInterfacesExist())
{
QAction * toggleRemoteAction = new QAction(tr("Remote interfaces"), this);
toggleRemoteAction->setCheckable(true);
toggleRemoteAction->setChecked(proxy_model_.remoteDisplay());
connect(toggleRemoteAction, SIGNAL(triggered()), this, SLOT(toggleRemoteInterfaces()));
contextMenu->addAction(toggleRemoteAction);
}
#endif
contextMenu->addSeparator();
QAction * toggleHideAction = new QAction(tr("Show hidden interfaces"), this);
toggleHideAction->setCheckable(true);
toggleHideAction->setChecked(! proxy_model_.filterHidden());
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHiddenInterfaces()));
contextMenu->addAction(toggleHideAction);
return contextMenu;
}
int InterfaceFrame::interfacesHidden()
{
return proxy_model_.interfacesHidden();
}
int InterfaceFrame::interfacesPresent()
{
return source_model_.rowCount() - proxy_model_.interfacesHidden();
}
void InterfaceFrame::ensureSelectedInterface()
{
#ifdef HAVE_LIBPCAP
if (interfacesPresent() < 1) return;
if (source_model_.selectedDevices().count() < 1) {
QModelIndex first_idx = info_model_.mapFromSource(proxy_model_.index(0, 0));
ui->interfaceTree->setCurrentIndex(first_idx);
}
ui->interfaceTree->setFocus();
#endif
}
void InterfaceFrame::hideEvent(QHideEvent *) {
#ifdef HAVE_LIBPCAP
if (stat_timer_)
stat_timer_->stop();
source_model_.stopStatistic();
#endif // HAVE_LIBPCAP
}
void InterfaceFrame::showEvent(QShowEvent *) {
#ifdef HAVE_LIBPCAP
if (stat_timer_)
stat_timer_->start(stat_update_interval_);
#endif // HAVE_LIBPCAP
}
void InterfaceFrame::actionButton_toggled(bool checked)
{
QVariant ifType = sender()->property(BTN_IFTYPE_PROPERTY);
if (ifType.isValid())
{
proxy_model_.setInterfaceTypeVisible(ifType.toInt(), checked);
}
resetInterfaceTreeDisplay();
}
void InterfaceFrame::triggeredIfTypeButton()
{
QAction *sender = qobject_cast<QAction *>(QObject::sender());
if (sender)
{
int ifType = sender->data().value<int>();
proxy_model_.toggleTypeVisibility(ifType);
resetInterfaceTreeDisplay();
emit typeSelectionChanged();
}
}
void InterfaceFrame::interfaceListChanged()
{
info_model_.clearInfos();
if (prefs.capture_no_extcap)
info_model_.appendInfo(tr("External capture interfaces disabled."));
resetInterfaceTreeDisplay();
// Ensure that device selection is consistent with the displayed selection.
updateSelectedInterfaces();
#ifdef HAVE_LIBPCAP
if (!stat_timer_) {
updateStatistics();
stat_timer_ = new QTimer(this);
connect(stat_timer_, SIGNAL(timeout()), this, SLOT(updateStatistics()));
stat_timer_->start(stat_update_interval_);
}
#endif
}
void InterfaceFrame::toggleHiddenInterfaces()
{
source_model_.interfaceListChanged();
proxy_model_.toggleFilterHidden();
emit typeSelectionChanged();
}
#ifdef HAVE_PCAP_REMOTE
void InterfaceFrame::toggleRemoteInterfaces()
{
proxy_model_.toggleRemoteDisplay();
emit typeSelectionChanged();
}
#endif
void InterfaceFrame::resetInterfaceTreeDisplay()
{
ui->warningLabel->hide();
ui->warningLabel->clear();
ui->warningLabel->setStyleSheet(QString(
"QLabel {"
" border-radius: 0.5em;"
" padding: 0.33em;"
" margin-bottom: 0.25em;"
// We might want to transition this to normal colors this after a timeout.
" background-color: %2;"
"}"
).arg(ColorUtils::warningBackground().name()));
#ifdef HAVE_LIBPCAP
#ifdef Q_OS_WIN
if (!has_wpcap) {
ui->warningLabel->setText(tr(
"<p>"
"Local interfaces are unavailable because no packet capture driver is installed."
"</p><p>"
"You can fix this by installing <a href=\"https://npcap.com/\">Npcap</a>."
"</p>"));
} else if (!npf_sys_is_running()) {
ui->warningLabel->setText(tr(
"<p>"
"Local interfaces are unavailable because the packet capture driver isn't loaded."
"</p><p>"
"You can fix this by running <pre>net start npcap</pre> if you have Npcap installed"
" or <pre>net start npf</pre> if you have WinPcap installed."
" Both commands must be run as Administrator."
"</p>"));
}
#endif
if (!haveLocalCapturePermissions())
{
#ifdef Q_OS_MAC
//
// NOTE: if you change this text, you must also change the
// definition of PLATFORM_PERMISSIONS_SUGGESTION that is
// used if __APPLE__ is defined, so that it reflects the
// new message text.
//
QString install_chmodbpf_path = mainApp->applicationDirPath() + "/../Resources/Extras/Install ChmodBPF.pkg";
ui->warningLabel->setText(tr(
"<p>"
"You don't have permission to capture on local interfaces."
"</p><p>"
"You can fix this by <a href=\"file://%1\">installing ChmodBPF</a>."
"</p>")
.arg(install_chmodbpf_path));
#else
//
// XXX - should this give similar platform-dependent recommendations,
// just as dumpcap gives platform-dependent recommendations in its
// PLATFORM_PERMISSIONS_SUGGESTION #define?
//
ui->warningLabel->setText(tr("You don't have permission to capture on local interfaces."));
#endif
}
if (proxy_model_.rowCount() == 0)
{
ui->warningLabel->setText(tr("No interfaces found."));
ui->warningLabel->setText(proxy_model_.interfaceError());
if (prefs.capture_no_interface_load) {
ui->warningLabel->setText(tr("Interfaces not loaded (due to preference). Go to Capture " UTF8_RIGHTWARDS_ARROW " Refresh Interfaces to load."));
}
}
// XXX Should we have a separate recent pref for each message?
if (!ui->warningLabel->text().isEmpty() && recent.sys_warn_if_no_capture)
{
QString warning_text = ui->warningLabel->text();
warning_text.append(QString("<p><a href=\"%1\">%2</a></p>")
.arg(no_capture_link)
.arg(SimpleDialog::dontShowThisAgain()));
ui->warningLabel->setText(warning_text);
ui->warningLabel->show();
}
#endif // HAVE_LIBPCAP
if (proxy_model_.rowCount() > 0)
{
ui->interfaceTree->show();
ui->interfaceTree->resizeColumnToContents(proxy_model_.mapSourceToColumn(IFTREE_COL_EXTCAP));
ui->interfaceTree->resizeColumnToContents(proxy_model_.mapSourceToColumn(IFTREE_COL_DISPLAY_NAME));
ui->interfaceTree->resizeColumnToContents(proxy_model_.mapSourceToColumn(IFTREE_COL_STATS));
}
else
{
ui->interfaceTree->hide();
}
}
// XXX Should this be in capture/capture-pcap-util.[ch]?
bool InterfaceFrame::haveLocalCapturePermissions() const
{
#ifdef Q_OS_MAC
QFileInfo bpf0_fi = QFileInfo("/dev/bpf0");
return bpf0_fi.isReadable() && bpf0_fi.isWritable();
#else
// XXX Add checks for other platforms.
return true;
#endif
}
void InterfaceFrame::updateSelectedInterfaces()
{
if (source_model_.rowCount() == 0)
return;
#ifdef HAVE_LIBPCAP
QItemSelection sourceSelection = source_model_.selectedDevices();
QItemSelection mySelection = info_model_.mapSelectionFromSource(proxy_model_.mapSelectionFromSource(sourceSelection));
ui->interfaceTree->selectionModel()->clearSelection();
ui->interfaceTree->selectionModel()->select(mySelection, QItemSelectionModel::SelectCurrent);
#endif
}
void InterfaceFrame::interfaceTreeSelectionChanged(const QItemSelection & selected, const QItemSelection & deselected)
{
if (selected.count() == 0 && deselected.count() == 0)
return;
if (source_model_.rowCount() == 0)
return;
#ifdef HAVE_LIBPCAP
/* Take all selected interfaces, not just the newly ones */
QItemSelection allSelected = ui->interfaceTree->selectionModel()->selection();
QItemSelection sourceSelection = proxy_model_.mapSelectionToSource(info_model_.mapSelectionToSource(allSelected));
if (source_model_.updateSelectedDevices(sourceSelection))
emit itemSelectionChanged();
#endif
}
void InterfaceFrame::on_interfaceTree_doubleClicked(const QModelIndex &index)
{
QModelIndex realIndex = proxy_model_.mapToSource(info_model_.mapToSource(index));
if (! realIndex.isValid())
return;
QStringList interfaces;
#ifdef HAVE_LIBPCAP
QString device_name = source_model_.getColumnContent(realIndex.row(), IFTREE_COL_NAME).toString();
QString extcap_string = source_model_.getColumnContent(realIndex.row(), IFTREE_COL_EXTCAP_PATH).toString();
interfaces << device_name;
/* We trust the string here. If this interface is really extcap, the string is
* being checked immediatly before the dialog is being generated */
if (extcap_string.length() > 0)
{
/* this checks if configuration is required and not yet provided or saved via prefs */
if (extcap_requires_configuration((const char *)(device_name.toStdString().c_str())))
{
emit showExtcapOptions(device_name, true);
return;
}
}
#endif
// Start capture for all columns except the first one with extcap
if (IFTREE_COL_EXTCAP != realIndex.column()) {
startCapture(interfaces);
}
}
#ifdef HAVE_LIBPCAP
void InterfaceFrame::on_interfaceTree_clicked(const QModelIndex &index)
{
if (index.column() == 0)
{
QModelIndex realIndex = proxy_model_.mapToSource(info_model_.mapToSource(index));
if (! realIndex.isValid())
return;
QString device_name = source_model_.getColumnContent(realIndex.row(), IFTREE_COL_NAME).toString();
QString extcap_string = source_model_.getColumnContent(realIndex.row(), IFTREE_COL_EXTCAP_PATH).toString();
/* We trust the string here. If this interface is really extcap, the string is
* being checked immediatly before the dialog is being generated */
if (extcap_string.length() > 0)
{
/* this checks if configuration is required and not yet provided or saved via prefs */
if (extcap_has_configuration((const char *)(device_name.toStdString().c_str())))
{
emit showExtcapOptions(device_name, false);
return;
}
}
}
}
#endif
void InterfaceFrame::updateStatistics(void)
{
if (source_model_.rowCount() == 0)
return;
#ifdef HAVE_LIBPCAP
for (int idx = 0; idx < source_model_.rowCount(); idx++)
{
QModelIndex selectIndex = info_model_.mapFromSource(proxy_model_.mapFromSource(source_model_.index(idx, 0)));
/* Proxy model has not masked out the interface */
if (selectIndex.isValid())
source_model_.updateStatistic(idx);
}
#endif
}
void InterfaceFrame::showRunOnFile(void)
{
ui->warningLabel->setText("Interfaces not loaded on startup (run on capture file). Go to Capture -> Refresh Interfaces to load.");
}
void InterfaceFrame::showContextMenu(QPoint pos)
{
QMenu * ctx_menu = new QMenu(this);
ctx_menu->setAttribute(Qt::WA_DeleteOnClose);
ctx_menu->addAction(tr("Start capture"), this, [=] () {
QStringList ifaces;
QModelIndexList selIndices = ui->interfaceTree->selectionModel()->selectedIndexes();
foreach(QModelIndex idx, selIndices)
{
QModelIndex realIndex = proxy_model_.mapToSource(info_model_.mapToSource(idx));
if (realIndex.column() != IFTREE_COL_NAME)
realIndex = realIndex.sibling(realIndex.row(), IFTREE_COL_NAME);
QString name = realIndex.data(Qt::DisplayRole).toString();
if (! ifaces.contains(name))
ifaces << name;
}
startCapture(ifaces);
});
ctx_menu->addSeparator();
QModelIndex actIndex = ui->interfaceTree->indexAt(pos);
QModelIndex realIndex = proxy_model_.mapToSource(info_model_.mapToSource(actIndex));
bool isHidden = realIndex.sibling(realIndex.row(), IFTREE_COL_HIDDEN).data(Qt::UserRole).toBool();
QAction * hideAction = ctx_menu->addAction(tr("Hide Interface"), this, [=] () {
/* Attention! Only realIndex.row is a 1:1 correlation to all_ifaces */
interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, realIndex.row());
device->hidden = ! device->hidden;
mainApp->emitAppSignal(MainApplication::LocalInterfacesChanged);
});
hideAction->setCheckable(true);
hideAction->setChecked(isHidden);
ctx_menu->popup(ui->interfaceTree->mapToGlobal(pos));
}
void InterfaceFrame::on_warningLabel_linkActivated(const QString &link)
{
if (link.compare(no_capture_link) == 0) {
recent.sys_warn_if_no_capture = FALSE;
resetInterfaceTreeDisplay();
} else {
QDesktopServices::openUrl(QUrl(link));
}
} |
C/C++ | wireshark/ui/qt/interface_frame.h | /** @file
*
* Display of interfaces, including their respective data, and the
* capability to filter interfaces by type
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef INTERFACE_FRAME_H
#define INTERFACE_FRAME_H
#include <config.h>
#include <glib.h>
#include <ui/qt/models/info_proxy_model.h>
#include <ui/qt/models/interface_tree_model.h>
#include <ui/qt/models/interface_sort_filter_model.h>
#include <QFrame>
#include <QHBoxLayout>
#include <QAbstractButton>
#include <QTimer>
#include <QMenu>
#include <QPushButton>
namespace Ui {
class InterfaceFrame;
}
class InterfaceFrame : public QFrame
{
Q_OBJECT
public:
explicit InterfaceFrame(QWidget *parent = 0);
~InterfaceFrame();
int interfacesHidden();
QMenu * getSelectionMenu();
int interfacesPresent();
void ensureSelectedInterface();
Q_SIGNALS:
void showExtcapOptions(QString device_name, bool startCaptureOnClose);
void startCapture(QStringList);
void itemSelectionChanged();
void typeSelectionChanged();
public slots:
void updateSelectedInterfaces();
void interfaceListChanged();
void toggleHiddenInterfaces();
#ifdef HAVE_PCAP_REMOTE
void toggleRemoteInterfaces();
#endif
void showRunOnFile();
void showContextMenu(QPoint pos);
protected:
void hideEvent(QHideEvent *evt);
void showEvent(QShowEvent *evt);
private:
void resetInterfaceTreeDisplay();
bool haveLocalCapturePermissions() const;
Ui::InterfaceFrame *ui;
InterfaceSortFilterModel proxy_model_;
InterfaceTreeModel source_model_;
InfoProxyModel info_model_;
QMap<int, QString> ifTypeDescription;
#ifdef HAVE_LIBPCAP
QTimer *stat_timer_;
#endif // HAVE_LIBPCAP
private slots:
void interfaceTreeSelectionChanged(const QItemSelection & selected, const QItemSelection & deselected);
void on_interfaceTree_doubleClicked(const QModelIndex &index);
#ifdef HAVE_LIBPCAP
void on_interfaceTree_clicked(const QModelIndex &index);
#endif
void updateStatistics(void);
void actionButton_toggled(bool checked);
void triggeredIfTypeButton();
void on_warningLabel_linkActivated(const QString &link);
};
#endif // INTERFACE_FRAME_H |
User Interface | wireshark/ui/qt/interface_frame.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>InterfaceFrame</class>
<widget class="QFrame" name="InterfaceFrame">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>256</width>
<height>209</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Frame</string>
</property>
<property name="lineWidth">
<number>0</number>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="spacing">
<number>1</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="warningLabel">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string/>
</property>
<property name="textFormat">
<enum>Qt::RichText</enum>
</property>
<property name="alignment">
<set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::TextBrowserInteraction</set>
</property>
</widget>
</item>
<item>
<widget class="QTreeView" name="interfaceTree">
<property name="selectionMode">
<enum>QAbstractItemView::ExtendedSelection</enum>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="headerHidden">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui> |
C++ | wireshark/ui/qt/interface_toolbar.cpp | /* interface_toolbar.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 <errno.h>
#include <ws_diag_control.h>
#if WS_IS_AT_LEAST_GNUC_VERSION(12,1)
DIAG_OFF(stringop-overflow)
#if WS_IS_AT_LEAST_GNUC_VERSION(13,0)
DIAG_OFF(restrict)
#endif
#endif
#include "interface_toolbar.h"
#if WS_IS_AT_LEAST_GNUC_VERSION(12,1)
DIAG_ON(stringop-overflow)
#if WS_IS_AT_LEAST_GNUC_VERSION(13,0)
DIAG_ON(restrict)
#endif
#endif
#include <ui/qt/widgets/interface_toolbar_lineedit.h>
#include "simple_dialog.h"
#include "main_application.h"
#include <ui_interface_toolbar.h>
#include "capture_opts.h"
#include "ui/capture_globals.h"
#include "sync_pipe.h"
#include "wsutil/file_util.h"
#ifdef _WIN32
#include <wsutil/win32-utils.h>
#endif
#include <QCheckBox>
#include <QComboBox>
#include <QDesktopServices>
#include <QLineEdit>
#include <QPushButton>
#include <QThread>
#include <QUrl>
static const char *interface_type_property = "control_type";
static const char *interface_role_property = "control_role";
// From interface control protocol.
enum InterfaceControlCommand {
commandControlInitialized = 0,
commandControlSet = 1,
commandControlAdd = 2,
commandControlRemove = 3,
commandControlEnable = 4,
commandControlDisable = 5,
commandStatusMessage = 6,
commandInformationMessage = 7,
commandWarningMessage = 8,
commandErrorMessage = 9
};
// To do:
// - Move control pipe handling to extcap
InterfaceToolbar::InterfaceToolbar(QWidget *parent, const iface_toolbar *toolbar) :
QFrame(parent),
ui(new Ui::InterfaceToolbar),
help_link_(toolbar->help),
use_spacer_(true)
{
ui->setupUi(this);
// Fill inn interfaces list and initialize default interface values
for (GList *walker = toolbar->ifnames; walker; walker = walker->next)
{
QString ifname((gchar *)walker->data);
interface_[ifname].reader_thread = NULL;
interface_[ifname].out_fd = -1;
}
initializeControls(toolbar);
#ifdef Q_OS_MAC
foreach (QWidget *w, findChildren<QWidget *>())
{
w->setAttribute(Qt::WA_MacSmallSize, true);
}
#endif
if (!use_spacer_)
{
ui->horizontalSpacer->changeSize(0,0, QSizePolicy::Fixed, QSizePolicy::Fixed);
}
updateWidgets();
}
InterfaceToolbar::~InterfaceToolbar()
{
foreach (QString ifname, interface_.keys())
{
foreach (int num, control_widget_.keys())
{
if (interface_[ifname].log_dialog.contains(num))
{
interface_[ifname].log_dialog[num]->close();
}
}
}
delete ui;
}
void InterfaceToolbar::initializeControls(const iface_toolbar *toolbar)
{
for (GList *walker = toolbar->controls; walker; walker = walker->next)
{
iface_toolbar_control *control = (iface_toolbar_control *)walker->data;
if (control_widget_.contains(control->num))
{
// Already have a widget with this number
continue;
}
QWidget *widget = NULL;
switch (control->ctrl_type)
{
case INTERFACE_TYPE_BOOLEAN:
widget = createCheckbox(control);
break;
case INTERFACE_TYPE_BUTTON:
widget = createButton(control);
break;
case INTERFACE_TYPE_SELECTOR:
widget = createSelector(control);
break;
case INTERFACE_TYPE_STRING:
widget = createString(control);
break;
default:
// Not supported
break;
}
if (widget)
{
widget->setProperty(interface_type_property, control->ctrl_type);
widget->setProperty(interface_role_property, control->ctrl_role);
control_widget_[control->num] = widget;
}
}
}
void InterfaceToolbar::setDefaultValue(int num, const QByteArray &value)
{
foreach (QString ifname, interface_.keys())
{
// Adding default value to all interfaces
interface_[ifname].value[num] = value;
}
default_value_[num] = value;
}
QWidget *InterfaceToolbar::createCheckbox(iface_toolbar_control *control)
{
QCheckBox *checkbox = new QCheckBox(QString().fromUtf8(control->display));
checkbox->setToolTip(QString().fromUtf8(control->tooltip));
if (control->default_value.boolean)
{
checkbox->setCheckState(Qt::Checked);
QByteArray default_value(1, 1);
setDefaultValue(control->num, default_value);
}
connect(checkbox, SIGNAL(stateChanged(int)), this, SLOT(onCheckBoxChanged(int)));
ui->leftLayout->addWidget(checkbox);
return checkbox;
}
QWidget *InterfaceToolbar::createButton(iface_toolbar_control *control)
{
QPushButton *button = new QPushButton(QString().fromUtf8((gchar *)control->display));
button->setMaximumHeight(27);
button->setToolTip(QString().fromUtf8(control->tooltip));
switch (control->ctrl_role)
{
case INTERFACE_ROLE_CONTROL:
setDefaultValue(control->num, (gchar *)control->display);
connect(button, SIGNAL(clicked()), this, SLOT(onControlButtonClicked()));
break;
case INTERFACE_ROLE_HELP:
connect(button, SIGNAL(clicked()), this, SLOT(onHelpButtonClicked()));
if (help_link_.isEmpty())
{
// No help URL provided
button->hide();
}
break;
case INTERFACE_ROLE_LOGGER:
connect(button, SIGNAL(clicked()), this, SLOT(onLogButtonClicked()));
break;
case INTERFACE_ROLE_RESTORE:
connect(button, SIGNAL(clicked()), this, SLOT(onRestoreButtonClicked()));
break;
default:
// Not supported
break;
}
ui->rightLayout->addWidget(button);
return button;
}
QWidget *InterfaceToolbar::createSelector(iface_toolbar_control *control)
{
QLabel *label = new QLabel(QString().fromUtf8(control->display));
label->setToolTip(QString().fromUtf8(control->tooltip));
QComboBox *combobox = new QComboBox();
combobox->setToolTip(QString().fromUtf8(control->tooltip));
combobox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
for (GList *walker = control->values; walker; walker = walker->next)
{
iface_toolbar_value *val = (iface_toolbar_value *)walker->data;
QString value = QString().fromUtf8((gchar *)val->value);
if (value.isEmpty())
{
// Invalid value
continue;
}
QString display = QString().fromUtf8((gchar *)val->display);
QByteArray interface_value;
interface_value.append(value.toUtf8());
if (display.isEmpty())
{
display = value;
}
else
{
interface_value.append(QString('\0' + display).toUtf8());
}
combobox->addItem(display, value);
if (val->is_default)
{
combobox->setCurrentText(display);
setDefaultValue(control->num, value.toUtf8());
}
foreach (QString ifname, interface_.keys())
{
// Adding values to all interfaces
interface_[ifname].list[control->num].append(interface_value);
}
default_list_[control->num].append(interface_value);
}
connect(combobox, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxChanged(int)));
ui->leftLayout->addWidget(label);
ui->leftLayout->addWidget(combobox);
label_widget_[control->num] = label;
return combobox;
}
QWidget *InterfaceToolbar::createString(iface_toolbar_control *control)
{
QLabel *label = new QLabel(QString().fromUtf8(control->display));
label->setToolTip(QString().fromUtf8(control->tooltip));
InterfaceToolbarLineEdit *lineedit = new InterfaceToolbarLineEdit(NULL, control->validation, control->is_required);
lineedit->setToolTip(QString().fromUtf8(control->tooltip));
lineedit->setPlaceholderText(QString().fromUtf8(control->placeholder));
if (control->default_value.string)
{
lineedit->setText(QString().fromUtf8(control->default_value.string));
setDefaultValue(control->num, control->default_value.string);
}
connect(lineedit, SIGNAL(editedTextApplied()), this, SLOT(onLineEditChanged()));
ui->leftLayout->addWidget(label);
ui->leftLayout->addWidget(lineedit);
label_widget_[control->num] = label;
use_spacer_ = false;
return lineedit;
}
void InterfaceToolbar::setWidgetValue(QWidget *widget, int command, QByteArray payload)
{
if (QComboBox *combobox = qobject_cast<QComboBox *>(widget))
{
combobox->blockSignals(true);
switch (command)
{
case commandControlSet:
{
int idx = combobox->findData(payload);
if (idx != -1)
{
combobox->setCurrentIndex(idx);
}
break;
}
case commandControlAdd:
{
QString value;
QString display;
if (payload.contains('\0'))
{
// The payload contains "value\0display"
QList<QByteArray> values = payload.split('\0');
value = values[0];
display = values[1];
}
else
{
value = display = payload;
}
int idx = combobox->findData(value);
if (idx != -1)
{
// The value already exists, update item text
combobox->setItemText(idx, display);
}
else
{
combobox->addItem(display, value);
}
break;
}
case commandControlRemove:
{
if (payload.size() == 0)
{
combobox->clear();
}
else
{
int idx = combobox->findData(payload);
if (idx != -1)
{
combobox->removeItem(idx);
}
}
break;
}
default:
break;
}
combobox->blockSignals(false);
}
else if (InterfaceToolbarLineEdit *lineedit = qobject_cast<InterfaceToolbarLineEdit *>(widget))
{
// We don't block signals here because changes are applied with enter or apply button,
// and we want InterfaceToolbarLineEdit to always syntax check the text.
switch (command)
{
case commandControlSet:
lineedit->setText(payload);
lineedit->disableApplyButton();
break;
default:
break;
}
}
else if (QCheckBox *checkbox = qobject_cast<QCheckBox *>(widget))
{
checkbox->blockSignals(true);
switch (command)
{
case commandControlSet:
{
Qt::CheckState state = Qt::Unchecked;
if (payload.size() > 0 && payload.at(0) != 0)
{
state = Qt::Checked;
}
checkbox->setCheckState(state);
break;
}
default:
break;
}
checkbox->blockSignals(false);
}
else if (QPushButton *button = qobject_cast<QPushButton *>(widget))
{
if ((command == commandControlSet) &&
widget->property(interface_role_property).toInt() == INTERFACE_ROLE_CONTROL)
{
button->setText(payload);
}
}
}
void InterfaceToolbar::setInterfaceValue(QString ifname, QWidget *widget, int num, int command, QByteArray payload)
{
if (!widget) {
return;
}
if (qobject_cast<QComboBox *>(widget))
{
switch (command)
{
case commandControlSet:
if (interface_[ifname].value[num] != payload)
{
interface_[ifname].value_changed[num] = false;
}
foreach (QByteArray entry, interface_[ifname].list[num])
{
if (entry == payload || entry.startsWith(payload + '\0'))
{
interface_[ifname].value[num] = payload;
}
}
break;
case commandControlAdd:
interface_[ifname].list[num].append(payload);
break;
case commandControlRemove:
if (payload.size() == 0)
{
interface_[ifname].value[num].clear();
interface_[ifname].list[num].clear();
}
else
{
foreach (QByteArray entry, interface_[ifname].list[num])
{
if (entry == payload || entry.startsWith(payload + '\0'))
{
interface_[ifname].list[num].removeAll(entry);
}
}
}
break;
default:
break;
}
}
else if (qobject_cast<InterfaceToolbarLineEdit *>(widget))
{
switch (command)
{
case commandControlSet:
if (interface_[ifname].value[num] != payload)
{
interface_[ifname].value_changed[num] = false;
}
interface_[ifname].value[num] = payload;
break;
default:
break;
}
}
else if ((widget->property(interface_type_property).toInt() == INTERFACE_TYPE_BUTTON) &&
(widget->property(interface_role_property).toInt() == INTERFACE_ROLE_LOGGER))
{
if (command == commandControlSet)
{
if (interface_[ifname].log_dialog.contains(num))
{
interface_[ifname].log_dialog[num]->clearText();
}
interface_[ifname].log_text.clear();
}
if (command == commandControlSet || command == commandControlAdd)
{
if (interface_[ifname].log_dialog.contains(num))
{
interface_[ifname].log_dialog[num]->appendText(payload);
}
interface_[ifname].log_text[num].append(payload);
}
}
else if (widget->property(interface_role_property).toInt() == INTERFACE_ROLE_CONTROL)
{
// QCheckBox or QPushButton
switch (command)
{
case commandControlSet:
if (interface_[ifname].value[num] != payload)
{
interface_[ifname].value_changed[num] = false;
}
interface_[ifname].value[num] = payload;
break;
default:
break;
}
}
}
void InterfaceToolbar::controlReceived(QString ifname, int num, int command, QByteArray payload)
{
switch (command)
{
case commandControlSet:
case commandControlAdd:
case commandControlRemove:
if (control_widget_.contains(num))
{
QWidget *widget = control_widget_[num];
setInterfaceValue(ifname, widget, num, command, payload);
if (ifname.compare(ui->interfacesComboBox->currentText()) == 0)
{
setWidgetValue(widget, command, payload);
}
}
break;
case commandControlEnable:
case commandControlDisable:
if (control_widget_.contains(num))
{
QWidget *widget = control_widget_[num];
if (widget->property(interface_role_property).toInt() == INTERFACE_ROLE_CONTROL)
{
bool enable = (command == commandControlEnable ? true : false);
interface_[ifname].widget_disabled[num] = !enable;
if (ifname.compare(ui->interfacesComboBox->currentText()) == 0)
{
widget->setEnabled(enable);
if (label_widget_.contains(num))
{
label_widget_[num]->setEnabled(enable);
}
}
}
}
break;
case commandStatusMessage:
mainApp->pushStatus(MainApplication::TemporaryStatus, payload);
break;
case commandInformationMessage:
simple_dialog_async(ESD_TYPE_INFO, ESD_BTN_OK, "%s", payload.data());
break;
case commandWarningMessage:
simple_dialog_async(ESD_TYPE_WARN, ESD_BTN_OK, "%s", payload.data());
break;
case commandErrorMessage:
simple_dialog_async(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", payload.data());
break;
default:
// Unknown commands are silently ignored
break;
}
}
void InterfaceToolbar::controlSend(QString ifname, int num, int command, const QByteArray &payload = QByteArray())
{
if (payload.length() > 65535)
{
// Not supported
return;
}
if (ifname.isEmpty() || interface_[ifname].out_fd == -1)
{
// Does not have a control out channel
return;
}
ssize_t payload_length = payload.length() + 2;
unsigned char high_nibble = (payload_length >> 16) & 0xFF;
unsigned char mid_nibble = (payload_length >> 8) & 0xFF;
unsigned char low_nibble = (payload_length >> 0) & 0xFF;
QByteArray ba;
ba.append(SP_TOOLBAR_CTRL);
ba.append(high_nibble);
ba.append(mid_nibble);
ba.append(low_nibble);
ba.append(num);
ba.append(command);
ba.append(payload);
if (ws_write(interface_[ifname].out_fd, ba.data(), ba.length()) != ba.length())
{
simple_dialog_async(ESD_TYPE_ERROR, ESD_BTN_OK,
"Unable to send control message:\n%s.",
g_strerror(errno));
}
}
void InterfaceToolbar::onControlButtonClicked()
{
const QString &ifname = ui->interfacesComboBox->currentText();
QPushButton *button = static_cast<QPushButton *>(sender());
int num = control_widget_.key(button);
controlSend(ifname, num, commandControlSet);
}
void InterfaceToolbar::onCheckBoxChanged(int state)
{
const QString &ifname = ui->interfacesComboBox->currentText();
QCheckBox *checkbox = static_cast<QCheckBox *>(sender());
int num = control_widget_.key(checkbox);
QByteArray payload(1, state == Qt::Unchecked ? 0 : 1);
controlSend(ifname, num, commandControlSet, payload);
interface_[ifname].value[num] = payload;
interface_[ifname].value_changed[num] = true;
}
void InterfaceToolbar::onComboBoxChanged(int idx)
{
const QString &ifname = ui->interfacesComboBox->currentText();
QComboBox *combobox = static_cast<QComboBox *>(sender());
int num = control_widget_.key(combobox);
QString value = combobox->itemData(idx).toString();
QByteArray payload(value.toUtf8());
controlSend(ifname, num, commandControlSet, payload);
interface_[ifname].value[num] = payload;
interface_[ifname].value_changed[num] = true;
}
void InterfaceToolbar::onLineEditChanged()
{
const QString &ifname = ui->interfacesComboBox->currentText();
InterfaceToolbarLineEdit *lineedit = static_cast<InterfaceToolbarLineEdit *>(sender());
int num = control_widget_.key(lineedit);
QByteArray payload(lineedit->text().toUtf8());
controlSend(ifname, num, commandControlSet, payload);
interface_[ifname].value[num] = payload;
interface_[ifname].value_changed[num] = true;
}
void InterfaceToolbar::onLogButtonClicked()
{
const QString &ifname = ui->interfacesComboBox->currentText();
QPushButton *button = static_cast<QPushButton *>(sender());
int num = control_widget_.key(button);
if (!interface_[ifname].log_dialog.contains(num))
{
interface_[ifname].log_dialog[num] = new FunnelTextDialog(window(), ifname + " " + button->text());
connect(interface_[ifname].log_dialog[num], SIGNAL(accepted()), this, SLOT(closeLog()));
connect(interface_[ifname].log_dialog[num], SIGNAL(rejected()), this, SLOT(closeLog()));
interface_[ifname].log_dialog[num]->setText(interface_[ifname].log_text[num]);
}
interface_[ifname].log_dialog[num]->show();
interface_[ifname].log_dialog[num]->raise();
interface_[ifname].log_dialog[num]->activateWindow();
}
void InterfaceToolbar::onHelpButtonClicked()
{
QUrl help_url(help_link_);
if (help_url.scheme().compare("file") != 0)
{
QDesktopServices::openUrl(help_url);
}
}
void InterfaceToolbar::closeLog()
{
FunnelTextDialog *log_dialog = static_cast<FunnelTextDialog *>(sender());
foreach (QString ifname, interface_.keys())
{
foreach (int num, control_widget_.keys())
{
if (interface_[ifname].log_dialog.value(num) == log_dialog)
{
interface_[ifname].log_dialog.remove(num);
}
}
}
}
void InterfaceToolbar::startReaderThread(QString ifname, void *control_in)
{
QThread *thread = new QThread;
InterfaceToolbarReader *reader = new InterfaceToolbarReader(ifname, control_in);
reader->moveToThread(thread);
connect(thread, SIGNAL(started()), reader, SLOT(loop()));
connect(reader, SIGNAL(finished()), thread, SLOT(quit()));
connect(reader, SIGNAL(finished()), reader, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), reader, SLOT(deleteLater()));
connect(reader, SIGNAL(received(QString, int, int, QByteArray)),
this, SLOT(controlReceived(QString, int, int, QByteArray)));
interface_[ifname].reader_thread = thread;
thread->start();
}
void InterfaceToolbar::startCapture(GArray *ifaces)
{
if (!ifaces || ifaces->len == 0)
return;
const QString &selected_ifname = ui->interfacesComboBox->currentText();
QString first_capturing_ifname;
bool selected_found = false;
for (guint i = 0; i < ifaces->len; i++)
{
interface_options *interface_opts = &g_array_index(ifaces, interface_options, i);
QString ifname(interface_opts->name);
if (!interface_.contains(ifname))
// This interface is not for us
continue;
if (first_capturing_ifname.isEmpty())
first_capturing_ifname = ifname;
if (ifname.compare(selected_ifname) == 0)
selected_found = true;
if (interface_[ifname].out_fd != -1)
// Already have control channels for this interface
continue;
// Open control out channel
#ifdef _WIN32
startReaderThread(ifname, interface_opts->extcap_control_in_h);
// Duplicate control out handle and pass the duplicate handle to _open_osfhandle().
// This allows the C run-time file descriptor (out_fd) and the extcap_control_out_h to be closed independently.
// The duplicated handle will get closed at the same time the file descriptor is closed.
// The control out pipe will close when both out_fd and extcap_control_out_h are closed.
HANDLE duplicate_out_handle = INVALID_HANDLE_VALUE;
if (!DuplicateHandle(GetCurrentProcess(), interface_opts->extcap_control_out_h,
GetCurrentProcess(), &duplicate_out_handle, 0, TRUE, DUPLICATE_SAME_ACCESS))
{
simple_dialog_async(ESD_TYPE_ERROR, ESD_BTN_OK,
"Failed to duplicate extcap control out handle: %s\n.",
win32strerror(GetLastError()));
}
else
{
interface_[ifname].out_fd = _open_osfhandle((intptr_t)duplicate_out_handle, O_APPEND | O_BINARY);
}
#else
startReaderThread(ifname, interface_opts->extcap_control_in);
interface_[ifname].out_fd = ws_open(interface_opts->extcap_control_out, O_WRONLY | O_BINARY, 0);
#endif
sendChangedValues(ifname);
controlSend(ifname, 0, commandControlInitialized);
}
if (!selected_found && !first_capturing_ifname.isEmpty())
{
ui->interfacesComboBox->setCurrentText(first_capturing_ifname);
}
else
{
updateWidgets();
}
}
void InterfaceToolbar::stopCapture()
{
foreach (QString ifname, interface_.keys())
{
if (interface_[ifname].reader_thread)
{
if (!interface_[ifname].reader_thread->isFinished())
{
interface_[ifname].reader_thread->requestInterruption();
}
interface_[ifname].reader_thread = NULL;
}
if (interface_[ifname].out_fd != -1)
{
ws_close_if_possible (interface_[ifname].out_fd);
interface_[ifname].out_fd = -1;
}
foreach (int num, control_widget_.keys())
{
// Reset disabled property for all widgets
interface_[ifname].widget_disabled[num] = false;
QWidget *widget = control_widget_[num];
if ((widget->property(interface_type_property).toInt() == INTERFACE_TYPE_BUTTON) &&
(widget->property(interface_role_property).toInt() == INTERFACE_ROLE_CONTROL))
{
// Reset default value for control buttons
interface_[ifname].value[num] = default_value_[num];
if (ifname.compare(ui->interfacesComboBox->currentText()) == 0)
{
setWidgetValue(widget, commandControlSet, default_value_[num]);
}
}
}
}
updateWidgets();
}
void InterfaceToolbar::sendChangedValues(QString ifname)
{
// Send all values which has changed
foreach (int num, control_widget_.keys())
{
QWidget *widget = control_widget_[num];
if ((interface_[ifname].value_changed[num]) &&
(widget->property(interface_type_property).toInt() != INTERFACE_TYPE_BUTTON) &&
(widget->property(interface_role_property).toInt() == INTERFACE_ROLE_CONTROL))
{
controlSend(ifname, num, commandControlSet, interface_[ifname].value[num]);
}
}
}
void InterfaceToolbar::onRestoreButtonClicked()
{
const QString &ifname = ui->interfacesComboBox->currentText();
// Set default values to all widgets and interfaces
foreach (int num, control_widget_.keys())
{
QWidget *widget = control_widget_[num];
if (default_list_[num].size() > 0)
{
// This is a QComboBox. Clear list and add new entries.
setWidgetValue(widget, commandControlRemove, QByteArray());
interface_[ifname].list[num].clear();
foreach (QByteArray value, default_list_[num])
{
setWidgetValue(widget, commandControlAdd, value);
interface_[ifname].list[num].append(value);
}
}
switch (widget->property(interface_role_property).toInt())
{
case INTERFACE_ROLE_CONTROL:
setWidgetValue(widget, commandControlSet, default_value_[num]);
interface_[ifname].value[num] = default_value_[num];
interface_[ifname].value_changed[num] = false;
break;
case INTERFACE_ROLE_LOGGER:
if (interface_[ifname].log_dialog.contains(num))
{
interface_[ifname].log_dialog[num]->clearText();
}
interface_[ifname].log_text[num].clear();
break;
default:
break;
}
}
}
bool InterfaceToolbar::hasInterface(QString ifname)
{
return interface_.contains(ifname);
}
void InterfaceToolbar::updateWidgets()
{
const QString &ifname = ui->interfacesComboBox->currentText();
bool is_capturing = (interface_[ifname].out_fd == -1 ? false : true);
foreach (int num, control_widget_.keys())
{
QWidget *widget = control_widget_[num];
bool widget_enabled = true;
if (ifname.isEmpty() &&
(widget->property(interface_role_property).toInt() != INTERFACE_ROLE_HELP))
{
// No interface selected, disable all but Help button
widget_enabled = false;
}
else if (!is_capturing &&
(widget->property(interface_type_property).toInt() == INTERFACE_TYPE_BUTTON) &&
(widget->property(interface_role_property).toInt() == INTERFACE_ROLE_CONTROL))
{
widget_enabled = false;
}
else if (widget->property(interface_role_property).toInt() == INTERFACE_ROLE_CONTROL)
{
widget_enabled = !interface_[ifname].widget_disabled[num];
}
widget->setEnabled(widget_enabled);
if (label_widget_.contains(num))
{
label_widget_[num]->setEnabled(widget_enabled);
}
}
foreach (int num, control_widget_.keys())
{
QWidget *widget = control_widget_[num];
if ((widget->property(interface_type_property).toInt() == INTERFACE_TYPE_BUTTON) &&
(widget->property(interface_role_property).toInt() == INTERFACE_ROLE_RESTORE))
{
widget->setEnabled(!is_capturing);
}
}
}
void InterfaceToolbar::interfaceListChanged()
{
#ifdef HAVE_LIBPCAP
const QString &selected_ifname = ui->interfacesComboBox->currentText();
bool keep_selected = false;
ui->interfacesComboBox->blockSignals(true);
ui->interfacesComboBox->clear();
for (guint i = 0; i < global_capture_opts.all_ifaces->len; i++)
{
interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i);
if (device->hidden)
continue;
if (interface_.keys().contains(device->name))
{
ui->interfacesComboBox->addItem(device->name);
if (selected_ifname.compare(device->name) == 0)
{
// Keep selected interface
ui->interfacesComboBox->setCurrentText(device->name);
keep_selected = true;
}
}
}
ui->interfacesComboBox->blockSignals(false);
if (!keep_selected)
{
// Select the first interface
on_interfacesComboBox_currentTextChanged(ui->interfacesComboBox->currentText());
}
updateWidgets();
#endif
}
void InterfaceToolbar::on_interfacesComboBox_currentTextChanged(const QString &ifname)
{
foreach (int num, control_widget_.keys())
{
QWidget *widget = control_widget_[num];
if (interface_[ifname].list[num].size() > 0)
{
// This is a QComboBox. Clear list and add new entries.
setWidgetValue(widget, commandControlRemove, QByteArray());
foreach (QByteArray value, interface_[ifname].list[num])
{
setWidgetValue(widget, commandControlAdd, value);
}
}
if (widget->property(interface_role_property).toInt() == INTERFACE_ROLE_CONTROL)
{
setWidgetValue(widget, commandControlSet, interface_[ifname].value[num]);
}
}
updateWidgets();
} |
C/C++ | wireshark/ui/qt/interface_toolbar.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef INTERFACE_TOOLBAR_H
#define INTERFACE_TOOLBAR_H
#include <glib.h>
#include "ui/iface_toolbar.h"
#include "funnel_text_dialog.h"
#include "interface_toolbar_reader.h"
#include <QFrame>
#include <QList>
#include <QMap>
#include <QString>
namespace Ui {
class InterfaceToolbar;
}
struct interface_values
{
QThread *reader_thread;
int out_fd;
QMap<int, QByteArray> value;
QMap<int, bool> value_changed;
QMap<int, QList<QByteArray> > list;
QMap<int, FunnelTextDialog *> log_dialog;
QMap<int, QString> log_text;
QMap<int, bool> widget_disabled;
};
class InterfaceToolbar : public QFrame
{
Q_OBJECT
public:
explicit InterfaceToolbar(QWidget *parent = 0, const iface_toolbar *toolbar = NULL);
~InterfaceToolbar();
void startCapture(GArray *ifaces);
void stopCapture();
bool hasInterface(QString ifname);
public slots:
void interfaceListChanged();
void controlReceived(QString ifname, int num, int command, QByteArray message);
signals:
void closeReader();
private slots:
void startReaderThread(QString ifname, void *control_in);
void updateWidgets();
void onControlButtonClicked();
void onLogButtonClicked();
void onHelpButtonClicked();
void onRestoreButtonClicked();
void onCheckBoxChanged(int state);
void onComboBoxChanged(int idx);
void onLineEditChanged();
void closeLog();
void on_interfacesComboBox_currentTextChanged(const QString &ifname);
private:
void initializeControls(const iface_toolbar *toolbar);
void setDefaultValue(int num, const QByteArray &value);
void sendChangedValues(QString ifname);
QWidget *createCheckbox(iface_toolbar_control *control);
QWidget *createButton(iface_toolbar_control *control);
QWidget *createSelector(iface_toolbar_control *control);
QWidget *createString(iface_toolbar_control *control);
void controlSend(QString ifname, int num, int type, const QByteArray &payload);
void setWidgetValue(QWidget *widget, int type, QByteArray payload);
void setInterfaceValue(QString ifname, QWidget *widget, int num, int type, QByteArray payload);
Ui::InterfaceToolbar *ui;
QMap<QString, struct interface_values> interface_;
QMap<int, QByteArray> default_value_;
QMap<int, QList<QByteArray> > default_list_;
QMap<int, QWidget *> control_widget_;
QMap<int, QWidget *> label_widget_;
QString help_link_;
bool use_spacer_;
};
#endif // INTERFACE_TOOLBAR_H |
User Interface | wireshark/ui/qt/interface_toolbar.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>InterfaceToolbar</class>
<widget class="QFrame" name="InterfaceToolbar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>600</width>
<height>32</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">
<property name="topMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="interfacesLabel">
<property name="toolTip">
<string>Select interface</string>
</property>
<property name="text">
<string>Interface</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="interfacesComboBox">
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContents</enum>
</property>
<property name="toolTip">
<string>Select interface</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="leftLayout"/>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>5</height>
</size>
</property>
</spacer>
</item>
<item>
<layout class="QHBoxLayout" name="rightLayout"/>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui> |
C++ | wireshark/ui/qt/interface_toolbar_reader.cpp | /* interface_toolbar_reader.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 <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <errno.h>
#include "interface_toolbar_reader.h"
#include "sync_pipe.h"
#include "wsutil/file_util.h"
#include <QThread>
const int header_size = 6;
#ifdef _WIN32
int InterfaceToolbarReader::async_pipe_read(void *data, int nbyte)
{
BOOL success;
DWORD nof_bytes_read;
OVERLAPPED overlap;
int bytes_read = -1;
overlap.Pointer = 0;
overlap.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (overlap.hEvent == NULL)
{
// CreateEvent failed with error code GetLastError()
return -1;
}
success = ReadFile(control_in_, data, nbyte, &nof_bytes_read, &overlap);
if (success && nof_bytes_read != 0)
{
// The read operation completed successfully.
bytes_read = nof_bytes_read;
}
else if (!success && GetLastError() == ERROR_IO_PENDING)
{
// The operation is still pending, wait for a signal.
if (WaitForSingleObject(overlap.hEvent, INFINITE) == WAIT_OBJECT_0)
{
// The wait operation has completed.
success = GetOverlappedResult(control_in_, &overlap, &nof_bytes_read, FALSE);
if (success && nof_bytes_read != 0)
{
// The get result operation completed successfully.
bytes_read = nof_bytes_read;
}
}
}
CloseHandle(overlap.hEvent);
return bytes_read;
}
#endif
int InterfaceToolbarReader::pipe_read(char *data, int nbyte)
{
int total_len = 0;
while (total_len < nbyte)
{
char *data_ptr = data + total_len;
int data_len = nbyte - total_len;
#ifdef _WIN32
int read_len = async_pipe_read(data_ptr, data_len);
#else
int read_len = (int)ws_read(fd_in_, data_ptr, data_len);
#endif
if (read_len == -1)
{
if (errno != EAGAIN)
{
return -1;
}
}
else
{
total_len += read_len;
}
if (QThread::currentThread()->isInterruptionRequested())
{
return -1;
}
}
return total_len;
}
void InterfaceToolbarReader::loop()
{
QByteArray header;
QByteArray payload;
#ifndef _WIN32
struct timeval timeout;
fd_set readfds;
fd_in_ = ws_open(control_in_.toUtf8(), O_RDONLY | O_BINARY | O_NONBLOCK, 0);
if (fd_in_ == -1)
{
emit finished();
return;
}
#endif
header.resize(header_size);
forever
{
#ifndef _WIN32
FD_ZERO(&readfds);
FD_SET(fd_in_, &readfds);
timeout.tv_sec = 2;
timeout.tv_usec = 0;
int ret = select(fd_in_ + 1, &readfds, NULL, NULL, &timeout);
if (ret == -1)
{
break;
}
if (QThread::currentThread()->isInterruptionRequested())
{
break;
}
if (ret == 0 || !FD_ISSET(fd_in_, &readfds))
{
continue;
}
#endif
// Read the header from the pipe.
if (pipe_read(header.data(), header_size) != header_size)
{
break;
}
unsigned char high_nibble = header[1] & 0xFF;
unsigned char mid_nibble = header[2] & 0xFF;
unsigned char low_nibble = header[3] & 0xFF;
int payload_len = (int)((high_nibble << 16) + (mid_nibble << 8) + low_nibble) - 2;
payload.resize(payload_len);
// Read the payload from the pipe.
if (pipe_read(payload.data(), payload_len) != payload_len)
{
break;
}
if (header[0] == SP_TOOLBAR_CTRL)
{
emit received(ifname_, (unsigned char)header[4], (unsigned char)header[5], payload);
}
}
#ifndef _WIN32
ws_close(fd_in_);
#endif
emit finished();
} |
C/C++ | wireshark/ui/qt/interface_toolbar_reader.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef INTERFACE_TOOLBAR_READER_H
#define INTERFACE_TOOLBAR_READER_H
#include <QObject>
#include <QByteArray>
#ifdef _WIN32
#include <windows.h>
#endif
namespace Ui {
class InterfaceToolbarReader;
}
class InterfaceToolbarReader : public QObject
{
Q_OBJECT
public:
InterfaceToolbarReader(QString ifname, void *control_in, QObject *parent = 0) :
QObject(parent),
ifname_(ifname),
#ifdef _WIN32
control_in_((HANDLE)control_in)
#else
control_in_((char *)control_in),
fd_in_(-1)
#endif
{
}
public slots:
void loop();
signals:
void received(QString ifname, int num, int command, QByteArray payload);
void finished();
private:
#ifdef _WIN32
int async_pipe_read(void *data, int nbyte);
#endif
int pipe_read(char *data, int nbyte);
QString ifname_;
#ifdef _WIN32
HANDLE control_in_;
#else
QString control_in_;
int fd_in_;
#endif
};
#endif // INTERFACE_TOOLBAR_READER_H |
C++ | wireshark/ui/qt/io_console_dialog.cpp | /*
* io_console_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>
#define WS_LOG_DOMAIN LOG_DOMAIN_QTUI
#include "io_console_dialog.h"
#include <ui_io_console_dialog.h>
#include "main_application.h"
extern "C" {
static void print_function(const char *str, void *ptr);
}
static void print_function(const char *str, void *print_data)
{
IOConsoleDialog *dialog = static_cast<IOConsoleDialog *>(print_data);
dialog->appendOutputText(QString(str));
}
IOConsoleDialog::IOConsoleDialog(QWidget &parent,
QString title,
funnel_console_eval_cb_t eval_cb,
funnel_console_open_cb_t open_cb,
funnel_console_close_cb_t close_cb,
void *callback_data = nullptr) :
GeometryStateDialog(&parent),
ui(new Ui::IOConsoleDialog),
eval_cb_(eval_cb),
open_cb_(open_cb),
close_cb_(close_cb),
callback_data_(callback_data)
{
ui->setupUi(this);
if (title.isEmpty())
title = QString("Console");
loadGeometry(0, 0, title);
setWindowTitle(mainApp->windowTitleString(title));
QPushButton *eval_button = ui->buttonBox->addButton(tr("Evaluate"), QDialogButtonBox::ActionRole);
eval_button->setDefault(true);
eval_button->setShortcut(QKeySequence("Ctrl+Return"));
connect(eval_button, &QPushButton::clicked, this, &IOConsoleDialog::acceptInput);
QPushButton *clear_button = ui->buttonBox->addButton(tr("Clear"), QDialogButtonBox::ActionRole);
connect(clear_button, &QPushButton::clicked, this, &IOConsoleDialog::on_clearActivated);
ui->inputTextEdit->setFont(mainApp->monospaceFont());
ui->inputTextEdit->setPlaceholderText(QString(tr("Use %1 to evaluate."))
.arg(eval_button->shortcut().toString(QKeySequence::NativeText)));
ui->outputTextEdit->setFont(mainApp->monospaceFont());
ui->hintLabel->clear();
// Reloading Lua plugins destroys the lua state, at a minimum the Lua print()
// will no longer work correctly and the callback_data_ will also be invalidated.
// Force close the console dialog when reloading Lua plugins.
// XXX In theory there might be console types other than Lua so we may
// want to fix the code to close only Lua type dialogs if only Lua plugins are
// reloaded.
connect(mainApp, &MainApplication::startingLuaReload, this, &IOConsoleDialog::close);
// Install print and save return
saved_blob_ = open_cb_(print_function, this, callback_data_);
}
IOConsoleDialog::~IOConsoleDialog()
{
delete ui;
close_cb_(saved_blob_, callback_data_);
}
void IOConsoleDialog::setHintText(const QString &text)
{
ui->hintLabel->setText(QString("<small><i>%1.</i></small>").arg(text));
}
void IOConsoleDialog::clearHintText()
{
ui->hintLabel->clear();
}
void IOConsoleDialog::clearSuccessHint()
{
// Text changed so we no longer have a success.
ui->hintLabel->clear();
// Disconnect this slot until the next success.
disconnect(ui->inputTextEdit, &QTextEdit::textChanged, this, &IOConsoleDialog::clearSuccessHint);
}
void IOConsoleDialog::acceptInput()
{
clearHintText();
QString text = ui->inputTextEdit->toPlainText();
if (text.isEmpty())
return;
char *error_str = nullptr;
char *error_hint = nullptr;
int result = eval_cb_(qUtf8Printable(text), &error_str, &error_hint, callback_data_);
if (result != 0) {
if (error_hint) {
QString hint(error_hint);
setHintText(hint.at(0).toUpper() + hint.mid(1));
g_free(error_hint);
}
else if (result < 0) {
setHintText("Error loading string");
}
else {
setHintText("Error running chunk");
}
if (error_str) {
appendOutputText(QString(error_str));
g_free(error_str);
}
}
else {
setHintText("Code evaluated successfully");
connect(ui->inputTextEdit, &QTextEdit::textChanged, this, &IOConsoleDialog::clearSuccessHint);
}
}
void IOConsoleDialog::appendOutputText(const QString &text)
{
ui->outputTextEdit->append(text);
}
void IOConsoleDialog::on_clearActivated()
{
ui->inputTextEdit->clear();
ui->outputTextEdit->clear();
ui->hintLabel->clear();
} |
C/C++ | wireshark/ui/qt/io_console_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 IO_CONSOLE_DIALOG_H
#define IO_CONSOLE_DIALOG_H
#include <wireshark.h>
#include <QTextEdit>
#include <QSplitter>
#include <QKeySequence>
#include <QPushButton>
#include <QSizePolicy>
#include "geometry_state_dialog.h"
#include <epan/funnel.h>
namespace Ui {
class IOConsoleDialog;
}
class IOConsoleDialog : public GeometryStateDialog
{
Q_OBJECT
public:
explicit IOConsoleDialog(QWidget &parent,
QString title,
funnel_console_eval_cb_t eval_cb,
funnel_console_open_cb_t open_cb,
funnel_console_close_cb_t close_cb,
void *callback_data);
~IOConsoleDialog();
void appendOutputText(const QString &text);
void setHintText(const QString &text);
void clearHintText();
private slots:
void acceptInput();
void on_clearActivated(void);
void clearSuccessHint(void);
private:
Ui::IOConsoleDialog *ui;
funnel_console_eval_cb_t eval_cb_;
funnel_console_open_cb_t open_cb_;
funnel_console_close_cb_t close_cb_;
void *callback_data_;
intptr_t saved_blob_;
};
#endif // IO_CONSOLE_DIALOG_H |
User Interface | wireshark/ui/qt/io_console_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>IOConsoleDialog</class>
<widget class="QDialog" name="IOConsoleDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>596</width>
<height>430</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Enter code</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<widget class="QTextEdit" name="inputTextEdit"/>
<widget class="QTextEdit" name="outputTextEdit"/>
</widget>
</item>
<item row="2" 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="3" 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>IOConsoleDialog</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>IOConsoleDialog</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/io_graph_dialog.cpp | /* io_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 "io_graph_dialog.h"
#include <ui_io_graph_dialog.h>
#include "file.h"
#include <epan/stat_tap_ui.h>
#include "epan/stats_tree_priv.h"
#include "epan/uat-int.h"
#include <wsutil/utf8_entities.h>
#include <wsutil/ws_assert.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/utils/variant_pointer.h>
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/widgets/qcustomplot.h>
#include "progress_frame.h"
#include "main_application.h"
#include <wsutil/filesystem.h>
#include <wsutil/report_message.h>
#include <ui/qt/utils/tango_colors.h> //provides some default colors
#include <ui/qt/widgets/copy_from_profile_button.h>
#include "ui/qt/widgets/wireshark_file_dialog.h"
#include <QClipboard>
#include <QFontMetrics>
#include <QFrame>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QMessageBox>
#include <QPushButton>
#include <QRubberBand>
#include <QSpacerItem>
#include <QTimer>
#include <QVariant>
// Bugs and uncertainties:
// - Regular (non-stacked) bar graphs are drawn on top of each other on the Z axis.
// The QCP forum suggests drawing them side by side:
// https://www.qcustomplot.com/index.php/support/forum/62
// - We retap and redraw more than we should.
// - Smoothing doesn't seem to match GTK+
// - Closing the color picker on macOS sends the dialog to the background.
// - The color picker triggers https://bugreports.qt.io/browse/QTBUG-58699.
// To do:
// - Use scroll bars?
// - Scroll during live captures
// - Set ticks per pixel (e.g. pressing "2" sets 2 tpp).
// - Explicitly handle missing values, e.g. via NAN.
// - Add a "show missing" or "show zero" option to the UAT?
// It would add yet another graph configuration column.
const qreal graph_line_width_ = 1.0;
const int DEFAULT_MOVING_AVERAGE = 0;
const int DEFAULT_Y_AXIS_FACTOR = 1;
// Don't accidentally zoom into a 1x1 rect if you happen to click on the graph
// in zoom mode.
const int min_zoom_pixels_ = 20;
const int stat_update_interval_ = 200; // ms
// Saved graph settings
typedef struct _io_graph_settings_t {
gboolean enabled;
char* name;
char* dfilter;
guint color;
guint32 style;
guint32 yaxis;
char* yfield;
guint32 sma_period;
guint32 y_axis_factor;
} io_graph_settings_t;
static const value_string graph_style_vs[] = {
{ IOGraph::psLine, "Line" },
{ IOGraph::psDotLine, "Dot Line" },
{ IOGraph::psStepLine, "Step Line" },
{ IOGraph::psDotStepLine, "Dot Step Line" },
{ IOGraph::psImpulse, "Impulse" },
{ IOGraph::psBar, "Bar" },
{ IOGraph::psStackedBar, "Stacked Bar" },
{ IOGraph::psDot, "Dot" },
{ IOGraph::psSquare, "Square" },
{ IOGraph::psDiamond, "Diamond" },
{ IOGraph::psCross, "Cross" },
{ IOGraph::psCircle, "Circle" },
{ IOGraph::psPlus, "Plus" },
{ 0, NULL }
};
static const value_string y_axis_vs[] = {
{ IOG_ITEM_UNIT_PACKETS, "Packets" },
{ IOG_ITEM_UNIT_BYTES, "Bytes" },
{ IOG_ITEM_UNIT_BITS, "Bits" },
{ IOG_ITEM_UNIT_CALC_SUM, "SUM(Y Field)" },
{ IOG_ITEM_UNIT_CALC_FRAMES, "COUNT FRAMES(Y Field)" },
{ IOG_ITEM_UNIT_CALC_FIELDS, "COUNT FIELDS(Y Field)" },
{ IOG_ITEM_UNIT_CALC_MAX, "MAX(Y Field)" },
{ IOG_ITEM_UNIT_CALC_MIN, "MIN(Y Field)" },
{ IOG_ITEM_UNIT_CALC_AVERAGE, "AVG(Y Field)" },
{ IOG_ITEM_UNIT_CALC_LOAD, "LOAD(Y Field)" },
{ 0, NULL }
};
static const value_string moving_avg_vs[] = {
{ 0, "None" },
{ 10, "10 interval SMA" },
{ 20, "20 interval SMA" },
{ 50, "50 interval SMA" },
{ 100, "100 interval SMA" },
{ 200, "200 interval SMA" },
{ 500, "500 interval SMA" },
{ 1000, "1000 interval SMA" },
{ 0, NULL }
};
static io_graph_settings_t *iog_settings_ = NULL;
static guint num_io_graphs_ = 0;
static uat_t *iog_uat_ = NULL;
// y_axis_factor was added in 3.6. Provide backward compatibility.
static const char *iog_uat_defaults_[] = {
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "1"
};
extern "C" {
//Allow the enable/disable field to be a checkbox, but for backwards compatibility,
//the strings have to be "Enabled"/"Disabled", not "TRUE"/"FALSE"
#define UAT_BOOL_ENABLE_CB_DEF(basename,field_name,rec_t) \
static void basename ## _ ## field_name ## _set_cb(void* rec, const char* buf, guint len, const void* UNUSED_PARAMETER(u1), const void* UNUSED_PARAMETER(u2)) {\
char* tmp_str = g_strndup(buf,len); \
if ((g_strcmp0(tmp_str, "Enabled") == 0) || \
(g_strcmp0(tmp_str, "TRUE") == 0)) \
((rec_t*)rec)->field_name = 1; \
else \
((rec_t*)rec)->field_name = 0; \
g_free(tmp_str); } \
static void basename ## _ ## field_name ## _tostr_cb(void* rec, char** out_ptr, unsigned* out_len, const void* UNUSED_PARAMETER(u1), const void* UNUSED_PARAMETER(u2)) {\
*out_ptr = ws_strdup_printf("%s",((rec_t*)rec)->field_name ? "Enabled" : "Disabled"); \
*out_len = (unsigned)strlen(*out_ptr); }
static gboolean uat_fld_chk_enable(void* u1 _U_, const char* strptr, guint len, const void* u2 _U_, const void* u3 _U_, char** err)
{
char* str = g_strndup(strptr,len);
if ((g_strcmp0(str, "Enabled") == 0) ||
(g_strcmp0(str, "Disabled") == 0) ||
(g_strcmp0(str, "TRUE") == 0) || //just for UAT functionality
(g_strcmp0(str, "FALSE") == 0)) {
*err = NULL;
g_free(str);
return TRUE;
}
//User should never see this unless they are manually modifying UAT
*err = ws_strdup_printf("invalid value: %s (must be Enabled or Disabled)", str);
g_free(str);
return FALSE;
}
#define UAT_FLD_BOOL_ENABLE(basename,field_name,title,desc) \
{#field_name, title, PT_TXTMOD_BOOL,{uat_fld_chk_enable,basename ## _ ## field_name ## _set_cb,basename ## _ ## field_name ## _tostr_cb},{0,0,0},0,desc,FLDFILL}
//"Custom" handler for sma_period enumeration for backwards compatibility
static void io_graph_sma_period_set_cb(void* rec, const char* buf, guint len, const void* vs, const void* u2 _U_)
{
guint i;
char* str = g_strndup(buf,len);
const char* cstr;
((io_graph_settings_t*)rec)->sma_period = 0;
//Original UAT had just raw numbers and not enumerated values with "interval SMA"
if (strstr(str, "interval SMA") == NULL) {
if (strcmp(str, "None") == 0) { //Valid enumerated value
} else if (strcmp(str, "0") == 0) {
g_free(str);
str = g_strdup("None");
} else {
char *str2 = ws_strdup_printf("%s interval SMA", str);
g_free(str);
str = str2;
}
}
for (i=0; (cstr = ((const value_string*)vs)[i].strptr) ;i++) {
if (g_str_equal(cstr,str)) {
((io_graph_settings_t*)rec)->sma_period = (guint32)((const value_string*)vs)[i].value;
g_free(str);
return;
}
}
g_free(str);
}
//Duplicated because macro covers both functions
static void io_graph_sma_period_tostr_cb(void* rec, char** out_ptr, unsigned* out_len, const void* vs, const void* u2 _U_)
{
guint i;
for (i=0;((const value_string*)vs)[i].strptr;i++) {
if (((const value_string*)vs)[i].value == ((io_graph_settings_t*)rec)->sma_period) {
*out_ptr = g_strdup(((const value_string*)vs)[i].strptr);
*out_len = (unsigned)strlen(*out_ptr);
return;
}
}
*out_ptr = g_strdup("None");
*out_len = (unsigned)strlen("None");
}
static gboolean sma_period_chk_enum(void* u1 _U_, const char* strptr, guint len, const void* v, const void* u3 _U_, char** err) {
char *str = g_strndup(strptr,len);
guint i;
const value_string* vs = (const value_string *)v;
//Original UAT had just raw numbers and not enumerated values with "interval SMA"
if (strstr(str, "interval SMA") == NULL) {
if (strcmp(str, "None") == 0) { //Valid enumerated value
} else if (strcmp(str, "0") == 0) {
g_free(str);
str = g_strdup("None");
} else {
char *str2 = ws_strdup_printf("%s interval SMA", str);
g_free(str);
str = str2;
}
}
for (i=0;vs[i].strptr;i++) {
if (g_strcmp0(vs[i].strptr,str) == 0) {
*err = NULL;
g_free(str);
return TRUE;
}
}
*err = ws_strdup_printf("invalid value: %s",str);
g_free(str);
return FALSE;
}
#define UAT_FLD_SMA_PERIOD(basename,field_name,title,enum,desc) \
{#field_name, title, PT_TXTMOD_ENUM,{sma_period_chk_enum,basename ## _ ## field_name ## _set_cb,basename ## _ ## field_name ## _tostr_cb},{&(enum),&(enum),&(enum)},&(enum),desc,FLDFILL}
UAT_BOOL_ENABLE_CB_DEF(io_graph, enabled, io_graph_settings_t)
UAT_CSTRING_CB_DEF(io_graph, name, io_graph_settings_t)
UAT_DISPLAY_FILTER_CB_DEF(io_graph, dfilter, io_graph_settings_t)
UAT_COLOR_CB_DEF(io_graph, color, io_graph_settings_t)
UAT_VS_DEF(io_graph, style, io_graph_settings_t, guint32, 0, "Line")
UAT_VS_DEF(io_graph, yaxis, io_graph_settings_t, guint32, 0, "Packets")
UAT_PROTO_FIELD_CB_DEF(io_graph, yfield, io_graph_settings_t)
UAT_DEC_CB_DEF(io_graph, y_axis_factor, io_graph_settings_t)
static uat_field_t io_graph_fields[] = {
UAT_FLD_BOOL_ENABLE(io_graph, enabled, "Enabled", "Graph visibility"),
UAT_FLD_CSTRING(io_graph, name, "Graph Name", "The name of the graph"),
UAT_FLD_DISPLAY_FILTER(io_graph, dfilter, "Display Filter", "Graph packets matching this display filter"),
UAT_FLD_COLOR(io_graph, color, "Color", "Graph color (#RRGGBB)"),
UAT_FLD_VS(io_graph, style, "Style", graph_style_vs, "Graph style (Line, Bars, etc.)"),
UAT_FLD_VS(io_graph, yaxis, "Y Axis", y_axis_vs, "Y Axis units"),
UAT_FLD_PROTO_FIELD(io_graph, yfield, "Y Field", "Apply calculations to this field"),
UAT_FLD_SMA_PERIOD(io_graph, sma_period, "SMA Period", moving_avg_vs, "Simple moving average period"),
UAT_FLD_DEC(io_graph, y_axis_factor, "Y Axis Factor", "Y Axis Factor"),
UAT_END_FIELDS
};
static void* io_graph_copy_cb(void* dst_ptr, const void* src_ptr, size_t) {
io_graph_settings_t* dst = (io_graph_settings_t *)dst_ptr;
const io_graph_settings_t* src = (const io_graph_settings_t *)src_ptr;
dst->enabled = src->enabled;
dst->name = g_strdup(src->name);
dst->dfilter = g_strdup(src->dfilter);
dst->color = src->color;
dst->style = src->style;
dst->yaxis = src->yaxis;
dst->yfield = g_strdup(src->yfield);
dst->sma_period = src->sma_period;
dst->y_axis_factor = src->y_axis_factor;
return dst;
}
static void io_graph_free_cb(void* p) {
io_graph_settings_t *iogs = (io_graph_settings_t *)p;
g_free(iogs->name);
g_free(iogs->dfilter);
g_free(iogs->yfield);
}
} // extern "C"
IOGraphDialog::IOGraphDialog(QWidget &parent, CaptureFile &cf, QString displayFilter) :
WiresharkDialog(parent, cf),
ui(new Ui::IOGraphDialog),
uat_model_(nullptr),
uat_delegate_(nullptr),
base_graph_(nullptr),
tracer_(nullptr),
start_time_(0.0),
mouse_drags_(true),
rubber_band_(nullptr),
stat_timer_(nullptr),
need_replot_(false),
need_retap_(false),
auto_axes_(true),
number_ticker_(new QCPAxisTicker),
datetime_ticker_(new QCPAxisTickerDateTime)
{
ui->setupUi(this);
ui->hintLabel->setSmallText();
loadGeometry();
setWindowSubtitle(tr("I/O Graphs"));
setAttribute(Qt::WA_DeleteOnClose, true);
QCustomPlot *iop = ui->ioPlot;
ui->newToolButton->setStockIcon("list-add");
ui->deleteToolButton->setStockIcon("list-remove");
ui->copyToolButton->setStockIcon("list-copy");
ui->clearToolButton->setStockIcon("list-clear");
ui->moveUpwardsToolButton->setStockIcon("list-move-up");
ui->moveDownwardsToolButton->setStockIcon("list-move-down");
#ifdef Q_OS_MAC
ui->newToolButton->setAttribute(Qt::WA_MacSmallSize, true);
ui->deleteToolButton->setAttribute(Qt::WA_MacSmallSize, true);
ui->copyToolButton->setAttribute(Qt::WA_MacSmallSize, true);
ui->clearToolButton->setAttribute(Qt::WA_MacSmallSize, true);
ui->moveUpwardsToolButton->setAttribute(Qt::WA_MacSmallSize, true);
ui->moveDownwardsToolButton->setAttribute(Qt::WA_MacSmallSize, true);
#endif
QPushButton *save_bt = ui->buttonBox->button(QDialogButtonBox::Save);
save_bt->setText(tr("Save As…"));
QPushButton *copy_bt = ui->buttonBox->addButton(tr("Copy"), QDialogButtonBox::ActionRole);
connect (copy_bt, SIGNAL(clicked()), this, SLOT(copyAsCsvClicked()));
CopyFromProfileButton * copy_button = new CopyFromProfileButton(this, "io_graphs", tr("Copy graphs from another profile."));
ui->buttonBox->addButton(copy_button, QDialogButtonBox::ActionRole);
connect(copy_button, &CopyFromProfileButton::copyProfile, this, &IOGraphDialog::copyFromProfile);
QPushButton *close_bt = ui->buttonBox->button(QDialogButtonBox::Close);
if (close_bt) {
close_bt->setDefault(true);
}
ui->automaticUpdateCheckBox->setChecked(prefs.gui_io_graph_automatic_update ? true : false);
ui->enableLegendCheckBox->setChecked(prefs.gui_io_graph_enable_legend ? true : false);
stat_timer_ = new QTimer(this);
connect(stat_timer_, SIGNAL(timeout()), this, SLOT(updateStatistics()));
stat_timer_->start(stat_update_interval_);
// Intervals (ms)
ui->intervalComboBox->addItem(tr("1 ms"), 1);
ui->intervalComboBox->addItem(tr("2 ms"), 2);
ui->intervalComboBox->addItem(tr("5 ms"), 5);
ui->intervalComboBox->addItem(tr("10 ms"), 10);
ui->intervalComboBox->addItem(tr("20 ms"), 20);
ui->intervalComboBox->addItem(tr("50 ms"), 50);
ui->intervalComboBox->addItem(tr("100 ms"), 100);
ui->intervalComboBox->addItem(tr("200 ms"), 200);
ui->intervalComboBox->addItem(tr("500 ms"), 500);
ui->intervalComboBox->addItem(tr("1 sec"), 1000);
ui->intervalComboBox->addItem(tr("2 sec"), 2000);
ui->intervalComboBox->addItem(tr("5 sec"), 5000);
ui->intervalComboBox->addItem(tr("10 sec"), 10000);
ui->intervalComboBox->addItem(tr("1 min"), 60000);
ui->intervalComboBox->addItem(tr("10 min"), 600000);
ui->intervalComboBox->setCurrentIndex(9);
ui->todCheckBox->setChecked(false);
iop->xAxis->setTicker(number_ticker_);
ui->dragRadioButton->setChecked(mouse_drags_);
ctx_menu_.addAction(ui->actionZoomIn);
ctx_menu_.addAction(ui->actionZoomInX);
ctx_menu_.addAction(ui->actionZoomInY);
ctx_menu_.addAction(ui->actionZoomOut);
ctx_menu_.addAction(ui->actionZoomOutX);
ctx_menu_.addAction(ui->actionZoomOutY);
ctx_menu_.addAction(ui->actionReset);
ctx_menu_.addSeparator();
ctx_menu_.addAction(ui->actionMoveRight10);
ctx_menu_.addAction(ui->actionMoveLeft10);
ctx_menu_.addAction(ui->actionMoveUp10);
ctx_menu_.addAction(ui->actionMoveDown10);
ctx_menu_.addAction(ui->actionMoveRight1);
ctx_menu_.addAction(ui->actionMoveLeft1);
ctx_menu_.addAction(ui->actionMoveUp1);
ctx_menu_.addAction(ui->actionMoveDown1);
ctx_menu_.addSeparator();
ctx_menu_.addAction(ui->actionGoToPacket);
ctx_menu_.addSeparator();
ctx_menu_.addAction(ui->actionDragZoom);
ctx_menu_.addAction(ui->actionToggleTimeOrigin);
ctx_menu_.addAction(ui->actionCrosshairs);
set_action_shortcuts_visible_in_context_menu(ctx_menu_.actions());
iop->xAxis->setLabel(tr("Time (s)"));
iop->setMouseTracking(true);
iop->setEnabled(true);
QCPTextElement *title = new QCPTextElement(iop);
iop->plotLayout()->insertRow(0);
iop->plotLayout()->addElement(0, 0, title);
title->setText(tr("Wireshark I/O Graphs: %1").arg(cap_file_.fileDisplayName()));
tracer_ = new QCPItemTracer(iop);
loadProfileGraphs();
bool filterExists = false;
QString graph_name = is_packet_configuration_namespace() ? tr("Filtered packets") : tr("Filtered events");
if (uat_model_->rowCount() > 0) {
for (int i = 0; i < uat_model_->rowCount(); i++) {
createIOGraph(i);
if (ioGraphs_.at(i)->filter().compare(displayFilter) == 0)
filterExists = true;
}
if (! filterExists && displayFilter.length() > 0)
addGraph(true, graph_name, displayFilter, ColorUtils::graphColor(uat_model_->rowCount()),
IOGraph::psLine, IOG_ITEM_UNIT_PACKETS, QString(), DEFAULT_MOVING_AVERAGE, DEFAULT_Y_AXIS_FACTOR);
} else {
addDefaultGraph(true, 0);
addDefaultGraph(true, 1);
if (displayFilter.length() > 0)
addGraph(true, graph_name, displayFilter, ColorUtils::graphColor(uat_model_->rowCount()),
IOGraph::psLine, IOG_ITEM_UNIT_PACKETS, QString(), DEFAULT_MOVING_AVERAGE, DEFAULT_Y_AXIS_FACTOR);
}
toggleTracerStyle(true);
iop->setFocus();
iop->rescaleAxes();
ui->clearToolButton->setEnabled(uat_model_->rowCount() != 0);
ui->splitter->setStretchFactor(0, 95);
ui->splitter->setStretchFactor(1, 5);
//XXX - resize columns?
ProgressFrame::addToButtonBox(ui->buttonBox, &parent);
connect(iop, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(graphClicked(QMouseEvent*)));
connect(iop, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMoved(QMouseEvent*)));
connect(iop, SIGNAL(mouseRelease(QMouseEvent*)), this, SLOT(mouseReleased(QMouseEvent*)));
disconnect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
}
IOGraphDialog::~IOGraphDialog()
{
cap_file_.stopLoading();
foreach(IOGraph* iog, ioGraphs_) {
delete iog;
}
delete ui;
ui = NULL;
}
void IOGraphDialog::copyFromProfile(QString filename)
{
guint orig_data_len = iog_uat_->raw_data->len;
gchar *err = NULL;
if (uat_load(iog_uat_, filename.toUtf8().constData(), &err)) {
iog_uat_->changed = TRUE;
uat_model_->reloadUat();
for (guint i = orig_data_len; i < iog_uat_->raw_data->len; i++) {
createIOGraph(i);
}
} else {
report_failure("Error while loading %s: %s", iog_uat_->name, err);
g_free(err);
}
}
void IOGraphDialog::addGraph(bool checked, QString name, QString dfilter, QRgb color_idx, IOGraph::PlotStyles style, io_graph_item_unit_t value_units, QString yfield, int moving_average, int y_axis_factor)
{
QVariantList newRowData;
newRowData.append(checked ? Qt::Checked : Qt::Unchecked);
newRowData.append(name);
newRowData.append(dfilter);
newRowData.append(QColor(color_idx));
newRowData.append(val_to_str_const(style, graph_style_vs, "None"));
if (is_packet_configuration_namespace()) {
newRowData.append(val_to_str_const(value_units, y_axis_vs, "Packets"));
} else {
newRowData.append(val_to_str_const(value_units, y_axis_vs, "Events"));
}
newRowData.append(yfield);
newRowData.append(val_to_str_const((guint32) moving_average, moving_avg_vs, "None"));
newRowData.append(y_axis_factor);
QModelIndex newIndex = uat_model_->appendEntry(newRowData);
if ( !newIndex.isValid() )
{
qDebug() << "Failed to add a new record";
return;
}
ui->graphUat->setCurrentIndex(newIndex);
createIOGraph(newIndex.row());
}
void IOGraphDialog::addGraph(bool copy_from_current)
{
const QModelIndex ¤t = ui->graphUat->currentIndex();
if (copy_from_current && !current.isValid())
return;
QModelIndex copyIdx;
if (copy_from_current) {
copyIdx = uat_model_->copyRow(current);
if (!copyIdx.isValid())
{
qDebug() << "Failed to add a new record";
return;
}
createIOGraph(copyIdx.row());
ui->graphUat->setCurrentIndex(copyIdx);
} else {
addDefaultGraph(false);
copyIdx = uat_model_->index(uat_model_->rowCount() - 1, 0);
}
ui->graphUat->setCurrentIndex(copyIdx);
}
void IOGraphDialog::createIOGraph(int currentRow)
{
// XXX - Should IOGraph have it's own list that has to sync with UAT?
ioGraphs_.append(new IOGraph(ui->ioPlot));
IOGraph* iog = ioGraphs_[currentRow];
connect(this, SIGNAL(recalcGraphData(capture_file *, bool)), iog, SLOT(recalcGraphData(capture_file *, bool)));
connect(this, SIGNAL(reloadValueUnitFields()), iog, SLOT(reloadValueUnitField()));
connect(&cap_file_, SIGNAL(captureEvent(CaptureEvent)),
iog, SLOT(captureEvent(CaptureEvent)));
connect(iog, SIGNAL(requestRetap()), this, SLOT(scheduleRetap()));
connect(iog, SIGNAL(requestRecalc()), this, SLOT(scheduleRecalc()));
connect(iog, SIGNAL(requestReplot()), this, SLOT(scheduleReplot()));
syncGraphSettings(currentRow);
if (iog->visible()) {
scheduleRetap();
}
}
void IOGraphDialog::addDefaultGraph(bool enabled, int idx)
{
if (is_packet_configuration_namespace()) {
switch (idx % 2) {
case 0:
addGraph(enabled, tr("All Packets"), QString(), ColorUtils::graphColor(idx),
IOGraph::psLine, IOG_ITEM_UNIT_PACKETS, QString(), DEFAULT_MOVING_AVERAGE, DEFAULT_Y_AXIS_FACTOR);
break;
default:
addGraph(enabled, tr("TCP Errors"), "tcp.analysis.flags", ColorUtils::graphColor(4), // 4 = red
IOGraph::psBar, IOG_ITEM_UNIT_PACKETS, QString(), DEFAULT_MOVING_AVERAGE, DEFAULT_Y_AXIS_FACTOR);
break;
}
} else {
switch (idx % 2) {
case 0:
addGraph(enabled, tr("All Events"), QString(), ColorUtils::graphColor(idx),
IOGraph::psLine, IOG_ITEM_UNIT_PACKETS, QString(), DEFAULT_MOVING_AVERAGE, DEFAULT_Y_AXIS_FACTOR);
break;
default:
addGraph(enabled, tr("Access Denied"), "ct.error == \"AccessDenied\"", ColorUtils::graphColor(4), // 4 = red
IOGraph::psDot, IOG_ITEM_UNIT_PACKETS, QString(), DEFAULT_MOVING_AVERAGE, DEFAULT_Y_AXIS_FACTOR);
break;
}
}
}
// Sync the settings from UAT model to its IOGraph.
// Disables the graph if any errors are found.
//
// NOTE: Setting dfilter, yaxis and yfield here will all end up in setFilter() and this
// has a chicken-and-egg problem because setFilter() depends on previous assigned
// values for filter_, val_units_ and vu_field_. Setting values in wrong order
// may give unpredicted results because setFilter() does not always set filter_
// on errors.
// TODO: The issues in the above note should be fixed and setFilter() should not be
// called so frequently.
void IOGraphDialog::syncGraphSettings(int row)
{
IOGraph *iog = ioGraphs_.value(row, Q_NULLPTR);
if (!uat_model_->index(row, colEnabled).isValid() || !iog)
return;
bool visible = graphIsEnabled(row);
bool retap = !iog->visible() && visible;
QString data_str;
iog->setName(uat_model_->data(uat_model_->index(row, colName)).toString());
iog->setFilter(uat_model_->data(uat_model_->index(row, colDFilter)).toString());
/* plot style depend on the value unit, so set it first. */
data_str = uat_model_->data(uat_model_->index(row, colYAxis)).toString();
iog->setValueUnits((int) str_to_val(qUtf8Printable(data_str), y_axis_vs, IOG_ITEM_UNIT_PACKETS));
iog->setValueUnitField(uat_model_->data(uat_model_->index(row, colYField)).toString());
iog->setColor(uat_model_->data(uat_model_->index(row, colColor), Qt::DecorationRole).value<QColor>().rgb());
data_str = uat_model_->data(uat_model_->index(row, colStyle)).toString();
iog->setPlotStyle((int) str_to_val(qUtf8Printable(data_str), graph_style_vs, 0));
data_str = uat_model_->data(uat_model_->index(row, colSMAPeriod)).toString();
iog->moving_avg_period_ = str_to_val(qUtf8Printable(data_str), moving_avg_vs, 0);
iog->y_axis_factor_ = uat_model_->data(uat_model_->index(row, colYAxisFactor)).toInt();
iog->setInterval(ui->intervalComboBox->itemData(ui->intervalComboBox->currentIndex()).toInt());
if (!iog->configError().isEmpty()) {
hint_err_ = iog->configError();
visible = false;
retap = false;
} else {
hint_err_.clear();
}
iog->setVisible(visible);
getGraphInfo();
mouseMoved(NULL); // Update hint
updateLegend();
if (visible) {
if (retap) {
scheduleRetap();
} else {
scheduleReplot();
}
}
}
void IOGraphDialog::updateWidgets()
{
WiresharkDialog::updateWidgets();
}
void IOGraphDialog::scheduleReplot(bool now)
{
need_replot_ = true;
if (now) updateStatistics();
// A plot finished, force an update of the legend now in case a time unit
// was involved (which might append "(ms)" to the label).
updateLegend();
}
void IOGraphDialog::scheduleRecalc(bool now)
{
need_recalc_ = true;
if (now) updateStatistics();
}
void IOGraphDialog::scheduleRetap(bool now)
{
need_retap_ = true;
if (now) updateStatistics();
}
void IOGraphDialog::reloadFields()
{
emit reloadValueUnitFields();
}
void IOGraphDialog::keyPressEvent(QKeyEvent *event)
{
int pan_pixels = event->modifiers() & Qt::ShiftModifier ? 1 : 10;
switch(event->key()) {
case Qt::Key_Minus:
case Qt::Key_Underscore: // Shifted minus on U.S. keyboards
case Qt::Key_O: // GTK+
case Qt::Key_R:
zoomAxes(false);
break;
case Qt::Key_Plus:
case Qt::Key_Equal: // Unshifted plus on U.S. keyboards
case Qt::Key_I: // GTK+
zoomAxes(true);
break;
case Qt::Key_X: // Zoom X axis only
if (event->modifiers() & Qt::ShiftModifier) {
zoomXAxis(false); // upper case X -> Zoom out
} else {
zoomXAxis(true); // lower case x -> Zoom in
}
break;
case Qt::Key_Y: // Zoom Y axis only
if (event->modifiers() & Qt::ShiftModifier) {
zoomYAxis(false); // upper case Y -> Zoom out
} else {
zoomYAxis(true); // lower case y -> Zoom in
}
break;
case Qt::Key_Right:
case Qt::Key_L:
panAxes(pan_pixels, 0);
break;
case Qt::Key_Left:
case Qt::Key_H:
panAxes(-1 * pan_pixels, 0);
break;
case Qt::Key_Up:
case Qt::Key_K:
panAxes(0, pan_pixels);
break;
case Qt::Key_Down:
case Qt::Key_J:
panAxes(0, -1 * pan_pixels);
break;
case Qt::Key_Space:
toggleTracerStyle();
break;
case Qt::Key_0:
case Qt::Key_ParenRight: // Shifted 0 on U.S. keyboards
case Qt::Key_Home:
resetAxes();
break;
case Qt::Key_G:
on_actionGoToPacket_triggered();
break;
case Qt::Key_T:
on_actionToggleTimeOrigin_triggered();
break;
case Qt::Key_Z:
on_actionDragZoom_triggered();
break;
}
QDialog::keyPressEvent(event);
}
void IOGraphDialog::reject()
{
if (!uat_model_)
return;
// Changes to the I/O Graphs settings are always saved,
// there is no possibility for "rejection".
QString error;
if (uat_model_->applyChanges(error)) {
if (!error.isEmpty()) {
report_failure("%s", qPrintable(error));
}
}
QDialog::reject();
}
void IOGraphDialog::zoomAxes(bool in)
{
QCustomPlot *iop = ui->ioPlot;
double h_factor = iop->axisRect()->rangeZoomFactor(Qt::Horizontal);
double v_factor = iop->axisRect()->rangeZoomFactor(Qt::Vertical);
auto_axes_ = false;
if (!in) {
h_factor = pow(h_factor, -1);
v_factor = pow(v_factor, -1);
}
iop->xAxis->scaleRange(h_factor, iop->xAxis->range().center());
iop->yAxis->scaleRange(v_factor, iop->yAxis->range().center());
iop->replot();
}
void IOGraphDialog::zoomXAxis(bool in)
{
QCustomPlot *iop = ui->ioPlot;
double h_factor = iop->axisRect()->rangeZoomFactor(Qt::Horizontal);
auto_axes_ = false;
if (!in) {
h_factor = pow(h_factor, -1);
}
iop->xAxis->scaleRange(h_factor, iop->xAxis->range().center());
iop->replot();
}
void IOGraphDialog::zoomYAxis(bool in)
{
QCustomPlot *iop = ui->ioPlot;
double v_factor = iop->axisRect()->rangeZoomFactor(Qt::Vertical);
auto_axes_ = false;
if (!in) {
v_factor = pow(v_factor, -1);
}
iop->yAxis->scaleRange(v_factor, iop->yAxis->range().center());
iop->replot();
}
void IOGraphDialog::panAxes(int x_pixels, int y_pixels)
{
QCustomPlot *iop = ui->ioPlot;
double h_pan = 0.0;
double v_pan = 0.0;
auto_axes_ = false;
h_pan = iop->xAxis->range().size() * x_pixels / iop->xAxis->axisRect()->width();
v_pan = iop->yAxis->range().size() * y_pixels / iop->yAxis->axisRect()->height();
// The GTK+ version won't pan unless we're zoomed. Should we do the same here?
if (h_pan) {
iop->xAxis->moveRange(h_pan);
iop->replot();
}
if (v_pan) {
iop->yAxis->moveRange(v_pan);
iop->replot();
}
}
void IOGraphDialog::toggleTracerStyle(bool force_default)
{
if (!tracer_->visible() && !force_default) return;
if (!ui->ioPlot->graph(0)) return;
QPen sp_pen = ui->ioPlot->graph(0)->pen();
QCPItemTracer::TracerStyle tstyle = QCPItemTracer::tsCrosshair;
QPen tr_pen = QPen(tracer_->pen());
QColor tr_color = sp_pen.color();
if (force_default || tracer_->style() != QCPItemTracer::tsCircle) {
tstyle = QCPItemTracer::tsCircle;
tr_color.setAlphaF(1.0);
tr_pen.setWidthF(1.5);
} else {
tr_color.setAlphaF(0.5);
tr_pen.setWidthF(1.0);
}
tracer_->setStyle(tstyle);
tr_pen.setColor(tr_color);
tracer_->setPen(tr_pen);
ui->ioPlot->replot();
}
// Returns the IOGraph which is most likely to be used by the user. This is the
// currently selected, visible graph or the first visible graph otherwise.
IOGraph *IOGraphDialog::currentActiveGraph() const
{
QModelIndex index = ui->graphUat->currentIndex();
if (index.isValid()) {
return ioGraphs_.value(index.row(), NULL);
}
//if no currently selected item, go with first item enabled
for (int row = 0; row < uat_model_->rowCount(); row++)
{
if (graphIsEnabled(row)) {
return ioGraphs_.value(row, NULL);
}
}
return NULL;
}
bool IOGraphDialog::graphIsEnabled(int row) const
{
Qt::CheckState state = static_cast<Qt::CheckState>(uat_model_->data(uat_model_->index(row, colEnabled), Qt::CheckStateRole).toInt());
return state == Qt::Checked;
}
// Scan through our graphs and gather information.
// QCPItemTracers can only be associated with QCPGraphs. Find the first one
// and associate it with our tracer. Set bar stacking order while we're here.
void IOGraphDialog::getGraphInfo()
{
base_graph_ = NULL;
QCPBars *prev_bars = NULL;
start_time_ = 0.0;
tracer_->setGraph(NULL);
IOGraph *selectedGraph = currentActiveGraph();
if (uat_model_ != NULL) {
//all graphs may not be created yet, so bounds check the graph array
for (int row = 0; row < uat_model_->rowCount(); row++) {
IOGraph* iog = ioGraphs_.value(row, Q_NULLPTR);
if (iog && graphIsEnabled(row)) {
QCPGraph *graph = iog->graph();
QCPBars *bars = iog->bars();
if (graph && (!base_graph_ || iog == selectedGraph)) {
base_graph_ = graph;
} else if (bars &&
(uat_model_->data(uat_model_->index(row, colStyle), Qt::DisplayRole).toString().compare(graph_style_vs[IOGraph::psStackedBar].strptr) == 0) &&
iog->visible()) {
bars->moveBelow(NULL); // Remove from existing stack
bars->moveBelow(prev_bars);
prev_bars = bars;
}
if (iog->visible() && iog->maxInterval() >= 0) {
double iog_start = iog->startOffset();
if (start_time_ == 0.0 || iog_start < start_time_) {
start_time_ = iog_start;
}
}
}
}
}
if (base_graph_ && base_graph_->data()->size() > 0) {
tracer_->setGraph(base_graph_);
tracer_->setVisible(true);
}
}
void IOGraphDialog::updateLegend()
{
QCustomPlot *iop = ui->ioPlot;
QSet<QString> vu_label_set;
QString intervalText = ui->intervalComboBox->itemText(ui->intervalComboBox->currentIndex());
iop->legend->setVisible(false);
iop->yAxis->setLabel(QString());
// Find unique labels
if (uat_model_ != NULL) {
for (int row = 0; row < uat_model_->rowCount(); row++) {
IOGraph *iog = ioGraphs_.value(row, Q_NULLPTR);
if (graphIsEnabled(row) && iog) {
QString label(iog->valueUnitLabel());
if (!iog->scaledValueUnit().isEmpty()) {
label += " (" + iog->scaledValueUnit() + ")";
}
vu_label_set.insert(label);
}
}
}
// Nothing.
if (vu_label_set.size() < 1) {
return;
}
// All the same. Use the Y Axis label.
if (vu_label_set.size() == 1) {
iop->yAxis->setLabel(vu_label_set.values()[0] + "/" + intervalText);
return;
}
// Differing labels. Create a legend with a Title label at top.
// Legend Title thanks to: https://www.qcustomplot.com/index.php/support/forum/443
QCPTextElement* legendTitle = qobject_cast<QCPTextElement*>(iop->legend->elementAt(0));
if (legendTitle == NULL) {
legendTitle = new QCPTextElement(iop, QString(""));
iop->legend->insertRow(0);
iop->legend->addElement(0, 0, legendTitle);
}
legendTitle->setText(QString(intervalText + " Intervals "));
if (uat_model_ != NULL) {
for (int row = 0; row < uat_model_->rowCount(); row++) {
IOGraph *iog = ioGraphs_.value(row, Q_NULLPTR);
if (iog) {
if (graphIsEnabled(row)) {
iog->addToLegend();
} else {
iog->removeFromLegend();
}
}
}
}
// Only show legend if the user requested it
if (prefs.gui_io_graph_enable_legend) {
iop->legend->setVisible(true);
}
else {
iop->legend->setVisible(false);
}
}
QRectF IOGraphDialog::getZoomRanges(QRect zoom_rect)
{
QRectF zoom_ranges = QRectF();
if (zoom_rect.width() < min_zoom_pixels_ && zoom_rect.height() < min_zoom_pixels_) {
return zoom_ranges;
}
QCustomPlot *iop = ui->ioPlot;
QRect zr = zoom_rect.normalized();
QRect ar = iop->axisRect()->rect();
if (ar.intersects(zr)) {
QRect zsr = ar.intersected(zr);
zoom_ranges.setX(iop->xAxis->range().lower
+ iop->xAxis->range().size() * (zsr.left() - ar.left()) / ar.width());
zoom_ranges.setWidth(iop->xAxis->range().size() * zsr.width() / ar.width());
// QRects grow down
zoom_ranges.setY(iop->yAxis->range().lower
+ iop->yAxis->range().size() * (ar.bottom() - zsr.bottom()) / ar.height());
zoom_ranges.setHeight(iop->yAxis->range().size() * zsr.height() / ar.height());
}
return zoom_ranges;
}
void IOGraphDialog::graphClicked(QMouseEvent *event)
{
QCustomPlot *iop = ui->ioPlot;
if (event->button() == Qt::RightButton) {
// XXX We should find some way to get ioPlot to handle a
// contextMenuEvent instead.
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
ctx_menu_.popup(event->globalPosition().toPoint());
#else
ctx_menu_.popup(event->globalPos());
#endif
} else if (mouse_drags_) {
if (iop->axisRect()->rect().contains(event->pos())) {
iop->setCursor(QCursor(Qt::ClosedHandCursor));
}
on_actionGoToPacket_triggered();
} else {
if (!rubber_band_) {
rubber_band_ = new QRubberBand(QRubberBand::Rectangle, iop);
}
rb_origin_ = event->pos();
rubber_band_->setGeometry(QRect(rb_origin_, QSize()));
rubber_band_->show();
}
iop->setFocus();
}
void IOGraphDialog::mouseMoved(QMouseEvent *event)
{
QCustomPlot *iop = ui->ioPlot;
QString hint;
Qt::CursorShape shape = Qt::ArrowCursor;
// XXX: ElidedLabel doesn't support rich text / HTML, we
// used to bold this error
if (!hint_err_.isEmpty()) {
hint += QString("%1 ").arg(hint_err_);
}
if (event) {
if (event->buttons().testFlag(Qt::LeftButton)) {
if (mouse_drags_) {
shape = Qt::ClosedHandCursor;
} else {
shape = Qt::CrossCursor;
}
} else if (iop->axisRect()->rect().contains(event->pos())) {
if (mouse_drags_) {
shape = Qt::OpenHandCursor;
} else {
shape = Qt::CrossCursor;
}
}
iop->setCursor(QCursor(shape));
}
if (mouse_drags_) {
double ts = 0;
packet_num_ = 0;
int interval_packet = -1;
if (event && tracer_->graph()) {
tracer_->setGraphKey(iop->xAxis->pixelToCoord(event->pos().x()));
ts = tracer_->position->key();
if (IOGraph *iog = currentActiveGraph()) {
interval_packet = iog->packetFromTime(ts - start_time_);
}
}
if (interval_packet < 0) {
hint += tr("Hover over the graph for details.");
} else {
QString msg = is_packet_configuration_namespace() ? tr("No packets in interval") : tr("No events in interval");
QString val;
if (interval_packet > 0) {
packet_num_ = (guint32) interval_packet;
if (is_packet_configuration_namespace()) {
msg = QString("%1 %2")
.arg(!file_closed_ ? tr("Click to select packet") : tr("Packet"))
.arg(packet_num_);
} else {
msg = QString("%1 %2")
.arg(!file_closed_ ? tr("Click to select event") : tr("Event"))
.arg(packet_num_);
}
val = " = " + QString::number(tracer_->position->value(), 'g', 4);
}
hint += tr("%1 (%2s%3).")
.arg(msg)
.arg(QString::number(ts, 'g', 4))
.arg(val);
}
iop->replot();
} else {
if (event && rubber_band_ && rubber_band_->isVisible()) {
rubber_band_->setGeometry(QRect(rb_origin_, event->pos()).normalized());
QRectF zoom_ranges = getZoomRanges(QRect(rb_origin_, event->pos()));
if (zoom_ranges.width() > 0.0 && zoom_ranges.height() > 0.0) {
hint += tr("Release to zoom, x = %1 to %2, y = %3 to %4")
.arg(zoom_ranges.x())
.arg(zoom_ranges.x() + zoom_ranges.width())
.arg(zoom_ranges.y())
.arg(zoom_ranges.y() + zoom_ranges.height());
} else {
hint += tr("Unable to select range.");
}
} else {
hint += tr("Click to select a portion of the graph.");
}
}
ui->hintLabel->setText(hint);
}
void IOGraphDialog::mouseReleased(QMouseEvent *event)
{
QCustomPlot *iop = ui->ioPlot;
auto_axes_ = false;
if (rubber_band_) {
rubber_band_->hide();
if (!mouse_drags_) {
QRectF zoom_ranges = getZoomRanges(QRect(rb_origin_, event->pos()));
if (zoom_ranges.width() > 0.0 && zoom_ranges.height() > 0.0) {
iop->xAxis->setRangeLower(zoom_ranges.x());
iop->xAxis->setRangeUpper(zoom_ranges.x() + zoom_ranges.width());
iop->yAxis->setRangeLower(zoom_ranges.y());
iop->yAxis->setRangeUpper(zoom_ranges.y() + zoom_ranges.height());
iop->replot();
}
}
} else if (iop->cursor().shape() == Qt::ClosedHandCursor) {
iop->setCursor(QCursor(Qt::OpenHandCursor));
}
}
void IOGraphDialog::resetAxes()
{
QCustomPlot *iop = ui->ioPlot;
QCPRange x_range = iop->xAxis->scaleType() == QCPAxis::stLogarithmic ?
iop->xAxis->range().sanitizedForLogScale() : iop->xAxis->range();
double pixel_pad = 10.0; // per side
iop->rescaleAxes(true);
double axis_pixels = iop->xAxis->axisRect()->width();
iop->xAxis->scaleRange((axis_pixels + (pixel_pad * 2)) / axis_pixels, x_range.center());
axis_pixels = iop->yAxis->axisRect()->height();
iop->yAxis->scaleRange((axis_pixels + (pixel_pad * 2)) / axis_pixels, iop->yAxis->range().center());
auto_axes_ = true;
iop->replot();
}
void IOGraphDialog::updateStatistics()
{
if (!isVisible()) return;
if (need_retap_ && !file_closed_ && prefs.gui_io_graph_automatic_update) {
need_retap_ = false;
cap_file_.retapPackets();
// The user might have closed the window while tapping, which means
// we might no longer exist.
} else {
if (need_recalc_ && !file_closed_ && prefs.gui_io_graph_automatic_update) {
need_recalc_ = false;
need_replot_ = true;
int enabled_graphs = 0;
if (uat_model_ != NULL) {
for (int row = 0; row < uat_model_->rowCount(); row++) {
if (graphIsEnabled(row)) {
++enabled_graphs;
}
}
}
// With multiple visible graphs, disable Y scaling to avoid
// multiple, distinct units.
emit recalcGraphData(cap_file_.capFile(), enabled_graphs == 1);
if (!tracer_->graph()) {
if (base_graph_ && base_graph_->data()->size() > 0) {
tracer_->setGraph(base_graph_);
tracer_->setVisible(true);
} else {
tracer_->setVisible(false);
}
}
}
if (need_replot_) {
need_replot_ = false;
if (auto_axes_) {
resetAxes();
}
ui->ioPlot->replot();
}
}
}
void IOGraphDialog::loadProfileGraphs()
{
if (iog_uat_ == NULL) {
iog_uat_ = uat_new("I/O Graphs",
sizeof(io_graph_settings_t),
"io_graphs",
TRUE,
&iog_settings_,
&num_io_graphs_,
0, /* doesn't affect anything that requires a GUI update */
"ChStatIOGraphs",
io_graph_copy_cb,
NULL,
io_graph_free_cb,
NULL,
NULL,
io_graph_fields);
uat_set_default_values(iog_uat_, iog_uat_defaults_);
char* err = NULL;
if (!uat_load(iog_uat_, NULL, &err)) {
report_failure("Error while loading %s: %s. Default graph values will be used", iog_uat_->name, err);
g_free(err);
uat_clear(iog_uat_);
}
}
uat_model_ = new UatModel(NULL, iog_uat_);
uat_delegate_ = new UatDelegate;
ui->graphUat->setModel(uat_model_);
ui->graphUat->setItemDelegate(uat_delegate_);
connect(uat_model_, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this, SLOT(modelDataChanged(QModelIndex)));
connect(uat_model_, SIGNAL(modelReset()), this, SLOT(modelRowsReset()));
}
// Slots
void IOGraphDialog::on_intervalComboBox_currentIndexChanged(int)
{
int interval = ui->intervalComboBox->itemData(ui->intervalComboBox->currentIndex()).toInt();
bool need_retap = false;
if (uat_model_ != NULL) {
for (int row = 0; row < uat_model_->rowCount(); row++) {
IOGraph *iog = ioGraphs_.value(row, NULL);
if (iog) {
iog->setInterval(interval);
if (iog->visible()) {
need_retap = true;
}
}
}
}
if (need_retap) {
scheduleRetap(true);
}
updateLegend();
}
void IOGraphDialog::on_todCheckBox_toggled(bool checked)
{
double orig_start = start_time_;
bool orig_auto = auto_axes_;
if (checked) {
ui->ioPlot->xAxis->setTicker(datetime_ticker_);
} else {
ui->ioPlot->xAxis->setTicker(number_ticker_);
}
auto_axes_ = false;
scheduleRecalc(true);
auto_axes_ = orig_auto;
getGraphInfo();
ui->ioPlot->xAxis->moveRange(start_time_ - orig_start);
mouseMoved(NULL); // Update hint
}
void IOGraphDialog::modelRowsReset()
{
ui->deleteToolButton->setEnabled(false);
ui->copyToolButton->setEnabled(false);
ui->clearToolButton->setEnabled(uat_model_->rowCount() != 0);
}
void IOGraphDialog::on_graphUat_currentItemChanged(const QModelIndex ¤t, const QModelIndex&)
{
if (current.isValid()) {
ui->deleteToolButton->setEnabled(true);
ui->copyToolButton->setEnabled(true);
ui->clearToolButton->setEnabled(true);
ui->moveUpwardsToolButton->setEnabled(true);
ui->moveDownwardsToolButton->setEnabled(true);
} else {
ui->deleteToolButton->setEnabled(false);
ui->copyToolButton->setEnabled(false);
ui->clearToolButton->setEnabled(false);
ui->moveUpwardsToolButton->setEnabled(false);
ui->moveDownwardsToolButton->setEnabled(false);
}
}
void IOGraphDialog::modelDataChanged(const QModelIndex &index)
{
bool recalc = false;
switch (index.column())
{
case colYAxis:
case colSMAPeriod:
recalc = true;
}
syncGraphSettings(index.row());
if (recalc) {
scheduleRecalc(true);
} else {
scheduleReplot(true);
}
}
void IOGraphDialog::on_resetButton_clicked()
{
resetAxes();
}
void IOGraphDialog::on_newToolButton_clicked()
{
addGraph();
}
void IOGraphDialog::on_deleteToolButton_clicked()
{
const QModelIndex ¤t = ui->graphUat->currentIndex();
if (uat_model_ && current.isValid()) {
delete ioGraphs_[current.row()];
ioGraphs_.remove(current.row());
if (!uat_model_->removeRows(current.row(), 1)) {
qDebug() << "Failed to remove row";
}
}
// We should probably be smarter about this.
hint_err_.clear();
mouseMoved(NULL);
}
void IOGraphDialog::on_copyToolButton_clicked()
{
addGraph(true);
}
void IOGraphDialog::on_clearToolButton_clicked()
{
if (uat_model_) {
foreach(IOGraph* iog, ioGraphs_) {
delete iog;
}
ioGraphs_.clear();
uat_model_->clearAll();
}
hint_err_.clear();
mouseMoved(NULL);
}
void IOGraphDialog::on_moveUpwardsToolButton_clicked()
{
const QModelIndex& current = ui->graphUat->currentIndex();
if (uat_model_ && current.isValid()) {
int current_row = current.row();
if (current_row > 0){
// Swap current row with the one above
IOGraph* temp = ioGraphs_[current_row - 1];
ioGraphs_[current_row - 1] = ioGraphs_[current_row];
ioGraphs_[current_row] = temp;
uat_model_->moveRow(current_row, current_row - 1);
}
}
}
void IOGraphDialog::on_moveDownwardsToolButton_clicked()
{
const QModelIndex& current = ui->graphUat->currentIndex();
if (uat_model_ && current.isValid()) {
int current_row = current.row();
if (current_row < uat_model_->rowCount() - 1) {
// Swap current row with the one below
IOGraph* temp = ioGraphs_[current_row + 1];
ioGraphs_[current_row + 1] = ioGraphs_[current_row];
ioGraphs_[current_row] = temp;
uat_model_->moveRow(current_row, current_row + 1);
}
}
}
void IOGraphDialog::on_dragRadioButton_toggled(bool checked)
{
if (checked) mouse_drags_ = true;
ui->ioPlot->setInteractions(
QCP::iRangeDrag |
QCP::iRangeZoom
);
}
void IOGraphDialog::on_zoomRadioButton_toggled(bool checked)
{
if (checked) mouse_drags_ = false;
ui->ioPlot->setInteractions(QCP::Interactions());
}
void IOGraphDialog::on_logCheckBox_toggled(bool checked)
{
QCustomPlot *iop = ui->ioPlot;
iop->yAxis->setScaleType(checked ? QCPAxis::stLogarithmic : QCPAxis::stLinear);
iop->replot();
}
void IOGraphDialog::on_automaticUpdateCheckBox_toggled(bool checked)
{
prefs.gui_io_graph_automatic_update = checked ? TRUE : FALSE;
prefs_main_write();
if(prefs.gui_io_graph_automatic_update)
{
updateStatistics();
}
}
void IOGraphDialog::on_enableLegendCheckBox_toggled(bool checked)
{
prefs.gui_io_graph_enable_legend = checked ? TRUE : FALSE;
prefs_main_write();
updateLegend();
}
void IOGraphDialog::on_actionReset_triggered()
{
on_resetButton_clicked();
}
void IOGraphDialog::on_actionZoomIn_triggered()
{
zoomAxes(true);
}
void IOGraphDialog::on_actionZoomInX_triggered()
{
zoomXAxis(true);
}
void IOGraphDialog::on_actionZoomInY_triggered()
{
zoomYAxis(true);
}
void IOGraphDialog::on_actionZoomOut_triggered()
{
zoomAxes(false);
}
void IOGraphDialog::on_actionZoomOutX_triggered()
{
zoomXAxis(false);
}
void IOGraphDialog::on_actionZoomOutY_triggered()
{
zoomYAxis(false);
}
void IOGraphDialog::on_actionMoveUp10_triggered()
{
panAxes(0, 10);
}
void IOGraphDialog::on_actionMoveLeft10_triggered()
{
panAxes(-10, 0);
}
void IOGraphDialog::on_actionMoveRight10_triggered()
{
panAxes(10, 0);
}
void IOGraphDialog::on_actionMoveDown10_triggered()
{
panAxes(0, -10);
}
void IOGraphDialog::on_actionMoveUp1_triggered()
{
panAxes(0, 1);
}
void IOGraphDialog::on_actionMoveLeft1_triggered()
{
panAxes(-1, 0);
}
void IOGraphDialog::on_actionMoveRight1_triggered()
{
panAxes(1, 0);
}
void IOGraphDialog::on_actionMoveDown1_triggered()
{
panAxes(0, -1);
}
void IOGraphDialog::on_actionGoToPacket_triggered()
{
if (tracer_->visible() && !file_closed_ && packet_num_ > 0) {
emit goToPacket(packet_num_);
}
}
void IOGraphDialog::on_actionDragZoom_triggered()
{
if (mouse_drags_) {
ui->zoomRadioButton->toggle();
} else {
ui->dragRadioButton->toggle();
}
}
void IOGraphDialog::on_actionToggleTimeOrigin_triggered()
{
}
void IOGraphDialog::on_actionCrosshairs_triggered()
{
}
void IOGraphDialog::on_buttonBox_helpRequested()
{
mainApp->helpTopicAction(HELP_STATS_IO_GRAPH_DIALOG);
}
// XXX - We have similar code in tcp_stream_dialog and packet_diagram. Should this be a common routine?
void IOGraphDialog::on_buttonBox_accepted()
{
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 csv_filter = tr("Comma Separated Values (*.csv)");
QString filter = QString("%1;;%2;;%3;;%4;;%5")
.arg(pdf_filter)
.arg(png_filter)
.arg(bmp_filter)
.arg(jpeg_filter)
.arg(csv_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.length() > 0) {
bool save_ok = false;
if (extension.compare(pdf_filter) == 0) {
save_ok = ui->ioPlot->savePdf(file_name);
} else if (extension.compare(png_filter) == 0) {
save_ok = ui->ioPlot->savePng(file_name);
} else if (extension.compare(bmp_filter) == 0) {
save_ok = ui->ioPlot->saveBmp(file_name);
} else if (extension.compare(jpeg_filter) == 0) {
save_ok = ui->ioPlot->saveJpg(file_name);
} else if (extension.compare(csv_filter) == 0) {
save_ok = saveCsv(file_name);
}
// else error dialog?
if (save_ok) {
mainApp->setLastOpenDirFromFilename(file_name);
}
}
}
void IOGraphDialog::makeCsv(QTextStream &stream) const
{
QList<IOGraph *> activeGraphs;
int ui_interval = ui->intervalComboBox->itemData(ui->intervalComboBox->currentIndex()).toInt();
int max_interval = 0;
stream << "\"Interval start\"";
if (uat_model_ != NULL) {
for (int row = 0; row < uat_model_->rowCount(); row++) {
if (graphIsEnabled(row) && ioGraphs_[row] != NULL) {
activeGraphs.append(ioGraphs_[row]);
if (max_interval < ioGraphs_[row]->maxInterval()) {
max_interval = ioGraphs_[row]->maxInterval();
}
QString name = ioGraphs_[row]->name().toUtf8();
name = QString("\"%1\"").arg(name.replace("\"", "\"\"")); // RFC 4180
stream << "," << name;
}
}
}
stream << '\n';
for (int interval = 0; interval <= max_interval; interval++) {
double interval_start = (double)interval * ((double)ui_interval / 1000.0);
stream << interval_start;
foreach (IOGraph *iog, activeGraphs) {
double value = 0.0;
if (interval <= iog->maxInterval()) {
value = iog->getItemValue(interval, cap_file_.capFile());
}
stream << "," << value;
}
stream << '\n';
}
}
void IOGraphDialog::copyAsCsvClicked()
{
QString csv;
QTextStream stream(&csv, QIODevice::Text);
makeCsv(stream);
mainApp->clipboard()->setText(stream.readAll());
}
bool IOGraphDialog::saveCsv(const QString &file_name) const
{
QFile save_file(file_name);
save_file.open(QFile::WriteOnly | QFile::Text);
QTextStream out(&save_file);
makeCsv(out);
return true;
}
// IOGraph
IOGraph::IOGraph(QCustomPlot *parent) :
parent_(parent),
visible_(false),
graph_(NULL),
bars_(NULL),
val_units_(IOG_ITEM_UNIT_FIRST),
hf_index_(-1),
cur_idx_(-1)
{
Q_ASSERT(parent_ != NULL);
graph_ = parent_->addGraph(parent_->xAxis, parent_->yAxis);
Q_ASSERT(graph_ != NULL);
GString *error_string;
error_string = register_tap_listener("frame",
this,
"",
TL_REQUIRES_PROTO_TREE,
tapReset,
tapPacket,
tapDraw,
NULL);
if (error_string) {
// QMessageBox::critical(this, tr("%1 failed to register tap listener").arg(name_),
// error_string->str);
// config_err_ = error_string->str;
g_string_free(error_string, TRUE);
}
}
IOGraph::~IOGraph() {
remove_tap_listener(this);
if (graph_) {
parent_->removeGraph(graph_);
}
if (bars_) {
parent_->removePlottable(bars_);
}
}
// Construct a full filter string from the display filter and value unit / Y axis.
// Check for errors and sets config_err_ if any are found.
void IOGraph::setFilter(const QString &filter)
{
GString *error_string;
QString full_filter(filter.trimmed());
config_err_.clear();
// Make sure we have a good display filter
if (!full_filter.isEmpty()) {
dfilter_t *dfilter;
bool status;
df_error_t *df_err = NULL;
status = dfilter_compile(full_filter.toUtf8().constData(), &dfilter, &df_err);
dfilter_free(dfilter);
if (!status) {
config_err_ = QString::fromUtf8(df_err->msg);
df_error_free(&df_err);
filter_ = full_filter;
return;
}
}
// Check our value unit + field combo.
error_string = check_field_unit(vu_field_.toUtf8().constData(), NULL, val_units_);
if (error_string) {
config_err_ = error_string->str;
g_string_free(error_string, TRUE);
return;
}
// Make sure vu_field_ survives edt tree pruning by adding it to our filter
// expression.
if (val_units_ >= IOG_ITEM_UNIT_CALC_SUM && !vu_field_.isEmpty() && hf_index_ >= 0) {
if (full_filter.isEmpty()) {
full_filter = vu_field_;
} else {
full_filter += QString(" && (%1)").arg(vu_field_);
}
}
error_string = set_tap_dfilter(this, full_filter.toUtf8().constData());
if (error_string) {
config_err_ = error_string->str;
g_string_free(error_string, TRUE);
return;
} else {
if (filter_.compare(filter) && visible_) {
emit requestRetap();
}
filter_ = filter;
}
}
void IOGraph::applyCurrentColor()
{
if (graph_) {
graph_->setPen(QPen(color_, graph_line_width_));
} else if (bars_) {
bars_->setPen(QPen(QBrush(ColorUtils::graphColor(0)), graph_line_width_)); // ...or omit it altogether?
bars_->setBrush(color_);
}
}
void IOGraph::setVisible(bool visible)
{
bool old_visibility = visible_;
visible_ = visible;
if (graph_) {
graph_->setVisible(visible_);
}
if (bars_) {
bars_->setVisible(visible_);
}
if (old_visibility != visible_) {
emit requestReplot();
}
}
void IOGraph::setName(const QString &name)
{
name_ = name;
if (graph_) {
graph_->setName(name_);
}
if (bars_) {
bars_->setName(name_);
}
}
QRgb IOGraph::color()
{
return color_.color().rgb();
}
void IOGraph::setColor(const QRgb color)
{
color_ = QBrush(color);
applyCurrentColor();
}
void IOGraph::setPlotStyle(int style)
{
// Switch plottable if needed
switch (style) {
case psBar:
case psStackedBar:
if (graph_) {
bars_ = new QCPBars(parent_->xAxis, parent_->yAxis);
parent_->removeGraph(graph_);
graph_ = NULL;
}
break;
default:
if (bars_) {
graph_ = parent_->addGraph(parent_->xAxis, parent_->yAxis);
parent_->removePlottable(bars_);
bars_ = NULL;
}
break;
}
setValueUnits(val_units_);
if (graph_) {
graph_->setLineStyle(QCPGraph::lsNone);
graph_->setScatterStyle(QCPScatterStyle::ssNone);
}
switch (style) {
case psLine:
if (graph_) {
graph_->setLineStyle(QCPGraph::lsLine);
}
break;
case psDotLine:
if (graph_) {
graph_->setLineStyle(QCPGraph::lsLine);
graph_->setScatterStyle(QCPScatterStyle::ssDisc);
}
break;
case psStepLine:
if (graph_) {
graph_->setLineStyle(QCPGraph::lsStepLeft);
}
break;
case psDotStepLine:
if (graph_) {
graph_->setLineStyle(QCPGraph::lsStepLeft);
graph_->setScatterStyle(QCPScatterStyle::ssDisc);
}
break;
case psImpulse:
if (graph_) {
graph_->setLineStyle(QCPGraph::lsImpulse);
}
break;
case psDot:
if (graph_) {
graph_->setScatterStyle(QCPScatterStyle::ssDisc);
}
break;
case psSquare:
if (graph_) {
graph_->setScatterStyle(QCPScatterStyle::ssSquare);
}
break;
case psDiamond:
if (graph_) {
graph_->setScatterStyle(QCPScatterStyle::ssDiamond);
}
break;
case psCross:
if (graph_) {
graph_->setScatterStyle(QCPScatterStyle::ssCross);
}
break;
case psPlus:
if (graph_) {
graph_->setScatterStyle(QCPScatterStyle::ssPlus);
}
break;
case psCircle:
if (graph_) {
graph_->setScatterStyle(QCPScatterStyle::ssCircle);
}
break;
case psBar:
case IOGraph::psStackedBar:
// Stacking set in scanGraphs
bars_->moveBelow(NULL);
break;
}
setName(name_);
applyCurrentColor();
}
const QString IOGraph::valueUnitLabel()
{
return val_to_str_const(val_units_, y_axis_vs, "Unknown");
}
void IOGraph::setValueUnits(int val_units)
{
if (val_units >= IOG_ITEM_UNIT_FIRST && val_units <= IOG_ITEM_UNIT_LAST) {
int old_val_units = val_units_;
val_units_ = (io_graph_item_unit_t)val_units;
if (old_val_units != val_units) {
setFilter(filter_); // Check config & prime vu field
if (val_units < IOG_ITEM_UNIT_CALC_SUM) {
emit requestRecalc();
}
}
}
}
void IOGraph::setValueUnitField(const QString &vu_field)
{
int old_hf_index = hf_index_;
vu_field_ = vu_field.trimmed();
hf_index_ = -1;
header_field_info *hfi = proto_registrar_get_byname(vu_field_.toUtf8().constData());
if (hfi) {
hf_index_ = hfi->id;
}
if (old_hf_index != hf_index_) {
setFilter(filter_); // Check config & prime vu field
}
}
bool IOGraph::addToLegend()
{
if (graph_) {
return graph_->addToLegend();
}
if (bars_) {
return bars_->addToLegend();
}
return false;
}
bool IOGraph::removeFromLegend()
{
if (graph_) {
return graph_->removeFromLegend();
}
if (bars_) {
return bars_->removeFromLegend();
}
return false;
}
double IOGraph::startOffset()
{
if (graph_ && qSharedPointerDynamicCast<QCPAxisTickerDateTime>(graph_->keyAxis()->ticker()) && graph_->data()->size() > 0) {
return graph_->data()->at(0)->key;
}
if (bars_ && qSharedPointerDynamicCast<QCPAxisTickerDateTime>(bars_->keyAxis()->ticker()) && bars_->data()->size() > 0) {
return bars_->data()->at(0)->key;
}
return 0.0;
}
int IOGraph::packetFromTime(double ts)
{
int idx = ts * 1000 / interval_;
if (idx >= 0 && idx < (int) cur_idx_) {
switch (val_units_) {
case IOG_ITEM_UNIT_CALC_MAX:
case IOG_ITEM_UNIT_CALC_MIN:
return items_[idx].extreme_frame_in_invl;
default:
return items_[idx].last_frame_in_invl;
}
}
return -1;
}
void IOGraph::clearAllData()
{
cur_idx_ = -1;
reset_io_graph_items(items_, max_io_items_);
if (graph_) {
graph_->data()->clear();
}
if (bars_) {
bars_->data()->clear();
}
start_time_ = 0.0;
}
void IOGraph::recalcGraphData(capture_file *cap_file, bool enable_scaling)
{
/* Moving average variables */
unsigned int mavg_in_average_count = 0, mavg_left = 0;
unsigned int mavg_to_remove = 0, mavg_to_add = 0;
double mavg_cumulated = 0;
QCPAxis *x_axis = nullptr;
if (graph_) {
graph_->data()->clear();
x_axis = graph_->keyAxis();
}
if (bars_) {
bars_->data()->clear();
x_axis = bars_->keyAxis();
}
if (moving_avg_period_ > 0 && cur_idx_ >= 0) {
/* "Warm-up phase" - calculate average on some data not displayed;
* just to make sure average on leftmost and rightmost displayed
* values is as reliable as possible
*/
guint64 warmup_interval = 0;
// for (; warmup_interval < first_interval; warmup_interval += interval_) {
// mavg_cumulated += get_it_value(io, i, (int)warmup_interval/interval_);
// mavg_in_average_count++;
// mavg_left++;
// }
mavg_cumulated += getItemValue((int)warmup_interval/interval_, cap_file);
mavg_in_average_count++;
for (warmup_interval = interval_;
((warmup_interval < (0 + (moving_avg_period_ / 2) * (guint64)interval_)) &&
(warmup_interval <= (cur_idx_ * (guint64)interval_)));
warmup_interval += interval_) {
mavg_cumulated += getItemValue((int)warmup_interval / interval_, cap_file);
mavg_in_average_count++;
}
mavg_to_add = (unsigned int)warmup_interval;
}
for (int i = 0; i <= cur_idx_; i++) {
double ts = (double) i * interval_ / 1000;
if (x_axis && qSharedPointerDynamicCast<QCPAxisTickerDateTime>(x_axis->ticker())) {
ts += start_time_;
}
double val = getItemValue(i, cap_file);
if (moving_avg_period_ > 0) {
if (i != 0) {
mavg_left++;
if (mavg_left > moving_avg_period_ / 2) {
mavg_left--;
mavg_in_average_count--;
mavg_cumulated -= getItemValue((int)mavg_to_remove / interval_, cap_file);
mavg_to_remove += interval_;
}
if (mavg_to_add <= (unsigned int) cur_idx_ * interval_) {
mavg_in_average_count++;
mavg_cumulated += getItemValue((int)mavg_to_add / interval_, cap_file);
mavg_to_add += interval_;
}
}
if (mavg_in_average_count > 0) {
val = mavg_cumulated / mavg_in_average_count;
}
}
val *= y_axis_factor_;
if (hasItemToShow(i, val))
{
if (graph_) {
graph_->addData(ts, val);
}
if (bars_) {
bars_->addData(ts, val);
}
}
// qDebug() << "=rgd i" << i << ts << val;
}
// attempt to rescale time values to specific units
if (enable_scaling) {
calculateScaledValueUnit();
} else {
scaled_value_unit_.clear();
}
emit requestReplot();
}
void IOGraph::calculateScaledValueUnit()
{
// Reset unit and recalculate if needed.
scaled_value_unit_.clear();
// If there is no field, scaling is not possible.
if (hf_index_ < 0) {
return;
}
switch (val_units_) {
case IOG_ITEM_UNIT_CALC_SUM:
case IOG_ITEM_UNIT_CALC_MAX:
case IOG_ITEM_UNIT_CALC_MIN:
case IOG_ITEM_UNIT_CALC_AVERAGE:
// Unit is not yet known, continue detecting it.
break;
default:
// Unit is Packets, Bytes, Bits, etc.
return;
}
if (proto_registrar_get_ftype(hf_index_) == FT_RELATIVE_TIME) {
// find maximum absolute value and scale accordingly
double maxValue = 0;
if (graph_) {
maxValue = maxValueFromGraphData(*graph_->data());
} else if (bars_) {
maxValue = maxValueFromGraphData(*bars_->data());
}
// If the maximum value is zero, then either we have no data or
// everything is zero, do not scale the unit in this case.
if (maxValue == 0) {
return;
}
// XXX GTK+ always uses "ms" for log scale, should we do that too?
int value_multiplier;
if (maxValue >= 1.0) {
scaled_value_unit_ = "s";
value_multiplier = 1;
} else if (maxValue >= 0.001) {
scaled_value_unit_ = "ms";
value_multiplier = 1000;
} else {
scaled_value_unit_ = "us";
value_multiplier = 1000000;
}
if (graph_) {
scaleGraphData(*graph_->data(), value_multiplier);
} else if (bars_) {
scaleGraphData(*bars_->data(), value_multiplier);
}
}
}
template<class DataMap>
double IOGraph::maxValueFromGraphData(const DataMap &map)
{
double maxValue = 0;
typename DataMap::const_iterator it = map.constBegin();
while (it != map.constEnd()) {
maxValue = MAX(fabs((*it).value), maxValue);
++it;
}
return maxValue;
}
template<class DataMap>
void IOGraph::scaleGraphData(DataMap &map, int scalar)
{
if (scalar != 1) {
typename DataMap::iterator it = map.begin();
while (it != map.end()) {
(*it).value *= scalar;
++it;
}
}
}
void IOGraph::captureEvent(CaptureEvent e)
{
if ((e.captureContext() == CaptureEvent::File) &&
(e.eventType() == CaptureEvent::Closing))
{
remove_tap_listener(this);
}
}
void IOGraph::reloadValueUnitField()
{
if (vu_field_.length() > 0) {
setValueUnitField(vu_field_);
}
}
// Check if a packet is available at the given interval (idx).
bool IOGraph::hasItemToShow(int idx, double value) const
{
ws_assert(idx < max_io_items_);
bool result = false;
const io_graph_item_t *item = &items_[idx];
switch (val_units_) {
case IOG_ITEM_UNIT_PACKETS:
case IOG_ITEM_UNIT_BYTES:
case IOG_ITEM_UNIT_BITS:
case IOG_ITEM_UNIT_CALC_FRAMES:
case IOG_ITEM_UNIT_CALC_FIELDS:
if(value == 0.0 && (graph_ && graph_->scatterStyle().shape() != QCPScatterStyle::ssNone)) {
result = false;
}
else {
result = true;
}
break;
case IOG_ITEM_UNIT_CALC_SUM:
case IOG_ITEM_UNIT_CALC_MAX:
case IOG_ITEM_UNIT_CALC_MIN:
case IOG_ITEM_UNIT_CALC_AVERAGE:
case IOG_ITEM_UNIT_CALC_LOAD:
if (item->fields) {
result = true;
}
break;
default:
result = true;
break;
}
return result;
}
void IOGraph::setInterval(int interval)
{
interval_ = interval;
}
// Get the value at the given interval (idx) for the current value unit.
double IOGraph::getItemValue(int idx, const capture_file *cap_file) const
{
ws_assert(idx < max_io_items_);
return get_io_graph_item(items_, val_units_, idx, hf_index_, cap_file, interval_, cur_idx_);
}
// "tap_reset" callback for register_tap_listener
void IOGraph::tapReset(void *iog_ptr)
{
IOGraph *iog = static_cast<IOGraph *>(iog_ptr);
if (!iog) return;
// qDebug() << "=tapReset" << iog->name_;
iog->clearAllData();
}
// "tap_packet" callback for register_tap_listener
tap_packet_status IOGraph::tapPacket(void *iog_ptr, packet_info *pinfo, epan_dissect_t *edt, const void *, tap_flags_t)
{
IOGraph *iog = static_cast<IOGraph *>(iog_ptr);
if (!pinfo || !iog) {
return TAP_PACKET_DONT_REDRAW;
}
int idx = get_io_graph_index(pinfo, iog->interval_);
bool recalc = false;
/* some sanity checks */
if ((idx < 0) || (idx >= max_io_items_)) {
iog->cur_idx_ = max_io_items_ - 1;
return TAP_PACKET_DONT_REDRAW;
}
/* update num_items */
if (idx > iog->cur_idx_) {
iog->cur_idx_ = (guint32) idx;
recalc = true;
}
/* set start time */
if (iog->start_time_ == 0.0) {
nstime_t start_nstime;
nstime_set_zero(&start_nstime);
nstime_delta(&start_nstime, &pinfo->abs_ts, &pinfo->rel_ts);
iog->start_time_ = nstime_to_sec(&start_nstime);
}
epan_dissect_t *adv_edt = NULL;
/* For ADVANCED mode we need to keep track of some more stuff than just frame and byte counts */
if (iog->val_units_ >= IOG_ITEM_UNIT_CALC_SUM) {
adv_edt = edt;
}
if (!update_io_graph_item(iog->items_, idx, pinfo, adv_edt, iog->hf_index_, iog->val_units_, iog->interval_)) {
return TAP_PACKET_DONT_REDRAW;
}
// qDebug() << "=tapPacket" << iog->name_ << idx << iog->hf_index_ << iog->val_units_ << iog->num_items_;
if (recalc) {
emit iog->requestRecalc();
}
return TAP_PACKET_REDRAW;
}
// "tap_draw" callback for register_tap_listener
void IOGraph::tapDraw(void *iog_ptr)
{
IOGraph *iog = static_cast<IOGraph *>(iog_ptr);
if (!iog) return;
emit iog->requestRecalc();
if (iog->graph_) {
// qDebug() << "=tapDraw g" << iog->name_ << iog->graph_->data()->keys().size();
}
if (iog->bars_) {
// qDebug() << "=tapDraw b" << iog->name_ << iog->bars_->data()->keys().size();
}
}
// Stat command + args
static void
io_graph_init(const char *, void*) {
mainApp->emitStatCommandSignal("IOGraph", NULL, NULL);
}
static stat_tap_ui io_stat_ui = {
REGISTER_STAT_GROUP_GENERIC,
NULL,
"io,stat",
io_graph_init,
0,
NULL
};
extern "C" {
void register_tap_listener_qt_iostat(void);
void
register_tap_listener_qt_iostat(void)
{
register_stat_tap_ui(&io_stat_ui, NULL);
}
} |
C/C++ | wireshark/ui/qt/io_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 IO_GRAPH_DIALOG_H
#define IO_GRAPH_DIALOG_H
#include <config.h>
#include <glib.h>
#include "epan/epan_dissect.h"
#include "epan/prefs.h"
#include "ui/preference_utils.h"
#include "ui/io_graph_item.h"
#include "wireshark_dialog.h"
#include <ui/qt/models/uat_model.h>
#include <ui/qt/models/uat_delegate.h>
#include <QIcon>
#include <QMenu>
#include <QTextStream>
class QRubberBand;
class QTimer;
class QCPBars;
class QCPGraph;
class QCPItemTracer;
class QCustomPlot;
class QCPAxisTicker;
class QCPAxisTickerDateTime;
// GTK+ sets this to 100000 (NUM_IO_ITEMS)
const int max_io_items_ = 250000;
// XXX - Move to its own file?
class IOGraph : public QObject {
Q_OBJECT
public:
// COUNT_TYPE_* in gtk/io_graph.c
enum PlotStyles { psLine, psDotLine, psStepLine, psDotStepLine, psImpulse, psBar, psStackedBar, psDot, psSquare, psDiamond, psCross, psPlus, psCircle };
explicit IOGraph(QCustomPlot *parent);
~IOGraph();
const QString configError() { return config_err_; }
const QString name() { return name_; }
void setName(const QString &name);
const QString filter() { return filter_; }
void setFilter(const QString &filter);
void applyCurrentColor();
bool visible() { return visible_; }
void setVisible(bool visible);
QRgb color();
void setColor(const QRgb color);
void setPlotStyle(int style);
const QString valueUnitLabel();
void setValueUnits(int val_units);
const QString valueUnitField() { return vu_field_; }
void setValueUnitField(const QString &vu_field);
unsigned int movingAveragePeriod() { return moving_avg_period_; }
void setInterval(int interval);
bool addToLegend();
bool removeFromLegend();
QCPGraph *graph() { return graph_; }
QCPBars *bars() { return bars_; }
double startOffset();
int packetFromTime(double ts);
bool hasItemToShow(int idx, double value) const;
double getItemValue(int idx, const capture_file *cap_file) const;
int maxInterval () const { return cur_idx_; }
QString scaledValueUnit() const { return scaled_value_unit_; }
void clearAllData();
unsigned int moving_avg_period_;
unsigned int y_axis_factor_;
public slots:
void recalcGraphData(capture_file *cap_file, bool enable_scaling);
void captureEvent(CaptureEvent e);
void reloadValueUnitField();
signals:
void requestReplot();
void requestRecalc();
void requestRetap();
private:
// Callbacks for register_tap_listener
static void tapReset(void *iog_ptr);
static tap_packet_status tapPacket(void *iog_ptr, packet_info *pinfo, epan_dissect_t *edt, const void *data, tap_flags_t flags);
static void tapDraw(void *iog_ptr);
void calculateScaledValueUnit();
template<class DataMap> double maxValueFromGraphData(const DataMap &map);
template<class DataMap> void scaleGraphData(DataMap &map, int scalar);
QCustomPlot *parent_;
QString config_err_;
QString name_;
bool visible_;
QCPGraph *graph_;
QCPBars *bars_;
QString filter_;
QBrush color_;
io_graph_item_unit_t val_units_;
QString vu_field_;
int hf_index_;
int interval_;
double start_time_;
QString scaled_value_unit_;
// Cached data. We should be able to change the Y axis without retapping as
// much as is feasible.
io_graph_item_t items_[max_io_items_];
int cur_idx_;
};
namespace Ui {
class IOGraphDialog;
}
class IOGraphDialog : public WiresharkDialog
{
Q_OBJECT
public:
explicit IOGraphDialog(QWidget &parent, CaptureFile &cf, QString displayFilter = QString());
~IOGraphDialog();
enum UatColumns { colEnabled = 0, colName, colDFilter, colColor, colStyle, colYAxis, colYField, colSMAPeriod, colYAxisFactor, colMaxNum};
void addGraph(bool checked, QString name, QString dfilter, QRgb color_idx, IOGraph::PlotStyles style,
io_graph_item_unit_t value_units, QString yfield, int moving_average, int yaxisfactor);
void addGraph(bool copy_from_current = false);
void addDefaultGraph(bool enabled, int idx = 0);
void syncGraphSettings(int row);
public slots:
void scheduleReplot(bool now = false);
void scheduleRecalc(bool now = false);
void scheduleRetap(bool now = false);
void modelRowsReset();
void reloadFields();
protected:
void keyPressEvent(QKeyEvent *event);
void reject();
signals:
void goToPacket(int packet_num);
void recalcGraphData(capture_file *cap_file, bool enable_scaling);
void intervalChanged(int interval);
void reloadValueUnitFields();
private:
Ui::IOGraphDialog *ui;
//Model and delegate were chosen over UatFrame because add/remove/copy
//buttons would need realignment (UatFrame has its own)
UatModel *uat_model_;
UatDelegate *uat_delegate_;
// XXX - This needs to stay synced with UAT index
QVector<IOGraph*> ioGraphs_;
QString hint_err_;
QCPGraph *base_graph_;
QCPItemTracer *tracer_;
guint32 packet_num_;
double start_time_;
bool mouse_drags_;
QRubberBand *rubber_band_;
QPoint rb_origin_;
QMenu ctx_menu_;
QTimer *stat_timer_;
bool need_replot_; // Light weight: tell QCP to replot existing data
bool need_recalc_; // Medium weight: recalculate values, then replot
bool need_retap_; // Heavy weight: re-read packet data
bool auto_axes_;
QSharedPointer<QCPAxisTicker> number_ticker_;
QSharedPointer<QCPAxisTickerDateTime> datetime_ticker_;
// void fillGraph();
void zoomAxes(bool in);
void zoomXAxis(bool in);
void zoomYAxis(bool in);
void panAxes(int x_pixels, int y_pixels);
void toggleTracerStyle(bool force_default = false);
void getGraphInfo();
void updateLegend();
QRectF getZoomRanges(QRect zoom_rect);
void createIOGraph(int currentRow);
void loadProfileGraphs();
void makeCsv(QTextStream &stream) const;
bool saveCsv(const QString &file_name) const;
IOGraph *currentActiveGraph() const;
bool graphIsEnabled(int row) const;
private slots:
void copyFromProfile(QString filename);
void updateWidgets();
void graphClicked(QMouseEvent *event);
void mouseMoved(QMouseEvent *event);
void mouseReleased(QMouseEvent *event);
void resetAxes();
void updateStatistics(void);
void copyAsCsvClicked();
void on_intervalComboBox_currentIndexChanged(int index);
void on_todCheckBox_toggled(bool checked);
void modelDataChanged(const QModelIndex &index);
void on_graphUat_currentItemChanged(const QModelIndex ¤t, const QModelIndex &previous);
void on_resetButton_clicked();
void on_logCheckBox_toggled(bool checked);
void on_automaticUpdateCheckBox_toggled(bool checked);
void on_enableLegendCheckBox_toggled(bool checked);
void on_newToolButton_clicked();
void on_deleteToolButton_clicked();
void on_copyToolButton_clicked();
void on_clearToolButton_clicked();
void on_moveUpwardsToolButton_clicked();
void on_moveDownwardsToolButton_clicked();
void on_dragRadioButton_toggled(bool checked);
void on_zoomRadioButton_toggled(bool checked);
void on_actionReset_triggered();
void on_actionZoomIn_triggered();
void on_actionZoomInX_triggered();
void on_actionZoomInY_triggered();
void on_actionZoomOut_triggered();
void on_actionZoomOutX_triggered();
void on_actionZoomOutY_triggered();
void on_actionMoveUp10_triggered();
void on_actionMoveLeft10_triggered();
void on_actionMoveRight10_triggered();
void on_actionMoveDown10_triggered();
void on_actionMoveUp1_triggered();
void on_actionMoveLeft1_triggered();
void on_actionMoveRight1_triggered();
void on_actionMoveDown1_triggered();
void on_actionGoToPacket_triggered();
void on_actionDragZoom_triggered();
void on_actionToggleTimeOrigin_triggered();
void on_actionCrosshairs_triggered();
void on_buttonBox_helpRequested();
void on_buttonBox_accepted();
};
#endif // IO_GRAPH_DIALOG_H |
User Interface | wireshark/ui/qt/io_graph_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>IOGraphDialog</class>
<widget class="QDialog" name="IOGraphDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>850</width>
<height>640</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<widget class="QWidget" name="">
<layout class="QVBoxLayout" name="verticalLayout" stretch="0,0">
<item>
<widget class="QCustomPlot" name="ioPlot" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>90</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<widget class="ElidedLabel" name="hintLabel">
<property name="toolTip">
<string><html><head/><body>
<h3>Valuable and amazing time-saving keyboard shortcuts</h3>
<table><tbody>
<tr><th>+</th><td>Zoom in</td></th>
<tr><th>-</th><td>Zoom out</td></th>
<tr><th>x</th><td>Zoom in X axis</td></th>
<tr><th>X</th><td>Zoom out X axis</td></th>
<tr><th>y</th><td>Zoom in Y axis</td></th>
<tr><th>Y</th><td>Zoom out Y axis</td></th>
<tr><th>0</th><td>Reset graph to its initial state</td></th>
<tr><th>→</th><td>Move right 10 pixels</td></th>
<tr><th>←</th><td>Move left 10 pixels</td></th>
<tr><th>↑</th><td>Move up 10 pixels</td></th>
<tr><th>↓</th><td>Move down 10 pixels</td></th>
<tr><th><i>Shift+</i>→</th><td>Move right 1 pixel</td></th>
<tr><th><i>Shift+</i>←</th><td>Move left 1 pixel</td></th>
<tr><th><i>Shift+</i>↑</th><td>Move up 1 pixel</td></th>
<tr><th><i>Shift+</i>↓</th><td>Move down 1 pixel</td></th>
<tr><th>g</th><td>Go to packet under cursor</td></th>
<tr><th>z</th><td>Toggle mouse drag / zoom</td></th>
<tr><th>t</th><td>Toggle capture / session time origin</td></th>
<tr><th>Space</th><td>Toggle crosshairs</td></th>
</tbody></table>
</body></html></string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="TabnavTreeView" name="graphUat">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="StockIconToolButton" name="newToolButton">
<property name="toolTip">
<string>Add a new graph.</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<widget class="StockIconToolButton" name="deleteToolButton">
<property name="toolTip">
<string>Remove this graph.</string>
</property>
</widget>
</item>
<item>
<widget class="StockIconToolButton" name="copyToolButton">
<property name="toolTip">
<string>Duplicate this graph.</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<widget class="StockIconToolButton" name="clearToolButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Clear all graphs.</string>
</property>
</widget>
</item>
<item>
<widget class="StockIconToolButton" name="moveUpwardsToolButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Move this graph upwards.</string>
</property>
</widget>
</item>
<item>
<widget class="StockIconToolButton" name="moveDownwardsToolButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="toolTip">
<string>Move this graph downwards.</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_4">
<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="QLabel" name="mouseLabel">
<property name="text">
<string>Mouse</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="dragRadioButton">
<property name="toolTip">
<string>Drag using the mouse button.</string>
</property>
<property name="text">
<string>drags</string>
</property>
<property name="checkable">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="zoomRadioButton">
<property name="toolTip">
<string>Select using the mouse button.</string>
</property>
<property name="text">
<string>zooms</string>
</property>
<property name="checkable">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_3">
<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="QLabel" name="label_2">
<property name="text">
<string>Interval</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="intervalComboBox"/>
</item>
<item>
<spacer name="horizontalSpacer_2">
<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="QCheckBox" name="todCheckBox">
<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>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QCheckBox" name="logCheckBox">
<property name="text">
<string>Log scale</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_1">
<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="QCheckBox" name="automaticUpdateCheckBox">
<property name="text">
<string>Automatic update</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_6">
<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="QCheckBox" name="enableLegendCheckBox">
<property name="text">
<string>Enable legend</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="QPushButton" name="resetButton">
<property name="text">
<string>Reset</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::Close|QDialogButtonBox::Help|QDialogButtonBox::Save</set>
</property>
</widget>
</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="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="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="actionZoomInX">
<property name="text">
<string>Zoom In X Axis</string>
</property>
<property name="toolTip">
<string>Zoom In X Axis</string>
</property>
<property name="shortcut">
<string>X</string>
</property>
</action>
<action name="actionZoomOutX">
<property name="text">
<string>Zoom Out X Axis</string>
</property>
<property name="toolTip">
<string>Zoom Out X Axis</string>
</property>
<property name="shortcut">
<string>Shift+X</string>
</property>
</action>
<action name="actionZoomInY">
<property name="text">
<string>Zoom In Y Axis</string>
</property>
<property name="toolTip">
<string>Zoom In Y Axis</string>
</property>
<property name="shortcut">
<string>Y</string>
</property>
</action>
<action name="actionZoomOutY">
<property name="text">
<string>Zoom Out Y Axis</string>
</property>
<property name="toolTip">
<string>Zoom Out Y Axis</string>
</property>
<property name="shortcut">
<string>Shift+Y</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>ElidedLabel</class>
<extends>QLabel</extends>
<header>widgets/elided_label.h</header>
</customwidget>
<customwidget>
<class>TabnavTreeView</class>
<extends>QTreeView</extends>
<header>widgets/tabnav_tree_view.h</header>
</customwidget>
<customwidget>
<class>StockIconToolButton</class>
<extends>QToolButton</extends>
<header>widgets/stock_icon_tool_button.h</header>
</customwidget>
<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>IOGraphDialog</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>IOGraphDialog</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/layout_preferences_frame.cpp | /* layout_preferences_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 "layout_preferences_frame.h"
#include <ui_layout_preferences_frame.h>
#include <QAbstractButton>
#include <QToolButton>
#include <QRadioButton>
#include <QDebug>
#include <epan/prefs-int.h>
#include <ui/qt/models/pref_models.h>
LayoutPreferencesFrame::LayoutPreferencesFrame(QWidget *parent) :
QFrame(parent),
ui(new Ui::LayoutPreferencesFrame)
{
ui->setupUi(this);
pref_layout_type_ = prefFromPrefPtr(&prefs.gui_layout_type);
pref_layout_content_1_ = prefFromPrefPtr(&prefs.gui_layout_content_1);
pref_layout_content_2_ = prefFromPrefPtr(&prefs.gui_layout_content_2);
pref_layout_content_3_ = prefFromPrefPtr(&prefs.gui_layout_content_3);
QString image_pad_ss = "QToolButton { padding: 0.3em; }";
ui->layout1ToolButton->setStyleSheet(image_pad_ss);
ui->layout2ToolButton->setStyleSheet(image_pad_ss);
ui->layout3ToolButton->setStyleSheet(image_pad_ss);
ui->layout4ToolButton->setStyleSheet(image_pad_ss);
ui->layout5ToolButton->setStyleSheet(image_pad_ss);
ui->layout6ToolButton->setStyleSheet(image_pad_ss);
QStyleOption style_opt;
QString indent_ss = QString(
"QCheckBox, QLabel {"
" margin-left: %1px;"
"}"
).arg(ui->packetListSeparatorCheckBox->style()->subElementRect(QStyle::SE_CheckBoxContents, &style_opt).left());
ui->packetListSeparatorCheckBox->setStyleSheet(indent_ss);
ui->packetListHeaderShowColumnDefinition->setStyleSheet(indent_ss);
ui->packetListHoverStyleCheckbox->setStyleSheet(indent_ss);
ui->packetListAllowSorting->setStyleSheet(indent_ss);
ui->packetListCachedRowsLabel->setStyleSheet(indent_ss);
ui->statusBarShowSelectedPacketCheckBox->setStyleSheet(indent_ss);
ui->statusBarShowFileLoadTimeCheckBox->setStyleSheet(indent_ss);
pref_packet_list_separator_ = prefFromPrefPtr(&prefs.gui_packet_list_separator);
ui->packetListSeparatorCheckBox->setChecked(prefs_get_bool_value(pref_packet_list_separator_, pref_stashed));
pref_packet_header_column_definition_ = prefFromPrefPtr(&prefs.gui_packet_header_column_definition);
ui->packetListHeaderShowColumnDefinition->setChecked(prefs_get_bool_value(pref_packet_header_column_definition_, pref_stashed));
pref_packet_list_hover_style_ = prefFromPrefPtr(&prefs.gui_packet_list_hover_style);
ui->packetListHoverStyleCheckbox->setChecked(prefs_get_bool_value(pref_packet_list_hover_style_, pref_stashed));
pref_packet_list_sorting_ = prefFromPrefPtr(&prefs.gui_packet_list_sortable);
ui->packetListAllowSorting->setChecked(prefs_get_bool_value(pref_packet_list_sorting_, pref_stashed));
pref_packet_list_cached_rows_max_ = prefFromPrefPtr(&prefs.gui_packet_list_cached_rows_max);
pref_show_selected_packet_ = prefFromPrefPtr(&prefs.gui_show_selected_packet);
ui->statusBarShowSelectedPacketCheckBox->setChecked(prefs_get_bool_value(pref_show_selected_packet_, pref_stashed));
pref_show_file_load_time_ = prefFromPrefPtr(&prefs.gui_show_file_load_time);
ui->statusBarShowFileLoadTimeCheckBox->setChecked(prefs_get_bool_value(pref_show_file_load_time_, pref_stashed));
}
LayoutPreferencesFrame::~LayoutPreferencesFrame()
{
delete ui;
}
void LayoutPreferencesFrame::showEvent(QShowEvent *)
{
updateWidgets();
}
void LayoutPreferencesFrame::updateWidgets()
{
switch (prefs_get_uint_value_real(pref_layout_type_, pref_stashed)) {
case layout_type_5:
ui->layout5ToolButton->setChecked(true);
break;
case layout_type_2:
ui->layout2ToolButton->setChecked(true);
break;
case layout_type_1:
ui->layout1ToolButton->setChecked(true);
break;
case layout_type_4:
ui->layout4ToolButton->setChecked(true);
break;
case layout_type_3:
ui->layout3ToolButton->setChecked(true);
break;
case layout_type_6:
ui->layout6ToolButton->setChecked(true);
break;
}
switch (prefs_get_enum_value(pref_layout_content_1_, pref_stashed)) {
case layout_pane_content_plist:
ui->pane1PacketListRadioButton->setChecked(true);
break;
case layout_pane_content_pdetails:
ui->pane1PacketDetailsRadioButton->setChecked(true);
break;
case layout_pane_content_pbytes:
ui->pane1PacketBytesRadioButton->setChecked(true);
break;
case layout_pane_content_pdiagram:
ui->pane1PacketDiagramRadioButton->setChecked(true);
break;
case layout_pane_content_none:
ui->pane1NoneRadioButton->setChecked(true);
break;
}
switch (prefs_get_enum_value(pref_layout_content_2_, pref_stashed)) {
case layout_pane_content_plist:
ui->pane2PacketListRadioButton->setChecked(true);
break;
case layout_pane_content_pdetails:
ui->pane2PacketDetailsRadioButton->setChecked(true);
break;
case layout_pane_content_pbytes:
ui->pane2PacketBytesRadioButton->setChecked(true);
break;
case layout_pane_content_pdiagram:
ui->pane2PacketDiagramRadioButton->setChecked(true);
break;
case layout_pane_content_none:
ui->pane2NoneRadioButton->setChecked(true);
break;
}
switch (prefs_get_enum_value(pref_layout_content_3_, pref_stashed)) {
case layout_pane_content_plist:
ui->pane3PacketListRadioButton->setChecked(true);
break;
case layout_pane_content_pdetails:
ui->pane3PacketDetailsRadioButton->setChecked(true);
break;
case layout_pane_content_pbytes:
ui->pane3PacketBytesRadioButton->setChecked(true);
break;
case layout_pane_content_pdiagram:
ui->pane3PacketDiagramRadioButton->setChecked(true);
break;
case layout_pane_content_none:
ui->pane3NoneRadioButton->setChecked(true);
break;
}
ui->packetListCachedRowsLineEdit->setText(QString::number(prefs_get_uint_value_real(pref_packet_list_cached_rows_max_, pref_stashed)));
}
void LayoutPreferencesFrame::on_layout5ToolButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_uint_value(pref_layout_type_, layout_type_5, pref_stashed);
}
void LayoutPreferencesFrame::on_layout2ToolButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_uint_value(pref_layout_type_, layout_type_2, pref_stashed);
}
void LayoutPreferencesFrame::on_layout1ToolButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_uint_value(pref_layout_type_, layout_type_1, pref_stashed);
}
void LayoutPreferencesFrame::on_layout4ToolButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_uint_value(pref_layout_type_, layout_type_4, pref_stashed);
}
void LayoutPreferencesFrame::on_layout3ToolButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_uint_value(pref_layout_type_, layout_type_3, pref_stashed);
}
void LayoutPreferencesFrame::on_layout6ToolButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_uint_value(pref_layout_type_, layout_type_6, pref_stashed);
}
void LayoutPreferencesFrame::on_pane1PacketListRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_1_, layout_pane_content_plist, pref_stashed);
if (ui->pane2PacketListRadioButton->isChecked())
ui->pane2NoneRadioButton->click();
if (ui->pane3PacketListRadioButton->isChecked())
ui->pane3NoneRadioButton->click();
}
void LayoutPreferencesFrame::on_pane1PacketDetailsRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_1_, layout_pane_content_pdetails, pref_stashed);
if (ui->pane2PacketDetailsRadioButton->isChecked())
ui->pane2NoneRadioButton->click();
if (ui->pane3PacketDetailsRadioButton->isChecked())
ui->pane3NoneRadioButton->click();
}
void LayoutPreferencesFrame::on_pane1PacketBytesRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_1_, layout_pane_content_pbytes, pref_stashed);
if (ui->pane2PacketBytesRadioButton->isChecked())
ui->pane2NoneRadioButton->click();
if (ui->pane3PacketBytesRadioButton->isChecked())
ui->pane3NoneRadioButton->click();
}
void LayoutPreferencesFrame::on_pane1PacketDiagramRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_1_, layout_pane_content_pdiagram, pref_stashed);
if (ui->pane2PacketDiagramRadioButton->isChecked())
ui->pane2NoneRadioButton->click();
if (ui->pane3PacketDiagramRadioButton->isChecked())
ui->pane3NoneRadioButton->click();
}
void LayoutPreferencesFrame::on_pane1NoneRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_1_, layout_pane_content_none, pref_stashed);
}
void LayoutPreferencesFrame::on_pane2PacketListRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_2_, layout_pane_content_plist, pref_stashed);
if (ui->pane1PacketListRadioButton->isChecked())
ui->pane1NoneRadioButton->click();
if (ui->pane3PacketListRadioButton->isChecked())
ui->pane3NoneRadioButton->click();
}
void LayoutPreferencesFrame::on_pane2PacketDetailsRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_2_, layout_pane_content_pdetails, pref_stashed);
if (ui->pane1PacketDetailsRadioButton->isChecked())
ui->pane1NoneRadioButton->click();
if (ui->pane3PacketDetailsRadioButton->isChecked())
ui->pane3NoneRadioButton->click();
}
void LayoutPreferencesFrame::on_pane2PacketBytesRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_2_, layout_pane_content_pbytes, pref_stashed);
if (ui->pane1PacketBytesRadioButton->isChecked())
ui->pane1NoneRadioButton->click();
if (ui->pane3PacketBytesRadioButton->isChecked())
ui->pane3NoneRadioButton->click();
}
void LayoutPreferencesFrame::on_pane2PacketDiagramRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_2_, layout_pane_content_pdiagram, pref_stashed);
if (ui->pane1PacketDiagramRadioButton->isChecked())
ui->pane1NoneRadioButton->click();
if (ui->pane3PacketDiagramRadioButton->isChecked())
ui->pane3NoneRadioButton->click();
}
void LayoutPreferencesFrame::on_pane2NoneRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_2_, layout_pane_content_none, pref_stashed);
}
void LayoutPreferencesFrame::on_pane3PacketListRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_3_, layout_pane_content_plist, pref_stashed);
if (ui->pane1PacketListRadioButton->isChecked())
ui->pane1NoneRadioButton->click();
if (ui->pane2PacketListRadioButton->isChecked())
ui->pane2NoneRadioButton->click();
}
void LayoutPreferencesFrame::on_pane3PacketDetailsRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_3_, layout_pane_content_pdetails, pref_stashed);
if (ui->pane1PacketDetailsRadioButton->isChecked())
ui->pane1NoneRadioButton->click();
if (ui->pane2PacketDetailsRadioButton->isChecked())
ui->pane2NoneRadioButton->click();
}
void LayoutPreferencesFrame::on_pane3PacketBytesRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_3_, layout_pane_content_pbytes, pref_stashed);
if (ui->pane1PacketBytesRadioButton->isChecked())
ui->pane1NoneRadioButton->click();
if (ui->pane2PacketBytesRadioButton->isChecked())
ui->pane2NoneRadioButton->click();
}
void LayoutPreferencesFrame::on_pane3PacketDiagramRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_3_, layout_pane_content_pdiagram, pref_stashed);
if (ui->pane1PacketDiagramRadioButton->isChecked())
ui->pane1NoneRadioButton->click();
if (ui->pane2PacketDiagramRadioButton->isChecked())
ui->pane2NoneRadioButton->click();
}
void LayoutPreferencesFrame::on_pane3NoneRadioButton_toggled(bool checked)
{
if (!checked) return;
prefs_set_enum_value(pref_layout_content_3_, layout_pane_content_none, pref_stashed);
}
void LayoutPreferencesFrame::on_restoreButtonBox_clicked(QAbstractButton *)
{
reset_stashed_pref(pref_layout_type_);
reset_stashed_pref(pref_layout_content_1_);
updateWidgets();
reset_stashed_pref(pref_layout_content_2_);
updateWidgets();
reset_stashed_pref(pref_layout_content_3_);
updateWidgets();
ui->packetListSeparatorCheckBox->setChecked(prefs_get_bool_value(pref_packet_list_separator_, pref_default));
ui->packetListHeaderShowColumnDefinition->setChecked(prefs_get_bool_value(pref_packet_header_column_definition_, pref_default));
ui->packetListHoverStyleCheckbox->setChecked(prefs_get_bool_value(pref_packet_list_hover_style_, pref_default));
ui->packetListAllowSorting->setChecked(prefs_get_bool_value(pref_packet_list_sorting_, pref_default));
ui->statusBarShowSelectedPacketCheckBox->setChecked(prefs_get_bool_value(pref_show_selected_packet_, pref_default));
ui->statusBarShowFileLoadTimeCheckBox->setChecked(prefs_get_bool_value(pref_show_file_load_time_, pref_default));
}
void LayoutPreferencesFrame::on_packetListSeparatorCheckBox_toggled(bool checked)
{
prefs_set_bool_value(pref_packet_list_separator_, (gboolean) checked, pref_stashed);
}
void LayoutPreferencesFrame::on_packetListHeaderShowColumnDefinition_toggled(bool checked)
{
prefs_set_bool_value(pref_packet_header_column_definition_, (gboolean) checked, pref_stashed);
}
void LayoutPreferencesFrame::on_packetListHoverStyleCheckbox_toggled(bool checked)
{
prefs_set_bool_value(pref_packet_list_hover_style_, (gboolean) checked, pref_stashed);
}
void LayoutPreferencesFrame::on_packetListAllowSorting_toggled(bool checked)
{
prefs_set_bool_value(pref_packet_list_sorting_, (gboolean) checked, pref_stashed);
}
void LayoutPreferencesFrame::on_packetListCachedRowsLineEdit_textEdited(const QString &new_str)
{
bool ok;
uint new_uint = new_str.toUInt(&ok, 0);
if (ok) {
prefs_set_uint_value(pref_packet_list_cached_rows_max_, new_uint, pref_stashed);
}
}
void LayoutPreferencesFrame::on_statusBarShowSelectedPacketCheckBox_toggled(bool checked)
{
prefs_set_bool_value(pref_show_selected_packet_, (gboolean) checked, pref_stashed);
}
void LayoutPreferencesFrame::on_statusBarShowFileLoadTimeCheckBox_toggled(bool checked)
{
prefs_set_bool_value(pref_show_file_load_time_, (gboolean) checked, pref_stashed);
} |
C/C++ | wireshark/ui/qt/layout_preferences_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 LAYOUT_PREFERENCES_FRAME_H
#define LAYOUT_PREFERENCES_FRAME_H
#include <epan/prefs.h>
#include <QFrame>
#include <QAbstractButton>
namespace Ui {
class LayoutPreferencesFrame;
}
class LayoutPreferencesFrame : public QFrame
{
Q_OBJECT
public:
explicit LayoutPreferencesFrame(QWidget *parent = 0);
~LayoutPreferencesFrame();
protected:
void showEvent(QShowEvent *evt);
private:
Ui::LayoutPreferencesFrame *ui;
pref_t *pref_layout_type_;
pref_t *pref_layout_content_1_;
pref_t *pref_layout_content_2_;
pref_t *pref_layout_content_3_;
pref_t *pref_packet_list_separator_;
pref_t *pref_packet_header_column_definition_;
pref_t *pref_packet_list_hover_style_;
pref_t *pref_packet_list_sorting_;
pref_t *pref_packet_list_cached_rows_max_;
pref_t *pref_show_selected_packet_;
pref_t *pref_show_file_load_time_;
void updateWidgets();
private slots:
void on_layout5ToolButton_toggled(bool checked);
void on_layout2ToolButton_toggled(bool checked);
void on_layout1ToolButton_toggled(bool checked);
void on_layout4ToolButton_toggled(bool checked);
void on_layout3ToolButton_toggled(bool checked);
void on_layout6ToolButton_toggled(bool checked);
void on_pane1PacketListRadioButton_toggled(bool checked);
void on_pane1PacketDetailsRadioButton_toggled(bool checked);
void on_pane1PacketBytesRadioButton_toggled(bool checked);
void on_pane1PacketDiagramRadioButton_toggled(bool checked);
void on_pane1NoneRadioButton_toggled(bool checked);
void on_pane2PacketListRadioButton_toggled(bool checked);
void on_pane2PacketDetailsRadioButton_toggled(bool checked);
void on_pane2PacketBytesRadioButton_toggled(bool checked);
void on_pane2PacketDiagramRadioButton_toggled(bool checked);
void on_pane2NoneRadioButton_toggled(bool checked);
void on_pane3PacketListRadioButton_toggled(bool checked);
void on_pane3PacketDetailsRadioButton_toggled(bool checked);
void on_pane3PacketBytesRadioButton_toggled(bool checked);
void on_pane3PacketDiagramRadioButton_toggled(bool checked);
void on_pane3NoneRadioButton_toggled(bool checked);
void on_restoreButtonBox_clicked(QAbstractButton *button);
void on_packetListSeparatorCheckBox_toggled(bool checked);
void on_packetListHeaderShowColumnDefinition_toggled(bool checked);
void on_packetListHoverStyleCheckbox_toggled(bool checked);
void on_packetListAllowSorting_toggled(bool checked);
void on_packetListCachedRowsLineEdit_textEdited(const QString &new_str);
void on_statusBarShowSelectedPacketCheckBox_toggled(bool checked);
void on_statusBarShowFileLoadTimeCheckBox_toggled(bool checked);
};
#endif // LAYOUT_PREFERENCES_FRAME_H |
User Interface | wireshark/ui/qt/layout_preferences_frame.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>LayoutPreferencesFrame</class>
<widget class="QFrame" name="LayoutPreferencesFrame">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>414</width>
<height>409</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>
<property name="lineWidth">
<number>0</number>
</property>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QToolButton" name="layout5ToolButton">
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="../../resources/layout.qrc">
<normaloff>:/layout/layout_5.png</normaloff>:/layout/layout_5.png</iconset>
</property>
<property name="iconSize">
<size>
<width>48</width>
<height>48</height>
</size>
</property>
<property name="checkable">
<bool>true</bool>
</property>
<attribute name="buttonGroup">
<string notr="true">layoutButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QToolButton" name="layout2ToolButton">
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="../../resources/layout.qrc">
<normaloff>:/layout/layout_2.png</normaloff>:/layout/layout_2.png</iconset>
</property>
<property name="iconSize">
<size>
<width>48</width>
<height>48</height>
</size>
</property>
<property name="checkable">
<bool>true</bool>
</property>
<attribute name="buttonGroup">
<string notr="true">layoutButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QToolButton" name="layout1ToolButton">
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="../../resources/layout.qrc">
<normaloff>:/layout/layout_1.png</normaloff>:/layout/layout_1.png</iconset>
</property>
<property name="iconSize">
<size>
<width>48</width>
<height>48</height>
</size>
</property>
<property name="checkable">
<bool>true</bool>
</property>
<attribute name="buttonGroup">
<string notr="true">layoutButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QToolButton" name="layout4ToolButton">
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="../../resources/layout.qrc">
<normaloff>:/layout/layout_4.png</normaloff>:/layout/layout_4.png</iconset>
</property>
<property name="iconSize">
<size>
<width>48</width>
<height>48</height>
</size>
</property>
<property name="checkable">
<bool>true</bool>
</property>
<attribute name="buttonGroup">
<string notr="true">layoutButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QToolButton" name="layout3ToolButton">
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="../../resources/layout.qrc">
<normaloff>:/layout/layout_3.png</normaloff>:/layout/layout_3.png</iconset>
</property>
<property name="iconSize">
<size>
<width>48</width>
<height>48</height>
</size>
</property>
<property name="checkable">
<bool>true</bool>
</property>
<attribute name="buttonGroup">
<string notr="true">layoutButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QToolButton" name="layout6ToolButton">
<property name="text">
<string/>
</property>
<property name="icon">
<iconset resource="../../resources/layout.qrc">
<normaloff>:/layout/layout_6.png</normaloff>:/layout/layout_6.png</iconset>
</property>
<property name="iconSize">
<size>
<width>48</width>
<height>48</height>
</size>
</property>
<property name="checkable">
<bool>true</bool>
</property>
<attribute name="buttonGroup">
<string notr="true">layoutButtonGroup</string>
</attribute>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Pane 1:</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane1PacketListRadioButton">
<property name="text">
<string>Packet List</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane1ButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane1PacketDetailsRadioButton">
<property name="text">
<string>Packet Details</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane1ButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane1PacketBytesRadioButton">
<property name="text">
<string>Packet Bytes</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane1ButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane1PacketDiagramRadioButton">
<property name="text">
<string>Packet Diagram</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane1ButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane1NoneRadioButton">
<property name="text">
<string>None</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane1ButtonGroup</string>
</attribute>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Pane 2:</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane2PacketListRadioButton">
<property name="text">
<string>Packet List</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane2ButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane2PacketDetailsRadioButton">
<property name="text">
<string>Packet Details</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane2ButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane2PacketBytesRadioButton">
<property name="text">
<string>Packet Bytes</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane2ButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane2PacketDiagramRadioButton">
<property name="text">
<string>Packet Diagram</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane2ButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane2NoneRadioButton">
<property name="text">
<string>None</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane2ButtonGroup</string>
</attribute>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>Pane 3:</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane3PacketListRadioButton">
<property name="text">
<string>Packet List</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane3ButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane3PacketDetailsRadioButton">
<property name="text">
<string>Packet Details</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane3ButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane3PacketBytesRadioButton">
<property name="text">
<string>Packet Bytes</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane3ButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane3PacketDiagramRadioButton">
<property name="text">
<string>Packet Diagram</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane3ButtonGroup</string>
</attribute>
</widget>
</item>
<item>
<widget class="QRadioButton" name="pane3NoneRadioButton">
<property name="text">
<string>None</string>
</property>
<attribute name="buttonGroup">
<string notr="true">pane3ButtonGroup</string>
</attribute>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item>
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</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="packetListSettings">
<property name="text">
<string>Packet List settings:</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="packetListSeparatorCheckBox">
<property name="text">
<string>Show packet separator</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="packetListHeaderShowColumnDefinition">
<property name="text">
<string>Show column definition in column context menu</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="packetListAllowSorting">
<property name="text">
<string>Allow the list to be sorted</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="packetListCachedRows">
<item>
<widget class="QLabel" name="packetListCachedRowsLabel">
<property name="text">
<string>Maximum number of cached rows (affects sorting)</string>
</property>
<property name="toolTip">
<string><html><head/><body><p>If more than this many rows are displayed, then sorting by columns that require packet dissection will be disabled. Increasing this number increases memory consumption by caching column values.</p></body></html></string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="packetListCachedRowsLineEdit">
<property name="toolTip">
<string><html><head/><body><p>If more than this many rows are displayed, then sorting by columns that require packet dissection will be disabled. Increasing this number increases memory consumption by caching column values.</p></body></html></string>
</property>
</widget>
</item>
<item>
<spacer name="packetListCachedRowsHorizontalSpacer">
<property name="orientation">
<enum>Qt:Horizontal</enum>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="QCheckBox" name="packetListHoverStyleCheckbox">
<property name="text">
<string>Enable mouse-over colorization</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer_3">
<property name="orientation">
<enum>Qt::Vertical</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="statusBarSettings">
<property name="text">
<string>Status Bar settings:</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="statusBarShowSelectedPacketCheckBox">
<property name="text">
<string>Show selected packet number</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="statusBarShowFileLoadTimeCheckBox">
<property name="text">
<string>Show file load time</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>68</width>
<height>13</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QDialogButtonBox" name="restoreButtonBox">
<property name="standardButtons">
<set>QDialogButtonBox::RestoreDefaults</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources>
<include location="../../resources/layout.qrc"/>
</resources>
<connections/>
<buttongroups>
<buttongroup name="layoutButtonGroup"/>
<buttongroup name="pane3ButtonGroup"/>
<buttongroup name="pane2ButtonGroup"/>
<buttongroup name="pane1ButtonGroup"/>
</buttongroups>
</ui> |
C++ | wireshark/ui/qt/lbm_lbtrm_transport_dialog.cpp | /* lbm_lbtrm_transport_dialog.cpp
*
* Copyright (c) 2005-2014 Informatica Corporation. All Rights Reserved.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "lbm_lbtrm_transport_dialog.h"
#include <ui_lbm_lbtrm_transport_dialog.h>
#include "file.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
#include <QClipboard>
#include <QMenu>
#include <QMessageBox>
#include <QTreeWidget>
#include <QTreeWidgetItemIterator>
#include <QMenu>
#include <epan/packet_info.h>
#include <epan/tap.h>
#include <epan/to_str.h>
#include <epan/dissectors/packet-lbm.h>
#include <wsutil/nstime.h>
namespace
{
static const int Source_AddressTransport_Column = 0;
static const int Source_DataFrames_Column = 1;
static const int Source_DataBytes_Column = 2;
static const int Source_DataFramesBytes_Column = 3;
static const int Source_DataRate_Column = 4;
static const int Source_RXDataFrames_Column = 5;
static const int Source_RXDataBytes_Column = 6;
static const int Source_RXDataFramesBytes_Column = 7;
static const int Source_RXDataRate_Column = 8;
static const int Source_NCFFrames_Column = 9;
static const int Source_NCFCount_Column = 10;
static const int Source_NCFBytes_Column = 11;
static const int Source_NCFFramesBytes_Column = 12;
static const int Source_NCFCountBytes_Column = 13;
static const int Source_NCFFramesCount_Column = 14;
static const int Source_NCFFramesCountBytes_Column = 15;
static const int Source_NCFRate_Column = 16;
static const int Source_SMFrames_Column = 17;
static const int Source_SMBytes_Column = 18;
static const int Source_SMFramesBytes_Column = 19;
static const int Source_SMRate_Column = 20;
static const int Receiver_AddressTransport_Column = 0;
static const int Receiver_NAKFrames_Column = 1;
static const int Receiver_NAKCount_Column = 2;
static const int Receiver_NAKBytes_Column = 3;
static const int Receiver_NAKRate_Column = 4;
static const int Detail_SQN_Column = 0;
static const int Detail_Count_Column = 1;
static const int Detail_Frame_Column = 2;
static const double OneKilobit = 1000.0;
static const double OneMegabit = OneKilobit * OneKilobit;
static const double OneGigabit = OneMegabit * OneKilobit;
}
static QString format_rate(const nstime_t & elapsed, guint64 bytes)
{
QString result;
double elapsed_sec;
double rate;
if (((elapsed.secs == 0) && (elapsed.nsecs == 0)) || (bytes == 0))
{
return (QString("0"));
}
elapsed_sec = elapsed.secs + (((double)elapsed.nsecs) / 1000000000.0);
rate = ((double)(bytes * 8)) / elapsed_sec;
// Currently rate is in bps
if (rate >= OneGigabit)
{
rate /= OneGigabit;
result = QString("%1G").arg(rate, 0, 'f', 2);
}
else if (rate >= OneMegabit)
{
rate /= OneMegabit;
result = QString("%1M").arg(rate, 0, 'f', 2);
}
else if (rate >= OneKilobit)
{
rate /= OneKilobit;
result = QString("%1K").arg(rate, 0, 'f', 2);
}
else
{
result = QString("%1").arg(rate, 0, 'f', 2);
}
return (result);
}
// Note:
// LBMLBTRMFrameEntry, LBMLBTRMSQNEntry, LBMLBTRMNCFReasonEntry, LBMLBTRMNCFSQNEntry, LBMLBTRMSourceTransportEntry, LBMLBTRMSourceEntry,
// LBMLBTRMReceiverTransportEntry, and LBMLBTRMReceiverEntry are all derived from a QTreeWidgetItem. Each instantiation can exist
// in two places: in a QTreeWidget, and in a containing QMap.
//
// For example:
// - LBMLBTRMTransportDialogInfo contains a QMap of the sources (LBMLBTRMSourceEntry) and receivers (LBMLBTRMReceiverEntry)
// - A source (LBMLBTRMSourceEntry) contains a QMap of the source transports originating from it (LBMLBTRMSourceTransportEntry)
// - A source transport (LBMLBTRMSourceTransportEntry) contains QMaps of data, RX data, and SM SQNs (LBMLBTRMSQNEntry) and NCF SQNs
// (LBMLBTRMNCFSQNEntry)
// - A data SQN (LBMLBTRMSQNEntry) contains a QMap of the frames (LBMLBTRMFrameEntry) in which that SQN appears
//
// Not all of the entries actually appear in a QTreeWidget at one time. For example, in the source details, if no specific source
// transport is selected, nothing is in the source details tree. If Data SQNs is selected, then those details appear in the source
// details tree. Switching to RX Data SQNs removes whatever is currently in the source details tree, and adds the RX details for
// the selected transport.
//
// The actual owner of one of the above QTreeWidgetItem-derived items is the QMap container in its parent. The item is "loaned" to
// the QTreeWidget for display.
//
// All of this is to explain why
// 1) we are frequently adding things to a QTreeWidget
// 2) things are removed (takeTopLevelItem) from a QTreeWidget
// 3) destruction involves removing all items from all QTreeWidgets (rather than letting QTreeWidget delete them)
// 4) the destructor for each item has the form
// <for each QMap container>
// for (XXXMapIterator it = m_xxx.begin(); it != m_xxx.end(); it++)
// {
// delete *it;
// }
// m_xxx.clear();
// The for-loop calls the destructor for each item, while the clear() cleans up the space used by the QMap itself.
// A frame entry
class LBMLBTRMFrameEntry : public QTreeWidgetItem
{
public:
LBMLBTRMFrameEntry(guint32 frame);
virtual ~LBMLBTRMFrameEntry(void) { }
guint32 getFrame(void) { return (m_frame); }
private:
guint32 m_frame;
};
LBMLBTRMFrameEntry::LBMLBTRMFrameEntry(guint32 frame) :
QTreeWidgetItem(),
m_frame(frame)
{
setText(Detail_SQN_Column, QString(" "));
setText(Detail_Count_Column, QString(" "));
setText(Detail_Frame_Column, QString("%1").arg(m_frame));
}
typedef QMap<guint32, LBMLBTRMFrameEntry *> LBMLBTRMFrameMap;
typedef QMap<guint32, LBMLBTRMFrameEntry *>::iterator LBMLBTRMFrameMapIterator;
// A SQN (SeQuence Number) entry
class LBMLBTRMSQNEntry : public QTreeWidgetItem
{
public:
LBMLBTRMSQNEntry(guint32 sqn);
virtual ~LBMLBTRMSQNEntry(void);
void processFrame(guint32 frame);
private:
LBMLBTRMSQNEntry(void);
guint32 m_sqn;
guint32 m_count;
LBMLBTRMFrameMap m_frames;
};
LBMLBTRMSQNEntry::LBMLBTRMSQNEntry(guint32 sqn) :
QTreeWidgetItem(),
m_sqn(sqn),
m_count(0),
m_frames()
{
setText(Detail_SQN_Column, QString("%1").arg(m_sqn));
setTextAlignment(Detail_SQN_Column, Qt::AlignRight);
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
setText(Detail_Frame_Column, QString(" "));
}
LBMLBTRMSQNEntry::~LBMLBTRMSQNEntry(void)
{
for (LBMLBTRMFrameMapIterator it = m_frames.begin(); it != m_frames.end(); ++it)
{
delete *it;
}
m_frames.clear();
}
void LBMLBTRMSQNEntry::processFrame(guint32 frame)
{
LBMLBTRMFrameMapIterator it;
it = m_frames.find(frame);
if (m_frames.end() == it)
{
LBMLBTRMFrameEntry * entry = new LBMLBTRMFrameEntry(frame);
m_frames.insert(frame, entry);
addChild(entry);
sortChildren(Detail_Frame_Column, Qt::AscendingOrder);
}
m_count++;
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
}
// An NCF (Nak ConFirmation) Reason entry
class LBMLBTRMNCFReasonEntry : public QTreeWidgetItem
{
public:
LBMLBTRMNCFReasonEntry(guint8 reason);
virtual ~LBMLBTRMNCFReasonEntry(void);
void processFrame(guint32 frame);
private:
LBMLBTRMNCFReasonEntry(void);
guint8 m_reason;
QString m_reason_string;
guint32 m_count;
LBMLBTRMFrameMap m_frames;
};
LBMLBTRMNCFReasonEntry::LBMLBTRMNCFReasonEntry(guint8 reason) :
QTreeWidgetItem(),
m_reason(reason),
m_reason_string(),
m_count(0),
m_frames()
{
switch (m_reason)
{
case LBTRM_NCF_REASON_NO_RETRY:
m_reason_string = "No Retry";
break;
case LBTRM_NCF_REASON_IGNORED:
m_reason_string = "Ignored";
break;
case LBTRM_NCF_REASON_RX_DELAY:
m_reason_string = "Retransmit Delay";
break;
case LBTRM_NCF_REASON_SHED:
m_reason_string = "Shed";
break;
default:
m_reason_string = QString("Unknown (%1)").arg(m_reason);
break;
}
setText(Detail_SQN_Column, m_reason_string);
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
setText(Detail_Frame_Column, QString(" "));
}
LBMLBTRMNCFReasonEntry::~LBMLBTRMNCFReasonEntry(void)
{
for (LBMLBTRMFrameMapIterator it = m_frames.begin(); it != m_frames.end(); ++it)
{
delete *it;
}
m_frames.clear();
}
void LBMLBTRMNCFReasonEntry::processFrame(guint32 frame)
{
LBMLBTRMFrameMapIterator it;
it = m_frames.find(frame);
if (m_frames.end() == it)
{
LBMLBTRMFrameEntry * entry = new LBMLBTRMFrameEntry(frame);
m_frames.insert(frame, entry);
addChild(entry);
sortChildren(Detail_Frame_Column, Qt::AscendingOrder);
}
m_count++;
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
}
typedef QMap<guint32, LBMLBTRMNCFReasonEntry *> LBMLBTRMNCFReasonMap;
typedef QMap<guint32, LBMLBTRMNCFReasonEntry *>::iterator LBMLBTRMNCFReasonMapIterator;
// An NCF SQN entry
class LBMLBTRMNCFSQNEntry : public QTreeWidgetItem
{
public:
LBMLBTRMNCFSQNEntry(guint32 sqn);
virtual ~LBMLBTRMNCFSQNEntry(void);
void processFrame(guint8 reason, guint32 frame);
private:
LBMLBTRMNCFSQNEntry(void);
guint32 m_sqn;
guint32 m_count;
LBMLBTRMNCFReasonMap m_reasons;
};
LBMLBTRMNCFSQNEntry::LBMLBTRMNCFSQNEntry(guint32 sqn) :
QTreeWidgetItem(),
m_sqn(sqn),
m_count(0),
m_reasons()
{
setText(Detail_SQN_Column, QString("%1").arg(m_sqn));
setTextAlignment(Detail_SQN_Column, Qt::AlignRight);
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
setText(Detail_Frame_Column, QString(" "));
}
LBMLBTRMNCFSQNEntry::~LBMLBTRMNCFSQNEntry(void)
{
for (LBMLBTRMNCFReasonMapIterator it = m_reasons.begin(); it != m_reasons.end(); ++it)
{
delete *it;
}
m_reasons.clear();
}
void LBMLBTRMNCFSQNEntry::processFrame(guint8 reason, guint32 frame)
{
LBMLBTRMNCFReasonMapIterator it;
LBMLBTRMNCFReasonEntry * entry = NULL;
it = m_reasons.find(reason);
if (m_reasons.end() == it)
{
entry = new LBMLBTRMNCFReasonEntry(reason);
m_reasons.insert(reason, entry);
addChild(entry);
sortChildren(Detail_Frame_Column, Qt::AscendingOrder);
}
else
{
entry = it.value();
}
m_count++;
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
entry->processFrame(frame);
}
typedef QMap<guint32, LBMLBTRMSQNEntry *> LBMLBTRMSQNMap;
typedef QMap<guint32, LBMLBTRMSQNEntry *>::iterator LBMLBTRMSQNMapIterator;
typedef QMap<guint32, LBMLBTRMNCFSQNEntry *> LBMLBTRMNCFSQNMap;
typedef QMap<guint32, LBMLBTRMNCFSQNEntry *>::iterator LBMLBTRMNCFSQNMapIterator;
// A source transport entry
class LBMLBTRMSourceTransportEntry : public QTreeWidgetItem
{
friend class LBMLBTRMTransportDialog;
public:
LBMLBTRMSourceTransportEntry(const QString & transport);
virtual ~LBMLBTRMSourceTransportEntry(void);
void processPacket(const packet_info * pinfo, const lbm_lbtrm_tap_info_t * tap_info);
protected:
QString m_transport;
private:
void fillItem(void);
guint64 m_data_frames;
guint64 m_data_bytes;
guint64 m_rx_data_frames;
guint64 m_rx_data_bytes;
guint64 m_ncf_frames;
guint64 m_ncf_count;
guint64 m_ncf_bytes;
guint64 m_sm_frames;
guint64 m_sm_bytes;
nstime_t m_first_frame_timestamp;
bool m_first_frame_timestamp_valid;
nstime_t m_last_frame_timestamp;
protected:
LBMLBTRMSQNMap m_data_sqns;
LBMLBTRMSQNMap m_rx_data_sqns;
LBMLBTRMNCFSQNMap m_ncf_sqns;
LBMLBTRMSQNMap m_sm_sqns;
};
LBMLBTRMSourceTransportEntry::LBMLBTRMSourceTransportEntry(const QString & transport) :
QTreeWidgetItem(),
m_transport(transport),
m_data_frames(0),
m_data_bytes(0),
m_rx_data_frames(0),
m_rx_data_bytes(0),
m_ncf_frames(0),
m_ncf_count(0),
m_ncf_bytes(0),
m_sm_frames(0),
m_sm_bytes(0),
m_first_frame_timestamp_valid(false),
m_data_sqns(),
m_rx_data_sqns(),
m_ncf_sqns(),
m_sm_sqns()
{
m_first_frame_timestamp.secs = 0;
m_first_frame_timestamp.nsecs = 0;
m_last_frame_timestamp.secs = 0;
m_last_frame_timestamp.nsecs = 0;
setText(Source_AddressTransport_Column, m_transport);
}
LBMLBTRMSourceTransportEntry::~LBMLBTRMSourceTransportEntry(void)
{
for (LBMLBTRMSQNMapIterator it = m_data_sqns.begin(); it != m_data_sqns.end(); ++it)
{
delete *it;
}
m_data_sqns.clear();
for (LBMLBTRMSQNMapIterator it = m_rx_data_sqns.begin(); it != m_rx_data_sqns.end(); ++it)
{
delete *it;
}
m_rx_data_sqns.clear();
for (LBMLBTRMNCFSQNMapIterator it = m_ncf_sqns.begin(); it != m_ncf_sqns.end(); ++it)
{
delete *it;
}
m_ncf_sqns.clear();
for (LBMLBTRMSQNMapIterator it = m_sm_sqns.begin(); it != m_sm_sqns.end(); ++it)
{
delete *it;
}
m_sm_sqns.clear();
}
void LBMLBTRMSourceTransportEntry::processPacket(const packet_info * pinfo, const lbm_lbtrm_tap_info_t * tap_info)
{
if (m_first_frame_timestamp_valid)
{
if (nstime_cmp(&(pinfo->abs_ts), &m_first_frame_timestamp) < 0)
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
}
}
else
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
m_first_frame_timestamp_valid = true;
}
if (nstime_cmp(&(pinfo->abs_ts), &m_last_frame_timestamp) > 0)
{
nstime_copy(&(m_last_frame_timestamp), &(pinfo->abs_ts));
}
if (tap_info->type == LBTRM_PACKET_TYPE_DATA)
{
LBMLBTRMSQNEntry * sqn = NULL;
LBMLBTRMSQNMapIterator it;
if (tap_info->retransmission)
{
m_rx_data_frames++;
m_rx_data_bytes += pinfo->fd->pkt_len;
it = m_rx_data_sqns.find(tap_info->sqn);
if (m_rx_data_sqns.end() == it)
{
sqn = new LBMLBTRMSQNEntry(tap_info->sqn);
m_rx_data_sqns.insert(tap_info->sqn, sqn);
}
else
{
sqn = it.value();
}
}
else
{
m_data_frames++;
m_data_bytes += pinfo->fd->pkt_len;
it = m_data_sqns.find(tap_info->sqn);
if (m_data_sqns.end() == it)
{
sqn = new LBMLBTRMSQNEntry(tap_info->sqn);
m_data_sqns.insert(tap_info->sqn, sqn);
}
else
{
sqn = it.value();
}
}
sqn->processFrame(pinfo->num);
}
else if (tap_info->type == LBTRM_PACKET_TYPE_NCF)
{
guint16 idx;
LBMLBTRMNCFSQNMapIterator it;
LBMLBTRMNCFSQNEntry * sqn = NULL;
m_ncf_frames++;
m_ncf_bytes += pinfo->fd->pkt_len;
m_ncf_count += (guint64)tap_info->num_sqns;
for (idx = 0; idx < tap_info->num_sqns; idx++)
{
it = m_ncf_sqns.find(tap_info->sqns[idx]);
if (m_ncf_sqns.end() == it)
{
sqn = new LBMLBTRMNCFSQNEntry(tap_info->sqns[idx]);
m_ncf_sqns.insert(tap_info->sqns[idx], sqn);
}
else
{
sqn = it.value();
}
sqn->processFrame(tap_info->ncf_reason, pinfo->num);
}
}
else if (tap_info->type == LBTRM_PACKET_TYPE_SM)
{
LBMLBTRMSQNEntry * sqn = NULL;
LBMLBTRMSQNMapIterator it;
m_sm_frames++;
m_sm_bytes += pinfo->fd->pkt_len;
it = m_sm_sqns.find(tap_info->sqn);
if (m_sm_sqns.end() == it)
{
sqn = new LBMLBTRMSQNEntry(tap_info->sqn);
m_sm_sqns.insert(tap_info->sqn, sqn);
}
else
{
sqn = it.value();
}
sqn->processFrame(pinfo->num);
}
else
{
return;
}
fillItem();
}
void LBMLBTRMSourceTransportEntry::fillItem(void)
{
nstime_t delta;
nstime_delta(&delta, &m_last_frame_timestamp, &m_first_frame_timestamp);
setText(Source_DataFrames_Column, QString("%1").arg(m_data_frames));
setTextAlignment(Source_DataFrames_Column, Qt::AlignRight);
setText(Source_DataBytes_Column, QString("%1").arg(m_data_bytes));
setTextAlignment(Source_DataBytes_Column, Qt::AlignRight);
setText(Source_DataFramesBytes_Column, QString("%1/%2").arg(m_data_frames).arg(m_data_bytes));
setTextAlignment(Source_DataFramesBytes_Column, Qt::AlignHCenter);
setText(Source_DataRate_Column, format_rate(delta, m_data_bytes));
setTextAlignment(Source_DataRate_Column, Qt::AlignRight);
setText(Source_RXDataFrames_Column, QString("%1").arg(m_rx_data_frames));
setTextAlignment(Source_RXDataFrames_Column, Qt::AlignRight);
setText(Source_RXDataBytes_Column, QString("%1").arg(m_rx_data_bytes));
setTextAlignment(Source_RXDataBytes_Column, Qt::AlignRight);
setText(Source_RXDataFramesBytes_Column, QString("%1/%2").arg(m_rx_data_frames).arg(m_rx_data_bytes));
setTextAlignment(Source_RXDataFramesBytes_Column, Qt::AlignHCenter);
setText(Source_RXDataRate_Column, format_rate(delta, m_rx_data_bytes));
setTextAlignment(Source_RXDataRate_Column, Qt::AlignRight);
setText(Source_NCFFrames_Column, QString("%1").arg(m_ncf_frames));
setTextAlignment(Source_NCFFrames_Column, Qt::AlignRight);
setText(Source_NCFCount_Column, QString("%1").arg(m_ncf_count));
setTextAlignment(Source_NCFCount_Column, Qt::AlignRight);
setText(Source_NCFBytes_Column, QString("%1").arg(m_ncf_bytes));
setTextAlignment(Source_NCFBytes_Column, Qt::AlignRight);
setText(Source_NCFFramesBytes_Column, QString("%1/%2").arg(m_ncf_frames).arg(m_ncf_bytes));
setTextAlignment(Source_NCFFramesBytes_Column, Qt::AlignHCenter);
setText(Source_NCFCountBytes_Column, QString("%1/%2").arg(m_ncf_count).arg(m_ncf_bytes));
setTextAlignment(Source_NCFCountBytes_Column, Qt::AlignHCenter);
setText(Source_NCFFramesCount_Column, QString("%1/%2").arg(m_ncf_count).arg(m_ncf_count));
setTextAlignment(Source_NCFFramesCount_Column, Qt::AlignHCenter);
setText(Source_NCFFramesCountBytes_Column, QString("%1/%2/%3").arg(m_ncf_frames).arg(m_ncf_count).arg(m_ncf_bytes));
setTextAlignment(Source_NCFFramesCountBytes_Column, Qt::AlignHCenter);
setText(Source_NCFRate_Column, format_rate(delta, m_ncf_bytes));
setTextAlignment(Source_NCFRate_Column, Qt::AlignRight);
setText(Source_SMFrames_Column, QString("%1").arg(m_sm_frames));
setTextAlignment(Source_SMFrames_Column, Qt::AlignRight);
setText(Source_SMBytes_Column, QString("%1").arg(m_sm_bytes));
setTextAlignment(Source_SMBytes_Column, Qt::AlignRight);
setText(Source_SMFramesBytes_Column, QString("%1/%2").arg(m_sm_frames).arg(m_sm_bytes));
setTextAlignment(Source_SMFramesBytes_Column, Qt::AlignHCenter);
setText(Source_SMRate_Column, format_rate(delta, m_sm_bytes));
setTextAlignment(Source_SMRate_Column, Qt::AlignRight);
}
typedef QMap<QString, LBMLBTRMSourceTransportEntry *> LBMLBTRMSourceTransportMap;
typedef QMap<QString, LBMLBTRMSourceTransportEntry *>::iterator LBMLBTRMSourceTransportMapIterator;
// A source (address) entry
class LBMLBTRMSourceEntry : public QTreeWidgetItem
{
public:
LBMLBTRMSourceEntry(const QString & source_address);
virtual ~LBMLBTRMSourceEntry(void);
void processPacket(const packet_info * pinfo, const lbm_lbtrm_tap_info_t * tap_info);
private:
void fillItem(void);
QString m_address;
QString m_transport;
guint64 m_data_frames;
guint64 m_data_bytes;
guint64 m_rx_data_frames;
guint64 m_rx_data_bytes;
guint64 m_ncf_frames;
guint64 m_ncf_count;
guint64 m_ncf_bytes;
guint64 m_sm_frames;
guint64 m_sm_bytes;
nstime_t m_first_frame_timestamp;
bool m_first_frame_timestamp_valid;
nstime_t m_last_frame_timestamp;
LBMLBTRMSourceTransportMap m_transports;
};
LBMLBTRMSourceEntry::LBMLBTRMSourceEntry(const QString & source_address) :
QTreeWidgetItem(),
m_address(source_address),
m_data_frames(0),
m_data_bytes(0),
m_rx_data_frames(0),
m_rx_data_bytes(0),
m_ncf_frames(0),
m_ncf_count(0),
m_ncf_bytes(0),
m_sm_frames(0),
m_sm_bytes(0),
m_first_frame_timestamp_valid(false),
m_transports()
{
m_first_frame_timestamp.secs = 0;
m_first_frame_timestamp.nsecs = 0;
m_last_frame_timestamp.secs = 0;
m_last_frame_timestamp.nsecs = 0;
setText(Source_AddressTransport_Column, m_address);
}
LBMLBTRMSourceEntry::~LBMLBTRMSourceEntry(void)
{
for (LBMLBTRMSourceTransportMapIterator it = m_transports.begin(); it != m_transports.end(); ++it)
{
delete *it;
}
m_transports.clear();
}
void LBMLBTRMSourceEntry::processPacket(const packet_info * pinfo, const lbm_lbtrm_tap_info_t * tap_info)
{
LBMLBTRMSourceTransportEntry * transport = NULL;
LBMLBTRMSourceTransportMapIterator it;
if (m_first_frame_timestamp_valid)
{
if (nstime_cmp(&(pinfo->abs_ts), &m_first_frame_timestamp) < 0)
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
}
}
else
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
m_first_frame_timestamp_valid = true;
}
if (nstime_cmp(&(pinfo->abs_ts), &m_last_frame_timestamp) > 0)
{
nstime_copy(&(m_last_frame_timestamp), &(pinfo->abs_ts));
}
if (tap_info->type == LBTRM_PACKET_TYPE_DATA)
{
if (tap_info->retransmission)
{
m_rx_data_frames++;
m_rx_data_bytes += pinfo->fd->pkt_len;
}
else
{
m_data_frames++;
m_data_bytes += pinfo->fd->pkt_len;
}
}
else if (tap_info->type == LBTRM_PACKET_TYPE_NCF)
{
m_ncf_frames++;
m_ncf_bytes += pinfo->fd->pkt_len;
m_ncf_count += tap_info->num_sqns;
}
else if (tap_info->type == LBTRM_PACKET_TYPE_SM)
{
m_sm_frames++;
m_sm_bytes += pinfo->fd->pkt_len;
}
it = m_transports.find(tap_info->transport);
if (m_transports.end() == it)
{
transport = new LBMLBTRMSourceTransportEntry(tap_info->transport);
m_transports.insert(tap_info->transport, transport);
addChild(transport);
sortChildren(Source_AddressTransport_Column, Qt::AscendingOrder);
}
else
{
transport = it.value();
}
fillItem();
transport->processPacket(pinfo, tap_info);
}
void LBMLBTRMSourceEntry::fillItem(void)
{
nstime_t delta;
nstime_delta(&delta, &m_last_frame_timestamp, &m_first_frame_timestamp);
setText(Source_DataFrames_Column, QString("%1").arg(m_data_frames));
setTextAlignment(Source_DataFrames_Column, Qt::AlignRight);
setText(Source_DataBytes_Column, QString("%1").arg(m_data_bytes));
setTextAlignment(Source_DataBytes_Column, Qt::AlignRight);
setText(Source_DataFramesBytes_Column, QString("%1/%2").arg(m_data_frames).arg(m_data_bytes));
setTextAlignment(Source_DataFramesBytes_Column, Qt::AlignHCenter);
setText(Source_DataRate_Column, format_rate(delta, m_data_bytes));
setTextAlignment(Source_DataRate_Column, Qt::AlignRight);
setText(Source_RXDataFrames_Column, QString("%1").arg(m_rx_data_frames));
setTextAlignment(Source_RXDataFrames_Column, Qt::AlignRight);
setText(Source_RXDataBytes_Column, QString("%1").arg(m_rx_data_bytes));
setTextAlignment(Source_RXDataBytes_Column, Qt::AlignRight);
setText(Source_RXDataFramesBytes_Column, QString("%1/%2").arg(m_rx_data_frames).arg(m_rx_data_bytes));
setTextAlignment(Source_RXDataFramesBytes_Column, Qt::AlignHCenter);
setText(Source_RXDataRate_Column, format_rate(delta, m_rx_data_bytes));
setTextAlignment(Source_RXDataRate_Column, Qt::AlignRight);
setText(Source_NCFFrames_Column, QString("%1").arg(m_ncf_frames));
setTextAlignment(Source_NCFFrames_Column, Qt::AlignRight);
setText(Source_NCFCount_Column, QString("%1").arg(m_ncf_count));
setTextAlignment(Source_NCFCount_Column, Qt::AlignRight);
setText(Source_NCFBytes_Column, QString("%1").arg(m_ncf_bytes));
setTextAlignment(Source_NCFBytes_Column, Qt::AlignRight);
setText(Source_NCFFramesBytes_Column, QString("%1/%2").arg(m_ncf_frames).arg(m_ncf_bytes));
setTextAlignment(Source_NCFFramesBytes_Column, Qt::AlignHCenter);
setText(Source_NCFCountBytes_Column, QString("%1/%2").arg(m_ncf_count).arg(m_ncf_bytes));
setTextAlignment(Source_NCFCountBytes_Column, Qt::AlignHCenter);
setText(Source_NCFFramesCount_Column, QString("%1/%2").arg(m_ncf_frames).arg(m_ncf_count));
setTextAlignment(Source_NCFFramesCount_Column, Qt::AlignHCenter);
setText(Source_NCFFramesCountBytes_Column, QString("%1/%2/%3").arg(m_ncf_frames).arg(m_ncf_count).arg(m_ncf_bytes));
setTextAlignment(Source_NCFFramesCountBytes_Column, Qt::AlignHCenter);
setText(Source_NCFRate_Column, format_rate(delta, m_ncf_bytes));
setTextAlignment(Source_NCFRate_Column, Qt::AlignRight);
setText(Source_SMFrames_Column, QString("%1").arg(m_sm_frames));
setTextAlignment(Source_SMFrames_Column, Qt::AlignRight);
setText(Source_SMBytes_Column, QString("%1").arg(m_sm_bytes));
setTextAlignment(Source_SMBytes_Column, Qt::AlignRight);
setText(Source_SMFramesBytes_Column, QString("%1/%2").arg(m_sm_frames).arg(m_sm_bytes));
setTextAlignment(Source_SMFramesBytes_Column, Qt::AlignRight);
setText(Source_SMRate_Column, format_rate(delta, m_sm_bytes));
setTextAlignment(Source_SMRate_Column, Qt::AlignRight);
}
typedef QMap<QString, LBMLBTRMSourceEntry *> LBMLBTRMSourceMap;
typedef QMap<QString, LBMLBTRMSourceEntry *>::iterator LBMLBTRMSourceMapIterator;
// A receiver transport entry
class LBMLBTRMReceiverTransportEntry : public QTreeWidgetItem
{
friend class LBMLBTRMTransportDialog;
public:
LBMLBTRMReceiverTransportEntry(const QString & transport);
virtual ~LBMLBTRMReceiverTransportEntry(void);
void processPacket(const packet_info * pinfo, const lbm_lbtrm_tap_info_t * tap_info);
private:
void fillItem(void);
QString m_transport;
guint64 m_nak_frames;
guint64 m_nak_count;
guint64 m_nak_bytes;
nstime_t m_first_frame_timestamp;
bool m_first_frame_timestamp_valid;
nstime_t m_last_frame_timestamp;
protected:
LBMLBTRMSQNMap m_nak_sqns;
};
LBMLBTRMReceiverTransportEntry::LBMLBTRMReceiverTransportEntry(const QString & transport) :
QTreeWidgetItem(),
m_transport(transport),
m_nak_frames(0),
m_nak_count(0),
m_nak_bytes(0),
m_first_frame_timestamp_valid(false),
m_nak_sqns()
{
m_first_frame_timestamp.secs = 0;
m_first_frame_timestamp.nsecs = 0;
m_last_frame_timestamp.secs = 0;
m_last_frame_timestamp.nsecs = 0;
setText(Receiver_AddressTransport_Column, m_transport);
}
LBMLBTRMReceiverTransportEntry::~LBMLBTRMReceiverTransportEntry(void)
{
for (LBMLBTRMSQNMapIterator it = m_nak_sqns.begin(); it != m_nak_sqns.end(); ++it)
{
delete *it;
}
m_nak_sqns.clear();
}
void LBMLBTRMReceiverTransportEntry::processPacket(const packet_info * pinfo, const lbm_lbtrm_tap_info_t * tap_info)
{
if (m_first_frame_timestamp_valid)
{
if (nstime_cmp(&(pinfo->abs_ts), &m_first_frame_timestamp) < 0)
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
}
}
else
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
m_first_frame_timestamp_valid = true;
}
if (nstime_cmp(&(pinfo->abs_ts), &m_last_frame_timestamp) > 0)
{
nstime_copy(&(m_last_frame_timestamp), &(pinfo->abs_ts));
}
if (tap_info->type == LBTRM_PACKET_TYPE_NAK)
{
guint16 idx;
LBMLBTRMSQNEntry * sqn = NULL;
LBMLBTRMSQNMapIterator it;
m_nak_frames++;
m_nak_bytes += pinfo->fd->pkt_len;
m_nak_count += tap_info->num_sqns;
for (idx = 0; idx < tap_info->num_sqns; idx++)
{
it = m_nak_sqns.find(tap_info->sqns[idx]);
if (m_nak_sqns.end() == it)
{
sqn = new LBMLBTRMSQNEntry(tap_info->sqns[idx]);
m_nak_sqns.insert(tap_info->sqns[idx], sqn);
}
else
{
sqn = it.value();
}
sqn->processFrame(pinfo->num);
}
}
else
{
return;
}
fillItem();
}
void LBMLBTRMReceiverTransportEntry::fillItem(void)
{
nstime_t delta;
nstime_delta(&delta, &m_last_frame_timestamp, &m_first_frame_timestamp);
setText(Receiver_NAKFrames_Column, QString("%1").arg(m_nak_frames));
setTextAlignment(Receiver_NAKFrames_Column, Qt::AlignRight);
setText(Receiver_NAKCount_Column, QString("%1").arg(m_nak_count));
setTextAlignment(Receiver_NAKCount_Column, Qt::AlignRight);
setText(Receiver_NAKBytes_Column, QString("%1").arg(m_nak_bytes));
setTextAlignment(Receiver_NAKBytes_Column, Qt::AlignRight);
setText(Receiver_NAKRate_Column, format_rate(delta, m_nak_bytes));
setTextAlignment(Receiver_NAKRate_Column, Qt::AlignRight);
}
typedef QMap<QString, LBMLBTRMReceiverTransportEntry *> LBMLBTRMReceiverTransportMap;
typedef QMap<QString, LBMLBTRMReceiverTransportEntry *>::iterator LBMLBTRMReceiverTransportMapIterator;
// A receiver (address) entry
class LBMLBTRMReceiverEntry : public QTreeWidgetItem
{
public:
LBMLBTRMReceiverEntry(const QString & receiver_address);
virtual ~LBMLBTRMReceiverEntry(void);
void processPacket(const packet_info * pinfo, const lbm_lbtrm_tap_info_t * tap_info);
private:
LBMLBTRMReceiverEntry(void);
void fillItem(void);
QString m_address;
QString m_transport;
guint64 m_nak_frames;
guint64 m_nak_count;
guint64 m_nak_bytes;
nstime_t m_first_frame_timestamp;
bool m_first_frame_timestamp_valid;
nstime_t m_last_frame_timestamp;
LBMLBTRMReceiverTransportMap m_transports;
};
LBMLBTRMReceiverEntry::LBMLBTRMReceiverEntry(const QString & receiver_address) :
QTreeWidgetItem(),
m_address(receiver_address),
m_nak_frames(0),
m_nak_count(0),
m_nak_bytes(0),
m_first_frame_timestamp_valid(false),
m_transports()
{
m_first_frame_timestamp.secs = 0;
m_first_frame_timestamp.nsecs = 0;
m_last_frame_timestamp.secs = 0;
m_last_frame_timestamp.nsecs = 0;
setText(Receiver_AddressTransport_Column, m_address);
}
LBMLBTRMReceiverEntry::~LBMLBTRMReceiverEntry(void)
{
for (LBMLBTRMReceiverTransportMapIterator it = m_transports.begin(); it != m_transports.end(); ++it)
{
delete *it;
}
m_transports.clear();
}
void LBMLBTRMReceiverEntry::processPacket(const packet_info * pinfo, const lbm_lbtrm_tap_info_t * tap_info)
{
LBMLBTRMReceiverTransportEntry * transport = NULL;
LBMLBTRMReceiverTransportMapIterator it;
if (m_first_frame_timestamp_valid)
{
if (nstime_cmp(&(pinfo->abs_ts), &m_first_frame_timestamp) < 0)
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
}
}
else
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
m_first_frame_timestamp_valid = true;
}
if (nstime_cmp(&(pinfo->abs_ts), &m_last_frame_timestamp) > 0)
{
nstime_copy(&(m_last_frame_timestamp), &(pinfo->abs_ts));
}
if (tap_info->type == LBTRM_PACKET_TYPE_NAK)
{
m_nak_frames++;
m_nak_bytes += pinfo->fd->pkt_len;
m_nak_count += tap_info->num_sqns;
}
it = m_transports.find(tap_info->transport);
if (m_transports.end() == it)
{
transport = new LBMLBTRMReceiverTransportEntry(tap_info->transport);
m_transports.insert(tap_info->transport, transport);
addChild(transport);
sortChildren(Receiver_AddressTransport_Column, Qt::AscendingOrder);
}
else
{
transport = it.value();
}
fillItem();
transport->processPacket(pinfo, tap_info);
}
void LBMLBTRMReceiverEntry::fillItem(void)
{
nstime_t delta;
nstime_delta(&delta, &m_last_frame_timestamp, &m_first_frame_timestamp);
setText(Receiver_NAKFrames_Column, QString("%1").arg(m_nak_frames));
setTextAlignment(Receiver_NAKFrames_Column, Qt::AlignRight);
setText(Receiver_NAKCount_Column, QString("%1").arg(m_nak_count));
setTextAlignment(Receiver_NAKCount_Column, Qt::AlignRight);
setText(Receiver_NAKBytes_Column, QString("%1").arg(m_nak_bytes));
setTextAlignment(Receiver_NAKBytes_Column, Qt::AlignRight);
setText(Receiver_NAKRate_Column, format_rate(delta, m_nak_bytes));
setTextAlignment(Receiver_NAKRate_Column, Qt::AlignRight);
}
typedef QMap<QString, LBMLBTRMReceiverEntry *> LBMLBTRMReceiverMap;
typedef QMap<QString, LBMLBTRMReceiverEntry *>::iterator LBMLBTRMReceiverMapIterator;
class LBMLBTRMTransportDialogInfo
{
public:
LBMLBTRMTransportDialogInfo(void);
~LBMLBTRMTransportDialogInfo(void);
void setDialog(LBMLBTRMTransportDialog * dialog);
LBMLBTRMTransportDialog * getDialog(void);
void processPacket(const packet_info * pinfo, const lbm_lbtrm_tap_info_t * tap_info);
void clearMaps(void);
private:
LBMLBTRMTransportDialog * m_dialog;
LBMLBTRMSourceMap m_sources;
LBMLBTRMReceiverMap m_receivers;
};
LBMLBTRMTransportDialogInfo::LBMLBTRMTransportDialogInfo(void) :
m_dialog(NULL),
m_sources(),
m_receivers()
{
}
LBMLBTRMTransportDialogInfo::~LBMLBTRMTransportDialogInfo(void)
{
clearMaps();
}
void LBMLBTRMTransportDialogInfo::setDialog(LBMLBTRMTransportDialog * dialog)
{
m_dialog = dialog;
}
LBMLBTRMTransportDialog * LBMLBTRMTransportDialogInfo::getDialog(void)
{
return (m_dialog);
}
void LBMLBTRMTransportDialogInfo::processPacket(const packet_info * pinfo, const lbm_lbtrm_tap_info_t * tap_info)
{
switch (tap_info->type)
{
case LBTRM_PACKET_TYPE_DATA:
case LBTRM_PACKET_TYPE_SM:
case LBTRM_PACKET_TYPE_NCF:
{
LBMLBTRMSourceEntry * source = NULL;
LBMLBTRMSourceMapIterator it;
QString src_address = address_to_qstring(&(pinfo->src));
it = m_sources.find(src_address);
if (m_sources.end() == it)
{
QTreeWidgetItem * parent = NULL;
Ui::LBMLBTRMTransportDialog * ui = NULL;
source = new LBMLBTRMSourceEntry(src_address);
it = m_sources.insert(src_address, source);
ui = m_dialog->getUI();
ui->sources_TreeWidget->addTopLevelItem(source);
parent = ui->sources_TreeWidget->invisibleRootItem();
parent->sortChildren(Source_AddressTransport_Column, Qt::AscendingOrder);
ui->sources_TreeWidget->resizeColumnToContents(Source_AddressTransport_Column);
}
else
{
source = it.value();
}
source->processPacket(pinfo, tap_info);
}
break;
case LBTRM_PACKET_TYPE_NAK:
{
LBMLBTRMReceiverEntry * receiver = NULL;
LBMLBTRMReceiverMapIterator it;
QString src_address = address_to_qstring(&(pinfo->src));
it = m_receivers.find(src_address);
if (m_receivers.end() == it)
{
QTreeWidgetItem * parent = NULL;
Ui::LBMLBTRMTransportDialog * ui = NULL;
receiver = new LBMLBTRMReceiverEntry(src_address);
it = m_receivers.insert(src_address, receiver);
ui = m_dialog->getUI();
ui->receivers_TreeWidget->addTopLevelItem(receiver);
parent = ui->receivers_TreeWidget->invisibleRootItem();
parent->sortChildren(Receiver_AddressTransport_Column, Qt::AscendingOrder);
ui->receivers_TreeWidget->resizeColumnToContents(Receiver_AddressTransport_Column);
}
else
{
receiver = it.value();
}
receiver->processPacket(pinfo, tap_info);
}
break;
default:
break;
}
}
void LBMLBTRMTransportDialogInfo::clearMaps(void)
{
for (LBMLBTRMSourceMapIterator it = m_sources.begin(); it != m_sources.end(); ++it)
{
delete *it;
}
m_sources.clear();
for (LBMLBTRMReceiverMapIterator it = m_receivers.begin(); it != m_receivers.end(); ++it)
{
delete *it;
}
m_receivers.clear();
}
LBMLBTRMTransportDialog::LBMLBTRMTransportDialog(QWidget * parent, capture_file * cfile) :
QDialog(parent),
m_ui(new Ui::LBMLBTRMTransportDialog),
m_dialog_info(NULL),
m_capture_file(cfile),
m_current_source_transport(NULL),
m_current_receiver_transport(NULL),
m_source_context_menu(NULL),
m_source_header(NULL)
{
m_ui->setupUi(this);
m_dialog_info = new LBMLBTRMTransportDialogInfo();
m_ui->tabWidget->setCurrentIndex(0);
m_ui->sources_detail_ComboBox->setCurrentIndex(0);
m_ui->sources_detail_transport_Label->setText(QString(" "));
m_ui->receivers_detail_transport_Label->setText(QString(" "));
m_ui->stackedWidget->setCurrentIndex(0);
m_source_header = m_ui->sources_TreeWidget->header();
m_source_context_menu = new QMenu(m_source_header);
m_source_context_menu->addAction(m_ui->action_SourceAutoResizeColumns);
connect(m_ui->action_SourceAutoResizeColumns, SIGNAL(triggered()), this, SLOT(actionSourceAutoResizeColumns_triggered()));
m_source_context_menu->addSeparator();
m_ui->action_SourceDataFrames->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceDataFrames);
connect(m_ui->action_SourceDataFrames, SIGNAL(triggered(bool)), this, SLOT(actionSourceDataFrames_triggered(bool)));
m_ui->action_SourceDataBytes->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceDataBytes);
connect(m_ui->action_SourceDataBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceDataBytes_triggered(bool)));
m_ui->action_SourceDataFramesBytes->setChecked(false);
m_source_context_menu->addAction(m_ui->action_SourceDataFramesBytes);
connect(m_ui->action_SourceDataFramesBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceDataFramesBytes_triggered(bool)));
m_ui->action_SourceDataRate->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceDataRate);
connect(m_ui->action_SourceDataRate, SIGNAL(triggered(bool)), this, SLOT(actionSourceDataRate_triggered(bool)));
m_ui->action_SourceRXDataFrames->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceRXDataFrames);
connect(m_ui->action_SourceRXDataFrames, SIGNAL(triggered(bool)), this, SLOT(actionSourceRXDataFrames_triggered(bool)));
m_ui->action_SourceRXDataBytes->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceRXDataBytes);
connect(m_ui->action_SourceRXDataBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceRXDataBytes_triggered(bool)));
m_ui->action_SourceRXDataFramesBytes->setChecked(false);
m_source_context_menu->addAction(m_ui->action_SourceRXDataFramesBytes);
connect(m_ui->action_SourceRXDataFramesBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceRXDataFramesBytes_triggered(bool)));
m_ui->action_SourceRXDataRate->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceRXDataRate);
connect(m_ui->action_SourceRXDataRate, SIGNAL(triggered(bool)), this, SLOT(actionSourceRXDataRate_triggered(bool)));
m_ui->action_SourceNCFFrames->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceNCFFrames);
connect(m_ui->action_SourceNCFFrames, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFFrames_triggered(bool)));
m_ui->action_SourceNCFCount->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceNCFCount);
connect(m_ui->action_SourceNCFCount, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFCount_triggered(bool)));
m_ui->action_SourceNCFBytes->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceNCFBytes);
connect(m_ui->action_SourceNCFBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFBytes_triggered(bool)));
m_ui->action_SourceNCFFramesBytes->setChecked(false);
m_source_context_menu->addAction(m_ui->action_SourceNCFFramesBytes);
connect(m_ui->action_SourceNCFFramesBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFFramesBytes_triggered(bool)));
m_ui->action_SourceNCFCountBytes->setChecked(false);
m_source_context_menu->addAction(m_ui->action_SourceNCFCountBytes);
connect(m_ui->action_SourceNCFCountBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFCountBytes_triggered(bool)));
m_ui->action_SourceNCFFramesCount->setChecked(false);
m_source_context_menu->addAction(m_ui->action_SourceNCFFramesCount);
connect(m_ui->action_SourceNCFFramesCount, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFFramesCount_triggered(bool)));
m_ui->action_SourceNCFFramesCountBytes->setChecked(false);
m_source_context_menu->addAction(m_ui->action_SourceNCFFramesCountBytes);
connect(m_ui->action_SourceNCFFramesCountBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFFramesCountBytes_triggered(bool)));
m_ui->action_SourceNCFRate->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceNCFRate);
connect(m_ui->action_SourceNCFRate, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFRate_triggered(bool)));
m_ui->action_SourceSMFrames->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceSMFrames);
connect(m_ui->action_SourceSMFrames, SIGNAL(triggered(bool)), this, SLOT(actionSourceSMFrames_triggered(bool)));
m_ui->action_SourceSMBytes->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceSMBytes);
connect(m_ui->action_SourceSMBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceSMBytes_triggered(bool)));
m_ui->action_SourceSMFramesBytes->setChecked(false);
m_source_context_menu->addAction(m_ui->action_SourceSMFramesBytes);
connect(m_ui->action_SourceSMFramesBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceSMFramesBytes_triggered(bool)));
m_ui->action_SourceSMRate->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceSMRate);
connect(m_ui->action_SourceSMRate, SIGNAL(triggered(bool)), this, SLOT(actionSourceSMRate_triggered(bool)));
m_source_header->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_source_header, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(custom_source_context_menuRequested(const QPoint &)));
m_ui->sources_TreeWidget->setColumnHidden(Source_DataFramesBytes_Column, true);
m_ui->sources_TreeWidget->setColumnHidden(Source_RXDataFramesBytes_Column, true);
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFramesBytes_Column, true);
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFCountBytes_Column, true);
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFramesCount_Column, true);
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFramesCountBytes_Column, true);
m_ui->sources_TreeWidget->setColumnHidden(Source_SMFramesBytes_Column, true);
setAttribute(Qt::WA_DeleteOnClose, true);
fillTree();
}
LBMLBTRMTransportDialog::~LBMLBTRMTransportDialog(void)
{
resetSourcesDetail();
resetSources();
resetReceiversDetail();
resetReceivers();
if (m_dialog_info != NULL)
{
delete m_dialog_info;
m_dialog_info = NULL;
}
delete m_source_context_menu;
m_source_context_menu = NULL;
delete m_ui;
m_ui = NULL;
m_capture_file = NULL;
}
void LBMLBTRMTransportDialog::setCaptureFile(capture_file * cfile)
{
if (cfile == NULL) // We only want to know when the file closes.
{
m_capture_file = NULL;
m_ui->displayFilterLineEdit->setEnabled(false);
m_ui->applyFilterButton->setEnabled(false);
}
}
void LBMLBTRMTransportDialog::resetSources(void)
{
while (m_ui->sources_TreeWidget->takeTopLevelItem(0) != NULL)
{}
}
void LBMLBTRMTransportDialog::resetReceivers(void)
{
while (m_ui->receivers_TreeWidget->takeTopLevelItem(0) != NULL)
{}
}
void LBMLBTRMTransportDialog::resetSourcesDetail(void)
{
while (m_ui->sources_detail_sqn_TreeWidget->takeTopLevelItem(0) != NULL)
{}
while (m_ui->sources_detail_ncf_sqn_TreeWidget->takeTopLevelItem(0) != NULL)
{}
m_ui->sources_detail_transport_Label->setText(QString(" "));
m_current_source_transport = NULL;
}
void LBMLBTRMTransportDialog::resetReceiversDetail(void)
{
while (m_ui->receivers_detail_TreeWidget->takeTopLevelItem(0) != NULL)
{}
m_ui->receivers_detail_transport_Label->setText(QString(" "));
m_current_receiver_transport = NULL;
}
void LBMLBTRMTransportDialog::fillTree(void)
{
GString * error_string;
if (m_capture_file == NULL)
{
return;
}
m_dialog_info->setDialog(this);
error_string = register_tap_listener("lbm_lbtrm",
(void *)m_dialog_info,
m_ui->displayFilterLineEdit->text().toUtf8().constData(),
TL_REQUIRES_COLUMNS,
resetTap,
tapPacket,
drawTreeItems,
NULL);
if (error_string)
{
QMessageBox::critical(this, tr("LBT-RM Statistics failed to attach to tap"),
error_string->str);
g_string_free(error_string, TRUE);
reject();
}
cf_retap_packets(m_capture_file);
drawTreeItems(&m_dialog_info);
remove_tap_listener((void *)m_dialog_info);
}
void LBMLBTRMTransportDialog::resetTap(void * tap_data)
{
LBMLBTRMTransportDialogInfo * info = (LBMLBTRMTransportDialogInfo *) tap_data;
LBMLBTRMTransportDialog * dialog = info->getDialog();
if (dialog == NULL)
{
return;
}
dialog->resetSourcesDetail();
dialog->resetSources();
dialog->resetReceiversDetail();
dialog->resetReceivers();
info->clearMaps();
}
tap_packet_status LBMLBTRMTransportDialog::tapPacket(void * tap_data, packet_info * pinfo, epan_dissect_t *, const void * tap_info, tap_flags_t)
{
if (pinfo->fd->passed_dfilter == 1)
{
const lbm_lbtrm_tap_info_t * tapinfo = (const lbm_lbtrm_tap_info_t *)tap_info;
LBMLBTRMTransportDialogInfo * info = (LBMLBTRMTransportDialogInfo *)tap_data;
info->processPacket(pinfo, tapinfo);
}
return (TAP_PACKET_REDRAW);
}
void LBMLBTRMTransportDialog::drawTreeItems(void *)
{
}
void LBMLBTRMTransportDialog::on_applyFilterButton_clicked(void)
{
fillTree();
}
void LBMLBTRMTransportDialog::sourcesDetailCurrentChanged(int index)
{
// Index 0: Data
// Index 1: RX data
// Index 2: NCF
// Index 3: SM
switch (index)
{
case 0:
case 1:
case 3:
m_ui->stackedWidget->setCurrentIndex(0);
break;
case 2:
m_ui->stackedWidget->setCurrentIndex(1);
break;
default:
return;
}
sourcesItemClicked(m_current_source_transport, 0);
}
void LBMLBTRMTransportDialog::sourcesItemClicked(QTreeWidgetItem * item, int)
{
LBMLBTRMSourceTransportEntry * transport = dynamic_cast<LBMLBTRMSourceTransportEntry *>(item);
resetSourcesDetail();
if (transport == NULL)
{
// Must be a source item, ignore it?
return;
}
m_current_source_transport = transport;
m_ui->sources_detail_transport_Label->setText(transport->m_transport);
int cur_idx = m_ui->sources_detail_ComboBox->currentIndex();
switch (cur_idx)
{
case 0:
loadSourceDataDetails(transport);
break;
case 1:
loadSourceRXDataDetails(transport);
break;
case 2:
loadSourceNCFDetails(transport);
break;
case 3:
loadSourceSMDetails(transport);
break;
default:
break;
}
}
void LBMLBTRMTransportDialog::loadSourceDataDetails(LBMLBTRMSourceTransportEntry * transport)
{
for (LBMLBTRMSQNMapIterator it = transport->m_data_sqns.begin(); it != transport->m_data_sqns.end(); ++it)
{
LBMLBTRMSQNEntry * sqn = it.value();
m_ui->sources_detail_sqn_TreeWidget->addTopLevelItem(sqn);
}
}
void LBMLBTRMTransportDialog::loadSourceRXDataDetails(LBMLBTRMSourceTransportEntry * transport)
{
for (LBMLBTRMSQNMapIterator it = transport->m_rx_data_sqns.begin(); it != transport->m_rx_data_sqns.end(); ++it)
{
LBMLBTRMSQNEntry * sqn = it.value();
m_ui->sources_detail_sqn_TreeWidget->addTopLevelItem(sqn);
}
}
void LBMLBTRMTransportDialog::loadSourceNCFDetails(LBMLBTRMSourceTransportEntry * transport)
{
for (LBMLBTRMNCFSQNMapIterator it = transport->m_ncf_sqns.begin(); it != transport->m_ncf_sqns.end(); ++it)
{
LBMLBTRMNCFSQNEntry * sqn = it.value();
m_ui->sources_detail_ncf_sqn_TreeWidget->addTopLevelItem(sqn);
}
}
void LBMLBTRMTransportDialog::loadSourceSMDetails(LBMLBTRMSourceTransportEntry * transport)
{
for (LBMLBTRMSQNMapIterator it = transport->m_sm_sqns.begin(); it != transport->m_sm_sqns.end(); ++it)
{
LBMLBTRMSQNEntry * sqn = it.value();
m_ui->sources_detail_sqn_TreeWidget->addTopLevelItem(sqn);
}
}
void LBMLBTRMTransportDialog::receiversItemClicked(QTreeWidgetItem * item, int)
{
LBMLBTRMReceiverTransportEntry * transport = dynamic_cast<LBMLBTRMReceiverTransportEntry *>(item);
resetReceiversDetail();
if (transport == NULL)
{
// Must be a receiver item, ignore it?
return;
}
m_current_receiver_transport = transport;
m_ui->receivers_detail_transport_Label->setText(transport->m_transport);
loadReceiverNAKDetails(transport);
}
void LBMLBTRMTransportDialog::loadReceiverNAKDetails(LBMLBTRMReceiverTransportEntry * transport)
{
for (LBMLBTRMSQNMapIterator it = transport->m_nak_sqns.begin(); it != transport->m_nak_sqns.end(); ++it)
{
LBMLBTRMSQNEntry * sqn = it.value();
m_ui->receivers_detail_TreeWidget->addTopLevelItem(sqn);
}
}
void LBMLBTRMTransportDialog::sourcesDetailItemDoubleClicked(QTreeWidgetItem * item, int)
{
LBMLBTRMFrameEntry * frame = dynamic_cast<LBMLBTRMFrameEntry *>(item);
if (frame == NULL)
{
// Must have double-clicked on something other than an expanded frame entry
return;
}
emit goToPacket((int)frame->getFrame());
}
void LBMLBTRMTransportDialog::receiversDetailItemDoubleClicked(QTreeWidgetItem * item, int)
{
LBMLBTRMFrameEntry * frame = dynamic_cast<LBMLBTRMFrameEntry *>(item);
if (frame == NULL)
{
// Must have double-clicked on something other than an expanded frame entry
return;
}
emit goToPacket((int)frame->getFrame());
}
void LBMLBTRMTransportDialog::custom_source_context_menuRequested(const QPoint & pos)
{
m_source_context_menu->popup(m_source_header->mapToGlobal(pos));
}
void LBMLBTRMTransportDialog::actionSourceDataFrames_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_DataFrames_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceDataBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_DataBytes_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceDataFramesBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_DataFramesBytes_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceDataRate_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_DataRate_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceRXDataFrames_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_RXDataFrames_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceRXDataBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_RXDataBytes_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceRXDataFramesBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_RXDataFramesBytes_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceRXDataRate_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_RXDataRate_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceNCFFrames_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFrames_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceNCFCount_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFCount_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceNCFBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFrames_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceNCFFramesBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFramesBytes_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceNCFCountBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFCountBytes_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceNCFFramesCount_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFramesCount_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceNCFFramesCountBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFramesCountBytes_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceNCFRate_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFRate_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceSMFrames_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_SMFrames_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceSMBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_SMBytes_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceSMFramesBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_SMFramesBytes_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceSMRate_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_SMRate_Column, !checked);
}
void LBMLBTRMTransportDialog::actionSourceAutoResizeColumns_triggered(void)
{
m_ui->sources_TreeWidget->resizeColumnToContents(Source_AddressTransport_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_DataFrames_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_DataBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_DataFramesBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_DataRate_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_RXDataFrames_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_RXDataBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_RXDataFramesBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_RXDataRate_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFFrames_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFCount_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFFramesBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFCountBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFFramesCount_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFFramesCountBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFRate_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_SMFrames_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_SMBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_SMFramesBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_SMRate_Column);
} |
C/C++ | wireshark/ui/qt/lbm_lbtrm_transport_dialog.h | /** @file
*
* Copyright (c) 2005-2014 Informatica Corporation. All Rights Reserved.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef LBM_LBTRM_TRANSPORT_DIALOG_H
#define LBM_LBTRM_TRANSPORT_DIALOG_H
#include <config.h>
#include <glib.h>
#include "cfile.h"
#include <epan/packet_info.h>
#include <epan/tap.h>
#include <QDialog>
class QHeaderView;
class QMenu;
class QTreeWidgetItem;
namespace Ui
{
class LBMLBTRMTransportDialog;
}
class LBMLBTRMTransportDialogInfo;
class LBMLBTRMSourceTransportEntry;
class LBMLBTRMReceiverTransportEntry;
class LBMLBTRMTransportDialog : public QDialog
{
Q_OBJECT
public:
explicit LBMLBTRMTransportDialog(QWidget * parent = 0, capture_file * cfile = NULL);
Ui::LBMLBTRMTransportDialog * getUI(void)
{
return (m_ui);
}
public slots:
void setCaptureFile(capture_file * cfile);
signals:
void goToPacket(int PacketNum);
private:
Ui::LBMLBTRMTransportDialog * m_ui;
LBMLBTRMTransportDialogInfo * m_dialog_info;
capture_file * m_capture_file;
LBMLBTRMSourceTransportEntry * m_current_source_transport;
LBMLBTRMReceiverTransportEntry * m_current_receiver_transport;
QMenu * m_source_context_menu;
QHeaderView * m_source_header;
virtual ~LBMLBTRMTransportDialog(void);
void resetSources(void);
void resetReceivers(void);
void resetSourcesDetail(void);
void resetReceiversDetail(void);
void fillTree(void);
static void resetTap(void * tap_data);
static tap_packet_status tapPacket(void * tap_data, packet_info * pinfo, epan_dissect_t * edt, const void * stream_info, tap_flags_t flags);
static void drawTreeItems(void * tap_data);
void loadSourceDataDetails(LBMLBTRMSourceTransportEntry * transport);
void loadSourceRXDataDetails(LBMLBTRMSourceTransportEntry * transport);
void loadSourceNCFDetails(LBMLBTRMSourceTransportEntry * transport);
void loadSourceSMDetails(LBMLBTRMSourceTransportEntry * transport);
void loadSourceRSTDetails(LBMLBTRMSourceTransportEntry * transport);
void loadReceiverNAKDetails(LBMLBTRMReceiverTransportEntry * transport);
private slots:
void on_applyFilterButton_clicked(void);
void sourcesDetailCurrentChanged(int Index);
void sourcesItemClicked(QTreeWidgetItem * item, int column);
void receiversItemClicked(QTreeWidgetItem * item, int column);
void sourcesDetailItemDoubleClicked(QTreeWidgetItem * item, int column);
void receiversDetailItemDoubleClicked(QTreeWidgetItem * item, int column);
void actionSourceDataFrames_triggered(bool checked);
void actionSourceDataBytes_triggered(bool checked);
void actionSourceDataFramesBytes_triggered(bool checked);
void actionSourceDataRate_triggered(bool checked);
void actionSourceRXDataFrames_triggered(bool checked);
void actionSourceRXDataBytes_triggered(bool checked);
void actionSourceRXDataFramesBytes_triggered(bool checked);
void actionSourceRXDataRate_triggered(bool checked);
void actionSourceNCFFrames_triggered(bool checked);
void actionSourceNCFCount_triggered(bool checked);
void actionSourceNCFBytes_triggered(bool checked);
void actionSourceNCFFramesBytes_triggered(bool checked);
void actionSourceNCFCountBytes_triggered(bool checked);
void actionSourceNCFFramesCount_triggered(bool checked);
void actionSourceNCFFramesCountBytes_triggered(bool checked);
void actionSourceNCFRate_triggered(bool checked);
void actionSourceSMFrames_triggered(bool checked);
void actionSourceSMBytes_triggered(bool checked);
void actionSourceSMFramesBytes_triggered(bool checked);
void actionSourceSMRate_triggered(bool checked);
void actionSourceAutoResizeColumns_triggered(void);
void custom_source_context_menuRequested(const QPoint & pos);
};
#endif |
User Interface | wireshark/ui/qt/lbm_lbtrm_transport_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>LBMLBTRMTransportDialog</class>
<widget class="QDialog" name="LBMLBTRMTransportDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>841</width>
<height>563</height>
</rect>
</property>
<property name="windowTitle">
<string>LBT-RM Transport Statistics</string>
</property>
<property name="sizeGripEnabled">
<bool>true</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="sourcesTab">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<attribute name="title">
<string>Sources</string>
</attribute>
<layout class="QHBoxLayout" name="horizontalLayout_5">
<item>
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="handleWidth">
<number>10</number>
</property>
<widget class="QTreeWidget" name="sources_TreeWidget">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<attribute name="headerDefaultSectionSize">
<number>80</number>
</attribute>
<column>
<property name="text">
<string>Address/Transport</string>
</property>
</column>
<column>
<property name="text">
<string>Data frames</string>
</property>
</column>
<column>
<property name="text">
<string>Data bytes</string>
</property>
</column>
<column>
<property name="text">
<string>Data frames/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>Data rate</string>
</property>
</column>
<column>
<property name="text">
<string>RX data frames</string>
</property>
</column>
<column>
<property name="text">
<string>RX data bytes</string>
</property>
</column>
<column>
<property name="text">
<string>RX data frames/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>RX data rate</string>
</property>
</column>
<column>
<property name="text">
<string>NCF frames</string>
</property>
</column>
<column>
<property name="text">
<string>NCF count</string>
</property>
</column>
<column>
<property name="text">
<string>NCF bytes</string>
</property>
</column>
<column>
<property name="text">
<string>NCF frames/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>NCF count/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>NCF frames/count</string>
</property>
</column>
<column>
<property name="text">
<string>NCF frames/count/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>NCF rate</string>
</property>
</column>
<column>
<property name="text">
<string>SM frames</string>
</property>
</column>
<column>
<property name="text">
<string>SM bytes</string>
</property>
</column>
<column>
<property name="text">
<string>SM frames/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>SM rate</string>
</property>
</column>
</widget>
<widget class="QWidget" name="layoutWidget">
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Show</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="sources_detail_ComboBox">
<item>
<property name="text">
<string>Data</string>
</property>
</item>
<item>
<property name="text">
<string>RX Data</string>
</property>
</item>
<item>
<property name="text">
<string extracomment="Nak ConFirmation">NCF</string>
</property>
</item>
<item>
<property name="text">
<string extracomment="Session Message">SM</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>sequence numbers for transport</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="sources_detail_transport_Label">
<property name="text">
<string>XXXXX:XXX.XXX.XXX.XXX:XXXXX:XXXXXXXX:XXX.XXX.XXX.XXX:XXXXX</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="QStackedWidget" name="stackedWidget">
<property name="enabled">
<bool>true</bool>
</property>
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="lineWidth">
<number>1</number>
</property>
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="sources_detail_sqn_page">
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QTreeWidget" name="sources_detail_sqn_TreeWidget">
<column>
<property name="text">
<string>SQN</string>
</property>
</column>
<column>
<property name="text">
<string>Count</string>
</property>
</column>
<column>
<property name="text">
<string>Frame</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="sources_detail_ncf_sqn_page">
<layout class="QHBoxLayout" name="horizontalLayout_6">
<item>
<widget class="QTreeWidget" name="sources_detail_ncf_sqn_TreeWidget">
<column>
<property name="text">
<string>SQN/Reason</string>
</property>
</column>
<column>
<property name="text">
<string>Count</string>
</property>
</column>
<column>
<property name="text">
<string>Frame</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="receiversTab">
<attribute name="title">
<string>Receivers</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<widget class="QSplitter" name="splitter_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="handleWidth">
<number>10</number>
</property>
<widget class="QTreeWidget" name="receivers_TreeWidget">
<column>
<property name="text">
<string>Address/Transport</string>
</property>
</column>
<column>
<property name="text">
<string>NAK frames</string>
</property>
</column>
<column>
<property name="text">
<string>NAK count</string>
</property>
</column>
<column>
<property name="text">
<string>NAK bytes</string>
</property>
</column>
<column>
<property name="text">
<string>NAK rate</string>
</property>
</column>
</widget>
<widget class="QWidget" name="layoutWidget_2">
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="label_4">
<property name="text">
<string>NAK sequence numbers for transport</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="receivers_detail_transport_Label">
<property name="text">
<string>XXXXX:XXX.XXX.XXX.XXX:XXXXX:XXXXXXXX:XXX.XXX.XXX.XXX:XXXXX</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Expanding</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>10</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="QTreeWidget" name="receivers_detail_TreeWidget">
<column>
<property name="text">
<string>SQN</string>
</property>
</column>
<column>
<property name="text">
<string>Count</string>
</property>
</column>
<column>
<property name="text">
<string>Frame</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="topMargin">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Display filter:</string>
</property>
</widget>
</item>
<item>
<widget class="DisplayFilterEdit" name="displayFilterLineEdit"/>
</item>
<item>
<widget class="QPushButton" name="applyFilterButton">
<property name="toolTip">
<string>Regenerate statistics using this display filter</string>
</property>
<property name="text">
<string>Apply</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::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 the tree as CSV</string>
</property>
<property name="shortcut">
<string notr="true">Ctrl+C</string>
</property>
</action>
<action name="actionCopyAsYAML">
<property name="text">
<string>Copy as YAML</string>
</property>
<property name="toolTip">
<string>Copy the tree as YAML</string>
</property>
<property name="shortcut">
<string notr="true">Ctrl+Y</string>
</property>
</action>
<action name="action_SourceDataFrames">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>Data frames</string>
</property>
<property name="toolTip">
<string>Show the data frames column</string>
</property>
</action>
<action name="action_SourceDataBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>Data bytes</string>
</property>
<property name="toolTip">
<string>Show the data bytes column</string>
</property>
</action>
<action name="action_SourceDataFramesBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>Data frames/bytes</string>
</property>
<property name="toolTip">
<string>Show the data frames/bytes column</string>
</property>
</action>
<action name="action_SourceRXDataFrames">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>RX data frames</string>
</property>
<property name="toolTip">
<string>Show the RX data frames column</string>
</property>
</action>
<action name="action_SourceRXDataBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>RX data bytes</string>
</property>
<property name="toolTip">
<string>Show the RX data bytes column</string>
</property>
</action>
<action name="action_SourceRXDataFramesBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>RX data frames/bytes</string>
</property>
<property name="toolTip">
<string>Show the RX data frames/bytes column</string>
</property>
</action>
<action name="action_SourceNCFFrames">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF frames</string>
</property>
<property name="toolTip">
<string>Show the NCF frames column</string>
</property>
</action>
<action name="action_SourceNCFBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF bytes</string>
</property>
<property name="toolTip">
<string>Show the NCF bytes column</string>
</property>
</action>
<action name="action_SourceNCFCount">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF count</string>
</property>
<property name="toolTip">
<string>Show the NCF count column</string>
</property>
</action>
<action name="action_SourceDataRate">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>Data rate</string>
</property>
<property name="toolTip">
<string>Show the data rate column</string>
</property>
</action>
<action name="action_SourceRXDataRate">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>RX data rate</string>
</property>
<property name="toolTip">
<string>Show the RX data rate column</string>
</property>
</action>
<action name="action_SourceNCFFramesBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF frames/bytes</string>
</property>
<property name="toolTip">
<string>Show the NCF frames/bytes column</string>
</property>
</action>
<action name="action_SourceNCFCountBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF count/bytes</string>
</property>
<property name="toolTip">
<string>Show the NCF count/bytes column</string>
</property>
</action>
<action name="action_SourceNCFFramesCount">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF frames/count</string>
</property>
<property name="toolTip">
<string>Show the NCF frames/count column</string>
</property>
</action>
<action name="action_SourceNCFFramesCountBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF frames/count/bytes</string>
</property>
<property name="toolTip">
<string>Show the NCF frames/count/bytes column</string>
</property>
</action>
<action name="action_SourceNCFRate">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF rate</string>
</property>
<property name="toolTip">
<string>Show the NCF rate column</string>
</property>
</action>
<action name="action_SourceSMFrames">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>SM frames</string>
</property>
<property name="toolTip">
<string>Show the SM frames column</string>
</property>
</action>
<action name="action_SourceSMBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>SM bytes</string>
</property>
<property name="toolTip">
<string>Show the SM bytes column</string>
</property>
</action>
<action name="action_SourceSMFramesBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>SM frames/bytes</string>
</property>
<property name="toolTip">
<string>Show the SM frames/bytes column</string>
</property>
</action>
<action name="action_SourceSMRate">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>SM rate</string>
</property>
<property name="toolTip">
<string>Show the SM rate column</string>
</property>
</action>
<action name="action_SourceAutoResizeColumns">
<property name="text">
<string>Auto-resize columns to content</string>
</property>
<property name="toolTip">
<string>Resize columns to content size</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>DisplayFilterEdit</class>
<extends>QLineEdit</extends>
<header>widgets/display_filter_edit.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>LBMLBTRMTransportDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>255</x>
<y>555</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>LBMLBTRMTransportDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>323</x>
<y>555</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>sources_detail_ComboBox</sender>
<signal>currentIndexChanged(int)</signal>
<receiver>LBMLBTRMTransportDialog</receiver>
<slot>sourcesDetailCurrentChanged(int)</slot>
<hints>
<hint type="sourcelabel">
<x>135</x>
<y>269</y>
</hint>
<hint type="destinationlabel">
<x>446</x>
<y>310</y>
</hint>
</hints>
</connection>
<connection>
<sender>sources_TreeWidget</sender>
<signal>itemClicked(QTreeWidgetItem*,int)</signal>
<receiver>LBMLBTRMTransportDialog</receiver>
<slot>sourcesItemClicked(QTreeWidgetItem*,int)</slot>
<hints>
<hint type="sourcelabel">
<x>440</x>
<y>149</y>
</hint>
<hint type="destinationlabel">
<x>446</x>
<y>310</y>
</hint>
</hints>
</connection>
<connection>
<sender>receivers_TreeWidget</sender>
<signal>itemClicked(QTreeWidgetItem*,int)</signal>
<receiver>LBMLBTRMTransportDialog</receiver>
<slot>receiversItemClicked(QTreeWidgetItem*,int)</slot>
<hints>
<hint type="sourcelabel">
<x>420</x>
<y>141</y>
</hint>
<hint type="destinationlabel">
<x>420</x>
<y>281</y>
</hint>
</hints>
</connection>
<connection>
<sender>receivers_detail_TreeWidget</sender>
<signal>itemDoubleClicked(QTreeWidgetItem*,int)</signal>
<receiver>LBMLBTRMTransportDialog</receiver>
<slot>receiversDetailItemDoubleClicked(QTreeWidgetItem*,int)</slot>
<hints>
<hint type="sourcelabel">
<x>75</x>
<y>328</y>
</hint>
<hint type="destinationlabel">
<x>420</x>
<y>281</y>
</hint>
</hints>
</connection>
<connection>
<sender>sources_detail_sqn_TreeWidget</sender>
<signal>itemDoubleClicked(QTreeWidgetItem*,int)</signal>
<receiver>LBMLBTRMTransportDialog</receiver>
<slot>sourcesDetailItemDoubleClicked(QTreeWidgetItem*,int)</slot>
<hints>
<hint type="sourcelabel">
<x>420</x>
<y>377</y>
</hint>
<hint type="destinationlabel">
<x>420</x>
<y>281</y>
</hint>
</hints>
</connection>
<connection>
<sender>sources_detail_ncf_sqn_TreeWidget</sender>
<signal>itemDoubleClicked(QTreeWidgetItem*,int)</signal>
<receiver>LBMLBTRMTransportDialog</receiver>
<slot>sourcesDetailItemDoubleClicked(QTreeWidgetItem*,int)</slot>
<hints>
<hint type="sourcelabel">
<x>66</x>
<y>290</y>
</hint>
<hint type="destinationlabel">
<x>420</x>
<y>281</y>
</hint>
</hints>
</connection>
</connections>
<slots>
<signal>goToPacket(int)</signal>
<slot>sourcesDetailCurrentChanged(int)</slot>
<slot>sourcesItemClicked(QTreeWidgetItem*,int)</slot>
<slot>receiversItemClicked(QTreeWidgetItem*,int)</slot>
<slot>sourcesDetailItemDoubleClicked(QTreeWidgetItem*,int)</slot>
<slot>receiversDetailItemDoubleClicked(QTreeWidgetItem*,int)</slot>
</slots>
</ui> |
C++ | wireshark/ui/qt/lbm_lbtru_transport_dialog.cpp | /* lbm_lbtru_transport_dialog.cpp
*
* Copyright (c) 2005-2014 Informatica Corporation. All Rights Reserved.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "lbm_lbtru_transport_dialog.h"
#include <ui_lbm_lbtru_transport_dialog.h>
#include "file.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
#include <QClipboard>
#include <QMessageBox>
#include <QTreeWidget>
#include <QTreeWidgetItemIterator>
#include <QMenu>
#include <QTreeWidgetItem>
#include <epan/packet_info.h>
#include <epan/tap.h>
#include <epan/to_str.h>
#include <epan/dissectors/packet-lbm.h>
#include <wsutil/nstime.h>
#include <QDebug>
namespace
{
static const int Source_AddressTransport_Column = 0;
static const int Source_DataFrames_Column = 1;
static const int Source_DataBytes_Column = 2;
static const int Source_DataFramesBytes_Column = 3;
static const int Source_DataRate_Column = 4;
static const int Source_RXDataFrames_Column = 5;
static const int Source_RXDataBytes_Column = 6;
static const int Source_RXDataFramesBytes_Column = 7;
static const int Source_RXDataRate_Column = 8;
static const int Source_NCFFrames_Column = 9;
static const int Source_NCFCount_Column = 10;
static const int Source_NCFBytes_Column = 11;
static const int Source_NCFFramesBytes_Column = 12;
static const int Source_NCFCountBytes_Column = 13;
static const int Source_NCFFramesCount_Column = 14;
static const int Source_NCFFramesCountBytes_Column = 15;
static const int Source_NCFRate_Column = 16;
static const int Source_SMFrames_Column = 17;
static const int Source_SMBytes_Column = 18;
static const int Source_SMFramesBytes_Column = 19;
static const int Source_SMRate_Column = 20;
static const int Source_RSTFrames_Column = 21;
static const int Source_RSTBytes_Column = 22;
static const int Source_RSTFramesBytes_Column = 23;
static const int Source_RSTRate_Column = 24;
static const int Receiver_AddressTransport_Column = 0;
static const int Receiver_NAKFrames_Column = 1;
static const int Receiver_NAKCount_Column = 2;
static const int Receiver_NAKBytes_Column = 3;
static const int Receiver_NAKFramesCount_Column = 4;
static const int Receiver_NAKCountBytes_Column = 5;
static const int Receiver_NAKFramesBytes_Column = 6;
static const int Receiver_NAKFramesCountBytes_Column = 7;
static const int Receiver_NAKRate_Column = 8;
static const int Receiver_ACKFrames_Column = 9;
static const int Receiver_ACKBytes_Column = 10;
static const int Receiver_ACKFramesBytes_Column = 11;
static const int Receiver_ACKRate_Column = 12;
static const int Receiver_CREQFrames_Column = 13;
static const int Receiver_CREQBytes_Column = 14;
static const int Receiver_CREQFramesBytes_Column = 15;
static const int Receiver_CREQRate_Column = 16;
static const int Detail_SQNReasonType_Column = 0;
static const int Detail_Count_Column = 1;
static const int Detail_Frame_Column = 2;
static const double OneKilobit = 1000.0;
static const double OneMegabit = OneKilobit * OneKilobit;
static const double OneGigabit = OneMegabit * OneKilobit;
}
static QString format_rate(const nstime_t & elapsed, guint64 bytes)
{
QString result;
double elapsed_sec;
double rate;
if (((elapsed.secs == 0) && (elapsed.nsecs == 0)) || (bytes == 0))
{
return (QString("0"));
}
elapsed_sec = elapsed.secs + (((double)elapsed.nsecs) / 1000000000.0);
rate = ((double)(bytes * 8)) / elapsed_sec;
// Currently rate is in bps
if (rate >= OneGigabit)
{
rate /= OneGigabit;
result = QString("%1G").arg(rate, 0, 'f', 2);
}
else if (rate >= OneMegabit)
{
rate /= OneMegabit;
result = QString("%1M").arg(rate, 0, 'f', 2);
}
else if (rate >= OneKilobit)
{
rate /= OneKilobit;
result = QString("%1K").arg(rate, 0, 'f', 2);
}
else
{
result = QString("%1").arg(rate, 0, 'f', 2);
}
return (result);
}
// Note:
// LBMLBTRUFrameEntry, LBMLBTRUSQNEntry, LBMLBTRUNCFReasonEntry, LBMLBTRUNCFSQNEntry, LBMLBTRURSTReasonEntry, LBMLBTRUCREQRequestEntry,
// LBMLBTRUSourceTransportEntry, LBMLBTRUSourceEntry, LBMLBTRUReceiverTransportEntry, and LBMLBTRUReceiverEntry are all derived from
// a QTreeWidgetItem. Each instantiation can exist in two places: in a QTreeWidget, and in a containing QMap.
//
// For example:
// - LBMLBTRUTransportDialogInfo contains a QMap of the sources (LBMLBTRUSourceEntry) and receivers (LBMLBTRUReceiverEntry)
// - A source (LBMLBTRUSourceEntry) contains a QMap of the source transports originating from it (LBMLBTRUSourceTransportEntry)
// - A source transport (LBMLBTRUSourceTransportEntry) contains QMaps of data, RX data, and SM SQNs (LBMLBTRUSQNEntry), NCF SQNs
// (LBMLBTRUNCFSQNEntry), and RST reasons (LBMLBTRURSTReasonEntry)
// - A data SQN (LBMLBTRUSQNEntry) contains a QMap of the frames (LBMLBTRUFrameEntry) in which that SQN appears
//
// Not all of the entries actually appear in a QTreeWidget at one time. For example, in the source details, if no specific source
// transport is selected, nothing is in the source details tree. If Data SQNs is selected, then those details appear in the source
// details tree. Switching to RX Data SQNs removes whatever is currently in the source details tree, and adds the RX details for
// the selected transport.
//
// The actual owner of one of the above QTreeWidgetItem-derived items is the QMap container in its parent. The item is "loaned" to
// the QTreeWidget for display.
//
// All of this is to explain why
// 1) we are frequently adding things to a QTreeWidget
// 2) things are removed (takeTopLevelItem) from a QTreeWidget
// 3) destruction involves removing all items from all QTreeWidgets (rather than letting QTreeWidget delete them)
// 4) the destructor for each item has the form
// <for each QMap container>
// for (XXXMapIterator it = m_xxx.begin(); it != m_xxx.end(); ++it)
// {
// delete *it;
// }
// m_xxx.clear();
// The for-loop calls the destructor for each item, while the clear() cleans up the space used by the QMap itself.
// A frame entry
class LBMLBTRUFrameEntry : public QTreeWidgetItem
{
public:
LBMLBTRUFrameEntry(guint32 frame);
virtual ~LBMLBTRUFrameEntry(void) { }
guint32 getFrame(void) { return (m_frame); }
private:
guint32 m_frame;
};
LBMLBTRUFrameEntry::LBMLBTRUFrameEntry(guint32 frame) :
QTreeWidgetItem(),
m_frame(frame)
{
setText(Detail_SQNReasonType_Column, QString(" "));
setText(Detail_Count_Column, QString(" "));
setText(Detail_Frame_Column, QString("%1").arg(m_frame));
}
typedef QMap<guint32, LBMLBTRUFrameEntry *> LBMLBTRUFrameMap;
typedef QMap<guint32, LBMLBTRUFrameEntry *>::iterator LBMLBTRUFrameMapIterator;
// An SQN (SeQuence Number) entry
class LBMLBTRUSQNEntry : public QTreeWidgetItem
{
public:
LBMLBTRUSQNEntry(guint32 sqn);
virtual ~LBMLBTRUSQNEntry(void);
void processFrame(guint32 frame);
private:
LBMLBTRUSQNEntry(void);
guint32 m_sqn;
guint32 m_count;
LBMLBTRUFrameMap m_frames;
};
LBMLBTRUSQNEntry::LBMLBTRUSQNEntry(guint32 sqn) :
QTreeWidgetItem(),
m_sqn(sqn),
m_count(0),
m_frames()
{
setText(Detail_SQNReasonType_Column, QString("%1").arg(m_sqn));
setTextAlignment(Detail_SQNReasonType_Column, Qt::AlignRight);
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
setText(Detail_Frame_Column, QString(" "));
}
LBMLBTRUSQNEntry::~LBMLBTRUSQNEntry(void)
{
for (LBMLBTRUFrameMapIterator it = m_frames.begin(); it != m_frames.end(); ++it)
{
delete *it;
}
m_frames.clear();
}
void LBMLBTRUSQNEntry::processFrame(guint32 frame)
{
LBMLBTRUFrameMapIterator it;
it = m_frames.find(frame);
if (m_frames.end() == it)
{
LBMLBTRUFrameEntry * entry = new LBMLBTRUFrameEntry(frame);
m_frames.insert(frame, entry);
addChild(entry);
sortChildren(Detail_Frame_Column, Qt::AscendingOrder);
}
m_count++;
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
}
// An NCF (Nak ConFirmation) Reason entry
class LBMLBTRUNCFReasonEntry : public QTreeWidgetItem
{
public:
LBMLBTRUNCFReasonEntry(guint8 reason);
virtual ~LBMLBTRUNCFReasonEntry(void);
void processFrame(guint32 frame);
private:
LBMLBTRUNCFReasonEntry(void);
guint8 m_reason;
guint32 m_count;
LBMLBTRUFrameMap m_frames;
};
LBMLBTRUNCFReasonEntry::LBMLBTRUNCFReasonEntry(guint8 reason) :
QTreeWidgetItem(),
m_reason(reason),
m_count(0),
m_frames()
{
switch (m_reason)
{
case LBTRU_NCF_REASON_NO_RETRY:
setText(Detail_SQNReasonType_Column, QString("No Retry"));
break;
case LBTRU_NCF_REASON_IGNORED:
setText(Detail_SQNReasonType_Column, QString("Ignored"));
break;
case LBTRU_NCF_REASON_RX_DELAY:
setText(Detail_SQNReasonType_Column, QString("Retransmit Delay"));
break;
case LBTRU_NCF_REASON_SHED:
setText(Detail_SQNReasonType_Column, QString("Shed"));
break;
default:
setText(Detail_SQNReasonType_Column, QString("Unknown"));
break;
}
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
setText(Detail_Frame_Column, QString(" "));
}
LBMLBTRUNCFReasonEntry::~LBMLBTRUNCFReasonEntry(void)
{
for (LBMLBTRUFrameMapIterator it = m_frames.begin(); it != m_frames.end(); ++it)
{
delete *it;
}
m_frames.clear();
}
void LBMLBTRUNCFReasonEntry::processFrame(guint32 frame)
{
LBMLBTRUFrameMapIterator it;
it = m_frames.find(frame);
if (m_frames.end() == it)
{
LBMLBTRUFrameEntry * entry = new LBMLBTRUFrameEntry(frame);
m_frames.insert(frame, entry);
addChild(entry);
sortChildren(Detail_Frame_Column, Qt::AscendingOrder);
}
m_count++;
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
}
typedef QMap<guint8, LBMLBTRUNCFReasonEntry *> LBMLBTRUNCFReasonMap;
typedef QMap<guint8, LBMLBTRUNCFReasonEntry *>::iterator LBMLBTRUNCFReasonMapIterator;
// An NCF SQN entry
class LBMLBTRUNCFSQNEntry : public QTreeWidgetItem
{
public:
LBMLBTRUNCFSQNEntry(guint32 sqn);
virtual ~LBMLBTRUNCFSQNEntry(void);
void processFrame(guint8 reason, guint32 frame);
private:
LBMLBTRUNCFSQNEntry(void);
guint32 m_sqn;
guint32 m_count;
LBMLBTRUNCFReasonMap m_reasons;
};
LBMLBTRUNCFSQNEntry::LBMLBTRUNCFSQNEntry(guint32 sqn) :
QTreeWidgetItem(),
m_sqn(sqn),
m_count(0),
m_reasons()
{
setText(Detail_SQNReasonType_Column, QString("%1").arg(m_sqn));
setTextAlignment(Detail_SQNReasonType_Column, Qt::AlignRight);
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
setText(Detail_Frame_Column, QString(" "));
}
LBMLBTRUNCFSQNEntry::~LBMLBTRUNCFSQNEntry(void)
{
for (LBMLBTRUNCFReasonMapIterator it = m_reasons.begin(); it != m_reasons.end(); ++it)
{
delete *it;
}
m_reasons.clear();
}
void LBMLBTRUNCFSQNEntry::processFrame(guint8 reason, guint32 frame)
{
LBMLBTRUNCFReasonMapIterator it;
LBMLBTRUNCFReasonEntry * entry = NULL;
it = m_reasons.find(reason);
if (m_reasons.end() == it)
{
entry = new LBMLBTRUNCFReasonEntry(reason);
m_reasons.insert(reason, entry);
addChild(entry);
sortChildren(Detail_Frame_Column, Qt::AscendingOrder);
}
else
{
entry = it.value();
}
m_count++;
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
entry->processFrame(frame);
}
// An RST (ReSeT) Reason entry
class LBMLBTRURSTReasonEntry : public QTreeWidgetItem
{
public:
LBMLBTRURSTReasonEntry(guint32 reason);
virtual ~LBMLBTRURSTReasonEntry(void);
void processFrame(guint32 frame);
private:
LBMLBTRURSTReasonEntry(void);
guint32 m_reason;
QString m_reason_string;
guint32 m_count;
LBMLBTRUFrameMap m_frames;
};
LBMLBTRURSTReasonEntry::LBMLBTRURSTReasonEntry(guint32 reason) :
QTreeWidgetItem(),
m_reason(reason),
m_reason_string(),
m_count(0),
m_frames()
{
switch (m_reason)
{
case LBTRU_RST_REASON_DEFAULT:
m_reason_string = "Default";
break;
default:
m_reason_string = QString("Unknown (%1)").arg(m_reason);
break;
}
setText(Detail_SQNReasonType_Column, m_reason_string);
setTextAlignment(Detail_SQNReasonType_Column, Qt::AlignLeft);
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
setText(Detail_Frame_Column, QString(" "));
}
LBMLBTRURSTReasonEntry::~LBMLBTRURSTReasonEntry(void)
{
for (LBMLBTRUFrameMapIterator it = m_frames.begin(); it != m_frames.end(); ++it)
{
delete *it;
}
m_frames.clear();
}
void LBMLBTRURSTReasonEntry::processFrame(guint32 frame)
{
LBMLBTRUFrameMapIterator it;
it = m_frames.find(frame);
if (m_frames.end() == it)
{
LBMLBTRUFrameEntry * entry = new LBMLBTRUFrameEntry(frame);
m_frames.insert(frame, entry);
addChild(entry);
sortChildren(Detail_Frame_Column, Qt::AscendingOrder);
}
m_count++;
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
}
// A CREQ (Connection REQuest) Request entry
class LBMLBTRUCREQRequestEntry : public QTreeWidgetItem
{
public:
LBMLBTRUCREQRequestEntry(guint32 request);
virtual ~LBMLBTRUCREQRequestEntry(void);
void processFrame(guint32 frame);
private:
LBMLBTRUCREQRequestEntry(void);
guint32 m_request;
QString m_request_string;
guint32 m_count;
LBMLBTRUFrameMap m_frames;
};
LBMLBTRUCREQRequestEntry::LBMLBTRUCREQRequestEntry(guint32 request) :
QTreeWidgetItem(),
m_request(request),
m_request_string(),
m_count(0),
m_frames()
{
switch (m_request)
{
case LBTRU_CREQ_REQUEST_SYN:
m_request_string = "SYN";
break;
default:
m_request_string = QString("Unknown (%1)").arg(m_request);
break;
}
setText(Detail_SQNReasonType_Column, m_request_string);
setTextAlignment(Detail_SQNReasonType_Column, Qt::AlignLeft);
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
setText(Detail_Frame_Column, QString(" "));
}
LBMLBTRUCREQRequestEntry::~LBMLBTRUCREQRequestEntry(void)
{
for (LBMLBTRUFrameMapIterator it = m_frames.begin(); it != m_frames.end(); ++it)
{
delete *it;
}
m_frames.clear();
}
void LBMLBTRUCREQRequestEntry::processFrame(guint32 frame)
{
LBMLBTRUFrameMapIterator it;
it = m_frames.find(frame);
if (m_frames.end() == it)
{
LBMLBTRUFrameEntry * entry = new LBMLBTRUFrameEntry(frame);
m_frames.insert(frame, entry);
addChild(entry);
sortChildren(Detail_Frame_Column, Qt::AscendingOrder);
}
m_count++;
setText(Detail_Count_Column, QString("%1").arg(m_count));
setTextAlignment(Detail_Count_Column, Qt::AlignRight);
}
typedef QMap<guint32, LBMLBTRUSQNEntry *> LBMLBTRUSQNMap;
typedef QMap<guint32, LBMLBTRUSQNEntry *>::iterator LBMLBTRUSQNMapIterator;
typedef QMap<guint32, LBMLBTRUNCFSQNEntry *> LBMLBTRUNCFSQNMap;
typedef QMap<guint32, LBMLBTRUNCFSQNEntry *>::iterator LBMLBTRUNCFSQNMapIterator;
typedef QMap<guint32, LBMLBTRURSTReasonEntry *> LBMLBTRURSTReasonMap;
typedef QMap<guint32, LBMLBTRURSTReasonEntry *>::iterator LBMLBTRURSTReasonMapIterator;
typedef QMap<guint32, LBMLBTRUCREQRequestEntry *> LBMLBTRUCREQRequestMap;
typedef QMap<guint32, LBMLBTRUCREQRequestEntry *>::iterator LBMLBTRUCREQRequestMapIterator;
// A source transport entry
class LBMLBTRUSourceTransportEntry : public QTreeWidgetItem
{
friend class LBMLBTRUTransportDialog;
public:
LBMLBTRUSourceTransportEntry(const QString & transport);
virtual ~LBMLBTRUSourceTransportEntry(void);
void processPacket(const packet_info * pinfo, const lbm_lbtru_tap_info_t * tap_info);
protected:
QString m_transport;
private:
void fillItem(void);
guint64 m_data_frames;
guint64 m_data_bytes;
guint64 m_rx_data_frames;
guint64 m_rx_data_bytes;
guint64 m_ncf_frames;
guint64 m_ncf_count;
guint64 m_ncf_bytes;
guint64 m_sm_frames;
guint64 m_sm_bytes;
guint64 m_rst_frames;
guint64 m_rst_bytes;
nstime_t m_first_frame_timestamp;
bool m_first_frame_timestamp_valid;
nstime_t m_last_frame_timestamp;
protected:
LBMLBTRUSQNMap m_data_sqns;
LBMLBTRUSQNMap m_rx_data_sqns;
LBMLBTRUNCFSQNMap m_ncf_sqns;
LBMLBTRUSQNMap m_sm_sqns;
LBMLBTRURSTReasonMap m_rst_reasons;
};
LBMLBTRUSourceTransportEntry::LBMLBTRUSourceTransportEntry(const QString & transport) :
QTreeWidgetItem(),
m_transport(transport),
m_data_frames(0),
m_data_bytes(0),
m_rx_data_frames(0),
m_rx_data_bytes(0),
m_ncf_frames(0),
m_ncf_count(0),
m_ncf_bytes(0),
m_sm_frames(0),
m_sm_bytes(0),
m_rst_frames(0),
m_rst_bytes(0),
m_first_frame_timestamp_valid(false),
m_data_sqns(),
m_rx_data_sqns(),
m_ncf_sqns(),
m_sm_sqns(),
m_rst_reasons()
{
m_first_frame_timestamp.secs = 0;
m_first_frame_timestamp.nsecs = 0;
m_last_frame_timestamp.secs = 0;
m_last_frame_timestamp.nsecs = 0;
setText(Source_AddressTransport_Column, m_transport);
}
LBMLBTRUSourceTransportEntry::~LBMLBTRUSourceTransportEntry(void)
{
for (LBMLBTRUSQNMapIterator it = m_data_sqns.begin(); it != m_data_sqns.end(); ++it)
{
delete *it;
}
m_data_sqns.clear();
for (LBMLBTRUSQNMapIterator it = m_rx_data_sqns.begin(); it != m_rx_data_sqns.end(); ++it)
{
delete *it;
}
m_rx_data_sqns.clear();
for (LBMLBTRUNCFSQNMapIterator it = m_ncf_sqns.begin(); it != m_ncf_sqns.end(); ++it)
{
delete *it;
}
m_ncf_sqns.clear();
for (LBMLBTRUSQNMapIterator it = m_sm_sqns.begin(); it != m_sm_sqns.end(); ++it)
{
delete *it;
}
m_sm_sqns.clear();
for (LBMLBTRURSTReasonMapIterator it = m_rst_reasons.begin(); it != m_rst_reasons.end(); ++it)
{
delete *it;
}
m_rst_reasons.clear();
}
void LBMLBTRUSourceTransportEntry::processPacket(const packet_info * pinfo, const lbm_lbtru_tap_info_t * tap_info)
{
if (m_first_frame_timestamp_valid)
{
if (nstime_cmp(&(pinfo->abs_ts), &m_first_frame_timestamp) < 0)
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
}
}
else
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
m_first_frame_timestamp_valid = true;
}
if (nstime_cmp(&(pinfo->abs_ts), &m_last_frame_timestamp) > 0)
{
nstime_copy(&(m_last_frame_timestamp), &(pinfo->abs_ts));
}
if (tap_info->type == LBTRU_PACKET_TYPE_DATA)
{
LBMLBTRUSQNEntry * sqn = NULL;
LBMLBTRUSQNMapIterator it;
if (tap_info->retransmission)
{
m_rx_data_frames++;
m_rx_data_bytes += pinfo->fd->pkt_len;
it = m_rx_data_sqns.find(tap_info->sqn);
if (m_rx_data_sqns.end() == it)
{
sqn = new LBMLBTRUSQNEntry(tap_info->sqn);
m_rx_data_sqns.insert(tap_info->sqn, sqn);
}
else
{
sqn = it.value();
}
sqn->processFrame(pinfo->num);
}
else
{
m_data_frames++;
m_data_bytes += pinfo->fd->pkt_len;
it = m_data_sqns.find(tap_info->sqn);
if (m_data_sqns.end() == it)
{
sqn = new LBMLBTRUSQNEntry(tap_info->sqn);
m_data_sqns.insert(tap_info->sqn, sqn);
}
else
{
sqn = it.value();
}
}
sqn->processFrame(pinfo->num);
}
else if (tap_info->type == LBTRU_PACKET_TYPE_NCF)
{
guint16 idx;
LBMLBTRUNCFSQNMapIterator it;
LBMLBTRUNCFSQNEntry * sqn = NULL;
m_ncf_frames++;
m_ncf_bytes += pinfo->fd->pkt_len;
m_ncf_count += (guint64)tap_info->num_sqns;
for (idx = 0; idx < tap_info->num_sqns; idx++)
{
it = m_ncf_sqns.find(tap_info->sqns[idx]);
if (m_ncf_sqns.end() == it)
{
sqn = new LBMLBTRUNCFSQNEntry(tap_info->sqns[idx]);
m_ncf_sqns.insert(tap_info->sqns[idx], sqn);
}
else
{
sqn = it.value();
}
sqn->processFrame(tap_info->ncf_reason, pinfo->num);
}
}
else if (tap_info->type == LBTRU_PACKET_TYPE_SM)
{
LBMLBTRUSQNEntry * sqn = NULL;
LBMLBTRUSQNMapIterator it;
m_sm_frames++;
m_sm_bytes += pinfo->fd->pkt_len;
it = m_sm_sqns.find(tap_info->sqn);
if (m_sm_sqns.end() == it)
{
sqn = new LBMLBTRUSQNEntry(tap_info->sqn);
m_sm_sqns.insert(tap_info->sqn, sqn);
}
else
{
sqn = it.value();
}
sqn->processFrame(pinfo->num);
}
else if (tap_info->type == LBTRU_PACKET_TYPE_RST)
{
LBMLBTRURSTReasonEntry * reason = NULL;
LBMLBTRURSTReasonMapIterator it;
m_rst_frames++;
m_rst_bytes += pinfo->fd->pkt_len;
it = m_rst_reasons.find(tap_info->rst_type);
if (m_rst_reasons.end() == it)
{
reason = new LBMLBTRURSTReasonEntry(tap_info->rst_type);
m_rst_reasons.insert((unsigned int) tap_info->rst_type, reason);
}
else
{
reason = it.value();
}
reason->processFrame(pinfo->num);
}
else
{
return;
}
fillItem();
}
void LBMLBTRUSourceTransportEntry::fillItem(void)
{
nstime_t delta;
nstime_delta(&delta, &m_last_frame_timestamp, &m_first_frame_timestamp);
setText(Source_DataFrames_Column, QString("%1").arg(m_data_frames));
setTextAlignment(Source_DataFrames_Column, Qt::AlignRight);
setText(Source_DataBytes_Column, QString("%1").arg(m_data_bytes));
setTextAlignment(Source_DataBytes_Column, Qt::AlignRight);
setText(Source_DataFramesBytes_Column, QString("%1/%2").arg(m_data_frames).arg(m_data_bytes));
setTextAlignment(Source_DataFramesBytes_Column, Qt::AlignHCenter);
setText(Source_DataRate_Column, format_rate(delta, m_data_bytes));
setTextAlignment(Source_DataRate_Column, Qt::AlignRight);
setText(Source_RXDataFrames_Column, QString("%1").arg(m_rx_data_frames));
setTextAlignment(Source_RXDataFrames_Column, Qt::AlignRight);
setText(Source_RXDataBytes_Column, QString("%1").arg(m_rx_data_bytes));
setTextAlignment(Source_RXDataBytes_Column, Qt::AlignRight);
setText(Source_RXDataFramesBytes_Column, QString("%1/%2").arg(m_rx_data_frames).arg(m_rx_data_bytes));
setTextAlignment(Source_RXDataFramesBytes_Column, Qt::AlignHCenter);
setText(Source_RXDataRate_Column, format_rate(delta, m_rx_data_bytes));
setTextAlignment(Source_RXDataRate_Column, Qt::AlignRight);
setText(Source_NCFFrames_Column, QString("%1").arg(m_ncf_frames));
setTextAlignment(Source_NCFFrames_Column, Qt::AlignRight);
setText(Source_NCFCount_Column, QString("%1").arg(m_ncf_count));
setTextAlignment(Source_NCFCount_Column, Qt::AlignRight);
setText(Source_NCFBytes_Column, QString("%1").arg(m_ncf_bytes));
setTextAlignment(Source_NCFBytes_Column, Qt::AlignRight);
setText(Source_NCFFramesBytes_Column, QString("%1/%2").arg(m_ncf_frames).arg(m_ncf_bytes));
setTextAlignment(Source_NCFFramesBytes_Column, Qt::AlignHCenter);
setText(Source_NCFCountBytes_Column, QString("%1/%2").arg(m_ncf_count).arg(m_ncf_bytes));
setTextAlignment(Source_NCFCountBytes_Column, Qt::AlignHCenter);
setText(Source_NCFFramesCount_Column, QString("%1/%2").arg(m_ncf_count).arg(m_ncf_count));
setTextAlignment(Source_NCFFramesCount_Column, Qt::AlignHCenter);
setText(Source_NCFFramesCountBytes_Column, QString("%1/%2/%3").arg(m_ncf_frames).arg(m_ncf_count).arg(m_ncf_bytes));
setTextAlignment(Source_NCFFramesCountBytes_Column, Qt::AlignHCenter);
setText(Source_NCFRate_Column, format_rate(delta, m_ncf_bytes));
setTextAlignment(Source_NCFRate_Column, Qt::AlignRight);
setText(Source_SMFrames_Column, QString("%1").arg(m_sm_frames));
setTextAlignment(Source_SMFrames_Column, Qt::AlignRight);
setText(Source_SMBytes_Column, QString("%1").arg(m_sm_bytes));
setTextAlignment(Source_SMBytes_Column, Qt::AlignRight);
setText(Source_SMFramesBytes_Column, QString("%1/%2").arg(m_sm_frames).arg(m_sm_bytes));
setTextAlignment(Source_SMFramesBytes_Column, Qt::AlignHCenter);
setText(Source_SMRate_Column, format_rate(delta, m_sm_bytes));
setTextAlignment(Source_SMRate_Column, Qt::AlignRight);
setText(Source_RSTFrames_Column, QString("%1").arg(m_rst_frames));
setTextAlignment(Source_RSTFrames_Column, Qt::AlignRight);
setText(Source_RSTBytes_Column, QString("%1").arg(m_rst_bytes));
setTextAlignment(Source_RSTBytes_Column, Qt::AlignRight);
setText(Source_RSTFramesBytes_Column, QString("%1/%2").arg(m_rst_frames).arg(m_rst_bytes));
setTextAlignment(Source_RSTFramesBytes_Column, Qt::AlignHCenter);
setText(Source_RSTRate_Column, format_rate(delta, m_rst_bytes));
setTextAlignment(Source_RSTRate_Column, Qt::AlignRight);
}
typedef QMap<QString, LBMLBTRUSourceTransportEntry *> LBMLBTRUSourceTransportMap;
typedef QMap<QString, LBMLBTRUSourceTransportEntry *>::iterator LBMLBTRUSourceTransportMapIterator;
// A source (address) entry
class LBMLBTRUSourceEntry : public QTreeWidgetItem
{
public:
LBMLBTRUSourceEntry(const QString & source_address);
virtual ~LBMLBTRUSourceEntry(void);
void processPacket(const packet_info * pinfo, const lbm_lbtru_tap_info_t * tap_info);
private:
void fillItem(void);
QString m_address;
QString m_transport;
guint64 m_data_frames;
guint64 m_data_bytes;
guint64 m_rx_data_frames;
guint64 m_rx_data_bytes;
guint64 m_ncf_frames;
guint64 m_ncf_count;
guint64 m_ncf_bytes;
guint64 m_sm_frames;
guint64 m_sm_bytes;
guint64 m_rst_frames;
guint64 m_rst_bytes;
nstime_t m_first_frame_timestamp;
bool m_first_frame_timestamp_valid;
nstime_t m_last_frame_timestamp;
LBMLBTRUSourceTransportMap m_transports;
};
LBMLBTRUSourceEntry::LBMLBTRUSourceEntry(const QString & source_address) :
QTreeWidgetItem(),
m_address(source_address),
m_data_frames(0),
m_data_bytes(0),
m_rx_data_frames(0),
m_rx_data_bytes(0),
m_ncf_frames(0),
m_ncf_count(0),
m_ncf_bytes(0),
m_sm_frames(0),
m_sm_bytes(0),
m_rst_frames(0),
m_rst_bytes(0),
m_first_frame_timestamp_valid(false),
m_transports()
{
m_first_frame_timestamp.secs = 0;
m_first_frame_timestamp.nsecs = 0;
m_last_frame_timestamp.secs = 0;
m_last_frame_timestamp.nsecs = 0;
setText(Source_AddressTransport_Column, m_address);
}
LBMLBTRUSourceEntry::~LBMLBTRUSourceEntry(void)
{
for (LBMLBTRUSourceTransportMapIterator it = m_transports.begin(); it != m_transports.end(); ++it)
{
delete *it;
}
m_transports.clear();
}
void LBMLBTRUSourceEntry::processPacket(const packet_info * pinfo, const lbm_lbtru_tap_info_t * tap_info)
{
LBMLBTRUSourceTransportEntry * transport = NULL;
LBMLBTRUSourceTransportMapIterator it;
if (m_first_frame_timestamp_valid)
{
if (nstime_cmp(&(pinfo->abs_ts), &m_first_frame_timestamp) < 0)
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
}
}
else
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
m_first_frame_timestamp_valid = true;
}
if (nstime_cmp(&(pinfo->abs_ts), &m_last_frame_timestamp) > 0)
{
nstime_copy(&(m_last_frame_timestamp), &(pinfo->abs_ts));
}
switch (tap_info->type)
{
case LBTRU_PACKET_TYPE_DATA:
if (tap_info->retransmission)
{
m_rx_data_frames++;
m_rx_data_bytes += pinfo->fd->pkt_len;
}
else
{
m_data_frames++;
m_data_bytes += pinfo->fd->pkt_len;
}
break;
case LBTRU_PACKET_TYPE_NCF:
m_ncf_frames++;
m_ncf_bytes += pinfo->fd->pkt_len;
m_ncf_count += tap_info->num_sqns;
break;
case LBTRU_PACKET_TYPE_SM:
m_sm_frames++;
m_sm_bytes += pinfo->fd->pkt_len;
break;
case LBTRU_PACKET_TYPE_RST:
m_rst_frames++;
m_rst_bytes += pinfo->fd->pkt_len;
break;
}
it = m_transports.find(tap_info->transport);
if (m_transports.end() == it)
{
transport = new LBMLBTRUSourceTransportEntry(tap_info->transport);
m_transports.insert(tap_info->transport, transport);
addChild(transport);
sortChildren(Source_AddressTransport_Column, Qt::AscendingOrder);
}
else
{
transport = it.value();
}
fillItem();
transport->processPacket(pinfo, tap_info);
}
void LBMLBTRUSourceEntry::fillItem(void)
{
nstime_t delta;
nstime_delta(&delta, &m_last_frame_timestamp, &m_first_frame_timestamp);
setText(Source_DataFrames_Column, QString("%1").arg(m_data_frames));
setTextAlignment(Source_DataFrames_Column, Qt::AlignRight);
setText(Source_DataBytes_Column, QString("%1").arg(m_data_bytes));
setTextAlignment(Source_DataBytes_Column, Qt::AlignRight);
setText(Source_DataFramesBytes_Column, QString("%1/%2").arg(m_data_frames).arg(m_data_bytes));
setTextAlignment(Source_DataFramesBytes_Column, Qt::AlignHCenter);
setText(Source_DataRate_Column, format_rate(delta, m_data_bytes));
setTextAlignment(Source_DataRate_Column, Qt::AlignRight);
setText(Source_RXDataFrames_Column, QString("%1").arg(m_rx_data_frames));
setTextAlignment(Source_RXDataFrames_Column, Qt::AlignRight);
setText(Source_RXDataBytes_Column, QString("%1").arg(m_rx_data_bytes));
setTextAlignment(Source_RXDataBytes_Column, Qt::AlignRight);
setText(Source_RXDataFramesBytes_Column, QString("%1/%2").arg(m_rx_data_frames).arg(m_rx_data_bytes));
setTextAlignment(Source_RXDataFramesBytes_Column, Qt::AlignHCenter);
setText(Source_RXDataRate_Column, format_rate(delta, m_rx_data_bytes));
setTextAlignment(Source_RXDataRate_Column, Qt::AlignRight);
setText(Source_NCFFrames_Column, QString("%1").arg(m_ncf_frames));
setTextAlignment(Source_NCFFrames_Column, Qt::AlignRight);
setText(Source_NCFCount_Column, QString("%1").arg(m_ncf_count));
setTextAlignment(Source_NCFCount_Column, Qt::AlignRight);
setText(Source_NCFBytes_Column, QString("%1").arg(m_ncf_bytes));
setTextAlignment(Source_NCFBytes_Column, Qt::AlignRight);
setText(Source_NCFFramesBytes_Column, QString("%1/%2").arg(m_ncf_frames).arg(m_ncf_bytes));
setTextAlignment(Source_NCFFramesBytes_Column, Qt::AlignHCenter);
setText(Source_NCFCountBytes_Column, QString("%1/%2").arg(m_ncf_count).arg(m_ncf_bytes));
setTextAlignment(Source_NCFCountBytes_Column, Qt::AlignHCenter);
setText(Source_NCFFramesCount_Column, QString("%1/%2").arg(m_ncf_frames).arg(m_ncf_count));
setTextAlignment(Source_NCFFramesCount_Column, Qt::AlignHCenter);
setText(Source_NCFFramesCountBytes_Column, QString("%1/%2/%3").arg(m_ncf_frames).arg(m_ncf_count).arg(m_ncf_bytes));
setTextAlignment(Source_NCFFramesCountBytes_Column, Qt::AlignHCenter);
setText(Source_NCFRate_Column, format_rate(delta, m_ncf_bytes));
setTextAlignment(Source_NCFRate_Column, Qt::AlignRight);
setText(Source_SMFrames_Column, QString("%1").arg(m_sm_frames));
setTextAlignment(Source_SMFrames_Column, Qt::AlignRight);
setText(Source_SMBytes_Column, QString("%1").arg(m_sm_bytes));
setTextAlignment(Source_SMBytes_Column, Qt::AlignRight);
setText(Source_SMFramesBytes_Column, QString("%1/%2").arg(m_sm_frames).arg(m_sm_bytes));
setTextAlignment(Source_SMFramesBytes_Column, Qt::AlignRight);
setText(Source_SMRate_Column, format_rate(delta, m_sm_bytes));
setTextAlignment(Source_SMRate_Column, Qt::AlignRight);
setText(Source_RSTFrames_Column, QString("%1").arg(m_rst_frames));
setTextAlignment(Source_RSTFrames_Column, Qt::AlignRight);
setText(Source_RSTBytes_Column, QString("%1").arg(m_rst_bytes));
setTextAlignment(Source_RSTBytes_Column, Qt::AlignRight);
setText(Source_RSTFramesBytes_Column, QString("%1/%2").arg(m_rst_frames).arg(m_rst_bytes));
setTextAlignment(Source_RSTFramesBytes_Column, Qt::AlignHCenter);
setText(Source_RSTRate_Column, format_rate(delta, m_rst_bytes));
setTextAlignment(Source_RSTRate_Column, Qt::AlignRight);
}
typedef QMap<QString, LBMLBTRUSourceEntry *> LBMLBTRUSourceMap;
typedef QMap<QString, LBMLBTRUSourceEntry *>::iterator LBMLBTRUSourceMapIterator;
// A receiver transport entry
class LBMLBTRUReceiverTransportEntry : public QTreeWidgetItem
{
friend class LBMLBTRUTransportDialog;
public:
LBMLBTRUReceiverTransportEntry(const QString & transport);
virtual ~LBMLBTRUReceiverTransportEntry(void);
void processPacket(const packet_info * pinfo, const lbm_lbtru_tap_info_t * tap_info);
private:
void fillItem(void);
QString m_transport;
guint64 m_nak_frames;
guint64 m_nak_count;
guint64 m_nak_bytes;
guint64 m_ack_frames;
guint64 m_ack_bytes;
guint64 m_creq_frames;
guint64 m_creq_bytes;
nstime_t m_first_frame_timestamp;
bool m_first_frame_timestamp_valid;
nstime_t m_last_frame_timestamp;
protected:
LBMLBTRUSQNMap m_nak_sqns;
LBMLBTRUSQNMap m_ack_sqns;
LBMLBTRUCREQRequestMap m_creq_requests;
};
LBMLBTRUReceiverTransportEntry::LBMLBTRUReceiverTransportEntry(const QString & transport) :
QTreeWidgetItem(),
m_transport(transport),
m_nak_frames(0),
m_nak_count(0),
m_nak_bytes(0),
m_ack_frames(0),
m_ack_bytes(0),
m_creq_frames(0),
m_creq_bytes(0),
m_first_frame_timestamp_valid(false),
m_nak_sqns(),
m_ack_sqns(),
m_creq_requests()
{
m_first_frame_timestamp.secs = 0;
m_first_frame_timestamp.nsecs = 0;
m_last_frame_timestamp.secs = 0;
m_last_frame_timestamp.nsecs = 0;
setText(Receiver_AddressTransport_Column, m_transport);
}
LBMLBTRUReceiverTransportEntry::~LBMLBTRUReceiverTransportEntry(void)
{
for (LBMLBTRUSQNMapIterator it = m_nak_sqns.begin(); it != m_nak_sqns.end(); ++it)
{
delete *it;
}
m_nak_sqns.clear();
for (LBMLBTRUSQNMapIterator it = m_ack_sqns.begin(); it != m_ack_sqns.end(); ++it)
{
delete *it;
}
m_ack_sqns.clear();
for (LBMLBTRUCREQRequestMapIterator it = m_creq_requests.begin(); it != m_creq_requests.end(); ++it)
{
delete *it;
}
m_creq_requests.clear();
}
void LBMLBTRUReceiverTransportEntry::processPacket(const packet_info * pinfo, const lbm_lbtru_tap_info_t * tap_info)
{
if (m_first_frame_timestamp_valid)
{
if (nstime_cmp(&(pinfo->abs_ts), &m_first_frame_timestamp) < 0)
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
}
}
else
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
m_first_frame_timestamp_valid = true;
}
if (nstime_cmp(&(pinfo->abs_ts), &m_last_frame_timestamp) > 0)
{
nstime_copy(&(m_last_frame_timestamp), &(pinfo->abs_ts));
}
switch (tap_info->type)
{
case LBTRU_PACKET_TYPE_NAK:
{
guint16 idx;
LBMLBTRUSQNEntry * sqn = NULL;
LBMLBTRUSQNMapIterator it;
m_nak_frames++;
m_nak_bytes += pinfo->fd->pkt_len;
m_nak_count += tap_info->num_sqns;
for (idx = 0; idx < tap_info->num_sqns; idx++)
{
it = m_nak_sqns.find(tap_info->sqns[idx]);
if (m_nak_sqns.end() == it)
{
sqn = new LBMLBTRUSQNEntry(tap_info->sqns[idx]);
m_nak_sqns.insert(tap_info->sqns[idx], sqn);
}
else
{
sqn = it.value();
}
sqn->processFrame(pinfo->num);
}
}
break;
case LBTRU_PACKET_TYPE_ACK:
{
LBMLBTRUSQNEntry * sqn = NULL;
LBMLBTRUSQNMapIterator it;
m_ack_frames++;
m_ack_bytes += pinfo->fd->pkt_len;
it = m_ack_sqns.find(tap_info->sqn);
if (m_ack_sqns.end() == it)
{
sqn = new LBMLBTRUSQNEntry(tap_info->sqn);
m_ack_sqns.insert(tap_info->sqn, sqn);
}
else
{
sqn = it.value();
}
sqn->processFrame(pinfo->num);
}
break;
case LBTRU_PACKET_TYPE_CREQ:
{
LBMLBTRUCREQRequestEntry * req = NULL;
LBMLBTRUCREQRequestMapIterator it;
m_creq_frames++;
m_creq_bytes += pinfo->fd->pkt_len;
it = m_creq_requests.find(tap_info->creq_type);
if (m_creq_requests.end() == it)
{
req = new LBMLBTRUCREQRequestEntry(tap_info->creq_type);
m_creq_requests.insert(tap_info->creq_type, req);
}
else
{
req = it.value();
}
req->processFrame(pinfo->num);
}
break;
default:
return;
break;
}
fillItem();
}
void LBMLBTRUReceiverTransportEntry::fillItem(void)
{
nstime_t delta;
nstime_delta(&delta, &m_last_frame_timestamp, &m_first_frame_timestamp);
setText(Receiver_NAKFrames_Column, QString("%1").arg(m_nak_frames));
setTextAlignment(Receiver_NAKFrames_Column, Qt::AlignRight);
setText(Receiver_NAKCount_Column, QString("%1").arg(m_nak_count));
setTextAlignment(Receiver_NAKCount_Column, Qt::AlignRight);
setText(Receiver_NAKBytes_Column, QString("%1").arg(m_nak_bytes));
setTextAlignment(Receiver_NAKBytes_Column, Qt::AlignRight);
setText(Receiver_NAKFramesCount_Column, QString("%1/%2").arg(m_nak_frames).arg(m_nak_count));
setTextAlignment(Receiver_NAKFramesCount_Column, Qt::AlignHCenter);
setText(Receiver_NAKCountBytes_Column, QString("%1/%2").arg(m_nak_count).arg(m_nak_bytes));
setTextAlignment(Receiver_NAKCountBytes_Column, Qt::AlignHCenter);
setText(Receiver_NAKFramesBytes_Column, QString("%1/%2").arg(m_nak_frames).arg(m_nak_bytes));
setTextAlignment(Receiver_NAKFramesBytes_Column, Qt::AlignHCenter);
setText(Receiver_NAKFramesCountBytes_Column, QString("%1/%2/%3").arg(m_nak_frames).arg(m_nak_count).arg(m_nak_bytes));
setTextAlignment(Receiver_NAKFramesCountBytes_Column, Qt::AlignHCenter);
setText(Receiver_NAKRate_Column, format_rate(delta, m_nak_bytes));
setTextAlignment(Receiver_NAKRate_Column, Qt::AlignRight);
setText(Receiver_ACKFrames_Column, QString("%1").arg(m_ack_frames));
setTextAlignment(Receiver_ACKFrames_Column, Qt::AlignRight);
setText(Receiver_ACKBytes_Column, QString("%1").arg(m_ack_bytes));
setTextAlignment(Receiver_ACKBytes_Column, Qt::AlignRight);
setText(Receiver_ACKFramesBytes_Column, QString("%1/%2").arg(m_ack_frames).arg(m_ack_bytes));
setTextAlignment(Receiver_ACKFramesBytes_Column, Qt::AlignHCenter);
setText(Receiver_ACKRate_Column, format_rate(delta, m_ack_bytes));
setTextAlignment(Receiver_ACKRate_Column, Qt::AlignRight);
setText(Receiver_CREQFrames_Column, QString("%1").arg(m_creq_frames));
setTextAlignment(Receiver_CREQFrames_Column, Qt::AlignRight);
setText(Receiver_CREQBytes_Column, QString("%1").arg(m_creq_bytes));
setTextAlignment(Receiver_CREQBytes_Column, Qt::AlignRight);
setText(Receiver_CREQFramesBytes_Column, QString("%1/%2").arg(m_creq_frames).arg(m_creq_bytes));
setTextAlignment(Receiver_CREQFramesBytes_Column, Qt::AlignHCenter);
setText(Receiver_CREQRate_Column, format_rate(delta, m_creq_bytes));
setTextAlignment(Receiver_CREQRate_Column, Qt::AlignRight);
}
typedef QMap<QString, LBMLBTRUReceiverTransportEntry *> LBMLBTRUReceiverTransportMap;
typedef QMap<QString, LBMLBTRUReceiverTransportEntry *>::iterator LBMLBTRUReceiverTransportMapIterator;
// A receiver (address) entry
class LBMLBTRUReceiverEntry : public QTreeWidgetItem
{
public:
LBMLBTRUReceiverEntry(const QString & receiver_address);
virtual ~LBMLBTRUReceiverEntry(void);
void processPacket(const packet_info * pinfo, const lbm_lbtru_tap_info_t * tap_info);
private:
void fillItem(void);
QString m_address;
QString m_transport;
guint64 m_nak_frames;
guint64 m_nak_count;
guint64 m_nak_bytes;
guint64 m_ack_frames;
guint64 m_ack_bytes;
guint64 m_creq_frames;
guint64 m_creq_bytes;
nstime_t m_first_frame_timestamp;
bool m_first_frame_timestamp_valid;
nstime_t m_last_frame_timestamp;
LBMLBTRUReceiverTransportMap m_transports;
};
LBMLBTRUReceiverEntry::LBMLBTRUReceiverEntry(const QString & receiver_address) :
QTreeWidgetItem(),
m_address(receiver_address),
m_nak_frames(0),
m_nak_count(0),
m_nak_bytes(0),
m_ack_frames(0),
m_ack_bytes(0),
m_creq_frames(0),
m_creq_bytes(0),
m_first_frame_timestamp_valid(false),
m_transports()
{
m_first_frame_timestamp.secs = 0;
m_first_frame_timestamp.nsecs = 0;
m_last_frame_timestamp.secs = 0;
m_last_frame_timestamp.nsecs = 0;
setText(Receiver_AddressTransport_Column, m_address);
}
LBMLBTRUReceiverEntry::~LBMLBTRUReceiverEntry(void)
{
for (LBMLBTRUReceiverTransportMapIterator it = m_transports.begin(); it != m_transports.end(); ++it)
{
delete *it;
}
m_transports.clear();
}
void LBMLBTRUReceiverEntry::processPacket(const packet_info * pinfo, const lbm_lbtru_tap_info_t * tap_info)
{
LBMLBTRUReceiverTransportEntry * transport = NULL;
LBMLBTRUReceiverTransportMapIterator it;
if (m_first_frame_timestamp_valid)
{
if (nstime_cmp(&(pinfo->abs_ts), &m_first_frame_timestamp) < 0)
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
}
}
else
{
nstime_copy(&(m_first_frame_timestamp), &(pinfo->abs_ts));
m_first_frame_timestamp_valid = true;
}
if (nstime_cmp(&(pinfo->abs_ts), &m_last_frame_timestamp) > 0)
{
nstime_copy(&(m_last_frame_timestamp), &(pinfo->abs_ts));
}
switch (tap_info->type)
{
case LBTRU_PACKET_TYPE_NAK:
m_nak_frames++;
m_nak_bytes += pinfo->fd->pkt_len;
m_nak_count += tap_info->num_sqns;
break;
case LBTRU_PACKET_TYPE_ACK:
m_ack_frames++;
m_ack_bytes += pinfo->fd->pkt_len;
break;
case LBTRU_PACKET_TYPE_CREQ:
m_creq_frames++;
m_creq_bytes += pinfo->fd->pkt_len;
break;
}
it = m_transports.find(tap_info->transport);
if (m_transports.end() == it)
{
transport = new LBMLBTRUReceiverTransportEntry(tap_info->transport);
m_transports.insert(tap_info->transport, transport);
addChild(transport);
sortChildren(Receiver_AddressTransport_Column, Qt::AscendingOrder);
}
else
{
transport = it.value();
}
fillItem();
transport->processPacket(pinfo, tap_info);
}
void LBMLBTRUReceiverEntry::fillItem(void)
{
nstime_t delta;
nstime_delta(&delta, &m_last_frame_timestamp, &m_first_frame_timestamp);
setText(Receiver_NAKFrames_Column, QString("%1").arg(m_nak_frames));
setTextAlignment(Receiver_NAKFrames_Column, Qt::AlignRight);
setText(Receiver_NAKCount_Column, QString("%1").arg(m_nak_count));
setTextAlignment(Receiver_NAKCount_Column, Qt::AlignRight);
setText(Receiver_NAKBytes_Column, QString("%1").arg(m_nak_bytes));
setTextAlignment(Receiver_NAKBytes_Column, Qt::AlignRight);
setText(Receiver_NAKFramesCount_Column, QString("%1/%2").arg(m_nak_frames).arg(m_nak_count));
setTextAlignment(Receiver_NAKFramesCount_Column, Qt::AlignHCenter);
setText(Receiver_NAKCountBytes_Column, QString("%1/%2").arg(m_nak_count).arg(m_nak_bytes));
setTextAlignment(Receiver_NAKCountBytes_Column, Qt::AlignHCenter);
setText(Receiver_NAKFramesBytes_Column, QString("%1/%2").arg(m_nak_frames).arg(m_nak_bytes));
setTextAlignment(Receiver_NAKFramesBytes_Column, Qt::AlignHCenter);
setText(Receiver_NAKFramesCountBytes_Column, QString("%1/%2/%3").arg(m_nak_frames).arg(m_nak_count).arg(m_nak_bytes));
setTextAlignment(Receiver_NAKFramesCountBytes_Column, Qt::AlignHCenter);
setText(Receiver_NAKRate_Column, format_rate(delta, m_nak_bytes));
setTextAlignment(Receiver_NAKRate_Column, Qt::AlignRight);
setText(Receiver_ACKFrames_Column, QString("%1").arg(m_ack_frames));
setTextAlignment(Receiver_ACKFrames_Column, Qt::AlignRight);
setText(Receiver_ACKBytes_Column, QString("%1").arg(m_ack_bytes));
setTextAlignment(Receiver_ACKBytes_Column, Qt::AlignRight);
setText(Receiver_ACKFramesBytes_Column, QString("%1/%2").arg(m_ack_frames).arg(m_ack_bytes));
setTextAlignment(Receiver_ACKFramesBytes_Column, Qt::AlignHCenter);
setText(Receiver_ACKRate_Column, format_rate(delta, m_ack_bytes));
setTextAlignment(Receiver_ACKRate_Column, Qt::AlignRight);
setText(Receiver_CREQFrames_Column, QString("%1").arg(m_creq_frames));
setTextAlignment(Receiver_CREQFrames_Column, Qt::AlignRight);
setText(Receiver_CREQBytes_Column, QString("%1").arg(m_creq_bytes));
setTextAlignment(Receiver_CREQBytes_Column, Qt::AlignRight);
setText(Receiver_CREQFramesBytes_Column, QString("%1/%2").arg(m_creq_frames).arg(m_creq_bytes));
setTextAlignment(Receiver_CREQFramesBytes_Column, Qt::AlignHCenter);
setText(Receiver_CREQRate_Column, format_rate(delta, m_creq_bytes));
setTextAlignment(Receiver_CREQRate_Column, Qt::AlignRight);
}
typedef QMap<QString, LBMLBTRUReceiverEntry *> LBMLBTRUReceiverMap;
typedef QMap<QString, LBMLBTRUReceiverEntry *>::iterator LBMLBTRUReceiverMapIterator;
class LBMLBTRUTransportDialogInfo
{
public:
LBMLBTRUTransportDialogInfo(void);
~LBMLBTRUTransportDialogInfo(void);
void setDialog(LBMLBTRUTransportDialog * dialog);
LBMLBTRUTransportDialog * getDialog(void);
void processPacket(const packet_info * pinfo, const lbm_lbtru_tap_info_t * tap_info);
void clearMaps(void);
private:
LBMLBTRUTransportDialog * m_dialog;
LBMLBTRUSourceMap m_sources;
LBMLBTRUReceiverMap m_receivers;
};
LBMLBTRUTransportDialogInfo::LBMLBTRUTransportDialogInfo(void) :
m_dialog(NULL),
m_sources(),
m_receivers()
{
}
LBMLBTRUTransportDialogInfo::~LBMLBTRUTransportDialogInfo(void)
{
clearMaps();
}
void LBMLBTRUTransportDialogInfo::setDialog(LBMLBTRUTransportDialog * dialog)
{
m_dialog = dialog;
}
LBMLBTRUTransportDialog * LBMLBTRUTransportDialogInfo::getDialog(void)
{
return (m_dialog);
}
void LBMLBTRUTransportDialogInfo::processPacket(const packet_info * pinfo, const lbm_lbtru_tap_info_t * tap_info)
{
switch (tap_info->type)
{
case LBTRU_PACKET_TYPE_DATA:
case LBTRU_PACKET_TYPE_SM:
case LBTRU_PACKET_TYPE_NCF:
case LBTRU_PACKET_TYPE_RST:
{
LBMLBTRUSourceEntry * source = NULL;
LBMLBTRUSourceMapIterator it;
QString src_address = address_to_qstring(&(pinfo->src));
it = m_sources.find(src_address);
if (m_sources.end() == it)
{
QTreeWidgetItem * parent = NULL;
Ui::LBMLBTRUTransportDialog * ui = NULL;
source = new LBMLBTRUSourceEntry(src_address);
it = m_sources.insert(src_address, source);
ui = m_dialog->getUI();
ui->sources_TreeWidget->addTopLevelItem(source);
parent = ui->sources_TreeWidget->invisibleRootItem();
parent->sortChildren(Source_AddressTransport_Column, Qt::AscendingOrder);
ui->sources_TreeWidget->resizeColumnToContents(Source_AddressTransport_Column);
}
else
{
source = it.value();
}
source->processPacket(pinfo, tap_info);
}
break;
case LBTRU_PACKET_TYPE_NAK:
case LBTRU_PACKET_TYPE_ACK:
case LBTRU_PACKET_TYPE_CREQ:
{
LBMLBTRUReceiverEntry * receiver = NULL;
LBMLBTRUReceiverMapIterator it;
QString src_address = address_to_qstring(&(pinfo->src));
it = m_receivers.find(src_address);
if (m_receivers.end() == it)
{
QTreeWidgetItem * parent = NULL;
Ui::LBMLBTRUTransportDialog * ui = NULL;
receiver = new LBMLBTRUReceiverEntry(src_address);
it = m_receivers.insert(src_address, receiver);
ui = m_dialog->getUI();
ui->receivers_TreeWidget->addTopLevelItem(receiver);
parent = ui->receivers_TreeWidget->invisibleRootItem();
parent->sortChildren(Receiver_AddressTransport_Column, Qt::AscendingOrder);
ui->receivers_TreeWidget->resizeColumnToContents(Receiver_AddressTransport_Column);
}
else
{
receiver = it.value();
}
receiver->processPacket(pinfo, tap_info);
}
break;
default:
break;
}
}
void LBMLBTRUTransportDialogInfo::clearMaps(void)
{
for (LBMLBTRUSourceMapIterator it = m_sources.begin(); it != m_sources.end(); ++it)
{
delete *it;
}
m_sources.clear();
for (LBMLBTRUReceiverMapIterator it = m_receivers.begin(); it != m_receivers.end(); ++it)
{
delete *it;
}
m_receivers.clear();
}
LBMLBTRUTransportDialog::LBMLBTRUTransportDialog(QWidget * parent, capture_file * cfile) :
QDialog(parent),
m_ui(new Ui::LBMLBTRUTransportDialog),
m_dialog_info(NULL),
m_capture_file(cfile),
m_current_source_transport(NULL),
m_current_receiver_transport(NULL),
m_source_context_menu(NULL),
m_source_header(NULL)
{
m_ui->setupUi(this);
m_dialog_info = new LBMLBTRUTransportDialogInfo();
m_ui->tabWidget->setCurrentIndex(0);
m_ui->sources_detail_ComboBox->setCurrentIndex(0);
m_ui->sources_detail_transport_Label->setText(QString(" "));
m_ui->sources_stackedWidget->setCurrentIndex(0);
m_ui->receivers_detail_ComboBox->setCurrentIndex(0);
m_ui->receivers_detail_transport_Label->setText(QString(" "));
m_ui->receivers_stackedWidget->setCurrentIndex(0);
// Setup the source context menu
m_source_header = m_ui->sources_TreeWidget->header();
m_source_context_menu = new QMenu(m_source_header);
m_source_context_menu->addAction(m_ui->action_SourceAutoResizeColumns);
connect(m_ui->action_SourceAutoResizeColumns, SIGNAL(triggered()), this, SLOT(actionSourceAutoResizeColumns_triggered()));
m_source_context_menu->addSeparator();
m_ui->action_SourceDataFrames->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceDataFrames);
connect(m_ui->action_SourceDataFrames, SIGNAL(triggered(bool)), this, SLOT(actionSourceDataFrames_triggered(bool)));
m_ui->action_SourceDataBytes->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceDataBytes);
connect(m_ui->action_SourceDataBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceDataBytes_triggered(bool)));
m_ui->action_SourceDataFramesBytes->setChecked(false);
m_source_context_menu->addAction(m_ui->action_SourceDataFramesBytes);
connect(m_ui->action_SourceDataFramesBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceDataFramesBytes_triggered(bool)));
m_ui->action_SourceDataRate->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceDataRate);
connect(m_ui->action_SourceDataRate, SIGNAL(triggered(bool)), this, SLOT(actionSourceDataRate_triggered(bool)));
m_ui->action_SourceRXDataFrames->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceRXDataFrames);
connect(m_ui->action_SourceRXDataFrames, SIGNAL(triggered(bool)), this, SLOT(actionSourceRXDataFrames_triggered(bool)));
m_ui->action_SourceRXDataBytes->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceRXDataBytes);
connect(m_ui->action_SourceRXDataBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceRXDataBytes_triggered(bool)));
m_ui->action_SourceRXDataFramesBytes->setChecked(false);
m_source_context_menu->addAction(m_ui->action_SourceRXDataFramesBytes);
connect(m_ui->action_SourceRXDataFramesBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceRXDataFramesBytes_triggered(bool)));
m_ui->action_SourceRXDataRate->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceRXDataRate);
connect(m_ui->action_SourceRXDataRate, SIGNAL(triggered(bool)), this, SLOT(actionSourceRXDataRate_triggered(bool)));
m_ui->action_SourceNCFFrames->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceNCFFrames);
connect(m_ui->action_SourceNCFFrames, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFFrames_triggered(bool)));
m_ui->action_SourceNCFCount->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceNCFCount);
connect(m_ui->action_SourceNCFCount, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFCount_triggered(bool)));
m_ui->action_SourceNCFBytes->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceNCFBytes);
connect(m_ui->action_SourceNCFBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFBytes_triggered(bool)));
m_ui->action_SourceNCFFramesBytes->setChecked(false);
m_source_context_menu->addAction(m_ui->action_SourceNCFFramesBytes);
connect(m_ui->action_SourceNCFFramesBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFFramesBytes_triggered(bool)));
m_ui->action_SourceNCFCountBytes->setChecked(false);
m_source_context_menu->addAction(m_ui->action_SourceNCFCountBytes);
connect(m_ui->action_SourceNCFCountBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFCountBytes_triggered(bool)));
m_ui->action_SourceNCFFramesCount->setChecked(false);
m_source_context_menu->addAction(m_ui->action_SourceNCFFramesCount);
connect(m_ui->action_SourceNCFFramesCount, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFFramesCount_triggered(bool)));
m_ui->action_SourceNCFFramesCountBytes->setChecked(false);
m_source_context_menu->addAction(m_ui->action_SourceNCFFramesCountBytes);
connect(m_ui->action_SourceNCFFramesCountBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFFramesCountBytes_triggered(bool)));
m_ui->action_SourceNCFRate->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceNCFRate);
connect(m_ui->action_SourceNCFRate, SIGNAL(triggered(bool)), this, SLOT(actionSourceNCFRate_triggered(bool)));
m_ui->action_SourceSMFrames->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceSMFrames);
connect(m_ui->action_SourceSMFrames, SIGNAL(triggered(bool)), this, SLOT(actionSourceSMFrames_triggered(bool)));
m_ui->action_SourceSMBytes->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceSMBytes);
connect(m_ui->action_SourceSMBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceSMBytes_triggered(bool)));
m_ui->action_SourceSMFramesBytes->setChecked(false);
m_source_context_menu->addAction(m_ui->action_SourceSMFramesBytes);
connect(m_ui->action_SourceSMFramesBytes, SIGNAL(triggered(bool)), this, SLOT(actionSourceSMFramesBytes_triggered(bool)));
m_ui->action_SourceSMRate->setChecked(true);
m_source_context_menu->addAction(m_ui->action_SourceSMRate);
connect(m_ui->action_SourceSMRate, SIGNAL(triggered(bool)), this, SLOT(actionSourceSMRate_triggered(bool)));
m_source_header->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_source_header, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(custom_source_context_menuRequested(const QPoint &)));
// Setup the receiver context menu
m_receiver_header = m_ui->receivers_TreeWidget->header();
m_receiver_context_menu = new QMenu(m_receiver_header);
m_receiver_context_menu->addAction(m_ui->action_ReceiverAutoResizeColumns);
connect(m_ui->action_ReceiverAutoResizeColumns, SIGNAL(triggered()), this, SLOT(actionReceiverAutoResizeColumns_triggered()));
m_receiver_context_menu->addSeparator();
m_ui->action_ReceiverNAKFrames->setChecked(true);
m_receiver_context_menu->addAction(m_ui->action_ReceiverNAKFrames);
connect(m_ui->action_ReceiverNAKFrames, SIGNAL(triggered(bool)), this, SLOT(actionReceiverNAKFrames_triggered(bool)));
m_ui->action_ReceiverNAKCount->setChecked(true);
m_receiver_context_menu->addAction(m_ui->action_ReceiverNAKCount);
connect(m_ui->action_ReceiverNAKCount, SIGNAL(triggered(bool)), this, SLOT(actionReceiverNAKCount_triggered(bool)));
m_ui->action_ReceiverNAKBytes->setChecked(true);
m_receiver_context_menu->addAction(m_ui->action_ReceiverNAKBytes);
connect(m_ui->action_ReceiverNAKBytes, SIGNAL(triggered(bool)), this, SLOT(actionReceiverNAKBytes_triggered(bool)));
m_ui->action_ReceiverNAKFramesBytes->setChecked(false);
m_receiver_context_menu->addAction(m_ui->action_ReceiverNAKFramesBytes);
connect(m_ui->action_ReceiverNAKFramesBytes, SIGNAL(triggered(bool)), this, SLOT(actionReceiverNAKFramesBytes_triggered(bool)));
m_ui->action_ReceiverNAKCountBytes->setChecked(false);
m_receiver_context_menu->addAction(m_ui->action_ReceiverNAKCountBytes);
connect(m_ui->action_ReceiverNAKCountBytes, SIGNAL(triggered(bool)), this, SLOT(actionReceiverNAKCountBytes_triggered(bool)));
m_ui->action_ReceiverNAKFramesCount->setChecked(false);
m_receiver_context_menu->addAction(m_ui->action_ReceiverNAKFramesCount);
connect(m_ui->action_ReceiverNAKFramesCount, SIGNAL(triggered(bool)), this, SLOT(actionReceiverNAKFramesCount_triggered(bool)));
m_ui->action_ReceiverNAKFramesCountBytes->setChecked(false);
m_receiver_context_menu->addAction(m_ui->action_ReceiverNAKFramesCountBytes);
connect(m_ui->action_ReceiverNAKFramesCountBytes, SIGNAL(triggered(bool)), this, SLOT(actionReceiverNAKFramesCountBytes_triggered(bool)));
m_ui->action_ReceiverNAKRate->setChecked(true);
m_receiver_context_menu->addAction(m_ui->action_ReceiverNAKRate);
connect(m_ui->action_ReceiverNAKRate, SIGNAL(triggered(bool)), this, SLOT(actionReceiverNAKRate_triggered(bool)));
m_ui->action_ReceiverACKFrames->setChecked(true);
m_receiver_context_menu->addAction(m_ui->action_ReceiverACKFrames);
connect(m_ui->action_ReceiverACKFrames, SIGNAL(triggered(bool)), this, SLOT(actionReceiverACKFrames_triggered(bool)));
m_ui->action_ReceiverACKBytes->setChecked(true);
m_receiver_context_menu->addAction(m_ui->action_ReceiverACKBytes);
connect(m_ui->action_ReceiverACKBytes, SIGNAL(triggered(bool)), this, SLOT(actionReceiverACKBytes_triggered(bool)));
m_ui->action_ReceiverACKFramesBytes->setChecked(false);
m_receiver_context_menu->addAction(m_ui->action_ReceiverACKFramesBytes);
connect(m_ui->action_ReceiverACKFramesBytes, SIGNAL(triggered(bool)), this, SLOT(actionReceiverACKFramesBytes_triggered(bool)));
m_ui->action_ReceiverACKRate->setChecked(true);
m_receiver_context_menu->addAction(m_ui->action_ReceiverACKRate);
connect(m_ui->action_ReceiverACKRate, SIGNAL(triggered(bool)), this, SLOT(actionReceiverACKRate_triggered(bool)));
m_ui->action_ReceiverCREQFrames->setChecked(true);
m_receiver_context_menu->addAction(m_ui->action_ReceiverCREQFrames);
connect(m_ui->action_ReceiverCREQFrames, SIGNAL(triggered(bool)), this, SLOT(actionReceiverCREQFrames_triggered(bool)));
m_ui->action_ReceiverCREQBytes->setChecked(true);
m_receiver_context_menu->addAction(m_ui->action_ReceiverCREQBytes);
connect(m_ui->action_ReceiverCREQBytes, SIGNAL(triggered(bool)), this, SLOT(actionReceiverCREQBytes_triggered(bool)));
m_ui->action_ReceiverCREQFramesBytes->setChecked(false);
m_receiver_context_menu->addAction(m_ui->action_ReceiverCREQFramesBytes);
connect(m_ui->action_ReceiverCREQFramesBytes, SIGNAL(triggered(bool)), this, SLOT(actionReceiverCREQFramesBytes_triggered(bool)));
m_ui->action_ReceiverCREQRate->setChecked(true);
m_receiver_context_menu->addAction(m_ui->action_ReceiverCREQRate);
connect(m_ui->action_ReceiverCREQRate, SIGNAL(triggered(bool)), this, SLOT(actionReceiverCREQRate_triggered(bool)));
m_receiver_header->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_receiver_header, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(custom_receiver_context_menuRequested(const QPoint &)));
// Setup the source tree widget header
m_ui->sources_TreeWidget->setColumnHidden(Source_DataFramesBytes_Column, true);
m_ui->sources_TreeWidget->setColumnHidden(Source_RXDataFramesBytes_Column, true);
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFramesBytes_Column, true);
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFCountBytes_Column, true);
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFramesCount_Column, true);
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFramesCountBytes_Column, true);
m_ui->sources_TreeWidget->setColumnHidden(Source_SMFramesBytes_Column, true);
m_ui->sources_TreeWidget->setColumnHidden(Source_RSTFramesBytes_Column, true);
// Setup the receiver tree widget header
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_NAKFramesBytes_Column, true);
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_NAKCountBytes_Column, true);
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_NAKFramesCount_Column, true);
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_NAKFramesCountBytes_Column, true);
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_ACKFramesBytes_Column, true);
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_CREQFramesBytes_Column, true);
setAttribute(Qt::WA_DeleteOnClose, true);
fillTree();
}
LBMLBTRUTransportDialog::~LBMLBTRUTransportDialog(void)
{
resetSourcesDetail();
resetSources();
resetReceiversDetail();
resetReceivers();
if (m_dialog_info != NULL)
{
delete m_dialog_info;
m_dialog_info = NULL;
}
delete m_source_context_menu;
m_source_context_menu = NULL;
delete m_ui;
m_ui = NULL;
m_capture_file = NULL;
}
void LBMLBTRUTransportDialog::setCaptureFile(capture_file * cfile)
{
if (cfile == NULL) // We only want to know when the file closes.
{
m_capture_file = NULL;
m_ui->displayFilterLineEdit->setEnabled(false);
m_ui->applyFilterButton->setEnabled(false);
}
}
void LBMLBTRUTransportDialog::resetSources(void)
{
while (m_ui->sources_TreeWidget->takeTopLevelItem(0) != NULL)
{}
}
void LBMLBTRUTransportDialog::resetReceivers(void)
{
while (m_ui->receivers_TreeWidget->takeTopLevelItem(0) != NULL)
{}
}
void LBMLBTRUTransportDialog::resetSourcesDetail(void)
{
while (m_ui->sources_detail_sqn_TreeWidget->takeTopLevelItem(0) != NULL)
{}
while (m_ui->sources_detail_ncf_sqn_TreeWidget->takeTopLevelItem(0) != NULL)
{}
while (m_ui->sources_detail_rst_TreeWidget->takeTopLevelItem(0) != NULL)
{}
m_ui->sources_detail_transport_Label->setText(QString(" "));
m_current_source_transport = NULL;
}
void LBMLBTRUTransportDialog::resetReceiversDetail(void)
{
while (m_ui->receivers_detail_sqn_TreeWidget->takeTopLevelItem(0) != NULL)
{}
while (m_ui->receivers_detail_reason_TreeWidget->takeTopLevelItem(0) != NULL)
{}
m_ui->receivers_detail_transport_Label->setText(QString(" "));
m_current_receiver_transport = NULL;
}
void LBMLBTRUTransportDialog::fillTree(void)
{
GString * error_string;
if (m_capture_file == NULL)
{
return;
}
m_dialog_info->setDialog(this);
error_string = register_tap_listener("lbm_lbtru",
(void *)m_dialog_info,
m_ui->displayFilterLineEdit->text().toUtf8().constData(),
TL_REQUIRES_COLUMNS,
resetTap,
tapPacket,
drawTreeItems,
NULL);
if (error_string)
{
QMessageBox::critical(this, tr("LBT-RU Statistics failed to attach to tap"),
error_string->str);
g_string_free(error_string, TRUE);
reject();
}
cf_retap_packets(m_capture_file);
drawTreeItems(&m_dialog_info);
remove_tap_listener((void *)m_dialog_info);
}
void LBMLBTRUTransportDialog::resetTap(void * tap_data)
{
LBMLBTRUTransportDialogInfo * info = (LBMLBTRUTransportDialogInfo *)tap_data;
LBMLBTRUTransportDialog * dialog = info->getDialog();
if (dialog == NULL)
{
return;
}
dialog->resetSourcesDetail();
dialog->resetSources();
dialog->resetReceiversDetail();
dialog->resetReceivers();
info->clearMaps();
}
tap_packet_status LBMLBTRUTransportDialog::tapPacket(void * tap_data, packet_info * pinfo, epan_dissect_t *, const void * tap_info, tap_flags_t)
{
if (pinfo->fd->passed_dfilter == 1)
{
const lbm_lbtru_tap_info_t * tapinfo = (const lbm_lbtru_tap_info_t *)tap_info;
LBMLBTRUTransportDialogInfo * info = (LBMLBTRUTransportDialogInfo *)tap_data;
info->processPacket(pinfo, tapinfo);
}
return (TAP_PACKET_REDRAW);
}
void LBMLBTRUTransportDialog::drawTreeItems(void *)
{
}
void LBMLBTRUTransportDialog::on_applyFilterButton_clicked(void)
{
fillTree();
}
void LBMLBTRUTransportDialog::sourcesDetailCurrentChanged(int index)
{
// Index 0: Data
// Index 1: RX data
// Index 2: NCF
// Index 3: SM
// Index 4: RST
switch (index)
{
case 0:
case 1:
case 3:
m_ui->sources_stackedWidget->setCurrentIndex(0);
break;
case 2:
m_ui->sources_stackedWidget->setCurrentIndex(2);
break;
case 4:
m_ui->sources_stackedWidget->setCurrentIndex(1);
break;
default:
return;
}
sourcesItemClicked(m_current_source_transport, 0);
}
void LBMLBTRUTransportDialog::sourcesItemClicked(QTreeWidgetItem * item, int)
{
LBMLBTRUSourceTransportEntry * transport = dynamic_cast<LBMLBTRUSourceTransportEntry *>(item);
resetSourcesDetail();
if (transport == NULL)
{
// Must be a source item, ignore it?
return;
}
m_current_source_transport = transport;
m_ui->sources_detail_transport_Label->setText(transport->m_transport);
int cur_idx = m_ui->sources_detail_ComboBox->currentIndex();
switch (cur_idx)
{
case 0:
loadSourceDataDetails(transport);
break;
case 1:
loadSourceRXDataDetails(transport);
break;
case 2:
loadSourceNCFDetails(transport);
break;
case 3:
loadSourceSMDetails(transport);
break;
case 4:
loadSourceRSTDetails(transport);
break;
default:
break;
}
}
void LBMLBTRUTransportDialog::loadSourceDataDetails(LBMLBTRUSourceTransportEntry * transport)
{
for (LBMLBTRUSQNMapIterator it = transport->m_data_sqns.begin(); it != transport->m_data_sqns.end(); ++it)
{
LBMLBTRUSQNEntry * sqn = it.value();
m_ui->sources_detail_sqn_TreeWidget->addTopLevelItem(sqn);
}
}
void LBMLBTRUTransportDialog::loadSourceRXDataDetails(LBMLBTRUSourceTransportEntry * transport)
{
for (LBMLBTRUSQNMapIterator it = transport->m_rx_data_sqns.begin(); it != transport->m_rx_data_sqns.end(); ++it)
{
LBMLBTRUSQNEntry * sqn = it.value();
m_ui->sources_detail_sqn_TreeWidget->addTopLevelItem(sqn);
}
}
void LBMLBTRUTransportDialog::loadSourceNCFDetails(LBMLBTRUSourceTransportEntry * transport)
{
for (LBMLBTRUNCFSQNMapIterator it = transport->m_ncf_sqns.begin(); it != transport->m_ncf_sqns.end(); ++it)
{
LBMLBTRUNCFSQNEntry * sqn = it.value();
m_ui->sources_detail_ncf_sqn_TreeWidget->addTopLevelItem(sqn);
}
}
void LBMLBTRUTransportDialog::loadSourceSMDetails(LBMLBTRUSourceTransportEntry * transport)
{
for (LBMLBTRUSQNMapIterator it = transport->m_sm_sqns.begin(); it != transport->m_sm_sqns.end(); ++it)
{
LBMLBTRUSQNEntry * sqn = it.value();
m_ui->sources_detail_sqn_TreeWidget->addTopLevelItem(sqn);
}
}
void LBMLBTRUTransportDialog::loadSourceRSTDetails(LBMLBTRUSourceTransportEntry * transport)
{
for (LBMLBTRURSTReasonMapIterator it = transport->m_rst_reasons.begin(); it != transport->m_rst_reasons.end(); ++it)
{
LBMLBTRURSTReasonEntry * reason = it.value();
m_ui->sources_detail_rst_TreeWidget->addTopLevelItem(reason);
}
}
void LBMLBTRUTransportDialog::sourcesDetailItemDoubleClicked(QTreeWidgetItem * item, int)
{
LBMLBTRUFrameEntry * frame = dynamic_cast<LBMLBTRUFrameEntry *>(item);
if (frame == NULL)
{
// Must have double-clicked on something other than an expanded frame entry
return;
}
emit goToPacket((int)frame->getFrame());
}
void LBMLBTRUTransportDialog::receiversDetailCurrentChanged(int index)
{
// Index 0: NAK
// Index 1: ACK
// Index 2: CREQ
switch (index)
{
case 0:
case 1:
m_ui->receivers_stackedWidget->setCurrentIndex(0);
break;
case 2:
m_ui->receivers_stackedWidget->setCurrentIndex(1);
break;
default:
return;
}
receiversItemClicked(m_current_receiver_transport, 0);
}
void LBMLBTRUTransportDialog::receiversItemClicked(QTreeWidgetItem * item, int)
{
LBMLBTRUReceiverTransportEntry * transport = dynamic_cast<LBMLBTRUReceiverTransportEntry *>(item);
resetReceiversDetail();
if (transport == NULL)
{
// Must be a receiver item, ignore it?
return;
}
m_current_receiver_transport = transport;
m_ui->receivers_detail_transport_Label->setText(transport->m_transport);
int cur_idx = m_ui->receivers_detail_ComboBox->currentIndex();
switch (cur_idx)
{
case 0:
loadReceiverNAKDetails(transport);
break;
case 1:
loadReceiverACKDetails(transport);
break;
case 2:
loadReceiverCREQDetails(transport);
break;
default:
break;
}
}
void LBMLBTRUTransportDialog::loadReceiverNAKDetails(LBMLBTRUReceiverTransportEntry * transport)
{
for (LBMLBTRUSQNMapIterator it = transport->m_nak_sqns.begin(); it != transport->m_nak_sqns.end(); ++it)
{
LBMLBTRUSQNEntry * sqn = it.value();
m_ui->receivers_detail_sqn_TreeWidget->addTopLevelItem(sqn);
}
}
void LBMLBTRUTransportDialog::loadReceiverACKDetails(LBMLBTRUReceiverTransportEntry * transport)
{
for (LBMLBTRUSQNMapIterator it = transport->m_ack_sqns.begin(); it != transport->m_ack_sqns.end(); ++it)
{
LBMLBTRUSQNEntry * sqn = it.value();
m_ui->receivers_detail_sqn_TreeWidget->addTopLevelItem(sqn);
}
}
void LBMLBTRUTransportDialog::loadReceiverCREQDetails(LBMLBTRUReceiverTransportEntry * transport)
{
for (LBMLBTRUCREQRequestMapIterator it = transport->m_creq_requests.begin(); it != transport->m_creq_requests.end(); ++it)
{
LBMLBTRUCREQRequestEntry * req = it.value();
m_ui->receivers_detail_reason_TreeWidget->addTopLevelItem(req);
}
}
void LBMLBTRUTransportDialog::receiversDetailItemDoubleClicked(QTreeWidgetItem * item, int)
{
LBMLBTRUFrameEntry * frame = dynamic_cast<LBMLBTRUFrameEntry *>(item);
if (frame == NULL)
{
// Must have double-clicked on something other than an expanded frame entry
return;
}
emit goToPacket((int)frame->getFrame());
}
void LBMLBTRUTransportDialog::custom_source_context_menuRequested(const QPoint & pos)
{
m_source_context_menu->popup(m_source_header->mapToGlobal(pos));
}
void LBMLBTRUTransportDialog::actionSourceDataFrames_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_DataFrames_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceDataBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_DataBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceDataFramesBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_DataFramesBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceDataRate_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_DataRate_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceRXDataFrames_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_RXDataFrames_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceRXDataBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_RXDataBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceRXDataFramesBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_RXDataFramesBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceRXDataRate_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_RXDataRate_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceNCFFrames_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFrames_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceNCFCount_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFCount_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceNCFBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFrames_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceNCFFramesBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFramesBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceNCFCountBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFCountBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceNCFFramesCount_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFramesCount_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceNCFFramesCountBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFFramesCountBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceNCFRate_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_NCFRate_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceSMFrames_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_SMFrames_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceSMBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_SMBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceSMFramesBytes_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_SMFramesBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceSMRate_triggered(bool checked)
{
m_ui->sources_TreeWidget->setColumnHidden(Source_SMRate_Column, !checked);
}
void LBMLBTRUTransportDialog::actionSourceAutoResizeColumns_triggered(void)
{
m_ui->sources_TreeWidget->resizeColumnToContents(Source_AddressTransport_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_DataFrames_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_DataBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_DataFramesBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_DataRate_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_RXDataFrames_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_RXDataBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_RXDataFramesBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_RXDataRate_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFFrames_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFCount_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFFramesBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFCountBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFFramesCount_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFFramesCountBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_NCFRate_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_SMFrames_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_SMBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_SMFramesBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_SMRate_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_RSTFrames_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_RSTBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_RSTFramesBytes_Column);
m_ui->sources_TreeWidget->resizeColumnToContents(Source_RSTRate_Column);
}
void LBMLBTRUTransportDialog::custom_receiver_context_menuRequested(const QPoint & pos)
{
m_receiver_context_menu->popup(m_receiver_header->mapToGlobal(pos));
}
void LBMLBTRUTransportDialog::actionReceiverNAKFrames_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_NAKFrames_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverNAKCount_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_NAKCount_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverNAKBytes_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_NAKBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverNAKFramesCount_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_NAKFramesCount_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverNAKCountBytes_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_NAKCountBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverNAKFramesBytes_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_NAKFramesBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverNAKFramesCountBytes_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_NAKFramesCountBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverNAKRate_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_NAKRate_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverACKFrames_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_ACKFrames_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverACKBytes_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_ACKBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverACKFramesBytes_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_ACKFramesBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverACKRate_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_ACKRate_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverCREQFrames_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_CREQFrames_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverCREQBytes_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_CREQBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverCREQFramesBytes_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_CREQFramesBytes_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverCREQRate_triggered(bool checked)
{
m_ui->receivers_TreeWidget->setColumnHidden(Receiver_CREQRate_Column, !checked);
}
void LBMLBTRUTransportDialog::actionReceiverAutoResizeColumns_triggered(void)
{
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_AddressTransport_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_NAKFrames_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_NAKCount_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_NAKBytes_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_NAKFramesBytes_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_NAKCountBytes_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_NAKFramesCount_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_NAKFramesCountBytes_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_NAKRate_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_ACKFrames_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_ACKBytes_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_ACKFramesBytes_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_ACKRate_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_CREQFrames_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_CREQBytes_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_CREQFramesBytes_Column);
m_ui->receivers_TreeWidget->resizeColumnToContents(Receiver_CREQRate_Column);
} |
C/C++ | wireshark/ui/qt/lbm_lbtru_transport_dialog.h | /** @file
*
* Copyright (c) 2005-2014 Informatica Corporation. All Rights Reserved.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef LBM_LBTRU_TRANSPORT_DIALOG_H
#define LBM_LBTRU_TRANSPORT_DIALOG_H
#include <config.h>
#include <glib.h>
#include "cfile.h"
#include <epan/packet_info.h>
#include <epan/tap.h>
#include <QDialog>
class QHeaderView;
class QMenu;
class QTreeWidgetItem;
namespace Ui
{
class LBMLBTRUTransportDialog;
}
class LBMLBTRUTransportDialogInfo;
class LBMLBTRUSourceTransportEntry;
class LBMLBTRUReceiverTransportEntry;
class LBMLBTRUTransportDialog : public QDialog
{
Q_OBJECT
public:
explicit LBMLBTRUTransportDialog(QWidget * parent = 0, capture_file * cfile = NULL);
Ui::LBMLBTRUTransportDialog * getUI(void)
{
return (m_ui);
}
public slots:
void setCaptureFile(capture_file * cfile);
signals:
void goToPacket(int packet_num);
private:
Ui::LBMLBTRUTransportDialog * m_ui;
LBMLBTRUTransportDialogInfo * m_dialog_info;
capture_file * m_capture_file;
LBMLBTRUSourceTransportEntry * m_current_source_transport;
LBMLBTRUReceiverTransportEntry * m_current_receiver_transport;
QMenu * m_source_context_menu;
QHeaderView * m_source_header;
QMenu * m_receiver_context_menu;
QHeaderView * m_receiver_header;
virtual ~LBMLBTRUTransportDialog(void);
void resetSources(void);
void resetReceivers(void);
void resetSourcesDetail(void);
void resetReceiversDetail(void);
void fillTree(void);
static void resetTap(void * tap_data);
static tap_packet_status tapPacket(void * tap_data, packet_info * pinfo, epan_dissect_t * edt, const void * stream_info, tap_flags_t flags);
static void drawTreeItems(void * tap_data);
void loadSourceDataDetails(LBMLBTRUSourceTransportEntry * transport);
void loadSourceRXDataDetails(LBMLBTRUSourceTransportEntry * transport);
void loadSourceNCFDetails(LBMLBTRUSourceTransportEntry * transport);
void loadSourceSMDetails(LBMLBTRUSourceTransportEntry * transport);
void loadSourceRSTDetails(LBMLBTRUSourceTransportEntry * transport);
void loadReceiverNAKDetails(LBMLBTRUReceiverTransportEntry * transport);
void loadReceiverACKDetails(LBMLBTRUReceiverTransportEntry * transport);
void loadReceiverCREQDetails(LBMLBTRUReceiverTransportEntry * transport);
private slots:
void on_applyFilterButton_clicked(void);
void sourcesDetailCurrentChanged(int index);
void sourcesItemClicked(QTreeWidgetItem * item, int column);
void sourcesDetailItemDoubleClicked(QTreeWidgetItem * item, int column);
void receiversDetailCurrentChanged(int index);
void receiversItemClicked(QTreeWidgetItem * item, int column);
void receiversDetailItemDoubleClicked(QTreeWidgetItem * item, int column);
void custom_source_context_menuRequested(const QPoint & pos);
void actionSourceDataFrames_triggered(bool checked);
void actionSourceDataBytes_triggered(bool checked);
void actionSourceDataFramesBytes_triggered(bool checked);
void actionSourceDataRate_triggered(bool checked);
void actionSourceRXDataFrames_triggered(bool checked);
void actionSourceRXDataBytes_triggered(bool checked);
void actionSourceRXDataFramesBytes_triggered(bool checked);
void actionSourceRXDataRate_triggered(bool checked);
void actionSourceNCFFrames_triggered(bool checked);
void actionSourceNCFCount_triggered(bool checked);
void actionSourceNCFBytes_triggered(bool checked);
void actionSourceNCFFramesBytes_triggered(bool checked);
void actionSourceNCFCountBytes_triggered(bool checked);
void actionSourceNCFFramesCount_triggered(bool checked);
void actionSourceNCFFramesCountBytes_triggered(bool checked);
void actionSourceNCFRate_triggered(bool checked);
void actionSourceSMFrames_triggered(bool checked);
void actionSourceSMBytes_triggered(bool checked);
void actionSourceSMFramesBytes_triggered(bool checked);
void actionSourceSMRate_triggered(bool checked);
void actionSourceAutoResizeColumns_triggered(void);
void custom_receiver_context_menuRequested(const QPoint & pos);
void actionReceiverNAKFrames_triggered(bool checked);
void actionReceiverNAKCount_triggered(bool checked);
void actionReceiverNAKBytes_triggered(bool checked);
void actionReceiverNAKFramesCount_triggered(bool checked);
void actionReceiverNAKCountBytes_triggered(bool checked);
void actionReceiverNAKFramesBytes_triggered(bool checked);
void actionReceiverNAKFramesCountBytes_triggered(bool checked);
void actionReceiverNAKRate_triggered(bool checked);
void actionReceiverACKFrames_triggered(bool checked);
void actionReceiverACKBytes_triggered(bool checked);
void actionReceiverACKFramesBytes_triggered(bool checked);
void actionReceiverACKRate_triggered(bool checked);
void actionReceiverCREQFrames_triggered(bool checked);
void actionReceiverCREQBytes_triggered(bool checked);
void actionReceiverCREQFramesBytes_triggered(bool checked);
void actionReceiverCREQRate_triggered(bool checked);
void actionReceiverAutoResizeColumns_triggered(void);
};
#endif |
User Interface | wireshark/ui/qt/lbm_lbtru_transport_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>LBMLBTRUTransportDialog</class>
<widget class="QDialog" name="LBMLBTRUTransportDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>872</width>
<height>667</height>
</rect>
</property>
<property name="windowTitle">
<string>LBT-RU Transport Statistics</string>
</property>
<property name="sizeGripEnabled">
<bool>true</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="sourcesTab">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<attribute name="title">
<string>Sources</string>
</attribute>
<layout class="QHBoxLayout" name="horizontalLayout_5">
<item>
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="handleWidth">
<number>10</number>
</property>
<widget class="QTreeWidget" name="sources_TreeWidget">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<attribute name="headerDefaultSectionSize">
<number>80</number>
</attribute>
<column>
<property name="text">
<string>Address/Transport/Client</string>
</property>
</column>
<column>
<property name="text">
<string>Data frames</string>
</property>
</column>
<column>
<property name="text">
<string>Data bytes</string>
</property>
</column>
<column>
<property name="text">
<string>Data frames/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>Data rate</string>
</property>
</column>
<column>
<property name="text">
<string>RX data frames</string>
</property>
</column>
<column>
<property name="text">
<string>RX data bytes</string>
</property>
</column>
<column>
<property name="text">
<string>RX data frames/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>RX data rate</string>
</property>
</column>
<column>
<property name="text">
<string>NCF frames</string>
</property>
</column>
<column>
<property name="text">
<string>NCF count</string>
</property>
</column>
<column>
<property name="text">
<string>NCF bytes</string>
</property>
</column>
<column>
<property name="text">
<string>NCF frames/count</string>
</property>
</column>
<column>
<property name="text">
<string>NCF frames/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>NCF count/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>NCF frames/count/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>NCF rate</string>
</property>
</column>
<column>
<property name="text">
<string>SM frames</string>
</property>
</column>
<column>
<property name="text">
<string>SM bytes</string>
</property>
</column>
<column>
<property name="text">
<string>SM frames/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>SM rate</string>
</property>
</column>
<column>
<property name="text">
<string>RST frames</string>
</property>
</column>
<column>
<property name="text">
<string>RST bytes</string>
</property>
</column>
<column>
<property name="text">
<string>RST frames/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>RST rate</string>
</property>
</column>
</widget>
<widget class="QWidget" name="layoutWidget">
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Show</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="sources_detail_ComboBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>120</width>
<height>0</height>
</size>
</property>
<item>
<property name="text">
<string>Data SQN</string>
</property>
</item>
<item>
<property name="text">
<string>RX Data SQN</string>
</property>
</item>
<item>
<property name="text">
<string>NCF SQN</string>
</property>
</item>
<item>
<property name="text">
<string>SM SQN</string>
</property>
</item>
<item>
<property name="text">
<string>RST reason</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>details for transport</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="sources_detail_transport_Label">
<property name="text">
<string>XXXXX:XXX.XXX.XXX.XXX:XXXXX:XXXXXXXX:XXX.XXX.XXX.XXX:XXXXX</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="QStackedWidget" name="sources_stackedWidget">
<property name="enabled">
<bool>true</bool>
</property>
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="lineWidth">
<number>1</number>
</property>
<property name="currentIndex">
<number>1</number>
</property>
<widget class="QWidget" name="sources_detail_sqn_page">
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QTreeWidget" name="sources_detail_sqn_TreeWidget">
<column>
<property name="text">
<string>SQN</string>
</property>
</column>
<column>
<property name="text">
<string>Count</string>
</property>
</column>
<column>
<property name="text">
<string>Frame</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="sources_detail_rst_page">
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<widget class="QTreeWidget" name="sources_detail_rst_TreeWidget">
<column>
<property name="text">
<string>Reason</string>
</property>
</column>
<column>
<property name="text">
<string>Count</string>
</property>
</column>
<column>
<property name="text">
<string>Frame</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="sources_detail_ncf_sqn_page">
<layout class="QHBoxLayout" name="horizontalLayout_6">
<item>
<widget class="QTreeWidget" name="sources_detail_ncf_sqn_TreeWidget">
<column>
<property name="text">
<string>SQN/Reason</string>
</property>
</column>
<column>
<property name="text">
<string>Count</string>
</property>
</column>
<column>
<property name="text">
<string>Frame</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="receiversTab">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<attribute name="title">
<string>Receivers</string>
</attribute>
<layout class="QHBoxLayout" name="horizontalLayout_9">
<item>
<widget class="QSplitter" name="splitter_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="handleWidth">
<number>10</number>
</property>
<widget class="QTreeWidget" name="receivers_TreeWidget">
<column>
<property name="text">
<string>Address/Transport</string>
</property>
</column>
<column>
<property name="text">
<string>NAK frames</string>
</property>
</column>
<column>
<property name="text">
<string>NAK count</string>
</property>
</column>
<column>
<property name="text">
<string>NAK bytes</string>
</property>
</column>
<column>
<property name="text">
<string>NAK frames/count</string>
</property>
</column>
<column>
<property name="text">
<string>NAK count/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>NAK frames/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>NAK frames/count/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>NAK rate</string>
</property>
</column>
<column>
<property name="text">
<string>ACK frames</string>
</property>
</column>
<column>
<property name="text">
<string>ACK bytes</string>
</property>
</column>
<column>
<property name="text">
<string>ACK frames/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>ACK rate</string>
</property>
</column>
<column>
<property name="text">
<string>CREQ frames</string>
</property>
</column>
<column>
<property name="text">
<string>CREQ bytes</string>
</property>
</column>
<column>
<property name="text">
<string>CREQ frames/bytes</string>
</property>
</column>
<column>
<property name="text">
<string>CREQ rate</string>
</property>
</column>
</widget>
<widget class="QWidget" name="layoutWidget_2">
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="label_4">
<property name="text">
<string>Show</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="receivers_detail_ComboBox">
<property name="minimumSize">
<size>
<width>130</width>
<height>0</height>
</size>
</property>
<item>
<property name="text">
<string>NAK SQN</string>
</property>
</item>
<item>
<property name="text">
<string>ACK SQN</string>
</property>
</item>
<item>
<property name="text">
<string>CREQ request</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QLabel" name="label_5">
<property name="text">
<string>details for transport</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="receivers_detail_transport_Label">
<property name="text">
<string>XXXXX:XXX.XXX.XXX.XXX:XXXXX:XXXXXXXX:XXX.XXX.XXX.XXX:XXXXX</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<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="QStackedWidget" name="receivers_stackedWidget">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<widget class="QWidget" name="receivers_detail_sqn_page">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_7">
<item>
<widget class="QTreeWidget" name="receivers_detail_sqn_TreeWidget">
<column>
<property name="text">
<string>SQN</string>
</property>
</column>
<column>
<property name="text">
<string>Count</string>
</property>
</column>
<column>
<property name="text">
<string>Frame</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="receivers_detail_reason_page">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_8">
<item>
<widget class="QTreeWidget" name="receivers_detail_reason_TreeWidget">
<column>
<property name="text">
<string>Reason</string>
</property>
</column>
<column>
<property name="text">
<string>Count</string>
</property>
</column>
<column>
<property name="text">
<string>Frame</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="topMargin">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Display filter:</string>
</property>
</widget>
</item>
<item>
<widget class="DisplayFilterEdit" name="displayFilterLineEdit"/>
</item>
<item>
<widget class="QPushButton" name="applyFilterButton">
<property name="toolTip">
<string>Regenerate statistics using this display filter</string>
</property>
<property name="text">
<string>Apply</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::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 the tree as CSV</string>
</property>
<property name="shortcut">
<string notr="true">Ctrl+C</string>
</property>
</action>
<action name="actionCopyAsYAML">
<property name="text">
<string>Copy as YAML</string>
</property>
<property name="toolTip">
<string>Copy the tree as YAML</string>
</property>
<property name="shortcut">
<string notr="true">Ctrl+Y</string>
</property>
</action>
<action name="action_SourceDataFrames">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>Data frames</string>
</property>
<property name="toolTip">
<string>Show the data frames column</string>
</property>
</action>
<action name="action_SourceDataBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>Data bytes</string>
</property>
<property name="toolTip">
<string>Show the data bytes column</string>
</property>
</action>
<action name="action_SourceDataFramesBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>Data frames/bytes</string>
</property>
<property name="toolTip">
<string>Show the data frames/bytes column</string>
</property>
</action>
<action name="action_SourceDataRate">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>Data rate</string>
</property>
<property name="toolTip">
<string>Show the data rate column</string>
</property>
</action>
<action name="action_SourceRXDataFrames">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>RX data frames</string>
</property>
<property name="toolTip">
<string>Show the RX data frames column</string>
</property>
</action>
<action name="action_SourceRXDataBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>RX data bytes</string>
</property>
<property name="toolTip">
<string>Show the RX data bytes column</string>
</property>
</action>
<action name="action_SourceRXDataFramesBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>RX data frames/bytes</string>
</property>
<property name="toolTip">
<string>Show the RX data frames/bytes column</string>
</property>
</action>
<action name="action_SourceRXDataRate">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>RX data rate</string>
</property>
<property name="toolTip">
<string>Show the RX data rate column</string>
</property>
</action>
<action name="action_SourceNCFFrames">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF frames</string>
</property>
<property name="toolTip">
<string>Show the NCF frames column</string>
</property>
</action>
<action name="action_SourceNCFCount">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF count</string>
</property>
<property name="toolTip">
<string>Show the NCF count column</string>
</property>
</action>
<action name="action_SourceNCFBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF bytes</string>
</property>
<property name="toolTip">
<string>Show the NCF bytes column</string>
</property>
</action>
<action name="action_SourceNCFFramesBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF frames/bytes</string>
</property>
<property name="toolTip">
<string>Show the NCF frames/bytes column</string>
</property>
</action>
<action name="action_SourceNCFCountBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF count/bytes</string>
</property>
<property name="toolTip">
<string>Show the NCF count/bytes column</string>
</property>
</action>
<action name="action_SourceNCFFramesCount">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF frames/count</string>
</property>
<property name="toolTip">
<string>Show the NCF frames/count column</string>
</property>
</action>
<action name="action_SourceNCFFramesCountBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF frames/count/bytes</string>
</property>
<property name="toolTip">
<string>Show the NCF frames/count/bytes column</string>
</property>
</action>
<action name="action_SourceSMFrames">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>SM frames</string>
</property>
<property name="toolTip">
<string>Show the SM frames column</string>
</property>
</action>
<action name="action_SourceSMBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>SM bytes</string>
</property>
<property name="toolTip">
<string>Show the SM bytes column</string>
</property>
</action>
<action name="action_SourceSMFramesBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>SM frames/bytes</string>
</property>
<property name="toolTip">
<string>Show the SM frames/bytes column</string>
</property>
</action>
<action name="action_SourceSMRate">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>SM rate</string>
</property>
<property name="toolTip">
<string>Show the SM rate column</string>
</property>
</action>
<action name="action_SourceRSTFrames">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>RST frames</string>
</property>
<property name="toolTip">
<string>Show the RST frames column</string>
</property>
</action>
<action name="action_SourceRSTBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>RST bytes</string>
</property>
<property name="toolTip">
<string>Show the RST bytes column</string>
</property>
</action>
<action name="action_SourceRSTFramesBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>RST frames/bytes</string>
</property>
<property name="toolTip">
<string>Show the RST frames/bytes column</string>
</property>
</action>
<action name="action_SourceRSTRate">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>RST rate</string>
</property>
<property name="toolTip">
<string>Show the RST rate column</string>
</property>
</action>
<action name="action_ReceiverNAKFrames">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NAK frames</string>
</property>
<property name="toolTip">
<string>Show the NAK frames column</string>
</property>
</action>
<action name="action_ReceiverNAKCount">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NAK count</string>
</property>
<property name="toolTip">
<string>Show the NAK count column</string>
</property>
</action>
<action name="action_ReceiverNAKBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NAK bytes</string>
</property>
<property name="toolTip">
<string>Show the NAK bytes column</string>
</property>
</action>
<action name="action_ReceiverNAKFramesCount">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NAK frames/count</string>
</property>
<property name="toolTip">
<string>Show the NAK frames/count column</string>
</property>
</action>
<action name="action_ReceiverNAKCountBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NAK count/bytes</string>
</property>
<property name="toolTip">
<string>Show the NAK count/bytes column</string>
</property>
</action>
<action name="action_ReceiverNAKFramesBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NAK frames/bytes</string>
</property>
<property name="toolTip">
<string>Show the NAK frames/bytes column</string>
</property>
</action>
<action name="action_ReceiverNAKFramesCountBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NAK frames/count/bytes</string>
</property>
<property name="toolTip">
<string>Show the NAK frames/count/bytes column</string>
</property>
</action>
<action name="action_ReceiverNAKRate">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NAK rate</string>
</property>
<property name="toolTip">
<string>Show the NAK rate column</string>
</property>
</action>
<action name="action_ReceiverACKFrames">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>ACK frames</string>
</property>
<property name="toolTip">
<string>Show the ACK frames column</string>
</property>
</action>
<action name="action_ReceiverACKBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>ACK bytes</string>
</property>
<property name="toolTip">
<string>Show the ACK bytes column</string>
</property>
</action>
<action name="action_ReceiverACKFramesBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>ACK frames/bytes</string>
</property>
<property name="toolTip">
<string>Show the ACK frames/bytes column</string>
</property>
</action>
<action name="action_ReceiverACKRate">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>ACK rate</string>
</property>
<property name="toolTip">
<string>Show the ACK rate column</string>
</property>
</action>
<action name="action_ReceiverCREQFrames">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>CREQ frames</string>
</property>
<property name="toolTip">
<string>Show the CREQ frames column</string>
</property>
</action>
<action name="action_ReceiverCREQBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>CREQ bytes</string>
</property>
<property name="toolTip">
<string>Show the CREQ bytes column</string>
</property>
</action>
<action name="action_ReceiverCREQFramesBytes">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>CREQ frames/bytes</string>
</property>
<property name="toolTip">
<string>Show the CREQ frames/bytes column</string>
</property>
</action>
<action name="action_ReceiverCREQRate">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>CREQ rate</string>
</property>
<property name="toolTip">
<string>Show the CREQ rate column</string>
</property>
</action>
<action name="action_SourceAutoResizeColumns">
<property name="text">
<string>Auto-resize columns to content</string>
</property>
<property name="toolTip">
<string>Resize columns to content size</string>
</property>
</action>
<action name="action_ReceiverAutoResizeColumns">
<property name="text">
<string>Auto-resize columns to content</string>
</property>
<property name="toolTip">
<string>Resize columns to content size</string>
</property>
</action>
<action name="action_SourceNCFRate">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>NCF rate</string>
</property>
<property name="toolTip">
<string>Show the NCF rate column</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>DisplayFilterEdit</class>
<extends>QLineEdit</extends>
<header>widgets/display_filter_edit.h</header>
</customwidget>
</customwidgets>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>LBMLBTRUTransportDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>262</x>
<y>659</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>LBMLBTRUTransportDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>330</x>
<y>659</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>sources_detail_ComboBox</sender>
<signal>currentIndexChanged(int)</signal>
<receiver>LBMLBTRUTransportDialog</receiver>
<slot>sourcesDetailCurrentChanged(int)</slot>
<hints>
<hint type="sourcelabel">
<x>175</x>
<y>315</y>
</hint>
<hint type="destinationlabel">
<x>446</x>
<y>310</y>
</hint>
</hints>
</connection>
<connection>
<sender>sources_TreeWidget</sender>
<signal>itemClicked(QTreeWidgetItem*,int)</signal>
<receiver>LBMLBTRUTransportDialog</receiver>
<slot>sourcesItemClicked(QTreeWidgetItem*,int)</slot>
<hints>
<hint type="sourcelabel">
<x>440</x>
<y>149</y>
</hint>
<hint type="destinationlabel">
<x>446</x>
<y>310</y>
</hint>
</hints>
</connection>
<connection>
<sender>sources_detail_sqn_TreeWidget</sender>
<signal>itemDoubleClicked(QTreeWidgetItem*,int)</signal>
<receiver>LBMLBTRUTransportDialog</receiver>
<slot>sourcesDetailItemDoubleClicked(QTreeWidgetItem*,int)</slot>
<hints>
<hint type="sourcelabel">
<x>109</x>
<y>344</y>
</hint>
<hint type="destinationlabel">
<x>420</x>
<y>281</y>
</hint>
</hints>
</connection>
<connection>
<sender>sources_detail_ncf_sqn_TreeWidget</sender>
<signal>itemDoubleClicked(QTreeWidgetItem*,int)</signal>
<receiver>LBMLBTRUTransportDialog</receiver>
<slot>sourcesDetailItemDoubleClicked(QTreeWidgetItem*,int)</slot>
<hints>
<hint type="sourcelabel">
<x>83</x>
<y>344</y>
</hint>
<hint type="destinationlabel">
<x>420</x>
<y>281</y>
</hint>
</hints>
</connection>
<connection>
<sender>receivers_TreeWidget</sender>
<signal>itemClicked(QTreeWidgetItem*,int)</signal>
<receiver>LBMLBTRUTransportDialog</receiver>
<slot>receiversItemClicked(QTreeWidgetItem*,int)</slot>
<hints>
<hint type="sourcelabel">
<x>420</x>
<y>141</y>
</hint>
<hint type="destinationlabel">
<x>420</x>
<y>281</y>
</hint>
</hints>
</connection>
<connection>
<sender>receivers_detail_ComboBox</sender>
<signal>currentIndexChanged(int)</signal>
<receiver>LBMLBTRUTransportDialog</receiver>
<slot>receiversDetailCurrentChanged(int)</slot>
<hints>
<hint type="sourcelabel">
<x>124</x>
<y>315</y>
</hint>
<hint type="destinationlabel">
<x>155</x>
<y>-8</y>
</hint>
</hints>
</connection>
<connection>
<sender>receivers_detail_sqn_TreeWidget</sender>
<signal>itemDoubleClicked(QTreeWidgetItem*,int)</signal>
<receiver>LBMLBTRUTransportDialog</receiver>
<slot>receiversDetailItemDoubleClicked(QTreeWidgetItem*,int)</slot>
<hints>
<hint type="sourcelabel">
<x>435</x>
<y>452</y>
</hint>
<hint type="destinationlabel">
<x>435</x>
<y>333</y>
</hint>
</hints>
</connection>
<connection>
<sender>receivers_detail_reason_TreeWidget</sender>
<signal>itemDoubleClicked(QTreeWidgetItem*,int)</signal>
<receiver>LBMLBTRUTransportDialog</receiver>
<slot>receiversDetailItemDoubleClicked(QTreeWidgetItem*,int)</slot>
<hints>
<hint type="sourcelabel">
<x>66</x>
<y>336</y>
</hint>
<hint type="destinationlabel">
<x>435</x>
<y>333</y>
</hint>
</hints>
</connection>
</connections>
<slots>
<signal>goToPacket(int)</signal>
<slot>sourcesDetailCurrentChanged(int)</slot>
<slot>sourcesItemClicked(QTreeWidgetItem*,int)</slot>
<slot>receiversItemClicked(QTreeWidgetItem*,int)</slot>
<slot>sourcesDetailItemDoubleClicked(QTreeWidgetItem*,int)</slot>
<slot>receiversDetailItemDoubleClicked(QTreeWidgetItem*,int)</slot>
<slot>receiversDetailCurrentChanged(int)</slot>
</slots>
</ui> |
C++ | wireshark/ui/qt/lbm_stream_dialog.cpp | /* lbm_stream_dialog.cpp
*
* Copyright (c) 2005-2014 Informatica Corporation. All Rights Reserved.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
// Adapted from stats_tree_packet.cpp
#include "lbm_stream_dialog.h"
#include <ui_lbm_stream_dialog.h>
#include "file.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
#include <QClipboard>
#include <QMessageBox>
#include <QTreeWidget>
#include <QTreeWidgetItemIterator>
#include <epan/packet_info.h>
#include <epan/to_str.h>
#include <epan/tap.h>
#include <epan/dissectors/packet-lbm.h>
#include <QDebug>
namespace
{
static const int Stream_Column = 0;
static const int EndpointA_Column = 1;
static const int EndpointB_Column = 2;
static const int Messages_Column = 3;
static const int Bytes_Column = 4;
static const int FirstFrame_Column = 5;
static const int LastFrame_Column = 6;
}
class LBMSubstreamEntry
{
public:
LBMSubstreamEntry(guint64 channel, guint32 substream_id, const address * source_address, guint16 source_port, const address * destination_address, guint16 destination_port);
~LBMSubstreamEntry(void);
void processPacket(guint32 frame, guint32 bytes);
void setItem(QTreeWidgetItem * item);
QTreeWidgetItem * getItem(void)
{
return (m_item);
}
private:
void fillItem(gboolean update_only = TRUE);
guint64 m_channel;
guint32 m_substream_id;
QString m_endpoint_a;
QString m_endpoint_b;
guint32 m_first_frame;
guint32 m_flast_frame;
guint32 m_messages;
guint32 m_bytes;
QTreeWidgetItem * m_item;
};
LBMSubstreamEntry::LBMSubstreamEntry(guint64 channel, guint32 substream_id, const address * source_address, guint16 source_port, const address * destination_address, guint16 destination_port) :
m_channel(channel),
m_substream_id(substream_id),
m_first_frame((guint32)(~0)),
m_flast_frame(0),
m_messages(0),
m_bytes(0),
m_item(NULL)
{
m_endpoint_a = QString("%1:%2")
.arg(address_to_qstring(source_address))
.arg(source_port);
m_endpoint_b = QString("%1:%2")
.arg(address_to_qstring(destination_address))
.arg(destination_port);
}
LBMSubstreamEntry::~LBMSubstreamEntry(void)
{
}
void LBMSubstreamEntry::processPacket(guint32 frame, guint32 bytes)
{
if (m_first_frame > frame)
{
m_first_frame = frame;
}
if (m_flast_frame < frame)
{
m_flast_frame = frame;
}
m_bytes += bytes;
m_messages++;
fillItem();
}
void LBMSubstreamEntry::setItem(QTreeWidgetItem * item)
{
m_item = item;
fillItem(FALSE);
}
void LBMSubstreamEntry::fillItem(gboolean update_only)
{
if (update_only == FALSE)
{
m_item->setText(Stream_Column, QString("%1.%2").arg(m_channel).arg(m_substream_id));
m_item->setText(EndpointA_Column, m_endpoint_a);
m_item->setText(EndpointB_Column, m_endpoint_b);
}
m_item->setText(Messages_Column, QString("%1").arg(m_messages));
m_item->setText(Bytes_Column, QString("%1").arg(m_bytes));
m_item->setText(FirstFrame_Column, QString("%1").arg(m_first_frame));
m_item->setText(LastFrame_Column, QString("%1").arg(m_flast_frame));
}
typedef QMap<guint32, LBMSubstreamEntry *> LBMSubstreamMap;
typedef QMap<guint32, LBMSubstreamEntry *>::iterator LBMSubstreamMapIterator;
class LBMStreamEntry
{
public:
LBMStreamEntry(const packet_info * pinfo, guint64 channel, const lbm_uim_stream_endpoint_t * endpoint_a, const lbm_uim_stream_endpoint_t * endpoint_b);
~LBMStreamEntry(void);
void processPacket(const packet_info * pinfo, const lbm_uim_stream_tap_info_t * stream_info);
void setItem(QTreeWidgetItem * item);
QTreeWidgetItem * getItem(void)
{
return (m_item);
}
private:
void fillItem(gboolean update_only = TRUE);
QString formatEndpoint(const packet_info * pinfo, const lbm_uim_stream_endpoint_t * endpoint);
guint64 m_channel;
QString m_endpoint_a;
QString m_endpoint_b;
guint32 m_first_frame;
guint32 m_flast_frame;
guint32 m_messages;
guint32 m_bytes;
QTreeWidgetItem * m_item;
LBMSubstreamMap m_substreams;
};
LBMStreamEntry::LBMStreamEntry(const packet_info * pinfo, guint64 channel, const lbm_uim_stream_endpoint_t * endpoint_a, const lbm_uim_stream_endpoint_t * endpoint_b) :
m_channel(channel),
m_first_frame((guint32)(~0)),
m_flast_frame(0),
m_messages(0),
m_bytes(0),
m_item(NULL),
m_substreams()
{
m_endpoint_a = formatEndpoint(pinfo, endpoint_a);
m_endpoint_b = formatEndpoint(pinfo, endpoint_b);
}
LBMStreamEntry::~LBMStreamEntry(void)
{
LBMSubstreamMapIterator it;
for (it = m_substreams.begin(); it != m_substreams.end(); ++it)
{
delete *it;
}
m_substreams.clear();
}
QString LBMStreamEntry::formatEndpoint(const packet_info * pinfo, const lbm_uim_stream_endpoint_t * endpoint)
{
if (endpoint->type == lbm_uim_instance_stream)
{
return QString(bytes_to_str(pinfo->pool, endpoint->stream_info.ctxinst.ctxinst, sizeof(endpoint->stream_info.ctxinst.ctxinst)));
}
else
{
return QString("%1:%2:%3")
.arg(endpoint->stream_info.dest.domain)
.arg(address_to_str(pinfo->pool, &(endpoint->stream_info.dest.addr)))
.arg(endpoint->stream_info.dest.port);
}
}
void LBMStreamEntry::processPacket(const packet_info * pinfo, const lbm_uim_stream_tap_info_t * stream_info)
{
LBMSubstreamEntry * substream = NULL;
LBMSubstreamMapIterator it;
if (m_first_frame > pinfo->num)
{
m_first_frame = pinfo->num;
}
if (m_flast_frame < pinfo->num)
{
m_flast_frame = pinfo->num;
}
m_bytes += stream_info->bytes;
m_messages++;
it = m_substreams.find(stream_info->substream_id);
if (m_substreams.end() == it)
{
QTreeWidgetItem * item = NULL;
substream = new LBMSubstreamEntry(m_channel, stream_info->substream_id, &(pinfo->src), pinfo->srcport, &(pinfo->dst), pinfo->destport);
m_substreams.insert(stream_info->substream_id, substream);
item = new QTreeWidgetItem();
substream->setItem(item);
m_item->addChild(item);
m_item->sortChildren(Stream_Column, Qt::AscendingOrder);
}
else
{
substream = it.value();
}
fillItem();
substream->processPacket(pinfo->num, stream_info->bytes);
}
void LBMStreamEntry::setItem(QTreeWidgetItem * item)
{
m_item = item;
fillItem(FALSE);
}
void LBMStreamEntry::fillItem(gboolean update_only)
{
if (update_only == FALSE)
{
m_item->setData(Stream_Column, Qt::DisplayRole, QVariant((qulonglong)m_channel));
m_item->setText(EndpointA_Column, m_endpoint_a);
m_item->setText(EndpointB_Column, m_endpoint_b);
}
m_item->setText(Messages_Column, QString("%1").arg(m_messages));
m_item->setText(Bytes_Column, QString("%1").arg(m_bytes));
m_item->setText(FirstFrame_Column, QString("%1").arg(m_first_frame));
m_item->setText(LastFrame_Column, QString("%1").arg(m_flast_frame));
}
typedef QMap<guint64, LBMStreamEntry *> LBMStreamMap;
typedef QMap<guint64, LBMStreamEntry *>::iterator LBMStreamMapIterator;
class LBMStreamDialogInfo
{
public:
LBMStreamDialogInfo(void);
~LBMStreamDialogInfo(void);
void setDialog(LBMStreamDialog * dialog);
LBMStreamDialog * getDialog(void);
void processPacket(const packet_info * pinfo, const lbm_uim_stream_tap_info_t * stream_info);
void resetStreams(void);
private:
LBMStreamDialog * m_dialog;
LBMStreamMap m_streams;
};
LBMStreamDialogInfo::LBMStreamDialogInfo(void) :
m_dialog(NULL),
m_streams()
{
}
LBMStreamDialogInfo::~LBMStreamDialogInfo(void)
{
resetStreams();
}
void LBMStreamDialogInfo::setDialog(LBMStreamDialog * dialog)
{
m_dialog = dialog;
}
LBMStreamDialog * LBMStreamDialogInfo::getDialog(void)
{
return (m_dialog);
}
void LBMStreamDialogInfo::processPacket(const packet_info * pinfo, const lbm_uim_stream_tap_info_t * stream_info)
{
LBMStreamEntry * stream = NULL;
LBMStreamMapIterator it;
it = m_streams.find(stream_info->channel);
if (m_streams.end() == it)
{
QTreeWidgetItem * item = NULL;
QTreeWidgetItem * parent = NULL;
Ui::LBMStreamDialog * ui = NULL;
stream = new LBMStreamEntry(pinfo, stream_info->channel, &(stream_info->endpoint_a), &(stream_info->endpoint_b));
it = m_streams.insert(stream_info->channel, stream);
item = new QTreeWidgetItem();
stream->setItem(item);
ui = m_dialog->getUI();
ui->lbm_stream_TreeWidget->addTopLevelItem(item);
parent = ui->lbm_stream_TreeWidget->invisibleRootItem();
parent->sortChildren(Stream_Column, Qt::AscendingOrder);
}
else
{
stream = it.value();
}
stream->processPacket(pinfo, stream_info);
}
void LBMStreamDialogInfo::resetStreams(void)
{
LBMStreamMapIterator it = m_streams.begin();
while (it != m_streams.end())
{
delete *it;
++it;
}
m_streams.clear();
}
LBMStreamDialog::LBMStreamDialog(QWidget * parent, capture_file * cfile) :
QDialog(parent),
m_ui(new Ui::LBMStreamDialog),
m_dialog_info(NULL),
m_capture_file(cfile)
{
m_ui->setupUi(this);
m_dialog_info = new LBMStreamDialogInfo();
setAttribute(Qt::WA_DeleteOnClose, true);
fillTree();
}
LBMStreamDialog::~LBMStreamDialog(void)
{
delete m_ui;
if (m_dialog_info != NULL)
{
delete m_dialog_info;
}
}
void LBMStreamDialog::setCaptureFile(capture_file * cfile)
{
if (cfile == NULL) // We only want to know when the file closes.
{
m_capture_file = NULL;
m_ui->displayFilterLineEdit->setEnabled(false);
m_ui->applyFilterButton->setEnabled(false);
}
}
void LBMStreamDialog::fillTree(void)
{
GString * error_string;
if (m_capture_file == NULL)
{
return;
}
m_dialog_info->setDialog(this);
error_string = register_tap_listener("lbm_stream",
(void *)m_dialog_info,
m_ui->displayFilterLineEdit->text().toUtf8().constData(),
TL_REQUIRES_COLUMNS,
resetTap,
tapPacket,
drawTreeItems,
NULL);
if (error_string)
{
QMessageBox::critical(this, tr("LBM Stream failed to attach to tap"),
error_string->str);
g_string_free(error_string, TRUE);
reject();
}
cf_retap_packets(m_capture_file);
drawTreeItems(&m_dialog_info);
remove_tap_listener((void *)m_dialog_info);
}
void LBMStreamDialog::resetTap(void * tap_data)
{
LBMStreamDialogInfo * info = (LBMStreamDialogInfo *)tap_data;
LBMStreamDialog * dialog = info->getDialog();
if (dialog == NULL)
{
return;
}
info->resetStreams();
dialog->m_ui->lbm_stream_TreeWidget->clear();
}
tap_packet_status LBMStreamDialog::tapPacket(void * tap_data, packet_info * pinfo, epan_dissect_t *, const void * stream_info, tap_flags_t)
{
if (pinfo->fd->passed_dfilter == 1)
{
const lbm_uim_stream_tap_info_t * tapinfo = (const lbm_uim_stream_tap_info_t *)stream_info;
LBMStreamDialogInfo * info = (LBMStreamDialogInfo *)tap_data;
info->processPacket(pinfo, tapinfo);
}
return (TAP_PACKET_REDRAW);
}
void LBMStreamDialog::drawTreeItems(void *)
{
}
void LBMStreamDialog::on_applyFilterButton_clicked(void)
{
fillTree();
} |
C/C++ | wireshark/ui/qt/lbm_stream_dialog.h | /** @file
*
* Copyright (c) 2005-2014 Informatica Corporation. All Rights Reserved.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef LBM_STREAM_DIALOG_H
#define LBM_STREAM_DIALOG_H
#include <config.h>
#include <glib.h>
#include "cfile.h"
#include <epan/packet_info.h>
#include <epan/tap.h>
#include <QDialog>
namespace Ui
{
class LBMStreamDialog;
}
class LBMStreamDialogInfo;
class LBMStreamDialog : public QDialog
{
Q_OBJECT
public:
explicit LBMStreamDialog(QWidget * parent = 0, capture_file * cfile = NULL);
~LBMStreamDialog(void);
Ui::LBMStreamDialog * getUI(void)
{
return (m_ui);
}
public slots:
void setCaptureFile(capture_file * cfile);
private:
Ui::LBMStreamDialog * m_ui;
LBMStreamDialogInfo * m_dialog_info;
capture_file * m_capture_file;
void fillTree(void);
static void resetTap(void * tap_data);
static tap_packet_status tapPacket(void * tap_data, packet_info * pinfo, epan_dissect_t * edt, const void * stream_info, tap_flags_t flags);
static void drawTreeItems(void * tap_data);
private slots:
void on_applyFilterButton_clicked(void);
};
#endif |
User Interface | wireshark/ui/qt/lbm_stream_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>LBMStreamDialog</class>
<widget class="QDialog" name="LBMStreamDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>652</width>
<height>459</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTreeWidget" name="lbm_stream_TreeWidget">
<column>
<property name="text">
<string>Stream</string>
</property>
</column>
<column>
<property name="text">
<string>Endpoint A</string>
</property>
</column>
<column>
<property name="text">
<string>Endpoint B</string>
</property>
</column>
<column>
<property name="text">
<string>Messages</string>
</property>
<property name="textAlignment">
<set>AlignLeft|AlignVCenter</set>
</property>
</column>
<column>
<property name="text">
<string>Bytes</string>
</property>
</column>
<column>
<property name="text">
<string>First Frame</string>
</property>
</column>
<column>
<property name="text">
<string>Last Frame</string>
</property>
</column>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Display filter:</string>
</property>
</widget>
</item>
<item>
<widget class="DisplayFilterEdit" name="displayFilterLineEdit"/>
</item>
<item>
<widget class="QPushButton" name="applyFilterButton">
<property name="toolTip">
<string>Regenerate statistics using this display filter</string>
</property>
<property name="text">
<string>Apply</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::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 the tree as CSV</string>
</property>
<property name="shortcut">
<string notr="true">Ctrl+C</string>
</property>
</action>
<action name="actionCopyAsYAML">
<property name="text">
<string>Copy as YAML</string>
</property>
<property name="toolTip">
<string>Copy the tree as YAML</string>
</property>
<property name="shortcut">
<string notr="true">Ctrl+Y</string>
</property>
</action>
</widget>
<customwidgets>
<customwidget>
<class>DisplayFilterEdit</class>
<extends>QLineEdit</extends>
<header>widgets/display_filter_edit.h</header>
</customwidget>
</customwidgets>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>LBMStreamDialog</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>LBMStreamDialog</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/lte_mac_statistics_dialog.cpp | /* lte_mac_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 "lte_mac_statistics_dialog.h"
#include <epan/packet.h>
#include <epan/strutil.h>
#include <epan/tap.h>
#include <epan/dissectors/packet-mac-lte.h>
#include <QFormLayout>
#include <QTreeWidgetItem>
#include <ui/qt/models/percent_bar_delegate.h>
#include "main_application.h"
// TODO: have never tested in a live capture.
// Whole-UE headings.
enum {
col_rnti_,
col_type_,
col_ueid_,
// UL-specific
col_ul_frames_,
col_ul_bytes_,
col_ul_mb_s_,
col_ul_padding_percent_,
/* col_ul_crc_failed_, */
col_ul_retx_,
// DL-specific
col_dl_frames_,
col_dl_bytes_,
col_dl_mb_s_,
col_dl_padding_percent_,
col_dl_crc_failed_,
col_dl_retx_
};
// Type of tree item, so can set column headings properly.
enum {
mac_whole_ue_row_type_ = 1000,
mac_ulsch_packet_count_row_type,
mac_ulsch_byte_count_row_type,
mac_dlsch_packet_count_row_type,
mac_dlsch_byte_count_row_type
};
// Calculate and return a bandwidth figure, in Mbs
static double calculate_bw(const nstime_t *start_time, const nstime_t *stop_time,
guint32 bytes)
{
// Can only calculate bandwidth if have time delta
if (memcmp(start_time, stop_time, sizeof(nstime_t)) != 0) {
double elapsed_ms = (((double)stop_time->secs - start_time->secs) * 1000) +
(((double)stop_time->nsecs - start_time->nsecs) / 1000000);
// Only really meaningful if have a few frames spread over time...
// For now at least avoid dividing by something very close to 0.0
if (elapsed_ms < 2.0) {
return 0.0f;
}
// N.B. very small values will display as scientific notation, but rather that than show 0
// when there is some traffic..
return ((bytes * 8) / elapsed_ms) / 1000;
}
else {
return 0.0f;
}
}
// Channels (by LCID) data node. Used for UL/DL frames/bytes.
class MacULDLTreeWidgetItem : public QTreeWidgetItem
{
public:
MacULDLTreeWidgetItem(QTreeWidgetItem *parent, unsigned ueid, unsigned rnti, int row_type) :
QTreeWidgetItem (parent, row_type),
ueid_(ueid),
rnti_(rnti)
{
// Init values held for all lcids to 0.
for (int n=0; n < MAC_LTE_DATA_LCID_COUNT_MAX; n++) {
lcids[n] = 0;
}
// Set first column to show what counts in this row mean.
switch (row_type) {
case mac_ulsch_packet_count_row_type:
setText(col_rnti_, "UL Packets");
break;
case mac_ulsch_byte_count_row_type:
setText(col_rnti_, "UL Bytes");
break;
case mac_dlsch_packet_count_row_type:
setText(col_rnti_, "DL Packets");
break;
case mac_dlsch_byte_count_row_type:
setText(col_rnti_, "DL Bytes");
break;
default:
// Should never get here...
break;
}
}
bool operator< (const QTreeWidgetItem &other) const
{
// We want rows with a UE to appear in the order they appear in the row_type enum.
return type() < other.type();
}
void draw()
{
// Show current value of counter for each LCID.
// N.B. fields that are set as % using percent_bar_delegate.h
// for UE headings don't display here...
for (int n=0; n < MAC_LTE_DATA_LCID_COUNT_MAX; n++) {
setText(col_type_+n, QString::number((uint)lcids[n]));
}
}
// Increase value held for lcid by given value.
void updateLCID(guint8 lcid, guint value)
{
lcids[lcid] += value;
}
// Generate expression for this UE and direction, also filter for SRs and RACH if indicated.
const QString filterExpression(bool showSR, bool showRACH) {
int direction = (type() == mac_dlsch_packet_count_row_type) ||
(type() == mac_dlsch_byte_count_row_type);
QString filter_expr;
if (showSR) {
filter_expr = QString("(mac-lte.sr-req and mac-lte.ueid == %1) or (").arg(ueid_);
}
if (showRACH) {
filter_expr += QString("(mac-lte.rar or (mac-lte.preamble-sent and mac-lte.ueid == %1)) or (").arg(ueid_);
}
// Main expression matching this UE and direction
filter_expr += QString("mac-lte.ueid==%1 && mac-lte.rnti==%2 && mac-lte.direction==%3").
arg(ueid_).arg(rnti_).arg(direction);
// Close () if open because of SR
if (showSR) {
filter_expr += QString(")");
}
// Close () if open because of RACH
if (showRACH) {
filter_expr += QString(")");
}
return filter_expr;
}
// Not showing anything for individual channels. Headings are different than from UEs, and
// trying to show both would be too confusing.
QList<QVariant> rowData() const
{
return QList<QVariant>();
}
private:
unsigned ueid_;
unsigned rnti_;
int lcids[MAC_LTE_DATA_LCID_COUNT_MAX]; /* 0 to 10 and 32 to 38 */
};
// Whole UE tree item
class MacUETreeWidgetItem : public QTreeWidgetItem
{
public:
MacUETreeWidgetItem(QTreeWidget *parent, const mac_lte_tap_info *mlt_info) :
QTreeWidgetItem (parent, mac_whole_ue_row_type_),
rnti_(0),
type_(0),
ueid_(0),
ul_frames_(0),
ul_bytes_(0),
ul_raw_bytes_(0),
ul_padding_bytes_(0),
ul_retx_(0),
dl_frames_(0),
dl_bytes_(0),
dl_raw_bytes_(0),
dl_padding_bytes_(0),
dl_crc_failed_(0),
dl_retx_(0)
{
// Set fixed fields.
rnti_ = mlt_info->rnti;
type_ = mlt_info->rntiType;
ueid_ = mlt_info->ueid;
setText(col_rnti_, QString::number(rnti_));
setText(col_type_, type_ == C_RNTI ? QObject::tr("C-RNTI") : QObject::tr("SPS-RNTI"));
setText(col_ueid_, QString::number(ueid_));
// Add UL/DL packet/byte count subitems.
addDetails();
}
// Does this tap-info match this existing UE item?
bool isMatch(const mac_lte_tap_info *mlt_info) {
return ((rnti_ == mlt_info->rnti) &&
(type_ == mlt_info->rntiType) &&
(ueid_ == mlt_info->ueid));
}
// Update this UE according to the tap info
void update(const mac_lte_tap_info *mlt_info) {
// Uplink.
if (mlt_info->direction == DIRECTION_UPLINK) {
if (mlt_info->isPHYRetx) {
ul_retx_++;
return;
}
if (mlt_info->crcStatusValid && (mlt_info->crcStatus != crc_success)) {
// TODO: there is not a column for this...
//ul_crc_errors_++;
return;
}
// Update time range
if (ul_frames_ == 0) {
ul_time_start_ = mlt_info->mac_lte_time;
}
ul_time_stop_ = mlt_info->mac_lte_time;
ul_frames_++;
// These values needed for padding % calculation.
ul_raw_bytes_ += mlt_info->raw_length;
ul_padding_bytes_ += mlt_info->padding_bytes;
// N.B. Not going to support predefined data in Qt version..
if (!mlt_info->isPredefinedData) {
for (int n=0; n < MAC_LTE_DATA_LCID_COUNT_MAX; n++) {
// Update UL child items
ul_frames_item_->updateLCID(n, mlt_info->sdus_for_lcid[n]);
ul_bytes_item_->updateLCID(n, mlt_info->bytes_for_lcid[n]);
ul_bytes_ += mlt_info->bytes_for_lcid[n];
}
}
}
// Downlink
else {
if (mlt_info->isPHYRetx) {
dl_retx_++;
return;
}
if (mlt_info->crcStatusValid && (mlt_info->crcStatus != crc_success)) {
switch (mlt_info->crcStatus) {
case crc_fail:
dl_crc_failed_++;
break;
default:
// Not a reason we currently care about.
break;
}
return;
}
// Update time range
if (dl_frames_ == 0) {
dl_time_start_ = mlt_info->mac_lte_time;
}
dl_time_stop_ = mlt_info->mac_lte_time;
dl_frames_++;
// These values needed for padding % calculation.
dl_raw_bytes_ += mlt_info->raw_length;
dl_padding_bytes_ += mlt_info->padding_bytes;
// N.B. Not going to support predefined data in Qt version..
if (!mlt_info->isPredefinedData) {
for (int n=0; n < MAC_LTE_DATA_LCID_COUNT_MAX; n++) {
// Update DL child items
dl_frames_item_->updateLCID(n, mlt_info->sdus_for_lcid[n]);
dl_bytes_item_->updateLCID(n, mlt_info->bytes_for_lcid[n]);
dl_bytes_ += mlt_info->bytes_for_lcid[n];
}
}
}
}
void addDetails() {
// Add UL/DL packet and byte counts.
ul_frames_item_ = new MacULDLTreeWidgetItem(this, ueid_, rnti_, mac_ulsch_packet_count_row_type);
ul_bytes_item_ = new MacULDLTreeWidgetItem(this, ueid_, rnti_, mac_ulsch_byte_count_row_type);
dl_frames_item_ = new MacULDLTreeWidgetItem(this, ueid_, rnti_, mac_dlsch_packet_count_row_type);
dl_bytes_item_ = new MacULDLTreeWidgetItem(this, ueid_, rnti_, mac_dlsch_byte_count_row_type);
setExpanded(false);
}
// Draw this UE.
void draw() {
// Fixed fields (rnti, type, ueid) won't change during lifetime of UE entry.
// Calculate bw now.
double UL_bw = calculate_bw(&ul_time_start_,
&ul_time_stop_,
ul_bytes_);
double DL_bw = calculate_bw(&dl_time_start_,
&dl_time_stop_,
dl_bytes_);
// Set columns with current values.
setText(col_ul_frames_, QString::number(ul_frames_));
setText(col_ul_bytes_, QString::number(ul_bytes_));
setText(col_ul_mb_s_, QString::number(UL_bw));
setData(col_ul_padding_percent_, Qt::UserRole,
QVariant::fromValue<double>(ul_raw_bytes_ ?
(((double)ul_padding_bytes_ / (double)ul_raw_bytes_) * 100.0) :
0.0));
setText(col_ul_retx_, QString::number(ul_retx_));
setText(col_dl_frames_, QString::number(dl_frames_));
setText(col_dl_bytes_, QString::number(dl_bytes_));
setText(col_dl_mb_s_, QString::number(DL_bw));
setData(col_dl_padding_percent_, Qt::UserRole,
QVariant::fromValue<double>(dl_raw_bytes_ ?
(((double)dl_padding_bytes_ / (double)dl_raw_bytes_) * 100.0) :
0.0));
setText(col_dl_crc_failed_, QString::number(dl_crc_failed_));
setText(col_dl_retx_, QString::number(dl_retx_));
// Draw child items with per-channel counts.
ul_frames_item_->draw();
ul_bytes_item_->draw();
dl_frames_item_->draw();
dl_bytes_item_->draw();
}
// < operator. Compare this item with another item, using the column we are currently sorting on.
bool operator< (const QTreeWidgetItem &other) const
{
if (other.type() != mac_whole_ue_row_type_) return QTreeWidgetItem::operator< (other);
const MacUETreeWidgetItem *other_row = static_cast<const MacUETreeWidgetItem *>(&other);
switch (treeWidget()->sortColumn()) {
case col_rnti_:
return rnti_ < other_row->rnti_;
case col_type_:
return type_ < other_row->type_;
case col_ueid_:
return ueid_ < other_row->ueid_;
// TODO: other fields?
default:
break;
}
return QTreeWidgetItem::operator< (other);
}
// Generate expression for this UE, also filter for SRs and RACH if indicated.
const QString filterExpression(bool showSR, bool showRACH) {
QString filter_expr;
if (showSR) {
filter_expr = QString("(mac-lte.sr-req and mac-lte.ueid == %1) or (").arg(ueid_);
}
if (showRACH) {
filter_expr += QString("(mac-lte.rar or (mac-lte.preamble-sent and mac-lte.ueid == %1)) or (").arg(ueid_);
}
// Main expression matching this UE
filter_expr += QString("mac-lte.ueid==%1 && mac-lte.rnti==%2").arg(ueid_).arg(rnti_);
// Close () if open because of SR
if (showSR) {
filter_expr += QString(")");
}
// Close () if open because of RACH
if (showRACH) {
filter_expr += QString(")");
}
return filter_expr;
}
// Return the UE-specific fields.
QList<QVariant> rowData() const
{
QList<QVariant> row_data;
// Key fields
row_data << rnti_ << (type_ == C_RNTI ? QObject::tr("C-RNTI") : QObject::tr("SPS-RNTI")) << ueid_;
// UL
row_data << ul_frames_ << ul_bytes_
<< calculate_bw(&ul_time_start_, &ul_time_stop_, ul_bytes_)
<< QVariant::fromValue<double>(ul_raw_bytes_ ?
(((double)ul_padding_bytes_ / (double)ul_raw_bytes_) * 100.0) :
0.0)
<< ul_retx_;
// DL
row_data << dl_frames_ << dl_bytes_
<< calculate_bw(&dl_time_start_, &dl_time_stop_, dl_bytes_)
<< QVariant::fromValue<double>(dl_raw_bytes_ ?
(((double)dl_padding_bytes_ / (double)dl_raw_bytes_) * 100.0) :
0.0)
<< dl_crc_failed_ << dl_retx_;
return row_data;
}
private:
// Unchanging (key) fields.
unsigned rnti_;
unsigned type_;
unsigned ueid_;
// UL-specific.
unsigned ul_frames_;
unsigned ul_bytes_;
unsigned ul_raw_bytes_;
unsigned ul_padding_bytes_;
nstime_t ul_time_start_;
nstime_t ul_time_stop_;
unsigned ul_retx_;
// DL-specific.
unsigned dl_frames_;
unsigned dl_bytes_;
unsigned dl_raw_bytes_;
unsigned dl_padding_bytes_;
nstime_t dl_time_start_;
nstime_t dl_time_stop_;
unsigned dl_crc_failed_;
unsigned dl_retx_;
// Child nodes storing per-lcid counts.
MacULDLTreeWidgetItem *ul_frames_item_;
MacULDLTreeWidgetItem *ul_bytes_item_;
MacULDLTreeWidgetItem *dl_frames_item_;
MacULDLTreeWidgetItem *dl_bytes_item_;
};
// Label headings. Show according to which type of tree item is currently selected.
static const QStringList mac_whole_ue_row_labels = QStringList()
<< QObject::tr("RNTI") << QObject::tr("Type") << QObject::tr("UEId")
<< QObject::tr("UL Frames") << QObject::tr("UL Bytes") << QObject::tr("UL MB/s")
<< QObject::tr("UL Padding %") << QObject::tr("UL Re TX")
<< QObject::tr("DL Frames") << QObject::tr("DL Bytes") << QObject::tr("DL MB/s")
<< QObject::tr("DL Padding %") << QObject::tr("DL CRC Failed")
<< QObject::tr("DL ReTX")
// 'Blank out' Channel-level fields
<< QObject::tr("") << QObject::tr("") << QObject::tr("") << QObject::tr("") << QObject::tr("");
static const QStringList mac_channel_counts_labels = QStringList()
<< QObject::tr("") << QObject::tr("CCCH")
<< QObject::tr("LCID 1") << QObject::tr("LCID 2") << QObject::tr("LCID 3")
<< QObject::tr("LCID 4") << QObject::tr("LCID 5") << QObject::tr("LCID 6")
<< QObject::tr("LCID 7") << QObject::tr("LCID 8") << QObject::tr("LCID 9")
<< QObject::tr("LCID 10") << QObject::tr("LCID 32") << QObject::tr("LCID 33")
<< QObject::tr("LCID 34") << QObject::tr("LCID 35") << QObject::tr("LCID 36")
<< QObject::tr("LCID 37") << QObject::tr("LCID 38");
//------------------------------------------------------------------------------------------
// Dialog
// Constructor.
LteMacStatisticsDialog::LteMacStatisticsDialog(QWidget &parent, CaptureFile &cf, const char *filter) :
TapParameterDialog(parent, cf, HELP_STATS_LTE_MAC_TRAFFIC_DIALOG),
commonStatsCurrent_(false)
{
setWindowSubtitle(tr("LTE Mac Statistics"));
loadGeometry(parent.width() * 1, parent.height() * 3 / 4, "LTEMacStatisticsDialog");
clearCommonStats();
// Create common_stats_grid to appear just above the filter area.
int statstree_layout_idx = verticalLayout()->indexOf(filterLayout()->widget());
QGridLayout *common_stats_grid = new QGridLayout();
// Insert into the vertical layout
verticalLayout()->insertLayout(statstree_layout_idx, common_stats_grid);
int one_em = fontMetrics().height();
common_stats_grid->setColumnMinimumWidth(2, one_em * 2);
common_stats_grid->setColumnStretch(2, 1);
common_stats_grid->setColumnMinimumWidth(5, one_em * 2);
common_stats_grid->setColumnStretch(5, 1);
// Create statistics label.
commonStatsLabel_ = new QLabel(this);
commonStatsLabel_->setObjectName("statisticsLabel");
commonStatsLabel_->setTextFormat(Qt::RichText);
commonStatsLabel_->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
common_stats_grid->addWidget(commonStatsLabel_);
// Create a grid for filtering-related widgetsto also appear in layout.
int filter_controls_layout_idx = verticalLayout()->indexOf(filterLayout()->widget());
QGridLayout *filter_controls_grid = new QGridLayout();
// Insert into the vertical layout
verticalLayout()->insertLayout(filter_controls_layout_idx, filter_controls_grid);
filter_controls_grid->setColumnMinimumWidth(2, one_em * 2);
filter_controls_grid->setColumnStretch(2, 1);
filter_controls_grid->setColumnMinimumWidth(5, one_em * 2);
filter_controls_grid->setColumnStretch(5, 1);
// Add individual controls into the grid
showSRFilterCheckBox_ = new QCheckBox(tr("Include SR frames in filter"));
filter_controls_grid->addWidget(showSRFilterCheckBox_);
showRACHFilterCheckBox_ = new QCheckBox(tr("Include RACH frames in filter"));
filter_controls_grid->addWidget(showRACHFilterCheckBox_);
// Will set whole-UE headings originally.
updateHeaderLabels();
ul_delegate_ = new PercentBarDelegate();
statsTreeWidget()->setItemDelegateForColumn(col_ul_padding_percent_, ul_delegate_);
dl_delegate_ = new PercentBarDelegate();
statsTreeWidget()->setItemDelegateForColumn(col_dl_padding_percent_, dl_delegate_);
statsTreeWidget()->sortByColumn(col_rnti_, Qt::AscendingOrder);
// Set up column widths.
// resizeColumnToContents doesn't work well here, so set sizes manually.
for (int col = 0; col < statsTreeWidget()->columnCount() - 1; col++) {
switch (col) {
case col_rnti_:
statsTreeWidget()->setColumnWidth(col, one_em * 8);
break;
case col_ul_frames_:
statsTreeWidget()->setColumnWidth(col, one_em * 5);
break;
case col_ul_bytes_:
statsTreeWidget()->setColumnWidth(col, one_em * 5);
break;
case col_ul_mb_s_:
statsTreeWidget()->setColumnWidth(col, one_em * 4);
break;
case col_ul_padding_percent_:
statsTreeWidget()->setColumnWidth(col, one_em * 6);
break;
case col_ul_retx_:
statsTreeWidget()->setColumnWidth(col, one_em * 6);
break;
case col_dl_frames_:
statsTreeWidget()->setColumnWidth(col, one_em * 5);
break;
case col_dl_bytes_:
statsTreeWidget()->setColumnWidth(col, one_em * 5);
break;
case col_dl_mb_s_:
statsTreeWidget()->setColumnWidth(col, one_em * 4);
break;
case col_dl_padding_percent_:
statsTreeWidget()->setColumnWidth(col, one_em * 6);
break;
case col_dl_crc_failed_:
statsTreeWidget()->setColumnWidth(col, one_em * 6);
break;
case col_dl_retx_:
statsTreeWidget()->setColumnWidth(col, one_em * 6);
break;
default:
// The rest are numeric
statsTreeWidget()->setColumnWidth(col, one_em * 4);
statsTreeWidget()->headerItem()->setTextAlignment(col, Qt::AlignRight);
break;
}
}
addFilterActions();
if (filter) {
setDisplayFilter(filter);
}
// Set handler for when the tree item changes to set the appropriate labels.
connect(statsTreeWidget(), &QTreeWidget::itemSelectionChanged,
this, &LteMacStatisticsDialog::updateHeaderLabels);
// Set handler for when display filter string is changed.
connect(this, &LteMacStatisticsDialog::updateFilter,
this, &LteMacStatisticsDialog::filterUpdated);
}
// Destructor.
LteMacStatisticsDialog::~LteMacStatisticsDialog()
{
delete ul_delegate_;
delete dl_delegate_;
}
// Update system/common counters, and redraw if changed.
void LteMacStatisticsDialog::updateCommonStats(const mac_lte_tap_info *tap_info)
{
commonStats_.all_frames++;
// For common channels, just update global counters
switch (tap_info->rntiType) {
case P_RNTI:
commonStats_.pch_frames++;
commonStats_.pch_bytes += tap_info->single_number_of_bytes;
commonStats_.pch_paging_ids += tap_info->number_of_paging_ids;
commonStatsCurrent_ = false;
break;
case SI_RNTI:
commonStats_.sib_frames++;
commonStats_.sib_bytes += tap_info->single_number_of_bytes;
commonStatsCurrent_ = false;
break;
case NO_RNTI:
commonStats_.mib_frames++;
commonStatsCurrent_ = false;
break;
case RA_RNTI:
commonStats_.rar_frames++;
commonStats_.rar_entries += tap_info->number_of_rars;
commonStatsCurrent_ = false;
break;
case C_RNTI:
case SPS_RNTI:
// UE-specific.
break;
default:
// Error...
return;
}
// Check max UEs/tti counter
switch (tap_info->direction) {
case DIRECTION_UPLINK:
if (tap_info->ueInTTI > commonStats_.max_ul_ues_in_tti) {
commonStats_.max_ul_ues_in_tti = tap_info->ueInTTI;
commonStatsCurrent_ = false;
}
break;
case DIRECTION_DOWNLINK:
if (tap_info->ueInTTI > commonStats_.max_dl_ues_in_tti) {
commonStats_.max_dl_ues_in_tti = tap_info->ueInTTI;
commonStatsCurrent_ = false;
}
break;
}
}
// Draw current common statistics by regenerating label with current values.
void LteMacStatisticsDialog::drawCommonStats()
{
if (!commonStatsCurrent_) {
QString stats_tables = "<html><head></head><body>\n";
stats_tables += QString("<table>\n");
stats_tables += QString("<tr><th align=\"left\">System</th> <td align=\"left\"> Max UL UEs/TTI=%1</td>").arg(commonStats_.max_ul_ues_in_tti);
stats_tables += QString("<td align=\"left\">Max DL UEs/TTI=%1</td></tr>\n").arg(commonStats_.max_dl_ues_in_tti);
stats_tables += QString("<tr><th align=\"left\">System broadcast</th><td align=\"left\">MIBs=%1</td>").arg(commonStats_.mib_frames);
stats_tables += QString("<td align=\"left\">SIBs=%1 (%2 bytes)</td></tr>\n").arg(commonStats_.sib_frames).arg(commonStats_.sib_bytes);
stats_tables += QString("<tr><th align=\"left\">RACH</th><td align=\"left\">RARs=%1 frames (%2 RARs)</td></tr>\n").
arg(commonStats_.rar_frames).
arg(commonStats_.rar_entries);
stats_tables += QString("<tr><th align=\"left\">Paging</th><td align=\"left\">PCH=%1 (%2 bytes, %3 IDs)</td></tr>\n").
arg(commonStats_.pch_frames).
arg(commonStats_.pch_bytes).
arg(commonStats_.pch_paging_ids);
stats_tables += QString("</table>\n");
stats_tables += "</body>\n";
commonStatsLabel_->setText(stats_tables);
commonStatsCurrent_ = true;
}
}
void LteMacStatisticsDialog::clearCommonStats()
{
memset(&commonStats_, 0, sizeof(commonStats_));
}
void LteMacStatisticsDialog::tapReset(void *ws_dlg_ptr)
{
LteMacStatisticsDialog *ws_dlg = static_cast<LteMacStatisticsDialog *>(ws_dlg_ptr);
if (!ws_dlg) {
return;
}
ws_dlg->statsTreeWidget()->clear();
ws_dlg->clearCommonStats();
}
//---------------------------------------------------------------------------------------
// Process tap info from a new packet.
// Returns TAP_PACKET_REDRAW if a redraw is needed, TAP_PACKET_DONT_REDRAW otherwise.
tap_packet_status LteMacStatisticsDialog::tapPacket(void *ws_dlg_ptr, struct _packet_info *, epan_dissect *, const void *mac_lte_tap_info_ptr, tap_flags_t)
{
// Look up dialog and tap info.
LteMacStatisticsDialog *ws_dlg = static_cast<LteMacStatisticsDialog *>(ws_dlg_ptr);
const mac_lte_tap_info *mlt_info = (const mac_lte_tap_info *) mac_lte_tap_info_ptr;
if (!ws_dlg || !mlt_info) {
return TAP_PACKET_DONT_REDRAW;
}
// Update common stats.
ws_dlg->updateCommonStats(mlt_info);
// Nothing more to do if tap entry isn't for a UE.
if ((mlt_info->rntiType != C_RNTI) && (mlt_info->rntiType != SPS_RNTI)) {
return TAP_PACKET_DONT_REDRAW;
}
// Look for an existing UE to match this tap info.
MacUETreeWidgetItem *mac_ue_ti = NULL;
for (int i = 0; i < ws_dlg->statsTreeWidget()->topLevelItemCount(); i++) {
QTreeWidgetItem *ti = ws_dlg->statsTreeWidget()->topLevelItem(i);
// Make sure we're looking at a UE entry
if (ti->type() != mac_whole_ue_row_type_) {
continue;
}
// See if current item matches tap.
MacUETreeWidgetItem *cur_muds_ti = static_cast<MacUETreeWidgetItem*>(ti);
if (cur_muds_ti->isMatch(mlt_info)) {
mac_ue_ti = cur_muds_ti;
break;
}
}
// If don't find matching UE, create a new one.
if (!mac_ue_ti) {
mac_ue_ti = new MacUETreeWidgetItem(ws_dlg->statsTreeWidget(), mlt_info);
for (int col = 0; col < ws_dlg->statsTreeWidget()->columnCount(); col++) {
// int QTreeWidgetItem::textAlignment(int column) const
// Returns the text alignment for the label in the given column.
// Note: This function returns an int for historical reasons. It will be corrected to return Qt::Alignment in Qt 7.
mac_ue_ti->setTextAlignment(col, static_cast<Qt::Alignment>(ws_dlg->statsTreeWidget()->headerItem()->textAlignment(col)));
}
}
// Update the UE item with info from tap!
mac_ue_ti->update(mlt_info);
return TAP_PACKET_REDRAW;
}
// Return total number of frames tapped.
unsigned LteMacStatisticsDialog::getFrameCount()
{
return commonStats_.all_frames;
}
void LteMacStatisticsDialog::tapDraw(void *ws_dlg_ptr)
{
// Look up dialog.
LteMacStatisticsDialog *ws_dlg = static_cast<LteMacStatisticsDialog *>(ws_dlg_ptr);
if (!ws_dlg) {
return;
}
// Go over all of the top-level items.
for (int i = 0; i < ws_dlg->statsTreeWidget()->topLevelItemCount(); i++) {
// Get item, make sure its of the whole-UE type.
QTreeWidgetItem *ti = ws_dlg->statsTreeWidget()->topLevelItem(i);
if (ti->type() != mac_whole_ue_row_type_) {
continue;
}
// Tell the UE item to draw itself.
MacUETreeWidgetItem *mac_ue_ti = static_cast<MacUETreeWidgetItem*>(ti);
mac_ue_ti->draw();
}
ws_dlg->drawCommonStats();
// Update title
ws_dlg->setWindowSubtitle(QString("LTE Mac Statistics (%1 UEs, %2 frames)").
arg(ws_dlg->statsTreeWidget()->topLevelItemCount()).arg(ws_dlg->getFrameCount()));
}
const QString LteMacStatisticsDialog::filterExpression()
{
QString filter_expr;
if (statsTreeWidget()->selectedItems().count() > 0) {
QTreeWidgetItem *ti = statsTreeWidget()->selectedItems()[0];
if (ti->type() == mac_whole_ue_row_type_) {
MacUETreeWidgetItem *mac_ue_ti = static_cast<MacUETreeWidgetItem*>(ti);
filter_expr = mac_ue_ti->filterExpression(showSRFilterCheckBox_->checkState() > Qt::Unchecked,
showRACHFilterCheckBox_->checkState() > Qt::Unchecked);
} else {
MacULDLTreeWidgetItem *mac_channels_ti = static_cast<MacULDLTreeWidgetItem*>(ti);
filter_expr = mac_channels_ti->filterExpression(showSRFilterCheckBox_->checkState() > Qt::Unchecked,
showRACHFilterCheckBox_->checkState() > Qt::Unchecked);
}
}
return filter_expr;
}
void LteMacStatisticsDialog::fillTree()
{
if (!registerTapListener("mac-lte",
this,
displayFilter_.toLatin1().data(),
TL_REQUIRES_NOTHING,
tapReset,
tapPacket,
tapDraw)) {
reject();
return;
}
cap_file_.retapPackets();
tapDraw(this);
removeTapListeners();
}
void LteMacStatisticsDialog::updateHeaderLabels()
{
if (statsTreeWidget()->selectedItems().count() > 0 && statsTreeWidget()->selectedItems()[0]->type() == mac_whole_ue_row_type_) {
// Whole-UE labels
statsTreeWidget()->setHeaderLabels(mac_whole_ue_row_labels);
} else if (statsTreeWidget()->selectedItems().count() > 0) {
// ULDL labels
switch (statsTreeWidget()->selectedItems()[0]->type()) {
case mac_ulsch_packet_count_row_type:
case mac_ulsch_byte_count_row_type:
case mac_dlsch_packet_count_row_type:
case mac_dlsch_byte_count_row_type:
statsTreeWidget()->setHeaderLabels(mac_channel_counts_labels);
break;
default:
break;
}
}
else {
// Nothing selected yet, but set whole-UE labels.
statsTreeWidget()->setHeaderLabels(mac_whole_ue_row_labels);
}
}
void LteMacStatisticsDialog::captureFileClosing()
{
remove_tap_listener(this);
WiresharkDialog::captureFileClosing();
}
// Store filter from signal.
void LteMacStatisticsDialog::filterUpdated(QString filter)
{
displayFilter_ = filter;
}
// Get the item for the row, depending upon the type of tree item.
QList<QVariant> LteMacStatisticsDialog::treeItemData(QTreeWidgetItem *item) const
{
// Cast up to our type.
MacULDLTreeWidgetItem *channel_item = dynamic_cast<MacULDLTreeWidgetItem*>(item);
if (channel_item) {
return channel_item->rowData();
}
MacUETreeWidgetItem *ue_item = dynamic_cast<MacUETreeWidgetItem*>(item);
if (ue_item) {
return ue_item->rowData();
}
// Need to return something..
return QList<QVariant>();
}
// Stat command + args
static void
lte_mac_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("LteMacStatistics", filter.constData(), NULL);
}
static stat_tap_ui lte_mac_statistics_ui = {
REGISTER_STAT_GROUP_TELEPHONY_LTE,
QT_TRANSLATE_NOOP("LteMacStatisticsDialog", "MAC Statistics"),
"mac-lte,stat",
lte_mac_statistics_init,
0,
NULL
};
extern "C" {
void register_tap_listener_qt_lte_mac_statistics(void);
void
register_tap_listener_qt_lte_mac_statistics(void)
{
register_stat_tap_ui(<e_mac_statistics_ui, NULL);
}
} |
C/C++ | wireshark/ui/qt/lte_mac_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 __LTE_MAC_STATISTICS_DIALOG_H__
#define __LTE_MAC_STATISTICS_DIALOG_H__
#include "tap_parameter_dialog.h"
#include <QLabel>
#include <QCheckBox>
#include <ui/qt/models/percent_bar_delegate.h>
// Common channel stats
typedef struct mac_lte_common_stats {
guint32 all_frames;
guint32 mib_frames;
guint32 sib_frames;
guint32 sib_bytes;
guint32 pch_frames;
guint32 pch_bytes;
guint32 pch_paging_ids;
guint32 rar_frames;
guint32 rar_entries;
guint16 max_ul_ues_in_tti;
guint16 max_dl_ues_in_tti;
} mac_lte_common_stats;
class LteMacStatisticsDialog : public TapParameterDialog
{
Q_OBJECT
public:
LteMacStatisticsDialog(QWidget &parent, CaptureFile &cf, const char *filter);
~LteMacStatisticsDialog();
protected:
void captureFileClosing();
private:
// Extra controls needed for this dialog.
QLabel *commonStatsLabel_;
QCheckBox *showSRFilterCheckBox_;
QCheckBox *showRACHFilterCheckBox_;
PercentBarDelegate *ul_delegate_, *dl_delegate_;
QString displayFilter_;
// Callbacks for register_tap_listener
static void tapReset(void *ws_dlg_ptr);
static tap_packet_status tapPacket(void *ws_dlg_ptr, struct _packet_info *, struct epan_dissect *, const void *mac_lte_tap_info_ptr, tap_flags_t flags);
static void tapDraw(void *ws_dlg_ptr);
virtual const QString filterExpression();
// Common stats.
mac_lte_common_stats commonStats_;
bool commonStatsCurrent_; // Set when changes have not yet been drawn
void updateCommonStats(const struct mac_lte_tap_info *mlt_info);
void drawCommonStats();
void clearCommonStats();
unsigned getFrameCount();
QList<QVariant> treeItemData(QTreeWidgetItem *item) const;
private slots:
virtual void fillTree();
void updateHeaderLabels();
void filterUpdated(QString filter);
};
#endif // __LTE_MAC_STATISTICS_DIALOG_H__ |
C++ | wireshark/ui/qt/lte_rlc_graph_dialog.cpp | /* lte_rlc_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 "lte_rlc_graph_dialog.h"
#include <ui_lte_rlc_graph_dialog.h>
#include <epan/epan.h>
#include <epan/epan_dissect.h>
#include <epan/tap.h>
#include <epan/stat_tap_ui.h>
#include <epan/tvbuff-int.h>
#include <epan/tvbuff.h>
#include <frame_tvbuff.h>
#include <ui/qt/utils/tango_colors.h>
#include <QMenu>
#include <QRubberBand>
#include <wsutil/utf8_entities.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
#include "simple_dialog.h"
#include "ui/qt/widgets/wireshark_file_dialog.h"
#include <epan/dissectors/packet-rlc-lte.h>
#include <ui/tap-rlc-graph.h>
const QRgb graph_color_ack = tango_sky_blue_4; // Blue for ACK lines
const QRgb graph_color_nack = tango_scarlet_red_3; // Red for NACKs
// Size of selectable packet points in the base graph
const double pkt_point_size_ = 3.0;
// Constructor.
LteRlcGraphDialog::LteRlcGraphDialog(QWidget &parent, CaptureFile &cf, bool channelKnown) :
WiresharkDialog(parent, cf),
ui(new Ui::LteRlcGraphDialog),
mouse_drags_(true),
rubber_band_(NULL),
base_graph_(NULL),
reseg_graph_(NULL),
acks_graph_(NULL),
nacks_graph_(NULL),
tracer_(NULL),
packet_num_(0)
{
ui->setupUi(this);
loadGeometry(parent.width() * 4 / 5, parent.height() * 3 / 4);
QCustomPlot *rp = ui->rlcPlot;
rp->xAxis->setLabel(tr("Time"));
rp->yAxis->setLabel(tr("Sequence Number"));
// TODO: couldn't work out how to tell rp->xAxis not to label fractions of a SN...
ui->dragRadioButton->setChecked(mouse_drags_);
ctx_menu_ = new QMenu(this);
ctx_menu_->addAction(ui->actionZoomIn);
ctx_menu_->addAction(ui->actionZoomInX);
ctx_menu_->addAction(ui->actionZoomInY);
ctx_menu_->addAction(ui->actionZoomOut);
ctx_menu_->addAction(ui->actionZoomOutX);
ctx_menu_->addAction(ui->actionZoomOutY);
ctx_menu_->addAction(ui->actionReset);
ctx_menu_->addSeparator();
ctx_menu_->addAction(ui->actionMoveRight10);
ctx_menu_->addAction(ui->actionMoveLeft10);
ctx_menu_->addAction(ui->actionMoveUp10);
ctx_menu_->addAction(ui->actionMoveUp100);
ctx_menu_->addAction(ui->actionMoveDown10);
ctx_menu_->addAction(ui->actionMoveDown100);
ctx_menu_->addAction(ui->actionMoveRight1);
ctx_menu_->addAction(ui->actionMoveLeft1);
ctx_menu_->addAction(ui->actionMoveUp1);
ctx_menu_->addAction(ui->actionMoveDown1);
ctx_menu_->addSeparator();
ctx_menu_->addAction(ui->actionGoToPacket);
ctx_menu_->addSeparator();
ctx_menu_->addAction(ui->actionDragZoom);
// ctx_menu_->addAction(ui->actionToggleTimeOrigin);
ctx_menu_->addAction(ui->actionCrosshairs);
ctx_menu_->addSeparator();
ctx_menu_->addAction(ui->actionSwitchDirection);
set_action_shortcuts_visible_in_context_menu(ctx_menu_->actions());
// Zero out this struct.
memset(&graph_, 0, sizeof(graph_));
// If channel is known, details will be supplied by setChannelInfo().
if (!channelKnown) {
completeGraph();
}
}
// Destructor
LteRlcGraphDialog::~LteRlcGraphDialog()
{
delete ui;
}
// Set the channel information that this graph should show.
void LteRlcGraphDialog::setChannelInfo(guint16 ueid, guint8 rlcMode,
guint16 channelType, guint16 channelId, guint8 direction,
bool maybe_empty)
{
graph_.ueid = ueid;
graph_.rlcMode = rlcMode;
graph_.channelType = channelType;
graph_.channelId = channelId;
graph_.channelSet = TRUE;
graph_.direction = direction;
completeGraph(maybe_empty);
}
// Once channel details are known, complete the graph with details that depend upon the channel.
void LteRlcGraphDialog::completeGraph(bool may_be_empty)
{
QCustomPlot *rp = ui->rlcPlot;
// If no channel chosen already, try to use currently selected frame.
findChannel(may_be_empty);
// Set window title here.
if (graph_.channelSet) {
QString dlg_title = tr("LTE RLC Graph (UE=%1 chan=%2%3 %4 - %5)")
.arg(graph_.ueid)
.arg((graph_.channelType == CHANNEL_TYPE_SRB) ? "SRB" : "DRB")
.arg(graph_.channelId)
.arg((graph_.direction == DIRECTION_UPLINK) ? "UL" : "DL")
.arg((graph_.rlcMode == RLC_UM_MODE) ? "UM" : "AM");
setWindowTitle(dlg_title);
}
else {
setWindowTitle(tr("LTE RLC Graph - no channel selected"));
}
// Set colours/styles for each of the traces on the graph.
QCustomPlot *sp = ui->rlcPlot;
base_graph_ = sp->addGraph(); // All: Selectable segments
base_graph_->setPen(QPen(QBrush(Qt::black), 0.25));
reseg_graph_ = sp->addGraph();
reseg_graph_->setPen(QPen(QBrush(Qt::lightGray), 0.25));
acks_graph_ = sp->addGraph();
acks_graph_->setPen(QPen(QBrush(graph_color_ack), 1.0));
nacks_graph_ = sp->addGraph();
nacks_graph_->setPen(QPen(QBrush(graph_color_nack), 0.25));
// Create tracer
tracer_ = new QCPItemTracer(sp);
tracer_->setVisible(false);
toggleTracerStyle(true);
// Change label on save/export button.
QPushButton *save_bt = ui->buttonBox->button(QDialogButtonBox::Save);
save_bt->setText(tr("Save As…"));
// Don't want to connect again after first time. - causes mouse handlers to get called
// multiple times.
if (!may_be_empty) {
connect(rp, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(graphClicked(QMouseEvent*)));
connect(rp, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMoved(QMouseEvent*)));
connect(rp, SIGNAL(mouseRelease(QMouseEvent*)), this, SLOT(mouseReleased(QMouseEvent*)));
}
disconnect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
this->setResult(QDialog::Accepted);
// Extract the data that the graph can use.
fillGraph();
}
// See if the given segment matches the channel this graph is plotting.
bool LteRlcGraphDialog::compareHeaders(rlc_segment *seg)
{
return compare_rlc_headers(graph_.ueid, graph_.channelType,
graph_.channelId, graph_.rlcMode, graph_.direction,
seg->ueid, seg->channelType,
seg->channelId, seg->rlcMode, seg->direction,
seg->isControlPDU);
}
// Look for channel to plot based upon currently selected frame.
void LteRlcGraphDialog::findChannel(bool may_fail)
{
// Temporarily disconnect mouse move signals.
QCustomPlot *rp = ui->rlcPlot;
disconnect(rp, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMoved(QMouseEvent*)));
char *err_string = NULL;
// Rescan for channel data.
rlc_graph_segment_list_free(&graph_);
if (!rlc_graph_segment_list_get(cap_file_.capFile(), &graph_, graph_.channelSet,
&err_string)) {
if (may_fail) {
g_free(err_string);
} else {
// Pop up an error box to report error.
simple_error_message_box("%s", err_string);
g_free(err_string);
return;
}
}
// Reconnect mouse move signal.
connect(rp, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMoved(QMouseEvent*)));
}
// Fill in graph data based upon what was read into the rlc_graph struct.
void LteRlcGraphDialog::fillGraph()
{
QCustomPlot *sp = ui->rlcPlot;
// We should always have 4 graphs, but cover case if no channel was chosen.
if (sp->graphCount() < 1) {
return;
}
tracer_->setGraph(NULL);
base_graph_->setLineStyle(QCPGraph::lsNone); // dot
reseg_graph_->setLineStyle(QCPGraph::lsNone); // dot
acks_graph_->setLineStyle(QCPGraph::lsStepLeft); // to get step effect...
nacks_graph_->setLineStyle(QCPGraph::lsNone); // dot, but bigger.
// Will show all graphs with data we find.
for (int i = 0; i < sp->graphCount(); i++) {
sp->graph(i)->data()->clear();
sp->graph(i)->setVisible(true);
}
// N.B. ssDisc is really too slow. TODO: work out how to turn off aliasing, or experiment
// with ssCustom. Other styles tried didn't look right.
// GTK version was speeded up noticibly by turning down aliasing level...
base_graph_->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, pkt_point_size_));
reseg_graph_->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, pkt_point_size_));
acks_graph_->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, pkt_point_size_));
// NACKs are shown bigger than others.
nacks_graph_->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, pkt_point_size_*2));
// Map timestamps -> segments in first pass.
time_stamp_map_.clear();
for (struct rlc_segment *seg = graph_.segments; seg != NULL; seg = seg->next) {
if (!compareHeaders(seg)) {
continue;
}
double ts = seg->rel_secs + seg->rel_usecs / 1000000.0;
time_stamp_map_.insert(ts, seg);
}
// Now sequence numbers.
QVector<double> seq_time, seq,
reseg_seq_time, reseg_seq,
acks_time, acks,
nacks_time, nacks;
for (struct rlc_segment *seg = graph_.segments; seg != NULL; seg = seg->next) {
double ts = seg->rel_secs + (seg->rel_usecs / 1000000.0);
if (compareHeaders(seg)) {
if (!seg->isControlPDU) {
// Data
if (seg->isResegmented) {
reseg_seq_time.append(ts);
reseg_seq.append(seg->SN);
}
else {
seq_time.append(ts);
seq.append(seg->SN);
}
}
else {
// Status (ACKs/NACKs)
acks_time.append(ts);
acks.append(seg->ACKNo-1);
for (int n=0; n < seg->noOfNACKs; n++) {
nacks_time.append(ts);
nacks.append(seg->NACKs[n]);
}
}
}
}
// Add the data from the graphs.
base_graph_->setData(seq_time, seq);
reseg_graph_->setData(reseg_seq_time, reseg_seq);
acks_graph_->setData(acks_time, acks);
nacks_graph_->setData(nacks_time, nacks);
sp->setEnabled(true);
// Auto-size...
mouseMoved(NULL);
resetAxes();
// This is why, in mouseMoved(), we only match the entries
// corresponding to data segments (base_graph_)...
tracer_->setGraph(base_graph_);
// XXX QCustomPlot doesn't seem to draw any sort of focus indicator.
sp->setFocus();
}
// Copied from TCP graphs, seems like a kludge to get the graph resized immediately after it is built...
void LteRlcGraphDialog::showEvent(QShowEvent *)
{
resetAxes();
}
// Respond to a key press.
void LteRlcGraphDialog::keyPressEvent(QKeyEvent *event)
{
int pan_pixels = (event->modifiers() & Qt::ShiftModifier) ? 1 : 10;
switch(event->key()) {
case Qt::Key_Minus:
case Qt::Key_Underscore: // Shifted minus on U.S. keyboards
case Qt::Key_O: // GTK+
zoomAxes(false);
break;
case Qt::Key_Plus:
case Qt::Key_Equal: // Unshifted plus on U.S. keyboards
case Qt::Key_I: // GTK+
zoomAxes(true);
break;
case Qt::Key_X: // Zoom X axis only
if (event->modifiers() & Qt::ShiftModifier) {
zoomXAxis(false); // upper case X -> Zoom out
} else {
zoomXAxis(true); // lower case x -> Zoom in
}
break;
case Qt::Key_Y: // Zoom Y axis only
if (event->modifiers() & Qt::ShiftModifier) {
zoomYAxis(false); // upper case Y -> Zoom out
} else {
zoomYAxis(true); // lower case y -> Zoom in
}
break;
case Qt::Key_Right:
case Qt::Key_L:
panAxes(pan_pixels, 0);
break;
case Qt::Key_Left:
case Qt::Key_H:
panAxes(-1 * pan_pixels, 0);
break;
case Qt::Key_Up:
case Qt::Key_K:
panAxes(0, pan_pixels);
break;
case Qt::Key_Down:
case Qt::Key_J:
panAxes(0, -1 * pan_pixels);
break;
case Qt::Key_PageUp:
panAxes(0, 20 * pan_pixels);
break;
case Qt::Key_PageDown:
panAxes(0, -20 * pan_pixels);
break;
case Qt::Key_Space:
toggleTracerStyle(false);
break;
case Qt::Key_0:
case Qt::Key_ParenRight: // Shifted 0 on U.S. keyboards
case Qt::Key_Home:
case Qt::Key_R:
resetAxes();
break;
case Qt::Key_G:
on_actionGoToPacket_triggered();
break;
case Qt::Key_T:
// on_actionToggleTimeOrigin_triggered();
break;
case Qt::Key_Z:
on_actionDragZoom_triggered();
break;
case Qt::Key_D:
on_actionSwitchDirection_triggered();
break;
}
WiresharkDialog::keyPressEvent(event);
}
void LteRlcGraphDialog::zoomAxes(bool in)
{
QCustomPlot *rp = ui->rlcPlot;
double h_factor = rp->axisRect()->rangeZoomFactor(Qt::Horizontal);
double v_factor = rp->axisRect()->rangeZoomFactor(Qt::Vertical);
if (!in) {
h_factor = pow(h_factor, -1);
v_factor = pow(v_factor, -1);
}
if (in) {
// Don't want to zoom in *too* far on y axis.
if (rp->yAxis->range().size() < 10) {
return;
}
}
else {
// Don't want to zoom out *too* far on y axis.
if (rp->yAxis->range().size() > (65536+10)) {
return;
}
}
rp->xAxis->scaleRange(h_factor, rp->xAxis->range().center());
rp->yAxis->scaleRange(v_factor, rp->yAxis->range().center());
rp->replot(QCustomPlot::rpQueuedReplot);
}
void LteRlcGraphDialog::zoomXAxis(bool in)
{
QCustomPlot *rp = ui->rlcPlot;
double h_factor = rp->axisRect()->rangeZoomFactor(Qt::Horizontal);
if (!in) {
h_factor = pow(h_factor, -1);
}
rp->xAxis->scaleRange(h_factor, rp->xAxis->range().center());
rp->replot(QCustomPlot::rpQueuedReplot);
}
void LteRlcGraphDialog::zoomYAxis(bool in)
{
QCustomPlot *rp = ui->rlcPlot;
double v_factor = rp->axisRect()->rangeZoomFactor(Qt::Vertical);
if (in) {
// Don't want to zoom in *too* far on y axis.
if (rp->yAxis->range().size() < 10) {
return;
}
}
else {
// Don't want to zoom out *too* far on y axis.
if (rp->yAxis->range().size() > (65536+10)) {
return;
}
}
if (!in) {
v_factor = pow(v_factor, -1);
}
rp->yAxis->scaleRange(v_factor, rp->yAxis->range().center());
rp->replot(QCustomPlot::rpQueuedReplot);
}
void LteRlcGraphDialog::panAxes(int x_pixels, int y_pixels)
{
QCustomPlot *rp = ui->rlcPlot;
double h_pan = 0.0;
double v_pan = 0.0;
// Don't scroll up beyond max range, or below 0
if (((y_pixels > 0) && (rp->yAxis->range().upper > 65536)) ||
((y_pixels < 0) && (rp->yAxis->range().lower < 0))) {
return;
}
// Don't scroll left beyond 0. Arguably should be time of first segment.
if ((x_pixels < 0) && (rp->xAxis->range().lower < 0)) {
return;
}
h_pan = rp->xAxis->range().size() * x_pixels / rp->xAxis->axisRect()->width();
v_pan = rp->yAxis->range().size() * y_pixels / rp->yAxis->axisRect()->height();
// The GTK+ version won't pan unless we're zoomed. Should we do the same here?
if (h_pan) {
rp->xAxis->moveRange(h_pan);
rp->replot(QCustomPlot::rpQueuedReplot);
}
if (v_pan) {
rp->yAxis->moveRange(v_pan);
rp->replot(QCustomPlot::rpQueuedReplot);
}
}
// Given a selected rect in pixels, work out what this should be in graph units.
// Don't accidentally zoom into a 1x1 rect if you happen to click on the graph
// in zoom mode.
const int min_zoom_pixels_ = 20;
QRectF LteRlcGraphDialog::getZoomRanges(QRect zoom_rect)
{
QRectF zoom_ranges = QRectF();
if (zoom_rect.width() < min_zoom_pixels_ && zoom_rect.height() < min_zoom_pixels_) {
return zoom_ranges;
}
QCustomPlot *rp = ui->rlcPlot;
QRect zr = zoom_rect.normalized();
QRect ar = rp->axisRect()->rect();
if (ar.intersects(zr)) {
QRect zsr = ar.intersected(zr);
zoom_ranges.setX(rp->xAxis->range().lower
+ rp->xAxis->range().size() * (zsr.left() - ar.left()) / ar.width());
zoom_ranges.setWidth(rp->xAxis->range().size() * zsr.width() / ar.width());
// QRects grow down
zoom_ranges.setY(rp->yAxis->range().lower
+ rp->yAxis->range().size() * (ar.bottom() - zsr.bottom()) / ar.height());
zoom_ranges.setHeight(rp->yAxis->range().size() * zsr.height() / ar.height());
}
return zoom_ranges;
}
void LteRlcGraphDialog::graphClicked(QMouseEvent *event)
{
QCustomPlot *rp = ui->rlcPlot;
if (event->button() == Qt::RightButton) {
// XXX We should find some way to get rlcPlot to handle a
// contextMenuEvent instead.
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
ctx_menu_->popup(event->globalPosition().toPoint());
#else
ctx_menu_->popup(event->globalPos());
#endif
} else if (mouse_drags_) {
if (rp->axisRect()->rect().contains(event->pos())) {
rp->setCursor(QCursor(Qt::ClosedHandCursor));
}
on_actionGoToPacket_triggered();
} else {
if (!rubber_band_) {
rubber_band_ = new QRubberBand(QRubberBand::Rectangle, rp);
}
rb_origin_ = event->pos();
rubber_band_->setGeometry(QRect(rb_origin_, QSize()));
rubber_band_->show();
}
rp->setFocus();
}
void LteRlcGraphDialog::mouseMoved(QMouseEvent *event)
{
QCustomPlot *rp = ui->rlcPlot;
Qt::CursorShape shape = Qt::ArrowCursor;
// Set the cursor shape.
if (event) {
if (event->buttons().testFlag(Qt::LeftButton)) {
if (mouse_drags_) {
shape = Qt::ClosedHandCursor;
} else {
shape = Qt::CrossCursor;
}
} else if (rp->axisRect()->rect().contains(event->pos())) {
if (mouse_drags_) {
shape = Qt::OpenHandCursor;
} else {
shape = Qt::CrossCursor;
}
}
rp->setCursor(QCursor(shape));
}
// Trying to let 'hint' grow efficiently. Still pretty slow for a dense graph...
QString hint;
hint.reserve(128);
hint = "<small><i>";
if (mouse_drags_) {
double tr_key = tracer_->position->key();
struct rlc_segment *packet_seg = NULL;
packet_num_ = 0;
// XXX If we have multiple packets with the same timestamp tr_key
// may not return the packet we want. It might be possible to fudge
// unique keys using nextafter().
if (event && tracer_->graph() && tracer_->position->axisRect()->rect().contains(event->pos())) {
packet_seg = time_stamp_map_.value(tr_key, NULL);
}
if (!packet_seg) {
tracer_->setVisible(false);
hint += "Hover over the graph for details. </i></small>";
ui->hintLabel->setText(hint);
ui->rlcPlot->replot(QCustomPlot::rpQueuedReplot);
return;
}
tracer_->setVisible(true);
packet_num_ = packet_seg->num;
// N.B. because tracer only looks up entries in base_graph_,
// we know that packet_seg will be a data segment, so no need to check
// iscontrolPDU or isResegmented fields.
hint += tr("%1 %2 (%3s seq %4 len %5)")
.arg(cap_file_.capFile() ? tr("Click to select packet") : tr("Packet"))
.arg(packet_num_)
.arg(QString::number(packet_seg->rel_secs + (packet_seg->rel_usecs / 1000000.0), 'g', 4))
.arg(packet_seg->SN)
.arg(packet_seg->pduLength);
tracer_->setGraphKey(ui->rlcPlot->xAxis->pixelToCoord(event->pos().x()));
// Redrawing the whole graph is making the update *very* slow!
// TODO: Is there a way just to draw the parts that may have changed?
// In the GTK version, we displayed the stored pixbuf and draw temporary items on top...
rp->replot(QCustomPlot::rpQueuedReplot);
} else {
if (event && rubber_band_ && rubber_band_->isVisible()) {
// Work out zoom based upon selected region (in pixels).
rubber_band_->setGeometry(QRect(rb_origin_, event->pos()).normalized());
QRectF zoom_ranges = getZoomRanges(QRect(rb_origin_, event->pos()));
if (zoom_ranges.width() > 0.0 && zoom_ranges.height() > 0.0) {
hint += tr("Release to zoom, x = %1 to %2, y = %3 to %4")
.arg(zoom_ranges.x())
.arg(zoom_ranges.x() + zoom_ranges.width())
.arg(zoom_ranges.y())
.arg(zoom_ranges.y() + zoom_ranges.height());
} else {
hint += tr("Unable to select range.");
}
} else {
hint += tr("Click to select a portion of the graph.");
}
}
hint.append("</i></small>");
ui->hintLabel->setText(hint);
}
void LteRlcGraphDialog::mouseReleased(QMouseEvent *event)
{
QCustomPlot *rp = ui->rlcPlot;
if (rubber_band_) {
rubber_band_->hide();
if (!mouse_drags_) {
// N.B. work out range to zoom to *before* resetting axes.
QRectF zoom_ranges = getZoomRanges(QRect(rb_origin_, event->pos()));
resetAxes();
if (zoom_ranges.width() > 0.0 && zoom_ranges.height() > 0.0) {
rp->xAxis->setRangeLower(zoom_ranges.x());
rp->xAxis->setRangeUpper(zoom_ranges.x() + zoom_ranges.width());
rp->yAxis->setRangeLower(zoom_ranges.y());
rp->yAxis->setRangeUpper(zoom_ranges.y() + zoom_ranges.height());
rp->replot();
}
}
} else if (rp->cursor().shape() == Qt::ClosedHandCursor) {
rp->setCursor(QCursor(Qt::OpenHandCursor));
}
}
void LteRlcGraphDialog::resetAxes()
{
QCustomPlot *rp = ui->rlcPlot;
QCPRange x_range = rp->xAxis->scaleType() == QCPAxis::stLogarithmic ?
rp->xAxis->range().sanitizedForLogScale() : rp->xAxis->range();
double pixel_pad = 10.0; // per side
rp->rescaleAxes(true);
base_graph_->rescaleValueAxis(false, true);
double axis_pixels = rp->xAxis->axisRect()->width();
rp->xAxis->scaleRange((axis_pixels + (pixel_pad * 2)) / axis_pixels, x_range.center());
axis_pixels = rp->yAxis->axisRect()->height();
rp->yAxis->scaleRange((axis_pixels + (pixel_pad * 2)) / axis_pixels, rp->yAxis->range().center());
rp->replot(QCustomPlot::rpQueuedReplot);
}
void LteRlcGraphDialog::on_actionGoToPacket_triggered()
{
if (tracer_->visible() && cap_file_.capFile() && (packet_num_ > 0)) {
// Signal to the packetlist which frame we want to show.
emit goToPacket(packet_num_);
}
}
void LteRlcGraphDialog::on_actionCrosshairs_triggered()
{
toggleTracerStyle(false);
}
void LteRlcGraphDialog::toggleTracerStyle(bool force_default)
{
if (!tracer_->visible() && !force_default) {
return;
}
QPen sp_pen = ui->rlcPlot->graph(0)->pen();
QCPItemTracer::TracerStyle tstyle = QCPItemTracer::tsCrosshair;
QPen tr_pen = QPen(tracer_->pen());
QColor tr_color = sp_pen.color();
if (force_default || tracer_->style() != QCPItemTracer::tsCircle) {
tstyle = QCPItemTracer::tsCircle;
tr_color.setAlphaF(1.0);
tr_pen.setWidthF(1.5);
} else {
tr_color.setAlphaF(0.5);
tr_pen.setWidthF(1.0);
}
tracer_->setStyle(tstyle);
tr_pen.setColor(tr_color);
tracer_->setPen(tr_pen);
ui->rlcPlot->replot();
}
void LteRlcGraphDialog::on_actionReset_triggered()
{
resetAxes();
}
void LteRlcGraphDialog::on_actionZoomIn_triggered()
{
zoomAxes(true);
}
void LteRlcGraphDialog::on_actionZoomOut_triggered()
{
zoomAxes(false);
}
void LteRlcGraphDialog::on_actionMoveUp10_triggered()
{
panAxes(0, 10);
}
void LteRlcGraphDialog::on_actionMoveUp100_triggered()
{
panAxes(0, 100);
}
void LteRlcGraphDialog::on_actionMoveLeft10_triggered()
{
panAxes(-10, 0);
}
void LteRlcGraphDialog::on_actionMoveRight10_triggered()
{
panAxes(10, 0);
}
void LteRlcGraphDialog::on_actionMoveDown10_triggered()
{
panAxes(0, -10);
}
void LteRlcGraphDialog::on_actionMoveDown100_triggered()
{
panAxes(0, -100);
}
void LteRlcGraphDialog::on_actionMoveUp1_triggered()
{
panAxes(0, 1);
}
void LteRlcGraphDialog::on_actionMoveLeft1_triggered()
{
panAxes(-1, 0);
}
void LteRlcGraphDialog::on_actionMoveRight1_triggered()
{
panAxes(1, 0);
}
void LteRlcGraphDialog::on_actionMoveDown1_triggered()
{
panAxes(0, -1);
}
void LteRlcGraphDialog::on_actionSwitchDirection_triggered()
{
// Channel settings exactly the same, except change direction.
// N.B. do not fail and close if there are no packets in opposite direction.
setChannelInfo(graph_.ueid,
graph_.rlcMode,
graph_.channelType,
graph_.channelId,
!graph_.direction,
true /* maybe_empty */);
}
// Switch between zoom/drag.
void LteRlcGraphDialog::on_actionDragZoom_triggered()
{
if (mouse_drags_) {
ui->zoomRadioButton->toggle();
} else {
ui->dragRadioButton->toggle();
}
}
void LteRlcGraphDialog::on_dragRadioButton_toggled(bool checked)
{
if (checked) {
mouse_drags_ = true;
}
ui->rlcPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
}
void LteRlcGraphDialog::on_zoomRadioButton_toggled(bool checked)
{
if (checked) mouse_drags_ = false;
ui->rlcPlot->setInteractions(QCP::Interactions());
}
void LteRlcGraphDialog::on_resetButton_clicked()
{
resetAxes();
}
void LteRlcGraphDialog::on_otherDirectionButton_clicked()
{
on_actionSwitchDirection_triggered();
}
// Prompt for filename/format to save graph to.
// N.B. Copied from tcp_stream_dialog.cpp
void LteRlcGraphDialog::on_buttonBox_accepted()
{
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(this, 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 = ui->rlcPlot->savePdf(file_name);
} else if (extension.compare(png_filter) == 0) {
save_ok = ui->rlcPlot->savePng(file_name);
} else if (extension.compare(bmp_filter) == 0) {
save_ok = ui->rlcPlot->saveBmp(file_name);
} else if (extension.compare(jpeg_filter) == 0) {
save_ok = ui->rlcPlot->saveJpg(file_name);
}
// else error dialog?
if (save_ok) {
mainApp->setLastOpenDirFromFilename(file_name);
}
}
}
// No need to register tap listeners here. This is done
// in calls to the common functions in ui/tap-rlc-graph.c |
C/C++ | wireshark/ui/qt/lte_rlc_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 LTE_RLC_GRAPH_DIALOG_H
#define LTE_RLC_GRAPH_DIALOG_H
#include "wireshark_dialog.h"
#include <ui/tap-rlc-graph.h>
#include <ui/qt/widgets/qcustomplot.h>
class QMenu;
class QRubberBand;
namespace Ui {
class LteRlcGraphDialog;
}
class LteRlcGraphDialog : public WiresharkDialog
{
Q_OBJECT
public:
// TODO: will need to add another constructor option to give channel explicitly,
// rather than find in currently selected packet, for when launch graph from
// RLC statistics dialog.
explicit LteRlcGraphDialog(QWidget &parent, CaptureFile &cf, bool channelKnown);
~LteRlcGraphDialog();
void setChannelInfo(guint16 ueid, guint8 rlcMode,
guint16 channelType, guint16 channelId, guint8 direction,
bool maybe_empty=false);
signals:
void goToPacket(int packet_num);
protected:
void showEvent(QShowEvent *event);
void keyPressEvent(QKeyEvent *event);
private:
Ui::LteRlcGraphDialog *ui;
bool mouse_drags_;
QRubberBand *rubber_band_;
QPoint rb_origin_;
QMenu *ctx_menu_;
// Data gleaned directly from tapping packets (shared with gtk impl)
struct rlc_graph graph_;
// Data
QMultiMap<double, struct rlc_segment *> time_stamp_map_;
QMap<double, struct rlc_segment *> sequence_num_map_;
QCPGraph *base_graph_; // Clickable packets
QCPGraph *reseg_graph_;
QCPGraph *acks_graph_;
QCPGraph *nacks_graph_;
QCPItemTracer *tracer_;
guint32 packet_num_;
void completeGraph(bool may_be_empty=false);
bool compareHeaders(rlc_segment *seg);
void findChannel(bool may_fail=false);
void fillGraph();
void zoomAxes(bool in);
void zoomXAxis(bool in);
void zoomYAxis(bool in);
void panAxes(int x_pixels, int y_pixels);
QRectF getZoomRanges(QRect zoom_rect);
void toggleTracerStyle(bool force_default);
private slots:
void graphClicked(QMouseEvent *event);
void mouseMoved(QMouseEvent *event);
void mouseReleased(QMouseEvent *event);
void resetAxes();
void on_dragRadioButton_toggled(bool checked);
void on_zoomRadioButton_toggled(bool checked);
void on_resetButton_clicked();
void on_otherDirectionButton_clicked();
void on_actionReset_triggered();
void on_actionZoomIn_triggered();
void on_actionZoomOut_triggered();
void on_actionMoveUp10_triggered();
void on_actionMoveLeft10_triggered();
void on_actionMoveRight10_triggered();
void on_actionMoveDown10_triggered();
void on_actionMoveUp1_triggered();
void on_actionMoveLeft1_triggered();
void on_actionMoveRight1_triggered();
void on_actionMoveDown1_triggered();
void on_actionDragZoom_triggered();
void on_actionMoveUp100_triggered();
void on_actionMoveDown100_triggered();
void on_actionGoToPacket_triggered();
void on_actionCrosshairs_triggered();
void on_actionSwitchDirection_triggered();
void on_buttonBox_accepted();
};
#endif // LTE_RLC_GRAPH_DIALOG_H |
User Interface | wireshark/ui/qt/lte_rlc_graph_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>LteRlcGraphDialog</class>
<widget class="QDialog" name="LteRlcGraphDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>660</width>
<height>447</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout" stretch="1,0,0,0">
<item>
<widget class="QCustomPlot" name="rlcPlot" native="true"/>
</item>
<item>
<widget class="QLabel" name="hintLabel">
<property name="toolTip">
<string><html><head/><body>
<h3>Valuable and amazing time-saving keyboard shortcuts</h3>
<table><tbody>
<tr><th>+</th><td>Zoom in</td></th>
<tr><th>-</th><td>Zoom out</td></th>
<tr><th>0</th><td>Reset graph to its initial state</td></th>
<tr><th>→</th><td>Move right 10 pixels</td></th>
<tr><th>←</th><td>Move left 10 pixels</td></th>
<tr><th>↑</th><td>Move up 10 pixels</td></th>
<tr><th>↓</th><td>Move down 10 pixels</td></th>
<tr><th><i>Shift+</i>→</th><td>Move right 1 pixel</td></th>
<tr><th><i>Shift+</i>←</th><td>Move left 1 pixel</td></th>
<tr><th><i>Shift+</i>↑</th><td>Move up 1 pixel</td></th>
<tr><th><i>Shift+</i>↓</th><td>Move down 1 pixel</td></th>
<tr><th>g</th><td>Go to packet under cursor</td></th>
<tr><th>z</th><td>Toggle mouse drag / zoom</td></th>
<tr><th>t</th><td>Toggle capture / session time origin</td></th>
<tr><th>Space</th><td>Toggle crosshairs</td></th>
</tbody></table>
</body></html></string>
</property>
<property name="text">
<string/>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="mouseLabel">
<property name="text">
<string>Mouse</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="dragRadioButton">
<property name="toolTip">
<string>Drag using the mouse button.</string>
</property>
<property name="text">
<string>drags</string>
</property>
<property name="checkable">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="zoomRadioButton">
<property name="toolTip">
<string>Select using the mouse button.</string>
</property>
<property name="text">
<string>zooms</string>
</property>
<property name="checkable">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<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="QPushButton" name="resetButton">
<property name="toolTip">
<string><html><head/><body><p>Reset the graph to its initial state.</p></body></html></string>
</property>
<property name="text">
<string>Reset</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="otherDirectionButton">
<property name="toolTip">
<string><html><head/><body><p>Switch the direction of the connection (view the opposite flow).</p></body></html></string>
</property>
<property name="text">
<string>Switch Direction</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::Close|QDialogButtonBox::Help|QDialogButtonBox::Save</set>
</property>
</widget>
</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="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="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="actionMoveUp100">
<property name="text">
<string>Move Up 100 Pixels</string>
</property>
<property name="toolTip">
<string>Move Up 100 Pixels</string>
</property>
<property name="shortcut">
<string>PgUp</string>
</property>
</action>
<action name="actionMoveDown100">
<property name="text">
<string>Move Up 100 Pixels</string>
</property>
<property name="toolTip">
<string>Move Up 100 Pixels</string>
</property>
<property name="shortcut">
<string>PgDown</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="actionZoomInX">
<property name="text">
<string>Zoom In X Axis</string>
</property>
<property name="toolTip">
<string>Zoom In X Axis</string>
</property>
<property name="shortcut">
<string>X</string>
</property>
</action>
<action name="actionZoomOutY">
<property name="text">
<string>Zoom Out Y Axis</string>
</property>
<property name="toolTip">
<string>Zoom Out Y Axis</string>
</property>
<property name="shortcut">
<string>Shift+Y</string>
</property>
</action>
<action name="actionZoomInY">
<property name="text">
<string>Zoom In Y Axis</string>
</property>
<property name="toolTip">
<string>Zoom In Y Axis</string>
</property>
<property name="shortcut">
<string>Y</string>
</property>
</action>
<action name="actionZoomOutX">
<property name="text">
<string>Zoom Out X Axis</string>
</property>
<property name="toolTip">
<string>Zoom Out X Axis</string>
</property>
<property name="shortcut">
<string>Shift+X</string>
</property>
</action>
<action name="actionSwitchDirection">
<property name="text">
<string>Switch Direction</string>
</property>
<property name="toolTip">
<string>Switch direction (swap between UL and DL)</string>
</property>
<property name="shortcut">
<string>D</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>LteRlcGraphDialog</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>LteRlcGraphDialog</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/lte_rlc_statistics_dialog.cpp | /* lte_rlc_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 "lte_rlc_statistics_dialog.h"
#include <epan/packet.h>
#include <epan/strutil.h>
#include <epan/tap.h>
#include <epan/dissectors/packet-rlc-lte.h>
#include <QFormLayout>
#include <QTreeWidgetItem>
#include <QPushButton>
#include "main_application.h"
#include "ui/recent.h"
// TODO: have never tested in a live capture.
enum {
col_ueid_,
col_mode_, // channel only
col_priority_, // channel only
col_ul_frames_,
col_ul_bytes_,
col_ul_mb_s_,
col_ul_acks_,
col_ul_nacks_,
col_ul_missing_,
col_dl_frames_,
col_dl_bytes_,
col_dl_mb_s_,
col_dl_acks_,
col_dl_nacks_,
col_dl_missing_
};
enum {
rlc_ue_row_type_ = 1000,
rlc_channel_row_type_
};
/* Calculate and return a bandwidth figure, in Mbs */
static double calculate_bw(const nstime_t *start_time, const nstime_t *stop_time, guint32 bytes)
{
/* Can only calculate bandwidth if have time delta */
if (memcmp(start_time, stop_time, sizeof(nstime_t)) != 0) {
double elapsed_ms = (((double)stop_time->secs - start_time->secs) * 1000) +
(((double)stop_time->nsecs - start_time->nsecs) / 1000000);
/* Only really meaningful if have a few frames spread over time...
For now at least avoid dividing by something very close to 0.0 */
if (elapsed_ms < 2.0) {
return 0.0f;
}
// N.B. very small values will display as scientific notation, but rather that than show 0
// when there is some traffic..
return ((bytes * 8) / elapsed_ms) / 1000;
}
else {
return 0.0f;
}
}
// Stats kept for one channel.
typedef struct rlc_channel_stats {
guint8 rlcMode;
guint8 priority;
guint16 channelType;
guint16 channelId;
guint32 UL_frames;
guint32 UL_bytes;
nstime_t UL_time_start;
nstime_t UL_time_stop;
gboolean UL_has_data; // i.e. not just ACKs for DL.
guint32 DL_frames;
guint32 DL_bytes;
nstime_t DL_time_start;
nstime_t DL_time_stop;
gboolean DL_has_data; // i.e. not just ACKs for UL.
guint32 UL_acks;
guint32 UL_nacks;
guint32 DL_acks;
guint32 DL_nacks;
guint32 UL_missing;
guint32 DL_missing;
} rlc_channel_stats;
//-------------------------------------------------------------------
// Channel item.
//-------------------------------------------------------------------
class RlcChannelTreeWidgetItem : public QTreeWidgetItem
{
public:
RlcChannelTreeWidgetItem(QTreeWidgetItem *parent,
unsigned ueid,
unsigned mode,
unsigned channelType, unsigned channelId) :
QTreeWidgetItem(parent, rlc_channel_row_type_),
ueid_(ueid),
channelType_(channelType),
channelId_(channelId),
mode_(mode),
priority_(0)
{
QString mode_str;
switch (mode_) {
case RLC_TM_MODE:
mode_str = QObject::tr("TM");
break;
case RLC_UM_MODE:
mode_str = QObject::tr("UM");
break;
case RLC_AM_MODE:
mode_str = QObject::tr("AM");
break;
case RLC_PREDEF:
mode_str = QObject::tr("Predef");
break;
default:
mode_str = QObject::tr("Unknown (%1)").arg(mode_);
break;
}
// Set name of channel.
switch (channelType) {
case CHANNEL_TYPE_CCCH:
setText(col_ueid_, QObject::tr("CCCH"));
break;
case CHANNEL_TYPE_SRB:
setText(col_ueid_, QObject::tr("SRB-%1").arg(channelId));
break;
case CHANNEL_TYPE_DRB:
setText(col_ueid_, QObject::tr("DRB-%1").arg(channelId));
break;
default:
setText(col_ueid_, QObject::tr("Unknown"));
break;
}
// Zero out stats.
memset(&stats_, 0, sizeof(stats_));
// TODO: could change, but should only reset string if changes.
setText(col_mode_, mode_str);
}
// Update UE/channels from tap info.
void update(const rlc_lte_tap_info *tap_info) {
// Copy these fields into UE stats.
if (tap_info->rlcMode != stats_.rlcMode) {
stats_.rlcMode = tap_info->rlcMode;
// TODO: update the column string!
}
// TODO: these 2 really shouldn't change!!
stats_.channelType = tap_info->channelType;
stats_.channelId = tap_info->channelId;
if (tap_info->priority != 0) {
priority_ = tap_info->priority;
// TODO: update the column string!
}
if (tap_info->direction == DIRECTION_UPLINK) {
// Update time range.
if (stats_.UL_frames == 0) {
stats_.UL_time_start = tap_info->rlc_lte_time;
}
stats_.UL_time_stop = tap_info->rlc_lte_time;
stats_.UL_frames++;
stats_.UL_bytes += tap_info->pduLength;
stats_.UL_nacks += tap_info->noOfNACKs;
stats_.UL_missing += tap_info->missingSNs;
if (tap_info->isControlPDU) {
stats_.UL_acks++;
}
else {
stats_.UL_has_data = TRUE;
}
}
else {
// Update time range.
if (stats_.DL_frames == 0) {
stats_.DL_time_start = tap_info->rlc_lte_time;
}
stats_.DL_time_stop = tap_info->rlc_lte_time;
stats_.DL_frames++;
stats_.DL_bytes += tap_info->pduLength;
stats_.DL_nacks += tap_info->noOfNACKs;
stats_.DL_missing += tap_info->missingSNs;
if (tap_info->isControlPDU) {
stats_.DL_acks++;
}
else {
stats_.DL_has_data = TRUE;
}
}
}
// Draw channel entry.
void draw() {
// Calculate bandwidths.
double UL_bw = calculate_bw(&stats_.UL_time_start,
&stats_.UL_time_stop,
stats_.UL_bytes);
double DL_bw = calculate_bw(&stats_.DL_time_start,
&stats_.DL_time_stop,
stats_.DL_bytes);
// Priority
setText(col_priority_, QString::number(priority_));
// Uplink.
setText(col_ul_frames_, QString::number(stats_.UL_frames));
setText(col_ul_bytes_, QString::number(stats_.UL_bytes));
setText(col_ul_mb_s_, QString::number(UL_bw));
setText(col_ul_acks_, QString::number(stats_.UL_acks));
setText(col_ul_nacks_, QString::number(stats_.UL_nacks));
setText(col_ul_missing_, QString::number(stats_.UL_missing));
// Downlink.
setText(col_dl_frames_, QString::number(stats_.DL_frames));
setText(col_dl_bytes_, QString::number(stats_.DL_bytes));
setText(col_dl_mb_s_, QString::number(DL_bw));
setText(col_dl_acks_, QString::number(stats_.DL_acks));
setText(col_dl_nacks_, QString::number(stats_.DL_nacks));
setText(col_dl_missing_, QString::number(stats_.DL_missing));
}
bool operator< (const QTreeWidgetItem &other) const
{
if (other.type() != rlc_channel_row_type_) return QTreeWidgetItem::operator< (other);
const RlcChannelTreeWidgetItem *other_row = static_cast<const RlcChannelTreeWidgetItem *>(&other);
// Switch by selected column.
switch (treeWidget()->sortColumn()) {
case col_ueid_:
// This is channel name. Rank CCCH before SRB before DRB, then channel ID.
return channelRank() < other_row->channelRank();
case col_mode_:
return mode_ < other_row->mode_;
case col_priority_:
return priority_ < other_row->priority_;
default:
break;
}
return QTreeWidgetItem::operator< (other);
}
// Filter expression for channel.
const QString filterExpression(bool showSR, bool showRACH) {
// Create an expression to match with all traffic for this UE.
QString filter_expr;
// Are we taking RLC PDUs from MAC, or not?
if (!recent.gui_rlc_use_pdus_from_mac) {
filter_expr += QString("not mac-lte and ");
}
else {
filter_expr += QString("mac-lte and ");
}
if (showSR) {
filter_expr += QString("(mac-lte.sr-req and mac-lte.ueid == %1) or (").arg(ueid_);
}
if (showRACH) {
filter_expr += QString("(mac-lte.rar or (mac-lte.preamble-sent and mac-lte.ueid == %1)) or (").arg(ueid_);
}
// Main part of expression.
filter_expr += QString("rlc-lte.ueid==%1 and rlc-lte.channel-type == %2").
arg(ueid_).arg(channelType_);
if ((channelType_ == CHANNEL_TYPE_SRB) || (channelType_ == CHANNEL_TYPE_DRB)) {
filter_expr += QString(" and rlc-lte.channel-id == %1").arg(channelId_);
}
// Close () if open because of SR
if (showSR) {
filter_expr += QString(")");
}
// Close () if open because of RACH
if (showRACH) {
filter_expr += QString(")");
}
return filter_expr;
}
// Accessors (queried for launching graph)
unsigned get_ueid() const { return ueid_; }
unsigned get_channelType() const { return channelType_; }
unsigned get_channelId() const { return channelId_; }
unsigned get_mode() const { return mode_; }
bool hasULData() const { return stats_.UL_has_data != 0; }
bool hasDLData() const { return stats_.DL_has_data != 0; }
QList<QVariant> rowData() const
{
// Don't output anything for channel entries when exporting to text.
return QList<QVariant>();
}
private:
unsigned ueid_;
unsigned channelType_;
unsigned channelId_;
unsigned mode_;
unsigned priority_;
unsigned channelRank() const
{
switch (channelType_) {
case CHANNEL_TYPE_CCCH:
return 0;
case CHANNEL_TYPE_SRB:
return channelId_;
case CHANNEL_TYPE_DRB:
return 3 + channelId_;
default:
// Shouldn't really get here..
return 0;
}
}
rlc_channel_stats stats_;
};
// Stats for one UE. TODO: private to class?
typedef struct rlc_ue_stats {
guint32 UL_frames;
guint32 UL_total_bytes;
nstime_t UL_time_start;
nstime_t UL_time_stop;
guint32 UL_total_acks;
guint32 UL_total_nacks;
guint32 UL_total_missing;
guint32 DL_frames;
guint32 DL_total_bytes;
nstime_t DL_time_start;
nstime_t DL_time_stop;
guint32 DL_total_acks;
guint32 DL_total_nacks;
guint32 DL_total_missing;
} rlc_ue_stats;
//-------------------------------------------------------------------
// UE item.
//-------------------------------------------------------------------
class RlcUeTreeWidgetItem : public QTreeWidgetItem
{
public:
RlcUeTreeWidgetItem(QTreeWidget *parent, const rlc_lte_tap_info *rlt_info) :
QTreeWidgetItem (parent, rlc_ue_row_type_),
ueid_(0)
{
ueid_ = rlt_info->ueid;
setText(col_ueid_, QString::number(ueid_));
// We create RlcChannelTreeWidgetItems when first data on new channel is seen.
// Of course, there will be a channel associated with the PDU
// that causes this UE item to be created...
memset(&stats_, 0, sizeof(stats_));
CCCH_stats_ = NULL;
for (int srb=0; srb < 2; srb++) {
srb_stats_[srb] = NULL;
}
for (int drb=0; drb < 32; drb++) {
drb_stats_[drb] = NULL;
}
}
// Does UE match?
bool isMatch(const rlc_lte_tap_info *rlt_info) {
return ueid_ == rlt_info->ueid;
}
// Update UE/channels from tap info.
void update(const rlc_lte_tap_info *tap_info) {
// Are we ignoring RLC frames that were found in MAC frames, or only those
// that were logged separately?
if ((!recent.gui_rlc_use_pdus_from_mac && tap_info->loggedInMACFrame) ||
(recent.gui_rlc_use_pdus_from_mac && !tap_info->loggedInMACFrame)) {
return;
}
// TODO: update title with number of UEs and frames like MAC does?
// N.B. not really expecting to see common stats - ignoring them.
switch (tap_info->channelType) {
case CHANNEL_TYPE_BCCH_BCH:
case CHANNEL_TYPE_BCCH_DL_SCH:
case CHANNEL_TYPE_PCCH:
return;
default:
// Drop through for UE-specific.
break;
}
// UE-level traffic stats.
if (tap_info->direction == DIRECTION_UPLINK) {
// Update time range.
if (stats_.UL_frames == 0) {
stats_.UL_time_start = tap_info->rlc_lte_time;
}
stats_.UL_time_stop = tap_info->rlc_lte_time;
stats_.UL_frames++;
stats_.UL_total_bytes += tap_info->pduLength;
// Status PDU counters.
if (tap_info->isControlPDU) {
stats_.UL_total_acks++;
stats_.UL_total_nacks += tap_info->noOfNACKs;
}
stats_.UL_total_missing += tap_info->missingSNs;
}
else {
// Update time range.
if (stats_.DL_frames == 0) {
stats_.DL_time_start = tap_info->rlc_lte_time;
}
stats_.DL_time_stop = tap_info->rlc_lte_time;
stats_.DL_frames++;
stats_.DL_total_bytes += tap_info->pduLength;
// Status PDU counters.
if (tap_info->isControlPDU) {
stats_.DL_total_acks++;
stats_.DL_total_nacks += tap_info->noOfNACKs;
}
stats_.DL_total_missing += tap_info->missingSNs;
}
RlcChannelTreeWidgetItem *channel_item;
// Find or create tree item for this channel.
switch (tap_info->channelType) {
case CHANNEL_TYPE_CCCH:
channel_item = CCCH_stats_;
if (channel_item == NULL) {
channel_item = CCCH_stats_ =
new RlcChannelTreeWidgetItem(this, tap_info->ueid, RLC_TM_MODE,
tap_info->channelType, tap_info->channelId);
}
break;
case CHANNEL_TYPE_SRB:
channel_item = srb_stats_[tap_info->channelId-1];
if (channel_item == NULL) {
channel_item = srb_stats_[tap_info->channelId-1] =
new RlcChannelTreeWidgetItem(this, tap_info->ueid, RLC_AM_MODE,
tap_info->channelType, tap_info->channelId);
}
break;
case CHANNEL_TYPE_DRB:
channel_item = drb_stats_[tap_info->channelId-1];
if (channel_item == NULL) {
channel_item = drb_stats_[tap_info->channelId-1] =
new RlcChannelTreeWidgetItem(this, tap_info->ueid, tap_info->rlcMode,
tap_info->channelType, tap_info->channelId);
}
break;
default:
// Shouldn't get here...
return;
}
// Update channel with tap_info.
channel_item->update(tap_info);
}
// Draw UE entry
void draw() {
// Fixed fields only drawn once from constructor so don't redraw here.
/* Calculate bandwidths. */
double UL_bw = calculate_bw(&stats_.UL_time_start,
&stats_.UL_time_stop,
stats_.UL_total_bytes);
double DL_bw = calculate_bw(&stats_.DL_time_start,
&stats_.DL_time_stop,
stats_.DL_total_bytes);
// Uplink.
setText(col_ul_frames_, QString::number(stats_.UL_frames));
setText(col_ul_bytes_, QString::number(stats_.UL_total_bytes));
setText(col_ul_mb_s_, QString::number(UL_bw));
setText(col_ul_acks_, QString::number(stats_.UL_total_acks));
setText(col_ul_nacks_, QString::number(stats_.UL_total_nacks));
setText(col_ul_missing_, QString::number(stats_.UL_total_missing));
// Downlink.
setText(col_dl_frames_, QString::number(stats_.DL_frames));
setText(col_dl_bytes_, QString::number(stats_.DL_total_bytes));
setText(col_dl_mb_s_, QString::number(DL_bw));
setText(col_dl_acks_, QString::number(stats_.DL_total_acks));
setText(col_dl_nacks_, QString::number(stats_.DL_total_nacks));
setText(col_dl_missing_, QString::number(stats_.DL_total_missing));
// Call draw() for each channel for this UE.
if (CCCH_stats_ != NULL) {
CCCH_stats_->draw();
}
for (int srb=0; srb < 2; srb++) {
if (srb_stats_[srb] != NULL) {
srb_stats_[srb]->draw();
}
}
for (int drb=0; drb < 32; drb++) {
if (drb_stats_[drb] != NULL) {
drb_stats_[drb]->draw();
}
}
}
bool operator< (const QTreeWidgetItem &other) const
{
if (other.type() != rlc_ue_row_type_) return QTreeWidgetItem::operator< (other);
const RlcUeTreeWidgetItem *other_row = static_cast<const RlcUeTreeWidgetItem *>(&other);
switch (treeWidget()->sortColumn()) {
case col_ueid_:
return ueid_ < other_row->ueid_;
default:
break;
}
return QTreeWidgetItem::operator< (other);
}
// Filter expression for UE.
const QString filterExpression(bool showSR, bool showRACH) {
// Create an expression to match with all traffic for this UE.
QString filter_expr;
// Are we taking RLC PDUs from MAC, or not?
if (!recent.gui_rlc_use_pdus_from_mac) {
filter_expr += QString("not mac-lte and ");
}
else {
filter_expr += QString("mac-lte and ");
}
if (showSR) {
filter_expr += QString("(mac-lte.sr-req and mac-lte.ueid == %1) or (").arg(ueid_);
}
if (showRACH) {
filter_expr += QString("(mac-lte.rar or (mac-lte.preamble-sent and mac-lte.ueid == %1)) or (").arg(ueid_);
}
filter_expr += QString("rlc-lte.ueid==%1").arg(ueid_);
// Close () if open because of SR
if (showSR) {
filter_expr += QString(")");
}
// Close () if open because of RACH
if (showRACH) {
filter_expr += QString(")");
}
return filter_expr;
}
QList<QVariant> rowData() const
{
QList<QVariant> row_data;
// Key fields.
// After the UEId field, there are 2 unused columns for UE entries.
row_data << ueid_ << QString("") << QString("");
// UL
row_data << stats_.UL_frames << stats_.UL_total_bytes
<< calculate_bw(&stats_.UL_time_start,
&stats_.UL_time_stop,
stats_.UL_total_bytes)
<< stats_.UL_total_acks << stats_.UL_total_nacks << stats_.UL_total_missing;
// DL
row_data << stats_.DL_frames << stats_.DL_total_bytes
<< calculate_bw(&stats_.DL_time_start,
&stats_.DL_time_stop,
stats_.DL_total_bytes)
<< stats_.DL_total_acks << stats_.DL_total_nacks << stats_.DL_total_missing;
return row_data;
}
private:
unsigned ueid_;
rlc_ue_stats stats_;
// Channel counters stored in channel sub-items.
RlcChannelTreeWidgetItem* CCCH_stats_;
RlcChannelTreeWidgetItem* srb_stats_[2];
RlcChannelTreeWidgetItem* drb_stats_[32];
};
// Only the first 3 columns headings differ between UE and channel rows.
static const QString ue_col_0_title_ = QObject::tr("UE Id");
static const QString ue_col_1_title_ = QObject::tr("");
static const QString ue_col_2_title_ = QObject::tr("");
static const QString channel_col_0_title_ = QObject::tr("Name");
static const QString channel_col_1_title_ = QObject::tr("Mode");
static const QString channel_col_2_title_ = QObject::tr("Priority");
//------------------------------------------------------------------------------------------
// Dialog
// Constructor.
LteRlcStatisticsDialog::LteRlcStatisticsDialog(QWidget &parent, CaptureFile &cf, const char *filter) :
TapParameterDialog(parent, cf, HELP_STATS_LTE_MAC_TRAFFIC_DIALOG),
cf_(cf),
packet_count_(0)
{
setWindowSubtitle(tr("LTE RLC Statistics"));
loadGeometry((parent.width() * 5) / 5, (parent.height() * 3) / 4, "LTERLCStatisticsDialog");
// Create a grid for filtering-related widgetsto also appear in layout.
int filter_controls_layout_idx = verticalLayout()->indexOf(filterLayout()->widget());
QGridLayout *filter_controls_grid = new QGridLayout();
// Insert into the vertical layout
verticalLayout()->insertLayout(filter_controls_layout_idx, filter_controls_grid);
int one_em = fontMetrics().height();
filter_controls_grid->setColumnMinimumWidth(2, one_em * 2);
filter_controls_grid->setColumnStretch(2, 1);
filter_controls_grid->setColumnMinimumWidth(5, one_em * 2);
filter_controls_grid->setColumnStretch(5, 1);
// Add individual controls into the grid
launchULGraph_ = new QPushButton(QString("Launch UL Graph"));
launchULGraph_->setEnabled(false);
filter_controls_grid->addWidget(launchULGraph_);
connect(launchULGraph_, SIGNAL(clicked()), this, SLOT(launchULGraphButtonClicked()));
launchDLGraph_ = new QPushButton(QString("Launch DL Graph"));
launchDLGraph_->setEnabled(false);
filter_controls_grid->addWidget(launchDLGraph_);
connect(launchDLGraph_, SIGNAL(clicked()), this, SLOT(launchDLGraphButtonClicked()));
showSRFilterCheckBox_ = new QCheckBox(tr("Include SR frames in filter"));
filter_controls_grid->addWidget(showSRFilterCheckBox_);
showRACHFilterCheckBox_ = new QCheckBox(tr("Include RACH frames in filter"));
filter_controls_grid->addWidget(showRACHFilterCheckBox_);
useRLCFramesFromMacCheckBox_ = new QCheckBox(tr("Use RLC frames only from MAC frames"));
useRLCFramesFromMacCheckBox_->setCheckState(recent.gui_rlc_use_pdus_from_mac ?
Qt::Checked :
Qt::Unchecked);
connect(useRLCFramesFromMacCheckBox_, SIGNAL(clicked(bool)), this,
SLOT(useRLCFramesFromMacCheckBoxToggled(bool)));
filter_controls_grid->addWidget(useRLCFramesFromMacCheckBox_);
QStringList header_labels = QStringList()
<< "" << "" << ""
<< tr("UL Frames") << tr("UL Bytes") << tr("UL MB/s")
<< tr("UL ACKs") << tr("UL NACKs") << tr("UL Missing")
<< tr("DL Frames") << tr("DL Bytes") << tr("DL MB/s")
<< tr("DL ACKs") << tr("DL NACKs") << tr("DL Missing");
statsTreeWidget()->setHeaderLabels(header_labels);
updateHeaderLabels();
statsTreeWidget()->sortByColumn(col_ueid_, Qt::AscendingOrder);
// resizeColumnToContents doesn't work well here, so set sizes manually.
for (int col = 0; col < statsTreeWidget()->columnCount() - 1; col++) {
switch (col) {
case col_ueid_:
statsTreeWidget()->setColumnWidth(col, one_em * 7);
break;
case col_ul_frames_:
case col_dl_frames_:
statsTreeWidget()->setColumnWidth(col, one_em * 5);
break;
case col_ul_acks_:
case col_dl_acks_:
statsTreeWidget()->setColumnWidth(col, one_em * 5);
break;
case col_ul_nacks_:
case col_dl_nacks_:
statsTreeWidget()->setColumnWidth(col, one_em * 6);
break;
case col_ul_missing_:
case col_dl_missing_:
statsTreeWidget()->setColumnWidth(col, one_em * 7);
break;
case col_ul_mb_s_:
case col_dl_mb_s_:
statsTreeWidget()->setColumnWidth(col, one_em * 6);
break;
default:
// The rest are numeric.
statsTreeWidget()->setColumnWidth(col, one_em * 4);
break;
}
}
addFilterActions();
if (filter) {
setDisplayFilter(filter);
}
// Set handler for when the tree item changes to set the appropriate labels.
connect(statsTreeWidget(), SIGNAL(itemSelectionChanged()),
this, SLOT(updateItemSelectionChanged()));
// Set handler for when display filter string is changed.
connect(this, SIGNAL(updateFilter(QString)),
this, SLOT(filterUpdated(QString)));
}
// Destructor.
LteRlcStatisticsDialog::~LteRlcStatisticsDialog()
{
}
void LteRlcStatisticsDialog::tapReset(void *ws_dlg_ptr)
{
LteRlcStatisticsDialog *ws_dlg = static_cast<LteRlcStatisticsDialog *>(ws_dlg_ptr);
if (!ws_dlg) {
return;
}
// Clears/deletes all UEs.
ws_dlg->statsTreeWidget()->clear();
ws_dlg->packet_count_ = 0;
}
// Process the tap info from a dissected RLC PDU.
// Returns TAP_PACKET_REDRAW if a redraw is needed, TAP_PACKET_DONT_REDRAW otherwise.
tap_packet_status LteRlcStatisticsDialog::tapPacket(void *ws_dlg_ptr, struct _packet_info *, epan_dissect *, const void *rlc_lte_tap_info_ptr, tap_flags_t)
{
// Look up dialog.
LteRlcStatisticsDialog *ws_dlg = static_cast<LteRlcStatisticsDialog *>(ws_dlg_ptr);
const rlc_lte_tap_info *rlt_info = (const rlc_lte_tap_info *) rlc_lte_tap_info_ptr;
if (!ws_dlg || !rlt_info) {
return TAP_PACKET_DONT_REDRAW;
}
ws_dlg->incFrameCount();
// Look for this UE (TODO: avoid linear search if have lots of UEs in capture...)
RlcUeTreeWidgetItem *ue_ti = NULL;
for (int i = 0; i < ws_dlg->statsTreeWidget()->topLevelItemCount(); i++) {
QTreeWidgetItem *ti = ws_dlg->statsTreeWidget()->topLevelItem(i);
if (ti->type() != rlc_ue_row_type_) continue;
RlcUeTreeWidgetItem *cur_ru_ti = static_cast<RlcUeTreeWidgetItem*>(ti);
if (cur_ru_ti->isMatch(rlt_info)) {
ue_ti = cur_ru_ti;
break;
}
}
if (!ue_ti) {
// Existing UE wasn't found so create a new one.
ue_ti = new RlcUeTreeWidgetItem(ws_dlg->statsTreeWidget(), rlt_info);
for (int col = 0; col < ws_dlg->statsTreeWidget()->columnCount(); col++) {
// int QTreeWidgetItem::textAlignment(int column) const
// Returns the text alignment for the label in the given column.
// Note: This function returns an int for historical reasons. It will be corrected to return Qt::Alignment in Qt 7.
ue_ti->setTextAlignment(col, static_cast<Qt::Alignment>(ws_dlg->statsTreeWidget()->headerItem()->textAlignment(col)));
}
}
// Update the UE from the information in the tap structure.
ue_ti->update(rlt_info);
return TAP_PACKET_REDRAW;
}
void LteRlcStatisticsDialog::tapDraw(void *ws_dlg_ptr)
{
// Look up UE.
LteRlcStatisticsDialog *ws_dlg = static_cast<LteRlcStatisticsDialog *>(ws_dlg_ptr);
if (!ws_dlg) {
return;
}
// Draw each UE.
for (int i = 0; i < ws_dlg->statsTreeWidget()->topLevelItemCount(); i++) {
QTreeWidgetItem *ti = ws_dlg->statsTreeWidget()->topLevelItem(i);
if (ti->type() != rlc_ue_row_type_) continue;
RlcUeTreeWidgetItem *ru_ti = static_cast<RlcUeTreeWidgetItem*>(ti);
ru_ti->draw();
}
// Update title
ws_dlg->setWindowSubtitle(QString("LTE RLC Statistics (%1 UEs, %2 frames)").
arg(ws_dlg->statsTreeWidget()->topLevelItemCount()).arg(ws_dlg->getFrameCount()));
}
void LteRlcStatisticsDialog::useRLCFramesFromMacCheckBoxToggled(bool state)
{
// Update state to be stored in recent preferences
recent.gui_rlc_use_pdus_from_mac = state;
// Retap to get updated list of PDUs
fillTree();
}
const QString LteRlcStatisticsDialog::filterExpression()
{
QString filter_expr;
if (statsTreeWidget()->selectedItems().count() > 0) {
QTreeWidgetItem *ti = statsTreeWidget()->selectedItems()[0];
// Generate expression according to what type of item is selected.
if (ti->type() == rlc_ue_row_type_) {
RlcUeTreeWidgetItem *ru_ti = static_cast<RlcUeTreeWidgetItem*>(ti);
filter_expr = ru_ti->filterExpression(showSRFilterCheckBox_->checkState() > Qt::Unchecked,
showRACHFilterCheckBox_->checkState() > Qt::Unchecked);
} else if (ti->type() == rlc_channel_row_type_) {
RlcChannelTreeWidgetItem *rc_ti = static_cast<RlcChannelTreeWidgetItem*>(ti);
filter_expr = rc_ti->filterExpression(showSRFilterCheckBox_->checkState() > Qt::Unchecked,
showRACHFilterCheckBox_->checkState() > Qt::Unchecked);
}
}
return filter_expr;
}
void LteRlcStatisticsDialog::fillTree()
{
if (!registerTapListener("rlc-lte",
this,
displayFilter_.toLatin1().data(),
TL_REQUIRES_NOTHING,
tapReset,
tapPacket,
tapDraw)) {
reject();
return;
}
cap_file_.retapPackets();
tapDraw(this);
removeTapListeners();
}
void LteRlcStatisticsDialog::updateItemSelectionChanged()
{
updateHeaderLabels();
bool enableULGraphButton = false, enableDLGraphButton = false;
if (statsTreeWidget()->selectedItems().count() > 0 && statsTreeWidget()->selectedItems()[0]->type() == rlc_channel_row_type_) {
QTreeWidgetItem *ti = statsTreeWidget()->selectedItems()[0];
RlcChannelTreeWidgetItem *rc_ti = static_cast<RlcChannelTreeWidgetItem*>(ti);
enableULGraphButton = rc_ti->hasULData();
enableDLGraphButton = rc_ti->hasDLData();
}
// Only enabling graph buttons for channel entries.
launchULGraph_->setEnabled(enableULGraphButton);
launchDLGraph_->setEnabled(enableDLGraphButton);
}
void LteRlcStatisticsDialog::updateHeaderLabels()
{
if (statsTreeWidget()->selectedItems().count() > 0 &&
statsTreeWidget()->selectedItems()[0]->type() == rlc_channel_row_type_) {
// UE column headings.
statsTreeWidget()->headerItem()->setText(col_ueid_, channel_col_0_title_);
statsTreeWidget()->headerItem()->setText(col_mode_, channel_col_1_title_);
statsTreeWidget()->headerItem()->setText(col_priority_, channel_col_2_title_);
} else {
// Channel column headings.
statsTreeWidget()->headerItem()->setText(col_ueid_, ue_col_0_title_);
statsTreeWidget()->headerItem()->setText(col_mode_, ue_col_1_title_);
statsTreeWidget()->headerItem()->setText(col_priority_, ue_col_2_title_);
}
}
void LteRlcStatisticsDialog::captureFileClosing()
{
remove_tap_listener(this);
WiresharkDialog::captureFileClosing();
}
// Launch a UL graph for the currently-selected channel.
void LteRlcStatisticsDialog::launchULGraphButtonClicked()
{
if (statsTreeWidget()->selectedItems().count() > 0 && statsTreeWidget()->selectedItems()[0]->type() == rlc_channel_row_type_) {
// Get the channel item.
QTreeWidgetItem *ti = statsTreeWidget()->selectedItems()[0];
RlcChannelTreeWidgetItem *rc_ti = static_cast<RlcChannelTreeWidgetItem*>(ti);
emit launchRLCGraph(true,
rc_ti->get_ueid(),
rc_ti->get_mode(),
rc_ti->get_channelType(),
rc_ti->get_channelId(),
DIRECTION_UPLINK);
}
}
// Launch a DL graph for the currently-selected channel.
void LteRlcStatisticsDialog::launchDLGraphButtonClicked()
{
if (statsTreeWidget()->selectedItems().count() > 0 && statsTreeWidget()->selectedItems()[0]->type() == rlc_channel_row_type_) {
// Get the channel item.
QTreeWidgetItem *ti = statsTreeWidget()->selectedItems()[0];
RlcChannelTreeWidgetItem *rc_ti = static_cast<RlcChannelTreeWidgetItem*>(ti);
emit launchRLCGraph(true,
rc_ti->get_ueid(),
rc_ti->get_mode(),
rc_ti->get_channelType(),
rc_ti->get_channelId(),
DIRECTION_DOWNLINK);
}
}
// Store filter from signal.
void LteRlcStatisticsDialog::filterUpdated(QString filter)
{
displayFilter_ = filter;
}
// Get the item for the row, depending upon the type of tree item.
QList<QVariant> LteRlcStatisticsDialog::treeItemData(QTreeWidgetItem *item) const
{
// Cast up to our type.
RlcChannelTreeWidgetItem *channel_item = dynamic_cast<RlcChannelTreeWidgetItem*>(item);
if (channel_item) {
return channel_item->rowData();
}
RlcUeTreeWidgetItem *ue_item = dynamic_cast<RlcUeTreeWidgetItem*>(item);
if (ue_item) {
return ue_item->rowData();
}
// Need to return something..
return QList<QVariant>();
}
// Stat command + args
static void
lte_rlc_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("LteRlcStatistics", filter.constData(), NULL);
}
static stat_tap_ui lte_rlc_statistics_ui = {
REGISTER_STAT_GROUP_TELEPHONY_LTE,
QT_TRANSLATE_NOOP("LteRlcStatisticsDialog", "RLC Statistics"),
"rlc-lte,stat",
lte_rlc_statistics_init,
0,
NULL
};
extern "C" {
void register_tap_listener_qt_lte_rlc_statistics(void);
void
register_tap_listener_qt_lte_rlc_statistics(void)
{
register_stat_tap_ui(<e_rlc_statistics_ui, NULL);
}
} |
C/C++ | wireshark/ui/qt/lte_rlc_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 __LTE_RLC_STATISTICS_DIALOG_H__
#define __LTE_RLC_STATISTICS_DIALOG_H__
#include "tap_parameter_dialog.h"
#include <QCheckBox>
class LteRlcStatisticsDialog : public TapParameterDialog
{
Q_OBJECT
public:
LteRlcStatisticsDialog(QWidget &parent, CaptureFile &cf, const char *filter);
~LteRlcStatisticsDialog();
unsigned getFrameCount() { return packet_count_; }
void incFrameCount() { ++packet_count_; }
protected:
void captureFileClosing();
signals:
void launchRLCGraph(bool channelKnown,
guint16 ueid, guint8 rlcMode,
guint16 channelType, guint16 channelId,
guint8 direction);
private:
// Extra controls needed for this dialog.
QCheckBox *useRLCFramesFromMacCheckBox_;
QCheckBox *showSRFilterCheckBox_;
QCheckBox *showRACHFilterCheckBox_;
QPushButton *launchULGraph_;
QPushButton *launchDLGraph_;
QString displayFilter_;
CaptureFile &cf_;
int packet_count_;
// Callbacks for register_tap_listener
static void tapReset(void *ws_dlg_ptr);
static tap_packet_status tapPacket(void *ws_dlg_ptr, struct _packet_info *, struct epan_dissect *, const void *rlc_lte_tap_info_ptr, tap_flags_t flags);
static void tapDraw(void *ws_dlg_ptr);
void updateHeaderLabels();
virtual const QString filterExpression();
QList<QVariant> treeItemData(QTreeWidgetItem *item) const;
private slots:
virtual void fillTree();
void updateItemSelectionChanged();
void useRLCFramesFromMacCheckBoxToggled(bool state);
void launchULGraphButtonClicked();
void launchDLGraphButtonClicked();
void filterUpdated(QString filter);
};
#endif // __LTE_RLC_STATISTICS_DIALOG_H__ |
C++ | wireshark/ui/qt/main.cpp | /* main.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>
#define WS_LOG_DOMAIN LOG_DOMAIN_MAIN
#include <glib.h>
#include <locale.h>
#ifdef _WIN32
#include <windows.h>
#include <tchar.h>
#include <wchar.h>
#include <shellapi.h>
#include <wsutil/console_win32.h>
#endif
#include <ws_exit_codes.h>
#include <wsutil/clopts_common.h>
#include <wsutil/cmdarg_err.h>
#include <ui/urls.h>
#include <wsutil/filesystem.h>
#include <wsutil/privileges.h>
#include <wsutil/socket.h>
#include <wsutil/wslog.h>
#ifdef HAVE_PLUGINS
#include <wsutil/plugins.h>
#endif
#include <wsutil/report_message.h>
#include <wsutil/please_report_bug.h>
#include <wsutil/unicode-utils.h>
#include <wsutil/version_info.h>
#include <epan/addr_resolv.h>
#include <epan/ex-opt.h>
#include <epan/tap.h>
#include <epan/stat_tap_ui.h>
#include <epan/column.h>
#include <epan/disabled_protos.h>
#include <epan/prefs.h>
#ifdef HAVE_KERBEROS
#include <epan/packet.h>
#include <epan/asn1.h>
#include <epan/dissectors/packet-kerberos.h>
#endif
#include <wsutil/codecs.h>
#include <extcap.h>
/* general (not Qt specific) */
#include "file.h"
#include "epan/color_filters.h"
#include "epan/rtd_table.h"
#include "epan/srt_table.h"
#include "ui/alert_box.h"
#include "ui/iface_lists.h"
#include "ui/language.h"
#include "ui/persfilepath_opt.h"
#include "ui/recent.h"
#include "ui/simple_dialog.h"
#include "ui/util.h"
#include "ui/dissect_opts.h"
#include "ui/commandline.h"
#include "ui/capture_ui_utils.h"
#include "ui/preference_utils.h"
#include "ui/software_update.h"
#include "ui/taps.h"
#include "ui/qt/conversation_dialog.h"
#include "ui/qt/utils/color_utils.h"
#include "ui/qt/coloring_rules_dialog.h"
#include "ui/qt/endpoint_dialog.h"
#include "ui/qt/glib_mainloop_on_qeventloop.h"
#include "ui/qt/wireshark_main_window.h"
#include "ui/qt/response_time_delay_dialog.h"
#include "ui/qt/service_response_time_dialog.h"
#include "ui/qt/simple_dialog.h"
#include "ui/qt/simple_statistics_dialog.h"
#include <ui/qt/widgets/splash_overlay.h>
#include "ui/qt/wireshark_application.h"
#include "capture/capture-pcap-util.h"
#include <QMessageBox>
#include <QScreen>
#ifdef _WIN32
# include "capture/capture-wpcap.h"
# include <wsutil/file_util.h>
#endif /* _WIN32 */
#ifdef HAVE_AIRPCAP
# include <capture/airpcap.h>
# include <capture/airpcap_loader.h>
//# include "airpcap_dlg.h"
//# include "airpcap_gui_utils.h"
#endif
#include "epan/crypt/dot11decrypt_ws.h"
/* Handle the addition of View menu items without request */
#if defined(Q_OS_MAC)
#include <ui/macosx/cocoa_bridge.h>
#endif
#include <ui/qt/utils/qt_ui_utils.h>
//#define DEBUG_STARTUP_TIME 1
/* update the main window */
void main_window_update(void)
{
WiresharkApplication::processEvents();
}
void exit_application(int status) {
if (wsApp) {
wsApp->quit();
}
exit(status);
}
/*
* Report an error in command-line arguments.
*
* On Windows, Wireshark is built for the Windows subsystem, and runs
* without a console, so we create a console on Windows to receive the
* output.
*
* See create_console(), in ui/win32/console_win32.c, for an example
* of code to check whether we need to create a console.
*
* On UN*Xes:
*
* If Wireshark is run from the command line, its output either goes
* to the terminal or to wherever the standard error was redirected.
*
* If Wireshark is run by executing it as a remote command, e.g. with
* ssh, its output either goes to whatever socket was set up for the
* remote command's standard error or to wherever the standard error
* was redirected.
*
* If Wireshark was run from the GUI, e.g. by double-clicking on its
* icon or on a file that it opens, there are no guarantees as to
* where the standard error went. It could be going to /dev/null
* (current macOS), or to a socket to systemd for the journal, or
* to a log file in the user's home directory, or to the "console
* device" ("workstation console"), or....
*
* Part of determining that, at least for locally-run Wireshark,
* is to try to open /dev/tty to determine whether the process
* has a controlling terminal. (It fails, at a minimum, for
* Wireshark launched from the GUI under macOS, Ubuntu with GNOME,
* and Ubuntu with KDE; in all cases, an attempt to open /dev/tty
* fails with ENXIO.) If it does have a controlling terminal,
* write to the standard error, otherwise assume that the standard
* error might not go anywhere that the user will be able to see.
* That doesn't handle the "run by ssh" case, however; that will
* not have a controlling terminal. (This means running it by
* remote execution, not by remote login.) Perhaps there's an
* environment variable to check there.
*/
// xxx copied from ../gtk/main.c
static void
wireshark_cmdarg_err(const char *fmt, va_list ap)
{
#ifdef _WIN32
create_console();
#endif
fprintf(stderr, "wireshark: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
}
/*
* Report additional information for an error in command-line arguments.
* Creates a console on Windows.
*/
// xxx copied from ../gtk/main.c
static void
wireshark_cmdarg_err_cont(const char *fmt, va_list ap)
{
#ifdef _WIN32
create_console();
#endif
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
}
void
gather_wireshark_qt_compiled_info(feature_list l)
{
#ifdef QT_VERSION
with_feature(l, "Qt %s", QT_VERSION_STR);
#else
with_feature(l, "Qt (version unknown)");
#endif
gather_caplibs_compile_info(l);
epan_gather_compile_info(l);
#ifdef QT_MULTIMEDIA_LIB
with_feature(l, "QtMultimedia");
#else
without_feature(l, "QtMultimedia");
#endif
const char *update_info = software_update_info();
if (update_info) {
with_feature(l, "automatic updates using %s", update_info);
} else {
without_feature(l, "automatic updates");
}
#ifdef _WIN32
#ifdef HAVE_AIRPCAP
gather_airpcap_compile_info(l);
#else
without_feature(l, "AirPcap");
#endif
#endif /* _WIN32 */
#ifdef HAVE_MINIZIP
with_feature(l, "Minizip");
#else
without_feature(l, "Minizip");
#endif
}
void
gather_wireshark_runtime_info(feature_list l)
{
with_feature(l, "Qt %s", qVersion());
#ifdef HAVE_LIBPCAP
gather_caplibs_runtime_info(l);
#endif
epan_gather_runtime_info(l);
#ifdef HAVE_AIRPCAP
gather_airpcap_runtime_info(l);
#endif
if (mainApp) {
// Display information
const char *display_mode = ColorUtils::themeIsDark() ? "dark" : "light";
with_feature(l, "%s display mode", display_mode);
int hidpi_count = 0;
foreach (QScreen *screen, mainApp->screens()) {
if (screen->devicePixelRatio() > 1.0) {
hidpi_count++;
}
}
if (hidpi_count == mainApp->screens().count()) {
with_feature(l, "HiDPI");
} else if (hidpi_count) {
with_feature(l, "mixed DPI");
} else {
without_feature(l, "HiDPI");
}
}
}
static void
qt_log_message_handler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
enum ws_log_level log_level = LOG_LEVEL_NONE;
// QMessageLogContext may contain null/zero for release builds.
const char *file = context.file;
int line = context.line > 0 ? context.line : -1;
const char *func = context.function;
switch (type) {
case QtInfoMsg:
log_level = LOG_LEVEL_INFO;
// Omit the file/line/function for this level.
file = nullptr;
line = -1;
func = nullptr;
break;
case QtWarningMsg:
log_level = LOG_LEVEL_WARNING;
break;
case QtCriticalMsg:
log_level = LOG_LEVEL_CRITICAL;
break;
case QtFatalMsg:
log_level = LOG_LEVEL_ERROR;
break;
// We want qDebug() messages to show up always for temporary print-outs.
case QtDebugMsg:
log_level = LOG_LEVEL_ECHO;
break;
}
// Qt gives the full method declaration as the function. Our convention
// (following the C/C++ standards) is to display only the function name.
// Hack the name into the message as a workaround to avoid formatting
// issues.
if (func != nullptr) {
ws_log_full(LOG_DOMAIN_QTUI, log_level, file, line, nullptr,
"%s -- %s", func, qUtf8Printable(msg));
}
else {
ws_log_full(LOG_DOMAIN_QTUI, log_level, file, line, nullptr,
"%s", qUtf8Printable(msg));
}
}
#ifdef HAVE_LIBPCAP
/* Check if there's something important to tell the user during startup.
* We want to do this *after* showing the main window so that any windows
* we pop up will be above the main window.
*/
static void
check_and_warn_user_startup()
{
gchar *cur_user, *cur_group;
/* Tell the user not to run as root. */
if (running_with_special_privs() && recent.privs_warn_if_elevated) {
cur_user = get_cur_username();
cur_group = get_cur_groupname();
simple_message_box(ESD_TYPE_WARN, &recent.privs_warn_if_elevated,
"Running as user \"%s\" and group \"%s\".\n"
"This could be dangerous.\n\n"
"If you're running Wireshark this way in order to perform live capture, "
"you may want to be aware that there is a better way documented at\n"
WS_WIKI_URL("CaptureSetup/CapturePrivileges"), cur_user, cur_group);
g_free(cur_user);
g_free(cur_group);
}
}
#endif
#if defined(_WIN32) && !defined(__MINGW32__)
// Try to avoid library search path collisions. QCoreApplication will
// search QT_INSTALL_PREFIX/plugins for platform DLLs before searching
// the application directory. If
//
// - You have Qt version 5.x.y installed in the default location
// (C:\Qt\5.x) on your machine.
//
// and
//
// - You install Wireshark that was built on a machine with Qt version
// 5.x.z installed in the default location.
//
// Qt5Core.dll will load qwindows.dll from your local C:\Qt\5.x\...\plugins
// directory. This may not be compatible with qwindows.dll from that
// same path on the build machine. At any rate, loading DLLs from paths
// you don't control is ill-advised. We work around this by removing every
// path except our application directory.
//
// NOTE: This does not apply to MinGW-w64 using MSYS2. In that case we use
// the system's Qt plugins with the default search paths.
//
// NOTE 2: When using MinGW-w64 without MSYS2 we also search for the system DLLS,
// because our installer might not have deployed them.
static inline void
win32_reset_library_path(void)
{
QString app_path = QDir(get_progfile_dir()).path();
foreach (QString path, QCoreApplication::libraryPaths()) {
QCoreApplication::removeLibraryPath(path);
}
QCoreApplication::addLibraryPath(app_path);
}
#endif
#ifdef Q_OS_MAC
// Try to work around
//
// https://gitlab.com/wireshark/wireshark/-/issues/17075
//
// aka
//
// https://bugreports.qt.io/browse/QTBUG-87014
//
// The fix at
//
// https://codereview.qt-project.org/c/qt/qtbase/+/322228/3/src/plugins/platforms/cocoa/qnsview_drawing.mm
//
// enables layer backing if we're running on Big Sur OR we're running on
// Catalina AND we were built with the Catalina SDK. Enable layer backing
// here by setting QT_MAC_WANTS_LAYER=1, but only if we're running on Big
// Sur and our version of Qt doesn't have a fix for QTBUG-87014.
#include <QOperatingSystemVersion>
static inline void
macos_enable_layer_backing(void)
{
// At the time of this writing, the QTBUG-87014 for layerEnabledByMacOS is...
//
// ...in https://github.com/qt/qtbase/blob/5.12/src/plugins/platforms/cocoa/qnsview_drawing.mm
// ...not in https://github.com/qt/qtbase/blob/5.12.10/src/plugins/platforms/cocoa/qnsview_drawing.mm
// ...in https://github.com/qt/qtbase/blob/5.15/src/plugins/platforms/cocoa/qnsview_drawing.mm
// ...not in https://github.com/qt/qtbase/blob/5.15.2/src/plugins/platforms/cocoa/qnsview_drawing.mm
// ...not in https://github.com/qt/qtbase/blob/6.0/src/plugins/platforms/cocoa/qnsview_drawing.mm
// ...not in https://github.com/qt/qtbase/blob/6.0.0/src/plugins/platforms/cocoa/qnsview_drawing.mm
//
// We'll assume that it will be fixed in 5.12.11, 5.15.3, and 6.0.1.
// Note that we only ship LTS versions of Qt with our macOS packages.
// Feel free to add other versions if needed.
#if \
(QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) && QT_VERSION < QT_VERSION_CHECK(5, 12, 11) \
|| (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) && QT_VERSION < QT_VERSION_CHECK(5, 15, 3)) \
|| (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) && QT_VERSION < QT_VERSION_CHECK(6, 0, 1)) \
)
QOperatingSystemVersion os_ver = QOperatingSystemVersion::current();
int major_ver = os_ver.majorVersion();
int minor_ver = os_ver.minorVersion();
if ( (major_ver == 10 && minor_ver >= 16) || major_ver >= 11 ) {
if (qgetenv("QT_MAC_WANTS_LAYER").isEmpty()) {
qputenv("QT_MAC_WANTS_LAYER", "1");
}
}
#endif
}
#endif
/* And now our feature presentation... [ fade to music ] */
int main(int argc, char *qt_argv[])
{
WiresharkMainWindow *main_w;
#ifdef _WIN32
LPWSTR *wc_argv;
int wc_argc;
#endif
int ret_val = EXIT_SUCCESS;
char **argv = qt_argv;
char *rf_path;
int rf_open_errno;
#ifdef HAVE_LIBPCAP
gchar *err_str, *err_str_secondary;;
#else
#ifdef _WIN32
#ifdef HAVE_AIRPCAP
gchar *err_str;
#endif
#endif
#endif
gchar *err_msg = NULL;
df_error_t *df_err = NULL;
QString dfilter, read_filter;
#ifdef HAVE_LIBPCAP
int caps_queries = 0;
#endif
/* Start time in microseconds */
guint64 start_time = g_get_monotonic_time();
static const struct report_message_routines wireshark_report_routines = {
vfailure_alert_box,
vwarning_alert_box,
open_failure_alert_box,
read_failure_alert_box,
write_failure_alert_box,
cfile_open_failure_alert_box,
cfile_dump_open_failure_alert_box,
cfile_read_failure_alert_box,
cfile_write_failure_alert_box,
cfile_close_failure_alert_box
};
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
/*
* See:
*
* issue #16908;
*
* https://doc.qt.io/qt-5/qvector.html#maximum-size-and-out-of-memory-conditions
*
* https://forum.qt.io/topic/114950/qvector-realloc-throwing-sigsegv-when-very-large-surface3d-is-rendered
*
* for why we're doing this; the widget we use for the packet list
* uses QVector, so those limitations apply to it.
*
* Apparently, this will be fixed in Qt 6:
*
* https://github.com/qt/qtbase/commit/215ca735341b9487826023a7983382851ce8bf26
*
* https://github.com/qt/qtbase/commit/2a6cdec718934ca2cc7f6f9c616ebe62f6912123#diff-724f419b0bb0487c2629bb16cf534c4b268ddcee89b5177189b607f940cfd83dR192
*
* Hopefully QList won't cause any performance hits relative to
* QVector.
*
* We pick 53 million records as a value that should avoid the problem;
* see the Wireshark issue for why that value was chosen.
*/
cf_set_max_records(53000000);
#endif
#ifdef Q_OS_MAC
macos_enable_layer_backing();
#endif
cmdarg_err_init(wireshark_cmdarg_err, wireshark_cmdarg_err_cont);
/* Initialize log handler early so we can have proper logging during startup. */
ws_log_init("wireshark", vcmdarg_err);
/* For backward compatibility with GLib logging and Wireshark 3.4. */
ws_log_console_writer_set_use_stdout(TRUE);
qInstallMessageHandler(qt_log_message_handler);
#ifdef _WIN32
restore_pipes();
#endif
#ifdef DEBUG_STARTUP_TIME
prefs.gui_console_open = console_open_always;
#endif /* DEBUG_STARTUP_TIME */
#if defined(Q_OS_MAC)
/* Disable automatic addition of tab menu entries in view menu */
CocoaBridge::cleanOSGeneratedMenuItems();
#endif
/*
* Set the C-language locale to the native environment and set the
* code page to UTF-8 on Windows.
*/
#ifdef _WIN32
setlocale(LC_ALL, ".UTF-8");
#else
setlocale(LC_ALL, "");
#endif
#ifdef _WIN32
//
// On Windows, QCoreApplication has its own WinMain(), which gets the
// command line using GetCommandLineW(), breaks it into individual
// arguments using CommandLineToArgvW(), and then "helpfully"
// converts those UTF-16LE arguments into strings in the local code
// page.
//
// We don't want that, because not all file names can be represented
// in the local code page, so we do the same, but we convert the
// strings into UTF-8.
//
wc_argv = CommandLineToArgvW(GetCommandLineW(), &wc_argc);
if (wc_argv) {
argc = wc_argc;
argv = arg_list_utf_16to8(wc_argc, wc_argv);
LocalFree(wc_argv);
} /* XXX else bail because something is horribly, horribly wrong? */
create_app_running_mutex();
#endif /* _WIN32 */
/* Early logging command-line initialization. */
ws_log_parse_args(&argc, argv, vcmdarg_err, WS_EXIT_INVALID_OPTION);
ws_noisy("Finished log init and parsing command line log arguments");
/*
* Get credential information for later use, and drop privileges
* before doing anything else.
* Let the user know if anything happened.
*/
init_process_policies();
relinquish_special_privs_perm();
/*
* Attempt to get the pathname of the directory containing the
* executable file.
*/
/* configuration_init_error = */ configuration_init(argv[0], NULL);
/* ws_log(NULL, LOG_LEVEL_DEBUG, "progfile_dir: %s", get_progfile_dir()); */
#ifdef _WIN32
ws_init_dll_search_path();
/* Load wpcap if possible. Do this before collecting the run-time version information */
load_wpcap();
#ifdef HAVE_AIRPCAP
/* Load the airpcap.dll. This must also be done before collecting
* run-time version information. */
load_airpcap();
#if 0
airpcap_dll_ret_val = load_airpcap();
switch (airpcap_dll_ret_val) {
case AIRPCAP_DLL_OK:
/* load the airpcap interfaces */
g_airpcap_if_list = get_airpcap_interface_list(&err, &err_str);
if (g_airpcap_if_list == NULL || g_list_length(g_airpcap_if_list) == 0) {
if (err == CANT_GET_AIRPCAP_INTERFACE_LIST && err_str != NULL) {
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", "Failed to open Airpcap Adapters.");
g_free(err_str);
}
airpcap_if_active = NULL;
} else {
/* select the first as default (THIS SHOULD BE CHANGED) */
airpcap_if_active = airpcap_get_default_if(airpcap_if_list);
}
break;
/*
* XXX - Maybe we need to warn the user if one of the following happens???
*/
case AIRPCAP_DLL_OLD:
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s","AIRPCAP_DLL_OLD\n");
break;
case AIRPCAP_DLL_ERROR:
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s","AIRPCAP_DLL_ERROR\n");
break;
case AIRPCAP_DLL_NOT_FOUND:
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s","AIRPCAP_DDL_NOT_FOUND\n");
break;
}
#endif
#endif /* HAVE_AIRPCAP */
#endif /* _WIN32 */
/* Get the compile-time version information string */
ws_init_version_info("Wireshark", gather_wireshark_qt_compiled_info,
gather_wireshark_runtime_info);
init_report_message("Wireshark", &wireshark_report_routines);
/* Create the user profiles directory */
if (create_profiles_dir(&rf_path) == -1) {
simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
"Could not create profiles directory\n\"%s\": %s.",
rf_path, g_strerror(errno));
g_free (rf_path);
}
profile_store_persconffiles(TRUE);
recent_init();
/* Read the profile independent recent file. We have to do this here so we can */
/* set the profile before it can be set from the command line parameter */
if (!recent_read_static(&rf_path, &rf_open_errno)) {
simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
"Could not open common recent file\n\"%s\": %s.",
rf_path, g_strerror(rf_open_errno));
g_free(rf_path);
}
commandline_early_options(argc, argv);
#if defined(_WIN32) && !defined(__MINGW32__)
win32_reset_library_path();
#endif
// Handle DPI scaling on Windows. This causes problems in at least
// one case on X11 and we don't yet support Android.
// We do the equivalent on macOS by setting NSHighResolutionCapable
// in Info.plist.
// Note that this enables Windows 8.1-style Per-monitor DPI
// awareness but not Windows 10-style Per-monitor v2 awareness.
// https://doc.qt.io/qt-5/scalability.html
// https://doc.qt.io/qt-5/highdpi.html
// https://bugreports.qt.io/browse/QTBUG-53022 - The device pixel ratio is pretty much bogus on Windows.
// https://bugreports.qt.io/browse/QTBUG-55510 - Windows have wrong size
//
// Deprecated in Qt6.
// warning: 'Qt::AA_EnableHighDpiScaling' is deprecated: High-DPI scaling is always enabled.
// This attribute no longer has any effect.
#if defined(Q_OS_WIN) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
/* Create The Wireshark app */
WiresharkApplication ws_app(argc, qt_argv);
// Default value is 400ms = "quickly typing" when searching in Preferences->Protocols
// 1000ms allows a more "hunt/peck" typing speed. 2000ms tested - too long.
QApplication::setKeyboardInputInterval(1000);
/* initialize the funnel mini-api */
// xxx qtshark
//initialize_funnel_ops();
Dot11DecryptInitContext(&dot11decrypt_ctx);
QString cf_name;
unsigned int in_file_type = WTAP_TYPE_AUTO;
err_msg = ws_init_sockets();
if (err_msg != NULL)
{
cmdarg_err("%s", err_msg);
g_free(err_msg);
cmdarg_err_cont("%s", please_report_bug());
ret_val = WS_EXIT_INIT_FAILED;
goto clean_exit;
}
/* Read the profile dependent (static part) of the recent file. */
/* Only the static part of it will be read, as we don't have the gui now to fill the */
/* recent lists which is done in the dynamic part. */
/* We have to do this already here, so command line parameters can overwrite these values. */
if (!recent_read_profile_static(&rf_path, &rf_open_errno)) {
simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
"Could not open recent file\n\"%s\": %s.",
rf_path, g_strerror(rf_open_errno));
g_free(rf_path);
}
wsApp->applyCustomColorsFromRecent();
// Initialize our language
read_language_prefs();
wsApp->loadLanguage(language);
/* ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_DEBUG, "Translator %s", language); */
// Init the main window (and splash)
main_w = new(WiresharkMainWindow);
main_w->show();
// Setup GLib mainloop on Qt event loop to enable GLib and GIO watches
GLibMainloopOnQEventLoop::setup(main_w);
// We may not need a queued connection here but it would seem to make sense
// to force the issue.
main_w->connect(&ws_app, SIGNAL(openCaptureFile(QString,QString,unsigned int)),
main_w, SLOT(openCaptureFile(QString,QString,unsigned int)));
main_w->connect(&ws_app, &WiresharkApplication::openCaptureOptions,
main_w, &WiresharkMainWindow::showCaptureOptionsDialog);
/* Init the "Open file" dialog directory */
/* (do this after the path settings are processed) */
if (recent.gui_fileopen_remembered_dir &&
test_for_directory(recent.gui_fileopen_remembered_dir) == EISDIR) {
wsApp->setLastOpenDir(recent.gui_fileopen_remembered_dir);
} else {
wsApp->setLastOpenDir(get_persdatafile_dir());
}
#ifdef DEBUG_STARTUP_TIME
ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "set_console_log_handler, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
#endif
#ifdef HAVE_LIBPCAP
/* Set the initial values in the capture options. This might be overwritten
by preference settings and then again by the command line parameters. */
capture_opts_init(&global_capture_opts);
#endif
/*
* Libwiretap must be initialized before libwireshark is, so that
* dissection-time handlers for file-type-dependent blocks can
* register using the file type/subtype value for the file type.
*/
wtap_init(TRUE);
splash_update(RA_DISSECTORS, NULL, NULL);
#ifdef DEBUG_STARTUP_TIME
ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling epan init, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
#endif
/* Register all dissectors; we must do this before checking for the
"-G" flag, as the "-G" flag dumps information registered by the
dissectors, and we must do it before we read the preferences, in
case any dissectors register preferences. */
if (!epan_init(splash_update, NULL, TRUE)) {
SimpleDialog::displayQueuedMessages(main_w);
ret_val = WS_EXIT_INIT_FAILED;
goto clean_exit;
}
#ifdef DEBUG_STARTUP_TIME
/* epan_init resets the preferences */
prefs.gui_console_open = console_open_always;
ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "epan done, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
#endif
/* Register all audio codecs. */
codecs_init();
// Read the dynamic part of the recent file. This determines whether or
// not the recent list appears in the main window so the earlier we can
// call this the better.
if (!recent_read_dynamic(&rf_path, &rf_open_errno)) {
simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
"Could not open recent file\n\"%s\": %s.",
rf_path, g_strerror(rf_open_errno));
g_free(rf_path);
}
wsApp->refreshRecentCaptures();
splash_update(RA_LISTENERS, NULL, NULL);
#ifdef DEBUG_STARTUP_TIME
ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Register all tap listeners, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
#endif
/* Register all tap listeners; we do this before we parse the arguments,
as the "-z" argument can specify a registered tap. */
register_all_tap_listeners(tap_reg_listener);
conversation_table_set_gui_info(init_conversation_table);
endpoint_table_set_gui_info(init_endpoint_table);
srt_table_iterate_tables(register_service_response_tables, NULL);
rtd_table_iterate_tables(register_response_time_delay_tables, NULL);
stat_tap_iterate_tables(register_simple_stat_tables, NULL);
if (ex_opt_count("read_format") > 0) {
in_file_type = open_info_name_to_type(ex_opt_get_next("read_format"));
}
#ifdef DEBUG_STARTUP_TIME
ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling extcap_register_preferences, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
#endif
splash_update(RA_EXTCAP, NULL, NULL);
extcap_register_preferences();
splash_update(RA_PREFERENCES, NULL, NULL);
#ifdef DEBUG_STARTUP_TIME
ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling module preferences, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
#endif
global_commandline_info.prefs_p = ws_app.readConfigurationFiles(false);
/* Now get our args */
commandline_other_options(argc, argv, TRUE);
/* Convert some command-line parameters to QStrings */
if (global_commandline_info.cf_name != NULL)
cf_name = QString(global_commandline_info.cf_name);
if (global_commandline_info.rfilter != NULL)
read_filter = QString(global_commandline_info.rfilter);
if (global_commandline_info.dfilter != NULL)
dfilter = QString(global_commandline_info.dfilter);
timestamp_set_type(recent.gui_time_format);
timestamp_set_precision(recent.gui_time_precision);
timestamp_set_seconds_type (recent.gui_seconds_format);
#ifdef HAVE_LIBPCAP
#ifdef DEBUG_STARTUP_TIME
ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling fill_in_local_interfaces, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
#endif
splash_update(RA_INTERFACES, NULL, NULL);
if (!global_commandline_info.cf_name && !prefs.capture_no_interface_load)
fill_in_local_interfaces(main_window_update);
if (global_commandline_info.list_link_layer_types)
caps_queries |= CAPS_QUERY_LINK_TYPES;
if (global_commandline_info.list_timestamp_types)
caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
if (global_commandline_info.start_capture || caps_queries) {
/* We're supposed to do a live capture or get a list of link-layer/timestamp
types for a live capture device; if the user didn't specify an
interface to use, pick a default. */
ret_val = capture_opts_default_iface_if_necessary(&global_capture_opts,
((global_commandline_info.prefs_p->capture_device) && (*global_commandline_info.prefs_p->capture_device != '\0')) ? get_if_name(global_commandline_info.prefs_p->capture_device) : NULL);
if (ret_val != 0) {
goto clean_exit;
}
}
/*
* If requested, list the link layer types and/or time stamp types
* and exit.
*/
if (caps_queries) {
guint i;
#ifdef _WIN32
create_console();
#endif /* _WIN32 */
/* Get the list of link-layer types for the capture devices. */
ret_val = EXIT_SUCCESS;
for (i = 0; i < global_capture_opts.ifaces->len; i++) {
interface_options *interface_opts;
if_capabilities_t *caps;
char *auth_str = NULL;
interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
#ifdef HAVE_PCAP_REMOTE
if (interface_opts->auth_type == CAPTURE_AUTH_PWD) {
auth_str = ws_strdup_printf("%s:%s", interface_opts->auth_username, interface_opts->auth_password);
}
#endif
caps = capture_get_if_capabilities(interface_opts->name, interface_opts->monitor_mode,
auth_str, &err_str, &err_str_secondary, NULL);
g_free(auth_str);
if (caps == NULL) {
cmdarg_err("%s%s%s", err_str, err_str_secondary ? "\n" : "", err_str_secondary ? err_str_secondary : "");
g_free(err_str);
g_free(err_str_secondary);
ret_val = WS_EXIT_INVALID_CAPABILITY;
break;
}
ret_val = capture_opts_print_if_capabilities(caps, interface_opts,
caps_queries);
free_if_capabilities(caps);
if (ret_val != EXIT_SUCCESS) {
break;
}
}
#ifdef _WIN32
destroy_console();
#endif /* _WIN32 */
goto clean_exit;
}
capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
capture_opts_trim_ring_num_files(&global_capture_opts);
#endif /* HAVE_LIBPCAP */
/* Notify all registered modules that have had any of their preferences
changed either from one of the preferences file or from the command
line that their preferences have changed. */
#ifdef DEBUG_STARTUP_TIME
ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Calling prefs_apply_all, elapsed time %" PRIu64 " us \n", g_get_monotonic_time() - start_time);
#endif
splash_update(RA_PREFERENCES_APPLY, NULL, NULL);
prefs_apply_all();
prefs_to_capture_opts();
wsApp->emitAppSignal(WiresharkApplication::PreferencesChanged);
#ifdef HAVE_LIBPCAP
if ((global_capture_opts.num_selected == 0) &&
(prefs.capture_device != NULL)) {
guint i;
interface_t *device;
for (i = 0; i < global_capture_opts.all_ifaces->len; i++) {
device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i);
if (!device->hidden && strcmp(device->display_name, prefs.capture_device) == 0) {
device->selected = TRUE;
global_capture_opts.num_selected++;
break;
}
}
}
#endif
/*
* Enabled and disabled protocols and heuristic dissectors as per
* command-line options.
*/
if (!setup_enabled_and_disabled_protocols()) {
ret_val = WS_EXIT_INVALID_OPTION;
goto clean_exit;
}
build_column_format_array(&CaptureFile::globalCapFile()->cinfo, global_commandline_info.prefs_p->num_cols, TRUE);
wsApp->emitAppSignal(WiresharkApplication::ColumnsChanged); // We read "recent" widths above.
wsApp->emitAppSignal(WiresharkApplication::RecentPreferencesRead); // Must be emitted after PreferencesChanged.
wsApp->setMonospaceFont(prefs.gui_font_name);
/* For update of WindowTitle (When use gui.window_title preference) */
main_w->setWSWindowTitle();
if (!color_filters_init(&err_msg, color_filter_add_cb)) {
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err_msg);
g_free(err_msg);
}
/* allSystemsGo() emits appInitialized(), which signals the WelcomePage to
* delete the splash overlay. However, it doesn't get redrawn until
* processEvents() is called. If we're opening a capture file that happens
* either when we finish reading the file or when the progress bar appears.
* It's probably better to leave the splash overlay up until that happens
* rather than showing the user the welcome page, so we don't call
* processEvents() here.
*/
wsApp->allSystemsGo();
ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "Wireshark is up and ready to go, elapsed time %.3fs", (float) (g_get_monotonic_time() - start_time) / 1000000);
SimpleDialog::displayQueuedMessages(main_w);
/* User could specify filename, or display filter, or both */
if (!dfilter.isEmpty())
main_w->filterPackets(dfilter, false);
if (!cf_name.isEmpty()) {
if (main_w->openCaptureFile(cf_name, read_filter, in_file_type)) {
/* Open stat windows; we do so after creating the main window,
to avoid Qt warnings, and after successfully opening the
capture file, so we know we have something to compute stats
on, and after registering all dissectors, so that MATE will
have registered its field array and we can have a tap filter
with one of MATE's late-registered fields as part of the
filter. */
start_requested_stats();
if (global_commandline_info.go_to_packet != 0) {
/* Jump to the specified frame number, kept for backward
compatibility. */
cf_goto_frame(CaptureFile::globalCapFile(), global_commandline_info.go_to_packet);
} else if (global_commandline_info.jfilter != NULL) {
dfilter_t *jump_to_filter = NULL;
/* try to compile given filter */
if (!dfilter_compile(global_commandline_info.jfilter, &jump_to_filter, &df_err)) {
// Similar code in MainWindow::mergeCaptureFile().
QMessageBox::warning(main_w, QObject::tr("Invalid Display Filter"),
QObject::tr("The filter expression %1 isn't a valid display filter. (%2).")
.arg(global_commandline_info.jfilter, df_err->msg),
QMessageBox::Ok);
df_error_free(&df_err);
} else {
/* Filter ok, jump to the first packet matching the filter
conditions. Default search direction is forward, but if
option d was given, search backwards */
cf_find_packet_dfilter(CaptureFile::globalCapFile(), jump_to_filter, global_commandline_info.jump_backwards);
}
}
}
}
#ifdef HAVE_LIBPCAP
else {
if (global_commandline_info.start_capture) {
if (global_capture_opts.save_file != NULL) {
/* Save the directory name for future file dialogs. */
/* (get_dirname overwrites filename) */
gchar *s = g_strdup(global_capture_opts.save_file);
set_last_open_dir(get_dirname(s));
g_free(s);
}
/* "-k" was specified; start a capture. */
check_and_warn_user_startup();
/* If no user interfaces were specified on the command line,
copy the list of selected interfaces to the set of interfaces
to use for this capture. */
if (global_capture_opts.ifaces->len == 0)
collect_ifaces(&global_capture_opts);
CaptureFile::globalCapFile()->window = main_w;
if (capture_start(&global_capture_opts, global_commandline_info.capture_comments,
main_w->captureSession(), main_w->captureInfoData(),
main_window_update)) {
/* The capture started. Open stat windows; we do so after creating
the main window, to avoid GTK warnings, and after successfully
opening the capture file, so we know we have something to compute
stats on, and after registering all dissectors, so that MATE will
have registered its field array and we can have a tap filter with
one of MATE's late-registered fields as part of the filter. */
start_requested_stats();
}
}
/* if the user didn't supply a capture filter, use the one to filter out remote connections like SSH */
if (!global_commandline_info.start_capture && !global_capture_opts.default_options.cfilter) {
global_capture_opts.default_options.cfilter = g_strdup(get_conn_cfilter());
}
}
#endif /* HAVE_LIBPCAP */
// UAT and UI settings files used in configuration profiles which are used
// in Qt dialogs are not registered during startup because they only get
// loaded when the dialog is shown. Register them here.
profile_register_persconffile("io_graphs");
profile_register_persconffile("import_hexdump.json");
profile_store_persconffiles(FALSE);
// If the wsApp->exec() event loop exits cleanly, we call
// WiresharkApplication::cleanup().
ret_val = wsApp->exec();
wsApp = NULL;
// Many widgets assume that they always have valid epan data, so this
// must be called before epan_cleanup().
// XXX We need to clean up the Lua GUI here. We currently paper over
// this in FunnelStatistics::~FunnelStatistics, which leaks memory.
delete main_w;
recent_cleanup();
epan_cleanup();
extcap_cleanup();
Dot11DecryptDestroyContext(&dot11decrypt_ctx);
ws_cleanup_sockets();
#ifdef _WIN32
/* For some unknown reason, the "atexit()" call in "create_console()"
doesn't arrange that "destroy_console()" be called when we exit,
so we call it here if a console was created. */
destroy_console();
#endif /* _WIN32 */
clean_exit:
#ifdef HAVE_LIBPCAP
capture_opts_cleanup(&global_capture_opts);
#endif
col_cleanup(&CaptureFile::globalCapFile()->cinfo);
codecs_cleanup();
wtap_cleanup();
free_progdirs();
commandline_options_free();
exit_application(ret_val);
} |
C++ | wireshark/ui/qt/main_application.cpp | /* main_application.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
#define WS_LOG_DOMAIN LOG_DOMAIN_MAIN
#include "main_application.h"
#include <algorithm>
#include <errno.h>
#include "wsutil/filesystem.h"
#include "epan/addr_resolv.h"
#include "epan/column-utils.h"
#include "epan/disabled_protos.h"
#include "epan/ftypes/ftypes.h"
#include "epan/prefs.h"
#include "epan/proto.h"
#include "epan/tap.h"
#include "epan/timestamp.h"
#include "epan/decode_as.h"
#include "ui/decode_as_utils.h"
#include "ui/preference_utils.h"
#include "ui/iface_lists.h"
#include "ui/language.h"
#include "ui/recent.h"
#include "ui/simple_dialog.h"
#include "ui/util.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/utils/color_utils.h>
#include "coloring_rules_dialog.h"
#include "epan/color_filters.h"
#include "recent_file_status.h"
#include "extcap.h"
#ifdef HAVE_LIBPCAP
#include <capture/iface_monitor.h>
#endif
#include "wsutil/filter_files.h"
#include "ui/capture_globals.h"
#include "ui/software_update.h"
#include "ui/last_open_dir.h"
#include "ui/recent_utils.h"
#ifdef HAVE_LIBPCAP
#include "ui/capture.h"
#endif
#include "wsutil/utf8_entities.h"
#ifdef _WIN32
# include "wsutil/file_util.h"
# include <QMessageBox>
# include <QSettings>
#endif /* _WIN32 */
#include <ui/qt/capture_file.h>
#include <ui/qt/main_window.h>
#include <ui/qt/main_status_bar.h>
#include <QAction>
#include <QApplication>
#include <QColorDialog>
#include <QDesktopServices>
#include <QDir>
#include <QEvent>
#include <QFileOpenEvent>
#include <QFontInfo>
#include <QFontMetrics>
#include <QLibraryInfo>
#include <QLocale>
#include <QMainWindow>
#include <QMutableListIterator>
#include <QSocketNotifier>
#include <QThreadPool>
#include <QUrl>
#include <qmath.h>
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
#include <QFontDatabase>
#endif
#include <QMimeDatabase>
#if QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)
#include <QStyleHints>
#endif
#ifdef _MSC_VER
#pragma warning(pop)
#endif
MainApplication *mainApp = NULL;
// XXX - Copied from ui/gtk/file_dlg.c
// MUST be UTF-8
static char *last_open_dir = NULL;
static QList<recent_item_status *> recent_captures_;
static QHash<int, QList<QAction *> > dynamic_menu_groups_;
static QHash<int, QList<QAction *> > added_menu_groups_;
static QHash<int, QList<QAction *> > removed_menu_groups_;
QString MainApplication::window_title_separator_ = QString::fromUtf8(" " UTF8_MIDDLE_DOT " ");
// QMimeDatabase parses a large-ish XML file and can be slow to initialize.
// Do so in a worker thread as early as possible.
// https://github.com/lxde/pcmanfm-qt/issues/415
class MimeDatabaseInitThread : public QRunnable
{
private:
void run()
{
QMimeDatabase mime_db;
mime_db.mimeTypeForData(QByteArray());
}
};
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
// Populating the font database can be slow as well.
class FontDatabaseInitThread : public QRunnable
{
private:
void run()
{
QFontDatabase font_db;
}
};
#endif
void
topic_action(topic_action_e action)
{
if (mainApp) mainApp->helpTopicAction(action);
}
extern "C" char *
get_last_open_dir(void)
{
return last_open_dir;
}
void
set_last_open_dir(const char *dirname)
{
if (mainApp) mainApp->setLastOpenDir(dirname);
}
/*
* Add the capture filename to the application-wide "Recent Files" list.
* Contrary to the name this isn't limited to the "recent" menu.
*/
/*
* XXX - We might want to call SHAddToRecentDocs under Windows 7:
* https://stackoverflow.com/questions/437212/how-do-you-register-a-most-recently-used-list-with-windows-in-preparation-for-win
*/
extern "C" void
add_menu_recent_capture_file(const gchar *cf_name) {
QString normalized_cf_name = QString::fromUtf8(cf_name);
QDir cf_path;
cf_path.setPath(normalized_cf_name);
normalized_cf_name = cf_path.absolutePath();
normalized_cf_name = QDir::cleanPath(normalized_cf_name);
normalized_cf_name = QDir::toNativeSeparators(normalized_cf_name);
/* Iterate through the recent items list, removing duplicate entries and every
* item above count_max
*/
unsigned int cnt = 1;
QMutableListIterator<recent_item_status *> rii(recent_captures_);
while (rii.hasNext()) {
recent_item_status *ri = rii.next();
/* if this element string is one of our special items (separator, ...) or
* already in the list or
* this element is above maximum count (too old), remove it
*/
if (ri->filename.length() < 1 ||
#ifdef _WIN32
/* do a case insensitive compare on win32 */
ri->filename.compare(normalized_cf_name, Qt::CaseInsensitive) == 0 ||
#else /* _WIN32 */
/*
* Do a case sensitive compare on UN*Xes.
*
* XXX - on UN*Xes such as macOS, where you can use pathconf()
* to check whether a given file system is case-sensitive or
* not, we should check whether this particular file system
* is case-sensitive and do the appropriate comparison.
*/
ri->filename.compare(normalized_cf_name) == 0 ||
#endif
cnt >= prefs.gui_recent_files_count_max) {
rii.remove();
delete(ri);
cnt--;
}
cnt++;
}
mainApp->addRecentItem(normalized_cf_name, 0, false);
}
/* write all capture filenames of the menu to the user's recent file */
extern "C" void menu_recent_file_write_all(FILE *rf) {
/* we have to iterate backwards through the children's list,
* so we get the latest item last in the file.
*/
QListIterator<recent_item_status *> rii(recent_captures_);
rii.toBack();
while (rii.hasPrevious()) {
QString cf_name;
/* get capture filename from the menu item label */
cf_name = rii.previous()->filename;
if (!cf_name.isNull()) {
fprintf (rf, RECENT_KEY_CAPTURE_FILE ": %s\n", qUtf8Printable(cf_name));
}
}
}
#if defined(HAVE_SOFTWARE_UPDATE) && defined(Q_OS_WIN)
/** Check to see if Wireshark can shut down safely (e.g. offer to save the
* current capture).
*/
extern "C" int software_update_can_shutdown_callback(void) {
return mainApp->softwareUpdateCanShutdown();
}
/** Shut down Wireshark in preparation for an upgrade.
*/
extern "C" void software_update_shutdown_request_callback(void) {
mainApp->softwareUpdateShutdownRequest();
}
#endif // HAVE_SOFTWARE_UPDATE && Q_OS_WIN
// Check each recent item in a separate thread so that we don't hang while
// calling stat(). This is called periodically because files and entire
// volumes can disappear and reappear at any time.
void MainApplication::refreshRecentCaptures() {
recent_item_status *ri;
RecentFileStatus *rf_status;
// We're in the middle of a capture. Don't create traffic.
if (active_captures_ > 0) return;
foreach (ri, recent_captures_) {
if (ri->in_thread) {
continue;
}
rf_status = new RecentFileStatus(ri->filename, this);
QThreadPool::globalInstance()->start(rf_status);
}
}
void MainApplication::refreshPacketData()
{
if (host_name_lookup_process()) {
emit addressResolutionChanged();
} else if (col_data_changed()) {
emit columnDataChanged();
}
}
void MainApplication::updateTaps()
{
draw_tap_listeners(FALSE);
}
QDir MainApplication::lastOpenDir() {
return QDir(last_open_dir);
}
void MainApplication::setLastOpenDirFromFilename(const QString file_name)
{
QString directory = QFileInfo(file_name).absolutePath();
setLastOpenDir(qUtf8Printable(directory));
}
void MainApplication::helpTopicAction(topic_action_e action)
{
QString url = gchar_free_to_qstring(topic_action_url(action));
if (!url.isEmpty()) {
QDesktopServices::openUrl(QUrl(url));
}
}
const QFont MainApplication::monospaceFont(bool zoomed) const
{
if (zoomed) {
return zoomed_font_;
}
return mono_font_;
}
void MainApplication::setMonospaceFont(const char *font_string) {
if (font_string && strlen(font_string) > 0) {
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
// Qt 6's QFont::toString returns a value with 16 or 17 fields, e.g.
// Consolas,11,-1,5,400,0,0,0,0,0,0,0,0,0,0,1
// Corbel,10,-1,5,400,0,0,0,0,0,0,0,0,0,0,1,Regular
// Qt 5's QFont::fromString expects a value with 10 or 11 fields, e.g.
// Consolas,10,-1,5,50,0,0,0,0,0
// Corbel,10,-1,5,50,0,0,0,0,0,Regular
// It looks like Qt6's QFont::fromString can read both forms:
// https://github.com/qt/qtbase/blob/6.0/src/gui/text/qfont.cpp#L2146
// but Qt5's cannot:
// https://github.com/qt/qtbase/blob/5.15/src/gui/text/qfont.cpp#L2151
const char *fs_ptr = font_string;
int field_count = 1;
while ((fs_ptr = strchr(fs_ptr, ',')) != NULL) {
fs_ptr++;
field_count++;
}
if (field_count <= 11) {
#endif
mono_font_.fromString(font_string);
// Only accept the font name if it actually exists.
if (mono_font_.family() == QFontInfo(mono_font_).family()) {
return;
} else {
ws_warning("Monospace font family %s differs from its fontinfo: %s",
qUtf8Printable(mono_font_.family()), qUtf8Printable(QFontInfo(mono_font_).family()));
}
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
} else {
ws_warning("Monospace font %s appears to be from Qt6 and we're running Qt5.", font_string);
}
#endif
}
// https://en.wikipedia.org/wiki/Category:Monospaced_typefaces
const char *win_default_font = "Consolas";
const char *win_alt_font = "Lucida Console";
// SF Mono might be a system font someday. Right now (Oct 2016) it appears
// to be limited to Xcode and Terminal.
// http://www.openradar.me/26790072
// http://www.openradar.me/26862220
const char *osx_default_font = "SF Mono";
const QStringList osx_alt_fonts = QStringList() << "Menlo" << "Monaco";
// XXX Detect Ubuntu systems (e.g. via /etc/os-release and/or
// /etc/lsb_release) and add "Ubuntu Mono Regular" there.
// https://design.ubuntu.com/font/
const char *x11_default_font = "Liberation Mono";
const QStringList x11_alt_fonts = QStringList() << "DejaVu Sans Mono" << "Bitstream Vera Sans Mono";
const QStringList fallback_fonts = QStringList() << "Lucida Sans Typewriter" << "Inconsolata" << "Droid Sans Mono" << "Andale Mono" << "Courier New" << "monospace";
QStringList substitutes;
int font_size_adjust = 0;
// Try to pick the latest, shiniest fixed-width font for our OS.
#if defined(Q_OS_WIN)
const char *default_font = win_default_font;
substitutes << win_alt_font << osx_default_font << osx_alt_fonts << x11_default_font << x11_alt_fonts << fallback_fonts;
# if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
font_size_adjust = 1;
# else // QT_VERSION
font_size_adjust = 2;
# endif // QT_VERSION
#elif defined(Q_OS_MAC)
const char *default_font = osx_default_font;
substitutes << osx_alt_fonts << win_default_font << win_alt_font << x11_default_font << x11_alt_fonts << fallback_fonts;
#else // Q_OS
const char *default_font = x11_default_font;
substitutes << x11_alt_fonts << win_default_font << win_alt_font << osx_default_font << osx_alt_fonts << fallback_fonts;
#endif // Q_OS
mono_font_ = QFont(default_font, mainApp->font().pointSize() + font_size_adjust);
mono_font_.insertSubstitutions(default_font, substitutes);
mono_font_.setBold(false);
// Retrieve the effective font and apply it.
mono_font_.setFamily(QFontInfo(mono_font_).family());
g_free(prefs.gui_font_name);
prefs.gui_font_name = qstring_strdup(mono_font_.toString());
}
int MainApplication::monospaceTextSize(const char *str)
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
return QFontMetrics(mono_font_).horizontalAdvance(str);
#else
return QFontMetrics(mono_font_).width(str);
#endif
}
void MainApplication::setConfigurationProfile(const gchar *profile_name, bool write_recent_file)
{
char *rf_path;
int rf_open_errno;
gchar *err_msg = NULL;
gboolean prev_capture_no_interface_load;
gboolean prev_capture_no_extcap;
/* First check if profile exists */
if (!profile_exists(profile_name, FALSE)) {
if (profile_exists(profile_name, TRUE)) {
char *pf_dir_path, *pf_dir_path2, *pf_filename;
/* Copy from global profile */
if (create_persconffile_profile(profile_name, &pf_dir_path) == -1) {
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
"Can't create directory\n\"%s\":\n%s.",
pf_dir_path, g_strerror(errno));
g_free(pf_dir_path);
}
if (copy_persconffile_profile(profile_name, profile_name, TRUE, &pf_filename,
&pf_dir_path, &pf_dir_path2) == -1) {
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
"Can't copy file \"%s\" in directory\n\"%s\" to\n\"%s\":\n%s.",
pf_filename, pf_dir_path2, pf_dir_path, g_strerror(errno));
g_free(pf_filename);
g_free(pf_dir_path);
g_free(pf_dir_path2);
}
} else {
/* No personal and no global profile exists */
return;
}
}
/* Then check if changing to another profile */
if (profile_name && strcmp (profile_name, get_profile_name()) == 0) {
return;
}
prev_capture_no_interface_load = prefs.capture_no_interface_load;
prev_capture_no_extcap = prefs.capture_no_extcap;
/* Get the current geometry, before writing it to disk */
emit profileChanging();
if (write_recent_file && profile_exists(get_profile_name(), FALSE))
{
/* Write recent file for profile we are leaving, if it still exists */
write_profile_recent();
}
/* Set profile name and update the status bar */
set_profile_name (profile_name);
emit profileNameChanged(profile_name);
/* Apply new preferences */
readConfigurationFiles(true);
if (!recent_read_profile_static(&rf_path, &rf_open_errno)) {
simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
"Could not open common recent file\n\"%s\": %s.",
rf_path, g_strerror(rf_open_errno));
g_free(rf_path);
}
if (recent.gui_fileopen_remembered_dir &&
test_for_directory(recent.gui_fileopen_remembered_dir) == EISDIR) {
set_last_open_dir(recent.gui_fileopen_remembered_dir);
}
timestamp_set_type(recent.gui_time_format);
timestamp_set_precision(recent.gui_time_precision);
timestamp_set_seconds_type (recent.gui_seconds_format);
tap_update_timer_.setInterval(prefs.tap_update_interval);
prefs_to_capture_opts();
prefs_apply_all();
#ifdef HAVE_LIBPCAP
update_local_interfaces();
#endif
setMonospaceFont(prefs.gui_font_name);
// 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.
emit freezePacketList(true);
emit columnsChanged();
emit preferencesChanged();
emit recentPreferencesRead();
emit filterExpressionsChanged();
emit checkDisplayFilter();
emit captureFilterListChanged();
emit displayFilterListChanged();
/* Reload color filters */
if (!color_filters_reload(&err_msg, color_filter_add_cb)) {
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err_msg);
g_free(err_msg);
}
/* Load interfaces if settings have changed */
if (!prefs.capture_no_interface_load &&
((prefs.capture_no_interface_load != prev_capture_no_interface_load) ||
(prefs.capture_no_extcap != prev_capture_no_extcap))) {
refreshLocalInterfaces();
}
emit localInterfaceListChanged();
emit packetDissectionChanged();
/* Write recent_common file to ensure last used profile setting is stored. */
write_recent();
}
void MainApplication::reloadLuaPluginsDelayed()
{
QTimer::singleShot(0, this, SIGNAL(reloadLuaPlugins()));
}
const QIcon &MainApplication::normalIcon()
{
if (normal_icon_.isNull()) {
initializeIcons();
}
return normal_icon_;
}
const QIcon &MainApplication::captureIcon()
{
if (capture_icon_.isNull()) {
initializeIcons();
}
return capture_icon_;
}
const QString MainApplication::windowTitleString(QStringList title_parts)
{
QMutableStringListIterator tii(title_parts);
while (tii.hasNext()) {
QString ti = tii.next();
if (ti.isEmpty()) tii.remove();
}
title_parts.prepend(applicationName());
return title_parts.join(window_title_separator_);
}
void MainApplication::applyCustomColorsFromRecent()
{
int i = 0;
bool ok;
for (GList *custom_color = recent.custom_colors; custom_color; custom_color = custom_color->next) {
QRgb rgb = QString((const char *)custom_color->data).toUInt(&ok, 16);
if (ok) {
QColorDialog::setCustomColor(i++, QColor(rgb));
}
}
}
// Return the first top-level QMainWindow.
QWidget *MainApplication::mainWindow()
{
foreach (QWidget *tlw, topLevelWidgets()) {
QMainWindow *tlmw = qobject_cast<QMainWindow *>(tlw);
if (tlmw && tlmw->isVisible()) {
return tlmw;
}
}
return 0;
}
void MainApplication::storeCustomColorsInRecent()
{
if (QColorDialog::customCount()) {
prefs_clear_string_list(recent.custom_colors);
recent.custom_colors = NULL;
for (int i = 0; i < QColorDialog::customCount(); i++) {
QRgb rgb = QColorDialog::customColor(i).rgb();
recent.custom_colors = g_list_append(recent.custom_colors, ws_strdup_printf("%08x", rgb));
}
}
}
void MainApplication::setLastOpenDir(const char *dir_name)
{
qint64 len;
gchar *new_last_open_dir;
if (dir_name && dir_name[0]) {
len = strlen(dir_name);
if (dir_name[len-1] == G_DIR_SEPARATOR) {
new_last_open_dir = g_strconcat(dir_name, (char *)NULL);
}
else {
new_last_open_dir = g_strconcat(dir_name,
G_DIR_SEPARATOR_S, (char *)NULL);
}
} else {
new_last_open_dir = NULL;
}
g_free(last_open_dir);
last_open_dir = new_last_open_dir;
}
bool MainApplication::event(QEvent *event)
{
QString display_filter = NULL;
if (event->type() == QEvent::FileOpen) {
QFileOpenEvent *foe = static_cast<QFileOpenEvent *>(event);
if (foe && foe->file().length() > 0) {
QString cf_path(foe->file());
if (initialized_) {
emit openCaptureFile(cf_path, display_filter, WTAP_TYPE_AUTO);
} else {
pending_open_files_.append(cf_path);
}
}
return true;
}
return QApplication::event(event);
}
void MainApplication::clearRecentCaptures() {
qDeleteAll(recent_captures_);
recent_captures_.clear();
emit updateRecentCaptureStatus(NULL, 0, false);
}
void MainApplication::cleanup()
{
software_update_cleanup();
storeCustomColorsInRecent();
// Write the user's recent file(s) to disk.
write_profile_recent();
write_recent();
qDeleteAll(recent_captures_);
recent_captures_.clear();
// We might end up here via exit_application.
QThreadPool::globalInstance()->waitForDone();
}
void MainApplication::itemStatusFinished(const QString filename, qint64 size, bool accessible) {
recent_item_status *ri;
foreach (ri, recent_captures_) {
if (filename == ri->filename && (size != ri->size || accessible != ri->accessible)) {
ri->size = size;
ri->accessible = accessible;
ri->in_thread = false;
emit updateRecentCaptureStatus(filename, size, accessible);
}
}
}
MainApplication::MainApplication(int &argc, char **argv) :
QApplication(argc, argv),
initialized_(false),
is_reloading_lua_(false),
if_notifier_(NULL),
active_captures_(0)
{
mainApp = this;
MimeDatabaseInitThread *mime_db_init_thread = new(MimeDatabaseInitThread);
QThreadPool::globalInstance()->start(mime_db_init_thread);
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
FontDatabaseInitThread *font_db_init_thread = new (FontDatabaseInitThread);
QThreadPool::globalInstance()->start(font_db_init_thread);
#endif
Q_INIT_RESOURCE(about);
Q_INIT_RESOURCE(i18n);
Q_INIT_RESOURCE(layout);
Q_INIT_RESOURCE(stock_icons);
Q_INIT_RESOURCE(languages);
#ifdef Q_OS_WIN
/* RichEd20.DLL is needed for native file dialog filter entries. */
ws_load_library("riched20.dll");
#endif // Q_OS_WIN
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) && defined(Q_OS_WIN)
setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
#endif
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) && QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
setAttribute(Qt::AA_DisableWindowContextHelpButton);
#endif
// Throw various settings at the wall with the hope that one of them will
// enable context menu shortcuts QTBUG-69452, QTBUG-109590
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
setAttribute(Qt::AA_DontShowShortcutsInContextMenus, false);
#endif
#if QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)
styleHints()->setShowShortcutsInContextMenus(true);
#endif
//
// XXX - this means we try to check for the existence of all files
// in the recent list every 2 seconds; that causes noticeable network
// traffic if any of them are stored on file servers.
//
// QFileSystemWatcher should allow us to watch for files being
// removed or renamed. It uses kqueues and EVFILT_VNODE on FreeBSD,
// NetBSD, FSEvents on macOS, inotify on Linux if available, and
// FindFirstChagneNotification() on Windows. On all other platforms,
// it just periodically polls, as we're doing now.
//
// For unmounts:
//
// macOS and FreeBSD deliver NOTE_REVOKE notes for EVFILT_VNODE, and
// QFileSystemWatcher delivers signals for them, just as it does for
// NOTE_DELETE and NOTE_RENAME.
//
// On Linux, inotify:
//
// http://man7.org/linux/man-pages/man7/inotify.7.html
//
// appears to deliver "filesystem containing watched object was
// unmounted" events. It looks as if Qt turns them into "changed"
// events.
//
// On Windows, it's not clearly documented what happens on a handle
// opened with FindFirstChangeNotification() if the volume on which
// the path handed to FindFirstChangeNotification() is removed, or
// ejected, or whatever the Windowsese is for "unmounted". The
// handle obviously isn't valid any more, but whether it just hangs
// around and never delivers any notifications or delivers an
// event that turns into an error indication doesn't seem to be
// documented. If it just hangs around, I think our main loop will
// receive a WM_DEVICECHANGE Windows message with DBT_DEVICEREMOVECOMPLETE
// if an unmount occurs - even for network devices. If we need to watch
// for those, we can use the winEvent method of the QWidget for the
// top-level window to get Windows messages.
//
// Note also that remote file systems might not report file
// removal or renames if they're done on the server or done by
// another client. At least on macOS, they *will* get reported
// if they're done on the machine running the program doing the
// kqueue stuff, and, at least in newer versions, should get
// reported on SMB-mounted (and AFP-mounted?) file systems
// even if done on the server or another client.
//
// But, when push comes to shove, the file manager(s) on the
// OSes in question probably use the same mechanisms to
// monitor folders in folder windows or open/save dialogs or...,
// so my inclination is just to use QFileSystemWatcher.
//
// However, that wouldn't catch files that become *re*-accessible
// by virtue of a file system being re-mounted. The only way to
// catch *that* would be to watch for mounts and re-check all
// marked-as-inaccessible files.
//
// macOS and FreeBSD also support EVFILT_FS events, which notify you
// of file system mounts and unmounts. We'd need to add our own
// kqueue for that, if we can check those with QSocketNotifier.
//
// On Linux, at least as of 2006, you're supposed to poll /proc/mounts:
//
// https://lkml.org/lkml/2006/2/22/169
//
// to discover mounts.
//
// On Windows, you'd probably have to watch for WM_DEVICECHANGE events.
//
// Then again, with an automounter, a file system containing a
// recent capture might get unmounted automatically if you haven't
// referred to anything on that file system for a while, and get
// treated as inaccessible. However, if you try to access it,
// the automounter will attempt to re-mount it, so the access *will*
// succeed if the automounter can remount the file.
//
// (Speaking of automounters, repeatedly polling recent files will
// keep the file system from being unmounted, for what that's worth.)
//
// At least on macOS, you can determine whether a file is on an
// automounted file system by calling statfs() on its path and
// checking whether MNT_AUTOMOUNTED is set in f_flags. FreeBSD
// appears to support that flag as well, but no other *BSD appears
// to.
//
// I'm not sure what can be done on Linux.
//
recent_timer_.setParent(this);
connect(&recent_timer_, SIGNAL(timeout()), this, SLOT(refreshRecentCaptures()));
recent_timer_.start(2000);
packet_data_timer_.setParent(this);
connect(&packet_data_timer_, SIGNAL(timeout()), this, SLOT(refreshPacketData()));
packet_data_timer_.start(1000);
tap_update_timer_.setParent(this);
tap_update_timer_.setInterval(TAP_UPDATE_DEFAULT_INTERVAL);
connect(this, SIGNAL(appInitialized()), &tap_update_timer_, SLOT(start()));
connect(&tap_update_timer_, SIGNAL(timeout()), this, SLOT(updateTaps()));
// Application-wide style sheet
QString app_style_sheet = qApp->styleSheet();
qApp->setStyleSheet(app_style_sheet);
// If our window text is lighter than the window background, assume the theme is dark.
QPalette gui_pal = qApp->palette();
prefs_set_gui_theme_is_dark(gui_pal.windowText().color().value() > gui_pal.window().color().value());
#if defined(HAVE_SOFTWARE_UPDATE) && defined(Q_OS_WIN)
connect(this, SIGNAL(softwareUpdateQuit()), this, SLOT(quit()), Qt::QueuedConnection);
#endif
connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(cleanup()));
}
MainApplication::~MainApplication()
{
mainApp = NULL;
clearDynamicMenuGroupItems();
free_filter_lists();
}
void MainApplication::registerUpdate(register_action_e action, const char *message)
{
emit splashUpdate(action, message);
}
void MainApplication::emitAppSignal(AppSignal signal)
{
switch (signal) {
case ColumnsChanged:
emit columnsChanged();
break;
case CaptureFilterListChanged:
emit captureFilterListChanged();
break;
case DisplayFilterListChanged:
emit displayFilterListChanged();
break;
case FilterExpressionsChanged:
emit filterExpressionsChanged();
break;
case LocalInterfacesChanged:
emit localInterfaceListChanged();
break;
case NameResolutionChanged:
emit addressResolutionChanged();
break;
case PreferencesChanged:
emit preferencesChanged();
break;
case PacketDissectionChanged:
emit packetDissectionChanged();
break;
case ProfileChanging:
emit profileChanging();
break;
case RecentCapturesChanged:
emit updateRecentCaptureStatus(NULL, 0, false);
break;
case RecentPreferencesRead:
emit recentPreferencesRead();
break;
case FieldsChanged:
emit fieldsChanged();
break;
case FreezePacketList:
emit freezePacketList(false);
break;
default:
break;
}
}
// Flush any collected app signals.
//
// On macOS emitting PacketDissectionChanged from a dialog can
// render the application unusable:
// https://gitlab.com/wireshark/wireshark/-/issues/11361
// https://gitlab.com/wireshark/wireshark/-/issues/11448
// Work around the problem by queueing up app signals and emitting them
// after the dialog is closed.
//
// The following bugs might be related although they don't describe the
// exact behavior we're working around here:
// https://bugreports.qt.io/browse/QTBUG-38512
// https://bugreports.qt.io/browse/QTBUG-38600
void MainApplication::flushAppSignals()
{
while (!app_signals_.isEmpty()) {
mainApp->emitAppSignal(app_signals_.takeFirst());
}
}
void MainApplication::emitStatCommandSignal(const QString &menu_path, const char *arg, void *userdata)
{
emit openStatCommandDialog(menu_path, arg, userdata);
}
void MainApplication::emitTapParameterSignal(const QString cfg_abbr, const QString arg, void *userdata)
{
emit openTapParameterDialog(cfg_abbr, arg, userdata);
}
// XXX Combine statistics and funnel routines into addGroupItem + groupItems?
void MainApplication::addDynamicMenuGroupItem(int group, QAction *sg_action)
{
if (!dynamic_menu_groups_.contains(group)) {
dynamic_menu_groups_[group] = QList<QAction *>();
}
dynamic_menu_groups_[group] << sg_action;
}
void MainApplication::appendDynamicMenuGroupItem(int group, QAction *sg_action)
{
if (!added_menu_groups_.contains(group)) {
added_menu_groups_[group] = QList<QAction *>();
}
added_menu_groups_[group] << sg_action;
addDynamicMenuGroupItem(group, sg_action);
}
void MainApplication::removeDynamicMenuGroupItem(int group, QAction *sg_action)
{
if (!removed_menu_groups_.contains(group)) {
removed_menu_groups_[group] = QList<QAction *>();
}
removed_menu_groups_[group] << sg_action;
dynamic_menu_groups_[group].removeAll(sg_action);
}
void MainApplication::clearDynamicMenuGroupItems()
{
foreach (int group, dynamic_menu_groups_.keys()) {
dynamic_menu_groups_[group].clear();
}
}
QList<QAction *> MainApplication::dynamicMenuGroupItems(int group)
{
if (!dynamic_menu_groups_.contains(group)) {
return QList<QAction *>();
}
QList<QAction *> sgi_list = dynamic_menu_groups_[group];
std::sort(sgi_list.begin(), sgi_list.end(), qActionLessThan);
return sgi_list;
}
QList<QAction *> MainApplication::addedMenuGroupItems(int group)
{
if (!added_menu_groups_.contains(group)) {
return QList<QAction *>();
}
QList<QAction *> sgi_list = added_menu_groups_[group];
std::sort(sgi_list.begin(), sgi_list.end(), qActionLessThan);
return sgi_list;
}
QList<QAction *> MainApplication::removedMenuGroupItems(int group)
{
if (!removed_menu_groups_.contains(group)) {
return QList<QAction *>();
}
QList<QAction *> sgi_list = removed_menu_groups_[group];
std::sort(sgi_list.begin(), sgi_list.end(), qActionLessThan);
return sgi_list;
}
void MainApplication::clearAddedMenuGroupItems()
{
foreach (int group, added_menu_groups_.keys()) {
added_menu_groups_[group].clear();
}
}
void MainApplication::clearRemovedMenuGroupItems()
{
foreach (int group, removed_menu_groups_.keys()) {
foreach (QAction *action, removed_menu_groups_[group]) {
delete action;
}
removed_menu_groups_[group].clear();
}
}
#ifdef HAVE_LIBPCAP
static void
iface_mon_event_cb(const char *iface, int added, int up)
{
int present = 0;
guint ifs, j;
interface_t *device;
interface_options *interface_opts;
for (ifs = 0; ifs < global_capture_opts.all_ifaces->len; ifs++) {
device = &g_array_index(global_capture_opts.all_ifaces, interface_t, ifs);
if (strcmp(device->name, iface) == 0) {
present = 1;
if (!up) {
/*
* Interface went down or disappeared; remove all instances
* of it from the current list of interfaces selected
* for capturing.
*/
for (j = 0; j < global_capture_opts.ifaces->len; j++) {
interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
if (strcmp(interface_opts->name, device->name) == 0) {
capture_opts_del_iface(&global_capture_opts, j);
}
}
}
}
}
mainApp->emitLocalInterfaceEvent(iface, added, up);
if (present != up) {
/*
* We've been told that there's a new interface or that an old
* interface is gone; reload the local interface list.
*/
mainApp->refreshLocalInterfaces();
}
}
#endif
void MainApplication::ifChangeEventsAvailable()
{
#ifdef HAVE_LIBPCAP
/*
* Something's readable from the descriptor for interface
* monitoring.
*
* Have the interface-monitoring code Read whatever interface-change
* events are available, and call the callback for them.
*/
iface_mon_event();
#endif
}
void MainApplication::emitLocalInterfaceEvent(const char *ifname, int added, int up)
{
emit localInterfaceEvent(ifname, added, up);
}
void MainApplication::refreshLocalInterfaces()
{
extcap_clear_interfaces();
#ifdef HAVE_LIBPCAP
/*
* Reload the local interface list.
*/
scan_local_interfaces(main_window_update);
/*
* Now emit a signal to indicate that the list changed, so that all
* places displaying the list will get updated.
*
* XXX - only if it *did* change.
*/
emit localInterfaceListChanged();
#endif
}
void MainApplication::allSystemsGo()
{
QString display_filter = NULL;
initialized_ = true;
emit appInitialized();
while (pending_open_files_.length() > 0) {
emit openCaptureFile(pending_open_files_.front(), display_filter, WTAP_TYPE_AUTO);
pending_open_files_.pop_front();
}
software_update_init();
#ifdef HAVE_LIBPCAP
int err;
err = iface_mon_start(&iface_mon_event_cb);
if (err == 0) {
if_notifier_ = new QSocketNotifier(iface_mon_get_sock(),
QSocketNotifier::Read, this);
connect(if_notifier_, SIGNAL(activated(int)), SLOT(ifChangeEventsAvailable()));
}
#endif
}
_e_prefs *MainApplication::readConfigurationFiles(bool reset)
{
e_prefs *prefs_p;
if (reset) {
//
// Reset current preferences and enabled/disabled protocols and
// heuristic dissectors before reading.
// (Needed except when this is called at startup.)
//
prefs_reset();
proto_reenable_all();
}
/* Load libwireshark settings from the current profile. */
prefs_p = epan_load_settings();
/* Read the capture filter file. */
read_filter_list(CFILTER_LIST);
return prefs_p;
}
QList<recent_item_status *> MainApplication::recentItems() const {
return recent_captures_;
}
void MainApplication::addRecentItem(const QString filename, qint64 size, bool accessible) {
recent_item_status *ri = new(recent_item_status);
ri->filename = filename;
ri->size = size;
ri->accessible = accessible;
ri->in_thread = false;
recent_captures_.prepend(ri);
itemStatusFinished(filename, size, accessible);
}
void MainApplication::removeRecentItem(const QString &filename)
{
QMutableListIterator<recent_item_status *> rii(recent_captures_);
while (rii.hasNext()) {
recent_item_status *ri = rii.next();
#ifdef _WIN32
/* Do a case insensitive compare on win32 */
if (ri->filename.compare(filename, Qt::CaseInsensitive) == 0) {
#else
/* Do a case sensitive compare on UN*Xes.
*
* XXX - on UN*Xes such as macOS, where you can use pathconf()
* to check whether a given file system is case-sensitive or
* not, we should check whether this particular file system
* is case-sensitive and do the appropriate comparison.
*/
if (ri->filename.compare(filename) == 0) {
#endif
rii.remove();
delete(ri);
}
}
emit updateRecentCaptureStatus(NULL, 0, false);
}
static void switchTranslator(QTranslator& myTranslator, const QString& filename,
const QString& searchPath)
{
mainApp->removeTranslator(&myTranslator);
if (myTranslator.load(filename, searchPath))
mainApp->installTranslator(&myTranslator);
}
void MainApplication::loadLanguage(const QString newLanguage)
{
QLocale locale;
QString localeLanguage;
if (newLanguage.isEmpty() || newLanguage == USE_SYSTEM_LANGUAGE) {
locale = QLocale::system();
localeLanguage = locale.name();
} else {
localeLanguage = newLanguage;
locale = QLocale(localeLanguage);
}
QLocale::setDefault(locale);
switchTranslator(mainApp->translator,
QString("wireshark_%1.qm").arg(localeLanguage), QString(":/i18n/"));
if (QFile::exists(QString("%1/%2/wireshark_%3.qm")
.arg(get_datafile_dir()).arg("languages").arg(localeLanguage)))
switchTranslator(mainApp->translator,
QString("wireshark_%1.qm").arg(localeLanguage), QString(get_datafile_dir()) + QString("/languages"));
if (QFile::exists(QString("%1/wireshark_%3.qm")
.arg(gchar_free_to_qstring(get_persconffile_path("languages", FALSE))).arg(localeLanguage)))
switchTranslator(mainApp->translator,
QString("wireshark_%1.qm").arg(localeLanguage), gchar_free_to_qstring(get_persconffile_path("languages", FALSE)));
if (QFile::exists(QString("%1/qt_%2.qm")
.arg(get_datafile_dir()).arg(localeLanguage))) {
switchTranslator(mainApp->translatorQt,
QString("qt_%1.qm").arg(localeLanguage), QString(get_datafile_dir()));
} else if (QFile::exists(QString("%1/qt_%2.qm")
.arg(get_datafile_dir()).arg(localeLanguage.left(localeLanguage.lastIndexOf('_'))))) {
switchTranslator(mainApp->translatorQt,
QString("qt_%1.qm").arg(localeLanguage.left(localeLanguage.lastIndexOf('_'))), QString(get_datafile_dir()));
} else {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
QString translationPath = QLibraryInfo::path(QLibraryInfo::TranslationsPath);
#else
QString translationPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
#endif
switchTranslator(mainApp->translatorQt, QString("qt_%1.qm").arg(localeLanguage), translationPath);
}
}
void MainApplication::doTriggerMenuItem(MainMenuItem menuItem)
{
switch (menuItem)
{
case FileOpenDialog:
emit openCaptureFile(QString(), QString(), WTAP_TYPE_AUTO);
break;
case CaptureOptionsDialog:
emit openCaptureOptions();
break;
}
}
void MainApplication::zoomTextFont(int zoomLevel)
{
// Scale by 10%, rounding to nearest half point, minimum 1 point.
// XXX Small sizes repeat. It might just be easier to create a map of multipliers.
qreal zoom_size = mono_font_.pointSize() * 2 * qPow(qreal(1.1), zoomLevel);
zoom_size = qRound(zoom_size) / qreal(2.0);
zoom_size = qMax(zoom_size, qreal(1.0));
zoomed_font_ = mono_font_;
zoomed_font_.setPointSizeF(zoom_size);
emit zoomMonospaceFont(zoomed_font_);
QFont zoomed_application_font = font();
zoomed_application_font.setPointSizeF(zoom_size);
emit zoomRegularFont(zoomed_application_font);
}
#if defined(HAVE_SOFTWARE_UPDATE) && defined(Q_OS_WIN)
bool MainApplication::softwareUpdateCanShutdown() {
software_update_ok_ = true;
// At this point the update is ready to install, but WinSparkle has
// not yet run the installer. We need to close our "Wireshark is
// running" mutexes along with those of our child processes, e.g.
// dumpcap.
// Step 1: See if we have any open files.
emit softwareUpdateRequested();
if (software_update_ok_ == true) {
// Step 2: Close the "running" mutexes.
emit softwareUpdateClose();
close_app_running_mutex();
}
return software_update_ok_;
}
void MainApplication::softwareUpdateShutdownRequest() {
// At this point the installer has been launched. Neither Wireshark nor
// its children should have any "Wireshark is running" mutexes open.
// The main window should be closed.
// Step 3: Quit.
emit softwareUpdateQuit();
}
#endif
void MainApplication::captureEventHandler(CaptureEvent ev)
{
switch(ev.captureContext())
{
#ifdef HAVE_LIBPCAP
case CaptureEvent::Update:
case CaptureEvent::Fixed:
switch (ev.eventType())
{
case CaptureEvent::Started:
active_captures_++;
emit captureActive(active_captures_);
break;
case CaptureEvent::Finished:
active_captures_--;
emit captureActive(active_captures_);
break;
default:
break;
}
break;
#endif
case CaptureEvent::File:
case CaptureEvent::Reload:
case CaptureEvent::Rescan:
switch (ev.eventType())
{
case CaptureEvent::Started:
QTimer::singleShot(TAP_UPDATE_DEFAULT_INTERVAL / 5, this, SLOT(updateTaps()));
QTimer::singleShot(TAP_UPDATE_DEFAULT_INTERVAL / 2, this, SLOT(updateTaps()));
break;
case CaptureEvent::Finished:
updateTaps();
break;
default:
break;
}
break;
default:
break;
}
}
void MainApplication::pushStatus(StatusInfo status, const QString &message, const QString &messagetip)
{
if (! mainWindow() || ! qobject_cast<MainWindow *>(mainWindow()))
return;
MainWindow * mw = qobject_cast<MainWindow *>(mainWindow());
if (! mw->statusBar())
return;
MainStatusBar * bar = mw->statusBar();
switch(status)
{
case FilterSyntax:
bar->pushGenericStatus(MainStatusBar::STATUS_CTX_FILTER, message);
break;
case FieldStatus:
bar->pushGenericStatus(MainStatusBar::STATUS_CTX_FIELD, message);
break;
case FileStatus:
bar->pushGenericStatus(MainStatusBar::STATUS_CTX_FILE, message, messagetip);
break;
case ByteStatus:
bar->pushGenericStatus(MainStatusBar::STATUS_CTX_BYTE, message);
break;
case BusyStatus:
bar->pushGenericStatus(MainStatusBar::STATUS_CTX_PROGRESS, message, messagetip);
break;
case TemporaryStatus:
bar->pushGenericStatus(MainStatusBar::STATUS_CTX_TEMPORARY, message);
break;
}
}
void MainApplication::popStatus(StatusInfo status)
{
if (! mainWindow() || ! qobject_cast<MainWindow *>(mainWindow()))
return;
MainWindow * mw = qobject_cast<MainWindow *>(mainWindow());
if (! mw->statusBar())
return;
MainStatusBar * bar = mw->statusBar();
switch(status)
{
case FilterSyntax:
bar->popGenericStatus(MainStatusBar::STATUS_CTX_FILTER);
break;
case FieldStatus:
bar->popGenericStatus(MainStatusBar::STATUS_CTX_FIELD);
break;
case FileStatus:
bar->popGenericStatus(MainStatusBar::STATUS_CTX_FILE);
break;
case ByteStatus:
bar->popGenericStatus(MainStatusBar::STATUS_CTX_BYTE);
break;
case BusyStatus:
bar->popGenericStatus(MainStatusBar::STATUS_CTX_PROGRESS);
break;
case TemporaryStatus:
bar->popGenericStatus(MainStatusBar::STATUS_CTX_TEMPORARY);
break;
}
}
void MainApplication::gotoFrame(int frame)
{
if (! mainWindow() || ! qobject_cast<MainWindow *>(mainWindow()))
return;
MainWindow * mw = qobject_cast<MainWindow *>(mainWindow());
mw->gotoFrame(frame);
} |
C/C++ | wireshark/ui/qt/main_application.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef MAIN_APPLICATION_H
#define MAIN_APPLICATION_H
#include <config.h>
#include <glib.h>
#include "wsutil/feature_list.h"
#include "epan/register.h"
#include "ui/help_url.h"
#include <QApplication>
#include <QDir>
#include <QFont>
#include <QIcon>
#include <QTimer>
#include <QTranslator>
#include "capture_event.h"
struct _e_prefs;
class QAction;
class QSocketNotifier;
// Recent items:
// - Read from prefs
// - Add from open file
// - Check current list
// - Signal updated item
// -
typedef struct _recent_item_status {
QString filename;
qint64 size;
bool accessible;
bool in_thread;
} recent_item_status;
class MainApplication : public QApplication
{
Q_OBJECT
public:
explicit MainApplication(int &argc, char **argv);
~MainApplication();
enum AppSignal {
CaptureFilterListChanged,
ColumnsChanged,
DisplayFilterListChanged,
FieldsChanged,
FilterExpressionsChanged,
LocalInterfacesChanged,
NameResolutionChanged,
PacketDissectionChanged,
PreferencesChanged,
ProfileChanging,
RecentCapturesChanged,
RecentPreferencesRead,
FreezePacketList
};
enum MainMenuItem {
FileOpenDialog,
CaptureOptionsDialog
};
enum StatusInfo {
FilterSyntax,
FieldStatus,
FileStatus,
BusyStatus,
ByteStatus,
TemporaryStatus
};
void registerUpdate(register_action_e action, const char *message);
void emitAppSignal(AppSignal signal);
// Emitting app signals (PacketDissectionChanged in particular) from
// dialogs on macOS can be problematic. Dialogs should call queueAppSignal
// instead.
void queueAppSignal(AppSignal signal) { app_signals_ << signal; }
void emitStatCommandSignal(const QString &menu_path, const char *arg, void *userdata);
void emitTapParameterSignal(const QString cfg_abbr, const QString arg, void *userdata);
void addDynamicMenuGroupItem(int group, QAction *sg_action);
void appendDynamicMenuGroupItem(int group, QAction *sg_action);
void removeDynamicMenuGroupItem(int group, QAction *sg_action);
QList<QAction *> dynamicMenuGroupItems(int group);
QList<QAction *> addedMenuGroupItems(int group);
QList<QAction *> removedMenuGroupItems(int group);
void clearAddedMenuGroupItems();
void clearRemovedMenuGroupItems();
void allSystemsGo();
void emitLocalInterfaceEvent(const char *ifname, int added, int up);
virtual void refreshLocalInterfaces();
struct _e_prefs * readConfigurationFiles(bool reset);
QList<recent_item_status *> recentItems() const;
void addRecentItem(const QString filename, qint64 size, bool accessible);
void removeRecentItem(const QString &filename);
QDir lastOpenDir();
void setLastOpenDir(const char *dir_name);
void setLastOpenDirFromFilename(QString file_name);
void helpTopicAction(topic_action_e action);
const QFont monospaceFont(bool zoomed = false) const;
void setMonospaceFont(const char *font_string);
int monospaceTextSize(const char *str);
void setConfigurationProfile(const gchar *profile_name, bool write_recent_file = true);
void reloadLuaPluginsDelayed();
bool isInitialized() { return initialized_; }
void setReloadingLua(bool is_reloading) { is_reloading_lua_ = is_reloading; }
bool isReloadingLua() { return is_reloading_lua_; }
const QIcon &normalIcon();
const QIcon &captureIcon();
const QString &windowTitleSeparator() const { return window_title_separator_; }
const QString windowTitleString(QStringList title_parts);
const QString windowTitleString(QString title_part) { return windowTitleString(QStringList() << title_part); }
void applyCustomColorsFromRecent();
#if defined(HAVE_SOFTWARE_UPDATE) && defined(Q_OS_WIN)
void rejectSoftwareUpdate() { software_update_ok_ = false; }
bool softwareUpdateCanShutdown();
void softwareUpdateShutdownRequest();
#endif
QWidget *mainWindow();
QTranslator translator;
QTranslator translatorQt;
void loadLanguage(const QString language);
void doTriggerMenuItem(MainMenuItem menuItem);
void zoomTextFont(int zoomLevel);
void pushStatus(StatusInfo sinfo, const QString &message, const QString &messagetip = QString());
void popStatus(StatusInfo sinfo);
void gotoFrame(int frameNum);
private:
bool initialized_;
bool is_reloading_lua_;
QFont mono_font_;
QFont zoomed_font_;
QTimer recent_timer_;
QTimer packet_data_timer_;
QTimer tap_update_timer_;
QList<QString> pending_open_files_;
QSocketNotifier *if_notifier_;
static QString window_title_separator_;
QList<AppSignal> app_signals_;
int active_captures_;
#if defined(HAVE_SOFTWARE_UPDATE) && defined(Q_OS_WIN)
bool software_update_ok_;
#endif
void storeCustomColorsInRecent();
void clearDynamicMenuGroupItems();
protected:
bool event(QEvent *event);
virtual void initializeIcons() = 0;
QIcon normal_icon_;
QIcon capture_icon_;
signals:
void appInitialized();
void localInterfaceEvent(const char *ifname, int added, int up);
void localInterfaceListChanged();
void openCaptureFile(QString cf_path, QString display_filter, unsigned int type);
void openCaptureOptions();
void recentPreferencesRead();
void updateRecentCaptureStatus(const QString &filename, qint64 size, bool accessible);
void splashUpdate(register_action_e action, const char *message);
void profileChanging();
void profileNameChanged(const gchar *profile_name);
void freezePacketList(bool changing_profile);
void columnsChanged(); // XXX This recreates the packet list. We might want to rename it accordingly.
void captureFilterListChanged();
void displayFilterListChanged();
void filterExpressionsChanged();
void packetDissectionChanged();
void preferencesChanged();
void addressResolutionChanged();
void columnDataChanged();
void checkDisplayFilter();
void fieldsChanged();
void reloadLuaPlugins();
void startingLuaReload();
void finishedLuaReload();
#if defined(HAVE_SOFTWARE_UPDATE) && defined(Q_OS_WIN)
// Each of these are called from a separate thread.
void softwareUpdateRequested();
void softwareUpdateClose();
void softwareUpdateQuit();
#endif
void openStatCommandDialog(const QString &menu_path, const char *arg, void *userdata);
void openTapParameterDialog(const QString cfg_str, const QString arg, void *userdata);
/* Signals activation and stop of a capture. The value provides the number of active captures */
void captureActive(int);
void zoomRegularFont(const QFont & font);
void zoomMonospaceFont(const QFont & font);
public slots:
void clearRecentCaptures();
void refreshRecentCaptures();
void captureEventHandler(CaptureEvent);
// Flush queued app signals. Should be called from the main window after
// each dialog that calls queueAppSignal closes.
void flushAppSignals();
private slots:
void updateTaps();
void cleanup();
void ifChangeEventsAvailable();
void itemStatusFinished(const QString filename = "", qint64 size = 0, bool accessible = false);
void refreshPacketData();
};
extern MainApplication *mainApp;
/** Global compile time version info */
extern void gather_wireshark_qt_compiled_info(feature_list l);
/** Global runtime version info */
extern void gather_wireshark_runtime_info(feature_list l);
#endif // MAIN_APPLICATION_H |
C++ | wireshark/ui/qt/main_status_bar.cpp | /* main_status_bar.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 "file.h"
#include <epan/expert.h>
#include <epan/prefs.h>
#include <wsutil/filesystem.h>
#include <wsutil/utf8_entities.h>
#include "ui/main_statusbar.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/main_window.h>
#include "capture_file.h"
#include "main_status_bar.h"
#include "profile_dialog.h"
#include <ui/qt/utils/stock_icon.h>
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/capture_file.h>
#include <ui/qt/widgets/clickable_label.h>
#include <QAction>
#include <QActionGroup>
#include <QHBoxLayout>
#include <QSplitter>
#include <QToolButton>
#include <QLatin1Char>
// To do:
// - Use the CaptureFile class.
// XXX - The GTK+ code assigns priorities to these and pushes/pops accordingly.
Q_DECLARE_METATYPE(ProfileDialog::ProfileAction)
// If we ever add support for multiple windows this will need to be replaced.
// See also: main_window.cpp
static MainStatusBar *cur_main_status_bar_ = NULL;
/*
* Push a formatted temporary message onto the statusbar.
*/
void
statusbar_push_temporary_msg(const gchar *msg_format, ...)
{
va_list ap;
QString push_msg;
if (!cur_main_status_bar_) return;
va_start(ap, msg_format);
push_msg = QString::vasprintf(msg_format, ap);
va_end(ap);
mainApp->pushStatus(WiresharkApplication::TemporaryStatus, push_msg);
}
/*
* Update the packets statusbar to the current values
*/
void
packets_bar_update(void)
{
if (!cur_main_status_bar_) return;
cur_main_status_bar_->updateCaptureStatistics(NULL);
}
static const int icon_size = 14; // px
MainStatusBar::MainStatusBar(QWidget *parent) :
QStatusBar(parent),
cap_file_(NULL),
#ifdef HAVE_LIBPCAP
ready_msg_(tr("Ready to load or capture")),
#else
ready_msg_(tr("Ready to load file")),
#endif
cs_fixed_(false),
cs_count_(0)
{
QSplitter *splitter = new QSplitter(this);
QWidget *info_progress = new QWidget(this);
QHBoxLayout *info_progress_hb = new QHBoxLayout(info_progress);
#if defined(Q_OS_WIN)
// Handles are the same color as widgets, at least on Windows 7.
splitter->setHandleWidth(3);
splitter->setStyleSheet(QString(
"QSplitter::handle {"
" border-left: 1px solid palette(mid);"
" border-right: 1px solid palette(mid);"
"}"
));
#endif
#ifdef Q_OS_MAC
profile_status_.setAttribute(Qt::WA_MacSmallSize, true);
#endif
QString button_ss =
"QToolButton {"
" border: none;"
" background: transparent;" // Disables platform style on Windows.
" padding: 0px;"
" margin: 0px;"
"}";
expert_button_ = new QToolButton(this);
expert_button_->setIconSize(QSize(icon_size, icon_size));
expert_button_->setStyleSheet(button_ss);
expert_button_->hide();
// We just want a clickable image. Using a QPushButton or QToolButton would require
// a lot of adjustment.
StockIcon comment_icon("x-capture-comment-update");
comment_button_ = new QToolButton(this);
comment_button_->setIcon(comment_icon);
comment_button_->setIconSize(QSize(icon_size, icon_size));
comment_button_->setStyleSheet(button_ss);
comment_button_->setToolTip(tr("Open the Capture File Properties dialog"));
comment_button_->setEnabled(false);
connect(expert_button_, SIGNAL(clicked(bool)), this, SIGNAL(showExpertInfo()));
connect(comment_button_, SIGNAL(clicked(bool)), this, SIGNAL(editCaptureComment()));
info_progress_hb->setContentsMargins(icon_size / 2, 0, 0, 0);
info_status_.setTemporaryContext(STATUS_CTX_TEMPORARY);
info_status_.setShrinkable(true);
info_progress_hb->addWidget(expert_button_);
info_progress_hb->addWidget(comment_button_);
info_progress_hb->addWidget(&info_status_);
info_progress_hb->addWidget(&progress_frame_);
info_progress_hb->addStretch(10);
splitter->addWidget(info_progress);
splitter->addWidget(&packet_status_);
splitter->addWidget(&profile_status_);
splitter->setStretchFactor(0, 3);
splitter->setStretchFactor(1, 3);
splitter->setStretchFactor(2, 1);
addWidget(splitter, 1);
cur_main_status_bar_ = this;
splitter->hide();
info_status_.pushText(ready_msg_, STATUS_CTX_MAIN);
packets_bar_update();
#ifdef QWINTASKBARPROGRESS_H
progress_frame_.enableTaskbarUpdates(true);
#endif
connect(mainApp, SIGNAL(appInitialized()), splitter, SLOT(show()));
connect(mainApp, SIGNAL(appInitialized()), this, SLOT(appInitialized()));
connect(&info_status_, SIGNAL(toggleTemporaryFlash(bool)),
this, SLOT(toggleBackground(bool)));
connect(mainApp, SIGNAL(profileNameChanged(const gchar *)),
this, SLOT(setProfileName()));
connect(&profile_status_, SIGNAL(clickedAt(QPoint,Qt::MouseButton)),
this, SLOT(showProfileMenu(QPoint,Qt::MouseButton)));
connect(&progress_frame_, SIGNAL(stopLoading()),
this, SIGNAL(stopLoading()));
}
void MainStatusBar::showExpert() {
expertUpdate();
}
void MainStatusBar::captureFileClosing() {
expert_button_->hide();
progress_frame_.captureFileClosing();
popGenericStatus(STATUS_CTX_FIELD);
}
void MainStatusBar::expertUpdate() {
// <img> won't load @2x versions in Qt versions earlier than 5.4.
// https://bugreports.qt.io/browse/QTBUG-36383
// We might have to switch to a QPushButton.
QString stock_name = "x-expert-";
QString tt_text = tr(" is the highest expert information level");
switch(expert_get_highest_severity()) {
case(PI_ERROR):
stock_name.append("error");
tt_text.prepend(tr("ERROR"));
break;
case(PI_WARN):
stock_name.append("warn");
tt_text.prepend(tr("WARNING"));
break;
case(PI_NOTE):
stock_name.append("note");
tt_text.prepend(tr("NOTE"));
break;
case(PI_CHAT):
stock_name.append("chat");
tt_text.prepend(tr("CHAT"));
break;
// case(PI_COMMENT):
// m_expertStatus.setText("<img src=\":/expert/expert_comment.png\"></img>");
// break;
default:
stock_name.append("none");
tt_text = tr("No expert information");
break;
}
StockIcon expert_icon(stock_name);
expert_button_->setIcon(expert_icon);
expert_button_->setToolTip(tt_text);
expert_button_->show();
}
// ui/gtk/main_statusbar.c
void MainStatusBar::setFileName(CaptureFile &cf)
{
if (cf.isValid()) {
popGenericStatus(STATUS_CTX_FILE);
QString msgtip = QString("%1 (%2)")
.arg(cf.capFile()->filename)
.arg(file_size_to_qstring(cf.capFile()->f_datalen));
pushGenericStatus(STATUS_CTX_FILE, cf.fileName(), msgtip);
}
}
void MainStatusBar::changeEvent(QEvent *event)
{
if (event->type() == QEvent::LanguageChange) {
info_status_.popText(STATUS_CTX_MAIN);
info_status_.pushText(ready_msg_, STATUS_CTX_MAIN);
setStatusbarForCaptureFile();
showCaptureStatistics();
setProfileName();
}
QStatusBar::changeEvent(event);
}
void MainStatusBar::setCaptureFile(capture_file *cf)
{
cap_file_ = cf;
comment_button_->setEnabled(cap_file_ != NULL);
}
void MainStatusBar::setStatusbarForCaptureFile()
{
if (cap_file_ && cap_file_->filename && (cap_file_->state != FILE_CLOSED)) {
popGenericStatus(STATUS_CTX_FILE);
QString msgtip = QString("%1 (%2)")
.arg(cap_file_->filename)
.arg(file_size_to_qstring(cap_file_->f_datalen));
pushGenericStatus(STATUS_CTX_FILE,
gchar_free_to_qstring(cf_get_display_name(cap_file_)), msgtip);
}
}
void MainStatusBar::selectedFieldChanged(FieldInformation * finfo)
{
QString item_info;
if (! finfo) {
pushGenericStatus(STATUS_CTX_FIELD, item_info);
return;
}
FieldInformation::HeaderInfo hInfo = finfo->headerInfo();
if (hInfo.isValid)
{
if (hInfo.description.length() > 0) {
item_info.append(hInfo.description);
} else {
item_info.append(hInfo.name);
}
}
if (!item_info.isEmpty()) {
int finfo_length;
if (hInfo.isValid)
item_info.append(" (" + hInfo.abbreviation + ")");
finfo_length = finfo->position().length + finfo->appendix().length;
if (finfo_length > 0) {
item_info.append(", " + tr("%Ln byte(s)", "", finfo_length));
}
}
pushGenericStatus(STATUS_CTX_FIELD, item_info);
}
void MainStatusBar::highlightedFieldChanged(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);
}
pushGenericStatus(STATUS_CTX_BYTE, hint);
}
void MainStatusBar::pushGenericStatus(StatusContext status, const QString &message, const QString &messagetip)
{
LabelStack * stack = &info_status_;
if (status == STATUS_CTX_MAIN)
stack = &packet_status_;
if (message.isEmpty() && status != STATUS_CTX_FILE && status != STATUS_CTX_TEMPORARY && status != STATUS_CTX_PROGRESS)
popGenericStatus(status);
else
stack->pushText(message, status);
stack->setToolTip(messagetip);
if (status == STATUS_CTX_FILTER || status == STATUS_CTX_FILE)
expertUpdate();
}
void MainStatusBar::popGenericStatus(StatusContext status)
{
LabelStack * stack = &info_status_;
if (status == STATUS_CTX_MAIN)
stack = &packet_status_;
stack->setToolTip(QString());
stack->popText(status);
}
void MainStatusBar::setProfileName()
{
profile_status_.setText(tr("Profile: %1").arg(get_profile_name()));
}
void MainStatusBar::appInitialized()
{
setProfileName();
connect(mainApp->mainWindow(), SIGNAL(framesSelected(QList<int>)), this, SLOT(selectedFrameChanged(QList<int>)));
}
void MainStatusBar::selectedFrameChanged(QList<int>)
{
showCaptureStatistics();
}
void MainStatusBar::showCaptureStatistics()
{
QString packets_str;
QList<int> rows;
MainWindow * mw = qobject_cast<MainWindow *>(mainApp->mainWindow());
if (mw)
rows = mw->selectedRows(true);
#ifdef HAVE_LIBPCAP
if (cap_file_) {
/* Do we have any packets? */
if (!cs_fixed_) {
cs_count_ = cap_file_->count;
}
if (cs_count_ > 0) {
if (prefs.gui_show_selected_packet && rows.count() == 1) {
packets_str.append(QString(tr("Selected Packet: %1 %2 "))
.arg(rows.at(0))
.arg(UTF8_MIDDLE_DOT));
}
packets_str.append(QString(tr("Packets: %1 %4 Displayed: %2 (%3%)"))
.arg(cs_count_)
.arg(cap_file_->displayed_count)
.arg((100.0*cap_file_->displayed_count)/cs_count_, 0, 'f', 1)
.arg(UTF8_MIDDLE_DOT));
if (rows.count() > 1) {
packets_str.append(QString(tr(" %1 Selected: %2 (%3%)"))
.arg(UTF8_MIDDLE_DOT)
.arg(rows.count())
.arg((100.0*rows.count())/cs_count_, 0, 'f', 1));
}
if (cap_file_->marked_count > 0) {
packets_str.append(QString(tr(" %1 Marked: %2 (%3%)"))
.arg(UTF8_MIDDLE_DOT)
.arg(cap_file_->marked_count)
.arg((100.0*cap_file_->marked_count)/cs_count_, 0, 'f', 1));
}
if (cap_file_->drops_known) {
packets_str.append(QString(tr(" %1 Dropped: %2 (%3%)"))
.arg(UTF8_MIDDLE_DOT)
.arg(cap_file_->drops)
.arg((100.0*cap_file_->drops)/cs_count_, 0, 'f', 1));
}
if (cap_file_->ignored_count > 0) {
packets_str.append(QString(tr(" %1 Ignored: %2 (%3%)"))
.arg(UTF8_MIDDLE_DOT)
.arg(cap_file_->ignored_count)
.arg((100.0*cap_file_->ignored_count)/cs_count_, 0, 'f', 1));
}
if (cap_file_->packet_comment_count > 0) {
packets_str.append(QString(tr(" %1 Comments: %2"))
.arg(UTF8_MIDDLE_DOT)
.arg(cap_file_->packet_comment_count));
}
if (prefs.gui_show_file_load_time && !cap_file_->is_tempfile) {
/* Loading an existing file */
gulong computed_elapsed = cf_get_computed_elapsed(cap_file_);
packets_str.append(QString(tr(" %1 Load time: %2:%3.%4"))
.arg(UTF8_MIDDLE_DOT)
.arg(computed_elapsed/60000, 2, 10, QLatin1Char('0'))
.arg(computed_elapsed%60000/1000, 2, 10, QLatin1Char('0'))
.arg(computed_elapsed%1000, 3, 10, QLatin1Char('0')));
}
}
} else if (cs_fixed_ && cs_count_ > 0) {
/* There shouldn't be any rows without a cap_file_ but this is benign */
if (prefs.gui_show_selected_packet && rows.count() == 1) {
packets_str.append(QString(tr("Selected Packet: %1 %2 "))
.arg(rows.at(0))
.arg(UTF8_MIDDLE_DOT));
}
packets_str.append(QString(tr("Packets: %1"))
.arg(cs_count_));
}
#endif // HAVE_LIBPCAP
if (packets_str.isEmpty()) {
packets_str = tr("No Packets");
}
popGenericStatus(STATUS_CTX_MAIN);
pushGenericStatus(STATUS_CTX_MAIN, packets_str);
}
void MainStatusBar::updateCaptureStatistics(capture_session *cap_session)
{
cs_fixed_ = false;
#ifndef HAVE_LIBPCAP
Q_UNUSED(cap_session)
#else
if ((!cap_session || cap_session->cf == cap_file_) && cap_file_ && cap_file_->count) {
cs_count_ = cap_file_->count;
} else {
cs_count_ = 0;
}
#endif // HAVE_LIBPCAP
showCaptureStatistics();
}
void MainStatusBar::updateCaptureFixedStatistics(capture_session *cap_session)
{
cs_fixed_ = true;
#ifndef HAVE_LIBPCAP
Q_UNUSED(cap_session)
#else
if (cap_session && cap_session->count) {
cs_count_ = cap_session->count;
} else {
cs_count_ = 0;
}
#endif // HAVE_LIBPCAP
showCaptureStatistics();
}
void MainStatusBar::showProfileMenu(const QPoint &global_pos, Qt::MouseButton button)
{
ProfileModel model;
QMenu * profile_menu = new QMenu(this);
profile_menu->setAttribute(Qt::WA_DeleteOnClose);
QActionGroup * global = new QActionGroup(profile_menu);
QActionGroup * user = new QActionGroup(profile_menu);
for (int cnt = 0; cnt < model.rowCount(); cnt++)
{
QModelIndex idx = model.index(cnt, ProfileModel::COL_NAME);
if (! idx.isValid())
continue;
QAction * pa = Q_NULLPTR;
QString name = idx.data().toString();
// An ampersand in the menu item's text sets Alt+F as a shortcut for this menu.
// Use "&&" to get a real ampersand in the menu bar.
name.replace('&', "&&");
if (idx.data(ProfileModel::DATA_IS_DEFAULT).toBool())
{
pa = profile_menu->addAction(name);
}
else if (idx.data(ProfileModel::DATA_IS_GLOBAL).toBool())
{
/* Check if this profile does not exist as user */
if (cnt == model.findByName(name))
pa = global->addAction(name);
}
else
pa = user->addAction(name);
if (! pa)
continue;
pa->setCheckable(true);
if (idx.data(ProfileModel::DATA_IS_SELECTED).toBool())
pa->setChecked(true);
pa->setFont(idx.data(Qt::FontRole).value<QFont>());
pa->setProperty("profile_name", idx.data());
pa->setProperty("profile_is_global", idx.data(ProfileModel::DATA_IS_GLOBAL));
connect(pa, &QAction::triggered, this, &MainStatusBar::switchToProfile);
}
profile_menu->addActions(user->actions());
profile_menu->addSeparator();
profile_menu->addActions(global->actions());
if (button == Qt::LeftButton) {
profile_menu->popup(global_pos);
} else {
bool enable_edit = false;
QModelIndex idx = model.activeProfile();
if (! idx.data(ProfileModel::DATA_IS_DEFAULT).toBool() && ! idx.data(ProfileModel::DATA_IS_GLOBAL).toBool())
enable_edit = true;
profile_menu->setTitle(tr("Switch to"));
QMenu * ctx_menu_ = new QMenu(this);
ctx_menu_->setAttribute(Qt::WA_DeleteOnClose);
QAction * action = ctx_menu_->addAction(tr("Manage Profiles…"), this, SLOT(manageProfile()));
action->setProperty("dialog_action_", (int)ProfileDialog::ShowProfiles);
ctx_menu_->addSeparator();
action = ctx_menu_->addAction(tr("New…"), this, SLOT(manageProfile()));
action->setProperty("dialog_action_", (int)ProfileDialog::NewProfile);
action = ctx_menu_->addAction(tr("Edit…"), this, SLOT(manageProfile()));
action->setProperty("dialog_action_", (int)ProfileDialog::EditCurrentProfile);
action->setEnabled(enable_edit);
action = ctx_menu_->addAction(tr("Delete"), this, SLOT(manageProfile()));
action->setProperty("dialog_action_", (int)ProfileDialog::DeleteCurrentProfile);
action->setEnabled(enable_edit);
ctx_menu_->addSeparator();
#ifdef HAVE_MINIZIP
QMenu * importMenu = new QMenu(tr("Import"));
action = importMenu->addAction(tr("From Zip File..."), this, SLOT(manageProfile()));
action->setProperty("dialog_action_", (int)ProfileDialog::ImportZipProfile);
action = importMenu->addAction(tr("From Directory..."), this, SLOT(manageProfile()));
action->setProperty("dialog_action_", (int)ProfileDialog::ImportDirProfile);
ctx_menu_->addMenu(importMenu);
if (model.userProfilesExist())
{
QMenu * exportMenu = new QMenu(tr("Export"), ctx_menu_);
if (enable_edit)
{
action = exportMenu->addAction(tr("Selected Personal Profile..."), this, SLOT(manageProfile()));
action->setProperty("dialog_action_", (int)ProfileDialog::ExportSingleProfile);
action->setEnabled(enable_edit);
}
action = exportMenu->addAction(tr("All Personal Profiles..."), this, SLOT(manageProfile()));
action->setProperty("dialog_action_", (int)ProfileDialog::ExportAllProfiles);
ctx_menu_->addMenu(exportMenu);
}
#else
action = ctx_menu_->addAction(tr("Import"), this, SLOT(manageProfile()));
action->setProperty("dialog_action_", (int)ProfileDialog::ImportDirProfile);
#endif
ctx_menu_->addSeparator();
ctx_menu_->addMenu(profile_menu);
ctx_menu_->popup(global_pos);
}
}
void MainStatusBar::toggleBackground(bool enabled)
{
if (enabled) {
setStyleSheet(QString(
"QStatusBar {"
" background-color: %2;"
"}"
)
.arg(ColorUtils::warningBackground().name()));
} else {
setStyleSheet(QString());
}
}
void MainStatusBar::switchToProfile()
{
QAction *pa = qobject_cast<QAction*>(sender());
if (pa && pa->property("profile_name").isValid()) {
QString profile = pa->property("profile_name").toString();
mainApp->setConfigurationProfile(profile.toUtf8().constData());
}
}
void MainStatusBar::manageProfile()
{
QAction *pa = qobject_cast<QAction*>(sender());
if (pa) {
ProfileDialog * cp_dialog = new ProfileDialog(this);
cp_dialog->setAttribute(Qt::WA_DeleteOnClose);
int profileAction = pa->property("dialog_action_").toInt();
cp_dialog->execAction(static_cast<ProfileDialog::ProfileAction>(profileAction));
}
}
void MainStatusBar::captureEventHandler(CaptureEvent ev)
{
switch(ev.captureContext())
{
#ifdef HAVE_LIBPCAP
case CaptureEvent::Update:
switch (ev.eventType())
{
case CaptureEvent::Continued:
updateCaptureStatistics(ev.capSession());
break;
case CaptureEvent::Finished:
updateCaptureStatistics(ev.capSession());
break;
default:
break;
}
break;
case CaptureEvent::Fixed:
switch (ev.eventType())
{
case CaptureEvent::Continued:
updateCaptureFixedStatistics(ev.capSession());
break;
default:
break;
}
break;
#endif
case CaptureEvent::Save:
switch (ev.eventType())
{
case CaptureEvent::Finished:
case CaptureEvent::Failed:
case CaptureEvent::Stopped:
popGenericStatus(STATUS_CTX_FILE);
break;
default:
break;
}
break;
default:
break;
}
} |
C/C++ | wireshark/ui/qt/main_status_bar.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef MAIN_STATUS_BAR_H
#define MAIN_STATUS_BAR_H
#include "config.h"
#include "cfile.h"
#include "capture/capture_session.h"
#include <ui/qt/utils/field_information.h>
#include <ui/qt/widgets/label_stack.h>
#include <ui/qt/widgets/clickable_label.h>
#include "progress_frame.h"
#include "wireshark_application.h"
#include <QLabel>
#include <QMenu>
#include <QStatusBar>
class CaptureFile;
class QToolButton;
class MainStatusBar : public QStatusBar
{
Q_OBJECT
public:
explicit MainStatusBar(QWidget *parent = 0);
void showExpert();
void captureFileClosing();
void expertUpdate();
void setFileName(CaptureFile &cf);
protected:
enum StatusContext {
STATUS_CTX_MAIN,
STATUS_CTX_FILE,
STATUS_CTX_FIELD,
STATUS_CTX_BYTE,
STATUS_CTX_FILTER,
STATUS_CTX_PROGRESS,
STATUS_CTX_TEMPORARY
};
virtual void changeEvent(QEvent* event);
private:
QToolButton *expert_button_;
QToolButton *comment_button_;
LabelStack info_status_;
ProgressFrame progress_frame_;
LabelStack packet_status_;
ClickableLabel profile_status_;
capture_file *cap_file_;
QString ready_msg_;
// Capture statistics
bool cs_fixed_;
guint32 cs_count_;
void showCaptureStatistics();
void setStatusbarForCaptureFile();
void pushGenericStatus(StatusContext status, const QString &message, const QString &messagetip = QString());
void popGenericStatus(StatusContext status);
signals:
void showExpertInfo();
void editCaptureComment();
void stopLoading();
public slots:
void setCaptureFile(capture_file *cf);
void selectedFieldChanged(FieldInformation *);
void highlightedFieldChanged(FieldInformation *);
void selectedFrameChanged(QList<int>);
void updateCaptureStatistics(capture_session * cap_session);
void updateCaptureFixedStatistics(capture_session * cap_session);
void captureEventHandler(CaptureEvent ev);
private slots:
void appInitialized();
void toggleBackground(bool enabled);
void setProfileName();
void switchToProfile();
void manageProfile();
void showProfileMenu(const QPoint &global_pos, Qt::MouseButton button);
friend MainApplication;
};
#endif // MAIN_STATUS_BAR_H |
C++ | wireshark/ui/qt/main_window.cpp | /* main_window.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 "ui/preference_utils.h"
#include "main_window.h"
#include "funnel_statistics.h"
#include "packet_list.h"
#include "widgets/display_filter_combo.h"
// Packet Menu actions
static QList<QAction *> dynamic_packet_menu_actions;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
main_stack_(nullptr),
welcome_page_(nullptr),
cur_layout_(QVector<unsigned>()),
packet_list_(nullptr),
proto_tree_(nullptr),
byte_view_tab_(nullptr),
packet_diagram_(nullptr),
df_combo_box_(nullptr),
main_status_bar_(nullptr)
{
}
MainWindow::~MainWindow()
{
clearAddedPacketMenus();
}
bool MainWindow::hasSelection()
{
if (packet_list_)
return packet_list_->multiSelectActive();
return false;
}
/*
* As hasSelection() is not looking for one single packet
* selection, but at least 2, this method returns TRUE in
* this specific case.
*/
bool MainWindow::hasUniqueSelection()
{
if (packet_list_)
return packet_list_->uniqueSelectActive();
return false;
}
QList<int> MainWindow::selectedRows(bool useFrameNum)
{
if (packet_list_)
return packet_list_->selectedRows(useFrameNum);
return QList<int>();
}
frame_data* MainWindow::frameDataForRow(int row) const
{
if (packet_list_)
return packet_list_->getFDataForRow(row);
return Q_NULLPTR;
}
void MainWindow::insertColumn(QString name, QString abbrev, gint pos)
{
gint colnr = 0;
if (name.length() > 0 && abbrev.length() > 0)
{
colnr = column_prefs_add_custom(COL_CUSTOM, name.toStdString().c_str(), abbrev.toStdString().c_str(), pos);
packet_list_->columnsChanged();
packet_list_->resizeColumnToContents(colnr);
prefs_main_write();
}
}
void MainWindow::gotoFrame(int packet_num)
{
if (packet_num > 0) {
packet_list_->goToPacket(packet_num);
}
}
QString MainWindow::getFilter()
{
return df_combo_box_->currentText();
}
MainStatusBar *MainWindow::statusBar()
{
return main_status_bar_;
}
void MainWindow::setDisplayFilter(QString filter, FilterAction::Action action, FilterAction::ActionType filterType)
{
emit filterAction(filter, action, filterType);
}
/*
* Used for registering custom packet menus
*
* @param funnel_action a custom packet menu action
*/
void MainWindow::appendPacketMenu(QAction* funnel_action)
{
dynamic_packet_menu_actions.append(funnel_action);
connect(funnel_action, SIGNAL(triggered(bool)), funnel_action, SLOT(triggerPacketCallback()));
}
/*
* Returns the list of registered packet menu actions
*
* After ensuring that all stored custom packet menu actions
* are registered with the Wireshark GUI, it returns them as a list
* so that they can potentially be displayed to a user.
*
* @return the list of registered packet menu actions
*/
QList<QAction *> MainWindow::getPacketMenuActions()
{
if (funnel_statistics_packet_menus_modified()) {
// If the packet menus were modified, we need to clear the already
// loaded packet menus to avoid duplicates
this->clearAddedPacketMenus();
funnel_statistics_load_packet_menus();
}
return dynamic_packet_menu_actions;
}
/*
* Clears the list of registered packet menu actions
*
* Clears the list of registered packet menu actions
* and frees all associated memory.
*/
void MainWindow::clearAddedPacketMenus()
{
for( int i=0; i<dynamic_packet_menu_actions.count(); ++i )
{
delete dynamic_packet_menu_actions[i];
}
dynamic_packet_menu_actions.clear();
}
/*
* Adds the custom packet menus to the supplied QMenu
*
* This method takes in QMenu and the selected packet's data
* and adds all applicable custom packet menus to it.
*
* @param ctx_menu The menu to add the packet menu entries to
* @param finfo_array The data in the selected packet
* @return true if a packet menu was added to the ctx_menu
*/
bool MainWindow::addPacketMenus(QMenu * ctx_menu, GPtrArray *finfo_array)
{
bool insertedPacketMenu = false;
QList<QAction *> myPacketMenuActions = this->getPacketMenuActions();
if (myPacketMenuActions.isEmpty()) {
return insertedPacketMenu;
}
// Build a set of fields present for efficient lookups
QSet<QString> fieldsPresent = QSet<QString>();
for (guint fieldInfoIndex = 0; fieldInfoIndex < finfo_array->len; fieldInfoIndex++) {
field_info *fi = (field_info *)g_ptr_array_index (finfo_array, fieldInfoIndex);
fieldsPresent.insert(QString(fi->hfinfo->abbrev));
}
// Place actions in the relevant (sub)menu
// The 'root' menu is the ctx_menu, so map NULL to that
QHash<QString, QMenu *> menuTextToMenus;
menuTextToMenus.insert(NULL, ctx_menu);
foreach (QAction * action, myPacketMenuActions) {
if (! qobject_cast<FunnelAction *>(action)) {
continue;
}
FunnelAction * packetAction = qobject_cast<FunnelAction *>(action);
// Only display a menu if all required fields are present
if (!fieldsPresent.contains(packetAction->getPacketRequiredFields())) {
continue;
}
packetAction->setPacketData(finfo_array);
packetAction->addToMenu(ctx_menu, menuTextToMenus);
insertedPacketMenu = true;
}
return insertedPacketMenu;
} |
C/C++ | wireshark/ui/qt/main_window.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <epan/prefs.h>
#include <epan/stat_groups.h>
#include <epan/frame_data.h>
// frame_data also available with this include in the original wireshark_main_window code
//#include "follow_stream_dialog.h"
#include "filter_action.h"
#include <QMainWindow>
#include <QSplitter>
class QSplitter;
class QStackedWidget;
class ByteViewTab;
class DisplayFilterCombo;
class FieldInformation;
class MainStatusBar;
class PacketDiagram;
class PacketList;
class ProtoTree;
class WelcomePage;
typedef struct _capture_file capture_file;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
bool hasSelection();
bool hasUniqueSelection();
QList<int> selectedRows(bool useFrameNum = false);
void insertColumn(QString name, QString abbrev, gint pos = -1);
void gotoFrame(int packet_num);
frame_data* frameDataForRow(int) const;
QString getFilter();
MainStatusBar *statusBar();
// Used for managing custom packet menus
void appendPacketMenu(QAction* funnel_action);
QList<QAction*> getPacketMenuActions();
void clearAddedPacketMenus();
bool addPacketMenus(QMenu * ctx_menu, GPtrArray *finfo_array);
public slots:
void setDisplayFilter(QString filter, FilterAction::Action action, FilterAction::ActionType filterType);
virtual void filterPackets(QString, bool) = 0;
virtual void showPreferencesDialog(QString module_name) = 0;
void layoutPanes();
void applyRecentPaneGeometry();
protected:
enum CopySelected {
CopyAllVisibleItems,
CopyAllVisibleSelectedTreeItems,
CopySelectedDescription,
CopySelectedFieldName,
CopySelectedValue,
CopyListAsText,
CopyListAsCSV,
CopyListAsYAML
};
void showWelcome();
void showCapture();
QList<register_stat_group_t> menu_groups_;
QWidget* getLayoutWidget(layout_pane_content_e type);
QStackedWidget *main_stack_;
WelcomePage *welcome_page_;
QSplitter master_split_;
QSplitter extra_split_;
QWidget empty_pane_;
QVector<unsigned> cur_layout_;
PacketList *packet_list_;
ProtoTree *proto_tree_;
ByteViewTab *byte_view_tab_;
PacketDiagram *packet_diagram_;
DisplayFilterCombo *df_combo_box_;
MainStatusBar *main_status_bar_;
signals:
void setCaptureFile(capture_file *cf);
void fieldSelected(FieldInformation *);
void framesSelected(QList<int>);
void filterAction(QString filter, FilterAction::Action action, FilterAction::ActionType type);
void displayFilterSuccess(bool success);
};
#endif // MAINWINDOW_H |
C++ | wireshark/ui/qt/main_window_layout.cpp | /* main_window_layout.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <config.h>
#include <ui/qt/main_window.h>
#include <ui/qt/widgets/additional_toolbar.h>
#include "ui/recent.h"
#include "epan/prefs.h"
#include <QSplitter>
#include <QVector>
#include <QList>
#include <QWidget>
#include <QRect>
#include <QAction>
#include <QStackedWidget>
#include <QToolBar>
#include <ui/qt/byte_view_tab.h>
#include <ui/qt/packet_list.h>
#include <ui/qt/packet_diagram.h>
#include <ui/qt/proto_tree.h>
#include <ui/qt/welcome_page.h>
#include <wsutil/ws_assert.h>
void MainWindow::showWelcome()
{
main_stack_->setCurrentWidget(welcome_page_);
}
void MainWindow::showCapture()
{
main_stack_->setCurrentWidget(&master_split_);
}
QWidget* MainWindow::getLayoutWidget(layout_pane_content_e type) {
switch (type) {
case layout_pane_content_none:
return &empty_pane_;
case layout_pane_content_plist:
return packet_list_;
case layout_pane_content_pdetails:
return proto_tree_;
case layout_pane_content_pbytes:
return byte_view_tab_;
case layout_pane_content_pdiagram:
return packet_diagram_;
default:
ws_assert_not_reached();
return NULL;
}
}
// A new layout should be applied when it differs from the old layout AND
// at the following times:
// - At startup
// - When the preferences change
// - When the profile changes
void MainWindow::layoutPanes()
{
QVector<unsigned> new_layout = QVector<unsigned>() << prefs.gui_layout_type
<< prefs.gui_layout_content_1
<< prefs.gui_layout_content_2
<< prefs.gui_layout_content_3
<< recent.packet_list_show
<< recent.tree_view_show
<< recent.byte_view_show
<< recent.packet_diagram_show;
if (cur_layout_ == new_layout) return;
QSplitter *parents[3];
// Reparent all widgets and add them back in the proper order below.
// This hides each widget as well.
bool frozen = packet_list_->freeze(); // Clears tree, byte view tabs, and diagram.
packet_list_->setParent(main_stack_);
proto_tree_->setParent(main_stack_);
byte_view_tab_->setParent(main_stack_);
packet_diagram_->setParent(main_stack_);
empty_pane_.setParent(main_stack_);
extra_split_.setParent(main_stack_);
// XXX We should try to preserve geometries if we can, e.g. by
// checking to see if the layout type is the same.
switch(prefs.gui_layout_type) {
case(layout_type_2):
case(layout_type_1):
extra_split_.setOrientation(Qt::Horizontal);
/* Fall Through */
case(layout_type_5):
master_split_.setOrientation(Qt::Vertical);
break;
case(layout_type_4):
case(layout_type_3):
extra_split_.setOrientation(Qt::Vertical);
/* Fall Through */
case(layout_type_6):
master_split_.setOrientation(Qt::Horizontal);
break;
default:
ws_assert_not_reached();
}
switch(prefs.gui_layout_type) {
case(layout_type_5):
case(layout_type_6):
parents[0] = &master_split_;
parents[1] = &master_split_;
parents[2] = &master_split_;
break;
case(layout_type_2):
case(layout_type_4):
parents[0] = &master_split_;
parents[1] = &extra_split_;
parents[2] = &extra_split_;
break;
case(layout_type_1):
case(layout_type_3):
parents[0] = &extra_split_;
parents[1] = &extra_split_;
parents[2] = &master_split_;
break;
default:
ws_assert_not_reached();
}
if (parents[0] == &extra_split_) {
master_split_.addWidget(&extra_split_);
}
parents[0]->addWidget(getLayoutWidget(prefs.gui_layout_content_1));
if (parents[2] == &extra_split_) {
master_split_.addWidget(&extra_split_);
}
parents[1]->addWidget(getLayoutWidget(prefs.gui_layout_content_2));
parents[2]->addWidget(getLayoutWidget(prefs.gui_layout_content_3));
if (frozen) {
// Show the packet list here to prevent pending resize events changing columns
// when the packet list is set as current widget for the first time.
packet_list_->show();
}
const QList<QWidget *> ms_children = master_split_.findChildren<QWidget *>();
extra_split_.setVisible(ms_children.contains(&extra_split_));
packet_list_->setVisible(ms_children.contains(packet_list_) && recent.packet_list_show);
proto_tree_->setVisible(ms_children.contains(proto_tree_) && recent.tree_view_show);
byte_view_tab_->setVisible(ms_children.contains(byte_view_tab_) && recent.byte_view_show);
packet_diagram_->setVisible(ms_children.contains(packet_diagram_) && recent.packet_diagram_show);
if (frozen) {
packet_list_->thaw(true);
}
cur_layout_ = new_layout;
}
// The recent layout geometry should be applied after the layout has been
// applied AND at the following times:
// - At startup
// - When the profile changes
void MainWindow::applyRecentPaneGeometry()
{
// XXX This shrinks slightly each time the application is run. For some
// reason the master_split_ geometry is two pixels shorter when
// saveWindowGeometry is invoked.
// This is also an awful lot of trouble to go through to reuse the GTK+
// pane settings. We might want to add gui.geometry_main_master_sizes
// and gui.geometry_main_extra_sizes and save QSplitter::saveState in
// each.
// Force a geometry recalculation
QWidget *cur_w = main_stack_->currentWidget();
showCapture();
QRect geom = main_stack_->geometry();
QList<int> master_sizes = master_split_.sizes();
QList<int> extra_sizes = extra_split_.sizes();
main_stack_->setCurrentWidget(cur_w);
int master_last_size = master_split_.orientation() == Qt::Vertical ? geom.height() : geom.width();
master_last_size -= master_split_.handleWidth() * (master_sizes.length() - 1);
int extra_last_size = extra_split_.orientation() == Qt::Vertical ? geom.height() : geom.width();
extra_last_size -= extra_split_.handleWidth();
if (recent.gui_geometry_main_upper_pane > 0) {
master_sizes[0] = recent.gui_geometry_main_upper_pane;
master_last_size -= recent.gui_geometry_main_upper_pane;
} else {
master_sizes[0] = master_last_size / master_sizes.length();
master_last_size -= master_last_size / master_sizes.length();
}
if (recent.gui_geometry_main_lower_pane > 0) {
if (master_sizes.length() > 2) {
master_sizes[1] = recent.gui_geometry_main_lower_pane;
master_last_size -= recent.gui_geometry_main_lower_pane;
} else if (extra_sizes.length() > 0) {
extra_sizes[0] = recent.gui_geometry_main_lower_pane;
extra_last_size -= recent.gui_geometry_main_lower_pane;
extra_sizes.last() = extra_last_size;
}
} else {
if (master_sizes.length() > 2) {
master_sizes[1] = master_last_size / 2;
master_last_size -= master_last_size / 2;
} else if (extra_sizes.length() > 0) {
extra_sizes[0] = extra_last_size / 2;
extra_last_size -= extra_last_size / 2;
extra_sizes.last() = extra_last_size;
}
}
master_sizes.last() = master_last_size;
master_split_.setSizes(master_sizes);
extra_split_.setSizes(extra_sizes);
} |
C++ | wireshark/ui/qt/main_window_preferences_frame.cpp | /* main_window_preferences_frame.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "main_window_preferences_frame.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui_main_window_preferences_frame.h>
#include "ui/language.h"
#include <epan/prefs-int.h>
#include <ui/qt/models/pref_models.h>
#include <ui/qt/utils/color_utils.h>
#include <wsutil/filesystem.h>
#include "ui/qt/widgets/wireshark_file_dialog.h"
#include <QDebug>
MainWindowPreferencesFrame::MainWindowPreferencesFrame(QWidget *parent) :
QFrame(parent),
ui(new Ui::MainWindowPreferencesFrame)
{
ui->setupUi(this);
pref_geometry_save_position_ = prefFromPrefPtr(&prefs.gui_geometry_save_position);
pref_geometry_save_size_ = prefFromPrefPtr(&prefs.gui_geometry_save_size);
pref_geometry_save_maximized_ = prefFromPrefPtr(&prefs.gui_geometry_save_maximized);
pref_fileopen_style_ = prefFromPrefPtr(&prefs.gui_fileopen_style);
pref_fileopen_dir_ = prefFromPrefPtr(&prefs.gui_fileopen_dir);
pref_recent_df_entries_max_ = prefFromPrefPtr(&prefs.gui_recent_df_entries_max);
pref_recent_files_count_max_ = prefFromPrefPtr(&prefs.gui_recent_files_count_max);
pref_ask_unsaved_ = prefFromPrefPtr(&prefs.gui_ask_unsaved);
pref_autocomplete_filter_ = prefFromPrefPtr(&prefs.gui_autocomplete_filter);
pref_toolbar_main_style_ = prefFromPrefPtr(&prefs.gui_toolbar_main_style);
pref_window_title_ = prefFromPrefPtr(&prefs.gui_window_title);
pref_prepend_window_title_ = prefFromPrefPtr(&prefs.gui_prepend_window_title);
QStyleOption style_opt;
QString indent_ss = QString(
"QRadioButton, QLineEdit, QLabel {"
" margin-left: %1px;"
"}"
).arg(ui->geometryCheckBox->style()->subElementRect(QStyle::SE_CheckBoxContents, &style_opt).left());
ui->foStyleLastOpenedRadioButton->setStyleSheet(indent_ss);
ui->foStyleSpecifiedRadioButton->setStyleSheet(indent_ss);
ui->maxFilterLineEdit->setStyleSheet(indent_ss);
ui->maxRecentLineEdit->setStyleSheet(indent_ss);
int num_entry_width = ui->maxFilterLineEdit->fontMetrics().height() * 3;
ui->maxFilterLineEdit->setMaximumWidth(num_entry_width);
ui->maxRecentLineEdit->setMaximumWidth(num_entry_width);
QString li_path = QString(":/languages/language%1.svg").arg(ColorUtils::themeIsDark() ? ".dark" : "");
QIcon language_icon = QIcon(li_path);
ui->languageComboBox->setItemIcon(0, language_icon);
QString globalLanguagesPath(QString(get_datafile_dir()) + "/languages/");
QString userLanguagesPath(gchar_free_to_qstring(get_persconffile_path("languages/", FALSE)));
QStringList filenames = QDir(":/i18n/").entryList(QStringList("wireshark_*.qm"));
filenames += QDir(globalLanguagesPath).entryList(QStringList("wireshark_*.qm"));
filenames += QDir(userLanguagesPath).entryList(QStringList("wireshark_*.qm"));
for (int i = 0; i < filenames.size(); i += 1) {
QString locale;
locale = filenames[i];
locale.truncate(locale.lastIndexOf('.'));
locale.remove(0, locale.indexOf('_') + 1);
QString lang = QLocale::languageToString(QLocale(locale).language());
ui->languageComboBox->addItem(lang, locale);
}
ui->languageComboBox->setItemData(0, USE_SYSTEM_LANGUAGE);
ui->languageComboBox->model()->sort(0);
for (int i = 0; i < ui->languageComboBox->count(); i += 1) {
if (QString(language) == ui->languageComboBox->itemData(i).toString()) {
ui->languageComboBox->setCurrentIndex(i);
break;
}
}
}
MainWindowPreferencesFrame::~MainWindowPreferencesFrame()
{
delete ui;
}
void MainWindowPreferencesFrame::showEvent(QShowEvent *)
{
updateWidgets();
}
void MainWindowPreferencesFrame::updateWidgets()
{
// Yes, this means we're potentially clobbering two prefs in favor of one.
if (prefs_get_bool_value(pref_geometry_save_position_, pref_stashed) || prefs_get_bool_value(pref_geometry_save_size_, pref_stashed) || prefs_get_bool_value(pref_geometry_save_maximized_, pref_stashed)) {
ui->geometryCheckBox->setChecked(true);
} else {
ui->geometryCheckBox->setChecked(false);
}
if (prefs_get_enum_value(pref_fileopen_style_, pref_stashed) == FO_STYLE_LAST_OPENED) {
ui->foStyleLastOpenedRadioButton->setChecked(true);
} else {
ui->foStyleSpecifiedRadioButton->setChecked(true);
}
ui->foStyleSpecifiedLineEdit->setText(prefs_get_string_value(pref_fileopen_dir_, pref_stashed));
ui->maxFilterLineEdit->setText(QString::number(prefs_get_uint_value_real(pref_recent_df_entries_max_, pref_stashed)));
ui->maxRecentLineEdit->setText(QString::number(prefs_get_uint_value_real(pref_recent_files_count_max_, pref_stashed)));
ui->confirmUnsavedCheckBox->setChecked(prefs_get_bool_value(pref_ask_unsaved_, pref_stashed));
ui->displayAutoCompleteCheckBox->setChecked(prefs_get_bool_value(pref_autocomplete_filter_, pref_stashed));
ui->mainToolbarComboBox->setCurrentIndex(prefs_get_enum_value(pref_toolbar_main_style_, pref_stashed));
for (int i = 0; i < ui->languageComboBox->count(); i += 1) {
if (QString(language) == ui->languageComboBox->itemData(i).toString()) {
ui->languageComboBox->setCurrentIndex(i);
break;
}
}
ui->windowTitle->setText(prefs_get_string_value(pref_window_title_, pref_stashed));
ui->prependWindowTitle->setText(prefs_get_string_value(pref_prepend_window_title_, pref_stashed));
}
void MainWindowPreferencesFrame::on_geometryCheckBox_toggled(bool checked)
{
prefs_set_bool_value(pref_geometry_save_position_, checked, pref_stashed);
prefs_set_bool_value(pref_geometry_save_size_, checked, pref_stashed);
prefs_set_bool_value(pref_geometry_save_maximized_, checked, pref_stashed);
}
void MainWindowPreferencesFrame::on_foStyleLastOpenedRadioButton_toggled(bool checked)
{
if (checked) {
prefs_set_enum_value(pref_fileopen_style_, FO_STYLE_LAST_OPENED, pref_stashed);
}
}
void MainWindowPreferencesFrame::on_foStyleSpecifiedRadioButton_toggled(bool checked)
{
if (checked) {
prefs_set_enum_value(pref_fileopen_style_, FO_STYLE_SPECIFIED, pref_stashed);
}
}
void MainWindowPreferencesFrame::on_foStyleSpecifiedLineEdit_textEdited(const QString &new_dir)
{
prefs_set_string_value(pref_fileopen_dir_, new_dir.toStdString().c_str(), pref_stashed);
ui->foStyleSpecifiedRadioButton->setChecked(true);
}
void MainWindowPreferencesFrame::on_foStyleSpecifiedPushButton_clicked()
{
QString specified_dir = WiresharkFileDialog::getExistingDirectory(this, tr("Open Files In"));
if (specified_dir.isEmpty()) return;
ui->foStyleSpecifiedLineEdit->setText(specified_dir);
prefs_set_string_value(pref_fileopen_dir_, specified_dir.toStdString().c_str(), pref_stashed);
ui->foStyleSpecifiedRadioButton->setChecked(true);
}
void MainWindowPreferencesFrame::on_maxFilterLineEdit_textEdited(const QString &new_max)
{
prefs_set_uint_value(pref_recent_df_entries_max_, new_max.toUInt(), pref_stashed);
}
void MainWindowPreferencesFrame::on_maxRecentLineEdit_textEdited(const QString &new_max)
{
prefs_set_uint_value(pref_recent_files_count_max_, new_max.toUInt(), pref_stashed);
}
void MainWindowPreferencesFrame::on_confirmUnsavedCheckBox_toggled(bool checked)
{
prefs_set_bool_value(pref_ask_unsaved_, checked, pref_stashed);
}
void MainWindowPreferencesFrame::on_displayAutoCompleteCheckBox_toggled(bool checked)
{
prefs_set_bool_value(pref_autocomplete_filter_, checked, pref_stashed);
}
void MainWindowPreferencesFrame::on_mainToolbarComboBox_currentIndexChanged(int index)
{
prefs_set_enum_value(pref_toolbar_main_style_, index, pref_stashed);
}
void MainWindowPreferencesFrame::on_languageComboBox_currentIndexChanged(int index)
{
g_free(language);
language = qstring_strdup(ui->languageComboBox->itemData(index).toString());
}
void MainWindowPreferencesFrame::on_windowTitle_textEdited(const QString &new_title)
{
prefs_set_string_value(pref_window_title_, new_title.toStdString().c_str(), pref_stashed);
}
void MainWindowPreferencesFrame::on_prependWindowTitle_textEdited(const QString &new_prefix)
{
prefs_set_string_value(pref_prepend_window_title_, new_prefix.toStdString().c_str(), pref_stashed);
} |
C/C++ | wireshark/ui/qt/main_window_preferences_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 MAIN_WINDOW_PREFERENCES_FRAME_H
#define MAIN_WINDOW_PREFERENCES_FRAME_H
#include <epan/prefs.h>
#include <QFrame>
namespace Ui {
class MainWindowPreferencesFrame;
}
class MainWindowPreferencesFrame : public QFrame
{
Q_OBJECT
public:
explicit MainWindowPreferencesFrame(QWidget *parent = 0);
~MainWindowPreferencesFrame();
protected:
void showEvent(QShowEvent *evt);
private:
Ui::MainWindowPreferencesFrame *ui;
pref_t *pref_geometry_save_position_;
pref_t *pref_geometry_save_size_;
pref_t *pref_geometry_save_maximized_;
pref_t *pref_fileopen_style_;
pref_t *pref_fileopen_dir_;
pref_t *pref_recent_df_entries_max_;
pref_t *pref_recent_files_count_max_;
pref_t *pref_ask_unsaved_;
pref_t *pref_autocomplete_filter_;
pref_t *pref_toolbar_main_style_;
pref_t *pref_window_title_;
pref_t *pref_prepend_window_title_;
void updateWidgets();
private slots:
void on_geometryCheckBox_toggled(bool checked);
void on_foStyleLastOpenedRadioButton_toggled(bool checked);
void on_foStyleSpecifiedRadioButton_toggled(bool checked);
void on_foStyleSpecifiedLineEdit_textEdited(const QString &new_dir);
void on_foStyleSpecifiedPushButton_clicked();
void on_maxFilterLineEdit_textEdited(const QString &new_max);
void on_maxRecentLineEdit_textEdited(const QString &new_max);
void on_confirmUnsavedCheckBox_toggled(bool checked);
void on_displayAutoCompleteCheckBox_toggled(bool checked);
void on_mainToolbarComboBox_currentIndexChanged(int index);
void on_languageComboBox_currentIndexChanged(int index);
void on_windowTitle_textEdited(const QString &new_title);
void on_prependWindowTitle_textEdited(const QString &new_prefix);
};
#endif // MAIN_WINDOW_PREFERENCES_FRAME_H |
User Interface | wireshark/ui/qt/main_window_preferences_frame.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindowPreferencesFrame</class>
<widget class="QFrame" name="MainWindowPreferencesFrame">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>405</width>
<height>445</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>384</height>
</size>
</property>
<property name="windowTitle">
<string>Frame</string>
</property>
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Plain</enum>
</property>
<property name="lineWidth">
<number>0</number>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QCheckBox" name="geometryCheckBox">
<property name="toolTip">
<string>Checking this will save the size, position, and maximized state of the main window.</string>
</property>
<property name="text">
<string>Remember main window size and placement</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Open files in</string>
</property>
</widget>
</item>
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="1" column="0">
<widget class="QRadioButton" name="foStyleSpecifiedRadioButton">
<property name="text">
<string>This folder:</string>
</property>
<attribute name="buttonGroup">
<string notr="true">openInButtonGroup</string>
</attribute>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="foStyleSpecifiedLineEdit"/>
</item>
<item row="1" column="2">
<widget class="QPushButton" name="foStyleSpecifiedPushButton">
<property name="text">
<string>Browse…</string>
</property>
</widget>
</item>
<item row="0" column="0" colspan="3">
<widget class="QRadioButton" name="foStyleLastOpenedRadioButton">
<property name="text">
<string>The most recently used folder</string>
</property>
<attribute name="buttonGroup">
<string notr="true">openInButtonGroup</string>
</attribute>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Show up to</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2" stretch="0,0,1">
<item>
<widget class="QLineEdit" name="maxFilterLineEdit"/>
</item>
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>filter entries</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>
<layout class="QHBoxLayout" name="horizontalLayout_3" stretch="0,0,1">
<item>
<widget class="QLineEdit" name="maxRecentLineEdit"/>
</item>
<item>
<widget class="QLabel" name="label_4">
<property name="text">
<string>recent files</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<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="QCheckBox" name="confirmUnsavedCheckBox">
<property name="text">
<string>Confirm unsaved capture files</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="displayAutoCompleteCheckBox">
<property name="text">
<string>Display autocompletion for filter text</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label_5">
<property name="text">
<string>Main toolbar style:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="mainToolbarComboBox">
<item>
<property name="text">
<string>Icons only</string>
</property>
</item>
<item>
<property name="text">
<string>Text only</string>
</property>
</item>
<item>
<property name="text">
<string>Icons & Text</string>
</property>
</item>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_4">
<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>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QLabel" name="label_6">
<property name="text">
<string>Window title</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="windowTitle">
<property name="toolTip">
<string><html><head/><body><p>Custom window title to be appended to the existing title<br/>%F = file path of the capture file<br/>%P = profile name<br/>%S = a conditional separator (&quot; - &quot;) that only shows when surrounded by variables with values or static text<br/>%V = version info</p></body></html></string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_5">
<item>
<widget class="QLabel" name="label_8">
<property name="text">
<string>Prepend window title</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="prependWindowTitle">
<property name="toolTip">
<string><html><head/><body><p>Custom window title to be prepended to the existing title<br/>%F = file path of the capture file<br/>%P = profile name<br/>%S = a conditional separator (&quot; - &quot;) that only shows when surrounded by variables with values or static text<br/>%V = version info</p></body></html></string>
</property>
</widget>
</item>
</layout>
</item>
<!-- Language should be the last item. -->
<item>
<layout class="QHBoxLayout" name="horizontalLayout_6">
<item>
<widget class="QLabel" name="label_7">
<property name="text">
<string>Language: </string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="languageComboBox">
<property name="enabled">
<bool>true</bool>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<item>
<property name="text">
<string>Use system setting</string>
</property>
</item>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_6">
<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>
<!-- Language should be the last item. -->
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>1</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<resources/>
<connections/>
<buttongroups>
<buttongroup name="openInButtonGroup"/>
</buttongroups>
</ui> |
C++ | wireshark/ui/qt/manage_interfaces_dialog.cpp | /* manage_interfaces_dialog.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <wireshark.h>
#include "manage_interfaces_dialog.h"
#include <ui_manage_interfaces_dialog.h>
#include "epan/prefs.h"
#include "epan/to_str.h"
#include "capture_opts.h"
#include "ui/capture_globals.h"
#include "ui/qt/capture_options_dialog.h"
#include <ui/qt/models/interface_tree_cache_model.h>
#include <ui/qt/models/interface_sort_filter_model.h>
#ifdef HAVE_PCAP_REMOTE
#include "ui/qt/remote_capture_dialog.h"
#include "ui/qt/remote_settings_dialog.h"
#include "capture/capture-pcap-util.h"
#include "ui/recent.h"
#endif
#include "ui/iface_lists.h"
#include "ui/preference_utils.h"
#include "ui/ws_ui_util.h"
#include <wsutil/utf8_entities.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
#include <QDebug>
#include "ui/capture_ui_utils.h"
#include <ui/qt/models/path_selection_delegate.h>
#include <QCheckBox>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QStandardItemModel>
#include <QTreeWidgetItemIterator>
#include <QMessageBox>
// To do:
// - Check the validity of pipes and remote interfaces and provide feedback
// via hintLabel.
// - We might want to move PathSelectionDelegate to its own module and use it in
// other parts of the application such as the general preferences and UATs.
// Qt Creator has a much more elaborate version from which we might want
// to draw inspiration.
enum {
col_p_pipe_
};
enum
{
col_r_show_,
col_r_host_dev_
};
enum {
tab_local_,
tab_pipe_,
tab_remote_
};
#ifdef HAVE_PCAP_REMOTE
static void populateExistingRemotes(gpointer key, gpointer value, gpointer user_data)
{
ManageInterfacesDialog *dialog = (ManageInterfacesDialog*)user_data;
const gchar *host = (const gchar *)key;
struct remote_host *remote_host = (struct remote_host *)value;
remote_options global_remote_opts;
int err;
gchar *err_str;
global_remote_opts.src_type = CAPTURE_IFREMOTE;
global_remote_opts.remote_host_opts.remote_host = g_strdup(host);
global_remote_opts.remote_host_opts.remote_port = g_strdup(remote_host->remote_port);
global_remote_opts.remote_host_opts.auth_type = remote_host->auth_type;
global_remote_opts.remote_host_opts.auth_username = g_strdup(remote_host->auth_username);
global_remote_opts.remote_host_opts.auth_password = g_strdup(remote_host->auth_password);
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) {
switch (err) {
case 0:
QMessageBox::warning(dialog, QObject::tr("Error"), QObject::tr("No remote interfaces found."));
break;
case CANT_GET_INTERFACE_LIST:
QMessageBox::critical(dialog, QObject::tr("Error"), err_str);
break;
case DONT_HAVE_PCAP:
QMessageBox::critical(dialog, QObject::tr("Error"), QObject::tr("PCAP not found"));
break;
default:
QMessageBox::critical(dialog, QObject::tr("Error"), QObject::tr("Unknown error"));
break;
}
return;
}
emit dialog->remoteAdded(rlist, &global_remote_opts);
}
#endif /* HAVE_PCAP_REMOTE */
ManageInterfacesDialog::ManageInterfacesDialog(QWidget *parent) :
GeometryStateDialog(parent),
ui(new Ui::ManageInterfacesDialog)
{
ui->setupUi(this);
loadGeometry();
setAttribute(Qt::WA_DeleteOnClose, true);
ui->addPipe->setStockIcon("list-add");
ui->delPipe->setStockIcon("list-remove");
ui->addRemote->setStockIcon("list-add");
ui->delRemote->setStockIcon("list-remove");
#ifdef Q_OS_MAC
ui->addPipe->setAttribute(Qt::WA_MacSmallSize, true);
ui->delPipe->setAttribute(Qt::WA_MacSmallSize, true);
ui->addRemote->setAttribute(Qt::WA_MacSmallSize, true);
ui->delRemote->setAttribute(Qt::WA_MacSmallSize, true);
#endif
sourceModel = new InterfaceTreeCacheModel(this);
proxyModel = new InterfaceSortFilterModel(this);
QList<InterfaceTreeColumns> columns;
columns.append(IFTREE_COL_HIDDEN);
columns.append(IFTREE_COL_DESCRIPTION);
columns.append(IFTREE_COL_NAME);
columns.append(IFTREE_COL_COMMENT);
proxyModel->setColumns(columns);
proxyModel->setSourceModel(sourceModel);
proxyModel->setFilterHidden(false);
#ifdef HAVE_PCAP_REMOTE
proxyModel->setRemoteDisplay(false);
#endif
proxyModel->setFilterByType(false);
ui->localView->setModel(proxyModel);
ui->localView->resizeColumnToContents(proxyModel->mapSourceToColumn(IFTREE_COL_HIDDEN));
ui->localView->resizeColumnToContents(proxyModel->mapSourceToColumn(IFTREE_COL_NAME));
pipeProxyModel = new InterfaceSortFilterModel(this);
columns.clear();
columns.append(IFTREE_COL_PIPE_PATH);
pipeProxyModel->setColumns(columns);
pipeProxyModel->setSourceModel(sourceModel);
pipeProxyModel->setFilterHidden(true);
#ifdef HAVE_PCAP_REMOTE
pipeProxyModel->setRemoteDisplay(false);
#endif
pipeProxyModel->setFilterByType(true, true);
pipeProxyModel->setInterfaceTypeVisible(IF_PIPE, false);
ui->pipeView->setModel(pipeProxyModel);
ui->delPipe->setEnabled(pipeProxyModel->rowCount() > 0);
ui->pipeView->setItemDelegateForColumn(pipeProxyModel->mapSourceToColumn(IFTREE_COL_PIPE_PATH), new PathSelectionDelegate());
connect(ui->pipeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, [=](const QItemSelection &sel, const QItemSelection &) {
ui->delPipe->setEnabled(sel.count() > 0);
});
#if defined(HAVE_PCAP_REMOTE)
// The default indentation (20) means our checkboxes are shifted too far on Windows.
// Assume that our disclosure and checkbox controls are square, or at least fit within an em.
int one_em = fontMetrics().height();
ui->remoteList->setIndentation(one_em);
ui->remoteList->setColumnWidth(col_r_show_, one_em * 4);
ui->remoteSettings->setEnabled(false);
showRemoteInterfaces();
#else
ui->tabWidget->removeTab(tab_remote_);
#endif
connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(updateWidgets()));
connect(this, SIGNAL(ifsChanged()), parent, SIGNAL(ifsChanged()));
#ifdef HAVE_PCAP_REMOTE
connect(this, SIGNAL(remoteAdded(GList*, remote_options*)), this, SLOT(addRemoteInterfaces(GList*, remote_options*)));
connect(this, SIGNAL(remoteSettingsChanged(interface_t *)), this, SLOT(setRemoteSettings(interface_t *)));
connect(ui->remoteList, SIGNAL(itemClicked(QTreeWidgetItem*, int)), this, SLOT(remoteSelectionChanged(QTreeWidgetItem*, int)));
recent_remote_host_list_foreach(populateExistingRemotes, this);
#endif
ui->tabWidget->setCurrentIndex(tab_local_);
updateWidgets();
}
ManageInterfacesDialog::~ManageInterfacesDialog()
{
delete ui;
}
void ManageInterfacesDialog::updateWidgets()
{
QString hint;
#ifdef HAVE_PCAP_REMOTE
bool enable_del_remote = false;
bool enable_remote_settings = false;
QTreeWidgetItem *item = ui->remoteList->currentItem();
if (item) {
if (item->childCount() < 1) { // Leaf
enable_remote_settings = true;
} else {
enable_del_remote = true;
}
}
ui->delRemote->setEnabled(enable_del_remote);
ui->remoteSettings->setEnabled(enable_remote_settings);
#endif
switch (ui->tabWidget->currentIndex()) {
case tab_pipe_:
hint = tr("This version of Wireshark does not save pipe settings.");
break;
case tab_remote_:
#ifdef HAVE_PCAP_REMOTE
hint = tr("This version of Wireshark does not save remote settings.");
#else
hint = tr("This version of Wireshark does not support remote interfaces.");
#endif
break;
default:
break;
}
hint.prepend("<small><i>");
hint.append("</i></small>");
ui->hintLabel->setText(hint);
}
void ManageInterfacesDialog::on_buttonBox_accepted()
{
#ifdef HAVE_LIBPCAP
sourceModel->save();
#endif
#ifdef HAVE_PCAP_REMOTE
remoteAccepted();
#endif
prefs_main_write();
mainApp->refreshLocalInterfaces();
emit ifsChanged();
}
#ifdef HAVE_LIBPCAP
void ManageInterfacesDialog::on_addPipe_clicked()
{
interface_t device;
memset(&device, 0, sizeof(device));
device.name = qstring_strdup(tr("New Pipe"));
device.display_name = g_strdup(device.name);
device.hidden = FALSE;
device.selected = TRUE;
device.pmode = global_capture_opts.default_options.promisc_mode;
device.has_snaplen = global_capture_opts.default_options.has_snaplen;
device.snaplen = global_capture_opts.default_options.snaplen;
device.cfilter = g_strdup(global_capture_opts.default_options.cfilter);
device.timestamp_type = g_strdup(global_capture_opts.default_options.timestamp_type);
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
device.buffer = DEFAULT_CAPTURE_BUFFER_SIZE;
#endif
device.active_dlt = -1;
device.if_info.name = g_strdup(device.name);
device.if_info.type = IF_PIPE;
sourceModel->addDevice(&device);
updateWidgets();
}
void ManageInterfacesDialog::on_delPipe_clicked()
{
/* Get correct selection and tell the source model to delete the itm. pipe view only
* displays IF_PIPE devices, therefore this will only delete pipes, and this is set
* to only select single items. */
QModelIndex selIndex = ui->pipeView->selectionModel()->selectedIndexes().at(0);
sourceModel->deleteDevice(pipeProxyModel->mapToSource(selIndex));
updateWidgets();
}
#endif
void ManageInterfacesDialog::on_buttonBox_helpRequested()
{
mainApp->helpTopicAction(HELP_CAPTURE_MANAGE_INTERFACES_DIALOG);
}
#ifdef HAVE_PCAP_REMOTE
void ManageInterfacesDialog::remoteSelectionChanged(QTreeWidgetItem*, int)
{
updateWidgets();
}
void ManageInterfacesDialog::updateRemoteInterfaceList(GList* rlist, remote_options* roptions)
{
GList *if_entry, *lt_entry;
if_info_t *if_info;
char *if_string = NULL;
gchar *descr, *auth_str;
if_capabilities_t *caps;
gint linktype_count;
bool monitor_mode, found = false;
GSList *curr_addr;
int ips = 0;
guint i;
if_addr_t *addr;
data_link_info_t *data_link_info;
GString *ip_str;
link_row *linkr = NULL;
interface_t device;
guint num_interfaces;
num_interfaces = global_capture_opts.all_ifaces->len;
for (if_entry = g_list_first(rlist); if_entry != NULL; if_entry = gxx_list_next(if_entry)) {
auth_str = NULL;
if_info = gxx_list_data(if_info_t *, if_entry);
#if 0
add_interface_to_remote_list(if_info);
#endif
for (i = 0; i < num_interfaces; i++) {
device = g_array_index(global_capture_opts.all_ifaces, interface_t, i);
if (device.hidden)
continue;
if (strcmp(device.name, if_info->name) == 0) {
found = TRUE;
break;
}
}
if (found) {
found = FALSE;
continue;
}
ip_str = g_string_new("");
ips = 0;
memset(&device, 0, sizeof(device));
device.name = g_strdup(if_info->name);
device.if_info.name = g_strdup("Don't crash on bug 13448");
/* Is this interface hidden and, if so, should we include it
anyway? */
descr = capture_dev_user_descr_find(if_info->name);
if (descr != NULL) {
/* Yes, we have a user-supplied description; use it. */
if_string = ws_strdup_printf("%s: %s", descr, if_info->name);
g_free(descr);
} else {
/* No, we don't have a user-supplied description; did we get
one from the OS or libpcap? */
if (if_info->vendor_description != NULL) {
/* Yes - use it. */
if_string = ws_strdup_printf("%s: %s", if_info->vendor_description, if_info->name);
} else {
/* No. */
if_string = g_strdup(if_info->name);
}
} /* else descr != NULL */
if (if_info->loopback) {
device.display_name = ws_strdup_printf("%s (loopback)", if_string);
} else {
device.display_name = g_strdup(if_string);
}
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
if ((device.buffer = capture_dev_user_buffersize_find(if_string)) == -1) {
device.buffer = global_capture_opts.default_options.buffer_size;
}
#endif
if (!capture_dev_user_pmode_find(if_string, &device.pmode)) {
device.pmode = global_capture_opts.default_options.promisc_mode;
}
if (!capture_dev_user_snaplen_find(if_string, &device.has_snaplen,
&device.snaplen)) {
device.has_snaplen = global_capture_opts.default_options.has_snaplen;
device.snaplen = global_capture_opts.default_options.snaplen;
}
device.cfilter = g_strdup(global_capture_opts.default_options.cfilter);
device.timestamp_type = g_strdup(global_capture_opts.default_options.timestamp_type);
monitor_mode = prefs_capture_device_monitor_mode(if_string);
if (roptions->remote_host_opts.auth_type == CAPTURE_AUTH_PWD) {
auth_str = ws_strdup_printf("%s:%s", roptions->remote_host_opts.auth_username,
roptions->remote_host_opts.auth_password);
}
caps = capture_get_if_capabilities(if_string, monitor_mode, auth_str, NULL, NULL, main_window_update);
g_free(auth_str);
for (; (curr_addr = g_slist_nth(if_info->addrs, ips)) != NULL; ips++) {
address addr_str;
char* temp_addr_str = NULL;
if (ips != 0) {
g_string_append(ip_str, "\n");
}
addr = (if_addr_t *)curr_addr->data;
switch (addr->ifat_type) {
case IF_AT_IPv4:
set_address(&addr_str, AT_IPv4, 4, &addr->addr.ip4_addr);
temp_addr_str = (char*)address_to_str(NULL, &addr_str);
g_string_append(ip_str, temp_addr_str);
break;
case IF_AT_IPv6:
set_address(&addr_str, AT_IPv6, 16, addr->addr.ip6_addr);
temp_addr_str = (char*)address_to_str(NULL, &addr_str);
g_string_append(ip_str, temp_addr_str);
break;
default:
/* In case we add non-IP addresses */
break;
}
wmem_free(NULL, temp_addr_str);
} /* for curr_addr */
linktype_count = 0;
device.links = NULL;
if (caps != NULL) {
#ifdef HAVE_PCAP_CREATE
device.monitor_mode_enabled = monitor_mode;
device.monitor_mode_supported = caps->can_set_rfmon;
#endif
for (lt_entry = caps->data_link_types; lt_entry != NULL; lt_entry = gxx_list_next(lt_entry)) {
data_link_info = gxx_list_data(data_link_info_t *, lt_entry);
linkr = new link_row;
/*
* For link-layer types libpcap/WinPcap/Npcap doesn't know
* about, the name will be "DLT n", and the description will
* be null.
* We mark those as unsupported, and don't allow them to be
* used.
*/
if (data_link_info->description != NULL) {
linkr->name = g_strdup(data_link_info->description);
linkr->dlt = data_link_info->dlt;
} else {
linkr->name = ws_strdup_printf("%s (not supported)", data_link_info->name);
linkr->dlt = -1;
}
if (linktype_count == 0) {
device.active_dlt = data_link_info->dlt;
}
device.links = g_list_append(device.links, linkr);
linktype_count++;
} /* for link_types */
} else {
#if defined(HAVE_PCAP_CREATE)
device.monitor_mode_enabled = FALSE;
device.monitor_mode_supported = FALSE;
#endif
device.active_dlt = -1;
}
device.addresses = g_strdup(ip_str->str);
device.no_addresses = ips;
device.remote_opts.src_type= roptions->src_type;
if (device.remote_opts.src_type == CAPTURE_IFREMOTE) {
device.local = FALSE;
}
device.remote_opts.remote_host_opts.remote_host = g_strdup(roptions->remote_host_opts.remote_host);
device.remote_opts.remote_host_opts.remote_port = g_strdup(roptions->remote_host_opts.remote_port);
device.remote_opts.remote_host_opts.auth_type = roptions->remote_host_opts.auth_type;
device.remote_opts.remote_host_opts.auth_username = g_strdup(roptions->remote_host_opts.auth_username);
device.remote_opts.remote_host_opts.auth_password = g_strdup(roptions->remote_host_opts.auth_password);
device.remote_opts.remote_host_opts.datatx_udp = roptions->remote_host_opts.datatx_udp;
device.remote_opts.remote_host_opts.nocap_rpcap = roptions->remote_host_opts.nocap_rpcap;
device.remote_opts.remote_host_opts.nocap_local = roptions->remote_host_opts.nocap_local;
#ifdef HAVE_PCAP_SETSAMPLING
device.remote_opts.sampling_method = roptions->sampling_method;
device.remote_opts.sampling_param = roptions->sampling_param;
#endif
device.selected = TRUE;
global_capture_opts.num_selected++;
g_array_append_val(global_capture_opts.all_ifaces, device);
g_string_free(ip_str, TRUE);
} /*for*/
}
void ManageInterfacesDialog::addRemoteInterfaces(GList* rlist, remote_options *roptions)
{
updateRemoteInterfaceList(rlist, roptions);
showRemoteInterfaces();
}
// We don't actually store these. When we do we should make sure they're stored
// securely using CryptProtectData, the macOS Keychain, GNOME Keyring, KWallet, etc.
void ManageInterfacesDialog::remoteAccepted()
{
QTreeWidgetItemIterator it(ui->remoteList);
while (*it) {
for (guint i = 0; i < global_capture_opts.all_ifaces->len; i++) {
interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i);
if ((*it)->text(col_r_host_dev_).compare(device->name))
continue;
device->hidden = ((*it)->checkState(col_r_show_) == Qt::Checked ? false : true);
}
++it;
}
}
void ManageInterfacesDialog::on_remoteList_currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)
{
updateWidgets();
}
void ManageInterfacesDialog::on_remoteList_itemClicked(QTreeWidgetItem *item, int column)
{
if (!item || column != col_r_show_) {
return;
}
for (guint i = 0; i < global_capture_opts.all_ifaces->len; i++) {
interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i);
if (!device->local) {
if (item->text(col_r_host_dev_).compare(device->name))
continue;
device->hidden = (item->checkState(col_r_show_) == Qt::Checked ? false : true);
}
}
}
void ManageInterfacesDialog::on_delRemote_clicked()
{
QTreeWidgetItem* item = ui->remoteList->currentItem();
if (!item) {
return;
}
for (guint i = 0; i < global_capture_opts.all_ifaces->len; i++) {
interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i);
if (item->text(col_r_host_dev_).compare(device->remote_opts.remote_host_opts.remote_host))
continue;
capture_opts_free_interface_t(device);
global_capture_opts.all_ifaces = g_array_remove_index(global_capture_opts.all_ifaces, i);
}
delete item;
fflush(stdout); // ???
}
void ManageInterfacesDialog::on_addRemote_clicked()
{
RemoteCaptureDialog *dlg = new RemoteCaptureDialog(this);
dlg->show();
}
void ManageInterfacesDialog::showRemoteInterfaces()
{
guint i;
interface_t *device;
QTreeWidgetItem * item = nullptr;
// We assume that remote interfaces are grouped by host.
for (i = 0; i < global_capture_opts.all_ifaces->len; i++) {
QTreeWidgetItem * child = nullptr;
device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i);
if (!device->local) {
// check if the QTreeWidgetItem for that interface already exists
QList<QTreeWidgetItem*> items = ui->remoteList->findItems(QString(device->name), Qt::MatchCaseSensitive | Qt::MatchFixedString, col_r_host_dev_);
if (items.count() > 0)
continue;
// create or find the QTreeWidgetItem for the remote host configuration
QString parentName = QString(device->remote_opts.remote_host_opts.remote_host);
items = ui->remoteList->findItems(parentName, Qt::MatchCaseSensitive | Qt::MatchFixedString, col_r_host_dev_);
if (items.count() == 0) {
item = new QTreeWidgetItem(ui->remoteList);
item->setText(col_r_host_dev_, parentName);
item->setExpanded(true);
}
else {
item = items.at(0);
}
items = ui->remoteList->findItems(QString(device->name), Qt::MatchCaseSensitive | Qt::MatchFixedString | Qt::MatchRecursive, col_r_host_dev_);
if (items.count() == 0)
{
child = new QTreeWidgetItem(item);
child->setCheckState(col_r_show_, device->hidden ? Qt::Unchecked : Qt::Checked);
child->setText(col_r_host_dev_, QString(device->name));
}
}
}
}
void ManageInterfacesDialog::on_remoteSettings_clicked()
{
guint i = 0;
interface_t *device;
QTreeWidgetItem* item = ui->remoteList->currentItem();
if (!item) {
return;
}
for (i = 0; i < global_capture_opts.all_ifaces->len; i++) {
device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i);
if (!device->local) {
if (item->text(col_r_host_dev_).compare(device->name)) {
continue;
} else {
RemoteSettingsDialog *dlg = new RemoteSettingsDialog(this, device);
dlg->show();
break;
}
}
}
}
void ManageInterfacesDialog::setRemoteSettings(interface_t *iface)
{
for (guint i = 0; i < global_capture_opts.all_ifaces->len; i++) {
interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i);
if (!device->local) {
if (strcmp(iface->name, device->name)) {
continue;
}
device->remote_opts.remote_host_opts.nocap_rpcap = iface->remote_opts.remote_host_opts.nocap_rpcap;
device->remote_opts.remote_host_opts.datatx_udp = iface->remote_opts.remote_host_opts.datatx_udp;
#ifdef HAVE_PCAP_SETSAMPLING
device->remote_opts.sampling_method = iface->remote_opts.sampling_method;
device->remote_opts.sampling_param = iface->remote_opts.sampling_param;
#endif //HAVE_PCAP_SETSAMPLING
}
}
}
#endif // HAVE_PCAP_REMOTE |
C/C++ | wireshark/ui/qt/manage_interfaces_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 MANAGE_INTERFACES_DIALOG_H
#define MANAGE_INTERFACES_DIALOG_H
#include <config.h>
#include <glib.h>
#include "capture_opts.h"
#include <ui/qt/models/interface_tree_cache_model.h>
#include <ui/qt/models/interface_sort_filter_model.h>
#include "geometry_state_dialog.h"
#include <QStyledItemDelegate>
class QTreeWidget;
class QTreeWidgetItem;
class QStandardItemModel;
class QLineEdit;
namespace Ui {
class ManageInterfacesDialog;
}
class ManageInterfacesDialog : public GeometryStateDialog
{
Q_OBJECT
public:
explicit ManageInterfacesDialog(QWidget *parent = 0);
~ManageInterfacesDialog();
private:
Ui::ManageInterfacesDialog *ui;
InterfaceTreeCacheModel * sourceModel;
InterfaceSortFilterModel * proxyModel;
InterfaceSortFilterModel * pipeProxyModel;
void showRemoteInterfaces();
signals:
void ifsChanged();
#ifdef HAVE_PCAP_REMOTE
void remoteAdded(GList *rlist, remote_options *roptions);
void remoteSettingsChanged(interface_t *iface);
#endif
private slots:
void updateWidgets();
void on_buttonBox_accepted();
#ifdef HAVE_LIBPCAP
void on_addPipe_clicked();
void on_delPipe_clicked();
#endif
#ifdef HAVE_PCAP_REMOTE
void on_addRemote_clicked();
void on_delRemote_clicked();
void remoteAccepted();
void on_remoteList_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous);
void on_remoteList_itemClicked(QTreeWidgetItem *item, int column);
void addRemoteInterfaces(GList *rlist, remote_options *roptions);
void updateRemoteInterfaceList(GList *rlist, remote_options *roptions);
void setRemoteSettings(interface_t *iface);
void remoteSelectionChanged(QTreeWidgetItem* item, int col);
void on_remoteSettings_clicked();
#endif
void on_buttonBox_helpRequested();
};
#endif // MANAGE_INTERFACES_DIALOG_H |
User Interface | wireshark/ui/qt/manage_interfaces_dialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ManageInterfacesDialog</class>
<widget class="QDialog" name="ManageInterfacesDialog">
<property name="windowModality">
<enum>Qt::ApplicationModal</enum>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>750</width>
<height>425</height>
</rect>
</property>
<property name="windowTitle">
<string>Manage Interfaces</string>
</property>
<property name="modal">
<bool>false</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="localTab">
<property name="toolTip">
<string><html><head/><body><p>Click the checkbox to hide or show a hidden interface.</p></body></html></string>
</property>
<attribute name="title">
<string>Local Interfaces</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTreeView" name="localView">
<property name="focusPolicy">
<enum>Qt::NoFocus</enum>
</property>
<property name="indentation">
<number>0</number>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="uniformRowHeights">
<bool>true</bool>
</property>
<property name="itemsExpandable">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="pipeTab">
<property name="toolTip">
<string><html><head/><body><p>Add a pipe to capture from or remove an existing pipe from the list.</p></body></html></string>
</property>
<attribute name="title">
<string>Pipes</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QTreeView" name="pipeView">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="baseSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAsNeeded</enum>
</property>
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="textElideMode">
<enum>Qt::ElideMiddle</enum>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="itemsExpandable">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="StockIconToolButton" name="addPipe">
<property name="toolTip">
<string><html><head/><body><p>Add a new pipe using default settings.</p></body></html></string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<widget class="StockIconToolButton" name="delPipe">
<property name="toolTip">
<string><html><head/><body><p>Remove the selected pipe from the list.</p></body></html></string>
</property>
<property name="text">
<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>
</layout>
</widget>
<widget class="QWidget" name="remoteTab">
<attribute name="title">
<string>Remote Interfaces</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QTreeWidget" name="remoteList">
<property name="uniformRowHeights">
<bool>true</bool>
</property>
<column>
<property name="text">
<string>Show</string>
</property>
</column>
<column>
<property name="text">
<string>Host / Device URL</string>
</property>
</column>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="StockIconToolButton" name="addRemote">
<property name="toolTip">
<string><html><head/><body><p>Add a remote host and its interfaces</p></body></html></string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<widget class="StockIconToolButton" name="delRemote">
<property name="toolTip">
<string><html><head/><body><p>Remove the selected host from the list.</p></body></html></string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>328</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="remoteSettings">
<property name="text">
<string>Remote Settings</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
</item>
<item>
<widget class="QLabel" name="hintLabel">
<property name="text">
<string><small><i></i></small></string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<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>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>ManageInterfacesDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>374</x>
<y>404</y>
</hint>
<hint type="destinationlabel">
<x>374</x>
<y>212</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>ManageInterfacesDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>374</x>
<y>404</y>
</hint>
<hint type="destinationlabel">
<x>374</x>
<y>212</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.