Bug Summary

File:builds/wireshark/wireshark/ui/qt/main_status_bar.cpp
Warning:line 824, column 9
Potential leak of memory pointed to by 'placer'

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 main_status_bar.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -fno-delete-null-pointer-checks -mframe-pointer=all -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -ffloat16-excess-precision=fast -fbfloat16-excess-precision=fast -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/builds/wireshark/wireshark/build -fcoverage-compilation-dir=/builds/wireshark/wireshark/build -resource-dir /usr/lib/llvm-22/lib/clang/22 -isystem /usr/include/glib-2.0 -isystem /usr/lib/x86_64-linux-gnu/glib-2.0/include -isystem /builds/wireshark/wireshark/build/ui/qt -isystem /builds/wireshark/wireshark/ui/qt -isystem /builds/wireshark/wireshark/ui/qt/lua_debugger -isystem /usr/include/x86_64-linux-gnu/qt6/QtConcurrent -isystem /usr/include/x86_64-linux-gnu/qt6 -isystem /usr/include/x86_64-linux-gnu/qt6/QtCore -isystem /usr/lib/x86_64-linux-gnu/qt6/mkspecs/linux-g++ -isystem /usr/include/x86_64-linux-gnu/qt6/QtNetwork -isystem /usr/include/x86_64-linux-gnu/qt6/QtPrintSupport -isystem /usr/include/x86_64-linux-gnu/qt6/QtGui -isystem /usr/include/x86_64-linux-gnu/qt6/QtWidgets -isystem /usr/include/x86_64-linux-gnu/qt6/QtSvg -isystem /usr/include/x86_64-linux-gnu/qt6/QtMultimedia -isystem /usr/include/x86_64-linux-gnu/qt6/QtDBus -D CARES_NO_DEPRECATED -D G_DISABLE_DEPRECATED -D G_DISABLE_SINGLE_INCLUDES -D QT_CONCURRENT_LIB -D QT_CORE_LIB -D QT_DBUS_LIB -D QT_GUI_LIB -D QT_MULTIMEDIA_LIB -D QT_NETWORK_LIB -D QT_PRINTSUPPORT_LIB -D QT_SVG_LIB -D QT_WIDGETS_LIB -D WS_DEBUG -D WS_DEBUG_UTF_8 -I /builds/wireshark/wireshark/build/ui/qt/qtui_autogen/include -I /builds/wireshark/wireshark/build -I /builds/wireshark/wireshark -I /builds/wireshark/wireshark/include -D _GLIBCXX_ASSERTIONS -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/x86_64-linux-gnu/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16/backward -internal-isystem /usr/lib/llvm-22/lib/clang/22/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/builds/wireshark/wireshark/= -fmacro-prefix-map=/builds/wireshark/wireshark/build/= -fmacro-prefix-map=../= -Wno-format-nonliteral -std=c++17 -fdeprecated-macro -ferror-limit 19 -fwrapv -fwrapv-pointer -fstrict-flex-arrays=3 -stack-protector 2 -fstack-clash-protection -fcf-protection=full -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fcxx-exceptions -fexceptions -fcolor-diagnostics -analyzer-output=html -faddrsig -fdwarf2-cfi-asm -o /builds/wireshark/wireshark/sbout/2026-11-28-100325-3662-1 -x c++ /builds/wireshark/wireshark/ui/qt/main_status_bar.cpp
1/* main_status_bar.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 "config.h"
11
12#include "file.h"
13
14#include <epan/expert.h>
15#include <epan/prefs.h>
16#include <epan/tag_rules.h>
17
18#include <wsutil/filesystem.h>
19#include <wsutil/utf8_entities.h>
20
21#include "ui/main_statusbar.h"
22#include <ui/qt/utils/qt_ui_utils.h>
23#include <ui/qt/main_window.h>
24
25#include "capture_file.h"
26#include "main_status_bar.h"
27#include "profile_dialog.h"
28#include <ui/qt/utils/color_utils.h>
29#include <ui/qt/utils/font_manager.h>
30#include <ui/qt/utils/theme_styler.h>
31#include <ui/qt/utils/zoom_scaling.h>
32#include <ui/qt/utils/themes/contrast_adapt_icon.h>
33#include <ui/qt/utils/themes/themed_icon.h>
34#include <ui/qt/capture_file.h>
35#include <ui/qt/widgets/clickable_label.h>
36#include <ui/recent.h>
37
38#include <QAction>
39#include <QHBoxLayout>
40#include <QMenu>
41#include <QPainter>
42#include <QScreen>
43#include <QSplitter>
44#include <QStyle>
45#include <QStyleOption>
46#include <QToolButton>
47#include <QLatin1Char>
48
49#include <functional>
50
51// To do:
52// - Use the CaptureFile class.
53
54// XXX - The GTK+ code assigns priorities to these and pushes/pops accordingly.
55
56Q_DECLARE_METATYPE(ProfileDialog::ProfileAction)template <> struct QMetaTypeId< ProfileDialog::ProfileAction
> { enum { Defined = 1 }; static_assert(QtPrivate::checkTypeIsSuitableForMetaType
<ProfileDialog::ProfileAction>()); static int qt_metatype_id
() { [[clang::require_constant_initialization]] static QBasicAtomicInt
metatype_id = { 0 }; if (const int id = metatype_id.loadAcquire
()) return id; constexpr auto arr = QtPrivate::typenameHelper
<ProfileDialog::ProfileAction>(); auto name = arr.data(
); if (QByteArrayView(name) == ("ProfileDialog::ProfileAction"
)) { const int id = qRegisterNormalizedMetaType<ProfileDialog
::ProfileAction>(name); metatype_id.storeRelease(id); return
id; } const int newId = qRegisterMetaType< ProfileDialog::
ProfileAction >("ProfileDialog::ProfileAction"); metatype_id
.storeRelease(newId); return newId; } };
57
58// The profile menu opens near the right edge of the screen. Without room on
59// the right, Qt opens a submenu on the left, but its submenus on the right
60// again, on top of the menus they were opened from. Once a submenu has been
61// opened on the left, keep opening its submenus on the left.
62class SubMenuPlacer : public QObject
63{
64public:
65 explicit SubMenuPlacer(QObject *parent) : QObject(parent) {}
66
67protected:
68 bool eventFilter(QObject *obj, QEvent *event) override
69 {
70 QMenu *menu = qobject_cast<QMenu *>(obj);
71 if (event->type() != QEvent::Show || !menu)
72 return false;
73
74 QMenu *parentMenu = qobject_cast<QMenu *>(menu->parentWidget());
75 QMenu *grandMenu = parentMenu ? qobject_cast<QMenu *>(parentMenu->parentWidget()) : Q_NULLPTRnullptr;
76 if (!grandMenu || parentMenu->x() >= grandMenu->x() || menu->x() < parentMenu->x())
77 return false;
78
79 QPoint pos(parentMenu->x() - menu->width(), menu->y());
80 if (menu->screen() && pos.x() >= menu->screen()->availableGeometry().left())
81 menu->move(pos);
82 return false;
83 }
84};
85
86// Menu actions with this property set are drawn with a double chevron
87// instead of a checkmark.
88static const char *profile_path_property_ = "profile_path";
89
90// The profile menu marks the current profile with a checkmark, and the
91// submenus on the path to it with a right-pointing double chevron icon. The
92// double chevron is drawn where the style draws a checkmark.
93class ProfileMenuStyle : public ThemeStyler
94{
95public:
96 ProfileMenuStyle() :
97 ThemeStyler(ThemeStyler::baseStyleName()),
98 chevron_icon_(QStringLiteral(":/svg_icons/profile-path.svg")(QString(QtPrivate::qMakeStringPrivate(u"" ":/svg_icons/profile-path.svg"
)))
,
99 ThemeManager::PaletteText, ThemeManager::PaletteHighlightedText)
100 {}
101
102 void drawControl(ControlElement element, const QStyleOption *option,
103 QPainter *painter, const QWidget *widget) const override
104 {
105 const QStyleOptionMenuItem *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(option);
106 const QMenu *menu = qobject_cast<const QMenu *>(widget);
107 QAction *action = (element == CE_MenuItem && menuItem && menu) ?
108 menu->actionAt(menuItem->rect.center()) : Q_NULLPTRnullptr;
109 if (!action || !action->property(profile_path_property_).toBool()) {
110 ThemeStyler::drawControl(element, option, painter, widget);
111 return;
112 }
113
114 // Draw the item as checked, and the double chevron in place of the checkmark
115 QStyleOptionMenuItem pathItem(*menuItem);
116 pathItem.checkType = QStyleOptionMenuItem::NonExclusive;
117 pathItem.checked = true;
118 chevron_item_ = &pathItem;
119 ThemeStyler::drawControl(element, &pathItem, painter, widget);
120 chevron_item_ = Q_NULLPTRnullptr;
121 }
122
123 void drawPrimitive(PrimitiveElement element, const QStyleOption *option,
124 QPainter *painter, const QWidget *widget) const override
125 {
126 // The checkmark is drawn as PE_IndicatorMenuCheckMark, or as
127 // PE_IndicatorCheckBox by Fusion
128 if (!chevron_item_ ||
129 (element != PE_IndicatorMenuCheckMark && element != PE_IndicatorCheckBox)) {
130 ThemeStyler::drawPrimitive(element, option, painter, widget);
131 return;
132 }
133
134 // The double chevron, as tall as a line of the menu item text so it
135 // follows the zoom, centered where the checkmark goes and on the
136 // capital letters of the vertically centered text
137 const QRect &itemRect = chevron_item_->rect;
138 QFontMetrics fm(chevron_item_->font);
139 int x = option->rect.center().x();
140 int textTop = itemRect.top() + (itemRect.height() - fm.height()) / 2;
141#ifdef Q_OS_MACOS
142 // The macOS style gives a check area narrower than the checkmark,
143 // starts the text 18 pixels into the menu item, which ThemeStyler
144 // widens with the zoom, and draws the text from the top of the menu
145 // item
146 if (baseStyleName() == QLatin1String("macos")) {
147 x = itemRect.left() + ZoomScaling::scaledPixels(18) / 2;
148 textTop = itemRect.top();
149 }
150#endif
151 QRect iconRect(0, 0, fm.height(), fm.height());
152 iconRect.moveCenter(QPoint(x, textTop + fm.ascent() - fm.capHeight() / 2));
153 QIcon::Mode mode = (chevron_item_->state & State_Selected) ? QIcon::Selected : QIcon::Normal;
154 chevron_icon_.paint(painter, iconRect, Qt::AlignCenter, mode);
155 }
156
157private:
158 ThemedIcon chevron_icon_;
159 // The menu item being drawn with a double chevron, null otherwise
160 mutable const QStyleOptionMenuItem *chevron_item_ = Q_NULLPTRnullptr;
161};
162
163// If we ever add support for multiple windows this will need to be replaced.
164// See also: main_window.cpp
165static MainStatusBar *cur_main_status_bar_;
166
167/*
168 * Push a formatted temporary message onto the statusbar.
169 */
170void
171statusbar_push_temporary_msg(const char *msg_format, ...)
172{
173 va_list ap;
174 QString push_msg;
175
176 if (!cur_main_status_bar_) return;
177
178 va_start(ap, msg_format)__builtin_va_start(ap, msg_format);
179 push_msg = QString::vasprintf(msg_format, ap);
180 va_end(ap)__builtin_va_end(ap);
181
182 mainApp->pushStatus(WiresharkApplication::TemporaryStatus, push_msg);
183}
184
185/*
186 * Update the packets statusbar to the current values
187 */
188void
189packets_bar_update(void)
190{
191 if (!cur_main_status_bar_) return;
192
193 cur_main_status_bar_->updateCaptureStatistics(NULL__null);
194}
195
196MainStatusBar::MainStatusBar(QWidget *parent) :
197 QStatusBar(parent),
198 cap_file_(NULL__null),
199 cs_fixed_(false),
200 cs_count_(0),
201 profile_menu_style_(new ProfileMenuStyle)
202{
203 profile_menu_style_->setParent(this);
204 QSplitter *splitter = new QSplitter(this);
205 QWidget *info_progress = new QWidget(this);
206 info_progress_hb_ = new QHBoxLayout(info_progress);
207
208#if defined(Q_OS_WIN)
209 // Handles are the same color as widgets, at least on Windows 7.
210 splitter->setHandleWidth(3);
211 splitter->setStyleSheet(QStringLiteral((QString(QtPrivate::qMakeStringPrivate(u"" "QSplitter::handle {"
" border-left: 1px solid palette(mid);" " border-right: 1px solid palette(mid);"
"}")))
212 "QSplitter::handle {"(QString(QtPrivate::qMakeStringPrivate(u"" "QSplitter::handle {"
" border-left: 1px solid palette(mid);" " border-right: 1px solid palette(mid);"
"}")))
213 " border-left: 1px solid palette(mid);"(QString(QtPrivate::qMakeStringPrivate(u"" "QSplitter::handle {"
" border-left: 1px solid palette(mid);" " border-right: 1px solid palette(mid);"
"}")))
214 " border-right: 1px solid palette(mid);"(QString(QtPrivate::qMakeStringPrivate(u"" "QSplitter::handle {"
" border-left: 1px solid palette(mid);" " border-right: 1px solid palette(mid);"
"}")))
215 "}"(QString(QtPrivate::qMakeStringPrivate(u"" "QSplitter::handle {"
" border-left: 1px solid palette(mid);" " border-right: 1px solid palette(mid);"
"}")))
216 )(QString(QtPrivate::qMakeStringPrivate(u"" "QSplitter::handle {"
" border-left: 1px solid palette(mid);" " border-right: 1px solid palette(mid);"
"}")))
);
217#endif
218
219#ifdef Q_OS_MACOS
220 profile_status_.setAttribute(Qt::WA_MacSmallSize, true);
221#endif
222
223 QString button_ss =
224 "QToolButton {"
225 " border: none;"
226 " background: transparent;" // Disables platform style on Windows.
227 " padding: 0px;"
228 " margin: 0px;"
229 "}";
230
231 QString label_ss =
232 "QLabel {"
233 " margin-left: 0.5em;"
234 "}";
235
236 expert_button_ = new QToolButton(this);
237 expert_button_->setStyleSheet(button_ss);
238 expert_button_->setAccessibleName(tr("Expert information"));
239 expert_button_->setAccessibleDescription(tr("Opens the expert information dialog, showing errors, warnings, and other relevant information about the capture."));
240 expert_button_->hide();
241
242 // We just want a clickable image. Using a QPushButton or QToolButton would require
243 // a lot of adjustment.
244 ThemedIcon comment_icon(QStringLiteral(":/svg_icons/capture-comment.svg")(QString(QtPrivate::qMakeStringPrivate(u"" ":/svg_icons/capture-comment.svg"
)))
, ThemeManager::PaletteText);
245 comment_button_ = new QToolButton(this);
246 comment_button_->setIcon(comment_icon);
247 comment_button_->setStyleSheet(button_ss);
248 comment_button_->setAccessibleName(tr("Capture comment"));
249 comment_button_->setAccessibleDescription(tr("Opens the Capture File Properties dialog to view or edit capture-level comments."));
250
251 comment_button_->setToolTip(tr("Open the Capture File Properties dialog"));
252 comment_button_->setEnabled(false);
253 connect(expert_button_, &QToolButton::clicked, this, &MainStatusBar::showExpertInfo);
254 connect(comment_button_, &QToolButton::clicked, this, &MainStatusBar::editCaptureComment);
255
256 applyIconSizes();
257 connect(FontManager::instance(), &FontManager::zoomChanged, this, &MainStatusBar::applyIconSizes);
258
259 info_status_.setTemporaryContext(STATUS_CTX_TEMPORARY);
260 info_status_.setShrinkable(true);
261 info_status_.setAccessibleName(tr("Information"));
262 info_status_.setAccessibleDescription(tr("Displays general information, status messages, and expert severity details."));
263
264 info_progress_hb_->addWidget(expert_button_);
265 info_progress_hb_->addWidget(comment_button_);
266 info_progress_hb_->addWidget(&info_status_);
267 info_progress_hb_->addWidget(&progress_frame_);
268 info_progress_hb_->addStretch(10);
269
270 // LabelStack does setStyleSheet for QLabel but ClickableLabel does not
271 packet_status_.setAccessibleName(tr("Packet statistics"));
272 packet_status_.setAccessibleDescription(tr("Shows the number of captured, displayed, and selected packets."));
273 profile_status_.setStyleSheet(label_ss);
274 // The profile menus, created in the status bar, have many neighbouring
275 // submenus, which open as the mouse moves over them
276 ThemeStyler::setPlainSubMenus(this);
277 profile_status_.setAccessibleName(tr("Configuration profile"));
278 profile_status_.setAccessibleDescription(tr("Displays the current configuration profile and allows switching between profiles."));
279
280 splitter->addWidget(info_progress);
281 splitter->addWidget(&packet_status_);
282 splitter->addWidget(&profile_status_);
283
284 splitter->setStretchFactor(0, 3);
285 splitter->setStretchFactor(1, 3);
286 splitter->setStretchFactor(2, 1);
287
288 addWidget(splitter, 1);
289
290 cur_main_status_bar_ = this;
291
292 splitter->hide();
293 setReadyMsg();
294 packets_bar_update();
295
296#ifdef QWINTASKBARPROGRESS_H
297 progress_frame_.enableTaskbarUpdates(true);
298#endif
299
300 mainApp->whenInitialized(splitter, [splitter]() { splitter->show(); });
301 mainApp->whenInitialized(this, [this]() { appInitialized(); });
302 connect(&info_status_, &LabelStack::toggleTemporaryFlash, this, &MainStatusBar::toggleBackground);
303 connect(mainApp, &MainApplication::profileNameChanged, this, &MainStatusBar::setProfileName);
304 connect(&profile_status_, &ClickableLabel::clickedAt, this, &MainStatusBar::showProfileMenu);
305
306 connect(&progress_frame_, &ProgressFrame::stopLoading, this, &MainStatusBar::stopLoading);
307}
308
309MainStatusBar::~MainStatusBar()
310{
311
312}
313
314
315void MainStatusBar::showExpert() {
316 expertUpdate();
317}
318
319void MainStatusBar::captureFileClosing() {
320 expert_button_->hide();
321 progress_frame_.captureFileClosing();
322 field_status_supplement_.clear();
323 field_status_include_base_ = true;
324 field_status_base_.clear();
325 popGenericStatus(STATUS_CTX_FIELD);
326}
327
328void MainStatusBar::expertUpdate() {
329 // <img> won't load @2x versions in Qt versions earlier than 5.4.
330 // https://bugreports.qt.io/browse/QTBUG-36383
331 // We might have to switch to a QPushButton.
332 QString stock_name = "expert-";
333 QString tt_text = tr(" is the highest expert information level");
334
335 switch(expert_get_highest_severity()) {
336 case(PI_ERROR0x00800000):
337 stock_name.append("error");
338 tt_text.prepend(tr("ERROR"));
339 break;
340 case(PI_WARN0x00600000):
341 stock_name.append("warn");
342 tt_text.prepend(tr("WARNING"));
343 break;
344 case(PI_NOTE0x00400000):
345 stock_name.append("note");
346 tt_text.prepend(tr("NOTE"));
347 break;
348 case(PI_CHAT0x00200000):
349 stock_name.append("chat");
350 tt_text.prepend(tr("CHAT"));
351 break;
352 default:
353 stock_name.append("none");
354 tt_text = tr("No expert information");
355 break;
356 }
357
358 ContrastAdaptIcon expert_icon(QStringLiteral(":/svg_icons/")(QString(QtPrivate::qMakeStringPrivate(u"" ":/svg_icons/"))) + stock_name.toLatin1() + QStringLiteral(".svg")(QString(QtPrivate::qMakeStringPrivate(u"" ".svg"))),
359 QPalette::Window);
360 applyIconSizes();
361 expert_button_->setIcon(expert_icon);
362 expert_button_->setToolTip(tt_text);
363 expert_button_->show();
364}
365
366// ui/gtk/main_statusbar.c
367void MainStatusBar::setFileName(CaptureFile &cf)
368{
369 if (cf.isValid()) {
370 popGenericStatus(STATUS_CTX_FILE);
371 QString msgtip = QStringLiteral("%1 (%2)")(QString(QtPrivate::qMakeStringPrivate(u"" "%1 (%2)")))
372 .arg(cf.capFile()->filename, file_size_to_qstring(cf.capFile()->f_datalen));
373 pushGenericStatus(STATUS_CTX_FILE, cf.fileName(), msgtip);
374 }
375}
376
377void MainStatusBar::setReadyMsg()
378{
379#ifdef HAVE_LIBPCAP1
380 QString ready_msg(tr("Ready to load or capture"));
381#else
382 QString ready_msg(tr("Ready to load file"));
383#endif
384 info_status_.pushText(std::move(ready_msg), STATUS_CTX_MAIN);
385}
386
387void MainStatusBar::applyIconSizes()
388{
389 // Both indicators match the display filter toolbar icons. They are not
390 // sized from the status text, whose font is smaller on macOS.
391 const int side = ZoomScaling::barIconSize();
392 expert_button_->setIconSize(QSize(side, side));
393 comment_button_->setIconSize(QSize(side, side));
394 info_progress_hb_->setContentsMargins(side / 2, 0, 0, 0);
395}
396
397void MainStatusBar::changeEvent(QEvent *event)
398{
399 if (event->type() == QEvent::LanguageChange) {
400 info_status_.popText(STATUS_CTX_MAIN);
401 setReadyMsg();
402 setStatusbarForCaptureFile();
403 showCaptureStatistics();
404 setProfileName();
405 }
406 if (event->type() == QEvent::FontChange || event->type() == QEvent::ApplicationFontChange) {
407 applyIconSizes();
408 }
409 QStatusBar::changeEvent(event);
410}
411
412void MainStatusBar::setCaptureFile(capture_file *cf)
413{
414 cap_file_ = cf;
415 comment_button_->setEnabled(cap_file_ != NULL__null);
416}
417
418void MainStatusBar::setStatusbarForCaptureFile()
419{
420 if (cap_file_ && cap_file_->filename && (cap_file_->state != FILE_CLOSED)) {
421 popGenericStatus(STATUS_CTX_FILE);
422 QString msgtip = QStringLiteral("%1 (%2)")(QString(QtPrivate::qMakeStringPrivate(u"" "%1 (%2)")))
423 .arg(cap_file_->filename, file_size_to_qstring(cap_file_->f_datalen));
424 pushGenericStatus(STATUS_CTX_FILE,
425 gchar_free_to_qstring(cf_get_display_name(cap_file_)), msgtip);
426 }
427}
428
429void MainStatusBar::setFieldStatusSupplement(const QString &supplement, bool include_selected_field)
430{
431 field_status_supplement_ = supplement;
432 field_status_include_base_ = include_selected_field;
433 refreshFieldStatus();
434}
435
436void MainStatusBar::refreshFieldStatus()
437{
438 QString display;
439 if (!field_status_supplement_.isEmpty()) {
440 display = field_status_supplement_;
441 if (field_status_include_base_ && !field_status_base_.isEmpty()) {
442 display += QLatin1Char(' ') + field_status_base_;
443 }
444 } else {
445 display = field_status_base_;
446 }
447 pushGenericStatus(STATUS_CTX_FIELD, display);
448}
449
450void MainStatusBar::selectedFieldChanged(FieldInformation * finfo)
451{
452 QString item_info;
453
454 if (! finfo) {
455 field_status_base_.clear();
456 refreshFieldStatus();
457 return;
458 }
459
460 FieldInformation::HeaderInfo hInfo = finfo->headerInfo();
461
462 if (hInfo.isValid)
463 {
464 /* For frame.tag items, show the rule's comment in the status bar instead of the blurb. */
465 if (hInfo.abbreviation == "frame.tag") {
466 field_info *fi = finfo->fieldInfo();
467 const char *rule_name = fi ? fvalue_get_string(fi->value) : nullptr;
468 QString comment_str;
469 if (rule_name) {
470 for (const GSList *r = tag_rules_get_list(); r; r = g_slist_next(r)((r) ? (((GSList *)(r))->next) : __null)) {
471 const tag_rule_t *rule = (const tag_rule_t *)r->data;
472 if (strcmp(rule->rule_name, rule_name) == 0) {
473 if (rule->comment && rule->comment[0])
474 comment_str = QString::fromUtf8(rule->comment);
475 break;
476 }
477 }
478 }
479 item_info.append(comment_str.isEmpty() ? hInfo.description : comment_str);
480 } else if (hInfo.description.length() > 0) {
481 item_info.append(hInfo.description);
482 } else {
483 item_info.append(hInfo.name);
484 }
485 }
486
487 if (!item_info.isEmpty()) {
488 int finfo_length;
489 if (hInfo.isValid)
490 item_info.append(" (" + hInfo.abbreviation + ")");
491
492 finfo_length = finfo->position().length + finfo->appendix().length;
493 if (finfo_length > 0) {
494 int finfo_bits = FI_GET_BITS_SIZE(finfo->fieldInfo())(((finfo->fieldInfo()) ? ((finfo->fieldInfo())->flags
& ((((63) & 63) << 12))) : 0) >> 12)
;
495 if (finfo_bits % 8 == 0) {
496 item_info.append(", " + tr("%Ln byte(s)", "", finfo_length));
497 } else {
498 item_info.append(", " + tr("%Ln bit(s)", "", finfo_bits));
499 }
500 }
501 }
502
503 field_status_base_ = item_info;
504 refreshFieldStatus();
505}
506
507void MainStatusBar::highlightedFieldChanged(FieldInformation * finfo)
508{
509 QString hint;
510
511 if (finfo)
512 {
513 FieldInformation::Position pos = finfo->position();
514
515 if (pos.length < 2) {
516 hint = tr("Byte %1").arg(pos.start);
517 } else {
518 hint = tr("Bytes %1-%2").arg(pos.start).arg(pos.start + pos.length - 1);
519 }
520 hint += QStringLiteral(": %1 (%2)")(QString(QtPrivate::qMakeStringPrivate(u"" ": %1 (%2)")))
521 .arg(finfo->headerInfo().name, finfo->headerInfo().abbreviation);
522 }
523
524 pushGenericStatus(STATUS_CTX_BYTE, hint);
525}
526
527void MainStatusBar::pushGenericStatus(StatusContext status, const QString &message, const QString &messagetip)
528{
529 LabelStack * stack = &info_status_;
530
531 if (status == STATUS_CTX_MAIN)
532 stack = &packet_status_;
533
534 if (message.isEmpty() && status != STATUS_CTX_FILE && status != STATUS_CTX_TEMPORARY && status != STATUS_CTX_PROGRESS)
535 popGenericStatus(status);
536 else
537 stack->pushText(message, status, messagetip);
538
539 if (status == STATUS_CTX_FILTER || status == STATUS_CTX_FILE)
540 expertUpdate();
541}
542
543void MainStatusBar::popGenericStatus(StatusContext status)
544{
545 LabelStack * stack = &info_status_;
546
547 if (status == STATUS_CTX_MAIN)
548 stack = &packet_status_;
549
550 stack->popText(status);
551}
552
553void MainStatusBar::setProfileName()
554{
555 profile_status_.setText(tr("Profile: %1").arg(get_profile_name()));
556}
557
558void MainStatusBar::appInitialized()
559{
560 setProfileName();
561 connect(mainApp->mainWindow(), &MainWindow::framesSelected, this, &MainStatusBar::selectedFrameChanged);
562}
563
564void MainStatusBar::selectedFrameChanged(QList<int>)
565{
566 showCaptureStatistics();
567}
568
569void MainStatusBar::showCaptureStatistics()
570{
571 QString packets_str;
572
573 QList<int> rows;
574 MainWindow * mw = mainApp->mainWindow();
575 // Only a single selected packet is shown, so don't build the
576 // list of a large selection.
577 if (mw && !mw->hasSelection()) {
578 rows = mw->selectedRows(true);
579 }
580
581#ifdef HAVE_LIBPCAP1
582 if (cap_file_) {
583 /* Do we have any packets? */
584 if (!cs_fixed_) {
585 cs_count_ = cap_file_->count;
586 }
587 if (cs_count_ > 0) {
588 if (prefs.gui_show_selected_packet && rows.count() == 1) {
589 packets_str.append(tr("Selected Packet: %1 %2 ")
590 .arg(rows.at(0))
591 .arg(UTF8_MIDDLE_DOT"\u00b7"));
592 }
593 packets_str.append(tr("Packets: %1").arg(cs_count_));
594
595 if (cap_file_->dfilter) {
596 packets_str.append(tr(" %1 Displayed: %2 (%3%)")
597 .arg(UTF8_MIDDLE_DOT"\u00b7")
598 .arg(cap_file_->displayed_count)
599 .arg((100.0*cap_file_->displayed_count)/cs_count_, 0, 'f', 1));
600 }
601 if (recent.aggregation_view) {
602 packets_str.append(tr(" %1 Aggregated: %2")
603 .arg(UTF8_MIDDLE_DOT"\u00b7")
604 .arg(cap_file_->aggregation_count));
605 }
606 if (rows.count() > 1) {
607 packets_str.append(tr(" %1 Selected: %2 (%3%)")
608 .arg(UTF8_MIDDLE_DOT"\u00b7")
609 .arg(rows.count())
610 .arg((100.0*rows.count())/cs_count_, 0, 'f', 1));
611 }
612 if (cap_file_->marked_count > 0) {
613 packets_str.append(tr(" %1 Marked: %2 (%3%)")
614 .arg(UTF8_MIDDLE_DOT"\u00b7")
615 .arg(cap_file_->marked_count)
616 .arg((100.0*cap_file_->marked_count)/cs_count_, 0, 'f', 1));
617 }
618 if (cap_file_->drops_known) {
619 packets_str.append(tr(" %1 Dropped: %2 (%3%)")
620 .arg(UTF8_MIDDLE_DOT"\u00b7")
621 .arg(cap_file_->drops)
622 .arg((100.0*cap_file_->drops)/(cs_count_ + cap_file_->drops), 0, 'f', 1));
623 }
624 if (cap_file_->ignored_count > 0) {
625 packets_str.append(tr(" %1 Ignored: %2 (%3%)")
626 .arg(UTF8_MIDDLE_DOT"\u00b7")
627 .arg(cap_file_->ignored_count)
628 .arg((100.0*cap_file_->ignored_count)/cs_count_, 0, 'f', 1));
629 }
630 if (cap_file_->packet_comment_count > 0) {
631 packets_str.append(tr(" %1 Comments: %2")
632 .arg(UTF8_MIDDLE_DOT"\u00b7")
633 .arg(cap_file_->packet_comment_count));
634 }
635 if (prefs.gui_show_file_load_time && !cap_file_->is_tempfile) {
636 /* Loading an existing file */
637 unsigned long computed_elapsed = cf_get_computed_elapsed(cap_file_);
638 packets_str.append(tr(" %1 Load time: %2:%3.%4")
639 .arg(UTF8_MIDDLE_DOT"\u00b7")
640 .arg(computed_elapsed/60000, 2, 10, QLatin1Char('0'))
641 .arg(computed_elapsed%60000/1000, 2, 10, QLatin1Char('0'))
642 .arg(computed_elapsed%1000, 3, 10, QLatin1Char('0')));
643 }
644 }
645 } else if (cs_fixed_ && cs_count_ > 0) {
646 /* There shouldn't be any rows without a cap_file_ but this is benign */
647 if (prefs.gui_show_selected_packet && rows.count() == 1) {
648 packets_str.append(tr("Selected Packet: %1 %2 ")
649 .arg(rows.at(0))
650 .arg(UTF8_MIDDLE_DOT"\u00b7"));
651 }
652 packets_str.append(tr("Packets: %1")
653 .arg(cs_count_));
654 }
655#endif // HAVE_LIBPCAP
656
657 if (packets_str.isEmpty()) {
658 packets_str = tr("No Packets");
659 }
660
661 popGenericStatus(STATUS_CTX_MAIN);
662 pushGenericStatus(STATUS_CTX_MAIN, packets_str);
663}
664
665// These two counts are different in multiple file mode. cap_session->count
666// is the total number in the session across all files; cap_file_->count is
667// count in the current file. Perhaps we could display both in both cases?
668
669void MainStatusBar::updateCaptureStatistics(capture_session *cap_session)
670{
671 cs_fixed_ = false;
672
673#ifndef HAVE_LIBPCAP1
674 Q_UNUSED(cap_session)(void)cap_session;
675#else
676 if ((!cap_session || cap_session->cf == cap_file_) && cap_file_ && cap_file_->count) {
677 cs_count_ = cap_file_->count;
678 } else {
679 cs_count_ = 0;
680 }
681#endif // HAVE_LIBPCAP
682
683 showCaptureStatistics();
684}
685
686void MainStatusBar::updateCaptureFixedStatistics(capture_session *cap_session)
687{
688 cs_fixed_ = true;
689
690#ifndef HAVE_LIBPCAP1
691 Q_UNUSED(cap_session)(void)cap_session;
692#else
693 if (cap_session && cap_session->count) {
694 cs_count_ = cap_session->count;
695 } else {
696 cs_count_ = 0;
697 }
698#endif // HAVE_LIBPCAP
699
700 showCaptureStatistics();
701}
702
703void MainStatusBar::showProfileMenu(const QPoint &global_pos, Qt::MouseButton button)
704{
705 //Use the model object to pull the profile information
706 ProfileModel model;
707 ProfileSortModel sortModel;
708 sortModel.setSourceModel(&model);
709 sortModel.sort(0, Qt::DescendingOrder);
710
711 QMenu * ctx_menu_;
712 QMenu * profile_menu;
713 if (button == Qt::LeftButton) {
1
Assuming 'button' is equal to LeftButton
2
Taking true branch
714 ctx_menu_ = nullptr;
715 profile_menu = new QMenu(this);
716 profile_menu->setAttribute(Qt::WA_DeleteOnClose);
717 } else {
718 ctx_menu_ = new QMenu(this);
719 ctx_menu_->setAttribute(Qt::WA_DeleteOnClose);
720 profile_menu = new QMenu(ctx_menu_);
721 }
722
723 const ProfileItem* currentProfile = model.getCurrentProfile();
724
725 // Add the profiles of one scope, using a submenu for profiles with children
726 std::function<void(QMenu *, const QModelIndex &, bool)> addProfiles;
727 // NOLINTNEXTLINE(misc-no-recursion)
728 addProfiles = [&](QMenu * menu, const QModelIndex &parent, bool global) {
729 for (int i = 0; i < sortModel.rowCount(parent); ++i)
730 {
731 //Go through the proxy model to get the profile information in the right order
732 QModelIndex proxyIndex = sortModel.index(i, 0, parent);
733 const ProfileItem* profile = model.getProfile(sortModel.mapToSource(proxyIndex));
734 if (profile == Q_NULLPTRnullptr || profile->isGlobal() != global)
735 continue;
736
737 /* Check if this profile does not exist as user */
738 bool hidden = global && model.getPersonalProfile(profile->getName()) != Q_NULLPTRnullptr;
739 bool hasChildren = sortModel.rowCount(proxyIndex) > 0;
740 if (hidden && !hasChildren)
741 continue;
742
743 // An ampersand in the menu item's text sets Alt+F as a shortcut for this menu.
744 // Use "&&" to get a real ampersand in the menu bar.
745 QString name = profile->getLeafName();
746 name.replace('&', "&&");
747
748 QMenu * subMenu = hasChildren ? menu->addMenu(name) : menu;
749
750 if (hasChildren)
751 {
752 QAction *subMenuAction = subMenu->menuAction();
753 QFont subMenuFont = subMenuAction->font();
754 subMenuFont.setItalic(profile->isGlobal());
755 bool sameScope = (currentProfile != Q_NULLPTRnullptr) &&
756 profile->isGlobal() == currentProfile->isGlobal();
757 bool isCurrent = sameScope &&
758 currentProfile->getName().compare(profile->getName()) == 0;
759 bool isAncestor = sameScope &&
760 currentProfile->getName().startsWith(profile->getName() + "/");
761 // Show the path to the current profile in bold, with a checkmark
762 // on the current profile and a double chevron on its ancestors
763 if (isCurrent)
764 {
765 subMenuFont.setBold(true);
766 subMenuAction->setCheckable(true);
767 subMenuAction->setChecked(true);
768 }
769 else if (isAncestor)
770 {
771 subMenuFont.setBold(true);
772 subMenuAction->setProperty(profile_path_property_, true);
773 }
774 subMenuAction->setFont(subMenuFont);
775 }
776 if (!hidden)
777 {
778 QAction * pa = subMenu->addAction(name);
779 QFont profileFont;
780 pa->setCheckable(true);
781 if ((currentProfile != Q_NULLPTRnullptr) &&
782 (profile->getName().compare(currentProfile->getName()) == 0) &&
783 profile->isGlobal() == currentProfile->isGlobal())
784 {
785 profileFont.setBold(true);
786 pa->setChecked(true);
787 }
788
789 if (profile->isGlobal())
790 profileFont.setItalic(true);
791
792 pa->setFont(profileFont);
793 pa->setProperty("profile_name", profile->getName());
794 pa->setProperty("profile_is_global", profile->isGlobal());
795
796 connect(pa, &QAction::triggered, this, &MainStatusBar::switchToProfile);
797 }
798
799 if (hasChildren)
800 {
801 subMenu->addSeparator();
802 addProfiles(subMenu, proxyIndex, global);
803
804 // Remove a submenu with only the separator, when the profile and all its children are hidden
805 if (subMenu->actions().count() <= 1)
806 delete subMenu;
807 }
808 }
809 };
810
811 addProfiles(profile_menu, QModelIndex(), false);
812 profile_menu->addSeparator();
813 addProfiles(profile_menu, QModelIndex(), true);
814
815 SubMenuPlacer *placer = new SubMenuPlacer(profile_menu);
3
Memory is allocated
816 profile_menu->setStyle(profile_menu_style_);
817 for (QMenu *subMenu : profile_menu->findChildren<QMenu *>())
818 {
819 subMenu->installEventFilter(placer);
820 subMenu->setStyle(profile_menu_style_);
821 }
822
823 if (button
3.1
'button' is equal to LeftButton
== Qt::LeftButton) {
4
Taking true branch
824 profile_menu->popup(global_pos);
5
Potential leak of memory pointed to by 'placer'
825 } else {
826
827 bool enable_edit = false;
828
829 if ((currentProfile != Q_NULLPTRnullptr) && !currentProfile->isDefault() && !currentProfile->isGlobal())
830 enable_edit = true;
831
832 profile_menu->setTitle(tr("Switch to"));
833 QAction * action = ctx_menu_->addAction(tr("Manage Profiles…"), this, SLOT(manageProfile())qFlagLocation("1" "manageProfile()" "\0" "ui/qt/main_status_bar.cpp"
":" "833")
);
834 action->setProperty("dialog_action_", (int)ProfileDialog::ShowProfiles);
835
836 ctx_menu_->addSeparator();
837 action = ctx_menu_->addAction(tr("New…"), this, SLOT(manageProfile())qFlagLocation("1" "manageProfile()" "\0" "ui/qt/main_status_bar.cpp"
":" "837")
);
838 action->setProperty("dialog_action_", (int)ProfileDialog::NewProfile);
839 action = ctx_menu_->addAction(tr("Edit…"), this, SLOT(manageProfile())qFlagLocation("1" "manageProfile()" "\0" "ui/qt/main_status_bar.cpp"
":" "839")
);
840 action->setProperty("dialog_action_", (int)ProfileDialog::EditCurrentProfile);
841 action->setEnabled(enable_edit);
842 action = ctx_menu_->addAction(tr("Delete"), this, SLOT(manageProfile())qFlagLocation("1" "manageProfile()" "\0" "ui/qt/main_status_bar.cpp"
":" "842")
);
843 action->setProperty("dialog_action_", (int)ProfileDialog::DeleteCurrentProfile);
844 action->setEnabled(enable_edit);
845 ctx_menu_->addSeparator();
846
847#if defined(HAVE_MINIZIP1) || defined(HAVE_MINIZIPNG)
848 QMenu * importMenu = new QMenu(tr("Import"), ctx_menu_);
849 action = importMenu->addAction(tr("From Zip File…"), this, SLOT(manageProfile())qFlagLocation("1" "manageProfile()" "\0" "ui/qt/main_status_bar.cpp"
":" "849")
);
850 action->setProperty("dialog_action_", (int)ProfileDialog::ImportZipProfile);
851 action = importMenu->addAction(tr("From Directory…"), this, SLOT(manageProfile())qFlagLocation("1" "manageProfile()" "\0" "ui/qt/main_status_bar.cpp"
":" "851")
);
852 action->setProperty("dialog_action_", (int)ProfileDialog::ImportDirProfile);
853 ctx_menu_->addMenu(importMenu);
854
855 if (model.userProfilesExist())
856 {
857 QMenu * exportMenu = new QMenu(tr("Export"), ctx_menu_);
858 if (enable_edit)
859 {
860 action = exportMenu->addAction(tr("Selected Personal Profile…"), this, SLOT(manageProfile())qFlagLocation("1" "manageProfile()" "\0" "ui/qt/main_status_bar.cpp"
":" "860")
);
861 action->setProperty("dialog_action_", (int)ProfileDialog::ExportSingleProfile);
862 action->setEnabled(enable_edit);
863
864 qsizetype count = model.withChildren({model.findByName(currentProfile->getName())}).count();
865 if (count > 1)
866 {
867 action = exportMenu->addAction(tr("%Ln Personal Profile(s) (including sub-profiles)…", "", static_cast<int>(count)), this, SLOT(manageProfile())qFlagLocation("1" "manageProfile()" "\0" "ui/qt/main_status_bar.cpp"
":" "867")
);
868 action->setProperty("dialog_action_", (int)ProfileDialog::ExportSingleProfileWithChildren);
869 }
870 }
871 action = exportMenu->addAction(tr("All Personal Profiles…"), this, SLOT(manageProfile())qFlagLocation("1" "manageProfile()" "\0" "ui/qt/main_status_bar.cpp"
":" "871")
);
872 action->setProperty("dialog_action_", (int)ProfileDialog::ExportAllProfiles);
873 ctx_menu_->addMenu(exportMenu);
874 }
875
876#else
877 action = ctx_menu_->addAction(tr("Import"), this, SLOT(manageProfile())qFlagLocation("1" "manageProfile()" "\0" "ui/qt/main_status_bar.cpp"
":" "877")
);
878 action->setProperty("dialog_action_", (int)ProfileDialog::ImportDirProfile);
879#endif
880 ctx_menu_->addSeparator();
881
882 ctx_menu_->addMenu(profile_menu);
883 ctx_menu_->popup(global_pos);
884 }
885}
886
887void MainStatusBar::toggleBackground(bool enabled)
888{
889 if (enabled) {
890 setStyleSheet(QStringLiteral((QString(QtPrivate::qMakeStringPrivate(u"" "QStatusBar {" " background-color: %2;"
"}")))
891 "QStatusBar {"(QString(QtPrivate::qMakeStringPrivate(u"" "QStatusBar {" " background-color: %2;"
"}")))
892 " background-color: %2;"(QString(QtPrivate::qMakeStringPrivate(u"" "QStatusBar {" " background-color: %2;"
"}")))
893 "}"(QString(QtPrivate::qMakeStringPrivate(u"" "QStatusBar {" " background-color: %2;"
"}")))
894 )(QString(QtPrivate::qMakeStringPrivate(u"" "QStatusBar {" " background-color: %2;"
"}")))
895 .arg(ColorUtils::warningBackground().name()));
896 } else {
897 setStyleSheet(QString());
898 }
899}
900
901void MainStatusBar::switchToProfile()
902{
903 QAction *pa = qobject_cast<QAction*>(sender());
904
905 if (pa && pa->property("profile_name").isValid()) {
906 QString profile = pa->property("profile_name").toString();
907 mainApp->setConfigurationProfile(profile.toUtf8().constData());
908 }
909}
910
911void MainStatusBar::manageProfile()
912{
913 QAction *pa = qobject_cast<QAction*>(sender());
914
915 if (pa) {
916 ProfileDialog * cp_dialog = new ProfileDialog(this);
917 cp_dialog->setAttribute(Qt::WA_DeleteOnClose);
918
919 int profileAction = pa->property("dialog_action_").toInt();
920 cp_dialog->execAction(static_cast<ProfileDialog::ProfileAction>(profileAction));
921 }
922}
923
924void MainStatusBar::captureEventHandler(CaptureEvent ev)
925{
926 switch(ev.captureContext())
927 {
928#ifdef HAVE_LIBPCAP1
929 case CaptureEvent::Update:
930 switch (ev.eventType())
931 {
932 case CaptureEvent::Continued:
933 updateCaptureStatistics(ev.capSession());
934 break;
935 case CaptureEvent::Finished:
936 updateCaptureStatistics(ev.capSession());
937 break;
938 default:
939 break;
940 }
941 break;
942 case CaptureEvent::Fixed:
943 switch (ev.eventType())
944 {
945 case CaptureEvent::Continued:
946 updateCaptureFixedStatistics(ev.capSession());
947 break;
948 default:
949 break;
950 }
951 break;
952#endif
953 case CaptureEvent::Save:
954 switch (ev.eventType())
955 {
956 case CaptureEvent::Finished:
957 case CaptureEvent::Failed:
958 case CaptureEvent::Stopped:
959 popGenericStatus(STATUS_CTX_FILE);
960 break;
961 default:
962 break;
963 }
964 break;
965 default:
966 break;
967 }
968}