Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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