### Bug Summary

File: | ui/qt/packet_list.cpp
Warning: | line 922, column 20 Potential leak of memory pointed to by 'drag_label'

### Annotated Source Code

Press '?' to see keyboard shortcuts

Show analyzer invocation
clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name packet_list.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -fno-delete-null-pointer-checks -mframe-pointer=all -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -ffloat16-excess-precision=fast -fbfloat16-excess-precision=fast -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/builds/wireshark/wireshark/build -fcoverage-compilation-dir=/builds/wireshark/wireshark/build -resource-dir /usr/lib/llvm-21/lib/clang/21 -isystem /usr/include/glib-2.0 -isystem /usr/lib/x86_64-linux-gnu/glib-2.0/include -isystem /builds/wireshark/wireshark/build/ui/qt -isystem /builds/wireshark/wireshark/ui/qt -isystem /usr/include/x86_64-linux-gnu/qt6/QtWidgets -isystem /usr/include/x86_64-linux-gnu/qt6 -isystem /usr/include/x86_64-linux-gnu/qt6/QtCore -isystem /usr/lib/x86_64-linux-gnu/qt6/mkspecs/linux-g++ -isystem /usr/include/x86_64-linux-gnu/qt6/QtGui -isystem /usr/include/x86_64-linux-gnu/qt6/QtCore5Compat -isystem /usr/include/x86_64-linux-gnu/qt6/QtConcurrent -isystem /usr/include/x86_64-linux-gnu/qt6/QtPrintSupport -isystem /usr/include/x86_64-linux-gnu/qt6/QtMultimedia -isystem /usr/include/x86_64-linux-gnu/qt6/QtNetwork -isystem /usr/include/x86_64-linux-gnu/qt6/QtDBus -D G_DISABLE_DEPRECATED -D G_DISABLE_SINGLE_INCLUDES -D QT_CONCURRENT_LIB -D QT_CORE5COMPAT_LIB -D QT_CORE_LIB -D QT_DBUS_LIB -D QT_GUI_LIB -D QT_MULTIMEDIA_LIB -D QT_NETWORK_LIB -D QT_PRINTSUPPORT_LIB -D QT_WIDGETS_LIB -D WS_DEBUG -D WS_DEBUG_UTF_8 -I /builds/wireshark/wireshark/build/ui/qt/qtui_autogen/include -I /builds/wireshark/wireshark/build -I /builds/wireshark/wireshark -I /builds/wireshark/wireshark/include -D _GLIBCXX_ASSERTIONS -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/x86_64-linux-gnu/c++/14 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/backward -internal-isystem /usr/lib/llvm-21/lib/clang/21/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/builds/wireshark/wireshark/= -fmacro-prefix-map=/builds/wireshark/wireshark/build/= -fmacro-prefix-map=../= -Wno-format-truncation -Wno-format-nonliteral -std=c++17 -fdeprecated-macro -ferror-limit 19 -fwrapv -fwrapv-pointer -fstrict-flex-arrays=3 -stack-protector 2 -fstack-clash-protection -fcf-protection=full -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fcxx-exceptions -fexceptions -fcolor-diagnostics -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /builds/wireshark/wireshark/sbout/2025-10-31-100325-3623-1 -x c++ /builds/wireshark/wireshark/ui/qt/packet_list.cpp

Keyboard shortcuts:

- Use 'j/k' keys for keyboard navigation
- Use 'Shift+S' to show/hide relevant lines
- Use '?' to toggle this window

Close
Show only relevant lines Show control flow arrows

