Bug Summary

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