Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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