1 | /* packet_list.cpp
2 | *
3 | * Wireshark - Network traffic analyzer
4 | * By Gerald Combs <gerald@wireshark.org>
5 | * Copyright 1998 Gerald Combs
6 | *
7 | * SPDX-License-Identifier: GPL-2.0-or-later
8 | */
9 |
10 | #include <ui/qt/packet_list.h>
11 |
12 | #include "config.h"
13 |
14 | #include "file.h"
15 |
16 | #include <epan/epan.h>
17 | #include <epan/epan_dissect.h>
18 |
19 | #include <epan/column.h>
20 | #include <epan/expert.h>
21 | #include <epan/ipproto.h>
22 | #include <epan/packet.h>
23 | #include <epan/prefs.h>
24 | #include <epan/proto.h>
25 |
26 | #include "ui/main_statusbar.h"
27 | #include "ui/packet_list_utils.h"
28 | #include "ui/preference_utils.h"
29 | #include "ui/recent.h"
30 | #include "ui/recent_utils.h"
31 | #include "ui/ws_ui_util.h"
32 | #include "ui/simple_dialog.h"
33 | #include <wsutil/utf8_entities.h>
34 | #include "ui/util.h"
35 |
36 | #include "wiretap/wtap_opttypes.h"
37 | #include "wsutil/application_flavor.h"
38 | #include "wsutil/str_util.h"
39 | #include <wsutil/wslog.h>
40 |
41 | #include <epan/color_filters.h>
42 |
43 | #include <ui/qt/utils/color_utils.h>
44 | #include <ui/qt/widgets/overlay_scroll_bar.h>
45 | #include "proto_tree.h"
46 | #include <ui/qt/utils/qt_ui_utils.h>
47 | #include "main_application.h"
48 | #include <ui/qt/utils/data_printer.h>
49 | #include <ui/qt/utils/frame_information.h>
50 | #include <ui/qt/utils/profile_switcher.h>
51 | #include <ui/qt/utils/variant_pointer.h>
52 | #include <ui/qt/models/pref_models.h>
53 | #include <ui/qt/widgets/packet_list_header.h>
54 | #include <ui/qt/utils/wireshark_mime_data.h>
55 | #include <ui/qt/widgets/drag_label.h>
56 | #include <ui/qt/filter_action.h>
57 | #include <ui/qt/follow_stream_action.h>
58 | #include <ui/qt/decode_as_dialog.h>
59 | #include <ui/qt/wireshark_main_window.h>
60 |
61 | #include <QAction>
62 | #include <QActionGroup>
63 | #include <QClipboard>
64 | #include <QContextMenuEvent>
65 | #include <QtCore/qmath.h>
66 | #include <QElapsedTimer>
67 | #include <QFontMetrics>
68 | #include <QHeaderView>
69 | #include <QMessageBox>
70 | #include <QPainter>
71 | #include <QScreen>
72 | #include <QScrollBar>
73 | #include <QTabWidget>
74 | #include <QTextEdit>
75 | #include <QTimerEvent>
76 | #include <QTreeWidget>
77 | #include <QWindow>
78 | #include <QJsonObject>
79 | #include <QJsonDocument>
80 |
81 | #ifdef Q_OS_WIN
82 | #include "wsutil/file_util.h"
83 | #include <QSysInfo>
84 | #include <uxtheme.h>
85 | #endif
86 |
87 | // To do:
88 | // - Fix "apply as filter" behavior.
89 | // - Add colorize conversation.
90 | // - Use a timer to trigger automatic scrolling.
91 |
92 | // If we ever add the ability to open multiple capture files we might be
93 | // able to use something like QMap<capture_file *, PacketList *> to match
94 | // capture files against packet lists and models.
95 | static PacketList *gbl_cur_packet_list;
96 |
97 | const int max_comments_to_fetch_ = 20000000; // Arbitrary
98 | const int overlay_update_interval_ = 100; // 250; // Milliseconds.
99 |
100 |
101 | /*
102 | * Given a frame_data structure, scroll to and select the row in the
103 | * packet list corresponding to that frame. If there is no such
104 | * row, return false, otherwise return true.
105 | */
106 | bool
107 | packet_list_select_row_from_data(frame_data *fdata_needle)
108 | {
109 | if (! gbl_cur_packet_list || ! gbl_cur_packet_list->model())
110 | return false;
111 | return gbl_cur_packet_list->selectRow(fdata_needle);
112 | }
113 |
114 | /*
115 | * Given a field_info, select the field (which will scroll to it in
116 | * the main ProtoTree, etc.) This is kind of an odd place for it,
117 | * but we call this when performing Find Packet in lieu of changing the
118 | * selected frame (the function above), because we found a match in the
119 | * same frame as the currently selected one.
120 | */
121 | bool
122 | packet_list_select_finfo(field_info *fi)
123 | {
124 | if (! gbl_cur_packet_list || ! gbl_cur_packet_list->model())
125 | return false;
126 |
127 | if (fi) {
128 | FieldInformation finfo(fi, gbl_cur_packet_list);
129 | emit gbl_cur_packet_list->fieldSelected(&finfo);
130 | } else {
131 | emit gbl_cur_packet_list->fieldSelected(0);
132 | }
133 | return true;
134 | }
135 |
136 | void
137 | packet_list_clear(void)
138 | {
139 | if (gbl_cur_packet_list) {
140 | gbl_cur_packet_list->clear();
141 | }
142 | }
143 |
144 | void
145 | packet_list_freeze(void)
146 | {
147 | if (gbl_cur_packet_list) {
148 | gbl_cur_packet_list->freeze();
149 | }
150 | }
151 |
152 | void
153 | packet_list_thaw(void)
154 | {
155 | if (gbl_cur_packet_list) {
156 | gbl_cur_packet_list->thaw();
157 | }
158 |
159 | packets_bar_update();
160 | }
161 |
162 | /* Redraw the packet list *and* currently-selected detail */
163 | void
164 | packet_list_queue_draw(void)
165 | {
166 | if (gbl_cur_packet_list)
167 | gbl_cur_packet_list->redrawVisiblePackets();
168 | }
169 |
170 | void
171 | packet_list_recent_write_all(FILE *rf) {
172 | if (!gbl_cur_packet_list)
173 | return;
174 |
175 | gbl_cur_packet_list->writeRecent(rf);
176 | }
177 |
178 | bool
179 | packet_list_multi_select_active(void)
180 | {
181 | if (gbl_cur_packet_list) {
182 | return gbl_cur_packet_list->multiSelectActive();
183 | }
184 | return false;
185 | }
186 |
187 | #define MIN_COL_WIDTH_STR"MMMMMM" "MMMMMM"
188 |
189 | PacketList::PacketList(QWidget *parent) :
190 | QTreeView(parent),
191 | proto_tree_(nullptr),
192 | cap_file_(nullptr),
193 | ctx_column_(-1),
194 | overlay_timer_id_(0),
195 | create_near_overlay_(true),
196 | create_far_overlay_(true),
197 | mouse_pressed_at_(QModelIndex()),
198 | capture_in_progress_(false),
199 | tail_at_end_(0),
200 | columns_changed_(false),
201 | set_column_visibility_(false),
202 | set_style_sheet_(false),
203 | frozen_current_row_(QModelIndex()),
204 | frozen_selected_rows_(QModelIndexList()),
205 | cur_history_(-1),
206 | in_history_(false),
207 | finfo_array(nullptr),
208 | profile_switcher_(nullptr)
209 | {
210 | setItemsExpandable(false);
211 | setRootIsDecorated(false);
212 | setSortingEnabled(prefs.gui_packet_list_sortable);
213 | setUniformRowHeights(true);
214 | setAccessibleName("Packet list");
215 |
216 | packet_list_header_ = new PacketListHeader(header()->orientation());
217 | connect(packet_list_header_, &PacketListHeader::resetColumnWidth, this, &PacketList::setRecentColumnWidth);
218 | connect(packet_list_header_, &PacketListHeader::updatePackets, this, &PacketList::updatePackets);
219 | connect(packet_list_header_, &PacketListHeader::showColumnPreferences, this, &PacketList::showProtocolPreferences);
220 | connect(packet_list_header_, &PacketListHeader::editColumn, this, &PacketList::editColumn);
221 | connect(packet_list_header_, &PacketListHeader::columnsChanged, this, &PacketList::columnsChanged);
222 | setHeader(packet_list_header_);
223 |
224 | header()->setFirstSectionMovable(true);
225 |
226 | setSelectionMode(QAbstractItemView::ExtendedSelection);
227 |
228 | // Shrink down to a small but nonzero size in the main splitter.
229 | int one_em = fontMetrics().height();
230 | setMinimumSize(one_em, one_em);
231 |
232 | overlay_sb_ = new OverlayScrollBar(Qt::Vertical, this);
233 | setVerticalScrollBar(overlay_sb_);
234 |
235 | header()->setSortIndicator(-1, Qt::AscendingOrder);
236 |
237 | packet_list_model_ = new PacketListModel(this, cap_file_);
238 | setModel(packet_list_model_);
239 |
240 | Q_ASSERT(gbl_cur_packet_list == Q_NULLPTR)((gbl_cur_packet_list == nullptr) ? static_cast<void>(0 ) : qt_assert("gbl_cur_packet_list == Q_NULLPTR", "ui/qt/packet_list.cpp" , 240));
241 | gbl_cur_packet_list = this;
242 |
243 | connect(packet_list_model_, &PacketListModel::goToPacket, this, [=](int packet) { goToPacket(packet); });
244 | connect(mainApp, &MainApplication::addressResolutionChanged, this, &PacketList::redrawVisiblePacketsDontSelectCurrent);
245 | connect(mainApp, &MainApplication::columnDataChanged, this, &PacketList::redrawVisiblePacketsDontSelectCurrent);
246 | connect(mainApp, &MainApplication::preferencesChanged, this, [=]() {
247 | /* The pref is a uint but QCache maxCost is a signed int (/
248 | * qsizetype in Qt 6). Note that QAbstractItemModel row numbers
249 | * are ints, not unsigned ints, so we're limited to INT_MAX
250 | * rows anyway.
251 | */
252 | PacketListRecord::setMaxCache(prefs.gui_packet_list_cached_rows_max > INT_MAX2147483647 ? INT_MAX2147483647 : prefs.gui_packet_list_cached_rows_max);
253 | if ((bool) (prefs.gui_packet_list_sortable) != isSortingEnabled()) {
254 | setSortingEnabled(prefs.gui_packet_list_sortable);
255 | }
256 | });
257 |
258 | connect(header(), &QHeaderView::sectionResized, this, &PacketList::sectionResized);
259 | connect(header(), &QHeaderView::sectionMoved, this, &PacketList::sectionMoved);
260 |
261 | connect(verticalScrollBar(), &QScrollBar::actionTriggered, this, &PacketList::vScrollBarActionTriggered);
262 | }
263 |
264 | PacketList::~PacketList()
265 | {
266 | if (finfo_array)
267 | {
268 | g_ptr_array_free(finfo_array, true);
269 | }
270 | }
271 |
272 | void PacketList::scrollTo(const QModelIndex &index, QAbstractItemView::ScrollHint hint)
273 | {
274 | /* QAbstractItemView doesn't have a way to indicate "auto scroll, but
275 | * only vertically." So just restore the horizontal scroll value whenever
276 | * it scrolls.
277 | */
278 | setUpdatesEnabled(false);
279 | int horizVal = horizontalScrollBar()->value();
280 | QTreeView::scrollTo(index, hint);
281 | horizontalScrollBar()->setValue(horizVal);
282 | setUpdatesEnabled(true);
283 | }
284 |
285 | void PacketList::colorsChanged()
286 | {
287 | const QString c_active = "active";
288 | const QString c_inactive = "!active";
289 |
290 | QString flat_style_format =
291 | "QTreeView::item:selected:%1 {"
292 | " color: %2;"
293 | " background-color: %3;"
294 | "}";
295 |
296 | QString gradient_style_format =
297 | "QTreeView::item:selected:%1 {"
298 | " color: %2;"
299 | " background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1 stop: 0 %4, stop: 0.5 %3, stop: 1 %4);"
300 | "}";
301 |
302 | QString hover_style = QStringLiteral((QString(QtPrivate::qMakeStringPrivate(u"" "QTreeView:item:hover {" " background-color: %1;" " color: palette(text);" "}")))
303 | "QTreeView:item:hover {"(QString(QtPrivate::qMakeStringPrivate(u"" "QTreeView:item:hover {" " background-color: %1;" " color: palette(text);" "}")))
304 | " background-color: %1;"(QString(QtPrivate::qMakeStringPrivate(u"" "QTreeView:item:hover {" " background-color: %1;" " color: palette(text);" "}")))
305 | " color: palette(text);"(QString(QtPrivate::qMakeStringPrivate(u"" "QTreeView:item:hover {" " background-color: %1;" " color: palette(text);" "}")))
306 | "}")(QString(QtPrivate::qMakeStringPrivate(u"" "QTreeView:item:hover {" " background-color: %1;" " color: palette(text);" "}"))).arg(ColorUtils::hoverBackground().name(QColor::HexArgb));
307 |
308 | QString active_style = QString();
309 | QString inactive_style = QString();
310 |
311 | if (prefs.gui_active_style == COLOR_STYLE_DEFAULT0) {
312 | // ACTIVE = Default
313 | } else if (prefs.gui_active_style == COLOR_STYLE_FLAT1) {
314 | // ACTIVE = Flat
315 | QColor foreground = ColorUtils::fromColorT(prefs.gui_active_fg);
316 | QColor background = ColorUtils::fromColorT(prefs.gui_active_bg);
317 |
318 | active_style = flat_style_format.arg(
319 | c_active,
320 | foreground.name(),
321 | background.name());
322 | } else if (prefs.gui_active_style == COLOR_STYLE_GRADIENT2) {
323 | // ACTIVE = Gradient
324 | QColor foreground = ColorUtils::fromColorT(prefs.gui_active_fg);
325 | QColor background1 = ColorUtils::fromColorT(prefs.gui_active_bg);
326 | QColor background2 = QColor::fromRgb(ColorUtils::alphaBlend(foreground, background1, COLOR_STYLE_ALPHA0.25));
327 |
328 | active_style = gradient_style_format.arg(
329 | c_active,
330 | foreground.name(),
331 | background1.name(),
332 | background2.name());
333 | }
334 |
335 | // INACTIVE style sheet settings
336 | if (prefs.gui_inactive_style == COLOR_STYLE_DEFAULT0) {
337 | // INACTIVE = Default
338 | } else if (prefs.gui_inactive_style == COLOR_STYLE_FLAT1) {
339 | // INACTIVE = Flat
340 | QColor foreground = ColorUtils::fromColorT(prefs.gui_inactive_fg);
341 | QColor background = ColorUtils::fromColorT(prefs.gui_inactive_bg);
342 |
343 | inactive_style = flat_style_format.arg(
344 | c_inactive,
345 | foreground.name(),
346 | background.name());
347 | } else if (prefs.gui_inactive_style == COLOR_STYLE_GRADIENT2) {
348 | // INACTIVE = Gradient
349 | QColor foreground = ColorUtils::fromColorT(prefs.gui_inactive_fg);
350 | QColor background1 = ColorUtils::fromColorT(prefs.gui_inactive_bg);
351 | QColor background2 = QColor::fromRgb(ColorUtils::alphaBlend(foreground, background1, COLOR_STYLE_ALPHA0.25));
352 |
353 | inactive_style = gradient_style_format.arg(
354 | c_inactive,
355 | foreground.name(),
356 | background1.name(),
357 | background2.name());
358 | }
359 |
360 | // Set the style sheet
361 | set_style_sheet_ = true;
362 | if(prefs.gui_packet_list_hover_style) {
363 | setStyleSheet(active_style + inactive_style + hover_style);
364 | } else {
365 | setStyleSheet(active_style + inactive_style);
366 | }
367 | set_style_sheet_ = false;
368 | #if \
369 | ( \
370 | (QT_VERSION((6<<16)|(4<<8)|(2)) >= QT_VERSION_CHECK(6, 5, 4)((6<<16)|(5<<8)|(4)) && QT_VERSION((6<<16)|(4<<8)|(2)) < QT_VERSION_CHECK(6, 6, 0)((6<<16)|(6<<8)|(0))) \
371 | || (QT_VERSION((6<<16)|(4<<8)|(2)) >= QT_VERSION_CHECK(6, 6, 1)((6<<16)|(6<<8)|(1))) \
372 | )
373 | // https://bugreports.qt.io/browse/QTBUG-122109
374 | // Affects Qt 6.5.4 and later, 6.6.1 and later.
375 | // When setting the style sheet, all visible sections are set
376 | // to the new minimum DefaultSectionSize (even if it hasn't
377 | // changed.) So make sure the new widths aren't saved to recent
378 | // and then restore from recent.
379 | applyRecentColumnWidths();
380 | setColumnVisibility();
381 | #endif
382 | }
383 |
384 | QString PacketList::joinSummaryRow(QStringList col_parts, int row, SummaryCopyType type)
385 | {
386 | QString copy_text;
387 | switch (type) {
388 | case CopyAsCSV:
389 | copy_text = "\"";
390 | copy_text += col_parts.join("\",\"");
391 | copy_text += "\"";
392 | break;
393 | case CopyAsYAML:
394 | copy_text = "----\n";
395 | copy_text += QStringLiteral("# Packet %1 from %2\n")(QString(QtPrivate::qMakeStringPrivate(u"" "# Packet %1 from %2\n" ))).arg(row).arg(cap_file_->filename);
396 | copy_text += "- ";
397 | copy_text += col_parts.join("\n- ");
398 | copy_text += "\n";
399 | break;
400 | case CopyAsText:
401 | default:
402 | copy_text = col_parts.join("\t");
403 | }
404 |
405 | return copy_text;
406 | }
407 |
408 | void PacketList::drawRow (QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
409 | {
410 | QTreeView::drawRow(painter, option, index);
411 |
412 | if (prefs.gui_packet_list_separator) {
413 | QRect rect = visualRect(index);
414 |
415 | painter->setPen(QColor(Qt::white));
416 | painter->drawLine(0, rect.y() + rect.height() - 1, width(), rect.y() + rect.height() - 1);
417 | }
418 | }
419 |
420 | void PacketList::setProtoTree (ProtoTree *proto_tree) {
421 | proto_tree_ = proto_tree;
422 |
423 | connect(proto_tree_, &ProtoTree::goToPacket, this, [=](int packet) { goToPacket(packet); });
424 | connect(proto_tree_, &ProtoTree::relatedFrame,
425 | &related_packet_delegate_, &RelatedPacketDelegate::addRelatedFrame);
426 | }
427 |
428 | bool PacketList::uniqueSelectActive()
429 | {
430 | return selectionModel()->selectedRows(0).count() == 1 ? true : false;
431 | }
432 |
433 | bool PacketList::multiSelectActive()
434 | {
435 | return selectionModel()->selectedRows(0).count() > 1 ? true : false;
436 | }
437 |
438 | QList<int> PacketList::selectedRows(bool useFrameNum)
439 | {
440 | QList<int> rows;
441 | if (selectionModel() && selectionModel()->hasSelection())
442 | {
443 | foreach (QModelIndex idx, selectionModel()->selectedRows(0))for (auto _container_443 = QtPrivate::qMakeForeachContainer(selectionModel ()->selectedRows(0)); _container_443.i != _container_443.e ; ++_container_443.i) if (QModelIndex idx = *_container_443.i ; false) {} else
444 | {
445 | if (idx.isValid())
446 | {
447 | if (! useFrameNum)
448 | rows << idx.row();
449 | else if (useFrameNum)
450 | {
451 | frame_data * frame = getFDataForRow(idx.row());
452 | if (frame)
453 | rows << frame->num;
454 | }
455 | }
456 | }
457 | }
458 | else if (currentIndex().isValid())
459 | {
460 | //
461 | // XXX - will we ever have a current index but not a selection
462 | // model?
463 | //
464 | if (! useFrameNum)
465 | rows << currentIndex().row();
466 | else
467 | {
468 | frame_data *frame = getFDataForRow(currentIndex().row());
469 | if (frame)
470 | rows << frame->num;
471 | }
472 | }
473 |
474 | return rows;
475 | }
476 |
477 | void PacketList::selectionChanged (const QItemSelection & selected, const QItemSelection & deselected)
478 | {
479 | QTreeView::selectionChanged(selected, deselected);
480 |
481 | if (!cap_file_) return;
482 |
483 | int row = -1;
484 | static bool multiSelect = false;
485 |
486 | if (selectionModel())
487 | {
488 | QModelIndexList selRows = selectionModel()->selectedRows(0);
489 | if (selRows.count() > 1)
490 | {
491 | QList<int> rows;
492 | foreach (QModelIndex idx, selRows)for (auto _container_492 = QtPrivate::qMakeForeachContainer(selRows ); _container_492.i != _container_492.e; ++_container_492.i) if (QModelIndex idx = *_container_492.i; false) {} else
493 | {
494 | if (idx.isValid())
495 | rows << idx.row();
496 | }
497 |
498 | emit framesSelected(rows);
499 | emit fieldSelected(0);
500 | cf_unselect_packet(cap_file_);
501 |
502 | /* We have to repaint the content while changing state, as some delegates react to multi-select */
503 | if (! multiSelect)
504 | {
505 | related_packet_delegate_.clear();
506 | viewport()->update();
507 | }
508 |
509 | multiSelect = true;
510 |
511 | return;
512 | }
513 | else if (selRows.count() > 0 && selRows.at(0).isValid())
514 | {
515 | multiSelect = false;
516 | row = selRows.at(0).row();
517 | }
518 |
519 | /* Handling empty selection */
520 | if (selRows.count() <= 0)
521 | {
522 | /* Nothing selected, but multiSelect is still active */
523 | if (multiSelect)
524 | {
525 | multiSelect = false;
526 | if (currentIndex().isValid())
527 | {
528 | selectionModel()->select(currentIndex(), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
529 | return;
530 | }
531 | }
532 | /* Nothing selected, so in WS <= 3.0 nothing was indicated as well */
533 | else if (currentIndex().isValid())
534 | {
535 | setCurrentIndex(QModelIndex());
536 | }
537 | }
538 | }
539 |
540 | if (row < 0 || !packet_list_model_)
541 | cf_unselect_packet(cap_file_);
542 | else {
543 | frame_data * fdata = packet_list_model_->getRowFdata(row);
544 | cf_select_packet(cap_file_, fdata);
545 | }
546 |
547 | if (!in_history_ && cap_file_->current_frame) {
548 | cur_history_++;
549 | selection_history_.resize(cur_history_);
550 | selection_history_.append(cap_file_->current_frame->num);
551 | }
552 |
553 | related_packet_delegate_.clear();
554 |
555 | // The previous dissection state has been invalidated by cf_select_packet
556 | // above, receivers must clear the previous state and apply the updated one.
557 | emit framesSelected(QList<int>() << row);
558 |
559 | if (!cap_file_->edt) {
560 | viewport()->update();
561 | emit fieldSelected(0);
562 | return;
563 | }
564 |
565 | if (cap_file_->edt->tree) {
566 | packet_info *pi = &cap_file_->edt->pi;
567 | related_packet_delegate_.setCurrentFrame(pi->num);
568 | conversation_t *conv = find_conversation_pinfo_ro(pi, 0);
569 | if (conv) {
570 | related_packet_delegate_.setConversation(conv);
571 | }
572 | viewport()->update();
573 | }
574 |
575 | if (cap_file_->search_in_progress) {
576 | field_info *fi = NULL__null;
577 |
578 | if (cap_file_->string && cap_file_->decode_data) {
579 | // The tree where the target string matched one of the labels was discarded in
580 | // match_protocol_tree() so we have to search again in the latest tree.
581 | fi = cf_find_string_protocol_tree(cap_file_, cap_file_->edt->tree);
582 | } else if (cap_file_->search_len != 0) {
583 | // Find the finfo that corresponds to our byte.
584 | // The match can span multiple fields (and a single byte can
585 | // match more than one field.) Our behavior is to find the last
586 | // field in the tree (so hopefully spanning fewer bytes) that
587 | // matches the last byte in the search match.
588 | // (regex search can find a zero length match not at the
589 | // start of the frame if lookbehind is used, but
590 | // proto_find_field_from_offset doesn't match such a field
591 | // and it's not clear which field we would want to match.)
592 | fi = proto_find_field_from_offset(cap_file_->edt->tree, cap_file_->search_pos + cap_file_->search_len - 1,
593 | cap_file_->edt->tvb);
594 | }
595 |
596 | if (fi) {
597 | FieldInformation finfo(fi, this);
598 | emit fieldSelected(&finfo);
599 | } else {
600 | emit fieldSelected(0);
601 | }
602 | } else if (proto_tree_) {
603 | proto_tree_->restoreSelectedField();
604 | }
605 | }
606 |
607 | void PacketList::contextMenuEvent(QContextMenuEvent *event)
608 | {
609 | const char *module_name = NULL__null;
610 |
611 | if (finfo_array)
612 | {
613 | g_ptr_array_free(finfo_array, true);
614 | finfo_array = NULL__null;
615 | }
616 |
617 | QModelIndex ctxIndex = indexAt(event->pos());
618 |
619 | if (selectionModel() && selectionModel()->selectedRows(0).count() > 1)
620 | selectionModel()->select(ctxIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
621 |
622 | // frameData will be owned by one of the submenus, see below.
623 | FrameInformation * frameData =
624 | new FrameInformation(new CaptureFile(this, cap_file_), packet_list_model_->getRowFdata(ctxIndex.row()));
625 |
626 | QMenu * ctx_menu = new QMenu(this);
627 | ctx_menu->setAttribute(Qt::WA_DeleteOnClose);
628 | // XXX We might want to reimplement setParent() and fill in the context
629 | // menu there.
630 | ctx_menu->addAction(window()->findChild<QAction *>("actionEditMarkSelected"));
631 | ctx_menu->addAction(window()->findChild<QAction *>("actionEditIgnoreSelected"));
632 | ctx_menu->addAction(window()->findChild<QAction *>("actionEditSetTimeReference"));
633 | ctx_menu->addAction(window()->findChild<QAction *>("actionEditTimeShift"));
634 | ctx_menu->addMenu(window()->findChild<QMenu *>("menuPacketComment"));
635 |
636 | ctx_menu->addSeparator();
637 |
638 | // Code for custom context menus from Lua's register_packet_menu()
639 | MainWindow * mainWindow = mainApp->mainWindow();
640 | // N.B., will only call for a single frame selection,
641 | if (cap_file_ && cap_file_->edt && cap_file_->edt->tree) {
642 | finfo_array = proto_all_finfos(cap_file_->edt->tree);
643 | if (mainWindow) {
644 | bool insertedPacketMenu = mainWindow->addPacketMenus(ctx_menu, finfo_array);
645 | if (insertedPacketMenu) {
646 | ctx_menu->addSeparator();
647 | }
648 | }
649 | }
650 |
651 | ctx_menu->addAction(window()->findChild<QAction *>("actionViewEditResolvedName"));
652 | ctx_menu->addSeparator();
653 |
654 | QString selectedfilter = getFilterFromRowAndColumn(currentIndex());
655 |
656 | if (! hasFocus() && cap_file_ && cap_file_->finfo_selected) {
657 | char *tmp_field = proto_construct_match_selected_string(cap_file_->finfo_selected, cap_file_->edt);
658 | selectedfilter = QString(tmp_field);
659 | wmem_free(NULL__null, tmp_field);
660 | }
661 |
662 | bool have_filter_expr = !selectedfilter.isEmpty();
663 | ctx_menu->addMenu(FilterAction::createFilterMenu(FilterAction::ActionApply, selectedfilter, have_filter_expr, ctx_menu));
664 | ctx_menu->addMenu(FilterAction::createFilterMenu(FilterAction::ActionPrepare, selectedfilter, have_filter_expr, ctx_menu));
665 |
666 | const char *conv_menu_name = "menuConversationFilter";
667 | QMenu * main_menu_item = window()->findChild<QMenu *>(conv_menu_name);
668 | conv_menu_.setTitle(main_menu_item->title());
669 | conv_menu_.setObjectName(conv_menu_name);
670 | ctx_menu->addMenu(&conv_menu_);
671 |
672 | const char *colorize_menu_name = "menuColorizeConversation";
673 | main_menu_item = window()->findChild<QMenu *>(colorize_menu_name);
674 | colorize_menu_.setTitle(main_menu_item->title());
675 | colorize_menu_.setObjectName(colorize_menu_name);
676 | ctx_menu->addMenu(&colorize_menu_);
677 |
678 | QMenu * submenu;
679 | main_menu_item = window()->findChild<QMenu *>("menuSCTP");
680 | if (main_menu_item) {
681 | submenu = new QMenu(main_menu_item->title(), ctx_menu);
682 | ctx_menu->addMenu(submenu);
683 | submenu->addAction(window()->findChild<QAction *>("actionSCTPAnalyseThisAssociation"));
684 | submenu->addAction(window()->findChild<QAction *>("actionSCTPShowAllAssociations"));
685 | submenu->addAction(window()->findChild<QAction *>("actionSCTPFilterThisAssociation"));
686 | }
687 |
688 | main_menu_item = window()->findChild<QMenu *>("menuFollow");
689 | if (main_menu_item) {
690 | submenu = new QMenu(main_menu_item->title(), ctx_menu);
691 | ctx_menu->addMenu(submenu);
692 | foreach (FollowStreamAction *follow_action, main_menu_item->findChildren<FollowStreamAction *>())for (auto _container_692 = QtPrivate::qMakeForeachContainer(main_menu_item ->findChildren<FollowStreamAction *>()); _container_692 .i != _container_692.e; ++_container_692.i) if (FollowStreamAction *follow_action = *_container_692.i; false) {} else {
693 | /* XXX: We could, like the prefs above, walk the protocols/layers
694 | * and add the follow actions in the order they appear in the packet.
695 | */
696 | if (follow_action->isEnabled()) {
697 | submenu->addAction(follow_action);
698 | }
699 | }
700 | }
701 |
702 | ctx_menu->addSeparator();
703 |
704 | main_menu_item = window()->findChild<QMenu *>("menuEditCopy");
705 | submenu = new QMenu(main_menu_item->title(), ctx_menu);
706 | submenu->setToolTipsVisible(true);
707 | ctx_menu->addMenu(submenu);
708 |
709 | QAction * action = submenu->addAction(tr("Summary as Text"));
710 | action->setData(CopyAsText);
711 | connect(action, &QAction::triggered, this, &PacketList::copySummary);
712 | action = submenu->addAction(tr("…as CSV"));
713 | action->setData(CopyAsCSV);
714 | connect(action, &QAction::triggered, this, &PacketList::copySummary);
715 | action = submenu->addAction(tr("…as YAML"));
716 | action->setData(CopyAsYAML);
717 | connect(action, &QAction::triggered, this, &PacketList::copySummary);
718 | action = submenu->addAction(tr("…as HTML"));
719 | action->setData(CopyAsHTML);
720 | connect(action, &QAction::triggered, this, &PacketList::copySummary);
721 | submenu->addSeparator();
722 |
723 | submenu->addAction(window()->findChild<QAction *>("actionEditCopyAsFilter"));
724 | submenu->addSeparator();
725 |
726 | QActionGroup * copyEntries = DataPrinter::copyActions(this, frameData);
727 | submenu->addActions(copyEntries->actions());
728 | copyEntries->setParent(submenu);
729 | frameData->setParent(submenu);
730 |
731 | if (application_flavor_is_wireshark()) {
732 | /* i.e., Wireshark only */
733 | ctx_menu->addSeparator();
734 | QMenu *proto_prefs_menus = new QMenu(ProtocolPreferencesMenu::tr("Protocol Preferences"), ctx_menu);
735 |
736 | if (cap_file_ && cap_file_->edt && cap_file_->edt->tree) {
737 | QList<QString> added_proto_prefs;
738 | // N.B. finfo_array will be assigned above
739 | for (unsigned i = 0; i < finfo_array->len; i++) {
740 | field_info *fi = (field_info *)g_ptr_array_index (finfo_array, i)((finfo_array)->pdata)[i];
741 | const header_field_info *hfinfo = fi->hfinfo;
742 |
743 | if (prefs_is_registered_protocol(hfinfo->abbrev)) {
744 | if (hfinfo->parent == -1) {
745 | module_name = hfinfo->abbrev;
746 | } else {
747 | module_name = proto_registrar_get_abbrev(hfinfo->parent);
748 | }
749 |
750 | if (added_proto_prefs.contains(module_name)) {
751 | continue;
752 | }
753 |
754 | ProtocolPreferencesMenu *proto_prefs_menu = new ProtocolPreferencesMenu(hfinfo->name, module_name, proto_prefs_menus);
755 |
756 | connect(proto_prefs_menu, &ProtocolPreferencesMenu::showProtocolPreferences,
757 | this, &PacketList::showProtocolPreferences);
758 | connect(proto_prefs_menu, SIGNAL(editProtocolPreference(pref_t*,module_t*))qFlagLocation("2" "editProtocolPreference(pref_t*,module_t*)" "\0" "ui/qt/packet_list.cpp" ":" "758"),
759 | this, SIGNAL(editProtocolPreference(pref_t*,module_t*))qFlagLocation("2" "editProtocolPreference(pref_t*,module_t*)" "\0" "ui/qt/packet_list.cpp" ":" "759"));
760 |
761 | proto_prefs_menus->addMenu(proto_prefs_menu);
762 | added_proto_prefs << module_name;
763 | }
764 | }
765 | }
766 | ctx_menu->addMenu(proto_prefs_menus);
767 | action = ctx_menu->addAction(tr("Decode As…"));
768 | action->setProperty("create_new", QVariant(true));
769 | connect(action, &QAction::triggered, this, &PacketList::ctxDecodeAsDialog);
770 | // "Print" not ported intentionally
771 | action = window()->findChild<QAction *>("actionViewShowPacketInNewWindow");
772 | ctx_menu->addAction(action);
773 | }
774 |
775 | // Set menu sensitivity for the current column and set action data.
776 | if (frameData)
777 | emit framesSelected(QList<int>() << frameData->frameNum());
778 | else
779 | emit framesSelected(QList<int>());
780 |
781 | ctx_menu->popup(event->globalPos());
782 | }
783 |
784 | void PacketList::ctxDecodeAsDialog()
785 | {
786 | QAction *da_action = qobject_cast<QAction*>(sender());
787 | if (! da_action)
788 | return;
789 | bool create_new = da_action->property("create_new").toBool();
790 |
791 | DecodeAsDialog *da_dialog = new DecodeAsDialog(this, cap_file_, create_new);
792 | connect(da_dialog, &DecodeAsDialog::destroyed, mainApp, &MainApplication::flushAppSignals);
793 | da_dialog->setWindowModality(Qt::ApplicationModal);
794 | da_dialog->setAttribute(Qt::WA_DeleteOnClose);
795 | da_dialog->show();
796 | }
797 |
798 | void PacketList::timerEvent(QTimerEvent *event)
799 | {
800 | if (event->timerId() == overlay_timer_id_) {
801 | if (!capture_in_progress_) {
802 | if (create_near_overlay_) drawNearOverlay();
803 | if (create_far_overlay_) drawFarOverlay();
804 | }
805 | } else {
806 | QTreeView::timerEvent(event);
807 | }
808 | }
809 |
810 | void PacketList::paintEvent(QPaintEvent *event)
811 | {
812 | // XXX This is overkill, but there are quite a few events that
813 | // require a new overlay, e.g. page up/down, scrolling, column
814 | // resizing, etc.
815 | create_near_overlay_ = true;
816 | QTreeView::paintEvent(event);
817 | }
818 |
819 | void PacketList::mousePressEvent(QMouseEvent *event)
820 | {
821 | QTreeView::mousePressEvent(event);
822 |
823 | QModelIndex curIndex = indexAt(event->pos());
824 | mouse_pressed_at_ = curIndex;
825 |
826 | bool midButton = (event->buttons() & Qt::MiddleButton) == Qt::MiddleButton;
827 | if (midButton && cap_file_ && packet_list_model_)
828 | {
829 | packet_list_model_->toggleFrameMark(QModelIndexList() << curIndex);
830 |
831 | // Make sure the packet list's frame.marked related field text is updated.
832 | redrawVisiblePackets();
833 |
834 | create_far_overlay_ = true;
835 | packets_bar_update();
836 | }
837 | }
838 |
839 | void PacketList::mouseReleaseEvent(QMouseEvent *event) {
840 | QTreeView::mouseReleaseEvent(event);
841 |
842 | mouse_pressed_at_ = QModelIndex();
843 | }
844 |
845 | void PacketList::mouseMoveEvent (QMouseEvent *event)
846 | {
847 | QModelIndex curIndex = indexAt(event->pos());
848 | if (event->buttons() & Qt::LeftButton && curIndex.isValid() && curIndex == mouse_pressed_at_)
1 | Assuming the condition is true | →
2 | ← | Taking true branch | →
849 | {
850 | ctx_column_ = curIndex.column();
851 | QMimeData * mimeData = new QMimeData();
852 | DragLabel * drag_label = nullptr;
853 |
854 | QString filter = getFilterFromRowAndColumn(curIndex);
855 | QList<int> rows = selectedRows();
856 | if (rows.count() > 1)
3 | ← | Assuming the condition is false | →
4 | ← | Taking false branch | →
857 | {
858 | QStringList entries;
859 | foreach (int row, rows)for (auto _container_859 = QtPrivate::qMakeForeachContainer(rows ); _container_859.i != _container_859.e; ++_container_859.i) if (int row = *_container_859.i; false) {} else
860 | {
861 | QModelIndex idx = model()->index(row, 0);
862 | if (! idx.isValid())
863 | continue;
864 |
865 | QString entry = createSummaryText(idx, CopyAsText);
866 | entries << entry;
867 | }
868 |
869 | if (entries.count() > 0)
870 | mimeData->setText(entries.join("\n"));
871 | }
872 | else if (! filter.isEmpty())
5 | ← | Assuming the condition is true | →
6 | ← | Taking true branch | →
873 | {
874 | QString abbrev;
875 | QString name = model()->headerData(curIndex.column(), header()->orientation()).toString();
876 |
877 | if (! filter.isEmpty())
7 | ← | Assuming the condition is false | →
8 | ← | Taking false branch | →
878 | {
879 | abbrev = filter.left(filter.indexOf(' '));
880 | }
881 | else
882 | {
883 | filter = model()->data(curIndex).toString().toLower();
884 | abbrev = filter;
885 | }
886 |
887 | mimeData->setText(filter);
888 |
889 | QJsonObject filterData;
890 | filterData["filter"] = filter;
891 | filterData["name"] = abbrev;
892 | filterData["description"] = name;
893 |
894 | mimeData->setData(WiresharkMimeData::DisplayFilterMimeType, QJsonDocument(filterData).toJson());
895 | drag_label = new DragLabel(QStringLiteral("%1\n%2")(QString(QtPrivate::qMakeStringPrivate(u"" "%1\n%2"))).arg(name, abbrev), this);
9 | ← | Memory is allocated | →
896 | }
897 | else
898 | {
899 | QString text = model()->data(curIndex).toString();
900 | if (! text.isEmpty())
901 | mimeData->setText(text);
902 | }
903 |
904 | if (mimeData->hasText() || mimeData->hasFormat(WiresharkMimeData::DisplayFilterMimeType))
10 | ← | Assuming the condition is false | →
11 | ← | Assuming the condition is false | →
12 | ← | Taking false branch | →
905 | {
906 | QDrag * drag = new QDrag(this);
907 | drag->setMimeData(mimeData);
908 | if (drag_label)
909 | {
910 | qreal dpr = window()->windowHandle()->devicePixelRatio();
911 | QPixmap pixmap= QPixmap(drag_label->size() * dpr);
912 | pixmap.setDevicePixelRatio(dpr);
913 | drag_label->render(&pixmap);
914 | drag->setPixmap(pixmap);
915 | delete drag_label;
916 | }
917 |
918 | drag->exec(Qt::CopyAction);
919 | }
920 | else
921 | {
922 | delete mimeData;
13 | ← | Potential leak of memory pointed to by 'drag_label'
923 | }
924 | }
925 | }
926 |
927 | void PacketList::keyPressEvent(QKeyEvent *event)
928 | {
929 | QTreeView::keyPressEvent(event);
930 |
931 | if (event->matches(QKeySequence::Copy))
932 | {
933 | QStringList content, htmlContent;
934 | if (model() && selectionModel() && selectionModel()->hasSelection())
935 | {
936 | QList<int> rows;
937 | QModelIndexList selRows = selectionModel()->selectedRows(0);
938 | foreach(QModelIndex row, selRows)for (auto _container_938 = QtPrivate::qMakeForeachContainer(selRows ); _container_938.i != _container_938.e; ++_container_938.i) if (QModelIndex row = *_container_938.i; false) {} else
939 | rows.append(row.row());
940 |
941 | QStringList hdr_parts;
942 | QList<int> align_parts, size_parts;
943 |
944 | switch (prefs.gui_packet_list_copy_format_options_for_keyboard_shortcut) {
945 | case COPY_FORMAT_TEXT:
946 | case COPY_FORMAT_HTML:
947 | if (prefs.gui_packet_list_copy_text_with_aligned_columns) {
948 | hdr_parts = createHeaderPartsForAligned();
949 | align_parts = createAlignmentPartsForAligned();
950 | size_parts = createSizePartsForAligned(false, hdr_parts, rows);
951 | }
952 | if (prefs.gui_packet_list_copy_format_options_for_keyboard_shortcut == COPY_FORMAT_HTML) {
953 | htmlContent << createDefaultStyleForHtml();
954 | htmlContent << createOpeningTagForHtml();
955 | }
956 | break;
957 | case COPY_FORMAT_CSV:
958 | case COPY_FORMAT_YAML:
959 | break;
960 | }
961 |
962 | QList<QStringList> entries;
963 | foreach(int row, rows)for (auto _container_963 = QtPrivate::qMakeForeachContainer(rows ); _container_963.i != _container_963.e; ++_container_963.i) if (int row = *_container_963.i; false) {} else
964 | {
965 | QModelIndex idx = model()->index(row, 0);
966 | if (! idx.isValid())
967 | continue;
968 |
969 | switch (prefs.gui_packet_list_copy_format_options_for_keyboard_shortcut) {
970 | case COPY_FORMAT_TEXT:
971 | case COPY_FORMAT_HTML:
972 | if (prefs.gui_packet_list_copy_text_with_aligned_columns)
973 | content << createSummaryForAligned(idx, align_parts, size_parts);
974 | else
975 | content << createSummaryText(idx, CopyAsText);
976 | if (prefs.gui_packet_list_copy_format_options_for_keyboard_shortcut == COPY_FORMAT_HTML)
977 | htmlContent << createSummaryForHtml(idx);
978 | break;
979 | case COPY_FORMAT_CSV:
980 | content << createSummaryText(idx, CopyAsCSV);
981 | break;
982 | case COPY_FORMAT_YAML:
983 | content << createSummaryText(idx, CopyAsYAML);
984 | break;
985 | }
986 | }
987 | }
988 |
989 | if (prefs.gui_packet_list_copy_format_options_for_keyboard_shortcut == COPY_FORMAT_HTML) {
990 | // htmlContent will never be empty as they will always have style and table tags
991 | QMimeData *mimeData = new QMimeData;
992 | htmlContent << createClosingTagForHtml();
993 | mimeData->setHtml(htmlContent.join('\n'));
994 | mimeData->setText(content.join('\n').append("\n"));
995 | mainApp->clipboard()->setMimeData(mimeData, QClipboard::Clipboard);
996 | }
997 | else {
998 | if (content.count() > 0) {
999 | QString copy_text;
1000 | if (prefs.gui_packet_list_copy_format_options_for_keyboard_shortcut == COPY_FORMAT_YAML) {
1001 | copy_text = content.join("");
1002 | }
1003 | else {
1004 | copy_text = content.join("\n");
1005 | copy_text += "\n";
1006 | }
1007 | mainApp->clipboard()->setText(copy_text);
1008 | }
1009 | }
1010 | }
1011 | }
1012 |
1013 | void PacketList::resizeEvent(QResizeEvent *event)
1014 | {
1015 | create_near_overlay_ = true;
1016 | create_far_overlay_ = true;
1017 | QTreeView::resizeEvent(event);
1018 | }
1019 |
1020 | void PacketList::setColumnVisibility()
1021 | {
1022 | set_column_visibility_ = true;
1023 | for (int i = 0; i < prefs.num_cols; i++) {
1024 | setColumnHidden(i, get_column_visible(i) ? false : true);
1025 | }
1026 | setColumnDelegate();
1027 | set_column_visibility_ = false;
1028 | }
1029 |
1030 | void PacketList::setColumnDelegate()
1031 | {
1032 | for (int i = 0; i < prefs.num_cols; i++) {
1033 | setItemDelegateForColumn(i, nullptr); // Reset all delegates
1034 | }
1035 |
1036 | if (prefs.gui_packet_list_show_related) {
1037 | for (int i = 0; i < prefs.num_cols; i++) {
1038 | if (get_column_visible(i)) {
1039 | setItemDelegateForColumn(i, &related_packet_delegate_);
1040 | break; // Set the delegate only on the first visible column
1041 | }
1042 | }
1043 | }
1044 | }
1045 |
1046 | void PacketList::setRecentColumnWidth(int col)
1047 | {
1048 | int col_width = recent_get_column_width(col);
1049 |
1050 | if (col_width < 1) {
1051 | int fmt = get_column_format(col);
1052 | const char *long_str = get_column_width_string(fmt, col);
1053 |
1054 | QFontMetrics fm = QFontMetrics(mainApp->monospaceFont());
1055 | if (long_str) {
1056 | col_width = fm.horizontalAdvance(long_str);
1057 | } else {
1058 | col_width = fm.horizontalAdvance(MIN_COL_WIDTH_STR"MMMMMM");
1059 | }
1060 | // Custom delegate padding
1061 | if (itemDelegateForColumn(col)) {
1062 | QStyleOptionViewItem option;
1063 | #if QT_VERSION((6<<16)|(4<<8)|(2)) >= QT_VERSION_CHECK(6, 0, 0)((6<<16)|(0<<8)|(0))
1064 | initViewItemOption(&option);
1065 | #else
1066 | option = viewOptions();
1067 | #endif
1068 | // This is adding "how much width hinted for an empty index, plus
1069 | // the decoration, plus any padding between the decoration and
1070 | // normal display?" Many styles however have a non zero hint for
1071 | // an empty index, so this isn't quite right. What we really want
1072 | // is a size hint for an index whose data is the string above, and
1073 | // to just use that for the width.
1074 | col_width += itemDelegateForColumn(col)->sizeHint(option, QModelIndex()).width();
1075 | }
1076 | }
1077 |
1078 | setColumnWidth(col, col_width);
1079 | }
1080 |
1081 | void PacketList::drawCurrentPacket()
1082 | {
1083 | // XXX - Update for multi-select? If more than one packet is Selected,
1084 | // this changes it so that only the Current packet is Selected.
1085 | QModelIndex current_index = currentIndex();
1086 | if (selectionModel() && current_index.isValid()) {
1087 | selectionModel()->clearSelection();
1088 | selectionModel()->setCurrentIndex(current_index, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
1089 | }
1090 | }
1091 |
1092 | // Redraw the packet list and detail. Re-selects the current packet (causes
1093 | // the UI to scroll to that packet).
1094 | // Called from many places.
1095 | void PacketList::redrawVisiblePackets() {
1096 | redrawVisiblePacketsDontSelectCurrent();
1097 | drawCurrentPacket();
1098 | }
1099 |
1100 | // Redraw the packet list and detail.
1101 | // Does not scroll back to the selected packet.
1102 | void PacketList::redrawVisiblePacketsDontSelectCurrent() {
1103 | packet_list_model_->invalidateAllColumnStrings();
1104 | }
1105 |
1106 | void PacketList::resetColumns()
1107 | {
1108 | packet_list_model_->resetColumns();
1109 | }
1110 |
1111 | // Return true if we have a visible packet further along in the history.
1112 | bool PacketList::haveNextHistory(bool update_cur)
1113 | {
1114 | if (selection_history_.size() < 1 || cur_history_ >= selection_history_.size() - 1) {
1115 | return false;
1116 | }
1117 |
1118 | for (int i = cur_history_ + 1; i < selection_history_.size(); i++) {
1119 | if (packet_list_model_->packetNumberToRow(selection_history_.at(i)) >= 0) {
1120 | if (update_cur) {
1121 | cur_history_ = i;
1122 | }
1123 | return true;
1124 | }
1125 | }
1126 | return false;
1127 | }
1128 |
1129 | // Return true if we have a visible packet back in the history.
1130 | bool PacketList::havePreviousHistory(bool update_cur)
1131 | {
1132 | if (selection_history_.size() < 1 || cur_history_ < 1) {
1133 | return false;
1134 | }
1135 |
1136 | for (int i = cur_history_ - 1; i >= 0; i--) {
1137 | if (packet_list_model_->packetNumberToRow(selection_history_.at(i)) >= 0) {
1138 | if (update_cur) {
1139 | cur_history_ = i;
1140 | }
1141 | return true;
1142 | }
1143 | }
1144 | return false;
1145 | }
1146 |
1147 | void PacketList::setProfileSwitcher(ProfileSwitcher *profile_switcher)
1148 | {
1149 | profile_switcher_ = profile_switcher;
1150 | if (profile_switcher) {
1151 | connect(packet_list_model_, &PacketListModel::packetAppended, profile_switcher_, &ProfileSwitcher::checkPacket);
1152 | }
1153 | }
1154 |
1155 | frame_data *PacketList::getFDataForRow(int row) const
1156 | {
1157 | return packet_list_model_->getRowFdata(row);
1158 | }
1159 |
1160 | // prefs.col_list has changed.
1161 | void PacketList::columnsChanged()
1162 | {
1163 | columns_changed_ = true;
1164 | column_register_fields();
1165 | mainApp->emitAppSignal(MainApplication::FieldsChanged);
1166 | if (!cap_file_) {
1167 | // Keep columns_changed_ = true until we load a capture file.
1168 | return;
1169 | }
1170 |
1171 | prefs.num_cols = g_list_length(prefs.col_list);
1172 | col_cleanup(&cap_file_->cinfo);
1173 | build_column_format_array(&cap_file_->cinfo, prefs.num_cols, false);
1174 | create_far_overlay_ = true;
1175 | resetColumns();
1176 | applyRecentColumnWidths();
1177 | setColumnVisibility();
1178 | columns_changed_ = false;
1179 | }
1180 |
1181 | // Fields have changed, update custom columns
1182 | void PacketList::fieldsChanged(capture_file *cf)
1183 | {
1184 | // hfids used by custom columns or by the _ws.col fields may have changed,
1185 | // so recreate the columns. We shouldn't need to if prefs.col_list is NULL,
1186 | // since that doesn't register and deregister _ws.col fields.
1187 | // If the column pref changes to or from NULL, that triggers columnsChanged
1188 | // above, so we don't need to do it twice.
1189 | //
1190 | // XXX - If we knew exactly which fields changed, we could rebuild the
1191 | // columns only if a field used by the columns changed.
1192 | if (prefs.col_list) {
1193 | prefs.num_cols = g_list_length(prefs.col_list);
1194 | col_cleanup(&cf->cinfo);
1195 | build_column_format_array(&cf->cinfo, prefs.num_cols, false);
1196 | resetColumns();
1197 | }
1198 | }
1199 |
1200 | // Column widths should
1201 | // - Load from recent when we load a new profile (including at starting up).
1202 | // - Reapply when changing columns.
1203 | // - Persist across freezes and thaws.
1204 | // - Persist across file closing and opening.
1205 | // - Save to recent when we save our profile (including shutting down).
1206 | // - Not be affected by the behavior of stretchLastSection. (XXX: We
1207 | // still save the stretched value to recent, sectionResized doesn't
1208 | // distinguish between a resize from being stretched and a manual change.)
1209 | void PacketList::applyRecentColumnWidths()
1210 | {
1211 | // Either we've just started up or a profile has changed. Read
1212 | // the recent settings, apply them, and save the header state.
1213 |
1214 | for (int col = 0; col < prefs.num_cols; col++) {
1215 | // The column must be shown before setting column width.
1216 | // Visibility will be updated in setColumnVisibility().
1217 | setColumnHidden(col, false);
1218 | setRecentColumnWidth(col);
1219 | }
1220 |
1221 | column_state_ = header()->saveState();
1222 | }
1223 |
1224 | void PacketList::preferencesChanged()
1225 | {
1226 | // Intelligent scroll bar (minimap)
1227 | if (prefs.gui_packet_list_show_minimap) {
1228 | if (overlay_timer_id_ == 0) {
1229 | overlay_timer_id_ = startTimer(overlay_update_interval_);
1230 | }
1231 | } else {
1232 | if (overlay_timer_id_ != 0) {
1233 | killTimer(overlay_timer_id_);
1234 | overlay_timer_id_ = 0;
1235 | }
1236 | }
1237 |
1238 | // Elide mode.
1239 | // This sets the mode for the entire view. If we want to make this setting
1240 | // per-column we'll either have to generalize RelatedPacketDelegate so that
1241 | // we can set it for entire rows or create another delegate.
1242 | Qt::TextElideMode elide_mode = Qt::ElideRight;
1243 | switch (prefs.gui_packet_list_elide_mode) {
1244 | case ELIDE_LEFT:
1245 | elide_mode = Qt::ElideLeft;
1246 | break;
1247 | case ELIDE_MIDDLE:
1248 | elide_mode = Qt::ElideMiddle;
1249 | break;
1250 | case ELIDE_NONE:
1251 | elide_mode = Qt::ElideNone;
1252 | break;
1253 | default:
1254 | break;
1255 | }
1256 | setTextElideMode(elide_mode);
1257 | }
1258 |
1259 | void PacketList::freezePacketList(bool changing_profile)
1260 | {
1261 | changing_profile_ = changing_profile;
1262 | freeze(true);
1263 | }
1264 |
1265 | void PacketList::recolorPackets()
1266 | {
1267 | packet_list_model_->resetColorized();
1268 | redrawVisiblePackets();
1269 | }
1270 |
1271 | // Enable autoscroll.
1272 | void PacketList::setVerticalAutoScroll(bool enabled)
1273 | {
1274 | tail_at_end_ = enabled;
1275 | if (enabled && capture_in_progress_) {
1276 | scrollToBottom();
1277 | }
1278 | }
1279 |
1280 | // Called when we finish reading, reloading, rescanning, and retapping
1281 | // packets.
1282 | void PacketList::captureFileReadFinished()
1283 | {
1284 | packet_list_model_->flushVisibleRows();
1285 | packet_list_model_->dissectIdle(true);
1286 | // Invalidating the column strings picks up and request/response
1287 | // tracking changes. We might just want to call it from flushVisibleRows.
1288 | packet_list_model_->invalidateAllColumnStrings();
1289 | // Sort *after* invalidating the column strings
1290 | if (isSortingEnabled()) {
1291 | sortByColumn(header()->sortIndicatorSection(), header()->sortIndicatorOrder());
1292 | }
1293 | }
1294 |
1295 | bool PacketList::freeze(bool keep_current_frame)
1296 | {
1297 | if (!cap_file_ || model() == Q_NULLPTRnullptr) {
1298 | // No capture file or already frozen
1299 | return false;
1300 | }
1301 |
1302 | frame_data *current_frame = cap_file_->current_frame;
1303 | column_state_ = header()->saveState();
1304 | setHeaderHidden(true);
1305 | frozen_current_row_ = currentIndex();
1306 | frozen_selected_rows_ = selectionModel()->selectedRows();
1307 | selectionModel()->clear();
1308 | setModel(Q_NULLPTRnullptr);
1309 | // It looks like GTK+ sends a cursor-changed signal at this point but Qt doesn't
1310 | // call selectionChanged.
1311 | related_packet_delegate_.clear();
1312 |
1313 | if (keep_current_frame) {
1314 | cap_file_->current_frame = current_frame;
1315 | }
1316 |
1317 | /* Clears packet list as well as byteview */
1318 | emit framesSelected(QList<int>());
1319 |
1320 | return true;
1321 | }
1322 |
1323 | bool PacketList::thaw(bool restore_selection)
1324 | {
1325 | if (!cap_file_ || model() != Q_NULLPTRnullptr) {
1326 | // No capture file or not frozen
1327 | return false;
1328 | }
1329 |
1330 | setHeaderHidden(false);
1331 | // Note that if we have a current sort status set in the header,
1332 | // this will automatically try to sort the model (we don't want
1333 | // that to happen if we're in the middle of reading the file).
1334 | setModel(packet_list_model_);
1335 |
1336 | if (changing_profile_) {
1337 | // When changing profile the new recent settings must be applied to the columns.
1338 | applyRecentColumnWidths();
1339 | setColumnVisibility();
1340 | changing_profile_ = false;
1341 | } else {
1342 | // Resetting the model resets our column widths so we restore them here.
1343 | // We don't reapply the recent settings because the user could have
1344 | // resized the columns manually since they were initially loaded.
1345 | header()->restoreState(column_state_);
1346 | }
1347 |
1348 | if (restore_selection && frozen_selected_rows_.length() > 0 && selectionModel()) {
1349 | /* This updates our selection, which redissects the current packet,
1350 | * which is needed when we're called from MainWindow::layoutPanes.
1351 | * Also, this resets all ProtoTree and ByteView data */
1352 | clearSelection();
1353 | setCurrentIndex(frozen_current_row_);
1354 | foreach (QModelIndex idx, frozen_selected_rows_)for (auto _container_1354 = QtPrivate::qMakeForeachContainer( frozen_selected_rows_); _container_1354.i != _container_1354. e; ++_container_1354.i) if (QModelIndex idx = *_container_1354 .i; false) {} else {
1355 | selectionModel()->select(idx, QItemSelectionModel::Select | QItemSelectionModel::Rows);
1356 | }
1357 | scrollTo(currentIndex(), PositionAtCenter);
1358 | }
1359 | frozen_current_row_ = QModelIndex();
1360 | frozen_selected_rows_ = QModelIndexList();
1361 |
1362 | return true;
1363 | }
1364 |
1365 | void PacketList::clear() {
1366 | related_packet_delegate_.clear();
1367 | selectionModel()->clear();
1368 | packet_list_model_->clear();
1369 | proto_tree_->clear();
1370 | selection_history_.clear();
1371 | cur_history_ = -1;
1372 | in_history_ = false;
1373 |
1374 | QImage overlay;
1375 | overlay_sb_->setNearOverlayImage(overlay);
1376 | overlay_sb_->setMarkedPacketImage(overlay);
1377 | create_near_overlay_ = true;
1378 | create_far_overlay_ = true;
1379 | }
1380 |
1381 | void PacketList::writeRecent(FILE *rf) {
1382 | int col, width, col_fmt;
1383 | char xalign;
1384 |
1385 | fprintf (rf, "%s:\n", RECENT_KEY_COL_WIDTH"column.width");
1386 | for (col = 0; col < prefs.num_cols; col++) {
1387 | if (col > 0) {
1388 | fprintf (rf, ",\n");
1389 | }
1390 | col_fmt = get_column_format(col);
1391 | if (col_fmt == COL_CUSTOM) {
1392 | fprintf (rf, " \"%%Cus:%s\",", get_column_custom_fields(col));
1393 | } else {
1394 | fprintf (rf, " %s,", col_format_to_string(col_fmt));
1395 | }
1396 | width = recent_get_column_width (col);
1397 | xalign = recent_get_column_xalign (col);
1398 | fprintf (rf, " %d", width);
1399 | if (xalign != COLUMN_XALIGN_DEFAULT0) {
1400 | fprintf (rf, ":%c", xalign);
1401 | }
1402 | }
1403 | fprintf (rf, "\n");
1404 | }
1405 |
1406 | bool PacketList::contextMenuActive()
1407 | {
1408 | return ctx_column_ >= 0 ? true : false;
1409 | }
1410 |
1411 | QString PacketList::getFilterFromRowAndColumn(QModelIndex idx)
1412 | {
1413 | frame_data *fdata;
1414 | QString filter;
1415 |
1416 | if (! idx.isValid())
1417 | return filter;
1418 |
1419 | int row = idx.row();
1420 | int column = idx.column();
1421 |
1422 | if (!cap_file_ || !packet_list_model_ || column < 0 || column >= cap_file_->cinfo.num_cols)
1423 | return filter;
1424 |
1425 | fdata = packet_list_model_->getRowFdata(row);
1426 |
1427 | if (fdata != NULL__null) {
1428 | epan_dissect_t edt;
1429 | wtap_rec rec; /* Record information */
1430 |
1431 | wtap_rec_init(&rec, DEFAULT_INIT_BUFFER_SIZE_2048(2 * 1024));
1432 | if (!cf_read_record(cap_file_, fdata, &rec)) {
1433 | wtap_rec_cleanup(&rec);
1434 | return filter; /* error reading the record */
1435 | }
1436 | /* proto tree, visible. We need a proto tree if there's custom columns */
1437 | epan_dissect_init(&edt, cap_file_->epan, have_custom_cols(&cap_file_->cinfo), false);
1438 | col_custom_prime_edt(&edt, &cap_file_->cinfo);
1439 |
1440 | epan_dissect_run(&edt, cap_file_->cd_t, &rec, fdata, &cap_file_->cinfo);
1441 |
1442 | if (cap_file_->cinfo.columns[column].col_fmt == COL_CUSTOM) {
1443 | filter.append(gchar_free_to_qstring(col_custom_get_filter(&edt, &cap_file_->cinfo, column)));
1444 | } else {
1445 | /* We don't need to fill in the custom columns, as we get their
1446 | * filters above.
1447 | */
1448 | col_fill_in(&edt.pi, true, true);
1449 | if (strlen(cap_file_->cinfo.col_expr.col_expr[column]) != 0 &&
1450 | strlen(cap_file_->cinfo.col_expr.col_expr_val[column]) != 0) {
1451 | bool is_string_value = false;
1452 | header_field_info *hfi = proto_registrar_get_byname(cap_file_->cinfo.col_expr.col_expr[column]);
1453 | if (hfi && FT_IS_STRING(hfi->type)((hfi->type) == FT_STRING || (hfi->type) == FT_STRINGZ || (hfi->type) == FT_STRINGZPAD || (hfi->type) == FT_STRINGZTRUNC || (hfi->type) == FT_UINT_STRING || (hfi->type) == FT_AX25 )) {
1454 | /* Could be an address type such as usb.src which must be quoted. */
1455 | is_string_value = true;
1456 | }
1457 |
1458 | if (filter.isEmpty()) {
1459 | if (is_string_value) {
1460 | filter.append(QStringLiteral("%1 == \"%2\"")(QString(QtPrivate::qMakeStringPrivate(u"" "%1 == \"%2\"")))
1461 | .arg(cap_file_->cinfo.col_expr.col_expr[column])
1462 | .arg(cap_file_->cinfo.col_expr.col_expr_val[column]));
1463 | } else {
1464 | filter.append(QStringLiteral("%1 == %2")(QString(QtPrivate::qMakeStringPrivate(u"" "%1 == %2")))
1465 | .arg(cap_file_->cinfo.col_expr.col_expr[column])
1466 | .arg(cap_file_->cinfo.col_expr.col_expr_val[column]));
1467 | }
1468 | }
1469 | }
1470 | }
1471 |
1472 | epan_dissect_cleanup(&edt);
1473 | wtap_rec_cleanup(&rec);
1474 | }
1475 |
1476 | return filter;
1477 | }
1478 |
1479 | void PacketList::resetColorized()
1480 | {
1481 | packet_list_model_->resetColorized();
1482 | update();
1483 | }
1484 |
1485 | QString PacketList::getPacketComment(unsigned c_number)
1486 | {
1487 | int row = currentIndex().row();
1488 | const frame_data *fdata;
1489 | char *pkt_comment;
1490 | wtap_opttype_return_val result;
1491 | QString ret_val = NULL__null;
1492 |
1493 | if (!cap_file_ || !packet_list_model_) return NULL__null;
1494 |
1495 | fdata = packet_list_model_->getRowFdata(row);
1496 |
1497 | if (!fdata) return NULL__null;
1498 |
1499 | wtap_block_t pkt_block = cf_get_packet_block(cap_file_, fdata);
1500 | result = wtap_block_get_nth_string_option_value(pkt_block, OPT_COMMENT1, c_number, &pkt_comment);
1501 | if (result == WTAP_OPTTYPE_SUCCESS) {
1502 | ret_val = QString(pkt_comment);
1503 | }
1504 | wtap_block_unref(pkt_block);
1505 | return ret_val;
1506 | }
1507 |
1508 | void PacketList::addPacketComment(QString new_comment)
1509 | {
1510 | if (!cap_file_ || !packet_list_model_) return;
1511 | if (new_comment.isEmpty()) return;
1512 |
1513 | QByteArray ba = new_comment.toUtf8();
1514 |
1515 | /*
1516 | * Make sure this would fit in a pcapng option.
1517 | *
1518 | * XXX - 65535 is the maximum size for an option in pcapng;
1519 | * what if another capture file format supports larger
1520 | * comments?
1521 | */
1522 | if (ba.size() > 65535) {
1523 | simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK0x01,
1524 | "That comment is too large to save in a capture file.");
1525 | return;
1526 | }
1527 |
1528 | if (selectionModel() && selectionModel()->hasSelection()) {
1529 | packet_list_model_->addFrameComment(selectionModel()->selectedRows(), ba);
1530 | drawCurrentPacket();
1531 | }
1532 | }
1533 |
1534 | void PacketList::setPacketComment(unsigned c_number, QString new_comment)
1535 | {
1536 | QModelIndex curIndex = currentIndex();
1537 |
1538 | if (!cap_file_ || !packet_list_model_) return;
1539 |
1540 | QByteArray ba = new_comment.toUtf8();
1541 | /*
1542 | * Make sure this would fit in a pcapng option.
1543 | *
1544 | * XXX - 65535 is the maximum size for an option in pcapng;
1545 | * what if another capture file format supports larger
1546 | * comments?
1547 | */
1548 | if (ba.size() > 65535) {
1549 | simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK0x01,
1550 | "That comment is too large to save in a capture file.");
1551 | return;
1552 | }
1553 |
1554 | packet_list_model_->setFrameComment(curIndex, ba, c_number);
1555 | drawCurrentPacket();
1556 | }
1557 |
1558 | QString PacketList::allPacketComments()
1559 | {
1560 | uint32_t framenum;
1561 | frame_data *fdata;
1562 | QString buf_str;
1563 |
1564 | if (!cap_file_) return buf_str;
1565 |
1566 | for (framenum = 1; framenum <= cap_file_->count ; framenum++) {
1567 | fdata = frame_data_sequence_find(cap_file_->provider.frames, framenum);
1568 |
1569 | wtap_block_t pkt_block = cf_get_packet_block(cap_file_, fdata);
1570 |
1571 | if (pkt_block) {
1572 | unsigned n_comments = wtap_block_count_option(pkt_block, OPT_COMMENT1);
1573 | for (unsigned i = 0; i < n_comments; i++) {
1574 | char *comment_text;
1575 | if (WTAP_OPTTYPE_SUCCESS == wtap_block_get_nth_string_option_value(pkt_block, OPT_COMMENT1, i, &comment_text)) {
1576 | buf_str.append(tr("Frame %1: %2\n\n").arg(framenum).arg(comment_text));
1577 | if (buf_str.length() > max_comments_to_fetch_) {
1578 | buf_str.append(tr("[ Comment text exceeds %1. Stopping. ]")
1579 | .arg(format_size(max_comments_to_fetch_, FORMAT_SIZE_UNIT_BYTES, FORMAT_SIZE_PREFIX_SI)format_size_wmem(__null, max_comments_to_fetch_, FORMAT_SIZE_UNIT_BYTES , (1 << 0))));
1580 | return buf_str;
1581 | }
1582 | }
1583 | }
1584 | }
1585 | }
1586 | return buf_str;
1587 | }
1588 |
1589 | void PacketList::deleteCommentsFromPackets()
1590 | {
1591 | if (!cap_file_ || !packet_list_model_) return;
1592 |
1593 | if (selectionModel() && selectionModel()->hasSelection()) {
1594 | packet_list_model_->deleteFrameComments(selectionModel()->selectedRows());
1595 | drawCurrentPacket();
1596 | }
1597 | }
1598 |
1599 | void PacketList::deleteAllPacketComments()
1600 | {
1601 | if (!cap_file_ || !packet_list_model_) return;
1602 |
1603 | packet_list_model_->deleteAllFrameComments();
1604 | drawCurrentPacket();
1605 | }
1606 |
1607 |
1608 | // Slots
1609 |
1610 | void PacketList::setCaptureFile(capture_file *cf)
1611 | {
1612 | cap_file_ = cf;
1613 | packet_list_model_->setCaptureFile(cf);
1614 | if (cf) {
1615 | if (columns_changed_) {
1616 | columnsChanged();
1617 | } else {
1618 | // Restore columns widths and visibility.
1619 | header()->restoreState(column_state_);
1620 | setColumnVisibility();
1621 | }
1622 | }
1623 | create_near_overlay_ = true;
1624 | changing_profile_ = false;
1625 | sortByColumn(-1, Qt::AscendingOrder);
1626 | }
1627 |
1628 | void PacketList::setMonospaceFont(const QFont &mono_font)
1629 | {
1630 | setFont(mono_font);
1631 | }
1632 |
1633 | void PacketList::setRegularFont(const QFont &regular_font)
1634 | {
1635 | header()->setFont(regular_font);
1636 | header()->viewport()->setFont(regular_font);
1637 | }
1638 |
1639 | void PacketList::goNextPacket(void)
1640 | {
1641 | if (QApplication::keyboardModifiers() & Qt::AltModifier) {
1642 | // Alt+toolbar
1643 | goNextHistoryPacket();
1644 | return;
1645 | }
1646 |
1647 | if (selectionModel()->hasSelection()) {
1648 | selectionModel()->setCurrentIndex(moveCursor(MoveDown, Qt::NoModifier), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
1649 | } else {
1650 | // First visible packet.
1651 | selectionModel()->setCurrentIndex(indexAt(viewport()->rect().topLeft()), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
1652 | }
1653 |
1654 | scrollViewChanged(false);
1655 | }
1656 |
1657 | void PacketList::goPreviousPacket(void)
1658 | {
1659 | if (QApplication::keyboardModifiers() & Qt::AltModifier) {
1660 | // Alt+toolbar
1661 | goPreviousHistoryPacket();
1662 | return;
1663 | }
1664 |
1665 | if (selectionModel()->hasSelection()) {
1666 | selectionModel()->setCurrentIndex(moveCursor(MoveUp, Qt::NoModifier), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
1667 | } else {
1668 | // Last visible packet.
1669 | QModelIndex last_idx = indexAt(viewport()->rect().bottomLeft());
1670 | if (last_idx.isValid()) {
1671 | selectionModel()->setCurrentIndex(last_idx, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
1672 | } else {
1673 | goLastPacket();
1674 | }
1675 | }
1676 |
1677 | scrollViewChanged(false);
1678 | }
1679 |
1680 | void PacketList::goFirstPacket(void) {
1681 | if (packet_list_model_->rowCount() < 1) return;
1682 | selectionModel()->setCurrentIndex(packet_list_model_->index(0, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
1683 | scrollTo(currentIndex());
1684 |
1685 | scrollViewChanged(false);
1686 | }
1687 |
1688 | void PacketList::goLastPacket(void) {
1689 | if (packet_list_model_->rowCount() < 1) return;
1690 | selectionModel()->setCurrentIndex(packet_list_model_->index(packet_list_model_->rowCount() - 1, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
1691 | scrollTo(currentIndex());
1692 |
1693 | scrollViewChanged(false);
1694 | }
1695 |
1696 | void PacketList::goToPacket(int packet, int hf_id)
1697 | {
1698 | if (!cf_goto_frame(cap_file_, packet, false))
1699 | return;
1700 |
1701 | // cf_goto_frame only returns true if packet_list_select_row_from_data
1702 | // succeeds, the latter has already selected and scrolled to the frame.
1703 | if (hf_id > 0) {
1704 | proto_tree_->goToHfid(hf_id);
1705 | }
1706 |
1707 | scrollViewChanged(false);
1708 | }
1709 |
1710 | void PacketList::goNextHistoryPacket()
1711 | {
1712 | if (haveNextHistory(true)) {
1713 | in_history_ = true;
1714 | goToPacket(selection_history_.at(cur_history_));
1715 | in_history_ = false;
1716 | }
1717 | }
1718 |
1719 | void PacketList::goPreviousHistoryPacket()
1720 | {
1721 | if (havePreviousHistory(true)) {
1722 | in_history_ = true;
1723 | goToPacket(selection_history_.at(cur_history_));
1724 | in_history_ = false;
1725 | }
1726 | }
1727 |
1728 | void PacketList::markFrame()
1729 | {
1730 | if (!cap_file_ || !packet_list_model_) return;
1731 |
1732 | QModelIndexList frames;
1733 |
1734 | if (selectionModel() && selectionModel()->hasSelection())
1735 | {
1736 | QModelIndexList selRows = selectionModel()->selectedRows(0);
1737 | foreach (QModelIndex idx, selRows)for (auto _container_1737 = QtPrivate::qMakeForeachContainer( selRows); _container_1737.i != _container_1737.e; ++_container_1737 .i) if (QModelIndex idx = *_container_1737.i; false) {} else
1738 | {
1739 | if (idx.isValid())
1740 | {
1741 | frames << idx;
1742 | }
1743 | }
1744 | }
1745 | else
1746 | frames << currentIndex();
1747 |
1748 | packet_list_model_->toggleFrameMark(frames);
1749 |
1750 | // Make sure the packet list's frame.marked related field text is updated.
1751 | redrawVisiblePackets();
1752 |
1753 | create_far_overlay_ = true;
1754 | packets_bar_update();
1755 | }
1756 |
1757 | void PacketList::markAllDisplayedFrames(bool set)
1758 | {
1759 | if (!cap_file_ || !packet_list_model_) return;
1760 |
1761 | packet_list_model_->setDisplayedFrameMark(set);
1762 |
1763 | // Make sure the packet list's frame.marked related field text is updated.
1764 | redrawVisiblePackets();
1765 |
1766 | create_far_overlay_ = true;
1767 | packets_bar_update();
1768 | }
1769 |
1770 | void PacketList::ignoreFrame()
1771 | {
1772 | if (!cap_file_ || !packet_list_model_) return;
1773 |
1774 | QModelIndexList frames;
1775 |
1776 | if (selectionModel() && selectionModel()->hasSelection())
1777 | {
1778 | foreach (QModelIndex idx, selectionModel()->selectedRows(0))for (auto _container_1778 = QtPrivate::qMakeForeachContainer( selectionModel()->selectedRows(0)); _container_1778.i != _container_1778 .e; ++_container_1778.i) if (QModelIndex idx = *_container_1778 .i; false) {} else
1779 | {
1780 | if (idx.isValid())
1781 | {
1782 | frames << idx;
1783 | }
1784 | }
1785 | }
1786 | else
1787 | frames << currentIndex();
1788 |
1789 |
1790 | packet_list_model_->toggleFrameIgnore(frames);
1791 | create_far_overlay_ = true;
1792 | int sb_val = verticalScrollBar()->value(); // Surely there's a better way to keep our position?
1793 | setUpdatesEnabled(false);
1794 | emit packetDissectionChanged();
1795 | setUpdatesEnabled(true);
1796 | verticalScrollBar()->setValue(sb_val);
1797 | }
1798 |
1799 | void PacketList::ignoreAllDisplayedFrames(bool set)
1800 | {
1801 | if (!cap_file_ || !packet_list_model_) return;
1802 |
1803 | packet_list_model_->setDisplayedFrameIgnore(set);
1804 | create_far_overlay_ = true;
1805 | emit packetDissectionChanged();
1806 | }
1807 |
1808 | void PacketList::setTimeReference()
1809 | {
1810 | if (!cap_file_ || !packet_list_model_) return;
1811 | packet_list_model_->toggleFrameRefTime(currentIndex());
1812 | create_far_overlay_ = true;
1813 | }
1814 |
1815 | void PacketList::unsetAllTimeReferences()
1816 | {
1817 | if (!cap_file_ || !packet_list_model_) return;
1818 | packet_list_model_->unsetAllFrameRefTime();
1819 | create_far_overlay_ = true;
1820 | }
1821 |
1822 | void PacketList::applyTimeShift()
1823 | {
1824 | packet_list_model_->resetColumns();
1825 | redrawVisiblePackets();
1826 | emit packetDissectionChanged();
1827 | }
1828 |
1829 | void PacketList::updatePackets(bool redraw)
1830 | {
1831 | if (redraw) {
1832 | packet_list_model_->resetColumns();
1833 | redrawVisiblePackets();
1834 | } else {
1835 | update();
1836 | }
1837 | }
1838 |
1839 | void PacketList::columnVisibilityTriggered()
1840 | {
1841 | QAction *ha = qobject_cast<QAction*>(sender());
1842 | if (!ha) return;
1843 |
1844 | int col = ha->data().toInt();
1845 | set_column_visible(col, ha->isChecked());
1846 | setColumnVisibility();
1847 | if (ha->isChecked()) {
1848 | setRecentColumnWidth(col);
1849 | }
1850 | prefs_main_write();
1851 | }
1852 |
1853 | void PacketList::sectionResized(int col, int, int new_width)
1854 | {
1855 | if (isVisible() && !columns_changed_ && !set_column_visibility_ && !set_style_sheet_ && new_width > 0) {
1856 | // Column 1 gets an invalid value (32 on macOS) when we're not yet
1857 | // visible.
1858 | //
1859 | // Don't set column width when columns changed or setting column
1860 | // visibility because we may get a sectionResized() from QTreeView
1861 | // with values from a old columns layout.
1862 | //
1863 | // Don't set column width when hiding a column.
1864 |
1865 | recent_set_column_width(col, new_width);
1866 | }
1867 | }
1868 |
1869 | // The user moved a column. Make sure prefs.col_list, the column format
1870 | // array, and the header's visual and logical indices all agree.
1871 | // gtk/packet_list.c:column_dnd_changed_cb
1872 | void PacketList::sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex)
1873 | {
1874 | GList *new_col_list = NULL__null;
1875 | GList *new_recent_col_list = NULL__null;
1876 | QList<int> saved_sizes;
1877 | int sort_idx;
1878 |
1879 | // Since we undo the move below, these should always stay in sync.
1880 | // Otherwise the order of columns can be unexpected after drag and drop.
1881 | if (logicalIndex != oldVisualIndex) {
1882 | ws_warning("Column moved from an unexpected state (%d, %d, %d)",do { if (true) { ws_log_full("", LOG_LEVEL_WARNING, "ui/qt/packet_list.cpp" , 1883, __func__, "Column moved from an unexpected state (%d, %d, %d)" , logicalIndex, oldVisualIndex, newVisualIndex); } } while (0 )
1883 | logicalIndex, oldVisualIndex, newVisualIndex)do { if (true) { ws_log_full("", LOG_LEVEL_WARNING, "ui/qt/packet_list.cpp" , 1883, __func__, "Column moved from an unexpected state (%d, %d, %d)" , logicalIndex, oldVisualIndex, newVisualIndex); } } while (0 );
1884 | }
1885 |
1886 | // Remember which column should be sorted. Use the visual index since this
1887 | // points to the current GUI state rather than the outdated column order
1888 | // (indicated by the logical index).
1889 | sort_idx = header()->sortIndicatorSection();
1890 | if (sort_idx != -1) {
1891 | sort_idx = header()->visualIndex(sort_idx);
1892 | }
1893 |
1894 | // Build a new column list based on the header's logical order.
1895 | for (int vis_idx = 0; vis_idx < header()->count(); vis_idx++) {
1896 | int log_idx = header()->logicalIndex(vis_idx);
1897 | saved_sizes << header()->sectionSize(log_idx);
1898 |
1899 | void *pref_data = g_list_nth_data(prefs.col_list, log_idx);
1900 | if (pref_data) {
1901 | new_col_list = g_list_append(new_col_list, pref_data);
1902 | }
1903 |
1904 | pref_data = g_list_nth_data(recent.col_width_list, log_idx);
1905 | if (pref_data) {
1906 | new_recent_col_list = g_list_append(new_recent_col_list, pref_data);
1907 | }
1908 | }
1909 |
1910 | // Undo move to ensure that the logical indices map to the visual indices,
1911 | // otherwise the column order is changed twice (once via the modified
1912 | // col_list, once because of the visual/logical index mismatch).
1913 | disconnect(header(), &QHeaderView::sectionMoved, this, &PacketList::sectionMoved);
1914 | header()->moveSection(newVisualIndex, oldVisualIndex);
1915 | connect(header(), &QHeaderView::sectionMoved, this, &PacketList::sectionMoved);
1916 |
1917 | // Clear and rebuild our (and the header's) model. There doesn't appear
1918 | // to be another way to reset the logical index.
1919 | freeze();
1920 |
1921 | g_list_free(prefs.col_list);
1922 | prefs.col_list = new_col_list;
1923 | g_list_free(recent.col_width_list);
1924 | recent.col_width_list = new_recent_col_list;
1925 |
1926 | thaw(true);
1927 |
1928 | for (int i = 0; i < saved_sizes.length(); i++) {
1929 | if (saved_sizes[i] < 1) continue;
1930 | header()->resizeSection(i, saved_sizes[i]);
1931 | }
1932 |
1933 | prefs_main_write();
1934 |
1935 | mainApp->emitAppSignal(MainApplication::ColumnsChanged);
1936 |
1937 | // If the column with the sort indicator got shifted, mark the new column
1938 | // after updating the columns contents (via ColumnsChanged) to ensure that
1939 | // the columns are sorted using the intended column contents.
1940 | int left_col = MIN(oldVisualIndex, newVisualIndex)(((oldVisualIndex) < (newVisualIndex)) ? (oldVisualIndex) : (newVisualIndex));
1941 | int right_col = MAX(oldVisualIndex, newVisualIndex)(((oldVisualIndex) > (newVisualIndex)) ? (oldVisualIndex) : (newVisualIndex));
1942 | if (left_col <= sort_idx && sort_idx <= right_col) {
1943 | header()->setSortIndicator(sort_idx, header()->sortIndicatorOrder());
1944 | }
1945 | }
1946 |
1947 | QString PacketList::createSummaryText(QModelIndex idx, SummaryCopyType type)
1948 | {
1949 | if (! idx.isValid())
1950 | return "";
1951 |
1952 | QStringList col_parts;
1953 | int row = idx.row();
1954 | for (int col = 0; col < packet_list_model_->columnCount(); col++) {
1955 | if (get_column_visible(col)) {
1956 | col_parts << packet_list_model_->data(packet_list_model_->index(row, col), Qt::DisplayRole).toString();
1957 | }
1958 | }
1959 | return joinSummaryRow(col_parts, row, type);
1960 | }
1961 |
1962 | QString PacketList::createHeaderSummaryText(SummaryCopyType type)
1963 | {
1964 | QStringList col_parts;
1965 | for (int col = 0; col < packet_list_model_->columnCount(); ++col) {
1966 | if (get_column_visible(col)) {
1967 | col_parts << packet_list_model_->headerData(col, Qt::Orientation::Horizontal, Qt::DisplayRole).toString();
1968 | }
1969 | }
1970 | return joinSummaryRow(col_parts, 0, type);
1971 | }
1972 |
1973 | QStringList PacketList::createHeaderPartsForAligned()
1974 | {
1975 | QStringList hdr_parts;
1976 | for (int col = 0; col < packet_list_model_->columnCount(); ++col) {
1977 | if (get_column_visible(col)) {
1978 | hdr_parts << packet_list_model_->headerData(col, Qt::Orientation::Horizontal, Qt::DisplayRole).toString();
1979 | }
1980 | }
1981 | return hdr_parts;
1982 | }
1983 |
1984 | QList<int> PacketList::createAlignmentPartsForAligned()
1985 | {
1986 | QList<int> align_parts;
1987 | for (int col = 0; col < packet_list_model_->columnCount(); col++) {
1988 | if (get_column_visible(col)) {
1989 | align_parts << packet_list_model_->data(packet_list_model_->index(0, col), Qt::TextAlignmentRole).toInt();
1990 | }
1991 | }
1992 | return align_parts;
1993 | }
1994 |
1995 | QList<int> PacketList::createSizePartsForAligned(bool useHeader, QStringList hdr_parts, QList<int> rows)
1996 | {
1997 | QList<int> size_parts;
1998 |
1999 | for (int i = 0; i < hdr_parts.size(); ++i) {
2000 | if (useHeader)
2001 | size_parts << static_cast<int>(hdr_parts.at(i).size());
2002 | else
2003 | size_parts << 0;
2004 | }
2005 |
2006 | foreach(int row, rows)for (auto _container_2006 = QtPrivate::qMakeForeachContainer( rows); _container_2006.i != _container_2006.e; ++_container_2006 .i) if (int row = *_container_2006.i; false) {} else
2007 | {
2008 | QModelIndex idx = model()->index(row, 0);
2009 | if (! idx.isValid())
2010 | continue;
2011 |
2012 | QStringList col_parts;
2013 | for (int col = 0; col < packet_list_model_->columnCount(); col++) {
2014 | if (get_column_visible(col)) {
2015 | col_parts << (packet_list_model_->data(packet_list_model_->index(row, col), Qt::DisplayRole).toString());
2016 | }
2017 | }
2018 |
2019 | for (int i = 0; i < col_parts.size(); ++i) {
2020 | if (col_parts.at(i).size() > size_parts.at(i)) {
2021 | size_parts[i] = static_cast<int>(col_parts.at(i).size());
2022 | }
2023 | }
2024 | col_parts.clear();
2025 | }
2026 |
2027 | return size_parts;
2028 | }
2029 |
2030 | QString PacketList::createHeaderSummaryForAligned(QStringList hdr_parts, QList<int> align_parts, QList<int> size_parts)
2031 | {
2032 | QString hdr_text;
2033 | for (int i = 0; i < hdr_parts.size(); ++i) {
2034 | if (align_parts.at(i) == Qt::AlignLeft) {
2035 | hdr_text += hdr_parts[i].leftJustified(size_parts.at(i), ' ') + " ";
2036 | }
2037 | else if (align_parts.at(i) == Qt::AlignRight) {
2038 | hdr_text += hdr_parts[i].rightJustified(size_parts.at(i), ' ') + " ";
2039 | }
2040 | }
2041 | return QStringLiteral("-%1")(QString(QtPrivate::qMakeStringPrivate(u"" "-%1"))).arg(hdr_text).trimmed().mid(1);
2042 | }
2043 |
2044 | QString PacketList::createSummaryForAligned(QModelIndex idx, QList<int> align_parts, QList<int> size_parts)
2045 | {
2046 | if (! idx.isValid())
2047 | return "";
2048 |
2049 | QStringList col_parts;
2050 | int row = idx.row();
2051 | for (int col = 0; col < packet_list_model_->columnCount(); col++) {
2052 | if (get_column_visible(col)) {
2053 | col_parts << packet_list_model_->data(packet_list_model_->index(row, col), Qt::DisplayRole).toString();
2054 | }
2055 | }
2056 |
2057 | QString col_text;
2058 | for (int i = 0; i < col_parts.size(); ++i) {
2059 | if (align_parts.at(i) == Qt::AlignLeft) {
2060 | col_text += col_parts[i].leftJustified(size_parts.at(i), ' ') + " ";
2061 | }
2062 | else if (align_parts.at(i) == Qt::AlignRight) {
2063 | col_text += col_parts[i].rightJustified(size_parts.at(i), ' ') + " ";
2064 | }
2065 | }
2066 |
2067 | return QStringLiteral("-%1")(QString(QtPrivate::qMakeStringPrivate(u"" "-%1"))).arg(col_text).trimmed().mid(1);
2068 | }
2069 |
2070 | QString PacketList::createDefaultStyleForHtml()
2071 | {
2072 | QString fontFamily = QString(prefs.gui_font_name).split(",")[0];
2073 | QString fontSize = QString(prefs.gui_font_name).split(",")[1];
2074 |
2075 | return QStringLiteral("<style>"(QString(QtPrivate::qMakeStringPrivate(u"" "<style>" "table{font-family:%1;font-size:%2pt;}" "th{background-color:#000000;color:#ffffff;text-align:left;}" "th,td{padding:%3pt}" "</style>")))
2076 | "table{font-family:%1;font-size:%2pt;}"(QString(QtPrivate::qMakeStringPrivate(u"" "<style>" "table{font-family:%1;font-size:%2pt;}" "th{background-color:#000000;color:#ffffff;text-align:left;}" "th,td{padding:%3pt}" "</style>")))
2077 | "th{background-color:#000000;color:#ffffff;text-align:left;}"(QString(QtPrivate::qMakeStringPrivate(u"" "<style>" "table{font-family:%1;font-size:%2pt;}" "th{background-color:#000000;color:#ffffff;text-align:left;}" "th,td{padding:%3pt}" "</style>")))
2078 | "th,td{padding:%3pt}"(QString(QtPrivate::qMakeStringPrivate(u"" "<style>" "table{font-family:%1;font-size:%2pt;}" "th{background-color:#000000;color:#ffffff;text-align:left;}" "th,td{padding:%3pt}" "</style>")))
2079 | "</style>")(QString(QtPrivate::qMakeStringPrivate(u"" "<style>" "table{font-family:%1;font-size:%2pt;}" "th{background-color:#000000;color:#ffffff;text-align:left;}" "th,td{padding:%3pt}" "</style>"))).arg(fontFamily, fontSize).arg(fontSize.toInt() / 2);
2080 | }
2081 |
2082 | QString PacketList::createOpeningTagForHtml()
2083 | {
2084 | return "<table>";
2085 | }
2086 |
2087 | QString PacketList::createHeaderSummaryForHtml()
2088 | {
2089 | QString hdr_text;
2090 | hdr_text += "<tr>";
2091 | for (int col = 0; col < packet_list_model_->columnCount(); ++col) {
2092 | if (get_column_visible(col)) {
2093 | hdr_text += "<th>";
2094 | hdr_text += packet_list_model_->headerData(col, Qt::Orientation::Horizontal, Qt::DisplayRole).toString();
2095 | hdr_text += "</th>";
2096 | }
2097 | }
2098 | hdr_text += "</tr>";
2099 | return hdr_text;
2100 | }
2101 |
2102 | QString PacketList::createSummaryForHtml(QModelIndex idx)
2103 | {
2104 | if (! idx.isValid())
2105 | return "";
2106 |
2107 | int row = idx.row();
2108 | QString col_text;
2109 |
2110 | QString bg_color = packet_list_model_->data(packet_list_model_->index(row, 0), Qt::BackgroundRole).toString();
2111 | QString fg_color = packet_list_model_->data(packet_list_model_->index(row, 0), Qt::ForegroundRole).toString();
2112 | col_text += "<tr style=\"background-color:" + bg_color + ";color:" + fg_color + ";\">";
2113 |
2114 | QString alignment[] = {"left", "right", "center", "justify"};
2115 |
2116 | for (int col = 0; col < packet_list_model_->columnCount(); col++) {
2117 | if (get_column_visible(col)) {
2118 | col_text += "<td style=\"text-align:" + alignment[packet_list_model_->data(packet_list_model_->index(row, col), Qt::TextAlignmentRole).toInt() / 2] + ";\">";
2119 | col_text += packet_list_model_->data(packet_list_model_->index(row, col), Qt::DisplayRole).toString();
2120 | col_text += "</td>";
2121 | }
2122 | }
2123 |
2124 | col_text += "</tr>";
2125 | return col_text;
2126 | }
2127 |
2128 | QString PacketList::createClosingTagForHtml()
2129 | {
2130 | return "</table>";
2131 | }
2132 |
2133 | void PacketList::copySummary()
2134 | {
2135 | if (!currentIndex().isValid()) return;
2136 |
2137 | QAction *ca = qobject_cast<QAction*>(sender());
2138 | if (!ca) return;
2139 |
2140 | QVariant type = ca->data();
2141 | if (! type.canConvert<SummaryCopyType>())
2142 | return;
2143 | SummaryCopyType copy_type = type.value<SummaryCopyType>();
2144 |
2145 | QString copy_text;
2146 | if (type == CopyAsText || type == CopyAsHTML) {
2147 | if (prefs.gui_packet_list_copy_text_with_aligned_columns) {
2148 | QList<int> rows;
2149 | rows << currentIndex().row();
2150 | QStringList hdr_parts;
2151 | QList<int> align_parts, size_parts;
2152 | hdr_parts = createHeaderPartsForAligned();
2153 | align_parts = createAlignmentPartsForAligned();
2154 | size_parts = createSizePartsForAligned(false, hdr_parts, rows);
2155 | copy_text = createSummaryForAligned(currentIndex(), align_parts, size_parts);
2156 | }
2157 | else {
2158 | copy_text = createSummaryText(currentIndex(), CopyAsText);
2159 | }
2160 | copy_text += "\n";
2161 | if (type == CopyAsHTML) {
2162 | QStringList htmlContent;
2163 | htmlContent << createDefaultStyleForHtml();
2164 | htmlContent << createOpeningTagForHtml();
2165 | htmlContent << createSummaryForHtml(currentIndex());
2166 | htmlContent << createClosingTagForHtml();
2167 | // htmlContent will never be empty as they will always have
2168 | // style and table tags
2169 | QMimeData *mimeData = new QMimeData;
2170 | mimeData->setHtml(htmlContent.join('\n'));
2171 | mimeData->setText(copy_text);
2172 | mainApp->clipboard()->setMimeData(mimeData, QClipboard::Clipboard);
2173 | }
2174 | else {
2175 | mainApp->clipboard()->setText(copy_text);
2176 | }
2177 | }
2178 | else {
2179 | copy_text = createSummaryText(currentIndex(), copy_type);
2180 | if (type != CopyAsYAML)
2181 | copy_text += "\n";
2182 | mainApp->clipboard()->setText(copy_text);
2183 | }
2184 | }
2185 |
2186 | // We need to tell when the user has scrolled the packet list, either to
2187 | // the end or anywhere other than the end.
2188 | void PacketList::vScrollBarActionTriggered(int)
2189 | {
2190 | // If we're scrolling with a mouse wheel or trackpad sliderPosition can end up
2191 | // past the end.
2192 | tail_at_end_ = (overlay_sb_->sliderPosition() >= overlay_sb_->maximum());
2193 |
2194 | scrollViewChanged(tail_at_end_);
2195 | }
2196 |
2197 | void PacketList::scrollViewChanged(bool at_end)
2198 | {
2199 | if (capture_in_progress_) {
2200 | // We want to start auto scrolling when the user scrolls to (or past)
2201 | // the end only if recent.capture_auto_scroll is set.
2202 | // We want to stop autoscrolling if the user scrolls up or uses
2203 | // Go to Packet regardless of the preference setting.
2204 | if (recent.capture_auto_scroll || !at_end) {
2205 | emit packetListScrolled(at_end);
2206 | }
2207 | }
2208 | }
2209 |
2210 | // Goal: Overlay the packet list scroll bar with the colors of all of the
2211 | // packets.
2212 | // Try 1: Average packet colors in each scroll bar raster line. This has
2213 | // two problems: It's easy to wash out colors and we dissect every packet.
2214 | // Try 2: Color across a 5000 or 10000 packet window. We still end up washing
2215 | // out colors.
2216 | // Try 3: One packet per vertical scroll bar pixel. This seems to work best
2217 | // but has the smallest window.
2218 | // Try 4: Use a multiple of the scroll bar height and scale the image down
2219 | // using Qt::SmoothTransformation. This gives us more packets per raster
2220 | // line.
2221 |
2222 | // Odd (prime?) numbers resulted in fewer scaling artifacts. A multiplier
2223 | // of 9 washed out colors a little too much.
2224 | //const int height_multiplier_ = 7;
2225 | void PacketList::drawNearOverlay()
2226 | {
2227 | if (create_near_overlay_) {
2228 | create_near_overlay_ = false;
2229 | }
2230 |
2231 | if (!cap_file_ || cap_file_->state != FILE_READ_DONE) return;
2232 |
2233 | if (!prefs.gui_packet_list_show_minimap) return;
2234 |
2235 | qreal dp_ratio = overlay_sb_->devicePixelRatio();
2236 | int o_height = overlay_sb_->height() * dp_ratio;
2237 | int o_rows = qMin(packet_list_model_->rowCount(), o_height);
2238 | QFontMetricsF fmf(mainApp->font());
2239 | int o_width = ((static_cast<int>(fmf.height())) * 2 * dp_ratio) + 2; // 2ems + 1-pixel border on either side.
2240 |
2241 | if (recent.packet_list_colorize && o_rows > 0) {
2242 | QImage overlay(o_width, o_height, QImage::Format_ARGB32_Premultiplied);
2243 |
2244 | QPainter painter(&overlay);
2245 |
2246 | overlay.fill(Qt::transparent);
2247 |
2248 | int cur_line = 0;
2249 | int start = 0;
2250 |
2251 | if (packet_list_model_->rowCount() > o_height && overlay_sb_->maximum() > 0) {
2252 | start += ((double) overlay_sb_->value() / overlay_sb_->maximum()) * (packet_list_model_->rowCount() - o_rows);
2253 | }
2254 | int end = start + o_rows;
2255 | for (int row = start; row < end; row++) {
2256 | packet_list_model_->ensureRowColorized(row);
2257 |
2258 | frame_data *fdata = packet_list_model_->getRowFdata(row);
2259 | const color_t *bgcolor = NULL__null;
2260 | if (fdata->color_filter) {
2261 | const color_filter_t *color_filter = (const color_filter_t *) fdata->color_filter;
2262 | bgcolor = &color_filter->bg_color;
2263 | }
2264 |
2265 | int next_line = (row - start + 1) * o_height / o_rows;
2266 | if (bgcolor) {
2267 | QColor color(ColorUtils::fromColorT(bgcolor));
2268 | painter.fillRect(0, cur_line, o_width, next_line - cur_line, color);
2269 | }
2270 | cur_line = next_line;
2271 | }
2272 |
2273 | // If the selected packet is in the overlay set selected_pos
2274 | // accordingly. Otherwise, pin it to either the top or bottom.
2275 | QList<int> positions;
2276 | if (selectionModel()->hasSelection()) {
2277 |
2278 | QModelIndexList selRows = selectionModel()->selectedRows(0);
2279 | int last_row = -1;
2280 | int last_pos = -1;
2281 | foreach (QModelIndex idx, selRows)for (auto _container_2281 = QtPrivate::qMakeForeachContainer( selRows); _container_2281.i != _container_2281.e; ++_container_2281 .i) if (QModelIndex idx = *_container_2281.i; false) {} else
2282 | {
2283 | int selected_pos = -1;
2284 | int sel_row = idx.row();
2285 | if (sel_row < start) {
2286 | selected_pos = 0;
2287 | } else if (sel_row >= end) {
2288 | selected_pos = overlay.height() - 1;
2289 | } else {
2290 | selected_pos = (sel_row - start) * o_height / o_rows;
2291 | }
2292 |
2293 | /* Due to the difference in the display height, we sometimes get empty positions
2294 | * inbetween consecutive valid rows. If those are detected, they are signaled as
2295 | * being selected as well */
2296 | if (last_pos >= 0 && selected_pos > (last_pos + 1) && (last_row + 1) == sel_row)
2297 | {
2298 | for (int pos = (last_pos + 1); pos < selected_pos; pos++)
2299 | {
2300 | if (! positions.contains(pos))
2301 | positions << pos;
2302 | }
2303 | }
2304 | else if (selected_pos != -1 && ! positions.contains(selected_pos))
2305 | positions << selected_pos;
2306 |
2307 | last_row = sel_row;
2308 | last_pos = selected_pos;
2309 | }
2310 | }
2311 |
2312 | overlay_sb_->setNearOverlayImage(overlay, packet_list_model_->rowCount(), start, end, positions, (o_height / o_rows));
2313 | } else {
2314 | QImage overlay;
2315 | overlay_sb_->setNearOverlayImage(overlay);
2316 | }
2317 | }
2318 |
2319 | void PacketList::drawFarOverlay()
2320 | {
2321 | if (create_far_overlay_) {
2322 | create_far_overlay_ = false;
2323 | }
2324 |
2325 | if (!cap_file_ || cap_file_->state != FILE_READ_DONE) return;
2326 |
2327 | if (!prefs.gui_packet_list_show_minimap) return;
2328 |
2329 | QSize groove_size = overlay_sb_->grooveRect().size();
2330 | qreal dp_ratio = overlay_sb_->devicePixelRatio();
2331 | groove_size *= dp_ratio;
2332 | int o_width = groove_size.width();
2333 | int o_height = groove_size.height();
2334 | int pl_rows = packet_list_model_->rowCount();
2335 | QImage overlay(o_width, o_height, QImage::Format_ARGB32_Premultiplied);
2336 | bool have_marked_image = false;
2337 |
2338 | // If only there were references from popular culture about getting into
2339 | // some sort of groove.
2340 | if (!overlay.isNull() && recent.packet_list_colorize && pl_rows > 0) {
2341 |
2342 | QPainter painter(&overlay);
2343 |
2344 | // Draw text-colored tick marks on a transparent background.
2345 | // Hopefully no themes use the text color for the groove color.
2346 | overlay.fill(Qt::transparent);
2347 |
2348 | QColor tick_color = palette().text().color();
2349 | tick_color.setAlphaF(0.3f);
2350 | painter.setPen(tick_color);
2351 |
2352 | for (int row = 0; row < pl_rows; row++) {
2353 |
2354 | frame_data *fdata = packet_list_model_->getRowFdata(row);
2355 | if (fdata->marked || fdata->ref_time || fdata->ignored) {
2356 | int new_line = row * o_height / pl_rows;
2357 | int tick_width = o_width / 3;
2358 | // Marked or ignored: left side, time refs: right side.
2359 | // XXX Draw ignored ticks in the middle?
2360 | int x1 = fdata->ref_time ? o_width - tick_width : 1;
2361 | int x2 = fdata->ref_time ? o_width - 1 : tick_width;
2362 |
2363 | painter.drawLine(x1, new_line, x2, new_line);
2364 | have_marked_image = true;
2365 | }
2366 | }
2367 |
2368 | if (have_marked_image) {
2369 | overlay_sb_->setMarkedPacketImage(overlay);
2370 | return;
2371 | }
2372 | }
2373 |
2374 | if (!have_marked_image) {
2375 | QImage null_overlay;
2376 | overlay_sb_->setMarkedPacketImage(null_overlay);
2377 | }
2378 | }
2379 |
2380 | // Auto scroll if:
2381 | // - We are capturing
2382 | // - actionGoAutoScroll in the main UI is checked.
2383 |
2384 | // actionGoAutoScroll in the main UI:
2385 | // - Is set to the value of recent.capture_auto_scroll when beginning a capture
2386 | // - Can be triggered manually by the user
2387 | // - Is turned on if the last user-set vertical scrollbar position is at the
2388 | // end and recent.capture_auto_scroll is enabled
2389 | // - Is turned off if the last user-set vertical scrollbar is not at the end,
2390 | // or if one of the Go to Packet actions is used (XXX: Should keyboard
2391 | // navigation in keyPressEvent turn it off for similar reasons?)
2392 | void PacketList::rowsInserted(const QModelIndex &parent, int start, int end)
2393 | {
2394 | QTreeView::rowsInserted(parent, start, end);
2395 | if (recent.aggregation_view && currentIndex().isValid() && currentIndex().row() >= 0) {
2396 | selectRow(getFDataForRow(currentIndex().row()), false);
2397 | }
2398 | if (capture_in_progress_ && tail_at_end_) {
2399 | scrollToBottom();
2400 | }
2401 | }
2402 |
2403 | void PacketList::resizeAllColumns(bool onlyTimeFormatted)
2404 | {
2405 | if (!cap_file_ || cap_file_->state == FILE_CLOSED || cap_file_->state == FILE_READ_PENDING)
2406 | return;
2407 |
2408 | for (int col = 0; col < cap_file_->cinfo.num_cols; col++) {
2409 | if (! onlyTimeFormatted || col_has_time_fmt(&cap_file_->cinfo, col)) {
2410 | resizeColumnToContents(col);
2411 | }
2412 | }
2413 | }
2414 |
2415 | bool PacketList::selectRow(const frame_data* fdata, bool flushRows)
2416 | {
2417 | PacketListModel* pktListModel = qobject_cast<PacketListModel*>(model());
2418 |
2419 | if (!pktListModel)
2420 | return false;
2421 |
2422 | if (flushRows) {
2423 | pktListModel->flushVisibleRows();
2424 | }
2425 | int row = -1;
2426 | if (!fdata)
2427 | row = 0;
2428 | else
2429 | row = pktListModel->visibleIndexOf(fdata);
2430 |
2431 | if (row >= 0) {
2432 | /* Calling ClearAndSelect with setCurrentIndex clears the "current"
2433 | * item, but doesn't clear the "selected" item. We want to clear
2434 | * the "selected" item as well so that selectionChanged() will be
2435 | * emitted in order to force an update of the packet details and
2436 | * packet bytes after a search.
2437 | */
2438 | selectionModel()->clearSelection();
2439 | selectionModel()->setCurrentIndex(pktListModel->index(row, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
2440 | scrollTo(currentIndex(), PacketList::PositionAtCenter);
2441 | return true;
2442 | }
2443 |
2444 | return false;
2445 | }