Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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-22/lib/clang/22 -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 /builds/wireshark/wireshark/ui/qt/lua_debugger -isystem /usr/include/x86_64-linux-gnu/qt6/QtConcurrent -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/QtNetwork -isystem /usr/include/x86_64-linux-gnu/qt6/QtPrintSupport -isystem /usr/include/x86_64-linux-gnu/qt6/QtGui -isystem /usr/include/x86_64-linux-gnu/qt6/QtWidgets -isystem /usr/include/x86_64-linux-gnu/qt6/QtSvg -isystem /usr/include/x86_64-linux-gnu/qt6/QtMultimedia -isystem /usr/include/x86_64-linux-gnu/qt6/QtDBus -D CARES_NO_DEPRECATED -D G_DISABLE_DEPRECATED -D G_DISABLE_SINGLE_INCLUDES -D QT_CONCURRENT_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_SVG_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/16/../../../../include/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/x86_64-linux-gnu/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16/backward -internal-isystem /usr/lib/llvm-22/lib/clang/22/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../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-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 -fdwarf2-cfi-asm -o /builds/wireshark/wireshark/sbout/2026-09-22-100352-3660-1 -x c++ /builds/wireshark/wireshark/ui/qt/packet_list.cpp
1/* packet_list.cpp
2 *
3 * Wireshark - Network traffic analyzer
4 * By Gerald Combs <[email protected]>
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 "file.h"
13
14#include <epan/epan.h>
15#include <epan/epan_dissect.h>
16
17#include <epan/column.h>
18#include <epan/expert.h>
19#include <epan/packet.h>
20#include <epan/prefs.h>
21#include <epan/proto.h>
22
23#include "ui/main_statusbar.h"
24#include "ui/packet_list_utils.h"
25#include "ui/preference_utils.h"
26#include "ui/recent.h"
27#include "ui/simple_dialog.h"
28#include <wsutil/utf8_entities.h>
29
30#include "wiretap/wtap_opttypes.h"
31#include "app/application_flavor.h"
32#include "wsutil/str_util.h"
33#include <wsutil/wslog.h>
34
35#include <epan/color_filters.h>
36
37#include <ui/qt/utils/color_utils.h>
38#include <ui/qt/utils/theme_manager.h>
39#include <ui/qt/utils/font_manager.h>
40#include <ui/qt/widgets/overlay_scroll_bar.h>
41#include "proto_tree.h"
42#include <ui/qt/utils/qt_ui_utils.h>
43#include "main_application.h"
44#include <ui/qt/utils/data_printer.h>
45#include <ui/qt/utils/frame_information.h>
46#include <ui/qt/utils/profile_switcher.h>
47#include <ui/qt/utils/variant_pointer.h>
48#include <ui/qt/models/pref_models.h>
49#include <ui/qt/widgets/packet_list_header.h>
50#include <ui/qt/utils/wireshark_mime_data.h>
51#include <ui/qt/widgets/drag_label.h>
52#include <ui/qt/filter_action.h>
53#include <ui/qt/follow_stream_action.h>
54#include <ui/qt/decode_as_dialog.h>
55#include <ui/qt/wireshark_main_window.h>
56
57#include <QAction>
58#include <QActionGroup>
59#include <QApplication>
60#include <QClipboard>
61#include <QContextMenuEvent>
62#include <QtCore/qmath.h>
63#include <QElapsedTimer>
64#include <QFontMetrics>
65#include <QHeaderView>
66#include <QKeyEvent>
67#include <QMessageBox>
68#include <QPainter>
69#include <QScreen>
70#include <QScrollBar>
71#include <QWheelEvent>
72#include <QTabWidget>
73#include <QTextEdit>
74#include <QTimerEvent>
75#include <QTreeWidget>
76#include <QWindow>
77#include <QJsonObject>
78#include <QJsonDocument>
79
80#ifdef Q_OS_WIN
81#include "wsutil/file_util.h"
82#include <QSysInfo>
83#include <uxtheme.h>
84#endif
85
86// To do:
87// - Fix "apply as filter" behavior.
88// - Add colorize conversation.
89// - Use a timer to trigger automatic scrolling.
90
91// If we ever add the ability to open multiple capture files we might be
92// able to use something like QMap<capture_file *, PacketList *> to match
93// capture files against packet lists and models.
94static PacketList *gbl_cur_packet_list;
95
96const int max_comments_to_fetch_ = 20000000; // Arbitrary
97const int overlay_update_interval_ = 100; // 250; // Milliseconds.
98// Turbo mode: If the user holds down the down or up key longer than the
99// activation delay, switch from the operating system's autorepeat rate to
100// our own, faster rate.
101const int turbo_activation_delay_ = 1500; // Milliseconds, somewhat arbitrary.
102// Our goal is to move to the next or previous packet as fast as possible
103// while still allowing the user to recognize changes in the hex view.
104// According to this paper on Rapid Serial Visual Presentation (RSVP), humans
105// can recognize images presented as fast as 13ms.
106// https://web.archive.org/web/20250216195443/https://mollylab-1.mit.edu/sites/default/files/documents/FastDetect2014withFigures.pdf
107// Hopefully 15ms is plenty.
108const int turbo_nav_interval_ = 15; // Milliseconds
109
110
111/*
112 * Given a frame_data structure, scroll to and select the row in the
113 * packet list corresponding to that frame. If there is no such
114 * row, return false, otherwise return true.
115 */
116bool
117packet_list_select_row_from_data(frame_data *fdata_needle)
118{
119 if (! gbl_cur_packet_list || ! gbl_cur_packet_list->model())
120 return false;
121
122 PacketListModel* model = qobject_cast<PacketListModel*>(gbl_cur_packet_list->model());
123
124 if (!model)
125 return false;
126
127 model->flushVisibleRows();
128 int row = -1;
129 if (!fdata_needle)
130 row = 0;
131 else
132 row = model->visibleIndexOf(fdata_needle);
133
134 if (row >= 0) {
135 /* Calling ClearAndSelect with setCurrentIndex clears the "current"
136 * item, but doesn't clear the "selected" item. We want to clear
137 * the "selected" item as well so that selectionChanged() will be
138 * emitted in order to force an update of the packet details and
139 * packet bytes after a search.
140 */
141 gbl_cur_packet_list->selectionModel()->clearSelection();
142 gbl_cur_packet_list->selectionModel()->setCurrentIndex(model->index(row, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
143 gbl_cur_packet_list->scrollTo(gbl_cur_packet_list->currentIndex(), PacketList::PositionAtCenter);
144 return true;
145 }
146
147 return false;
148}
149
150/*
151 * Given a field_info, select the field (which will scroll to it in
152 * the main ProtoTree, etc.) This is kind of an odd place for it,
153 * but we call this when performing Find Packet in lieu of changing the
154 * selected frame (the function above), because we found a match in the
155 * same frame as the currently selected one.
156 */
157bool
158packet_list_select_finfo(field_info *fi)
159{
160 if (! gbl_cur_packet_list || ! gbl_cur_packet_list->model())
161 return false;
162
163 if (fi) {
164 FieldInformation finfo(fi, gbl_cur_packet_list);
165 emit gbl_cur_packet_list->fieldSelected(&finfo);
166 } else {
167 emit gbl_cur_packet_list->fieldSelected(0);
168 }
169 return true;
170}
171
172void
173packet_list_clear(void)
174{
175 if (gbl_cur_packet_list) {
176 gbl_cur_packet_list->clear();
177 }
178}
179
180void
181packet_list_freeze(void)
182{
183 if (gbl_cur_packet_list) {
184 gbl_cur_packet_list->freeze();
185 }
186}
187
188void
189packet_list_thaw(void)
190{
191 if (gbl_cur_packet_list) {
192 gbl_cur_packet_list->thaw();
193 }
194
195 packets_bar_update();
196}
197
198/* Redraw the packet list *and* currently-selected detail */
199void
200packet_list_queue_draw(void)
201{
202 if (gbl_cur_packet_list)
203 gbl_cur_packet_list->redrawVisiblePackets();
204}
205
206void
207packet_list_recent_write_all(FILE *rf) {
208 if (!gbl_cur_packet_list)
209 return;
210
211 gbl_cur_packet_list->writeRecent(rf);
212}
213
214bool
215packet_list_multi_select_active(void)
216{
217 if (gbl_cur_packet_list) {
218 return gbl_cur_packet_list->multiSelectActive();
219 }
220 return false;
221}
222
223#define MIN_COL_WIDTH_STR"MMMMMM" "MMMMMM"
224
225PacketList::PacketList(QWidget *parent) :
226 QTreeView(parent),
227 proto_tree_(nullptr),
228 cap_file_(nullptr),
229 ctx_column_(-1),
230 ctx_from_pinned_row_strip_(false),
231 overlay_timer_id_(0),
232 turbo_timer_id_(0),
233 turbo_key_(Qt::Key(0)),
234 held_key_(Qt::Key(0)),
235 create_near_overlay_(true),
236 create_far_overlay_(true),
237 mouse_pressed_at_(QModelIndex()),
238 capture_in_progress_(false),
239 tail_at_end_(0),
240 columns_changed_(false),
241 set_column_visibility_(false),
242 set_style_sheet_(false),
243 frozen_current_row_(QModelIndex()),
244 frozen_selected_rows_(QModelIndexList()),
245 pinned_rows_model_(nullptr),
246 pinned_column_boundary_(0),
247 pinned_column_view_(nullptr),
248 pinned_row_view_(nullptr),
249 pinned_row_corner_view_(nullptr),
250 hovered_frame_num_(-1),
251 cur_history_(-1),
252 in_history_(false),
253 finfo_array(nullptr),
254 profile_switcher_(nullptr)
255{
256 setItemsExpandable(false);
257 setRootIsDecorated(false);
258 setSortingEnabled(prefs.gui_packet_list_sortable);
259 setUniformRowHeights(true);
260 setFocusPolicy(Qt::StrongFocus);
261 // Needed so mouseMoveEvent() fires on a plain hover (no button held),
262 // to track hovered_frame_num_ for the cross-pane hover highlight.
263 setMouseTracking(true);
264
265#ifdef Q_OS_MAC
266 setAttribute(Qt::WA_MacShowFocusRect, true);
267#endif
268
269 verticalScrollBar()->setFocusPolicy(Qt::NoFocus);
270 horizontalScrollBar()->setFocusPolicy(Qt::NoFocus);
271
272 packet_list_header_ = new PacketListHeader(header()->orientation());
273 connect(packet_list_header_, &PacketListHeader::resetColumnWidth, this, &PacketList::setRecentColumnWidth);
274 connect(packet_list_header_, &PacketListHeader::updatePackets, this, &PacketList::updatePackets);
275 connect(packet_list_header_, &PacketListHeader::showColumnPreferences, this, &PacketList::showProtocolPreferences);
276 connect(packet_list_header_, &PacketListHeader::editColumn, this, &PacketList::editColumn);
277 connect(packet_list_header_, &PacketListHeader::columnsChanged, this, &PacketList::columnsChanged);
278 setHeader(packet_list_header_);
279
280 header()->setFirstSectionMovable(true);
281
282 setSelectionMode(QAbstractItemView::ExtendedSelection);
283
284 // Shrink down to a small but nonzero size in the main splitter.
285 int one_em = fontMetrics().height();
286 setMinimumSize(one_em, one_em);
287
288 overlay_sb_ = new OverlayScrollBar(Qt::Vertical, this);
289 setVerticalScrollBar(overlay_sb_);
290
291 header()->setSortIndicator(-1, Qt::AscendingOrder);
292
293 packet_list_model_ = new PacketListModel(this, cap_file_);
294 setModel(packet_list_model_);
295
296 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"
, 296))
;
297 gbl_cur_packet_list = this;
298
299 connect(packet_list_model_, &PacketListModel::goToPacket, this, [=](int packet) { goToPacket(packet); });
300 connect(mainApp, &MainApplication::addressResolutionChanged, this, &PacketList::redrawVisiblePacketsDontSelectCurrent);
301 connect(mainApp, &MainApplication::columnDataChanged, this, &PacketList::redrawVisiblePacketsDontSelectCurrent);
302 connect(mainApp, &MainApplication::preferencesChanged, this, [=]() {
303 /* The pref is a uint but QCache maxCost is a signed int (/
304 * qsizetype in Qt 6). Note that QAbstractItemModel row numbers
305 * are ints, not unsigned ints, so we're limited to INT_MAX
306 * rows anyway.
307 */
308 PacketListRecord::setMaxCache(prefs.gui_packet_list_cached_rows_max > INT_MAX2147483647 ? INT_MAX2147483647 : prefs.gui_packet_list_cached_rows_max);
309 if ((bool) (prefs.gui_packet_list_sortable) != isSortingEnabled()) {
310 setSortingEnabled(prefs.gui_packet_list_sortable);
311 }
312 });
313
314 connect(header(), &QHeaderView::sectionResized, this, &PacketList::sectionResized);
315 connect(header(), &QHeaderView::sectionMoved, this, &PacketList::sectionMoved);
316 // The frozen column view's own header is a separate QHeaderView and
317 // doesn't automatically follow this one's sort indicator (the arrow
318 // icon), so keep it mirrored whenever a click on the real header (not
319 // just sortByColumnFromOverlay()) changes it.
320 connect(header(), &QHeaderView::sortIndicatorChanged, this, [this](int column, Qt::SortOrder order) {
321 if (pinned_column_view_) {
322 pinned_column_view_->mirrorSortIndicator(column, order);
323 }
324 });
325
326 connect(verticalScrollBar(), &QScrollBar::actionTriggered, this, &PacketList::vScrollBarActionTriggered);
327
328 connect(packet_list_header_, &PacketListHeader::freezeColumnsToHere, this, &PacketList::setPinnedColumnBoundary);
329 connect(packet_list_header_, &PacketListHeader::unfreezeColumns, this, [this]() { setPinnedColumnBoundary(0); });
330
331 pinned_rows_model_ = new PinnedRowsModel(this);
332 pinned_rows_model_->setSourceModel(packet_list_model_);
333 // Filtering (modelReset) and sorting (layoutChanged) on the source
334 // model both need the pinned set re-resolved/re-ordered to match.
335 connect(packet_list_model_, &QAbstractItemModel::modelReset, this, &PacketList::updatePinnedRowVisibility);
336 connect(packet_list_model_, &QAbstractItemModel::layoutChanged, this, &PacketList::updatePinnedRowVisibility);
337
338 pinned_column_view_ = new PinnedColumnView(this, this);
339 pinned_column_view_->setModel(packet_list_model_);
340 pinned_column_view_->setSelectionModel(selectionModel());
341
342 connect(verticalScrollBar(), &QScrollBar::valueChanged, pinned_column_view_, &PinnedColumnView::setVerticalScrollValue);
343
344 // Own the font: seed it now and follow the FontManager for later changes.
345 connect(FontManager::instance(), &FontManager::monospaceFontChanged, this, &PacketList::setMonospaceFont);
346 connect(FontManager::instance(), &FontManager::applicationFontChanged, this, &PacketList::setRegularFont);
347 setMonospaceFont(FontManager::zoomedMonospaceFont());
348 setRegularFont(FontManager::zoomedFont());
349
350 // isActiveWindow()/QEvent::ActivationChange can lag behind the actual
351 // activation state on some platforms until the next event loop
352 // iteration, so also track focus moving to/from the application
353 // entirely to keep the pinned overlay views' selection color synced.
354 connect(qApp(static_cast<QApplication *>(QCoreApplication::instance
()))
, &QApplication::focusChanged, this, &PacketList::applicationFocusChanged);
355}
356
357void PacketList::setPinnedRowViews(PinnedRowView *row_view, PinnedRowView *corner_view)
358{
359 pinned_row_view_ = row_view;
360 pinned_row_corner_view_ = corner_view;
361
362 if (pinned_row_view_) {
363 pinned_row_view_->setModel(pinned_rows_model_);
364 connect(horizontalScrollBar(), &QScrollBar::valueChanged, pinned_row_view_, &PinnedRowView::setHorizontalScrollValue);
365 }
366 if (pinned_row_corner_view_) {
367 pinned_row_corner_view_->setModel(pinned_rows_model_);
368 }
369}
370
371QList<QTreeView *> PacketList::pinnedOverlayViews() const
372{
373 QList<QTreeView *> views;
374 if (pinned_column_view_) {
375 views << pinned_column_view_;
376 }
377 if (pinned_row_view_) {
378 views << pinned_row_view_;
379 }
380 if (pinned_row_corner_view_) {
381 views << pinned_row_corner_view_;
382 }
383 return views;
384}
385
386void PacketList::repaintPinnedOverlays()
387{
388 for (QTreeView *view : pinnedOverlayViews()) {
389 view->viewport()->update();
390 }
391}
392
393void PacketList::mirrorSectionWidthToOverlays(int column, int width)
394{
395 if (pinned_column_view_) {
396 pinned_column_view_->mirrorSectionWidth(column, width);
397 }
398 if (pinned_row_view_) {
399 pinned_row_view_->mirrorSectionWidth(column, width);
400 }
401 if (pinned_row_corner_view_) {
402 pinned_row_corner_view_->mirrorSectionWidth(column, width);
403 }
404}
405
406PacketList::~PacketList()
407{
408 if (finfo_array)
409 {
410 g_ptr_array_free(finfo_array, true);
411 }
412}
413
414void PacketList::scrollTo(const QModelIndex &index, QAbstractItemView::ScrollHint hint)
415{
416 /* QAbstractItemView doesn't have a way to indicate "auto scroll, but
417 * only vertically." So just restore the horizontal scroll value whenever
418 * it scrolls.
419 */
420 setUpdatesEnabled(false);
421 int horizVal = horizontalScrollBar()->value();
422 QTreeView::scrollTo(index, hint);
423 horizontalScrollBar()->setValue(horizVal);
424 setUpdatesEnabled(true);
425}
426
427void PacketList::colorsChanged()
428{
429 const QString c_active = "active";
430 const QString c_inactive = "!active";
431
432 const QString flat_style_format =
433 "QTreeView::item:selected:%1 {"
434 " color: %2;"
435 " background-color: %3;"
436 "}";
437
438 // Same as flat_style_format but with no :active/:!active selector at
439 // all, for the overlay panes (see applyOverlayActiveState()).
440 const QString plain_style_format =
441 "QTreeView::item:selected {"
442 " color: %1;"
443 " background-color: %2;"
444 "}";
445
446 ThemeManager *tm = ThemeManager::instance();
447 QColor active_bg = tm->color(ThemeManager::PacketsSelection);
448 QColor inactive_bg = tm->color(ThemeManager::PacketsInactive);
449 QColor active_fg = tm->color(ThemeManager::PacketsSelectionText);
450 QColor inactive_fg = tm->color(ThemeManager::PacketsInactiveText);
451
452 QString active_style = flat_style_format.arg(
453 c_active,
454 active_fg.name(),
455 active_bg.name());
456 QString inactive_style = flat_style_format.arg(
457 c_inactive,
458 inactive_fg.name(),
459 inactive_bg.name());
460
461 // Hover highlighting is painted manually in drawRow() (driven by
462 // hovered_frame_num_) rather than through a :hover stylesheet
463 // selector, since the mouse hovering a pinned overlay view needs to
464 // highlight the corresponding row in every pane, not just the one
465 // widget Qt considers "hovered".
466 QString full_style = active_style + inactive_style;
467
468 // Cache the plain flat colors (no :active/:!active selector -- see
469 // applyOverlayActiveState()) so window-activation changes can pick the
470 // right one without recomputing from ThemeManager every time.
471 overlay_active_flat_style_ = plain_style_format.arg(active_fg.name(), active_bg.name());
472 overlay_inactive_flat_style_ = plain_style_format.arg(inactive_fg.name(), inactive_bg.name());
473
474 set_style_sheet_ = true;
475 setStyleSheet(full_style);
476 set_style_sheet_ = false;
477
478 applyOverlayActiveState();
479#if \
480 ( \
481 (QT_VERSION((6<<16)|(10<<8)|(2)) >= QT_VERSION_CHECK(6, 5, 4)((6<<16)|(5<<8)|(4)) && QT_VERSION((6<<16)|(10<<8)|(2)) < QT_VERSION_CHECK(6, 6, 0)((6<<16)|(6<<8)|(0))) \
482 || (QT_VERSION((6<<16)|(10<<8)|(2)) >= QT_VERSION_CHECK(6, 6, 1)((6<<16)|(6<<8)|(1))) \
483 )
484 // https://bugreports.qt.io/browse/QTBUG-122109
485 // Affects Qt 6.5.4 and later, 6.6.1 and later.
486 // When setting the style sheet, all visible sections are set
487 // to the new minimum DefaultSectionSize (even if it hasn't
488 // changed.) So make sure the new widths aren't saved to recent
489 // and then restore from recent.
490 applyRecentColumnWidths();
491 setColumnVisibility();
492#endif
493}
494
495void PacketList::applyOverlayActiveState()
496{
497 // Match the plain flat_style_format(":active"/:!active") selectors
498 // applied to this view itself, which are keyed to whether THIS widget
499 // has focus (not just whether the window is active) -- Qt's
500 // :active/:!active tracks the same thing per-widget. Clicking into the
501 // packet details/bytes pane keeps the window active but moves focus
502 // away from PacketList, and the overlay panes should dim along with
503 // it, not stay "focused" on their own.
504 const QString &style = (hasFocus() && isActiveWindow()) ? overlay_active_flat_style_ : overlay_inactive_flat_style_;
505 if (pinned_column_view_) {
506 pinned_column_view_->setStyleSheet(style);
507 }
508 if (pinned_row_view_) {
509 pinned_row_view_->setStyleSheet(style);
510 }
511 if (pinned_row_corner_view_) {
512 pinned_row_corner_view_->setStyleSheet(style);
513 }
514}
515
516void PacketList::changeEvent(QEvent *event)
517{
518 QTreeView::changeEvent(event);
519
520 if (event->type() == QEvent::ActivationChange) {
521 applyOverlayActiveState();
522 }
523}
524
525void PacketList::applicationFocusChanged(QWidget *, QWidget *)
526{
527 applyOverlayActiveState();
528}
529
530QString PacketList::joinSummaryRow(QStringList col_parts, int row, SummaryCopyType type)
531{
532 QString copy_text;
533 switch (type) {
534 case CopyAsCSV:
535 copy_text = "\"";
536 copy_text += col_parts.join("\",\"");
537 copy_text += "\"";
538 break;
539 case CopyAsYAML:
540 copy_text = "----\n";
541 copy_text += QStringLiteral("# Packet %1 from %2\n")(QString(QtPrivate::qMakeStringPrivate(u"" "# Packet %1 from %2\n"
)))
.arg(row).arg(cap_file_->filename);
542 copy_text += "- ";
543 copy_text += col_parts.join("\n- ");
544 copy_text += "\n";
545 break;
546 case CopyAsText:
547 default:
548 copy_text = col_parts.join("\t");
549 }
550
551 return copy_text;
552}
553
554void PacketList::drawRow (QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
555{
556 QTreeView::drawRow(painter, option, index);
557
558 // The hover highlight is driven by hovered_frame_num_ rather than Qt's
559 // native per-widget hover state, since the mouse hovering a pinned
560 // overlay view needs to highlight this row here too -- native :hover
561 // styling only ever reacts to the mouse being over this specific
562 // widget. Painted even on a selected row so hover wins over selection,
563 // matching the pre-ThemeManager behavior (see the old :selected:hover
564 // stylesheet rule this replaced -- "background-color: ...;
565 // color: palette(text);"). Uses ColorUtils::paintFlatCell() rather
566 // than re-invoking each column's delegate with overridden palette
567 // roles -- QStyledItemDelegate::paint() calls initStyleOption(),
568 // which re-fetches Qt::BackgroundRole from the model and clobbers any
569 // backgroundBrush/palette override made beforehand, so a colored,
570 // marked, or ignored row's own background always won that fight and
571 // showed through instead of the flat hover color.
572 if (prefs.gui_packet_list_hover_style && index.isValid()) {
573 frame_data *fdata = getFDataForRow(index.row());
574 if (fdata && (int)fdata->num == hovered_frame_num_) {
575 QColor hover_bg = ColorUtils::hoverBackground();
576 QColor text_color = palette().color(QPalette::Text);
577
578 for (int visual_col = 0; visual_col < header()->count(); visual_col++) {
579 int logical_col = header()->logicalIndex(visual_col);
580 if (isColumnHidden(logical_col)) {
581 continue;
582 }
583 QModelIndex col_index = index.siblingAtColumn(logical_col);
584 QStyleOptionViewItem col_option = option;
585 col_option.rect = visualRect(col_index);
586 ColorUtils::paintFlatCell(painter, this, col_option, col_index, hover_bg, text_color);
587 }
588 }
589 }
590
591 if (prefs.gui_packet_list_separator) {
592 QRect rect = visualRect(index);
593
594 painter->setPen(QColor(Qt::white));
595 painter->drawLine(0, rect.y() + rect.height() - 1, width(), rect.y() + rect.height() - 1);
596 }
597}
598
599void PacketList::setProtoTree (ProtoTree *proto_tree) {
600 proto_tree_ = proto_tree;
601
602 connect(proto_tree_, &ProtoTree::goToPacket, this, [=](int packet) { goToPacket(packet); });
603 connect(proto_tree_, &ProtoTree::relatedFrame,
604 &related_packet_delegate_, &RelatedPacketDelegate::addRelatedFrame);
605}
606
607bool PacketList::uniqueSelectActive()
608{
609 return selectionModel()->selectedRows(0).count() == 1 ? true : false;
610}
611
612bool PacketList::multiSelectActive()
613{
614 return selectionModel()->selectedRows(0).count() > 1 ? true : false;
615}
616
617QList<int> PacketList::selectedRows(bool useFrameNum)
618{
619 QList<int> rows;
620 if (selectionModel() && selectionModel()->hasSelection())
621 {
622 foreach (QModelIndex idx, selectionModel()->selectedRows(0))for (auto _container_622 = QtPrivate::qMakeForeachContainer(selectionModel
()->selectedRows(0)); _container_622.i != _container_622.e
; ++_container_622.i) if (QModelIndex idx = *_container_622.i
; false) {} else
623 {
624 if (idx.isValid())
625 {
626 if (! useFrameNum)
627 rows << idx.row();
628 else if (useFrameNum)
629 {
630 frame_data * frame = getFDataForRow(idx.row());
631 if (frame)
632 rows << frame->num;
633 }
634 }
635 }
636 }
637 else if (currentIndex().isValid())
638 {
639 //
640 // XXX - will we ever have a current index but not a selection
641 // model?
642 //
643 if (! useFrameNum)
644 rows << currentIndex().row();
645 else
646 {
647 frame_data *frame = getFDataForRow(currentIndex().row());
648 if (frame)
649 rows << frame->num;
650 }
651 }
652
653 return rows;
654}
655
656int PacketList::currentFrameNum() const
657{
658 if (!cap_file_ || !cap_file_->current_frame) {
659 return -1;
660 }
661 return (int)cap_file_->current_frame->num;
662}
663
664void PacketList::selectionChanged (const QItemSelection & selected, const QItemSelection & deselected)
665{
666 QTreeView::selectionChanged(selected, deselected);
667
668 // The pinned overlay views share this view's selection model, but each
669 // is a separate QAbstractItemView with its own viewport; force a
670 // repaint there too so the highlight always shows on both sides of a
671 // freeze boundary, regardless of which view the selection change
672 // originated from.
673 repaintPinnedOverlays();
674
675 if (!cap_file_) return;
676
677 int row = -1;
678 static bool multiSelect = false;
679
680 if (selectionModel())
681 {
682 QModelIndexList selRows = selectionModel()->selectedRows(0);
683 if (selRows.count() > 1)
684 {
685 QList<int> rows;
686 foreach (QModelIndex idx, selRows)for (auto _container_686 = QtPrivate::qMakeForeachContainer(selRows
); _container_686.i != _container_686.e; ++_container_686.i) if
(QModelIndex idx = *_container_686.i; false) {} else
687 {
688 if (idx.isValid())
689 rows << idx.row();
690 }
691
692 emit framesSelected(rows);
693 emit fieldSelected(0);
694 cf_unselect_packet(cap_file_);
695
696 /* We have to repaint the content while changing state, as some delegates react to multi-select */
697 if (! multiSelect)
698 {
699 related_packet_delegate_.clear();
700 viewport()->update();
701 }
702
703 multiSelect = true;
704
705 return;
706 }
707 else if (selRows.count() > 0 && selRows.at(0).isValid())
708 {
709 multiSelect = false;
710 row = selRows.at(0).row();
711 }
712
713 /* Handling empty selection */
714 if (selRows.count() <= 0)
715 {
716 /* Nothing selected, but multiSelect is still active */
717 if (multiSelect)
718 {
719 multiSelect = false;
720 if (currentIndex().isValid())
721 {
722 selectionModel()->select(currentIndex(), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
723 return;
724 }
725 }
726 /* Nothing selected, so in WS <= 3.0 nothing was indicated as well */
727 else if (currentIndex().isValid())
728 {
729 setCurrentIndex(QModelIndex());
730 }
731 }
732 }
733
734 if (row < 0 || !packet_list_model_)
735 cf_unselect_packet(cap_file_);
736 else {
737 frame_data * fdata = packet_list_model_->getRowFdata(row);
738 cf_select_packet(cap_file_, fdata);
739 }
740
741 if (!in_history_ && cap_file_->current_frame) {
742 cur_history_++;
743 selection_history_.resize(cur_history_);
744 selection_history_.append(cap_file_->current_frame->num);
745 }
746
747 related_packet_delegate_.clear();
748
749 // The previous dissection state has been invalidated by cf_select_packet
750 // above, receivers must clear the previous state and apply the updated one.
751 emit framesSelected(QList<int>() << row);
752
753 if (!cap_file_->edt) {
754 viewport()->update();
755 emit fieldSelected(0);
756 return;
757 }
758
759 if (cap_file_->edt->tree) {
760 packet_info *pi = &cap_file_->edt->pi;
761 related_packet_delegate_.setCurrentFrame(pi->num);
762 conversation_t *conv = find_conversation_pinfo_ro(pi, 0);
763 if (conv) {
764 related_packet_delegate_.setConversation(conv);
765 }
766 viewport()->update();
767 }
768
769 if (cap_file_->search_in_progress) {
770 field_info *fi = NULL__null;
771
772 if (cap_file_->string && cap_file_->decode_data) {
773 // The tree where the target string matched one of the labels was discarded in
774 // match_protocol_tree() so we have to search again in the latest tree.
775 fi = cf_find_string_protocol_tree(cap_file_, cap_file_->edt->tree);
776 } else if (cap_file_->search_len != 0) {
777 // Find the finfo that corresponds to our byte.
778 // The match can span multiple fields (and a single byte can
779 // match more than one field.) Our behavior is to find the last
780 // field in the tree (so hopefully spanning fewer bytes) that
781 // matches the last byte in the search match.
782 // (regex search can find a zero length match not at the
783 // start of the frame if lookbehind is used, but
784 // proto_find_field_from_offset doesn't match such a field
785 // and it's not clear which field we would want to match.)
786 fi = proto_find_field_from_offset(cap_file_->edt->tree, cap_file_->search_pos + cap_file_->search_len - 1,
787 cap_file_->edt->tvb);
788 }
789
790 if (fi) {
791 FieldInformation finfo(fi, this);
792 emit fieldSelected(&finfo);
793 } else {
794 emit fieldSelected(0);
795 }
796 } else if (proto_tree_) {
797 proto_tree_->restoreSelectedField();
798 }
799}
800
801void PacketList::contextMenuEvent(QContextMenuEvent *event)
802{
803 const char *module_name = NULL__null;
804
805 if (finfo_array)
806 {
807 g_ptr_array_free(finfo_array, true);
808 finfo_array = NULL__null;
809 }
810
811 QModelIndex ctxIndex = indexAt(event->pos());
812
813 if (selectionModel() && selectionModel()->selectedRows(0).count() > 1)
814 selectionModel()->select(ctxIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
815
816 // ctxIndex is invalid when this is called via showContextMenuForFrame()
817 // for a pinned packet that's been filtered out of this view entirely
818 // (no row here to resolve via indexAt()/getRowFdata()) -- fall back to
819 // whatever frame was actually selected (by selectFrameFromOverlay(),
820 // just before this runs), which for that case is exactly the pinned
821 // packet's own frame, resolved independently of any row here.
822 frame_data *ctx_row_fdata = ctxIndex.isValid() ?
823 packet_list_model_->getRowFdata(ctxIndex.row()) :
824 (cap_file_ ? cap_file_->current_frame : nullptr);
825
826 // frameData will be owned by one of the submenus, see below.
827 FrameInformation * frameData =
828 new FrameInformation(new CaptureFile(this, cap_file_), ctx_row_fdata);
829
830 QMenu * ctx_menu = new QMenu(this);
831 ctx_menu->setAttribute(Qt::WA_DeleteOnClose);
832 // XXX We might want to reimplement setParent() and fill in the context
833 // menu there.
834 ctx_menu->addAction(window()->findChild<QAction *>("actionEditMarkSelected"));
835 ctx_menu->addAction(window()->findChild<QAction *>("actionEditIgnoreSelected"));
836 ctx_menu->addAction(window()->findChild<QAction *>("actionEditSetTimeReference"));
837 ctx_menu->addAction(window()->findChild<QAction *>("actionEditTimeShift"));
838 ctx_menu->addMenu(window()->findChild<QMenu *>("menuPacketComment"));
839
840 ctx_menu->addSeparator();
841
842 // Code for custom context menus from Lua's register_packet_menu()
843 MainWindow * mainWindow = mainApp->mainWindow();
844 // N.B., will only call for a single frame selection,
845 if (cap_file_ && cap_file_->edt && cap_file_->edt->tree) {
846 finfo_array = proto_all_finfos(cap_file_->edt->tree);
847 if (mainWindow) {
848 bool insertedPacketMenu = mainWindow->addPacketMenus(ctx_menu, finfo_array);
849 if (insertedPacketMenu) {
850 ctx_menu->addSeparator();
851 }
852 }
853 }
854
855 ctx_menu->addAction(window()->findChild<QAction *>("actionViewEditResolvedName"));
856
857 frame_data *ctx_fdata = ctx_row_fdata;
858 if (ctx_fdata) {
859 bool rowPinned = pinned_rows_model_->isPinned((int)ctx_fdata->num);
860 bool maxReached = !rowPinned && pinned_rows_model_->pinnedCount() >= PinnedRowsModel::kMaxPinnedRows;
861 QString pin_label = rowPinned ? tr("Unpin Row")
862 : maxReached ? tr("Pin Row to Top (max %1 reached)").arg(PinnedRowsModel::kMaxPinnedRows)
863 : tr("Pin Row to Top");
864 QAction *pin_action = ctx_menu->addAction(pin_label);
865 pin_action->setEnabled(!maxReached);
866 int ctx_frame_num = ctx_fdata->num;
867 connect(pin_action, &QAction::triggered, this, [this, rowPinned, ctx_frame_num]() {
868 if (rowPinned) {
869 unpinRow(ctx_frame_num);
870 } else {
871 pinRow(ctx_frame_num);
872 }
873 });
874 }
875
876 // Shown only for a context menu request that actually originated from
877 // the pinned-row strip (PinnedRowView) itself -- not the frozen-column
878 // overlay or a direct right-click on the primary view -- since
879 // scrolling the main view to a packet already visible there (or
880 // clearing every pinned row) doesn't make sense as an action offered
881 // from either of those.
882 if (ctx_from_pinned_row_strip_ && ctx_fdata) {
883 int ctx_frame_num = ctx_fdata->num;
884 QAction *goto_action = ctx_menu->addAction(tr("Go to Packet"));
885 connect(goto_action, &QAction::triggered, this, [this, ctx_frame_num]() {
886 goToPacket(ctx_frame_num);
887 });
888 }
889 if (ctx_from_pinned_row_strip_ && pinned_rows_model_->pinnedCount() > 0) {
890 QAction *unpin_all_action = ctx_menu->addAction(tr("Unpin All Rows"));
891 connect(unpin_all_action, &QAction::triggered, this, &PacketList::unpinAllRows);
892 }
893 // Reset for the next context menu request: showContextMenuForRow()/
894 // showContextMenuForFrame() set this immediately before calling here,
895 // but a direct right-click on the primary view calls this override
896 // straight from Qt's own event dispatch, bypassing both wrappers
897 // entirely -- so it can't be reset at entry the way ctx_column_ is,
898 // only after this one use.
899 ctx_from_pinned_row_strip_ = false;
900
901 ctx_menu->addSeparator();
902
903 QString selectedfilter = getFilterFromRowAndColumn(currentIndex());
904
905 if (! hasFocus() && cap_file_ && cap_file_->finfo_selected) {
906 char *tmp_field = proto_construct_match_selected_string(cap_file_->finfo_selected, cap_file_->edt);
907 selectedfilter = QString(tmp_field);
908 wmem_free(NULL__null, tmp_field);
909 }
910
911 bool have_filter_expr = !selectedfilter.isEmpty();
912 ctx_menu->addMenu(FilterAction::createFilterMenu(FilterAction::ActionApply, selectedfilter, have_filter_expr, ctx_menu));
913 ctx_menu->addMenu(FilterAction::createFilterMenu(FilterAction::ActionPrepare, selectedfilter, have_filter_expr, ctx_menu));
914
915 const char *conv_menu_name = "menuConversationFilter";
916 QMenu * main_menu_item = window()->findChild<QMenu *>(conv_menu_name);
917 conv_menu_.setTitle(main_menu_item->title());
918 conv_menu_.setObjectName(conv_menu_name);
919 ctx_menu->addMenu(&conv_menu_);
920
921 const char *colorize_menu_name = "menuColorizeConversation";
922 main_menu_item = window()->findChild<QMenu *>(colorize_menu_name);
923 colorize_menu_.setTitle(main_menu_item->title());
924 colorize_menu_.setObjectName(colorize_menu_name);
925 ctx_menu->addMenu(&colorize_menu_);
926
927 QMenu * submenu;
928 main_menu_item = window()->findChild<QMenu *>("menuSCTP");
929 if (main_menu_item) {
930 submenu = new QMenu(main_menu_item->title(), ctx_menu);
931 ctx_menu->addMenu(submenu);
932 submenu->addAction(window()->findChild<QAction *>("actionSCTPAnalyseThisAssociation"));
933 submenu->addAction(window()->findChild<QAction *>("actionSCTPShowAllAssociations"));
934 submenu->addAction(window()->findChild<QAction *>("actionSCTPFilterThisAssociation"));
935 }
936
937 main_menu_item = window()->findChild<QMenu *>("menuFollow");
938 if (main_menu_item) {
939 submenu = new QMenu(main_menu_item->title(), ctx_menu);
940 ctx_menu->addMenu(submenu);
941 foreach (FollowStreamAction *follow_action, main_menu_item->findChildren<FollowStreamAction *>())for (auto _container_941 = QtPrivate::qMakeForeachContainer(main_menu_item
->findChildren<FollowStreamAction *>()); _container_941
.i != _container_941.e; ++_container_941.i) if (FollowStreamAction
*follow_action = *_container_941.i; false) {} else
{
942 /* XXX: We could, like the prefs above, walk the protocols/layers
943 * and add the follow actions in the order they appear in the packet.
944 */
945 if (follow_action->isEnabled()) {
946 submenu->addAction(follow_action);
947 }
948 }
949 }
950
951 ctx_menu->addSeparator();
952
953 main_menu_item = window()->findChild<QMenu *>("menuEditCopy");
954 submenu = new QMenu(main_menu_item->title(), ctx_menu);
955 submenu->setToolTipsVisible(true);
956 ctx_menu->addMenu(submenu);
957
958 QAction * action = submenu->addAction(tr("Summary as Text"));
959 action->setData(CopyAsText);
960 connect(action, &QAction::triggered, this, &PacketList::copySummary);
961 action = submenu->addAction(tr("…as CSV"));
962 action->setData(CopyAsCSV);
963 connect(action, &QAction::triggered, this, &PacketList::copySummary);
964 action = submenu->addAction(tr("…as YAML"));
965 action->setData(CopyAsYAML);
966 connect(action, &QAction::triggered, this, &PacketList::copySummary);
967 action = submenu->addAction(tr("…as HTML"));
968 action->setData(CopyAsHTML);
969 connect(action, &QAction::triggered, this, &PacketList::copySummary);
970 submenu->addSeparator();
971
972 submenu->addAction(window()->findChild<QAction *>("actionEditCopyAsFilter"));
973 submenu->addSeparator();
974
975 QActionGroup * copyEntries = DataPrinter::copyActions(this, frameData);
976 submenu->addActions(copyEntries->actions());
977 copyEntries->setParent(submenu);
978 frameData->setParent(submenu);
979
980 if (application_flavor_is_wireshark()) {
981 /* i.e., Wireshark only */
982 ctx_menu->addSeparator();
983 QMenu *proto_prefs_menus = new QMenu(ProtocolPreferencesMenu::tr("Protocol Preferences"), ctx_menu);
984
985 if (cap_file_ && cap_file_->edt && cap_file_->edt->tree) {
986 QList<QString> added_proto_prefs;
987 // N.B. finfo_array will be assigned above
988 for (unsigned i = 0; i < finfo_array->len; i++) {
989 field_info *fi = (field_info *)g_ptr_array_index (finfo_array, i)((finfo_array)->pdata)[i];
990 const header_field_info *hfinfo = fi->hfinfo;
991
992 if (prefs_is_registered_protocol(hfinfo->abbrev)) {
993 if (hfinfo->parent == -1) {
994 module_name = hfinfo->abbrev;
995 } else {
996 module_name = proto_registrar_get_abbrev(hfinfo->parent);
997 }
998
999 if (added_proto_prefs.contains(module_name)) {
1000 continue;
1001 }
1002
1003 ProtocolPreferencesMenu *proto_prefs_menu = new ProtocolPreferencesMenu(hfinfo->name, module_name, proto_prefs_menus);
1004
1005 connect(proto_prefs_menu, &ProtocolPreferencesMenu::showProtocolPreferences,
1006 this, &PacketList::showProtocolPreferences);
1007 connect(proto_prefs_menu, SIGNAL(editProtocolPreference(pref_t*,module_t*))qFlagLocation("2" "editProtocolPreference(pref_t*,module_t*)"
"\0" "ui/qt/packet_list.cpp" ":" "1007")
,
1008 this, SIGNAL(editProtocolPreference(pref_t*,module_t*))qFlagLocation("2" "editProtocolPreference(pref_t*,module_t*)"
"\0" "ui/qt/packet_list.cpp" ":" "1008")
);
1009
1010 proto_prefs_menus->addMenu(proto_prefs_menu);
1011 added_proto_prefs << module_name;
1012 }
1013 }
1014 }
1015 ctx_menu->addMenu(proto_prefs_menus);
1016 action = ctx_menu->addAction(tr("Decode As…"));
1017 action->setProperty("create_new", QVariant(true));
1018 connect(action, &QAction::triggered, this, &PacketList::ctxDecodeAsDialog);
1019 // "Print" not ported intentionally
1020 action = window()->findChild<QAction *>("actionViewShowPacketInNewWindow");
1021 ctx_menu->addAction(action);
1022 }
1023
1024 // Set menu sensitivity for the current column and set action data.
1025 if (frameData)
1026 emit framesSelected(QList<int>() << frameData->frameNum());
1027 else
1028 emit framesSelected(QList<int>());
1029
1030 ctx_menu->popup(event->globalPos());
1031}
1032
1033void PacketList::ctxDecodeAsDialog()
1034{
1035 QAction *da_action = qobject_cast<QAction*>(sender());
1036 if (! da_action)
1037 return;
1038 bool create_new = da_action->property("create_new").toBool();
1039
1040 DecodeAsDialog *da_dialog = new DecodeAsDialog(this, cap_file_, create_new);
1041 connect(da_dialog, &DecodeAsDialog::destroyed, mainApp, &MainApplication::flushAppSignals);
1042 da_dialog->setWindowModality(Qt::ApplicationModal);
1043 da_dialog->setAttribute(Qt::WA_DeleteOnClose);
1044 da_dialog->show();
1045}
1046
1047void PacketList::timerEvent(QTimerEvent *event)
1048{
1049 if (event->timerId() == overlay_timer_id_) {
1050 if (!capture_in_progress_ && model() != nullptr) {
1051 if (create_near_overlay_) drawNearOverlay();
1052 if (create_far_overlay_) drawFarOverlay();
1053 }
1054 } else if (event->timerId() == turbo_timer_id_) {
1055 QKeyEvent turbo_step(QEvent::KeyPress, turbo_key_, Qt::NoModifier, QString(), true);
1056 QTreeView::keyPressEvent(&turbo_step);
1057 } else {
1058 QTreeView::timerEvent(event);
1059 }
1060}
1061
1062void PacketList::paintEvent(QPaintEvent *event)
1063{
1064 // XXX This is overkill, but there are quite a few events that
1065 // require a new overlay, e.g. page up/down, scrolling, column
1066 // resizing, etc.
1067 create_near_overlay_ = true;
1068 QTreeView::paintEvent(event);
1069}
1070
1071void PacketList::mousePressEvent(QMouseEvent *event)
1072{
1073 QTreeView::mousePressEvent(event);
1074
1075 QModelIndex curIndex = indexAt(event->pos());
1076 mouse_pressed_at_ = curIndex;
1077
1078 bool midButton = (event->buttons() & Qt::MiddleButton) == Qt::MiddleButton;
1079 if (midButton && cap_file_ && packet_list_model_)
1080 {
1081 packet_list_model_->toggleFrameMark(QModelIndexList() << curIndex);
1082
1083 // Make sure the packet list's frame.marked related field text is updated.
1084 redrawVisiblePackets();
1085
1086 create_far_overlay_ = true;
1087 packets_bar_update();
1088 }
1089}
1090
1091void PacketList::mouseReleaseEvent(QMouseEvent *event) {
1092 QTreeView::mouseReleaseEvent(event);
1093
1094 mouse_pressed_at_ = QModelIndex();
1095}
1096
1097// The pinned overlay views (PinnedColumnView/PinnedRowView) are separate
1098// QTreeViews that only ever show a slice of the real content, laid out
1099// independently of the primary view. Translating pixel coordinates from an
1100// overlay's click into this view's coordinate space is unreliable -- their
1101// row geometry can drift by a row even when the two appear visually
1102// aligned (e.g. differing sub-pixel scroll remainders). Instead, the
1103// overlay resolves the row itself via its own (always-correct, since it's
1104// local) indexAt(), and these entry points act on that row/index directly
1105// within this view, exactly as a real click here would.
1106void PacketList::selectRowFromOverlay(int row, int column, Qt::MouseButtons buttons)
1107{
1108 QModelIndex index = model()->index(row, column);
1109 if (!index.isValid()) {
1110 return;
1111 }
1112
1113 // Selecting a pinned packet (the whole point of pinning it) shouldn't
1114 // yank the primary view's scroll position to wherever that packet
1115 // happens to be -- setCurrentIndex() below scrolls to make the new
1116 // current index visible (QAbstractItemView's normal behavior for
1117 // e.g. arrow-key navigation), which is exactly what a click in the
1118 // pinned strip should NOT do. Save and restore the vertical scroll
1119 // position around it, the same way scrollTo() already does for the
1120 // horizontal one.
1121 int vert_scroll_value = verticalScrollBar()->value();
1122
1123 mouse_pressed_at_ = index;
1124 setCurrentIndex(index);
1125 verticalScrollBar()->setValue(vert_scroll_value);
1126 selectionModel()->select(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
1127 // Keep keyboard focus on the primary view so the selection highlight
1128 // always renders in its "active" color, regardless of which pane the
1129 // click that produced this selection landed in.
1130 setFocus();
1131
1132 // The pinned-row views draw their own selection highlight by reading
1133 // currentFrameNum()/selectedRows() directly (see PinnedRowView::drawRow()),
1134 // rather than sharing this view's QItemSelectionModel, so updating that
1135 // state above doesn't itself trigger a repaint there -- request one
1136 // explicitly, the same way setHoveredFrameNum() already does for hover.
1137 repaintPinnedOverlays();
1138
1139 if (buttons & Qt::MiddleButton) {
1140 packet_list_model_->toggleFrameMark(QModelIndexList() << index);
1141 redrawVisiblePackets();
1142 create_far_overlay_ = true;
1143 packets_bar_update();
1144 }
1145}
1146
1147void PacketList::selectFrameFromOverlay(int frame_num)
1148{
1149 if (!cap_file_ || !packet_list_model_) {
1150 return;
1151 }
1152
1153 PacketListRecord *record = packet_list_model_->physicalRecordForFrameNum(frame_num);
1154 frame_data *fdata = record ? record->frameData() : nullptr;
1155 if (!fdata) {
1156 return;
1157 }
1158
1159 // Clear any real selection in this view's own model: the frame being
1160 // selected may not even have a row here (it can be filtered out), so
1161 // there's no index to select instead. Mirrors the "nothing selected"
1162 // path selectionChanged() takes for row < 0.
1163 selectionModel()->clearSelection();
1164 setCurrentIndex(QModelIndex());
1165 mouse_pressed_at_ = QModelIndex();
1166 setFocus();
1167
1168 // The pinned-row views draw their own selection highlight by reading
1169 // currentFrameNum()/selectedRows() directly (see PinnedRowView::drawRow()),
1170 // rather than sharing this view's QItemSelectionModel, so updating that
1171 // state above doesn't itself trigger a repaint there -- request one
1172 // explicitly, the same way setHoveredFrameNum() already does for hover.
1173 repaintPinnedOverlays();
1174
1175 // cf_select_packet() works directly against the capture file's own
1176 // frame array and is independent of the display filter/QModelIndex
1177 // entirely -- unlike selectionChanged()'s row-based path, which can
1178 // only ever resolve a frame that currently has a row in this view.
1179 cf_select_packet(cap_file_, fdata);
1180
1181 if (!in_history_ && cap_file_->current_frame) {
1182 cur_history_++;
1183 selection_history_.resize(cur_history_);
1184 selection_history_.append(cap_file_->current_frame->num);
1185 }
1186
1187 related_packet_delegate_.clear();
1188
1189 // The previous dissection state has been invalidated by
1190 // cf_select_packet() above; receivers must clear the previous state
1191 // and apply the updated one. The emitted value is a frame number
1192 // here, not a row -- consistent with contextMenuEvent()'s own
1193 // framesSelected() emit further down, and safe because every
1194 // receiver (DataSourceTab, ProtoTree, MainStatusBar, etc.) only
1195 // checks the list's count and then reads cap_file_->edt/current_frame
1196 // directly, never the integer values themselves.
1197 emit framesSelected(QList<int>() << frame_num);
1198
1199 if (!cap_file_->edt) {
1200 viewport()->update();
1201 emit fieldSelected(0);
1202 return;
1203 }
1204
1205 if (cap_file_->edt->tree) {
1206 packet_info *pi = &cap_file_->edt->pi;
1207 related_packet_delegate_.setCurrentFrame(pi->num);
1208 conversation_t *conv = find_conversation_pinfo_ro(pi, 0);
1209 if (conv) {
1210 related_packet_delegate_.setConversation(conv);
1211 }
1212 viewport()->update();
1213 }
1214
1215 if (proto_tree_) {
1216 proto_tree_->restoreSelectedField();
1217 } else {
1218 emit fieldSelected(0);
1219 }
1220}
1221
1222void PacketList::showContextMenuForRow(int row, const QPoint &global_pos, bool from_pinned_row_strip)
1223{
1224 QModelIndex index = model()->index(row, 0);
1225 if (!index.isValid()) {
1226 return;
1227 }
1228
1229 ctx_from_pinned_row_strip_ = from_pinned_row_strip;
1230
1231 // visualRect() is this view's own geometry query, so it can't drift
1232 // the way a translated cross-view pixel position could; it guarantees
1233 // contextMenuEvent()'s own indexAt() resolves back to this exact row.
1234 QPoint local_pos = visualRect(index).center();
1235 QContextMenuEvent translated(QContextMenuEvent::Mouse, local_pos, global_pos);
1236 contextMenuEvent(&translated);
1237}
1238
1239void PacketList::showContextMenuForFrame(int frame_num, const QPoint &global_pos, bool from_pinned_row_strip)
1240{
1241 ctx_from_pinned_row_strip_ = from_pinned_row_strip;
1242
1243 // Select the frame first so cap_file_->current_frame/edt reflect it --
1244 // contextMenuEvent() falls back to cap_file_->current_frame whenever
1245 // indexAt() resolves to an invalid index (see below), which is
1246 // exactly what happens for a pinned packet with no row in this view
1247 // at all (i.e. filtered out).
1248 selectFrameFromOverlay(frame_num);
1249
1250 // A position guaranteed to resolve to an invalid index via
1251 // indexAt(), same idea as showContextMenuForRow() using a real row's
1252 // visualRect() to guarantee the opposite. contextMenuEvent() then
1253 // uses the ctx_row_fdata fallback to cap_file_->current_frame set by
1254 // selectFrameFromOverlay() above instead of a row-based lookup.
1255 QPoint local_pos(-1, -1);
1256 QContextMenuEvent translated(QContextMenuEvent::Mouse, local_pos, global_pos);
1257 contextMenuEvent(&translated);
1258}
1259
1260// header_pos must already be in packet_list_header_'s (the real, primary
1261// header's) own coordinate space by the time it reaches each forwarder
1262// below -- every caller (PinnedColumnHeader, and PacketListPane's
1263// duplicate_header_corner_/duplicate_header_main_ event filter) is
1264// responsible for translating its own local position into that space
1265// first, since each has a different relationship to it (PinnedColumnHeader
1266// and duplicate_header_corner_ both start at the frozen boundary the same
1267// way packet_list_header_'s own unscrolled columns [0, boundary) do;
1268// duplicate_header_main_ instead starts at the boundary itself and must
1269// add its own width). See PacketList::frozenHeaderPosToReal() for the
1270// shared translation helper used by PinnedColumnHeader.
1271QPoint PacketList::frozenHeaderPosToReal(const QPoint &frozen_pos) const
1272{
1273 int logical_index = pinned_column_view_->header()->logicalIndexAt(frozen_pos);
1274 if (logical_index < 0) {
1275 return frozen_pos;
1276 }
1277 int real_x = packet_list_header_->sectionViewportPosition(logical_index)
1278 + (frozen_pos.x() - pinned_column_view_->header()->sectionViewportPosition(logical_index));
1279 return QPoint(real_x, frozen_pos.y());
1280}
1281
1282void PacketList::forwardHeaderContextMenu(QContextMenuEvent *event, const QPoint &header_pos)
1283{
1284 // event->globalPos() (from the original click, wherever it actually
1285 // happened on screen) rather than packet_list_header_->mapToGlobal(
1286 // header_pos): the latter assumes the real header is on-screen at its
1287 // usual position, which isn't true when this request originated from
1288 // duplicate_header_ (PacketListPane's stand-in header shown above the
1289 // pinned-rows strip while the real one is hidden) -- that would pop
1290 // the menu up at the real header's location instead of where the user
1291 // actually right-clicked.
1292 QContextMenuEvent translated(event->reason(), header_pos, event->globalPos(), event->modifiers());
1293 packet_list_header_->showContextMenuAt(&translated);
1294}
1295
1296void PacketList::forwardHeaderMousePress(QMouseEvent *event, const QPoint &header_pos)
1297{
1298 // Temporarily disable click-to-sort on the real header: forwarding
1299 // press/release here is only meant to drive its resize-drag state
1300 // machine (needed so a frozen column's resize actually changes the
1301 // shared column width). QHeaderView's mouseReleaseEvent does its own
1302 // native click-to-sort detection as a side effect of the same event,
1303 // which would otherwise double up with the explicit
1304 // sortByColumnFromOverlay() call and cancel it out.
1305 packet_list_header_->setSectionsClickable(false);
1306 QMouseEvent translated(event->type(), header_pos, packet_list_header_->mapToGlobal(header_pos),
1307 event->button(), event->buttons(), event->modifiers());
1308 packet_list_header_->forwardMousePressEvent(&translated);
1309}
1310
1311void PacketList::forwardHeaderMouseMove(QMouseEvent *event, const QPoint &header_pos)
1312{
1313 QMouseEvent translated(event->type(), header_pos, packet_list_header_->mapToGlobal(header_pos),
1314 event->button(), event->buttons(), event->modifiers());
1315 packet_list_header_->forwardMouseMoveEvent(&translated);
1316}
1317
1318void PacketList::forwardHeaderMouseRelease(QMouseEvent *event, const QPoint &header_pos)
1319{
1320 QMouseEvent translated(event->type(), header_pos, packet_list_header_->mapToGlobal(header_pos),
1321 event->button(), event->buttons(), event->modifiers());
1322 packet_list_header_->forwardMouseReleaseEvent(&translated);
1323 packet_list_header_->setSectionsClickable(true);
1324}
1325
1326void PacketList::forwardWheelEvent(QWheelEvent *event)
1327{
1328 QTreeView::wheelEvent(event);
1329}
1330
1331void PacketList::sortByColumnFromOverlay(int column)
1332{
1333 if (!isSortingEnabled()) {
1334 return;
1335 }
1336
1337 Qt::SortOrder order = Qt::AscendingOrder;
1338 if (header()->sortIndicatorSection() == column) {
1339 order = (header()->sortIndicatorOrder() == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder;
1340 }
1341 header()->setSortIndicator(column, order);
1342
1343 // The frozen column view's own header is a separate QHeaderView, so it
1344 // needs its sort indicator (the arrow icon) set explicitly to match --
1345 // it doesn't automatically follow the primary header's indicator.
1346 if (pinned_column_view_) {
1347 pinned_column_view_->mirrorSortIndicator(column, order);
1348 }
1349}
1350
1351void PacketList::mouseMoveEvent (QMouseEvent *event)
1352{
1353 QModelIndex curIndex = indexAt(event->pos());
1354 frame_data *hovered_fdata = curIndex.isValid() ? getFDataForRow(curIndex.row()) : nullptr;
1
'?' condition is true
1355 int new_hovered_frame_num = hovered_fdata ? (int)hovered_fdata->num : -1;
2
Assuming 'hovered_fdata' is null
3
'?' condition is false
1356 if (new_hovered_frame_num != hovered_frame_num_) {
4
Assuming 'new_hovered_frame_num' is equal to field 'hovered_frame_num_'
1357 hovered_frame_num_ = new_hovered_frame_num;
1358 viewport()->update();
1359 repaintPinnedOverlays();
1360 }
1361
1362 if (event->buttons() & Qt::LeftButton && curIndex.isValid() && curIndex == mouse_pressed_at_)
5
Assuming the condition is true
6
Taking true branch
1363 {
1364 ctx_column_ = curIndex.column();
1365 QMimeData * mimeData = new QMimeData();
1366 DragLabel * drag_label = nullptr;
1367
1368 QString filter = getFilterFromRowAndColumn(curIndex);
1369 QList<int> rows = selectedRows();
1370 if (rows.count() > 1)
7
Assuming the condition is false
8
Taking false branch
1371 {
1372 QStringList entries;
1373 foreach (int row, rows)for (auto _container_1373 = QtPrivate::qMakeForeachContainer(
rows); _container_1373.i != _container_1373.e; ++_container_1373
.i) if (int row = *_container_1373.i; false) {} else
1374 {
1375 QModelIndex idx = model()->index(row, 0);
1376 if (! idx.isValid())
1377 continue;
1378
1379 QString entry = createSummaryText(idx, CopyAsText);
1380 entries << entry;
1381 }
1382
1383 if (entries.count() > 0)
1384 mimeData->setText(entries.join("\n"));
1385 }
1386 else if (! filter.isEmpty())
9
Assuming the condition is true
10
Taking true branch
1387 {
1388 QString abbrev;
1389 QString name = model()->headerData(curIndex.column(), header()->orientation()).toString();
1390
1391 if (! filter.isEmpty())
11
Assuming the condition is false
12
Taking false branch
1392 {
1393 abbrev = filter.left(filter.indexOf(' '));
1394 }
1395 else
1396 {
1397 filter = model()->data(curIndex).toString().toLower();
1398 abbrev = filter;
1399 }
1400
1401 mimeData->setText(filter);
1402
1403 QJsonObject filterData;
1404 filterData["filter"] = filter;
1405 filterData["name"] = abbrev;
1406 filterData["description"] = name;
1407
1408 mimeData->setData(WiresharkMimeData::DisplayFilterMimeType, QJsonDocument(filterData).toJson());
1409 drag_label = new DragLabel(QStringLiteral("%1\n%2")(QString(QtPrivate::qMakeStringPrivate(u"" "%1\n%2"))).arg(name, abbrev), this);
13
Memory is allocated
1410 }
1411 else
1412 {
1413 QString text = model()->data(curIndex).toString();
1414 if (! text.isEmpty())
1415 mimeData->setText(text);
1416 }
1417
1418 if (mimeData->hasText() || mimeData->hasFormat(WiresharkMimeData::DisplayFilterMimeType))
14
Assuming the condition is false
15
Assuming the condition is false
16
Taking false branch
1419 {
1420 QDrag * drag = new QDrag(this);
1421 drag->setMimeData(mimeData);
1422 if (drag_label)
1423 {
1424 qreal dpr = window()->windowHandle()->devicePixelRatio();
1425 QPixmap pixmap= QPixmap(drag_label->size() * dpr);
1426 pixmap.setDevicePixelRatio(dpr);
1427 drag_label->render(&pixmap);
1428 drag->setPixmap(pixmap);
1429 delete drag_label;
1430 }
1431
1432 drag->exec(Qt::CopyAction);
1433 }
1434 else
1435 {
1436 delete mimeData;
17
Potential leak of memory pointed to by 'drag_label'
1437 }
1438 }
1439}
1440
1441void PacketList::leaveEvent(QEvent *event)
1442{
1443 QTreeView::leaveEvent(event);
1444
1445 if (hovered_frame_num_ != -1) {
1446 hovered_frame_num_ = -1;
1447 viewport()->update();
1448 repaintPinnedOverlays();
1449 }
1450}
1451
1452void PacketList::setHoveredRowFromOverlay(int row)
1453{
1454 frame_data *fdata = (row >= 0) ? getFDataForRow(row) : nullptr;
1455 setHoveredFrameNum(fdata ? (int)fdata->num : -1);
1456}
1457
1458void PacketList::setHoveredFrameNum(int frame_num)
1459{
1460 if (frame_num == hovered_frame_num_) {
1461 return;
1462 }
1463
1464 hovered_frame_num_ = frame_num;
1465 viewport()->update();
1466 repaintPinnedOverlays();
1467}
1468
1469void PacketList::keyPressEvent(QKeyEvent *event)
1470{
1471 // XXX Add support for Qt::Key_F7 and Qt::Key_F8
1472 bool nav_key = (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down);
1473
1474 if (nav_key && event->isAutoRepeat()) {
1475 Qt::Key key = static_cast<Qt::Key>(event->key());
1476
1477 if (turbo_timer_id_ != 0 && key == turbo_key_) {
1478 // We're handling autorepeat ourselves.
1479 event->accept();
1480 return;
1481 }
1482
1483 if (turbo_timer_id_ == 0 && key == held_key_ && key_hold_elapsed_.isValid() &&
1484 key_hold_elapsed_.hasExpired(turbo_activation_delay_)) {
1485 turbo_key_ = key;
1486 turbo_timer_id_ = startTimer(turbo_nav_interval_);
1487 event->accept();
1488 return;
1489 }
1490 }
1491
1492 QTreeView::keyPressEvent(event);
1493
1494 if (nav_key && !event->isAutoRepeat()) {
1495 held_key_ = static_cast<Qt::Key>(event->key());
1496 key_hold_elapsed_.start();
1497 }
1498
1499 if (event->matches(QKeySequence::Copy))
1500 {
1501 QStringList content, htmlContent;
1502 if (model() && selectionModel() && selectionModel()->hasSelection())
1503 {
1504 QList<int> rows;
1505 QModelIndexList selRows = selectionModel()->selectedRows(0);
1506 foreach(QModelIndex row, selRows)for (auto _container_1506 = QtPrivate::qMakeForeachContainer(
selRows); _container_1506.i != _container_1506.e; ++_container_1506
.i) if (QModelIndex row = *_container_1506.i; false) {} else
1507 rows.append(row.row());
1508
1509 QStringList hdr_parts;
1510 QList<int> align_parts, size_parts;
1511
1512 switch (prefs.gui_packet_list_copy_format_options_for_keyboard_shortcut) {
1513 case COPY_FORMAT_TEXT:
1514 case COPY_FORMAT_HTML:
1515 if (prefs.gui_packet_list_copy_text_with_aligned_columns) {
1516 hdr_parts = createHeaderPartsForAligned();
1517 align_parts = createAlignmentPartsForAligned();
1518 size_parts = createSizePartsForAligned(false, hdr_parts, rows);
1519 }
1520 if (prefs.gui_packet_list_copy_format_options_for_keyboard_shortcut == COPY_FORMAT_HTML) {
1521 htmlContent << createDefaultStyleForHtml();
1522 htmlContent << createOpeningTagForHtml();
1523 }
1524 break;
1525 case COPY_FORMAT_CSV:
1526 case COPY_FORMAT_YAML:
1527 break;
1528 }
1529
1530 QList<QStringList> entries;
1531 foreach(int row, rows)for (auto _container_1531 = QtPrivate::qMakeForeachContainer(
rows); _container_1531.i != _container_1531.e; ++_container_1531
.i) if (int row = *_container_1531.i; false) {} else
1532 {
1533 QModelIndex idx = model()->index(row, 0);
1534 if (! idx.isValid())
1535 continue;
1536
1537 switch (prefs.gui_packet_list_copy_format_options_for_keyboard_shortcut) {
1538 case COPY_FORMAT_TEXT:
1539 case COPY_FORMAT_HTML:
1540 if (prefs.gui_packet_list_copy_text_with_aligned_columns)
1541 content << createSummaryForAligned(idx, align_parts, size_parts);
1542 else
1543 content << createSummaryText(idx, CopyAsText);
1544 if (prefs.gui_packet_list_copy_format_options_for_keyboard_shortcut == COPY_FORMAT_HTML)
1545 htmlContent << createSummaryForHtml(idx);
1546 break;
1547 case COPY_FORMAT_CSV:
1548 content << createSummaryText(idx, CopyAsCSV);
1549 break;
1550 case COPY_FORMAT_YAML:
1551 content << createSummaryText(idx, CopyAsYAML);
1552 break;
1553 }
1554 }
1555 }
1556
1557 if (prefs.gui_packet_list_copy_format_options_for_keyboard_shortcut == COPY_FORMAT_HTML) {
1558 // htmlContent will never be empty as they will always have style and table tags
1559 QMimeData *mimeData = new QMimeData;
1560 htmlContent << createClosingTagForHtml();
1561 mimeData->setHtml(htmlContent.join('\n'));
1562 mimeData->setText(content.join('\n').append("\n"));
1563 mainApp->clipboard()->setMimeData(mimeData, QClipboard::Clipboard);
1564 }
1565 else {
1566 if (content.count() > 0) {
1567 QString copy_text;
1568 if (prefs.gui_packet_list_copy_format_options_for_keyboard_shortcut == COPY_FORMAT_YAML) {
1569 copy_text = content.join("");
1570 }
1571 else {
1572 copy_text = content.join("\n");
1573 copy_text += "\n";
1574 }
1575 mainApp->clipboard()->setText(copy_text);
1576 }
1577 }
1578 }
1579}
1580
1581void PacketList::keyReleaseEvent(QKeyEvent *event)
1582{
1583 if (!event->isAutoRepeat() && event->key() == held_key_) {
1584 if (turbo_timer_id_ != 0 && event->key() == turbo_key_) {
1585 killTimer(turbo_timer_id_);
1586 turbo_timer_id_ = 0;
1587 }
1588 held_key_ = Qt::Key(0);
1589 key_hold_elapsed_.invalidate();
1590 }
1591
1592 QTreeView::keyReleaseEvent(event);
1593}
1594
1595void PacketList::focusInEvent(QFocusEvent *event)
1596{
1597 QTreeView::focusInEvent(event);
1598
1599 if (event->reason() == Qt::TabFocusReason || event->reason() == Qt::BacktabFocusReason) {
1600 if (model() && model()->rowCount() > 0 && selectionModel()) {
1601 if (!selectionModel()->hasSelection()) {
1602 QModelIndex first = model()->index(0, 0);
1603 if (first.isValid()) {
1604 selectionModel()->setCurrentIndex(first, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
1605 setCurrentIndex(first);
1606 }
1607 }
1608
1609 // ALWAYS scroll to the current index if we have one
1610 if (currentIndex().isValid()) {
1611 scrollTo(currentIndex());
1612 }
1613 }
1614 }
1615}
1616
1617void PacketList::focusOutEvent(QFocusEvent *event)
1618{
1619 if (turbo_timer_id_ != 0) {
1620 killTimer(turbo_timer_id_);
1621 turbo_timer_id_ = 0;
1622 }
1623 held_key_ = Qt::Key(0);
1624 key_hold_elapsed_.invalidate();
1625
1626 QTreeView::focusOutEvent(event);
1627}
1628
1629void PacketList::resizeEvent(QResizeEvent *event)
1630{
1631 create_near_overlay_ = true;
1632 create_far_overlay_ = true;
1633 QTreeView::resizeEvent(event);
1634 layoutPinnedOverlays();
1635}
1636
1637void PacketList::setColumnVisibility()
1638{
1639 set_column_visibility_ = true;
1640 for (unsigned i = 0; i < prefs.num_cols; i++) {
1641 bool hidden = get_column_visible(i) ? false : true;
1642 bool frozen = isColumnFrozen((int)i, pinned_column_boundary_);
1643 setColumnHidden(i, hidden);
1644 if (pinned_column_view_) {
1645 pinned_column_view_->setColumnHidden(i, hidden || !frozen);
1646 }
1647 if (pinned_row_view_) {
1648 pinned_row_view_->setColumnHidden(i, hidden || frozen);
1649 }
1650 if (pinned_row_corner_view_) {
1651 pinned_row_corner_view_->setColumnHidden(i, hidden || !frozen);
1652 }
1653 emit columnHiddenChanged(i, hidden);
1654 }
1655 setColumnDelegate();
1656 set_column_visibility_ = false;
1657}
1658
1659void PacketList::setColumnDelegate()
1660{
1661 for (unsigned i = 0; i < prefs.num_cols; i++) {
1662 setItemDelegateForColumn(i, nullptr); // Reset all delegates
1663 }
1664
1665 // Multi-color delegate takes precedence over related packet delegate (row stripes only, not scrollbar-only mode)
1666 if (prefs.gui_packet_list_multi_color_mode == PACKET_LIST_MULTI_COLOR_MODE_FULL ||
1667 prefs.gui_packet_list_multi_color_mode == PACKET_LIST_MULTI_COLOR_MODE_SHIFT_RIGHT) {
1668 for (unsigned i = 0; i < prefs.num_cols; i++) {
1669 if (get_column_visible(i)) {
1670 setItemDelegateForColumn(i, &multi_color_delegate_);
1671 }
1672 }
1673 }
1674 else if (prefs.gui_packet_list_show_related) {
1675 for (unsigned i = 0; i < prefs.num_cols; i++) {
1676 if (get_column_visible(i)) {
1677 setItemDelegateForColumn(i, &related_packet_delegate_);
1678 break; // Set the delegate only on the first visible column
1679 }
1680 }
1681 }
1682
1683 for (unsigned i = 0; i < prefs.num_cols; i++) {
1684 QAbstractItemDelegate *col_delegate = itemDelegateForColumn(i);
1685 if (!col_delegate) {
1686 continue;
1687 }
1688 for (QTreeView *view : pinnedOverlayViews()) {
1689 view->setItemDelegateForColumn(i, col_delegate);
1690 }
1691 }
1692}
1693
1694void PacketList::setRecentColumnWidth(int col)
1695{
1696 int col_width = recent_get_column_width(col);
1697
1698 if (col_width < 1) {
1699 int fmt = get_column_format(col);
1700 const char *long_str = get_column_width_string(fmt, col);
1701
1702 // TODO: a column's natural width is model data, not a view concern.
1703 // PacketListModel should hint it instead of the view measuring against
1704 // the font here.
1705 QFontMetrics fm = QFontMetrics(FontManager::monospaceFont());
1706 if (long_str) {
1707 col_width = fm.horizontalAdvance(long_str);
1708 } else {
1709 col_width = fm.horizontalAdvance(MIN_COL_WIDTH_STR"MMMMMM");
1710 }
1711 // Custom delegate padding
1712 if (itemDelegateForColumn(col)) {
1713 QStyleOptionViewItem option;
1714 initViewItemOption(&option);
1715 // This is adding "how much width hinted for an empty index, plus
1716 // the decoration, plus any padding between the decoration and
1717 // normal display?" Many styles however have a non zero hint for
1718 // an empty index, so this isn't quite right. What we really want
1719 // is a size hint for an index whose data is the string above, and
1720 // to just use that for the width.
1721 col_width += itemDelegateForColumn(col)->sizeHint(option, QModelIndex()).width();
1722 }
1723 }
1724
1725 setColumnWidth(col, col_width);
1726}
1727
1728void PacketList::drawCurrentPacket()
1729{
1730 // XXX - Update for multi-select? If more than one packet is Selected,
1731 // this changes it so that only the Current packet is Selected.
1732 QModelIndex current_index = currentIndex();
1733 if (selectionModel() && current_index.isValid()) {
1734 selectionModel()->clearSelection();
1735 selectionModel()->setCurrentIndex(current_index, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
1736 }
1737}
1738
1739// Redraw the packet list and detail. Re-selects the current packet (causes
1740// the UI to scroll to that packet).
1741// Called from many places.
1742void PacketList::redrawVisiblePackets() {
1743 redrawVisiblePacketsDontSelectCurrent();
1744 drawCurrentPacket();
1745}
1746
1747// Redraw the packet list and detail.
1748// Does not scroll back to the selected packet.
1749void PacketList::redrawVisiblePacketsDontSelectCurrent() {
1750 packet_list_model_->invalidateAllColumnStrings();
1751}
1752
1753void PacketList::resetColumns()
1754{
1755 packet_list_model_->resetColumns();
1756}
1757
1758// Return true if we have a visible packet further along in the history.
1759bool PacketList::haveNextHistory(bool update_cur)
1760{
1761 if (selection_history_.size() < 1 || cur_history_ >= selection_history_.size() - 1) {
1762 return false;
1763 }
1764
1765 for (int i = cur_history_ + 1; i < selection_history_.size(); i++) {
1766 if (packet_list_model_->packetNumberToRow(selection_history_.at(i)) >= 0) {
1767 if (update_cur) {
1768 cur_history_ = i;
1769 }
1770 return true;
1771 }
1772 }
1773 return false;
1774}
1775
1776// Return true if we have a visible packet back in the history.
1777bool PacketList::havePreviousHistory(bool update_cur)
1778{
1779 if (selection_history_.size() < 1 || cur_history_ < 1) {
1780 return false;
1781 }
1782
1783 for (int i = cur_history_ - 1; i >= 0; i--) {
1784 if (packet_list_model_->packetNumberToRow(selection_history_.at(i)) >= 0) {
1785 if (update_cur) {
1786 cur_history_ = i;
1787 }
1788 return true;
1789 }
1790 }
1791 return false;
1792}
1793
1794void PacketList::setProfileSwitcher(ProfileSwitcher *profile_switcher)
1795{
1796 profile_switcher_ = profile_switcher;
1797 if (profile_switcher) {
1798 connect(packet_list_model_, &PacketListModel::packetAppended, profile_switcher_, &ProfileSwitcher::checkPacket);
1799 }
1800}
1801
1802frame_data *PacketList::getFDataForRow(int row) const
1803{
1804 return packet_list_model_->getRowFdata(row);
1805}
1806
1807// prefs.col_list has changed.
1808void PacketList::columnsChanged()
1809{
1810 columns_changed_ = true;
1811 column_register_fields();
1812 mainApp->emitAppSignal(MainApplication::FieldsChanged);
1813 if (!cap_file_) {
1814 // Keep columns_changed_ = true until we load a capture file.
1815 return;
1816 }
1817
1818 prefs.num_cols = g_list_length(prefs.col_list);
1819 col_cleanup(&cap_file_->cinfo);
1820 build_column_format_array(&cap_file_->cinfo, prefs.num_cols, false);
1821 create_far_overlay_ = true;
1822 resetColumns();
1823 applyRecentColumnWidths();
1824 setColumnVisibility();
1825 // Freezing is defined purely positionally ("the first N columns"), and
1826 // this signal doesn't say which column(s) actually changed -- a
1827 // removal, addition, or reorder can each change which logical columns
1828 // now sit at positions [0, pinned_column_boundary_), so there's no way
1829 // to tell from here whether the frozen set still means what the user
1830 // last chose. Unfreezing unconditionally is conservative (it also
1831 // clears a freeze that a change elsewhere in the column list didn't
1832 // actually affect), but guarantees the frozen set is never silently
1833 // wrong. setPinnedColumnBoundary() also re-syncs the pinned overlays
1834 // and duplicate header pair to match.
1835 if (pinned_column_boundary_ > 0) {
1836 setPinnedColumnBoundary(0);
1837 }
1838 columns_changed_ = false;
1839}
1840
1841// Fields have changed, update custom columns
1842void PacketList::fieldsChanged(capture_file *cf)
1843{
1844 // hfids used by custom columns or by the _ws.col fields may have changed,
1845 // so recreate the columns. We shouldn't need to if prefs.col_list is NULL,
1846 // since that doesn't register and deregister _ws.col fields.
1847 // If the column pref changes to or from NULL, that triggers columnsChanged
1848 // above, so we don't need to do it twice.
1849 //
1850 // XXX - If we knew exactly which fields changed, we could rebuild the
1851 // columns only if a field used by the columns changed.
1852 if (prefs.col_list) {
1853 prefs.num_cols = g_list_length(prefs.col_list);
1854 col_cleanup(&cf->cinfo);
1855 build_column_format_array(&cf->cinfo, prefs.num_cols, false);
1856 resetColumns();
1857 }
1858}
1859
1860// Column widths should
1861// - Load from recent when we load a new profile (including at starting up).
1862// - Reapply when changing columns.
1863// - Persist across freezes and thaws.
1864// - Persist across file closing and opening.
1865// - Save to recent when we save our profile (including shutting down).
1866// - Not be affected by the behavior of stretchLastSection. (XXX: We
1867// still save the stretched value to recent, sectionResized doesn't
1868// distinguish between a resize from being stretched and a manual change.)
1869void PacketList::applyRecentColumnWidths()
1870{
1871 // Either we've just started up or a profile has changed. Read
1872 // the recent settings, apply them, and save the header state.
1873
1874 for (unsigned col = 0; col < prefs.num_cols; col++) {
1875 // The column must be shown before setting column width.
1876 // Visibility will be updated in setColumnVisibility().
1877 setColumnHidden(col, false);
1878 setRecentColumnWidth(col);
1879 }
1880}
1881
1882void PacketList::preferencesChanged()
1883{
1884 // Previously driven by the separate MainApplication::colorsChanged
1885 // signal, which has been removed — every colorsChanged emit was
1886 // paired with a preferencesChanged emit anyway. Rebuilding the
1887 // selection stylesheet on every pref change is cheap (single
1888 // setStyleSheet call) and idempotent.
1889 colorsChanged();
1890
1891 // Intelligent scroll bar (minimap)
1892 if (prefs.gui_packet_list_show_minimap) {
1893 if (overlay_timer_id_ == 0) {
1894 overlay_timer_id_ = startTimer(overlay_update_interval_);
1895 }
1896 } else {
1897 if (overlay_timer_id_ != 0) {
1898 killTimer(overlay_timer_id_);
1899 overlay_timer_id_ = 0;
1900 }
1901 }
1902
1903 // Elide mode.
1904 // This sets the mode for the entire view. If we want to make this setting
1905 // per-column we'll either have to generalize RelatedPacketDelegate so that
1906 // we can set it for entire rows or create another delegate.
1907 Qt::TextElideMode elide_mode = Qt::ElideRight;
1908 switch (prefs.gui_packet_list_elide_mode) {
1909 case ELIDE_LEFT:
1910 elide_mode = Qt::ElideLeft;
1911 break;
1912 case ELIDE_MIDDLE:
1913 elide_mode = Qt::ElideMiddle;
1914 break;
1915 case ELIDE_NONE:
1916 elide_mode = Qt::ElideNone;
1917 break;
1918 default:
1919 break;
1920 }
1921 setTextElideMode(elide_mode);
1922}
1923
1924void PacketList::freezePacketList(bool changing_profile)
1925{
1926 changing_profile_ = changing_profile;
1927 freeze(true);
1928}
1929
1930void PacketList::recolorPackets()
1931{
1932 packet_list_model_->resetColorized();
1933 redrawVisiblePackets();
1934}
1935
1936// Enable autoscroll.
1937void PacketList::setVerticalAutoScroll(bool enabled)
1938{
1939 tail_at_end_ = enabled;
1940 if (enabled && capture_in_progress_) {
1941 scrollToBottom();
1942 }
1943}
1944
1945// Called when we finish reading, reloading, rescanning, and retapping
1946// packets.
1947void PacketList::captureFileReadFinished()
1948{
1949 packet_list_model_->flushVisibleRows();
1950 packet_list_model_->dissectIdle(true);
1951 // Invalidating the column strings picks up and request/response
1952 // tracking changes. We might just want to call it from flushVisibleRows.
1953 packet_list_model_->invalidateAllColumnStrings();
1954 // Sort *after* invalidating the column strings
1955 if (isSortingEnabled()) {
1956 sortByColumn(header()->sortIndicatorSection(), header()->sortIndicatorOrder());
1957 }
1958}
1959
1960bool PacketList::freeze(bool keep_current_frame)
1961{
1962 if (!cap_file_ || model() == Q_NULLPTRnullptr) {
1963 // No capture file or already frozen
1964 return false;
1965 }
1966
1967 frame_data *current_frame = cap_file_->current_frame;
1968 column_state_ = header()->saveState();
1969 setHeaderHidden(true);
1970 frozen_current_row_ = currentIndex();
1971 frozen_selected_rows_ = selectionModel()->selectedRows();
1972 selectionModel()->clear();
1973 setModel(Q_NULLPTRnullptr);
1974 // It looks like GTK+ sends a cursor-changed signal at this point but Qt doesn't
1975 // call selectionChanged.
1976 related_packet_delegate_.clear();
1977
1978 if (keep_current_frame) {
1979 cap_file_->current_frame = current_frame;
1980 }
1981
1982 /* Clears packet list as well as byteview */
1983 emit framesSelected(QList<int>());
1984
1985 return true;
1986}
1987
1988bool PacketList::thaw(bool restore_selection)
1989{
1990 if (!cap_file_ || model() != Q_NULLPTRnullptr) {
1991 // No capture file or not frozen
1992 return false;
1993 }
1994
1995 setHeaderHidden(false);
1996 // Note that if we have a current sort status set in the header,
1997 // this will automatically try to sort the model (we don't want
1998 // that to happen if we're in the middle of reading the file).
1999 setModel(packet_list_model_);
2000
2001 // setModel() always creates a brand-new default selection model, even
2002 // when passed the same model pointer, discarding the one we'd shared
2003 // with pinned_column_view_ back in the constructor. Re-share it so its
2004 // selection highlighting doesn't silently go stale. (The pinned-row
2005 // overlays use a separate proxy model -- PinnedRowsModel -- and so
2006 // never shared this selection model to begin with.)
2007 if (pinned_column_view_) {
2008 pinned_column_view_->setSelectionModel(selectionModel());
2009 }
2010
2011 if (changing_profile_) {
2012 // When changing profile the new recent settings must be applied to the columns.
2013 applyRecentColumnWidths();
2014 setColumnVisibility();
2015 changing_profile_ = false;
2016 } else {
2017 // Resetting the model resets our column widths so we restore them here.
2018 // We don't reapply the recent settings because the user could have
2019 // resized the columns manually since they were initially loaded.
2020 header()->restoreState(column_state_);
2021 }
2022
2023 if (restore_selection && frozen_selected_rows_.length() > 0 && selectionModel()) {
2024 /* This updates our selection, which redissects the current packet,
2025 * which is needed when we're called from MainWindow::layoutPanes.
2026 * Also, this resets all ProtoTree and ByteView data */
2027 clearSelection();
2028 setCurrentIndex(frozen_current_row_);
2029 foreach (QModelIndex idx, frozen_selected_rows_)for (auto _container_2029 = QtPrivate::qMakeForeachContainer(
frozen_selected_rows_); _container_2029.i != _container_2029.
e; ++_container_2029.i) if (QModelIndex idx = *_container_2029
.i; false) {} else
{
2030 selectionModel()->select(idx, QItemSelectionModel::Select | QItemSelectionModel::Rows);
2031 }
2032 scrollTo(currentIndex(), PositionAtCenter);
2033 }
2034 frozen_current_row_ = QModelIndex();
2035 frozen_selected_rows_ = QModelIndexList();
2036
2037 return true;
2038}
2039
2040void PacketList::clear() {
2041 // Cleared before packet_list_model_ below: that call emits modelReset,
2042 // which updatePinnedRowVisibility() (connected to it) reacts to by
2043 // calling pinned_rows_model_->refresh() -- resolving pinned frame
2044 // numbers against packet_list_model_ while it's already been cleared,
2045 // if pinned_rows_model_ itself hadn't been cleared first. Every
2046 // consumer of that resolution currently null-checks defensively, so
2047 // this ordering wasn't otherwise observably wrong, but doing the
2048 // pinned-state clear first removes the transient window entirely
2049 // rather than relying on those checks to mask it.
2050 pinned_rows_model_->clear();
2051 setPinnedColumnBoundary(0);
2052
2053 related_packet_delegate_.clear();
2054 selectionModel()->clear();
2055 packet_list_model_->clear();
2056 proto_tree_->clear();
2057 selection_history_.clear();
2058 cur_history_ = -1;
2059 in_history_ = false;
2060
2061 QImage overlay;
2062 overlay_sb_->setNearOverlayImage(overlay);
2063 overlay_sb_->setMarkedPacketImage(overlay);
2064 create_near_overlay_ = true;
2065 create_far_overlay_ = true;
2066
2067 updatePinnedRowVisibility();
2068}
2069
2070void PacketList::writeRecent(FILE *rf) {
2071 int width, col_fmt;
2072 char xalign;
2073
2074 fprintf (rf, "%s:\n", RECENT_KEY_COL_WIDTH"column.width");
2075 for (unsigned col = 0; col < prefs.num_cols; col++) {
2076 if (col > 0) {
2077 fprintf (rf, ",\n");
2078 }
2079 col_fmt = get_column_format(col);
2080 if (col_fmt == COL_CUSTOM) {
2081 fprintf (rf, " \"%%Cus:%s\",", get_column_custom_fields(col));
2082 } else {
2083 fprintf (rf, " %s,", col_format_to_string(col_fmt));
2084 }
2085 width = recent_get_column_width (col);
2086 xalign = recent_get_column_xalign (col);
2087 fprintf (rf, " %d", width);
2088 if (xalign != COLUMN_XALIGN_DEFAULT0) {
2089 fprintf (rf, ":%c", xalign);
2090 }
2091 }
2092 fprintf (rf, "\n");
2093}
2094
2095bool PacketList::contextMenuActive()
2096{
2097 return ctx_column_ >= 0 ? true : false;
2098}
2099
2100QString PacketList::getFilterFromRowAndColumn(QModelIndex idx)
2101{
2102 frame_data *fdata;
2103 QString filter;
2104
2105 if (! idx.isValid())
2106 return filter;
2107
2108 int row = idx.row();
2109 int column = idx.column();
2110
2111 if (!cap_file_ || !packet_list_model_ || column < 0 || (unsigned)column >= cap_file_->cinfo.num_cols)
2112 return filter;
2113
2114 fdata = packet_list_model_->getRowFdata(row);
2115
2116 if (fdata != NULL__null) {
2117 epan_dissect_t edt;
2118 wtap_rec rec; /* Record information */
2119
2120 wtap_rec_init(&rec, DEFAULT_INIT_BUFFER_SIZE_2048(2 * 1024));
2121 if (!cf_read_record(cap_file_, fdata, &rec)) {
2122 wtap_rec_cleanup(&rec);
2123 return filter; /* error reading the record */
2124 }
2125 /* proto tree, visible. We need a proto tree if there's custom columns */
2126 epan_dissect_init(&edt, cap_file_->epan, have_custom_cols(&cap_file_->cinfo), false);
2127 col_custom_prime_edt(&edt, &cap_file_->cinfo);
2128
2129 epan_dissect_run(&edt, cap_file_->cd_t, &rec, fdata, &cap_file_->cinfo);
2130
2131 if (cap_file_->cinfo.columns[column].col_fmt == COL_CUSTOM) {
2132 filter.append(gchar_free_to_qstring(col_custom_get_filter(&edt, &cap_file_->cinfo, (unsigned)column)));
2133 } else {
2134 /* We don't need to fill in the custom columns, as we get their
2135 * filters above.
2136 */
2137 col_fill_in(&edt.pi, true, true);
2138 if (strlen(cap_file_->cinfo.col_expr.col_expr[column]) != 0 &&
2139 strlen(cap_file_->cinfo.col_expr.col_expr_val[column]) != 0) {
2140 bool is_string_value = false;
2141 header_field_info *hfi = proto_registrar_get_byname(cap_file_->cinfo.col_expr.col_expr[column]);
2142 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
)
) {
2143 /* Could be an address type such as usb.src which must be quoted. */
2144 is_string_value = true;
2145 }
2146
2147 if (filter.isEmpty()) {
2148 if (is_string_value) {
2149 filter.append(QStringLiteral("%1 == \"%2\"")(QString(QtPrivate::qMakeStringPrivate(u"" "%1 == \"%2\"")))
2150 .arg(cap_file_->cinfo.col_expr.col_expr[column])
2151 .arg(cap_file_->cinfo.col_expr.col_expr_val[column]));
2152 } else {
2153 filter.append(QStringLiteral("%1 == %2")(QString(QtPrivate::qMakeStringPrivate(u"" "%1 == %2")))
2154 .arg(cap_file_->cinfo.col_expr.col_expr[column])
2155 .arg(cap_file_->cinfo.col_expr.col_expr_val[column]));
2156 }
2157 }
2158 }
2159 }
2160
2161 epan_dissect_cleanup(&edt);
2162 wtap_rec_cleanup(&rec);
2163 }
2164
2165 return filter;
2166}
2167
2168void PacketList::resetColorized()
2169{
2170 packet_list_model_->resetColorized();
2171 update();
2172}
2173
2174QString PacketList::getPacketComment(unsigned c_number)
2175{
2176 int row = currentIndex().row();
2177 const frame_data *fdata;
2178 char *pkt_comment;
2179 wtap_opttype_return_val result;
2180 QString ret_val = NULL__null;
2181
2182 if (!cap_file_ || !packet_list_model_) return NULL__null;
2183
2184 fdata = packet_list_model_->getRowFdata(row);
2185
2186 if (!fdata) return NULL__null;
2187
2188 wtap_block_t pkt_block = cf_get_packet_block(cap_file_, fdata);
2189 result = wtap_block_get_nth_string_option_value(pkt_block, OPT_COMMENT1, c_number, &pkt_comment);
2190 if (result == WTAP_OPTTYPE_SUCCESS) {
2191 ret_val = QString(pkt_comment);
2192 }
2193 wtap_block_unref(pkt_block);
2194 return ret_val;
2195}
2196
2197void PacketList::addPacketComment(QString new_comment)
2198{
2199 if (!cap_file_ || !packet_list_model_) return;
2200 if (new_comment.isEmpty()) return;
2201
2202 QByteArray ba = new_comment.toUtf8();
2203
2204 /*
2205 * Make sure this would fit in a pcapng option.
2206 *
2207 * XXX - 65535 is the maximum size for an option in pcapng;
2208 * what if another capture file format supports larger
2209 * comments?
2210 */
2211 if (ba.size() > 65535) {
2212 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK0x01,
2213 "That comment is too large to save in a capture file.");
2214 return;
2215 }
2216
2217 if (selectionModel() && selectionModel()->hasSelection()) {
2218 packet_list_model_->addFrameComment(selectionModel()->selectedRows(), ba);
2219 drawCurrentPacket();
2220 }
2221}
2222
2223void PacketList::setPacketComment(unsigned c_number, QString new_comment)
2224{
2225 QModelIndex curIndex = currentIndex();
2226
2227 if (!cap_file_ || !packet_list_model_) return;
2228
2229 QByteArray ba = new_comment.toUtf8();
2230 /*
2231 * Make sure this would fit in a pcapng option.
2232 *
2233 * XXX - 65535 is the maximum size for an option in pcapng;
2234 * what if another capture file format supports larger
2235 * comments?
2236 */
2237 if (ba.size() > 65535) {
2238 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK0x01,
2239 "That comment is too large to save in a capture file.");
2240 return;
2241 }
2242
2243 packet_list_model_->setFrameComment(curIndex, ba, c_number);
2244 drawCurrentPacket();
2245}
2246
2247QString PacketList::allPacketComments()
2248{
2249 uint32_t framenum;
2250 frame_data *fdata;
2251 QString buf_str;
2252
2253 if (!cap_file_) return buf_str;
2254
2255 for (framenum = 1; framenum <= cap_file_->count ; framenum++) {
2256 fdata = frame_data_sequence_find(cap_file_->provider.frames, framenum);
2257
2258 wtap_block_t pkt_block = cf_get_packet_block(cap_file_, fdata);
2259
2260 if (pkt_block) {
2261 unsigned n_comments = wtap_block_count_option(pkt_block, OPT_COMMENT1);
2262 for (unsigned i = 0; i < n_comments; i++) {
2263 char *comment_text;
2264 if (WTAP_OPTTYPE_SUCCESS == wtap_block_get_nth_string_option_value(pkt_block, OPT_COMMENT1, i, &comment_text)) {
2265 buf_str.append(tr("Frame %1: %2\n\n").arg(framenum).arg(comment_text));
2266 if (buf_str.length() > max_comments_to_fetch_) {
2267 buf_str.append(tr("[ Comment text exceeds %1. Stopping. ]")
2268 .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))
));
2269 return buf_str;
2270 }
2271 }
2272 }
2273 }
2274 }
2275 return buf_str;
2276}
2277
2278void PacketList::deleteCommentsFromPackets()
2279{
2280 if (!cap_file_ || !packet_list_model_) return;
2281
2282 if (selectionModel() && selectionModel()->hasSelection()) {
2283 packet_list_model_->deleteFrameComments(selectionModel()->selectedRows());
2284 drawCurrentPacket();
2285 }
2286}
2287
2288void PacketList::deleteAllPacketComments()
2289{
2290 if (!cap_file_ || !packet_list_model_) return;
2291
2292 packet_list_model_->deleteAllFrameComments();
2293 drawCurrentPacket();
2294}
2295
2296
2297// Slots
2298
2299void PacketList::setCaptureFile(capture_file *cf)
2300{
2301 cap_file_ = cf;
2302 packet_list_model_->setCaptureFile(cf);
2303 if (cap_file_ && columns_changed_) {
2304 columnsChanged();
2305 }
2306 create_near_overlay_ = true;
2307 changing_profile_ = false;
2308 sortByColumn(-1, Qt::AscendingOrder);
2309}
2310
2311void PacketList::setMonospaceFont(const QFont &mono_font)
2312{
2313 setFont(mono_font);
2314 for (QTreeView *view : pinnedOverlayViews()) {
2315 view->setFont(mono_font);
2316 }
2317 layoutPinnedOverlays();
2318}
2319
2320void PacketList::setRegularFont(const QFont &regular_font)
2321{
2322 header()->setFont(regular_font);
2323 header()->viewport()->setFont(regular_font);
2324 // pinned_column_view_'s own header isn't covered by setMonospaceFont()
2325 // looping over pinnedOverlayViews() (that sets the *view's* font, for
2326 // cell content -- QHeaderView doesn't automatically inherit a
2327 // different font set on its own separately-headed QTreeView the way
2328 // the primary view's header is explicitly given the regular font
2329 // above), so without this it silently kept whatever font QHeaderView
2330 // fell back to, differing from the primary header's.
2331 if (pinned_column_view_) {
2332 pinned_column_view_->header()->setFont(regular_font);
2333 }
2334}
2335
2336void PacketList::goNextPacket(void)
2337{
2338 if (QApplication::keyboardModifiers() & Qt::AltModifier) {
2339 // Alt+toolbar
2340 goNextHistoryPacket();
2341 return;
2342 }
2343
2344 if (selectionModel()->hasSelection()) {
2345 selectionModel()->setCurrentIndex(moveCursor(MoveDown, Qt::NoModifier), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
2346 } else {
2347 // First visible packet.
2348 selectionModel()->setCurrentIndex(indexAt(viewport()->rect().topLeft()), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
2349 }
2350
2351 scrollViewChanged(false);
2352}
2353
2354void PacketList::goPreviousPacket(void)
2355{
2356 if (QApplication::keyboardModifiers() & Qt::AltModifier) {
2357 // Alt+toolbar
2358 goPreviousHistoryPacket();
2359 return;
2360 }
2361
2362 if (selectionModel()->hasSelection()) {
2363 selectionModel()->setCurrentIndex(moveCursor(MoveUp, Qt::NoModifier), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
2364 } else {
2365 // Last visible packet.
2366 QModelIndex last_idx = indexAt(viewport()->rect().bottomLeft());
2367 if (last_idx.isValid()) {
2368 selectionModel()->setCurrentIndex(last_idx, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
2369 } else {
2370 goLastPacket();
2371 }
2372 }
2373
2374 scrollViewChanged(false);
2375}
2376
2377void PacketList::goFirstPacket(void) {
2378 if (packet_list_model_->rowCount() < 1) return;
2379 selectionModel()->setCurrentIndex(packet_list_model_->index(0, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
2380 scrollTo(currentIndex());
2381
2382 scrollViewChanged(false);
2383}
2384
2385void PacketList::goLastPacket(void) {
2386 if (packet_list_model_->rowCount() < 1) return;
2387 selectionModel()->setCurrentIndex(packet_list_model_->index(packet_list_model_->rowCount() - 1, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
2388 scrollTo(currentIndex());
2389
2390 scrollViewChanged(false);
2391}
2392
2393void PacketList::goToPacket(int packet, int hf_id)
2394{
2395 if (!cf_goto_frame(cap_file_, packet, false))
2396 return;
2397
2398 // cf_goto_frame only returns true if packet_list_select_row_from_data
2399 // succeeds, the latter has already selected and scrolled to the frame.
2400 if (hf_id > 0) {
2401 proto_tree_->goToHfid(hf_id);
2402 }
2403
2404 scrollViewChanged(false);
2405}
2406
2407void PacketList::goNextHistoryPacket()
2408{
2409 if (haveNextHistory(true)) {
2410 in_history_ = true;
2411 goToPacket(selection_history_.at(cur_history_));
2412 in_history_ = false;
2413 }
2414}
2415
2416void PacketList::goPreviousHistoryPacket()
2417{
2418 if (havePreviousHistory(true)) {
2419 in_history_ = true;
2420 goToPacket(selection_history_.at(cur_history_));
2421 in_history_ = false;
2422 }
2423}
2424
2425void PacketList::markFrame()
2426{
2427 if (!cap_file_ || !packet_list_model_) return;
2428
2429 QModelIndexList frames;
2430
2431 if (selectionModel() && selectionModel()->hasSelection())
2432 {
2433 QModelIndexList selRows = selectionModel()->selectedRows(0);
2434 foreach (QModelIndex idx, selRows)for (auto _container_2434 = QtPrivate::qMakeForeachContainer(
selRows); _container_2434.i != _container_2434.e; ++_container_2434
.i) if (QModelIndex idx = *_container_2434.i; false) {} else
2435 {
2436 if (idx.isValid())
2437 {
2438 frames << idx;
2439 }
2440 }
2441 }
2442 else
2443 frames << currentIndex();
2444
2445 packet_list_model_->toggleFrameMark(frames);
2446
2447 // Make sure the packet list's frame.marked related field text is updated.
2448 redrawVisiblePackets();
2449
2450 create_far_overlay_ = true;
2451 packets_bar_update();
2452}
2453
2454void PacketList::markAllDisplayedFrames(bool set)
2455{
2456 if (!cap_file_ || !packet_list_model_) return;
2457
2458 packet_list_model_->setDisplayedFrameMark(set);
2459
2460 // Make sure the packet list's frame.marked related field text is updated.
2461 redrawVisiblePackets();
2462
2463 create_far_overlay_ = true;
2464 packets_bar_update();
2465}
2466
2467void PacketList::ignoreFrame()
2468{
2469 if (!cap_file_ || !packet_list_model_) return;
2470
2471 QModelIndexList frames;
2472
2473 if (selectionModel() && selectionModel()->hasSelection())
2474 {
2475 foreach (QModelIndex idx, selectionModel()->selectedRows(0))for (auto _container_2475 = QtPrivate::qMakeForeachContainer(
selectionModel()->selectedRows(0)); _container_2475.i != _container_2475
.e; ++_container_2475.i) if (QModelIndex idx = *_container_2475
.i; false) {} else
2476 {
2477 if (idx.isValid())
2478 {
2479 frames << idx;
2480 }
2481 }
2482 }
2483 else
2484 frames << currentIndex();
2485
2486
2487 packet_list_model_->toggleFrameIgnore(frames);
2488 create_far_overlay_ = true;
2489 int sb_val = verticalScrollBar()->value(); // Surely there's a better way to keep our position?
2490 setUpdatesEnabled(false);
2491 emit packetDissectionChanged();
2492 setUpdatesEnabled(true);
2493 verticalScrollBar()->setValue(sb_val);
2494}
2495
2496void PacketList::ignoreAllDisplayedFrames(bool set)
2497{
2498 if (!cap_file_ || !packet_list_model_) return;
2499
2500 packet_list_model_->setDisplayedFrameIgnore(set);
2501 create_far_overlay_ = true;
2502 emit packetDissectionChanged();
2503}
2504
2505void PacketList::setTimeReference()
2506{
2507 if (!cap_file_ || !packet_list_model_) return;
2508 packet_list_model_->toggleFrameRefTime(currentIndex());
2509 create_far_overlay_ = true;
2510}
2511
2512void PacketList::unsetAllTimeReferences()
2513{
2514 if (!cap_file_ || !packet_list_model_) return;
2515 packet_list_model_->unsetAllFrameRefTime();
2516 create_far_overlay_ = true;
2517}
2518
2519void PacketList::applyTimeShift()
2520{
2521 packet_list_model_->resetColumns();
2522 redrawVisiblePackets();
2523 emit packetDissectionChanged();
2524}
2525
2526void PacketList::updatePackets(bool redraw)
2527{
2528 if (redraw) {
2529 packet_list_model_->resetColumns();
2530 redrawVisiblePackets();
2531 } else {
2532 update();
2533 }
2534}
2535
2536void PacketList::columnVisibilityTriggered()
2537{
2538 QAction *ha = qobject_cast<QAction*>(sender());
2539 if (!ha) return;
2540
2541 int col = ha->data().toInt();
2542 set_column_visible(col, ha->isChecked());
2543 setColumnVisibility();
2544 if (ha->isChecked()) {
2545 setRecentColumnWidth(col);
2546 }
2547 prefs_main_write();
2548}
2549
2550void PacketList::sectionResized(int col, int, int new_width)
2551{
2552 if (isVisible() && !columns_changed_ && !set_column_visibility_ && !set_style_sheet_ && new_width > 0) {
2553 // Column 1 gets an invalid value (32 on macOS) when we're not yet
2554 // visible.
2555 //
2556 // Don't set column width when columns changed or setting column
2557 // visibility because we may get a sectionResized() from QTreeView
2558 // with values from a old columns layout.
2559 //
2560 // Don't set column width when hiding a column.
2561
2562 recent_set_column_width(col, new_width);
2563 }
2564
2565 mirrorSectionWidthToOverlays(col, new_width);
2566 layoutPinnedOverlays();
2567}
2568
2569// The user moved a column. Make sure prefs.col_list, the column format
2570// array, and the header's visual and logical indices all agree.
2571// gtk/packet_list.c:column_dnd_changed_cb
2572void PacketList::sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex)
2573{
2574 GList *new_col_list = NULL__null;
2575 GList *new_recent_col_list = NULL__null;
2576 QList<int> saved_sizes;
2577 int sort_idx;
2578
2579 // Since we undo the move below, these should always stay in sync.
2580 // Otherwise the order of columns can be unexpected after drag and drop.
2581 if (logicalIndex != oldVisualIndex) {
2582 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"
, 2583, __func__, "Column moved from an unexpected state (%d, %d, %d)"
, logicalIndex, oldVisualIndex, newVisualIndex); } } while (0
)
2583 logicalIndex, oldVisualIndex, newVisualIndex)do { if (true) { ws_log_full("", LOG_LEVEL_WARNING, "ui/qt/packet_list.cpp"
, 2583, __func__, "Column moved from an unexpected state (%d, %d, %d)"
, logicalIndex, oldVisualIndex, newVisualIndex); } } while (0
)
;
2584 }
2585
2586 // Remember which column should be sorted. Use the visual index since this
2587 // points to the current GUI state rather than the outdated column order
2588 // (indicated by the logical index).
2589 sort_idx = header()->sortIndicatorSection();
2590 if (sort_idx != -1) {
2591 sort_idx = header()->visualIndex(sort_idx);
2592 }
2593
2594 // Build a new column list based on the header's logical order.
2595 for (int vis_idx = 0; vis_idx < header()->count(); vis_idx++) {
2596 int log_idx = header()->logicalIndex(vis_idx);
2597 saved_sizes << header()->sectionSize(log_idx);
2598
2599 void *pref_data = g_list_nth_data(prefs.col_list, log_idx);
2600 if (pref_data) {
2601 new_col_list = g_list_append(new_col_list, pref_data);
2602 }
2603
2604 pref_data = g_list_nth_data(recent.col_width_list, log_idx);
2605 if (pref_data) {
2606 new_recent_col_list = g_list_append(new_recent_col_list, pref_data);
2607 }
2608 }
2609
2610 // Undo move to ensure that the logical indices map to the visual indices,
2611 // otherwise the column order is changed twice (once via the modified
2612 // col_list, once because of the visual/logical index mismatch).
2613 disconnect(header(), &QHeaderView::sectionMoved, this, &PacketList::sectionMoved);
2614 header()->moveSection(newVisualIndex, oldVisualIndex);
2615 connect(header(), &QHeaderView::sectionMoved, this, &PacketList::sectionMoved);
2616
2617 // Clear and rebuild our (and the header's) model. There doesn't appear
2618 // to be another way to reset the logical index.
2619 freeze();
2620
2621 g_list_free(prefs.col_list);
2622 prefs.col_list = new_col_list;
2623 g_list_free(recent.col_width_list);
2624 recent.col_width_list = new_recent_col_list;
2625
2626 thaw(true);
2627
2628 for (int i = 0; i < saved_sizes.length(); i++) {
2629 if (saved_sizes[i] < 1) continue;
2630 header()->resizeSection(i, saved_sizes[i]);
2631 }
2632
2633 prefs_main_write();
2634
2635 mainApp->emitAppSignal(MainApplication::ColumnsChanged);
2636
2637 // If the column with the sort indicator got shifted, mark the new column
2638 // after updating the columns contents (via ColumnsChanged) to ensure that
2639 // the columns are sorted using the intended column contents.
2640 int left_col = MIN(oldVisualIndex, newVisualIndex)(((oldVisualIndex) < (newVisualIndex)) ? (oldVisualIndex) :
(newVisualIndex))
;
2641 int right_col = MAX(oldVisualIndex, newVisualIndex)(((oldVisualIndex) > (newVisualIndex)) ? (oldVisualIndex) :
(newVisualIndex))
;
2642 if (left_col <= sort_idx && sort_idx <= right_col) {
2643 header()->setSortIndicator(sort_idx, header()->sortIndicatorOrder());
2644 }
2645
2646 layoutPinnedOverlays();
2647}
2648
2649void PacketList::pinRow(int frame_num)
2650{
2651 pinned_rows_model_->pinFrame(frame_num);
2652 updatePinnedRowVisibility();
2653}
2654
2655void PacketList::unpinRow(int frame_num)
2656{
2657 pinned_rows_model_->unpinFrame(frame_num);
2658 updatePinnedRowVisibility();
2659}
2660
2661void PacketList::unpinAllRows()
2662{
2663 pinned_rows_model_->clear();
2664 updatePinnedRowVisibility();
2665}
2666
2667int PacketList::pinnedRowHeight() const
2668{
2669 int row_height = sizeHintForRow(0);
2670 if (row_height > 0) {
2671 return row_height;
2672 }
2673 // No rows laid out yet (e.g. empty capture); fall back to font-based
2674 // spacing so the strip still sizes sensibly rather than to 0.
2675 return fontMetrics().height() + 2;
2676}
2677
2678void PacketList::setPinnedColumnBoundary(int column_count)
2679{
2680 pinned_column_boundary_ = column_count;
2681 emit pinnedColumnBoundaryChanged(pinned_column_boundary_);
2682
2683 // Seed widths for the newly-pinned range; afterward sectionResized()
2684 // keeps these in sync as the user resizes columns.
2685 for (int i = 0; i < pinned_column_boundary_; i++) {
2686 int width = header()->sectionSize(i);
2687 if (pinned_column_view_) {
2688 pinned_column_view_->mirrorSectionWidth(i, width);
2689 }
2690 if (pinned_row_corner_view_) {
2691 pinned_row_corner_view_->mirrorSectionWidth(i, width);
2692 }
2693 }
2694
2695 if (pinned_column_view_) {
2696 pinned_column_view_->setFrozenColumnCount(pinned_column_boundary_);
2697 }
2698 if (packet_list_header_) {
2699 packet_list_header_->setFrozenColumnCount(pinned_column_boundary_);
2700 }
2701
2702 updatePinnedRowVisibility();
2703 layoutPinnedOverlays();
2704}
2705
2706void PacketList::updatePinnedRowVisibility()
2707{
2708 pinned_rows_model_->refresh();
2709
2710 bool have_pinned_rows = pinned_rows_model_->pinnedCount() > 0;
2711
2712 for (unsigned i = 0; i < prefs.num_cols; i++) {
2713 int width = header()->sectionSize(i);
2714 if (pinned_row_view_) {
2715 pinned_row_view_->mirrorSectionWidth(i, width);
2716 }
2717 if (pinned_row_corner_view_) {
2718 pinned_row_corner_view_->mirrorSectionWidth(i, width);
2719 }
2720 }
2721
2722 if (pinned_row_view_) {
2723 pinned_row_view_->setColumnRange(pinned_column_boundary_, -1);
2724 pinned_row_view_->setVisible(have_pinned_rows);
2725 pinned_row_view_->updateGeometry();
2726 }
2727 if (pinned_row_corner_view_) {
2728 bool show_corner = have_pinned_rows && pinned_column_boundary_ > 0;
2729 if (show_corner) {
2730 pinned_row_corner_view_->setColumnRange(0, pinned_column_boundary_ - 1);
2731 }
2732 pinned_row_corner_view_->setVisible(show_corner);
2733 pinned_row_corner_view_->updateGeometry();
2734 }
2735
2736 layoutPinnedOverlays();
2737}
2738
2739void PacketList::layoutPinnedOverlays()
2740{
2741 // Width of the frozen-column portion, shared between the column-freeze
2742 // overlay below and the pinned-row strip's "corner" widget (whose
2743 // sizing PacketListPane keeps in sync via pinnedRowsCornerWidthChanged()).
2744 int corner_width = 0;
2745 for (int i = 0; i < pinned_column_boundary_; i++) {
2746 corner_width += header()->sectionSize(i);
2747 }
2748 bool have_pinned_rows = pinned_rows_model_ && pinned_rows_model_->pinnedCount() > 0;
2749 emit pinnedRowsCornerWidthChanged(corner_width, have_pinned_rows);
2750
2751 if (!pinned_column_view_) {
2752 return;
2753 }
2754
2755 // Derive the real on-screen offsets from the primary view's own child
2756 // widgets rather than assuming (0, 0): QTreeView's default frame
2757 // border/margin means header()/viewport() do not actually start flush
2758 // with PacketList's own top-left corner.
2759 int left_offset = header()->pos().x();
2760 int top_offset = header()->pos().y();
2761 int header_height = header()->height();
2762
2763 if (pinned_column_boundary_ > 0) {
2764 pinned_column_view_->mirrorHeaderHeight(header_height);
2765 // Span from the header's own top offset (not the viewport's) so
2766 // this view's own header covers the primary header's frozen-column
2767 // titles, which would otherwise scroll horizontally with the rest
2768 // of the header.
2769 QSize new_size(corner_width, header_height + viewport()->height());
2770 pinned_column_view_->setGeometry(left_offset, top_offset,
2771 new_size.width(), new_size.height());
2772 pinned_column_view_->setVisible(true);
2773 pinned_column_view_->raise();
2774 // refreshLayout() forces a full row-geometry recompute
2775 // (doItemsLayout()), which must run after setGeometry() since
2776 // QTreeView computes its vertical scroll range from the current
2777 // viewport size -- but only the height actually affects that
2778 // range, so skip the recompute when only corner_width (the
2779 // column-resize-driven part of new_size) changed. Without this,
2780 // dragging a column resize handle while frozen columns are active
2781 // re-runs a full O(rows) layout on every mouse-move tick.
2782 if (new_size.height() != pinned_column_view_size_.height()) {
2783 pinned_column_view_->refreshLayout();
2784 }
2785 pinned_column_view_size_ = new_size;
2786 pinned_column_view_->setVerticalScrollValue(verticalScrollBar()->value());
2787 } else {
2788 pinned_column_view_->setVisible(false);
2789 }
2790}
2791
2792QString PacketList::createSummaryText(QModelIndex idx, SummaryCopyType type)
2793{
2794 if (! idx.isValid())
2795 return "";
2796
2797 QStringList col_parts;
2798 int row = idx.row();
2799 for (int col = 0; col < packet_list_model_->columnCount(); col++) {
2800 if (get_column_visible(col)) {
2801 col_parts << packet_list_model_->data(packet_list_model_->index(row, col), Qt::DisplayRole).toString();
2802 }
2803 }
2804 return joinSummaryRow(col_parts, row, type);
2805}
2806
2807QString PacketList::createHeaderSummaryText(SummaryCopyType type)
2808{
2809 QStringList col_parts;
2810 for (int col = 0; col < packet_list_model_->columnCount(); ++col) {
2811 if (get_column_visible(col)) {
2812 col_parts << packet_list_model_->headerData(col, Qt::Orientation::Horizontal, Qt::DisplayRole).toString();
2813 }
2814 }
2815 return joinSummaryRow(col_parts, 0, type);
2816}
2817
2818QStringList PacketList::createHeaderPartsForAligned()
2819{
2820 QStringList hdr_parts;
2821 for (int col = 0; col < packet_list_model_->columnCount(); ++col) {
2822 if (get_column_visible(col)) {
2823 hdr_parts << packet_list_model_->headerData(col, Qt::Orientation::Horizontal, Qt::DisplayRole).toString();
2824 }
2825 }
2826 return hdr_parts;
2827}
2828
2829QList<int> PacketList::createAlignmentPartsForAligned()
2830{
2831 QList<int> align_parts;
2832 for (int col = 0; col < packet_list_model_->columnCount(); col++) {
2833 if (get_column_visible(col)) {
2834 align_parts << packet_list_model_->data(packet_list_model_->index(0, col), Qt::TextAlignmentRole).toInt();
2835 }
2836 }
2837 return align_parts;
2838}
2839
2840QList<int> PacketList::createSizePartsForAligned(bool useHeader, QStringList hdr_parts, QList<int> rows)
2841{
2842 QList<int> size_parts;
2843
2844 for (int i = 0; i < hdr_parts.size(); ++i) {
2845 if (useHeader)
2846 size_parts << static_cast<int>(hdr_parts.at(i).size());
2847 else
2848 size_parts << 0;
2849 }
2850
2851 foreach(int row, rows)for (auto _container_2851 = QtPrivate::qMakeForeachContainer(
rows); _container_2851.i != _container_2851.e; ++_container_2851
.i) if (int row = *_container_2851.i; false) {} else
2852 {
2853 QModelIndex idx = model()->index(row, 0);
2854 if (! idx.isValid())
2855 continue;
2856
2857 QStringList col_parts;
2858 for (int col = 0; col < packet_list_model_->columnCount(); col++) {
2859 if (get_column_visible(col)) {
2860 col_parts << (packet_list_model_->data(packet_list_model_->index(row, col), Qt::DisplayRole).toString());
2861 }
2862 }
2863
2864 for (int i = 0; i < col_parts.size(); ++i) {
2865 if (col_parts.at(i).size() > size_parts.at(i)) {
2866 size_parts[i] = static_cast<int>(col_parts.at(i).size());
2867 }
2868 }
2869 col_parts.clear();
2870 }
2871
2872 return size_parts;
2873}
2874
2875QString PacketList::createHeaderSummaryForAligned(QStringList hdr_parts, QList<int> align_parts, QList<int> size_parts)
2876{
2877 QString hdr_text;
2878 for (int i = 0; i < hdr_parts.size(); ++i) {
2879 if (align_parts.at(i) == Qt::AlignLeft) {
2880 hdr_text += hdr_parts[i].leftJustified(size_parts.at(i), ' ') + " ";
2881 }
2882 else if (align_parts.at(i) == Qt::AlignRight) {
2883 hdr_text += hdr_parts[i].rightJustified(size_parts.at(i), ' ') + " ";
2884 }
2885 }
2886 return QStringLiteral("-%1")(QString(QtPrivate::qMakeStringPrivate(u"" "-%1"))).arg(hdr_text).trimmed().mid(1);
2887}
2888
2889QString PacketList::createSummaryForAligned(QModelIndex idx, QList<int> align_parts, QList<int> size_parts)
2890{
2891 if (! idx.isValid())
2892 return "";
2893
2894 QStringList col_parts;
2895 int row = idx.row();
2896 for (int col = 0; col < packet_list_model_->columnCount(); col++) {
2897 if (get_column_visible(col)) {
2898 col_parts << packet_list_model_->data(packet_list_model_->index(row, col), Qt::DisplayRole).toString();
2899 }
2900 }
2901
2902 QString col_text;
2903 for (int i = 0; i < col_parts.size(); ++i) {
2904 if (align_parts.at(i) == Qt::AlignLeft) {
2905 col_text += col_parts[i].leftJustified(size_parts.at(i), ' ') + " ";
2906 }
2907 else if (align_parts.at(i) == Qt::AlignRight) {
2908 col_text += col_parts[i].rightJustified(size_parts.at(i), ' ') + " ";
2909 }
2910 }
2911
2912 return QStringLiteral("-%1")(QString(QtPrivate::qMakeStringPrivate(u"" "-%1"))).arg(col_text).trimmed().mid(1);
2913}
2914
2915QString PacketList::createDefaultStyleForHtml()
2916{
2917 QString fontFamily = QString(prefs.gui_font_name).split(",")[0];
2918 QString fontSize = QString(prefs.gui_font_name).split(",")[1];
2919
2920 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>")))
2921 "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>")))
2922 "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>")))
2923 "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>")))
2924 "</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);
2925}
2926
2927QString PacketList::createOpeningTagForHtml()
2928{
2929 return "<table>";
2930}
2931
2932QString PacketList::createHeaderSummaryForHtml()
2933{
2934 QString hdr_text;
2935 hdr_text += "<tr>";
2936 for (int col = 0; col < packet_list_model_->columnCount(); ++col) {
2937 if (get_column_visible(col)) {
2938 hdr_text += "<th>";
2939 hdr_text += packet_list_model_->headerData(col, Qt::Orientation::Horizontal, Qt::DisplayRole).toString();
2940 hdr_text += "</th>";
2941 }
2942 }
2943 hdr_text += "</tr>";
2944 return hdr_text;
2945}
2946
2947QString PacketList::createSummaryForHtml(QModelIndex idx)
2948{
2949 if (! idx.isValid())
2950 return "";
2951
2952 int row = idx.row();
2953 QString col_text;
2954
2955 QString bg_color = packet_list_model_->data(packet_list_model_->index(row, 0), Qt::BackgroundRole).toString();
2956 QString fg_color = packet_list_model_->data(packet_list_model_->index(row, 0), Qt::ForegroundRole).toString();
2957 col_text += "<tr style=\"background-color:" + bg_color + ";color:" + fg_color + ";\">";
2958
2959 QString alignment[] = {"left", "right", "center", "justify"};
2960
2961 for (int col = 0; col < packet_list_model_->columnCount(); col++) {
2962 if (get_column_visible(col)) {
2963 col_text += "<td style=\"text-align:" + alignment[packet_list_model_->data(packet_list_model_->index(row, col), Qt::TextAlignmentRole).toInt() / 2] + ";\">";
2964 col_text += packet_list_model_->data(packet_list_model_->index(row, col), Qt::DisplayRole).toString();
2965 col_text += "</td>";
2966 }
2967 }
2968
2969 col_text += "</tr>";
2970 return col_text;
2971}
2972
2973QString PacketList::createClosingTagForHtml()
2974{
2975 return "</table>";
2976}
2977
2978void PacketList::copySummary()
2979{
2980 if (!currentIndex().isValid()) return;
2981
2982 QAction *ca = qobject_cast<QAction*>(sender());
2983 if (!ca) return;
2984
2985 QVariant type = ca->data();
2986 if (! type.canConvert<SummaryCopyType>())
2987 return;
2988 SummaryCopyType copy_type = type.value<SummaryCopyType>();
2989
2990 QString copy_text;
2991 if (type == CopyAsText || type == CopyAsHTML) {
2992 if (prefs.gui_packet_list_copy_text_with_aligned_columns) {
2993 QList<int> rows;
2994 rows << currentIndex().row();
2995 QStringList hdr_parts;
2996 QList<int> align_parts, size_parts;
2997 hdr_parts = createHeaderPartsForAligned();
2998 align_parts = createAlignmentPartsForAligned();
2999 size_parts = createSizePartsForAligned(false, hdr_parts, rows);
3000 copy_text = createSummaryForAligned(currentIndex(), align_parts, size_parts);
3001 }
3002 else {
3003 copy_text = createSummaryText(currentIndex(), CopyAsText);
3004 }
3005 copy_text += "\n";
3006 if (type == CopyAsHTML) {
3007 QStringList htmlContent;
3008 htmlContent << createDefaultStyleForHtml();
3009 htmlContent << createOpeningTagForHtml();
3010 htmlContent << createSummaryForHtml(currentIndex());
3011 htmlContent << createClosingTagForHtml();
3012 // htmlContent will never be empty as they will always have
3013 // style and table tags
3014 QMimeData *mimeData = new QMimeData;
3015 mimeData->setHtml(htmlContent.join('\n'));
3016 mimeData->setText(copy_text);
3017 mainApp->clipboard()->setMimeData(mimeData, QClipboard::Clipboard);
3018 }
3019 else {
3020 mainApp->clipboard()->setText(copy_text);
3021 }
3022 }
3023 else {
3024 copy_text = createSummaryText(currentIndex(), copy_type);
3025 if (type != CopyAsYAML)
3026 copy_text += "\n";
3027 mainApp->clipboard()->setText(copy_text);
3028 }
3029}
3030
3031// We need to tell when the user has scrolled the packet list, either to
3032// the end or anywhere other than the end.
3033void PacketList::vScrollBarActionTriggered(int)
3034{
3035 // If we're scrolling with a mouse wheel or trackpad sliderPosition can end up
3036 // past the end.
3037 tail_at_end_ = (overlay_sb_->sliderPosition() >= overlay_sb_->maximum());
3038
3039 scrollViewChanged(tail_at_end_);
3040}
3041
3042void PacketList::scrollViewChanged(bool at_end)
3043{
3044 if (capture_in_progress_) {
3045 // We want to start auto scrolling when the user scrolls to (or past)
3046 // the end only if recent.capture_auto_scroll is set.
3047 // We want to stop autoscrolling if the user scrolls up or uses
3048 // Go to Packet regardless of the preference setting.
3049 if (recent.capture_auto_scroll || !at_end) {
3050 emit packetListScrolled(at_end);
3051 }
3052 }
3053}
3054
3055// Goal: Overlay the packet list scroll bar with the colors of all of the
3056// packets.
3057// Try 1: Average packet colors in each scroll bar raster line. This has
3058// two problems: It's easy to wash out colors and we dissect every packet.
3059// Try 2: Color across a 5000 or 10000 packet window. We still end up washing
3060// out colors.
3061// Try 3: One packet per vertical scroll bar pixel. This seems to work best
3062// but has the smallest window.
3063// Try 4: Use a multiple of the scroll bar height and scale the image down
3064// using Qt::SmoothTransformation. This gives us more packets per raster
3065// line.
3066
3067// Odd (prime?) numbers resulted in fewer scaling artifacts. A multiplier
3068// of 9 washed out colors a little too much.
3069//const int height_multiplier_ = 7;
3070void PacketList::drawNearOverlay()
3071{
3072 if (create_near_overlay_) {
3073 create_near_overlay_ = false;
3074 }
3075
3076 if (!cap_file_ || cap_file_->state != FILE_READ_DONE) return;
3077
3078 if (!prefs.gui_packet_list_show_minimap) return;
3079
3080 qreal dp_ratio = overlay_sb_->devicePixelRatio();
3081 int o_height = overlay_sb_->height() * dp_ratio;
3082 int o_rows = qMin(packet_list_model_->rowCount(), o_height);
3083 QFontMetricsF fmf(mainApp->font());
3084 int o_width = ((static_cast<int>(fmf.height())) * 2 * dp_ratio) + 2; // 2ems + 1-pixel border on either side.
3085
3086 if (recent.packet_list_colorize && o_rows > 0) {
3087 QImage overlay(o_width, o_height, QImage::Format_ARGB32_Premultiplied);
3088
3089 QPainter painter(&overlay);
3090
3091 overlay.fill(Qt::transparent);
3092
3093 int cur_line = 0;
3094 int start = 0;
3095
3096 if (packet_list_model_->rowCount() > o_height && overlay_sb_->maximum() > 0) {
3097 start += ((double) overlay_sb_->value() / overlay_sb_->maximum()) * (packet_list_model_->rowCount() - o_rows);
3098 }
3099 int end = start + o_rows;
3100 for (int row = start; row < end; row++) {
3101 packet_list_model_->ensureRowColorized(row);
3102
3103 frame_data *fdata = packet_list_model_->getRowFdata(row);
3104 int next_line = (row - start + 1) * o_height / o_rows;
3105 int row_height = next_line - cur_line;
3106
3107 // Multi-color support in minimap (enabled for all non-Off modes)
3108 if (prefs.gui_packet_list_multi_color_mode != PACKET_LIST_MULTI_COLOR_MODE_OFF) {
3109 QModelIndex idx = packet_list_model_->index(row, 0);
3110 PacketListRecord *record = static_cast<PacketListRecord*>(idx.internalPointer());
3111 // Conversation color filters take full precedence — skip multi-color stripe rendering
3112 bool is_conversation_color = fdata->color_filter &&
3113 strncmp(((const color_filter_t *)fdata->color_filter)->filter_name,
3114 CONVERSATION_COLOR_PREFIX"___conversation_color_filter___", strlen(CONVERSATION_COLOR_PREFIX"___conversation_color_filter___")) == 0;
3115 if (record && record->hasMultipleColors() && !is_conversation_color) {
3116 // Draw vertical stripes for multiple colors (skip paused filters)
3117 const GSList *filters = record->matchingColorFilters();
3118
3119 // Count non-paused filters
3120 int num_active_colors = 0;
3121 for (const GSList *item = filters; item != NULL__null; item = g_slist_next(item)((item) ? (((GSList *)(item))->next) : __null)) {
3122 const color_filter_t *colorf = (const color_filter_t *)item->data;
3123 if (!color_filter_is_session_disabled(colorf->filter_name)) {
3124 num_active_colors++;
3125 }
3126 }
3127
3128 if (num_active_colors > 0) {
3129 int stripe_width = o_width / num_active_colors;
3130 int x_pos = 0;
3131 int stripe_idx = 0;
3132
3133 for (const GSList *item = filters; item != NULL__null; item = g_slist_next(item)((item) ? (((GSList *)(item))->next) : __null)) {
3134 const color_filter_t *colorf = (const color_filter_t *)item->data;
3135 // Skip paused filters
3136 if (!color_filter_is_session_disabled(colorf->filter_name)) {
3137 QColor color(ColorUtils::fromColorT(&colorf->bg_color));
3138 int width = (stripe_idx == num_active_colors - 1) ? (o_width - x_pos) : stripe_width;
3139 painter.fillRect(x_pos, cur_line, width, row_height, color);
3140 x_pos += stripe_width;
3141 stripe_idx++;
3142 }
3143 }
3144 } else {
3145 // All filters paused, draw no color
3146 painter.fillRect(0, cur_line, o_width, row_height, QColor(Qt::white));
3147 }
3148 } else if (fdata->color_filter) {
3149 // Single color fallback
3150 const color_filter_t *color_filter = (const color_filter_t *) fdata->color_filter;
3151 QColor color(ColorUtils::fromColorT(&color_filter->bg_color));
3152 painter.fillRect(0, cur_line, o_width, row_height, color);
3153 }
3154 } else {
3155 // Original single-color behavior
3156 const color_t *bgcolor = NULL__null;
3157 if (fdata->color_filter) {
3158 const color_filter_t *color_filter = (const color_filter_t *) fdata->color_filter;
3159 bgcolor = &color_filter->bg_color;
3160 }
3161
3162 if (bgcolor) {
3163 QColor color(ColorUtils::fromColorT(bgcolor));
3164 painter.fillRect(0, cur_line, o_width, row_height, color);
3165 }
3166 }
3167
3168 cur_line = next_line;
3169 }
3170
3171 // If the selected packet is in the overlay set selected_pos
3172 // accordingly. Otherwise, pin it to either the top or bottom.
3173 QList<int> positions;
3174 if (selectionModel()->hasSelection()) {
3175
3176 QModelIndexList selRows = selectionModel()->selectedRows(0);
3177 int last_row = -1;
3178 int last_pos = -1;
3179 foreach (QModelIndex idx, selRows)for (auto _container_3179 = QtPrivate::qMakeForeachContainer(
selRows); _container_3179.i != _container_3179.e; ++_container_3179
.i) if (QModelIndex idx = *_container_3179.i; false) {} else
3180 {
3181 int selected_pos = -1;
3182 int sel_row = idx.row();
3183 if (sel_row < start) {
3184 selected_pos = 0;
3185 } else if (sel_row >= end) {
3186 selected_pos = overlay.height() - 1;
3187 } else {
3188 selected_pos = (sel_row - start) * o_height / o_rows;
3189 }
3190
3191 /* Due to the difference in the display height, we sometimes get empty positions
3192 * inbetween consecutive valid rows. If those are detected, they are signaled as
3193 * being selected as well */
3194 if (last_pos >= 0 && selected_pos > (last_pos + 1) && (last_row + 1) == sel_row)
3195 {
3196 for (int pos = (last_pos + 1); pos < selected_pos; pos++)
3197 {
3198 if (! positions.contains(pos))
3199 positions << pos;
3200 }
3201 }
3202 else if (selected_pos != -1 && ! positions.contains(selected_pos))
3203 positions << selected_pos;
3204
3205 last_row = sel_row;
3206 last_pos = selected_pos;
3207 }
3208 }
3209
3210 overlay_sb_->setNearOverlayImage(overlay, packet_list_model_->rowCount(), start, end, positions, (o_height / o_rows));
3211 } else {
3212 QImage overlay;
3213 overlay_sb_->setNearOverlayImage(overlay);
3214 }
3215}
3216
3217void PacketList::drawFarOverlay()
3218{
3219 if (create_far_overlay_) {
3220 create_far_overlay_ = false;
3221 }
3222
3223 if (!cap_file_ || cap_file_->state != FILE_READ_DONE) return;
3224
3225 if (!prefs.gui_packet_list_show_minimap) return;
3226
3227 QSize groove_size = overlay_sb_->grooveRect().size();
3228 qreal dp_ratio = overlay_sb_->devicePixelRatio();
3229 groove_size *= dp_ratio;
3230 int o_width = groove_size.width();
3231 int o_height = groove_size.height();
3232 int pl_rows = packet_list_model_->rowCount();
3233 QImage overlay(o_width, o_height, QImage::Format_ARGB32_Premultiplied);
3234 bool have_marked_image = false;
3235
3236 // If only there were references from popular culture about getting into
3237 // some sort of groove.
3238 if (!overlay.isNull() && recent.packet_list_colorize && pl_rows > 0) {
3239
3240 QPainter painter(&overlay);
3241
3242 // Draw text-colored tick marks on a transparent background.
3243 // Hopefully no themes use the text color for the groove color.
3244 overlay.fill(Qt::transparent);
3245
3246 QColor tick_color = palette().text().color();
3247 tick_color.setAlphaF(0.3f);
3248 painter.setPen(tick_color);
3249
3250 for (int row = 0; row < pl_rows; row++) {
3251
3252 frame_data *fdata = packet_list_model_->getRowFdata(row);
3253 if (fdata->marked || fdata->ref_time || fdata->ignored) {
3254 int new_line = row * o_height / pl_rows;
3255 int tick_width = o_width / 3;
3256 // Marked or ignored: left side, time refs: right side.
3257 // XXX Draw ignored ticks in the middle?
3258 int x1 = fdata->ref_time ? o_width - tick_width : 1;
3259 int x2 = fdata->ref_time ? o_width - 1 : tick_width;
3260
3261 painter.drawLine(x1, new_line, x2, new_line);
3262 have_marked_image = true;
3263 }
3264 }
3265
3266 if (have_marked_image) {
3267 overlay_sb_->setMarkedPacketImage(overlay);
3268 return;
3269 }
3270 }
3271
3272 if (!have_marked_image) {
3273 QImage null_overlay;
3274 overlay_sb_->setMarkedPacketImage(null_overlay);
3275 }
3276}
3277
3278// Auto scroll if:
3279// - We are capturing
3280// - actionGoAutoScroll in the main UI is checked.
3281
3282// actionGoAutoScroll in the main UI:
3283// - Is set to the value of recent.capture_auto_scroll when beginning a capture
3284// - Can be triggered manually by the user
3285// - Is turned on if the last user-set vertical scrollbar position is at the
3286// end and recent.capture_auto_scroll is enabled
3287// - Is turned off if the last user-set vertical scrollbar is not at the end,
3288// or if one of the Go to Packet actions is used (XXX: Should keyboard
3289// navigation in keyPressEvent turn it off for similar reasons?)
3290void PacketList::rowsInserted(const QModelIndex &parent, int start, int end)
3291{
3292 QTreeView::rowsInserted(parent, start, end);
3293 const QModelIndex& cIndex = currentIndex();
3294 bool aggregation_mode = recent.aggregation_view && prefs.aggregation_fields_num > 0;
3295 if (aggregation_mode && cIndex.isValid() && cIndex.row() >= 0) {
3296 int row = cIndex.row();
3297 frame_data* fdata = getFDataForRow(row);
3298 if (fdata && cap_file_->current_frame->num != fdata->num) {
3299 cf_select_packet(cap_file_, fdata);
3300 emit framesSelected(QList<int>() << row);
3301 }
3302 }
3303 if (capture_in_progress_ && tail_at_end_) {
3304 scrollToBottom();
3305 }
3306}
3307
3308void PacketList::resizeAllColumns(bool onlyTimeFormatted)
3309{
3310 if (!cap_file_ || cap_file_->state == FILE_CLOSED || cap_file_->state == FILE_READ_PENDING)
3311 return;
3312
3313 for (unsigned col = 0; col < cap_file_->cinfo.num_cols; col++) {
3314 if (! onlyTimeFormatted || col_has_time_fmt(&cap_file_->cinfo, col)) {
3315 resizeColumnToContents(col);
3316 }
3317 }
3318}