Bug Summary

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