language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
C/C++ | wireshark/ui/qt/models/enabled_protocols_model.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef ENABLED_PROTOCOLS_MODEL_H
#define ENABLED_PROTOCOLS_MODEL_H
#include <config.h>
#include <ui/qt/models/tree_model_helpers.h>
#include <epan/proto.h>
#include <QAbstractItemModel>
#include <QSortFilterProxyModel>
class EnabledProtocolItem : public ModelHelperTreeItem<EnabledProtocolItem>
{
Q_GADGET
public:
enum EnableProtocolType{
Any,
Standard,
Heuristic
};
Q_ENUM(EnableProtocolType)
EnabledProtocolItem(QString name, QString description, bool enabled, EnabledProtocolItem* parent);
virtual ~EnabledProtocolItem();
QString name() const {return name_;}
QString description() const {return description_;}
bool enabled() const {return enabled_;}
void setEnabled(bool enable) {enabled_ = enable;}
EnableProtocolType type() const;
bool applyValue();
protected:
virtual void applyValuePrivate(gboolean value) = 0;
QString name_;
QString description_;
bool enabled_;
bool enabledInit_; //value that model starts with to determine change
EnableProtocolType type_;
};
class EnabledProtocolsModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit EnabledProtocolsModel(QObject * parent = Q_NULLPTR);
virtual ~EnabledProtocolsModel();
enum EnabledProtocolsColumn {
colProtocol = 0,
colDescription,
colLast
};
enum EnableProtocolData {
DATA_ENABLE = Qt::UserRole,
DATA_PROTOCOL_TYPE
};
QModelIndex index(int row, int column,
const QModelIndex & = QModelIndex()) const;
QModelIndex parent(const QModelIndex &) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
QVariant data(const QModelIndex &index, int role) const;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
void populate();
void applyChanges(bool writeChanges = true);
static void disableProtocol(struct _protocol *protocol);
protected:
static void saveChanges(bool writeChanges = true);
private:
EnabledProtocolItem* root_;
};
class EnabledProtocolsProxyModel : public QSortFilterProxyModel
{
Q_OBJECT
public:
enum SearchType
{
EveryWhere,
OnlyProtocol,
OnlyDescription,
EnabledItems,
DisabledItems
};
Q_ENUM(SearchType)
enum EnableType
{
Enable,
Disable,
Invert
};
explicit EnabledProtocolsProxyModel(QObject * parent = Q_NULLPTR);
virtual bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override;
virtual Qt::ItemFlags flags(const QModelIndex &index) const override;
void setFilter(const QString& filter, EnabledProtocolsProxyModel::SearchType type,
EnabledProtocolItem::EnableProtocolType protocolType);
void setItemsEnable(EnabledProtocolsProxyModel::EnableType enable, QModelIndex parent = QModelIndex());
protected:
bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override;
private:
EnabledProtocolsProxyModel::SearchType type_;
EnabledProtocolItem::EnableProtocolType protocolType_;
QString filter_;
bool filterAcceptsSelf(int sourceRow, const QModelIndex &sourceParent) const;
bool filterAcceptsChild(int sourceRow, const QModelIndex &sourceParent) const;
};
#endif // ENABLED_PROTOCOLS_MODEL_H |
C++ | wireshark/ui/qt/models/expert_info_model.cpp | /* expert_info_model.cpp
* Data model for Expert Info tap data.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "expert_info_model.h"
#include "file.h"
#include <epan/proto.h>
ExpertPacketItem::ExpertPacketItem(const expert_info_t& expert_info, column_info *cinfo, ExpertPacketItem* parent) :
packet_num_(expert_info.packet_num),
group_(expert_info.group),
severity_(expert_info.severity),
hf_id_(expert_info.hf_index),
protocol_(expert_info.protocol),
summary_(expert_info.summary),
parentItem_(parent)
{
if (cinfo) {
info_ = col_get_text(cinfo, COL_INFO);
}
}
ExpertPacketItem::~ExpertPacketItem()
{
for (int row = 0; row < childItems_.count(); row++)
{
delete childItems_.value(row);
}
childItems_.clear();
}
QString ExpertPacketItem::groupKey(bool group_by_summary, int severity, int group, QString protocol, int expert_hf)
{
QString key = QString("%1|%2|%3")
.arg(severity)
.arg(group)
.arg(protocol);
if (group_by_summary) {
key += QString("|%1").arg(expert_hf);
}
return key;
}
QString ExpertPacketItem::groupKey(bool group_by_summary) {
return groupKey(group_by_summary, severity_, group_, protocol_, hf_id_);
}
void ExpertPacketItem::appendChild(ExpertPacketItem* child, QString hash)
{
childItems_.append(child);
hashChild_[hash] = child;
}
ExpertPacketItem* ExpertPacketItem::child(int row)
{
return childItems_.value(row);
}
ExpertPacketItem* ExpertPacketItem::child(QString hash)
{
return hashChild_[hash];
}
int ExpertPacketItem::childCount() const
{
return static_cast<int>(childItems_.count());
}
int ExpertPacketItem::row() const
{
if (parentItem_)
return static_cast<int>(parentItem_->childItems_.indexOf(const_cast<ExpertPacketItem*>(this)));
return 0;
}
ExpertPacketItem* ExpertPacketItem::parentItem()
{
return parentItem_;
}
ExpertInfoModel::ExpertInfoModel(CaptureFile& capture_file, QObject *parent) :
QAbstractItemModel(parent),
capture_file_(capture_file),
group_by_summary_(true),
root_(createRootItem())
{
}
ExpertInfoModel::~ExpertInfoModel()
{
delete root_;
}
void ExpertInfoModel::clear()
{
beginResetModel();
eventCounts_.clear();
delete root_;
root_ = createRootItem();
endResetModel();
}
ExpertPacketItem* ExpertInfoModel::createRootItem()
{
static const char* rootName = "ROOT";
DIAG_OFF_CAST_AWAY_CONST
static expert_info_t root_expert = { 0, -1, -1, -1, rootName, (gchar*)rootName, NULL };
DIAG_ON_CAST_AWAY_CONST
return new ExpertPacketItem(root_expert, NULL, NULL);
}
int ExpertInfoModel::numEvents(enum ExpertSeverity severity)
{
return eventCounts_[severity];
}
QModelIndex ExpertInfoModel::index(int row, int column, const QModelIndex& parent) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
ExpertPacketItem *parent_item, *child_item;
if (!parent.isValid())
parent_item = root_;
else
parent_item = static_cast<ExpertPacketItem*>(parent.internalPointer());
Q_ASSERT(parent_item);
if (group_by_summary_) {
//don't allow group layer
if (parent_item == root_) {
int row_count = 0;
ExpertPacketItem *grandchild_item;
for (int subrow = 0; subrow < parent_item->childCount(); subrow++) {
child_item = parent_item->child(subrow);
//summary children are always stored in first child of group
grandchild_item = child_item->child(0);
if (row_count+grandchild_item->childCount() > row) {
return createIndex(row, column, grandchild_item->child(row-row_count));
}
row_count += grandchild_item->childCount();
}
//shouldn't happen
return QModelIndex();
}
int root_level = 0;
ExpertPacketItem *item = parent_item;
while (item != root_)
{
root_level++;
item = item->parentItem();
}
if (root_level == 3) {
child_item = parent_item->child(row);
if (child_item) {
return createIndex(row, column, child_item);
}
}
} else {
child_item = parent_item->child(row);
if (child_item) {
//only allow 2 levels deep
if (((parent_item == root_) || (parent_item->parentItem() == root_)))
return createIndex(row, column, child_item);
}
}
return QModelIndex();
}
QModelIndex ExpertInfoModel::parent(const QModelIndex& index) const
{
if (!index.isValid())
return QModelIndex();
ExpertPacketItem *item = static_cast<ExpertPacketItem*>(index.internalPointer());
ExpertPacketItem *parent_item = item->parentItem();
if (group_by_summary_)
{
//don't allow group layer
int root_level = 0;
item = parent_item;
while ((item != root_) && (item != NULL))
{
root_level++;
item = item->parentItem();
}
if (root_level == 3)
return createIndex(parent_item->row(), 0, parent_item);
} else {
if (parent_item == root_)
return QModelIndex();
return createIndex(parent_item->row(), 0, parent_item);
}
return QModelIndex();
}
#if 0
Qt::ItemFlags ExpertInfoModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
ExpertPacketItem* item = static_cast<ExpertPacketItem*>(index.internalPointer());
Qt::ItemFlags flags = QAbstractTableModel::flags(index);
//collapse???
return flags;
}
#endif
QVariant ExpertInfoModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || (role != Qt::DisplayRole && role != Qt::ToolTipRole))
return QVariant();
ExpertPacketItem* item = static_cast<ExpertPacketItem*>(index.internalPointer());
if (item == NULL)
return QVariant();
if (role == Qt::ToolTipRole)
{
QString filterName = proto_registrar_get_abbrev(item->hfId());
return filterName;
}
else if (role == Qt::DisplayRole)
{
switch ((enum ExpertColumn)index.column()) {
case colSeverity:
return QString(val_to_str_const(item->severity(), expert_severity_vals, "Unknown"));
case colSummary:
if (index.parent().isValid())
{
if (item->severity() == PI_COMMENT)
return item->summary().simplified();
if (group_by_summary_)
return item->colInfo().simplified();
return item->summary().simplified();
}
else
{
if (group_by_summary_)
{
if (item->severity() == PI_COMMENT)
return "Packet comments listed below.";
if (item->hfId() != -1) {
return proto_registrar_get_name(item->hfId());
} else {
return item->summary().simplified();
}
}
}
return QVariant();
case colGroup:
return QString(val_to_str_const(item->group(), expert_group_vals, "Unknown"));
case colProtocol:
return item->protocol();
case colCount:
if (!index.parent().isValid())
{
return item->childCount();
}
break;
case colPacket:
return item->packetNum();
case colHf:
return item->hfId();
default:
break;
}
}
return QVariant();
}
//GUI helpers
void ExpertInfoModel::setGroupBySummary(bool group_by_summary)
{
beginResetModel();
group_by_summary_ = group_by_summary;
endResetModel();
}
int ExpertInfoModel::rowCount(const QModelIndex &parent) const
{
ExpertPacketItem *parent_item;
if (parent.column() > 0)
return 0;
if (!parent.isValid())
parent_item = root_;
else
parent_item = static_cast<ExpertPacketItem*>(parent.internalPointer());
if (group_by_summary_) {
int row_count = 0;
//don't allow group layer
if (parent_item == root_) {
ExpertPacketItem *child_item, *grandchild_item;
for (int row = 0; row < parent_item->childCount(); row++) {
child_item = parent_item->child(row);
grandchild_item = child_item->child(0);
row_count += grandchild_item->childCount();
}
return row_count;
}
return parent_item->childCount();
} else {
//only allow 2 levels deep
if ((parent_item == root_) || (parent_item->parentItem() == root_))
return parent_item->childCount();
}
return 0;
}
int ExpertInfoModel::columnCount(const QModelIndex&) const
{
return colLast;
}
void ExpertInfoModel::addExpertInfo(const struct expert_info_s& expert_info)
{
QString groupKey = ExpertPacketItem::groupKey(FALSE, expert_info.severity, expert_info.group, QString(expert_info.protocol), expert_info.hf_index);
QString summaryKey = ExpertPacketItem::groupKey(TRUE, expert_info.severity, expert_info.group, QString(expert_info.protocol), expert_info.hf_index);
ExpertPacketItem* expert_root = root_->child(groupKey);
if (expert_root == NULL) {
ExpertPacketItem *new_item = new ExpertPacketItem(expert_info, &(capture_file_.capFile()->cinfo), root_);
root_->appendChild(new_item, groupKey);
expert_root = new_item;
}
ExpertPacketItem *expert = new ExpertPacketItem(expert_info, &(capture_file_.capFile()->cinfo), expert_root);
expert_root->appendChild(expert, groupKey);
//add the summary children off of the first child of the root children
ExpertPacketItem* summary_root = expert_root->child(0);
//make a summary child
ExpertPacketItem* expert_summary_root = summary_root->child(summaryKey);
if (expert_summary_root == NULL) {
ExpertPacketItem *new_summary = new ExpertPacketItem(expert_info, &(capture_file_.capFile()->cinfo), summary_root);
summary_root->appendChild(new_summary, summaryKey);
expert_summary_root = new_summary;
}
ExpertPacketItem *expert_summary = new ExpertPacketItem(expert_info, &(capture_file_.capFile()->cinfo), expert_summary_root);
expert_summary_root->appendChild(expert_summary, summaryKey);
}
void ExpertInfoModel::tapReset(void *eid_ptr)
{
ExpertInfoModel *model = static_cast<ExpertInfoModel*>(eid_ptr);
if (!model)
return;
model->clear();
}
tap_packet_status ExpertInfoModel::tapPacket(void *eid_ptr, struct _packet_info *pinfo, struct epan_dissect *, const void *data, tap_flags_t)
{
ExpertInfoModel *model = static_cast<ExpertInfoModel*>(eid_ptr);
const expert_info_t *expert_info = (const expert_info_t *) data;
tap_packet_status status = TAP_PACKET_DONT_REDRAW;
if (!pinfo || !model || !expert_info)
return TAP_PACKET_DONT_REDRAW;
model->addExpertInfo(*expert_info);
status = TAP_PACKET_REDRAW;
model->eventCounts_[(enum ExpertSeverity)expert_info->severity]++;
return status;
}
void ExpertInfoModel::tapDraw(void *eid_ptr)
{
ExpertInfoModel *model = static_cast<ExpertInfoModel*>(eid_ptr);
if (!model)
return;
model->beginResetModel();
model->endResetModel();
} |
C/C++ | wireshark/ui/qt/models/expert_info_model.h | /** @file
*
* Data model for Expert Info tap data.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef EXPERT_INFO_MODEL_H
#define EXPERT_INFO_MODEL_H
#include <config.h>
#include <QAbstractItemModel>
#include <QList>
#include <QMap>
#include <ui/qt/capture_file.h>
#include <epan/expert.h>
#include <epan/tap.h>
#include <epan/column-utils.h>
class ExpertPacketItem
{
public:
ExpertPacketItem(const expert_info_t& expert_info, column_info *cinfo, ExpertPacketItem* parent);
virtual ~ExpertPacketItem();
unsigned int packetNum() const { return packet_num_; }
int group() const { return group_; }
int severity() const { return severity_; }
int hfId() const { return hf_id_; }
QString protocol() const { return protocol_; }
QString summary() const { return summary_; }
QString colInfo() const { return info_; }
static QString groupKey(bool group_by_summary, int severity, int group, QString protocol, int expert_hf);
QString groupKey(bool group_by_summary);
void appendChild(ExpertPacketItem* child, QString hash);
ExpertPacketItem* child(int row);
ExpertPacketItem* child(QString hash);
int childCount() const;
int row() const;
ExpertPacketItem* parentItem();
private:
unsigned int packet_num_;
int group_;
int severity_;
int hf_id_;
// Half-hearted attempt at conserving memory. If this isn't sufficient,
// PacketListRecord interns column strings in a GStringChunk.
QByteArray protocol_;
QByteArray summary_;
QByteArray info_;
QList<ExpertPacketItem*> childItems_;
ExpertPacketItem* parentItem_;
QHash<QString, ExpertPacketItem*> hashChild_; //optimization for insertion
};
class ExpertInfoModel : public QAbstractItemModel
{
public:
ExpertInfoModel(CaptureFile& capture_file, QObject *parent = 0);
virtual ~ExpertInfoModel();
enum ExpertColumn {
colSeverity = 0,
colSummary,
colGroup,
colProtocol,
colCount,
colPacket,
colHf,
colLast
};
enum ExpertSeverity {
severityError = PI_ERROR,
severityWarn = PI_WARN,
severityNote = PI_NOTE,
severityChat = PI_CHAT,
severityComment = PI_COMMENT
};
QModelIndex index(int row, int column,
const QModelIndex & = QModelIndex()) const;
QModelIndex parent(const QModelIndex &) const;
#if 0
Qt::ItemFlags flags(const QModelIndex &index) const;
#endif
QVariant data(const QModelIndex &index, int role) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
int numEvents(enum ExpertSeverity severity);
void clear();
//GUI helpers
void setGroupBySummary(bool group_by_summary);
// Called from tapPacket
void addExpertInfo(const struct expert_info_s& expert_info);
// Callbacks for register_tap_listener
static void tapReset(void *eid_ptr);
static tap_packet_status tapPacket(void *eid_ptr, struct _packet_info *pinfo, struct epan_dissect *, const void *data, tap_flags_t flags);
static void tapDraw(void *eid_ptr);
private:
CaptureFile& capture_file_;
ExpertPacketItem* createRootItem();
bool group_by_summary_;
ExpertPacketItem* root_;
QHash<enum ExpertSeverity, int> eventCounts_;
};
#endif // EXPERT_INFO_MODEL_H |
C++ | wireshark/ui/qt/models/expert_info_proxy_model.cpp | /* expert_info_model.cpp
* Data model for Expert Info tap data.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/expert_info_model.h>
#include <ui/qt/models/expert_info_proxy_model.h>
#include <ui/qt/utils/color_utils.h>
#include <QRegularExpression>
ExpertInfoProxyModel::ExpertInfoProxyModel(QObject *parent) : QSortFilterProxyModel(parent),
severityMode_(Group)
{
}
bool ExpertInfoProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
{
ExpertPacketItem *left_item,
*right_item;
QString leftStr, rightStr;
bool checkPacketNumber = false;
int compare_ret;
if (source_left.parent().isValid() && source_right.parent().isValid()) {
left_item = static_cast<ExpertPacketItem*>(source_left.parent().internalPointer());
right_item = static_cast<ExpertPacketItem*>(source_right.parent().internalPointer());
} else {
left_item = static_cast<ExpertPacketItem*>(source_left.internalPointer());
right_item = static_cast<ExpertPacketItem*>(source_right.internalPointer());
}
if ((left_item != NULL) && (right_item != NULL)) {
switch (source_left.column())
{
case colProxySeverity:
if (left_item->severity() != right_item->severity()) {
return (left_item->severity() < right_item->severity());
}
checkPacketNumber = true;
break;
case colProxySummary:
compare_ret = left_item->summary().compare(right_item->summary());
if (compare_ret < 0)
return true;
if (compare_ret > 0)
return false;
checkPacketNumber = true;
break;
case colProxyGroup:
if (left_item->group() != right_item->group()) {
return (left_item->group() < right_item->group());
}
checkPacketNumber = true;
break;
case colProxyProtocol:
compare_ret = left_item->protocol().compare(right_item->protocol());
if (compare_ret < 0)
return true;
if (compare_ret > 0)
return false;
checkPacketNumber = true;
break;
case colProxyCount:
break;
default:
break;
}
if (checkPacketNumber) {
return (left_item->packetNum() < right_item->packetNum());
}
}
// fallback to string cmp on other fields
return QSortFilterProxyModel::lessThan(source_left, source_right);
}
QVariant ExpertInfoProxyModel::data(const QModelIndex &proxy_index, int role) const
{
QModelIndex source_index;
switch (role)
{
case Qt::BackgroundRole:
{
source_index = mapToSource(proxy_index);
// only color base row
if (!source_index.isValid() || source_index.parent().isValid())
return QVariant();
ExpertPacketItem* item = static_cast<ExpertPacketItem*>(source_index.internalPointer());
if (item == NULL)
return QVariant();
// provide background color for groups
switch(item->severity()) {
case(PI_COMMENT):
return QBrush(ColorUtils::expert_color_comment);
case(PI_CHAT):
return QBrush(ColorUtils::expert_color_chat);
case(PI_NOTE):
return QBrush(ColorUtils::expert_color_note);
case(PI_WARN):
return QBrush(ColorUtils::expert_color_warn);
case(PI_ERROR):
return QBrush(ColorUtils::expert_color_error);
}
}
break;
case Qt::ForegroundRole:
{
source_index = mapToSource(proxy_index);
// only color base row
if (!source_index.isValid() || source_index.parent().isValid())
return QVariant();
ExpertPacketItem* item = static_cast<ExpertPacketItem*>(source_index.internalPointer());
if (item == NULL)
return QVariant();
// provide foreground color for groups
switch(item->severity()) {
case(PI_COMMENT):
case(PI_CHAT):
case(PI_NOTE):
case(PI_WARN):
case(PI_ERROR):
return QBrush(ColorUtils::expert_color_foreground);
}
}
break;
case Qt::TextAlignmentRole:
switch (proxy_index.column())
{
case colProxySeverity:
//packet number should be right aligned
if (source_index.parent().isValid())
return Qt::AlignRight;
break;
case colProxyCount:
return Qt::AlignRight;
default:
break;
}
return Qt::AlignLeft;
case Qt::DisplayRole:
source_index = mapToSource(proxy_index);
switch (proxy_index.column())
{
case colProxySeverity:
if (source_index.parent().isValid())
return sourceModel()->data(source_index.sibling(source_index.row(), ExpertInfoModel::colPacket), role);
return sourceModel()->data(source_index.sibling(source_index.row(), ExpertInfoModel::colSeverity), role);
case colProxySummary:
return sourceModel()->data(source_index.sibling(source_index.row(), ExpertInfoModel::colSummary), role);
case colProxyGroup:
return sourceModel()->data(source_index.sibling(source_index.row(), ExpertInfoModel::colGroup), role);
case colProxyProtocol:
return sourceModel()->data(source_index.sibling(source_index.row(), ExpertInfoModel::colProtocol), role);
case colProxyCount:
//only show counts for parent
if (!source_index.parent().isValid()) {
//because of potential filtering, count is computed manually
unsigned int count = 0;
ExpertPacketItem *child_item,
*item = static_cast<ExpertPacketItem*>(source_index.internalPointer());
for (int row = 0; row < item->childCount(); row++) {
child_item = item->child(row);
if (child_item == NULL)
continue;
if (filterAcceptItem(*child_item))
count++;
}
return count;
}
}
break;
}
return QSortFilterProxyModel::data(proxy_index, role);
}
QVariant ExpertInfoProxyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
switch ((enum ExpertProxyColumn)section) {
case colProxySeverity:
if (severityMode_ == Packet)
return tr("Packet");
else
return tr("Severity");
case colProxySummary:
return tr("Summary");
case colProxyGroup:
return tr("Group");
case colProxyProtocol:
return tr("Protocol");
case colProxyCount:
return tr("Count");
default:
break;
}
}
return QVariant();
}
int ExpertInfoProxyModel::columnCount(const QModelIndex&) const
{
return colProxyLast;
}
bool ExpertInfoProxyModel::filterAcceptItem(ExpertPacketItem& item) const
{
if (hidden_severities_.contains(item.severity()))
return false;
if (!textFilter_.isEmpty()) {
QRegularExpression regex(textFilter_, QRegularExpression::CaseInsensitiveOption |
QRegularExpression::UseUnicodePropertiesOption);
if (! regex.isValid())
return false;
if (item.protocol().contains(regex))
return true;
if (item.summary().contains(regex))
return true;
if (item.colInfo().contains(regex))
return true;
return false;
}
return true;
}
bool ExpertInfoProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
QModelIndex severityIdx = sourceModel()->index(sourceRow, ExpertInfoModel::colSeverity, sourceParent);
ExpertPacketItem* item = static_cast<ExpertPacketItem*>(severityIdx.internalPointer());
if (item == NULL)
return true;
return filterAcceptItem(*item);
}
//GUI helpers
void ExpertInfoProxyModel::setSeverityMode(enum SeverityMode mode)
{
severityMode_ = mode;
emit headerDataChanged(Qt::Vertical, 0, 1);
}
void ExpertInfoProxyModel::setSeverityFilter(int severity, bool hide)
{
if (hide)
{
hidden_severities_ << severity;
}
else
{
hidden_severities_.removeOne(severity);
}
invalidateFilter();
}
void ExpertInfoProxyModel::setSummaryFilter(const QString &filter)
{
textFilter_ = filter;
invalidateFilter();
} |
C/C++ | wireshark/ui/qt/models/expert_info_proxy_model.h | /** @file
*
* Data model for Expert Info tap data.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef EXPERT_INFO_PROXY_MODEL_H
#define EXPERT_INFO_PROXY_MODEL_H
#include <config.h>
#include <QSortFilterProxyModel>
class ExpertPacketItem;
class ExpertInfoProxyModel : public QSortFilterProxyModel
{
Q_OBJECT
public:
ExpertInfoProxyModel(QObject *parent = 0);
enum SeverityMode { Group, Packet };
enum ExpertProxyColumn {
colProxySeverity = 0,
colProxySummary,
colProxyGroup,
colProxyProtocol,
colProxyCount,
colProxyLast
};
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
virtual bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
//GUI helpers
void setSeverityMode(enum SeverityMode);
void setSeverityFilter(int severity, bool hide);
void setSummaryFilter(const QString &filter);
protected:
bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const;
bool filterAcceptItem(ExpertPacketItem& item) const;
enum SeverityMode severityMode_;
QList<int> hidden_severities_;
QString textFilter_;
};
#endif // EXPERT_INFO_PROXY_MODEL_H |
C++ | wireshark/ui/qt/models/export_objects_model.cpp | /* export_objects_model.cpp
* Data model for Export Objects.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "export_objects_model.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/utils/variant_pointer.h>
#include <wsutil/filesystem.h>
#include <epan/prefs.h>
#include <QDir>
extern "C" {
static void
object_list_add_entry(void *gui_data, export_object_entry_t *entry) {
export_object_list_gui_t *object_list = (export_object_list_gui_t*)gui_data;
if (object_list && object_list->model)
object_list->model->addObjectEntry(entry);
}
static export_object_entry_t*
object_list_get_entry(void *gui_data, int row) {
export_object_list_gui_t *object_list = (export_object_list_gui_t*)gui_data;
if (object_list && object_list->model)
return object_list->model->objectEntry(row);
return NULL;
}
} // extern "C"
ExportObjectModel::ExportObjectModel(register_eo_t* eo, QObject *parent) :
QAbstractTableModel(parent),
eo_(eo)
{
eo_gui_data_.model = this;
export_object_list_.add_entry = object_list_add_entry;
export_object_list_.get_entry = object_list_get_entry;
export_object_list_.gui_data = (void*)&eo_gui_data_;
}
ExportObjectModel::~ExportObjectModel()
{
foreach (QVariant v, objects_) {
eo_free_entry(VariantPointer<export_object_entry_t>::asPtr(v));
}
}
QVariant ExportObjectModel::data(const QModelIndex &index, int role) const
{
if ((!index.isValid()) || ((role != Qt::DisplayRole) && (role != Qt::UserRole))) {
return QVariant();
}
if (role == Qt::DisplayRole)
{
export_object_entry_t *entry = VariantPointer<export_object_entry_t>::asPtr(objects_.value(index.row()));
if (entry == NULL)
return QVariant();
switch(index.column())
{
case colPacket:
return QString::number(entry->pkt_num);
case colHostname:
return QString::fromUtf8(entry->hostname);
case colContent:
return QString::fromUtf8(entry->content_type);
case colSize:
return file_size_to_qstring(entry->payload_len);
case colFilename:
return QString::fromUtf8(entry->filename);
}
}
else if (role == Qt::UserRole)
{
return objects_.value(index.row());
}
return QVariant();
}
QVariant ExportObjectModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole || orientation != Qt::Horizontal)
return QVariant();
switch (section) {
case colPacket:
return tr("Packet");
case colHostname:
return tr("Hostname");
case colContent:
return tr("Content Type");
case colSize:
return tr("Size");
case colFilename:
return tr("Filename");
}
return QVariant();
}
int ExportObjectModel::rowCount(const QModelIndex &parent) const
{
// there are no children
if (parent.isValid()) {
return 0;
}
return static_cast<int>(objects_.count());
}
int ExportObjectModel::columnCount(const QModelIndex&) const
{
return colExportObjectMax;
}
void ExportObjectModel::addObjectEntry(export_object_entry_t *entry)
{
if (entry == NULL)
return;
int count = static_cast<int>(objects_.count());
beginInsertRows(QModelIndex(), count, count);
objects_.append(VariantPointer<export_object_entry_t>::asQVariant(entry));
endInsertRows();
}
export_object_entry_t* ExportObjectModel::objectEntry(int row)
{
return VariantPointer<export_object_entry_t>::asPtr(objects_.value(row));
}
bool ExportObjectModel::saveEntry(QModelIndex &index, QString filename)
{
if (!index.isValid() || filename.isEmpty())
return false;
export_object_entry_t *entry = VariantPointer<export_object_entry_t>::asPtr(objects_.value(index.row()));
if (entry == NULL)
return false;
if (filename.length() > 0) {
write_file_binary_mode(qUtf8Printable(filename), entry->payload_data, entry->payload_len);
}
return true;
}
void ExportObjectModel::saveAllEntries(QString path)
{
if (path.isEmpty())
return;
QDir save_dir(path);
export_object_entry_t *entry;
for (QList<QVariant>::iterator it = objects_.begin(); it != objects_.end(); ++it)
{
entry = VariantPointer<export_object_entry_t>::asPtr(*it);
if (entry == NULL)
continue;
guint count = 0;
QString filename;
do {
GString *safe_filename;
if (entry->filename)
safe_filename = eo_massage_str(entry->filename,
EXPORT_OBJECT_MAXFILELEN, count);
else {
char generic_name[EXPORT_OBJECT_MAXFILELEN+1];
const char *ext;
ext = eo_ct2ext(entry->content_type);
snprintf(generic_name, sizeof(generic_name),
"object%u%s%s", entry->pkt_num, ext ? "." : "",
ext ? ext : "");
safe_filename = eo_massage_str(generic_name,
EXPORT_OBJECT_MAXFILELEN, count);
}
filename = QString::fromUtf8(safe_filename->str);
g_string_free(safe_filename, TRUE);
} while (save_dir.exists(filename) && ++count < prefs.gui_max_export_objects);
write_file_binary_mode(qUtf8Printable(save_dir.filePath(filename)),
entry->payload_data, entry->payload_len);
}
}
void ExportObjectModel::resetObjects()
{
export_object_gui_reset_cb reset_cb = get_eo_reset_func(eo_);
beginResetModel();
objects_.clear();
endResetModel();
if (reset_cb)
reset_cb();
}
// Called by taps
/* Runs at the beginning of tapping only */
void ExportObjectModel::resetTap(void *tapdata)
{
export_object_list_t *tap_object = (export_object_list_t *)tapdata;
export_object_list_gui_t *object_list = (export_object_list_gui_t *)tap_object->gui_data;
if (object_list && object_list->model)
object_list->model->resetObjects();
}
const char* ExportObjectModel::getTapListenerName()
{
return get_eo_tap_listener_name(eo_);
}
void* ExportObjectModel::getTapData()
{
return &export_object_list_;
}
tap_packet_cb ExportObjectModel::getTapPacketFunc()
{
return get_eo_packet_func(eo_);
}
void ExportObjectModel::removeTap()
{
eo_gui_data_.model = NULL;
}
ExportObjectProxyModel::ExportObjectProxyModel(QObject * parent)
: QSortFilterProxyModel(parent)
{
}
bool ExportObjectProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
{
export_object_entry_t *left_entry = VariantPointer<export_object_entry_t>::asPtr(sourceModel()->data(source_left, Qt::UserRole)),
*right_entry = VariantPointer<export_object_entry_t>::asPtr(sourceModel()->data(source_right, Qt::UserRole));
if ((left_entry != NULL) && (right_entry != NULL))
{
switch (source_left.column())
{
case ExportObjectModel::colPacket:
return left_entry->pkt_num < right_entry->pkt_num;
case ExportObjectModel::colSize:
return left_entry->payload_len < right_entry->payload_len;
case ExportObjectModel::colFilename:
break;
}
}
return QSortFilterProxyModel::lessThan(source_left, source_right);
}
void ExportObjectProxyModel::setContentFilterString(QString filter_)
{
contentFilter_ = filter_;
invalidateFilter();
}
void ExportObjectProxyModel::setTextFilterString(QString filter_)
{
textFilter_ = filter_;
invalidateFilter();
}
bool ExportObjectProxyModel::filterAcceptsRow(int source_row, const QModelIndex &/*source_parent*/) const
{
if (contentFilter_.length() > 0)
{
QModelIndex idx = sourceModel()->index(source_row, ExportObjectModel::colContent);
if (!idx.isValid())
return false;
if (contentFilter_.compare(idx.data().toString()) != 0)
return false;
}
if (textFilter_.length() > 0)
{
QModelIndex hostIdx = sourceModel()->index(source_row, ExportObjectModel::colHostname);
QModelIndex fileIdx = sourceModel()->index(source_row, ExportObjectModel::colFilename);
if (!hostIdx.isValid() || !fileIdx.isValid())
return false;
QString host = hostIdx.data().toString();
QString file = fileIdx.data().toString();
if (!host.contains(textFilter_) && !file.contains(textFilter_))
return false;
}
return true;
} |
C/C++ | wireshark/ui/qt/models/export_objects_model.h | /** @file
*
* Data model for Export Objects.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef EXPORT_OBJECTS_MODEL_H
#define EXPORT_OBJECTS_MODEL_H
#include <config.h>
#include <epan/tap.h>
#include <epan/export_object.h>
#include <QAbstractTableModel>
#include <QSortFilterProxyModel>
#include <QList>
typedef struct export_object_list_gui_t {
class ExportObjectModel *model;
} export_object_list_gui_t;
class ExportObjectModel : public QAbstractTableModel
{
Q_OBJECT
public:
ExportObjectModel(register_eo_t* eo, QObject *parent);
virtual ~ExportObjectModel();
enum ExportObjectColumn {
colPacket = 0,
colHostname,
colContent,
colSize,
colFilename,
colExportObjectMax
};
void addObjectEntry(export_object_entry_t *entry);
export_object_entry_t *objectEntry(int row);
void resetObjects();
bool saveEntry(QModelIndex &index, QString filename);
void saveAllEntries(QString path);
const char* getTapListenerName();
void* getTapData();
tap_packet_cb getTapPacketFunc();
static void resetTap(void *tapdata);
void removeTap();
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
private:
QList<QVariant> objects_;
export_object_list_t export_object_list_;
export_object_list_gui_t eo_gui_data_;
register_eo_t* eo_;
};
class ExportObjectProxyModel : public QSortFilterProxyModel
{
public:
explicit ExportObjectProxyModel(QObject * parent = Q_NULLPTR);
void setContentFilterString(QString contentFilter);
void setTextFilterString(QString textFilter);
protected:
bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const;
bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const;
private:
QString contentFilter_;
QString textFilter_;
};
#endif // EXPORT_OBJECTS_MODEL_H |
C++ | wireshark/ui/qt/models/fileset_entry_model.cpp | /* fileset_entry_model.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/fileset_entry_model.h>
#include "wsutil/utf8_entities.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include <QRegularExpression>
FilesetEntryModel::FilesetEntryModel(QObject * parent) :
QAbstractItemModel(parent)
{}
QModelIndex FilesetEntryModel::index(int row, int column, const QModelIndex &) const
{
if (row >= entries_.count() || row < 0 || column > ColumnCount) {
return QModelIndex();
}
return createIndex(row, column, const_cast<fileset_entry *>(entries_.at(row)));
}
int FilesetEntryModel::rowCount(const QModelIndex &) const
{
return static_cast<int>(entries_.count());
}
QVariant FilesetEntryModel::data(const QModelIndex &index, int role) const
{
if (! index.isValid() || index.row() >= rowCount())
return QVariant();
const fileset_entry *entry = static_cast<fileset_entry*>(index.internalPointer());
if (role == Qt::DisplayRole && entry) {
switch (index.column()) {
case Name:
return QString(entry->name);
case Created:
{
QString created = nameToDate(entry->name);
if (created.length() < 1) {
/* if this file doesn't follow the file set pattern, */
/* use the creation time of that file if available */
/* https://en.wikipedia.org/wiki/ISO_8601 */
/*
* macOS provides 0 if the file system doesn't support the
* creation time; FreeBSD provides -1.
*
* If this OS doesn't provide the creation time with stat(),
* it will be 0.
*/
if (entry->ctime > 0) {
created = time_tToString(entry->ctime);
} else {
created = UTF8_EM_DASH;
}
}
return created;
}
case Modified:
return time_tToString(entry->mtime);
case Size:
return file_size_to_qstring(entry->size);
default:
break;
}
} else if (role == Qt::ToolTipRole) {
return QString(tr("Open this capture file"));
} else if (role == Qt::TextAlignmentRole) {
switch (index.column()) {
case Size:
// Not perfect but better than nothing.
return Qt::AlignRight;
default:
return Qt::AlignLeft;
}
}
return QVariant();
}
QVariant FilesetEntryModel::headerData(int section, Qt::Orientation, int role) const
{
if (role != Qt::DisplayRole) return QVariant();
switch (section) {
case Name:
return tr("Filename");
case Created:
return tr("Created");
case Modified:
return tr("Modified");
case Size:
return tr("Size");
default:
break;
}
return QVariant();
}
void FilesetEntryModel::appendEntry(const fileset_entry *entry)
{
emit beginInsertRows(QModelIndex(), rowCount(), rowCount());
entries_ << entry;
emit endInsertRows();
}
void FilesetEntryModel::clear()
{
fileset_delete();
beginResetModel();
entries_.clear();
endResetModel();
}
QString FilesetEntryModel::nameToDate(const char *name) const {
QString dn;
if (!fileset_filename_match_pattern(name))
return NULL;
dn = name;
dn.remove(QRegularExpression(".*_"));
dn.truncate(14);
dn.insert(4, '-');
dn.insert(7, '-');
dn.insert(10, ' ');
dn.insert(13, ':');
dn.insert(16, ':');
return dn;
}
QString FilesetEntryModel::time_tToString(time_t clock) const
{
struct tm *local = localtime(&clock);
if (!local) return UTF8_EM_DASH;
// yyyy-MM-dd HH:mm:ss
// The equivalent QDateTime call is pretty slow here, possibly related to QTBUG-21678
// and/or QTBUG-41714.
return QString("%1-%2-%3 %4:%5:%6")
.arg(local->tm_year + 1900, 4, 10, QChar('0'))
.arg(local->tm_mon+1, 2, 10, QChar('0'))
.arg(local->tm_mday, 2, 10, QChar('0'))
.arg(local->tm_hour, 2, 10, QChar('0'))
.arg(local->tm_min, 2, 10, QChar('0'))
.arg(local->tm_sec, 2, 10, QChar('0'));
} |
C/C++ | wireshark/ui/qt/models/fileset_entry_model.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef FILESET_ENTRY_MODEL_H
#define FILESET_ENTRY_MODEL_H
#include <config.h>
#include <glib.h>
#include <fileset.h>
#include <QAbstractItemModel>
#include <QModelIndex>
#include <QVector>
class FilesetEntryModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit FilesetEntryModel(QObject * parent = 0);
QModelIndex index(int row, int column, const QModelIndex & = QModelIndex()) const;
// Everything is under the root.
virtual QModelIndex parent(const QModelIndex &) const { return QModelIndex(); }
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
virtual int columnCount(const QModelIndex &) const { return ColumnCount; }
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
virtual QVariant headerData(int section, Qt::Orientation, int role = Qt::DisplayRole) const;
virtual void appendEntry(const fileset_entry *entry);
const fileset_entry *getRowEntry(int row) const { return entries_.value(row, NULL); }
int entryCount() const { return static_cast<int>(entries_.count()); }
// Calls fileset_delete and clears our model data.
void clear();
private:
QVector<const fileset_entry *> entries_;
enum Column { Name, Created, Modified, Size, ColumnCount };
QString nameToDate(const char *name) const ;
QString time_tToString(time_t clock) const;
};
#endif // FILESET_ENTRY_MODEL_H |
C++ | wireshark/ui/qt/models/filter_list_model.cpp | /* filter_list_model.cpp
* Model for all filter types
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <glib.h>
#include <wsutil/filesystem.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/utils/wireshark_mime_data.h>
#include <ui/qt/models/filter_list_model.h>
#include <ui/qt/models/profile_model.h>
#include <QFile>
#include <QTextStream>
#include <QRegularExpression>
#include <QDir>
#include <QMimeData>
/*
* Old filter file name.
*/
#define FILTER_FILE_NAME "filters"
/*
* Capture filter file name.
*/
#define CFILTER_FILE_NAME "cfilters"
/*
* Display filter file name.
*/
#define DFILTER_FILE_NAME "dfilters"
FilterListModel::FilterListModel(QObject * parent) :
QAbstractListModel(parent),
type_(FilterListModel::Display)
{
reload();
}
FilterListModel::FilterListModel(FilterListModel::FilterListType type, QObject * parent) :
QAbstractListModel(parent),
type_(type)
{
reload();
}
void FilterListModel::reload()
{
storage.clear();
const char * cfile = (type_ == FilterListModel::Capture) ? CFILTER_FILE_NAME : DFILTER_FILE_NAME;
/* Try personal config file first */
QString fileName = gchar_free_to_qstring(get_persconffile_path(cfile, TRUE));
if (fileName.length() <= 0 || ! QFileInfo::exists(fileName))
fileName = gchar_free_to_qstring(get_persconffile_path(FILTER_FILE_NAME, TRUE));
if (fileName.length() <= 0 || ! QFileInfo::exists(fileName))
fileName = gchar_free_to_qstring(get_datafile_path(cfile));
if (fileName.length() <= 0 || ! QFileInfo::exists(fileName))
return;
QFile file(fileName);
/* Still can use the model, just have to start from an empty set */
if (! file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&file);
QRegularExpression rx("\\s*\\\"\\s*(.*?)\\s*\\\"\\s(.*)");
while (!in.atEnd())
{
QString data = in.readLine().trimmed();
/* Filter out lines that do not contain content:
* - Starting with # is a comment
* - Does not start with a quoted string
*/
if (data.startsWith("#") || ! data.trimmed().startsWith("\""))
continue;
QStringList content = data.split(QChar('\n'));
foreach (QString line, content)
{
QRegularExpressionMatch match = rx.match(line);
if (match.hasMatch()) {
addFilter(match.captured(1).trimmed(), match.captured(2).trimmed());
}
}
}
}
void FilterListModel::setFilterType(FilterListModel::FilterListType type)
{
type_ = type;
reload();
}
FilterListModel::FilterListType FilterListModel::filterType() const
{
return type_;
}
int FilterListModel::rowCount(const QModelIndex &/* parent */) const
{
return static_cast<int>(storage.count());
}
int FilterListModel::columnCount(const QModelIndex &/* parent */) const
{
return 2;
}
QVariant FilterListModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (section >= columnCount() || section < 0 || orientation != Qt::Horizontal)
return QVariant();
if (role == Qt::DisplayRole)
{
switch (section) {
case ColumnName:
return tr("Filter Name");
break;
case ColumnExpression:
return tr("Filter Expression");
break;
}
}
return QVariant();
}
QVariant FilterListModel::data(const QModelIndex &index, int role) const
{
if (! index.isValid() || index.row() >= rowCount())
return QVariant();
QStringList row = storage.at(index.row()).split("\n");
if (role == Qt::DisplayRole)
return row.at(index.column());
return QVariant();
}
bool FilterListModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (! index.isValid() || index.row() >= rowCount() || role != Qt::EditRole)
return false;
QStringList row = storage.at(index.row()).split("\n");
if (row.count() <= index.column())
return false;
if (index.column() == FilterListModel::ColumnName && value.toString().contains("\""))
return false;
row[index.column()] = value.toString();
storage[index.row()] = row.join("\n");
return true;
}
Qt::ItemFlags FilterListModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags fl = QAbstractListModel::flags(index);
fl |= Qt::ItemIsDropEnabled;
if (! index.isValid() || index.row() >= rowCount())
return fl;
fl |= Qt::ItemIsEditable | Qt::ItemIsDragEnabled;
return fl;
}
QModelIndex FilterListModel::addFilter(QString name, QString expression)
{
if (name.length() == 0 || expression.length() == 0)
return QModelIndex();
beginInsertRows(QModelIndex(), rowCount(), rowCount());
storage << QString("%1\n%2").arg(name).arg(expression);
endInsertRows();
return index(rowCount() - 1, 0);
}
QModelIndex FilterListModel::findByName(QString name)
{
if (name.length() == 0)
return QModelIndex();
for (int cnt = 0; cnt < rowCount(); cnt++)
{
if (storage.at(cnt).startsWith(QString("%1\n").arg(name)))
return index(cnt, 0);
}
return QModelIndex();
}
QModelIndex FilterListModel::findByExpression(QString expression)
{
if (expression.length() == 0)
return QModelIndex();
for (int cnt = 0; cnt < rowCount(); cnt++)
{
if (storage.at(cnt).endsWith(QString("\n%1").arg(expression)))
return index(cnt, 0);
}
return QModelIndex();
}
void FilterListModel::removeFilter(QModelIndex idx)
{
if (! idx.isValid() || idx.row() >= rowCount())
return;
beginRemoveRows(QModelIndex(), idx.row(), idx.row());
storage.removeAt(idx.row());
endRemoveRows();
}
void FilterListModel::saveList()
{
QString filename = (type_ == FilterListModel::Capture) ? CFILTER_FILE_NAME : DFILTER_FILE_NAME;
filename = QString("%1%2%3").arg(ProfileModel::activeProfilePath()).arg("/").arg(filename);
QFile file(filename);
if (! file.open(QIODevice::WriteOnly | QIODevice::Text))
return;
QTextStream out(&file);
for (int row = 0; row < rowCount(); row++)
{
QString line = QString("\"%1\"").arg(index(row, ColumnName).data().toString().trimmed());
line.append(QString(" %1").arg(index(row, ColumnExpression).data().toString()));
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
out << line << Qt::endl;
#else
out << line << endl;
#endif
}
file.close();
}
Qt::DropActions FilterListModel::supportedDropActions() const
{
return Qt::MoveAction;
}
QStringList FilterListModel::mimeTypes() const
{
return QStringList() << WiresharkMimeData::FilterListMimeType;
}
QMimeData *FilterListModel::mimeData(const QModelIndexList &indexes) const
{
QMimeData *mimeData = new QMimeData();
QStringList rows;
foreach (const QModelIndex &index, indexes)
{
if (! rows.contains(QString::number(index.row())))
rows << QString::number(index.row());
}
mimeData->setData(WiresharkMimeData::FilterListMimeType, rows.join(",").toUtf8());
return mimeData;
}
bool FilterListModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int /* column */, const QModelIndex & parent)
{
if (action != Qt::MoveAction)
return true;
if (! data->hasFormat(WiresharkMimeData::FilterListMimeType))
return true;
QStringList rows = QString(data->data(WiresharkMimeData::FilterListMimeType)).split(",");
int insertRow = parent.isValid() ? parent.row() : row;
/* for now, only single rows can be selected */
if (rows.count() > 0)
{
bool ok = false;
int strow = rows[0].toInt(&ok);
if (ok)
{
int storeTo = insertRow;
if (storeTo < 0 || storeTo >= storage.count())
{
storeTo = static_cast<int>(storage.count()) - 1;
}
beginResetModel();
storage.move(strow, storeTo);
endResetModel();
}
}
return true;
} |
C/C++ | wireshark/ui/qt/models/filter_list_model.h | /** @file
*
* Model for all filter types
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef FILTER_LIST_MODEL_h
#define FILTER_LIST_MODEL_h
#include <config.h>
#include <QAbstractListModel>
#include <QList>
#include <QStringList>
class FilterListModel : public QAbstractListModel
{
Q_OBJECT
public:
enum FilterListType {
Display,
Capture
};
explicit FilterListModel(FilterListType type = FilterListModel::Display, QObject * parent = Q_NULLPTR);
explicit FilterListModel(QObject * parent = Q_NULLPTR);
enum {
ColumnName,
ColumnExpression
};
void setFilterType(FilterListModel::FilterListType type);
FilterListModel::FilterListType filterType() const;
QModelIndex findByName(QString name);
QModelIndex findByExpression(QString expression);
QModelIndex addFilter(QString name, QString expression);
void removeFilter(QModelIndex idx);
void saveList();
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const override;
virtual int columnCount(const QModelIndex &parent = QModelIndex()) const override;
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
virtual bool setData(const QModelIndex &index, const QVariant &value, int role) override;
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
virtual Qt::ItemFlags flags(const QModelIndex &index) const override;
virtual Qt::DropActions supportedDropActions() const override;
virtual QStringList mimeTypes() const override;
virtual QMimeData *mimeData(const QModelIndexList &indexes) const override;
virtual bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override;
private:
FilterListModel::FilterListType type_;
QStringList storage;
void reload();
};
#endif // FILTER_LIST_MODEL_h |
C++ | wireshark/ui/qt/models/info_proxy_model.cpp | /* info_proxy_model.cpp
* Proxy model for displaying an info text at the end of any QAbstractListModel
*
* 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/models/info_proxy_model.h>
#include <QFont>
InfoProxyModel::InfoProxyModel(QObject * parent)
: QIdentityProxyModel(parent),
column_(-1)
{
}
InfoProxyModel::~InfoProxyModel()
{
infos_.clear();
}
void InfoProxyModel::appendInfo(QString info)
{
if (! infos_.contains(info))
infos_ << info;
}
void InfoProxyModel::clearInfos()
{
infos_.clear();
}
int InfoProxyModel::rowCount(const QModelIndex &parent) const
{
return static_cast<int>(sourceModel()->rowCount(parent) + infos_.count());
}
QVariant InfoProxyModel::data (const QModelIndex &index, int role) const
{
if (! index.isValid())
return QVariant();
if (index.row() < sourceModel()->rowCount())
return sourceModel()->data(mapToSource(index), role);
int ifIdx = index.row() - sourceModel()->rowCount();
if (index.column() != column_ || ifIdx < 0 || ifIdx >= infos_.count())
return QVariant();
switch (role)
{
case Qt::DisplayRole:
return infos_.at(ifIdx);
break;
case Qt::FontRole:
QFont font = QIdentityProxyModel::data(index, Qt::FontRole).value<QFont>();
font.setItalic(true);
return font;
}
return QIdentityProxyModel::data(index, role);
}
Qt::ItemFlags InfoProxyModel::flags(const QModelIndex &index) const
{
if (index.row() < sourceModel()->rowCount())
return sourceModel()->flags(mapToSource(index));
return Qt::ItemFlags();
}
QModelIndex InfoProxyModel::index(int row, int column, const QModelIndex &parent) const
{
if (row >= sourceModel()->rowCount() && row < rowCount())
return createIndex(row, column);
return QIdentityProxyModel::index(row, column, parent);
}
QModelIndex InfoProxyModel::mapToSource(const QModelIndex &proxyIndex) const
{
if (! proxyIndex.isValid())
return QModelIndex();
if (proxyIndex.row() >= sourceModel()->rowCount())
return QModelIndex();
return QIdentityProxyModel::mapToSource(proxyIndex);
}
QModelIndex InfoProxyModel::mapFromSource(const QModelIndex &fromIndex) const
{
return QIdentityProxyModel::mapFromSource(fromIndex);
}
void InfoProxyModel::setColumn(int column)
{
int old_column = column_;
column_ = column;
QVector<int> roles;
roles << Qt::DisplayRole;
if (old_column >= 0) {
//Notify old column has changed
emit dataChanged(index(0, old_column), index(rowCount(), old_column), roles);
}
if (column_ >= 0) {
//Notify new column has changed
emit dataChanged(index(0, column_), index(rowCount(), column_), roles);
}
} |
C/C++ | wireshark/ui/qt/models/info_proxy_model.h | /** @file
*
* Proxy model for displaying an info text at the end of any QAbstractListModel
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef INFO_PROXY_MODEL_H
#define INFO_PROXY_MODEL_H
#include <config.h>
#include <QStringList>
#include <QIdentityProxyModel>
class InfoProxyModel : public QIdentityProxyModel
{
public:
explicit InfoProxyModel(QObject * parent = 0);
~InfoProxyModel();
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
virtual QVariant data (const QModelIndex &index, int role = Qt::DisplayRole) const;
virtual Qt::ItemFlags flags(const QModelIndex &index) const;
virtual QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
virtual QModelIndex mapToSource(const QModelIndex &proxyIndex) const;
virtual QModelIndex mapFromSource(const QModelIndex &fromIndex) const;
void appendInfo(QString info);
void clearInfos();
void setColumn(int column);
private:
int column_;
QStringList infos_;
};
#endif // INFO_PROXY_MODEL_H |
C++ | wireshark/ui/qt/models/interface_sort_filter_model.cpp | /* interface_sort_filter_model.cpp
* Proxy model for the display of interface data for the interface tree
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/interface_tree_model.h>
#include <ui/qt/models/interface_tree_cache_model.h>
#include <ui/qt/models/interface_sort_filter_model.h>
#include <glib.h>
#include <epan/prefs.h>
#include <ui/preference_utils.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
#include <QAbstractItemModel>
InterfaceSortFilterModel::InterfaceSortFilterModel(QObject *parent) :
QSortFilterProxyModel(parent)
{
resetAllFilter();
}
void InterfaceSortFilterModel::resetAllFilter()
{
_filterHidden = true;
_filterTypes = true;
_invertTypeFilter = false;
_storeOnChange = false;
_sortByActivity = false;
#ifdef HAVE_PCAP_REMOTE
_remoteDisplay = true;
#endif
/* Adding all columns, to have a default setting */
for (int col = 0; col < IFTREE_COL_MAX; col++)
_columns.append((InterfaceTreeColumns)col);
invalidateFilter();
invalidate();
}
void InterfaceSortFilterModel::setStoreOnChange(bool storeOnChange)
{
_storeOnChange = storeOnChange;
if (storeOnChange)
{
connect(mainApp, &MainApplication::preferencesChanged, this, &InterfaceSortFilterModel::resetPreferenceData);
resetPreferenceData();
}
}
void InterfaceSortFilterModel::setFilterHidden(bool filter)
{
_filterHidden = filter;
invalidate();
}
void InterfaceSortFilterModel::setSortByActivity(bool sort)
{
_sortByActivity = sort;
invalidate();
}
bool InterfaceSortFilterModel::sortByActivity() const
{
return _sortByActivity;
}
#ifdef HAVE_PCAP_REMOTE
void InterfaceSortFilterModel::setRemoteDisplay(bool remoteDisplay)
{
_remoteDisplay = remoteDisplay;
invalidate();
}
bool InterfaceSortFilterModel::remoteDisplay()
{
return _remoteDisplay;
}
void InterfaceSortFilterModel::toggleRemoteDisplay()
{
_remoteDisplay = ! _remoteDisplay;
if (_storeOnChange)
{
prefs.gui_interfaces_remote_display = ! _remoteDisplay;
prefs_main_write();
}
invalidateFilter();
invalidate();
}
bool InterfaceSortFilterModel::remoteInterfacesExist()
{
bool exist = false;
if (sourceModel()->rowCount() == 0)
return exist;
for (int idx = 0; idx < sourceModel()->rowCount() && ! exist; idx++)
exist = ((InterfaceTreeModel *)sourceModel())->isRemote(idx);
return exist;
}
#endif
void InterfaceSortFilterModel::setFilterByType(bool filter, bool invert)
{
_filterTypes = filter;
_invertTypeFilter = invert;
invalidate();
}
void InterfaceSortFilterModel::resetPreferenceData()
{
displayHiddenTypes.clear();
QString stored_prefs(prefs.gui_interfaces_hide_types);
if (stored_prefs.length() > 0)
{
QStringList ifTypesStored = stored_prefs.split(',');
QStringList::const_iterator it = ifTypesStored.constBegin();
while (it != ifTypesStored.constEnd())
{
int i_val = (*it).toInt();
if (! displayHiddenTypes.contains(i_val))
displayHiddenTypes.append(i_val);
++it;
}
}
#if 0
// Disabled until bug 13354 is fixed
_filterHidden = ! prefs.gui_interfaces_show_hidden;
#endif
#ifdef HAVE_PCAP_REMOTE
_remoteDisplay = prefs.gui_interfaces_remote_display;
#endif
invalidate();
}
bool InterfaceSortFilterModel::filterHidden() const
{
return _filterHidden;
}
void InterfaceSortFilterModel::toggleFilterHidden()
{
_filterHidden = ! _filterHidden;
if (_storeOnChange)
{
prefs.gui_interfaces_show_hidden = ! _filterHidden;
prefs_main_write();
}
invalidateFilter();
invalidate();
}
bool InterfaceSortFilterModel::filterByType() const
{
return _filterTypes;
}
int InterfaceSortFilterModel::interfacesHidden()
{
#ifdef HAVE_LIBPCAP
if (! global_capture_opts.all_ifaces)
return 0;
#endif
return sourceModel()->rowCount() - rowCount();
}
QList<int> InterfaceSortFilterModel::typesDisplayed()
{
QList<int> shownTypes;
if (sourceModel()->rowCount() == 0)
return shownTypes;
for (int idx = 0; idx < sourceModel()->rowCount(); idx++)
{
int type = ((InterfaceTreeModel *)sourceModel())->getColumnContent(idx, IFTREE_COL_TYPE).toInt();
bool hidden = ((InterfaceTreeModel *)sourceModel())->getColumnContent(idx, IFTREE_COL_HIDDEN).toBool();
if (! hidden)
{
if (! shownTypes.contains(type))
shownTypes.append(type);
}
}
return shownTypes;
}
void InterfaceSortFilterModel::setInterfaceTypeVisible(int ifType, bool visible)
{
if (visible && displayHiddenTypes.contains(ifType))
displayHiddenTypes.removeAll(ifType);
else if (! visible && ! displayHiddenTypes.contains(ifType))
displayHiddenTypes.append(ifType);
else
/* Nothing should have changed */
return;
if (_storeOnChange)
{
QString new_pref;
QList<int>::const_iterator it = displayHiddenTypes.constBegin();
while (it != displayHiddenTypes.constEnd())
{
new_pref.append(QString("%1,").arg(*it));
++it;
}
if (new_pref.length() > 0)
new_pref = new_pref.left(new_pref.length() - 1);
prefs.gui_interfaces_hide_types = qstring_strdup(new_pref);
prefs_main_write();
}
invalidateFilter();
invalidate();
}
void InterfaceSortFilterModel::toggleTypeVisibility(int ifType)
{
bool checked = isInterfaceTypeShown(ifType);
setInterfaceTypeVisible(ifType, checked ? false : true);
}
bool InterfaceSortFilterModel::isInterfaceTypeShown(int ifType) const
{
bool result = false;
if (displayHiddenTypes.size() == 0)
result = true;
else if (! displayHiddenTypes.contains(ifType))
result = true;
return ((_invertTypeFilter && ! result) || (! _invertTypeFilter && result) );
}
bool InterfaceSortFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex & sourceParent) const
{
QModelIndex realIndex = sourceModel()->index(sourceRow, 0, sourceParent);
if (! realIndex.isValid())
return false;
#ifdef HAVE_LIBPCAP
int idx = realIndex.row();
/* No data loaded, we do not display anything */
if (sourceModel()->rowCount() == 0)
return false;
int type = -1;
bool hidden = false;
if (dynamic_cast<InterfaceTreeCacheModel*>(sourceModel()) != 0)
{
type = ((InterfaceTreeCacheModel *)sourceModel())->getColumnContent(idx, IFTREE_COL_TYPE).toInt();
hidden = ((InterfaceTreeCacheModel *)sourceModel())->getColumnContent(idx, IFTREE_COL_HIDDEN, Qt::UserRole).toBool();
}
else if (dynamic_cast<InterfaceTreeModel*>(sourceModel()) != 0)
{
type = ((InterfaceTreeModel *)sourceModel())->getColumnContent(idx, IFTREE_COL_TYPE).toInt();
hidden = ((InterfaceTreeModel *)sourceModel())->getColumnContent(idx, IFTREE_COL_HIDDEN, Qt::UserRole).toBool();
}
else
return false;
if (hidden && _filterHidden)
return false;
if (_filterTypes && ! isInterfaceTypeShown(type))
{
#ifdef HAVE_PCAP_REMOTE
/* Remote interfaces have the if type IF_WIRED, therefore would be filtered, if not explicitly checked here */
if (type != IF_WIRED || ! ((InterfaceTreeModel *)sourceModel())->isRemote(idx))
#endif
return false;
}
#ifdef HAVE_PCAP_REMOTE
if (((InterfaceTreeModel *)sourceModel())->isRemote(idx))
{
if (! _remoteDisplay)
return false;
}
#endif
#endif
return true;
}
bool InterfaceSortFilterModel::filterAcceptsColumn(int sourceColumn, const QModelIndex & sourceParent) const
{
QModelIndex realIndex = sourceModel()->index(0, sourceColumn, sourceParent);
if (! realIndex.isValid())
return false;
if (! _columns.contains((InterfaceTreeColumns)sourceColumn))
return false;
return true;
}
void InterfaceSortFilterModel::setColumns(QList<InterfaceTreeColumns> columns)
{
_columns.clear();
_columns.append(columns);
}
int InterfaceSortFilterModel::mapSourceToColumn(InterfaceTreeColumns mdlIndex)
{
if (! _columns.contains(mdlIndex))
return -1;
return static_cast<int>(_columns.indexOf(mdlIndex, 0));
}
QModelIndex InterfaceSortFilterModel::mapToSource(const QModelIndex &proxyIndex) const
{
if (! proxyIndex.isValid())
return QModelIndex();
if (! sourceModel())
return QModelIndex();
QModelIndex baseIndex = QSortFilterProxyModel::mapToSource(proxyIndex);
QModelIndex newIndex = sourceModel()->index(baseIndex.row(), _columns.at(proxyIndex.column()));
return newIndex;
}
QModelIndex InterfaceSortFilterModel::mapFromSource(const QModelIndex &sourceIndex) const
{
if (! sourceIndex.isValid())
return QModelIndex();
else if (! _columns.contains((InterfaceTreeColumns) sourceIndex.column()) )
return QModelIndex();
QModelIndex newIndex = QSortFilterProxyModel::mapFromSource(sourceIndex);
return index(newIndex.row(), static_cast<int>(_columns.indexOf((InterfaceTreeColumns) sourceIndex.column())));
}
QString InterfaceSortFilterModel::interfaceError()
{
QString result;
InterfaceTreeModel * sourceModel = dynamic_cast<InterfaceTreeModel *>(this->sourceModel());
if (sourceModel != NULL)
result = sourceModel->interfaceError();
if (result.size() == 0 && rowCount() == 0)
result = tr("No interfaces to be displayed. %1 interfaces hidden.").arg(interfacesHidden());
return result;
}
bool InterfaceSortFilterModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
{
bool leftActive = source_left.sibling(source_left.row(), InterfaceTreeColumns::IFTREE_COL_ACTIVE).data(Qt::UserRole).toBool();
bool rightActive = source_right.sibling(source_right.row(), InterfaceTreeColumns::IFTREE_COL_ACTIVE).data(Qt::UserRole).toBool();
if (_sortByActivity && rightActive && ! leftActive)
return true;
return QSortFilterProxyModel::lessThan(source_left, source_right);
} |
C/C++ | wireshark/ui/qt/models/interface_sort_filter_model.h | /** @file
*
* Proxy model for the display of interface data for the interface tree
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef INTERFACE_SORT_FILTER_MODEL_H
#define INTERFACE_SORT_FILTER_MODEL_H
#include <config.h>
#include <ui/qt/models/interface_tree_model.h>
#include <glib.h>
#include <QSortFilterProxyModel>
class InterfaceSortFilterModel : public QSortFilterProxyModel
{
Q_OBJECT
public:
InterfaceSortFilterModel(QObject *parent);
void setStoreOnChange(bool storeOnChange);
void resetAllFilter();
void setFilterHidden(bool filter);
bool filterHidden() const;
int interfacesHidden();
void toggleFilterHidden();
void setSortByActivity(bool sort);
bool sortByActivity() const;
#ifdef HAVE_PCAP_REMOTE
void setRemoteDisplay(bool remoteDisplay);
bool remoteDisplay();
void toggleRemoteDisplay();
bool remoteInterfacesExist();
#endif
void setInterfaceTypeVisible(int ifType, bool visible);
bool isInterfaceTypeShown(int ifType) const;
void setFilterByType(bool filter, bool invert = false);
bool filterByType() const;
void toggleTypeVisibility(int ifType);
QList<int> typesDisplayed();
void setColumns(QList<InterfaceTreeColumns> columns);
int mapSourceToColumn(InterfaceTreeColumns mdlIndex);
QModelIndex mapToSource(const QModelIndex &proxyIndex) const;
QModelIndex mapFromSource(const QModelIndex &sourceIndex) const;
QString interfaceError();
protected:
bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const;
bool filterAcceptsColumn(int source_column, const QModelIndex & source_parent) const;
bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const;
private:
bool _filterHidden;
bool _filterTypes;
bool _invertTypeFilter;
bool _storeOnChange;
bool _sortByActivity;
#ifdef HAVE_PCAP_REMOTE
bool _remoteDisplay;
#endif
QList<int> displayHiddenTypes;
QList<InterfaceTreeColumns> _columns;
private slots:
void resetPreferenceData();
};
#endif // INTERFACE_SORT_FILTER_MODEL_H |
C++ | wireshark/ui/qt/models/interface_tree_cache_model.cpp | /* interface_tree_cache_model.cpp
* Model caching interface changes before sending them to global storage
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/interface_tree_cache_model.h>
#include "epan/prefs.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include "ui/capture_globals.h"
#include "wsutil/utf8_entities.h"
#include "wiretap/wtap.h"
#include "main_application.h"
#include <QIdentityProxyModel>
InterfaceTreeCacheModel::InterfaceTreeCacheModel(QObject *parent) :
QIdentityProxyModel(parent)
{
/* ATTENTION: This cache model is not intended to be used with anything
* else then InterfaceTreeModel, and will break with anything else
* leading to unintended results. */
sourceModel = new InterfaceTreeModel(parent);
QIdentityProxyModel::setSourceModel(sourceModel);
storage = new QMap<int, QMap<InterfaceTreeColumns, QVariant> *>();
checkableColumns << IFTREE_COL_HIDDEN << IFTREE_COL_PROMISCUOUSMODE;
#ifdef HAVE_PCAP_CREATE
checkableColumns << IFTREE_COL_MONITOR_MODE;
#endif
editableColumns << IFTREE_COL_COMMENT << IFTREE_COL_SNAPLEN << IFTREE_COL_PIPE_PATH;
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
editableColumns << IFTREE_COL_BUFFERLEN;
#endif
}
InterfaceTreeCacheModel::~InterfaceTreeCacheModel()
{
#ifdef HAVE_LIBPCAP
/* This list should only exist, if the dialog is closed, without calling save first */
newDevices.clear();
#endif
delete storage;
delete sourceModel;
}
QVariant InterfaceTreeCacheModel::getColumnContent(int idx, int col, int role)
{
return InterfaceTreeCacheModel::data(index(idx, col), role);
}
#ifdef HAVE_LIBPCAP
void InterfaceTreeCacheModel::reset(int row)
{
if (row < 0)
{
delete storage;
storage = new QMap<int, QMap<InterfaceTreeColumns, QVariant> *>();
}
else
{
if (storage->count() > row)
storage->remove(storage->keys().at(row));
}
}
void InterfaceTreeCacheModel::saveNewDevices()
{
QList<interface_t>::const_iterator it = newDevices.constBegin();
/* idx is used for iterating only over the indices of the new devices. As all new
* devices are stored with an index higher then sourceModel->rowCount(), we start
* only with those storage indices.
* it is just the iterator over the new devices. A new device must not necessarily
* have storage, which will lead to that device not being stored in global_capture_opts */
for (int idx = sourceModel->rowCount(); it != newDevices.constEnd(); ++it, idx++)
{
interface_t *device = const_cast<interface_t *>(&(*it));
bool useDevice = false;
QMap<InterfaceTreeColumns, QVariant> * dataField = storage->value(idx, 0);
/* When devices are being added, they are added using generic values. So only devices
* whose data have been changed should be used from here on out. */
if (dataField != 0)
{
if (device->if_info.type != IF_PIPE)
{
continue;
}
if (device->if_info.type == IF_PIPE)
{
QVariant saveValue = dataField->value(IFTREE_COL_PIPE_PATH);
if (saveValue.isValid())
{
g_free(device->if_info.name);
device->if_info.name = qstring_strdup(saveValue.toString());
g_free(device->name);
device->name = qstring_strdup(saveValue.toString());
g_free(device->display_name);
device->display_name = qstring_strdup(saveValue.toString());
useDevice = true;
}
}
if (useDevice)
g_array_append_val(global_capture_opts.all_ifaces, *device);
}
/* All entries of this new devices have been considered */
storage->remove(idx);
delete dataField;
}
newDevices.clear();
}
void InterfaceTreeCacheModel::save()
{
if (storage->count() == 0)
return;
QMap<char**, QStringList> prefStorage;
/* No devices are hidden until checking "Show" state */
prefStorage[&prefs.capture_devices_hide] = QStringList();
/* Storing new devices first including their changed values */
saveNewDevices();
for (unsigned int idx = 0; idx < global_capture_opts.all_ifaces->len; idx++)
{
interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, idx);
if (! device->name)
continue;
/* Try to load a saved value row for this index */
QMap<InterfaceTreeColumns, QVariant> * dataField = storage->value(idx, 0);
/* Handle the storing of values for this device here */
if (dataField)
{
QMap<InterfaceTreeColumns, QVariant>::const_iterator it = dataField->constBegin();
while (it != dataField->constEnd())
{
InterfaceTreeColumns col = it.key();
QVariant saveValue = it.value();
/* Setting the field values for each individual saved value cannot be generic, as the
* struct cannot be accessed in a generic way. Therefore below, each individually changed
* value has to be handled separately. Comments are stored only in the preference file
* and applied to the data name during loading. Therefore comments are not handled here */
if (col == IFTREE_COL_HIDDEN)
{
device->hidden = saveValue.toBool();
}
else if (device->if_info.type == IF_EXTCAP)
{
/* extcap interfaces do not have the following columns.
* ATTENTION: all generic columns must be added, BEFORE this
* if-clause, or they will be ignored for extcap interfaces */
}
else if (col == IFTREE_COL_PROMISCUOUSMODE)
{
device->pmode = saveValue.toBool();
}
#ifdef HAVE_PCAP_CREATE
else if (col == IFTREE_COL_MONITOR_MODE)
{
device->monitor_mode_enabled = saveValue.toBool();
}
#endif
else if (col == IFTREE_COL_SNAPLEN)
{
int iVal = saveValue.toInt();
if (iVal != WTAP_MAX_PACKET_SIZE_STANDARD)
{
device->has_snaplen = true;
device->snaplen = iVal;
}
else
{
device->has_snaplen = false;
device->snaplen = WTAP_MAX_PACKET_SIZE_STANDARD;
}
}
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
else if (col == IFTREE_COL_BUFFERLEN)
{
device->buffer = saveValue.toInt();
}
#endif
++it;
}
}
QVariant content = getColumnContent(idx, IFTREE_COL_HIDDEN, Qt::CheckStateRole);
if (content.isValid() && static_cast<Qt::CheckState>(content.toInt()) == Qt::Unchecked)
prefStorage[&prefs.capture_devices_hide] << QString(device->name);
content = getColumnContent(idx, IFTREE_COL_COMMENT);
if (content.isValid() && content.toString().size() > 0)
prefStorage[&prefs.capture_devices_descr] << QString("%1(%2)").arg(device->name).arg(content.toString());
bool allowExtendedColumns = true;
if (device->if_info.type == IF_EXTCAP)
allowExtendedColumns = false;
if (allowExtendedColumns)
{
content = getColumnContent(idx, IFTREE_COL_PROMISCUOUSMODE, Qt::CheckStateRole);
if (content.isValid())
{
bool value = static_cast<Qt::CheckState>(content.toInt()) == Qt::Checked;
prefStorage[&prefs.capture_devices_pmode] << QString("%1(%2)").arg(device->name).arg(value ? 1 : 0);
}
#ifdef HAVE_PCAP_CREATE
content = getColumnContent(idx, IFTREE_COL_MONITOR_MODE, Qt::CheckStateRole);
if (content.isValid() && static_cast<Qt::CheckState>(content.toInt()) == Qt::Checked)
prefStorage[&prefs.capture_devices_monitor_mode] << QString(device->name);
#endif
content = getColumnContent(idx, IFTREE_COL_SNAPLEN);
if (content.isValid())
{
int value = content.toInt();
prefStorage[&prefs.capture_devices_snaplen] <<
QString("%1:%2(%3)").arg(device->name).
arg(device->has_snaplen ? 1 : 0).
arg(device->has_snaplen ? value : WTAP_MAX_PACKET_SIZE_STANDARD);
}
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
content = getColumnContent(idx, IFTREE_COL_BUFFERLEN);
if (content.isValid())
{
int value = content.toInt();
if (value != -1)
{
prefStorage[&prefs.capture_devices_buffersize] <<
QString("%1(%2)").arg(device->name).
arg(value);
}
}
#endif
}
}
QMap<char**, QStringList>::const_iterator it = prefStorage.constBegin();
while (it != prefStorage.constEnd())
{
char ** key = it.key();
g_free(*key);
*key = qstring_strdup(it.value().join(","));
++it;
}
mainApp->emitAppSignal(MainApplication::LocalInterfacesChanged);
}
#endif
int InterfaceTreeCacheModel::rowCount(const QModelIndex & parent) const
{
int totalCount = sourceModel->rowCount(parent);
#ifdef HAVE_LIBPCAP
totalCount += newDevices.size();
#endif
return totalCount;
}
bool InterfaceTreeCacheModel::changeIsAllowed(InterfaceTreeColumns col) const
{
if (editableColumns.contains(col) || checkableColumns.contains(col))
return true;
return false;
}
#ifdef HAVE_LIBPCAP
const interface_t * InterfaceTreeCacheModel::lookup(const QModelIndex &index) const
{
const interface_t * result = 0;
if (! index.isValid() || ! global_capture_opts.all_ifaces)
return result;
int idx = index.row();
if ((unsigned int) idx >= global_capture_opts.all_ifaces->len)
{
idx = idx - global_capture_opts.all_ifaces->len;
if (idx < newDevices.size())
result = &newDevices[idx];
}
else
{
result = &g_array_index(global_capture_opts.all_ifaces, interface_t, idx);
}
return result;
}
#endif
/* This checks if the column can be edited for the given index. This differs from
* isAvailableField in such a way, that it is only used in flags and not any
* other method.*/
bool InterfaceTreeCacheModel::isAllowedToBeEdited(const QModelIndex &index) const
{
#ifndef HAVE_LIBPCAP
Q_UNUSED(index);
#else
const interface_t * device = lookup(index);
if (device == 0)
return false;
InterfaceTreeColumns col = (InterfaceTreeColumns) index.column();
if (device->if_info.type == IF_EXTCAP)
{
/* extcap interfaces do not have those settings */
if (col == IFTREE_COL_PROMISCUOUSMODE || col == IFTREE_COL_SNAPLEN)
return false;
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
if (col == IFTREE_COL_BUFFERLEN)
return false;
#endif
}
#endif
return true;
}
// Whether this field is available for modification and display.
bool InterfaceTreeCacheModel::isAvailableField(const QModelIndex &index) const
{
#ifndef HAVE_LIBPCAP
Q_UNUSED(index);
#else
const interface_t * device = lookup(index);
if (device == 0)
return false;
InterfaceTreeColumns col = (InterfaceTreeColumns) index.column();
if (col == IFTREE_COL_HIDDEN)
{
// Do not allow default capture interface to be hidden.
if (! g_strcmp0(prefs.capture_device, device->display_name))
return false;
}
#endif
return true;
}
Qt::ItemFlags InterfaceTreeCacheModel::flags(const QModelIndex &index) const
{
if (! index.isValid())
return Qt::ItemFlags();
Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
InterfaceTreeColumns col = (InterfaceTreeColumns) index.column();
if (changeIsAllowed(col) && isAvailableField(index) && isAllowedToBeEdited(index))
{
if (checkableColumns.contains(col))
{
flags |= Qt::ItemIsUserCheckable;
}
else
{
flags |= Qt::ItemIsEditable;
}
}
return flags;
}
bool InterfaceTreeCacheModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (! index.isValid())
return false;
if (! isAvailableField(index))
return false;
int row = index.row();
InterfaceTreeColumns col = (InterfaceTreeColumns)index.column();
if (role == Qt::CheckStateRole || role == Qt::EditRole)
{
if (changeIsAllowed(col) )
{
QVariant saveValue = value;
QMap<InterfaceTreeColumns, QVariant> * dataField = 0;
/* obtain the list of already stored changes for this row. If none exist
* create a new storage row for this entry */
if ((dataField = storage->value(row, 0)) == 0)
{
dataField = new QMap<InterfaceTreeColumns, QVariant>();
storage->insert(row, dataField);
}
dataField->insert(col, saveValue);
return true;
}
}
return false;
}
QVariant InterfaceTreeCacheModel::data(const QModelIndex &index, int role) const
{
if (! index.isValid())
return QVariant();
int row = index.row();
InterfaceTreeColumns col = (InterfaceTreeColumns)index.column();
if (isAvailableField(index) && isAllowedToBeEdited(index))
{
if (((role == Qt::DisplayRole || role == Qt::EditRole) && editableColumns.contains(col)) ||
(role == Qt::CheckStateRole && checkableColumns.contains(col)) )
{
QMap<InterfaceTreeColumns, QVariant> * dataField = 0;
if ((dataField = storage->value(row, 0)) != 0)
{
if (dataField->contains(col))
{
return dataField->value(col, QVariant());
}
}
}
}
else
{
if (role == Qt::CheckStateRole)
return QVariant();
else if (role == Qt::DisplayRole)
return QString(UTF8_EM_DASH);
}
if (row < sourceModel->rowCount())
{
return sourceModel->data(index, role);
}
#ifdef HAVE_LIBPCAP
else
{
/* Handle all fields, which will have to be displayed for new devices. Only pipes
* are supported at the moment, so the information to be displayed is pretty limited.
* After saving, the devices are stored in global_capture_opts and no longer
* classify as new devices. */
const interface_t * device = lookup(index);
if (device != 0)
{
if (role == Qt::DisplayRole || role == Qt::EditRole)
{
if (col == IFTREE_COL_PIPE_PATH ||
col == IFTREE_COL_NAME ||
col == IFTREE_COL_DESCRIPTION)
{
QMap<InterfaceTreeColumns, QVariant> * dataField = 0;
if ((dataField = storage->value(row, 0)) != 0 &&
dataField->contains(IFTREE_COL_PIPE_PATH))
{
return dataField->value(IFTREE_COL_PIPE_PATH, QVariant());
}
else
return QString(device->name);
}
else if (col == IFTREE_COL_TYPE)
{
return QVariant::fromValue((int)device->if_info.type);
}
}
else if (role == Qt::CheckStateRole)
{
if (col == IFTREE_COL_HIDDEN)
{
// Do not allow default capture interface to be hidden.
if (! g_strcmp0(prefs.capture_device, device->display_name))
return QVariant();
/* Hidden is a de-selection, therefore inverted logic here */
return device->hidden ? Qt::Unchecked : Qt::Checked;
}
}
}
}
#endif
return QVariant();
}
#ifdef HAVE_LIBPCAP
QModelIndex InterfaceTreeCacheModel::index(int row, int column, const QModelIndex &parent) const
{
if (row >= sourceModel->rowCount() && (row - sourceModel->rowCount()) < newDevices.count())
{
return createIndex(row, column, (void *)0);
}
return QIdentityProxyModel::index(row, column, parent);
}
void InterfaceTreeCacheModel::addDevice(const interface_t * newDevice)
{
emit beginInsertRows(QModelIndex(), rowCount(), rowCount());
newDevices << *newDevice;
emit endInsertRows();
}
void InterfaceTreeCacheModel::deleteDevice(const QModelIndex &index)
{
if (! index.isValid())
return;
emit beginRemoveRows(QModelIndex(), index.row(), index.row());
int row = index.row();
/* device is in newDevices */
if (row >= sourceModel->rowCount())
{
int newDeviceIdx = row - sourceModel->rowCount();
newDevices.removeAt(newDeviceIdx);
if (storage->contains(index.row()))
storage->remove(index.row());
/* The storage array has to be resorted, if the index, that was removed
* had been in the middle of the array. Can't start at index.row(), as
* it may not be contained in storage
* We must iterate using a list, not an iterator, otherwise the change
* will fold on itself. */
QList<int> storageKeys = storage->keys();
for (int i = 0; i < storageKeys.size(); ++i)
{
int key = storageKeys.at(i);
if (key > index.row())
{
storage->insert(key - 1, storage->value(key));
storage->remove(key);
}
}
emit endRemoveRows();
}
else
{
interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, row);
capture_opts_free_interface_t(device);
global_capture_opts.all_ifaces = g_array_remove_index(global_capture_opts.all_ifaces, row);
emit endRemoveRows();
mainApp->emitAppSignal(MainApplication::LocalInterfacesChanged);
}
}
#endif |
C/C++ | wireshark/ui/qt/models/interface_tree_cache_model.h | /** @file
*
* Model caching interface changes before sending them to global storage
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef INTERFACE_TREE_CACHE_MODEL_H_
#define INTERFACE_TREE_CACHE_MODEL_H_
#include <ui/qt/models/interface_tree_model.h>
#include <QMap>
#include <QAbstractItemModel>
#include <QIdentityProxyModel>
class InterfaceTreeCacheModel : public QIdentityProxyModel
{
public:
explicit InterfaceTreeCacheModel(QObject *parent);
~InterfaceTreeCacheModel();
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data (const QModelIndex &index, int role = Qt::DisplayRole) const;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
Qt::ItemFlags flags(const QModelIndex &index) const;
QVariant getColumnContent(int idx, int col, int role = Qt::DisplayRole);
#ifdef HAVE_LIBPCAP
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
void reset(int row);
void save();
void addDevice(const interface_t * newDevice);
void deleteDevice(const QModelIndex &index);
#endif
private:
InterfaceTreeModel * sourceModel;
#ifdef HAVE_LIBPCAP
QList<interface_t> newDevices;
void saveNewDevices();
#endif
QMap<int, QMap<InterfaceTreeColumns, QVariant> *> * storage;
QList<InterfaceTreeColumns> editableColumns;
QList<InterfaceTreeColumns> checkableColumns;
#ifdef HAVE_LIBPCAP
const interface_t * lookup(const QModelIndex &index) const;
#endif
bool changeIsAllowed(InterfaceTreeColumns col) const;
bool isAvailableField(const QModelIndex &index) const;
bool isAllowedToBeEdited(const QModelIndex &index) const;
};
#endif /* INTERFACE_TREE_CACHE_MODEL_H_ */ |
C++ | wireshark/ui/qt/models/interface_tree_model.cpp | /* interface_tree_model.cpp
* Model for the interface data for display in the interface frame
*
* 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/models/interface_tree_model.h>
#ifdef HAVE_LIBPCAP
#include "ui/capture.h"
#include "capture/capture-pcap-util.h"
#include "capture_opts.h"
#include "ui/capture_ui_utils.h"
#include "ui/capture_globals.h"
#endif
#include "wsutil/filesystem.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/utils/stock_icon.h>
#include "main_application.h"
/* Needed for the meta type declaration of QList<int>* */
#include <ui/qt/models/sparkline_delegate.h>
#include "extcap.h"
const QString InterfaceTreeModel::DefaultNumericValue = QObject::tr("default");
/**
* This is the data model for interface trees. It implies, that the index within
* global_capture_opts.all_ifaces is identical to the row. This is always the case, even
* when interfaces are hidden by the proxy model. But for this to work, every access
* to the index from within the view, has to be filtered through the proxy model.
*/
InterfaceTreeModel::InterfaceTreeModel(QObject *parent) :
QAbstractTableModel(parent)
#ifdef HAVE_LIBPCAP
,stat_cache_(NULL)
#endif
{
connect(mainApp, &MainApplication::appInitialized, this, &InterfaceTreeModel::interfaceListChanged);
connect(mainApp, &MainApplication::localInterfaceListChanged, this, &InterfaceTreeModel::interfaceListChanged);
}
InterfaceTreeModel::~InterfaceTreeModel(void)
{
#ifdef HAVE_LIBPCAP
if (stat_cache_) {
capture_stat_stop(stat_cache_);
stat_cache_ = NULL;
}
#endif // HAVE_LIBPCAP
}
QString InterfaceTreeModel::interfaceError()
{
#ifdef HAVE_LIBPCAP
//
// First, see if there was an error fetching the interfaces.
// If so, report it.
//
if (global_capture_opts.ifaces_err != 0)
{
return tr(global_capture_opts.ifaces_err_info);
}
//
// Otherwise, if there are no rows, there were no interfaces
// found.
//
if (rowCount() == 0)
{
return tr("No interfaces found.");
}
//
// No error. Return an empty string.
//
return "";
#else
//
// We were built without pcap support, so we have no notion of
// local interfaces.
//
return tr("This version of Wireshark was built without packet capture support.");
#endif
}
int InterfaceTreeModel::rowCount(const QModelIndex &) const
{
#ifdef HAVE_LIBPCAP
return (global_capture_opts.all_ifaces ? global_capture_opts.all_ifaces->len : 0);
#else
/* Currently no interfaces available for libpcap-less builds */
return 0;
#endif
}
int InterfaceTreeModel::columnCount(const QModelIndex &) const
{
/* IFTREE_COL_MAX is not being displayed, it is the definition for the maximum numbers of columns */
return ((int) IFTREE_COL_MAX);
}
QVariant InterfaceTreeModel::data(const QModelIndex &index, int role) const
{
#ifdef HAVE_LIBPCAP
bool interfacesLoaded = true;
if (! global_capture_opts.all_ifaces || global_capture_opts.all_ifaces->len == 0)
interfacesLoaded = false;
if (!index.isValid())
return QVariant();
int row = index.row();
InterfaceTreeColumns col = (InterfaceTreeColumns) index.column();
if (interfacesLoaded)
{
interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, row);
/* Data for display in cell */
if (role == Qt::DisplayRole)
{
/* Only the name is being displayed */
if (col == IFTREE_COL_NAME)
{
return QString(device->name);
}
else if (col == IFTREE_COL_DESCRIPTION)
{
return QString(device->friendly_name);
}
else if (col == IFTREE_COL_DISPLAY_NAME)
{
return QString(device->display_name);
}
else if (col == IFTREE_COL_PIPE_PATH)
{
return QString(device->if_info.name);
}
else if (col == IFTREE_COL_CAPTURE_FILTER)
{
if (device->cfilter && strlen(device->cfilter) > 0)
return html_escape(QString(device->cfilter));
}
else if (col == IFTREE_COL_EXTCAP_PATH)
{
return QString(device->if_info.extcap);
}
else if (col == IFTREE_COL_SNAPLEN)
{
return device->has_snaplen ? QString::number(device->snaplen) : DefaultNumericValue;
}
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
else if (col == IFTREE_COL_BUFFERLEN)
{
return QString::number(device->buffer);
}
#endif
else if (col == IFTREE_COL_TYPE)
{
return QVariant::fromValue((int)device->if_info.type);
}
else if (col == IFTREE_COL_COMMENT)
{
QString comment = gchar_free_to_qstring(capture_dev_user_descr_find(device->name));
if (comment.length() > 0)
return comment;
else
return QString(device->if_info.vendor_description);
}
else if (col == IFTREE_COL_DLT)
{
// XXX - this is duplicated in
// InterfaceTreeWidgetItem::updateInterfaceColumns;
// it should be done in common code somewhere.
QString linkname;
if (device->active_dlt == -1)
linkname = "Unknown";
else {
linkname = QObject::tr("DLT %1").arg(device->active_dlt);
for (GList *list = device->links; list != Q_NULLPTR; list = gxx_list_next(list)) {
link_row *linkr = gxx_list_data(link_row *, list);
if (linkr->dlt == device->active_dlt) {
linkname = linkr->name;
break;
}
}
}
return linkname;
}
else
{
/* Return empty string for every other DisplayRole */
return QVariant();
}
}
else if (role == Qt::CheckStateRole)
{
if (col == IFTREE_COL_HIDDEN)
{
/* Hidden is a de-selection, therefore inverted logic here */
return device->hidden ? Qt::Unchecked : Qt::Checked;
}
else if (col == IFTREE_COL_PROMISCUOUSMODE)
{
return device->pmode ? Qt::Checked : Qt::Unchecked;
}
#ifdef HAVE_PCAP_CREATE
else if (col == IFTREE_COL_MONITOR_MODE)
{
return device->monitor_mode_enabled ? Qt::Checked : Qt::Unchecked;
}
#endif
}
/* Used by SparkLineDelegate for loading the data for the statistics line */
else if (role == Qt::UserRole)
{
if (col == IFTREE_COL_STATS)
{
if ((active.contains(device->name) && active[device->name]) && points.contains(device->name))
return QVariant::fromValue(points[device->name]);
}
else if (col == IFTREE_COL_ACTIVE)
{
if (active.contains(device->name))
return QVariant::fromValue(active[device->name]);
}
else if (col == IFTREE_COL_HIDDEN)
{
return QVariant::fromValue((bool)device->hidden);
}
}
/* Displays the configuration icon for extcap interfaces */
else if (role == Qt::DecorationRole)
{
if (col == IFTREE_COL_EXTCAP)
{
if (device->if_info.type == IF_EXTCAP)
return QIcon(StockIcon("x-capture-options"));
}
}
else if (role == Qt::TextAlignmentRole)
{
if (col == IFTREE_COL_EXTCAP)
{
return Qt::AlignRight;
}
}
/* Displays the tooltip for each row */
else if (role == Qt::ToolTipRole)
{
return toolTipForInterface(row);
}
}
#else
Q_UNUSED(index)
Q_UNUSED(role)
#endif
return QVariant();
}
QVariant InterfaceTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal)
{
if (role == Qt::DisplayRole)
{
if (section == IFTREE_COL_HIDDEN)
{
return tr("Show");
}
else if (section == IFTREE_COL_NAME)
{
return tr("Interface Name");
}
else if (section == IFTREE_COL_DESCRIPTION)
{
return tr("Friendly Name");
}
else if (section == IFTREE_COL_DISPLAY_NAME)
{
return tr("Friendly Name");
}
else if (section == IFTREE_COL_PIPE_PATH)
{
return tr("Local Pipe Path");
}
else if (section == IFTREE_COL_COMMENT)
{
return tr("Comment");
}
else if (section == IFTREE_COL_DLT)
{
return tr("Link-Layer Header");
}
else if (section == IFTREE_COL_PROMISCUOUSMODE)
{
return tr("Promiscuous");
}
else if (section == IFTREE_COL_SNAPLEN)
{
return tr("Snaplen (B)");
}
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
else if (section == IFTREE_COL_BUFFERLEN)
{
return tr("Buffer (MB)");
}
#endif
#ifdef HAVE_PCAP_CREATE
else if (section == IFTREE_COL_MONITOR_MODE)
{
return tr("Monitor Mode");
}
#endif
else if (section == IFTREE_COL_CAPTURE_FILTER)
{
return tr("Capture Filter");
}
}
}
return QVariant();
}
QVariant InterfaceTreeModel::getColumnContent(int idx, int col, int role)
{
return InterfaceTreeModel::data(index(idx, col), role);
}
#ifdef HAVE_PCAP_REMOTE
bool InterfaceTreeModel::isRemote(int idx)
{
interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, idx);
if (device->remote_opts.src_type == CAPTURE_IFREMOTE)
return true;
return false;
}
#endif
/**
* The interface list has changed. global_capture_opts.all_ifaces may have been reloaded
* or changed with current data. beginResetModel() and endResetModel() will signalize the
* proxy model and the view, that the data has changed and the view has to reload
*/
void InterfaceTreeModel::interfaceListChanged()
{
beginResetModel();
points.clear();
active.clear();
endResetModel();
}
/*
* Displays the tooltip code for the given device index.
*/
QVariant InterfaceTreeModel::toolTipForInterface(int idx) const
{
#ifdef HAVE_LIBPCAP
if (! global_capture_opts.all_ifaces || global_capture_opts.all_ifaces->len <= (guint) idx)
return QVariant();
interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, idx);
QString tt_str = "<p>";
if (device->no_addresses > 0)
{
tt_str += QString("%1: %2")
.arg(device->no_addresses > 1 ? tr("Addresses") : tr("Address"))
.arg(html_escape(device->addresses))
.replace('\n', ", ");
}
else if (device->if_info.type == IF_EXTCAP)
{
tt_str = QString(tr("Extcap interface: %1")).arg(get_basename(device->if_info.extcap));
}
else
{
tt_str = tr("No addresses");
}
tt_str += "<br/>";
QString cfilter = device->cfilter;
if (cfilter.isEmpty())
{
tt_str += tr("No capture filter");
}
else
{
tt_str += QString("%1: %2")
.arg(tr("Capture filter"))
.arg(html_escape(cfilter));
}
tt_str += "</p>";
return tt_str;
#else
Q_UNUSED(idx)
return QVariant();
#endif
}
#ifdef HAVE_LIBPCAP
void InterfaceTreeModel::stopStatistic()
{
if (stat_cache_)
{
capture_stat_stop(stat_cache_);
stat_cache_ = NULL;
}
}
#endif
void InterfaceTreeModel::updateStatistic(unsigned int idx)
{
#ifdef HAVE_LIBPCAP
if (! global_capture_opts.all_ifaces || global_capture_opts.all_ifaces->len <= (guint) idx)
return;
interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, idx);
if (device->if_info.type == IF_PIPE || device->if_info.type == IF_EXTCAP)
return;
if (!stat_cache_)
{
// Start gathering statistics using dumpcap
// We crash (on macOS at least) if we try to do this from ::showEvent.
stat_cache_ = capture_stat_start(&global_capture_opts);
}
struct pcap_stat stats;
unsigned diff = 0;
bool isActive = false;
if (capture_stats(stat_cache_, device->name, &stats))
{
if ( (int) stats.ps_recv > 0 )
isActive = true;
if ((int)(stats.ps_recv - device->last_packets) >= 0)
{
diff = stats.ps_recv - device->last_packets;
device->packet_diff = diff;
}
device->last_packets = stats.ps_recv;
}
points[device->name].append(diff);
if (active[device->name] != isActive)
{
beginResetModel();
active[device->name] = isActive;
endResetModel();
}
emit dataChanged(index(idx, IFTREE_COL_STATS), index(idx, IFTREE_COL_STATS));
#else
Q_UNUSED(idx)
#endif
}
QItemSelection InterfaceTreeModel::selectedDevices()
{
QItemSelection mySelection;
#ifdef HAVE_LIBPCAP
for (int idx = 0; idx < rowCount(); idx++)
{
interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, idx);
if (device->selected)
{
QModelIndex selectIndex = index(idx, 0);
mySelection.merge(
QItemSelection(selectIndex, index(selectIndex.row(), columnCount() - 1)),
QItemSelectionModel::SelectCurrent
);
}
}
#endif
return mySelection;
}
bool InterfaceTreeModel::updateSelectedDevices(QItemSelection sourceSelection)
{
bool selectionHasChanged = false;
#ifdef HAVE_LIBPCAP
QList<int> selectedIndices;
QItemSelection::const_iterator it = sourceSelection.constBegin();
while (it != sourceSelection.constEnd())
{
QModelIndexList indeces = ((QItemSelectionRange) (*it)).indexes();
QModelIndexList::const_iterator cit = indeces.constBegin();
while (cit != indeces.constEnd())
{
QModelIndex index = (QModelIndex) (*cit);
if (! selectedIndices.contains(index.row()))
{
selectedIndices.append(index.row());
}
++cit;
}
++it;
}
global_capture_opts.num_selected = 0;
for (unsigned int idx = 0; idx < global_capture_opts.all_ifaces->len; idx++)
{
interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, idx);
if (selectedIndices.contains(idx))
{
if (! device->selected)
selectionHasChanged = true;
device->selected = TRUE;
global_capture_opts.num_selected++;
} else {
if (device->selected)
selectionHasChanged = true;
device->selected = FALSE;
}
}
#else
Q_UNUSED(sourceSelection)
#endif
return selectionHasChanged;
} |
C/C++ | wireshark/ui/qt/models/interface_tree_model.h | /** @file
*
* Model for the interface data for display in the interface frame
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef INTERFACE_TREE_MODEL_H
#define INTERFACE_TREE_MODEL_H
#include <config.h>
#include <wireshark.h>
#ifdef HAVE_LIBPCAP
#include "ui/capture.h"
#include "ui/capture_globals.h"
#endif
#include <QAbstractTableModel>
#include <QList>
#include <QMap>
#include <QItemSelection>
typedef QList<int> PointList;
enum InterfaceTreeColumns
{
IFTREE_COL_EXTCAP,
IFTREE_COL_EXTCAP_PATH,
IFTREE_COL_NAME,
IFTREE_COL_DESCRIPTION,
IFTREE_COL_DISPLAY_NAME,
IFTREE_COL_COMMENT,
IFTREE_COL_HIDDEN,
IFTREE_COL_DLT,
IFTREE_COL_PROMISCUOUSMODE,
IFTREE_COL_TYPE,
IFTREE_COL_STATS,
IFTREE_COL_ACTIVE,
IFTREE_COL_SNAPLEN,
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
IFTREE_COL_BUFFERLEN,
#endif
#ifdef HAVE_PCAP_CREATE
IFTREE_COL_MONITOR_MODE,
#endif
IFTREE_COL_CAPTURE_FILTER,
IFTREE_COL_PIPE_PATH,
IFTREE_COL_MAX /* is not being displayed, it is the definition for the maximum numbers of columns */
};
class InterfaceTreeModel : public QAbstractTableModel
{
Q_OBJECT
public:
InterfaceTreeModel(QObject *parent);
~InterfaceTreeModel();
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data (const QModelIndex &index, int role = Qt::DisplayRole) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
void updateStatistic(unsigned int row);
#ifdef HAVE_LIBPCAP
void stopStatistic();
#endif
QString interfaceError();
QItemSelection selectedDevices();
bool updateSelectedDevices(QItemSelection sourceSelection);
QVariant getColumnContent(int idx, int col, int role = Qt::DisplayRole);
#ifdef HAVE_PCAP_REMOTE
bool isRemote(int idx);
#endif
static const QString DefaultNumericValue;
public slots:
void interfaceListChanged();
private:
QVariant toolTipForInterface(int idx) const;
QMap<QString, PointList> points;
QMap<QString, bool> active;
#ifdef HAVE_LIBPCAP
if_stat_cache_t *stat_cache_;
#endif // HAVE_LIBPCAP
};
#endif // INTERFACE_TREE_MODEL_H |
C++ | wireshark/ui/qt/models/manuf_table_model.cpp | /*
* manuf_table_model.h
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "manuf_table_model.h"
ManufTableItem::ManufTableItem(struct ws_manuf *ptr) :
short_name_(QString::fromUtf8(ptr->short_name)),
long_name_(QString::fromUtf8(ptr->long_name))
{
qsizetype size;
switch (ptr->mask) {
case 24:
size = 3;
break;
case 28:
size = 4;
break;
case 36:
size = 5;
break;
default:
ws_assert_not_reached();
}
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
block_bytes_ = QByteArray(reinterpret_cast<const char *>(ptr->addr), size);
#else
block_bytes_ = QByteArray(reinterpret_cast<const char *>(ptr->addr), static_cast<int>(size));
#endif
char buf[64];
block_name_ = QString::fromUtf8(ws_manuf_block_str(buf, sizeof(buf), ptr));
}
ManufTableItem::~ManufTableItem()
{
}
ManufTableModel::ManufTableModel(QObject *parent) : QAbstractTableModel(parent)
{
ws_manuf_iter_t iter;
struct ws_manuf buf[3], *ptr;
ws_manuf_iter_init(&iter);
while ((ptr = ws_manuf_iter_next(&iter, buf))) {
rows_.append(new ManufTableItem(ptr));
}
}
ManufTableModel::~ManufTableModel()
{
clear();
}
int ManufTableModel::rowCount(const QModelIndex &) const
{
return static_cast<int>(rows_.count());
}
int ManufTableModel::columnCount(const QModelIndex &) const
{
return NUM_COLS;
}
QVariant ManufTableModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= rows_.size())
return QVariant();
ManufTableItem *item = rows_.at(index.row());
if (index.column() >= NUM_COLS)
return QVariant();
if (role == Qt::DisplayRole) {
switch (index.column()) {
case COL_MAC_PREFIX:
return item->block_name_;
case COL_SHORT_NAME:
return item->short_name_;
case COL_VENDOR_NAME:
return item->long_name_;
default:
return QVariant();
}
}
if (role == Qt::UserRole) {
switch (index.column()) {
case COL_MAC_PREFIX:
return item->block_bytes_;
case COL_SHORT_NAME:
return item->short_name_;
case COL_VENDOR_NAME:
return item->long_name_;
default:
return QVariant();
}
}
return QVariant();
}
void ManufTableModel::addRecord(struct ws_manuf *ptr)
{
emit beginInsertRows(QModelIndex(), rowCount(), rowCount());
ManufTableItem *item = new ManufTableItem(ptr);
rows_.append(item);
emit endInsertRows();
}
void ManufTableModel::clear()
{
if (!rows_.isEmpty()) {
emit beginRemoveRows(QModelIndex(), 0, rowCount() - 1);
qDeleteAll(rows_.begin(), rows_.end());
rows_.clear();
emit endRemoveRows();
}
}
QVariant ManufTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal) {
switch (section) {
case COL_MAC_PREFIX:
return QString(tr("Address Block"));
case COL_SHORT_NAME:
return QString(tr("Short Name"));
case COL_VENDOR_NAME:
return QString(tr("Vendor Name"));
}
}
return QVariant();
}
ManufSortFilterProxyModel::ManufSortFilterProxyModel(QObject* parent) :
QSortFilterProxyModel(parent),
filter_type_(FilterEmpty)
{
}
void ManufSortFilterProxyModel::clearFilter()
{
if (filter_type_ == FilterEmpty)
return;
filter_type_ = FilterEmpty;
invalidateFilter();
}
void ManufSortFilterProxyModel::setFilterAddress(const QByteArray &bytes)
{
filter_type_ = FilterByAddress;
filter_bytes_ = bytes;
invalidateFilter();
}
void ManufSortFilterProxyModel::setFilterName(QRegularExpression &name)
{
filter_type_ = FilterByName;
filter_name_ = name;
invalidateFilter();
}
static bool match_filter(const QByteArray &bytes, const QByteArray &mac_block)
{
if (bytes.size() < mac_block.size())
return mac_block.startsWith(bytes);
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
QByteArray prefix = bytes.first(mac_block.size());
#else
QByteArray prefix = bytes.left(mac_block.size());
#endif
// Blocks are 3, 4 or 5 bytes wide
if (mac_block.size() > 3) {
// Mask out the last nibble of the bytes for 28 and 36 bit block lengths
// (but not 24 bit OUIs)
prefix[prefix.size() - 1] = prefix[prefix.size() - 1] & 0xF0;
}
return prefix == mac_block;
}
bool ManufSortFilterProxyModel::filterAddressAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
QModelIndex chkIdx = sourceModel()->index(source_row, ManufTableModel::COL_MAC_PREFIX, source_parent);
QByteArray mac_block = chkIdx.data(Qt::UserRole).toByteArray();
return match_filter(filter_bytes_, mac_block);
}
bool ManufSortFilterProxyModel::filterNameAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
QModelIndex chkIdx = sourceModel()->index(source_row, ManufTableModel::COL_VENDOR_NAME, source_parent);
QString vendor_name = chkIdx.data(Qt::UserRole).toString();
return filter_name_.match(vendor_name).hasMatch();
}
bool ManufSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
switch (filter_type_) {
case FilterEmpty: return true;
case FilterByAddress: return filterAddressAcceptsRow(source_row, source_parent);
case FilterByName: return filterNameAcceptsRow(source_row, source_parent);
}
ws_error("unknown filter type %d", filter_type_);
} |
C/C++ | wireshark/ui/qt/models/manuf_table_model.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef MANUF_TABLE_MODEL_H
#define MANUF_TABLE_MODEL_H
#include <QSortFilterProxyModel>
#include <QAbstractTableModel>
#include <QList>
#include <wireshark.h>
#include <epan/manuf.h>
class ManufTableItem
{
public:
ManufTableItem(struct ws_manuf *ptr);
~ManufTableItem();
QByteArray block_bytes_;
QString block_name_;
QString short_name_;
QString long_name_;
};
class ManufTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
ManufTableModel(QObject *parent);
~ManufTableModel();
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const ;
virtual int columnCount(const QModelIndex &parent = QModelIndex()) const;
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
void addRecord(struct ws_manuf *ptr);
void clear();
enum {
COL_MAC_PREFIX,
COL_SHORT_NAME,
COL_VENDOR_NAME,
NUM_COLS,
};
private:
QList<ManufTableItem *> rows_;
};
class ManufSortFilterProxyModel : public QSortFilterProxyModel
{
Q_OBJECT
public:
enum ManufProxyFilterType
{
FilterEmpty = 0,
FilterByAddress,
FilterByName,
};
Q_ENUM(ManufProxyFilterType)
ManufSortFilterProxyModel(QObject *parent);
virtual bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const;
public slots:
void setFilterAddress(const QByteArray&);
void setFilterName(QRegularExpression&);
void clearFilter();
private:
ManufProxyFilterType filter_type_;
QByteArray filter_bytes_;
QRegularExpression filter_name_;
bool filterAddressAcceptsRow(int source_row, const QModelIndex& source_parent) const;
bool filterNameAcceptsRow(int source_row, const QModelIndex& source_parent) const;
};
#endif |
C++ | wireshark/ui/qt/models/numeric_value_chooser_delegate.cpp | /* numeric_value_chooser_delegate.cpp
* Delegate to select a numeric value for a treeview entry
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <ui/qt/models/numeric_value_chooser_delegate.h>
#include <QStyledItemDelegate>
#include <QSpinBox>
NumericValueChooserDelegate::NumericValueChooserDelegate(int min, int max, QObject *parent)
: QStyledItemDelegate(parent)
{
_min = min;
_max = max;
_default = min;
}
NumericValueChooserDelegate::~NumericValueChooserDelegate()
{
}
void NumericValueChooserDelegate::setMinMaxRange(int min, int max)
{
_min = qMin(min, max);
_max = qMax(min, max);
/* ensure, that the default value is within the new min<->max */
_default = qMin(_max, qMax(_min, _default));
_defReturn = QVariant::fromValue(_default);
}
void NumericValueChooserDelegate::setDefaultValue(int defValue, QVariant defaultReturn)
{
/* ensure, that the new default value is within min<->max */
_default = qMin(_max, qMax(_min, defValue));
_defReturn = defaultReturn;
}
QWidget* NumericValueChooserDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if (!index.isValid()) {
return QStyledItemDelegate::createEditor(parent, option, index);
}
QSpinBox * editor = new QSpinBox(parent);
editor->setMinimum(_min);
editor->setMaximum(_max);
editor->setWrapping(true);
connect(editor, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this,
&NumericValueChooserDelegate::onValueChanged);
return editor;
}
void NumericValueChooserDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
if (index.isValid())
{
bool canConvert = false;
int val = index.data().toInt(&canConvert);
if (! canConvert)
val = _default;
QSpinBox * spinBox = qobject_cast<QSpinBox *>(editor);
spinBox->setValue(val);
}
else
QStyledItemDelegate::setEditorData(editor, index);
}
void NumericValueChooserDelegate::setModelData(QWidget *editor, QAbstractItemModel * model, const QModelIndex &index) const
{
if (index.isValid()) {
QSpinBox * spinBox = qobject_cast<QSpinBox *>(editor);
model->setData(index, _default == spinBox->value() ? _defReturn : QVariant::fromValue(spinBox->value()));
} else {
QStyledItemDelegate::setModelData(editor, model, index);
}
}
void NumericValueChooserDelegate::onValueChanged(int)
{
QSpinBox * spinBox = qobject_cast<QSpinBox *>(sender());
emit commitData(spinBox);
} |
C/C++ | wireshark/ui/qt/models/numeric_value_chooser_delegate.h | /** @file
*
* Delegate to select a numeric value for a treeview entry
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef NUMERIC_VALUE_CHOOSER_DELEGATE_H_
#define NUMERIC_VALUE_CHOOSER_DELEGATE_H_
#include <QStyledItemDelegate>
class NumericValueChooserDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
NumericValueChooserDelegate(int min = 0, int max = 0, QObject *parent = 0);
~NumericValueChooserDelegate();
void setMinMaxRange(int min, int max);
void setDefaultValue(int defValue, QVariant defaultReturn);
protected:
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void setEditorData(QWidget *editor, const QModelIndex &index) const;
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
private:
int _min;
int _max;
int _default;
QVariant _defReturn;
private slots:
void onValueChanged(int i);
};
#endif /* NUMERIC_VALUE_CHOOSER_DELEGATE_H_ */ |
C++ | wireshark/ui/qt/models/packet_list_model.cpp | /* packet_list_model.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <algorithm>
#include <glib.h>
#include <cmath>
#include <stdexcept>
#include "packet_list_model.h"
#include "file.h"
#include <wsutil/nstime.h>
#include <epan/column.h>
#include <epan/expert.h>
#include <epan/prefs.h>
#include "ui/packet_list_utils.h"
#include "ui/recent.h"
#include <epan/color_filters.h>
#include "frame_tvbuff.h"
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "main_application.h"
#include <ui/qt/main_window.h>
#include <ui/qt/main_status_bar.h>
#include <ui/qt/widgets/wireless_timeline.h>
#include <QColor>
#include <QElapsedTimer>
#include <QFontMetrics>
#include <QModelIndex>
#include <QElapsedTimer>
// Print timing information
//#define DEBUG_PACKET_LIST_MODEL 1
#ifdef DEBUG_PACKET_LIST_MODEL
#include <wsutil/time_util.h>
#endif
class SortAbort : public std::runtime_error
{
using std::runtime_error::runtime_error;
};
static PacketListModel * glbl_plist_model = Q_NULLPTR;
static const int reserved_packets_ = 100000;
guint
packet_list_append(column_info *, frame_data *fdata)
{
if (!glbl_plist_model)
return 0;
/* fdata should be filled with the stuff we need
* strings are built at display time.
*/
return glbl_plist_model->appendPacket(fdata);
}
void
packet_list_recreate_visible_rows(void)
{
if (glbl_plist_model)
glbl_plist_model->recreateVisibleRows();
}
PacketListModel::PacketListModel(QObject *parent, capture_file *cf) :
QAbstractItemModel(parent),
number_to_row_(QVector<int>()),
max_row_height_(0),
max_line_count_(1),
idle_dissection_row_(0)
{
Q_ASSERT(glbl_plist_model == Q_NULLPTR);
glbl_plist_model = this;
setCaptureFile(cf);
physical_rows_.reserve(reserved_packets_);
visible_rows_.reserve(reserved_packets_);
new_visible_rows_.reserve(1000);
number_to_row_.reserve(reserved_packets_);
if (qobject_cast<MainWindow *>(mainApp->mainWindow()))
{
MainWindow *mw = qobject_cast<MainWindow *>(mainApp->mainWindow());
QWidget * wtWidget = mw->findChild<WirelessTimeline *>();
if (wtWidget && qobject_cast<WirelessTimeline *>(wtWidget))
{
WirelessTimeline * wt = qobject_cast<WirelessTimeline *>(wtWidget);
connect(this, &PacketListModel::bgColorizationProgress,
wt, &WirelessTimeline::bgColorizationProgress);
}
}
connect(this, &PacketListModel::maxLineCountChanged,
this, &PacketListModel::emitItemHeightChanged,
Qt::QueuedConnection);
idle_dissection_timer_ = new QElapsedTimer();
}
PacketListModel::~PacketListModel()
{
delete idle_dissection_timer_;
}
void PacketListModel::setCaptureFile(capture_file *cf)
{
cap_file_ = cf;
}
// Packet list records have no children (for now, at least).
QModelIndex PacketListModel::index(int row, int column, const QModelIndex &) const
{
if (row >= visible_rows_.count() || row < 0 || !cap_file_ || column >= prefs.num_cols)
return QModelIndex();
PacketListRecord *record = visible_rows_[row];
return createIndex(row, column, record);
}
// Everything is under the root.
QModelIndex PacketListModel::parent(const QModelIndex &) const
{
return QModelIndex();
}
int PacketListModel::packetNumberToRow(int packet_num) const
{
// map 1-based values to 0-based row numbers. Invisible rows are stored as
// the default value (0) and should map to -1.
return number_to_row_.value(packet_num) - 1;
}
guint PacketListModel::recreateVisibleRows()
{
beginResetModel();
visible_rows_.resize(0);
number_to_row_.fill(0);
endResetModel();
foreach (PacketListRecord *record, physical_rows_) {
frame_data *fdata = record->frameData();
if (fdata->passed_dfilter || fdata->ref_time) {
visible_rows_ << record;
if (static_cast<guint32>(number_to_row_.size()) <= fdata->num) {
number_to_row_.resize(fdata->num + 10000);
}
number_to_row_[fdata->num] = static_cast<int>(visible_rows_.count());
}
}
if (!visible_rows_.isEmpty()) {
beginInsertRows(QModelIndex(), 0, static_cast<int>(visible_rows_.count()) - 1);
endInsertRows();
}
idle_dissection_row_ = 0;
return static_cast<guint>(visible_rows_.count());
}
void PacketListModel::clear() {
beginResetModel();
qDeleteAll(physical_rows_);
PacketListRecord::invalidateAllRecords();
physical_rows_.resize(0);
visible_rows_.resize(0);
new_visible_rows_.resize(0);
number_to_row_.resize(0);
endResetModel();
max_row_height_ = 0;
max_line_count_ = 1;
idle_dissection_row_ = 0;
}
void PacketListModel::invalidateAllColumnStrings()
{
PacketListRecord::invalidateAllRecords();
emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1),
QVector<int>() << Qt::DisplayRole);
}
void PacketListModel::resetColumns()
{
if (cap_file_) {
PacketListRecord::resetColumns(&cap_file_->cinfo);
}
emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1));
emit headerDataChanged(Qt::Horizontal, 0, columnCount() - 1);
}
void PacketListModel::resetColorized()
{
PacketListRecord::resetColorization();
emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1),
QVector<int>() << Qt::BackgroundRole << Qt::ForegroundRole);
}
void PacketListModel::toggleFrameMark(const QModelIndexList &indeces)
{
if (!cap_file_ || indeces.count() <= 0)
return;
int sectionMax = columnCount() - 1;
foreach (QModelIndex index, indeces) {
if (! index.isValid())
continue;
PacketListRecord *record = static_cast<PacketListRecord*>(index.internalPointer());
if (!record)
continue;
frame_data *fdata = record->frameData();
if (!fdata)
continue;
if (fdata->marked)
cf_unmark_frame(cap_file_, fdata);
else
cf_mark_frame(cap_file_, fdata);
emit dataChanged(index.sibling(index.row(), 0), index.sibling(index.row(), sectionMax),
QVector<int>() << Qt::BackgroundRole << Qt::ForegroundRole);
}
}
void PacketListModel::setDisplayedFrameMark(gboolean set)
{
foreach (PacketListRecord *record, visible_rows_) {
if (set) {
cf_mark_frame(cap_file_, record->frameData());
} else {
cf_unmark_frame(cap_file_, record->frameData());
}
}
emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1),
QVector<int>() << Qt::BackgroundRole << Qt::ForegroundRole);
}
void PacketListModel::toggleFrameIgnore(const QModelIndexList &indeces)
{
if (!cap_file_ || indeces.count() <= 0)
return;
int sectionMax = columnCount() - 1;
foreach (QModelIndex index, indeces) {
if (! index.isValid())
continue;
PacketListRecord *record = static_cast<PacketListRecord*>(index.internalPointer());
if (!record)
continue;
frame_data *fdata = record->frameData();
if (!fdata)
continue;
if (fdata->ignored)
cf_unignore_frame(cap_file_, fdata);
else
cf_ignore_frame(cap_file_, fdata);
emit dataChanged(index.sibling(index.row(), 0), index.sibling(index.row(), sectionMax),
QVector<int>() << Qt::BackgroundRole << Qt::ForegroundRole << Qt::DisplayRole);
}
}
void PacketListModel::setDisplayedFrameIgnore(gboolean set)
{
foreach (PacketListRecord *record, visible_rows_) {
if (set) {
cf_ignore_frame(cap_file_, record->frameData());
} else {
cf_unignore_frame(cap_file_, record->frameData());
}
}
emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1),
QVector<int>() << Qt::BackgroundRole << Qt::ForegroundRole << Qt::DisplayRole);
}
void PacketListModel::toggleFrameRefTime(const QModelIndex &rt_index)
{
if (!cap_file_ || !rt_index.isValid()) return;
PacketListRecord *record = static_cast<PacketListRecord*>(rt_index.internalPointer());
if (!record) return;
frame_data *fdata = record->frameData();
if (!fdata) return;
if (fdata->ref_time) {
fdata->ref_time=0;
cap_file_->ref_time_count--;
} else {
fdata->ref_time=1;
cap_file_->ref_time_count++;
}
cf_reftime_packets(cap_file_);
if (!fdata->ref_time && !fdata->passed_dfilter) {
cap_file_->displayed_count--;
}
record->resetColumns(&cap_file_->cinfo);
emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1));
}
void PacketListModel::unsetAllFrameRefTime()
{
if (!cap_file_) return;
/* XXX: we might need a progressbar here */
foreach (PacketListRecord *record, physical_rows_) {
frame_data *fdata = record->frameData();
if (fdata->ref_time) {
fdata->ref_time = 0;
}
}
cap_file_->ref_time_count = 0;
cf_reftime_packets(cap_file_);
PacketListRecord::resetColumns(&cap_file_->cinfo);
emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1));
}
void PacketListModel::addFrameComment(const QModelIndexList &indices, const QByteArray &comment)
{
int sectionMax = columnCount() - 1;
frame_data *fdata;
if (!cap_file_) return;
for (const auto &index : qAsConst(indices)) {
if (!index.isValid()) continue;
PacketListRecord *record = static_cast<PacketListRecord*>(index.internalPointer());
if (!record) continue;
fdata = record->frameData();
wtap_block_t pkt_block = cf_get_packet_block(cap_file_, fdata);
wtap_block_add_string_option(pkt_block, OPT_COMMENT, comment.data(), comment.size());
if (!cf_set_modified_block(cap_file_, fdata, pkt_block)) {
cap_file_->packet_comment_count++;
expert_update_comment_count(cap_file_->packet_comment_count);
}
// In case there are coloring rules or columns related to comments.
// (#12519)
//
// XXX: "Does any active coloring rule relate to frame data"
// could be an optimization. For columns, note that
// "col_based_on_frame_data" only applies to built in columns,
// not custom columns based on frame data. (Should we prevent
// custom columns based on frame data from being created,
// substituting them with the other columns?)
//
// Note that there are not currently any fields that depend on
// whether other frames have comments, unlike with time references
// and time shifts ("frame.time_relative", "frame.offset_shift", etc.)
// If there were, then we'd need to reset data for all frames instead
// of just the frames changed.
record->invalidateColorized();
record->invalidateRecord();
emit dataChanged(index.sibling(index.row(), 0), index.sibling(index.row(), sectionMax),
QVector<int>() << Qt::BackgroundRole << Qt::ForegroundRole << Qt::DisplayRole);
}
}
void PacketListModel::setFrameComment(const QModelIndex &index, const QByteArray &comment, guint c_number)
{
int sectionMax = columnCount() - 1;
frame_data *fdata;
if (!cap_file_) return;
if (!index.isValid()) return;
PacketListRecord *record = static_cast<PacketListRecord*>(index.internalPointer());
if (!record) return;
fdata = record->frameData();
wtap_block_t pkt_block = cf_get_packet_block(cap_file_, fdata);
if (comment.isEmpty()) {
wtap_block_remove_nth_option_instance(pkt_block, OPT_COMMENT, c_number);
if (!cf_set_modified_block(cap_file_, fdata, pkt_block)) {
cap_file_->packet_comment_count--;
expert_update_comment_count(cap_file_->packet_comment_count);
}
} else {
wtap_block_set_nth_string_option_value(pkt_block, OPT_COMMENT, c_number, comment.data(), comment.size());
cf_set_modified_block(cap_file_, fdata, pkt_block);
}
record->invalidateColorized();
record->invalidateRecord();
emit dataChanged(index.sibling(index.row(), 0), index.sibling(index.row(), sectionMax),
QVector<int>() << Qt::BackgroundRole << Qt::ForegroundRole << Qt::DisplayRole);
}
void PacketListModel::deleteFrameComments(const QModelIndexList &indices)
{
int sectionMax = columnCount() - 1;
frame_data *fdata;
if (!cap_file_) return;
for (const auto &index : qAsConst(indices)) {
if (!index.isValid()) continue;
PacketListRecord *record = static_cast<PacketListRecord*>(index.internalPointer());
if (!record) continue;
fdata = record->frameData();
wtap_block_t pkt_block = cf_get_packet_block(cap_file_, fdata);
guint n_comments = wtap_block_count_option(pkt_block, OPT_COMMENT);
if (n_comments) {
for (guint i = 0; i < n_comments; i++) {
wtap_block_remove_nth_option_instance(pkt_block, OPT_COMMENT, 0);
}
if (!cf_set_modified_block(cap_file_, fdata, pkt_block)) {
cap_file_->packet_comment_count -= n_comments;
expert_update_comment_count(cap_file_->packet_comment_count);
}
record->invalidateColorized();
record->invalidateRecord();
emit dataChanged(index.sibling(index.row(), 0), index.sibling(index.row(), sectionMax),
QVector<int>() << Qt::BackgroundRole << Qt::ForegroundRole << Qt::DisplayRole);
}
}
}
void PacketListModel::deleteAllFrameComments()
{
int row;
int sectionMax = columnCount() - 1;
if (!cap_file_) return;
/* XXX: we might need a progressbar here */
foreach (PacketListRecord *record, physical_rows_) {
frame_data *fdata = record->frameData();
wtap_block_t pkt_block = cf_get_packet_block(cap_file_, fdata);
guint n_comments = wtap_block_count_option(pkt_block, OPT_COMMENT);
if (n_comments) {
for (guint i = 0; i < n_comments; i++) {
wtap_block_remove_nth_option_instance(pkt_block, OPT_COMMENT, 0);
}
cf_set_modified_block(cap_file_, fdata, pkt_block);
record->invalidateColorized();
record->invalidateRecord();
row = packetNumberToRow(fdata->num);
if (row > -1) {
emit dataChanged(index(row, 0), index(row, sectionMax),
QVector<int>() << Qt::BackgroundRole << Qt::ForegroundRole << Qt::DisplayRole);
}
}
}
cap_file_->packet_comment_count = 0;
expert_update_comment_count(cap_file_->packet_comment_count);
}
void PacketListModel::setMaximumRowHeight(int height)
{
max_row_height_ = height;
// As the QTreeView uniformRowHeights documentation says,
// "The height is obtained from the first item in the view. It is
// updated when the data changes on that item."
emit dataChanged(index(0, 0), index(0, columnCount() - 1));
}
int PacketListModel::sort_column_;
int PacketListModel::sort_column_is_numeric_;
int PacketListModel::text_sort_column_;
Qt::SortOrder PacketListModel::sort_order_;
capture_file *PacketListModel::sort_cap_file_;
gboolean PacketListModel::stop_flag_;
ProgressFrame *PacketListModel::progress_frame_;
double PacketListModel::comps_;
double PacketListModel::exp_comps_;
QElapsedTimer busy_timer_;
const int busy_timeout_ = 65; // ms, approximately 15 fps
void PacketListModel::sort(int column, Qt::SortOrder order)
{
if (!cap_file_ || visible_rows_.count() < 1) return;
if (column < 0) return;
if (physical_rows_.count() < 1)
return;
sort_column_ = column;
text_sort_column_ = PacketListRecord::textColumn(column);
sort_order_ = order;
sort_cap_file_ = cap_file_;
QString col_title = get_column_title(column);
if (text_sort_column_ >= 0 && (guint)visible_rows_.count() > prefs.gui_packet_list_cached_rows_max) {
/* Column not based on frame data but by column text that requires
* dissection, so to sort in a reasonable amount of time the column
* text needs to be cached.
*/
/* If the sort is being triggered because the columns were already
* sorted and the filter is being cleared (or changed to something
* else with more rows than fit in the cache), then the temporary
* message will be immediately overwritten with the standard capture
* statistics by the packets_bar_update() call after thawing the rows.
* It will still blink yellow, and the user will get the message if
* they then click on the header file (wondering why it didn't sort.)
*/
if (col_title.isEmpty()) {
col_title = tr("Column");
}
QString temp_msg = tr("%1 can only be sorted with %2 or fewer visible rows; increase cache size in Layout preferences").arg(col_title).arg(prefs.gui_packet_list_cached_rows_max);
mainApp->pushStatus(MainApplication::TemporaryStatus, temp_msg);
return;
}
/* If we are currently in the middle of reading the capture file, don't
* sort. PacketList::captureFileReadFinished invalidates all the cached
* column strings and then tries to sort again.
* Similarly, claim the read lock because we don't want the file to
* change out from under us while sorting, which can segfault. (Previously
* we ignored user input, but now in order to cancel sorting we don't.)
*/
if (sort_cap_file_->read_lock) {
ws_info("Refusing to sort because capture file is being read");
/* We shouldn't have to tell the user because we're just deferring
* the sort until PacketList::captureFileReadFinished
*/
return;
}
sort_cap_file_->read_lock = TRUE;
QString busy_msg;
if (!col_title.isEmpty()) {
busy_msg = tr("Sorting \"%1\"…").arg(col_title);
} else {
busy_msg = tr("Sorting …");
}
stop_flag_ = FALSE;
comps_ = 0;
/* XXX: The expected number of comparisons is O(N log N), but this could
* be a pretty significant overestimate of the amount of time it takes,
* if there are lots of identical entries. (Especially with string
* comparisons, some comparisons are faster than others.) Better to
* overestimate?
*/
exp_comps_ = log2(visible_rows_.count()) * visible_rows_.count();
progress_frame_ = nullptr;
if (qobject_cast<MainWindow *>(mainApp->mainWindow())) {
MainWindow *mw = qobject_cast<MainWindow *>(mainApp->mainWindow());
progress_frame_ = mw->findChild<ProgressFrame *>();
if (progress_frame_) {
progress_frame_->showProgress(busy_msg, true, false, &stop_flag_, 0);
connect(progress_frame_, &ProgressFrame::stopLoading,
this, &PacketListModel::stopSorting);
}
}
busy_timer_.start();
sort_column_is_numeric_ = isNumericColumn(sort_column_);
QVector<PacketListRecord *> sorted_visible_rows_ = visible_rows_;
try {
std::sort(sorted_visible_rows_.begin(), sorted_visible_rows_.end(), recordLessThan);
beginResetModel();
visible_rows_.resize(0);
number_to_row_.fill(0);
foreach (PacketListRecord *record, sorted_visible_rows_) {
frame_data *fdata = record->frameData();
if (fdata->passed_dfilter || fdata->ref_time) {
visible_rows_ << record;
if (number_to_row_.size() <= (int)fdata->num) {
number_to_row_.resize(fdata->num + 10000);
}
number_to_row_[fdata->num] = static_cast<int>(visible_rows_.count());
}
}
endResetModel();
} catch (const SortAbort& e) {
mainApp->pushStatus(MainApplication::TemporaryStatus, e.what());
}
if (progress_frame_ != nullptr) {
progress_frame_->hide();
disconnect(progress_frame_, &ProgressFrame::stopLoading,
this, &PacketListModel::stopSorting);
}
sort_cap_file_->read_lock = FALSE;
if (cap_file_->current_frame) {
emit goToPacket(cap_file_->current_frame->num);
}
}
void PacketListModel::stopSorting()
{
stop_flag_ = TRUE;
}
bool PacketListModel::isNumericColumn(int column)
{
if (column < 0) {
return false;
}
switch (sort_cap_file_->cinfo.columns[column].col_fmt) {
case COL_CUMULATIVE_BYTES: /**< 3) Cumulative number of bytes */
case COL_DELTA_TIME: /**< 5) Delta time */
case COL_DELTA_TIME_DIS: /**< 8) Delta time displayed*/
case COL_UNRES_DST_PORT: /**< 10) Unresolved dest port */
case COL_FREQ_CHAN: /**< 15) IEEE 802.11 (and WiMax?) - Channel */
case COL_RSSI: /**< 22) IEEE 802.11 - received signal strength */
case COL_TX_RATE: /**< 23) IEEE 802.11 - TX rate in Mbps */
case COL_NUMBER: /**< 32) Packet list item number */
case COL_PACKET_LENGTH: /**< 33) Packet length in bytes */
case COL_UNRES_SRC_PORT: /**< 41) Unresolved source port */
return true;
/*
* Try to sort port numbers as number, if the numeric comparison fails (due
* to name resolution), it will fallback to string comparison.
* */
case COL_RES_DST_PORT: /**< 10) Resolved dest port */
case COL_DEF_DST_PORT: /**< 12) Destination port */
case COL_DEF_SRC_PORT: /**< 37) Source port */
case COL_RES_SRC_PORT: /**< 40) Resolved source port */
return true;
case COL_CUSTOM:
/* handle custom columns below. */
break;
default:
return false;
}
guint num_fields = g_slist_length(sort_cap_file_->cinfo.columns[column].col_custom_fields_ids);
for (guint i = 0; i < num_fields; i++) {
guint *field_idx = (guint *) g_slist_nth_data(sort_cap_file_->cinfo.columns[column].col_custom_fields_ids, i);
header_field_info *hfi = proto_registrar_get_nth(*field_idx);
/*
* Reject a field when there is no numeric field type or when:
* - there are (value_string) "strings"
* (but do accept fields which have a unit suffix).
* - BASE_HEX or BASE_HEX_DEC (these have a constant width, string
* comparison is faster than conversion to double).
* - BASE_CUSTOM (these can be formatted in any way).
*/
if (!hfi ||
(hfi->strings != NULL && !(hfi->display & BASE_UNIT_STRING)) ||
!(((FT_IS_INT(hfi->type) || FT_IS_UINT(hfi->type)) &&
((FIELD_DISPLAY(hfi->display) == BASE_DEC) ||
(FIELD_DISPLAY(hfi->display) == BASE_OCT) ||
(FIELD_DISPLAY(hfi->display) == BASE_DEC_HEX))) ||
(hfi->type == FT_DOUBLE) || (hfi->type == FT_FLOAT) ||
(hfi->type == FT_BOOLEAN) || (hfi->type == FT_FRAMENUM) ||
(hfi->type == FT_RELATIVE_TIME))) {
return false;
}
}
return true;
}
bool PacketListModel::recordLessThan(PacketListRecord *r1, PacketListRecord *r2)
{
int cmp_val = 0;
comps_++;
// Wherein we try to cram the logic of packet_list_compare_records,
// _packet_list_compare_records, and packet_list_compare_custom from
// gtk/packet_list_store.c into one function
if (busy_timer_.elapsed() > busy_timeout_) {
if (progress_frame_) {
progress_frame_->setValue(static_cast<int>(comps_/exp_comps_ * 100));
}
// What's the least amount of processing that we can do which will draw
// the busy indicator?
mainApp->processEvents(QEventLoop::ExcludeSocketNotifiers, 1);
if (stop_flag_) {
throw SortAbort("Sorting aborted");
}
busy_timer_.restart();
}
if (sort_column_ < 0) {
// No column.
cmp_val = frame_data_compare(sort_cap_file_->epan, r1->frameData(), r2->frameData(), COL_NUMBER);
} else if (text_sort_column_ < 0) {
// Column comes directly from frame data
cmp_val = frame_data_compare(sort_cap_file_->epan, r1->frameData(), r2->frameData(), sort_cap_file_->cinfo.columns[sort_column_].col_fmt);
} else {
QString r1String = r1->columnString(sort_cap_file_, sort_column_);
QString r2String = r2->columnString(sort_cap_file_, sort_column_);
// XXX: The naive string comparison compares Unicode code points.
// Proper collation is more expensive
cmp_val = r1String.compare(r2String);
if (cmp_val != 0 && sort_column_is_numeric_) {
// Custom column with numeric data (or something like a port number).
// Attempt to convert to numbers.
// XXX This is slow. Can we avoid doing this? Perhaps the actual
// values used for sorting should be cached too as QVariant[List].
// If so, we could consider using QCollatorSortKeys or similar
// for strings as well.
bool ok_r1, ok_r2;
double num_r1 = parseNumericColumn(r1String, &ok_r1);
double num_r2 = parseNumericColumn(r2String, &ok_r2);
if (!ok_r1 && !ok_r2) {
cmp_val = 0;
} else if (!ok_r1 || (ok_r2 && num_r1 < num_r2)) {
// either r1 is invalid (and sort it before others) or both
// r1 and r2 are valid (sort normally)
cmp_val = -1;
} else if (!ok_r2 || (num_r1 > num_r2)) {
cmp_val = 1;
}
}
if (cmp_val == 0) {
// All else being equal, compare column numbers.
cmp_val = frame_data_compare(sort_cap_file_->epan, r1->frameData(), r2->frameData(), COL_NUMBER);
}
}
if (sort_order_ == Qt::AscendingOrder) {
return cmp_val < 0;
} else {
return cmp_val > 0;
}
}
// Parses a field as a double. Handle values with suffixes ("12ms"), negative
// values ("-1.23") and fields with multiple occurrences ("1,2"). Marks values
// that do not contain any numeric value ("Unknown") as invalid.
double PacketListModel::parseNumericColumn(const QString &val, bool *ok)
{
QByteArray ba = val.toUtf8();
const char *strval = ba.constData();
gchar *end = NULL;
double num = g_ascii_strtod(strval, &end);
*ok = strval != end;
return num;
}
// ::data is const so we have to make changes here.
void PacketListModel::emitItemHeightChanged(const QModelIndex &ih_index)
{
if (!ih_index.isValid()) return;
PacketListRecord *record = static_cast<PacketListRecord*>(ih_index.internalPointer());
if (!record) return;
if (record->lineCount() > max_line_count_) {
max_line_count_ = record->lineCount();
emit itemHeightChanged(ih_index);
}
}
int PacketListModel::rowCount(const QModelIndex &) const
{
return static_cast<int>(visible_rows_.count());
}
int PacketListModel::columnCount(const QModelIndex &) const
{
return prefs.num_cols;
}
QVariant PacketListModel::data(const QModelIndex &d_index, int role) const
{
if (!d_index.isValid())
return QVariant();
PacketListRecord *record = static_cast<PacketListRecord*>(d_index.internalPointer());
if (!record)
return QVariant();
const frame_data *fdata = record->frameData();
if (!fdata)
return QVariant();
switch (role) {
case Qt::TextAlignmentRole:
switch(recent_get_column_xalign(d_index.column())) {
case COLUMN_XALIGN_RIGHT:
return Qt::AlignRight;
break;
case COLUMN_XALIGN_CENTER:
return Qt::AlignCenter;
break;
case COLUMN_XALIGN_LEFT:
return Qt::AlignLeft;
break;
case COLUMN_XALIGN_DEFAULT:
default:
if (right_justify_column(d_index.column(), cap_file_)) {
return Qt::AlignRight;
}
break;
}
return Qt::AlignLeft;
case Qt::BackgroundRole:
const color_t *color;
if (fdata->ignored) {
color = &prefs.gui_ignored_bg;
} else if (fdata->marked) {
color = &prefs.gui_marked_bg;
} else if (fdata->color_filter && recent.packet_list_colorize) {
const color_filter_t *color_filter = (const color_filter_t *) fdata->color_filter;
color = &color_filter->bg_color;
} else {
return QVariant();
}
return ColorUtils::fromColorT(color);
case Qt::ForegroundRole:
if (fdata->ignored) {
color = &prefs.gui_ignored_fg;
} else if (fdata->marked) {
color = &prefs.gui_marked_fg;
} else if (fdata->color_filter && recent.packet_list_colorize) {
const color_filter_t *color_filter = (const color_filter_t *) fdata->color_filter;
color = &color_filter->fg_color;
} else {
return QVariant();
}
return ColorUtils::fromColorT(color);
case Qt::DisplayRole:
{
int column = d_index.column();
QString column_string = record->columnString(cap_file_, column, true);
// We don't know an item's sizeHint until we fetch its text here.
// Assume each line count is 1. If the line count changes, emit
// itemHeightChanged which triggers another redraw (including a
// fetch of SizeHintRole and DisplayRole) in the next event loop.
if (column == 0 && record->lineCountChanged() && record->lineCount() > max_line_count_) {
emit maxLineCountChanged(d_index);
}
return column_string;
}
case Qt::SizeHintRole:
{
// If this is the first row and column, return the maximum row height...
if (d_index.row() < 1 && d_index.column() < 1 && max_row_height_ > 0) {
QSize size = QSize(-1, max_row_height_);
return size;
}
// ...otherwise punt so that the item delegate can correctly calculate the item width.
return QVariant();
}
default:
return QVariant();
}
}
QVariant PacketListModel::headerData(int section, Qt::Orientation orientation,
int role) const
{
if (!cap_file_) return QVariant();
if (orientation == Qt::Horizontal && section < prefs.num_cols) {
switch (role) {
case Qt::DisplayRole:
return QVariant::fromValue(QString(get_column_title(section)));
case Qt::ToolTipRole:
return QVariant::fromValue(gchar_free_to_qstring(get_column_tooltip(section)));
case PacketListModel::HEADER_CAN_RESOLVE:
return (bool)resolve_column(section, cap_file_);
default:
break;
}
}
return QVariant();
}
void PacketListModel::flushVisibleRows()
{
int pos = static_cast<int>(visible_rows_.count());
if (new_visible_rows_.count() > 0) {
beginInsertRows(QModelIndex(), pos, pos + static_cast<int>(new_visible_rows_.count()));
foreach (PacketListRecord *record, new_visible_rows_) {
frame_data *fdata = record->frameData();
visible_rows_ << record;
if (static_cast<unsigned int>(number_to_row_.size()) <= fdata->num) {
number_to_row_.resize(fdata->num + 10000);
}
number_to_row_[fdata->num] = static_cast<int>(visible_rows_.count());
}
endInsertRows();
new_visible_rows_.resize(0);
}
}
// Fill our column string and colorization cache while the application is
// idle. Try to be as conservative with the CPU and disk as possible.
static const int idle_dissection_interval_ = 5; // ms
void PacketListModel::dissectIdle(bool reset)
{
if (reset) {
// qDebug() << "=di reset" << idle_dissection_row_;
idle_dissection_row_ = 0;
} else if (!idle_dissection_timer_->isValid()) {
return;
}
idle_dissection_timer_->restart();
int first = idle_dissection_row_;
while (idle_dissection_timer_->elapsed() < idle_dissection_interval_
&& idle_dissection_row_ < physical_rows_.count()) {
ensureRowColorized(idle_dissection_row_);
idle_dissection_row_++;
// if (idle_dissection_row_ % 1000 == 0) qDebug() << "=di row" << idle_dissection_row_;
}
if (idle_dissection_row_ < physical_rows_.count()) {
QTimer::singleShot(0, this, [=]() { dissectIdle(); });
} else {
idle_dissection_timer_->invalidate();
}
// report colorization progress
emit bgColorizationProgress(first+1, idle_dissection_row_+1);
}
// XXX Pass in cinfo from packet_list_append so that we can fill in
// line counts?
gint PacketListModel::appendPacket(frame_data *fdata)
{
PacketListRecord *record = new PacketListRecord(fdata);
qsizetype pos = -1;
#ifdef DEBUG_PACKET_LIST_MODEL
if (fdata->num % 10000 == 1) {
log_resource_usage(fdata->num == 1, "%u packets", fdata->num);
}
#endif
physical_rows_ << record;
if (fdata->passed_dfilter || fdata->ref_time) {
new_visible_rows_ << record;
if (new_visible_rows_.count() < 2) {
// This is the first queued packet. Schedule an insertion for
// the next UI update.
QTimer::singleShot(0, this, &PacketListModel::flushVisibleRows);
}
pos = static_cast<int>( visible_rows_.count() + new_visible_rows_.count() ) - 1;
}
return static_cast<gint>(pos);
}
frame_data *PacketListModel::getRowFdata(QModelIndex idx)
{
if (!idx.isValid())
return Q_NULLPTR;
return getRowFdata(idx.row());
}
frame_data *PacketListModel::getRowFdata(int row) {
if (row < 0 || row >= visible_rows_.count())
return NULL;
PacketListRecord *record = visible_rows_[row];
if (!record)
return NULL;
return record->frameData();
}
void PacketListModel::ensureRowColorized(int row)
{
if (row < 0 || row >= visible_rows_.count())
return;
PacketListRecord *record = visible_rows_[row];
if (!record)
return;
if (!record->colorized()) {
record->ensureColorized(cap_file_);
}
}
int PacketListModel::visibleIndexOf(frame_data *fdata) const
{
int row = 0;
foreach (PacketListRecord *record, visible_rows_) {
if (record->frameData() == fdata) {
return row;
}
row++;
}
return -1;
} |
C/C++ | wireshark/ui/qt/models/packet_list_model.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PACKET_LIST_MODEL_H
#define PACKET_LIST_MODEL_H
#include <config.h>
#include <stdio.h>
#include <glib.h>
#include <epan/packet.h>
#include <QAbstractItemModel>
#include <QFont>
#include <QVector>
#include <ui/qt/progress_frame.h>
#include "packet_list_record.h"
#include "cfile.h"
class QElapsedTimer;
class PacketListModel : public QAbstractItemModel
{
Q_OBJECT
public:
enum {
HEADER_CAN_RESOLVE = Qt::UserRole,
};
explicit PacketListModel(QObject *parent = 0, capture_file *cf = NULL);
~PacketListModel();
void setCaptureFile(capture_file *cf);
QModelIndex index(int row, int column,
const QModelIndex & = QModelIndex()) const;
QModelIndex parent(const QModelIndex &) const;
int packetNumberToRow(int packet_num) const;
guint recreateVisibleRows();
void clear();
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex & = QModelIndex()) const;
QVariant data(const QModelIndex &d_index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
gint appendPacket(frame_data *fdata);
frame_data *getRowFdata(QModelIndex idx);
frame_data *getRowFdata(int row);
void ensureRowColorized(int row);
int visibleIndexOf(frame_data *fdata) const;
/**
* @brief Invalidate any cached column strings.
*/
void invalidateAllColumnStrings();
/**
* @brief Rebuild columns from settings.
*/
void resetColumns();
void resetColorized();
void toggleFrameMark(const QModelIndexList &indeces);
void setDisplayedFrameMark(gboolean set);
void toggleFrameIgnore(const QModelIndexList &indeces);
void setDisplayedFrameIgnore(gboolean set);
void toggleFrameRefTime(const QModelIndex &rt_index);
void unsetAllFrameRefTime();
void addFrameComment(const QModelIndexList &indices, const QByteArray &comment);
void setFrameComment(const QModelIndex &index, const QByteArray &comment, guint c_number);
void deleteFrameComments(const QModelIndexList &indices);
void deleteAllFrameComments();
void setMaximumRowHeight(int height);
signals:
void goToPacket(int);
void maxLineCountChanged(const QModelIndex &ih_index) const;
void itemHeightChanged(const QModelIndex &ih_index);
void bgColorizationProgress(int first, int last);
public slots:
void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
void stopSorting();
void flushVisibleRows();
void dissectIdle(bool reset = false);
private:
capture_file *cap_file_;
QList<QString> col_names_;
QVector<PacketListRecord *> physical_rows_;
QVector<PacketListRecord *> visible_rows_;
QVector<PacketListRecord *> new_visible_rows_;
QVector<int> number_to_row_;
int max_row_height_; // px
int max_line_count_;
static int sort_column_;
static int sort_column_is_numeric_;
static int text_sort_column_;
static Qt::SortOrder sort_order_;
static capture_file *sort_cap_file_;
static bool recordLessThan(PacketListRecord *r1, PacketListRecord *r2);
static double parseNumericColumn(const QString &val, bool *ok);
static gboolean stop_flag_;
static ProgressFrame *progress_frame_;
static double exp_comps_;
static double comps_;
QElapsedTimer *idle_dissection_timer_;
int idle_dissection_row_;
bool isNumericColumn(int column);
private slots:
void emitItemHeightChanged(const QModelIndex &ih_index);
};
#endif // PACKET_LIST_MODEL_H |
C++ | wireshark/ui/qt/models/packet_list_record.cpp | /* packet_list_record.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "packet_list_record.h"
#include <file.h>
#include <epan/epan_dissect.h>
#include <epan/column.h>
#include <epan/conversation.h>
#include <epan/wmem_scopes.h>
#include <epan/color_filters.h>
#include "frame_tvbuff.h"
#include <ui/qt/utils/qt_ui_utils.h>
#include <QStringList>
QCache<guint32, QStringList> PacketListRecord::col_text_cache_(500);
QMap<int, int> PacketListRecord::cinfo_column_;
unsigned PacketListRecord::rows_color_ver_ = 1;
PacketListRecord::PacketListRecord(frame_data *frameData) :
fdata_(frameData),
lines_(1),
line_count_changed_(false),
color_ver_(0),
colorized_(false),
conv_index_(0),
read_failed_(false)
{
}
PacketListRecord::~PacketListRecord()
{
}
void PacketListRecord::ensureColorized(capture_file *cap_file)
{
// packet_list_store.c:packet_list_get_value
Q_ASSERT(fdata_);
if (!cap_file) {
return;
}
bool dissect_color = !colorized_ || ( color_ver_ != rows_color_ver_ );
if (dissect_color) {
/* Dissect columns only if it won't evict anything from cache */
bool dissect_columns = col_text_cache_.totalCost() < col_text_cache_.maxCost();
dissect(cap_file, dissect_columns, dissect_color);
}
}
// We might want to return a const char * instead. This would keep us from
// creating excessive QByteArrays, e.g. in PacketListModel::recordLessThan.
const QString PacketListRecord::columnString(capture_file *cap_file, int column, bool colorized)
{
// packet_list_store.c:packet_list_get_value
Q_ASSERT(fdata_);
if (!cap_file || column < 0 || column >= cap_file->cinfo.num_cols) {
return QString();
}
//
// XXX - do we still need to check the colorization, given that we now
// have the ensureColorized() method to ensure that the record is
// properly colorized?
//
bool dissect_color = ( colorized && !colorized_ ) || ( color_ver_ != rows_color_ver_ );
QStringList *col_text = nullptr;
if (!dissect_color) {
col_text = col_text_cache_.object(fdata_->num);
}
if (col_text == nullptr || column >= col_text->count() || col_text->at(column).isNull()) {
dissect(cap_file, true, dissect_color);
col_text = col_text_cache_.object(fdata_->num);
}
return col_text ? col_text->at(column) : QString();
}
void PacketListRecord::resetColumns(column_info *cinfo)
{
invalidateAllRecords();
if (!cinfo) {
return;
}
cinfo_column_.clear();
int i, j;
for (i = 0, j = 0; i < cinfo->num_cols; i++) {
if (!col_based_on_frame_data(cinfo, i)) {
cinfo_column_[i] = j;
j++;
}
}
}
void PacketListRecord::dissect(capture_file *cap_file, bool dissect_columns, bool dissect_color)
{
// packet_list_store.c:packet_list_dissect_and_cache_record
epan_dissect_t edt;
column_info *cinfo = NULL;
gboolean create_proto_tree;
wtap_rec rec; /* Record metadata */
Buffer buf; /* Record data */
if (!cap_file) {
return;
}
if (dissect_columns) {
cinfo = &cap_file->cinfo;
}
wtap_rec_init(&rec);
ws_buffer_init(&buf, 1514);
if (read_failed_) {
read_failed_ = !cf_read_record_no_alert(cap_file, fdata_, &rec, &buf);
} else {
read_failed_ = !cf_read_record(cap_file, fdata_, &rec, &buf);
}
if (read_failed_) {
/*
* Error reading the record.
*
* Don't set the color filter for now (we might want
* to colorize it in some fashion to warn that the
* row couldn't be filled in or colorized), and
* set the columns to placeholder values, except
* for the Info column, where we'll put in an
* error message.
*/
if (dissect_columns) {
col_fill_in_error(cinfo, fdata_, FALSE, FALSE /* fill_fd_columns */);
cacheColumnStrings(cinfo);
}
if (dissect_color) {
fdata_->color_filter = NULL;
colorized_ = true;
}
ws_buffer_free(&buf);
wtap_rec_cleanup(&rec);
return; /* error reading the record */
}
/*
* Determine whether we need to create a protocol tree.
* We do if:
*
* we're going to apply a color filter to this packet;
*
* we're need to fill in the columns and we have custom columns
* (which require field values, which currently requires that
* we build a protocol tree).
*
* XXX - field extractors? (Not done for GTK+....)
*/
create_proto_tree = ((dissect_color && color_filters_used()) ||
(dissect_columns && (have_custom_cols(cinfo) ||
have_field_extractors())));
epan_dissect_init(&edt, cap_file->epan,
create_proto_tree,
FALSE /* proto_tree_visible */);
/* Re-color when the coloring rules are changed via the UI. */
if (dissect_color) {
color_filters_prime_edt(&edt);
fdata_->need_colorize = 1;
}
if (dissect_columns)
col_custom_prime_edt(&edt, cinfo);
/*
* XXX - need to catch an OutOfMemoryError exception and
* attempt to recover from it.
*/
epan_dissect_run(&edt, cap_file->cd_t, &rec,
frame_tvbuff_new_buffer(&cap_file->provider, fdata_, &buf),
fdata_, cinfo);
if (dissect_columns) {
/* "Stringify" non frame_data vals */
epan_dissect_fill_in_columns(&edt, FALSE, FALSE /* fill_fd_columns */);
cacheColumnStrings(cinfo);
}
if (dissect_color) {
colorized_ = true;
color_ver_ = rows_color_ver_;
}
struct conversation * conv = find_conversation_pinfo(&edt.pi, 0);
conv_index_ = ! conv ? 0 : conv->conv_index;
epan_dissect_cleanup(&edt);
ws_buffer_free(&buf);
wtap_rec_cleanup(&rec);
}
void PacketListRecord::cacheColumnStrings(column_info *cinfo)
{
// packet_list_store.c:packet_list_change_record(PacketList *packet_list, PacketListRecord *record, gint col, column_info *cinfo)
if (!cinfo) {
return;
}
QStringList *col_text = new QStringList();
lines_ = 1;
line_count_changed_ = false;
for (int column = 0; column < cinfo->num_cols; ++column) {
int col_lines = 1;
QString col_str;
int text_col = cinfo_column_.value(column, -1);
if (text_col < 0) {
col_fill_in_frame_data(fdata_, cinfo, column, FALSE);
}
col_str = QString(get_column_text(cinfo, column));
*col_text << col_str;
col_lines = static_cast<int>(col_str.count('\n'));
if (col_lines > lines_) {
lines_ = col_lines;
line_count_changed_ = true;
}
}
col_text_cache_.insert(fdata_->num, col_text);
} |
C/C++ | wireshark/ui/qt/models/packet_list_record.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PACKET_LIST_RECORD_H
#define PACKET_LIST_RECORD_H
#include <config.h>
#include <glib.h>
#include "cfile.h"
#include <epan/column.h>
#include <epan/packet.h>
#include <QByteArray>
#include <QCache>
#include <QList>
#include <QVariant>
struct conversation;
struct _GStringChunk;
class PacketListRecord
{
public:
PacketListRecord(frame_data *frameData);
virtual ~PacketListRecord();
// Ensure that the record is colorized.
void ensureColorized(capture_file *cap_file);
// Return the string value for a column. Data is cached if possible.
const QString columnString(capture_file *cap_file, int column, bool colorized = false);
frame_data *frameData() const { return fdata_; }
// packet_list->col_to_text in gtk/packet_list_store.c
static int textColumn(int column) { return cinfo_column_.value(column, -1); }
bool colorized() { return colorized_ && (color_ver_ == rows_color_ver_); }
unsigned int conversation() { return conv_index_; }
int columnTextSize(const char *str);
void invalidateColorized() { colorized_ = false; }
void invalidateRecord() { col_text_cache_.remove(fdata_->num); }
static void invalidateAllRecords() { col_text_cache_.clear(); }
/* In Qt 6, QCache maxCost is a qsizetype, but the QAbstractItemModel
* number of rows is still an int, so we're limited to INT_MAX anyway.
*/
static void setMaxCache(int cost) { col_text_cache_.setMaxCost(cost); }
static void resetColumns(column_info *cinfo);
static void resetColorization() { rows_color_ver_++; }
inline int lineCount() { return lines_; }
inline int lineCountChanged() { return line_count_changed_; }
private:
/** The column text for some columns */
static QCache<guint32, QStringList> col_text_cache_;
frame_data *fdata_;
int lines_;
bool line_count_changed_;
static QMap<int, int> cinfo_column_;
/** Has this record been colorized? */
static unsigned int rows_color_ver_;
unsigned int color_ver_;
bool colorized_;
/** Conversation. Used by RelatedPacketDelegate */
unsigned int conv_index_;
bool read_failed_;
void dissect(capture_file *cap_file, bool dissect_columns, bool dissect_color = false);
void cacheColumnStrings(column_info *cinfo);
};
#endif // PACKET_LIST_RECORD_H |
C++ | wireshark/ui/qt/models/path_selection_delegate.cpp | /* path_chooser_delegate.cpp
* Delegate to select a file path for a treeview entry
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/path_selection_delegate.h>
#include <ui/qt/widgets/path_selection_edit.h>
PathSelectionDelegate::PathSelectionDelegate(QObject *parent)
: QStyledItemDelegate(parent)
{
}
QWidget* PathSelectionDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &) const
{
PathSelectionEdit * editor = new PathSelectionEdit(tr("Open a pipe"), QString(), true, parent);
connect(editor, &PathSelectionEdit::pathChanged, this, &PathSelectionDelegate::pathHasChanged);
return editor;
}
void PathSelectionDelegate::pathHasChanged(QString)
{
PathSelectionEdit * editor = qobject_cast<PathSelectionEdit *>(sender());
if (editor)
emit commitData(editor);
}
void PathSelectionDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &) const
{
editor->setGeometry(option.rect);
}
void PathSelectionDelegate::setEditorData(QWidget *editor, const QModelIndex &idx) const
{
if (idx.isValid() && qobject_cast<PathSelectionEdit *>(editor) != nullptr)
{
PathSelectionEdit * edit = qobject_cast<PathSelectionEdit *>(editor);
edit->setPath(idx.data().toString());
}
else
QStyledItemDelegate::setEditorData(editor, idx);
}
void PathSelectionDelegate::setModelData(QWidget *editor, QAbstractItemModel * model, const QModelIndex &idx) const
{
if (idx.isValid() && qobject_cast<PathSelectionEdit *>(editor) != nullptr)
{
PathSelectionEdit * edit = qobject_cast<PathSelectionEdit *>(editor);
model->setData(idx, edit->path());
}
else
{
QStyledItemDelegate::setModelData(editor, model, idx);
}
} |
C/C++ | wireshark/ui/qt/models/path_selection_delegate.h | /** @file
*
* Delegate to select a file path for a treeview entry
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PATH_SELECTION_DELEGATE_H_
#define PATH_SELECTION_DELEGATE_H_
#include <QStyledItemDelegate>
class PathSelectionDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
PathSelectionDelegate(QObject *parent = 0);
protected:
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &idx) const override;
void updateEditorGeometry (QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & idx) const override;
void setEditorData(QWidget *editor, const QModelIndex &idx) const override;
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &idx) const override;
protected slots:
void pathHasChanged(QString newPath);
};
#endif /* PATH_SELECTION_DELEGATE_H_ */ |
C++ | wireshark/ui/qt/models/percent_bar_delegate.cpp | /* percent_bar_delegate.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/percent_bar_delegate.h>
#include <ui/qt/utils/color_utils.h>
#include <QApplication>
#include <QPainter>
static const int bar_em_width_ = 8;
static const double bar_blend_ = 0.15;
void PercentBarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QStyleOptionViewItem option_vi = option;
QStyledItemDelegate::initStyleOption(&option_vi, index);
// Paint our rect with no text using the current style, then draw our
// bar and text over it.
QStyledItemDelegate::paint(painter, option, index);
bool ok = false;
double value = index.data(Qt::UserRole).toDouble(&ok);
if (!ok || !index.data(Qt::DisplayRole).toString().isEmpty()) {
// We don't have a valid value or the item has visible text.
return;
}
// If our value is out range our caller has a bug. Clamp the graph and
// Print the numeric value so that the bug is obvious.
QString pct_str = QString::number(value, 'f', 1);
if (value < 0) {
value = 0;
}
if (value > 100.0) {
value = 100.0;
}
if (QApplication::style()->objectName().contains("vista")) {
// QWindowsVistaStyle::drawControl does this internally. Unfortunately there
// doesn't appear to be a more general way to do this.
option_vi.palette.setColor(QPalette::All, QPalette::HighlightedText,
option_vi.palette.color(QPalette::Active, QPalette::Text));
}
QPalette::ColorGroup cg = option_vi.state & QStyle::State_Enabled
? QPalette::Normal : QPalette::Disabled;
QColor text_color = option_vi.palette.color(cg, QPalette::Text);
QColor bar_color = ColorUtils::alphaBlend(option_vi.palette.windowText(),
option_vi.palette.window(), bar_blend_);
if (cg == QPalette::Normal && !(option_vi.state & QStyle::State_Active))
cg = QPalette::Inactive;
if (option_vi.state & QStyle::State_Selected) {
text_color = option_vi.palette.color(cg, QPalette::HighlightedText);
bar_color = ColorUtils::alphaBlend(option_vi.palette.color(cg, QPalette::Window),
option_vi.palette.color(cg, QPalette::Highlight),
bar_blend_);
}
painter->save();
int border_radius = 3; // We use 3 px elsewhere, e.g. filter combos.
QRect pct_rect = option.rect;
pct_rect.adjust(1, 1, -1, -1);
pct_rect.setWidth(((pct_rect.width() * value) / 100.0) + 0.5);
painter->setPen(Qt::NoPen);
painter->setBrush(bar_color);
painter->drawRoundedRect(pct_rect, border_radius, border_radius);
painter->restore();
painter->save();
painter->setPen(text_color);
painter->drawText(option.rect, Qt::AlignCenter, pct_str);
painter->restore();
}
QSize PercentBarDelegate::sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
return QSize(option.fontMetrics.height() * bar_em_width_,
QStyledItemDelegate::sizeHint(option, index).height());
} |
C/C++ | wireshark/ui/qt/models/percent_bar_delegate.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PERCENTBARDELEGATE_H
#define PERCENTBARDELEGATE_H
/*
* @file Percent bar delegate.
*
* QStyledItemDelegate subclass that will draw a percentage value and a
* single-item bar chart for the specified value.
*
* This is intended to be used in QTreeWidgets to show percentage values.
* To use it, first call setItemDelegate:
*
* myTreeWidget()->setItemDelegateForColumn(col_pct_, new PercentBarDelegate());
*
* Then, for each QTreeWidgetItem, set a double value using setData:
*
* setData(col_pct_, Qt::UserRole, QVariant::fromValue<double>(packets_ * 100.0 / num_packets));
*
* If the item data cannot be converted to a valid double value or if its
* text string is non-empty then it will be rendered normally (i.e. the
* percent text and bar will not be drawn). This lets you mix normal and
* percent bar rendering between rows.
*/
#include <QStyledItemDelegate>
class PercentBarDelegate : public QStyledItemDelegate
{
public:
PercentBarDelegate(QWidget *parent = 0) : QStyledItemDelegate(parent) { }
// Make sure QStyledItemDelegate::paint doesn't draw any text.
virtual QString displayText(const QVariant &, const QLocale &) const { return QString(); }
protected:
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const;
QSize sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const;
};
#endif // PERCENTBARDELEGATE_H |
C++ | wireshark/ui/qt/models/pref_delegate.cpp | /* pref_delegate.cpp
* Delegates for editing prefereneces.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/pref_delegate.h>
#include <epan/prefs-int.h>
#include <ui/qt/manager/preference_manager.h>
#include <ui/qt/manager/wireshark_preference.h>
AdvancedPrefDelegate::AdvancedPrefDelegate(QObject *parent) : QStyledItemDelegate(parent)
{
}
PrefsItem* AdvancedPrefDelegate::indexToPref(const QModelIndex &index) const
{
const QVariant v = index.model()->data(index, Qt::UserRole);
return VariantPointer<PrefsItem>::asPtr(v);
}
QWidget *AdvancedPrefDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
PrefsItem* pref;
QString filename;
switch(index.column())
{
case AdvancedPrefsModel::colName:
case AdvancedPrefsModel::colStatus:
case AdvancedPrefsModel::colType:
//If user clicks on any of these columns, reset preference back to default
//There is no need to launch an editor
const_cast<QAbstractItemModel*>(index.model())->setData(index, QVariant(), Qt::EditRole);
break;
case AdvancedPrefsModel::colValue:
pref = indexToPref(index);
WiresharkPreference * wspref = PreferenceManager::instance()->getPreference(pref);
if (wspref) {
QWidget *editor = wspref->editor(parent, option, index);
if (editor) {
editor->setAutoFillBackground(true);
}
return editor;
}
break;
}
return Q_NULLPTR;
}
void AdvancedPrefDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
PrefsItem* pref = indexToPref(index);
WiresharkPreference * wspref = PreferenceManager::instance()->getPreference(pref);
if (wspref)
{
wspref->setData(editor, index);
return;
}
Q_ASSERT(FALSE);
}
void AdvancedPrefDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
PrefsItem* pref = indexToPref(index);
WiresharkPreference * wspref = PreferenceManager::instance()->getPreference(pref);
if (wspref)
{
wspref->setModelData(editor, model, index);
return;
}
Q_ASSERT(FALSE);
} |
C/C++ | wireshark/ui/qt/models/pref_delegate.h | /** @file
*
* Delegates for editing prefereneces.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PREF_DELEGATE_H
#define PREF_DELEGATE_H
#include <config.h>
#include <ui/qt/models/pref_models.h>
#include <QStyledItemDelegate>
#include <QModelIndex>
class AdvancedPrefDelegate : public QStyledItemDelegate
{
public:
AdvancedPrefDelegate(QObject *parent = 0);
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const;
void setEditorData(QWidget *editor, const QModelIndex &index) const;
void setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const;
private:
PrefsItem* indexToPref(const QModelIndex &index) const;
};
#endif // PREF_DELEGATE_H |
C++ | wireshark/ui/qt/models/pref_models.cpp | /* pref_models.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/pref_models.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <epan/prefs-int.h>
#ifdef HAVE_LIBPCAP
#ifdef _WIN32
#include "capture/capture-wpcap.h"
#endif /* _WIN32 */
#endif /* HAVE_LIBPCAP */
#include <QFont>
#include <QColor>
#include <QRegularExpression>
#include <QApplication>
// XXX Should we move this to ui/preference_utils?
static GHashTable * pref_ptr_to_pref_ = NULL;
pref_t *prefFromPrefPtr(void *pref_ptr)
{
return (pref_t *)g_hash_table_lookup(pref_ptr_to_pref_, (gpointer) pref_ptr);
}
static void prefInsertPrefPtr(void * pref_ptr, pref_t * pref)
{
if (! pref_ptr_to_pref_)
pref_ptr_to_pref_ = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);
gpointer key = (gpointer) pref_ptr;
gpointer val = (gpointer) pref;
/* Already existing entries will be ignored */
if ((void *)g_hash_table_lookup(pref_ptr_to_pref_, key) == NULL)
g_hash_table_insert(pref_ptr_to_pref_, key, val);
}
PrefsItem::PrefsItem(module_t *module, pref_t *pref, PrefsItem* parent)
: ModelHelperTreeItem<PrefsItem>(parent),
pref_(pref),
module_(module),
name_(module->name ? module->name : module->parent->name),
changed_(false)
{
if (pref_ != NULL) {
name_ += QString(".%1").arg(prefs_get_name(pref_));
}
}
PrefsItem::PrefsItem(const QString name, PrefsItem* parent)
: ModelHelperTreeItem<PrefsItem>(parent),
pref_(NULL),
module_(NULL),
name_(name),
changed_(false)
{
}
PrefsItem::~PrefsItem()
{
}
int PrefsItem::getPrefType() const
{
if (pref_ == NULL)
return 0;
return prefs_get_type(pref_);
}
bool PrefsItem::isPrefDefault() const
{
if (pref_ == NULL)
return true;
if (changed_ == false)
return prefs_pref_is_default(pref_) ? true : false;
return false;
}
QString PrefsItem::getPrefTypeName() const
{
if (pref_ == NULL)
return "";
return QString(prefs_pref_type_name(pref_));
}
QString PrefsItem::getModuleName() const
{
if (module_ == NULL)
return name_;
return QString(module_->name);
}
QString PrefsItem::getModuleTitle() const
{
if ((module_ == NULL) && (pref_ == NULL))
return name_;
Q_ASSERT(module_);
return QString(module_->title);
}
void PrefsItem::setChanged(bool changed)
{
changed_ = changed;
}
PrefsModel::PrefsModel(QObject *parent) :
QAbstractItemModel(parent),
root_(new PrefsItem(QString("ROOT"), NULL))
{
populate();
}
PrefsModel::~PrefsModel()
{
delete root_;
}
int PrefsModel::rowCount(const QModelIndex &parent) const
{
PrefsItem *parent_item;
if (parent.column() > 0)
return 0;
if (!parent.isValid())
parent_item = root_;
else
parent_item = static_cast<PrefsItem*>(parent.internalPointer());
if (parent_item == NULL)
return 0;
return static_cast<int>(parent_item->childCount());
}
int PrefsModel::columnCount(const QModelIndex&) const
{
return colLast;
}
QModelIndex PrefsModel::parent(const QModelIndex& index) const
{
if (!index.isValid())
return QModelIndex();
PrefsItem* item = static_cast<PrefsItem*>(index.internalPointer());
if (item != NULL) {
PrefsItem* parent_item = item->parentItem();
if (parent_item != NULL) {
if (parent_item == root_)
return QModelIndex();
return createIndex(parent_item->row(), 0, parent_item);
}
}
return QModelIndex();
}
QModelIndex PrefsModel::index(int row, int column, const QModelIndex& parent) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
PrefsItem *parent_item, *child_item;
if (!parent.isValid())
parent_item = root_;
else
parent_item = static_cast<PrefsItem*>(parent.internalPointer());
Q_ASSERT(parent_item);
child_item = parent_item->child(row);
if (child_item) {
return createIndex(row, column, child_item);
}
return QModelIndex();
}
QVariant PrefsModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || (role != Qt::DisplayRole && role != Qt::UserRole))
return QVariant();
PrefsItem* item = static_cast<PrefsItem*>(index.internalPointer());
if (item == NULL)
return QVariant();
if (role == Qt::UserRole)
return VariantPointer<PrefsItem>::asQVariant(item);
switch ((enum PrefsModelColumn)index.column()) {
case colName:
return item->getName();
case colStatus:
if (item->getPrefType() == PREF_UAT || item->getPrefType() == PREF_CUSTOM)
return QObject::tr("Unknown");
if (item->isPrefDefault())
return QObject::tr("Default");
return QObject::tr("Changed");
case colType:
return item->getPrefTypeName();
case colValue:
if (item->getPref() == NULL)
return QVariant();
return QString(gchar_free_to_qstring(prefs_pref_to_str(item->getPref(), pref_stashed)).remove(QRegularExpression("\n\t")));
default:
break;
}
return QVariant();
}
static guint
fill_prefs(module_t *module, gpointer root_ptr)
{
PrefsItem* root_item = static_cast<PrefsItem*>(root_ptr);
if ((module == NULL) || (root_item == NULL))
return 1;
if (module->numprefs < 1 && !prefs_module_has_submodules(module))
return 0;
PrefsItem* module_item = new PrefsItem(module, NULL, root_item);
root_item->prependChild(module_item);
for (GList *pref_l = module->prefs; pref_l && pref_l->data; pref_l = gxx_list_next(pref_l)) {
pref_t *pref = gxx_list_data(pref_t *, pref_l);
if (prefs_get_type(pref) == PREF_OBSOLETE || prefs_get_type(pref) == PREF_STATIC_TEXT)
continue;
const char *type_name = prefs_pref_type_name(pref);
if (!type_name)
continue;
pref_stash(pref, NULL);
PrefsItem* item = new PrefsItem(module, pref, module_item);
module_item->prependChild(item);
// .uat is a void * so it wins the "useful key value" prize.
if (prefs_get_uat_value(pref)) {
prefInsertPrefPtr(prefs_get_uat_value(pref), pref);
}
}
if (prefs_module_has_submodules(module))
return prefs_modules_foreach_submodules(module, fill_prefs, module_item);
return 0;
}
void PrefsModel::populate()
{
prefs_modules_foreach_submodules(NULL, fill_prefs, (gpointer)root_);
//Add the "specially handled" preferences
PrefsItem *appearance_item, *appearance_subitem, *special_item;
appearance_item = new PrefsItem(typeToString(PrefsModel::Appearance), root_);
root_->prependChild(appearance_item);
appearance_subitem = new PrefsItem(typeToString(PrefsModel::Layout), appearance_item);
appearance_item->prependChild(appearance_subitem);
appearance_subitem = new PrefsItem(typeToString(PrefsModel::Columns), appearance_item);
appearance_item->prependChild(appearance_subitem);
appearance_subitem = new PrefsItem(typeToString(PrefsModel::FontAndColors), appearance_item);
appearance_item->prependChild(appearance_subitem);
special_item = new PrefsItem(typeToString(PrefsModel::Capture), root_);
root_->prependChild(special_item);
special_item = new PrefsItem(typeToString(PrefsModel::Expert), root_);
root_->prependChild(special_item);
special_item = new PrefsItem(typeToString(PrefsModel::FilterButtons), root_);
root_->prependChild(special_item);
#ifdef HAVE_LIBGNUTLS
special_item = new PrefsItem(typeToString(PrefsModel::RSAKeys), root_);
root_->prependChild(special_item);
#endif
special_item = new PrefsItem(typeToString(PrefsModel::Advanced), root_);
root_->prependChild(special_item);
}
QString PrefsModel::typeToString(int type)
{
QString typeStr;
switch(type)
{
case Advanced: typeStr = tr("Advanced"); break;
case Appearance: typeStr = tr("Appearance"); break;
case Layout: typeStr = tr("Layout"); break;
case Columns: typeStr = tr("Columns"); break;
case FontAndColors: typeStr = tr("Font and Colors"); break;
case Capture: typeStr = tr("Capture"); break;
case Expert: typeStr = tr("Expert"); break;
case FilterButtons: typeStr = tr("Filter Buttons"); break;
case RSAKeys: typeStr = tr("RSA Keys"); break;
}
return typeStr;
}
AdvancedPrefsModel::AdvancedPrefsModel(QObject * parent)
: QSortFilterProxyModel(parent),
filter_(),
passwordChar_(QApplication::style()->styleHint(QStyle::SH_LineEdit_PasswordCharacter))
{
}
QVariant AdvancedPrefsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
switch (section) {
case colName:
return tr("Name");
case colStatus:
return tr("Status");
case colType:
return tr("Type");
case colValue:
return tr("Value");
default:
break;
}
}
return QVariant();
}
QVariant AdvancedPrefsModel::data(const QModelIndex &dataindex, int role) const
{
if (!dataindex.isValid())
return QVariant();
QModelIndex modelIndex = mapToSource(dataindex);
PrefsItem* item = static_cast<PrefsItem*>(modelIndex.internalPointer());
if (item == NULL)
return QVariant();
switch (role)
{
case Qt::DisplayRole:
switch ((AdvancedPrefsModelColumn)dataindex.column())
{
case colName:
if (item->getPref() == NULL)
return item->getModule()->title;
return sourceModel()->data(sourceModel()->index(modelIndex.row(), PrefsModel::colName, modelIndex.parent()), role);
case colStatus:
if (item->getPref() == NULL)
return QVariant();
return sourceModel()->data(sourceModel()->index(modelIndex.row(), PrefsModel::colStatus, modelIndex.parent()), role);
case colType:
if (item->getPref() == NULL)
return QVariant();
return sourceModel()->data(sourceModel()->index(modelIndex.row(), PrefsModel::colType, modelIndex.parent()), role);
case colValue:
if (item->getPref() == NULL)
return QVariant();
if (PREF_PASSWORD == item->getPrefType())
{
return QString(sourceModel()->data(sourceModel()->index(modelIndex.row(), PrefsModel::colValue, modelIndex.parent()), role).toString().size(), passwordChar_);
} else {
return sourceModel()->data(sourceModel()->index(modelIndex.row(), PrefsModel::colValue, modelIndex.parent()), role);
}
default:
break;
}
break;
case Qt::ToolTipRole:
switch ((AdvancedPrefsModelColumn)dataindex.column())
{
case colName:
if (item->getPref() == NULL)
return QString("<span>%1</span>").arg(item->getModule()->description);
return QString("<span>%1</span>").arg(prefs_get_description(item->getPref()));
case colStatus:
if (item->getPref() == NULL)
return QVariant();
return QObject::tr("Has this preference been changed?");
case colType:
if (item->getPref() == NULL) {
return QVariant();
} else {
QString type_desc = gchar_free_to_qstring(prefs_pref_type_description(item->getPref()));
return QString("<span>%1</span>").arg(type_desc);
}
break;
case colValue:
if (item->getPref() == NULL) {
return QVariant();
} else {
QString default_value = gchar_free_to_qstring(prefs_pref_to_str(item->getPref(), pref_stashed));
return QString("<span>%1</span>").arg(
default_value.isEmpty() ? default_value : QObject::tr("Default value is empty"));
}
default:
break;
}
break;
case Qt::FontRole:
if (item->getPref() == NULL)
return QVariant();
if (!item->isPrefDefault() &&
/* UATs and custom preferences are "unknown", that shouldn't mean that they are always bolded */
item->getPrefType() != PREF_UAT && item->getPrefType() != PREF_CUSTOM) {
QFont font;
font.setBold(true);
return font;
}
break;
case Qt::UserRole:
return sourceModel()->data(modelIndex, role);
default:
break;
}
return QVariant();
}
bool AdvancedPrefsModel::setData(const QModelIndex &dataindex, const QVariant &value, int role)
{
if ((!dataindex.isValid()) || (role != Qt::EditRole))
return false;
QModelIndex modelIndex = mapToSource(dataindex);
PrefsItem* item = static_cast<PrefsItem*>(modelIndex.internalPointer());
if (item == NULL)
return false;
if (value.isNull()) {
//reset preference to default
reset_stashed_pref(item->getPref());
item->setChanged(false);
} else {
item->setChanged(true);
switch (item->getPrefType())
{
case PREF_DECODE_AS_UINT:
case PREF_UINT:
{
bool ok;
guint new_val = value.toString().toUInt(&ok, prefs_get_uint_base(item->getPref()));
if (ok)
prefs_set_uint_value(item->getPref(), new_val, pref_stashed);
}
break;
case PREF_BOOL:
prefs_invert_bool_value(item->getPref(), pref_stashed);
break;
case PREF_ENUM:
prefs_set_enum_value(item->getPref(), value.toInt(), pref_stashed);
break;
case PREF_STRING:
prefs_set_string_value(item->getPref(), value.toString().toStdString().c_str(), pref_stashed);
break;
case PREF_PASSWORD:
prefs_set_password_value(item->getPref(), value.toString().toStdString().c_str(), pref_stashed);
break;
case PREF_DECODE_AS_RANGE:
case PREF_RANGE:
prefs_set_stashed_range_value(item->getPref(), value.toString().toUtf8().constData());
break;
case PREF_SAVE_FILENAME:
case PREF_OPEN_FILENAME:
case PREF_DIRNAME:
prefs_set_string_value(item->getPref(), value.toString().toStdString().c_str(), pref_stashed);
break;
case PREF_COLOR:
{
QColor qc(value.toString());
color_t color;
color.red = qc.red() << 8 | qc.red();
color.green = qc.green() << 8 | qc.green();
color.blue = qc.blue() << 8 | qc.blue();
prefs_set_color_value(item->getPref(), color, pref_stashed);
break;
}
case PREF_CUSTOM:
prefs_set_custom_value(item->getPref(), value.toString().toStdString().c_str(), pref_stashed);
break;
}
}
QVector<int> roles;
roles << role;
// The status field may change as well as the value, so mark them for update
emit dataChanged(index(dataindex.row(), AdvancedPrefsModel::colStatus),
index(dataindex.row(), AdvancedPrefsModel::colValue), roles);
return true;
}
Qt::ItemFlags AdvancedPrefsModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::ItemFlags();
QModelIndex modelIndex = mapToSource(index);
PrefsItem* item = static_cast<PrefsItem*>(modelIndex.internalPointer());
if (item == NULL)
return Qt::ItemFlags();
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
if (item->getPref() == NULL) {
/* Base modules aren't changable */
flags &= ~(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
} else {
flags |= Qt::ItemIsEditable;
}
return flags;
}
int AdvancedPrefsModel::columnCount(const QModelIndex&) const
{
return colLast;
}
void AdvancedPrefsModel::setFirstColumnSpanned(QTreeView* tree, const QModelIndex& mIndex)
{
int childCount, row;
PrefsItem* item;
if (mIndex.isValid()) {
item = VariantPointer<PrefsItem>::asPtr(data(mIndex, Qt::UserRole));
if (item != NULL) {
childCount = item->childCount();
if (childCount > 0) {
tree->setFirstColumnSpanned(mIndex.row(), mIndex.parent(), true);
for (row = 0; row < childCount; row++) {
setFirstColumnSpanned(tree, index(row, 0, mIndex));
}
}
}
} else {
for (row = 0; row < rowCount(); row++) {
setFirstColumnSpanned(tree, index(row, 0));
}
}
}
bool AdvancedPrefsModel::filterAcceptItem(PrefsItem& item) const
{
if (filter_.isEmpty())
return true;
QString name, tooltip;
if (item.getPref() == NULL) {
name = item.getModule()->title;
tooltip = item.getModule()->description;
} else {
name = QString(item.getModule()->name ? item.getModule()->name : item.getModule()->parent->name);
name += QString(".%1").arg(prefs_get_name(item.getPref()));
tooltip = prefs_get_description(item.getPref());
}
if (name.contains(filter_, Qt::CaseInsensitive) || tooltip.contains(filter_, Qt::CaseInsensitive))
return true;
PrefsItem *child_item;
for (int child_row = 0; child_row < item.childCount(); child_row++)
{
child_item = item.child(child_row);
if ((child_item != NULL) && (filterAcceptItem(*child_item)))
return true;
}
return false;
}
bool AdvancedPrefsModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
QModelIndex nameIdx = sourceModel()->index(sourceRow, PrefsModel::colName, sourceParent);
PrefsItem* item = static_cast<PrefsItem*>(nameIdx.internalPointer());
if (item == NULL)
return true;
//filter out the "special" preferences
if ((item->getModule() == NULL) && (item->getPref() == NULL))
return false;
if (filterAcceptItem(*item))
return true;
return false;
}
void AdvancedPrefsModel::setFilter(const QString& filter)
{
filter_ = filter;
invalidateFilter();
}
ModulePrefsModel::ModulePrefsModel(QObject* parent)
: QSortFilterProxyModel(parent)
, advancedPrefName_(PrefsModel::typeToString(PrefsModel::Advanced))
{
}
QVariant ModulePrefsModel::data(const QModelIndex &dataindex, int role) const
{
if (!dataindex.isValid())
return QVariant();
QModelIndex modelIndex = mapToSource(dataindex);
PrefsItem* item = static_cast<PrefsItem*>(modelIndex.internalPointer());
if (item == NULL)
return QVariant();
switch (role)
{
case Qt::DisplayRole:
switch ((ModulePrefsModelColumn)dataindex.column())
{
case colName:
return item->getModuleTitle();
default:
break;
}
break;
case Qt::UserRole:
return sourceModel()->data(modelIndex, role);
case ModuleName:
return item->getModuleName();
default:
break;
}
return QVariant();
}
Qt::ItemFlags ModulePrefsModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::ItemFlags();
bool disable_capture = true;
#ifdef HAVE_LIBPCAP
#ifdef _WIN32
/* Is WPcap loaded? */
if (has_wpcap) {
#endif /* _WIN32 */
disable_capture = false;
#ifdef _WIN32
}
#endif /* _WIN32 */
#endif /* HAVE_LIBPCAP */
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
if (disable_capture) {
QModelIndex modelIndex = mapToSource(index);
PrefsItem* item = static_cast<PrefsItem*>(modelIndex.internalPointer());
if (item == NULL)
return flags;
if (item->getName().compare(PrefsModel::typeToString(PrefsModel::Capture)) == 0) {
flags &= (~Qt::ItemIsEnabled);
}
}
return flags;
}
int ModulePrefsModel::columnCount(const QModelIndex&) const
{
return colLast;
}
bool ModulePrefsModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
{
PrefsItem* left_item = static_cast<PrefsItem*>(source_left.internalPointer());
PrefsItem* right_item = static_cast<PrefsItem*>(source_right.internalPointer());
if ((left_item != NULL) && (right_item != NULL)) {
QString left_name = left_item->getModuleTitle(),
right_name = right_item->getModuleTitle();
//Force "Advanced" preferences to be at bottom of model
if (source_left.isValid() && !source_left.parent().isValid() &&
source_right.isValid() && !source_right.parent().isValid()) {
if (left_name.compare(advancedPrefName_) == 0) {
return false;
}
if (right_name.compare(advancedPrefName_) == 0) {
return true;
}
}
if (left_name.compare(right_name, Qt::CaseInsensitive) < 0)
return true;
}
return false;
}
bool ModulePrefsModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
QModelIndex nameIdx = sourceModel()->index(sourceRow, PrefsModel::colName, sourceParent);
PrefsItem* item = static_cast<PrefsItem*>(nameIdx.internalPointer());
if (item == NULL)
return true;
if (item->getPref() != NULL)
return false;
if (item->getModule() != NULL) {
if (!item->getModule()->use_gui) {
return false;
}
}
return true;
} |
C/C++ | wireshark/ui/qt/models/pref_models.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PREF_MODELS_H
#define PREF_MODELS_H
#include <config.h>
#include <ui/qt/models/tree_model_helpers.h>
#include <epan/prefs.h>
#include <QSortFilterProxyModel>
#include <QTreeView>
class PrefsItem : public ModelHelperTreeItem<PrefsItem>
{
public:
PrefsItem(module_t *module, pref_t *pref, PrefsItem* parent);
PrefsItem(const QString name, PrefsItem* parent);
virtual ~PrefsItem();
QString getName() const {return name_;}
pref_t* getPref() const {return pref_;}
int getPrefType() const;
bool isPrefDefault() const;
QString getPrefTypeName() const;
module_t* getModule() const {return module_;}
QString getModuleName() const;
QString getModuleTitle() const;
void setChanged(bool changed = true);
private:
pref_t *pref_;
module_t *module_;
QString name_;
//set to true if changed during module manipulation
//Used to determine proper "default" for comparison
bool changed_;
};
class PrefsModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit PrefsModel(QObject * parent = Q_NULLPTR);
virtual ~PrefsModel();
enum PrefsModelType {
Advanced = Qt::UserRole,
Appearance,
Layout,
Columns,
FontAndColors,
Capture,
Expert,
FilterButtons,
RSAKeys
};
enum PrefsModelColumn {
colName = 0,
colStatus,
colType,
colValue,
colLast
};
QModelIndex index(int row, int column,
const QModelIndex & = QModelIndex()) const;
QModelIndex parent(const QModelIndex &) const;
QVariant data(const QModelIndex &index, int role) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
static QString typeToString(int type);
private:
void populate();
PrefsItem* root_;
};
class AdvancedPrefsModel : public QSortFilterProxyModel
{
Q_OBJECT
public:
explicit AdvancedPrefsModel(QObject * parent = Q_NULLPTR);
enum AdvancedPrefsModelColumn {
colName = 0,
colStatus,
colType,
colValue,
colLast
};
virtual bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
void setFilter(const QString& filter);
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const;
QVariant data(const QModelIndex &index, int role) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
int columnCount(const QModelIndex &parent = QModelIndex()) const;
//Keep the internals of model hidden from tree
void setFirstColumnSpanned(QTreeView* tree, const QModelIndex &index = QModelIndex());
protected:
bool filterAcceptItem(PrefsItem& item) const;
private:
QString filter_;
const QChar passwordChar_;
};
class ModulePrefsModel : public QSortFilterProxyModel
{
public:
explicit ModulePrefsModel(QObject * parent = Q_NULLPTR);
enum ModulePrefsModelColumn {
colName = 0,
colLast
};
enum ModulePrefsRoles {
ModuleName = Qt::UserRole + 1
};
QVariant data(const QModelIndex &index, int role) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
virtual bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
protected:
bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const;
private:
//cache of the translated "Advanced" preference name
QString advancedPrefName_;
};
extern pref_t *prefFromPrefPtr(void *pref_ptr);
#endif // PREF_MODELS_H |
C++ | wireshark/ui/qt/models/profile_model.cpp | /* profile_model.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 "glib.h"
#include "ui/profile.h"
#include "ui/recent.h"
#include "wsutil/filesystem.h"
#include "epan/prefs.h"
#include <ui/qt/models/profile_model.h>
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/utils/wireshark_zip_helper.h>
#include <QDir>
#include <QFont>
#include <QTemporaryDir>
#include <QRegularExpression>
Q_LOGGING_CATEGORY(profileLogger, "wireshark.profiles")
ProfileSortModel::ProfileSortModel(QObject * parent):
QSortFilterProxyModel (parent),
ft_(ProfileSortModel::AllProfiles),
ftext_(QString())
{}
bool ProfileSortModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
{
QModelIndex left = source_left;
if (source_left.column() != ProfileModel::COL_NAME)
left = source_left.sibling(source_left.row(), ProfileModel::COL_NAME);
QModelIndex right = source_right;
if (source_right.column() != ProfileModel::COL_NAME)
right = source_right.sibling(source_right.row(), ProfileModel::COL_NAME);
bool igL = left.data(ProfileModel::DATA_IS_GLOBAL).toBool();
bool igR = right.data(ProfileModel::DATA_IS_GLOBAL).toBool();
if (left.data(ProfileModel::DATA_STATUS).toInt() == PROF_STAT_DEFAULT)
igL = true;
if (right.data(ProfileModel::DATA_STATUS).toInt() == PROF_STAT_DEFAULT)
igR = true;
if (igL && ! igR)
return true;
else if (! igL && igR)
return false;
else if (igL && igR)
{
if (left.data(ProfileModel::DATA_STATUS) == PROF_STAT_DEFAULT)
return true;
}
if (left.data().toString().compare(right.data().toString()) <= 0)
return true;
return false;
}
void ProfileSortModel::setFilterType(FilterType ft)
{
ft_ = ft;
invalidateFilter();
}
void ProfileSortModel::setFilterString(QString txt)
{
ftext_ = ! txt.isEmpty() ? txt : "";
invalidateFilter();
}
QStringList ProfileSortModel::filterTypes()
{
QMap<int, QString> filter_types_;
filter_types_.insert(ProfileSortModel::AllProfiles, tr("All profiles"));
filter_types_.insert(ProfileSortModel::PersonalProfiles, tr("Personal profiles"));
filter_types_.insert(ProfileSortModel::GlobalProfiles, tr("Global profiles"));
return filter_types_.values();
}
bool ProfileSortModel::filterAcceptsRow(int source_row, const QModelIndex &) const
{
bool accept = true;
QModelIndex idx = sourceModel()->index(source_row, ProfileModel::COL_NAME);
if (ft_ != ProfileSortModel::AllProfiles)
{
bool gl = idx.data(ProfileModel::DATA_IS_GLOBAL).toBool();
if (ft_ == ProfileSortModel::PersonalProfiles && gl)
accept = false;
else if (ft_ == ProfileSortModel::GlobalProfiles && ! gl)
accept = false;
}
if (ftext_.length() > 0)
{
QString name = idx.data().toString();
if (! name.contains(ftext_, Qt::CaseInsensitive))
accept = false;
}
return accept;
}
ProfileModel::ProfileModel(QObject * parent) :
QAbstractTableModel(parent)
{
/* Store preset profile name */
set_profile_ = get_profile_name();
reset_default_ = false;
profiles_imported_ = false;
last_set_row_ = 0;
/* Set filenames for profiles */
GList *files, *file;
files = g_hash_table_get_keys(const_cast<GHashTable *>(allowed_profile_filenames()));
file = g_list_first(files);
while (file) {
profile_files_ << static_cast<char *>(file->data);
file = gxx_list_next(file);
}
g_list_free(files);
loadProfiles();
}
void ProfileModel::loadProfiles()
{
beginResetModel();
bool refresh = profiles_.count() > 0;
if (refresh)
profiles_.clear();
else
init_profile_list();
GList *fl_entry = edited_profile_list();
while (fl_entry && fl_entry->data)
{
profiles_ << reinterpret_cast<profile_def *>(fl_entry->data);
fl_entry = gxx_list_next(fl_entry);
}
endResetModel();
}
GList * ProfileModel::entry(profile_def *ref) const
{
GList *fl_entry = edited_profile_list();
while (fl_entry && fl_entry->data)
{
profile_def *profile = reinterpret_cast<profile_def *>(fl_entry->data);
if (QString(ref->name).compare(profile->name) == 0 &&
QString(ref->reference).compare(profile->reference) == 0 &&
ref->is_global == profile->is_global &&
ref->status == profile->status)
{
return fl_entry;
}
fl_entry = gxx_list_next(fl_entry);
}
return Q_NULLPTR;
}
GList *ProfileModel::at(int row) const
{
if (row < 0 || row >= profiles_.count())
return Q_NULLPTR;
profile_def * prof = profiles_.at(row);
return entry(prof);
}
bool ProfileModel::changesPending() const
{
if (reset_default_)
return true;
if (g_list_length(edited_profile_list()) != g_list_length(current_profile_list()))
return true;
bool pending = false;
GList *fl_entry = edited_profile_list();
while (fl_entry && fl_entry->data && ! pending) {
profile_def *profile = reinterpret_cast<profile_def *>(fl_entry->data);
pending = (profile->status == PROF_STAT_NEW || profile->status == PROF_STAT_CHANGED || profile->status == PROF_STAT_COPY);
fl_entry = gxx_list_next(fl_entry);
}
return pending;
}
bool ProfileModel::importPending() const
{
return profiles_imported_;
}
bool ProfileModel::userProfilesExist() const
{
bool user_exists = false;
for (int cnt = 0; cnt < rowCount() && ! user_exists; cnt++)
{
QModelIndex idx = index(cnt, ProfileModel::COL_NAME);
if (! idx.data(ProfileModel::DATA_IS_GLOBAL).toBool() && ! idx.data(ProfileModel::DATA_IS_DEFAULT).toBool())
user_exists = true;
}
return user_exists;
}
int ProfileModel::rowCount(const QModelIndex &) const
{
return static_cast<int>(profiles_.count());
}
int ProfileModel::columnCount(const QModelIndex &) const
{
return static_cast<int>(_LAST_ENTRY);
}
profile_def * ProfileModel::guard(const QModelIndex &index) const
{
if (! index.isValid())
return Q_NULLPTR;
return guard(index.row());
}
profile_def * ProfileModel::guard(int row) const
{
if (row < 0 || profiles_.count() <= row)
return Q_NULLPTR;
if (! edited_profile_list())
{
static_cast<QList<profile_def *>>(profiles_).clear();
return Q_NULLPTR;
}
return profiles_.value(row, Q_NULLPTR);
}
QVariant ProfileModel::dataDisplay(const QModelIndex &index) const
{
profile_def * prof = guard(index);
if (! prof)
return QVariant();
switch (index.column())
{
case COL_NAME:
return QString(prof->name);
case COL_TYPE:
if (prof->status == PROF_STAT_DEFAULT)
return tr("Default");
else if (prof->is_global)
return tr("Global");
else
return tr("Personal");
default:
break;
}
return QVariant();
}
QVariant ProfileModel::dataFontRole(const QModelIndex &index) const
{
if (! index.isValid() || profiles_.count() <= index.row())
return QVariant();
profile_def * prof = guard(index.row());
if (! prof)
return QVariant();
QFont font;
if (prof->is_global)
font.setItalic(true);
if (! prof->is_global && ! checkDuplicate(index))
{
if ((set_profile_.compare(prof->name) == 0 && prof->status == PROF_STAT_EXISTS) ||
(set_profile_.compare(prof->reference) == 0 && prof->status == PROF_STAT_CHANGED) )
font.setBold(true);
}
if (prof->status == PROF_STAT_DEFAULT && reset_default_)
font.setStrikeOut(true);
return font;
}
bool ProfileModel::checkIfDeleted(int row) const
{
QModelIndex idx = index(row, ProfileModel::COL_NAME);
return checkIfDeleted(idx);
}
bool ProfileModel::checkIfDeleted(const QModelIndex &index) const
{
profile_def * prof = guard(index);
if (! prof)
return false;
QStringList deletedNames;
GList * current = current_profile_list();
/* search the current list as long as we have not found anything */
while (current)
{
bool found = false;
GList * edited = edited_profile_list();
profile_def * profcurr = static_cast<profile_def *>(current->data);
if (! profcurr->is_global && profcurr->status != PROF_STAT_DEFAULT)
{
while (edited && ! found)
{
profile_def * profed = static_cast<profile_def *>(edited->data);
if (! profed->is_global && profed->status != PROF_STAT_DEFAULT)
{
if (g_strcmp0(profcurr->name, profed->name) == 0 || g_strcmp0(profcurr->name, profed->reference) == 0)
{
if (profed->status == profcurr->status && prof->status != PROF_STAT_NEW && prof->status != PROF_STAT_COPY)
found = true;
}
}
edited = gxx_list_next(edited);
}
/* profile has been deleted, check if it has the name we ask for */
if (! found)
deletedNames << profcurr->name;
}
if (profcurr->is_global && deletedNames.contains(profcurr->name))
deletedNames.removeAll(profcurr->name);
current = gxx_list_next(current);
}
if (deletedNames.contains(prof->name))
return true;
return false;
}
bool ProfileModel::checkInvalid(const QModelIndex &index) const
{
profile_def * prof = guard(index);
if (! prof)
return false;
int ref = this->findAsReference(prof->name);
if (ref == index.row())
return false;
profile_def * pg = guard(ref);
if (pg && pg->status == PROF_STAT_CHANGED && g_strcmp0(pg->name, pg->reference) != 0 && ! prof->is_global)
return true;
return false;
}
bool ProfileModel::checkDuplicate(const QModelIndex &index, bool isOriginalToDuplicate) const
{
profile_def * prof = guard(index);
if (! prof || (! isOriginalToDuplicate && prof->status == PROF_STAT_EXISTS) )
return false;
QList<int> rows = this->findAllByNameAndVisibility(prof->name, prof->is_global, false);
int found = 0;
profile_def * check = Q_NULLPTR;
for (int cnt = 0; cnt < rows.count(); cnt++)
{
int row = rows.at(cnt);
if (row == index.row())
continue;
check = guard(row);
if (! check || (isOriginalToDuplicate && check->status == PROF_STAT_EXISTS) )
continue;
found++;
}
if (found > 0)
return true;
return false;
}
QVariant ProfileModel::dataBackgroundRole(const QModelIndex &index) const
{
if (! index.isValid() || profiles_.count() <= index.row())
return QVariant();
profile_def * prof = guard(index.row());
if (! prof)
return QVariant();
if (prof->status == PROF_STAT_DEFAULT && reset_default_)
return ColorUtils::fromColorT(&prefs.gui_text_deprecated);
if (prof->status != PROF_STAT_DEFAULT && ! prof->is_global)
{
/* Highlights errorneous line */
if (checkInvalid(index) || checkIfDeleted(index) || checkDuplicate(index) || ! checkNameValidity(prof->name))
return ColorUtils::fromColorT(&prefs.gui_text_invalid);
/* Highlights line, which has been duplicated by another index */
if (checkDuplicate(index, true))
return ColorUtils::fromColorT(&prefs.gui_text_valid);
}
return QVariant();
}
QVariant ProfileModel::dataToolTipRole(const QModelIndex &idx) const
{
if (! idx.isValid() || profiles_.count() <= idx.row())
return QVariant();
profile_def * prof = guard(idx.row());
if (! prof)
return QVariant();
if (prof->is_global)
return tr("This is a system provided profile");
else
return dataPath(idx);
}
QVariant ProfileModel::dataPath(const QModelIndex &index) const
{
if (! index.isValid() || profiles_.count() <= index.row())
return QVariant();
profile_def * prof = guard(index.row());
if (! prof)
return QVariant();
if (checkInvalid(index))
{
int ref = this->findAsReference(prof->name);
if (ref != index.row() && ref >= 0)
{
profile_def * prof = guard(ref);
QString msg = tr("A profile change for this name is pending");
if (prof)
msg.append(tr(" (See: %1)").arg(prof->name));
return msg;
}
return tr("This is an invalid profile definition");
}
if ((prof->status == PROF_STAT_NEW || prof->status == PROF_STAT_CHANGED || prof->status == PROF_STAT_COPY) && checkDuplicate(index))
return tr("A profile already exists with this name");
if (checkIfDeleted(index))
{
return tr("A profile with this name is being deleted");
}
if (prof->is_import)
return tr("Imported profile");
switch (prof->status)
{
case PROF_STAT_DEFAULT:
if (!reset_default_)
return gchar_free_to_qstring(get_persconffile_path("", FALSE));
else
return tr("Resetting to default");
case PROF_STAT_EXISTS:
{
QString profile_path;
if (prof->is_global) {
profile_path = gchar_free_to_qstring(get_global_profiles_dir());
} else {
profile_path = gchar_free_to_qstring(get_profiles_dir());
}
profile_path.append("/").append(prof->name);
return QDir::toNativeSeparators(profile_path);
}
case PROF_STAT_NEW:
{
QString errMsg;
if (! checkNameValidity(prof->name, &errMsg))
return errMsg;
else
return tr("Created from default settings");
}
case PROF_STAT_CHANGED:
{
QString msg;
if (! ProfileModel::checkNameValidity(QString(prof->name), &msg))
return msg;
if (prof->reference)
return tr("Renamed from: %1").arg(prof->reference);
return QVariant();
}
case PROF_STAT_COPY:
{
QString msg;
/* this should always be the case, but just as a precaution it is checked */
if (prof->reference)
{
msg = tr("Copied from: %1").arg(prof->reference);
QString appendix;
/* A global profile is neither deleted or removed, only system provided is allowed as appendix */
if (profile_exists(prof->reference, TRUE) && prof->from_global)
appendix = tr("system provided");
/* A default model as reference can neither be deleted or renamed, so skip if the reference was one */
else if (! index.data(ProfileModel::DATA_IS_DEFAULT).toBool())
{
/* find a non-global, non-default profile which could be referenced by this one. Those are the only
* ones which could be renamed or deleted */
int row = this->findByNameAndVisibility(prof->reference, false, true);
profile_def * ref = guard(row);
/* The reference is itself a copy of the original, therefore it is not accepted */
if (ref && (ref->status == PROF_STAT_COPY || ref->status == PROF_STAT_NEW) && QString(ref->name).compare(prof->reference) != 0)
ref = Q_NULLPTR;
/* found no other profile, original one had to be deleted */
if (! ref || row == index.row() || checkIfDeleted(row))
{
appendix = tr("deleted");
}
/* found another profile, so the reference had been renamed, it the status is changed */
else if (ref && ref->status == PROF_STAT_CHANGED)
{
appendix = tr("renamed to %1").arg(ref->name);
}
}
if (appendix.length() > 0)
msg.append(QString(" (%1)").arg(appendix));
}
return msg;
}
}
return QVariant();
}
QVariant ProfileModel::data(const QModelIndex &index, int role) const
{
profile_def * prof = guard(index);
if (! prof)
return QVariant();
switch (role)
{
case Qt::DisplayRole:
return dataDisplay(index);
case Qt::FontRole:
return dataFontRole(index);
case Qt::BackgroundRole:
return dataBackgroundRole(index);
case Qt::ToolTipRole:
return dataToolTipRole(index);
case ProfileModel::DATA_STATUS:
return QVariant::fromValue(prof->status);
case ProfileModel::DATA_IS_DEFAULT:
return QVariant::fromValue(prof->status == PROF_STAT_DEFAULT);
case ProfileModel::DATA_IS_GLOBAL:
return QVariant::fromValue(prof->is_global);
case ProfileModel::DATA_IS_SELECTED:
{
QModelIndex selected = activeProfile();
profile_def * selprof = guard(selected);
if (selprof)
{
if (selprof && selprof->is_global != prof->is_global)
return QVariant::fromValue(false);
if (selprof && strcmp(selprof->name, prof->name) == 0)
return QVariant::fromValue(true);
}
return QVariant::fromValue(false);
}
case ProfileModel::DATA_PATH:
return dataPath(index);
case ProfileModel::DATA_INDEX_VALUE_IS_URL:
if (index.column() <= ProfileModel::COL_TYPE)
return QVariant::fromValue(false);
return QVariant::fromValue(true);
case ProfileModel::DATA_PATH_IS_NOT_DESCRIPTION:
if (prof->status == PROF_STAT_NEW || prof->status == PROF_STAT_COPY
|| (prof->status == PROF_STAT_DEFAULT && reset_default_)
|| prof->status == PROF_STAT_CHANGED || prof->is_import)
return QVariant::fromValue(false);
else
return QVariant::fromValue(true);
default:
break;
}
return QVariant();
}
QVariant ProfileModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
{
switch (section)
{
case COL_NAME:
return tr("Profile");
case COL_TYPE:
return tr("Type");
default:
break;
}
}
return QVariant();
}
Qt::ItemFlags ProfileModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags fl = QAbstractTableModel::flags(index);
profile_def * prof = guard(index);
if (! prof)
return fl;
if (index.column() == ProfileModel::COL_NAME && prof->status != PROF_STAT_DEFAULT && ! prof->is_global)
fl |= Qt::ItemIsEditable;
return fl;
}
int ProfileModel::findByName(QString name)
{
int row = findByNameAndVisibility(name, false);
if (row < 0)
row = findByNameAndVisibility(name, true);
return row;
}
int ProfileModel::findAsReference(QString reference) const
{
int found = -1;
if (reference.length() <= 0)
return found;
for (int cnt = 0; cnt < profiles_.count() && found < 0; cnt++)
{
profile_def * prof = guard(cnt);
if (prof && reference.compare(prof->reference) == 0)
found = cnt;
}
return found;
}
int ProfileModel::findByNameAndVisibility(QString name, bool isGlobal, bool searchReference) const
{
QList<int> result = findAllByNameAndVisibility(name, isGlobal, searchReference);
return result.count() == 0 ? -1 : result.at(0);
}
QList<int> ProfileModel::findAllByNameAndVisibility(QString name, bool isGlobal, bool searchReference) const
{
QList<int> result;
for (int cnt = 0; cnt < profiles_.count(); cnt++)
{
profile_def * prof = guard(cnt);
if (prof && static_cast<bool>(prof->is_global) == isGlobal)
{
if (name.compare(prof->name) == 0 || (searchReference && name.compare(prof->reference) == 0) )
result << cnt;
}
}
return result;
}
QModelIndex ProfileModel::addNewProfile(QString name)
{
int cnt = 1;
QString newName = name;
while (findByNameAndVisibility(newName) >= 0)
{
newName = QString("%1 %2").arg(name).arg(QString::number(cnt));
cnt++;
}
add_to_profile_list(newName.toUtf8().constData(), newName.toUtf8().constData(), PROF_STAT_NEW, FALSE, FALSE, FALSE);
loadProfiles();
return index(findByName(newName), COL_NAME);
}
QModelIndex ProfileModel::duplicateEntry(QModelIndex idx, int new_status)
{
profile_def * prof = guard(idx);
if (! prof)
return QModelIndex();
/* only new and copied stati can be set */
if (new_status != PROF_STAT_NEW && new_status != PROF_STAT_COPY)
new_status = PROF_STAT_COPY;
/* this is a copy from a personal profile, check if the original has been a
* new profile or a preexisting one. In the case of a new profile, restart
* with the state PROF_STAT_NEW */
if (prof->status == PROF_STAT_COPY && ! prof->from_global)
{
int row = findByNameAndVisibility(prof->reference, false);
profile_def * copyParent = guard(row);
if (copyParent && copyParent->status == PROF_STAT_NEW)
return duplicateEntry(index(row, ProfileModel::COL_NAME), PROF_STAT_NEW);
}
/* Rules for figuring out the name to copy from:
*
* General, use copy name
* If status of copy is new or changed => use copy reference
* If copy is non global and status of copy is != changed, use original parent name
*/
QString parent = prof->name;
if (prof->status == PROF_STAT_CHANGED)
parent = prof->reference;
else if (! prof->is_global && prof->status != PROF_STAT_NEW && prof->status != PROF_STAT_CHANGED)
parent = get_profile_parent (prof->name);
if (parent.length() == 0)
return QModelIndex();
/* parent references the parent profile to be used, parentName is the base for the new name */
QString parentName = parent;
/* the user has changed the profile name, therefore this is also the name to be used */
if (prof->status != PROF_STAT_EXISTS)
parentName = prof->name;
/* check to ensure we do not end up with (copy) (copy) (copy) ... */
QRegularExpression rx("\\s+(\\(\\s*" + tr("copy", "noun") + "\\s*\\d*\\))");
parentName.replace(rx, "");
QString new_name;
/* if copy is global and name has not been used before, use that, else create first copy */
if (prof->is_global && findByNameAndVisibility(parentName) < 0)
new_name = QString(prof->name);
else
new_name = QString("%1 (%2)").arg(parentName).arg(tr("copy", "noun"));
/* check if copy already exists and iterate, until an unused version is found */
int cnt = 1;
while (findByNameAndVisibility(new_name) >= 0)
{
new_name = QString("%1 (%2 %3)").arg(parentName).arg(tr("copy", "noun")).arg(QString::number(cnt));
cnt++;
}
/* if this would be a copy, but the original is already a new one, this is a copy as well */
if (new_status == PROF_STAT_COPY && prof->status == PROF_STAT_NEW)
new_status = PROF_STAT_NEW;
/* add element */
add_to_profile_list(new_name.toUtf8().constData(), parent.toUtf8().constData(), new_status, FALSE, prof->from_global ? prof->from_global : prof->is_global, FALSE);
/* reload profile list in model */
loadProfiles();
int row = findByNameAndVisibility(new_name, false);
/* sanity check, if adding the profile went correctly */
if (row < 0 || row == idx.row())
return QModelIndex();
/* return the index of the profile */
return index(row, COL_NAME);
}
void ProfileModel::deleteEntry(QModelIndex idx)
{
if (! idx.isValid())
return;
QModelIndexList temp;
temp << idx;
deleteEntries(temp);
}
void ProfileModel::deleteEntries(QModelIndexList idcs)
{
bool changes = false;
QList<int> indeces;
foreach (QModelIndex idx, idcs)
{
if (! indeces.contains(idx.row()) && ! idx.data(ProfileModel::DATA_IS_GLOBAL).toBool())
indeces << idx.row();
}
/* Security blanket. This ensures, that we start deleting from the end and do not get any issues iterating the list */
std::sort(indeces.begin(), indeces.end(), std::less<int>());
foreach (int row, indeces)
{
profile_def * prof = guard(row);
if (! prof)
continue;
if (prof->is_global)
continue;
if (prof->status == PROF_STAT_DEFAULT)
{
reset_default_ = ! reset_default_;
}
else
{
GList * fl_entry = entry(prof);
if (fl_entry)
{
changes = true;
remove_from_profile_list(fl_entry);
}
}
}
if (changes)
loadProfiles();
if (reset_default_)
{
emit layoutAboutToBeChanged();
emit dataChanged(index(0, 0), index(rowCount(), columnCount()));
emit layoutChanged();
}
}
bool ProfileModel::resetDefault() const
{
return reset_default_;
}
void ProfileModel::doResetModel(bool reset_import)
{
reset_default_ = false;
if (reset_import)
profiles_imported_ = false;
loadProfiles();
}
QModelIndex ProfileModel::activeProfile() const
{
QList<int> rows = this->findAllByNameAndVisibility(set_profile_, false, true);
foreach (int row, rows)
{
profile_def * prof = profiles_.at(row);
if (prof->is_global || checkDuplicate(index(row, ProfileModel::COL_NAME)) )
return QModelIndex();
if ((set_profile_.compare(prof->name) == 0 && (prof->status == PROF_STAT_EXISTS || prof->status == PROF_STAT_DEFAULT) ) ||
(set_profile_.compare(prof->reference) == 0 && prof->status == PROF_STAT_CHANGED) )
return index(row, ProfileModel::COL_NAME);
}
return QModelIndex();
}
bool ProfileModel::setData(const QModelIndex &idx, const QVariant &value, int role)
{
last_set_row_ = -1;
if (role != Qt::EditRole || ! value.isValid() || value.toString().isEmpty())
return false;
QString newValue = value.toString();
profile_def * prof = guard(idx);
if (! prof || prof->status == PROF_STAT_DEFAULT)
return false;
last_set_row_ = idx.row();
QString current(prof->name);
if (current.compare(newValue) != 0)
{
g_free(prof->name);
prof->name = qstring_strdup(newValue);
if (prof->reference && g_strcmp0(prof->name, prof->reference) == 0 && ! (prof->status == PROF_STAT_NEW || prof->status == PROF_STAT_COPY)) {
prof->status = PROF_STAT_EXISTS;
} else if (prof->status == PROF_STAT_EXISTS) {
prof->status = PROF_STAT_CHANGED;
}
emit itemChanged(idx);
}
loadProfiles();
return true;
}
int ProfileModel::lastSetRow() const
{
return last_set_row_;
}
bool ProfileModel::copyTempToProfile(QString tempPath, QString profilePath, bool * wasEmpty)
{
bool was_empty = true;
QDir profileDir(profilePath);
if (! profileDir.mkpath(profilePath) || ! QFile::exists(tempPath))
return false;
QDir tempProfile(tempPath);
tempProfile.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
QFileInfoList files = tempProfile.entryInfoList();
if (files.count() <= 0)
return false;
int created = 0;
foreach (QFileInfo finfo, files)
{
QString tempFile = finfo.absoluteFilePath();
QString profileFile = profilePath + "/" + finfo.fileName();
if (! profile_files_.contains(finfo.fileName()))
{
was_empty = false;
continue;
}
if (! QFile::exists(tempFile) || QFile::exists(profileFile))
continue;
if (QFile::copy(tempFile, profileFile))
created++;
}
if (wasEmpty)
*wasEmpty = was_empty;
if (created > 0)
return true;
return false;
}
QFileInfoList ProfileModel::uniquePaths(QFileInfoList lst)
{
QStringList files;
QFileInfoList newLst;
foreach (QFileInfo entry, lst)
{
if (! files.contains(entry.absoluteFilePath()))
{
if (entry.exists() && entry.isDir())
{
newLst << QFileInfo(entry.absoluteFilePath());
files << entry.absoluteFilePath();
}
}
}
return newLst;
}
QFileInfoList ProfileModel::filterProfilePath(QString path, QFileInfoList ent, bool fromZip)
{
QFileInfoList result = ent;
QDir temp(path);
temp.setSorting(QDir::Name);
temp.setFilter(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
QFileInfoList entries = temp.entryInfoList();
if (! fromZip)
entries << QFileInfo(path);
foreach (QFileInfo entry, entries)
{
QDir fPath(entry.absoluteFilePath());
fPath.setSorting(QDir::Name);
fPath.setFilter(QDir::Files | QDir::NoSymLinks);
QFileInfoList fEntries = fPath.entryInfoList();
bool found = false;
for (int cnt = 0; cnt < fEntries.count() && ! found; cnt++)
{
if (config_file_exists_with_entries(fEntries[cnt].absoluteFilePath().toUtf8().constData(), '#'))
found = true;
}
if (found)
{
result.append(entry);
}
else
{
if (path.compare(entry.absoluteFilePath()) != 0)
result.append(filterProfilePath(entry.absoluteFilePath(), result, fromZip));
}
}
return result;
}
#ifdef HAVE_MINIZIP
QStringList ProfileModel::exportFileList(QModelIndexList items)
{
QStringList result;
foreach(QModelIndex idx, items)
{
profile_def * prof = guard(idx);
if (! prof || prof->is_global || QString(prof->name).compare(DEFAULT_PROFILE) == 0)
continue;
if (! idx.data(ProfileModel::DATA_PATH_IS_NOT_DESCRIPTION).toBool())
continue;
QString path = idx.data(ProfileModel::DATA_PATH).toString();
QDir temp(path);
temp.setSorting(QDir::Name);
temp.setFilter(QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot);
QFileInfoList entries = temp.entryInfoList();
foreach (QFileInfo fi, entries)
result << fi.absoluteFilePath();
}
return result;
}
bool ProfileModel::exportProfiles(QString filename, QModelIndexList items, QString *err)
{
if (changesPending())
{
if (err)
err->append(tr("Exporting profiles while changes are pending is not allowed"));
return false;
}
/* Write recent file for current profile before exporting */
write_profile_recent();
QStringList files = exportFileList(items);
if (files.count() == 0)
{
if (err)
err->append((tr("No profiles found to export")));
return false;
}
if (WiresharkZipHelper::zip(filename, files, gchar_free_to_qstring(get_profiles_dir()) + "/") )
return true;
return false;
}
/* This check runs BEFORE the file has been unzipped! */
bool ProfileModel::acceptFile(QString fileName, int fileSize)
{
if (fileName.toLower().endsWith(".zip"))
return false;
/* Arbitrary maximum config file size accepted: 256MB */
if (fileSize > 1024 * 1024 * 256)
return false;
return true;
}
QString ProfileModel::cleanName(QString fileName)
{
QStringList parts = fileName.split("/");
QString temp = parts[parts.count() - 1].replace(QRegularExpression("[" + QRegularExpression::escape(illegalCharacters()) + "]"), QString("_") );
temp = parts.join("/");
return temp;
}
int ProfileModel::importProfilesFromZip(QString filename, int * skippedCnt, QStringList *result)
{
QTemporaryDir dir;
#if 0
dir.setAutoRemove(false);
g_printerr("Temp dir for unzip: %s\n", dir.path().toUtf8().constData());
#endif
int cnt = 0;
if (dir.isValid())
{
WiresharkZipHelper::unzip(filename, dir.path(), &ProfileModel::acceptFile, &ProfileModel::cleanName);
cnt = importProfilesFromDir(dir.path(), skippedCnt, true, result);
}
return cnt;
}
#endif
int ProfileModel::importProfilesFromDir(QString dirname, int * skippedCnt, bool fromZip, QStringList *result)
{
int count = 0;
int skipped = 0;
QDir profileDir(gchar_free_to_qstring(get_profiles_dir()));
QDir dir(dirname);
if (skippedCnt)
*skippedCnt = 0;
if (dir.exists())
{
QFileInfoList entries = uniquePaths(filterProfilePath(dirname, QFileInfoList(), fromZip));
foreach (QFileInfo fentry, entries)
{
if (fentry.fileName().length() <= 0)
continue;
bool wasEmpty = true;
bool success = false;
QString profilePath = profileDir.absolutePath() + "/" + fentry.fileName();
QString tempPath = fentry.absoluteFilePath();
if (fentry.fileName().compare(DEFAULT_PROFILE, Qt::CaseInsensitive) == 0 || QFile::exists(profilePath))
{
skipped++;
continue;
}
if (result)
*result << fentry.fileName();
success = copyTempToProfile(tempPath, profilePath, &wasEmpty);
if (success)
{
count++;
add_to_profile_list(fentry.fileName().toUtf8().constData(), fentry.fileName().toUtf8().constData(), PROF_STAT_NEW, FALSE, FALSE, TRUE);
}
else if (! wasEmpty && QFile::exists(profilePath))
{
QDir dh(profilePath);
dh.rmdir(profilePath);
}
}
}
if (count > 0)
{
profiles_imported_ = true;
loadProfiles();
}
if (skippedCnt)
*skippedCnt = skipped;
return count;
}
void ProfileModel::markAsImported(QStringList importedItems)
{
if (importedItems.count() <= 0)
return;
profiles_imported_ = true;
foreach (QString item, importedItems)
{
int row = findByNameAndVisibility(item, false);
profile_def * prof = guard(row);
if (! prof)
continue;
prof->is_import = true;
}
}
bool ProfileModel::clearImported(QString *msg)
{
QList<int> rows;
bool result = true;
for (int cnt = 0; cnt < rowCount(); cnt++)
{
profile_def * prof = guard(cnt);
if (prof && prof->is_import && ! rows.contains(cnt))
rows << cnt;
}
/* Security blanket. This ensures, that we start deleting from the end and do not get any issues iterating the list */
std::sort(rows.begin(), rows.end(), std::less<int>());
char * ret_path = Q_NULLPTR;
for (int cnt = 0; cnt < rows.count() && result; cnt++)
{
int row = rows.at(cnt);
if (delete_persconffile_profile (index(row, ProfileModel::COL_NAME).data().toString().toUtf8().constData(), &ret_path) != 0)
{
if (msg)
{
QString errmsg = QString("%1\n\"%2\":\n%3").arg(tr("Can't delete profile directory")).arg(ret_path).arg(g_strerror(errno));
msg->append(errmsg);
}
result = false;
}
}
return result;
}
QString ProfileModel::illegalCharacters()
{
#ifdef _WIN32
/* According to https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions */
return QString("<>:\"/\\|?*");
#else
return QDir::separator();
#endif
}
bool ProfileModel::checkNameValidity(QString name, QString *msg)
{
QString message;
bool invalid = false;
QString msgChars;
QString invalid_dir_chars = illegalCharacters();
for (int cnt = 0; cnt < invalid_dir_chars.length() && ! invalid; cnt++)
{
msgChars += invalid_dir_chars[cnt];
msgChars += ' ';
if (name.contains(invalid_dir_chars[cnt]))
invalid = true;
}
#ifdef _WIN32
if (invalid)
{
message = tr("A profile name cannot contain the following characters: %1").arg(msgChars);
}
if (message.isEmpty() && (name.startsWith('.') || name.endsWith('.')) )
message = tr("A profile cannot start or end with a period (.)");
#else
if (invalid)
message = tr("A profile name cannot contain the '/' character");
#endif
if (! message.isEmpty()) {
if (msg)
msg->append(message);
return false;
}
return true;
}
QString ProfileModel::activeProfileName()
{
ProfileModel model;
QModelIndex idx = model.activeProfile();
return idx.data(ProfileModel::COL_NAME).toString();
}
QString ProfileModel::activeProfilePath()
{
ProfileModel model;
QModelIndex idx = model.activeProfile();
return idx.data(ProfileModel::DATA_PATH).toString();
} |
C/C++ | wireshark/ui/qt/models/profile_model.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PROFILE_MODEL_H
#define PROFILE_MODEL_H
#include "config.h"
#include "glib.h"
#include <ui/profile.h>
#include <QAbstractTableModel>
#include <QSortFilterProxyModel>
#include <QLoggingCategory>
#include <QFileInfoList>
Q_DECLARE_LOGGING_CATEGORY(profileLogger)
class ProfileSortModel : public QSortFilterProxyModel
{
Q_OBJECT
public:
ProfileSortModel(QObject *parent = Q_NULLPTR);
enum FilterType {
AllProfiles = 0,
PersonalProfiles,
GlobalProfiles
};
void setFilterType(FilterType ft);
void setFilterString(QString txt = QString());
static QStringList filterTypes();
protected:
virtual bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const;
virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const;
private:
FilterType ft_;
QString ftext_;
};
class ProfileModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit ProfileModel(QObject * parent = Q_NULLPTR);
enum {
COL_NAME,
COL_TYPE,
_LAST_ENTRY
} columns_;
enum {
DATA_STATUS = Qt::UserRole,
DATA_IS_DEFAULT,
DATA_IS_GLOBAL,
DATA_IS_SELECTED,
DATA_PATH,
DATA_PATH_IS_NOT_DESCRIPTION,
DATA_INDEX_VALUE_IS_URL
} data_values_;
// QAbstractItemModel interface
virtual int rowCount(const QModelIndex & parent = QModelIndex()) const;
virtual int columnCount(const QModelIndex & parent = QModelIndex()) const;
virtual QVariant data(const QModelIndex & idx, int role = Qt::DisplayRole) const;
virtual bool setData(const QModelIndex &index, const QVariant &value, int role);
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
virtual Qt::ItemFlags flags(const QModelIndex &index) const;
void deleteEntry(QModelIndex idx);
void deleteEntries(QModelIndexList idcs);
int findByName(QString name);
QModelIndex addNewProfile(QString name);
QModelIndex duplicateEntry(QModelIndex idx, int new_status = PROF_STAT_COPY);
void doResetModel(bool reset_import = false);
bool resetDefault() const;
QModelIndex activeProfile() const;
static QString activeProfileName();
static QString activeProfilePath();
GList * at(int row) const;
bool changesPending() const;
bool importPending() const;
bool userProfilesExist() const;
#ifdef HAVE_MINIZIP
bool exportProfiles(QString filename, QModelIndexList items, QString * err = Q_NULLPTR);
int importProfilesFromZip(QString filename, int *skippedCnt = Q_NULLPTR, QStringList *result = Q_NULLPTR);
#endif
int importProfilesFromDir(QString filename, int *skippedCnt = Q_NULLPTR, bool fromZip = false, QStringList *result = Q_NULLPTR);
static bool checkNameValidity(QString name, QString *msg = Q_NULLPTR);
QList<int> findAllByNameAndVisibility(QString name, bool isGlobal = false, bool searchReference = false) const;
void markAsImported(QStringList importedItems);
bool clearImported(QString *msg = Q_NULLPTR);
int lastSetRow() const;
bool checkInvalid(const QModelIndex &index) const;
bool checkIfDeleted(const QModelIndex &index) const;
bool checkIfDeleted(int row) const;
bool checkDuplicate(const QModelIndex &index, bool isOriginalToDuplicate = false) const;
signals:
void itemChanged(const QModelIndex &idx);
protected:
static QString illegalCharacters();
private:
QList<profile_def *> profiles_;
QStringList profile_files_;
QString set_profile_;
bool reset_default_;
bool profiles_imported_;
int last_set_row_;
void loadProfiles();
profile_def * guard(const QModelIndex &index) const;
profile_def * guard(int row) const;
GList * entry(profile_def *) const;
int findByNameAndVisibility(QString name, bool isGlobal = false, bool searchReference = false) const;
int findAsReference(QString reference) const;
#ifdef HAVE_MINIZIP
static bool acceptFile(QString fileName, int fileSize);
static QString cleanName(QString fileName);
#endif
QVariant dataDisplay(const QModelIndex & idx) const;
QVariant dataFontRole(const QModelIndex & idx) const;
QVariant dataBackgroundRole(const QModelIndex & idx) const;
QVariant dataToolTipRole(const QModelIndex & idx) const;
QVariant dataPath(const QModelIndex & idx) const;
#ifdef HAVE_MINIZIP
QStringList exportFileList(QModelIndexList items);
#endif
bool copyTempToProfile(QString tempPath, QString profilePath, bool *wasEmpty = Q_NULLPTR);
QFileInfoList filterProfilePath(QString, QFileInfoList ent, bool fromZip);
QFileInfoList uniquePaths(QFileInfoList lst);
};
#endif |
C++ | wireshark/ui/qt/models/proto_tree_model.cpp | /* proto_tree_model.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/proto_tree_model.h>
#include <epan/prefs.h>
#include <wsutil/wslog.h>
#include <ui/qt/utils/color_utils.h>
#include <QApplication>
#include <QPalette>
#include <QFont>
// To do:
// - Add ProtoTreeDelegate
// - Add ProtoTreeModel to CaptureFile
ProtoTreeModel::ProtoTreeModel(QObject * parent) :
QAbstractItemModel(parent)
{
root_node_ = new ProtoNode(NULL);
}
ProtoTreeModel::~ProtoTreeModel()
{
delete root_node_;
}
Qt::ItemFlags ProtoTreeModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags item_flags = QAbstractItemModel::flags(index);
if (rowCount(index) < 1) {
item_flags |= Qt::ItemNeverHasChildren;
}
return item_flags;
}
QModelIndex ProtoTreeModel::index(int row, int, const QModelIndex &parent) const
{
ProtoNode *parent_node = root_node_;
if (parent.isValid()) {
// index is not a top level item.
parent_node = protoNodeFromIndex(parent);
}
if (! parent_node->isValid())
return QModelIndex();
ProtoNode *child = parent_node->child(row);
if (! child) {
return QModelIndex();
}
return createIndex(row, 0, static_cast<void *>(child));
}
QModelIndex ProtoTreeModel::parent(const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
ProtoNode *parent_node = protoNodeFromIndex(index)->parentNode();
return indexFromProtoNode(parent_node);
}
int ProtoTreeModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid()) {
return protoNodeFromIndex(parent)->childrenCount();
}
return root_node_->childrenCount();
}
// The QItemDelegate documentation says
// "When displaying items from a custom model in a standard view, it is
// often sufficient to simply ensure that the model returns appropriate
// data for each of the roles that determine the appearance of items in
// views."
// We might want to move this to a delegate regardless.
QVariant ProtoTreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
ProtoNode *index_node = protoNodeFromIndex(index);
FieldInformation finfo(index_node);
if (!finfo.isValid()) {
return QVariant();
}
switch (role) {
case Qt::DisplayRole:
return index_node->labelText();
case Qt::BackgroundRole:
{
switch(finfo.flag(PI_SEVERITY_MASK)) {
case(0):
break;
case(PI_COMMENT):
return ColorUtils::expert_color_comment;
case(PI_CHAT):
return ColorUtils::expert_color_chat;
case(PI_NOTE):
return ColorUtils::expert_color_note;
case(PI_WARN):
return ColorUtils::expert_color_warn;
case(PI_ERROR):
return ColorUtils::expert_color_error;
default:
ws_warning("Unhandled severity flag: %u", finfo.flag(PI_SEVERITY_MASK));
}
if (finfo.headerInfo().type == FT_PROTOCOL) {
return QApplication::palette().window();
}
return QApplication::palette().base();
}
case Qt::ForegroundRole:
{
if (finfo.flag(PI_SEVERITY_MASK)) {
return ColorUtils::expert_color_foreground;
}
if (finfo.isLink()) {
return ColorUtils::themeLinkBrush();
}
if (finfo.headerInfo().type == FT_PROTOCOL) {
return QApplication::palette().windowText();
}
return QApplication::palette().text();
}
case Qt::FontRole:
if (finfo.isLink()) {
QFont font;
font.setUnderline(true);
return font;
}
default:
break;
}
return QVariant();
}
void ProtoTreeModel::setRootNode(proto_node *root_node)
{
beginResetModel();
delete root_node_;
root_node_ = new ProtoNode(root_node);
endResetModel();
if (!root_node) return;
int row_count = root_node_->childrenCount();
if (row_count < 1) return;
beginInsertRows(QModelIndex(), 0, row_count - 1);
endInsertRows();
}
ProtoNode* ProtoTreeModel::protoNodeFromIndex(const QModelIndex &index) const
{
return static_cast<ProtoNode*>(index.internalPointer());
}
QModelIndex ProtoTreeModel::indexFromProtoNode(ProtoNode *index_node) const
{
if (!index_node) {
return QModelIndex();
}
int row = index_node->row();
if (!index_node->isValid() || row < 0) {
return QModelIndex();
}
return createIndex(row, 0, static_cast<void *>(index_node));
}
struct find_hfid_ {
int hfid;
ProtoNode *node;
};
bool ProtoTreeModel::foreachFindHfid(ProtoNode *node, gpointer find_hfid_ptr)
{
struct find_hfid_ *find_hfid = (struct find_hfid_ *) find_hfid_ptr;
if (PNODE_FINFO(node->protoNode()) && PNODE_FINFO(node->protoNode())->hfinfo->id == find_hfid->hfid) {
find_hfid->node = node;
return true;
}
for (int i = 0; i < node->childrenCount(); i++) {
if (foreachFindHfid(node->child(i), find_hfid)) {
return true;
}
}
return false;
}
QModelIndex ProtoTreeModel::findFirstHfid(int hf_id)
{
if (!root_node_ || hf_id < 0) return QModelIndex();
struct find_hfid_ find_hfid;
find_hfid.hfid = hf_id;
if (foreachFindHfid(root_node_, &find_hfid) && find_hfid.node->isValid()) {
return indexFromProtoNode(find_hfid.node);
}
return QModelIndex();
}
struct find_field_info_ {
field_info *fi;
ProtoNode *node;
};
bool ProtoTreeModel::foreachFindField(ProtoNode *node, gpointer find_finfo_ptr)
{
struct find_field_info_ *find_finfo = (struct find_field_info_ *) find_finfo_ptr;
if (PNODE_FINFO(node->protoNode()) == find_finfo->fi) {
find_finfo->node = node;
return true;
}
for (int i = 0; i < node->childrenCount(); i++) {
if (foreachFindField(node->child(i), find_finfo)) {
return true;
}
}
return false;
}
QModelIndex ProtoTreeModel::findFieldInformation(FieldInformation *finfo)
{
if (!root_node_ || !finfo) return QModelIndex();
field_info * fi = finfo->fieldInfo();
if (!fi) return QModelIndex();
struct find_field_info_ find_finfo;
find_finfo.fi = fi;
if (foreachFindField(root_node_, &find_finfo) && find_finfo.node->isValid()) {
return indexFromProtoNode(find_finfo.node);
}
return QModelIndex();
} |
C/C++ | wireshark/ui/qt/models/proto_tree_model.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PROTO_TREE_MODEL_H
#define PROTO_TREE_MODEL_H
#include <ui/qt/utils/field_information.h>
#include <ui/qt/utils/proto_node.h>
#include <QAbstractItemModel>
#include <QModelIndex>
class ProtoTreeModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit ProtoTreeModel(QObject * parent = 0);
~ProtoTreeModel();
virtual Qt::ItemFlags flags(const QModelIndex &index) const;
QModelIndex index(int row, int, const QModelIndex &parent = QModelIndex()) const;
virtual QModelIndex parent(const QModelIndex &index) const;
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
virtual int columnCount(const QModelIndex &) const { return 1; }
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
// root_node can be NULL.
void setRootNode(proto_node *root_node);
ProtoNode* protoNodeFromIndex(const QModelIndex &index) const;
QModelIndex indexFromProtoNode(ProtoNode *index_node) const;
QModelIndex findFirstHfid(int hf_id);
QModelIndex findFieldInformation(FieldInformation *finfo);
private:
ProtoNode *root_node_;
static bool foreachFindHfid(ProtoNode *node, gpointer find_hfid_ptr);
static bool foreachFindField(ProtoNode *node, gpointer find_finfo_ptr);
};
#endif // PROTO_TREE_MODEL_H |
C++ | wireshark/ui/qt/models/related_packet_delegate.cpp | /* related_packet_delegate.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/related_packet_delegate.h>
#include "packet_list_record.h"
#include <ui/qt/main_application.h>
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/main_window.h>
#include <QApplication>
#include <QPainter>
typedef enum {
CT_NONE, // Not within the selected conversation.
CT_STARTING, // First packet in a conversation.
CT_CONTINUING, // Part of the selected conversation.
CT_BYPASSING, // *Not* part of the selected conversation.
CT_ENDING, // Last packet in a conversation.
CT_NUM_TYPES,
} ct_conversation_trace_type_t;
// To do:
// - Add other frame types and symbols. If `tshark -G fields | grep FT_FRAMENUM`
// is any indication, we should add "reassembly" and "reassembly error"
// fields.
// - Don't add *too* many frame types and symbols. The goal is context, not
// clutter.
// - Add tooltips. It looks like this needs to be done in ::helpEvent
// or PacketListModel::data.
// - Add "Go -> Next Related" and "Go -> Previous Related"?
// - Apply as filter?
RelatedPacketDelegate::RelatedPacketDelegate(QWidget *parent) :
QStyledItemDelegate(parent),
conv_(NULL),
current_frame_(0)
{
clear();
}
void RelatedPacketDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
/* This prevents the drawing of related objects, if multiple lines are being selected */
if (mainApp && mainApp->mainWindow())
{
MainWindow * mw = qobject_cast<MainWindow *>(mainApp->mainWindow());
if (mw && mw->hasSelection())
{
QStyledItemDelegate::paint(painter, option, index);
return;
}
}
QStyleOptionViewItem option_vi = option;
QStyledItemDelegate::initStyleOption(&option_vi, index);
int em_w = option_vi.fontMetrics.height();
int en_w = (em_w + 1) / 2;
int line_w = (option_vi.fontMetrics.lineWidth());
option_vi.features |= QStyleOptionViewItem::HasDecoration;
option_vi.decorationSize.setHeight(1);
option_vi.decorationSize.setWidth(em_w);
QStyledItemDelegate::paint(painter, option_vi, index);
guint32 setup_frame = 0, last_frame = 0;
if (conv_) {
setup_frame = (int) conv_->setup_frame;
last_frame = (int) conv_->last_frame;
}
const frame_data *fd;
PacketListRecord *record = static_cast<PacketListRecord*>(index.internalPointer());
if (!record || (fd = record->frameData()) == NULL) {
return;
}
ct_conversation_trace_type_t conversation_trace_type = CT_NONE;
ft_framenum_type_t related_frame_type =
related_frames_.contains(fd->num) ? related_frames_[fd->num] : FT_FRAMENUM_NUM_TYPES;
if (setup_frame > 0 && last_frame > 0 && setup_frame != last_frame) {
if (fd->num == setup_frame) {
conversation_trace_type = CT_STARTING;
} else if (fd->num > setup_frame && fd->num < last_frame) {
conversation_trace_type =
conv_->conv_index == record->conversation() ? CT_CONTINUING : CT_BYPASSING;
} else if (fd->num == last_frame) {
conversation_trace_type = CT_ENDING;
}
}
painter->save();
if (QApplication::style()->objectName().contains("vista")) {
// QWindowsVistaStyle::drawControl does this internally. Unfortunately there
// doesn't appear to be a more general way to do this.
option_vi.palette.setColor(QPalette::All, QPalette::HighlightedText, option_vi.palette.color(QPalette::Active, QPalette::Text));
}
QPalette::ColorGroup cg = option_vi.state & QStyle::State_Enabled
? QPalette::Normal : QPalette::Disabled;
QColor fg;
if (cg == QPalette::Normal && !(option_vi.state & QStyle::State_Active))
cg = QPalette::Inactive;
#if !defined(Q_OS_WIN)
if (option_vi.state & QStyle::State_MouseOver) {
fg = QApplication::palette().text().color();
} else
#endif
if (option_vi.state & QStyle::State_Selected) {
fg = option_vi.palette.color(cg, QPalette::HighlightedText);
} else {
fg = option_vi.palette.color(cg, QPalette::Text);
}
fg = ColorUtils::alphaBlend(fg, option_vi.palette.color(cg, QPalette::Base), 0.5);
QPen line_pen(fg);
line_pen.setWidth(line_w);
line_pen.setJoinStyle(Qt::RoundJoin);
painter->setPen(line_pen);
painter->translate(option_vi.rect.x(), option_vi.rect.y());
painter->translate(en_w + 0.5, 0.5);
painter->setRenderHint(QPainter::Antialiasing, true);
int height = option_vi.rect.height();
// Uncomment to make the boundary visible.
// painter->save();
// painter->setPen(Qt::darkRed);
// painter->drawRect(QRectF(0.5, 0.5, en_w - 1, height - 1));
// painter->restore();
// The current decorations are based on what looked good and were easy
// to code.
// It might be useful to have a JACKPOT_MODE define that shows each
// decoration in sequence in order to make it easier to create
// screenshots for the User's Guide.
// Vertical line. Lower and upper half for the start and end of the
// conversation respectively, solid for conversation member, dashed
// for other packets in the start-end range.
switch (conversation_trace_type) {
case CT_STARTING:
{
QPoint start_line[] = {
QPoint(en_w - 1, height / 2),
QPoint(0, height / 2),
QPoint(0, height)
};
painter->drawPolyline(start_line, 3);
break;
}
case CT_CONTINUING:
case CT_BYPASSING:
{
painter->save();
if (conversation_trace_type == CT_BYPASSING) {
// Dashed line as we bypass packets not part of the conv.
QPen other_pen(line_pen);
other_pen.setStyle(Qt::DashLine);
painter->setPen(other_pen);
}
// analysis overriding mark (three horizontal lines)
if(fd->tcp_snd_manual_analysis) {
int wbound = (en_w - 1) / 2;
painter->drawLine(-wbound, 1, wbound, 1);
painter->drawLine(-wbound, height / 2, wbound, height / 2);
painter->drawLine(-wbound, height - 2, wbound, height - 2);
}
painter->drawLine(0, 0, 0, height);
painter->restore();
break;
}
case CT_ENDING:
{
QPoint end_line[] = {
QPoint(en_w - 1, height / 2),
QPoint(0, height / 2),
QPoint(0, 0)
};
painter->drawPolyline(end_line, 3);
/* analysis overriding on the last packet of the conversation,
* we mark it with an additional horizontal line only.
* See issue 10725 for example.
*/
// analysis overriding mark (three horizontal lines)
if(fd->tcp_snd_manual_analysis) {
int wbound = (en_w - 1) / 2;
painter->drawLine(-wbound, 1, wbound, 1);
painter->drawLine(-wbound, height / 2, wbound, height / 2);
}
break;
}
default:
break;
}
// Related packet indicator. Rightward arrow for requests, leftward
// arrow for responses, circle for others.
// XXX These are comically oversized when we have multi-line rows.
if (related_frame_type != FT_FRAMENUM_NUM_TYPES) {
painter->setBrush(fg);
switch (related_frame_type) {
// Request and response arrows are moved forward one pixel in order to
// maximize white space between the heads and the conversation line.
case FT_FRAMENUM_REQUEST:
{
int hh = height / 2;
QPoint tail(2 - en_w, hh);
QPoint head(en_w, hh);
drawArrow(painter, tail, head, hh / 2);
break;
}
case FT_FRAMENUM_RESPONSE:
{
int hh = height / 2;
QPoint tail(en_w - 1, hh);
QPoint head(1 - en_w, hh);
drawArrow(painter, tail, head, hh / 2);
break;
}
case FT_FRAMENUM_ACK:
{
QRect bbox (2 - en_w, height / 3, em_w - 2, height / 2);
drawCheckMark(painter, bbox);
break;
}
case FT_FRAMENUM_DUP_ACK:
{
QRect bbox (2 - en_w, (height / 3) - (line_w * 2), em_w - 2, height / 2);
drawCheckMark(painter, bbox);
bbox.moveTop(bbox.top() + (line_w * 3));
drawCheckMark(painter, bbox);
break;
}
case FT_FRAMENUM_RETRANS_PREV:
{
int hh = height / 2;
QPoint tail(2 - en_w, hh);
QPoint head(en_w, hh);
drawChevrons(painter, tail, head, hh / 2);
break;
}
case FT_FRAMENUM_RETRANS_NEXT:
{
int hh = height / 2;
QPoint tail(en_w - 1, hh);
QPoint head(1 - en_w, hh);
drawChevrons(painter, tail, head, hh / 2);
break;
}
case FT_FRAMENUM_NONE:
default:
painter->drawEllipse(QPointF(0.0, option_vi.rect.height() / 2), 2, 2);
}
}
painter->restore();
}
QSize RelatedPacketDelegate::sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
/* This prevents the sizeHint for the delegate, if multiple lines are being selected */
if (mainApp && mainApp->mainWindow())
{
MainWindow * mw = qobject_cast<MainWindow *>(mainApp->mainWindow());
if (mw && mw->selectedRows().count() > 1)
return QStyledItemDelegate::sizeHint(option, index);
}
return QSize(option.fontMetrics.height() + QStyledItemDelegate::sizeHint(option, index).width(),
QStyledItemDelegate::sizeHint(option, index).height());
}
void RelatedPacketDelegate::drawArrow(QPainter *painter, const QPoint tail, const QPoint head, int head_size) const
{
int x_mul = head.x() > tail.x() ? -1 : 1;
QPoint head_points[] = {
head,
QPoint(head.x() + (head_size * x_mul), head.y() + (head_size / 2)),
QPoint(head.x() + (head_size * x_mul), head.y() - (head_size / 2)),
};
painter->drawLine(tail.x(), tail.y(), head.x() + (head_size * x_mul), head.y());
painter->drawPolygon(head_points, 3);
}
void RelatedPacketDelegate::drawChevrons(QPainter *painter, const QPoint tail, const QPoint head, int head_size) const
{
int x_mul = head.x() > tail.x() ? -1 : 1;
QPoint head_points1[] = {
head,
QPoint(head.x() + (head_size * x_mul), head.y() + (head_size / 2)),
QPoint(head.x() + (head_size * x_mul), head.y() - (head_size / 2)),
};
QPoint head2(head.x() + (head_size * x_mul), head.y());
QPoint head_points2[] = {
head2,
QPoint(head2.x() + (head_size * x_mul), head2.y() + (head_size / 2)),
QPoint(head2.x() + (head_size * x_mul), head2.y() - (head_size / 2)),
};
painter->drawPolygon(head_points1, 3);
painter->drawPolygon(head_points2, 3);
}
void RelatedPacketDelegate::drawCheckMark(QPainter *painter, const QRect bbox) const
{
QPoint cm_points[] = {
QPoint(bbox.x(), bbox.y() + (bbox.height() / 2)),
QPoint(bbox.x() + (bbox.width() / 4), bbox.y() + (bbox.height() * 3 / 4)),
bbox.topRight()
};
painter->drawPolyline(cm_points, 3);
}
void RelatedPacketDelegate::clear()
{
related_frames_.clear();
current_frame_ = 0;
conv_ = NULL;
}
void RelatedPacketDelegate::setCurrentFrame(guint32 current_frame)
{
current_frame_ = current_frame;
foreach (ft_framenum_type_t framenum_type, related_frames_) {
addRelatedFrame(-1, framenum_type); /* No need to check if this element belongs to the hash... */
}
}
void RelatedPacketDelegate::addRelatedFrame(int frame_num, ft_framenum_type_t framenum_type)
{
if (frame_num != -1 && !related_frames_.contains(frame_num))
related_frames_[frame_num] = framenum_type;
// Last match wins. Last match might not make sense, however.
if (current_frame_ > 0) {
switch (framenum_type) {
case FT_FRAMENUM_REQUEST:
related_frames_[current_frame_] = FT_FRAMENUM_RESPONSE;
break;
case FT_FRAMENUM_RESPONSE:
related_frames_[current_frame_] = FT_FRAMENUM_REQUEST;
break;
default:
break;
}
}
}
void RelatedPacketDelegate::setConversation(conversation *conv)
{
conv_ = conv;
} |
C/C++ | wireshark/ui/qt/models/related_packet_delegate.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef RELATED_PACKET_DELEGATE_H
#define RELATED_PACKET_DELEGATE_H
#include <config.h>
#include "epan/conversation.h"
#include <QHash>
#include <QStyledItemDelegate>
class QPainter;
struct conversation;
class RelatedPacketDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
RelatedPacketDelegate(QWidget *parent = 0);
void clear();
void setCurrentFrame(guint32 current_frame);
void setConversation(struct conversation *conv);
public slots:
void addRelatedFrame(int frame_num, ft_framenum_type_t framenum_type = FT_FRAMENUM_NONE);
protected:
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const;
QSize sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const;
private:
QHash<int, ft_framenum_type_t> related_frames_;
struct conversation *conv_;
guint32 current_frame_;
void drawArrow(QPainter *painter, const QPoint tail, const QPoint head, int head_size) const;
void drawChevrons(QPainter *painter, const QPoint tail, const QPoint head, int head_size) const;
void drawCheckMark(QPainter *painter, const QRect bbox) const;
};
#endif // RELATED_PACKET_DELEGATE_H |
C++ | wireshark/ui/qt/models/resolved_addresses_models.cpp | /* resolved_addresses_models.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/resolved_addresses_models.h>
#include <glib.h>
#include "file.h"
#include "epan/addr_resolv.h"
#include <wiretap/wtap.h>
extern "C"
{
static void
serv_port_hash_to_qstringlist(gpointer key, gpointer value, gpointer member_ptr)
{
PortsModel *model = static_cast<PortsModel *>(member_ptr);
serv_port_t *serv_port = (serv_port_t *)value;
guint port = GPOINTER_TO_UINT(key);
if (serv_port->tcp_name) {
QStringList entries;
entries << serv_port->tcp_name;
entries << QString::number(port);
entries << "tcp";
model->appendRow(entries);
}
if (serv_port->udp_name) {
QStringList entries;
entries << serv_port->udp_name;
entries << QString::number(port);
entries << "udp";
model->appendRow(entries);
}
if (serv_port->sctp_name) {
QStringList entries;
entries << serv_port->sctp_name;
entries << QString::number(port);
entries << "sctp";
model->appendRow(entries);
}
if (serv_port->dccp_name) {
QStringList entries;
entries << serv_port->dccp_name;
entries << QString::number(port);
entries << "dccp";
model->appendRow(entries);
}
}
static void
ipv4_hash_table_resolved_to_list(gpointer, gpointer value, gpointer sl_ptr)
{
QList<QStringList> *hosts = (QList<QStringList> *) sl_ptr;
hashipv4_t *ipv4_hash_table_entry = (hashipv4_t *) value;
if ((ipv4_hash_table_entry->flags & NAME_RESOLVED)) {
*hosts << (QStringList() << QString(ipv4_hash_table_entry->ip) << QString(ipv4_hash_table_entry->name));
}
}
static void
ipv6_hash_table_resolved_to_list(gpointer, gpointer value, gpointer sl_ptr)
{
QList<QStringList> *hosts = (QList<QStringList> *) sl_ptr;
hashipv6_t *ipv6_hash_table_entry = (hashipv6_t *) value;
if ((ipv6_hash_table_entry->flags & NAME_RESOLVED)) {
*hosts << (QStringList() << QString(ipv6_hash_table_entry->ip6) << QString(ipv6_hash_table_entry->name));
}
}
static void
eth_hash_to_qstringlist(gpointer, gpointer value, gpointer sl_ptr)
{
QStringList *string_list = (QStringList *) sl_ptr;
hashether_t* tp = (hashether_t*)value;
QString entry = QString(get_hash_ether_hexaddr(tp)) + QString(" ") + get_hash_ether_resolved_name(tp);
*string_list << entry;
}
static void
manuf_hash_to_qstringlist(gpointer key, gpointer value, gpointer sl_ptr)
{
QStringList *string_list = (QStringList *) sl_ptr;
hashmanuf_t *manuf = (hashmanuf_t*)value;
guint eth_as_guint = GPOINTER_TO_UINT(key);
QString entry = QString("%1:%2:%3 %4")
.arg((eth_as_guint >> 16 & 0xff), 2, 16, QChar('0'))
.arg((eth_as_guint >> 8 & 0xff), 2, 16, QChar('0'))
.arg((eth_as_guint & 0xff), 2, 16, QChar('0'))
.arg(get_hash_manuf_resolved_name(manuf));
*string_list << entry;
}
static void
wka_hash_to_qstringlist(gpointer key, gpointer value, gpointer sl_ptr)
{
QStringList *string_list = (QStringList *) sl_ptr;
gchar *name = (gchar *)value;
guint8 *eth_addr = (guint8*)key;
QString entry = QString("%1:%2:%3:%4:%5:%6 %7")
.arg(eth_addr[0], 2, 16, QChar('0'))
.arg(eth_addr[1], 2, 16, QChar('0'))
.arg(eth_addr[2], 2, 16, QChar('0'))
.arg(eth_addr[3], 2, 16, QChar('0'))
.arg(eth_addr[4], 2, 16, QChar('0'))
.arg(eth_addr[5], 2, 16, QChar('0'))
.arg(name);
*string_list << entry;
}
}
EthernetAddressModel::EthernetAddressModel(QObject * parent):
AStringListListModel(parent)
{
populate();
}
QStringList EthernetAddressModel::headerColumns() const
{
return QStringList() << tr("Type") << tr("Address") << tr("Name");
}
QStringList EthernetAddressModel::filterValues() const
{
return QStringList()
<< tr("All entries")
<< tr("Hosts")
<< tr("Ethernet Addresses") << tr("Ethernet Manufacturers")
<< tr("Ethernet Well-Known Addresses");
}
void EthernetAddressModel::populate()
{
QList<QStringList> hosts; // List of (address, names)
if (wmem_map_t *ipv4_hash_table = get_ipv4_hash_table()) {
wmem_map_foreach(ipv4_hash_table, ipv4_hash_table_resolved_to_list, &hosts);
}
if (wmem_map_t *ipv6_hash_table = get_ipv6_hash_table()) {
wmem_map_foreach(ipv6_hash_table, ipv6_hash_table_resolved_to_list, &hosts);
}
const QString &hosts_label = tr("Hosts");
foreach (const QStringList &addr_name, hosts)
appendRow(QStringList() << hosts_label << addr_name);
QStringList values;
if (wmem_map_t *eth_hashtable = get_eth_hashtable()) {
wmem_map_foreach(eth_hashtable, eth_hash_to_qstringlist, &values);
}
const QString ð_label = tr("Ethernet Addresses");
foreach (const QString &line, values)
appendRow(QStringList() << eth_label << line.split(" "));
values.clear();
if (wmem_map_t *eth_hashtable = get_manuf_hashtable()) {
wmem_map_foreach(eth_hashtable, manuf_hash_to_qstringlist, &values);
}
const QString &manuf_label = tr("Ethernet Manufacturers");
foreach (const QString &line, values)
appendRow(QStringList() << manuf_label << line.split(" "));
values.clear();
if (wmem_map_t *eth_hashtable = get_wka_hashtable()) {
wmem_map_foreach(eth_hashtable, wka_hash_to_qstringlist, &values);
}
const QString &wka_label = tr("Ethernet Well-Known Addresses");
foreach (const QString &line, values)
appendRow(QStringList() << wka_label << line.split(" "));
}
PortsModel::PortsModel(QObject * parent):
AStringListListModel(parent)
{
populate();
}
QStringList PortsModel::filterValues() const
{
return QStringList()
<< tr("All entries") << tr("tcp") << tr("udp") << tr("sctp") << tr("dccp");
}
QStringList PortsModel::headerColumns() const
{
return QStringList() << tr("Name") << tr("Port") << tr("Type");
}
void PortsModel::populate()
{
wmem_map_t *serv_port_hashtable = get_serv_port_hashtable();
if (serv_port_hashtable) {
wmem_map_foreach(serv_port_hashtable, serv_port_hash_to_qstringlist, this);
}
} |
C/C++ | wireshark/ui/qt/models/resolved_addresses_models.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef RESOLVED_ADDRESSES_MODELS_H
#define RESOLVED_ADDRESSES_MODELS_H
#include <ui/qt/models/astringlist_list_model.h>
#include <QAbstractListModel>
#include <QSortFilterProxyModel>
class EthernetAddressModel : public AStringListListModel
{
Q_OBJECT
public:
EthernetAddressModel(QObject * parent = Q_NULLPTR);
QStringList filterValues() const;
protected:
QStringList headerColumns() const override;
void populate();
};
class PortsModel : public AStringListListModel
{
Q_OBJECT
public:
PortsModel(QObject * parent = Q_NULLPTR);
QStringList filterValues() const;
protected:
QStringList headerColumns() const override;
void populate();
};
#endif // RESOLVED_ADDRESSES_MODELS_H |
C++ | wireshark/ui/qt/models/sparkline_delegate.cpp | /* sparkline_delegate.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/sparkline_delegate.h>
#include <QPainter>
#include <QApplication>
#define SPARKLINE_MIN_EM_WIDTH 10
void SparkLineDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QList<int> points = qvariant_cast<QList<int> >(index.data(Qt::UserRole));
int max = 1;
// We typically draw a sparkline alongside some text. Size our
// drawing area based on an Em width. and a bit of eyballing on
// Linux, macOS, and Windows.
int em_w = option.fontMetrics.height();
int content_w = option.rect.width() - (em_w / 4);
int content_h = option.fontMetrics.ascent() - 1;
int val;
qreal idx = 0.0;
qreal step_w = em_w / 10.0;
qreal steps = content_w / step_w;
QVector<QPointF> fpoints;
QStyledItemDelegate::paint(painter, option, index);
if (points.isEmpty() || steps < 1.0 || content_h <= 0) {
return;
}
while ((qreal) points.length() > steps) {
points.removeFirst();
}
foreach (val, points) {
if (val > max) max = val;
}
foreach (val, points) {
fpoints.append(QPointF(idx, (qreal) content_h - (val * content_h / max)));
idx = idx + step_w;
}
QStyleOptionViewItem option_vi = option;
QStyledItemDelegate::initStyleOption(&option_vi, index);
painter->save();
if (QApplication::style()->objectName().contains("vista")) {
// QWindowsVistaStyle::drawControl does this internally. Unfortunately there
// doesn't appear to be a more general way to do this.
option_vi.palette.setColor(QPalette::All, QPalette::HighlightedText, option_vi.palette.color(QPalette::Active, QPalette::Text));
}
QPalette::ColorGroup cg = option_vi.state & QStyle::State_Enabled
? QPalette::Normal : QPalette::Disabled;
if (cg == QPalette::Normal && !(option_vi.state & QStyle::State_Active))
cg = QPalette::Inactive;
#if defined(Q_OS_WIN)
if (option_vi.state & QStyle::State_Selected) {
#else
if ((option_vi.state & QStyle::State_Selected) && !(option_vi.state & QStyle::State_MouseOver)) {
#endif
painter->setPen(option_vi.palette.color(cg, QPalette::HighlightedText));
} else {
painter->setPen(option_vi.palette.color(cg, QPalette::Text));
}
// As a general rule, aliased painting renders to pixels and
// antialiased painting renders to mathematical coordinates:
// https://doc.qt.io/qt-5/coordsys.html
// Shift our coordinates by 0.5 pixels, otherwise our lines end
// up blurry.
painter->setRenderHint(QPainter::Antialiasing, true);
painter->translate(
option.rect.x() + (em_w / 8) + 0.5,
option.rect.y() + ((option.rect.height() - option.fontMetrics.height()) / 2) + 1 + 0.5);
painter->drawPolyline(QPolygonF(fpoints));
// Some sparklines are decorated with dots at the beginning and end.
// Ours look better without in my (gcc) opinion.
// painter->setPen(Qt::NoPen);
// painter->setBrush(option.palette.foreground());
// painter->drawEllipse(fpoints.first(), 2, 2);
// painter->setBrush(Qt::red);
// painter->drawEllipse(fpoints.last(), 2, 2);
painter->restore();
}
QSize SparkLineDelegate::sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const {
return QSize(option.fontMetrics.height() * SPARKLINE_MIN_EM_WIDTH, QStyledItemDelegate::sizeHint(option, index).height());
}
QWidget *SparkLineDelegate::createEditor(QWidget *, const QStyleOptionViewItem &, const QModelIndex &) const
{
return NULL;
} |
C/C++ | wireshark/ui/qt/models/sparkline_delegate.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef SPARKLINE_DELEGATE_H
#define SPARKLINE_DELEGATE_H
#include <QStyledItemDelegate>
class SparkLineDelegate : public QStyledItemDelegate
{
public:
SparkLineDelegate(QWidget *parent = 0) : QStyledItemDelegate(parent) {}
protected:
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const;
QSize sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const;
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
signals:
public slots:
};
Q_DECLARE_METATYPE(QList<int>)
#endif // SPARKLINE_DELEGATE_H |
C++ | wireshark/ui/qt/models/supported_protocols_model.cpp | /* supported_protocols_model.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <QSortFilterProxyModel>
#include <QStringList>
#include <QPalette>
#include <QApplication>
#include <QBrush>
#include <QRegularExpression>
#include <ui/qt/models/supported_protocols_model.h>
SupportedProtocolsItem::SupportedProtocolsItem(protocol_t* proto, const char *name, const char* filter, ftenum_t ftype, const char* descr, SupportedProtocolsItem* parent)
: ModelHelperTreeItem<SupportedProtocolsItem>(parent),
proto_(proto),
name_(name),
filter_(filter),
ftype_(ftype),
descr_(descr)
{
}
SupportedProtocolsItem::~SupportedProtocolsItem()
{
}
SupportedProtocolsModel::SupportedProtocolsModel(QObject *parent) :
QAbstractItemModel(parent),
root_(new SupportedProtocolsItem(NULL, NULL, NULL, FT_NONE, NULL, NULL)),
field_count_(0)
{
}
SupportedProtocolsModel::~SupportedProtocolsModel()
{
delete root_;
}
int SupportedProtocolsModel::rowCount(const QModelIndex &parent) const
{
SupportedProtocolsItem *parent_item;
if (parent.column() > 0)
return 0;
if (!parent.isValid())
parent_item = root_;
else
parent_item = static_cast<SupportedProtocolsItem*>(parent.internalPointer());
if (parent_item == NULL)
return 0;
return parent_item->childCount();
}
int SupportedProtocolsModel::columnCount(const QModelIndex&) const
{
return colLast;
}
QVariant SupportedProtocolsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
switch ((enum SupportedProtocolsColumn)section) {
case colName:
return tr("Name");
case colFilter:
return tr("Filter");
case colType:
return tr("Type");
case colDescription:
return tr("Description");
default:
break;
}
}
return QVariant();
}
QModelIndex SupportedProtocolsModel::parent(const QModelIndex& index) const
{
if (!index.isValid())
return QModelIndex();
SupportedProtocolsItem* item = static_cast<SupportedProtocolsItem*>(index.internalPointer());
if (item != NULL) {
SupportedProtocolsItem* parent_item = item->parentItem();
if (parent_item != NULL) {
if (parent_item == root_)
return QModelIndex();
return createIndex(parent_item->row(), 0, parent_item);
}
}
return QModelIndex();
}
QModelIndex SupportedProtocolsModel::index(int row, int column, const QModelIndex& parent) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
SupportedProtocolsItem *parent_item, *child_item;
if (!parent.isValid())
parent_item = root_;
else
parent_item = static_cast<SupportedProtocolsItem*>(parent.internalPointer());
Q_ASSERT(parent_item);
child_item = parent_item->child(row);
if (child_item) {
return createIndex(row, column, child_item);
}
return QModelIndex();
}
QVariant SupportedProtocolsModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || role != Qt::DisplayRole)
return QVariant();
SupportedProtocolsItem* item = static_cast<SupportedProtocolsItem*>(index.internalPointer());
if (item == NULL)
return QVariant();
switch ((enum SupportedProtocolsColumn)index.column()) {
case colName:
return item->name();
case colFilter:
return item->filter();
case colType:
if (index.parent().isValid())
return QString(ftype_pretty_name(item->type()));
return QVariant();
case colDescription:
return item->description();
default:
break;
}
return QVariant();
}
void SupportedProtocolsModel::populate()
{
void *proto_cookie;
void *field_cookie;
beginResetModel();
SupportedProtocolsItem *protoItem, *fieldItem;
protocol_t *protocol;
for (int proto_id = proto_get_first_protocol(&proto_cookie); proto_id != -1;
proto_id = proto_get_next_protocol(&proto_cookie)) {
protocol = find_protocol_by_id(proto_id);
protoItem = new SupportedProtocolsItem(protocol, proto_get_protocol_short_name(protocol), proto_get_protocol_filter_name(proto_id), FT_PROTOCOL, proto_get_protocol_long_name(protocol), root_);
root_->prependChild(protoItem);
for (header_field_info *hfinfo = proto_get_first_protocol_field(proto_id, &field_cookie); hfinfo != NULL;
hfinfo = proto_get_next_protocol_field(proto_id, &field_cookie)) {
if (hfinfo->same_name_prev_id != -1)
continue;
fieldItem = new SupportedProtocolsItem(protocol, hfinfo->name, hfinfo->abbrev, hfinfo->type, hfinfo->blurb, protoItem);
protoItem->prependChild(fieldItem);
field_count_++;
}
}
endResetModel();
}
SupportedProtocolsProxyModel::SupportedProtocolsProxyModel(QObject * parent)
: QSortFilterProxyModel(parent),
filter_()
{
}
bool SupportedProtocolsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
{
//Use SupportedProtocolsItem directly for better performance
SupportedProtocolsItem* left_item = static_cast<SupportedProtocolsItem*>(left.internalPointer());
SupportedProtocolsItem* right_item = static_cast<SupportedProtocolsItem*>(right.internalPointer());
if ((left_item != NULL) && (right_item != NULL)) {
int compare_ret = left_item->name().compare(right_item->name());
if (compare_ret < 0)
return true;
}
return false;
}
bool SupportedProtocolsProxyModel::filterAcceptItem(SupportedProtocolsItem& item) const
{
QRegularExpression regex(filter_, QRegularExpression::CaseInsensitiveOption);
if (! regex.isValid())
return false;
if (item.name().contains(regex))
return true;
if (item.filter().contains(regex))
return true;
if (item.description().contains(regex))
return true;
return false;
}
bool SupportedProtocolsProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
QModelIndex nameIdx = sourceModel()->index(sourceRow, SupportedProtocolsModel::colName, sourceParent);
SupportedProtocolsItem* item = static_cast<SupportedProtocolsItem*>(nameIdx.internalPointer());
if (item == NULL)
return true;
if (!filter_.isEmpty()) {
if (filterAcceptItem(*item))
return true;
if (!nameIdx.parent().isValid())
{
SupportedProtocolsItem* child_item;
for (int row = 0; row < item->childCount(); row++)
{
child_item = item->child(row);
if ((child_item != NULL) && (filterAcceptItem(*child_item)))
return true;
}
}
return false;
}
return true;
}
void SupportedProtocolsProxyModel::setFilter(const QString& filter)
{
filter_ = filter;
invalidateFilter();
} |
C/C++ | wireshark/ui/qt/models/supported_protocols_model.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef SUPPORTED_PROTOCOLS_MODEL_H
#define SUPPORTED_PROTOCOLS_MODEL_H
#include <config.h>
#include <ui/qt/models/tree_model_helpers.h>
#include <epan/proto.h>
#include <QSortFilterProxyModel>
class SupportedProtocolsItem : public ModelHelperTreeItem<SupportedProtocolsItem>
{
public:
SupportedProtocolsItem(protocol_t* proto, const char *name, const char* filter, ftenum_t ftype, const char* descr, SupportedProtocolsItem* parent);
virtual ~SupportedProtocolsItem();
protocol_t* protocol() const {return proto_; }
QString name() const { return name_; }
ftenum_t type() const {return ftype_; }
QString filter() const { return filter_; }
QString description() const { return descr_; }
private:
protocol_t* proto_;
QString name_;
QString filter_;
ftenum_t ftype_;
QString descr_;
};
class SupportedProtocolsModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit SupportedProtocolsModel(QObject * parent = Q_NULLPTR);
virtual ~SupportedProtocolsModel();
enum SupportedProtocolsColumn {
colName = 0,
colFilter,
colType,
colDescription,
colLast
};
int fieldCount() {return field_count_;}
QModelIndex index(int row, int column,
const QModelIndex & = QModelIndex()) const;
QModelIndex parent(const QModelIndex &) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
void populate();
private:
SupportedProtocolsItem* root_;
int field_count_;
};
class SupportedProtocolsProxyModel : public QSortFilterProxyModel
{
public:
explicit SupportedProtocolsProxyModel(QObject * parent = Q_NULLPTR);
virtual bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
void setFilter(const QString& filter);
protected:
bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const;
bool filterAcceptItem(SupportedProtocolsItem& item) const;
private:
QString filter_;
};
#endif // SUPPORTED_PROTOCOLS_MODEL_H |
C++ | wireshark/ui/qt/models/timeline_delegate.cpp | /* timeline_delegate.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/timeline_delegate.h>
#include <ui/qt/models/atap_data_model.h>
#include <ui/qt/utils/color_utils.h>
#include <QApplication>
#include <QPainter>
#include <QTreeView>
#include <QAbstractProxyModel>
// XXX We might want to move this to conversation_dialog.cpp.
// PercentBarDelegate uses a stronger blend value, but its bars are also
// more of a prominent feature. Make the blend weaker here so that we don't
// obscure our text.
static const double bar_blend_ = 0.08;
TimelineDelegate::TimelineDelegate(QWidget *parent) :
QStyledItemDelegate(parent)
{
_dataRole = Qt::UserRole;
}
void TimelineDelegate::setDataRole(int dataRole)
{
_dataRole = dataRole;
}
void TimelineDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QStyleOptionViewItem option_vi = option;
QStyledItemDelegate::initStyleOption(&option_vi, index);
bool drawBar = false;
struct timeline_span span_px = index.data(_dataRole).value<struct timeline_span>();
if (_dataRole == ATapDataModel::TIMELINE_DATA) {
double span_s = span_px.maxRelTime - span_px.minRelTime;
QTreeView * tree = qobject_cast<QTreeView *>(parent());
if (tree) {
QAbstractProxyModel * proxy = qobject_cast<QAbstractProxyModel *>(tree->model());
if (proxy && proxy->sourceModel()) {
QModelIndex indexStart = proxy->mapFromSource(proxy->sourceModel()->index(0, span_px.colStart));
int colStart = -1;
int start_px = 0;
if (indexStart.isValid()) {
colStart = indexStart.column();
start_px = tree->columnWidth(colStart);
}
int colDuration = -1;
int column_px = start_px;
QModelIndex indexDuration = proxy->mapFromSource(proxy->sourceModel()->index(0, span_px.colDuration));
if (indexDuration.isValid()) {
colDuration = indexDuration.column();
column_px += tree->columnWidth(colDuration);
}
span_px.start = ((span_px.startTime - span_px.minRelTime) * column_px) / span_s;
span_px.width = ((span_px.stopTime - span_px.startTime) * column_px) / span_s;
if (index.column() == colStart) {
drawBar = true;
} else if (index.column() == colDuration) {
drawBar = true;
span_px.start -= start_px;
}
}
}
}
if (!drawBar) {
QStyledItemDelegate::paint(painter, option, index);
return;
}
// Paint our rect with no text using the current style, then draw our
// bar and text over it.
option_vi.text = QString();
QStyle *style = option_vi.widget ? option_vi.widget->style() : QApplication::style();
style->drawControl(QStyle::CE_ItemViewItem, &option_vi, painter, option_vi.widget);
if (QApplication::style()->objectName().contains("vista")) {
// QWindowsVistaStyle::drawControl does this internally. Unfortunately there
// doesn't appear to be a more general way to do this.
option_vi.palette.setColor(QPalette::All, QPalette::HighlightedText,
option_vi.palette.color(QPalette::Active, QPalette::Text));
}
QPalette::ColorGroup cg = option_vi.state & QStyle::State_Enabled
? QPalette::Normal : QPalette::Disabled;
QColor text_color = option_vi.palette.color(cg, QPalette::Text);
QColor bar_color = ColorUtils::alphaBlend(option_vi.palette.windowText(),
option_vi.palette.window(), bar_blend_);
if (cg == QPalette::Normal && !(option_vi.state & QStyle::State_Active))
cg = QPalette::Inactive;
if (option_vi.state & QStyle::State_Selected) {
text_color = option_vi.palette.color(cg, QPalette::HighlightedText);
bar_color = ColorUtils::alphaBlend(option_vi.palette.color(cg, QPalette::Window),
option_vi.palette.color(cg, QPalette::Highlight),
bar_blend_);
}
painter->save();
int border_radius = 3; // We use 3 px elsewhere, e.g. filter combos.
QRect timeline_rect = option.rect;
timeline_rect.adjust(span_px.start, 1, 0, -1);
timeline_rect.setWidth(span_px.width);
painter->setClipRect(option.rect);
painter->setPen(Qt::NoPen);
painter->setBrush(bar_color);
painter->drawRoundedRect(timeline_rect, border_radius, border_radius);
painter->restore();
painter->save();
painter->setPen(text_color);
painter->drawText(option.rect, Qt::AlignCenter, index.data(Qt::DisplayRole).toString());
painter->restore();
} |
C/C++ | wireshark/ui/qt/models/timeline_delegate.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef TIMELINE_DELEGATE_H
#define TIMELINE_DELEGATE_H
/*
* @file Timeline delegate.
*
* QStyledItemDelegate subclass that will draw a timeline indicator for
* the specified value.
*
* This is intended to be used in QTreeWidgets to show timelines, e.g. for
* conversations.
* To use it, first call setItemDelegate:
*
* myTreeWidget()->setItemDelegateForColumn(col_time_start_, new TimelineDelegate());
*
* Then, for each QTreeWidgetItem, set or return a timeline_span for the start and end
* of the timeline in pixels relative to the column width.
*
* setData(col_start_, Qt::UserRole, start_span);
* setData(col_end_, Qt::UserRole, end_span);
*
*/
#include <QStyledItemDelegate>
// Pixels are relative to item rect and will be clipped.
struct timeline_span {
int start;
int width;
double startTime;
double stopTime;
double minRelTime;
double maxRelTime;
int colStart;
int colDuration;
};
Q_DECLARE_METATYPE(timeline_span)
class TimelineDelegate : public QStyledItemDelegate
{
public:
TimelineDelegate(QWidget *parent = 0);
void setDataRole(int role);
protected:
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const;
private:
int _dataRole;
};
#endif // TIMELINE_DELEGATE_H |
C/C++ | wireshark/ui/qt/models/tree_model_helpers.h | /** @file
*
* Utility template classes for basic tree model functionality
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef TREE_MODEL_HELPERS_H
#define TREE_MODEL_HELPERS_H
#include <config.h>
#include <ui/qt/utils/variant_pointer.h>
#include <QAbstractItemModel>
//Base class to inherit basic tree item from
template <typename Item>
class ModelHelperTreeItem
{
public:
ModelHelperTreeItem(Item* parent)
: parent_(parent)
{
}
virtual ~ModelHelperTreeItem()
{
for (int row = 0; row < childItems_.count(); row++)
{
delete VariantPointer<Item>::asPtr(childItems_.value(row));
}
childItems_.clear();
}
void appendChild(Item* child)
{
childItems_.append(VariantPointer<Item>::asQVariant(child));
}
void prependChild(Item* child)
{
childItems_.prepend(VariantPointer<Item>::asQVariant(child));
}
void insertChild(int row, Item* child)
{
childItems_.insert(row, VariantPointer<Item>::asQVariant(child));
}
void removeChild(int row)
{
delete VariantPointer<Item>::asPtr(childItems_.value(row));
childItems_.removeAt(row);
}
Item* child(int row)
{
return VariantPointer<Item>::asPtr(childItems_.value(row));
}
int childCount() const
{
return static_cast<int>(childItems_.count());
}
int row()
{
if (parent_)
{
return static_cast<int>(parent_->childItems_.indexOf(VariantPointer<Item>::asQVariant((Item *)this)));
}
return 0;
}
Item* parentItem() {return parent_; }
protected:
Item* parent_;
QList<QVariant> childItems_;
};
#endif // TREE_MODEL_HELPERS_H |
C++ | wireshark/ui/qt/models/uat_delegate.cpp | /* uat_delegate.cpp
* Delegates for editing various field types in a UAT record.
*
* Copyright 2016 Peter Wu <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/uat_delegate.h>
#include <epan/packet.h> // for get_dissector_names()
#include "epan/value_string.h"
#include <wsutil/ws_assert.h>
#include <QRegularExpression>
#include <QComboBox>
#include <QEvent>
#include <QFileDialog>
#include <QLineEdit>
#include <QCheckBox>
#include <QColorDialog>
#include <ui/qt/widgets/display_filter_edit.h>
#include <ui/qt/widgets/dissector_syntax_line_edit.h>
#include <ui/qt/widgets/field_filter_edit.h>
#include <ui/qt/widgets/editor_file_dialog.h>
#include <ui/qt/widgets/path_selection_edit.h>
// The Qt docs suggest overriding updateEditorGeometry, but the
// defaults seem sane.
UatDelegate::UatDelegate(QObject *parent) : QStyledItemDelegate(parent)
{
}
uat_field_t *UatDelegate::indexToField(const QModelIndex &index) const
{
const QVariant v = index.model()->data(index, Qt::UserRole);
return static_cast<uat_field_t *>(v.value<void *>());
}
QWidget *UatDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
uat_field_t *field = indexToField(index);
QWidget *editor = nullptr;
switch (field->mode) {
case PT_TXTMOD_DIRECTORYNAME:
case PT_TXTMOD_FILENAME:
if (index.isValid()) {
QString filename_old = index.model()->data(index, Qt::EditRole).toString();
PathSelectionEdit * pathEdit = new PathSelectionEdit(field->title, QString(), field->mode != PT_TXTMOD_DIRECTORYNAME, parent);
connect(pathEdit, &PathSelectionEdit::pathChanged, this, &UatDelegate::pathHasChanged);
return pathEdit;
}
break;
case PT_TXTMOD_COLOR:
if (index.isValid()) {
QColor color(index.model()->data(index, Qt::DecorationRole).toString());
QColorDialog * colorDialog = new QColorDialog(color, parent);
// Don't fall through and set setAutoFillBackground(true)
return colorDialog;
}
break;
case PT_TXTMOD_ENUM:
{
// Note: the string repr. is written, not the integer value.
QComboBox *cb_editor = new QComboBox(parent);
const value_string *enum_vals = (const value_string *)field->fld_data;
for (int i = 0; enum_vals[i].strptr != nullptr; i++) {
cb_editor->addItem(enum_vals[i].strptr);
}
editor = cb_editor;
cb_editor->setMinimumWidth(cb_editor->minimumSizeHint().width());
break;
}
case PT_TXTMOD_DISSECTOR:
{
editor = new DissectorSyntaxLineEdit(parent);
break;
}
case PT_TXTMOD_STRING:
// TODO add a live validator? Should SyntaxLineEdit be used?
editor = QStyledItemDelegate::createEditor(parent, option, index);
break;
case PT_TXTMOD_DISPLAY_FILTER:
editor = new DisplayFilterEdit(parent);
break;
case PT_TXTMOD_PROTO_FIELD:
editor = new FieldFilterEdit(parent);
break;
case PT_TXTMOD_HEXBYTES:
{
// Requires input of the form "ab cd ef" (with possibly no or a colon
// separator instead of a single whitespace) for the editor to accept.
QRegularExpression hexbytes_regex("([0-9a-f]{2}[ :]?)*");
hexbytes_regex.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
// QString types from QStyledItemDelegate are documented to return a
// QLineEdit. Note that Qt returns a subclass from QLineEdit which
// automatically adapts the width to the typed contents.
QLineEdit *le_editor = static_cast<QLineEdit *>(
QStyledItemDelegate::createEditor(parent, option, index));
le_editor->setValidator(new QRegularExpressionValidator(hexbytes_regex, le_editor));
editor = le_editor;
break;
}
case PT_TXTMOD_BOOL:
// model will handle creating checkbox
break;
case PT_TXTMOD_NONE:
break;
default:
ws_assert_not_reached();
break;
}
if (editor) {
editor->setAutoFillBackground(true);
}
return editor;
}
void UatDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
uat_field_t *field = indexToField(index);
switch (field->mode) {
case PT_TXTMOD_DIRECTORYNAME:
case PT_TXTMOD_FILENAME:
if (index.isValid() && qobject_cast<PathSelectionEdit *>(editor))
qobject_cast<PathSelectionEdit *>(editor)->setPath(index.model()->data(index, Qt::EditRole).toString());
break;
case PT_TXTMOD_ENUM:
{
QComboBox *combobox = static_cast<QComboBox *>(editor);
const QString &data = index.model()->data(index, Qt::EditRole).toString();
combobox->setCurrentText(data);
break;
}
case PT_TXTMOD_COLOR:
{
if (qobject_cast<QColorDialog *>(editor))
{
QColor color(index.model()->data(index, Qt::DecorationRole).toString());
qobject_cast<QColorDialog *>(editor)->setCurrentColor(color);
}
break;
}
default:
QStyledItemDelegate::setEditorData(editor, index);
}
}
void UatDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
uat_field_t *field = indexToField(index);
switch (field->mode) {
case PT_TXTMOD_DIRECTORYNAME:
case PT_TXTMOD_FILENAME:
if (index.isValid() && qobject_cast<PathSelectionEdit *>(editor))
const_cast<QAbstractItemModel *>(index.model())->setData(index, qobject_cast<PathSelectionEdit *>(editor)->path(), Qt::EditRole);
break;
case PT_TXTMOD_ENUM:
{
QComboBox *combobox = static_cast<QComboBox *>(editor);
const QString &data = combobox->currentText();
model->setData(index, data, Qt::EditRole);
break;
}
case PT_TXTMOD_COLOR:
//do nothing, dialog signals will update table
if (qobject_cast<QColorDialog *>(editor))
{
QColor newColor = qobject_cast<QColorDialog *>(editor)->currentColor();
const_cast<QAbstractItemModel *>(index.model())->setData(index, newColor.name(), Qt::EditRole);
}
break;
default:
QStyledItemDelegate::setModelData(editor, model, index);
}
}
void UatDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
uat_field_t *field = indexToField(index);
switch (field->mode) {
case PT_TXTMOD_DIRECTORYNAME:
case PT_TXTMOD_FILENAME:
editor->setGeometry(option.rect);
break;
default:
QStyledItemDelegate::updateEditorGeometry(editor, option, index);
}
}
void UatDelegate::pathHasChanged(QString)
{
PathSelectionEdit * editor = qobject_cast<PathSelectionEdit *>(sender());
if (editor)
emit commitData(editor);
} |
C/C++ | wireshark/ui/qt/models/uat_delegate.h | /** @file
*
* Delegates for editing various field types in a UAT record.
*
* Copyright 2016 Peter Wu <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef UAT_DELEGATE_H
#define UAT_DELEGATE_H
#include <config.h>
#include <glib.h>
#include <epan/uat-int.h>
#include <QStyledItemDelegate>
#include <QModelIndex>
class UatDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
UatDelegate(QObject *parent = 0);
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
void setEditorData(QWidget *editor, const QModelIndex &index) const override;
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override;
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
protected slots:
void pathHasChanged(QString newPath);
private:
uat_field_t *indexToField(const QModelIndex &index) const;
};
#endif // UAT_DELEGATE_H |
C++ | wireshark/ui/qt/models/uat_model.cpp | /* uat_model.cpp
* Data model for UAT records.
*
* Copyright 2016 Peter Wu <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "uat_model.h"
#include <epan/to_str.h>
#include <QBrush>
#include <QDebug>
UatModel::UatModel(QObject *parent, epan_uat *uat) :
QAbstractTableModel(parent),
uat_(0)
{
loadUat(uat);
}
UatModel::UatModel(QObject * parent, QString tableName) :
QAbstractTableModel(parent),
uat_(0)
{
loadUat(uat_get_table_by_name(tableName.toStdString().c_str()));
}
void UatModel::loadUat(epan_uat * uat)
{
uat_ = uat;
dirty_records.reserve(uat_->raw_data->len);
// Validate existing data such that they can be marked as invalid if necessary.
record_errors.reserve(uat_->raw_data->len);
for (int i = 0; i < (int)uat_->raw_data->len; i++) {
record_errors.push_back(QMap<int, QString>());
checkRow(i);
// Assume that records are initially not modified.
dirty_records.push_back(false);
}
}
void UatModel::reloadUat()
{
beginResetModel();
loadUat(uat_);
endResetModel();
}
bool UatModel::applyChanges(QString &error)
{
if (uat_->changed) {
gchar *err = NULL;
if (!uat_save(uat_, &err)) {
error = QString("Error while saving %1: %2").arg(uat_->name).arg(err);
g_free(err);
}
if (uat_->post_update_cb) {
uat_->post_update_cb();
}
return true;
}
return false;
}
bool UatModel::revertChanges(QString &error)
{
// Ideally this model should remember the changes made and try to undo them
// to avoid calling post_update_cb. Calling uat_clear + uat_load is a lazy
// option and might fail (e.g. when the UAT file is removed).
if (uat_->changed) {
gchar *err = NULL;
uat_clear(uat_);
if (!uat_load(uat_, NULL, &err)) {
error = QString("Error while loading %1: %2").arg(uat_->name).arg(err);
g_free(err);
}
return true;
}
return false;
}
Qt::ItemFlags UatModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::ItemFlags();
uat_field_t *field = &uat_->fields[index.column()];
Qt::ItemFlags flags = QAbstractTableModel::flags(index);
if (field->mode == PT_TXTMOD_BOOL)
{
flags |= Qt::ItemIsUserCheckable;
}
flags |= Qt::ItemIsEditable;
return flags;
}
QVariant UatModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
void *rec = UAT_INDEX_PTR(uat_, index.row());
uat_field_t *field = &uat_->fields[index.column()];
if (role == Qt::DisplayRole || role == Qt::EditRole) {
char *str = NULL;
guint length = 0;
field->cb.tostr(rec, &str, &length, field->cbdata.tostr, field->fld_data);
switch (field->mode) {
case PT_TXTMOD_HEXBYTES:
{
char* temp_str = bytes_to_str(NULL, (const guint8 *) str, length);
g_free(str);
QString qstr(temp_str);
wmem_free(NULL, temp_str);
return qstr;
}
case PT_TXTMOD_BOOL:
case PT_TXTMOD_COLOR:
return QVariant();
default:
{
QString qstr(str);
g_free(str);
return qstr;
}
}
}
if ((role == Qt::CheckStateRole) && (field->mode == PT_TXTMOD_BOOL))
{
char *str = NULL;
guint length = 0;
enum Qt::CheckState state = Qt::Unchecked;
field->cb.tostr(rec, &str, &length, field->cbdata.tostr, field->fld_data);
if ((g_strcmp0(str, "TRUE") == 0) ||
(g_strcmp0(str, "Enabled") == 0))
state = Qt::Checked;
g_free(str);
return state;
}
if (role == Qt::UserRole) {
return QVariant::fromValue(static_cast<void *>(field));
}
const QMap<int, QString> &errors = record_errors[index.row()];
// mark fields that fail the validation.
if (role == Qt::BackgroundRole) {
if (errors.contains(index.column())) {
// TODO is it OK to color cells like this? Maybe some other marker is better?
return QBrush("pink");
}
return QVariant();
}
if ((role == Qt::DecorationRole) && (field->mode == PT_TXTMOD_COLOR)) {
char *str = NULL;
guint length = 0;
field->cb.tostr(rec, &str, &length, field->cbdata.tostr, field->fld_data);
return QColor(QString(str));
}
// expose error message if any.
if (role == Qt::UserRole + 1) {
if (errors.contains(index.column())) {
return errors[index.column()];
}
return QVariant();
}
return QVariant();
}
QModelIndex UatModel::findRowForColumnContent(QVariant columnContent, int columnToCheckAgainst, int role)
{
if (! columnContent.isValid())
return QModelIndex();
for (int i = 0; i < rowCount(); i++)
{
QVariant r_expr = data(index(i, columnToCheckAgainst), role);
if (r_expr == columnContent)
return index(i, columnToCheckAgainst);
}
return QModelIndex();
}
QVariant UatModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation != Qt::Horizontal) {
return QVariant();
}
if (role == Qt::ToolTipRole && uat_->fields[section].desc) {
return uat_->fields[section].desc;
}
if (role == Qt::DisplayRole) {
return uat_->fields[section].title;
}
return QVariant();
}
int UatModel::rowCount(const QModelIndex &parent) const
{
// there are no children
if (parent.isValid()) {
return 0;
}
return uat_->raw_data->len;
}
int UatModel::columnCount(const QModelIndex &parent) const
{
// there are no children
if (parent.isValid()) {
return 0;
}
return uat_->ncols;
}
QModelIndex UatModel::appendEntry(QVariantList rowData)
{
// Don't add an empty row, or a row with more entries than we have columns,
// but a row with fewer can be added, where the remaining entries are empty
if (rowData.count() == 0 || rowData.count() > columnCount())
return QModelIndex();
QModelIndex newIndex;
int row = rowCount();
emit beginInsertRows(QModelIndex(), row, row);
// Initialize with given values
void *record = g_malloc0(uat_->record_size);
for (int col = 0; col < columnCount(); col++) {
uat_field_t *field = &uat_->fields[col];
QString data;
if (rowData.count() > col) {
if (field->mode != PT_TXTMOD_BOOL) {
data = rowData[col].toString();
} else {
if (rowData[col].toInt() == Qt::Checked) {
data = QString("TRUE");
} else {
data = QString("FALSE");
}
}
}
QByteArray bytes = field->mode == PT_TXTMOD_HEXBYTES ? QByteArray::fromHex(data.toUtf8()) : data.toUtf8();
field->cb.set(record, bytes.constData(), (unsigned) bytes.size(), field->cbdata.set, field->fld_data);
}
uat_insert_record_idx(uat_, row, record);
if (uat_->free_cb) {
uat_->free_cb(record);
}
g_free(record);
record_errors.insert(row, QMap<int, QString>());
// a new row is created. For the moment all fields are empty, so validation
// will likely mark everything as invalid. Ideally validation should be
// postponed until the row (in the view) is not selected anymore
checkRow(row);
dirty_records.insert(row, true);
uat_->changed = TRUE;
emit endInsertRows();
newIndex = index(row, 0, QModelIndex());
return newIndex;
}
bool UatModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid())
return false;
uat_field_t *field = &uat_->fields[index.column()];
if ((role != Qt::EditRole) &&
((field->mode == PT_TXTMOD_BOOL) && (role != Qt::CheckStateRole)))
return false;
if (data(index, role) == value) {
// Data appears unchanged, do not do additional checks.
return true;
}
const int row = index.row();
void *rec = UAT_INDEX_PTR(uat_, row);
//qDebug() << "Changing (" << row << "," << index.column() << ") from " << data(index, Qt::EditRole) << " to " << value;
if (field->mode != PT_TXTMOD_BOOL) {
const QByteArray &str = value.toString().toUtf8();
const QByteArray &bytes = field->mode == PT_TXTMOD_HEXBYTES ? QByteArray::fromHex(str) : str;
field->cb.set(rec, bytes.constData(), (unsigned) bytes.size(), field->cbdata.set, field->fld_data);
} else {
if (value.toInt() == Qt::Checked) {
field->cb.set(rec, "TRUE", 4, field->cbdata.set, field->fld_data);
} else {
field->cb.set(rec, "FALSE", 5, field->cbdata.set, field->fld_data);
}
}
QVector<int> roles;
roles << role;
// Check validity of all rows, obtaining a list of columns where the
// validity status has changed.
const QList<int> &updated_cols = checkRow(row);
if (!updated_cols.isEmpty()) {
roles << Qt::BackgroundRole;
//qDebug() << "validation status changed:" << updated_cols;
}
if (record_errors[row].isEmpty()) {
// If all individual fields are valid, invoke the update callback. This
// might detect additional issues in either individual fields, or the
// combination of them.
if (uat_->update_cb) {
char *err = NULL;
if (!uat_->update_cb(rec, &err)) {
// TODO the error is not exactly on the first column, but we need a way to show the error.
record_errors[row].insert(0, err);
g_free(err);
}
}
}
uat_update_record(uat_, rec, record_errors[row].isEmpty());
dirty_records[row] = true;
uat_->changed = TRUE;
if (updated_cols.size() > updated_cols.count(index.column())) {
// The validation status for other columns were also affected by
// changing this field, mark those as dirty!
emit dataChanged(this->index(row, updated_cols.first()),
this->index(row, updated_cols.last()), roles);
} else {
emit dataChanged(index, index, roles);
}
return true;
}
bool UatModel::insertRows(int row, int count, const QModelIndex &/*parent*/)
{
// support insertion of just one item for now.
if (count != 1 || row < 0 || row > rowCount())
return false;
beginInsertRows(QModelIndex(), row, row);
// Initialize with empty values, caller should use setData to populate it.
void *record = g_malloc0(uat_->record_size);
for (int col = 0; col < columnCount(); col++) {
uat_field_t *field = &uat_->fields[col];
field->cb.set(record, "", 0, field->cbdata.set, field->fld_data);
}
uat_insert_record_idx(uat_, row, record);
if (uat_->free_cb) {
uat_->free_cb(record);
}
g_free(record);
record_errors.insert(row, QMap<int, QString>());
// a new row is created. For the moment all fields are empty, so validation
// will likely mark everything as invalid. Ideally validation should be
// postponed until the row (in the view) is not selected anymore
checkRow(row);
dirty_records.insert(row, true);
uat_->changed = TRUE;
endInsertRows();
return true;
}
bool UatModel::removeRows(int row, int count, const QModelIndex &/*parent*/)
{
if (count != 1 || row < 0 || row >= rowCount())
return false;
beginRemoveRows(QModelIndex(), row, row);
uat_remove_record_idx(uat_, row);
record_errors.removeAt(row);
dirty_records.removeAt(row);
uat_->changed = TRUE;
endRemoveRows();
return true;
}
void UatModel::clearAll()
{
if (rowCount() < 1)
return;
beginResetModel();
uat_clear(uat_);
record_errors.clear();
dirty_records.clear();
uat_->changed = TRUE;
endResetModel();
}
QModelIndex UatModel::copyRow(QModelIndex original)
{
if (! original.isValid())
return QModelIndex();
int newRow = rowCount();
beginInsertRows(QModelIndex(), newRow, newRow);
// Initialize with empty values, caller should use setData to populate it.
void *record = g_malloc0(uat_->record_size);
for (int col = 0; col < columnCount(); col++) {
uat_field_t *field = &uat_->fields[col];
field->cb.set(record, "", 0, field->cbdata.set, field->fld_data);
}
uat_insert_record_idx(uat_, newRow, record);
if (uat_->free_cb) {
uat_->free_cb(record);
}
g_free(record);
record_errors.insert(newRow, QMap<int, QString>());
// a new row is created. For the moment all fields are empty, so validation
// will likely mark everything as invalid. Ideally validation should be
// postponed until the row (in the view) is not selected anymore
checkRow(newRow);
dirty_records.insert(newRow, true);
// the UAT record has been created, now it is filled with the infromation
const void *src_record = UAT_INDEX_PTR(uat_, original.row());
void *dst_record = UAT_INDEX_PTR(uat_, newRow);
// insertRows always initializes the record with empty value. Before copying
// over the new values, be sure to clear the old fields.
if (uat_->free_cb) {
uat_->free_cb(dst_record);
}
if (uat_->copy_cb) {
uat_->copy_cb(dst_record, src_record, uat_->record_size);
} else {
/* According to documentation of uat_copy_cb_t memcpy should be used if uat_->copy_cb is NULL */
memcpy(dst_record, src_record, uat_->record_size);
}
gboolean src_valid = g_array_index(uat_->valid_data, gboolean, original.row());
uat_update_record(uat_, dst_record, src_valid);
record_errors[newRow] = record_errors[original.row()];
dirty_records[newRow] = true;
uat_->changed = TRUE;
endInsertRows();
return index(newRow, 0, QModelIndex());
}
bool UatModel::moveRow(int src_row, int dst_row)
{
if (src_row < 0 || src_row >= rowCount() || dst_row < 0 || dst_row >= rowCount())
return false;
int dst = src_row < dst_row ? dst_row + 1 : dst_row;
beginMoveRows(QModelIndex(), src_row, src_row, QModelIndex(), dst);
uat_move_index(uat_, src_row, dst_row);
record_errors.move(src_row, dst_row);
dirty_records.move(src_row, dst_row);
uat_->changed = TRUE;
endMoveRows();
return true;
}
bool UatModel::hasErrors() const
{
for (int i = 0; i < rowCount(); i++) {
// Ignore errors on unmodified records, these should not prevent the OK
// button from saving modifications to other entries.
if (dirty_records[i] && !record_errors[i].isEmpty()) {
return true;
}
}
return false;
}
bool UatModel::checkField(int row, int col, char **error) const
{
uat_field_t *field = &uat_->fields[col];
void *rec = UAT_INDEX_PTR(uat_, row);
if (!field->cb.chk) {
return true;
}
char *str = NULL;
guint length;
field->cb.tostr(rec, &str, &length, field->cbdata.tostr, field->fld_data);
bool ok = field->cb.chk(rec, str, length, field->cbdata.chk, field->fld_data, error);
g_free(str);
return ok;
}
// Validates all fields in the given record, setting error messages as needed.
// Returns the columns that have changed (not the columns with errors).
QList<int> UatModel::checkRow(int row)
{
Q_ASSERT(0 <= row && row < rowCount());
QList<int> changed;
QMap<int, QString> &errors = record_errors[row];
for (int col = 0; col < columnCount(); col++) {
char *err;
bool error_changed = errors.remove(col) > 0;
if (!checkField(row, col, &err)) {
errors.insert(col, err);
g_free(err);
error_changed = !error_changed;
}
if (error_changed) {
changed << col;
}
}
return changed;
} |
C/C++ | wireshark/ui/qt/models/uat_model.h | /** @file
*
* Data model for UAT records.
*
* Copyright 2016 Peter Wu <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef UAT_MODEL_H
#define UAT_MODEL_H
#include <config.h>
#include <glib.h>
#include <QAbstractItemModel>
#include <QList>
#include <QMap>
#include <epan/uat-int.h>
class UatModel : public QAbstractTableModel
{
public:
UatModel(QObject *parent, uat_t *uat = 0);
UatModel(QObject *parent, QString tableName);
Qt::ItemFlags flags(const QModelIndex &index) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex());
bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
QModelIndex appendEntry(QVariantList row);
QModelIndex copyRow(QModelIndex original);
bool moveRow(int src_row, int dst_row);
bool moveRow(const QModelIndex &sourceParent, int sourceRow, const QModelIndex &destinationParent, int destinationChild);
void reloadUat();
bool hasErrors() const;
void clearAll();
/**
* If the UAT has changed, save the contents to file and invoke the UAT
* post_update_cb.
*
* @param error An error while saving changes, if any.
* @return true if anything changed, false otherwise.
*/
bool applyChanges(QString &error);
/**
* Undo any changes to the UAT.
*
* @param error An error while restoring the original UAT, if any.
* @return true if anything changed, false otherwise.
*/
bool revertChanges(QString &error);
QModelIndex findRowForColumnContent(QVariant columnContent, int columnToCheckAgainst, int role = Qt::DisplayRole);
private:
bool checkField(int row, int col, char **error) const;
QList<int> checkRow(int row);
void loadUat(uat_t * uat = 0);
epan_uat *uat_;
QList<bool> dirty_records;
QList<QMap<int, QString> > record_errors;
};
#endif // UAT_MODEL_H |
C++ | wireshark/ui/qt/models/url_link_delegate.cpp | /* url_link_delegate.cpp
* Delegates for displaying links as links, including elide model
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/models/url_link_delegate.h>
#include <QPainter>
#include <ui/qt/utils/color_utils.h>
UrlLinkDelegate::UrlLinkDelegate(QObject *parent)
: QStyledItemDelegate(parent),
re_col_(-1),
url_re_(new QRegularExpression())
{}
UrlLinkDelegate::~UrlLinkDelegate()
{
delete url_re_;
}
void UrlLinkDelegate::setColCheck(int column, QString &pattern)
{
re_col_ = column;
url_re_->setPattern(pattern);
}
void UrlLinkDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
if (re_col_ >= 0 && url_re_) {
QModelIndex re_idx = index.model()->index(index.row(), re_col_);
QString col_text = index.model()->data(re_idx).toString();
if (!url_re_->match(col_text).hasMatch()) {
QStyledItemDelegate::paint(painter, option, index);
return;
}
}
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
opt.font.setUnderline(true);
opt.palette.setColor(QPalette::Text, ColorUtils::themeLinkBrush().color());
QStyledItemDelegate::paint(painter, opt, index);
} |
C/C++ | wireshark/ui/qt/models/url_link_delegate.h | /** @file
*
* Delegates for displaying links as links, including elide model
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef URL_LINK_DELEGATE_H
#define URL_LINK_DELEGATE_H
#include <QStyledItemDelegate>
#include <QStyleOptionViewItem>
#include <QModelIndex>
#include <QRegularExpression>
class UrlLinkDelegate : public QStyledItemDelegate
{
public:
explicit UrlLinkDelegate(QObject *parent = Q_NULLPTR);
~UrlLinkDelegate();
// If pattern matches the string in column, render as a URL.
// Otherwise render as plain text.
void setColCheck(int column, QString &pattern);
protected:
virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
private:
int re_col_;
QRegularExpression *url_re_;
};
#endif // URL_LINK_DELEGATE_H |
C++ | wireshark/ui/qt/models/voip_calls_info_model.cpp | /* voip_calls_info_model.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "voip_calls_info_model.h"
#include <wsutil/utf8_entities.h>
#include <wsutil/ws_assert.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <QDateTime>
VoipCallsInfoModel::VoipCallsInfoModel(QObject *parent) :
QAbstractTableModel(parent),
mTimeOfDay_(false)
{
}
voip_calls_info_t *VoipCallsInfoModel::indexToCallInfo(const QModelIndex &index)
{
return VariantPointer<voip_calls_info_t>::asPtr(index.data(Qt::UserRole));
}
QVariant VoipCallsInfoModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
// call_info will be non-NULL since the index is valid
voip_calls_info_t *call_info = static_cast<voip_calls_info_t *>(callinfos_[index.row()]);
if (role == Qt::UserRole) {
return VariantPointer<voip_calls_info_t>::asQVariant(call_info);
}
if (role != Qt::DisplayRole) {
return QVariant();
}
switch ((Column) index.column()) {
case StartTime:
return timeData(&(call_info->start_fd->abs_ts), &(call_info->start_rel_ts));
case StopTime:
return timeData(&(call_info->stop_fd->abs_ts), &(call_info->stop_rel_ts));
case InitialSpeaker:
return address_to_display_qstring(&(call_info->initial_speaker));
case From:
return QString::fromUtf8(call_info->from_identity);
case To:
return QString::fromUtf8(call_info->to_identity);
case Protocol:
return ((call_info->protocol == VOIP_COMMON) && call_info->protocol_name) ?
call_info->protocol_name : voip_protocol_name[call_info->protocol];
case Duration:
{
guint callDuration = nstime_to_sec(&(call_info->stop_fd->abs_ts)) - nstime_to_sec(&(call_info->start_fd->abs_ts));
return QString("%1:%2:%3").arg(callDuration / 3600, 2, 10, QChar('0')).arg((callDuration % 3600) / 60, 2, 10, QChar('0')).arg(callDuration % 60, 2, 10, QChar('0'));
}
case Packets:
return call_info->npackets;
case State:
return QString(voip_call_state_name[call_info->call_state]);
case Comments:
/* Add comments based on the protocol */
switch (call_info->protocol) {
case VOIP_ISUP:
{
isup_calls_info_t *isup_info = (isup_calls_info_t *)call_info->prot_info;
return QString("%1-%2 %3 %4-%5")
.arg(isup_info->ni)
.arg(isup_info->opc)
.arg(UTF8_RIGHTWARDS_ARROW)
.arg(isup_info->ni)
.arg(isup_info->dpc);
}
break;
case VOIP_H323:
{
h323_calls_info_t *h323_info = (h323_calls_info_t *)call_info->prot_info;
gboolean flag = FALSE;
static const QString on_str = tr("On");
static const QString off_str = tr("Off");
if (call_info->call_state == VOIP_CALL_SETUP) {
flag = h323_info->is_faststart_Setup;
} else {
if ((h323_info->is_faststart_Setup) && (h323_info->is_faststart_Proc)) {
flag = TRUE;
}
}
return tr("Tunneling: %1 Fast Start: %2")
.arg(h323_info->is_h245Tunneling ? on_str : off_str)
.arg(flag ? on_str : off_str);
}
break;
case VOIP_COMMON:
default:
return QString::fromUtf8(call_info->call_comment);
}
case ColumnCount:
ws_assert_not_reached();
}
return QVariant();
}
QVariant VoipCallsInfoModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
switch ((Column) section) {
case StartTime:
return tr("Start Time");
case StopTime:
return tr("Stop Time");
case InitialSpeaker:
return tr("Initial Speaker");
case From:
return tr("From");
case To:
return tr("To");
case Protocol:
return tr("Protocol");
case Duration:
return tr("Duration");
case Packets:
return tr("Packets");
case State:
return tr("State");
case Comments:
return tr("Comments");
case ColumnCount:
ws_assert_not_reached();
}
}
return QVariant();
}
int VoipCallsInfoModel::rowCount(const QModelIndex &parent) const
{
// there are no children
if (parent.isValid()) {
return 0;
}
return static_cast<int>(callinfos_.size());
}
int VoipCallsInfoModel::columnCount(const QModelIndex &parent) const
{
// there are no children
if (parent.isValid()) {
return 0;
}
return ColumnCount;
}
QVariant VoipCallsInfoModel::timeData(nstime_t *abs_ts, nstime_t *rel_ts) const
{
if (mTimeOfDay_) {
return QDateTime::fromMSecsSinceEpoch(nstime_to_msec(abs_ts), Qt::LocalTime).toString("yyyy-MM-dd hh:mm:ss");
} else {
// XXX Pull digit count from capture file precision
return QString::number(nstime_to_sec(rel_ts), 'f', 6);
}
}
void VoipCallsInfoModel::setTimeOfDay(bool timeOfDay)
{
mTimeOfDay_ = timeOfDay;
if (rowCount() > 0) {
// Update both the start and stop column in all rows.
emit dataChanged(index(0, StartTime), index(rowCount() - 1, StopTime));
}
}
bool VoipCallsInfoModel::timeOfDay() const
{
return mTimeOfDay_;
}
void VoipCallsInfoModel::updateCalls(GQueue *callsinfos)
{
if (callsinfos) {
qsizetype calls = callinfos_.count();
int cnt = 0;
GList *cur_call;
// Iterate new callsinfos and replace data in mode if required
cur_call = g_queue_peek_nth_link(callsinfos, 0);
while (cur_call && (cnt < calls)) {
if (callinfos_.at(cnt) != cur_call->data) {
// Data changed, use it
callinfos_.replace(cnt, cur_call->data);
}
cur_call = gxx_list_next(cur_call);
cnt++;
}
// Add new rows
cur_call = g_queue_peek_nth_link(callsinfos, rowCount());
guint extra = g_list_length(cur_call);
if (extra > 0) {
beginInsertRows(QModelIndex(), rowCount(), rowCount() + extra - 1);
while (cur_call && cur_call->data) {
voip_calls_info_t *call_info = gxx_list_data(voip_calls_info_t*, cur_call);
callinfos_.push_back(call_info);
cur_call = gxx_list_next(cur_call);
}
endInsertRows();
}
}
}
void VoipCallsInfoModel::removeAllCalls()
{
beginRemoveRows(QModelIndex(), 0, rowCount() - 1);
callinfos_.clear();
endRemoveRows();
}
// Proxy model that allows columns to be sorted.
VoipCallsInfoSortedModel::VoipCallsInfoSortedModel(QObject *parent) :
QSortFilterProxyModel(parent)
{
}
bool VoipCallsInfoSortedModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
{
voip_calls_info_t *a = VoipCallsInfoModel::indexToCallInfo(source_left);
voip_calls_info_t *b = VoipCallsInfoModel::indexToCallInfo(source_right);
if (a && b) {
switch (source_left.column()) {
case VoipCallsInfoModel::StartTime:
return nstime_cmp(&(a->start_rel_ts), &(b->start_rel_ts)) < 0;
case VoipCallsInfoModel::StopTime:
return nstime_cmp(&(a->stop_rel_ts), &(b->stop_rel_ts)) < 0;
case VoipCallsInfoModel::InitialSpeaker:
return cmp_address(&(a->initial_speaker), &(b->initial_speaker)) < 0;
}
}
// fallback to string cmp on other fields
return QSortFilterProxyModel::lessThan(source_left, source_right);
} |
C/C++ | wireshark/ui/qt/models/voip_calls_info_model.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef VOIP_CALLS_INFO_MODEL_H
#define VOIP_CALLS_INFO_MODEL_H
#include <config.h>
#include <glib.h>
#include "ui/voip_calls.h"
#include <ui/qt/utils/variant_pointer.h>
#include <QAbstractTableModel>
#include <QSortFilterProxyModel>
class VoipCallsInfoModel : public QAbstractTableModel
{
Q_OBJECT
public:
VoipCallsInfoModel(QObject *parent = 0);
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
void setTimeOfDay(bool timeOfDay);
bool timeOfDay() const;
void updateCalls(GQueue *callsinfos);
void removeAllCalls();
static voip_calls_info_t *indexToCallInfo(const QModelIndex &index);
enum Column
{
StartTime,
StopTime,
InitialSpeaker,
From,
To,
Protocol,
Duration,
Packets,
State,
Comments,
ColumnCount /* not an actual column, but used to find max. cols. */
};
private:
QList<void *> callinfos_;
bool mTimeOfDay_;
QVariant timeData(nstime_t *abs_ts, nstime_t *rel_ts) const;
};
class VoipCallsInfoSortedModel : public QSortFilterProxyModel
{
public:
VoipCallsInfoSortedModel(QObject *parent = 0);
protected:
bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const;
};
#endif // VOIP_CALLS_INFO_MODEL_H |
C++ | wireshark/ui/qt/utils/color_utils.cpp | /* color_utils.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/utils/color_utils.h>
#include <ui/qt/utils/tango_colors.h>
#include <QApplication>
#include <QPalette>
// Colors we use in various parts of the UI.
//
// New colors should be chosen from tango_colors.h. The expert and hidden
// colors come from the GTK+ UI and are grandfathered in.
//
// At some point we should probably make these configurable along with the
// graph and sequence colors.
const QColor ColorUtils::expert_color_comment = QColor (0xb7, 0xf7, 0x74); /* Green */
const QColor ColorUtils::expert_color_chat = QColor (0x80, 0xb7, 0xf7); /* Light blue */
const QColor ColorUtils::expert_color_note = QColor (0xa0, 0xff, 0xff); /* Bright turquoise */
const QColor ColorUtils::expert_color_warn = QColor (0xf7, 0xf2, 0x53); /* Yellow */
const QColor ColorUtils::expert_color_error = QColor (0xff, 0x5c, 0x5c); /* Pale red */
const QColor ColorUtils::expert_color_foreground = QColor (0x00, 0x00, 0x00); /* Black */
const QColor ColorUtils::hidden_proto_item = QColor (0x44, 0x44, 0x44); /* Gray */
ColorUtils::ColorUtils(QObject *parent) :
QObject(parent)
{
}
//
// A color_t has RGB values in [0,65535].
// Qt RGB colors have RGB values in [0,255].
//
// 65535/255 = 257 = 0x0101, so converting from [0,255] to
// [0,65535] involves just shifting the 8-bit value left 8 bits
// and ORing them together.
//
// Converting from [0,65535] to [0,255] without rounding involves
// just shifting the 16-bit value right 8 bits; I guess you could
// round them by adding 0x80 to the value before shifting.
//
QColor ColorUtils::fromColorT (const color_t *color) {
if (!color) return QColor();
// Convert [0,65535] values to [0,255] values
return QColor(color->red >> 8, color->green >> 8, color->blue >> 8);
}
QColor ColorUtils::fromColorT(color_t color)
{
return fromColorT(&color);
}
const color_t ColorUtils::toColorT(const QColor color)
{
color_t colort;
// Convert [0,255] values to [0,65535] values
colort.red = (color.red() << 8) | color.red();
colort.green = (color.green() << 8) | color.green();
colort.blue = (color.blue() << 8) | color.blue();
return colort;
}
QRgb ColorUtils::alphaBlend(const QColor &color1, const QColor &color2, qreal alpha)
{
alpha = qBound(qreal(0.0), alpha, qreal(1.0));
int r1 = color1.red() * alpha;
int g1 = color1.green() * alpha;
int b1 = color1.blue() * alpha;
int r2 = color2.red() * (1 - alpha);
int g2 = color2.green() * (1 - alpha);
int b2 = color2.blue() * (1 - alpha);
QColor alpha_color(r1 + r2, g1 + g2, b1 + b2);
return alpha_color.rgb();
}
QRgb ColorUtils::alphaBlend(const QBrush &brush1, const QBrush &brush2, qreal alpha)
{
return alphaBlend(brush1.color(), brush2.color(), alpha);
}
QList<QRgb> ColorUtils::graph_colors_;
const QList<QRgb> ColorUtils::graphColors()
{
if (graph_colors_.isEmpty()) {
// Available graph colors
// XXX - Add custom
graph_colors_ = QList<QRgb>()
<< tango_aluminium_6 // Bar outline (use black instead)?
<< tango_sky_blue_5
<< tango_butter_6
<< tango_chameleon_5
<< tango_scarlet_red_5
<< tango_plum_5
<< tango_orange_6
<< tango_aluminium_3
<< tango_sky_blue_3
<< tango_butter_3
<< tango_chameleon_3
<< tango_scarlet_red_3
<< tango_plum_3
<< tango_orange_3;
}
return graph_colors_;
}
QRgb ColorUtils::graphColor(int item)
{
if (graph_colors_.isEmpty()) graphColors(); // Init list.
return graph_colors_[item % graph_colors_.size()];
}
QList<QRgb> ColorUtils::sequence_colors_;
QRgb ColorUtils::sequenceColor(int item)
{
if (sequence_colors_.isEmpty()) {
// Available sequence colors. Copied from gtk/graph_analysis.c.
// XXX - Add custom?
sequence_colors_ = QList<QRgb>()
<< qRgb(144, 238, 144)
<< qRgb(255, 160, 123)
<< qRgb(255, 182, 193)
<< qRgb(250, 250, 210)
<< qRgb(255, 255, 52)
<< qRgb(103, 205, 170)
<< qRgb(224, 255, 255)
<< qRgb(176, 196, 222)
<< qRgb(135, 206, 254)
<< qRgb(211, 211, 211);
}
return sequence_colors_[item % sequence_colors_.size()];
}
bool ColorUtils::themeIsDark()
{
return qApp->palette().windowText().color().lightness() > qApp->palette().window().color().lightness();
}
// Qt < 5.12.6 on macOS always uses Qt::blue for the link color, which is
// unreadable when using a dark theme. Changing the application palette
// via ...Application::setPalette is problematic, since QGuiApplication
// sets a flag (ApplicationPaletteExplicitlySet) which keeps us from
// catching theme changes.
//
// themeLinkBrush and themeLinkStyle provide convenience routines for
// fetching the link brush and style.
//
// We could also override MainApplication::palette, but keeping the
// routines together here seemed to make more sense.
QBrush ColorUtils::themeLinkBrush()
{
#if QT_VERSION < QT_VERSION_CHECK(5, 12, 6)
// https://bugreports.qt.io/browse/QTBUG-71740
if (themeIsDark()) {
return QBrush(tango_sky_blue_2);
}
#endif
return qApp->palette().link();
}
QString ColorUtils::themeLinkStyle()
{
QString link_style;
if (themeIsDark()) {
link_style = QString("<style>a:link { color: %1; }</style>")
.arg(themeLinkBrush().color().name());
}
return link_style;
}
const QColor ColorUtils::contrastingTextColor(const QColor color)
{
bool background_is_light = color.lightness() > 127;
if ( (background_is_light && !ColorUtils::themeIsDark()) || (!background_is_light && ColorUtils::themeIsDark()) ) {
return QApplication::palette().text().color();
}
return QApplication::palette().base().color();
}
const QColor ColorUtils::hoverBackground()
{
QPalette hover_palette = QApplication::palette();
#if defined(Q_OS_MAC)
hover_palette.setCurrentColorGroup(QPalette::Active);
return hover_palette.highlight().color();
#else
return ColorUtils::alphaBlend(hover_palette.window(), hover_palette.highlight(), 0.5);
#endif
}
const QColor ColorUtils::warningBackground()
{
if (themeIsDark()) {
return QColor(tango_butter_6);
}
return QColor(tango_butter_2);
} |
C/C++ | wireshark/ui/qt/utils/color_utils.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef COLOR_UTILS_H
#define COLOR_UTILS_H
#include <config.h>
#include <glib.h>
#include <epan/color_filters.h>
#include <QBrush>
#include <QColor>
#include <QObject>
class ColorUtils : public QObject
{
public:
explicit ColorUtils(QObject *parent = 0);
static QColor fromColorT(const color_t *color);
static QColor fromColorT(color_t color);
static const color_t toColorT(const QColor color);
static QRgb alphaBlend(const QColor &color1, const QColor &color2, qreal alpha);
static QRgb alphaBlend(const QBrush &brush1, const QBrush &brush2, qreal alpha);
// ...because they don't really fit anywhere else?
static const QColor expert_color_comment; /* green */
static const QColor expert_color_chat; /* light blue */
static const QColor expert_color_note; /* bright turquoise */
static const QColor expert_color_warn; /* yellow */
static const QColor expert_color_error; /* pale red */
static const QColor expert_color_foreground; /* black */
static const QColor hidden_proto_item; /* gray */
static const QList<QRgb> graphColors();
static QRgb graphColor(int item);
static QRgb sequenceColor(int item);
/** Checks if our application is in "dark mode".
* Dark mode is determined by comparing the application palette's window
* text color with the window color.
*
* @return true if we're running in dark mode, false otherwise.
*/
static bool themeIsDark();
/**
* Returns an appropriate link color for the current mode.
* @return A brush suitable for setting a text color.
*/
static QBrush themeLinkBrush();
/**
* Returns an appropriate HTML+CSS link style for the current mode.
* @return A "<style>a:link { color: ... ; }</style>" string
*/
static QString themeLinkStyle();
/**
* Returns either QPalette::Text or QPalette::Base as appropriate for the
* specified foreground color
*
* @param color The background color.
* @return A contrasting foreground color for the current mode / theme.
*/
static const QColor contrastingTextColor(const QColor color);
/**
* Returns an appropriate background color for hovered abstract items.
* @return The background color.
*/
static const QColor hoverBackground();
/**
* Returns an appropriate warning background color for the current mode.
* @return The background color.
*/
static const QColor warningBackground();
private:
static QList<QRgb> graph_colors_;
static QList<QRgb> sequence_colors_;
};
void color_filter_qt_add_cb(color_filter_t *colorf, gpointer user_data);
#endif // COLOR_UTILS_H |
C++ | wireshark/ui/qt/utils/data_printer.cpp | /* data_printer.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/utils/data_printer.h>
#include <ui/qt/utils/variant_pointer.h>
#include <ui/recent.h>
#include <wsutil/utf8_entities.h>
#include <stdint.h>
#include <QApplication>
#include <QClipboard>
#include <QString>
#include <QMimeData>
DataPrinter::DataPrinter(QObject * parent)
: QObject(parent),
byteLineLength_(16)
{}
void DataPrinter::toClipboard(DataPrinter::DumpType type, IDataPrintable * printable)
{
const QByteArray printData = printable->printableData();
QString clipboard_text;
switch(type)
{
case DP_CString:
// Beginning quote
clipboard_text += QString("\"");
for (int i = 0; i < printData.length(); i++) {
/* ASCII printable */
int ch = printData[i];
if (ch >= 32 && ch <= 126) {
clipboard_text += QChar(ch);
}
else {
clipboard_text += QString("\\x%1").arg((uint8_t) printData[i], 2, 16, QChar('0'));
}
}
// End quote
clipboard_text += QString("\"");
break;
case DP_HexStream:
for (int i = 0; i < printData.length(); i++)
clipboard_text += QString("%1").arg((uint8_t) printData[i], 2, 16, QChar('0'));
break;
case DP_Base64:
#if WS_IS_AT_LEAST_GNUC_VERSION(12,1)
DIAG_OFF(stringop-overread)
#endif
clipboard_text = printData.toBase64();
#if WS_IS_AT_LEAST_GNUC_VERSION(12,1)
DIAG_ON(stringop-overread)
#endif
break;
case DP_MimeData:
binaryDump(printData);
break;
case DP_HexDump:
clipboard_text = hexTextDump(printData, true);
break;
case DP_HexOnly:
clipboard_text = hexTextDump(printData, false);
break;
default:
break;
}
if (!clipboard_text.isEmpty()) {
qApp->clipboard()->setText(clipboard_text);
}
}
void DataPrinter::binaryDump(const QByteArray printData)
{
if (!printData.isEmpty()) {
QMimeData *mime_data = new QMimeData;
// gtk/gui_utils.c:copy_binary_to_clipboard says:
/* XXX - this is not understood by most applications,
* but can be pasted into the better hex editors - is
* there something better that we can do?
*/
// As of 2015-07-30, pasting into Frhed works on Windows. Pasting into
// Hex Editor Neo and HxD does not.
mime_data->setData("application/octet-stream", printData);
qApp->clipboard()->setMimeData(mime_data);
}
}
void DataPrinter::setByteLineLength(int bll)
{
byteLineLength_ = bll;
}
int DataPrinter::byteLineLength() const
{
return byteLineLength_;
}
int DataPrinter::hexChars()
{
int row_width, chars_per_byte;
switch (recent.gui_bytes_view) {
case BYTES_HEX:
row_width = 16;
chars_per_byte = 3;
break;
case BYTES_BITS:
row_width = 8;
chars_per_byte = 9;
break;
case BYTES_DEC:
case BYTES_OCT:
row_width = 16;
chars_per_byte = 4;
break;
default:
ws_assert_not_reached();
}
return (row_width * chars_per_byte) + ((row_width - 1) / separatorInterval());
}
QString DataPrinter::hexTextDump(const QByteArray printData, bool showASCII)
{
QString clipboard_text;
QString byteStr;
QString dataStr;
int cnt = 0;
while (cnt < printData.length())
{
byteStr += QString(" %1").arg((uint8_t) printData[cnt], 2, 16, QChar('0'));
if (showASCII)
{
QChar ch(printData[cnt]);
if (g_ascii_isprint(printData[cnt]))
dataStr += printData[cnt];
else
dataStr += '.';
}
cnt++;
}
int lines = static_cast<int>(printData.length()) / byteLineLength_;
if (printData.length() % byteLineLength_ > 0)
lines++;
for (cnt = 0; cnt < lines; cnt++)
{
int offset = cnt * 0x10;
clipboard_text += QString("%1 ").arg(offset, 4, 16, QChar('0'));
clipboard_text += byteStr.mid(offset * 3, byteLineLength_ * 3);
if (showASCII)
{
/* separation bytes for byte and text */
clipboard_text += QString(3, ' ');
/* separation bytes last line */
if (cnt == (lines - 1) )
{
int remSpace = byteLineLength_ - static_cast<int>(dataStr.mid(offset, byteLineLength_).length());
clipboard_text += QString(remSpace * 3, ' ');
}
/* text representation */
clipboard_text += dataStr.mid(offset, byteLineLength_);
}
clipboard_text += "\n";
}
return clipboard_text;
}
DataPrinter * DataPrinter::instance()
{
static DataPrinter * inst = Q_NULLPTR;
if (inst == Q_NULLPTR)
inst = new DataPrinter();
return inst;
}
QActionGroup * DataPrinter::copyActions(QObject * copyClass, QObject * data)
{
QActionGroup * actions = new QActionGroup(copyClass);
if (! data && ! dynamic_cast<IDataPrintable *>(copyClass))
return actions;
DataPrinter * dpi = DataPrinter::instance();
if (data)
actions->setProperty("idataprintable", VariantPointer<QObject>::asQVariant(data));
else
actions->setProperty("idataprintable", VariantPointer<QObject>::asQVariant(copyClass));
// Mostly duplicated from main_window.ui
QAction * action = new QAction(tr("Copy Bytes as Hex + ASCII Dump"), actions);
action->setToolTip(tr("Copy packet bytes as a hex and ASCII dump."));
action->setProperty("printertype", DataPrinter::DP_HexDump);
connect(action, &QAction::triggered, dpi, &DataPrinter::copyIDataBytes);
action = new QAction(tr("…as Hex Dump"), actions);
action->setToolTip(tr("Copy packet bytes as a hex dump."));
action->setProperty("printertype", DataPrinter::DP_HexOnly);
connect(action, &QAction::triggered, dpi, &DataPrinter::copyIDataBytes);
action = new QAction(tr("…as a Hex Stream"), actions);
action->setToolTip(tr("Copy packet bytes as a stream of hex."));
action->setProperty("printertype", DataPrinter::DP_HexStream);
connect(action, &QAction::triggered, dpi, &DataPrinter::copyIDataBytes);
action = new QAction(tr("…as a Base64 String"), actions);
action->setToolTip(tr("Copy packet bytes as a base64 encoded string."));
action->setProperty("printertype", DataPrinter::DP_Base64);
connect(action, &QAction::triggered, dpi, &DataPrinter::copyIDataBytes);
action = new QAction(tr("…as MIME Data"), actions);
action->setToolTip(tr("Copy packet bytes as application/octet-stream MIME data."));
action->setProperty("printertype", DataPrinter::DP_MimeData);
connect(action, &QAction::triggered, dpi, &DataPrinter::copyIDataBytes);
action = new QAction(tr("…as C String"), actions);
action->setToolTip(tr("Copy packet bytes as printable ASCII characters and escape sequences."));
action->setProperty("printertype", DataPrinter::DP_CString);
connect(action, &QAction::triggered, dpi, &DataPrinter::copyIDataBytes);
return actions;
}
void DataPrinter::copyIDataBytes(bool /* state */)
{
if (! dynamic_cast<QAction*>(sender()))
return;
QAction * sendingAction = dynamic_cast<QAction *>(sender());
if (! sendingAction->actionGroup() || ! sendingAction->actionGroup()->property("idataprintable").isValid())
return;
QObject * dataObject = VariantPointer<QObject>::asPtr(sendingAction->actionGroup()->property("idataprintable"));
if (! dataObject || ! dynamic_cast<IDataPrintable *>(dataObject))
return;
int dump_type = sendingAction->property("printertype").toInt();
if (dump_type >= 0 && dump_type <= DataPrinter::DP_Base64) {
DataPrinter printer;
printer.toClipboard((DataPrinter::DumpType) dump_type, dynamic_cast<IDataPrintable *>(dataObject));
}
} |
C/C++ | wireshark/ui/qt/utils/data_printer.h | /** @file
*
* Used by ByteView and others, to create data dumps in printable
* form
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef DATA_PRINTER_H
#define DATA_PRINTER_H
#include <config.h>
#include <QObject>
#include <QActionGroup>
#include <ui/qt/utils/idata_printable.h>
class DataPrinter : public QObject
{
Q_OBJECT
public:
explicit DataPrinter(QObject *parent = 0);
enum DumpType {
DP_HexDump,
DP_HexOnly,
DP_HexStream,
DP_CString,
DP_MimeData,
DP_Base64
};
void toClipboard(DataPrinter::DumpType type, IDataPrintable * printable);
void setByteLineLength(int);
int byteLineLength() const;
// Insert a space after this many bytes
static int separatorInterval() { return 8; }
// The number of hexadecimal characters per line
static int hexChars();
static QActionGroup * copyActions(QObject * copyClass, QObject * data = Q_NULLPTR);
static DataPrinter * instance();
protected slots:
void copyIDataBytes(bool);
private:
QString hexTextDump(const QByteArray printData, bool showASCII);
void binaryDump(const QByteArray printData);
int byteLineLength_;
};
#endif // DATA_PRINTER_H |
C++ | wireshark/ui/qt/utils/field_information.cpp | /* field_information.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <stdint.h>
#include <ui/qt/utils/field_information.h>
FieldInformation::FieldInformation(field_info *fi, QObject * parent)
:QObject(parent)
{
fi_ = fi;
parent_fi_ = NULL;
}
FieldInformation::FieldInformation(ProtoNode *node, QObject * parent)
:QObject(parent)
{
fi_ = NULL;
if (node && node->isValid()) {
fi_ = node->protoNode()->finfo;
}
parent_fi_ = NULL;
}
bool FieldInformation::isValid() const
{
bool ret = false;
if (fi_ && fi_->hfinfo)
{
if (fi_->hfinfo->blurb != NULL && fi_->hfinfo->blurb[0] != '\0') {
ret = true;
} else {
ret = QString((fi_->hfinfo->name)).length() > 0;
}
}
return ret;
}
bool FieldInformation::isLink() const
{
if (fi_ && fi_->hfinfo) {
if ((fi_->hfinfo->type == FT_FRAMENUM) ||
(FI_GET_FLAG(fi_, FI_URL) && FT_IS_STRING(fi_->hfinfo->type))) {
return true;
}
}
return false;
}
void FieldInformation::setParentField(field_info * par_fi)
{
parent_fi_ = par_fi;
}
int FieldInformation::treeType()
{
if (fi_) {
Q_ASSERT(fi_->tree_type >= -1 && fi_->tree_type < num_tree_types);
return fi_->tree_type;
}
return -1;
}
field_info * FieldInformation::fieldInfo() const
{
return fi_;
}
FieldInformation::HeaderInfo FieldInformation::headerInfo() const
{
HeaderInfo header;
if (fi_ && fi_->hfinfo)
{
header.name = fi_->hfinfo->name;
header.description = fi_->hfinfo->blurb;
header.abbreviation = fi_->hfinfo->abbrev;
header.isValid = true;
header.type = fi_->hfinfo->type;
header.parent = fi_->hfinfo->parent;
header.id = fi_->hfinfo->id;
}
else
{
header.name = "";
header.description = "";
header.abbreviation = "";
header.isValid = false;
header.type = FT_NONE;
header.parent = 0;
header.id = 0;
}
return header;
}
FieldInformation * FieldInformation::parentField() const
{
return new FieldInformation(parent_fi_, parent());
}
bool FieldInformation::tvbContains(FieldInformation *child)
{
if (fi_ && child && fi_->ds_tvb == child->fieldInfo()->ds_tvb)
return true;
return false;
}
unsigned FieldInformation::flag(unsigned mask)
{
if (fi_) {
return FI_GET_FLAG(fi_, mask);
}
return 0;
}
const QString FieldInformation::moduleName()
{
QString module_name;
if (isValid()) {
if (headerInfo().parent == -1) {
module_name = fi_->hfinfo->abbrev;
} else {
module_name = proto_registrar_get_abbrev(headerInfo().parent);
}
}
return module_name;
}
QString FieldInformation::toString()
{
QByteArray display_label;
display_label.resize(80); // Arbitrary.
int label_len = proto_item_fill_display_label(fi_, display_label.data(), static_cast<int>(display_label.size())-1);
display_label.resize(label_len);
if (display_label.isEmpty()) {
return "[no value for field]";
}
return QString(display_label);
}
QString FieldInformation::url()
{
QString url;
if (flag(FI_URL) && headerInfo().isValid && FT_IS_STRING(fi_->hfinfo->type)) {
url = toString();
}
return url;
}
FieldInformation::Position FieldInformation::position() const
{
Position pos = {-1, -1};
if (fi_ && fi_->ds_tvb)
{
int len = (int) tvb_captured_length(fi_->ds_tvb);
pos.start = fi_->start;
pos.length = fi_->length;
if (pos.start < 0 || pos.length < 0 || pos.start >= len)
{
if (fi_->appendix_start >= 0 && fi_->appendix_length > 0 && fi_->appendix_start < len)
{
pos.start = fi_->appendix_start;
pos.length = fi_->appendix_length;
}
}
}
return pos;
}
FieldInformation::Position FieldInformation::appendix() const
{
Position pos = {-1, -1};
if (fi_ && fi_->ds_tvb)
{
pos.start = fi_->appendix_start;
pos.length = fi_->appendix_length;
}
return pos;
}
const QByteArray FieldInformation::printableData()
{
QByteArray data;
if (fi_ && fi_->ds_tvb)
{
FieldInformation::Position pos = position();
int rem_length = tvb_captured_length_remaining(fi_->ds_tvb, pos.start);
int length = pos.length;
if (length > rem_length)
length = rem_length;
uint8_t * dataSet = (uint8_t *)tvb_memdup(wmem_file_scope(), fi_->ds_tvb, pos.start, length);
data = QByteArray::fromRawData((char *)dataSet, length);
}
return data;
} |
C/C++ | wireshark/ui/qt/utils/field_information.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef FIELD_INFORMATION_H_
#define FIELD_INFORMATION_H_
#include <config.h>
#include <epan/proto.h>
#include <ui/qt/utils/proto_node.h>
#include "data_printer.h"
#include <QObject>
class FieldInformation : public QObject, public IDataPrintable
{
Q_OBJECT
Q_INTERFACES(IDataPrintable)
public:
struct HeaderInfo
{
QString name;
QString description;
QString abbreviation;
bool isValid;
enum ftenum type;
int parent;
int id;
};
struct Position
{
int start;
int length;
};
explicit FieldInformation(field_info * fi, QObject * parent = Q_NULLPTR);
explicit FieldInformation(ProtoNode * node, QObject * parent = Q_NULLPTR);
bool isValid() const;
bool isLink() const ;
field_info * fieldInfo() const;
HeaderInfo headerInfo() const;
Position position() const;
Position appendix() const;
void setParentField(field_info * fi);
int treeType();
FieldInformation * parentField() const;
bool tvbContains(FieldInformation *);
unsigned flag(unsigned mask);
const QString moduleName();
QString toString();
QString url();
const QByteArray printableData();
private:
field_info * fi_;
field_info * parent_fi_;
};
#endif // FIELD_INFORMATION_H_ |
C++ | wireshark/ui/qt/utils/frame_information.cpp | /* frame_information.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 <epan/epan_dissect.h>
#include "epan/epan.h"
#include "epan/column.h"
#include "epan/ftypes/ftypes.h"
#include "wiretap/wtap.h"
#include "cfile.h"
#include "file.h"
#include <ui/qt/capture_file.h>
#include "frame_tvbuff.h"
#include <stdint.h>
#include <ui/qt/utils/frame_information.h>
FrameInformation::FrameInformation(CaptureFile * capfile, frame_data * fi, QObject * parent)
:QObject(parent),
fi_(fi),
cap_file_(capfile),
edt_(Q_NULLPTR)
{
wtap_rec_init(&rec_);
ws_buffer_init(&buf_, 1514);
loadFrameTree();
}
void FrameInformation::loadFrameTree()
{
if (! fi_ || ! cap_file_ || !cap_file_->capFile())
return;
if (!cf_read_record(cap_file_->capFile(), fi_, &rec_, &buf_))
return;
edt_ = g_new0(epan_dissect_t, 1);
/* proto tree, visible. We need a proto tree if there's custom columns */
epan_dissect_init(edt_, cap_file_->capFile()->epan, TRUE, TRUE);
col_custom_prime_edt(edt_, &(cap_file_->capFile()->cinfo));
epan_dissect_run(edt_, cap_file_->capFile()->cd_t, &rec_,
frame_tvbuff_new_buffer(&cap_file_->capFile()->provider, fi_, &buf_),
fi_, &(cap_file_->capFile()->cinfo));
epan_dissect_fill_in_columns(edt_, TRUE, TRUE);
}
FrameInformation::~FrameInformation()
{
if (edt_) {
epan_dissect_cleanup(edt_);
g_free(edt_);
}
wtap_rec_cleanup(&rec_);
ws_buffer_free(&buf_);
}
bool FrameInformation::isValid()
{
bool ret = false;
if (fi_ && cap_file_ && edt_ && edt_->tvb)
{
ret = true;
}
return ret;
}
frame_data * FrameInformation::frameData() const
{
return fi_;
}
int FrameInformation::frameNum() const
{
if (! fi_)
return -1;
return fi_->num;
}
const QByteArray FrameInformation::printableData()
{
if (!fi_ || !edt_)
return QByteArray();
int length = tvb_captured_length(edt_->tvb);
const char *data = (const char *)tvb_get_ptr(edt_->tvb, 0, length);
return QByteArray(data, length);
} |
C/C++ | wireshark/ui/qt/utils/frame_information.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef FRAME_INFORMATION_H_
#define FRAME_INFORMATION_H_
#include <config.h>
#include <epan/proto.h>
#include <epan/epan_dissect.h>
#include "epan/epan.h"
#include "epan/column.h"
#include "epan/ftypes/ftypes.h"
#include <ui/qt/capture_file.h>
#include "data_printer.h"
#include <QObject>
class FrameInformation : public QObject, public IDataPrintable
{
Q_OBJECT
Q_INTERFACES(IDataPrintable)
public:
explicit FrameInformation(CaptureFile * cfile, frame_data * fi, QObject * parent = Q_NULLPTR);
virtual ~FrameInformation();
bool isValid();
frame_data * frameData() const;
int frameNum() const;
const QByteArray printableData();
private:
frame_data * fi_;
CaptureFile * cap_file_;
epan_dissect_t * edt_;
wtap_rec rec_; /* Record metadata */
Buffer buf_; /* Record data */
void loadFrameTree();
};
#endif // FRAME_INFORMATION_H_ |
C/C++ | wireshark/ui/qt/utils/idata_printable.h | /** @file
*
* Interface class for classes, which provide an interface to
* print objects
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef IDATA_PRINTABLE_H
#define IDATA_PRINTABLE_H
#include <config.h>
#include <QtPlugin>
#include <QByteArray>
#include <QObject>
class IDataPrintable
{
public:
virtual ~IDataPrintable() {}
virtual const QByteArray printableData() = 0;
};
#define IDataPrintable_iid "org.wireshark.Qt.UI.IDataPrintable"
Q_DECLARE_INTERFACE(IDataPrintable, IDataPrintable_iid)
#endif // IDATA_PRINTABLE_H |
C++ | wireshark/ui/qt/utils/proto_node.cpp | /* proto_node.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/utils/proto_node.h>
#include <ui/qt/utils/field_information.h>
#include <epan/prefs.h>
ProtoNode::ProtoNode(proto_node *node, ProtoNode *parent) :
node_(node), parent_(parent)
{
if (node_) {
int num_children = 0;
for (proto_node *child = node_->first_child; child; child = child->next) {
if (!isHidden(child)) {
num_children++;
}
}
m_children.reserve(num_children);
for (proto_node *child = node_->first_child; child; child = child->next) {
if (!isHidden(child)) {
m_children.append(new ProtoNode(child, this));
}
}
}
}
ProtoNode::~ProtoNode()
{
qDeleteAll(m_children);
}
bool ProtoNode::isValid() const
{
return node_;
}
bool ProtoNode::isChild() const
{
return node_ && node_->parent;
}
ProtoNode* ProtoNode::parentNode()
{
return parent_;
}
QString ProtoNode::labelText() const
{
if (!node_) {
return QString();
}
field_info *fi = PNODE_FINFO(node_);
if (!fi) {
return QString();
}
QString label;
/* was a free format label produced? */
if (fi->rep) {
label = fi->rep->representation;
}
else { /* no, make a generic label */
gchar label_str[ITEM_LABEL_LENGTH];
proto_item_fill_label(fi, label_str);
label = label_str;
}
// Generated takes precedence.
if (proto_item_is_generated(node_)) {
label.prepend("[");
label.append("]");
}
if (proto_item_is_hidden(node_)) {
label.prepend("<");
label.append(">");
}
return label;
}
int ProtoNode::childrenCount() const
{
if (!node_) return 0;
return (int)m_children.count();
}
int ProtoNode::row()
{
if (!isChild()) {
return -1;
}
return (int)parent_->m_children.indexOf(const_cast<ProtoNode*>(this));
}
bool ProtoNode::isExpanded() const
{
if (node_ && node_->finfo && node_->first_child && tree_expanded(node_->finfo->tree_type)) {
return true;
}
return false;
}
proto_node * ProtoNode::protoNode() const
{
return node_;
}
ProtoNode* ProtoNode::child(int row)
{
if (row < 0 || row >= m_children.size())
return nullptr;
return m_children.at(row);
}
ProtoNode::ChildIterator ProtoNode::children() const
{
/* XXX: Iterate over m_children instead?
* Somewhat faster as m_children already excludes any hidden items. */
proto_node *child = node_->first_child;
while (child && isHidden(child)) {
child = child->next;
}
return ProtoNode::ChildIterator(child);
}
ProtoNode::ChildIterator::ChildIterator(ProtoNode::ChildIterator::NodePtr n)
{
node = n;
}
bool ProtoNode::ChildIterator::hasNext()
{
if (! node || node->next == Q_NULLPTR)
return false;
return true;
}
ProtoNode::ChildIterator ProtoNode::ChildIterator::next()
{
do {
node = node->next;
} while (node && isHidden(node));
return *this;
}
ProtoNode ProtoNode::ChildIterator::element()
{
return ProtoNode(node);
}
bool ProtoNode::isHidden(proto_node * node)
{
return proto_item_is_hidden(node) && !prefs.display_hidden_proto_items;
} |
C/C++ | wireshark/ui/qt/utils/proto_node.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PROTO_NODE_H_
#define PROTO_NODE_H_
#include <config.h>
#include <epan/proto.h>
#include <QObject>
#include <QVector>
class ProtoNode
{
public:
class ChildIterator {
public:
typedef struct _proto_node * NodePtr;
ChildIterator(NodePtr n = Q_NULLPTR);
bool hasNext();
ChildIterator next();
ProtoNode element();
protected:
NodePtr node;
};
explicit ProtoNode(proto_node * node = NULL, ProtoNode *parent = nullptr);
~ProtoNode();
bool isValid() const;
bool isChild() const;
bool isExpanded() const;
proto_node *protoNode() const;
ProtoNode *child(int row);
int childrenCount() const;
int row();
ProtoNode *parentNode();
QString labelText() const;
ChildIterator children() const;
private:
proto_node * node_;
QVector<ProtoNode*>m_children;
ProtoNode *parent_;
static bool isHidden(proto_node * node);
};
#endif // PROTO_NODE_H_ |
C++ | wireshark/ui/qt/utils/qt_ui_utils.cpp | /* qt_ui_utils.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <epan/addr_resolv.h>
#include <epan/range.h>
#include <epan/to_str.h>
#include <epan/value_string.h>
#include <epan/prefs.h>
#include <ui/recent.h>
#include <ui/last_open_dir.h>
#include "ui/ws_ui_util.h"
#include <wsutil/str_util.h>
#include <ui/qt/main_application.h>
#include <QAction>
#include <QApplication>
#include <QDateTime>
#include <QDesktopServices>
#include <QDir>
#include <QFileInfo>
#include <QFontDatabase>
#include <QProcess>
#include <QUrl>
#include <QUuid>
#include <QScreen>
/*
* We might want to create our own "wsstring" class with convenience
* methods for handling g_malloc()ed strings, GStrings, and a shortcut
* to .toUtf8().constData().
*/
gchar *qstring_strdup(QString q_string) {
return g_strdup(q_string.toUtf8().constData());
}
QString gchar_free_to_qstring(gchar *glib_string) {
return QString(gchar_free_to_qbytearray(glib_string));
}
QByteArray gchar_free_to_qbytearray(gchar *glib_string)
{
QByteArray qt_bytearray(glib_string);
g_free(glib_string);
return qt_bytearray;
}
QByteArray gstring_free_to_qbytearray(GString *glib_gstring)
{
QByteArray qt_ba(glib_gstring->str);
g_string_free(glib_gstring, TRUE);
return qt_ba;
}
QByteArray gbytearray_free_to_qbytearray(GByteArray *glib_array)
{
QByteArray qt_ba(reinterpret_cast<char *>(glib_array->data), glib_array->len);
g_byte_array_free(glib_array, TRUE);
return qt_ba;
}
const QString int_to_qstring(qint64 value, int field_width, int base)
{
// Qt deprecated QString::sprintf in Qt 5.0, then added ::asprintf in
// Qt 5.5. Rather than navigate a maze of QT_VERSION_CHECKs, just use
// QString::arg.
QString int_qstr;
switch (base) {
case 8:
int_qstr = "0";
break;
case 16:
int_qstr = "0x";
break;
default:
break;
}
int_qstr += QString("%1").arg(value, field_width, base, QChar('0'));
return int_qstr;
}
const QString address_to_qstring(const _address *address, bool enclose)
{
QString address_qstr = QString();
if (address) {
if (enclose && address->type == AT_IPv6) address_qstr += "[";
gchar *address_gchar_p = address_to_str(NULL, address);
address_qstr += address_gchar_p;
wmem_free(NULL, address_gchar_p);
if (enclose && address->type == AT_IPv6) address_qstr += "]";
}
return address_qstr;
}
const QString address_to_display_qstring(const _address *address)
{
QString address_qstr = QString();
if (address) {
gchar *address_gchar_p = address_to_display(NULL, address);
address_qstr = address_gchar_p;
wmem_free(NULL, address_gchar_p);
}
return address_qstr;
}
const QString val_to_qstring(const guint32 val, const value_string *vs, const char *fmt)
{
QString val_qstr;
gchar* gchar_p = val_to_str_wmem(NULL, val, vs, fmt);
val_qstr = gchar_p;
wmem_free(NULL, gchar_p);
return val_qstr;
}
const QString val_ext_to_qstring(const guint32 val, value_string_ext *vse, const char *fmt)
{
QString val_qstr;
gchar* gchar_p = val_to_str_ext_wmem(NULL, val, vse, fmt);
val_qstr = gchar_p;
wmem_free(NULL, gchar_p);
return val_qstr;
}
const QString range_to_qstring(const range_string *range)
{
QString range_qstr = QString();
if (range) {
range_qstr += QString("%1-%2").arg(range->value_min).arg(range->value_max);
}
return range_qstr;
}
const QString bits_s_to_qstring(const double bits_s)
{
return gchar_free_to_qstring(
format_size(bits_s, FORMAT_SIZE_UNIT_NONE, FORMAT_SIZE_PREFIX_SI));
}
const QString file_size_to_qstring(const gint64 size)
{
return gchar_free_to_qstring(
format_size(size, FORMAT_SIZE_UNIT_BYTES, FORMAT_SIZE_PREFIX_SI));
}
const QString time_t_to_qstring(time_t ti_time)
{
QDateTime date_time = QDateTime::fromSecsSinceEpoch(qint64(ti_time));
QString time_str = date_time.toLocalTime().toString("yyyy-MM-dd hh:mm:ss");
return time_str;
}
QString html_escape(const QString plain_string) {
return plain_string.toHtmlEscaped();
}
void smooth_font_size(QFont &font) {
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
QList<int> size_list = QFontDatabase::smoothSizes(font.family(), font.styleName());
#else
QFontDatabase fdb;
QList<int> size_list = fdb.smoothSizes(font.family(), font.styleName());
#endif
if (size_list.size() < 2) return;
int last_size = size_list.takeFirst();
foreach (int cur_size, size_list) {
if (font.pointSize() > last_size && font.pointSize() <= cur_size) {
font.setPointSize(cur_size);
return;
}
last_size = cur_size;
}
}
bool qActionLessThan(const QAction * a1, const QAction * a2) {
return a1->text().compare(a2->text()) < 0;
}
bool qStringCaseLessThan(const QString &s1, const QString &s2)
{
return s1.compare(s2, Qt::CaseInsensitive) < 0;
}
void desktop_show_in_folder(const QString file_path)
{
bool success = false;
// https://stackoverflow.com/questions/3490336/how-to-reveal-in-finder-or-show-in-explorer-with-qt
#if defined(Q_OS_WIN)
QString command = "explorer.exe";
QStringList arguments;
QString path = QDir::toNativeSeparators(file_path);
arguments << "/select," << path + "";
success = QProcess::startDetached(command, arguments);
#elif defined(Q_OS_MAC)
QStringList script_args;
QString escaped_path = file_path;
escaped_path.replace('"', "\\\"");
script_args << "-e"
<< QString("tell application \"Finder\" to reveal POSIX file \"%1\"")
.arg(escaped_path);
if (QProcess::execute("/usr/bin/osascript", script_args) == 0) {
success = true;
script_args.clear();
script_args << "-e"
<< "tell application \"Finder\" to activate";
QProcess::execute("/usr/bin/osascript", script_args);
}
#else
// Is there a way to highlight the file using xdg-open?
#endif
if (!success) {
QFileInfo file_info(file_path);
QDesktopServices::openUrl(QUrl::fromLocalFile(file_info.dir().absolutePath()));
}
}
bool rect_on_screen(const QRect &rect)
{
foreach (QScreen *screen, qApp->screens()) {
if (screen->availableGeometry().contains(rect)) {
return true;
}
}
return false;
}
void set_action_shortcuts_visible_in_context_menu(QList<QAction *> actions)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) && QT_VERSION < QT_VERSION_CHECK(5, 13, 0)
// For QT_VERSION >= 5.13.0 we call styleHints()->setShowShortcutsInContextMenus(true)
// in WiresharkApplication.
// QTBUG-71471
// QTBUG-61181
foreach (QAction *action, actions) {
action->setShortcutVisibleInContextMenu(true);
}
#else
Q_UNUSED(actions)
#endif
}
QVector<rtpstream_id_t *>qvector_rtpstream_ids_copy(QVector<rtpstream_id_t *> stream_ids)
{
QVector<rtpstream_id_t *>new_ids;
foreach(rtpstream_id_t *id, stream_ids) {
rtpstream_id_t *new_id = g_new0(rtpstream_id_t, 1);
rtpstream_id_copy(id, new_id);
new_ids << new_id;
}
return new_ids;
}
void qvector_rtpstream_ids_free(QVector<rtpstream_id_t *> stream_ids)
{
foreach(rtpstream_id_t *id, stream_ids) {
rtpstream_id_free(id);
}
}
QString make_filter_based_on_rtpstream_id(QVector<rtpstream_id_t *> stream_ids)
{
QStringList stream_filters;
QString filter;
foreach(rtpstream_id_t *id, stream_ids) {
QString ip_proto = id->src_addr.type == AT_IPv6 ? "ipv6" : "ip";
stream_filters << QString("(%1.src==%2 && udp.srcport==%3 && %1.dst==%4 && udp.dstport==%5 && rtp.ssrc==0x%6)")
.arg(ip_proto) // %1
.arg(address_to_qstring(&id->src_addr)) // %2
.arg(id->src_port) // %3
.arg(address_to_qstring(&id->dst_addr)) // %4
.arg(id->dst_port) // %5
.arg(id->ssrc, 0, 16);
}
if (stream_filters.length() > 0) {
filter = stream_filters.join(" || ");
}
return filter;
}
QString lastOpenDir()
{
QString result;
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() */
result = QString(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')
result = QString(prefs.gui_fileopen_dir);
break;
}
QDir ld(result);
if (ld.exists())
return result;
return QString();
}
void storeLastDir(QString dir)
{
if (mainApp && dir.length() > 0)
mainApp->setLastOpenDir(qUtf8Printable(dir));
} |
C/C++ | wireshark/ui/qt/utils/qt_ui_utils.h | /** @file
*
* Declarations of Qt-specific UI utility routines
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __QT_UI_UTILS_H__
#define __QT_UI_UTILS_H__
// xxx - copied from ui/gtk/gui_utils.h
/** @file
* Utility functions for working with the Wireshark and GLib APIs.
*/
#include <config.h>
#include <glib.h>
#include "ui/rtp_stream.h"
#include <QString>
class QAction;
class QFont;
class QRect;
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
// These are defined elsewhere in ../gtk/
#define RECENT_KEY_CAPTURE_FILE "recent.capture_file"
#define RECENT_KEY_REMOTE_HOST "recent.remote_host"
struct _address;
struct epan_range;
#ifdef __cplusplus
}
#endif /* __cplusplus */
/*
* Helper macro, to prevent old-style-cast warnings, when using GList in c++ code
*/
#define gxx_list_next(list) ((list) ? ((reinterpret_cast<GList *>(list))->next) : Q_NULLPTR)
#define gxx_constlist_next(list) ((list) ? ((reinterpret_cast<const GList *>(list))->next) : Q_NULLPTR)
#define gxx_list_previous(list) ((list) ? ((reinterpret_cast<GList *>(list))->prev) : Q_NULLPTR)
#define gxx_constlist_previous(list) ((list) ? ((reinterpret_cast<const GList *>(list))->prev) : Q_NULLPTR)
#define gxx_list_data(type, list) ((list) ? ((reinterpret_cast<type>(list->data))) : Q_NULLPTR)
/** Create a glib-compatible copy of a QString.
*
* @param q_string A QString.
*
* @return A copy of the QString. UTF-8 allocated with g_malloc().
*/
gchar *qstring_strdup(QString q_string);
/** Transfer ownership of a GLib character string to a newly constructed QString
*
* @param glib_string A string allocated with g_malloc() or NULL. Will be
* freed.
*
* @return A QString instance created from the input string.
*/
QString gchar_free_to_qstring(gchar *glib_string);
/** Transfer ownership of a GLib character string to a newly constructed QString
*
* @param glib_string A string allocated with g_malloc() or NULL. Will be
* freed.
*
* @return A QByteArray instance created from the input string.
*/
QByteArray gchar_free_to_qbytearray(gchar *glib_string);
/** Transfer ownership of a GLib character string to a newly constructed QByteArray
*
* @param glib_gstring A string allocated with g_malloc() or NULL. Will be
* freed.
*
* @return A QByteArray instance created from the input string.
*/
QByteArray gstring_free_to_qbytearray(GString *glib_gstring);
/** Transfer ownership of a GbyteArray to a newly constructed QByteArray
*
* @param glib_array A GByteArray or NULL. Will be freed.
* @return A QByteArray instance created from the input array.
*/
QByteArray gbytearray_free_to_qbytearray(GByteArray *glib_array);
/** Convert an integer to a formatted string representation.
*
* @param value The integer to format.
* @param field_width Width of the output, not including any base prefix.
* Output will be zero-padded.
* @param base Number base between 2 and 36 (limited by QString::arg).
*
* @return A QString representation of the integer
*/
const QString int_to_qstring(qint64 value, int field_width = 0, int base = 10);
/** Convert an address to a QString using address_to_str().
*
* @param address A pointer to an address.
* @param enclose Enclose IPv6 addresses in square brackets.
*
* @return A QString representation of the address. May be the null string (QString())
*/
const QString address_to_qstring(const struct _address *address, bool enclose = false);
/** Convert an address to a QString using address_to_display().
*
* @param address A pointer to an address.
*
* @return A QString representation of the address. May be the null string (QString())
*/
const QString address_to_display_qstring(const struct _address *address);
/** Convert a value_string to a QString using val_to_str_wmem().
*
* @param val The value to convert to string.
* @param vs value_string array.
* @param fmt Formatting for value not in array.
*
* @return A QString representation of the value_string.
*/
const QString val_to_qstring(const guint32 val, const struct _value_string *vs, const char *fmt)
G_GNUC_PRINTF(3, 0);
/** Convert a value_string_ext to a QString using val_to_str_ext_wmem().
*
* @param val The value to convert to string.
* @param vse value_string_ext array.
* @param fmt Formatting for value not in array.
*
* @return A QString representation of the value_string_ext.
*/
const QString val_ext_to_qstring(const guint32 val, struct _value_string_ext *vse, const char *fmt)
G_GNUC_PRINTF(3, 0);
/** Convert a range to a QString using range_convert_range().
*
* @param range A pointer to a range_string struct.
*
* @return A QString representation of the range_string. May be the null string (QString())
*/
const QString range_to_qstring(const range_string *range);
/** Convert a bits per second value to a human-readable QString using format_size().
*
* @param bits_s The value to convert to string.
*
* @return A QString representation of the data rate in SI units.
*/
const QString bits_s_to_qstring(const double bits_s);
/** Convert a file size value to a human-readable QString using format_size().
*
* @param size The value to convert to string.
*
* @return A QString representation of the file size in SI units.
*/
const QString file_size_to_qstring(const gint64 size);
/** Convert a time_t value to a human-readable QString using QDateTime.
*
* @param ti_time The value to convert.
*
* @return A QString representation of the file size in SI units.
*/
const QString time_t_to_qstring(time_t ti_time);
/** Escape HTML metacharacters in a string.
*
* @param plain_string String to convert.
*
* @return A QString with escaped metacharacters.
*/
QString html_escape(const QString plain_string);
/**
* Round the current size of a font up to its next "smooth" size.
* If a smooth size can't be found the font is left unchanged.
*
* @param font The font to smooth.
*/
void smooth_font_size(QFont &font);
/**
* Compare the text of two QActions. Useful for passing to std::sort.
*
* @param a1 First action
* @param a2 Second action
*/
bool qActionLessThan(const QAction *a1, const QAction *a2);
/**
* Compare two QStrings, ignoring case. Useful for passing to std::sort.
*
* @param s1 First string
* @param s2 Second string
*/
bool qStringCaseLessThan(const QString &s1, const QString &s2);
/**
* Given the path to a file, open its containing folder in the desktop
* shell. Highlight the file if possible.
*
* @param file_path Path to the file.
*/
void desktop_show_in_folder(const QString file_path);
/**
* Test to see if a rect is visible on screen.
*
* @param rect The rect to test, typically a "recent.gui_geometry_*" setting.
* @return true if the rect is completely enclosed by one of the display
* screens, false otherwise.
*/
bool rect_on_screen(const QRect &rect);
/**
* Set the "shortcutVisibleInContextMenu" property to true for
* a list of qactions.
*
* @param actions The actions to make visible.
*/
void set_action_shortcuts_visible_in_context_menu(QList<QAction *> actions);
/**
* Create copy of all rtpstream_ids to new QVector
* => caller must release it with qvector_rtpstream_ids_free()
*
* @param stream_ids List of infos
* @return Vector of rtpstream_ids
*/
QVector<rtpstream_id_t *>qvector_rtpstream_ids_copy(QVector<rtpstream_id_t *> stream_ids);
/**
* Free all rtpstream_ids in QVector
*
* @param stream_ids List of infos
*/
void qvector_rtpstream_ids_free(QVector<rtpstream_id_t *> stream_ids);
/**
* Make display filter from list of rtpstream_id
*
* @param stream_ids List of ids
* @return Filter or empty string
*/
QString make_filter_based_on_rtpstream_id(QVector<rtpstream_id_t *> stream_ids);
/**
* @brief Return the last directory that had been opened.
*
* This can be influenced by prefs.gui_fileopen_style which will allow to either
* open the real last dir or have the user set one specifically.
*
* @return a reference to that directory.
*/
QString lastOpenDir();
/**
* @brief Store the directory as last directory being used
*/
void storeLastDir(QString dir);
#endif /* __QT_UI_UTILS__H__ */
// XXX Add a routine to fetch the HWND corresponding to a widget using QPlatformIntegration |
C++ | wireshark/ui/qt/utils/rtp_audio_file.cpp | /* rtp_audio_file.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/*
* RTP samples are stored in "sparse" file. File knows where are silence gaps
* and they are handled special way (not stored).
*
* File uses Frame as piece of information. One Frame match audio of one
* decoded packet or audio silence in between them. Frame holds information
* about frame type (audio/silence), its length and realtime position and
* sample possition (where decoded audio is really stored, with gaps omitted).
*
* There are three stages of the object use
* - writing data by frames during decoding of the stream
* - reading data by frames during creating the visual waveform
* - reading data by bytes/samples during audio play or audio save
*
* There is no stage indication in the object, but there are different calls
* used by the code. For last stage the object looks like QIODevice therefore
* any read of it looks like reading of sequence of bytes.
*
* If audio starts later than start of the file, first Frame contains silence
* record. It is leaved out at some cases.
*/
#include "rtp_audio_file.h"
#include <ws_attributes.h>
RtpAudioFile::RtpAudioFile(bool use_disk_for_temp, bool use_disk_for_frames):
real_pos_(0)
, real_size_(0)
, sample_pos_(0)
, sample_size_(0)
{
QString tempname;
// ReadOnly because we write different way
QIODevice::open(QIODevice::ReadOnly);
tempname = "memory";
if (use_disk_for_temp) {
tempname = QString("%1/wireshark_rtp_stream").arg(QDir::tempPath());
sample_file_ = new QTemporaryFile(tempname, this);
} else {
sample_file_ = new QBuffer(this);
}
if (!sample_file_->open(QIODevice::ReadWrite)) {
// We are out of file resources
delete sample_file_;
qWarning() << "Can't create temp file in " << tempname;
throw -1;
}
tempname = "memory";
if (use_disk_for_frames) {
tempname = QString("%1/wireshark_rtp_frames").arg(QDir::tempPath());
sample_file_frame_ = new QTemporaryFile(tempname, this);
} else {
sample_file_frame_ = new QBuffer(this);
}
if (!sample_file_frame_->open(QIODevice::ReadWrite)) {
// We are out of file resources
delete sample_file_;
delete sample_file_frame_;
qWarning() << "Can't create frame file in " << tempname;
throw -1;
}
}
RtpAudioFile::~RtpAudioFile()
{
if (sample_file_) delete sample_file_;
if (sample_file_frame_) delete sample_file_frame_;
}
/*
* Functions for writing Frames
*/
void RtpAudioFile::setFrameWriteStage()
{
sample_file_->seek(0);
sample_file_frame_->seek(0);
real_pos_ = 0;
real_size_ = 0;
sample_pos_ = 0;
sample_size_ = 0;
}
void RtpAudioFile::frameUpdateRealCounters(qint64 written_bytes)
{
if (real_pos_ < real_size_) {
// We are writing before end, calculate if we are over real_size_
qint64 diff = real_pos_ + written_bytes - real_size_;
if (diff > 0) {
// Update size
real_size_ += diff;
}
} else {
real_size_ += written_bytes;
}
real_pos_ += written_bytes;
}
void RtpAudioFile::frameUpdateSampleCounters(qint64 written_bytes)
{
if (sample_pos_ < sample_size_) {
// We are writing before end, calculate if we are over sample_size_
qint64 diff = sample_pos_ + written_bytes - sample_size_;
if (diff > 0) {
// Update size
sample_size_ += diff;
}
} else {
sample_size_ += written_bytes;
}
sample_pos_ += written_bytes;
}
qint64 RtpAudioFile::frameWriteFrame(guint32 frame_num, qint64 real_pos, qint64 sample_pos, qint64 len, rtp_frame_type type)
{
rtp_frame_info frame_info;
frame_info.real_pos = real_pos;
frame_info.sample_pos = sample_pos;
frame_info.len = len;
frame_info.frame_num = frame_num;
frame_info.type = type;
return sample_file_frame_->write((char *)&frame_info, sizeof(frame_info));
}
void RtpAudioFile::frameWriteSilence(guint32 frame_num, qint64 samples)
{
if (samples < 1) return;
qint64 silence_bytes = samples * SAMPLE_BYTES;
frameWriteFrame(frame_num, real_pos_, sample_pos_, silence_bytes, RTP_FRAME_SILENCE);
frameUpdateRealCounters(silence_bytes);
}
qint64 RtpAudioFile::frameWriteSamples(guint32 frame_num, const char *data, qint64 max_size)
{
gint64 written;
written = sample_file_->write(data, max_size);
if (written != -1) {
frameWriteFrame(frame_num, real_pos_, sample_pos_, written, RTP_FRAME_AUDIO);
frameUpdateRealCounters(written);
frameUpdateSampleCounters(written);
}
return written;
}
/*
* Functions for reading Frames
*/
void RtpAudioFile::setFrameReadStage(qint64 prepend_samples)
{
sample_file_frame_->seek(0);
if (prepend_samples > 0) {
// Skip first frame which contains openning silence
sample_file_frame_->read((char *)&cur_frame_, sizeof(cur_frame_));
}
}
bool RtpAudioFile::readFrameSamples(gint32 *read_buff_bytes, SAMPLE **read_buff, spx_uint32_t *read_len, guint32 *frame_num, rtp_frame_type *type)
{
rtp_frame_info frame_info;
guint64 read_bytes = 0;
if (!sample_file_frame_->read((char *)&frame_info, sizeof(frame_info))) {
// Can't read frame, some error occurred
return false;
}
*frame_num = frame_info.frame_num;
*type = frame_info.type;
if (frame_info.type == RTP_FRAME_AUDIO) {
// Resize buffer when needed
if (frame_info.len > *read_buff_bytes) {
while ((frame_info.len > *read_buff_bytes)) {
*read_buff_bytes *= 2;
}
*read_buff = (SAMPLE *) g_realloc(*read_buff, *read_buff_bytes);
}
sample_file_->seek(frame_info.sample_pos);
read_bytes = sample_file_->read((char *)*read_buff, frame_info.len);
} else {
// For silence we do nothing
read_bytes = frame_info.len;
}
*read_len = (spx_uint32_t)(read_bytes / SAMPLE_BYTES);
return true;
}
/*
* Functions for reading data during play
*/
void RtpAudioFile::setDataReadStage()
{
sample_file_frame_->seek(0);
sample_file_frame_->read((char *)&cur_frame_, sizeof(cur_frame_));
real_pos_ = cur_frame_.real_pos;
}
bool RtpAudioFile::open(QIODevice::OpenMode mode)
{
if (mode == QIODevice::ReadOnly) {
return true;
}
return false;
}
qint64 RtpAudioFile::size() const
{
return real_size_;
}
qint64 RtpAudioFile::pos() const
{
return real_pos_;
}
/*
* Seek starts from beginning of Frames and search one where offset belongs
* to. It looks inefficient, but seek is used usually just to jump to 0 or
* to skip first Frame where silence is stored.
*/
bool RtpAudioFile::seek(qint64 off)
{
if (real_size_ <= off) {
// Can't seek above end of file
return false;
}
// Search for correct offset from first frame
sample_file_frame_->seek(0);
while (1) {
// Read frame
if (!sample_file_frame_->read((char *)&cur_frame_, sizeof(cur_frame_))) {
// Can't read frame, some error occurred
return false;
}
if ((cur_frame_.real_pos + cur_frame_.len) > off) {
// We found correct frame
// Calculate offset in frame
qint64 diff = off - cur_frame_.real_pos;
qint64 new_real_pos = cur_frame_.real_pos + diff;
qint64 new_sample_pos = cur_frame_.sample_pos + diff;
if (cur_frame_.type == RTP_FRAME_AUDIO) {
// For audio frame we should to seek to correct place
if (!sample_file_->seek(new_sample_pos)) {
return false;
}
// Real seek was successful
real_pos_ = new_real_pos;
return true;
} else {
// For silence frame we blindly confirm it
real_pos_ = new_real_pos;
return true;
}
}
}
return false;
}
qint64 RtpAudioFile::sampleFileSize()
{
return real_size_;
}
void RtpAudioFile::seekSample(qint64 samples)
{
seek(sizeof(SAMPLE) * samples);
}
qint64 RtpAudioFile::readFrameData(char *data , qint64 want_read)
{
// Calculate remaining data in frame
qint64 remaining = cur_frame_.len - (real_pos_ - cur_frame_.real_pos);
qint64 was_read;
if (remaining < want_read) {
// Incorrect call, can't read more than is stored in frame
return -1;
}
if (cur_frame_.type == RTP_FRAME_AUDIO) {
was_read = sample_file_->read(data, want_read);
real_pos_ += was_read;
} else {
memset(data, 0, want_read);
real_pos_ += want_read;
was_read = want_read;
}
return was_read;
}
qint64 RtpAudioFile::readSample(SAMPLE *sample)
{
return read((char *)sample, sizeof(SAMPLE));
}
qint64 RtpAudioFile::getTotalSamples()
{
return (real_size_/(qint64)sizeof(SAMPLE));
}
qint64 RtpAudioFile::getEndOfSilenceSample()
{
if (cur_frame_.type == RTP_FRAME_SILENCE) {
return (cur_frame_.real_pos + cur_frame_.len) / (qint64)sizeof(SAMPLE);
} else {
return -1;
}
}
qint64 RtpAudioFile::readData(char *data, qint64 maxSize)
{
qint64 to_read = maxSize;
qint64 can_read;
qint64 was_read = 0;
qint64 remaining;
while (1) {
// Calculate remaining data in frame
remaining = cur_frame_.len - (real_pos_ - cur_frame_.real_pos);
if (remaining > to_read) {
// Even we want to read more, we can read just till end of frame
can_read = to_read;
} else {
can_read = remaining;
}
if (can_read==readFrameData(data, can_read)) {
to_read -= can_read;
data += can_read;
was_read += can_read;
if (real_pos_ >= cur_frame_.real_pos + cur_frame_.len) {
// We exhausted the frame, read next one
if (!sample_file_frame_->read((char *)&cur_frame_, sizeof(cur_frame_))) {
// We are at the end of the file
return was_read;
}
if ((cur_frame_.type == RTP_FRAME_AUDIO) && (!sample_file_->seek(cur_frame_.sample_pos))) {
// We tried to seek to correct place, but it failed
return -1;
}
}
if (to_read == 0) {
return was_read;
}
} else {
return -1;
}
}
}
qint64 RtpAudioFile::writeData(const char *data _U_, qint64 maxSize _U_)
{
// Writing is not supported
return -1;
} |
C/C++ | wireshark/ui/qt/utils/rtp_audio_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 RTP_AUDIO_FILE_H
#define RTP_AUDIO_FILE_H
#include "config.h"
#include <ui/rtp_media.h>
#include <speex/speex_resampler.h>
#include <QIODevice>
#include <QDir>
#include <QTemporaryFile>
#include <QDebug>
#include <QBuffer>
struct _rtp_info;
typedef enum {
RTP_FRAME_AUDIO = 0,
RTP_FRAME_SILENCE
} rtp_frame_type;
// Structure used for storing frame num during visual waveform decoding
typedef struct {
qint64 real_pos;
qint64 sample_pos;
qint64 len;
guint32 frame_num;
rtp_frame_type type;
} rtp_frame_info;
class RtpAudioFile: public QIODevice
{
public:
explicit RtpAudioFile(bool use_disk_for_temp, bool use_disk_for_frames);
~RtpAudioFile();
// Functions for writing Frames
void setFrameWriteStage();
void frameWriteSilence(guint32 frame_num, qint64 samples);
qint64 frameWriteSamples(guint32 frame_num, const char *data, qint64 max_size);
// Functions for reading Frames
void setFrameReadStage(qint64 prepend_samples);
bool readFrameSamples(gint32 *read_buff_bytes, SAMPLE **read_buff, spx_uint32_t *read_len, guint32 *frame_num, rtp_frame_type *type);
// Functions for reading data during play
void setDataReadStage();
bool open(QIODevice::OpenMode mode) override;
qint64 size() const override;
qint64 pos() const override;
bool seek(qint64 off) override;
qint64 sampleFileSize();
void seekSample(qint64 samples);
qint64 readSample(SAMPLE *sample);
qint64 getTotalSamples();
qint64 getEndOfSilenceSample();
protected:
// Functions for reading data during play
qint64 readData(char *data, qint64 maxSize) override;
qint64 writeData(const char *data, qint64 maxSize) override;
private:
QIODevice *sample_file_; // Stores waveform samples
QIODevice *sample_file_frame_; // Stores rtp_packet_info per packet
qint64 real_pos_;
qint64 real_size_;
qint64 sample_pos_;
qint64 sample_size_;
rtp_frame_info cur_frame_;
// Functions for writing Frames
qint64 frameWriteFrame(guint32 frame_num, qint64 real_pos, qint64 sample_pos, qint64 len, rtp_frame_type type);
void frameUpdateRealCounters(qint64 written_bytes);
void frameUpdateSampleCounters(qint64 written_bytes);
// Functions for reading Frames
// Functions for reading data during play
qint64 readFrameData(char *data , qint64 want_read);
};
#endif // RTP_AUDIO_FILE_H |
C++ | wireshark/ui/qt/utils/rtp_audio_routing.cpp | /* rtp_audio_routing.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "rtp_audio_routing.h"
AudioRouting::AudioRouting(bool muted, audio_routing_channel_t channel):
muted_(muted),
channel_(channel)
{
}
char const *AudioRouting::formatAudioRoutingToString()
{
if (muted_) {
return "Muted";
} else {
switch (channel_) {
case channel_any:
// Should not happen ever
return "ERR";
case channel_mono:
return "Play";
case channel_stereo_left:
return "L";
case channel_stereo_right:
return "R";
case channel_stereo_both:
return "L+R";
}
}
// Should not happen ever
return "ERR";
}
AudioRouting AudioRouting::getNextChannel(bool stereo_available)
{
if (stereo_available) {
// Stereo
if (muted_) {
return AudioRouting(AUDIO_UNMUTED, channel_stereo_left);
} else {
switch (channel_) {
case channel_stereo_left:
return AudioRouting(AUDIO_UNMUTED, channel_stereo_both);
case channel_stereo_both:
return AudioRouting(AUDIO_UNMUTED, channel_stereo_right);
case channel_stereo_right:
return AudioRouting(AUDIO_MUTED, channel_stereo_right);
default:
return AudioRouting(AUDIO_UNMUTED, channel_stereo_left);
}
}
} else {
// Mono
if (muted_) {
return AudioRouting(AUDIO_UNMUTED, channel_mono);
} else {
return AudioRouting(AUDIO_MUTED, channel_mono);
}
}
}
AudioRouting AudioRouting::convert(bool stereo_available)
{
// Muting is not touched by conversion
if (stereo_available) {
switch (channel_) {
case channel_mono:
// Mono -> Stereo
return AudioRouting(muted_, channel_stereo_both);
case channel_any:
// Unknown -> Unknown
return AudioRouting(muted_, channel_any);
default:
// Stereo -> Stereo
return AudioRouting(muted_, channel_);
}
} else {
switch (channel_) {
case channel_mono:
// Mono -> Mono
return AudioRouting(muted_, channel_mono);
case channel_any:
// Unknown -> Unknown
return AudioRouting(muted_, channel_any);
default:
// Stereo -> Mono
return AudioRouting(muted_, channel_mono);
}
}
}
void AudioRouting::mergeAudioRouting(AudioRouting new_audio_routing)
{
if (new_audio_routing.getChannel() == channel_any) {
muted_ = new_audio_routing.isMuted();
} else {
muted_ = new_audio_routing.isMuted();
channel_ = new_audio_routing.getChannel();
}
} |
C/C++ | wireshark/ui/qt/utils/rtp_audio_routing.h | /** @file
*
* Declarations of RTP audio routing class
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef RTP_AUDIO_ROUTING_H
#define RTP_AUDIO_ROUTING_H
#include "config.h"
#include <QMetaType>
typedef enum {
channel_any, // Used just for changes of mute
channel_mono, // Play
channel_stereo_left, // L
channel_stereo_right, // R
channel_stereo_both // L+R
} audio_routing_channel_t;
class AudioRouting
{
public:
AudioRouting() = default;
~AudioRouting() = default;
AudioRouting(const AudioRouting &) = default;
AudioRouting &operator=(const AudioRouting &) = default;
AudioRouting(bool muted, audio_routing_channel_t channel);
bool isMuted() { return muted_; }
void setMuted(bool muted) { muted_ = muted; }
audio_routing_channel_t getChannel() { return channel_; }
void setChannel(audio_routing_channel_t channel) { channel_ = channel; }
char const *formatAudioRoutingToString();
AudioRouting getNextChannel(bool stereo_available);
AudioRouting convert(bool stereo_available);
void mergeAudioRouting(AudioRouting new_audio_routing);
private:
bool muted_;
audio_routing_channel_t channel_;
};
Q_DECLARE_METATYPE(AudioRouting)
#define AUDIO_MUTED true
#define AUDIO_UNMUTED false
#endif // RTP_AUDIO_ROUTING_H |
C++ | wireshark/ui/qt/utils/rtp_audio_routing_filter.cpp | /* rtp_audio_routing_filter.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "rtp_audio_routing_filter.h"
AudioRoutingFilter::AudioRoutingFilter(QIODevice *input, bool stereo_required, AudioRouting audio_routing) :
QIODevice(input),
input_(input),
stereo_required_(stereo_required),
audio_routing_(audio_routing)
{
QIODevice::open(input_->openMode());
}
void AudioRoutingFilter::close()
{
input_->close();
}
qint64 AudioRoutingFilter::size() const
{
if (!stereo_required_)
{
return input_->size();
} else {
// For stereo we must return twice more bytes
return input_->size() * 2;
}
}
qint64 AudioRoutingFilter::pos() const
{
if (!stereo_required_)
{
return input_->pos();
} else {
// For stereo we must return twice more bytes
return input_->pos() * 2;
}
}
bool AudioRoutingFilter::seek(qint64 off)
{
if (!stereo_required_)
{
return input_->seek(off);
} else {
// For stereo we must return half of offset
return input_->seek(off / 2);
}
}
qint64 AudioRoutingFilter::readData(char *data, qint64 maxSize)
{
if (!stereo_required_)
{
// For mono we just return data
return input_->read(data, maxSize);
} else {
// For stereo
gint64 silence = 0;
// Read half of data
qint64 readBytes = input_->read(data, maxSize/SAMPLE_BYTES);
// If error or no data available, just return
if (readBytes < 1)
return readBytes;
// Expand it
for(qint64 i = (readBytes / SAMPLE_BYTES) - 1; i > 0; i--) {
qint64 j = SAMPLE_BYTES * i;
if (audio_routing_.getChannel() == channel_stereo_left) {
memcpy(&data[j*2], &data[j], SAMPLE_BYTES);
memcpy(&data[j*2+SAMPLE_BYTES], &silence, SAMPLE_BYTES);
} else if (audio_routing_.getChannel() == channel_stereo_right) {
memcpy(&data[j*2], &silence, SAMPLE_BYTES);
memcpy(&data[j*2+SAMPLE_BYTES], &data[j], SAMPLE_BYTES);
} else if (audio_routing_.getChannel() == channel_stereo_both) {
memcpy(&data[j*2], &data[j], SAMPLE_BYTES);
memcpy(&data[j*2+SAMPLE_BYTES], &data[j], SAMPLE_BYTES);
} else {
// Should not happen ever
memcpy(&data[j*2], &silence, SAMPLE_BYTES*2);
}
}
return readBytes * 2;
}
}
qint64 AudioRoutingFilter::writeData(const char *data, qint64 maxSize)
{
return input_->write(data, maxSize);
}
/*
bool AudioRoutingFilter::atEnd() const
{
return input_->atEnd();
}
bool AudioRoutingFilter::canReadLine() const
{
return input_->canReadLine();
}
*/ |
C/C++ | wireshark/ui/qt/utils/rtp_audio_routing_filter.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef RTP_AUDIO_ROUTING_FILTER_H
#define RTP_AUDIO_ROUTING_FILTER_H
#include "config.h"
#include <ui/rtp_media.h>
#include <ui/qt/utils/rtp_audio_routing.h>
#include <QObject>
#include <QIODevice>
class AudioRoutingFilter: public QIODevice
{
public:
explicit AudioRoutingFilter(QIODevice *input, bool stereo_required, AudioRouting audio_routing);
~AudioRoutingFilter() { }
void close() override;
qint64 size() const override;
qint64 pos() const override;
bool seek(qint64 off) override;
protected:
qint64 readData(char *data, qint64 maxSize) override;
qint64 writeData(const char *data, qint64 maxSize) override;
private:
QIODevice *input_;
bool stereo_required_;
AudioRouting audio_routing_;
};
#endif // RTP_AUDIO_ROUTING_FILTER_H |
C++ | wireshark/ui/qt/utils/rtp_audio_silence_generator.cpp | /* rtp_audio_silence_stream.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "rtp_audio_silence_generator.h"
#include <ws_attributes.h>
AudioSilenceGenerator::AudioSilenceGenerator(QObject *parent) : QIODevice(parent)
{
QIODevice::open(QIODevice::ReadOnly);
}
qint64 AudioSilenceGenerator::size() const
{
return std::numeric_limits <qint64>::max();
}
qint64 AudioSilenceGenerator::pos() const
{
return pos_;
}
bool AudioSilenceGenerator::seek(qint64 off)
{
pos_ = off;
return true;
}
qint64 AudioSilenceGenerator::readData(char *data, qint64 maxSize)
{
memset(data, 0, maxSize);
pos_ += maxSize;
return maxSize;
}
qint64 AudioSilenceGenerator::writeData(const char *data _U_, qint64 maxSize)
{
return maxSize;
} |
C/C++ | wireshark/ui/qt/utils/rtp_audio_silence_generator.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef RTP_AUDIO_SILENCE_GENERATOR_H
#define RTP_AUDIO_SILENCE_GENERATOR_H
#include "config.h"
#include <QIODevice>
class AudioSilenceGenerator: public QIODevice
{
public:
explicit AudioSilenceGenerator(QObject *parent = nullptr);
~AudioSilenceGenerator() { }
qint64 size() const override;
qint64 pos() const override;
bool seek(qint64 off) override;
protected:
qint64 readData(char *data, qint64 maxSize) override;
qint64 writeData(const char *data, qint64 maxSize) override;
private:
quint64 pos_;
};
#endif // RTP_AUDIO_SILENCE_GENERATOR_H |
C++ | wireshark/ui/qt/utils/stock_icon.cpp | /* stock_icon.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/utils/stock_icon.h>
// Stock icons. Based on gtk/stock_icons.h
// Toolbar icon sizes:
// macOS freestanding: 32x32, 32x32@2x, segmented (inside a button): <= 19x19
// Windows: 16x16, 24x24, 32x32
// GNOME: 24x24 (default), 48x48
// References:
//
// https://specifications.freedesktop.org/icon-theme-spec/icon-theme-spec-latest.html
// https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
//
// https://mithatkonar.com/wiki/doku.php/qt/icons
//
// https://web.archive.org/web/20140829010224/https://developer.apple.com/library/mac/documentation/userexperience/conceptual/applehiguidelines/IconsImages/IconsImages.html
// https://developer.apple.com/design/human-interface-guidelines/macos/icons-and-images/image-size-and-resolution/
// https://developer.apple.com/design/human-interface-guidelines/macos/icons-and-images/app-icon/
// https://docs.microsoft.com/en-us/windows/win32/uxguide/vis-icons
// https://developer.gnome.org/hig/stable/icons-and-artwork.html.en
// https://docs.microsoft.com/en-us/visualstudio/designers/the-visual-studio-image-library
// To do:
// - 32x32, 48x48, 64x64, and unscaled (.svg) icons.
// - Indent find & go actions when those panes are open.
// - Replace or remove:
// WIRESHARK_STOCK_CAPTURE_FILTER x-capture-filter
// WIRESHARK_STOCK_DISPLAY_FILTER x-display-filter
// GTK_STOCK_SELECT_COLOR x-coloring-rules
// GTK_STOCK_PREFERENCES preferences-system
// GTK_STOCK_HELP help-contents
#include <QApplication>
#include <QFile>
#include <QFontMetrics>
#include <QMap>
#include <QPainter>
#include <QPainterPath>
#include <QStyle>
#include <QStyleOption>
static const QString path_pfx_ = ":/stock_icons/";
// Map FreeDesktop icon names to Qt standard pixmaps.
static QMap<QString, QStyle::StandardPixmap> icon_name_to_standard_pixmap_;
StockIcon::StockIcon(const QString icon_name) :
QIcon()
{
if (icon_name_to_standard_pixmap_.isEmpty()) {
fillIconNameMap();
}
// Does our theme contain this icon?
// X11 only as per the QIcon documentation.
if (hasThemeIcon(icon_name)) {
QIcon theme_icon = fromTheme(icon_name);
swap(theme_icon);
return;
}
// Is this is an icon we've manually mapped to a standard pixmap below?
if (icon_name_to_standard_pixmap_.contains(icon_name)) {
QIcon standard_icon = qApp->style()->standardIcon(icon_name_to_standard_pixmap_[icon_name]);
swap(standard_icon);
return;
}
// Is this one of our locally sourced, cage-free, organic icons?
QStringList types = QStringList() << "8x8" << "14x14" << "16x16" << "24x14" << "24x24";
QList<QIcon::Mode> icon_modes = QList<QIcon::Mode>()
<< QIcon::Disabled
<< QIcon::Active
<< QIcon::Selected;
foreach (QString type, types) {
// First, check for a template (mask) icon
// Templates should be monochrome as described at
// https://developer.apple.com/design/human-interface-guidelines/macos/icons-and-images/custom-icons/
// Transparency is supported.
QString icon_path_template = path_pfx_ + QString("%1/%2.template.png").arg(type).arg(icon_name);
if (QFile::exists(icon_path_template)) {
QIcon mask_icon = QIcon();
mask_icon.addFile(icon_path_template);
foreach(QSize sz, mask_icon.availableSizes()) {
QPixmap mask_pm = mask_icon.pixmap(sz);
QImage normal_img(sz, QImage::Format_ARGB32);
QPainter painter(&normal_img);
QBrush br(qApp->palette().color(QPalette::Active, QPalette::WindowText));
painter.fillRect(0, 0, sz.width(), sz.height(), br);
painter.setCompositionMode(QPainter::CompositionMode_DestinationIn);
painter.drawPixmap(0, 0, mask_pm);
QPixmap normal_pm = QPixmap::fromImage(normal_img);
addPixmap(normal_pm, QIcon::Normal, QIcon::On);
addPixmap(normal_pm, QIcon::Normal, QIcon::Off);
QStyleOption opt = {};
opt.palette = qApp->palette();
foreach (QIcon::Mode icon_mode, icon_modes) {
QPixmap mode_pm = qApp->style()->generatedIconPixmap(icon_mode, normal_pm, &opt);
addPixmap(mode_pm, icon_mode, QIcon::On);
addPixmap(mode_pm, icon_mode, QIcon::Off);
}
}
continue;
}
// Regular full-color icons
QString icon_path = path_pfx_ + QString("%1/%2.png").arg(type).arg(icon_name);
if (QFile::exists(icon_path)) {
addFile(icon_path);
}
// Along with each name check for "<name>.active" and
// "<name>.selected" for the Active and Selected modes, and
// "<name>.on" to use for the on (checked) state.
// XXX Allow more (or all) combinations.
QString icon_path_active = path_pfx_ + QString("%1/%2.active.png").arg(type).arg(icon_name);
if (QFile::exists(icon_path_active)) {
addFile(icon_path_active, QSize(), QIcon::Active, QIcon::On);
}
QString icon_path_selected = path_pfx_ + QString("%1/%2.selected.png").arg(type).arg(icon_name);
if (QFile::exists(icon_path_selected)) {
addFile(icon_path_selected, QSize(), QIcon::Selected, QIcon::On);
}
QString icon_path_on = path_pfx_ + QString("%1/%2.on.png").arg(type).arg(icon_name);
if (QFile::exists(icon_path_on)) {
addFile(icon_path_on, QSize(), QIcon::Normal, QIcon::On);
}
}
}
// Create a square icon filled with the specified color.
QIcon StockIcon::colorIcon(const QRgb bg_color, const QRgb fg_color, const QString glyph)
{
QList<int> sizes = QList<int>() << 12 << 16 << 24 << 32 << 48;
QIcon color_icon;
foreach (int size, sizes) {
QPixmap pm(size, size);
QPainter painter(&pm);
QRect border(0, 0, size - 1, size - 1);
painter.setPen(fg_color);
painter.setBrush(QColor(bg_color));
painter.drawRect(border);
if (!glyph.isEmpty()) {
QFont font(qApp->font());
font.setPointSizeF(size / 2.0);
painter.setFont(font);
QRectF bounding = painter.boundingRect(pm.rect(), glyph, Qt::AlignHCenter | Qt::AlignVCenter);
painter.drawText(bounding, glyph);
}
color_icon.addPixmap(pm);
}
return color_icon;
}
// Create a triangle icon filled with the specified color.
QIcon StockIcon::colorIconTriangle(const QRgb bg_color, const QRgb fg_color)
{
QList<int> sizes = QList<int>() << 12 << 16 << 24 << 32 << 48;
QIcon color_icon;
foreach (int size, sizes) {
QPixmap pm(size, size);
QPainter painter(&pm);
QPainterPath triangle;
pm.fill();
painter.fillRect(0, 0, size-1, size-1, Qt::transparent);
painter.setPen(fg_color);
painter.setBrush(QColor(bg_color));
triangle.moveTo(0, size-1);
triangle.lineTo(size-1, size-1);
triangle.lineTo((size-1)/2, 0);
triangle.closeSubpath();
painter.fillPath(triangle, QColor(bg_color));
color_icon.addPixmap(pm);
}
return color_icon;
}
// Create a cross icon filled with the specified color.
QIcon StockIcon::colorIconCross(const QRgb bg_color, const QRgb fg_color)
{
QList<int> sizes = QList<int>() << 12 << 16 << 24 << 32 << 48;
QIcon color_icon;
foreach (int size, sizes) {
QPixmap pm(size, size);
QPainter painter(&pm);
QPainterPath cross;
pm.fill();
painter.fillRect(0, 0, size-1, size-1, Qt::transparent);
painter.setPen(QPen(QBrush(bg_color), 3));
painter.setBrush(QColor(fg_color));
cross.moveTo(0, 0);
cross.lineTo(size-1, size-1);
cross.moveTo(0, size-1);
cross.lineTo(size-1, 0);
painter.drawPath(cross);
color_icon.addPixmap(pm);
}
return color_icon;
}
// Create a circle icon filled with the specified color.
QIcon StockIcon::colorIconCircle(const QRgb bg_color, const QRgb fg_color)
{
QList<int> sizes = QList<int>() << 12 << 16 << 24 << 32 << 48;
QIcon color_icon;
foreach (int size, sizes) {
QPixmap pm(size, size);
QPainter painter(&pm);
QRect border(2, 2, size - 3, size - 3);
pm.fill();
painter.fillRect(0, 0, size-1, size-1, Qt::transparent);
painter.setPen(QPen(QBrush(bg_color), 3));
painter.setBrush(QColor(fg_color));
painter.setBrush(QColor(bg_color));
painter.drawEllipse(border);
color_icon.addPixmap(pm);
}
return color_icon;
}
void StockIcon::fillIconNameMap()
{
// Note that some of Qt's standard pixmaps are awful. We shouldn't add an
// entry just because a match can be made.
icon_name_to_standard_pixmap_["document-open"] = QStyle::SP_DirIcon;
icon_name_to_standard_pixmap_["media-playback-pause"] = QStyle::SP_MediaPause;
icon_name_to_standard_pixmap_["media-playback-start"] = QStyle::SP_MediaPlay;
icon_name_to_standard_pixmap_["media-playback-stop"] = QStyle::SP_MediaStop;
} |
C/C++ | wireshark/ui/qt/utils/stock_icon.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef STOCK_ICON_H
#define STOCK_ICON_H
#include <QIcon>
/** @file
* Goal: Beautiful icons appropriate for each of our supported platforms.
*/
// Supported standard names:
// document-open
// Supported custom names (see images/toolbar):
// x-capture-file-close
// x-capture-file-save
class StockIcon : public QIcon
{
public:
explicit StockIcon(const QString icon_name);
static QIcon colorIcon(const QRgb bg_color, const QRgb fg_color, const QString glyph = QString());
static QIcon colorIconTriangle(const QRgb bg_color, const QRgb fg_color);
static QIcon colorIconCross(const QRgb bg_color, const QRgb fg_color);
static QIcon colorIconCircle(const QRgb bg_color, const QRgb fg_color);
private:
void fillIconNameMap();
};
#endif // STOCK_ICON_H |
C/C++ | wireshark/ui/qt/utils/tango_colors.h | /** @file
*
* Tango theme colors
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __TANGO_COLORS_H__
#define __TANGO_COLORS_H__
// http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines
// with added hues from http://emilis.info/other/extended_tango/
// (all colors except aluminium)
const QRgb tango_aluminium_1 = 0xeeeeec;
const QRgb tango_aluminium_2 = 0xd3d7cf;
const QRgb tango_aluminium_3 = 0xbabdb6;
const QRgb tango_aluminium_4 = 0x888a85;
const QRgb tango_aluminium_5 = 0x555753;
const QRgb tango_aluminium_6 = 0x2e3436;
const QRgb tango_butter_1 = 0xfeffd0;
const QRgb tango_butter_2 = 0xfffc9c;
const QRgb tango_butter_3 = 0xfce94f;
const QRgb tango_butter_4 = 0xedd400;
const QRgb tango_butter_5 = 0xc4a000;
const QRgb tango_butter_6 = 0x725000;
const QRgb tango_chameleon_1 = 0xe4ffc7;
const QRgb tango_chameleon_2 = 0xb7f774;
const QRgb tango_chameleon_3 = 0x8ae234;
const QRgb tango_chameleon_4 = 0x73d216;
const QRgb tango_chameleon_5 = 0x4e9a06;
const QRgb tango_chameleon_6 = 0x2a5703;
const QRgb tango_chocolate_1 = 0xfaf0d7;
const QRgb tango_chocolate_2 = 0xefd0a7;
const QRgb tango_chocolate_3 = 0xe9b96e;
const QRgb tango_chocolate_4 = 0xc17d11;
const QRgb tango_chocolate_5 = 0x8f5902;
const QRgb tango_chocolate_6 = 0x503000;
const QRgb tango_orange_1 = 0xfff0d7;
const QRgb tango_orange_2 = 0xffd797;
const QRgb tango_orange_3 = 0xfcaf3e;
const QRgb tango_orange_4 = 0xf57900;
const QRgb tango_orange_5 = 0xce5c00;
const QRgb tango_orange_6 = 0x8c3700;
const QRgb tango_plum_1 = 0xfce0ff;
const QRgb tango_plum_2 = 0xe0c0e4;
const QRgb tango_plum_3 = 0xad7fa8;
const QRgb tango_plum_4 = 0x75507b;
const QRgb tango_plum_5 = 0x5c3566;
const QRgb tango_plum_6 = 0x371740;
const QRgb tango_scarlet_red_1 = 0xffcccc;
const QRgb tango_scarlet_red_2 = 0xf78787;
const QRgb tango_scarlet_red_3 = 0xef2929;
const QRgb tango_scarlet_red_4 = 0xcc0000;
const QRgb tango_scarlet_red_5 = 0xa40000;
const QRgb tango_scarlet_red_6 = 0x600000;
const QRgb tango_sky_blue_1 = 0xdaeeff;
const QRgb tango_sky_blue_2 = 0x97c4f0;
const QRgb tango_sky_blue_3 = 0x729fcf;
const QRgb tango_sky_blue_4 = 0x3465a4;
const QRgb tango_sky_blue_5 = 0x204a87;
const QRgb tango_sky_blue_6 = 0x0a3050;
#endif // __TANGO_COLORS_H__ |
C/C++ | wireshark/ui/qt/utils/variant_pointer.h | /** @file
*
* Range routines
*
* Roland Knall <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef UI_QT_VARIANT_POINTER_H_
#define UI_QT_VARIANT_POINTER_H_
#include <QVariant>
template <typename T> class VariantPointer
{
public:
static T* asPtr(QVariant v)
{
return (T *) v.value<void *>();
}
static QVariant asQVariant(T* ptr)
{
return QVariant::fromValue((void *) ptr);
}
};
#endif /* UI_QT_VARIANT_POINTER_H_ */ |
C++ | wireshark/ui/qt/utils/wireshark_mime_data.cpp | /* wireshark_mime_data.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <utils/wireshark_mime_data.h>
const QString WiresharkMimeData::ColoringRulesMimeType = "application/vnd.wireshark.coloringrules";
const QString WiresharkMimeData::ColumnListMimeType = "application/vnd.wireshark.columnlist";
const QString WiresharkMimeData::FilterListMimeType = "application/vnd.wireshark.filterlist";
const QString WiresharkMimeData::DisplayFilterMimeType = "application/vnd.wireshark.displayfilter";
void WiresharkMimeData::allowPlainText()
{
setText(labelText());
}
ToolbarEntryMimeData::ToolbarEntryMimeData(QString element, int pos) :
WiresharkMimeData(),
element_(element),
filter_(QString()),
pos_(pos)
{}
QString ToolbarEntryMimeData::element() const
{
return element_;
}
QString ToolbarEntryMimeData::labelText() const
{
return QString("%1").arg(element_);
}
int ToolbarEntryMimeData::position() const
{
return pos_;
}
void ToolbarEntryMimeData::setFilter(QString text)
{
filter_ = text;
}
QString ToolbarEntryMimeData::filter() const
{
return filter_;
} |
C/C++ | wireshark/ui/qt/utils/wireshark_mime_data.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_UTILS_WIRESHARK_MIME_DATA_H_
#define UI_QT_UTILS_WIRESHARK_MIME_DATA_H_
#include <QMimeData>
class WiresharkMimeData: public QMimeData {
public:
virtual QString labelText() const = 0;
virtual void allowPlainText();
static const QString ColoringRulesMimeType;
static const QString ColumnListMimeType;
static const QString FilterListMimeType;
static const QString DisplayFilterMimeType;
};
class ToolbarEntryMimeData: public WiresharkMimeData {
Q_OBJECT
public:
ToolbarEntryMimeData(QString element, int pos);
int position() const;
QString element() const;
QString filter() const;
void setFilter(QString);
QString labelText() const override;
private:
QString element_;
QString filter_;
int pos_;
};
#endif /* UI_QT_UTILS_WIRESHARK_MIME_DATA_H_ */ |
C++ | wireshark/ui/qt/utils/wireshark_zip_helper.cpp | /* wireshark_zip_helper.cpp
*
* Definitions for zip / unzip of files
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/utils/wireshark_zip_helper.h>
#ifdef HAVE_MINIZIP
#include "config.h"
#include "glib.h"
#include <iosfwd>
#include <iostream>
#include <zlib.h> // For Z_DEFLATED, etc.
#include <minizip/unzip.h>
#include <minizip/zip.h>
#include "epan/prefs.h"
#include "wsutil/file_util.h"
#include <QDataStream>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QDateTime>
#include <QMap>
/* Whether we are using minizip-ng and it uses an incompatible 'dos_date'
* struct member. */
#ifdef HAVE_MZCOMPAT_DOS_DATE
#define _MZDOSDATE dos_date
#else
#define _MZDOSDATE dosDate
#endif
bool WiresharkZipHelper::unzip(QString zipFile, QString directory, bool (*fileCheck)(QString, int), QString (*cleanName)(QString))
{
unzFile uf = Q_NULLPTR;
QFileInfo fi(zipFile);
QDir di(directory);
int files = 0;
if (! fi.exists() || ! di.exists())
return false;
if ((uf = unzOpen64(zipFile.toUtf8().constData())) == Q_NULLPTR)
return false;
unz_global_info64 gi;
int err;
unzGetGlobalInfo64(uf,&gi);
unsigned int nmbr = static_cast<unsigned int>(gi.number_entry);
if (nmbr <= 0)
return false;
QMap<QString, QString> cleanPaths;
for (unsigned int cnt = 0; cnt < nmbr; cnt++)
{
char filename_inzip[256];
unz_file_info64 file_info;
err = unzGetCurrentFileInfo64(uf, &file_info, filename_inzip, sizeof(filename_inzip),
Q_NULLPTR, 0, Q_NULLPTR, 0);
if (err == UNZ_OK)
{
QString fileInZip(filename_inzip);
int fileSize = static_cast<int>(file_info.uncompressed_size);
/* Sanity check for the file */
if (fileInZip.length() == 0 || (fileCheck && ! fileCheck(fileInZip, fileSize)) )
{
if ((cnt + 1) < nmbr)
{
err = unzGoToNextFile(uf);
if (err != UNZ_OK)
{
break;
}
}
continue;
}
if (di.exists())
{
#ifdef _WIN32
/* This is an additional fix for bug 16608, in which exports did contain the full path they
* where exported from, leading to imports not possible if the path does not exist on that
* machine */
if (fileInZip.contains(":/") || fileInZip.contains(":\\"))
{
QFileInfo fileName(fileInZip);
QFileInfo path(fileName.dir(), "");
QString newFile = path.baseName() + "/" + fileName.baseName();
fileInZip = newFile;
}
#endif
QString fullPath = di.path() + "/" + fileInZip;
QFileInfo fi(fullPath);
QString dirPath = fi.absolutePath();
/* clean up name from import. e.g. illegal characters in name */
if (cleanName)
{
if (! cleanPaths.keys().contains(dirPath))
{
QString tempPath = cleanName(dirPath);
int cnt = 1;
while (QFile::exists(tempPath))
{
tempPath = cleanName(dirPath) + QString::number(cnt);
cnt++;
}
cleanPaths.insert(dirPath, tempPath);
}
dirPath = cleanPaths[dirPath];
if (dirPath.length() == 0)
continue;
fi = QFileInfo(dirPath + "/" + fi.fileName());
fullPath = fi.absoluteFilePath();
}
if (fullPath.length() == 0)
continue;
QDir tP(fi.absolutePath());
if (! tP.exists())
di.mkpath(fi.absolutePath());
if (fileInZip.contains("/"))
{
QString filePath = fi.absoluteFilePath();
QFile file(filePath);
if (! file.exists())
{
err = unzOpenCurrentFile(uf);
if (err == UNZ_OK)
{
if (file.open(QIODevice::WriteOnly))
{
QByteArray buf;
buf.resize(IO_BUF_SIZE);
while ((err = unzReadCurrentFile(uf, buf.data(), static_cast<int>(buf.size()))) != UNZ_EOF)
file.write(buf.constData(), err);
file.close();
}
unzCloseCurrentFile(uf);
files++;
}
}
}
}
}
if ((cnt+1) < nmbr)
{
err = unzGoToNextFile(uf);
if (err!=UNZ_OK)
{
break;
}
}
}
unzClose(uf);
return files > 0 ? true : false;
}
#ifndef UINT32_MAX
#define UINT32_MAX (0xffffffff)
#endif
static uint32_t qDateToDosDate(QDateTime time)
{
QDate ld = time.toLocalTime().date();
int year = ld.year() - 1900;
if (year >= 1980)
year -= 1980;
else if (year >= 80)
year -= 80;
else
year += 20;
int month = ld.month() - 1;
int day = ld.day();
if (year < 0 || year > 127 || month < 1 || month > 31)
return 0;
QTime lt = time.toLocalTime().time();
unsigned int dosDate = static_cast<unsigned int>((day + (32 * (month + 1)) + (512 * year)));
unsigned int dosTime = static_cast<unsigned int>((lt.second() / 2) + (32 * lt.minute()) + (2048 * lt.hour()));
return (uint32_t)(dosDate << 16 | dosTime);
}
void WiresharkZipHelper::addFileToZip(zipFile zf, QString filepath, QString fileInZip)
{
QFileInfo fi(filepath);
zip_fileinfo zi;
int err = ZIP_OK;
memset(&zi, 0, sizeof(zi));
QDateTime fTime = fi.lastModified();
zi._MZDOSDATE = qDateToDosDate(fTime);
QFile fh(filepath);
/* Checks if a large file block has to be written */
bool isLarge = (fh.size() > UINT32_MAX);
err = zipOpenNewFileInZip3_64(zf, fileInZip.toUtf8().constData(), &zi,
Q_NULLPTR, 0, Q_NULLPTR, 0, Q_NULLPTR, Z_DEFLATED, 9 , 0,
-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
Q_NULLPTR, 0, static_cast<int>(isLarge));
if (err != ZIP_OK)
return;
if (fh.open(QIODevice::ReadOnly))
{
QByteArray buf;
buf.resize(IO_BUF_SIZE);
while (! fh.atEnd() && err == ZIP_OK)
{
qint64 bytesIn = fh.read(buf.data(), buf.size());
if (bytesIn > 0 && bytesIn <= buf.size())
{
err = zipWriteInFileInZip(zf, buf, (unsigned int) bytesIn);
}
}
fh.close();
}
zipCloseFileInZip(zf);
}
bool WiresharkZipHelper::zip(QString fileName, QStringList files, QString relativeTo)
{
QFileInfo fi(fileName);
if (fi.exists())
QFile::remove(fileName);
zipFile zf = zipOpen(fileName.toUtf8().constData(), APPEND_STATUS_CREATE);
if (zf == Q_NULLPTR)
return false;
for (int cnt = 0; cnt < files.count(); cnt++)
{
QFileInfo sf(files.at(cnt));
QString fileInZip = sf.absoluteFilePath();
QFileInfo relat(relativeTo);
fileInZip.replace(relat.absoluteFilePath(), "");
/* Windows cannot open zip files, if the filenames starts with a separator */
while (fileInZip.length() > 0 && fileInZip.startsWith("/"))
fileInZip = fileInZip.right(fileInZip.length() - 1);
WiresharkZipHelper::addFileToZip(zf, sf.absoluteFilePath(), fileInZip);
}
if (zipClose(zf, Q_NULLPTR))
return false;
return true;
}
#endif |
C/C++ | wireshark/ui/qt/utils/wireshark_zip_helper.h | /** @file
*
* Definitions for zip / unzip of files
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef WS_ZIP_HELPER_H
#define WS_ZIP_HELPER_H
#include "config.h"
#include <QDir>
#ifdef HAVE_MINIZIP
#include "minizip/zip.h"
class WiresharkZipHelper
{
public:
static bool zip(QString zipFile, QStringList files, QString relativeTo = QString());
static bool unzip(QString zipFile, QString directory, bool (*fileCheck)(QString fileName, int fileSize) = Q_NULLPTR, QString (*cleanName)(QString name) = Q_NULLPTR);
protected:
static void addFileToZip(zipFile zf, QString filepath, QString fileInZip);
};
#endif
#endif // WS_ZIP_HELPER_H |
C++ | wireshark/ui/qt/widgets/additional_toolbar.cpp | /* additional_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 <glib.h>
#include <ui/qt/widgets/additional_toolbar.h>
#include <ui/qt/widgets/apply_line_edit.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include <ui/qt/utils/variant_pointer.h>
#include <ui/qt/main_application.h>
#include <QLabel>
#include <QLineEdit>
#include <QHBoxLayout>
#include <QComboBox>
#include <QWidget>
#include <QCheckBox>
#include <QPushButton>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QLayoutItem>
const char * AdditionalToolbarWidgetAction::propertyName = "additional_toolbar_item";
AdditionalToolBar::AdditionalToolBar(ext_toolbar_t * exttoolbar, QWidget * parent)
: QToolBar(parent),
toolbar(exttoolbar)
{ }
AdditionalToolBar::~AdditionalToolBar()
{ }
AdditionalToolBar * AdditionalToolBar::create(QWidget * parent, ext_toolbar_t * toolbar)
{
if (g_list_length(toolbar->children) == 0)
return NULL;
AdditionalToolBar * result = new AdditionalToolBar(toolbar, parent);
result->setMovable(false);
result->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
result->layout()->setContentsMargins(0, 0, 0, 0);
result->layout()->setSpacing(4);
GList * walker = toolbar->children;
bool spacerNeeded = true;
while (walker && walker->data)
{
ext_toolbar_t * item = gxx_list_data(ext_toolbar_t *, walker);
if (item->type == EXT_TOOLBAR_ITEM)
{
if (item->item_type == EXT_TOOLBAR_STRING)
spacerNeeded = false;
QAction * newAction = new AdditionalToolbarWidgetAction(item, result);
if (newAction)
{
result->addAction(newAction);
/* Necessary, because enable state is reset upon adding the action */
result->actions()[result->actions().count() - 1]->setEnabled(!item->capture_only);
}
}
walker = gxx_list_next (walker);
}
if (result->children().count() == 0)
return Q_NULLPTR;
if (spacerNeeded)
{
QWidget * empty = new QWidget();
empty->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred);
result->addWidget(empty);
}
return result;
}
QString AdditionalToolBar::menuName()
{
return (toolbar && toolbar->name) ? QString(toolbar->name) : QString();
}
AdditionalToolbarWidgetAction::AdditionalToolbarWidgetAction(QObject * parent)
: QWidgetAction(parent),
toolbar_item(0)
{ }
AdditionalToolbarWidgetAction::AdditionalToolbarWidgetAction(ext_toolbar_t * item, QObject * parent)
: QWidgetAction(parent),
toolbar_item(item)
{
connect(mainApp, &MainApplication::captureActive, this, &AdditionalToolbarWidgetAction::captureActive);
}
AdditionalToolbarWidgetAction::AdditionalToolbarWidgetAction(const AdditionalToolbarWidgetAction & copy_object)
: QWidgetAction(copy_object.parent()),
toolbar_item(copy_object.toolbar_item)
{
connect(mainApp, &MainApplication::captureActive, this, &AdditionalToolbarWidgetAction::captureActive);
}
void AdditionalToolbarWidgetAction::captureActive(int activeCaptures)
{
if (toolbar_item && toolbar_item->capture_only)
{
setEnabled(activeCaptures != 0);
}
}
/* Exists, so a default deconstructor does not call delete on toolbar_item */
AdditionalToolbarWidgetAction::~AdditionalToolbarWidgetAction() { }
QWidget * AdditionalToolbarWidgetAction::createWidget(QWidget * parent)
{
QWidget * barItem = 0;
if (toolbar_item->type != EXT_TOOLBAR_ITEM)
return barItem;
switch (toolbar_item->item_type)
{
case EXT_TOOLBAR_BUTTON:
barItem = createButton(toolbar_item, parent);
break;
case EXT_TOOLBAR_BOOLEAN:
barItem = createBoolean(toolbar_item, parent);
break;
case EXT_TOOLBAR_STRING:
barItem = createTextEditor(toolbar_item, parent);
break;
case EXT_TOOLBAR_SELECTOR:
barItem = createSelector(toolbar_item, parent);
break;
}
if (! barItem)
return 0;
barItem->setToolTip(toolbar_item->tooltip);
barItem->setProperty(propertyName, VariantPointer<ext_toolbar_t>::asQVariant(toolbar_item));
#ifdef Q_OS_MAC
barItem->setAttribute(Qt::WA_MacSmallSize, true);
#endif
return barItem;
}
static void
toolbar_button_cb(gpointer item, gpointer item_data, gpointer user_data)
{
if (! item || ! item_data || ! user_data)
return;
QPushButton * widget = (QPushButton *)(item_data);
ext_toolbar_update_t * update_entry = (ext_toolbar_update_t *)user_data;
if (widget)
{
if (update_entry->type == EXT_TOOLBAR_UPDATE_VALUE)
widget->setText((gchar *)update_entry->user_data);
else if (update_entry->type == EXT_TOOLBAR_SET_ACTIVE)
{
bool enableState = GPOINTER_TO_INT(update_entry->user_data) == 1;
widget->setEnabled(enableState);
}
}
}
QWidget * AdditionalToolbarWidgetAction::createButton(ext_toolbar_t * item, QWidget * parent)
{
if (! item || item->type != EXT_TOOLBAR_ITEM || item->item_type != EXT_TOOLBAR_BUTTON)
return 0;
QPushButton * button = new QPushButton(item->name, parent);
button->setText(item->name);
connect(button, &QPushButton::clicked, this, &AdditionalToolbarWidgetAction::onButtonClicked);
ext_toolbar_register_update_cb(item, (ext_toolbar_action_cb)&toolbar_button_cb, (void *)button);
return button;
}
static void
toolbar_boolean_cb(gpointer item, gpointer item_data, gpointer user_data)
{
if (! item || ! item_data || ! user_data)
return;
QCheckBox * widget = (QCheckBox *)(item_data);
ext_toolbar_update_t * update_entry = (ext_toolbar_update_t *)user_data;
if (update_entry->type == EXT_TOOLBAR_UPDATE_VALUE)
{
bool oldState = false;
if (update_entry->silent)
oldState = widget->blockSignals(true);
widget->setCheckState(GPOINTER_TO_INT(update_entry->user_data) == 1 ? Qt::Checked : Qt::Unchecked);
if (update_entry->silent)
widget->blockSignals(oldState);
}
else if (update_entry->type == EXT_TOOLBAR_SET_ACTIVE)
{
bool enableState = GPOINTER_TO_INT(update_entry->user_data) == 1;
widget->setEnabled(enableState);
}
}
QWidget * AdditionalToolbarWidgetAction::createBoolean(ext_toolbar_t * item, QWidget * parent)
{
if (! item || item->type != EXT_TOOLBAR_ITEM || item->item_type != EXT_TOOLBAR_BOOLEAN)
return 0;
QString defValue = toolbar_item->defvalue;
QCheckBox * checkbox = new QCheckBox(item->name, parent);
checkbox->setText(item->name);
setCheckable(true);
checkbox->setCheckState(defValue.compare("true", Qt::CaseInsensitive) == 0 ? Qt::Checked : Qt::Unchecked);
connect(checkbox, &QCheckBox::stateChanged, this, &AdditionalToolbarWidgetAction::onCheckBoxChecked);
ext_toolbar_register_update_cb(item, (ext_toolbar_action_cb)&toolbar_boolean_cb, (void *)checkbox);
return checkbox;
}
QWidget * AdditionalToolbarWidgetAction::createLabelFrame(ext_toolbar_t * item, QWidget * parent)
{
if (! item)
return new QWidget();
QWidget * frame = new QWidget(parent);
QHBoxLayout * frameLayout = new QHBoxLayout(frame);
frameLayout->setContentsMargins(0, 0, 0, 0);
frameLayout->setSpacing(0);
QLabel * strLabel = new QLabel(item->name, frame);
strLabel->setToolTip(item->tooltip);
#ifdef Q_OS_MAC
frame->setAttribute(Qt::WA_MacSmallSize, true);
strLabel->setAttribute(Qt::WA_MacSmallSize, true);
#endif
frameLayout->addWidget(strLabel);
frame->setLayout(frameLayout);
return frame;
}
static void
toolbar_string_cb(gpointer item, gpointer item_data, gpointer user_data)
{
if (! item || ! item_data || ! user_data)
return;
ApplyLineEdit * edit = (ApplyLineEdit *)(item_data);
ext_toolbar_update_t * update_entry = (ext_toolbar_update_t *)user_data;
if (update_entry->type == EXT_TOOLBAR_UPDATE_VALUE)
{
bool oldState = false;
if (update_entry->silent)
oldState = edit->blockSignals(true);
edit->setText((gchar *)update_entry->user_data);
if (update_entry->silent)
edit->blockSignals(oldState);
}
else if (update_entry->type == EXT_TOOLBAR_SET_ACTIVE)
{
bool enableState = GPOINTER_TO_INT(update_entry->user_data) == 1;
edit->setEnabled(enableState);
}
}
QWidget * AdditionalToolbarWidgetAction::createTextEditor(ext_toolbar_t * item, QWidget * parent)
{
if (! item || item->type != EXT_TOOLBAR_ITEM || item->item_type != EXT_TOOLBAR_STRING)
return 0;
QWidget * frame = createLabelFrame(toolbar_item, parent);
ApplyLineEdit * strEdit = new ApplyLineEdit(toolbar_item->defvalue, frame);
strEdit->setToolTip(toolbar_item->tooltip);
strEdit->setRegEx(toolbar_item->regex);
strEdit->setEmptyAllowed(toolbar_item->is_required);
strEdit->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
#ifdef Q_OS_MAC
strEdit->setAttribute(Qt::WA_MacSmallSize, true);
#endif
frame->layout()->addWidget(strEdit);
connect(strEdit, &ApplyLineEdit::textApplied, this, &AdditionalToolbarWidgetAction::sendTextToCallback);
ext_toolbar_register_update_cb(item, (ext_toolbar_action_cb)&toolbar_string_cb, (void *)strEdit);
return frame;
}
static void
toolbar_selector_cb(gpointer item, gpointer item_data, gpointer user_data)
{
if (! item || ! item_data || ! user_data)
return;
QComboBox * comboBox = (QComboBox *)(item_data);
ext_toolbar_update_t * update_entry = (ext_toolbar_update_t *)user_data;
bool oldState = false;
if (update_entry->silent)
oldState = comboBox->blockSignals(true);
QStandardItemModel * sourceModel = (QStandardItemModel *)comboBox->model();
if (update_entry->type == EXT_TOOLBAR_SET_ACTIVE)
{
bool enableState = GPOINTER_TO_INT(update_entry->user_data) == 1;
comboBox->setEnabled(enableState);
}
else if (update_entry->type != EXT_TOOLBAR_UPDATE_DATA_REMOVE && ! update_entry->user_data)
return;
if (update_entry->type == EXT_TOOLBAR_UPDATE_VALUE)
{
QString data = QString((gchar *)update_entry->user_data);
for (int i = 0; i < sourceModel->rowCount(); i++)
{
QStandardItem * dataValue = ((QStandardItemModel *)sourceModel)->item(i, 0);
ext_toolbar_value_t * tbValue = VariantPointer<ext_toolbar_value_t>::asPtr(dataValue->data(Qt::UserRole));
if (tbValue && data.compare(QString(tbValue->value)) == 0)
{
comboBox->setCurrentIndex(i);
break;
}
}
}
else if (update_entry->type == EXT_TOOLBAR_UPDATE_DATA)
{
GList * walker = (GList *)update_entry->user_data;
if (g_list_length(walker) == 0)
return;
sourceModel->clear();
while (walker && walker->data)
{
ext_toolbar_value_t * listvalue = gxx_list_data(ext_toolbar_value_t *, walker);
QStandardItem * si = new QStandardItem(listvalue->display);
si->setData(VariantPointer<ext_toolbar_value_t>::asQVariant(listvalue), Qt::UserRole);
sourceModel->appendRow(si);
walker = gxx_list_next(walker);
}
}
else if (update_entry->type == EXT_TOOLBAR_UPDATE_DATABYINDEX ||
update_entry->type == EXT_TOOLBAR_UPDATE_DATA_ADD ||
update_entry->type == EXT_TOOLBAR_UPDATE_DATA_REMOVE)
{
if (! update_entry->data_index)
return;
gchar * idx = (gchar *)update_entry->data_index;
gchar * display = (gchar *)update_entry->user_data;
if (update_entry->type == EXT_TOOLBAR_UPDATE_DATABYINDEX)
{
for (int i = 0; i < sourceModel->rowCount(); i++)
{
QStandardItem * dataValue = sourceModel->item(i, 0);
ext_toolbar_value_t * entry = VariantPointer<ext_toolbar_value_t>::asPtr(dataValue->data(Qt::UserRole));
if (entry && g_strcmp0(entry->value, idx) == 0)
{
g_free(entry->display);
entry->display = g_strdup(display);
dataValue->setData(VariantPointer<ext_toolbar_value_t>::asQVariant(entry), Qt::UserRole);
dataValue->setText(display);
break;
}
}
}
else if (update_entry->type == EXT_TOOLBAR_UPDATE_DATA_ADD)
{
ext_toolbar_value_t * listvalue = g_new0(ext_toolbar_value_t, 1);
listvalue->display = g_strdup(display);
listvalue->value = g_strdup(idx);
QStandardItem * si = new QStandardItem(listvalue->display);
si->setData(VariantPointer<ext_toolbar_value_t>::asQVariant(listvalue), Qt::UserRole);
sourceModel->appendRow(si);
}
else if (update_entry->type == EXT_TOOLBAR_UPDATE_DATA_REMOVE)
{
QList<QStandardItem *> entryList = sourceModel->findItems(display);
/* Search for index if display did not find anything */
if (entryList.size() == 0)
entryList = sourceModel->findItems(idx);
foreach(QStandardItem *entry, entryList)
{
QModelIndex index = sourceModel->indexFromItem(entry);
if (index.isValid())
sourceModel->removeRow(index.row());
}
}
}
if (update_entry->silent)
comboBox->blockSignals(oldState);
}
QWidget * AdditionalToolbarWidgetAction::createSelector(ext_toolbar_t * item, QWidget * parent)
{
if (! item || item->type != EXT_TOOLBAR_ITEM || item->item_type != EXT_TOOLBAR_SELECTOR)
return 0;
if (g_list_length(item->values) == 0)
return 0;
QWidget * frame = createLabelFrame(item, parent);
QComboBox * myBox = new QComboBox(parent);
myBox->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
QStandardItemModel * sourceModel = new QStandardItemModel();
GList * walker = item->values;
int selIndex = 0;
while (walker && walker->data)
{
ext_toolbar_value_t * listvalue = gxx_list_data(ext_toolbar_value_t *, walker);
QStandardItem * si = new QStandardItem(listvalue->display);
si->setData(VariantPointer<ext_toolbar_value_t>::asQVariant(listvalue), Qt::UserRole);
sourceModel->appendRow(si);
if (listvalue->is_default)
selIndex = sourceModel->rowCount();
walker = gxx_list_next(walker);
}
myBox->setModel(sourceModel);
myBox->setCurrentIndex(selIndex);
#ifdef Q_OS_MAC
myBox->setAttribute(Qt::WA_MacSmallSize, true);
#endif
frame->layout()->addWidget(myBox);
connect(myBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this, &AdditionalToolbarWidgetAction::onSelectionInWidgetChanged);
ext_toolbar_register_update_cb(item, (ext_toolbar_action_cb)&toolbar_selector_cb, (void *)myBox);
return frame;
}
ext_toolbar_t * AdditionalToolbarWidgetAction::extractToolbarItemFromObject(QObject * object)
{
QWidget * widget = dynamic_cast<QWidget *>(object);
if (! widget)
return 0;
QVariant propValue = widget->property(propertyName);
/* If property is invalid, look if our parent has this property */
if (! propValue.isValid())
{
QWidget * frame = dynamic_cast<QWidget *>(widget->parent());
if (! frame)
return 0;
propValue = frame->property(propertyName);
}
if (! propValue.isValid())
return 0;
return VariantPointer<ext_toolbar_t>::asPtr(propValue);
}
void AdditionalToolbarWidgetAction::onButtonClicked()
{
ext_toolbar_t * item = extractToolbarItemFromObject(sender());
if (! item)
return;
item->callback(item, 0, item->user_data);
}
void AdditionalToolbarWidgetAction::onCheckBoxChecked(int checkState)
{
ext_toolbar_t * item = extractToolbarItemFromObject(sender());
if (! item)
return;
gboolean value = checkState == Qt::Checked ? true : false;
item->callback(item, &value, item->user_data);
}
void AdditionalToolbarWidgetAction::sendTextToCallback()
{
ext_toolbar_t * item = extractToolbarItemFromObject(sender());
if (! item)
return;
if (item->item_type != EXT_TOOLBAR_STRING)
return;
ApplyLineEdit * editor = dynamic_cast<ApplyLineEdit *>(sender());
if (! editor)
{
/* Called from button, searching for acompanying line edit */
QWidget * parent = dynamic_cast<QWidget *>(sender()->parent());
if (parent)
{
QList<ApplyLineEdit *> children = parent->findChildren<ApplyLineEdit *>();
if (children.count() >= 0)
editor = children.at(0);
}
}
if (editor)
item->callback(item, qstring_strdup(editor->text()), item->user_data);
}
void AdditionalToolbarWidgetAction::onSelectionInWidgetChanged(int idx)
{
QComboBox * editor = dynamic_cast<QComboBox *>(sender());
ext_toolbar_t * item = extractToolbarItemFromObject(editor);
if (! item || item->item_type != EXT_TOOLBAR_SELECTOR)
return;
QStandardItemModel * sourceModel = (QStandardItemModel *) editor->model();
if (sourceModel->rowCount() <= idx)
return;
QModelIndex mdIdx = sourceModel->index(idx, 0);
QVariant dataSet = sourceModel->data(mdIdx, Qt::UserRole);
if (dataSet.isValid())
{
ext_toolbar_value_t * value_entry = VariantPointer<ext_toolbar_value_t>::asPtr(dataSet);
item->callback(item, value_entry, item->user_data);
}
} |
C/C++ | wireshark/ui/qt/widgets/additional_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 UI_QT_ADDITIONAL_TOOLBAR_H_
#define UI_QT_ADDITIONAL_TOOLBAR_H_
#include <epan/plugin_if.h>
#include <QToolBar>
#include <QWidgetAction>
/* Class for all display widgets.
*
* Inherits QWidgetAction, otherwise the extension popup might not work for the toolbar
*/
class AdditionalToolbarWidgetAction: public QWidgetAction
{
Q_OBJECT
public:
AdditionalToolbarWidgetAction(QObject * parent = 0);
AdditionalToolbarWidgetAction(ext_toolbar_t * item, QObject * parent = 0);
AdditionalToolbarWidgetAction(const AdditionalToolbarWidgetAction & copy_object);
~AdditionalToolbarWidgetAction();
protected:
virtual QWidget * createWidget(QWidget * parent);
static const char * propertyName;
private:
ext_toolbar_t * toolbar_item;
QWidget * createButton(ext_toolbar_t * item, QWidget * parent);
QWidget * createBoolean(ext_toolbar_t * item, QWidget * parent);
QWidget * createTextEditor(ext_toolbar_t * item, QWidget * parent);
QWidget * createSelector(ext_toolbar_t * item, QWidget * parent);
QWidget * createLabelFrame(ext_toolbar_t * item, QWidget * parent);
ext_toolbar_t * extractToolbarItemFromObject(QObject *);
private slots:
void onButtonClicked();
void onCheckBoxChecked(int);
void sendTextToCallback();
void onSelectionInWidgetChanged(int idx);
void captureActive(int);
};
class AdditionalToolBar: public QToolBar
{
Q_OBJECT
public:
AdditionalToolBar(ext_toolbar_t * toolbar, QWidget * parent = 0);
virtual ~AdditionalToolBar();
static AdditionalToolBar * create(QWidget * parent, ext_toolbar_t * toolbar);
QString menuName();
private:
ext_toolbar_t * toolbar;
};
#endif /* UI_QT_ADDITIONAL_TOOLBAR_H_ */ |
C++ | wireshark/ui/qt/widgets/apply_line_edit.cpp | /* apply_lineedit.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/apply_line_edit.h>
#include <epan/prefs.h>
#include <ui/qt/utils/color_utils.h>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QStyle>
ApplyLineEdit::ApplyLineEdit(QString linePlaceholderText, QWidget * parent)
: QLineEdit(parent),
apply_button_(0)
{
emptyAllowed_ = false;
regex_ = QString();
apply_button_ = new StockIconToolButton(parent, "x-filter-apply");
apply_button_->setCursor(Qt::ArrowCursor);
apply_button_->setEnabled(false);
apply_button_->setToolTip(tr("Apply changes"));
apply_button_->setIconSize(QSize(24, 14));
apply_button_->setMaximumWidth(30);
apply_button_->setStyleSheet(
"QToolButton {"
" border: none;"
" background: transparent;" // Disables platform style on Windows.
" padding: 0 0 0 0;"
"}"
);
#ifdef Q_OS_MAC
setAttribute(Qt::WA_MacSmallSize, true);
apply_button_->setAttribute(Qt::WA_MacSmallSize, true);
#endif
setPlaceholderText(linePlaceholderText);
connect(this, &ApplyLineEdit::textEdited, this, &ApplyLineEdit::onTextEdited);
connect(this, &ApplyLineEdit::textChanged, this, &ApplyLineEdit::onTextChanged);
connect(this, &ApplyLineEdit::returnPressed, this, &ApplyLineEdit::onSubmitContent);
connect(apply_button_, &StockIconToolButton::clicked, this, &ApplyLineEdit::onSubmitContent);
handleValidation(QString(linePlaceholderText));
setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
}
ApplyLineEdit::~ApplyLineEdit() {}
void ApplyLineEdit::setRegEx(QString regex)
{
regex_ = regex;
}
QString ApplyLineEdit::regex()
{
return regex_;
}
void ApplyLineEdit::setEmptyAllowed(bool emptyAllowed)
{
emptyAllowed_ = emptyAllowed;
}
bool ApplyLineEdit::emptyAllowed()
{
return emptyAllowed_;
}
bool ApplyLineEdit::isValidText(QString & text, bool ignoreEmptyCheck)
{
if (text.length() == 0)
{
if (! ignoreEmptyCheck && ! emptyAllowed_)
return false;
else if (ignoreEmptyCheck)
return true;
}
if (regex_.length() > 0)
{
QRegularExpression rx (regex_);
QRegularExpressionValidator v(rx, 0);
int pos = 0;
if (! rx.isValid() || v.validate(text, pos) != QValidator::Acceptable)
return false;
}
return true;
}
void ApplyLineEdit::onTextEdited(const QString & text)
{
QString newText = QString(text);
apply_button_->setEnabled(isValidText(newText));
handleValidation(newText);
}
void ApplyLineEdit::onTextChanged(const QString & text)
{
handleValidation(QString(text));
}
void ApplyLineEdit::handleValidation(QString newText)
{
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
QString style_sheet = QString(
"ApplyLineEdit {"
" padding-left: %1px;"
" padding-right: %2px;"
" background-color: %3;"
"}"
)
.arg(frameWidth + 1)
.arg(apply_button_->sizeHint().width() + frameWidth)
.arg(isValidText(newText, true) ? QString("") : ColorUtils::fromColorT(prefs.gui_text_invalid).name());
setStyleSheet(style_sheet);
}
void ApplyLineEdit::resizeEvent(QResizeEvent *)
{
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
QSize apsz = apply_button_->sizeHint();
apply_button_->move((contentsRect().right() + pos().x()) - (frameWidth + apsz.width()) - 2,
contentsRect().top() + pos().y());
apply_button_->setMinimumHeight(height());
apply_button_->setMaximumHeight(height());
}
void ApplyLineEdit::onSubmitContent()
{
QString data = text();
if (! isValidText(data))
return;
/* Freeze apply button to signal the text has been sent. Will be unfreezed, if the text in the textbox changes again */
apply_button_->setEnabled(false);
emit textApplied();
} |
C/C++ | wireshark/ui/qt/widgets/apply_line_edit.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef UI_QT_APPLY_LINE_EDIT_H_
#define UI_QT_APPLY_LINE_EDIT_H_
#include <QLineEdit>
#include <QString>
#include <ui/qt/widgets/stock_icon_tool_button.h>
class ApplyLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit ApplyLineEdit(QString linePlaceholderText, QWidget *parent = 0);
~ApplyLineEdit();
Q_PROPERTY(QString regex READ regex WRITE setRegEx)
Q_PROPERTY(bool emptyAllowed READ emptyAllowed WRITE setEmptyAllowed)
QString regex();
void setRegEx(QString);
bool emptyAllowed();
void setEmptyAllowed(bool);
signals:
void textApplied();
protected:
void resizeEvent(QResizeEvent *);
private:
QString regex_;
bool emptyAllowed_;
StockIconToolButton *apply_button_;
bool isValidText(QString &, bool ignoreEmptyCheck = false);
void handleValidation(QString newText);
private slots:
void onTextEdited(const QString &);
void onTextChanged(const QString &);
void onSubmitContent();
};
#endif /* UI_QT_APPLY_LINE_EDIT_H_ */ |
C++ | wireshark/ui/qt/widgets/byte_view_text.cpp | /* byte_view_text.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
// Some code based on QHexView by Evan Teran
// https://github.com/eteran/qhexview/
#include "byte_view_text.h"
#include <wsutil/str_util.h>
#include <wsutil/utf8_entities.h>
#include <ui/qt/utils/color_utils.h>
#include "main_application.h"
#include "ui/recent.h"
#include <QActionGroup>
#include <QMouseEvent>
#include <QPainter>
#include <QScreen>
#include <QScrollBar>
#include <QStyle>
#include <QStyleOption>
#include <QTextLayout>
#include <QWindow>
// To do:
// - Add recent settings and context menu items to show/hide the offset.
// - Add a UTF-8 and possibly UTF-xx option to the ASCII display.
// - Move more common metrics to DataPrinter.
// Alternative implementations:
// - Pre-draw all of our characters and paint our display using pixmap
// copying? That would make this behave like a terminal screen, which
// is what we ultimately want.
// - Use QGraphicsView + QGraphicsScene + QGraphicsTextItem instead?
Q_DECLARE_METATYPE(bytes_view_type)
Q_DECLARE_METATYPE(bytes_encoding_type)
Q_DECLARE_METATYPE(DataPrinter::DumpType)
ByteViewText::ByteViewText(const QByteArray &data, packet_char_enc encoding, QWidget *parent) :
QAbstractScrollArea(parent),
layout_(new QTextLayout()),
data_(data),
encoding_(encoding),
hovered_byte_offset_(-1),
marked_byte_offset_(-1),
proto_start_(0),
proto_len_(0),
field_start_(0),
field_len_(0),
field_a_start_(0),
field_a_len_(0),
show_offset_(true),
show_hex_(true),
show_ascii_(true),
row_width_(recent.gui_bytes_view == BYTES_BITS ? 8 : 16),
em_width_(0),
line_height_(0),
allow_hover_selection_(false)
{
layout_->setCacheEnabled(true);
offset_normal_fg_ = ColorUtils::alphaBlend(palette().windowText(), palette().window(), 0.35);
offset_field_fg_ = ColorUtils::alphaBlend(palette().windowText(), palette().window(), 0.65);
window()->winId(); // Required for screenChanged? https://phabricator.kde.org/D20171
connect(window()->windowHandle(), &QWindow::screenChanged, viewport(), [=](const QScreen *) { viewport()->update(); });
createContextMenu();
setMouseTracking(true);
#ifdef Q_OS_MAC
setAttribute(Qt::WA_MacShowFocusRect, true);
#endif
}
ByteViewText::~ByteViewText()
{
ctx_menu_.clear();
delete(layout_);
}
void ByteViewText::createContextMenu()
{
action_allow_hover_selection_ = ctx_menu_.addAction(tr("Allow hover highlighting"));
action_allow_hover_selection_->setCheckable(true);
action_allow_hover_selection_->setChecked(true);
connect(action_allow_hover_selection_, &QAction::toggled, this, &ByteViewText::toggleHoverAllowed);
ctx_menu_.addSeparator();
QActionGroup * copy_actions = DataPrinter::copyActions(this);
ctx_menu_.addActions(copy_actions->actions());
ctx_menu_.addSeparator();
QActionGroup * format_actions = new QActionGroup(this);
action_bytes_hex_ = format_actions->addAction(tr("Show bytes as hexadecimal"));
action_bytes_hex_->setData(QVariant::fromValue(BYTES_HEX));
action_bytes_hex_->setCheckable(true);
action_bytes_dec_ = format_actions->addAction(tr("…as decimal"));
action_bytes_dec_->setData(QVariant::fromValue(BYTES_DEC));
action_bytes_dec_->setCheckable(true);
action_bytes_oct_ = format_actions->addAction(tr("…as octal"));
action_bytes_oct_->setData(QVariant::fromValue(BYTES_OCT));
action_bytes_oct_->setCheckable(true);
action_bytes_bits_ = format_actions->addAction(tr("…as bits"));
action_bytes_bits_->setData(QVariant::fromValue(BYTES_BITS));
action_bytes_bits_->setCheckable(true);
ctx_menu_.addActions(format_actions->actions());
connect(format_actions, &QActionGroup::triggered, this, &ByteViewText::setHexDisplayFormat);
ctx_menu_.addSeparator();
QActionGroup * encoding_actions = new QActionGroup(this);
action_bytes_enc_from_packet_ = encoding_actions->addAction(tr("Show text based on packet"));
action_bytes_enc_from_packet_->setData(QVariant::fromValue(BYTES_ENC_FROM_PACKET));
action_bytes_enc_from_packet_->setCheckable(true);
action_bytes_enc_ascii_ = encoding_actions->addAction(tr("…as ASCII"));
action_bytes_enc_ascii_->setData(QVariant::fromValue(BYTES_ENC_ASCII));
action_bytes_enc_ascii_->setCheckable(true);
action_bytes_enc_ebcdic_ = encoding_actions->addAction(tr("…as EBCDIC"));
action_bytes_enc_ebcdic_->setData(QVariant::fromValue(BYTES_ENC_EBCDIC));
action_bytes_enc_ebcdic_->setCheckable(true);
updateContextMenu();
ctx_menu_.addActions(encoding_actions->actions());
connect(encoding_actions, &QActionGroup::triggered, this, &ByteViewText::setCharacterEncoding);
}
void ByteViewText::toggleHoverAllowed(bool checked)
{
allow_hover_selection_ = ! checked;
recent.gui_allow_hover_selection = checked;
}
void ByteViewText::updateContextMenu()
{
action_allow_hover_selection_->setChecked(recent.gui_allow_hover_selection);
switch (recent.gui_bytes_view) {
case BYTES_HEX:
action_bytes_hex_->setChecked(true);
break;
case BYTES_BITS:
action_bytes_bits_->setChecked(true);
break;
case BYTES_DEC:
action_bytes_dec_->setChecked(true);
break;
case BYTES_OCT:
action_bytes_oct_->setChecked(true);
break;
}
switch (recent.gui_bytes_encoding) {
case BYTES_ENC_FROM_PACKET:
action_bytes_enc_from_packet_->setChecked(true);
break;
case BYTES_ENC_ASCII:
action_bytes_enc_ascii_->setChecked(true);
break;
case BYTES_ENC_EBCDIC:
action_bytes_enc_ebcdic_->setChecked(true);
break;
}
}
bool ByteViewText::isEmpty() const
{
return data_.isEmpty();
}
QSize ByteViewText::minimumSizeHint() const
{
// Allow panel to shrink to any size
return QSize();
}
void ByteViewText::markProtocol(int start, int length)
{
proto_start_ = start;
proto_len_ = length;
viewport()->update();
}
void ByteViewText::markField(int start, int length, bool scroll_to)
{
field_start_ = start;
field_len_ = length;
// This might be called as a result of (de)selecting a proto tree
// item, so take us out of marked mode.
marked_byte_offset_ = -1;
if (scroll_to) {
scrollToByte(start);
}
viewport()->update();
}
void ByteViewText::markAppendix(int start, int length)
{
field_a_start_ = start;
field_a_len_ = length;
viewport()->update();
}
void ByteViewText::setMonospaceFont(const QFont &mono_font)
{
QFont int_font(mono_font);
setFont(int_font);
viewport()->setFont(int_font);
layout_->setFont(int_font);
updateLayoutMetrics();
updateScrollbars();
viewport()->update();
}
void ByteViewText::updateByteViewSettings()
{
row_width_ = recent.gui_bytes_view == BYTES_BITS ? 8 : 16;
updateContextMenu();
updateScrollbars();
viewport()->update();
}
void ByteViewText::detachData()
{
data_.detach();
}
void ByteViewText::paintEvent(QPaintEvent *)
{
updateLayoutMetrics();
QPainter painter(viewport());
painter.translate(-horizontalScrollBar()->value() * em_width_, 0);
// Pixel offset of this row
int row_y = 0;
// Starting byte offset
int offset = verticalScrollBar()->value() * row_width_;
// Clear the area
painter.fillRect(viewport()->rect(), palette().base());
// Offset background. We want the entire height to be filled.
if (show_offset_) {
QRect offset_rect = QRect(viewport()->rect());
offset_rect.setWidth(offsetPixels());
painter.fillRect(offset_rect, palette().window());
}
if (data_.isEmpty()) {
return;
}
// Data rows
int widget_height = height();
painter.save();
x_pos_to_column_.clear();
while ((int) (row_y + line_height_) < widget_height && offset < (int) data_.size()) {
drawLine(&painter, offset, row_y);
offset += row_width_;
row_y += line_height_;
}
painter.restore();
// We can't do this in drawLine since the next line might draw over our rect.
// This looks best when our highlight and background have similar lightnesses.
// We might want to set a composition mode when that's not the case.
if (!hover_outlines_.isEmpty()) {
qreal pen_width = 1.0;
qreal hover_alpha = 0.6;
QPen ho_pen;
QColor ho_color = palette().text().color();
if (marked_byte_offset_ < 0) {
hover_alpha = 0.3;
if (devicePixelRatio() > 1) {
pen_width = 0.5;
}
}
ho_pen.setWidthF(pen_width);
ho_color.setAlphaF(hover_alpha);
ho_pen.setColor(ho_color);
painter.save();
painter.setPen(ho_pen);
painter.setBrush(Qt::NoBrush);
foreach (QRect ho_rect, hover_outlines_) {
// These look good on retina and non-retina displays on macOS.
// We might want to use fontMetrics numbers instead.
ho_rect.adjust(-1, 0, -1, -1);
painter.drawRect(ho_rect);
}
painter.restore();
}
hover_outlines_.clear();
QStyleOptionFocusRect option;
option.initFrom(this);
style()->drawPrimitive(QStyle::PE_FrameFocusRect, &option, &painter, this);
}
void ByteViewText::resizeEvent(QResizeEvent *)
{
updateScrollbars();
}
void ByteViewText::mousePressEvent (QMouseEvent *event) {
if (data_.isEmpty() || !event || event->button() != Qt::LeftButton) {
return;
}
// byteSelected does the following:
// - Triggers selectedFieldChanged in ProtoTree, which clears the
// selection and selects the corresponding (or no) item.
// - The new tree selection triggers markField, which clobbers
// marked_byte_offset_.
const bool hover_mode = marked_byte_offset_ < 0;
const int byte_offset = byteOffsetAtPixel(event->pos());
setUpdatesEnabled(false);
emit byteSelected(byte_offset);
if (hover_mode && byte_offset >= 0) {
// Switch to marked mode.
hovered_byte_offset_ = -1;
marked_byte_offset_ = byte_offset;
viewport()->update();
} else {
// Back to hover mode.
mouseMoveEvent(event);
}
setUpdatesEnabled(true);
}
void ByteViewText::mouseMoveEvent(QMouseEvent *event)
{
if (marked_byte_offset_ >= 0 || allow_hover_selection_ ||
(!allow_hover_selection_ && event->modifiers() & Qt::ControlModifier)) {
return;
}
hovered_byte_offset_ = byteOffsetAtPixel(event->pos());
emit byteHovered(hovered_byte_offset_);
viewport()->update();
}
void ByteViewText::leaveEvent(QEvent *event)
{
hovered_byte_offset_ = -1;
emit byteHovered(hovered_byte_offset_);
viewport()->update();
QAbstractScrollArea::leaveEvent(event);
}
void ByteViewText::contextMenuEvent(QContextMenuEvent *event)
{
ctx_menu_.popup(event->globalPos());
}
// Private
const int ByteViewText::separator_interval_ = DataPrinter::separatorInterval();
void ByteViewText::updateLayoutMetrics()
{
em_width_ = stringWidth("M");
// We might want to match ProtoTree::rowHeight.
line_height_ = viewport()->fontMetrics().lineSpacing();
}
int ByteViewText::stringWidth(const QString &line)
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
return viewport()->fontMetrics().horizontalAdvance(line);
#else
return viewport()->fontMetrics().boundingRect(line).width();
#endif
}
// Draw a line of byte view text for a given offset.
// Text highlighting is handled using QTextLayout::FormatRange.
void ByteViewText::drawLine(QPainter *painter, const int offset, const int row_y)
{
if (data_.isEmpty()) {
return;
}
// Build our pixel to byte offset vector the first time through.
bool build_x_pos = x_pos_to_column_.empty() ? true : false;
int tvb_len = static_cast<int>(data_.size());
int max_tvb_pos = qMin(offset + row_width_, tvb_len) - 1;
QList<QTextLayout::FormatRange> fmt_list;
static const char hexchars[16] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
QString line;
HighlightMode offset_mode = ModeOffsetNormal;
// Offset.
if (show_offset_) {
line = QString(" %1 ").arg(offset, offsetChars(false), 16, QChar('0'));
if (build_x_pos) {
x_pos_to_column_.fill(-1, stringWidth(line));
}
}
// Hex
if (show_hex_) {
int ascii_start = static_cast<int>(line.length()) + DataPrinter::hexChars() + 3;
// Extra hover space before and after each byte.
int slop = em_width_ / 2;
unsigned char c;
if (build_x_pos) {
x_pos_to_column_ += QVector<int>().fill(-1, slop);
}
for (int tvb_pos = offset; tvb_pos <= max_tvb_pos; tvb_pos++) {
line += ' ';
/* insert a space every separator_interval_ bytes */
if ((tvb_pos != offset) && ((tvb_pos % separator_interval_) == 0)) {
line += ' ';
x_pos_to_column_ += QVector<int>().fill(tvb_pos - offset - 1, em_width_);
}
switch (recent.gui_bytes_view) {
case BYTES_HEX:
line += hexchars[(data_[tvb_pos] & 0xf0) >> 4];
line += hexchars[data_[tvb_pos] & 0x0f];
break;
case BYTES_BITS:
/* XXX, bitmask */
for (int j = 7; j >= 0; j--) {
line += (data_[tvb_pos] & (1 << j)) ? '1' : '0';
}
break;
case BYTES_DEC:
c = data_[tvb_pos];
line += c < 100 ? ' ' : hexchars[c / 100];
line += c < 10 ? ' ' : hexchars[(c / 10) % 10];
line += hexchars[c % 10];
break;
case BYTES_OCT:
line += hexchars[(data_[tvb_pos] & 0xc0) >> 6];
line += hexchars[(data_[tvb_pos] & 0x38) >> 3];
line += hexchars[data_[tvb_pos] & 0x07];
break;
}
if (build_x_pos) {
x_pos_to_column_ += QVector<int>().fill(tvb_pos - offset, stringWidth(line) - x_pos_to_column_.size() + slop);
}
if (tvb_pos == hovered_byte_offset_ || tvb_pos == marked_byte_offset_) {
int ho_len;
switch (recent.gui_bytes_view) {
case BYTES_HEX:
ho_len = 2;
break;
case BYTES_BITS:
ho_len = 8;
break;
case BYTES_DEC:
case BYTES_OCT:
ho_len = 3;
break;
default:
ws_assert_not_reached();
}
QRect ho_rect = painter->boundingRect(QRect(), Qt::AlignHCenter|Qt::AlignVCenter, line.right(ho_len));
ho_rect.moveRight(stringWidth(line));
ho_rect.moveTop(row_y);
hover_outlines_.append(ho_rect);
}
}
line += QString(ascii_start - line.length(), ' ');
if (build_x_pos) {
x_pos_to_column_ += QVector<int>().fill(-1, stringWidth(line) - x_pos_to_column_.size());
}
addHexFormatRange(fmt_list, proto_start_, proto_len_, offset, max_tvb_pos, ModeProtocol);
if (addHexFormatRange(fmt_list, field_start_, field_len_, offset, max_tvb_pos, ModeField)) {
offset_mode = ModeOffsetField;
}
addHexFormatRange(fmt_list, field_a_start_, field_a_len_, offset, max_tvb_pos, ModeField);
}
// ASCII
if (show_ascii_) {
bool in_non_printable = false;
int np_start = 0;
int np_len = 0;
char c;
for (int tvb_pos = offset; tvb_pos <= max_tvb_pos; tvb_pos++) {
/* insert a space every separator_interval_ bytes */
if ((tvb_pos != offset) && ((tvb_pos % separator_interval_) == 0)) {
line += ' ';
if (build_x_pos) {
x_pos_to_column_ += QVector<int>().fill(tvb_pos - offset - 1, em_width_ / 2);
}
}
if (recent.gui_bytes_encoding != BYTES_ENC_EBCDIC && encoding_ == PACKET_CHAR_ENC_CHAR_ASCII) {
c = data_[tvb_pos];
} else {
c = EBCDIC_to_ASCII1(data_[tvb_pos]);
}
if (g_ascii_isprint(c)) {
line += c;
if (in_non_printable) {
in_non_printable = false;
addAsciiFormatRange(fmt_list, np_start, np_len, offset, max_tvb_pos, ModeNonPrintable);
}
} else {
line += UTF8_MIDDLE_DOT;
if (!in_non_printable) {
in_non_printable = true;
np_start = tvb_pos;
np_len = 1;
} else {
np_len++;
}
}
if (build_x_pos) {
x_pos_to_column_ += QVector<int>().fill(tvb_pos - offset, stringWidth(line) - x_pos_to_column_.size());
}
if (tvb_pos == hovered_byte_offset_ || tvb_pos == marked_byte_offset_) {
QRect ho_rect = painter->boundingRect(QRect(), 0, line.right(1));
ho_rect.moveRight(stringWidth(line));
ho_rect.moveTop(row_y);
hover_outlines_.append(ho_rect);
}
}
if (in_non_printable) {
addAsciiFormatRange(fmt_list, np_start, np_len, offset, max_tvb_pos, ModeNonPrintable);
}
addAsciiFormatRange(fmt_list, proto_start_, proto_len_, offset, max_tvb_pos, ModeProtocol);
if (addAsciiFormatRange(fmt_list, field_start_, field_len_, offset, max_tvb_pos, ModeField)) {
offset_mode = ModeOffsetField;
}
addAsciiFormatRange(fmt_list, field_a_start_, field_a_len_, offset, max_tvb_pos, ModeField);
}
// XXX Fields won't be highlighted if neither hex nor ascii are enabled.
addFormatRange(fmt_list, 0, offsetChars(), offset_mode);
layout_->clearLayout();
layout_->clearFormats();
layout_->setText(line);
layout_->setFormats(fmt_list.toVector());
layout_->beginLayout();
QTextLine tl = layout_->createLine();
tl.setLineWidth(totalPixels());
tl.setLeadingIncluded(true);
layout_->endLayout();
layout_->draw(painter, QPointF(0.0, row_y));
}
bool ByteViewText::addFormatRange(QList<QTextLayout::FormatRange> &fmt_list, int start, int length, HighlightMode mode)
{
if (length < 1)
return false;
QTextLayout::FormatRange format_range;
format_range.start = start;
format_range.length = length;
switch (mode) {
case ModeNormal:
return false;
case ModeField:
format_range.format.setBackground(palette().highlight());
format_range.format.setForeground(palette().highlightedText());
break;
case ModeProtocol:
format_range.format.setBackground(palette().window());
format_range.format.setForeground(palette().windowText());
break;
case ModeOffsetNormal:
format_range.format.setForeground(offset_normal_fg_);
break;
case ModeOffsetField:
format_range.format.setForeground(offset_field_fg_);
break;
case ModeNonPrintable:
format_range.format.setForeground(offset_normal_fg_);
break;
}
fmt_list << format_range;
return true;
}
bool ByteViewText::addHexFormatRange(QList<QTextLayout::FormatRange> &fmt_list, int mark_start, int mark_length, int tvb_offset, int max_tvb_pos, ByteViewText::HighlightMode mode)
{
int mark_end = mark_start + mark_length - 1;
if (mark_start < 0 || mark_length < 1) return false;
if (mark_start > max_tvb_pos && mark_end < tvb_offset) return false;
int chars_per_byte;
switch (recent.gui_bytes_view) {
case BYTES_HEX:
chars_per_byte = 2;
break;
case BYTES_BITS:
chars_per_byte = 8;
break;
case BYTES_DEC:
case BYTES_OCT:
chars_per_byte = 3;
break;
default:
ws_assert_not_reached();
}
int chars_plus_pad = chars_per_byte + 1;
int byte_start = qMax(tvb_offset, mark_start) - tvb_offset;
int byte_end = qMin(max_tvb_pos, mark_end) - tvb_offset;
int fmt_start = offsetChars() + 1 // offset + spacing
+ (byte_start / separator_interval_)
+ (byte_start * chars_plus_pad);
int fmt_length = offsetChars() + 1 // offset + spacing
+ (byte_end / separator_interval_)
+ (byte_end * chars_plus_pad)
+ chars_per_byte
- fmt_start;
return addFormatRange(fmt_list, fmt_start, fmt_length, mode);
}
bool ByteViewText::addAsciiFormatRange(QList<QTextLayout::FormatRange> &fmt_list, int mark_start, int mark_length, int tvb_offset, int max_tvb_pos, ByteViewText::HighlightMode mode)
{
int mark_end = mark_start + mark_length - 1;
if (mark_start < 0 || mark_length < 1) return false;
if (mark_start > max_tvb_pos && mark_end < tvb_offset) return false;
int byte_start = qMax(tvb_offset, mark_start) - tvb_offset;
int byte_end = qMin(max_tvb_pos, mark_end) - tvb_offset;
int fmt_start = offsetChars() + DataPrinter::hexChars() + 3 // offset + hex + spacing
+ (byte_start / separator_interval_)
+ byte_start;
int fmt_length = offsetChars() + DataPrinter::hexChars() + 3 // offset + hex + spacing
+ (byte_end / separator_interval_)
+ byte_end
+ 1 // Just one character.
- fmt_start;
return addFormatRange(fmt_list, fmt_start, fmt_length, mode);
}
void ByteViewText::scrollToByte(int byte)
{
verticalScrollBar()->setValue(byte / row_width_);
}
// Offset character width
int ByteViewText::offsetChars(bool include_pad)
{
int padding = include_pad ? 2 : 0;
if (! data_.isEmpty() && data_.size() > 0xffff) {
return 8 + padding;
}
return 4 + padding;
}
// Offset pixel width
int ByteViewText::offsetPixels()
{
if (show_offset_) {
// One pad space before and after
QString zeroes = QString(offsetChars(), '0');
return stringWidth(zeroes);
}
return 0;
}
// Hex pixel width
int ByteViewText::hexPixels()
{
if (show_hex_) {
// One pad space before and after
QString zeroes = QString(DataPrinter::hexChars() + 2, '0');
return stringWidth(zeroes);
}
return 0;
}
int ByteViewText::asciiPixels()
{
if (show_ascii_) {
// Two pad spaces before, one after
int ascii_chars = (row_width_ + ((row_width_ - 1) / separator_interval_));
QString zeroes = QString(ascii_chars + 3, '0');
return stringWidth(zeroes);
}
return 0;
}
int ByteViewText::totalPixels()
{
return offsetPixels() + hexPixels() + asciiPixels();
}
void ByteViewText::copyBytes(bool)
{
QAction* action = qobject_cast<QAction*>(sender());
if (!action) {
return;
}
int dump_type = action->data().toInt();
if (dump_type <= DataPrinter::DP_MimeData) {
DataPrinter printer;
printer.toClipboard((DataPrinter::DumpType) dump_type, this);
}
}
// We do chunky (per-character) scrolling because it makes some of the
// math easier. Should we do smooth scrolling?
void ByteViewText::updateScrollbars()
{
const int length = static_cast<int>(data_.size());
if (length > 0 && line_height_ > 0 && em_width_ > 0) {
int all_lines_height = length / row_width_ + ((length % row_width_) ? 1 : 0) - viewport()->height() / line_height_;
verticalScrollBar()->setRange(0, qMax(0, all_lines_height));
horizontalScrollBar()->setRange(0, qMax(0, int((totalPixels() - viewport()->width()) / em_width_)));
}
}
int ByteViewText::byteOffsetAtPixel(QPoint pos)
{
int byte = (verticalScrollBar()->value() + (pos.y() / line_height_)) * row_width_;
int x = (horizontalScrollBar()->value() * em_width_) + pos.x();
int col = x_pos_to_column_.value(x, -1);
if (col < 0) {
return -1;
}
byte += col;
if (byte > data_.size()) {
return -1;
}
return byte;
}
void ByteViewText::setHexDisplayFormat(QAction *action)
{
if (!action) {
return;
}
recent.gui_bytes_view = action->data().value<bytes_view_type>();
emit byteViewSettingsChanged();
}
void ByteViewText::setCharacterEncoding(QAction *action)
{
if (!action) {
return;
}
recent.gui_bytes_encoding = action->data().value<bytes_encoding_type>();
emit byteViewSettingsChanged();
} |
C/C++ | wireshark/ui/qt/widgets/byte_view_text.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef BYTE_VIEW_TEXT_H
#define BYTE_VIEW_TEXT_H
#include <config.h>
#include "ui/recent.h"
#include <QAbstractScrollArea>
#include <QFont>
#include <QVector>
#include <QMenu>
#include <QSize>
#include <QString>
#include <QTextLayout>
#include <QVector>
#include <ui/qt/utils/data_printer.h>
#include <ui/qt/utils/idata_printable.h>
// XXX - Is there any reason we shouldn't add ByteViewImage, etc?
class ByteViewText : public QAbstractScrollArea, public IDataPrintable
{
Q_OBJECT
Q_INTERFACES(IDataPrintable)
public:
explicit ByteViewText(const QByteArray &data, packet_char_enc encoding = PACKET_CHAR_ENC_CHAR_ASCII, QWidget *parent = 0);
~ByteViewText();
virtual QSize minimumSizeHint() const;
void setFormat(bytes_view_type format);
bool isEmpty() const;
signals:
void byteHovered(int pos);
void byteSelected(int pos);
void byteViewSettingsChanged();
public slots:
void setMonospaceFont(const QFont &mono_font);
void updateByteViewSettings();
void detachData();
void markProtocol(int start, int length);
void markField(int start, int length, bool scroll_to = true);
void markAppendix(int start, int length);
protected:
virtual void paintEvent(QPaintEvent *);
virtual void resizeEvent(QResizeEvent *);
virtual void mousePressEvent (QMouseEvent * event);
virtual void mouseMoveEvent (QMouseEvent * event);
virtual void leaveEvent(QEvent *event);
virtual void contextMenuEvent(QContextMenuEvent *event);
private:
// Text highlight modes.
typedef enum {
ModeNormal,
ModeField,
ModeProtocol,
ModeOffsetNormal,
ModeOffsetField,
ModeNonPrintable
} HighlightMode;
QTextLayout *layout_;
QByteArray data_;
void updateLayoutMetrics();
int stringWidth(const QString &line);
void drawLine(QPainter *painter, const int offset, const int row_y);
bool addFormatRange(QList<QTextLayout::FormatRange> &fmt_list, int start, int length, HighlightMode mode);
bool addHexFormatRange(QList<QTextLayout::FormatRange> &fmt_list, int mark_start, int mark_length, int tvb_offset, int max_tvb_pos, HighlightMode mode);
bool addAsciiFormatRange(QList<QTextLayout::FormatRange> &fmt_list, int mark_start, int mark_length, int tvb_offset, int max_tvb_pos, HighlightMode mode);
void scrollToByte(int byte);
void updateScrollbars();
int byteOffsetAtPixel(QPoint pos);
void createContextMenu();
void updateContextMenu();
int offsetChars(bool include_pad = true);
int offsetPixels();
int hexPixels();
int asciiPixels();
int totalPixels();
const QByteArray printableData() { return data_; }
static const int separator_interval_;
// Colors
QColor offset_normal_fg_;
QColor offset_field_fg_;
// Data
packet_char_enc encoding_; // ASCII or EBCDIC
QMenu ctx_menu_;
// Data highlight
int hovered_byte_offset_;
int marked_byte_offset_;
int proto_start_;
int proto_len_;
int field_start_;
int field_len_;
int field_a_start_;
int field_a_len_;
bool show_offset_; // Should we show the byte offset?
bool show_hex_; // Should we show the hex display?
bool show_ascii_; // Should we show the ASCII display?
int row_width_; // Number of bytes per line
int em_width_; // Single character width and text margin. NOTE: Use fontMetrics::width for multiple characters.
int line_height_; // Font line spacing
QList<QRect> hover_outlines_; // Hovered byte outlines.
bool allow_hover_selection_;
// Data selection
QVector<int> x_pos_to_column_;
// Context menu actions
QAction *action_allow_hover_selection_;
QAction *action_bytes_hex_;
QAction *action_bytes_dec_;
QAction *action_bytes_oct_;
QAction *action_bytes_bits_;
QAction *action_bytes_enc_from_packet_;
QAction *action_bytes_enc_ascii_;
QAction *action_bytes_enc_ebcdic_;
private slots:
void copyBytes(bool);
void setHexDisplayFormat(QAction *action);
void setCharacterEncoding(QAction *action);
void toggleHoverAllowed(bool);
};
#endif // BYTE_VIEW_TEXT_H |
C++ | wireshark/ui/qt/widgets/capture_filter_combo.cpp | /* capture_filter_combo.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <stdio.h>
#include <ui/qt/utils/qt_ui_utils.h>
#include "ui/recent_utils.h"
#include "ui/recent.h"
#include <epan/prefs.h>
#include <ui/qt/widgets/capture_filter_combo.h>
#include <ui/qt/utils/color_utils.h>
#include "main_application.h"
CaptureFilterCombo::CaptureFilterCombo(QWidget *parent, bool plain) :
QComboBox(parent),
cf_edit_(NULL)
{
cf_edit_ = new CaptureFilterEdit(this, plain);
setEditable(true);
setLineEdit(cf_edit_);
// setLineEdit will create a new QCompleter that performs inline completion,
// be sure to disable that since our CaptureFilterEdit performs its own
// popup completion. As QLineEdit's completer is designed for full line
// completion, we cannot reuse it for word completion.
setCompleter(0);
// Default is Preferred.
setSizePolicy(QSizePolicy::MinimumExpanding, sizePolicy().verticalPolicy());
setInsertPolicy(QComboBox::NoInsert);
setAccessibleName(tr("Capture filter selector"));
updateStyleSheet();
connect(this, &CaptureFilterCombo::interfacesChanged, cf_edit_,
static_cast<void (CaptureFilterEdit::*)()>(&CaptureFilterEdit::checkFilter));
connect(cf_edit_, &CaptureFilterEdit::captureFilterSyntaxChanged,
this, &CaptureFilterCombo::captureFilterSyntaxChanged);
connect(cf_edit_, &CaptureFilterEdit::startCapture, this, &CaptureFilterCombo::startCapture);
connect(cf_edit_, &CaptureFilterEdit::startCapture, this, &CaptureFilterCombo::saveAndRebuildFilterList);
connect(mainApp, &MainApplication::appInitialized, this, &CaptureFilterCombo::rebuildFilterList);
connect(mainApp, &MainApplication::preferencesChanged, this, &CaptureFilterCombo::rebuildFilterList);
rebuildFilterList();
clearEditText();
}
void CaptureFilterCombo::writeRecent(FILE *rf)
{
int i;
for (i = 0; i < count(); i++) {
const QByteArray& filter = itemText(i).toUtf8();
if (!filter.isEmpty()) {
fprintf(rf, RECENT_KEY_DISPLAY_FILTER ": %s\n", filter.constData());
}
}
}
bool CaptureFilterCombo::event(QEvent *event)
{
switch (event->type()) {
case QEvent::ApplicationPaletteChange:
updateStyleSheet();
break;
default:
break;
}
return QComboBox::event(event);
}
void CaptureFilterCombo::updateStyleSheet()
{
const char *display_mode = ColorUtils::themeIsDark() ? "dark" : "light";
QString ss = QString(
"QComboBox {"
#ifdef Q_OS_MAC
" border: 1px solid gray;"
#else
" border: 1px solid palette(shadow);"
#endif
" border-radius: 3px;"
" padding: 0px 0px 0px 0px;"
" margin-left: 0px;"
" min-width: 20em;"
" }"
"QComboBox::drop-down {"
" subcontrol-origin: padding;"
" subcontrol-position: top right;"
" width: 14px;"
" border-left-width: 0px;"
" }"
"QComboBox::down-arrow {"
" image: url(:/stock_icons/14x14/x-filter-dropdown.%1.png);"
" }"
"QComboBox::down-arrow:on { /* shift the arrow when popup is open */"
" top: 1px;"
" left: 1px;"
"}"
).arg(display_mode);
setStyleSheet(ss);
}
void CaptureFilterCombo::saveAndRebuildFilterList()
{
if (!currentText().isEmpty()) {
recent_add_cfilter(NULL, currentText().toUtf8().constData());
}
rebuildFilterList();
}
void CaptureFilterCombo::rebuildFilterList()
{
lineEdit()->blockSignals(true);
GList *cfilter_list = recent_get_cfilter_list(NULL);
QString cur_filter = currentText();
clear();
for (GList *li = g_list_first(cfilter_list); li != NULL; li = gxx_list_next(li)) {
insertItem(0, gxx_list_data(const gchar *, li));
}
lineEdit()->setText(cur_filter);
lineEdit()->blockSignals(false);
} |
C/C++ | wireshark/ui/qt/widgets/capture_filter_combo.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef CAPTURE_FILTER_COMBO_H
#define CAPTURE_FILTER_COMBO_H
#include <ui/qt/widgets/capture_filter_edit.h>
#include <QComboBox>
#include <QList>
class CaptureFilterCombo : public QComboBox
{
Q_OBJECT
public:
explicit CaptureFilterCombo(QWidget *parent = 0, bool plain = false);
bool addRecentCapture(const char *filter);
void writeRecent(FILE *rf);
void setConflict(bool conflict = false) { cf_edit_->setConflict(conflict); }
signals:
void interfacesChanged();
void captureFilterSyntaxChanged(bool valid);
void startCapture();
protected:
virtual bool event(QEvent *event);
private:
void updateStyleSheet();
CaptureFilterEdit *cf_edit_;
private slots:
void saveAndRebuildFilterList();
void rebuildFilterList();
};
#endif // CAPTURE_FILTER_COMBO_H |
C/C++ | wireshark/ui/qt/widgets/capture_filter_edit.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef CAPTURE_FILTER_EDIT_H
#define CAPTURE_FILTER_EDIT_H
#include <QThread>
#include <QToolButton>
#include <QActionGroup>
#include <ui/qt/widgets/syntax_line_edit.h>
class CaptureFilterSyntaxWorker;
class StockIconToolButton;
class CaptureFilterEdit : public SyntaxLineEdit
{
Q_OBJECT
public:
explicit CaptureFilterEdit(QWidget *parent = 0, bool plain = false);
~CaptureFilterEdit();
void setConflict(bool conflict = false);
// No selections: (QString(), false)
// Selections, same filter: (filter, false)
// Selections, different filters (QString(), true)
static QPair<const QString, bool> getSelectedFilter();
protected:
void paintEvent(QPaintEvent *evt);
void resizeEvent(QResizeEvent *);
void keyPressEvent(QKeyEvent *event) { completionKeyPressEvent(event); }
void focusInEvent(QFocusEvent *event) { completionFocusInEvent(event); }
public slots:
void checkFilter();
void updateBookmarkMenu();
void saveFilter();
void removeFilter();
void showFilters();
void prepareFilter();
private slots:
void applyCaptureFilter();
void checkFilter(const QString &filter);
void setFilterSyntaxState(QString filter, int state, QString err_msg);
void bookmarkClicked();
void clearFilter();
private:
bool plain_;
bool field_name_only_;
bool enable_save_action_;
QString placeholder_text_;
QAction *save_action_;
QAction *remove_action_;
QActionGroup * actions_;
StockIconToolButton *bookmark_button_;
StockIconToolButton *clear_button_;
StockIconToolButton *apply_button_;
CaptureFilterSyntaxWorker *syntax_worker_;
QThread *syntax_thread_;
void buildCompletionList(const QString &primitive_word, const QString &preamble);
signals:
void captureFilterSyntaxChanged(bool valid);
void captureFilterChanged(const QString filter);
void startCapture();
void addBookmark(const QString filter);
};
#endif // CAPTURE_FILTER_EDIT_H |
C++ | wireshark/ui/qt/widgets/clickable_label.cpp | /* clickable_label.cpp
*
* Taken from https://wiki.qt.io/Clickable_QLabel and adapted for usage
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/clickable_label.h>
#include <QMouseEvent>
ClickableLabel::ClickableLabel(QWidget* parent)
: QLabel(parent)
{
setMinimumWidth(0);
setText(QString());
setStyleSheet(QString(
"QLabel {"
" margin-left: 0.5em;"
" }"
));
}
void ClickableLabel::mouseReleaseEvent(QMouseEvent * event)
{
/* It has to be ensured, that if the user clicks on the label and then moves away out of
* the scope of the widget, the event does not fire. Otherwise this behavior differs from
* the way, the toolbar buttons work for instance */
if (event->pos().x() < 0 || event->pos().x() > size().width())
return;
if (event->pos().y() < 0 || event->pos().y() > size().height())
return;
emit clicked();
}
void ClickableLabel::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
#if QT_VERSION >= QT_VERSION_CHECK(6, 0 ,0)
emit clickedAt(event->globalPosition().toPoint(), Qt::LeftButton);
#else
emit clickedAt(event->globalPos(), Qt::LeftButton);
#endif
}
void ClickableLabel::contextMenuEvent(QContextMenuEvent *event)
{
emit clickedAt(QPoint(event->globalPos()), Qt::RightButton);
} |
C/C++ | wireshark/ui/qt/widgets/clickable_label.h | /** @file
*
* Taken from https://wiki.qt.io/Clickable_QLabel and adapted for usage
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef CLICKABLE_LABEL_H_
#define CLICKABLE_LABEL_H_
#include <QLabel>
class ClickableLabel : public QLabel
{
Q_OBJECT
public:
explicit ClickableLabel(QWidget* parent=0);
signals:
void clicked();
void clickedAt(const QPoint &global_pos, Qt::MouseButton button);
protected:
void mouseReleaseEvent(QMouseEvent* event);
void mousePressEvent(QMouseEvent *event);
void contextMenuEvent(QContextMenuEvent *event);
};
#endif /* CLICKABLE_LABEL_H_ */ |
C++ | wireshark/ui/qt/widgets/copy_from_profile_button.cpp | /* copy_from_profile_button.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <ui/qt/widgets/copy_from_profile_button.h>
#include <ui/qt/models/profile_model.h>
#include <wsutil/filesystem.h>
#include <QDir>
#include <QFileInfo>
#include <QMenu>
#include <QAction>
CopyFromProfileButton::CopyFromProfileButton(QWidget * parent, QString fileName, QString toolTip) :
QPushButton(parent),
buttonMenu_(Q_NULLPTR)
{
setText(tr("Copy from"));
if (toolTip.length() == 0)
setToolTip(tr("Copy entries from another profile."));
else {
setToolTip(toolTip);
}
if (fileName.length() > 0)
setFilename(fileName);
}
void CopyFromProfileButton::setFilename(QString filename)
{
setEnabled(false);
if (filename.length() <= 0)
return;
ProfileModel model(this);
QList<QAction *> global;
QList<QAction *> user;
QAction * pa = systemDefault(filename);
if (pa)
global << pa;
if (! buttonMenu_)
buttonMenu_ = new QMenu();
if (buttonMenu_->actions().count() > 0)
buttonMenu_->clear();
for (int cnt = 0; cnt < model.rowCount(); cnt++)
{
QModelIndex idx = model.index(cnt, ProfileModel::COL_NAME);
QString profilePath = idx.data(ProfileModel::DATA_PATH).toString();
if (! idx.isValid() || profilePath.isEmpty())
continue;
if (! idx.data(ProfileModel::DATA_PATH_IS_NOT_DESCRIPTION).toBool() || idx.data(ProfileModel::DATA_IS_SELECTED).toBool())
continue;
QDir profileDir(profilePath);
if (! profileDir.exists())
continue;
QFileInfo fi(profileDir.filePath(filename));
if (! fi.exists())
continue;
if (! config_file_exists_with_entries(fi.absoluteFilePath().toUtf8().constData(), '#'))
continue;
QString name = idx.data().toString();
pa = new QAction(name, this);
if (idx.data(ProfileModel::DATA_IS_DEFAULT).toBool())
buttonMenu_->addAction(pa);
else if (idx.data(ProfileModel::DATA_IS_GLOBAL).toBool())
global << pa;
else
user << pa;
pa->setFont(idx.data(Qt::FontRole).value<QFont>());
pa->setProperty("profile_name", name);
pa->setProperty("profile_is_global", idx.data(ProfileModel::DATA_IS_GLOBAL));
pa->setProperty("profile_filename", fi.absoluteFilePath());
}
buttonMenu_->addActions(user);
if (global.count() > 0)
{
if (actions().count() > 0)
buttonMenu_->addSeparator();
buttonMenu_->addActions(global);
}
if (buttonMenu_->actions().count() <= 0)
return;
connect(buttonMenu_, &QMenu::triggered, this, &CopyFromProfileButton::menuActionTriggered);
setMenu(buttonMenu_);
setEnabled(true);
}
// "System default" is not a profile.
// Add a special entry for this if the filename exists.
QAction * CopyFromProfileButton::systemDefault(QString filename)
{
QAction * data = Q_NULLPTR;
QDir dataDir(get_datafile_dir());
QString path = dataDir.filePath(filename);
if (QFile::exists(path))
{
data = new QAction(tr("System default"), this);
data->setData(path);
QFont font = data->font();
font.setItalic(true);
data->setFont(font);
data->setProperty("profile_filename", path);
}
return data;
}
void CopyFromProfileButton::menuActionTriggered(QAction * action)
{
if (action->property("profile_filename").toString().length() > 0)
{
QString filename = action->property("profile_filename").toString();
if (QFileInfo::exists(filename))
emit copyProfile(filename);
}
} |
C/C++ | wireshark/ui/qt/widgets/copy_from_profile_button.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef COPY_FROM_PROFILE_BUTTON_H
#define COPY_FROM_PROFILE_BUTTON_H
#include <config.h>
#include <glib.h>
#include <QMenu>
#include <QPushButton>
#include <QDialogButtonBox>
#include <QMetaObject>
class CopyFromProfileButton : public QPushButton
{
Q_OBJECT
public:
CopyFromProfileButton(QWidget * parent = Q_NULLPTR, QString profileFile = QString(), QString toolTip = QString());
void setFilename(QString filename);
signals:
void copyProfile(QString filename);
private:
QString filename_;
QMenu * buttonMenu_;
QAction * systemDefault(QString filename);
private slots:
void menuActionTriggered(QAction *);
};
#endif // COPY_FROM_PROFILE_BUTTON_H |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.