Bug Summary

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