language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
C/C++
wireshark/ui/logray/logray_main_window.h
/** @file * * Logray - Event log analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef LOGRAY_MAIN_WINDOW_H #define LOGRAY_MAIN_WINDOW_H /** @defgroup main_window_group Main window * The main window has the following submodules: @dot digraph main_dependencies { node [shape=record, fontname=Helvetica, fontsize=10]; main [ label="main window" URL="\ref main.h"]; menu [ label="menubar" URL="\ref menus.h"]; toolbar [ label="toolbar" URL="\ref main_toolbar.h"]; packet_list [ label="packet list pane" URL="\ref packet_list.h"]; proto_draw [ label="packet details & bytes panes" URL="\ref main_proto_draw.h"]; recent [ label="recent user settings" URL="\ref recent.h"]; main -> menu [ arrowhead="open", style="solid" ]; main -> toolbar [ arrowhead="open", style="solid" ]; main -> packet_list [ arrowhead="open", style="solid" ]; main -> proto_draw [ arrowhead="open", style="solid" ]; main -> recent [ arrowhead="open", style="solid" ]; } @enddot */ /** @file * The Logray main window * @ingroup main_window_group * @ingroup windows_group */ #include <stdio.h> #include <config.h> #include <glib.h> #include "file.h" #include "ui/ws_ui_util.h" #include "ui/iface_toolbar.h" #include <epan/plugin_if.h> #include <epan/timestamp.h> #ifdef HAVE_LIBPCAP #include "capture_opts.h" #endif #include <capture/capture_session.h> #include <QMainWindow> #include <QPointer> #include <QTextCodec> #ifdef _WIN32 # include <QTimer> #else # include <QSocketNotifier> #endif #include "capture_file.h" #include "capture_file_dialog.h" #include "capture_file_properties_dialog.h" #include <ui/qt/utils/field_information.h> #include <ui/qt/widgets/display_filter_combo.h> #include "main_window.h" class AccordionFrame; class ByteViewTab; class CaptureOptionsDialog; class PrintDialog; class FileSetDialog; class FilterDialog; class FunnelStatistics; class WelcomePage; class PacketCommentDialog; class PacketDiagram; class PacketList; class ProtoTree; class FilterExpressionToolBar; class WiresharkApplication; class QAction; class QActionGroup; namespace Ui { class LograyMainWindow; } Q_DECLARE_METATYPE(ts_type) Q_DECLARE_METATYPE(ts_precision) class LograyMainWindow : public MainWindow { Q_OBJECT public: explicit LograyMainWindow(QWidget *parent = nullptr); ~LograyMainWindow(); #ifdef HAVE_LIBPCAP capture_session *captureSession() { return &cap_session_; } info_data_t *captureInfoData() { return &info_data_; } #endif virtual QMenu *createPopupMenu(); CaptureFile *captureFile() { return &capture_file_; } void removeAdditionalToolbar(QString toolbarName); void addInterfaceToolbar(const iface_toolbar *toolbar_entry); void removeInterfaceToolbar(const gchar *menu_title); QString getMwFileName(); void setMwFileName(QString fileName); protected: virtual bool eventFilter(QObject *obj, QEvent *event); virtual bool event(QEvent *event); virtual void keyPressEvent(QKeyEvent *event); virtual void closeEvent(QCloseEvent *event); virtual void dragEnterEvent(QDragEnterEvent *event); virtual void dropEvent(QDropEvent *event); virtual void changeEvent(QEvent* event); private: // XXX Move to FilterUtils enum MatchSelected { MatchSelectedReplace, MatchSelectedAnd, MatchSelectedOr, MatchSelectedNot, MatchSelectedAndNot, MatchSelectedOrNot }; enum FileCloseContext { Default, Quit, Restart, Reload }; Ui::LograyMainWindow *main_ui_; CaptureFile capture_file_; QFont mono_font_; QMap<QString, QTextCodec *> text_codec_map_; QWidget *previous_focus_; FileSetDialog *file_set_dialog_; QActionGroup *show_hide_actions_; QActionGroup *time_display_actions_; QActionGroup *time_precision_actions_; FunnelStatistics *funnel_statistics_; QList<QPair<QAction *, bool> > freeze_actions_; QPointer<QWidget> freeze_focus_; QMap<QAction *, ts_type> td_actions; QMap<QAction *, ts_precision> tp_actions; bool was_maximized_; /* the following values are maintained so that the capture file name and status is available when there is no cf structure available */ QString mwFileName_; bool capture_stopping_; bool capture_filter_valid_; #ifdef HAVE_LIBPCAP capture_session cap_session_; CaptureOptionsDialog *capture_options_dialog_; info_data_t info_data_; #endif #if defined(Q_OS_MAC) QMenu *dock_menu_; #endif #ifdef HAVE_SOFTWARE_UPDATE QAction *update_action_; #endif QPoint dragStartPosition; void freeze(); void thaw(); void mergeCaptureFile(); void importCaptureFile(); bool saveCaptureFile(capture_file *cf, bool dont_reopen); bool saveAsCaptureFile(capture_file *cf, bool must_support_comments = false, bool dont_reopen = false); void exportSelectedPackets(); void exportDissections(export_type_e export_type); #ifdef Q_OS_WIN void fileAddExtension(QString &file_name, int file_type, wtap_compression_type compression_type); #endif // Q_OS_WIN bool testCaptureFileClose(QString before_what, FileCloseContext context = Default); void captureStop(); void findTextCodecs(); void initMainToolbarIcons(); void initShowHideMainWidgets(); void initTimeDisplayFormatMenu(); void initTimePrecisionFormatMenu(); void initFreezeActions(); void setTitlebarForCaptureInProgress(); void setMenusForCaptureFile(bool force_disable = false); void setMenusForCaptureInProgress(bool capture_in_progress = false); void setMenusForCaptureStopping(); void setForCapturedPackets(bool have_captured_packets); void setMenusForFileSet(bool enable_list_files); void setWindowIcon(const QIcon &icon); QString replaceWindowTitleVariables(QString title); void externalMenuHelper(ext_menu_t * menu, QMenu * subMenu, gint depth); void setForCaptureInProgress(bool capture_in_progress = false, bool handle_toolbars = false, GArray *ifaces = NULL); QMenu* findOrAddMenu(QMenu *parent_menu, QString& menu_text); void captureFileReadStarted(const QString &action); void addMenuActions(QList<QAction *> &actions, int menu_group); void removeMenuActions(QList<QAction *> &actions, int menu_group); void goToConversationFrame(bool go_next); void colorizeWithFilter(QByteArray filter, int color_number = -1); signals: void setDissectedCaptureFile(capture_file *cf); void closePacketDialogs(); void reloadFields(); void packetInfoChanged(struct _packet_info *pinfo); void fieldFilterChanged(const QByteArray field_filter); void fieldHighlight(FieldInformation *); void captureActive(int); #ifdef HAVE_LIBPCAP void showExtcapOptions(QString &device_name, bool startCaptureOnClose); #endif public slots: // in main_window_slots.cpp /** * Open a capture file. * @param cf_path Path to the file. * @param display_filter Display filter to apply. May be empty. * @param type File type. * @param is_tempfile TRUE/FALSE. * @return True on success, false on failure. */ // XXX We might want to return a cf_read_status_t or a CaptureFile. bool openCaptureFile(QString cf_path, QString display_filter, unsigned int type, gboolean is_tempfile = FALSE); bool openCaptureFile(QString cf_path = QString(), QString display_filter = QString()) { return openCaptureFile(cf_path, display_filter, WTAP_TYPE_AUTO); } void filterPackets(QString new_filter = QString(), bool force = false); void updateForUnsavedChanges(); void layoutToolbars(); void updatePreferenceActions(); void updateRecentActions(); void setTitlebarForCaptureFile(); void setWSWindowTitle(QString title = QString()); void showCaptureOptionsDialog(); #ifdef HAVE_LIBPCAP void captureCapturePrepared(capture_session *); void captureCaptureUpdateStarted(capture_session *); void captureCaptureUpdateFinished(capture_session *); void captureCaptureFixedFinished(capture_session *cap_session); void captureCaptureFailed(capture_session *); #endif void captureFileOpened(); void captureFileReadFinished(); void captureFileClosing(); void captureFileClosed(); private slots: void captureEventHandler(CaptureEvent ev); // Manually connected slots (no "on_<object>_<signal>"). void initViewColorizeMenu(); void initConversationMenus(); static bool addExportObjectsMenuItem(const void *key, void *value, void *userdata); void initExportObjectsMenus(); // in main_window_slots.cpp /** * @brief startCapture * Start capturing from the selected interfaces using the capture filter * shown in the main welcome screen. */ void startCapture(QStringList); void startCapture(); void popLiveCaptureInProgress(); void stopCapture(); void loadWindowGeometry(); void saveWindowGeometry(); void mainStackChanged(int); void updateRecentCaptures(); void recentActionTriggered(); void addPacketComment(); void editPacketComment(); void deletePacketComment(); void deleteCommentsFromPackets(); QString commentToMenuText(QString text, int max_len = 40); void setEditCommentsMenu(); void setMenusForSelectedPacket(); void setMenusForSelectedTreeRow(FieldInformation *fi = NULL); void interfaceSelectionChanged(); void captureFilterSyntaxChanged(bool valid); void redissectPackets(); void checkDisplayFilter(); void fieldsChanged(); void reloadLuaPlugins(); void showAccordionFrame(AccordionFrame *show_frame, bool toggle = false); void showColumnEditor(int column); void showPreferenceEditor(); // module_t *, pref * void addStatsPluginsToMenu(); void addDynamicMenus(); void reloadDynamicMenus(); void addPluginIFStructures(); QMenu * searchSubMenu(QString objectName); void activatePluginIFToolbar(bool); void startInterfaceCapture(bool valid, const QString capture_filter); void applyGlobalCommandLineOptions(); void setFeaturesEnabled(bool enabled = true); void on_actionNewDisplayFilterExpression_triggered(); void onFilterSelected(QString, bool); void onFilterPreferences(); void onFilterEdit(int uatIndex); // Handle FilterAction signals void queuedFilterAction(QString filter, FilterAction::Action action, FilterAction::ActionType type); /** Pass stat cmd arguments to a slot. * @param menu_path slot Partial slot name, e.g. "StatisticsIOGraph". * @param arg "-z" argument, e.g. "io,stat". * @param userdata Optional user data. */ void openStatCommandDialog(const QString &menu_path, const char *arg, void *userdata); /** Pass tap parameter arguments to a slot. * @param cfg_str slot Partial slot name, e.g. "StatisticsAFPSrt". * @param arg "-z" argument, e.g. "afp,srt". * @param userdata Optional user data. */ void openTapParameterDialog(const QString cfg_str, const QString arg, void *userdata); void openTapParameterDialog(); #if defined(HAVE_SOFTWARE_UPDATE) && defined(Q_OS_WIN) void softwareUpdateRequested(); #endif // Automatically connected slots ("on_<object>_<signal>"). // // The slots below follow the naming conventaion described in // https://doc.qt.io/archives/qt-4.8/qmetaobject.html#connectSlotsByName // and are automatically connected at initialization time via // main_ui_->setupUi, which in turn calls connectSlotsByName. // // If you're manually connecting a signal to a slot, don't prefix its name // with "on_". Otherwise you'll get runtime warnings. // We might want move these to main_window_actions.cpp similar to // gtk/main_menubar.c void connectFileMenuActions(); void exportPacketBytes(); void exportPDU(); void printFile(); void connectEditMenuActions(); void copySelectedItems(LograyMainWindow::CopySelected selection_type); void findPacket(); void editTimeShift(); void editConfigurationProfiles(); void editTimeShiftFinished(int); void addPacketCommentFinished(PacketCommentDialog* pc_dialog, int result); void editPacketCommentFinished(PacketCommentDialog* pc_dialog, int result, guint nComment); void deleteAllPacketComments(); void deleteAllPacketCommentsFinished(int result); void showPreferencesDialog(QString module_name); void connectViewMenuActions(); void showHideMainWidgets(QAction *action); void setTimestampFormat(QAction *action); void setTimestampPrecision(QAction *action); void setTimeDisplaySecondsWithHoursAndMinutes(bool checked); void editResolvedName(); void setNameResolution(); void zoomText(); void showColoringRulesDialog(); void colorizeConversation(bool create_rule = false); void colorizeActionTriggered(); void openPacketDialog(bool from_reference = false); void reloadCaptureFileAsFormatOrCapture(); void reloadCaptureFile(); void connectGoMenuActions(); void resetPreviousFocus(); void connectCaptureMenuActions(); void startCaptureTriggered(); void connectAnalyzeMenuActions(); void matchFieldFilter(FilterAction::Action action, FilterAction::ActionType filter_type); void applyFieldAsColumn(); void filterMenuAboutToShow(); void applyConversationFilter(); void applyExportObject(); void statCommandExpertInfo(const char *, void *); void connectHelpMenuActions(); #ifdef HAVE_SOFTWARE_UPDATE void checkForUpdates(); #endif void goToCancelClicked(); void goToGoClicked(); void goToLineEditReturnPressed(); void connectStatisticsMenuActions(); void showResolvedAddressesDialog(); void showConversationsDialog(); void showEndpointsDialog(); void openStatisticsTreeDialog(const gchar *abbr); void statCommandIOGraph(const char *, void *); void externalMenuItemTriggered(); void on_actionContextWikiProtocolPage_triggered(); void on_actionContextFilterFieldReference_triggered(); void extcap_options_finished(int result); void showExtcapOptionsDialog(QString & device_name, bool startCaptureOnClose); friend class MainApplication; }; #endif // LOGRAY_MAIN_WINDOW_H
User Interface
wireshark/ui/logray/logray_main_window.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>LograyMainWindow</class> <widget class="QMainWindow" name="LograyMainWindow"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>960</width> <height>768</height> </rect> </property> <property name="acceptDrops"> <bool>true</bool> </property> <property name="windowTitle"> <string>Wireshark</string> </property> <property name="unifiedTitleAndToolBarOnMac"> <bool>true</bool> </property> <widget class="QWidget" name="centralWidget"> <property name="sizePolicy"> <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <layout class="QVBoxLayout" name="verticalLayout"> <property name="spacing"> <number>0</number> </property> <property name="leftMargin"> <number>0</number> </property> <property name="topMargin"> <number>0</number> </property> <property name="rightMargin"> <number>0</number> </property> <property name="bottomMargin"> <number>0</number> </property> <item> <widget class="AccordionFrame" name="goToFrame"> <layout class="QHBoxLayout" name="goToHB"> <property name="topMargin"> <number>0</number> </property> <property name="bottomMargin"> <number>0</number> </property> <item> <spacer name="horizontalSpacer"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>10</height> </size> </property> </spacer> </item> <item> <widget class="QLabel" name="goToPacketLabel"> <property name="text"> <string>Packet:</string> </property> </widget> </item> <item> <widget class="QLineEdit" name="goToLineEdit"> </widget> </item> <item> <widget class="QPushButton" name="goToGo"> <property name="maximumSize"> <size> <width>16777215</width> <height>27</height> </size> </property> <property name="text"> <string>Go to packet</string> </property> <property name="default"> <bool>true</bool> </property> </widget> </item> <item> <widget class="QPushButton" name="goToCancel"> <property name="maximumSize"> <size> <width>16777215</width> <height>27</height> </size> </property> <property name="text"> <string>Cancel</string> </property> </widget> </item> </layout> </widget> </item> <item> <widget class="SearchFrame" name="searchFrame" native="true"/> </item> <item> <widget class="AddressEditorFrame" name="addressEditorFrame"/> </item> <item> <widget class="ColumnEditorFrame" name="columnEditorFrame"/> </item> <item> <widget class="PreferenceEditorFrame" name="preferenceEditorFrame"/> </item> <item> <widget class="FilterExpressionFrame" name="filterExpressionFrame"/> </item> <item> <widget class="QStackedWidget" name="mainStack"> <property name="enabled"> <bool>true</bool> </property> <widget class="WelcomePage" name="welcomePage"/> </widget> </item> </layout> </widget> <widget class="QMenuBar" name="menuBar"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>960</width> <height>21</height> </rect> </property> <widget class="QMenu" name="menuFile"> <property name="title"> <string>&amp;File</string> </property> <widget class="QMenu" name="menuOpenRecentCaptureFile"> <property name="title"> <string>Open &amp;Recent</string> </property> <addaction name="actionDummyNoFilesFound"/> </widget> <widget class="QMenu" name="menuFileSet"> <property name="title"> <string>File Set</string> </property> <addaction name="actionFileSetListFiles"/> <addaction name="actionFileSetNextFile"/> <addaction name="actionFileSetPreviousFile"/> </widget> <widget class="QMenu" name="menuFileExportPacketDissections"> <property name="title"> <string>Export Packet Dissections</string> </property> <addaction name="actionFileExportAsPlainText"/> <addaction name="actionFileExportAsCSV"/> <addaction name="actionFileExportAsCArrays"/> <addaction name="separator"/> <addaction name="actionFileExportAsPSML"/> <addaction name="actionFileExportAsPDML"/> <addaction name="actionFileExportAsJSON"/> </widget> <widget class="QMenu" name="menuFileExportObjects"> <property name="title"> <string>Export Objects</string> </property> </widget> <addaction name="actionFileOpen"/> <addaction name="menuOpenRecentCaptureFile"/> <addaction name="actionFileMerge"/> <addaction name="actionFileImportFromHexDump"/> <addaction name="actionFileClose"/> <addaction name="separator"/> <addaction name="actionFileSave"/> <addaction name="actionFileSaveAs"/> <addaction name="separator"/> <addaction name="menuFileSet"/> <addaction name="separator"/> <addaction name="actionFileExportPackets"/> <addaction name="menuFileExportPacketDissections"/> <addaction name="actionFileExportPacketBytes"/> <addaction name="actionFileExportPDU"/> <addaction name="menuFileExportObjects"/> <addaction name="separator"/> <addaction name="actionFilePrint"/> <addaction name="separator"/> <addaction name="actionFileQuit"/> </widget> <widget class="QMenu" name="menuCapture"> <property name="title"> <string>&amp;Capture</string> </property> <addaction name="actionCaptureOptions"/> <addaction name="actionCaptureStart"/> <addaction name="actionCaptureStop"/> <addaction name="actionCaptureRestart"/> <addaction name="actionCaptureCaptureFilters"/> <addaction name="actionCaptureRefreshInterfaces"/> <addaction name="separator"/> </widget> <widget class="QMenu" name="menuHelp"> <property name="title"> <string>&amp;Help</string> </property> <property name="toolTipsVisible"> <bool>true</bool> </property> <widget class="QMenu" name="menuHelpManualPages"> <property name="title"> <string>Manual pages</string> </property> <property name="toolTipsVisible"> <bool>true</bool> </property> <addaction name="actionHelpMPWireshark"/> <addaction name="actionHelpMPWireshark_Filter"/> <addaction name="separator"/> <addaction name="actionHelpMPCapinfos"/> <addaction name="actionHelpMPDumpcap"/> <addaction name="actionHelpMPEditcap"/> <addaction name="actionHelpMPMergecap"/> <addaction name="actionHelpMPRawshark"/> <addaction name="actionHelpMPReordercap"/> <addaction name="actionHelpMPText2pcap"/> <addaction name="actionHelpMPTShark"/> </widget> <addaction name="actionHelpContents"/> <addaction name="menuHelpManualPages"/> <addaction name="separator"/> <addaction name="actionHelpWebsite"/> <addaction name="actionHelpFAQ"/> <addaction name="actionHelpAsk"/> <addaction name="actionHelpDownloads"/> <addaction name="separator"/> <addaction name="actionHelpWiki"/> <addaction name="actionHelpSampleCaptures"/> <addaction name="separator"/> <addaction name="actionHelpAbout"/> </widget> <widget class="QMenu" name="menuGo"> <property name="title"> <string>&amp;Go</string> </property> <addaction name="actionGoGoToPacket"/> <addaction name="actionGoGoToLinkedPacket"/> <addaction name="separator"/> <addaction name="actionGoNextPacket"/> <addaction name="actionGoPreviousPacket"/> <addaction name="actionGoFirstPacket"/> <addaction name="actionGoLastPacket"/> <addaction name="actionGoNextConversationPacket"/> <addaction name="actionGoPreviousConversationPacket"/> <addaction name="actionGoNextHistoryPacket"/> <addaction name="actionGoPreviousHistoryPacket"/> <addaction name="separator"/> <addaction name="actionGoAutoScroll"/> </widget> <widget class="QMenu" name="menuView"> <property name="title"> <string>&amp;View</string> </property> <widget class="QMenu" name="menuInterfaceToolbars"> <property name="title"> <string>Interface Toolbars</string> </property> </widget> <widget class="QMenu" name="menuZoom"> <property name="title"> <string>&amp;Zoom</string> </property> <addaction name="actionViewZoomIn"/> <addaction name="actionViewZoomOut"/> <addaction name="actionViewNormalSize"/> </widget> <widget class="QMenu" name="menuTime_Display_Format"> <property name="title"> <string>&amp;Time Display Format</string> </property> <addaction name="actionViewTimeDisplayFormatDateYMDandTimeOfDay"/> <addaction name="actionViewTimeDisplayFormatDateYDOYandTimeOfDay"/> <addaction name="actionViewTimeDisplayFormatTimeOfDay"/> <addaction name="actionViewTimeDisplayFormatSecondsSinceEpoch"/> <addaction name="actionViewTimeDisplayFormatSecondsSinceBeginningOfCapture"/> <addaction name="actionViewTimeDisplayFormatSecondsSincePreviousCapturedPacket"/> <addaction name="actionViewTimeDisplayFormatSecondsSincePreviousDisplayedPacket"/> <addaction name="actionViewTimeDisplayFormatUTCDateYMDandTimeOfDay"/> <addaction name="actionViewTimeDisplayFormatUTCDateYDOYandTimeOfDay"/> <addaction name="actionViewTimeDisplayFormatUTCTimeOfDay"/> <addaction name="separator"/> <addaction name="actionViewTimeDisplayFormatPrecisionAutomatic"/> <addaction name="actionViewTimeDisplayFormatPrecisionSeconds"/> <addaction name="actionViewTimeDisplayFormatPrecisionDeciseconds"/> <addaction name="actionViewTimeDisplayFormatPrecisionCentiseconds"/> <addaction name="actionViewTimeDisplayFormatPrecisionMilliseconds"/> <addaction name="actionViewTimeDisplayFormatPrecisionMicroseconds"/> <addaction name="actionViewTimeDisplayFormatPrecisionNanoseconds"/> <addaction name="separator"/> <addaction name="actionViewTimeDisplaySecondsWithHoursAndMinutes"/> </widget> <widget class="QMenu" name="menuName_Resolution"> <property name="title"> <string>Name Resol&amp;ution</string> </property> <addaction name="actionViewEditResolvedName"/> <addaction name="separator"/> <addaction name="actionViewNameResolutionPhysical"/> <addaction name="actionViewNameResolutionNetwork"/> <addaction name="actionViewNameResolutionTransport"/> </widget> <widget class="QMenu" name="menuColorizeConversation"> <property name="title"> <string>Colorize Conversation</string> </property> <addaction name="actionViewColorizeConversation1"/> <addaction name="actionViewColorizeConversation2"/> <addaction name="actionViewColorizeConversation3"/> <addaction name="actionViewColorizeConversation4"/> <addaction name="actionViewColorizeConversation5"/> <addaction name="actionViewColorizeConversation6"/> <addaction name="actionViewColorizeConversation7"/> <addaction name="actionViewColorizeConversation8"/> <addaction name="actionViewColorizeConversation9"/> <addaction name="actionViewColorizeConversation10"/> <addaction name="separator"/> <addaction name="actionViewColorizeResetColorization"/> <addaction name="actionViewColorizeNewColoringRule"/> </widget> <widget class="QMenu" name="menuInternals"> <property name="title"> <string>Internals</string> </property> <addaction name="actionViewInternalsConversationHashTables"/> <addaction name="actionViewInternalsDissectorTables"/> <addaction name="actionViewInternalsSupportedProtocols"/> </widget> <widget class="QMenu" name="menuAdditionalToolbars"> <property name="title"> <string>Additional Toolbars</string> </property> </widget> <addaction name="actionViewMainToolbar"/> <addaction name="actionViewFilterToolbar"/> <addaction name="menuInterfaceToolbars"/> <addaction name="menuAdditionalToolbars"/> <addaction name="actionViewStatusBar"/> <addaction name="separator"/> <addaction name="actionViewFullScreen"/> <addaction name="separator"/> <addaction name="actionViewPacketList"/> <addaction name="actionViewPacketDetails"/> <addaction name="actionViewPacketBytes"/> <addaction name="actionViewPacketDiagram"/> <addaction name="separator"/> <addaction name="menuTime_Display_Format"/> <addaction name="menuName_Resolution"/> <addaction name="separator"/> <addaction name="menuZoom"/> <addaction name="separator"/> <addaction name="actionViewExpandSubtrees"/> <addaction name="actionViewCollapseSubtrees"/> <addaction name="actionViewExpandAll"/> <addaction name="actionViewCollapseAll"/> <addaction name="separator"/> <addaction name="actionViewColorizePacketList"/> <addaction name="actionViewColoringRules"/> <addaction name="menuColorizeConversation"/> <addaction name="separator"/> <addaction name="actionViewResetLayout"/> <addaction name="actionViewResizeColumns"/> <addaction name="separator"/> <addaction name="menuInternals"/> <addaction name="separator"/> <addaction name="actionViewShowPacketInNewWindow"/> <addaction name="actionViewReload_as_File_Format_or_Capture"/> <addaction name="actionViewReload"/> </widget> <widget class="QMenu" name="menuAnalyze"> <property name="title"> <string>&amp;Analyze</string> </property> <widget class="QMenu" name="menuApplyAsFilter"> <property name="title"> <string>Apply as Filter</string> </property> </widget> <widget class="QMenu" name="menuPrepareAFilter"> <property name="title"> <string>Prepare as Filter</string> </property> </widget> <widget class="QMenu" name="menuConversationFilter"> <property name="title"> <string>Conversation Filter</string> </property> </widget> <addaction name="actionAnalyzeDisplayFilters"/> <addaction name="actionAnalyzeDisplayFilterMacros"/> <addaction name="actionDisplayFilterExpression"/> <addaction name="separator"/> <addaction name="actionAnalyzeApplyAsColumn"/> <addaction name="menuApplyAsFilter"/> <addaction name="menuPrepareAFilter"/> <addaction name="menuConversationFilter"/> <addaction name="separator"/> <addaction name="actionAnalyzeEnabledProtocols"/> <addaction name="actionAnalyzeDecodeAs"/> <addaction name="actionAnalyzeReloadLuaPlugins"/> <addaction name="separator"/> <addaction name="actionAnalyzeShowPacketBytes"/> <addaction name="actionAnalyzeExpertInfo"/> </widget> <widget class="QMenu" name="menuStatistics"> <property name="enabled"> <bool>true</bool> </property> <property name="title"> <string>&amp;Statistics</string> </property> <addaction name="actionStatisticsCaptureFileProperties"/> <addaction name="actionStatisticsResolvedAddresses"/> <addaction name="actionStatisticsProtocolHierarchy"/> <addaction name="actionStatisticsConversations"/> <addaction name="actionStatisticsEndpoints"/> <addaction name="actionStatisticsPacketLengths"/> <addaction name="actionStatisticsIOGraph"/> <addaction name="separator"/> <addaction name="actionStatistics_REGISTER_STAT_GROUP_UNSORTED"/> <addaction name="actionStatisticsFlowGraph"/> </widget> <widget class="QMenu" name="menuEdit"> <property name="title"> <string>&amp;Edit</string> </property> <widget class="QMenu" name="menuEditCopy"> <property name="title"> <string>Copy</string> </property> <addaction name="actionCopyListAsText"/> <addaction name="actionCopyListAsCSV"/> <addaction name="actionCopyListAsYAML"/> <addaction name="separator"/> <addaction name="actionCopyAllVisibleItems"/> <addaction name="actionCopyAllVisibleSelectedTreeItems"/> <addaction name="actionEditCopyDescription"/> <addaction name="actionEditCopyFieldName"/> <addaction name="actionEditCopyValue"/> <addaction name="separator"/> <addaction name="actionEditCopyAsFilter"/> </widget> <widget class="QMenu" name="menuPacketComment"> <property name="title"> <string>Packet Comments</string> </property> </widget> <addaction name="menuEditCopy"/> <addaction name="actionEditFindPacket"/> <addaction name="actionEditFindNext"/> <addaction name="actionEditFindPrevious"/> <addaction name="separator"/> <addaction name="actionEditMarkPacket"/> <addaction name="actionEditMarkAllDisplayed"/> <addaction name="actionEditUnmarkAllDisplayed"/> <addaction name="actionEditNextMark"/> <addaction name="actionEditPreviousMark"/> <addaction name="separator"/> <addaction name="actionEditIgnorePacket"/> <addaction name="actionEditIgnoreAllDisplayed"/> <addaction name="actionEditUnignoreAllDisplayed"/> <addaction name="separator"/> <addaction name="actionEditSetTimeReference"/> <addaction name="actionEditUnsetAllTimeReferences"/> <addaction name="actionEditNextTimeReference"/> <addaction name="actionEditPreviousTimeReference"/> <addaction name="separator"/> <addaction name="actionEditTimeShift"/> <addaction name="separator"/> <addaction name="menuPacketComment"/> <addaction name="actionDeleteAllPacketComments"/> <addaction name="separator"/> <addaction name="actionEditConfigurationProfiles"/> <addaction name="actionEditPreferences"/> </widget> <widget class="QMenu" name="menuTools"> <property name="title"> <string>&amp;Tools</string> </property> </widget> <addaction name="menuFile"/> <addaction name="menuEdit"/> <addaction name="menuView"/> <addaction name="menuGo"/> <addaction name="menuCapture"/> <addaction name="menuAnalyze"/> <addaction name="menuStatistics"/> <addaction name="menuTools"/> <addaction name="menuHelp"/> </widget> <widget class="QToolBar" name="mainToolBar"> <property name="sizePolicy"> <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="windowTitle"> <string>Main Toolbar</string> </property> <property name="movable"> <bool>false</bool> </property> <property name="iconSize"> <size> <width>32</width> <height>32</height> </size> </property> <property name="toolButtonStyle"> <enum>Qt::ToolButtonIconOnly</enum> </property> <attribute name="toolBarArea"> <enum>TopToolBarArea</enum> </attribute> <attribute name="toolBarBreak"> <bool>false</bool> </attribute> <addaction name="actionCaptureStart"/> <addaction name="actionCaptureStop"/> <addaction name="actionCaptureRestart"/> <addaction name="actionCaptureOptions"/> <addaction name="separator"/> <addaction name="actionFileOpen"/> <addaction name="actionFileSave"/> <addaction name="actionFileClose"/> <addaction name="actionViewReload"/> <addaction name="separator"/> <addaction name="actionEditFindPacket"/> <addaction name="actionGoPreviousPacket"/> <addaction name="actionGoNextPacket"/> <addaction name="actionGoGoToPacket"/> <addaction name="actionGoFirstPacket"/> <addaction name="actionGoLastPacket"/> <addaction name="actionGoAutoScroll"/> <addaction name="separator"/> <addaction name="actionViewColorizePacketList"/> <addaction name="separator"/> <addaction name="actionViewZoomIn"/> <addaction name="actionViewZoomOut"/> <addaction name="actionViewNormalSize"/> <addaction name="actionViewResizeColumns"/> </widget> <widget class="MainStatusBar" name="statusBar"/> <widget class="QToolBar" name="displayFilterToolBar"> <property name="windowTitle"> <string>Display Filter Toolbar</string> </property> <property name="movable"> <bool>false</bool> </property> <property name="iconSize"> <size> <width>14</width> <height>14</height> </size> </property> <attribute name="toolBarArea"> <enum>TopToolBarArea</enum> </attribute> <attribute name="toolBarBreak"> <bool>true</bool> </attribute> <addaction name="actionNewDisplayFilterExpression"/> </widget> <action name="actionFileOpen"> <property name="text"> <string>&amp;Open</string> </property> <property name="toolTip"> <string>Open a capture file</string> </property> <property name="shortcut"> <string notr="true">Ctrl+O</string> </property> <property name="iconVisibleInMenu"> <bool>false</bool> </property> </action> <action name="actionFileQuit"> <property name="text"> <string>&amp;Quit</string> </property> <property name="toolTip"> <string>Quit Wireshark</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Q</string> </property> <property name="menuRole"> <enum>QAction::QuitRole</enum> </property> </action> <action name="actionCaptureStart"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>&amp;Start</string> </property> <property name="toolTip"> <string>Start capturing packets</string> </property> <property name="shortcut"> <string notr="true">Ctrl+E</string> </property> </action> <action name="actionCaptureStop"> <property name="text"> <string>S&amp;top</string> </property> <property name="toolTip"> <string>Stop capturing packets</string> </property> <property name="shortcut"> <string notr="true">Ctrl+E</string> </property> </action> <action name="actionFileClose"> <property name="text"> <string>&amp;Close</string> </property> <property name="toolTip"> <string>Close this capture file</string> </property> <property name="shortcut"> <string notr="true">Ctrl+W</string> </property> <property name="iconVisibleInMenu"> <bool>false</bool> </property> </action> <action name="actionDummyNoFilesFound"> <property name="enabled"> <bool>false</bool> </property> <property name="text"> <string>No files found</string> </property> </action> <action name="actionHelpContents"> <property name="text"> <string>&amp;Contents</string> </property> <property name="toolTip"> <string>Help contents</string> </property> <property name="shortcut"> <string notr="true">F1</string> </property> <property name="iconVisibleInMenu"> <bool>true</bool> </property> </action> <action name="actionHelpMPWireshark"> <property name="text"> <string>Wireshark</string> </property> </action> <action name="actionHelpMPWireshark_Filter"> <property name="text"> <string>Wireshark Filter</string> </property> </action> <action name="actionHelpMPTShark"> <property name="text"> <string>TShark</string> </property> </action> <action name="actionHelpMPRawshark"> <property name="text"> <string>Rawshark</string> </property> </action> <action name="actionHelpMPDumpcap"> <property name="text"> <string>Dumpcap</string> </property> </action> <action name="actionHelpMPMergecap"> <property name="text"> <string>Mergecap</string> </property> </action> <action name="actionHelpMPEditcap"> <property name="text"> <string>Editcap</string> </property> </action> <action name="actionHelpMPText2pcap"> <property name="text"> <string>Text2pcap</string> </property> </action> <action name="actionHelpWebsite"> <property name="icon"> <iconset resource="../../resources/stock_icons.qrc"> <normaloff>:/menu/help/lricon16.png</normaloff>:/menu/help/lricon16.png</iconset> </property> <property name="text"> <string>Website</string> </property> </action> <action name="actionHelpFAQ"> <property name="text"> <string>FAQs</string> </property> </action> <action name="actionHelpDownloads"> <property name="text"> <string>Downloads</string> </property> </action> <action name="actionHelpWiki"> <property name="icon"> <iconset resource="../../resources/stock_icons.qrc"> <normaloff>:/menu/help/lricon16.png</normaloff>:/menu/help/lricon16.png</iconset> </property> <property name="text"> <string>Wiki</string> </property> <property name="iconVisibleInMenu"> <bool>true</bool> </property> </action> <action name="actionHelpSampleCaptures"> <property name="text"> <string>Sample Captures</string> </property> </action> <action name="actionHelpAbout"> <property name="text"> <string>&amp;About Wireshark</string> </property> <property name="menuRole"> <enum>QAction::AboutRole</enum> </property> </action> <action name="actionHelpAsk"> <property name="icon"> <iconset resource="../../resources/stock_icons.qrc"> <normaloff>:/menu/help/wsicon-ask.png</normaloff>:/menu/help/wsicon-ask.png</iconset> </property> <property name="text"> <string>Ask (Q&amp;&amp;A)</string> </property> <property name="iconVisibleInMenu"> <bool>true</bool> </property> </action> <action name="actionGoNextPacket"> <property name="text"> <string>Next Packet</string> </property> <property name="toolTip"> <string>Go to the next packet</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Down</string> </property> </action> <action name="actionGoPreviousPacket"> <property name="text"> <string>Previous Packet</string> </property> <property name="toolTip"> <string>Go to the previous packet</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Up</string> </property> </action> <action name="actionGoNextConversationPacket"> <property name="text"> <string>Next Packet in Conversation</string> </property> <property name="toolTip"> <string>Go to the next packet in this conversation</string> </property> <property name="shortcut"> <string notr="true">Ctrl+.</string> </property> </action> <action name="actionGoPreviousConversationPacket"> <property name="text"> <string>Previous Packet in Conversation</string> </property> <property name="toolTip"> <string>Go to the previous packet in this conversation</string> </property> <property name="shortcut"> <string notr="true">Ctrl+,</string> </property> </action> <action name="actionGoNextHistoryPacket"> <property name="text"> <string>Next Packet In History</string> </property> <property name="toolTip"> <string>Go to the next packet in your selection history</string> </property> <property name="shortcut"> <string notr="true">Alt+Right</string> </property> </action> <action name="actionGoPreviousHistoryPacket"> <property name="text"> <string>Previous Packet In History</string> </property> <property name="toolTip"> <string>Go to the previous packet in your selection history</string> </property> <property name="shortcut"> <string notr="true">Alt+Left</string> </property> </action> <action name="actionGoFirstPacket"> <property name="text"> <string>First Packet</string> </property> <property name="toolTip"> <string>Go to the first packet</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Home</string> </property> </action> <action name="actionGoLastPacket"> <property name="text"> <string>Last Packet</string> </property> <property name="toolTip"> <string>Go to the last packet</string> </property> <property name="shortcut"> <string notr="true">Ctrl+End</string> </property> </action> <action name="actionViewExpandSubtrees"> <property name="enabled"> <bool>false</bool> </property> <property name="text"> <string>E&amp;xpand Subtrees</string> </property> <property name="toolTip"> <string>Expand the current packet detail</string> </property> <property name="shortcut"> <string notr="true">Shift+Right</string> </property> </action> <action name="actionViewCollapseSubtrees"> <property name="enabled"> <bool>false</bool> </property> <property name="text"> <string>Collapse Subtrees</string> </property> <property name="toolTip"> <string>Collapse the current packet detail</string> </property> <property name="shortcut"> <string notr="true">Shift+Left</string> </property> </action> <action name="actionViewExpandAll"> <property name="text"> <string>&amp;Expand All</string> </property> <property name="toolTip"> <string>Expand packet details</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Right</string> </property> </action> <action name="actionViewCollapseAll"> <property name="text"> <string>Collapse &amp;All</string> </property> <property name="toolTip"> <string>Collapse all packet details</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Left</string> </property> </action> <action name="actionGoGoToPacket"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Go to Packet…</string> </property> <property name="toolTip"> <string>Go to specified packet</string> </property> <property name="shortcut"> <string notr="true">Ctrl+G</string> </property> </action> <action name="actionFileMerge"> <property name="text"> <string>&amp;Merge…</string> </property> <property name="toolTip"> <string>Merge one or more files</string> </property> </action> <action name="actionFileImportFromHexDump"> <property name="text"> <string>&amp;Import from Hex Dump…</string> </property> <property name="toolTip"> <string>Import a file</string> </property> </action> <action name="actionFileSave"> <property name="text"> <string>&amp;Save</string> </property> <property name="toolTip"> <string>Save this capture file</string> </property> <property name="shortcut"> <string notr="true">Ctrl+S</string> </property> <property name="iconVisibleInMenu"> <bool>false</bool> </property> </action> <action name="actionFileSaveAs"> <property name="text"> <string>Save &amp;As…</string> </property> <property name="toolTip"> <string>Save as a different file</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+S</string> </property> </action> <action name="actionFileExportPackets"> <property name="text"> <string>Export Specified Packets…</string> </property> <property name="toolTip"> <string>Export specified packets</string> </property> </action> <action name="actionFileExportPacketBytes"> <property name="text"> <string>Export Packet &amp;Bytes…</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+X</string> </property> </action> <action name="actionFilePrint"> <property name="text"> <string>&amp;Print…</string> </property> <property name="shortcut"> <string notr="true">Ctrl+P</string> </property> </action> <action name="actionFileSetListFiles"> <property name="text"> <string>List Files</string> </property> </action> <action name="actionFileSetNextFile"> <property name="text"> <string>Next File</string> </property> </action> <action name="actionFileSetPreviousFile"> <property name="text"> <string>Previous File</string> </property> </action> <action name="actionViewReload"> <property name="text"> <string>&amp;Reload</string> </property> <property name="toolTip"> <string>Reload this file</string> </property> <property name="shortcut"> <string notr="true">Ctrl+R</string> </property> <property name="iconVisibleInMenu"> <bool>true</bool> </property> </action> <action name="actionViewReload_as_File_Format_or_Capture"> <property name="text"> <string>Reload as File Format/Capture</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+F</string> </property> </action> <action name="actionCaptureOptions"> <property name="text"> <string>&amp;Options…</string> </property> <property name="iconText"> <string>Options</string> </property> <property name="toolTip"> <string>Capture options</string> </property> <property name="shortcut"> <string notr="true">Ctrl+K</string> </property> <property name="menuRole"> <enum>QAction::NoRole</enum> </property> </action> <action name="actionCaptureCaptureFilters"> <property name="text"> <string>Capture &amp;Filters…</string> </property> <property name="toolTip"> <string>Capture filters</string> </property> </action> <action name="actionCaptureRefreshInterfaces"> <property name="text"> <string>Refresh Interfaces</string> </property> <property name="toolTip"> <string>Refresh interfaces</string> </property> <property name="shortcut"> <string notr="true">F5</string> </property> </action> <action name="actionCaptureRestart"> <property name="text"> <string>&amp;Restart</string> </property> <property name="toolTip"> <string>Restart current capture</string> </property> <property name="shortcut"> <string notr="true">Ctrl+R</string> </property> </action> <action name="actionFileExportAsPlainText"> <property name="text"> <string>As Plain &amp;Text…</string> </property> </action> <action name="actionFileExportAsCSV"> <property name="text"> <string>As &amp;CSV…</string> </property> </action> <action name="actionFileExportAsCArrays"> <property name="text"> <string>As &quot;C&quot; &amp;Arrays…</string> </property> </action> <action name="actionFileExportAsPSML"> <property name="text"> <string>As P&amp;SML XML…</string> </property> </action> <action name="actionFileExportAsPDML"> <property name="text"> <string>As P&amp;DML XML…</string> </property> </action> <action name="actionFileExportAsJSON"> <property name="text"> <string>As &amp;JSON…</string> </property> </action> <action name="actionEditCopyDescription"> <property name="text"> <string>Description</string> </property> <property name="toolTip"> <string>Copy this item's description</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+Shift+D</string> </property> </action> <action name="actionCopyListAsText"> <property name="text"> <string>As Plain &amp;Text</string> </property> </action> <action name="actionCopyListAsCSV"> <property name="text"> <string>As &amp;CSV</string> </property> </action> <action name="actionCopyListAsYAML"> <property name="text"> <string>As &amp;YAML</string> </property> </action> <action name="actionCopyAllVisibleItems"> <property name="text"> <string>All Visible Items</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+Shift+A</string> </property> </action> <action name="actionCopyAllVisibleSelectedTreeItems"> <property name="text"> <string>All Visible Selected Tree Items</string> </property> </action> <action name="actionEditCopyFieldName"> <property name="text"> <string>Field Name</string> </property> <property name="toolTip"> <string>Copy this item's field name</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+Shift+F</string> </property> </action> <action name="actionEditCopyValue"> <property name="text"> <string>Value</string> </property> <property name="toolTip"> <string>Copy this item's value</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+Shift+V</string> </property> </action> <action name="actionEditCopyAsFilter"> <property name="text"> <string>As Filter</string> </property> <property name="toolTip"> <string>Copy this item as a display filter</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+C</string> </property> </action> <action name="actionAnalyzeDisplayFilters"> <property name="text"> <string>Display &amp;Filters…</string> </property> </action> <action name="actionAnalyzeDisplayFilterMacros"> <property name="text"> <string>Display Filter &amp;Macros…</string> </property> </action> <action name="actionAnalyzeApplyAsColumn"> <property name="text"> <string>Apply as Column</string> </property> <property name="toolTip"> <string>Create a packet list column from the selected field.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+I</string> </property> </action> <action name="actionEditFindPacket"> <property name="text"> <string>&amp;Find Packet…</string> </property> <property name="toolTip"> <string>Find a packet</string> </property> <property name="shortcut"> <string notr="true">Ctrl+F</string> </property> </action> <action name="actionEditFindNext"> <property name="text"> <string>Find Ne&amp;xt</string> </property> <property name="toolTip"> <string>Find the next packet</string> </property> <property name="shortcut"> <string notr="true">Ctrl+N</string> </property> </action> <action name="actionEditFindPrevious"> <property name="text"> <string>Find Pre&amp;vious</string> </property> <property name="toolTip"> <string>Find the previous packet</string> </property> <property name="shortcut"> <string notr="true">Ctrl+B</string> </property> </action> <action name="actionEditMarkPacket"> <property name="text"> <string>&amp;Mark/Unmark Packet(s)</string> </property> <property name="toolTip"> <string>Mark or unmark each selected packet</string> </property> <property name="shortcut"> <string notr="true">Ctrl+M</string> </property> </action> <action name="actionEditMarkAllDisplayed"> <property name="text"> <string>Mark All Displayed</string> </property> <property name="toolTip"> <string>Mark all displayed packets</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+M</string> </property> </action> <action name="actionEditUnmarkAllDisplayed"> <property name="text"> <string>&amp;Unmark All Displayed</string> </property> <property name="toolTip"> <string>Unmark all displayed packets</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+M</string> </property> </action> <action name="actionEditNextMark"> <property name="text"> <string>Next Mark</string> </property> <property name="toolTip"> <string>Go to the next marked packet</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+N</string> </property> </action> <action name="actionEditPreviousMark"> <property name="text"> <string>Previous Mark</string> </property> <property name="toolTip"> <string>Go to the previous marked packet</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+B</string> </property> </action> <action name="actionEditIgnorePacket"> <property name="text"> <string>&amp;Ignore/Unignore Packet(s)</string> </property> <property name="toolTip"> <string>Ignore or unignore each selected packet</string> </property> <property name="shortcut"> <string notr="true">Ctrl+D</string> </property> </action> <action name="actionEditIgnoreAllDisplayed"> <property name="text"> <string>Ignore All Displayed</string> </property> <property name="toolTip"> <string>Ignore all displayed packets</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+D</string> </property> </action> <action name="actionEditUnignoreAllDisplayed"> <property name="text"> <string>U&amp;nignore All Displayed</string> </property> <property name="toolTip"> <string>Unignore all displayed packets</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+D</string> </property> </action> <action name="actionEditSetTimeReference"> <property name="text"> <string>Set/Unset Time Reference</string> </property> <property name="toolTip"> <string>Set or unset a time reference for this packet</string> </property> <property name="shortcut"> <string notr="true">Ctrl+T</string> </property> </action> <action name="actionEditUnsetAllTimeReferences"> <property name="text"> <string>Unset All Time References</string> </property> <property name="toolTip"> <string>Remove all time references</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+T</string> </property> </action> <action name="actionEditNextTimeReference"> <property name="text"> <string>Next Time Reference</string> </property> <property name="toolTip"> <string>Go to the next time reference</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+N</string> </property> </action> <action name="actionEditPreviousTimeReference"> <property name="text"> <string>Previous Time Reference</string> </property> <property name="toolTip"> <string>Go to the previous time reference</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+B</string> </property> </action> <action name="actionEditTimeShift"> <property name="text"> <string>Time Shift…</string> </property> <property name="toolTip"> <string>Shift or change packet timestamps</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+T</string> </property> </action> <action name="actionDeleteAllPacketComments"> <property name="text"> <string>Delete All Packet Comments</string> </property> <property name="toolTip"> <string>Remove all packet comments in the capture file</string> </property> </action> <action name="actionEditConfigurationProfiles"> <property name="checkable"> <bool>false</bool> </property> <property name="text"> <string>&amp;Configuration Profiles…</string> </property> <property name="iconText"> <string>Configuration profiles</string> </property> <property name="toolTip"> <string>Manage your configuration profiles</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+A</string> </property> <property name="menuRole"> <enum>QAction::NoRole</enum> </property> </action> <action name="actionEditPreferences"> <property name="text"> <string>&amp;Preferences…</string> </property> <property name="toolTip"> <string>Manage Wireshark's preferences</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+P</string> </property> <property name="menuRole"> <enum>QAction::PreferencesRole</enum> </property> </action> <action name="actionStatisticsCaptureFileProperties"> <property name="enabled"> <bool>false</bool> </property> <property name="text"> <string>Capture File Properties</string> </property> <property name="toolTip"> <string>Capture file properties</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+Shift+C</string> </property> </action> <action name="actionStatisticsProtocolHierarchy"> <property name="enabled"> <bool>false</bool> </property> <property name="text"> <string>&amp;Protocol Hierarchy</string> </property> <property name="toolTip"> <string>Show a summary of protocols present in the capture file.</string> </property> </action> <action name="actionHelpMPCapinfos"> <property name="text"> <string>Capinfos</string> </property> </action> <action name="actionHelpMPReordercap"> <property name="text"> <string>Reordercap</string> </property> </action> <action name="actionStatisticsFlowGraph"> <property name="text"> <string>Flow Graph</string> </property> <property name="toolTip"> <string>Flow sequence diagram</string> </property> </action> <action name="actionStatisticsPacketLengths"> <property name="text"> <string>Packet Lengths</string> </property> <property name="toolTip"> <string>Packet length statistics</string> </property> </action> <action name="actionAnalyzeDecodeAs"> <property name="text"> <string>Decode &amp;As…</string> </property> <property name="toolTip"> <string>Change the way packets are dissected</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+U</string> </property> </action> <action name="actionAnalyzeReloadLuaPlugins"> <property name="text"> <string>Reload Lua Plugins</string> </property> <property name="toolTip"> <string>Reload Lua plugins</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+L</string> </property> </action> <action name="actionFileExportPDU"> <property name="text"> <string>Export PDUs to File…</string> </property> </action> <action name="actionStatisticsIOGraph"> <property name="text"> <string>&amp;I/O Graphs</string> </property> <property name="toolTip"> <string>Create graphs based on display filter fields</string> </property> </action> <action name="actionViewMainToolbar"> <property name="checkable"> <bool>true</bool> </property> <property name="checked"> <bool>true</bool> </property> <property name="text"> <string>&amp;Main Toolbar</string> </property> <property name="toolTip"> <string>Show or hide the main toolbar</string> </property> </action> <action name="actionViewFilterToolbar"> <property name="checkable"> <bool>true</bool> </property> <property name="checked"> <bool>true</bool> </property> <property name="text"> <string>&amp;Filter Toolbar</string> </property> <property name="toolTip"> <string>Show or hide the display filter toolbar</string> </property> </action> <action name="actionStatisticsConversations"> <property name="text"> <string>&amp;Conversations</string> </property> <property name="toolTip"> <string>Conversations at different protocol levels</string> </property> </action> <action name="actionStatisticsEndpoints"> <property name="text"> <string>&amp;Endpoints</string> </property> <property name="toolTip"> <string>Endpoints at different protocol levels</string> </property> </action> <action name="actionViewColorizePacketList"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Colorize Packet List</string> </property> <property name="toolTip"> <string>Draw packets using your coloring rules</string> </property> </action> <action name="actionViewZoomIn"> <property name="text"> <string>&amp;Zoom In</string> </property> <property name="toolTip"> <string>Enlarge the main window text</string> </property> <property name="shortcut"> <string notr="true">Ctrl++</string> </property> </action> <action name="actionViewZoomOut"> <property name="text"> <string>Zoom Out</string> </property> <property name="toolTip"> <string>Shrink the main window text</string> </property> <property name="shortcut"> <string notr="true">Ctrl+-</string> </property> </action> <action name="actionViewNormalSize"> <property name="text"> <string>Normal Size</string> </property> <property name="toolTip"> <string>Return the main window text to its normal size</string> </property> <property name="shortcut"> <string notr="true">Ctrl+0</string> </property> </action> <action name="actionViewResetLayout"> <property name="text"> <string>Reset Layout</string> </property> <property name="toolTip"> <string>Reset appearance layout to default size</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+W</string> </property> </action> <action name="actionViewResizeColumns"> <property name="text"> <string>Resize Columns</string> </property> <property name="toolTip"> <string>Resize packet list columns to fit contents</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+R</string> </property> </action> <action name="actionViewTimeDisplayFormatDateYMDandTimeOfDay"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Date and Time of Day (1970-01-01 01:02:03.123456)</string> </property> <property name="toolTip"> <string>Show packet times as the date and time of day.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+1</string> </property> </action> <action name="actionViewTimeDisplayFormatDateYDOYandTimeOfDay"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Year, Day of Year, and Time of Day (1970/001 01:02:03.123456)</string> </property> <property name="toolTip"> <string>Show packet times as the year, day of the year and time of day.</string> </property> </action> <action name="actionViewTimeDisplayFormatTimeOfDay"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Time of Day (01:02:03.123456)</string> </property> <property name="toolTip"> <string>Show packet times as the date and time of day.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+2</string> </property> </action> <action name="actionViewTimeDisplayFormatSecondsSinceEpoch"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Seconds Since 1970-01-01</string> </property> <property name="toolTip"> <string>Show packet times as the seconds since the UNIX / POSIX epoch (1970-01-01).</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+3</string> </property> </action> <action name="actionViewTimeDisplayFormatSecondsSinceBeginningOfCapture"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Seconds Since Beginning of Capture</string> </property> <property name="toolTip"> <string>Show packet times as the date and time of day.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+4</string> </property> </action> <action name="actionViewTimeDisplayFormatSecondsSincePreviousCapturedPacket"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Seconds Since Previous Captured Packet</string> </property> <property name="toolTip"> <string>Show packet times as the seconds since the previous captured packet.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+5</string> </property> </action> <action name="actionViewTimeDisplayFormatSecondsSincePreviousDisplayedPacket"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Seconds Since Previous Displayed Packet</string> </property> <property name="toolTip"> <string>Show packet times as the seconds since the previous displayed packet.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+6</string> </property> </action> <action name="actionViewTimeDisplayFormatUTCDateYMDandTimeOfDay"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>UTC Date and Time of Day (1970-01-01 01:02:03.123456)</string> </property> <property name="toolTip"> <string>Show packet times as the UTC date and time of day.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+7</string> </property> </action> <action name="actionViewTimeDisplayFormatUTCDateYDOYandTimeOfDay"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>UTC Year, Day of Year, and Time of Day (1970/001 01:02:03.123456)</string> </property> <property name="toolTip"> <string>Show packet times as the UTC year, day of the year and time of day.</string> </property> </action> <action name="actionViewTimeDisplayFormatUTCTimeOfDay"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>UTC Time of Day (01:02:03.123456)</string> </property> <property name="toolTip"> <string>Show packet times as the UTC time of day.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Alt+8</string> </property> </action> <action name="actionViewTimeDisplayFormatPrecisionAutomatic"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Automatic (from capture file)</string> </property> <property name="toolTip"> <string>Use the time precision indicated in the capture file.</string> </property> </action> <action name="actionViewTimeDisplayFormatPrecisionSeconds"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Seconds</string> </property> </action> <action name="actionViewTimeDisplayFormatPrecisionDeciseconds"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Tenths of a second</string> </property> </action> <action name="actionViewTimeDisplayFormatPrecisionCentiseconds"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Hundredths of a second</string> </property> </action> <action name="actionViewTimeDisplayFormatPrecisionMilliseconds"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Milliseconds</string> </property> </action> <action name="actionViewTimeDisplayFormatPrecisionMicroseconds"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Microseconds</string> </property> </action> <action name="actionViewTimeDisplayFormatPrecisionNanoseconds"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Nanoseconds</string> </property> </action> <action name="actionViewTimeDisplaySecondsWithHoursAndMinutes"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Display Seconds With Hours and Minutes</string> </property> <property name="toolTip"> <string>Display seconds with hours and minutes</string> </property> </action> <action name="actionViewNameResolutionPhysical"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Resolve &amp;Physical Addresses</string> </property> <property name="toolTip"> <string>Show names for known MAC addresses. Lookups use a local database.</string> </property> </action> <action name="actionViewNameResolutionNetwork"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Resolve &amp;Network Addresses</string> </property> <property name="toolTip"> <string>Show names for known IPv4, IPv6, and IPX addresses. Lookups can generate network traffic.</string> </property> </action> <action name="actionViewNameResolutionTransport"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Resolve &amp;Transport Addresses</string> </property> <property name="toolTip"> <string>Show names for known TCP, UDP, and SCTP services. Lookups can generate traffic on some systems.</string> </property> </action> <action name="actionViewStatusBar"> <property name="checkable"> <bool>true</bool> </property> <property name="checked"> <bool>true</bool> </property> <property name="text"> <string>&amp;Status Bar</string> </property> <property name="toolTip"> <string>Show or hide the status bar</string> </property> </action> <action name="actionViewPacketList"> <property name="checkable"> <bool>true</bool> </property> <property name="checked"> <bool>true</bool> </property> <property name="text"> <string>Packet &amp;List</string> </property> <property name="toolTip"> <string>Show or hide the packet list</string> </property> </action> <action name="actionViewPacketDetails"> <property name="checkable"> <bool>true</bool> </property> <property name="checked"> <bool>true</bool> </property> <property name="text"> <string>Packet &amp;Details</string> </property> <property name="toolTip"> <string>Show or hide the packet details</string> </property> </action> <action name="actionViewPacketBytes"> <property name="checkable"> <bool>true</bool> </property> <property name="checked"> <bool>true</bool> </property> <property name="text"> <string>Packet &amp;Bytes</string> </property> <property name="toolTip"> <string>Show or hide the packet bytes</string> </property> </action> <action name="actionViewPacketDiagram"> <property name="checkable"> <bool>true</bool> </property> <property name="checked"> <bool>true</bool> </property> <property name="text"> <string>Packet &amp;Diagram</string> </property> <property name="toolTip"> <string>Show or hide the packet diagram</string> </property> </action> <action name="actionViewInternalsConversationHashTables"> <property name="text"> <string>&amp;Conversation Hash Tables</string> </property> <property name="toolTip"> <string>Show each conversation hash table</string> </property> </action> <action name="actionViewInternalsDissectorTables"> <property name="text"> <string>&amp;Dissector Tables</string> </property> <property name="toolTip"> <string>Show each dissector table and its entries</string> </property> </action> <action name="actionViewInternalsSupportedProtocols"> <property name="text"> <string>&amp;Supported Protocols</string> </property> <property name="toolTip"> <string>Show the currently supported protocols and display filter fields</string> </property> </action> <action name="actionViewColoringRules"> <property name="text"> <string>&amp;Coloring Rules…</string> </property> <property name="toolTip"> <string>Edit the packet list coloring rules.</string> </property> </action> <action name="actionViewShowPacketInNewWindow"> <property name="text"> <string>Show Packet in New &amp;Window</string> </property> <property name="toolTip"> <string>Show this packet in a separate window.</string> </property> </action> <action name="actionContextShowLinkedPacketInNewWindow"> <property name="text"> <string>Show Linked Packet in New Window</string> </property> <property name="toolTip"> <string>Show the linked packet in a separate window.</string> </property> </action> <action name="actionGoAutoScroll"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>Auto Scroll in Li&amp;ve Capture</string> </property> <property name="toolTip"> <string>Automatically scroll to the last packet during a live capture.</string> </property> </action> <action name="actionAnalyzeExpertInfo"> <property name="text"> <string>Expert Information</string> </property> <property name="toolTip"> <string>Show expert notifications</string> </property> </action> <action name="actionDisplayFilterExpression"> <property name="text"> <string>Display Filter &amp;Expression…</string> </property> <property name="iconText"> <string>Display Filter Expression…</string> </property> <property name="toolTip"> <string>Add an expression to the display filter.</string> </property> </action> <action name="actionStatistics_REGISTER_STAT_GROUP_UNSORTED"> <property name="text"> <string>REGISTER_STAT_GROUP_UNSORTED</string> </property> <property name="toolTip"> <string>Start of &quot;REGISTER_STAT_GROUP_UNSORTED&quot;</string> </property> <property name="visible"> <bool>false</bool> </property> <property name="menuRole"> <enum>QAction::NoRole</enum> </property> </action> <action name="actionStatisticsResolvedAddresses"> <property name="text"> <string>Resolved Addresses</string> </property> <property name="toolTip"> <string>Show each table of resolved addresses as copyable text.</string> </property> </action> <action name="actionViewColorizeConversation1"> <property name="text"> <string>Color &amp;1</string> </property> <property name="toolTip"> <string>Mark the current conversation with its own color.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+1</string> </property> </action> <action name="actionViewColorizeConversation2"> <property name="text"> <string>Color &amp;2</string> </property> <property name="toolTip"> <string>Mark the current conversation with its own color.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+2</string> </property> </action> <action name="actionViewColorizeConversation3"> <property name="text"> <string>Color &amp;3</string> </property> <property name="toolTip"> <string>Mark the current conversation with its own color.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+3</string> </property> </action> <action name="actionViewColorizeConversation4"> <property name="text"> <string>Color &amp;4</string> </property> <property name="toolTip"> <string>Mark the current conversation with its own color.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+4</string> </property> </action> <action name="actionViewColorizeConversation5"> <property name="text"> <string>Color &amp;5</string> </property> <property name="toolTip"> <string>Mark the current conversation with its own color.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+5</string> </property> </action> <action name="actionViewColorizeConversation6"> <property name="text"> <string>Color &amp;6</string> </property> <property name="toolTip"> <string>Mark the current conversation with its own color.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+6</string> </property> </action> <action name="actionViewColorizeConversation7"> <property name="text"> <string>Color &amp;7</string> </property> <property name="toolTip"> <string>Mark the current conversation with its own color.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+7</string> </property> </action> <action name="actionViewColorizeConversation8"> <property name="text"> <string>Color &amp;8</string> </property> <property name="toolTip"> <string>Mark the current conversation with its own color.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+8</string> </property> </action> <action name="actionViewColorizeConversation9"> <property name="text"> <string>Color &amp;9</string> </property> <property name="toolTip"> <string>Mark the current conversation with its own color.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+9</string> </property> </action> <action name="actionViewColorizeConversation10"> <property name="text"> <string>Color 1&amp;0</string> </property> <property name="toolTip"> <string>Mark the current conversation with its own color.</string> </property> </action> <action name="actionViewColorizeNewColoringRule"> <property name="text"> <string>New Coloring Rule…</string> </property> <property name="toolTip"> <string>Create a new coloring rule based on this field.</string> </property> </action> <action name="actionViewColorizeResetColorization"> <property name="text"> <string>Reset Colorization</string> </property> <property name="toolTip"> <string>Reset colorized conversations.</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Space</string> </property> </action> <action name="actionViewEditResolvedName"> <property name="text"> <string>Edit Resolved Name</string> </property> <property name="toolTip"> <string>Manually edit a name resolution entry.</string> </property> </action> <action name="actionAnalyzeEnabledProtocols"> <property name="text"> <string>Enabled Protocols…</string> </property> <property name="toolTip"> <string>Enable and disable specific protocols</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+E</string> </property> </action> <action name="actionAnalyzeShowPacketBytes"> <property name="text"> <string>Show Packet Bytes…</string> </property> <property name="shortcut"> <string notr="true">Ctrl+Shift+O</string> </property> </action> <action name="actionContextWikiProtocolPage"> <property name="text"> <string>Wiki Protocol Page</string> </property> <property name="toolTip"> <string>Open the Wireshark wiki page for this protocol.</string> </property> </action> <action name="actionContextFilterFieldReference"> <property name="text"> <string>Filter Field Reference</string> </property> <property name="toolTip"> <string>Open the display filter reference page for this filter field.</string> </property> </action> <action name="actionGoGoToLinkedPacket"> <property name="text"> <string>Go to &amp;Linked Packet</string> </property> <property name="toolTip"> <string>Go to the packet referenced by the selected field.</string> </property> </action> <action name="actionNewDisplayFilterExpression"> <property name="toolTip"> <string>Add a display filter button.</string> </property> </action> <action name="actionViewFullScreen"> <property name="checkable"> <bool>true</bool> </property> <property name="text"> <string>&amp;Full Screen</string> </property> </action> </widget> <layoutdefault spacing="6" margin="11"/> <customwidgets> <customwidget> <class>AccordionFrame</class> <extends>QFrame</extends> <header>accordion_frame.h</header> <container>1</container> </customwidget> <customwidget> <class>MainStatusBar</class> <extends>QStatusBar</extends> <header>main_status_bar.h</header> </customwidget> <customwidget> <class>WelcomePage</class> <extends>QFrame</extends> <header>welcome_page.h</header> <container>1</container> </customwidget> <customwidget> <class>SearchFrame</class> <extends>QWidget</extends> <header>search_frame.h</header> </customwidget> <customwidget> <class>ColumnEditorFrame</class> <extends>QFrame</extends> <header>column_editor_frame.h</header> <container>1</container> </customwidget> <customwidget> <class>PreferenceEditorFrame</class> <extends>QFrame</extends> <header>preference_editor_frame.h</header> <container>1</container> </customwidget> <customwidget> <class>AddressEditorFrame</class> <extends>QFrame</extends> <header>address_editor_frame.h</header> <container>1</container> </customwidget> <customwidget> <class>FilterExpressionFrame</class> <extends>QFrame</extends> <header>filter_expression_frame.h</header> <container>1</container> </customwidget> </customwidgets> <resources> <include location="../../resources/stock_icons.qrc"/> <include location="../../resources/stock_icons.qrc"/> </resources> <connections> <connection> <sender>actionFileQuit</sender> <signal>triggered()</signal> <receiver>LograyMainWindow</receiver> <slot>close()</slot> <hints> <hint type="sourcelabel"> <x>-1</x> <y>-1</y> </hint> <hint type="destinationlabel"> <x>408</x> <y>258</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/logray/logray_main_window_slots.cpp
/* main_window_slots.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include <config.h> // Qt 5.5.0 + Visual C++ 2013 #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4996) #endif #include "logray_main_window.h" /* * The generated Ui_LograyMainWindow::setupUi() can grow larger than our configured limit, * so turn off -Wframe-larger-than= for ui_main_window.h. */ DIAG_OFF(frame-larger-than=) #include <ui_logray_main_window.h> DIAG_ON(frame-larger-than=) #ifdef _WIN32 #include <windows.h> #endif #include "ui/dissect_opts.h" #ifdef HAVE_LIBPCAP #include "ui/capture.h" #endif #include "ui/commandline.h" #include "ui/urls.h" #include "epan/color_filters.h" #include "epan/export_object.h" #include "wsutil/file_util.h" #include "wsutil/filesystem.h" #include <wsutil/wslog.h> #include <wsutil/ws_assert.h> #include "epan/addr_resolv.h" #include "epan/column.h" #include "epan/dfilter/dfilter-macro.h" #include "epan/conversation_filter.h" #include "epan/epan_dissect.h" #include "epan/filter_expressions.h" #include "epan/prefs.h" #include "epan/plugin_if.h" #include "epan/uat.h" #include "epan/uat-int.h" #include "epan/value_string.h" #ifdef HAVE_LUA #include <epan/wslua/init_wslua.h> #endif #include "ui/alert_box.h" #ifdef HAVE_LIBPCAP #include "ui/capture_ui_utils.h" #endif #include "ui/capture_globals.h" #include "ui/help_url.h" #include "ui/main_statusbar.h" #include "ui/preference_utils.h" #include "ui/recent.h" #include "ui/recent_utils.h" #include "ui/ssl_key_export.h" #include "ui/ws_ui_util.h" #include "ui/all_files_wildcard.h" #include "ui/qt/simple_dialog.h" #include <ui/qt/utils/variant_pointer.h> #include <ui/qt/widgets/drag_drop_toolbar.h> #include "ui/qt/widgets/wireshark_file_dialog.h" #ifdef HAVE_SOFTWARE_UPDATE #include "ui/software_update.h" #endif #include "about_dialog.h" #include "capture_file_dialog.h" #include "capture_file_properties_dialog.h" #ifdef HAVE_LIBPCAP #include "capture_options_dialog.h" #endif #include <ui/qt/utils/color_utils.h> #include "coloring_rules_dialog.h" #include "conversation_dialog.h" #include "conversation_colorize_action.h" #include "conversation_hash_tables_dialog.h" #include "enabled_protocols_dialog.h" #include "decode_as_dialog.h" #include <ui/qt/widgets/display_filter_edit.h> #include "display_filter_expression_dialog.h" #include "dissector_tables_dialog.h" #include "endpoint_dialog.h" #include "expert_info_dialog.h" #include "export_object_action.h" #include "export_object_dialog.h" #include "export_pdu_dialog.h" #include "extcap_options_dialog.h" #include "file_set_dialog.h" #include "filter_action.h" #include "filter_dialog.h" #include "funnel_statistics.h" #include "interface_toolbar.h" #include "io_graph_dialog.h" #include <ui/qt/widgets/additional_toolbar.h> #include "main_application.h" #include "packet_comment_dialog.h" #include "packet_diagram.h" #include "packet_dialog.h" #include "packet_list.h" #include "preferences_dialog.h" #include "print_dialog.h" #include "profile_dialog.h" #include "protocol_hierarchy_dialog.h" #include <ui/qt/utils/qt_ui_utils.h> #include "resolved_addresses_dialog.h" #include "show_packet_bytes_dialog.h" #include "stats_tree_dialog.h" #include <ui/qt/utils/stock_icon.h> #include "supported_protocols_dialog.h" #include "tap_parameter_dialog.h" #include "time_shift_dialog.h" #include "uat_dialog.h" #include <functional> #include <QClipboard> #include <QFileInfo> #include <QMessageBox> #include <QMetaObject> #include <QToolBar> #include <QDesktopServices> #include <QUrl> #include <QMutex> // XXX You must uncomment QT_WINEXTRAS_LIB lines in CMakeList.txt and // cmakeconfig.h.in. // #if defined(QT_WINEXTRAS_LIB) // #include <QWinJumpList> // #include <QWinJumpListCategory> // #include <QWinJumpListItem> // #endif // // Public slots // bool LograyMainWindow::openCaptureFile(QString cf_path, QString read_filter, unsigned int type, gboolean is_tempfile) { QString file_name = ""; dfilter_t *rfcode = NULL; df_error_t *df_err = NULL; int err; gboolean name_param; gboolean ret = true; // was a file name given as function parameter? name_param = !cf_path.isEmpty(); for (;;) { if (cf_path.isEmpty()) { CaptureFileDialog open_dlg(this, capture_file_.capFile()); if (open_dlg.open(file_name, type, read_filter)) { cf_path = file_name; } else { ret = false; goto finish; } } else { this->welcome_page_->getInterfaceFrame()->showRunOnFile(); } // TODO detect call from "cf_read" -> "update_progress_dlg" // ("capture_file_.capFile()->read_lock"), possibly queue opening the // file and return early to avoid the warning in testCaptureFileClose. QString before_what(tr(" before opening another file")); if (!testCaptureFileClose(before_what)) { ret = false; goto finish; } if (dfilter_compile(qUtf8Printable(read_filter), &rfcode, &df_err)) { cf_set_rfcode(CaptureFile::globalCapFile(), rfcode); } else { /* Not valid. Tell the user, and go back and run the file selection box again once they dismiss the alert. */ //bad_dfilter_alert_box(top_level, read_filter->str); QMessageBox::warning(this, tr("Invalid Display Filter"), QString("The filter expression ") + read_filter + QString(" isn't a valid display filter. (") + df_err->msg + QString(")."), QMessageBox::Ok); df_error_free(&df_err); if (!name_param) { // go back to the selection dialogue only if the file // was selected from this dialogue cf_path.clear(); continue; } } /* Make the file name available via MainWindow */ setMwFileName(cf_path); /* Try to open the capture file. This closes the current file if it succeeds. */ CaptureFile::globalCapFile()->window = this; if (cf_open(CaptureFile::globalCapFile(), qUtf8Printable(cf_path), type, is_tempfile, &err) != CF_OK) { /* We couldn't open it; don't dismiss the open dialog box, just leave it around so that the user can, after they dismiss the alert box popped up for the open error, try again. */ CaptureFile::globalCapFile()->window = NULL; dfilter_free(rfcode); cf_path.clear(); continue; } switch (cf_read(CaptureFile::globalCapFile(), /*reloading=*/FALSE)) { case CF_READ_OK: case CF_READ_ERROR: /* Just because we got an error, that doesn't mean we were unable to read any of the file; we handle what we could get from the file. */ break; case CF_READ_ABORTED: /* The user bailed out of re-reading the capture file; the capture file has been closed - just free the capture file name string and return (without changing the last containing directory). */ capture_file_.setCapFile(NULL); ret = false; goto finish; } break; } mainApp->setLastOpenDirFromFilename(cf_path); main_ui_->statusBar->showExpert(); finish: #ifdef HAVE_LIBPCAP if (global_commandline_info.quit_after_cap) exit(0); #endif return ret; } void LograyMainWindow::filterPackets(QString new_filter, bool force) { cf_status_t cf_status; cf_status = cf_filter_packets(CaptureFile::globalCapFile(), new_filter.toUtf8().data(), force); if (cf_status == CF_OK) { if (new_filter.length() > 0) { int index = df_combo_box_->findText(new_filter); if (index == -1) { df_combo_box_->insertItem(0, new_filter); df_combo_box_->setCurrentIndex(0); } else { df_combo_box_->setCurrentIndex(index); } } else { df_combo_box_->lineEdit()->clear(); } // Only after the display filter has been updated, // disable the arrow button emit displayFilterSuccess(true); } else { emit displayFilterSuccess(false); } } void LograyMainWindow::layoutToolbars() { Qt::ToolButtonStyle tbstyle = Qt::ToolButtonIconOnly; switch (prefs.gui_toolbar_main_style) { case TB_STYLE_TEXT: tbstyle = Qt::ToolButtonTextOnly; break; case TB_STYLE_BOTH: tbstyle = Qt::ToolButtonTextUnderIcon; break; } main_ui_->mainToolBar->setToolButtonStyle(tbstyle); main_ui_->mainToolBar->setVisible(recent.main_toolbar_show); main_ui_->displayFilterToolBar->setVisible(recent.filter_toolbar_show); main_ui_->statusBar->setVisible(recent.statusbar_show); foreach(QAction *action, main_ui_->menuInterfaceToolbars->actions()) { QToolBar *toolbar = action->data().value<QToolBar *>(); if (g_list_find_custom(recent.interface_toolbars, action->text().toUtf8(), (GCompareFunc)strcmp)) { toolbar->setVisible(true); } else { toolbar->setVisible(false); } } QList<QToolBar *> toolbars = findChildren<QToolBar *>(); foreach(QToolBar *bar, toolbars) { AdditionalToolBar *iftoolbar = dynamic_cast<AdditionalToolBar *>(bar); if (iftoolbar) { bool visible = false; if (g_list_find_custom(recent.gui_additional_toolbars, qUtf8Printable(iftoolbar->menuName()), (GCompareFunc)strcmp)) visible = true; iftoolbar->setVisible(visible); } } } void LograyMainWindow::updatePreferenceActions() { main_ui_->actionViewPacketList->setEnabled(prefs_has_layout_pane_content(layout_pane_content_plist)); main_ui_->actionViewPacketDetails->setEnabled(prefs_has_layout_pane_content(layout_pane_content_pdetails)); main_ui_->actionViewPacketBytes->setEnabled(prefs_has_layout_pane_content(layout_pane_content_pbytes)); main_ui_->actionViewPacketDiagram->setEnabled(prefs_has_layout_pane_content(layout_pane_content_pdiagram)); main_ui_->actionViewNameResolutionPhysical->setChecked(gbl_resolv_flags.mac_name); main_ui_->actionViewNameResolutionNetwork->setChecked(gbl_resolv_flags.network_name); main_ui_->actionViewNameResolutionTransport->setChecked(gbl_resolv_flags.transport_name); } void LograyMainWindow::updateRecentActions() { main_ui_->actionViewMainToolbar->setChecked(recent.main_toolbar_show); main_ui_->actionViewFilterToolbar->setChecked(recent.filter_toolbar_show); main_ui_->actionViewStatusBar->setChecked(recent.statusbar_show); main_ui_->actionViewPacketList->setChecked(recent.packet_list_show && prefs_has_layout_pane_content(layout_pane_content_plist)); main_ui_->actionViewPacketDetails->setChecked(recent.tree_view_show && prefs_has_layout_pane_content(layout_pane_content_pdetails)); main_ui_->actionViewPacketBytes->setChecked(recent.byte_view_show && prefs_has_layout_pane_content(layout_pane_content_pbytes)); main_ui_->actionViewPacketDiagram->setChecked(recent.packet_diagram_show && prefs_has_layout_pane_content(layout_pane_content_pdiagram)); foreach(QAction *action, main_ui_->menuInterfaceToolbars->actions()) { if (g_list_find_custom(recent.interface_toolbars, action->text().toUtf8(), (GCompareFunc)strcmp)) { action->setChecked(true); } else { action->setChecked(false); } } foreach(QAction * action, main_ui_->menuAdditionalToolbars->actions()) { ext_toolbar_t * toolbar = VariantPointer<ext_toolbar_t>::asPtr(action->data()); bool checked = false; if (toolbar && g_list_find_custom(recent.gui_additional_toolbars, toolbar->name, (GCompareFunc)strcmp)) checked = true; action->setChecked(checked); } foreach(QAction* tda, td_actions.keys()) { if (recent.gui_time_format == td_actions[tda]) { tda->setChecked(true); } } foreach(QAction* tpa, tp_actions.keys()) { if (recent.gui_time_precision == tp_actions[tpa]) { tpa->setChecked(true); break; } } main_ui_->actionViewTimeDisplaySecondsWithHoursAndMinutes->setChecked(recent.gui_seconds_format == TS_SECONDS_HOUR_MIN_SEC); main_ui_->actionViewColorizePacketList->setChecked(recent.packet_list_colorize); main_ui_->actionGoAutoScroll->setChecked(recent.capture_auto_scroll); } // Don't connect to this directly. Connect to or emit fiterAction(...) instead. void LograyMainWindow::queuedFilterAction(QString action_filter, FilterAction::Action action, FilterAction::ActionType type) { QString cur_filter, new_filter; if (!df_combo_box_) return; cur_filter = df_combo_box_->lineEdit()->text(); switch (type) { case FilterAction::ActionTypePlain: new_filter = action_filter; break; case FilterAction::ActionTypeAnd: if (cur_filter.length()) { new_filter = "(" + cur_filter + ") && (" + action_filter + ")"; } else { new_filter = action_filter; } break; case FilterAction::ActionTypeOr: if (cur_filter.length()) { new_filter = "(" + cur_filter + ") || (" + action_filter + ")"; } else { new_filter = action_filter; } break; case FilterAction::ActionTypeNot: new_filter = "!(" + action_filter + ")"; break; case FilterAction::ActionTypeAndNot: if (cur_filter.length()) { new_filter = "(" + cur_filter + ") && !(" + action_filter + ")"; } else { new_filter = "!(" + action_filter + ")"; } break; case FilterAction::ActionTypeOrNot: if (cur_filter.length()) { new_filter = "(" + cur_filter + ") || !(" + action_filter + ")"; } else { new_filter = "!(" + action_filter + ")"; } break; default: ws_assert_not_reached(); break; } switch (action) { case FilterAction::ActionApply: df_combo_box_->lineEdit()->setText(new_filter); df_combo_box_->applyDisplayFilter(); break; case FilterAction::ActionColorize: colorizeWithFilter(new_filter.toUtf8()); break; case FilterAction::ActionCopy: mainApp->clipboard()->setText(new_filter); break; case FilterAction::ActionFind: main_ui_->searchFrame->findFrameWithFilter(new_filter); break; case FilterAction::ActionPrepare: df_combo_box_->lineEdit()->setText(new_filter); df_combo_box_->lineEdit()->setFocus(); break; case FilterAction::ActionWebLookup: { QString url = QString("https://www.google.com/search?q=") + new_filter; QDesktopServices::openUrl(QUrl(url)); break; } default: ws_assert_not_reached(); break; } } // Capture callbacks #ifdef HAVE_LIBPCAP void LograyMainWindow::captureCapturePrepared(capture_session *session) { setTitlebarForCaptureInProgress(); setWindowIcon(mainApp->captureIcon()); /* Disable menu items that make no sense if you're currently running a capture. */ bool handle_toolbars = (session->session_will_restart ? false : true); setForCaptureInProgress(true, handle_toolbars, session->capture_opts->ifaces); // set_capture_if_dialog_for_capture_in_progress(TRUE); // /* Don't set up main window for a capture file. */ // main_set_for_capture_file(FALSE); showCapture(); } void LograyMainWindow::captureCaptureUpdateStarted(capture_session *session) { /* We've done this in "prepared" above, but it will be cleared while switching to the next multiple file. */ setTitlebarForCaptureInProgress(); setWindowIcon(mainApp->captureIcon()); bool handle_toolbars = (session->session_will_restart ? false : true); setForCaptureInProgress(true, handle_toolbars, session->capture_opts->ifaces); setForCapturedPackets(true); } void LograyMainWindow::captureCaptureUpdateFinished(capture_session *session) { /* The capture isn't stopping any more - it's stopped. */ capture_stopping_ = false; /* Update the main window as appropriate */ updateForUnsavedChanges(); /* Enable menu items that make sense if you're not currently running a capture. */ bool handle_toolbars = (session->session_will_restart ? false : true); setForCaptureInProgress(false, handle_toolbars); setMenusForCaptureFile(); setWindowIcon(mainApp->normalIcon()); popLiveCaptureInProgress(); if (global_commandline_info.quit_after_cap) { // Command line asked us to quit after capturing. // Don't pop up a dialog to ask for unsaved files etc. exit(0); } } void LograyMainWindow::captureCaptureFixedFinished(capture_session *) { /* The capture isn't stopping any more - it's stopped. */ capture_stopping_ = false; /* Enable menu items that make sense if you're not currently running a capture. */ setForCaptureInProgress(false); /* There isn't a real capture_file structure yet, so just force disabling menu options. They will "refresh" when the capture file is reloaded to display packets */ setMenusForCaptureFile(true); setWindowIcon(mainApp->normalIcon()); popLiveCaptureInProgress(); if (global_commandline_info.quit_after_cap) { // Command line asked us to quit after capturing. // Don't pop up a dialog to ask for unsaved files etc. exit(0); } } void LograyMainWindow::captureCaptureFailed(capture_session *) { /* Capture isn't stopping any more. */ capture_stopping_ = false; setForCaptureInProgress(false); showWelcome(); // Reset expert information indicator main_ui_->statusBar->captureFileClosing(); mainApp->popStatus(WiresharkApplication::FileStatus); setWindowIcon(mainApp->normalIcon()); popLiveCaptureInProgress(); if (global_commandline_info.quit_after_cap) { // Command line asked us to quit after capturing. // Don't pop up a dialog to ask for unsaved files etc. exit(0); } } #endif // HAVE_LIBPCAP // Callbacks from cfile.c and file.c via CaptureFile::captureFileCallback void LograyMainWindow::captureEventHandler(CaptureEvent ev) { switch (ev.captureContext()) { case CaptureEvent::File: switch (ev.eventType()) { case CaptureEvent::Opened: captureFileOpened(); break; case CaptureEvent::Closing: captureFileClosing(); break; case CaptureEvent::Closed: captureFileClosed(); break; case CaptureEvent::Started: captureFileReadStarted(tr("Loading")); break; case CaptureEvent::Finished: captureFileReadFinished(); break; default: break; } break; case CaptureEvent::Reload: switch (ev.eventType()) { case CaptureEvent::Started: captureFileReadStarted(tr("Reloading")); break; case CaptureEvent::Finished: captureFileReadFinished(); break; default: break; } break; case CaptureEvent::Rescan: switch (ev.eventType()) { case CaptureEvent::Started: setMenusForCaptureFile(true); captureFileReadStarted(tr("Rescanning")); break; case CaptureEvent::Finished: captureFileReadFinished(); break; default: break; } break; case CaptureEvent::Retap: switch (ev.eventType()) { case CaptureEvent::Started: freeze(); break; case CaptureEvent::Finished: thaw(); break; case CaptureEvent::Flushed: draw_tap_listeners(FALSE); break; default: break; } break; case CaptureEvent::Merge: switch (ev.eventType()) { case CaptureEvent::Started: mainApp->popStatus(WiresharkApplication::FileStatus); mainApp->pushStatus(WiresharkApplication::FileStatus, tr("Merging files."), QString()); break; case CaptureEvent::Finished: mainApp->popStatus(WiresharkApplication::FileStatus); break; default: break; } break; case CaptureEvent::Save: switch (ev.eventType()) { case CaptureEvent::Started: { QFileInfo file_info(ev.filePath()); mainApp->popStatus(WiresharkApplication::FileStatus); mainApp->pushStatus(WiresharkApplication::FileStatus, tr("Saving %1…").arg(file_info.fileName())); break; } default: break; } break; #ifdef HAVE_LIBPCAP case CaptureEvent::Capture: switch (ev.eventType()) { case CaptureEvent::Prepared: captureCapturePrepared(ev.capSession()); break; case CaptureEvent::Stopping: capture_stopping_ = true; setMenusForCaptureStopping(); break; case CaptureEvent::Failed: captureCaptureFailed(ev.capSession()); default: break; } break; case CaptureEvent::Update: switch (ev.eventType()) { case CaptureEvent::Started: captureCaptureUpdateStarted(ev.capSession()); break; case CaptureEvent::Finished: captureCaptureUpdateFinished(ev.capSession()); break; default: break; } break; case CaptureEvent::Fixed: switch (ev.eventType()) { case CaptureEvent::Finished: captureCaptureFixedFinished(ev.capSession()); break; default: break; } break; #endif } } void LograyMainWindow::captureFileOpened() { if (capture_file_.window() != this) return; file_set_dialog_->fileOpened(capture_file_.capFile()); setMenusForFileSet(true); emit setCaptureFile(capture_file_.capFile()); } void LograyMainWindow::captureFileReadStarted(const QString &action) { // tap_param_dlg_update(); /* Set up main window for a capture file. */ // main_set_for_capture_file(TRUE); mainApp->popStatus(WiresharkApplication::FileStatus); QString msg = QString(tr("%1: %2")).arg(action).arg(capture_file_.fileName()); QString msgtip = QString(); mainApp->pushStatus(WiresharkApplication::FileStatus, msg, msgtip); showCapture(); main_ui_->actionAnalyzeReloadLuaPlugins->setEnabled(false); } void LograyMainWindow::captureFileReadFinished() { if (!capture_file_.capFile()->is_tempfile && capture_file_.capFile()->filename) { /* Add this filename to the list of recent files in the "Recent Files" submenu */ add_menu_recent_capture_file(capture_file_.capFile()->filename); /* Remember folder for next Open dialog and save it in recent */ mainApp->setLastOpenDirFromFilename(capture_file_.capFile()->filename); } /* Update the appropriate parts of the main window. */ updateForUnsavedChanges(); /* Enable menu items that make sense if you have some captured packets. */ setForCapturedPackets(true); main_ui_->statusBar->setFileName(capture_file_); main_ui_->actionAnalyzeReloadLuaPlugins->setEnabled(true); packet_list_->captureFileReadFinished(); emit setDissectedCaptureFile(capture_file_.capFile()); } void LograyMainWindow::captureFileClosing() { setMenusForCaptureFile(true); setForCapturedPackets(false); setForCaptureInProgress(false); // Reset expert information indicator main_ui_->statusBar->captureFileClosing(); main_ui_->searchFrame->animatedHide(); main_ui_->goToFrame->animatedHide(); // gtk_widget_show(expert_info_none); emit setCaptureFile(NULL); emit setDissectedCaptureFile(NULL); } void LograyMainWindow::captureFileClosed() { packets_bar_update(); file_set_dialog_->fileClosed(); setMenusForFileSet(false); setWindowModified(false); // Reset expert information indicator main_ui_->statusBar->captureFileClosing(); mainApp->popStatus(WiresharkApplication::FileStatus); setWSWindowTitle(); setWindowIcon(mainApp->normalIcon()); setMenusForSelectedPacket(); setMenusForSelectedTreeRow(); #ifdef HAVE_LIBPCAP if (!global_capture_opts.multi_files_on) showWelcome(); #endif } // // Private slots // // ui/gtk/capture_dlg.c:start_capture_confirmed void LograyMainWindow::startCapture() { startCapture(QStringList()); } void LograyMainWindow::startCapture(QStringList interfaces _U_) { #ifdef HAVE_LIBPCAP interface_options *interface_opts; guint i; interface_t *device; gboolean can_start_capture = TRUE; /* did the user ever select a capture interface before? */ if (global_capture_opts.num_selected == 0) { QString msg = QString(tr("No interface selected.")); mainApp->pushStatus(WiresharkApplication::TemporaryStatus, msg); main_ui_->actionCaptureStart->setChecked(false); return; } for (i = 0; i < global_capture_opts.all_ifaces->len; i++) { device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i); if (device->selected && (device->if_info.type == IF_EXTCAP)) { /* device is EXTCAP and is selected. Check if all mandatory * settings are set. */ if (extcap_requires_configuration(device->name)) { /* Request openning of extcap options dialog */ QString device_name(device->name); emit showExtcapOptions(device_name, false); /* Cancel start of capture */ can_start_capture = FALSE; } } } /* If some of extcap was not configured, do not start with the capture */ if (!can_start_capture) { QString msg = QString(tr("Configure all extcaps before start of capture.")); mainApp->pushStatus(WiresharkApplication::TemporaryStatus, msg); main_ui_->actionCaptureStart->setChecked(false); return; } // Ideally we should have disabled the start capture // toolbar buttons and menu items. This may not be the // case, e.g. with QtMacExtras. if (!capture_filter_valid_) { QString msg = QString(tr("Invalid capture filter.")); mainApp->pushStatus(WiresharkApplication::TemporaryStatus, msg); main_ui_->actionCaptureStart->setChecked(false); return; } showCapture(); /* XXX - we might need to init other pref data as well... */ main_ui_->actionGoAutoScroll->setChecked(recent.capture_auto_scroll); /* XXX - can this ever happen? */ if (cap_session_.state != CAPTURE_STOPPED) return; /* close the currently loaded capture file */ cf_close((capture_file *)cap_session_.cf); /* Copy the selected interfaces to the set of interfaces to use for this capture. */ collect_ifaces(&global_capture_opts); CaptureFile::globalCapFile()->window = this; info_data_.ui.ui = this; if (capture_start(&global_capture_opts, NULL, &cap_session_, &info_data_, main_window_update)) { capture_options *capture_opts = cap_session_.capture_opts; GString *interface_names; /* Add "interface name<live capture in progress>" on main status bar */ interface_names = get_iface_list_string(capture_opts, 0); if (strlen(interface_names->str) > 0) { g_string_append(interface_names, ":"); } g_string_append(interface_names, " "); mainApp->popStatus(WiresharkApplication::FileStatus); QString msg = QString("%1<live capture in progress>").arg(interface_names->str); QString msgtip = QString("to file: "); if (capture_opts->save_file) msgtip += capture_opts->save_file; mainApp->pushStatus(WiresharkApplication::FileStatus, msg, msgtip); g_string_free(interface_names, TRUE); /* The capture succeeded, which means the capture filter syntax is valid; add this capture filter to the recent capture filter list. */ QByteArray filter_ba; for (i = 0; i < global_capture_opts.ifaces->len; i++) { interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i); if (interface_opts->cfilter) { recent_add_cfilter(interface_opts->name, interface_opts->cfilter); if (filter_ba.isEmpty()) { filter_ba = interface_opts->cfilter; } else { /* Not the first selected interface; is its capture filter the same as the one the other interfaces we've looked at have? */ if (strcmp(interface_opts->cfilter, filter_ba.constData()) != 0) { /* No, so not all selected interfaces have the same capture filter. */ filter_ba.clear(); } } } } if (!filter_ba.isEmpty()) { recent_add_cfilter(NULL, filter_ba.constData()); } } else { CaptureFile::globalCapFile()->window = NULL; } #endif // HAVE_LIBPCAP } void LograyMainWindow::popLiveCaptureInProgress() { /* Pop the "<live capture in progress>" message off the status bar. */ main_ui_->statusBar->setFileName(capture_file_); } void LograyMainWindow::stopCapture() { //#ifdef HAVE_AIRPCAP // if (airpcap_if_active) // airpcap_set_toolbar_stop_capture(airpcap_if_active); //#endif #ifdef HAVE_LIBPCAP capture_stop(&cap_session_); #endif // HAVE_LIBPCAP } // Keep focus rects from showing through the welcome screen. Primarily for // macOS. void LograyMainWindow::mainStackChanged(int) { for (int i = 0; i < main_ui_->mainStack->count(); i++) { main_ui_->mainStack->widget(i)->setEnabled(i == main_ui_->mainStack->currentIndex()); } } // XXX - Copied from ui/gtk/menus.c /** * Add the capture filename (with an absolute path) to the "Recent Files" menu. */ // XXX - We should probably create a RecentFile class. void LograyMainWindow::updateRecentCaptures() { QAction *ra; QMenu *recentMenu = main_ui_->menuOpenRecentCaptureFile; QString action_cf_name; if (!recentMenu) { return; } recentMenu->clear(); #if 0 #if defined(QT_WINEXTRAS_LIB) QWinJumpList recent_jl(this); QWinJumpListCategory *recent_jlc = recent_jl.recent(); if (recent_jlc) { recent_jlc->clear(); recent_jlc->setVisible(true); } #endif #endif #if defined(Q_OS_MAC) if (!dock_menu_) { dock_menu_ = new QMenu(); dock_menu_->setAsDockMenu(); } dock_menu_->clear(); #endif /* Iterate through the actions in menuOpenRecentCaptureFile, * removing special items, a maybe duplicate entry and every item above count_max */ int shortcut = Qt::Key_0; foreach(recent_item_status *ri, mainApp->recentItems()) { // Add the new item ra = new QAction(recentMenu); ra->setData(ri->filename); // XXX - Needs get_recent_item_status or equivalent ra->setEnabled(ri->accessible); recentMenu->insertAction(NULL, ra); action_cf_name = ra->data().toString(); if (shortcut <= Qt::Key_9) { ra->setShortcut(Qt::META | (Qt::Key)shortcut); shortcut++; } ra->setText(action_cf_name); connect(ra, SIGNAL(triggered()), this, SLOT(recentActionTriggered())); /* This is slow, at least on my VM here. The added links also open Wireshark * in a new window. It might make more sense to add a recent item when we * open a capture file. */ #if 0 #if defined(QT_WINEXTRAS_LIB) if (recent_jlc) { QFileInfo fi(ri->filename); QWinJumpListItem *jli = recent_jlc->addLink( fi.fileName(), QApplication::applicationFilePath(), QStringList() << "-r" << ri->filename ); // XXX set icon jli->setWorkingDirectory(QDir::toNativeSeparators(QApplication::applicationDirPath())); } #endif #endif #if defined(Q_OS_MAC) QAction *rda = new QAction(dock_menu_); QFileInfo fi(ri->filename); rda->setText(fi.fileName()); dock_menu_->insertAction(NULL, rda); connect(rda, SIGNAL(triggered()), ra, SLOT(trigger())); #endif } if (recentMenu->actions().count() > 0) { // Separator + "Clear" // XXX - Do we really need this? ra = new QAction(recentMenu); ra->setSeparator(true); recentMenu->insertAction(NULL, ra); ra = new QAction(recentMenu); ra->setText(tr("Clear Menu")); recentMenu->insertAction(NULL, ra); connect(ra, SIGNAL(triggered()), mainApp, SLOT(clearRecentCaptures())); } else { if (main_ui_->actionDummyNoFilesFound) { recentMenu->addAction(main_ui_->actionDummyNoFilesFound); } } } void LograyMainWindow::recentActionTriggered() { QAction *ra = qobject_cast<QAction*>(sender()); if (ra) { QString cfPath = ra->data().toString(); openCaptureFile(cfPath); } } QString LograyMainWindow::commentToMenuText(QString text, int max_len) { text = text.trimmed().replace(QRegularExpression("(\\r?\\n|\\r\\n?)+"), " "); if (text.size() > 0) { if (text.size() > max_len) { text.truncate(max_len); text += "…"; } } else { text = tr("(empty comment)", "placeholder for empty comment"); } return text; } void LograyMainWindow::setEditCommentsMenu() { main_ui_->menuPacketComment->clear(); QAction *action = main_ui_->menuPacketComment->addAction(tr("Add New Comment…")); connect(action, &QAction::triggered, this, &LograyMainWindow::addPacketComment); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_C)); if (selectedRows().count() == 1) { const int thisRow = selectedRows().first(); frame_data * current_frame = frameDataForRow(thisRow); wtap_block_t pkt_block = cf_get_packet_block(capture_file_.capFile(), current_frame); guint nComments = wtap_block_count_option(pkt_block, OPT_COMMENT); if (nComments > 0) { main_ui_->menuPacketComment->addSeparator(); for (guint i = 0; i < nComments; i++) { QString comment = packet_list_->getPacketComment(i); comment = this->commentToMenuText(comment); action = main_ui_->menuPacketComment->addAction(tr("Edit \"%1\"", "edit packet comment").arg(comment)); connect(action, &QAction::triggered, this, &LograyMainWindow::editPacketComment); action->setData(i); } main_ui_->menuPacketComment->addSeparator(); for (guint i = 0; i < nComments; i++) { QString comment = packet_list_->getPacketComment(i); comment = this->commentToMenuText(comment); action = main_ui_->menuPacketComment->addAction(tr("Delete \"%1\"", "delete packet comment").arg(comment)); connect(action, &QAction::triggered, this, &LograyMainWindow::deletePacketComment); action->setData(i); } main_ui_->menuPacketComment->addSeparator(); action = main_ui_->menuPacketComment->addAction(tr("Delete packet comments")); connect(action, &QAction::triggered, this, &LograyMainWindow::deleteCommentsFromPackets); } wtap_block_unref(pkt_block); } if (selectedRows().count() > 1) { main_ui_->menuPacketComment->addSeparator(); action = main_ui_->menuPacketComment->addAction(tr("Delete comments from %n packet(s)", nullptr, static_cast<int>(selectedRows().count()))); connect(action, &QAction::triggered, this, &LograyMainWindow::deleteCommentsFromPackets); } } void LograyMainWindow::setMenusForSelectedPacket() { /* Making the menu context-sensitive allows for easier selection of the desired item and has the added benefit, with large captures, of avoiding needless looping through huge lists for marked, ignored, or time-referenced packets. */ /* We have one or more items in the packet list */ bool have_frames = false; /* A frame is selected */ bool frame_selected = false; bool multi_selection = false; /* A visible packet comes after this one in the selection history */ bool next_selection_history = false; /* A visible packet comes before this one in the selection history */ bool previous_selection_history = false; /* We have marked frames. (XXX - why check frame_selected?) */ bool have_marked = false; /* We have a marked frame other than the current frame (i.e., we have at least one marked frame, and either there's more than one marked frame or the current frame isn't marked). */ bool another_is_marked = false; /* One or more frames are hidden by a display filter */ bool have_filtered = false; /* One or more frames have been ignored */ bool have_ignored = false; bool have_time_ref = false; /* We have a time reference frame other than the current frame (i.e., we have at least one time reference frame, and either there's more than one time reference frame or the current frame isn't a time reference frame). (XXX - why check frame_selected?) */ bool another_is_time_ref = false; QList<QAction *> cc_actions = QList<QAction *>() << main_ui_->actionViewColorizeConversation1 << main_ui_->actionViewColorizeConversation2 << main_ui_->actionViewColorizeConversation3 << main_ui_->actionViewColorizeConversation4 << main_ui_->actionViewColorizeConversation5 << main_ui_->actionViewColorizeConversation6 << main_ui_->actionViewColorizeConversation7 << main_ui_->actionViewColorizeConversation8 << main_ui_->actionViewColorizeConversation9 << main_ui_->actionViewColorizeConversation10; if (capture_file_.capFile()) { QList<int> rows = selectedRows(); frame_data * current_frame = 0; if (rows.count() > 0) current_frame = frameDataForRow(rows.at(0)); frame_selected = rows.count() == 1; if (packet_list_->multiSelectActive()) { frame_selected = false; multi_selection = true; } next_selection_history = packet_list_->haveNextHistory(); previous_selection_history = packet_list_->havePreviousHistory(); have_frames = capture_file_.capFile()->count > 0; have_marked = capture_file_.capFile()->marked_count > 0; another_is_marked = have_marked && rows.count() <= 1 && !(capture_file_.capFile()->marked_count == 1 && frame_selected && current_frame->marked); have_filtered = capture_file_.capFile()->displayed_count > 0 && capture_file_.capFile()->displayed_count != capture_file_.capFile()->count; have_ignored = capture_file_.capFile()->ignored_count > 0; have_time_ref = capture_file_.capFile()->ref_time_count > 0; another_is_time_ref = have_time_ref && rows.count() <= 1 && !(capture_file_.capFile()->ref_time_count == 1 && frame_selected && current_frame->ref_time); } main_ui_->actionEditMarkPacket->setText(tr("&Mark/Unmark Packet(s)", "", static_cast<int>(selectedRows().count()))); main_ui_->actionEditIgnorePacket->setText(tr("&Ignore/Unignore Packet(s)", "", static_cast<int>(selectedRows().count()))); main_ui_->actionCopyListAsText->setEnabled(selectedRows().count() > 0); main_ui_->actionCopyListAsCSV->setEnabled(selectedRows().count() > 0); main_ui_->actionCopyListAsYAML->setEnabled(selectedRows().count() > 0); main_ui_->actionEditMarkPacket->setEnabled(frame_selected || multi_selection); main_ui_->actionEditMarkAllDisplayed->setEnabled(have_frames); /* Unlike un-ignore, do not allow unmark of all frames when no frames are displayed */ main_ui_->actionEditUnmarkAllDisplayed->setEnabled(have_marked); main_ui_->actionEditNextMark->setEnabled(another_is_marked); main_ui_->actionEditPreviousMark->setEnabled(another_is_marked); GArray * linkTypes = Q_NULLPTR; if (capture_file_.capFile() && capture_file_.capFile()->linktypes) linkTypes = capture_file_.capFile()->linktypes; bool enableEditComments = linkTypes && wtap_dump_can_write(capture_file_.capFile()->linktypes, WTAP_COMMENT_PER_PACKET); main_ui_->menuPacketComment->setEnabled(enableEditComments && selectedRows().count() > 0); main_ui_->actionDeleteAllPacketComments->setEnabled(enableEditComments); main_ui_->actionEditIgnorePacket->setEnabled(frame_selected || multi_selection); main_ui_->actionEditIgnoreAllDisplayed->setEnabled(have_filtered); /* Allow un-ignore of all frames even with no frames currently displayed */ main_ui_->actionEditUnignoreAllDisplayed->setEnabled(have_ignored); main_ui_->actionEditSetTimeReference->setEnabled(frame_selected); main_ui_->actionEditUnsetAllTimeReferences->setEnabled(have_time_ref); main_ui_->actionEditNextTimeReference->setEnabled(another_is_time_ref); main_ui_->actionEditPreviousTimeReference->setEnabled(another_is_time_ref); main_ui_->actionEditTimeShift->setEnabled(have_frames); main_ui_->actionGoGoToLinkedPacket->setEnabled(false); main_ui_->actionGoNextHistoryPacket->setEnabled(next_selection_history); main_ui_->actionGoPreviousHistoryPacket->setEnabled(previous_selection_history); foreach(QAction *cc_action, cc_actions) { cc_action->setEnabled(frame_selected); } main_ui_->actionViewColorizeNewColoringRule->setEnabled(frame_selected); main_ui_->actionViewColorizeResetColorization->setEnabled(tmp_color_filters_used()); main_ui_->actionViewShowPacketInNewWindow->setEnabled(frame_selected); // main_ui_->actionViewEditResolvedName->setEnabled(frame_selected && is_ip); emit packetInfoChanged(capture_file_.packetInfo()); // set_menu_sensitivity(ui_manager_main_menubar, "/Menubar/ViewMenu/NameResolution/ResolveName", // frame_selected && (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name || // gbl_resolv_flags.transport_name)); } void LograyMainWindow::setMenusForSelectedTreeRow(FieldInformation *finfo) { bool can_match_selected = false; bool is_framenum = false; bool have_subtree = false; bool can_open_url = false; bool have_packet_bytes = false; QByteArray field_filter; int field_id = -1; field_info * fi = 0; if (finfo) fi = finfo->fieldInfo(); if (capture_file_.capFile()) { capture_file_.capFile()->finfo_selected = fi; if (fi && fi->tree_type != -1) { have_subtree = true; } if (fi && fi->ds_tvb && (fi->length > 0)) { have_packet_bytes = true; } } if (capture_file_.capFile() != NULL && fi != NULL) { header_field_info *hfinfo = fi->hfinfo; int linked_frame = -1; can_match_selected = proto_can_match_selected(capture_file_.capFile()->finfo_selected, capture_file_.capFile()->edt); if (hfinfo && hfinfo->type == FT_FRAMENUM) { is_framenum = true; linked_frame = fvalue_get_uinteger(fi->value); } char *tmp_field = proto_construct_match_selected_string(fi, capture_file_.capFile()->edt); field_filter = tmp_field; wmem_free(NULL, tmp_field); emit fieldFilterChanged(field_filter); field_id = fi->hfinfo->id; /* if the selected field isn't a protocol, get its parent */ if (!proto_registrar_is_protocol(field_id)) { field_id = proto_registrar_get_parent(fi->hfinfo->id); } if (field_id >= 0) { can_open_url = true; main_ui_->actionContextWikiProtocolPage->setData(field_id); main_ui_->actionContextFilterFieldReference->setData(field_id); } else { main_ui_->actionContextWikiProtocolPage->setData(QVariant()); main_ui_->actionContextFilterFieldReference->setData(QVariant()); } if (linked_frame > 0) { main_ui_->actionGoGoToLinkedPacket->setData(linked_frame); } else { main_ui_->actionGoGoToLinkedPacket->setData(QVariant()); } } // Always enable / disable the following items. main_ui_->actionCopyAllVisibleItems->setEnabled(capture_file_.capFile() != NULL && ! packet_list_->multiSelectActive()); main_ui_->actionCopyAllVisibleSelectedTreeItems->setEnabled(can_match_selected); main_ui_->actionEditCopyDescription->setEnabled(can_match_selected); main_ui_->actionEditCopyFieldName->setEnabled(can_match_selected); main_ui_->actionEditCopyValue->setEnabled(can_match_selected); main_ui_->actionEditCopyAsFilter->setEnabled(can_match_selected); main_ui_->actionAnalyzeShowPacketBytes->setEnabled(have_packet_bytes); main_ui_->actionFileExportPacketBytes->setEnabled(have_packet_bytes); main_ui_->actionViewExpandSubtrees->setEnabled(have_subtree); main_ui_->actionViewCollapseSubtrees->setEnabled(have_subtree); main_ui_->actionGoGoToLinkedPacket->setEnabled(is_framenum); main_ui_->actionAnalyzeApplyAsColumn->setEnabled(can_match_selected); main_ui_->actionContextShowLinkedPacketInNewWindow->setEnabled(is_framenum); main_ui_->actionContextWikiProtocolPage->setEnabled(can_open_url); main_ui_->actionContextFilterFieldReference->setEnabled(can_open_url); // Only enable / disable the following items if we have focus so that we // don't clobber anything we may have set in setMenusForSelectedPacket. if (!proto_tree_ || !proto_tree_->hasFocus()) return; emit packetInfoChanged(capture_file_.packetInfo()); // set_menu_sensitivity(ui_manager_tree_view_menu, "/TreeViewPopup/ResolveName", // frame_selected && (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name || // gbl_resolv_flags.transport_name)); } void LograyMainWindow::interfaceSelectionChanged() { #ifdef HAVE_LIBPCAP // XXX This doesn't disable the toolbar button when using // QtMacExtras. if (global_capture_opts.num_selected > 0 && capture_filter_valid_) { main_ui_->actionCaptureStart->setEnabled(true); } else { main_ui_->actionCaptureStart->setEnabled(false); } #endif // HAVE_LIBPCAP } void LograyMainWindow::captureFilterSyntaxChanged(bool valid) { capture_filter_valid_ = valid; interfaceSelectionChanged(); } void LograyMainWindow::startInterfaceCapture(bool valid, const QString capture_filter) { capture_filter_valid_ = valid; welcome_page_->setCaptureFilter(capture_filter); QString before_what(tr(" before starting a new capture")); if (testCaptureFileClose(before_what)) { // The interface tree will update the selected interfaces via its timer // so no need to do anything here. startCapture(); } } void LograyMainWindow::applyGlobalCommandLineOptions() { if (global_dissect_options.time_format != TS_NOT_SET) { foreach(QAction* tda, td_actions.keys()) { if (global_dissect_options.time_format == td_actions[tda]) { tda->setChecked(true); // XXX - this means that if the user sets the // time stamp format with the -t flag, that // setting will persist and will be used as // the default the next time Logray is run. recent.gui_time_format = global_dissect_options.time_format; timestamp_set_type(global_dissect_options.time_format); break; } } } if (global_dissect_options.time_precision != TS_PREC_NOT_SET) { foreach(QAction* tpa, tp_actions.keys()) { if (global_dissect_options.time_precision == tp_actions[tpa]) { tpa->setChecked(true); // XXX - this means that if the user sets the // time stamp precision with the -t flag, that // setting will persist and will be used as // the default the next time Logray is run. recent.gui_time_precision = global_dissect_options.time_precision; timestamp_set_precision(global_dissect_options.time_precision); break; } } } if (global_commandline_info.full_screen) { this->showFullScreen(); } } void LograyMainWindow::redissectPackets() { if (capture_file_.capFile()) { cf_redissect_packets(capture_file_.capFile()); main_ui_->statusBar->expertUpdate(); } proto_free_deregistered_fields(); } void LograyMainWindow::checkDisplayFilter() { if (!df_combo_box_->checkDisplayFilter()) { g_free(CaptureFile::globalCapFile()->dfilter); CaptureFile::globalCapFile()->dfilter = NULL; } } void LograyMainWindow::fieldsChanged() { gchar *err_msg = NULL; if (!color_filters_reload(&err_msg, color_filter_add_cb)) { simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err_msg); g_free(err_msg); } tap_listeners_dfilter_recompile(); emit checkDisplayFilter(); if (have_custom_cols(&CaptureFile::globalCapFile()->cinfo)) { // Recreate packet list columns according to new/changed/deleted fields packet_list_->fieldsChanged(CaptureFile::globalCapFile()); } emit reloadFields(); } void LograyMainWindow::reloadLuaPlugins() { #ifdef HAVE_LUA if (mainApp->isReloadingLua()) return; gboolean uses_lua_filehandler = FALSE; if (capture_file_.capFile()) { // Check if the current capture file is opened with a Lua FileHandler capture_file *cf = capture_file_.capFile(); uses_lua_filehandler = wtap_uses_lua_filehandler(cf->provider.wth); if (uses_lua_filehandler && cf->unsaved_changes) { // Prompt to save the file before reloading, in case the FileHandler has changed QString before_what(tr(" before reloading Lua plugins")); if (!testCaptureFileClose(before_what, Reload)) { return; } } } mainApp->setReloadingLua(true); wslua_reload_plugins(NULL, NULL); funnel_statistics_reload_menus(); reloadDynamicMenus(); closePacketDialogs(); // Preferences may have been deleted so close all widgets using prefs main_ui_->preferenceEditorFrame->animatedHide(); mainApp->readConfigurationFiles(true); commandline_options_reapply(); fieldsChanged(); prefs_apply_all(); if (uses_lua_filehandler) { // Reload the file in case the FileHandler has changed if (cf_reload(capture_file_.capFile()) != CF_OK) { cf_close(capture_file_.capFile()); } proto_free_deregistered_fields(); } else { redissectPackets(); } mainApp->setReloadingLua(false); SimpleDialog::displayQueuedMessages(); #endif } void LograyMainWindow::showAccordionFrame(AccordionFrame *show_frame, bool toggle) { QList<AccordionFrame *>frame_list = QList<AccordionFrame *>() << main_ui_->goToFrame << main_ui_->searchFrame << main_ui_->addressEditorFrame << main_ui_->columnEditorFrame << main_ui_->preferenceEditorFrame << main_ui_->filterExpressionFrame; frame_list.removeAll(show_frame); foreach(AccordionFrame *af, frame_list) af->animatedHide(); if (toggle) { if (show_frame->isVisible()) { show_frame->animatedHide(); return; } } show_frame->animatedShow(); } void LograyMainWindow::showColumnEditor(int column) { previous_focus_ = mainApp->focusWidget(); connect(previous_focus_, SIGNAL(destroyed()), this, SLOT(resetPreviousFocus())); main_ui_->columnEditorFrame->editColumn(column); showAccordionFrame(main_ui_->columnEditorFrame); } void LograyMainWindow::showPreferenceEditor() { showAccordionFrame(main_ui_->preferenceEditorFrame); } void LograyMainWindow::initViewColorizeMenu() { QList<QAction *> cc_actions = QList<QAction *>() << main_ui_->actionViewColorizeConversation1 << main_ui_->actionViewColorizeConversation2 << main_ui_->actionViewColorizeConversation3 << main_ui_->actionViewColorizeConversation4 << main_ui_->actionViewColorizeConversation5 << main_ui_->actionViewColorizeConversation6 << main_ui_->actionViewColorizeConversation7 << main_ui_->actionViewColorizeConversation8 << main_ui_->actionViewColorizeConversation9 << main_ui_->actionViewColorizeConversation10; guint8 color_num = 1; foreach(QAction *cc_action, cc_actions) { cc_action->setData(color_num); connect(cc_action, SIGNAL(triggered()), this, SLOT(colorizeConversation())); const color_filter_t *colorf = color_filters_tmp_color(color_num); if (colorf) { QColor bg = ColorUtils::fromColorT(colorf->bg_color); QColor fg = ColorUtils::fromColorT(colorf->fg_color); cc_action->setIcon(StockIcon::colorIcon(bg.rgb(), fg.rgb(), QString::number(color_num))); } color_num++; } #ifdef Q_OS_MAC // Spotlight uses Cmd+Space main_ui_->actionViewColorizeResetColorization->setShortcut(QKeySequence("Meta+Space")); #endif } void LograyMainWindow::addStatsPluginsToMenu() { GList *cfg_list = stats_tree_get_cfg_list(); QAction *stats_tree_action; QMenu *parent_menu; bool first_item = true; for (GList *iter = g_list_first(cfg_list); iter; iter = gxx_list_next(iter)) { stats_tree_cfg *cfg = gxx_list_data(stats_tree_cfg *, iter); if (!menu_groups_.contains(cfg->stat_group)) { continue; } if (cfg->plugin) { if (first_item) { main_ui_->menuStatistics->addSeparator(); first_item = false; } parent_menu = main_ui_->menuStatistics; // gtk/main_menubar.c compresses double slashes, hence SkipEmptyParts #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) QStringList cfg_name_parts = QString(cfg->name).split("/", Qt::SkipEmptyParts); #else QStringList cfg_name_parts = QString(cfg->name).split("/", QString::SkipEmptyParts); #endif if (cfg_name_parts.isEmpty()) continue; QString stat_name = cfg_name_parts.takeLast(); if (!cfg_name_parts.isEmpty()) { QString menu_name = cfg_name_parts.join("/"); parent_menu = findOrAddMenu(parent_menu, menu_name); } stats_tree_action = new QAction(stat_name, this); stats_tree_action->setData(QString::fromUtf8(cfg->abbr)); parent_menu->addAction(stats_tree_action); connect(stats_tree_action, &QAction::triggered, this, [this]() { QAction* action = qobject_cast<QAction*>(sender()); if (action) { openStatisticsTreeDialog(action->data().toString().toUtf8()); } }); } } g_list_free(cfg_list); } void LograyMainWindow::setFeaturesEnabled(bool enabled) { main_ui_->menuBar->setEnabled(enabled); main_ui_->mainToolBar->setEnabled(enabled); main_ui_->displayFilterToolBar->setEnabled(enabled); if (enabled) { main_ui_->statusBar->clearMessage(); #ifdef HAVE_LIBPCAP main_ui_->actionGoAutoScroll->setChecked(recent.capture_auto_scroll); #endif } else { main_ui_->statusBar->showMessage(tr("Please wait while Wireshark is initializing…")); } } // Display Filter Toolbar void LograyMainWindow::on_actionNewDisplayFilterExpression_triggered() { main_ui_->filterExpressionFrame->addExpression(df_combo_box_->lineEdit()->text()); } void LograyMainWindow::onFilterSelected(QString filterText, bool prepare) { if (filterText.length() <= 0) return; df_combo_box_->setDisplayFilter(filterText); // Holding down the Shift key will only prepare filter. if (!prepare) df_combo_box_->applyDisplayFilter(); } void LograyMainWindow::onFilterPreferences() { emit showPreferencesDialog(PrefsModel::typeToString(PrefsModel::FilterButtons)); } void LograyMainWindow::onFilterEdit(int uatIndex) { main_ui_->filterExpressionFrame->editExpression(uatIndex); } void LograyMainWindow::openStatCommandDialog(const QString &menu_path, const char *arg, void *userdata) { QString slot = QString("statCommand%1").arg(menu_path); QMetaObject::invokeMethod(this, slot.toLatin1().constData(), Q_ARG(const char *, arg), Q_ARG(void *, userdata)); } void LograyMainWindow::openTapParameterDialog(const QString cfg_str, const QString arg, void *userdata) { TapParameterDialog *tp_dialog = TapParameterDialog::showTapParameterStatistics(*this, capture_file_, cfg_str, arg, userdata); if (!tp_dialog) return; connect(tp_dialog, SIGNAL(filterAction(QString, FilterAction::Action, FilterAction::ActionType)), this, SIGNAL(filterAction(QString, FilterAction::Action, FilterAction::ActionType))); connect(tp_dialog, SIGNAL(updateFilter(QString)), df_combo_box_->lineEdit(), SLOT(setText(QString))); tp_dialog->show(); } void LograyMainWindow::openTapParameterDialog() { QAction *tpa = qobject_cast<QAction *>(QObject::sender()); if (!tpa) return; const QString cfg_str = tpa->data().toString(); openTapParameterDialog(cfg_str, NULL, NULL); } #if defined(HAVE_SOFTWARE_UPDATE) && defined(Q_OS_WIN) void LograyMainWindow::softwareUpdateRequested() { // We could call testCaptureFileClose here, but that would give us yet // another dialog. Just try again later. if (capture_file_.capFile() && capture_file_.capFile()->state != FILE_CLOSED) { mainApp->rejectSoftwareUpdate(); } } #endif // File Menu void LograyMainWindow::connectFileMenuActions() { connect(main_ui_->actionFileOpen, &QAction::triggered, this, [this]() { openCaptureFile(); }); connect(main_ui_->actionFileMerge, &QAction::triggered, this, [this]() { mergeCaptureFile(); }); connect(main_ui_->actionFileImportFromHexDump, &QAction::triggered, this, [this]() { importCaptureFile(); }); connect(main_ui_->actionFileClose, &QAction::triggered, this, [this]() { QString before_what(tr(" before closing the file")); if (testCaptureFileClose(before_what)) { showWelcome(); } }); connect(main_ui_->actionFileSave, &QAction::triggered, this, [this]() { saveCaptureFile(capture_file_.capFile(), false); }); connect(main_ui_->actionFileSaveAs, &QAction::triggered, this, [this]() { saveAsCaptureFile(capture_file_.capFile()); }); connect(main_ui_->actionFileSetListFiles, &QAction::triggered, this, [this]() { file_set_dialog_->show(); }); connect(main_ui_->actionFileSetNextFile, &QAction::triggered, this, [this]() { fileset_entry *entry = fileset_get_next(); if (entry) { QString new_cf_path = entry->fullname; openCaptureFile(new_cf_path); } }); connect(main_ui_->actionFileSetPreviousFile, &QAction::triggered, this, [this]() { fileset_entry *entry = fileset_get_previous(); if (entry) { QString new_cf_path = entry->fullname; openCaptureFile(new_cf_path); } }); connect(main_ui_->actionFileExportPackets, &QAction::triggered, this, [this]() { exportSelectedPackets(); }); connect(main_ui_->actionFileExportAsPlainText, &QAction::triggered, this, [this]() { exportDissections(export_type_text); }); connect(main_ui_->actionFileExportAsCSV, &QAction::triggered, this, [this]() { exportDissections(export_type_csv); }); connect(main_ui_->actionFileExportAsCArrays, &QAction::triggered, this, [this]() { exportDissections(export_type_carrays); }); connect(main_ui_->actionFileExportAsPSML, &QAction::triggered, this, [this]() { exportDissections(export_type_psml); }); connect(main_ui_->actionFileExportAsPDML, &QAction::triggered, this, [this]() { exportDissections(export_type_pdml); }); connect(main_ui_->actionFileExportAsJSON, &QAction::triggered, this, [this]() { exportDissections(export_type_json); }); connect(main_ui_->actionFileExportPacketBytes, &QAction::triggered, this, [this]() { exportPacketBytes(); }, Qt::QueuedConnection); connect(main_ui_->actionFileExportPDU, &QAction::triggered, this, [this]() { exportPDU(); }); connect(main_ui_->actionFilePrint, &QAction::triggered, this, [this]() { printFile(); }); } void LograyMainWindow::exportPacketBytes() { QString file_name; if (!capture_file_.capFile() || !capture_file_.capFile()->finfo_selected) return; file_name = WiresharkFileDialog::getSaveFileName(this, mainApp->windowTitleString(tr("Export Selected Packet Bytes")), mainApp->lastOpenDir().canonicalPath(), tr("Raw data (*.bin *.dat *.raw);;All Files (" ALL_FILES_WILDCARD ")") ); if (file_name.length() > 0) { const guint8 *data_p; data_p = tvb_get_ptr(capture_file_.capFile()->finfo_selected->ds_tvb, 0, -1) + capture_file_.capFile()->finfo_selected->start; write_file_binary_mode(qUtf8Printable(file_name), data_p, capture_file_.capFile()->finfo_selected->length); /* Save the directory name for future file dialogs. */ mainApp->setLastOpenDirFromFilename(file_name); } } void LograyMainWindow::exportPDU() { ExportPDUDialog *exportpdu_dialog = new ExportPDUDialog(this); if (exportpdu_dialog->isMinimized() == true) { exportpdu_dialog->showNormal(); } else { exportpdu_dialog->show(); } exportpdu_dialog->raise(); exportpdu_dialog->activateWindow(); } void LograyMainWindow::printFile() { capture_file *cf = capture_file_.capFile(); g_return_if_fail(cf); QList<int> rows = packet_list_->selectedRows(true); QStringList entries; foreach (int row, rows) entries << QString::number(row); QString selRange = entries.join(","); PrintDialog * pdlg_ = new PrintDialog(this, cf, selRange); pdlg_->setWindowModality(Qt::ApplicationModal); pdlg_->show(); } // Edit Menu void LograyMainWindow::connectEditMenuActions() { connect(main_ui_->actionCopyAllVisibleItems, &QAction::triggered, this, [this]() { copySelectedItems(CopyAllVisibleItems); }); connect(main_ui_->actionCopyListAsText, &QAction::triggered, this, [this]() { copySelectedItems(CopyListAsText); }); connect(main_ui_->actionCopyListAsCSV, &QAction::triggered, this, [this]() { copySelectedItems(CopyListAsCSV); }); connect(main_ui_->actionCopyListAsYAML, &QAction::triggered, this, [this]() { copySelectedItems(CopyListAsYAML); }); connect(main_ui_->actionCopyAllVisibleSelectedTreeItems, &QAction::triggered, this, [this]() { copySelectedItems(CopyAllVisibleSelectedTreeItems); }); connect(main_ui_->actionEditCopyDescription, &QAction::triggered, this, [this]() { copySelectedItems(CopySelectedDescription); }); connect(main_ui_->actionEditCopyFieldName, &QAction::triggered, this, [this]() { copySelectedItems(CopySelectedFieldName); }); connect(main_ui_->actionEditCopyValue, &QAction::triggered, this, [this]() { copySelectedItems(CopySelectedValue); }); connect(main_ui_->actionEditCopyAsFilter, &QAction::triggered, this, [this]() { matchFieldFilter(FilterAction::ActionCopy, FilterAction::ActionTypePlain); }); connect(main_ui_->actionEditFindPacket, &QAction::triggered, this, [this]() { findPacket(); }); connect(main_ui_->actionEditFindNext, &QAction::triggered, this, [this]() { main_ui_->searchFrame->findNext(); }); connect(main_ui_->actionEditFindPrevious, &QAction::triggered, this, [this]() { main_ui_->searchFrame->findPrevious(); }); // The items below are used in the packet list and detail context menus. // Use QueuedConnections so that the context menus aren't destroyed // prematurely. connect(main_ui_->actionEditMarkPacket, &QAction::triggered, this, [this]() { freeze(); packet_list_->markFrame(); thaw(); setMenusForSelectedPacket(); }, Qt::QueuedConnection); connect(main_ui_->actionEditMarkAllDisplayed, &QAction::triggered, this, [this]() { freeze(); packet_list_->markAllDisplayedFrames(true); thaw(); setMenusForSelectedPacket(); }, Qt::QueuedConnection); connect(main_ui_->actionEditUnmarkAllDisplayed, &QAction::triggered, this, [this]() { freeze(); packet_list_->markAllDisplayedFrames(false); thaw(); setMenusForSelectedPacket(); }, Qt::QueuedConnection); connect(main_ui_->actionEditNextMark, &QAction::triggered, this, [this]() { if (capture_file_.capFile()) { cf_find_packet_marked(capture_file_.capFile(), SD_FORWARD); } }, Qt::QueuedConnection); connect(main_ui_->actionEditPreviousMark, &QAction::triggered, this, [this]() { if (capture_file_.capFile()) { cf_find_packet_marked(capture_file_.capFile(), SD_BACKWARD); } }, Qt::QueuedConnection); connect(main_ui_->actionEditIgnorePacket, &QAction::triggered, this, [this]() { freeze(); packet_list_->ignoreFrame(); thaw(); setMenusForSelectedPacket(); }, Qt::QueuedConnection); connect(main_ui_->actionEditIgnoreAllDisplayed, &QAction::triggered, this, [this]() { freeze(); packet_list_->ignoreAllDisplayedFrames(true); thaw(); setMenusForSelectedPacket(); }, Qt::QueuedConnection); connect(main_ui_->actionEditUnignoreAllDisplayed, &QAction::triggered, this, [this]() { freeze(); packet_list_->ignoreAllDisplayedFrames(false); thaw(); setMenusForSelectedPacket(); }, Qt::QueuedConnection); connect(main_ui_->actionEditSetTimeReference, &QAction::triggered, this, [this]() { packet_list_->setTimeReference(); setMenusForSelectedPacket(); }, Qt::QueuedConnection); connect(main_ui_->actionEditUnsetAllTimeReferences, &QAction::triggered, this, [this]() { packet_list_->unsetAllTimeReferences(); setMenusForSelectedPacket(); }, Qt::QueuedConnection); connect(main_ui_->actionEditNextTimeReference, &QAction::triggered, this, [this]() { if (!capture_file_.capFile()) return; cf_find_packet_time_reference(capture_file_.capFile(), SD_FORWARD); }, Qt::QueuedConnection); connect(main_ui_->actionEditPreviousTimeReference, &QAction::triggered, this, [this]() { if (!capture_file_.capFile()) return; cf_find_packet_time_reference(capture_file_.capFile(), SD_BACKWARD); }, Qt::QueuedConnection); connect(main_ui_->actionEditTimeShift, &QAction::triggered, this, [this]() { editTimeShift(); }, Qt::QueuedConnection); connect(main_ui_->actionDeleteAllPacketComments, &QAction::triggered, this, [this]() { deleteAllPacketComments(); }, Qt::QueuedConnection); connect(main_ui_->actionEditConfigurationProfiles, &QAction::triggered, this, [this]() { editConfigurationProfiles(); }, Qt::QueuedConnection); connect(main_ui_->actionEditPreferences, &QAction::triggered, this, [this]() { showPreferencesDialog(PrefsModel::typeToString(PrefsModel::Appearance)); }, Qt::QueuedConnection); } // XXX This should probably be somewhere else. void LograyMainWindow::copySelectedItems(LograyMainWindow::CopySelected selection_type) { char label_str[ITEM_LABEL_LENGTH]; QString clip; if (!capture_file_.capFile()) return; field_info *finfo_selected = capture_file_.capFile()->finfo_selected; switch (selection_type) { case CopySelectedDescription: if (proto_tree_->selectionModel()->hasSelection()) { QModelIndex idx = proto_tree_->selectionModel()->selectedIndexes().first(); clip = idx.data(Qt::DisplayRole).toString(); } break; case CopySelectedFieldName: if (finfo_selected && finfo_selected->hfinfo->abbrev != 0) { clip.append(finfo_selected->hfinfo->abbrev); } break; case CopySelectedValue: if (finfo_selected && capture_file_.capFile()->edt != 0) { gchar* field_str = get_node_field_value(finfo_selected, capture_file_.capFile()->edt); clip.append(field_str); g_free(field_str); } break; case CopyAllVisibleItems: clip = proto_tree_->toString(); break; case CopyAllVisibleSelectedTreeItems: if (proto_tree_->selectionModel()->hasSelection()) { clip = proto_tree_->toString(proto_tree_->selectionModel()->selectedIndexes().first()); } break; case CopyListAsText: case CopyListAsCSV: case CopyListAsYAML: if (packet_list_->selectedRows().count() > 0) { QList<int> rows = packet_list_->selectedRows(); QStringList content; PacketList::SummaryCopyType copyType = PacketList::CopyAsText; if (selection_type == CopyListAsCSV) copyType = PacketList::CopyAsCSV; else if (selection_type == CopyListAsYAML) copyType = PacketList::CopyAsYAML; if ((copyType == PacketList::CopyAsText) || (copyType == PacketList::CopyAsCSV)) { QString headerEntry = packet_list_->createHeaderSummaryText(copyType); content << headerEntry; } foreach (int row, rows) { QModelIndex idx = packet_list_->model()->index(row, 0); if (! idx.isValid()) continue; QString entry = packet_list_->createSummaryText(idx, copyType); content << entry; } if (content.count() > 0) { clip = content.join("\n"); // // Each YAML item ends with a newline, so the string // ends with a newline already if it's CopyListAsYAML. // If we add a newline, there'd be an extra blank // line. // // Otherwise, we've used newlines as separators, not // terminators, so there's no final newline. Add it. // if (selection_type != CopyListAsYAML) clip += "\n"; } } break; } if (clip.length() == 0) { /* If no representation then... Try to read the value */ proto_item_fill_label(capture_file_.capFile()->finfo_selected, label_str); clip.append(label_str); } if (clip.length()) { mainApp->clipboard()->setText(clip); } else { QString err = tr("Couldn't copy text. Try another item."); mainApp->pushStatus(WiresharkApplication::TemporaryStatus, err); } } void LograyMainWindow::findPacket() { if (! packet_list_->model() || packet_list_->model()->rowCount() < 1) { return; } previous_focus_ = mainApp->focusWidget(); connect(previous_focus_, SIGNAL(destroyed()), this, SLOT(resetPreviousFocus())); if (!main_ui_->searchFrame->isVisible()) { showAccordionFrame(main_ui_->searchFrame, true); } else { main_ui_->searchFrame->animatedHide(); } main_ui_->searchFrame->setFocus(); } void LograyMainWindow::editTimeShift() { TimeShiftDialog *ts_dialog = new TimeShiftDialog(this, capture_file_.capFile()); connect(ts_dialog, SIGNAL(finished(int)), this, SLOT(editTimeShiftFinished(int))); connect(this, SIGNAL(setCaptureFile(capture_file*)), ts_dialog, SLOT(setCaptureFile(capture_file*))); connect(ts_dialog, SIGNAL(timeShifted()), packet_list_, SLOT(applyTimeShift())); ts_dialog->setWindowModality(Qt::ApplicationModal); ts_dialog->setAttribute(Qt::WA_DeleteOnClose); ts_dialog->show(); } void LograyMainWindow::editTimeShiftFinished(int) { if (capture_file_.capFile()->unsaved_changes) { updateForUnsavedChanges(); } } void LograyMainWindow::addPacketComment() { QList<int> rows = selectedRows(); if (rows.count() == 0) return; frame_data * fdata = frameDataForRow(rows.at(0)); if (! fdata) return; PacketCommentDialog* pc_dialog; pc_dialog = new PacketCommentDialog(false, this, NULL); connect(pc_dialog, &QDialog::finished, std::bind(&LograyMainWindow::addPacketCommentFinished, this, pc_dialog, std::placeholders::_1)); pc_dialog->setWindowModality(Qt::ApplicationModal); pc_dialog->setAttribute(Qt::WA_DeleteOnClose); pc_dialog->show(); } void LograyMainWindow::addPacketCommentFinished(PacketCommentDialog* pc_dialog _U_, int result _U_) { if (result == QDialog::Accepted) { packet_list_->addPacketComment(pc_dialog->text()); updateForUnsavedChanges(); } } void LograyMainWindow::editPacketComment() { QList<int> rows = selectedRows(); if (rows.count() != 1) return; QAction *ra = qobject_cast<QAction*>(sender()); guint nComment = ra->data().toUInt(); PacketCommentDialog* pc_dialog; pc_dialog = new PacketCommentDialog(true, this, packet_list_->getPacketComment(nComment)); connect(pc_dialog, &QDialog::finished, std::bind(&LograyMainWindow::editPacketCommentFinished, this, pc_dialog, std::placeholders::_1, nComment)); pc_dialog->setWindowModality(Qt::ApplicationModal); pc_dialog->setAttribute(Qt::WA_DeleteOnClose); pc_dialog->show(); } void LograyMainWindow::editPacketCommentFinished(PacketCommentDialog* pc_dialog _U_, int result _U_, guint nComment) { if (result == QDialog::Accepted) { packet_list_->setPacketComment(nComment, pc_dialog->text()); updateForUnsavedChanges(); } } void LograyMainWindow::deletePacketComment() { QAction *ra = qobject_cast<QAction*>(sender()); guint nComment = ra->data().toUInt(); packet_list_->setPacketComment(nComment, QString("")); updateForUnsavedChanges(); } void LograyMainWindow::deleteCommentsFromPackets() { packet_list_->deleteCommentsFromPackets(); updateForUnsavedChanges(); } void LograyMainWindow::deleteAllPacketComments() { QMessageBox *msg_dialog = new QMessageBox(); connect(msg_dialog, SIGNAL(finished(int)), this, SLOT(deleteAllPacketCommentsFinished(int))); msg_dialog->setIcon(QMessageBox::Question); msg_dialog->setText(tr("Are you sure you want to remove all packet comments?")); msg_dialog->setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msg_dialog->setDefaultButton(QMessageBox::Ok); msg_dialog->setWindowModality(Qt::ApplicationModal); msg_dialog->setAttribute(Qt::WA_DeleteOnClose); msg_dialog->show(); } void LograyMainWindow::deleteAllPacketCommentsFinished(int result) { if (result == QMessageBox::Ok) { /* XXX Do we need a wait/hourglass for large files? */ packet_list_->deleteAllPacketComments(); updateForUnsavedChanges(); } } void LograyMainWindow::editConfigurationProfiles() { ProfileDialog *cp_dialog = new ProfileDialog(); cp_dialog->setWindowModality(Qt::ApplicationModal); cp_dialog->setAttribute(Qt::WA_DeleteOnClose); cp_dialog->show(); } void LograyMainWindow::showPreferencesDialog(QString module_name) { PreferencesDialog *pref_dialog = new PreferencesDialog(this); connect(pref_dialog, SIGNAL(destroyed(QObject*)), mainApp, SLOT(flushAppSignals())); saveWindowGeometry(); // Save in case the layout panes are rearranged pref_dialog->setPane(module_name); pref_dialog->setWindowModality(Qt::ApplicationModal); pref_dialog->setAttribute(Qt::WA_DeleteOnClose); pref_dialog->show(); } // View Menu void LograyMainWindow::connectViewMenuActions() { connect(main_ui_->actionViewFullScreen, &QAction::triggered, this, [this](bool checked) { if (checked) { // Save the state for future restore was_maximized_ = this->isMaximized(); this->showFullScreen(); } else { // Restore the previous state if (was_maximized_) { this->showMaximized(); } else { this->showNormal(); } } }); connect(main_ui_->actionViewTimeDisplaySecondsWithHoursAndMinutes, &QAction::triggered, this, [this](bool checked) { setTimeDisplaySecondsWithHoursAndMinutes(checked); }); connect(main_ui_->actionViewEditResolvedName, &QAction::triggered, this, [this]() { editResolvedName(); }); connect(main_ui_->actionViewNameResolutionPhysical, &QAction::triggered, this, [this]() { setNameResolution(); }); connect(main_ui_->actionViewNameResolutionNetwork, &QAction::triggered, this, [this]() { setNameResolution(); }); connect(main_ui_->actionViewNameResolutionTransport, &QAction::triggered, this, [this]() { setNameResolution(); }); connect(main_ui_->actionViewZoomIn, &QAction::triggered, this, [this]() { recent.gui_zoom_level++; zoomText(); }); connect(main_ui_->actionViewZoomOut, &QAction::triggered, this, [this]() { recent.gui_zoom_level--; zoomText(); }); connect(main_ui_->actionViewNormalSize, &QAction::triggered, this, [this]() { recent.gui_zoom_level = 0; zoomText(); }); connect(main_ui_->actionViewExpandSubtrees, &QAction::triggered, proto_tree_, &ProtoTree::expandSubtrees); connect(main_ui_->actionViewCollapseSubtrees, &QAction::triggered, proto_tree_, &ProtoTree::collapseSubtrees); connect(main_ui_->actionViewExpandAll, &QAction::triggered, proto_tree_, &ProtoTree::expandAll); connect(main_ui_->actionViewCollapseAll, &QAction::triggered, proto_tree_, &ProtoTree::collapseAll); connect(main_ui_->actionViewColorizePacketList, &QAction::triggered, this, [this](bool checked) { recent.packet_list_colorize = checked; packet_list_->recolorPackets(); }); connect(main_ui_->actionViewColoringRules, &QAction::triggered, this, [this]() { showColoringRulesDialog(); }); connect(main_ui_->actionViewColorizeResetColorization, &QAction::triggered, this, [this]() { gchar *err_msg = NULL; if (!color_filters_reset_tmp(&err_msg)) { simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err_msg); g_free(err_msg); } packet_list_->recolorPackets(); setMenusForSelectedPacket(); }); connect(main_ui_->actionViewColorizeNewColoringRule, &QAction::triggered, this, [this]() { colorizeConversation(true); }); connect(main_ui_->actionViewResetLayout, &QAction::triggered, this, [this]() { recent.gui_geometry_main_upper_pane = 0; recent.gui_geometry_main_lower_pane = 0; applyRecentPaneGeometry(); }); connect(main_ui_->actionViewResizeColumns, &QAction::triggered, this, [this]() { if (! packet_list_->model()) return; for (int col = 0; col < packet_list_->model()->columnCount(); col++) { packet_list_->resizeColumnToContents(col); recent_set_column_width(col, packet_list_->columnWidth(col)); } }); connect(main_ui_->actionViewInternalsConversationHashTables, &QAction::triggered, this, [this]() { ConversationHashTablesDialog *conversation_hash_tables_dlg = new ConversationHashTablesDialog(this); conversation_hash_tables_dlg->show(); }); connect(main_ui_->actionViewInternalsDissectorTables, &QAction::triggered, this, [this]() { DissectorTablesDialog *dissector_tables_dlg = new DissectorTablesDialog(this); dissector_tables_dlg->show(); }); connect(main_ui_->actionViewInternalsSupportedProtocols, &QAction::triggered, this, [this]() { SupportedProtocolsDialog *supported_protocols_dlg = new SupportedProtocolsDialog(this); supported_protocols_dlg->show(); }); connect(main_ui_->actionViewShowPacketInNewWindow, &QAction::triggered, this, [this]() { openPacketDialog(); }); // This is only used in ProtoTree. Defining it here makes more sense. connect(main_ui_->actionContextShowLinkedPacketInNewWindow, &QAction::triggered, this, [this]() { openPacketDialog(true); }); connect(main_ui_->actionViewReload_as_File_Format_or_Capture, &QAction::triggered, this, [this]() { reloadCaptureFileAsFormatOrCapture(); }); connect(main_ui_->actionViewReload, &QAction::triggered, this, [this]() { reloadCaptureFile(); }); } void LograyMainWindow::showHideMainWidgets(QAction *action) { if (!action) { return; } bool show = action->isChecked(); QWidget *widget = action->data().value<QWidget*>(); // We may have come from the toolbar context menu, so check/uncheck each // action as well. if (widget == main_ui_->mainToolBar) { recent.main_toolbar_show = show; main_ui_->actionViewMainToolbar->setChecked(show); } else if (widget == main_ui_->displayFilterToolBar) { recent.filter_toolbar_show = show; main_ui_->actionViewFilterToolbar->setChecked(show); } else if (widget == main_ui_->statusBar) { recent.statusbar_show = show; main_ui_->actionViewStatusBar->setChecked(show); } else if (widget == packet_list_) { recent.packet_list_show = show; main_ui_->actionViewPacketList->setChecked(show); } else if (widget == proto_tree_) { recent.tree_view_show = show; main_ui_->actionViewPacketDetails->setChecked(show); } else if (widget == byte_view_tab_) { recent.byte_view_show = show; main_ui_->actionViewPacketBytes->setChecked(show); } else if (widget == packet_diagram_) { recent.packet_diagram_show = show; main_ui_->actionViewPacketDiagram->setChecked(show); } else { foreach(QAction *action, main_ui_->menuInterfaceToolbars->actions()) { QToolBar *toolbar = action->data().value<QToolBar *>(); if (widget == toolbar) { GList *entry = g_list_find_custom(recent.interface_toolbars, action->text().toUtf8(), (GCompareFunc)strcmp); if (show && !entry) { recent.interface_toolbars = g_list_append(recent.interface_toolbars, g_strdup(action->text().toUtf8())); } else if (!show && entry) { recent.interface_toolbars = g_list_remove(recent.interface_toolbars, entry->data); } action->setChecked(show); } } ext_toolbar_t * toolbar = VariantPointer<ext_toolbar_t>::asPtr(action->data()); if (toolbar) { GList *entry = g_list_find_custom(recent.gui_additional_toolbars, toolbar->name, (GCompareFunc)strcmp); if (show && !entry) { recent.gui_additional_toolbars = g_list_append(recent.gui_additional_toolbars, g_strdup(toolbar->name)); } else if (!show && entry) { recent.gui_additional_toolbars = g_list_remove(recent.gui_additional_toolbars, entry->data); } action->setChecked(show); QList<QToolBar *> toolbars = findChildren<QToolBar *>(); foreach(QToolBar *bar, toolbars) { AdditionalToolBar *iftoolbar = dynamic_cast<AdditionalToolBar *>(bar); if (iftoolbar && iftoolbar->menuName().compare(toolbar->name) == 0) { iftoolbar->setVisible(show); } } } } if (widget) { widget->setVisible(show); } } void LograyMainWindow::setTimestampFormat(QAction *action) { if (!action) { return; } ts_type tsf = action->data().value<ts_type>(); if (recent.gui_time_format != tsf) { timestamp_set_type(tsf); recent.gui_time_format = tsf; if (packet_list_) { packet_list_->resetColumns(); packet_list_->resizeAllColumns(true); } } } void LograyMainWindow::setTimestampPrecision(QAction *action) { if (!action) { return; } ts_precision tsp = action->data().value<ts_precision>(); if (recent.gui_time_precision != tsp) { timestamp_set_precision(tsp); recent.gui_time_precision = tsp; if (packet_list_) { packet_list_->resetColumns(); packet_list_->resizeAllColumns(true); } } } void LograyMainWindow::setTimeDisplaySecondsWithHoursAndMinutes(bool checked) { if (checked) { recent.gui_seconds_format = TS_SECONDS_HOUR_MIN_SEC; } else { recent.gui_seconds_format = TS_SECONDS_DEFAULT; } timestamp_set_seconds_type(recent.gui_seconds_format); if (packet_list_) { packet_list_->resetColumns(); packet_list_->resizeAllColumns(true); } } void LograyMainWindow::editResolvedName() { //int column = packet_list_->selectedColumn(); int column = -1; if (packet_list_->currentIndex().isValid()) { column = packet_list_->currentIndex().column(); } main_ui_->addressEditorFrame->editAddresses(capture_file_, column); showAccordionFrame(main_ui_->addressEditorFrame); } void LograyMainWindow::setNameResolution() { gbl_resolv_flags.mac_name = main_ui_->actionViewNameResolutionPhysical->isChecked() ? TRUE : FALSE; gbl_resolv_flags.network_name = main_ui_->actionViewNameResolutionNetwork->isChecked() ? TRUE : FALSE; gbl_resolv_flags.transport_name = main_ui_->actionViewNameResolutionTransport->isChecked() ? TRUE : FALSE; if (packet_list_) { packet_list_->resetColumns(); } mainApp->emitAppSignal(WiresharkApplication::NameResolutionChanged); } void LograyMainWindow::zoomText() { mainApp->zoomTextFont(recent.gui_zoom_level); } void LograyMainWindow::showColoringRulesDialog() { ColoringRulesDialog *coloring_rules_dialog = new ColoringRulesDialog(this); connect(coloring_rules_dialog, &ColoringRulesDialog::accepted, packet_list_, &PacketList::recolorPackets); connect(coloring_rules_dialog, &ColoringRulesDialog::filterAction, this, &LograyMainWindow::filterAction); coloring_rules_dialog->setWindowModality(Qt::ApplicationModal); coloring_rules_dialog->setAttribute(Qt::WA_DeleteOnClose); coloring_rules_dialog->show(); } // actionViewColorizeConversation1 - 10 void LograyMainWindow::colorizeConversation(bool create_rule) { QAction *colorize_action = qobject_cast<QAction *>(sender()); if (!colorize_action) return; if (capture_file_.capFile() && selectedRows().count() > 0) { packet_info *pi = capture_file_.packetInfo(); guint8 cc_num = colorize_action->data().toUInt(); gchar *filter = conversation_filter_from_log(pi); if (filter == NULL) { mainApp->pushStatus(WiresharkApplication::TemporaryStatus, tr("Unable to build conversation filter.")); return; } if (create_rule) { ColoringRulesDialog coloring_rules_dialog(this, filter); connect(&coloring_rules_dialog, &ColoringRulesDialog::accepted, packet_list_, &PacketList::recolorPackets); connect(&coloring_rules_dialog, &ColoringRulesDialog::filterAction, this, &LograyMainWindow::filterAction); coloring_rules_dialog.exec(); } else { gchar *err_msg = NULL; if (!color_filters_set_tmp(cc_num, filter, FALSE, &err_msg)) { simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err_msg); g_free(err_msg); } packet_list_->recolorPackets(); } } setMenusForSelectedPacket(); } void LograyMainWindow::colorizeActionTriggered() { QByteArray filter; int color_number = -1; ConversationAction *conv_action = qobject_cast<ConversationAction *>(sender()); if (conv_action) { filter = conv_action->filter(); color_number = conv_action->colorNumber(); } else { ColorizeAction *colorize_action = qobject_cast<ColorizeAction *>(sender()); if (colorize_action) { filter = colorize_action->filter(); color_number = colorize_action->colorNumber(); } } colorizeWithFilter(filter, color_number); } void LograyMainWindow::colorizeWithFilter(QByteArray filter, int color_number) { if (filter.isEmpty()) return; if (color_number > 0) { // Assume "Color X" gchar *err_msg = NULL; if (!color_filters_set_tmp(color_number, filter.constData(), FALSE, &err_msg)) { simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err_msg); g_free(err_msg); } packet_list_->recolorPackets(); } else { // New coloring rule ColoringRulesDialog coloring_rules_dialog(window(), filter); connect(&coloring_rules_dialog, &ColoringRulesDialog::accepted, packet_list_, &PacketList::recolorPackets); connect(&coloring_rules_dialog, &ColoringRulesDialog::filterAction, this, &LograyMainWindow::filterAction); coloring_rules_dialog.exec(); } main_ui_->actionViewColorizeResetColorization->setEnabled(tmp_color_filters_used()); } void LograyMainWindow::openPacketDialog(bool from_reference) { frame_data * fdata = Q_NULLPTR; /* Find the frame for which we're popping up a dialog */ if (from_reference) { guint32 framenum = fvalue_get_uinteger(capture_file_.capFile()->finfo_selected->value); if (framenum == 0) return; fdata = frame_data_sequence_find(capture_file_.capFile()->provider.frames, framenum); } else if (selectedRows().count() == 1) { fdata = frameDataForRow(selectedRows().at(0)); } else if (selectedRows().count() > 1) return; /* If we have a frame, pop up the dialog */ if (fdata) { PacketDialog *packet_dialog = new PacketDialog(*this, capture_file_, fdata); connect(packet_dialog, &PacketDialog::showProtocolPreferences, this, &LograyMainWindow::showPreferencesDialog); connect(packet_dialog, SIGNAL(editProtocolPreference(preference*, pref_module*)), main_ui_->preferenceEditorFrame, SLOT(editPreference(preference*, pref_module*))); connect(this, &LograyMainWindow::closePacketDialogs, packet_dialog, &PacketDialog::close); zoomText(); // Emits mainApp->zoomMonospaceFont(QFont) packet_dialog->show(); } } void LograyMainWindow::reloadCaptureFileAsFormatOrCapture() { capture_file *cf = CaptureFile::globalCapFile(); if (cf->unsaved_changes) { QString before_what(tr(" before reloading the file")); if (!testCaptureFileClose(before_what, Reload)) return; } if (cf->open_type == WTAP_TYPE_AUTO) cf->open_type = open_info_name_to_type("MIME Files Format"); else /* TODO: This should be latest format chosen by user */ cf->open_type = WTAP_TYPE_AUTO; cf_reload(cf); } void LograyMainWindow::reloadCaptureFile() { capture_file *cf = CaptureFile::globalCapFile(); if (cf->unsaved_changes) { QString before_what(tr(" before reloading the file")); if (!testCaptureFileClose(before_what, Reload)) return; } cf_reload(cf); } // Expand / collapse slots in proto_tree // Go Menu void LograyMainWindow::connectGoMenuActions() { connect(main_ui_->actionGoGoToPacket, &QAction::triggered, this, [this]() { if (! packet_list_->model() || packet_list_->model()->rowCount() < 1) { return; } previous_focus_ = mainApp->focusWidget(); connect(previous_focus_, SIGNAL(destroyed()), this, SLOT(resetPreviousFocus())); showAccordionFrame(main_ui_->goToFrame, true); if (main_ui_->goToFrame->isVisible()) { main_ui_->goToLineEdit->clear(); main_ui_->goToLineEdit->setFocus(); } }); connect(main_ui_->actionGoGoToLinkedPacket, &QAction::triggered, this, [this]() { QAction *gta = qobject_cast<QAction*>(sender()); if (!gta) return; bool ok = false; int packet_num = gta->data().toInt(&ok); if (!ok) return; packet_list_->goToPacket(packet_num); }); connect(main_ui_->actionGoNextPacket, &QAction::triggered, packet_list_, &PacketList::goNextPacket); connect(main_ui_->actionGoPreviousPacket, &QAction::triggered, packet_list_, &PacketList::goPreviousPacket); connect(main_ui_->actionGoFirstPacket, &QAction::triggered, packet_list_, &PacketList::goFirstPacket); connect(main_ui_->actionGoLastPacket, &QAction::triggered, packet_list_, &PacketList::goLastPacket); connect(main_ui_->actionGoNextConversationPacket, &QAction::triggered, this, [this]() { goToConversationFrame(true); }); connect(main_ui_->actionGoPreviousConversationPacket, &QAction::triggered, this, [this]() { goToConversationFrame(false); }); connect(main_ui_->actionGoNextHistoryPacket, &QAction::triggered, packet_list_, &PacketList::goNextHistoryPacket); connect(main_ui_->actionGoPreviousHistoryPacket, &QAction::triggered, packet_list_, &PacketList::goPreviousHistoryPacket); // triggered is whenever the user clicks the button; save that as // the new recent value connect(main_ui_->actionGoAutoScroll, &QAction::triggered, this, [](bool checked) { recent.capture_auto_scroll = checked; }); // toggled is whenever the value changes; if it changes programmatically // (e.g., the user scrolls upwards so we stop auto scrolling) change // whether the button is checked but don't save value to recent (it's // a temporary change) connect(main_ui_->actionGoAutoScroll, &QAction::toggled, this, [this](bool checked) { packet_list_->setVerticalAutoScroll(checked); }); } void LograyMainWindow::goToConversationFrame(bool go_next) { gchar *filter = NULL; dfilter_t *dfcode = NULL; gboolean found_packet = FALSE; packet_info *pi = capture_file_.packetInfo(); if (!pi) { // No packet was selected, or multiple packets were selected. return; } /* Try to build a conversation * filter in the order TCP, UDP, IP, Ethernet and apply the * coloring */ filter = conversation_filter_from_log(pi); if (filter == NULL) { mainApp->pushStatus(WiresharkApplication::TemporaryStatus, tr("Unable to build conversation filter.")); g_free(filter); return; } if (!dfilter_compile(filter, &dfcode, NULL)) { /* The attempt failed; report an error. */ mainApp->pushStatus(WiresharkApplication::TemporaryStatus, tr("Error compiling filter for this conversation.")); g_free(filter); return; } found_packet = cf_find_packet_dfilter(capture_file_.capFile(), dfcode, go_next ? SD_FORWARD : SD_BACKWARD); if (!found_packet) { /* We didn't find a packet */ mainApp->pushStatus(WiresharkApplication::TemporaryStatus, tr("No previous/next packet in conversation.")); } dfilter_free(dfcode); g_free(filter); } // Capture Menu void LograyMainWindow::connectCaptureMenuActions() { #ifdef HAVE_LIBPCAP connect(main_ui_->actionCaptureOptions, &QAction::triggered, this, [this]() { showCaptureOptionsDialog(); }); #endif connect(main_ui_->actionCaptureStart, &QAction::triggered, this, [this]() { startCaptureTriggered(); }); connect(main_ui_->actionCaptureStop, &QAction::triggered, this, [this]() { stopCapture(); }); connect(main_ui_->actionCaptureRestart, &QAction::triggered, this, [this]() { #ifdef HAVE_LIBPCAP QString before_what(tr(" before restarting the capture")); cap_session_.capture_opts->restart = TRUE; if (!testCaptureFileClose(before_what, Restart)) { return; } startCapture(QStringList()); #endif // HAVE_LIBPCAP }); connect(main_ui_->actionCaptureCaptureFilters, &QAction::triggered, this, [this]() { FilterDialog *capture_filter_dlg = new FilterDialog(window(), FilterDialog::CaptureFilter); capture_filter_dlg->setWindowModality(Qt::ApplicationModal); capture_filter_dlg->setAttribute(Qt::WA_DeleteOnClose); capture_filter_dlg->show(); }); #ifdef HAVE_LIBPCAP connect(main_ui_->actionCaptureRefreshInterfaces, &QAction::triggered, this, [this]() { main_ui_->actionCaptureRefreshInterfaces->setEnabled(false); mainApp->refreshLocalInterfaces(); main_ui_->actionCaptureRefreshInterfaces->setEnabled(true); }); #endif } void LograyMainWindow::showCaptureOptionsDialog() { #ifdef HAVE_LIBPCAP if (!capture_options_dialog_) { capture_options_dialog_ = new CaptureOptionsDialog(this); connect(capture_options_dialog_, &CaptureOptionsDialog::startCapture, this, [this]() { startCapture(); }); connect(capture_options_dialog_, &CaptureOptionsDialog::stopCapture, this, &LograyMainWindow::stopCapture); connect(capture_options_dialog_, &CaptureOptionsDialog::interfacesChanged, this->welcome_page_, &WelcomePage::interfaceSelected); connect(capture_options_dialog_, &CaptureOptionsDialog::interfacesChanged, this->welcome_page_->getInterfaceFrame(), &InterfaceFrame::updateSelectedInterfaces); connect(capture_options_dialog_, &CaptureOptionsDialog::interfaceListChanged, this->welcome_page_->getInterfaceFrame(), &InterfaceFrame::interfaceListChanged); connect(capture_options_dialog_, &CaptureOptionsDialog::captureFilterTextEdited, this->welcome_page_, &WelcomePage::setCaptureFilterText); // Propagate selection changes from main UI to dialog. connect(this->welcome_page_, &WelcomePage::interfacesChanged, capture_options_dialog_, &CaptureOptionsDialog::interfaceSelected); connect(capture_options_dialog_, &CaptureOptionsDialog::setFilterValid, this, &LograyMainWindow::startInterfaceCapture); connect(capture_options_dialog_, &CaptureOptionsDialog::showExtcapOptions, this, &LograyMainWindow::showExtcapOptionsDialog); } capture_options_dialog_->updateInterfaces(); if (capture_options_dialog_->isMinimized()) { capture_options_dialog_->showNormal(); } else { capture_options_dialog_->show(); } capture_options_dialog_->raise(); capture_options_dialog_->activateWindow(); #endif } void LograyMainWindow::startCaptureTriggered() { //#ifdef HAVE_AIRPCAP // airpcap_if_active = airpcap_if_selected; // if (airpcap_if_active) // airpcap_set_toolbar_start_capture(airpcap_if_active); //#endif // if (cap_open_w) { // /* // * There's an options dialog; get the values from it and close it. // */ // gboolean success; // /* Determine if "capture start" while building of the "capture options" window */ // /* is in progress. If so, ignore the "capture start. */ // /* XXX: Would it be better/cleaner for the "capture options" window code to */ // /* disable the capture start button temporarily ? */ // if (cap_open_complete == FALSE) { // return; /* Building options window: ignore "capture start" */ // } // success = capture_dlg_prep(cap_open_w); // window_destroy(GTK_WIDGET(cap_open_w)); // if (!success) // return; /* error in options dialog */ // } #ifdef HAVE_LIBPCAP if (global_capture_opts.num_selected == 0) { QString err_msg = tr("No Interface Selected."); mainApp->pushStatus(WiresharkApplication::TemporaryStatus, err_msg); main_ui_->actionCaptureStart->setChecked(false); return; } /* XXX - will closing this remove a temporary file? */ QString before_what(tr(" before starting a new capture")); if (testCaptureFileClose(before_what)) { startCapture(); } else { // simply clicking the button sets it to 'checked' even though we've // decided to do nothing, so undo that main_ui_->actionCaptureStart->setChecked(false); } #endif // HAVE_LIBPCAP } // Analyze Menu void LograyMainWindow::connectAnalyzeMenuActions() { connect(main_ui_->actionAnalyzeDisplayFilters, &QAction::triggered, this, [=]() { FilterDialog *display_filter_dlg = new FilterDialog(window(), FilterDialog::DisplayFilter); display_filter_dlg->setWindowModality(Qt::ApplicationModal); display_filter_dlg->setAttribute(Qt::WA_DeleteOnClose); display_filter_dlg->show(); }); connect(main_ui_->actionAnalyzeDisplayFilterMacros, &QAction::triggered, this, [=]() { struct epan_uat* dfm_uat; dfilter_macro_get_uat(&dfm_uat); UatDialog *uat_dlg = new UatDialog(parentWidget(), dfm_uat); connect(uat_dlg, SIGNAL(destroyed(QObject*)), mainApp, SLOT(flushAppSignals())); uat_dlg->setWindowModality(Qt::ApplicationModal); uat_dlg->setAttribute(Qt::WA_DeleteOnClose); uat_dlg->show(); }); connect(main_ui_->actionDisplayFilterExpression, &QAction::triggered, this, [=]() { DisplayFilterExpressionDialog *dfe_dialog = new DisplayFilterExpressionDialog(this); connect(dfe_dialog, &DisplayFilterExpressionDialog::insertDisplayFilter, qobject_cast<SyntaxLineEdit *>(df_combo_box_->lineEdit()), &SyntaxLineEdit::insertFilter); dfe_dialog->show(); }); connect(main_ui_->actionAnalyzeApplyAsColumn, &QAction::triggered, this, &LograyMainWindow::applyFieldAsColumn); connect(main_ui_->actionAnalyzeEnabledProtocols, &QAction::triggered, this, [=]() { EnabledProtocolsDialog *enable_proto_dialog = new EnabledProtocolsDialog(this); connect(enable_proto_dialog, SIGNAL(destroyed(QObject*)), mainApp, SLOT(flushAppSignals())); enable_proto_dialog->setWindowModality(Qt::ApplicationModal); enable_proto_dialog->setAttribute(Qt::WA_DeleteOnClose); enable_proto_dialog->show(); }); connect(main_ui_->actionAnalyzeDecodeAs, &QAction::triggered, this, [=]() { QAction *da_action = qobject_cast<QAction*>(sender()); bool create_new = da_action && da_action->property("create_new").toBool(); DecodeAsDialog *da_dialog = new DecodeAsDialog(this, capture_file_.capFile(), create_new); connect(da_dialog, SIGNAL(destroyed(QObject*)), mainApp, SLOT(flushAppSignals())); da_dialog->setWindowModality(Qt::ApplicationModal); da_dialog->setAttribute(Qt::WA_DeleteOnClose); da_dialog->show(); }); connect(main_ui_->actionAnalyzeReloadLuaPlugins, &QAction::triggered, this, &LograyMainWindow::reloadLuaPlugins); connect(main_ui_->actionAnalyzeShowPacketBytes, &QAction::triggered, this, [=]() { ShowPacketBytesDialog *spbd = new ShowPacketBytesDialog(*this, capture_file_); spbd->addCodecs(text_codec_map_); spbd->show(); }); connect(main_ui_->actionAnalyzeExpertInfo, &QAction::triggered, this, [=]() { statCommandExpertInfo(NULL, NULL); }); } void LograyMainWindow::filterMenuAboutToShow() { QMenu * menu = qobject_cast<QMenu *>(sender()); QString field_filter; if (capture_file_.capFile() && capture_file_.capFile()->finfo_selected) { char *tmp_field = proto_construct_match_selected_string(capture_file_.capFile()->finfo_selected, capture_file_.capFile()->edt); field_filter = QString(tmp_field); wmem_free(NULL, tmp_field); } bool enable = ! field_filter.isEmpty(); bool prepare = menu->objectName().compare("menuPrepareAFilter") == 0; menu->clear(); QActionGroup * group = FilterAction::createFilterGroup(field_filter, prepare, enable, menu); menu->addActions(group->actions()); } void LograyMainWindow::matchFieldFilter(FilterAction::Action action, FilterAction::ActionType filter_type) { QString field_filter; if (packet_list_->contextMenuActive() || packet_list_->hasFocus()) { field_filter = packet_list_->getFilterFromRowAndColumn(packet_list_->currentIndex()); } else if (capture_file_.capFile() && capture_file_.capFile()->finfo_selected) { char *tmp_field = proto_construct_match_selected_string(capture_file_.capFile()->finfo_selected, capture_file_.capFile()->edt); field_filter = QString(tmp_field); wmem_free(NULL, tmp_field); } if (field_filter.isEmpty()) { QString err = tr("No filter available. Try another %1.").arg(packet_list_->contextMenuActive() ? tr("column") : tr("item")); mainApp->pushStatus(WiresharkApplication::TemporaryStatus, err); return; } setDisplayFilter(field_filter, action, filter_type); } void LograyMainWindow::applyFieldAsColumn() { if (capture_file_.capFile() != 0 && capture_file_.capFile()->finfo_selected != 0) { header_field_info *hfinfo = capture_file_.capFile()->finfo_selected->hfinfo; int col = column_prefs_has_custom(hfinfo->abbrev); if (col == -1) { insertColumn(hfinfo->name, hfinfo->abbrev); } else { QString status; if (QString(hfinfo->name) == get_column_title(col)) { status = tr("The \"%1\" column already exists.").arg(hfinfo->name); } else { status = tr("The \"%1\" column already exists as \"%2\".").arg(hfinfo->name).arg(get_column_title(col)); } mainApp->pushStatus(WiresharkApplication::TemporaryStatus, status); if (!get_column_visible(col)) { packet_list_->setColumnHidden(col, false); set_column_visible(col, TRUE); prefs_main_write(); } } } } void LograyMainWindow::applyConversationFilter() { ConversationAction *conv_action = qobject_cast<ConversationAction*>(sender()); if (!conv_action) return; packet_info *pinfo = capture_file_.packetInfo(); if (!pinfo) return; QByteArray conv_filter = conv_action->filter(); if (conv_filter.isEmpty()) return; if (conv_action->isFilterValid(pinfo)) { df_combo_box_->lineEdit()->setText(conv_filter); df_combo_box_->applyDisplayFilter(); } } void LograyMainWindow::applyExportObject() { ExportObjectAction *export_action = qobject_cast<ExportObjectAction*>(sender()); if (!export_action) return; ExportObjectDialog* export_dialog = new ExportObjectDialog(*this, capture_file_, export_action->exportObject()); export_dialog->setWindowModality(Qt::ApplicationModal); export_dialog->setAttribute(Qt::WA_DeleteOnClose); export_dialog->show(); } // -z expert void LograyMainWindow::statCommandExpertInfo(const char *, void *) { const DisplayFilterEdit *df_edit = dynamic_cast<DisplayFilterEdit *>(df_combo_box_->lineEdit()); ExpertInfoDialog *expert_dialog = new ExpertInfoDialog(*this, capture_file_, df_edit->text()); connect(expert_dialog->getExpertInfoView(), SIGNAL(goToPacket(int, int)), packet_list_, SLOT(goToPacket(int, int))); connect(expert_dialog, SIGNAL(filterAction(QString, FilterAction::Action, FilterAction::ActionType)), this, SIGNAL(filterAction(QString, FilterAction::Action, FilterAction::ActionType))); expert_dialog->show(); } // Next / previous / first / last slots in packet_list // Statistics Menu void LograyMainWindow::connectStatisticsMenuActions() { connect(main_ui_->actionStatisticsCaptureFileProperties, &QAction::triggered, this, [=]() { CaptureFilePropertiesDialog *capture_file_properties_dialog = new CaptureFilePropertiesDialog(*this, capture_file_); connect(capture_file_properties_dialog, SIGNAL(captureCommentChanged()), this, SLOT(updateForUnsavedChanges())); capture_file_properties_dialog->show(); }); connect(main_ui_->actionStatisticsResolvedAddresses, &QAction::triggered, this, &LograyMainWindow::showResolvedAddressesDialog); connect(main_ui_->actionStatisticsProtocolHierarchy, &QAction::triggered, this, [=]() { ProtocolHierarchyDialog *phd = new ProtocolHierarchyDialog(*this, capture_file_); connect(phd, SIGNAL(filterAction(QString, FilterAction::Action, FilterAction::ActionType)), this, SIGNAL(filterAction(QString, FilterAction::Action, FilterAction::ActionType))); phd->show(); }); connect(main_ui_->actionStatisticsConversations, &QAction::triggered, this, &LograyMainWindow::showConversationsDialog); connect(main_ui_->actionStatisticsEndpoints, &QAction::triggered, this, &LograyMainWindow::showEndpointsDialog); connect(main_ui_->actionStatisticsPacketLengths, &QAction::triggered, this, [=]() { openStatisticsTreeDialog("plen"); }); connect(main_ui_->actionStatisticsIOGraph, &QAction::triggered, this, [=]() { statCommandIOGraph(NULL, NULL); }); connect(main_ui_->actionStatisticsFlowGraph, &QAction::triggered, this, [=]() { QMessageBox::warning(this, "Oops", "SequenceDialog depends on RTPStreamDialog"); // SequenceDialog *sequence_dialog = new SequenceDialog(*this, capture_file_); // sequence_dialog->show(); }); } void LograyMainWindow::openStatisticsTreeDialog(const gchar *abbr) { StatsTreeDialog *st_dialog = new StatsTreeDialog(*this, capture_file_, abbr); // connect(st_dialog, SIGNAL(goToPacket(int)), // packet_list_, SLOT(goToPacket(int))); st_dialog->show(); } // -z io,stat void LograyMainWindow::statCommandIOGraph(const char *, void *) { const DisplayFilterEdit *df_edit = qobject_cast<DisplayFilterEdit *>(df_combo_box_->lineEdit()); QString displayFilter; if (df_edit) displayFilter = df_edit->text(); IOGraphDialog *iog_dialog = new IOGraphDialog(*this, capture_file_, displayFilter); connect(iog_dialog, SIGNAL(goToPacket(int)), packet_list_, SLOT(goToPacket(int))); connect(this, SIGNAL(reloadFields()), iog_dialog, SLOT(reloadFields())); iog_dialog->show(); } // Tools Menu // XXX No log tools yet // Help Menu void LograyMainWindow::connectHelpMenuActions() { connect(main_ui_->actionHelpAbout, &QAction::triggered, this, [=]() { AboutDialog *about_dialog = new AboutDialog(this); if (about_dialog->isMinimized() == true) { about_dialog->showNormal(); } else { about_dialog->show(); } about_dialog->raise(); about_dialog->activateWindow(); }); connect(main_ui_->actionHelpContents, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(HELP_CONTENT); }); connect(main_ui_->actionHelpMPWireshark, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(LOCALPAGE_MAN_WIRESHARK); }); connect(main_ui_->actionHelpMPWireshark_Filter, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(LOCALPAGE_MAN_WIRESHARK_FILTER); }); connect(main_ui_->actionHelpMPCapinfos, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(LOCALPAGE_MAN_CAPINFOS); }); connect(main_ui_->actionHelpMPDumpcap, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(LOCALPAGE_MAN_DUMPCAP); }); connect(main_ui_->actionHelpMPEditcap, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(LOCALPAGE_MAN_EDITCAP); }); connect(main_ui_->actionHelpMPMergecap, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(LOCALPAGE_MAN_MERGECAP); }); connect(main_ui_->actionHelpMPRawshark, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(LOCALPAGE_MAN_RAWSHARK); }); connect(main_ui_->actionHelpMPReordercap, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(LOCALPAGE_MAN_REORDERCAP); }); connect(main_ui_->actionHelpMPText2pcap, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(LOCALPAGE_MAN_TEXT2PCAP); }); connect(main_ui_->actionHelpMPTShark, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(LOCALPAGE_MAN_TSHARK); }); connect(main_ui_->actionHelpWebsite, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(ONLINEPAGE_HOME); }); connect(main_ui_->actionHelpFAQ, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(ONLINEPAGE_FAQ); }); connect(main_ui_->actionHelpAsk, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(ONLINEPAGE_ASK); }); connect(main_ui_->actionHelpDownloads, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(ONLINEPAGE_DOWNLOAD); }); connect(main_ui_->actionHelpWiki, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(ONLINEPAGE_WIKI); }); connect(main_ui_->actionHelpSampleCaptures, &QAction::triggered, this, [=]() { mainApp->helpTopicAction(ONLINEPAGE_SAMPLE_FILES); }); } #ifdef HAVE_SOFTWARE_UPDATE void LograyMainWindow::checkForUpdates() { software_update_check(); } #endif void LograyMainWindow::resetPreviousFocus() { previous_focus_ = NULL; } void LograyMainWindow::goToCancelClicked() { main_ui_->goToFrame->animatedHide(); if (previous_focus_) { disconnect(previous_focus_, SIGNAL(destroyed()), this, SLOT(resetPreviousFocus())); previous_focus_->setFocus(); resetPreviousFocus(); } } void LograyMainWindow::goToGoClicked() { gotoFrame(main_ui_->goToLineEdit->text().toInt()); goToCancelClicked(); } void LograyMainWindow::goToLineEditReturnPressed() { goToGoClicked(); } void LograyMainWindow::showResolvedAddressesDialog() { QString capFileName; wtap* wth = Q_NULLPTR; if (capture_file_.isValid()) { capFileName = capture_file_.capFile()->filename; wth = capture_file_.capFile()->provider.wth; } ResolvedAddressesDialog *resolved_addresses_dialog = new ResolvedAddressesDialog(this, capFileName, wth); resolved_addresses_dialog->show(); } void LograyMainWindow::showConversationsDialog() { ConversationDialog *conv_dialog = new ConversationDialog(*this, capture_file_); connect(conv_dialog, SIGNAL(filterAction(QString, FilterAction::Action, FilterAction::ActionType)), this, SIGNAL(filterAction(QString, FilterAction::Action, FilterAction::ActionType))); connect(conv_dialog, SIGNAL(openFollowStreamDialog(int, guint, guint)), this, SLOT(openFollowStreamDialog(int, guint, guint))); conv_dialog->show(); } void LograyMainWindow::showEndpointsDialog() { EndpointDialog *endp_dialog = new EndpointDialog(*this, capture_file_); connect(endp_dialog, SIGNAL(filterAction(QString, FilterAction::Action, FilterAction::ActionType)), this, SIGNAL(filterAction(QString, FilterAction::Action, FilterAction::ActionType))); connect(endp_dialog, SIGNAL(openFollowStreamDialog(int)), this, SLOT(openFollowStreamDialog(int))); endp_dialog->show(); } void LograyMainWindow::externalMenuItemTriggered() { QAction * triggerAction = NULL; QVariant v; ext_menubar_t * entry = NULL; if (QObject::sender()) { triggerAction = (QAction *)QObject::sender(); v = triggerAction->data(); if (v.canConvert<void *>()) { entry = (ext_menubar_t *)v.value<void *>(); if (entry->type == EXT_MENUBAR_ITEM) { entry->callback(EXT_MENUBAR_QT_GUI, (gpointer)((void *)main_ui_), entry->user_data); } else { QDesktopServices::openUrl(QUrl(QString((gchar *)entry->user_data))); } } } } void LograyMainWindow::extcap_options_finished(int result) { if (result == QDialog::Accepted) { QString before_what(tr(" before starting a new capture")); if (testCaptureFileClose(before_what)) { startCapture(); } } this->welcome_page_->getInterfaceFrame()->interfaceListChanged(); } void LograyMainWindow::showExtcapOptionsDialog(QString &device_name, bool startCaptureOnClose) { ExtcapOptionsDialog * extcap_options_dialog = ExtcapOptionsDialog::createForDevice(device_name, startCaptureOnClose, this); /* The dialog returns null, if the given device name is not a valid extcap device */ if (extcap_options_dialog) { extcap_options_dialog->setModal(true); extcap_options_dialog->setAttribute(Qt::WA_DeleteOnClose); if (startCaptureOnClose) { connect(extcap_options_dialog, SIGNAL(finished(int)), this, SLOT(extcap_options_finished(int))); } #ifdef HAVE_LIBPCAP if (capture_options_dialog_ && startCaptureOnClose) { /* Allow capture options dialog to close */ connect(extcap_options_dialog, SIGNAL(accepted()), capture_options_dialog_, SLOT(accept())); } #endif extcap_options_dialog->show(); } } void LograyMainWindow::on_actionContextWikiProtocolPage_triggered() { QAction *wa = qobject_cast<QAction*>(sender()); if (!wa) return; bool ok = false; int field_id = wa->data().toInt(&ok); if (!ok) return; const QString proto_abbrev = proto_registrar_get_abbrev(field_id); int ret = QMessageBox::question(this, mainApp->windowTitleString(tr("Wiki Page for %1").arg(proto_abbrev)), tr("<p>The Wireshark Wiki is maintained by the community.</p>" "<p>The page you are about to load might be wonderful, " "incomplete, wrong, or nonexistent.</p>" "<p>Proceed to the wiki?</p>"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); if (ret != QMessageBox::Yes) return; QUrl wiki_url = QString(WS_WIKI_URL("Protocols/%1")).arg(proto_abbrev); QDesktopServices::openUrl(wiki_url); } void LograyMainWindow::on_actionContextFilterFieldReference_triggered() { QAction *wa = qobject_cast<QAction*>(sender()); if (!wa) return; bool ok = false; int field_id = wa->data().toInt(&ok); if (!ok) return; const QString proto_abbrev = proto_registrar_get_abbrev(field_id); QUrl dfref_url = QString(WS_DOCS_URL "/dfref/%1/%2") .arg(proto_abbrev[0]) .arg(proto_abbrev); QDesktopServices::openUrl(dfref_url); } void LograyMainWindow::activatePluginIFToolbar(bool) { QAction *sendingAction = dynamic_cast<QAction *>(sender()); if (!sendingAction || !sendingAction->data().isValid()) return; ext_toolbar_t *toolbar = VariantPointer<ext_toolbar_t>::asPtr(sendingAction->data()); QList<QToolBar *> toolbars = findChildren<QToolBar *>(); foreach(QToolBar *bar, toolbars) { AdditionalToolBar *iftoolbar = dynamic_cast<AdditionalToolBar *>(bar); if (iftoolbar && iftoolbar->menuName().compare(toolbar->name) == 0) { if (iftoolbar->isVisible()) { iftoolbar->setVisible(false); sendingAction->setChecked(true); } else { iftoolbar->setVisible(true); sendingAction->setChecked(true); } } } } #ifdef _MSC_VER #pragma warning(pop) #endif
C/C++
wireshark/ui/macosx/cocoa_bridge.h
/** @file * * This code was taken directly from: * https://forum.qt.io/topic/82609/remove-native-mac-menu-items-such-as-show-tab-bar * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef COCOABRIDGE_H #define COCOABRIDGE_H class CocoaBridge { CocoaBridge() {} public: static void cleanOSGeneratedMenuItems(); }; #endif // COCOABRIDGE_H
wireshark/ui/macosx/cocoa_bridge.mm
/* cocoa_bridge.mm * * This code was taken directly from: * https://forum.qt.io/topic/82609/remove-native-mac-menu-items-such-as-show-tab-bar * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include <ui/macosx/cocoa_bridge.h> #include <ui/macosx/macos_compat.h> #import <Cocoa/Cocoa.h> void CocoaBridge::cleanOSGeneratedMenuItems() { #ifdef AVAILABLE_MAC_OS_X_VERSION_10_12_AND_LATER // Remove (don't allow) the "Show Tab Bar" menu item from the "View" menu, if // supported if ([NSWindow respondsToSelector:@selector(setAllowsAutomaticWindowTabbing:)]) [NSWindow setAllowsAutomaticWindowTabbing: NO]; #endif [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"NSFullScreenMenuItemEverywhere"]; // Remove (disable) the "Start Dictation..." and "Emoji & Symbols" menu items // from the "Edit" menu [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"NSDisabledDictationMenuItem"]; [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"NSDisabledCharacterPaletteMenuItem"]; }
C/C++
wireshark/ui/macosx/macos_compat.h
/** @file * * This code was taken directly from: * https://forum.qt.io/topic/82609/remove-native-mac-menu-items-such-as-show-tab-bar * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef MACOS_COMPAT_H #define MACOS_COMPAT_H #import <Cocoa/Cocoa.h> #if !defined(MAC_OS_X_VERSION_10_9) # define MAC_OS_X_VERSION_10_9 1090 #endif #if !defined(MAC_OS_X_VERSION_10_10) # define MAC_OS_X_VERSION_10_10 101000 #endif #if !defined(MAC_OS_X_VERSION_10_12) # define MAC_OS_X_VERSION_10_12 101200 #endif #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12) @interface NSWindow (macOS10_12_SDK) + (void)setAllowsAutomaticWindowTabbing:(BOOL)allow; @end #endif #endif // MACOS_COMPAT_H
C/C++
wireshark/ui/macosx/sparkle_bridge.h
/** @file * * C wrapper for the Sparkle API * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ // XXX We could alternatively do this via C++: // https://github.com/sparkle-project/Sparkle/issues/1137 #ifndef SPARKLE_BRIDGE_H #define SPARKLE_BRIDGE_H #include <stdbool.h> void sparkle_software_update_init(const char *url, bool enabled, int interval); void sparkle_software_update_check(void); #endif // SPARKLE_BRIDGE_H
wireshark/ui/macosx/sparkle_bridge.m
/* sparkle_bridge.m * * C wrapper for the Sparkle API * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include <ui/macosx/sparkle_bridge.h> #import <Cocoa/Cocoa.h> #import <Sparkle.h> // https://sparkle-project.org/documentation/customization/ // Sparkle stores its state in ~/Library/Preferences/org.wireshark.Wireshark.plist. // You can check its log output via `log stream | grep -i sparkle`. // The Sparkle 1 UI provided a sharedUpdater singleton, which is deprecated // in Sparkle 2: // https://sparkle-project.org/documentation/upgrading/ // Create our own singleton which uses the updated API. // https://sparkle-project.org/documentation/programmatic-setup/ @interface SparkleBridge : NSObject + (SPUStandardUpdaterController *)sharedStandardUpdaterController; @end @implementation SparkleBridge + (SPUStandardUpdaterController *)sharedStandardUpdaterController { static SPUStandardUpdaterController *sharedStandardUpdaterController_ = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedStandardUpdaterController_ = [[SPUStandardUpdaterController alloc] initWithUpdaterDelegate: nil userDriverDelegate: nil]; }); return sharedStandardUpdaterController_; } @end void sparkle_software_update_init(const char *url, bool enabled, int interval) { [[[SparkleBridge sharedStandardUpdaterController] updater] setAutomaticallyChecksForUpdates: enabled]; [[[SparkleBridge sharedStandardUpdaterController] updater] setUpdateCheckInterval: interval]; [[[SparkleBridge sharedStandardUpdaterController] updater] setFeedURL: [NSURL URLWithString: [[NSString alloc] initWithUTF8String: url] ]]; } void sparkle_software_update_check(void) { [[SparkleBridge sharedStandardUpdaterController] checkForUpdates: [[NSApplication sharedApplication] delegate]]; }
C++
wireshark/ui/qt/about_dialog.cpp
/* about_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "about_dialog.h" #include <ui_about_dialog.h> #include "main_application.h" #include <wsutil/filesystem.h> #include <QDesktopServices> #include <QUrl> #ifdef HAVE_LIBSMI #include <epan/oids.h> #endif #include <epan/maxmind_db.h> #include <epan/prefs.h> #ifdef HAVE_LUA #include <epan/wslua/init_wslua.h> #endif #include "ui/alert_box.h" #include "ui/last_open_dir.h" #include "ui/help_url.h" #include <wsutil/utf8_entities.h> #include "file.h" #include "wsutil/file_util.h" #include "wsutil/tempfile.h" #include "wsutil/plugins.h" #include "wsutil/version_info.h" #include "ui/capture_globals.h" #include "extcap.h" #include <ui/qt/utils/color_utils.h> #include <ui/qt/utils/qt_ui_utils.h> #include <ui/qt/utils/variant_pointer.h> #include <ui/qt/models/astringlist_list_model.h> #include <ui/qt/models/url_link_delegate.h> #include <QFontMetrics> #include <QKeySequence> #include <QTextStream> #include <QUrl> #include <QRegularExpression> #include <QAbstractItemModel> #include <QHash> #include <QDesktopServices> #include <QClipboard> #include <QMenu> #include <QFileInfo> #include <QMessageBox> #include <QPlainTextEdit> AuthorListModel::AuthorListModel(QObject * parent) : AStringListListModel(parent) { QFile f_authors; f_authors.setFileName(":/about/authors.csv"); f_authors.open(QFile::ReadOnly | QFile::Text); QTextStream ReadFile_authors(&f_authors); #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) ReadFile_authors.setEncoding(QStringConverter::Utf8); #else ReadFile_authors.setCodec("UTF-8"); #endif while (!ReadFile_authors.atEnd()) { QString line = ReadFile_authors.readLine(); #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) QStringList entry = line.split(",", Qt::SkipEmptyParts); #else QStringList entry = QStringList() << line.section(',', 0, 0) << line.section(',', 1, 1); #endif if (entry.size() == 2) { appendRow(entry); } } f_authors.close(); } AuthorListModel::~AuthorListModel() { } QStringList AuthorListModel::headerColumns() const { return QStringList() << tr("Name") << tr("Email"); } static void plugins_add_description(const char *name, const char *version, const char *types, const char *filename, void *user_data) { QList<QStringList> *plugin_data = (QList<QStringList> *)user_data; QStringList plugin_row = QStringList() << name << version << types << filename; *plugin_data << plugin_row; } PluginListModel::PluginListModel(QObject * parent) : AStringListListModel(parent) { QList<QStringList> plugin_data; #ifdef HAVE_PLUGINS plugins_get_descriptions(plugins_add_description, &plugin_data); #endif #ifdef HAVE_LUA wslua_plugins_get_descriptions(plugins_add_description, &plugin_data); #endif extcap_get_descriptions(plugins_add_description, &plugin_data); typeNames_ << QString(""); foreach(QStringList row, plugin_data) { QString type_name = row.at(2); typeNames_ << type_name; appendRow(row); } typeNames_.sort(); typeNames_.removeDuplicates(); } QStringList PluginListModel::typeNames() const { return typeNames_; } QStringList PluginListModel::headerColumns() const { return QStringList() << tr("Name") << tr("Version") << tr("Type") << tr("Path"); } ShortcutListModel::ShortcutListModel(QObject * parent): AStringListListModel(parent) { QMap<QString, QPair<QString, QString> > shortcuts; // name -> (shortcut, description) foreach (const QWidget *child, mainApp->mainWindow()->findChildren<QWidget *>()) { // Recent items look funny here. if (child->objectName().compare("menuOpenRecentCaptureFile") == 0) continue; foreach (const QAction *action, child->actions()) { if (!action->shortcut().isEmpty()) { QString name = action->text(); name.replace('&', ""); shortcuts[name] = QPair<QString, QString>(action->shortcut().toString(QKeySequence::NativeText), action->toolTip()); } } } QStringList names = shortcuts.keys(); names.sort(); foreach (const QString &name, names) { QStringList row; row << shortcuts[name].first << name << shortcuts[name].second; appendRow(row); } } QStringList ShortcutListModel::headerColumns() const { return QStringList() << tr("Shortcut") << tr("Name") << tr("Description"); } FolderListModel::FolderListModel(QObject * parent): AStringListListModel(parent) { /* "file open" */ appendRow(QStringList() << tr("\"File\" dialogs") << get_last_open_dir() << tr("capture files")); /* temp */ appendRow(QStringList() << tr("Temp") << (global_capture_opts.temp_dir && global_capture_opts.temp_dir[0] ? global_capture_opts.temp_dir : g_get_tmp_dir()) << tr("untitled capture files")); /* pers conf */ appendRow(QStringList() << tr("Personal configuration") << gchar_free_to_qstring(get_persconffile_path("", FALSE)) << tr("dfilters, preferences, ethers, …")); /* global conf */ QString dirPath = get_datafile_dir(); if (! dirPath.isEmpty()) { appendRow (QStringList() << tr("Global configuration") << dirPath << tr("dfilters, preferences, manuf, …")); } /* system */ appendRow(QStringList() << tr("System") << get_systemfile_dir() << tr("ethers, ipxnets")); /* program */ appendRow(QStringList() << tr("Program") << get_progfile_dir() << tr("program files")); #ifdef HAVE_PLUGINS /* pers plugins */ appendRow(QStringList() << tr("Personal Plugins") << get_plugins_pers_dir_with_version() << tr("binary plugins")); /* global plugins */ appendRow(QStringList() << tr("Global Plugins") << get_plugins_dir_with_version() << tr("binary plugins")); #endif #ifdef HAVE_LUA /* pers plugins */ appendRow(QStringList() << tr("Personal Lua Plugins") << get_plugins_pers_dir() << tr("Lua scripts")); /* global plugins */ appendRow(QStringList() << tr("Global Lua Plugins") << get_plugins_dir() << tr("Lua scripts")); #endif /* Extcap */ appendRow(QStringList() << tr("Personal Extcap path") << QString(get_extcap_pers_dir()) << tr("external capture (extcap) plugins")); appendRow(QStringList() << tr("Global Extcap path") << QString(get_extcap_dir()) << tr("external capture (extcap) plugins")); #ifdef HAVE_MAXMINDDB /* MaxMind DB */ QStringList maxMindDbPaths = QString(maxmind_db_get_paths()).split(G_SEARCHPATH_SEPARATOR_S); foreach(QString path, maxMindDbPaths) appendRow(QStringList() << tr("MaxMind DB path") << path.trimmed() << tr("MaxMind DB database search path")); #endif #ifdef HAVE_LIBSMI /* SMI MIBs/PIBs */ char *default_mib_path = oid_get_default_mib_path(); QStringList smiPaths = QString(default_mib_path).split(G_SEARCHPATH_SEPARATOR_S); g_free(default_mib_path); foreach(QString path, smiPaths) appendRow(QStringList() << tr("MIB/PIB path") << path.trimmed() << tr("SMI MIB/PIB search path")); #endif #ifdef Q_OS_MAC /* Mac Extras */ QString extras_path = mainApp->applicationDirPath() + "/../Resources/Extras"; appendRow(QStringList() << tr("macOS Extras") << QDir::cleanPath(extras_path) << tr("Extra macOS packages")); #endif } QStringList FolderListModel::headerColumns() const { return QStringList() << tr("Name") << tr("Location") << tr("Typical Files"); } // To do: // - Tweak and enhance ui... AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); setAttribute(Qt::WA_DeleteOnClose, true); QFile f_acknowledgements; QFile f_license; AuthorListModel * authorModel = new AuthorListModel(this); AStringListListSortFilterProxyModel * proxyAuthorModel = new AStringListListSortFilterProxyModel(this); proxyAuthorModel->setSourceModel(authorModel); proxyAuthorModel->setFilterCaseSensitivity(Qt::CaseInsensitive); proxyAuthorModel->setColumnToFilter(0); proxyAuthorModel->setColumnToFilter(1); ui->tblAuthors->setModel(proxyAuthorModel); ui->tblAuthors->setRootIsDecorated(false); ui->tblAuthors->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->tblAuthors, &QTreeView::customContextMenuRequested, this, &AboutDialog::handleCopyMenu); connect(ui->searchAuthors, &QLineEdit::textChanged, proxyAuthorModel, &AStringListListSortFilterProxyModel::setFilter); /* Wireshark tab */ updateWiresharkText(); ui->pte_wireshark->setFrameStyle(QFrame::NoFrame); ui->pte_wireshark->viewport()->setAutoFillBackground(false); /* Check if it is a dev release... (VERSION_MINOR is odd in dev release) */ #if VERSION_MINOR & 1 ui->label_logo->setPixmap(QPixmap(":/about/wssplash_dev.png")); #endif /* Folders */ FolderListModel * folderModel = new FolderListModel(this); AStringListListSortFilterProxyModel * folderProxyModel = new AStringListListSortFilterProxyModel(this); folderProxyModel->setSourceModel(folderModel); folderProxyModel->setColumnToFilter(1); folderProxyModel->setFilterType(AStringListListSortFilterProxyModel::FilterByStart); AStringListListUrlProxyModel * folderDisplayModel = new AStringListListUrlProxyModel(this); folderDisplayModel->setSourceModel(folderProxyModel); folderDisplayModel->setUrlColumn(1); ui->tblFolders->setModel(folderDisplayModel); ui->tblFolders->setRootIsDecorated(false); ui->tblFolders->setItemDelegateForColumn(1, new UrlLinkDelegate(this)); ui->tblFolders->setContextMenuPolicy(Qt::CustomContextMenu); ui->tblFolders->setTextElideMode(Qt::ElideMiddle); ui->tblFolders->setSortingEnabled(true); ui->tblFolders->sortByColumn(0, Qt::AscendingOrder); connect(ui->tblFolders, &QTreeView::customContextMenuRequested, this, &AboutDialog::handleCopyMenu); connect(ui->searchFolders, &QLineEdit::textChanged, folderProxyModel, &AStringListListSortFilterProxyModel::setFilter); connect(ui->tblFolders, &QTreeView::doubleClicked, this, &AboutDialog::urlDoubleClicked); /* Plugins */ ui->label_no_plugins->hide(); PluginListModel * pluginModel = new PluginListModel(this); AStringListListSortFilterProxyModel * pluginFilterModel = new AStringListListSortFilterProxyModel(this); pluginFilterModel->setSourceModel(pluginModel); pluginFilterModel->setColumnToFilter(0); AStringListListSortFilterProxyModel * pluginTypeModel = new AStringListListSortFilterProxyModel(this); pluginTypeModel->setSourceModel(pluginFilterModel); pluginTypeModel->setColumnToFilter(2); ui->tblPlugins->setModel(pluginTypeModel); ui->tblPlugins->setRootIsDecorated(false); UrlLinkDelegate *plugin_delegate = new UrlLinkDelegate(this); script_pattern = QString("\\.(lua|py)$"); plugin_delegate->setColCheck(3, script_pattern); ui->tblPlugins->setItemDelegateForColumn(3, plugin_delegate); ui->cmbType->addItems(pluginModel->typeNames()); ui->tblPlugins->setContextMenuPolicy(Qt::CustomContextMenu); ui->tblPlugins->setTextElideMode(Qt::ElideMiddle); ui->tblPlugins->setSortingEnabled(true); ui->tblPlugins->sortByColumn(0, Qt::AscendingOrder); connect(ui->tblPlugins, &QTreeView::customContextMenuRequested, this, &AboutDialog::handleCopyMenu); connect(ui->searchPlugins, &QLineEdit::textChanged, pluginFilterModel, &AStringListListSortFilterProxyModel::setFilter); connect(ui->cmbType, &QComboBox::currentTextChanged, pluginTypeModel, &AStringListListSortFilterProxyModel::setFilter); if (ui->tblPlugins->model()->rowCount() < 1) { foreach (QWidget *w, ui->tab_plugins->findChildren<QWidget *>()) { w->hide(); } ui->label_no_plugins->setAlignment(Qt::AlignVCenter | Qt::AlignHCenter); ui->label_no_plugins->setEnabled(false); ui->label_no_plugins->show(); } /* Shortcuts */ ShortcutListModel * shortcutModel = new ShortcutListModel(this); AStringListListSortFilterProxyModel * shortcutProxyModel = new AStringListListSortFilterProxyModel(this); shortcutProxyModel->setSourceModel(shortcutModel); shortcutProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); shortcutProxyModel->setColumnToFilter(1); shortcutProxyModel->setColumnToFilter(2); ui->tblShortcuts->setModel(shortcutProxyModel); ui->tblShortcuts->setRootIsDecorated(false); ui->tblShortcuts->setContextMenuPolicy(Qt::CustomContextMenu); ui->tblShortcuts->setSortingEnabled(true); ui->tblShortcuts->sortByColumn(1, Qt::AscendingOrder); connect(ui->tblShortcuts, &QTreeView::customContextMenuRequested, this, &AboutDialog::handleCopyMenu); connect(ui->searchShortcuts, &QLineEdit::textChanged, shortcutProxyModel, &AStringListListSortFilterProxyModel::setFilter); /* Acknowledgements */ f_acknowledgements.setFileName(":/about/Acknowledgements.md"); f_acknowledgements.open(QFile::ReadOnly | QFile::Text); QTextStream ReadFile_acks(&f_acknowledgements); /* QTextBrowser markdown support added in 5.14. */ #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) QTextBrowser *textBrowserAcks = new QTextBrowser(); textBrowserAcks->setMarkdown(ReadFile_acks.readAll()); textBrowserAcks->setReadOnly(true); textBrowserAcks->setOpenExternalLinks(true); textBrowserAcks->moveCursor(QTextCursor::Start); ui->ackVerticalLayout->addWidget(textBrowserAcks); #else QPlainTextEdit *pte = new QPlainTextEdit(); pte->setPlainText(ReadFile_acks.readAll()); pte->setReadOnly(true); pte->moveCursor(QTextCursor::Start); ui->ackVerticalLayout->addWidget(pte); #endif /* License */ f_license.setFileName(":/about/gpl-2.0-standalone.html"); f_license.open(QFile::ReadOnly | QFile::Text); QTextStream ReadFile_license(&f_license); ui->textBrowserLicense->setHtml(ReadFile_license.readAll()); ui->textBrowserLicense->moveCursor(QTextCursor::Start); } AboutDialog::~AboutDialog() { delete ui; } bool AboutDialog::event(QEvent *event) { switch (event->type()) { case QEvent::ApplicationPaletteChange: updateWiresharkText(); break; default: break; } return QDialog::event(event); } void AboutDialog::showEvent(QShowEvent * event) { int one_em = fontMetrics().height(); // Authors: Names slightly narrower than emails. QAbstractItemModel *model = ui->tblAuthors->model(); int column_count = model->columnCount(); if (column_count) { ui->tblAuthors->setColumnWidth(0, (ui->tblAuthors->parentWidget()->width() / column_count) - one_em); } // Folders: First and last to contents. ui->tblFolders->resizeColumnToContents(0); ui->tblFolders->resizeColumnToContents(2); ui->tblFolders->setColumnWidth(1, ui->tblFolders->parentWidget()->width() - (ui->tblFolders->columnWidth(0) + ui->tblFolders->columnWidth(2))); // Plugins: All but the last to contents. model = ui->tblPlugins->model(); for (int col = 0; model && col < model->columnCount() - 1; col++) { ui->tblPlugins->resizeColumnToContents(col); } // Contents + 2 em-widths ui->tblShortcuts->resizeColumnToContents(0); ui->tblShortcuts->setColumnWidth(0, ui->tblShortcuts->columnWidth(0) + (one_em * 2)); ui->tblShortcuts->setColumnWidth(1, one_em * 12); ui->tblShortcuts->resizeColumnToContents(2); QDialog::showEvent(event); } void AboutDialog::updateWiresharkText() { QString vcs_version_info_str = get_ws_vcs_version_info(); QString copyright_info_str = get_copyright_info(); QString license_info_str = get_license_info(); QString comp_info_str = gstring_free_to_qbytearray(get_compiled_version_info(gather_wireshark_qt_compiled_info)); QString runtime_info_str = gstring_free_to_qbytearray(get_runtime_version_info(gather_wireshark_runtime_info)); QString message = ColorUtils::themeLinkStyle(); /* Construct the message string */ message += "<p>Version " + html_escape(vcs_version_info_str) + ".</p>\n"; message += "<p>" + html_escape(copyright_info_str) + "</p>\n"; message += "<p>" + html_escape(license_info_str) + "</p>\n"; message += "<p>" + html_escape(comp_info_str) + "</p>\n"; message += "<p>" + html_escape(runtime_info_str) + "</p>\n"; message += "<p>Check the man page and <a href=https://www.wireshark.org>www.wireshark.org</a> " "for more information.</p>\n"; ui->pte_wireshark->setHtml(message); /* Save the info for the clipboard copy */ clipboardInfo = ""; clipboardInfo += "Version " + vcs_version_info_str + ".\n\n"; /* XXX: GCC 12.1 has a bogus stringop-overread warning using the Qt * conversions from QByteArray to QString at -O2 and higher due to * computing a branch that will never be taken. */ #if WS_IS_AT_LEAST_GNUC_VERSION(12,1) DIAG_OFF(stringop-overread) #endif clipboardInfo += gstring_free_to_qbytearray(get_compiled_version_info(gather_wireshark_qt_compiled_info)) + "\n"; clipboardInfo += gstring_free_to_qbytearray(get_runtime_version_info(gather_wireshark_runtime_info)) + "\n"; #if WS_IS_AT_LEAST_GNUC_VERSION(12,1) DIAG_ON(stringop-overread) #endif } void AboutDialog::on_copyToClipboard_clicked() { QClipboard * clipBoard = QApplication::clipboard(); clipBoard->setText(clipboardInfo); } void AboutDialog::urlDoubleClicked(const QModelIndex &idx) { if (idx.column() != 1) { return; } QTreeView * table = qobject_cast<QTreeView *>(sender()); if (! table) return; QString urlText = table->model()->data(idx).toString(); if (urlText.isEmpty()) return; if (! QDir(urlText).exists()) { if (QMessageBox::question(this, tr("The directory does not exist"), QString(tr("Should the directory %1 be created?").arg(urlText))) == QMessageBox::Yes) { if (! QDir().mkpath(urlText)) { QMessageBox::warning(this, tr("The directory could not be created"), QString(tr("The directory %1 could not be created.").arg(urlText))); } } } if (QDir(urlText).exists()) { QUrl url = QUrl::fromLocalFile(urlText); if (url.isValid()) QDesktopServices::openUrl(url); } } void AboutDialog::handleCopyMenu(QPoint pos) { QTreeView * tree = qobject_cast<QTreeView *>(sender()); if (! tree) return; QModelIndex index = tree->indexAt(pos); if (! index.isValid()) return; QMenu * menu = new QMenu(this); menu->setAttribute(Qt::WA_DeleteOnClose); if (ui->tabWidget->currentWidget() == ui->tab_plugins) { #ifdef Q_OS_MAC QString show_in_str = tr("Show in Finder"); #else QString show_in_str = tr("Show in Folder"); #endif QAction * showInFolderAction = menu->addAction(show_in_str); showInFolderAction->setData(VariantPointer<QTreeView>::asQVariant(tree)); connect(showInFolderAction, &QAction::triggered, this, &AboutDialog::showInFolderActionTriggered); } QAction * copyColumnAction = menu->addAction(tr("Copy")); copyColumnAction->setData(VariantPointer<QTreeView>::asQVariant(tree)); connect(copyColumnAction, &QAction::triggered, this, &AboutDialog::copyActionTriggered); QModelIndexList selectedRows = tree->selectionModel()->selectedRows(); QAction * copyRowAction = menu->addAction(tr("Copy Row(s)", "", static_cast<int>(selectedRows.count()))); copyRowAction->setData(VariantPointer<QTreeView>::asQVariant(tree)); connect(copyRowAction, &QAction::triggered, this, &AboutDialog::copyRowActionTriggered); menu->popup(tree->viewport()->mapToGlobal(pos)); } void AboutDialog::showInFolderActionTriggered() { QAction * sendingAction = qobject_cast<QAction *>(sender()); if (!sendingAction) return; QTreeView * tree = VariantPointer<QTreeView>::asPtr(sendingAction->data()); QModelIndexList selectedRows = tree->selectionModel()->selectedRows(); foreach (QModelIndex index, selectedRows) { QString cf_path = tree->model()->index(index.row(), 3).data().toString(); desktop_show_in_folder(cf_path); } } void AboutDialog::copyRowActionTriggered() { copyActionTriggered(true); } void AboutDialog::copyActionTriggered(bool copyRow) { QAction * sendingAction = qobject_cast<QAction *>(sender()); if (! sendingAction) return; QTreeView * tree = VariantPointer<QTreeView>::asPtr(sendingAction->data()); QModelIndexList selIndeces = tree->selectionModel()->selectedIndexes(); int copyColumn = -1; if (! copyRow) { QMenu * menu = qobject_cast<QMenu *>(sendingAction->parent()); if (menu) { QPoint menuPosOnTable = tree->mapFromGlobal(menu->pos()); QModelIndex clickedIndex = tree->indexAt(menuPosOnTable); if (clickedIndex.isValid()) copyColumn = clickedIndex.column(); } } QString clipdata; if (selIndeces.count() > 0) { int columnCount = tree->model()->columnCount(); QList<int> visitedRows; foreach(QModelIndex index, selIndeces) { if (visitedRows.contains(index.row())) continue; QStringList row; if (copyRow) { for (int cnt = 0; cnt < columnCount; cnt++) { QModelIndex dataIdx = tree->model()->index(index.row(), cnt); row << tree->model()->data(dataIdx).toString(); } } else { if (copyColumn < 0) copyColumn = index.column(); QModelIndex dataIdx = tree->model()->index(index.row(), copyColumn); row << tree->model()->data(dataIdx).toString(); } clipdata.append(row.join("\t\t").append("\n")); visitedRows << index.row(); } } QClipboard * clipBoard = QApplication::clipboard(); clipBoard->setText(clipdata); } void AboutDialog::on_tblPlugins_doubleClicked(const QModelIndex &index) { const int path_col = 3; if (index.column() != path_col) { return; } const int row = index.row(); const QAbstractItemModel *model = index.model(); if (model->index(row, path_col).data().toString().contains(QRegularExpression(script_pattern))) { QDesktopServices::openUrl(QUrl::fromLocalFile(model->index(row, path_col).data().toString())); } }
C/C++
wireshark/ui/qt/about_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef ABOUT_DIALOG_H #define ABOUT_DIALOG_H #include "config.h" #include <ui/qt/models/astringlist_list_model.h> #include <QDialog> #include <QAbstractItemModel> #include <QModelIndex> #include <QHash> #include <QString> #include <QSortFilterProxyModel> namespace Ui { class AboutDialog; } class AuthorListModel : public AStringListListModel { Q_OBJECT public: explicit AuthorListModel(QObject * parent = Q_NULLPTR); virtual ~AuthorListModel(); protected: virtual QStringList headerColumns() const; }; class PluginListModel : public AStringListListModel { Q_OBJECT public: explicit PluginListModel(QObject * parent = Q_NULLPTR); QStringList typeNames() const; protected: virtual QStringList headerColumns() const; private: QStringList typeNames_; }; class ShortcutListModel : public AStringListListModel { Q_OBJECT public: explicit ShortcutListModel(QObject * parent = Q_NULLPTR); protected: virtual QStringList headerColumns() const; }; class FolderListModel : public AStringListListModel { Q_OBJECT public: explicit FolderListModel(QObject * parent = Q_NULLPTR); protected: virtual QStringList headerColumns() const; }; class AboutDialog : public QDialog { Q_OBJECT public: explicit AboutDialog(QWidget *parent = 0); ~AboutDialog(); protected: virtual bool event(QEvent *event); virtual void showEvent(QShowEvent *); private: void updateWiresharkText(); Ui::AboutDialog *ui; QString script_pattern; QString clipboardInfo; private slots: void urlDoubleClicked(const QModelIndex &); void handleCopyMenu(QPoint); void showInFolderActionTriggered(); void copyActionTriggered(bool row = false); void copyRowActionTriggered(); void on_tblPlugins_doubleClicked(const QModelIndex &index); void on_copyToClipboard_clicked(); }; #endif // ABOUT_DIALOG_H
User Interface
wireshark/ui/qt/about_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>AboutDialog</class> <widget class="QDialog" name="AboutDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>740</width> <height>650</height> </rect> </property> <property name="windowTitle"> <string>About Wireshark</string> </property> <layout class="QVBoxLayout" name="verticalLayout_6"> <item> <widget class="QTabWidget" name="tabWidget"> <property name="minimumSize"> <size> <width>371</width> <height>231</height> </size> </property> <property name="currentIndex"> <number>0</number> </property> <property name="documentMode"> <bool>false</bool> </property> <widget class="QWidget" name="tab_wireshark"> <property name="enabled"> <bool>true</bool> </property> <attribute name="title"> <string>Wireshark</string> </attribute> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QLabel" name="label_logo"> <property name="text"> <string/> </property> <property name="pixmap"> <pixmap resource="../../resources/about.qrc">:/about/wssplash.png</pixmap> </property> <property name="scaledContents"> <bool>false</bool> </property> <property name="alignment"> <set>Qt::AlignHCenter|Qt::AlignTop</set> </property> </widget> </item> <item> <widget class="QLabel" name="label_title"> <property name="maximumSize"> <size> <width>16777215</width> <height>20</height> </size> </property> <property name="text"> <string>&lt;span size=\&quot;x-large\&quot; weight=\&quot;bold\&quot;&gt;Network Protocol Analyzer&lt;/span&gt;</string> </property> <property name="alignment"> <set>Qt::AlignCenter</set> </property> </widget> </item> <item> <widget class="QTextBrowser" name="pte_wireshark"> <property name="readOnly"> <bool>true</bool> </property> <property name="textInteractionFlags"> <set>Qt::TextBrowserInteraction</set> </property> <property name="openExternalLinks"> <bool>true</bool> </property> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <widget class="QPushButton" name="copyToClipboard"> <property name="sizePolicy"> <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="toolTip"> <string>Copy the version information to the clipboard</string> </property> <property name="text"> <string>Copy to Clipboard</string> </property> </widget> </item> <item> <spacer name="horizontalSpacer"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> </layout> </item> </layout> </widget> <widget class="QWidget" name="tab_authors"> <attribute name="title"> <string>Authors</string> </attribute> <layout class="QVBoxLayout" name="verticalLayout_2"> <item> <widget class="QLineEdit" name="searchAuthors"> <property name="placeholderText"> <string>Search Authors</string> </property> </widget> </item> <item> <widget class="QTreeView" name="tblAuthors"> <property name="editTriggers"> <set>QAbstractItemView::NoEditTriggers</set> </property> <property name="selectionMode"> <enum>QAbstractItemView::ContiguousSelection</enum> </property> <property name="selectionBehavior"> <enum>QAbstractItemView::SelectRows</enum> </property> <attribute name="headerMinimumSectionSize"> <number>100</number> </attribute> <attribute name="headerStretchLastSection"> <bool>true</bool> </attribute> </widget> </item> </layout> </widget> <widget class="QWidget" name="tab_folders"> <attribute name="title"> <string>Folders</string> </attribute> <layout class="QVBoxLayout" name="verticalLayout_3"> <item> <widget class="QLineEdit" name="searchFolders"> <property name="placeholderText"> <string>Filter by path</string> </property> </widget> </item> <item> <widget class="QTreeView" name="tblFolders"> <property name="editTriggers"> <set>QAbstractItemView::NoEditTriggers</set> </property> <property name="selectionMode"> <enum>QAbstractItemView::ContiguousSelection</enum> </property> <property name="selectionBehavior"> <enum>QAbstractItemView::SelectRows</enum> </property> </widget> </item> </layout> </widget> <widget class="QWidget" name="tab_plugins"> <attribute name="title"> <string>Plugins</string> </attribute> <layout class="QVBoxLayout" name="verticalLayout_4"> <item> <widget class="QLabel" name="label_no_plugins"> <property name="text"> <string>No plugins found.</string> </property> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout_3"> <item> <widget class="QLineEdit" name="searchPlugins"> <property name="placeholderText"> <string>Search Plugins</string> </property> </widget> </item> <item> <widget class="QLabel" name="label"> <property name="text"> <string>Filter by type:</string> </property> </widget> </item> <item> <widget class="QComboBox" name="cmbType"/> </item> </layout> </item> <item> <widget class="QTreeView" name="tblPlugins"> <property name="editTriggers"> <set>QAbstractItemView::NoEditTriggers</set> </property> <property name="selectionMode"> <enum>QAbstractItemView::ContiguousSelection</enum> </property> <property name="selectionBehavior"> <enum>QAbstractItemView::SelectRows</enum> </property> </widget> </item> </layout> </widget> <widget class="QWidget" name="tab_shortcuts"> <attribute name="title"> <string>Keyboard Shortcuts</string> </attribute> <layout class="QVBoxLayout" name="verticalLayout_shortcuts"> <item> <widget class="QLineEdit" name="searchShortcuts"> <property name="placeholderText"> <string>Search Shortcuts</string> </property> </widget> </item> <item> <widget class="QTreeView" name="tblShortcuts"> <property name="editTriggers"> <set>QAbstractItemView::NoEditTriggers</set> </property> <property name="selectionMode"> <enum>QAbstractItemView::ContiguousSelection</enum> </property> <property name="selectionBehavior"> <enum>QAbstractItemView::SelectRows</enum> </property> <property name="textElideMode"> <enum>Qt::ElideRight</enum> </property> <property name="wordWrap"> <bool>true</bool> </property> </widget> </item> </layout> </widget> <widget class="QWidget" name="tab_acknowledgements"> <attribute name="title"> <string>Acknowledgments</string> </attribute> <layout class="QVBoxLayout" name="ackVerticalLayout"/> </widget> <widget class="QWidget" name="tab_license"> <attribute name="title"> <string>License</string> </attribute> <layout class="QVBoxLayout" name="verticalLayout_5"> <item> <widget class="QTextBrowser" name="textBrowserLicense"> <property name="readOnly"> <bool>true</bool> </property> <property name="openExternalLinks"> <bool>true</bool> </property> </widget> </item> </layout> </widget> </widget> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Ok</set> </property> </widget> </item> </layout> </widget> <resources> <include location="../../resources/about.qrc"/> </resources> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>AboutDialog</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>254</x> <y>595</y> </hint> <hint type="destinationlabel"> <x>157</x> <y>274</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>AboutDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>322</x> <y>595</y> </hint> <hint type="destinationlabel"> <x>286</x> <y>274</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/accordion_frame.cpp
/* accordion_frame.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include <glib.h> #include "accordion_frame.h" #include "ui/util.h" #include <QLayout> #include <QPropertyAnimation> const int duration_ = 150; AccordionFrame::AccordionFrame(QWidget *parent) : QFrame(parent), frame_height_(0) { QString subframe_style( // ".QFrame {" // " background: palette(window);" // " padding-top: 0.1em;" // " padding-bottom: 0.1em;" // " border-bottom: 1px solid palette(shadow);" // "}" "QLineEdit#goToLineEdit {" " max-width: 5em;" "}" ); setStyleSheet(subframe_style); animation_ = new QPropertyAnimation(this, "maximumHeight", this); animation_->setDuration(duration_); animation_->setEasingCurve(QEasingCurve::InOutQuad); connect(animation_, &QPropertyAnimation::finished, this, &AccordionFrame::animationFinished); } void AccordionFrame::animatedShow() { if (isVisible()) { show(); return; } if (!display_is_remote()) { QWidget *parent = parentWidget(); if (parent && parent->layout()) { // Force our parent layout to update its geometry. There are a number // of ways of doing this. Calling invalidate + activate seems to // be the best. show(); parent->layout()->invalidate(); // Calls parent->layout()->update() parent->layout()->activate(); // Calculates sizes then calls parent->updateGeometry() frame_height_ = height(); hide(); } if (frame_height_ > 0) { animation_->setStartValue(0); animation_->setEndValue(frame_height_); animation_->start(); } } show(); } void AccordionFrame::animatedHide() { if (!isVisible()) { hide(); return; } if (!display_is_remote()) { animation_->setStartValue(frame_height_); animation_->setEndValue(0); animation_->start(); } else { hide(); } } void AccordionFrame::animationFinished() { if (animation_->currentValue().toInt() < 1) { hide(); setMaximumHeight(frame_height_); } }
C/C++
wireshark/ui/qt/accordion_frame.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef ACCORDION_FRAME_H #define ACCORDION_FRAME_H #include <QFrame> class QPropertyAnimation; class AccordionFrame : public QFrame { Q_OBJECT public: explicit AccordionFrame(QWidget *parent = 0); void animatedShow(); void animatedHide(); signals: void visibilityChanged(bool visible); protected: virtual void hideEvent(QHideEvent *) { emit visibilityChanged(false); } virtual void showEvent(QShowEvent *) { emit visibilityChanged(true); } private: int frame_height_; QPropertyAnimation *animation_; private slots: void animationFinished(); }; #endif // ACCORDION_FRAME_H
C++
wireshark/ui/qt/address_editor_frame.cpp
/* address_editor_frame.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include <glib.h> #include "file.h" #include "frame_tvbuff.h" #include "epan/addr_resolv.h" #include "epan/epan_dissect.h" #include "epan/frame_data.h" #include "main_application.h" #include "address_editor_frame.h" #include <ui_address_editor_frame.h> #include <QPushButton> #include <QKeyEvent> #include <ui/qt/utils/qt_ui_utils.h> // To do: // - Fill in currently resolved address. AddressEditorFrame::AddressEditorFrame(QWidget *parent) : AccordionFrame(parent), ui(new Ui::AddressEditorFrame), cap_file_(NULL) { ui->setupUi(this); #ifdef Q_OS_MAC foreach (QWidget *w, findChildren<QWidget *>()) { w->setAttribute(Qt::WA_MacSmallSize, true); } #endif } AddressEditorFrame::~AddressEditorFrame() { delete ui; } void AddressEditorFrame::editAddresses(CaptureFile &cf, int column) { cap_file_ = cf.capFile(); if (!cap_file_->current_frame) { on_buttonBox_rejected(); return; } if (!cf_read_current_record(cap_file_)) { on_buttonBox_rejected(); return; // error reading the frame } epan_dissect_t edt; QStringList addresses; ui->addressComboBox->clear(); epan_dissect_init(&edt, cap_file_->epan, FALSE, FALSE); col_custom_prime_edt(&edt, &cap_file_->cinfo); epan_dissect_run(&edt, cap_file_->cd_t, &cap_file_->rec, frame_tvbuff_new_buffer(&cap_file_->provider, cap_file_->current_frame, &cap_file_->buf), cap_file_->current_frame, &cap_file_->cinfo); epan_dissect_fill_in_columns(&edt, TRUE, TRUE); /* First check selected column */ if (isAddressColumn(&cap_file_->cinfo, column)) { addresses << cap_file_->cinfo.col_expr.col_expr_val[column]; } for (int col = 0; col < cap_file_->cinfo.num_cols; col++) { /* Then check all columns except the selected */ if ((col != column) && (isAddressColumn(&cap_file_->cinfo, col))) { addresses << cap_file_->cinfo.col_expr.col_expr_val[col]; } } epan_dissect_cleanup(&edt); displayPreviousUserDefinedHostname(); ui->addressComboBox->addItems(addresses); ui->nameLineEdit->setFocus(); updateWidgets(); } void AddressEditorFrame::showEvent(QShowEvent *event) { ui->nameLineEdit->setFocus(); ui->nameLineEdit->selectAll(); AccordionFrame::showEvent(event); } void AddressEditorFrame::keyPressEvent(QKeyEvent *event) { if (event->modifiers() == Qt::NoModifier) { if (event->key() == Qt::Key_Escape) { on_buttonBox_rejected(); } else if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { if (ui->buttonBox->button(QDialogButtonBox::Ok)->isEnabled()) { on_buttonBox_accepted(); } } } AccordionFrame::keyPressEvent(event); } void AddressEditorFrame::displayPreviousUserDefinedHostname() { QString addr = ui->addressComboBox->currentText(); resolved_name_t* previous_entry = get_edited_resolved_name(addr.toUtf8().constData()); if (previous_entry) { ui->nameLineEdit->setText(previous_entry->name); } else { ui->nameLineEdit->setText(""); } } void AddressEditorFrame::updateWidgets() { bool ok_enable = false; if (ui->addressComboBox->count() > 0) { ok_enable = true; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ok_enable); } void AddressEditorFrame::on_nameResolutionPreferencesToolButton_clicked() { on_buttonBox_rejected(); emit showNameResolutionPreferences("nameres"); } void AddressEditorFrame::on_addressComboBox_currentIndexChanged(int) { displayPreviousUserDefinedHostname(); updateWidgets(); } void AddressEditorFrame::on_nameLineEdit_textEdited(const QString &) { updateWidgets(); } void AddressEditorFrame::on_buttonBox_accepted() { if (ui->addressComboBox->count() < 1) { return; } QString addr = ui->addressComboBox->currentText(); QString name = ui->nameLineEdit->text(); if (!cf_add_ip_name_from_string(cap_file_, addr.toUtf8().constData(), name.toUtf8().constData())) { QString error_msg = tr("Can't assign %1 to %2.").arg(name).arg(addr); mainApp->pushStatus(MainApplication::TemporaryStatus, error_msg); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); return; } on_buttonBox_rejected(); emit redissectPackets(); } void AddressEditorFrame::on_buttonBox_rejected() { ui->addressComboBox->clear(); ui->nameLineEdit->clear(); animatedHide(); } bool AddressEditorFrame::isAddressColumn(epan_column_info *cinfo, int column) { if (!cinfo || column < 0 || column >= cinfo->num_cols) return false; if (((cinfo->columns[column].col_fmt == COL_DEF_SRC) || (cinfo->columns[column].col_fmt == COL_RES_SRC) || (cinfo->columns[column].col_fmt == COL_DEF_DST) || (cinfo->columns[column].col_fmt == COL_RES_DST)) && strlen(cinfo->col_expr.col_expr_val[column])) { return true; } return false; }
C/C++
wireshark/ui/qt/address_editor_frame.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef ADDRESS_EDITOR_FRAME_H #define ADDRESS_EDITOR_FRAME_H #include "accordion_frame.h" #include "capture_file.h" namespace Ui { class AddressEditorFrame; } struct epan_column_info; class AddressEditorFrame : public AccordionFrame { Q_OBJECT public: explicit AddressEditorFrame(QWidget *parent = 0); ~AddressEditorFrame(); public slots: void editAddresses(CaptureFile &cf, int column = -1); signals: void showNameResolutionPreferences(const QString module_name); void redissectPackets(); protected: virtual void showEvent(QShowEvent *event); virtual void keyPressEvent(QKeyEvent *event); private slots: void displayPreviousUserDefinedHostname(); void updateWidgets(); void on_nameResolutionPreferencesToolButton_clicked(); void on_addressComboBox_currentIndexChanged(int idx); void on_nameLineEdit_textEdited(const QString &); void on_buttonBox_accepted(); void on_buttonBox_rejected(); private: Ui::AddressEditorFrame *ui; capture_file *cap_file_; bool isAddressColumn(struct epan_column_info *cinfo, int column); }; #endif // ADDRESS_EDITOR_FRAME_H
User Interface
wireshark/ui/qt/address_editor_frame.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>AddressEditorFrame</class> <widget class="AccordionFrame" name="AddressEditorFrame"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>833</width> <height>34</height> </rect> </property> <property name="windowTitle"> <string>Frame</string> </property> <property name="frameShape"> <enum>QFrame::NoFrame</enum> </property> <property name="frameShadow"> <enum>QFrame::Plain</enum> </property> <layout class="QHBoxLayout" name="horizontalLayout" stretch="0,3,0,0,0,0,1,0,0"> <property name="topMargin"> <number>0</number> </property> <property name="bottomMargin"> <number>0</number> </property> <item> <widget class="QToolButton" name="nameResolutionPreferencesToolButton"> <property name="text"> <string>Name Resolution Preferences…</string> </property> </widget> </item> <item> <spacer name="horizontalSpacer_2"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>81</width> <height>5</height> </size> </property> </spacer> </item> <item> <widget class="QLabel" name="addressLabel"> <property name="text"> <string>Address:</string> </property> </widget> </item> <item> <widget class="QComboBox" name="addressComboBox"/> </item> <item> <spacer name="horizontalSpacer_3"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>10</width> <height>5</height> </size> </property> </spacer> </item> <item> <widget class="QLabel" name="label"> <property name="text"> <string>Name:</string> </property> </widget> </item> <item> <widget class="SyntaxLineEdit" name="nameLineEdit"> <property name="sizePolicy"> <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> <horstretch>1</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>80</width> <height>0</height> </size> </property> </widget> </item> <item> <spacer name="horizontalSpacer"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>20</width> <height>13</height> </size> </property> </spacer> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="maximumSize"> <size> <width>16777215</width> <height>27</height> </size> </property> <property name="standardButtons"> <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set> </property> </widget> </item> </layout> </widget> <customwidgets> <customwidget> <class>AccordionFrame</class> <extends>QFrame</extends> <header>accordion_frame.h</header> <container>1</container> </customwidget> <customwidget> <class>SyntaxLineEdit</class> <extends>QLineEdit</extends> <header>widgets/syntax_line_edit.h</header> </customwidget> </customwidgets> <resources/> <connections/> </ui>
C++
wireshark/ui/qt/bluetooth_att_server_attributes_dialog.cpp
/* bluetooth_att_server_attributes_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "bluetooth_att_server_attributes_dialog.h" #include <ui_bluetooth_att_server_attributes_dialog.h> #include <ui/qt/utils/color_utils.h> #include "epan/epan.h" #include "epan/to_str.h" #include "epan/epan_dissect.h" #include "epan/prefs.h" #include "epan/dissectors/packet-bluetooth.h" #include "epan/dissectors/packet-btatt.h" #include "ui/simple_dialog.h" #include "ui/qt/widgets/wireshark_file_dialog.h" #include <QClipboard> #include <QContextMenuEvent> #include <QPushButton> #include <QTreeWidget> static const int column_number_handle = 0; static const int column_number_uuid = 1; static const int column_number_uuid_name = 2; static tap_packet_status btatt_handle_tap_packet(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *edt, const void* data, tap_flags_t flags) { tapinfo_t *tapinfo = (tapinfo_t *) tapinfo_ptr; if (tapinfo->tap_packet) tapinfo->tap_packet(tapinfo, pinfo, edt, data, flags); return TAP_PACKET_REDRAW; } static void btatt_handle_tap_reset(void *tapinfo_ptr) { tapinfo_t *tapinfo = (tapinfo_t *) tapinfo_ptr; if (tapinfo->tap_reset) tapinfo->tap_reset(tapinfo); } BluetoothAttServerAttributesDialog::BluetoothAttServerAttributesDialog(QWidget &parent, CaptureFile &cf) : WiresharkDialog(parent, cf), ui(new Ui::BluetoothAttServerAttributesDialog) { ui->setupUi(this); loadGeometry(parent.width() * 4 / 5, parent.height() * 2 / 3); connect(ui->tableTreeWidget, &QTreeWidget::customContextMenuRequested, this, &BluetoothAttServerAttributesDialog::tableContextMenu); connect(ui->interfaceComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &BluetoothAttServerAttributesDialog::interfaceCurrentIndexChanged); connect(ui->deviceComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &BluetoothAttServerAttributesDialog::deviceCurrentIndexChanged); connect(ui->removeDuplicatesCheckBox, &QCheckBox::stateChanged, this, &BluetoothAttServerAttributesDialog::removeDuplicatesStateChanged); ui->tableTreeWidget->sortByColumn(column_number_handle, Qt::AscendingOrder); ui->tableTreeWidget->setStyleSheet("QTreeView::item:hover{background-color:lightyellow; color:black;}"); context_menu_.addActions(QList<QAction *>() << ui->actionMark_Unmark_Cell); context_menu_.addActions(QList<QAction *>() << ui->actionMark_Unmark_Row); context_menu_.addActions(QList<QAction *>() << ui->actionCopy_Cell); context_menu_.addActions(QList<QAction *>() << ui->actionCopy_Rows); context_menu_.addActions(QList<QAction *>() << ui->actionCopy_All); context_menu_.addActions(QList<QAction *>() << ui->actionSave_as_image); tapinfo_.tap_packet = tapPacket; tapinfo_.tap_reset = tapReset; tapinfo_.ui = this; registerTapListener("btatt.handles", &tapinfo_, NULL, 0, btatt_handle_tap_reset, btatt_handle_tap_packet, NULL ); cap_file_.retapPackets(); } BluetoothAttServerAttributesDialog::~BluetoothAttServerAttributesDialog() { delete ui; } void BluetoothAttServerAttributesDialog::captureFileClosed() { ui->interfaceComboBox->setEnabled(FALSE); ui->deviceComboBox->setEnabled(FALSE); ui->removeDuplicatesCheckBox->setEnabled(FALSE); WiresharkDialog::captureFileClosed(); } void BluetoothAttServerAttributesDialog::changeEvent(QEvent *event) { if (0 != event) { switch (event->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } QDialog::changeEvent(event); } void BluetoothAttServerAttributesDialog::keyPressEvent(QKeyEvent *event) { /* NOTE: Do nothing*, but in real it "takes focus" from button_box so allow user * to use Enter button to jump to frame from tree widget */ /* * - reimplement shortcuts from contex menu */ if (event->modifiers() & Qt::ControlModifier && event->key()== Qt::Key_M) on_actionMark_Unmark_Row_triggered(); } void BluetoothAttServerAttributesDialog::tableContextMenu(const QPoint &pos) { context_menu_.popup(ui->tableTreeWidget->viewport()->mapToGlobal(pos)); } void BluetoothAttServerAttributesDialog::on_actionMark_Unmark_Cell_triggered() { QTreeWidgetItem *current_item = ui->tableTreeWidget->currentItem(); if (!current_item) return; QBrush fg; QBrush bg; if (current_item->background(ui->tableTreeWidget->currentColumn()) == QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg))) { fg = QBrush(); bg = QBrush(); } else { fg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_fg)); bg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg)); } current_item->setForeground(ui->tableTreeWidget->currentColumn(), fg); current_item->setBackground(ui->tableTreeWidget->currentColumn(), bg); } void BluetoothAttServerAttributesDialog::on_actionMark_Unmark_Row_triggered() { QTreeWidgetItem *current_item = ui->tableTreeWidget->currentItem(); if (!current_item) return; QBrush fg; QBrush bg; bool is_marked = TRUE; for (int i = 0; i < ui->tableTreeWidget->columnCount(); i += 1) { if (current_item->background(i) != QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg))) is_marked = FALSE; } if (is_marked) { fg = QBrush(); bg = QBrush(); } else { fg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_fg)); bg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg)); } for (int i = 0; i < ui->tableTreeWidget->columnCount(); i += 1) { current_item->setForeground(i, fg); current_item->setBackground(i, bg); } } void BluetoothAttServerAttributesDialog::on_actionCopy_Cell_triggered() { QTreeWidgetItem *current_item = ui->tableTreeWidget->currentItem(); if (!current_item) return; QClipboard *clipboard = QApplication::clipboard(); QString copy; copy = QString(current_item->text(ui->tableTreeWidget->currentColumn())); clipboard->setText(copy); } void BluetoothAttServerAttributesDialog::on_actionCopy_Rows_triggered() { QClipboard *clipboard = QApplication::clipboard(); QString copy; QList<QTreeWidgetItem *> items; QList<QTreeWidgetItem *>::iterator i_item; items = ui->tableTreeWidget->selectedItems(); for (i_item = items.begin(); i_item != items.end(); ++i_item) { copy += QString("%1 %2 %3\n") .arg((*i_item)->text(column_number_handle), -6) .arg((*i_item)->text(column_number_uuid), -32) .arg((*i_item)->text(column_number_uuid_name)); } clipboard->setText(copy); } void BluetoothAttServerAttributesDialog::tapReset(void *tapinfo_ptr) { tapinfo_t *tapinfo = (tapinfo_t *) tapinfo_ptr; BluetoothAttServerAttributesDialog *bluetooth_att_server_attributes_dialog = static_cast<BluetoothAttServerAttributesDialog *>(tapinfo->ui); bluetooth_att_server_attributes_dialog->ui->tableTreeWidget->clear(); } tap_packet_status BluetoothAttServerAttributesDialog::tapPacket(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *, const void *data, tap_flags_t) { tapinfo_t *tapinfo = static_cast<tapinfo_t *>(tapinfo_ptr); BluetoothAttServerAttributesDialog *dialog = static_cast<BluetoothAttServerAttributesDialog *>(tapinfo->ui); tap_handles_t *tap_handles = static_cast<tap_handles_t *>(const_cast<void *>(data)); QString handle; QString uuid; QString uuid_name; gchar *addr = NULL; if (dialog->file_closed_) return TAP_PACKET_DONT_REDRAW; if (pinfo->rec->rec_type != REC_TYPE_PACKET) return TAP_PACKET_DONT_REDRAW; if (pinfo->rec->presence_flags & WTAP_HAS_INTERFACE_ID) { gchar *interface; const char *interface_name; interface_name = epan_get_interface_name(pinfo->epan, pinfo->rec->rec_header.packet_header.interface_id); interface = wmem_strdup_printf(pinfo->pool, "%u: %s", pinfo->rec->rec_header.packet_header.interface_id, interface_name); if (dialog->ui->interfaceComboBox->findText(interface) == -1) dialog->ui->interfaceComboBox->addItem(interface); if (interface && dialog->ui->interfaceComboBox->currentIndex() > 0) { if (dialog->ui->interfaceComboBox->currentText() != interface) return TAP_PACKET_REDRAW; } } if (pinfo->p2p_dir == P2P_DIR_SENT || pinfo->p2p_dir == P2P_DIR_RECV) addr = address_to_str(pinfo->pool, &pinfo->src); if (addr && dialog->ui->deviceComboBox->findText(addr) == -1) { dialog->ui->deviceComboBox->addItem(addr); } if (addr && dialog->ui->deviceComboBox->currentIndex() > 0) { if (dialog->ui->deviceComboBox->currentText() != addr) return TAP_PACKET_REDRAW; } handle = QString("0x%1").arg(tap_handles->handle, 4, 16, QChar('0')); uuid = QString(print_numeric_bluetooth_uuid(pinfo->pool, &tap_handles->uuid)); uuid_name = QString(print_bluetooth_uuid(pinfo->pool, &tap_handles->uuid)); if (dialog->ui->removeDuplicatesCheckBox->checkState() == Qt::Checked) { QTreeWidgetItemIterator i_item(dialog->ui->tableTreeWidget); while (*i_item) { QTreeWidgetItem *item = static_cast<QTreeWidgetItem*>(*i_item); if (item->text(column_number_handle) == handle && item->text(column_number_uuid) == uuid && item->text(column_number_uuid_name) == uuid_name) return TAP_PACKET_REDRAW; ++i_item; } } QTreeWidgetItem *item = new QTreeWidgetItem(dialog->ui->tableTreeWidget); item->setText(column_number_handle, handle); item->setText(column_number_uuid, uuid); item->setText(column_number_uuid_name, uuid_name); item->setData(0, Qt::UserRole, QVariant::fromValue(pinfo->num)); for (int i = 0; i < dialog->ui->tableTreeWidget->columnCount(); i++) { dialog->ui->tableTreeWidget->resizeColumnToContents(i); } return TAP_PACKET_REDRAW; } void BluetoothAttServerAttributesDialog::interfaceCurrentIndexChanged(int) { cap_file_.retapPackets(); } void BluetoothAttServerAttributesDialog::deviceCurrentIndexChanged(int) { cap_file_.retapPackets(); } void BluetoothAttServerAttributesDialog::removeDuplicatesStateChanged(int) { cap_file_.retapPackets(); } void BluetoothAttServerAttributesDialog::on_tableTreeWidget_itemActivated(QTreeWidgetItem *item, int) { if (file_closed_) return; guint32 frame_number = item->data(0, Qt::UserRole).value<guint32>(); emit goToPacket(frame_number); } void BluetoothAttServerAttributesDialog::on_actionCopy_All_triggered() { QClipboard *clipboard = QApplication::clipboard(); QString copy; QTreeWidgetItemIterator i_item(ui->tableTreeWidget); copy = QString("%1 %2 %3\n") .arg(ui->tableTreeWidget->headerItem()->text(column_number_handle), -6) .arg(ui->tableTreeWidget->headerItem()->text(column_number_uuid), -32) .arg(ui->tableTreeWidget->headerItem()->text(column_number_uuid_name)); while (*i_item) { QTreeWidgetItem *item = static_cast<QTreeWidgetItem*>(*i_item); copy += QString("%1 %2 %3\n") .arg(item->text(column_number_handle), -6) .arg(item->text(column_number_uuid), -32) .arg(item->text(column_number_uuid_name)); ++i_item; } clipboard->setText(copy); } void BluetoothAttServerAttributesDialog::on_actionSave_as_image_triggered() { QPixmap image; QString fileName = WiresharkFileDialog::getSaveFileName(this, tr("Save Table Image"), "att_server_attributes_table.png", tr("PNG Image (*.png)")); if (fileName.isEmpty()) return; image = ui->tableTreeWidget->grab(); image.save(fileName, "PNG"); } void BluetoothAttServerAttributesDialog::on_buttonBox_clicked(QAbstractButton *) { /* if (button == foo_button_) */ }
C/C++
wireshark/ui/qt/bluetooth_att_server_attributes_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef BLUETOOTH_ATT_SERVER_ATTRIBUTES_DIALOG_H #define BLUETOOTH_ATT_SERVER_ATTRIBUTES_DIALOG_H #include <config.h> #include <glib.h> #include "wireshark_dialog.h" #include "cfile.h" #include "epan/tap.h" #include <QMenu> class QAbstractButton; class QPushButton; class QTreeWidgetItem; typedef struct _tapinfo_t { tap_reset_cb tap_reset; tap_packet_cb tap_packet; void *ui; } tapinfo_t; namespace Ui { class BluetoothAttServerAttributesDialog; } class QTreeWidgetItem; class BluetoothAttServerAttributesDialog : public WiresharkDialog { Q_OBJECT public: explicit BluetoothAttServerAttributesDialog(QWidget &parent, CaptureFile &cf); ~BluetoothAttServerAttributesDialog(); public slots: signals: void updateFilter(QString filter, bool force = false); void captureFileChanged(capture_file *cf); void goToPacket(int packet_num); protected: void keyPressEvent(QKeyEvent *event); void captureFileClosed(); protected slots: void changeEvent(QEvent* event); private: Ui::BluetoothAttServerAttributesDialog *ui; tapinfo_t tapinfo_; QMenu context_menu_; static void tapReset(void *tapinfo_ptr); static tap_packet_status tapPacket(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *, const void *data, tap_flags_t flags); private slots: void on_tableTreeWidget_itemActivated(QTreeWidgetItem *item, int); void on_buttonBox_clicked(QAbstractButton *button); void on_actionMark_Unmark_Cell_triggered(); void on_actionMark_Unmark_Row_triggered(); void on_actionCopy_Cell_triggered(); void on_actionCopy_Rows_triggered(); void on_actionCopy_All_triggered(); void on_actionSave_as_image_triggered(); void tableContextMenu(const QPoint &pos); void interfaceCurrentIndexChanged(int index); void deviceCurrentIndexChanged(int index); void removeDuplicatesStateChanged(int state); }; #endif // BLUETOOTH_ATT_SERVER_ATTRIBUTES_DIALOG_H
User Interface
wireshark/ui/qt/bluetooth_att_server_attributes_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>BluetoothAttServerAttributesDialog</class> <widget class="QDialog" name="BluetoothAttServerAttributesDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>880</width> <height>477</height> </rect> </property> <property name="baseSize"> <size> <width>0</width> <height>0</height> </size> </property> <property name="windowTitle"> <string>Bluetooth ATT Server Attributes</string> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QTreeWidget" name="tableTreeWidget"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="selectionMode"> <enum>QAbstractItemView::ExtendedSelection</enum> </property> <property name="textElideMode"> <enum>Qt::ElideMiddle</enum> </property> <property name="rootIsDecorated"> <bool>false</bool> </property> <property name="itemsExpandable"> <bool>false</bool> </property> <property name="sortingEnabled"> <bool>true</bool> </property> <attribute name="headerCascadingSectionResizes"> <bool>false</bool> </attribute> <attribute name="headerHighlightSections"> <bool>false</bool> </attribute> <attribute name="headerShowSortIndicator" stdset="0"> <bool>true</bool> </attribute> <column> <property name="text"> <string>Handle</string> </property> </column> <column> <property name="text"> <string>UUID</string> </property> </column> <column> <property name="text"> <string>UUID Name</string> </property> </column> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0,0"> <property name="spacing"> <number>-1</number> </property> <property name="sizeConstraint"> <enum>QLayout::SetDefaultConstraint</enum> </property> <property name="bottomMargin"> <number>0</number> </property> <item> <widget class="QComboBox" name="interfaceComboBox"> <property name="sizePolicy"> <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>350</width> <height>0</height> </size> </property> <item> <property name="text"> <string>All Interfaces</string> </property> </item> </widget> </item> <item> <widget class="QComboBox" name="deviceComboBox"> <property name="enabled"> <bool>true</bool> </property> <property name="sizePolicy"> <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>325</width> <height>0</height> </size> </property> <property name="baseSize"> <size> <width>0</width> <height>0</height> </size> </property> <property name="mouseTracking"> <bool>false</bool> </property> <property name="focusPolicy"> <enum>Qt::WheelFocus</enum> </property> <property name="acceptDrops"> <bool>false</bool> </property> <property name="layoutDirection"> <enum>Qt::LeftToRight</enum> </property> <property name="currentIndex"> <number>0</number> </property> <property name="duplicatesEnabled"> <bool>false</bool> </property> <property name="frame"> <bool>true</bool> </property> <property name="modelColumn"> <number>0</number> </property> <item> <property name="text"> <string>All Devices</string> </property> </item> </widget> </item> <item> <widget class="QCheckBox" name="removeDuplicatesCheckBox"> <property name="text"> <string>Remove duplicates</string> </property> <property name="checked"> <bool>true</bool> </property> </widget> </item> </layout> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Close</set> </property> </widget> </item> </layout> <action name="actionCopy_Cell"> <property name="text"> <string>Copy Cell</string> </property> </action> <action name="actionCopy_Rows"> <property name="text"> <string>Copy Rows</string> </property> </action> <action name="actionCopy_All"> <property name="text"> <string>Copy All</string> </property> </action> <action name="actionSave_as_image"> <property name="text"> <string>Save as image</string> </property> </action> <action name="actionMark_Unmark_Row"> <property name="text"> <string>Mark/Unmark Row</string> </property> <property name="toolTip"> <string>Mark/Unmark Row</string> </property> <property name="shortcut"> <string>Ctrl-M</string> </property> </action> <action name="actionMark_Unmark_Cell"> <property name="text"> <string>Mark/Unmark Cell</string> </property> </action> </widget> <resources/> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>BluetoothAttServerAttributesDialog</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>374</x> <y>407</y> </hint> <hint type="destinationlabel"> <x>374</x> <y>214</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>BluetoothAttServerAttributesDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>374</x> <y>407</y> </hint> <hint type="destinationlabel"> <x>374</x> <y>214</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/bluetooth_devices_dialog.cpp
/* bluetooth_devices_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "bluetooth_devices_dialog.h" #include <ui_bluetooth_devices_dialog.h> #include "bluetooth_device_dialog.h" #include <ui/qt/utils/color_utils.h> #include "epan/epan.h" #include "epan/addr_resolv.h" #include "epan/to_str.h" #include "epan/epan_dissect.h" #include "epan/prefs.h" #include "epan/dissectors/packet-bluetooth.h" #include "epan/dissectors/packet-bthci_evt.h" #include <ui/qt/utils/variant_pointer.h> #include "ui/simple_dialog.h" #include "ui/qt/widgets/wireshark_file_dialog.h" #include <QClipboard> #include <QContextMenuEvent> #include <QPushButton> #include <QTreeWidget> static const int column_number_bd_addr = 0; static const int column_number_bd_addr_oui = 1; static const int column_number_name = 2; static const int column_number_lmp_version = 3; static const int column_number_lmp_subversion = 4; static const int column_number_manufacturer = 5; static const int column_number_hci_version = 6; static const int column_number_hci_revision = 7; static const int column_number_is_local_adapter = 8; static tap_packet_status bluetooth_device_tap_packet(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *edt, const void* data, tap_flags_t flags) { bluetooth_devices_tapinfo_t *tapinfo = (bluetooth_devices_tapinfo_t *) tapinfo_ptr; if (tapinfo->tap_packet) tapinfo->tap_packet(tapinfo, pinfo, edt, data, flags); return TAP_PACKET_REDRAW; } static void bluetooth_device_tap_reset(void *tapinfo_ptr) { bluetooth_devices_tapinfo_t *tapinfo = (bluetooth_devices_tapinfo_t *) tapinfo_ptr; if (tapinfo->tap_reset) tapinfo->tap_reset(tapinfo); } BluetoothDevicesDialog::BluetoothDevicesDialog(QWidget &parent, CaptureFile &cf, PacketList *packet_list) : WiresharkDialog(parent, cf), ui(new Ui::BluetoothDevicesDialog) { ui->setupUi(this); loadGeometry(parent.width() * 4 / 5, parent.height() * 2 / 3); packet_list_ = packet_list; connect(ui->tableTreeWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(tableContextMenu(const QPoint &))); connect(ui->tableTreeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(tableItemDoubleClicked(QTreeWidgetItem *, int))); connect(ui->interfaceComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(interfaceCurrentIndexChanged(int))); connect(ui->showInformationStepsCheckBox, SIGNAL(stateChanged(int)), this, SLOT(showInformationStepsChanged(int))); ui->tableTreeWidget->sortByColumn(column_number_bd_addr, Qt::AscendingOrder); ui->tableTreeWidget->setStyleSheet("QTreeView::item:hover{background-color:lightyellow; color:black;}"); context_menu_.addActions(QList<QAction *>() << ui->actionMark_Unmark_Cell); context_menu_.addActions(QList<QAction *>() << ui->actionMark_Unmark_Row); context_menu_.addActions(QList<QAction *>() << ui->actionCopy_Cell); context_menu_.addActions(QList<QAction *>() << ui->actionCopy_Rows); context_menu_.addActions(QList<QAction *>() << ui->actionCopy_All); context_menu_.addActions(QList<QAction *>() << ui->actionSave_as_image); tapinfo_.tap_packet = tapPacket; tapinfo_.tap_reset = tapReset; tapinfo_.ui = this; registerTapListener("bluetooth.device", &tapinfo_, NULL, 0, bluetooth_device_tap_reset, bluetooth_device_tap_packet, NULL ); ui->hintLabel->setText(ui->hintLabel->text().arg(0)); cap_file_.retapPackets(); } BluetoothDevicesDialog::~BluetoothDevicesDialog() { delete ui; } void BluetoothDevicesDialog::captureFileClosed() { ui->interfaceComboBox->setEnabled(FALSE); ui->showInformationStepsCheckBox->setEnabled(FALSE); WiresharkDialog::captureFileClosed(); } void BluetoothDevicesDialog::changeEvent(QEvent *event) { if (0 != event) { switch (event->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } QDialog::changeEvent(event); } void BluetoothDevicesDialog::keyPressEvent(QKeyEvent *event) { /* NOTE: Do nothing*, but in real it "takes focus" from button_box so allow user * to use Enter button to jump to frame from tree widget */ /* * - reimplement shortcuts from contex menu */ if (event->modifiers() & Qt::ControlModifier && event->key()== Qt::Key_M) on_actionMark_Unmark_Row_triggered(); } void BluetoothDevicesDialog::tableContextMenu(const QPoint &pos) { context_menu_.popup(ui->tableTreeWidget->viewport()->mapToGlobal(pos)); } void BluetoothDevicesDialog::tableItemDoubleClicked(QTreeWidgetItem *item, int) { bluetooth_item_data_t *item_data; BluetoothDeviceDialog *bluetooth_device_dialog; item_data = VariantPointer<bluetooth_item_data_t>::asPtr(item->data(0, Qt::UserRole)); bluetooth_device_dialog = new BluetoothDeviceDialog(*this, cap_file_, item->text(column_number_bd_addr), item->text(column_number_name), item_data->interface_id, item_data->adapter_id, !item->text(column_number_is_local_adapter).isEmpty()); connect(bluetooth_device_dialog, SIGNAL(goToPacket(int)), packet_list_, SLOT(goToPacket(int))); bluetooth_device_dialog->show(); } void BluetoothDevicesDialog::on_actionMark_Unmark_Cell_triggered() { QBrush fg; QBrush bg; if (ui->tableTreeWidget->currentItem()->background(ui->tableTreeWidget->currentColumn()) == QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg))) { fg = QBrush(); bg = QBrush(); } else { fg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_fg)); bg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg)); } ui->tableTreeWidget->currentItem()->setForeground(ui->tableTreeWidget->currentColumn(), fg); ui->tableTreeWidget->currentItem()->setBackground(ui->tableTreeWidget->currentColumn(), bg); } void BluetoothDevicesDialog::on_actionMark_Unmark_Row_triggered() { QBrush fg; QBrush bg; bool is_marked = TRUE; for (int i = 0; i < ui->tableTreeWidget->columnCount(); i += 1) { if (ui->tableTreeWidget->currentItem()->background(i) != QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg))) is_marked = FALSE; } if (is_marked) { fg = QBrush(); bg = QBrush(); } else { fg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_fg)); bg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg)); } for (int i = 0; i < ui->tableTreeWidget->columnCount(); i += 1) { ui->tableTreeWidget->currentItem()->setForeground(i, fg); ui->tableTreeWidget->currentItem()->setBackground(i, bg); } } void BluetoothDevicesDialog::on_actionCopy_Cell_triggered() { QClipboard *clipboard = QApplication::clipboard(); QString copy; copy = QString(ui->tableTreeWidget->currentItem()->text(ui->tableTreeWidget->currentColumn())); clipboard->setText(copy); } void BluetoothDevicesDialog::on_actionCopy_Rows_triggered() { QClipboard *clipboard = QApplication::clipboard(); QString copy; QList<QTreeWidgetItem *> items; QList<QTreeWidgetItem *>::iterator i_item; items = ui->tableTreeWidget->selectedItems(); for (i_item = items.begin(); i_item != items.end(); ++i_item) { copy += QString("%1 %2 %3 %4 %5 %6 %7 %8 %9\n") .arg((*i_item)->text(column_number_bd_addr), -20) .arg((*i_item)->text(column_number_bd_addr_oui), -20) .arg((*i_item)->text(column_number_name), -30) .arg((*i_item)->text(column_number_lmp_version), -20) .arg((*i_item)->text(column_number_lmp_subversion), -20) .arg((*i_item)->text(column_number_manufacturer), -30) .arg((*i_item)->text(column_number_hci_version), -20) .arg((*i_item)->text(column_number_hci_revision), -20) .arg((*i_item)->text(column_number_is_local_adapter), -20); } clipboard->setText(copy); } void BluetoothDevicesDialog::tapReset(void *tapinfo_ptr) { bluetooth_devices_tapinfo_t *tapinfo = (bluetooth_devices_tapinfo_t *) tapinfo_ptr; BluetoothDevicesDialog *bluetooth_devices_dialog = static_cast<BluetoothDevicesDialog *>(tapinfo->ui); bluetooth_devices_dialog->ui->tableTreeWidget->clear(); } tap_packet_status BluetoothDevicesDialog::tapPacket(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *, const void *data, tap_flags_t) { bluetooth_devices_tapinfo_t *tapinfo = static_cast<bluetooth_devices_tapinfo_t *>(tapinfo_ptr); BluetoothDevicesDialog *dialog = static_cast<BluetoothDevicesDialog *>(tapinfo->ui); bluetooth_device_tap_t *tap_device = static_cast<bluetooth_device_tap_t *>(const_cast<void *>(data)); QString bd_addr; QString bd_addr_oui; const gchar *manuf; QTreeWidgetItem *item = NULL; if (dialog->file_closed_) return TAP_PACKET_DONT_REDRAW; if (pinfo->rec->rec_type != REC_TYPE_PACKET) return TAP_PACKET_DONT_REDRAW; if (pinfo->rec->presence_flags & WTAP_HAS_INTERFACE_ID) { gchar *interface; const char *interface_name; interface_name = epan_get_interface_name(pinfo->epan, pinfo->rec->rec_header.packet_header.interface_id); interface = wmem_strdup_printf(pinfo->pool, "%u: %s", pinfo->rec->rec_header.packet_header.interface_id, interface_name); if (dialog->ui->interfaceComboBox->findText(interface) == -1) dialog->ui->interfaceComboBox->addItem(interface); if (interface && dialog->ui->interfaceComboBox->currentIndex() > 0) { if (dialog->ui->interfaceComboBox->currentText() != interface) return TAP_PACKET_REDRAW; } } if (tap_device->has_bd_addr) { for (int i = 0; i < 6; ++i) { bd_addr += QString("%1:").arg(tap_device->bd_addr[i], 2, 16, QChar('0')); } bd_addr.chop(1); // remove extra character ":" from the end of the string manuf = get_ether_name(tap_device->bd_addr); if (manuf) { int pos; bd_addr_oui = QString(manuf); pos = static_cast<int>(bd_addr_oui.indexOf('_')); if (pos < 0) { manuf = NULL; } else { bd_addr_oui.remove(pos, bd_addr_oui.size()); } } if (!manuf) bd_addr_oui = ""; } if (dialog->ui->showInformationStepsCheckBox->checkState() != Qt::Checked) { QTreeWidgetItemIterator i_item(dialog->ui->tableTreeWidget); while (*i_item) { QTreeWidgetItem *current_item = static_cast<QTreeWidgetItem*>(*i_item); bluetooth_item_data_t *item_data = VariantPointer<bluetooth_item_data_t>::asPtr(current_item->data(0, Qt::UserRole)); if ((tap_device->has_bd_addr && current_item->text(column_number_bd_addr) == bd_addr) || (tap_device->is_local && item_data->interface_id == tap_device->interface_id && item_data->adapter_id == tap_device->adapter_id && !current_item->text(column_number_is_local_adapter).isEmpty())) { item = current_item; break; } ++i_item; } } if (!item) { item = new QTreeWidgetItem(dialog->ui->tableTreeWidget); item->setText(column_number_bd_addr, bd_addr); item->setText(column_number_bd_addr_oui, bd_addr_oui); if (tap_device->is_local) { item->setText(column_number_is_local_adapter, tr("true")); } bluetooth_item_data_t *item_data = wmem_new(wmem_file_scope(), bluetooth_item_data_t); item_data->interface_id = tap_device->interface_id; item_data->adapter_id = tap_device->adapter_id; item_data->frame_number = pinfo->num; item->setData(0, Qt::UserRole, VariantPointer<bluetooth_item_data_t>::asQVariant(item_data)); } if (tap_device->type == BLUETOOTH_DEVICE_BD_ADDR) { item->setText(column_number_bd_addr, bd_addr); item->setText(column_number_bd_addr_oui, bd_addr_oui); } if (tap_device->type == BLUETOOTH_DEVICE_NAME) { item->setText(column_number_name, tap_device->data.name); } if (tap_device->type == BLUETOOTH_DEVICE_LOCAL_ADAPTER) item->setText(column_number_is_local_adapter, tr("true")); if (tap_device->type == BLUETOOTH_DEVICE_LOCAL_VERSION) { item->setText(column_number_hci_version, val_to_str_const(tap_device->data.local_version.hci_version, bthci_evt_hci_version, "Unknown 0x%02x")); item->setText(column_number_hci_revision, QString::number(tap_device->data.local_version.hci_revision)); item->setText(column_number_lmp_version, val_to_str_const(tap_device->data.local_version.lmp_version, bthci_evt_lmp_version, "Unknown 0x%02x")); item->setText(column_number_lmp_subversion, QString::number(tap_device->data.local_version.lmp_subversion)); item->setText(column_number_manufacturer, val_to_str_ext_const(tap_device->data.local_version.manufacturer, &bluetooth_company_id_vals_ext, "Unknown 0x%04x")); } if (tap_device->type == BLUETOOTH_DEVICE_REMOTE_VERSION) { item->setText(column_number_lmp_version, val_to_str_const(tap_device->data.remote_version.lmp_version, bthci_evt_lmp_version, "Unknown 0x%02x")); item->setText(column_number_lmp_subversion, QString::number(tap_device->data.remote_version.lmp_subversion)); item->setText(column_number_manufacturer, val_to_str_ext_const(tap_device->data.remote_version.manufacturer, &bluetooth_company_id_vals_ext, "Unknown 0x%04x")); } for (int i = 0; i < dialog->ui->tableTreeWidget->columnCount(); i++) { dialog->ui->tableTreeWidget->resizeColumnToContents(i); } dialog->ui->hintLabel->setText(QString(tr("%1 items; Right click for more option; Double click for device details")).arg(dialog->ui->tableTreeWidget->topLevelItemCount())); return TAP_PACKET_REDRAW; } void BluetoothDevicesDialog::interfaceCurrentIndexChanged(int) { cap_file_.retapPackets(); } void BluetoothDevicesDialog::showInformationStepsChanged(int) { cap_file_.retapPackets(); } void BluetoothDevicesDialog::on_tableTreeWidget_itemActivated(QTreeWidgetItem *item, int) { if (file_closed_) return; bluetooth_item_data_t *item_data = VariantPointer<bluetooth_item_data_t>::asPtr(item->data(0, Qt::UserRole)); emit goToPacket(item_data->frame_number); } void BluetoothDevicesDialog::on_actionCopy_All_triggered() { QClipboard *clipboard = QApplication::clipboard(); QString copy; QTreeWidgetItemIterator i_item(ui->tableTreeWidget); QTreeWidgetItem *item; item = ui->tableTreeWidget->headerItem(); copy += QString("%1 %2 %3 %4 %5 %6 %7 %8 %9\n") .arg(item->text(column_number_bd_addr), -20) .arg(item->text(column_number_bd_addr_oui), -20) .arg(item->text(column_number_name), -30) .arg(item->text(column_number_lmp_version), -20) .arg(item->text(column_number_lmp_subversion), -20) .arg(item->text(column_number_manufacturer), -30) .arg(item->text(column_number_hci_version), -20) .arg(item->text(column_number_hci_revision), -20) .arg(item->text(column_number_is_local_adapter), -20); while (*i_item) { item = static_cast<QTreeWidgetItem*>(*i_item); copy += QString("%1 %2 %3 %4 %5 %6 %7 %8 %9\n") .arg(item->text(column_number_bd_addr), -20) .arg(item->text(column_number_bd_addr_oui), -20) .arg(item->text(column_number_name), -30) .arg(item->text(column_number_lmp_version), -20) .arg(item->text(column_number_lmp_subversion), -20) .arg(item->text(column_number_manufacturer), -30) .arg(item->text(column_number_hci_version), -20) .arg(item->text(column_number_hci_revision), -20) .arg(item->text(column_number_is_local_adapter), -20); ++i_item; } clipboard->setText(copy); } void BluetoothDevicesDialog::on_actionSave_as_image_triggered() { QPixmap image; QString fileName = WiresharkFileDialog::getSaveFileName(this, tr("Save Table Image"), "bluetooth_devices_table.png", tr("PNG Image (*.png)")); if (fileName.isEmpty()) return; image = ui->tableTreeWidget->grab(); image.save(fileName, "PNG"); } void BluetoothDevicesDialog::on_buttonBox_clicked(QAbstractButton *) { /* if (button == foo_button_) */ }
C/C++
wireshark/ui/qt/bluetooth_devices_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef BLUETOOTH_DEVICES_DIALOG_H #define BLUETOOTH_DEVICES_DIALOG_H #include "config.h" #include <glib.h> #include "wireshark_dialog.h" #include "cfile.h" #include "packet_list.h" #include "epan/tap.h" #include <QMenu> class QAbstractButton; class QPushButton; class QTreeWidgetItem; typedef struct _bluetooth_devices_tapinfo_t { tap_reset_cb tap_reset; tap_packet_cb tap_packet; void *ui; } bluetooth_devices_tapinfo_t; namespace Ui { class BluetoothDevicesDialog; } class BluetoothDevicesDialog : public WiresharkDialog { Q_OBJECT public: explicit BluetoothDevicesDialog(QWidget &parent, CaptureFile &cf, PacketList *packet_list); ~BluetoothDevicesDialog(); public slots: signals: void updateFilter(QString filter, bool force = false); void captureFileChanged(capture_file *cf); void goToPacket(int packet_num); protected: void keyPressEvent(QKeyEvent *event); void captureFileClosed(); protected slots: void changeEvent(QEvent* event); private: Ui::BluetoothDevicesDialog *ui; PacketList *packet_list_; bluetooth_devices_tapinfo_t tapinfo_; QMenu context_menu_; static void tapReset(void *tapinfo_ptr); static tap_packet_status tapPacket(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *, const void *data, tap_flags_t flags); private slots: void on_tableTreeWidget_itemActivated(QTreeWidgetItem *item, int); void on_buttonBox_clicked(QAbstractButton *button); void on_actionMark_Unmark_Cell_triggered(); void on_actionMark_Unmark_Row_triggered(); void on_actionCopy_Cell_triggered(); void on_actionCopy_Rows_triggered(); void on_actionCopy_All_triggered(); void on_actionSave_as_image_triggered(); void tableContextMenu(const QPoint &pos); void tableItemDoubleClicked(QTreeWidgetItem *item, int column); void interfaceCurrentIndexChanged(int index); void showInformationStepsChanged(int state); }; #endif // BLUETOOTH_DEVICES_DIALOG_H
User Interface
wireshark/ui/qt/bluetooth_devices_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>BluetoothDevicesDialog</class> <widget class="QDialog" name="BluetoothDevicesDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>880</width> <height>477</height> </rect> </property> <property name="baseSize"> <size> <width>0</width> <height>0</height> </size> </property> <property name="windowTitle"> <string>Bluetooth Devices</string> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QTreeWidget" name="tableTreeWidget"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="selectionMode"> <enum>QAbstractItemView::ExtendedSelection</enum> </property> <property name="textElideMode"> <enum>Qt::ElideMiddle</enum> </property> <property name="rootIsDecorated"> <bool>false</bool> </property> <property name="itemsExpandable"> <bool>false</bool> </property> <property name="sortingEnabled"> <bool>true</bool> </property> <attribute name="headerCascadingSectionResizes"> <bool>false</bool> </attribute> <attribute name="headerHighlightSections"> <bool>false</bool> </attribute> <attribute name="headerShowSortIndicator" stdset="0"> <bool>true</bool> </attribute> <column> <property name="text"> <string>BD_ADDR</string> </property> </column> <column> <property name="text"> <string>OUI</string> </property> </column> <column> <property name="text"> <string>Name</string> </property> </column> <column> <property name="text"> <string>LMP Version</string> </property> </column> <column> <property name="text"> <string>LMP Subversion</string> </property> </column> <column> <property name="text"> <string>Manufacturer</string> </property> </column> <column> <property name="text"> <string>HCI Version</string> </property> </column> <column> <property name="text"> <string>HCI Revision</string> </property> </column> <column> <property name="text"> <string>Is Local Adapter</string> </property> </column> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0"> <property name="spacing"> <number>-1</number> </property> <property name="sizeConstraint"> <enum>QLayout::SetDefaultConstraint</enum> </property> <property name="bottomMargin"> <number>0</number> </property> <item> <widget class="QComboBox" name="interfaceComboBox"> <property name="sizePolicy"> <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>350</width> <height>0</height> </size> </property> <item> <property name="text"> <string>All Interfaces</string> </property> </item> </widget> </item> <item> <widget class="QCheckBox" name="showInformationStepsCheckBox"> <property name="text"> <string>Show information steps</string> </property> <property name="checked"> <bool>false</bool> </property> </widget> </item> </layout> </item> <item> <widget class="QLabel" name="hintLabel"> <property name="text"> <string>%1 items; Right click for more option; Double click for device details</string> </property> </widget> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Close</set> </property> </widget> </item> </layout> <action name="actionCopy_Cell"> <property name="text"> <string>Copy Cell</string> </property> </action> <action name="actionCopy_Rows"> <property name="text"> <string>Copy Rows</string> </property> </action> <action name="actionCopy_All"> <property name="text"> <string>Copy All</string> </property> </action> <action name="actionSave_as_image"> <property name="text"> <string>Save as image</string> </property> </action> <action name="actionMark_Unmark_Row"> <property name="text"> <string>Mark/Unmark Row</string> </property> <property name="toolTip"> <string>Mark/Unmark Row</string> </property> <property name="shortcut"> <string>Ctrl-M</string> </property> </action> <action name="actionMark_Unmark_Cell"> <property name="text"> <string>Mark/Unmark Cell</string> </property> </action> </widget> <resources/> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>BluetoothDevicesDialog</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>374</x> <y>407</y> </hint> <hint type="destinationlabel"> <x>374</x> <y>214</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>BluetoothDevicesDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>374</x> <y>407</y> </hint> <hint type="destinationlabel"> <x>374</x> <y>214</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/bluetooth_device_dialog.cpp
/* bluetooth_device_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "bluetooth_device_dialog.h" #include <ui_bluetooth_device_dialog.h> #include <ui/qt/utils/color_utils.h> #include "epan/epan.h" #include "epan/addr_resolv.h" #include "epan/to_str.h" #include "epan/epan_dissect.h" #include "epan/prefs.h" #include "epan/dissectors/packet-bthci_cmd.h" #include "epan/dissectors/packet-bthci_evt.h" #include "ui/simple_dialog.h" #include <ui/qt/utils/variant_pointer.h> #include "ui/qt/widgets/wireshark_file_dialog.h" #include <QClipboard> #include <QContextMenuEvent> #include <QPushButton> #include <QTreeWidget> static const int column_number_value = 0; static const int column_number_changes = 1; static const int row_number_bd_addr = 0; static const int row_number_bd_addr_oui = 1; static const int row_number_name = 2; static const int row_number_class_of_device = 3; static const int row_number_lmp_version = 4; static const int row_number_lmp_subversion = 5; static const int row_number_manufacturer = 6; static const int row_number_hci_version = 7; static const int row_number_hci_revision = 8; static const int row_number_scan = 9; static const int row_number_authentication = 10; static const int row_number_encryption = 11; static const int row_number_acl_mtu = 12; static const int row_number_acl_packets = 13; static const int row_number_sco_mtu = 14; static const int row_number_sco_packets = 15; static const int row_number_le_acl_mtu = 16; static const int row_number_le_acl_packets = 17; static const int row_number_le_iso_mtu = 18; static const int row_number_le_iso_packets = 19; static const int row_number_inquiry_mode = 20; static const int row_number_page_timeout = 21; static const int row_number_simple_pairing_mode = 22; static const int row_number_voice_setting = 23; static tap_packet_status bluetooth_device_tap_packet(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *edt, const void* data, tap_flags_t flags) { bluetooth_device_tapinfo_t *tapinfo = (bluetooth_device_tapinfo_t *) tapinfo_ptr; if (tapinfo->tap_packet) tapinfo->tap_packet(tapinfo, pinfo, edt, data, flags); return TAP_PACKET_REDRAW; } static void bluetooth_device_tap_reset(void *tapinfo_ptr) { bluetooth_device_tapinfo_t *tapinfo = (bluetooth_device_tapinfo_t *) tapinfo_ptr; if (tapinfo->tap_reset) tapinfo->tap_reset(tapinfo); } static void bluetooth_devices_tap(void *data) { GString *error_string; error_string = register_tap_listener("bluetooth.device", data, NULL, 0, bluetooth_device_tap_reset, bluetooth_device_tap_packet, NULL, NULL ); if (error_string != NULL) { simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", error_string->str); g_string_free(error_string, TRUE); } } BluetoothDeviceDialog::BluetoothDeviceDialog(QWidget &parent, CaptureFile &cf, QString bdAddr, QString name, guint32 interface_id, guint32 adapter_id, gboolean is_local) : WiresharkDialog(parent, cf), ui(new Ui::BluetoothDeviceDialog) { ui->setupUi(this); resize(parent.width() * 4 / 10, parent.height() * 2 / 2); setTitle(bdAddr, name); connect(ui->tableWidget, &QTableWidget::customContextMenuRequested, this, &BluetoothDeviceDialog::tableContextMenu); ui->tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); ui->tableWidget->setStyleSheet("QTableView::item:hover{background-color:lightyellow; color:black;}"); context_menu_.addActions(QList<QAction *>() << ui->actionMark_Unmark_Cell); context_menu_.addActions(QList<QAction *>() << ui->actionMark_Unmark_Row); context_menu_.addActions(QList<QAction *>() << ui->actionCopy_Cell); context_menu_.addActions(QList<QAction *>() << ui->actionCopy_Rows); context_menu_.addActions(QList<QAction *>() << ui->actionCopy_All); context_menu_.addActions(QList<QAction *>() << ui->actionSave_as_image); changes_ = 0; tapinfo_.tap_packet = tapPacket; tapinfo_.tap_reset = tapReset; tapinfo_.ui = this; tapinfo_.is_local = is_local; tapinfo_.bdAddr = bdAddr; tapinfo_.interface_id = interface_id; tapinfo_.adapter_id = adapter_id; tapinfo_.changes = &changes_; ui->hintLabel->setText(ui->hintLabel->text().arg(changes_)); for (int i_row = 0; i_row < ui->tableWidget->rowCount(); i_row += 1) { for (int i_column = 0; i_column < ui->tableWidget->columnCount(); i_column += 1) { QTableWidgetItem *item = new QTableWidgetItem(); ui->tableWidget->setItem(i_row, i_column, item); } } bluetooth_devices_tap(&tapinfo_); cap_file_.retapPackets(); } BluetoothDeviceDialog::~BluetoothDeviceDialog() { delete ui; remove_tap_listener(&tapinfo_); } void BluetoothDeviceDialog::setTitle(QString bdAddr, QString name) { QString titleBdAddr; QString titleName; if (bdAddr.isEmpty()) titleBdAddr = QString(tr("Unknown")); else titleBdAddr = bdAddr; if (name.isEmpty()) titleName = ""; else titleName = " ("+name+")"; setWindowTitle(tr("Bluetooth Device - %1%2").arg(titleBdAddr).arg(titleName)); } void BluetoothDeviceDialog::captureFileClosing() { remove_tap_listener(&tapinfo_); WiresharkDialog::captureFileClosing(); } void BluetoothDeviceDialog::changeEvent(QEvent *event) { if (0 != event) { switch (event->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } QDialog::changeEvent(event); } void BluetoothDeviceDialog::keyPressEvent(QKeyEvent *event) { /* NOTE: Do nothing*, but in real it "takes focus" from button_box so allow user * to use Enter button to jump to frame from tree widget */ /* * - reimplement shortcuts from contex menu */ if (event->modifiers() & Qt::ControlModifier && event->key()== Qt::Key_M) on_actionMark_Unmark_Row_triggered(); } void BluetoothDeviceDialog::on_actionMark_Unmark_Cell_triggered() { QTableWidgetItem *current_item = ui->tableWidget->currentItem(); if (!current_item) return; QBrush fg; QBrush bg; if (current_item->background() == QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg))) { fg = QBrush(); bg = QBrush(); } else { fg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_fg)); bg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg)); } current_item->setForeground(fg); current_item->setBackground(bg); } void BluetoothDeviceDialog::on_actionMark_Unmark_Row_triggered() { QBrush fg; QBrush bg; bool is_marked = TRUE; QTableWidgetItem *current_item = ui->tableWidget->currentItem(); if (!current_item) return; for (int i = 0; i < ui->tableWidget->columnCount(); i += 1) { QTableWidgetItem *item = ui->tableWidget->item(current_item->row(), i); if (item->background() != QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg))) is_marked = FALSE; } if (is_marked) { fg = QBrush(); bg = QBrush(); } else { fg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_fg)); bg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg)); } for (int i = 0; i < ui->tableWidget->columnCount(); i += 1) { QTableWidgetItem *item = ui->tableWidget->item(current_item->row(), i); item->setForeground(fg); item->setBackground(bg); } } void BluetoothDeviceDialog::tableContextMenu(const QPoint &pos) { context_menu_.popup(ui->tableWidget->viewport()->mapToGlobal(pos)); } void BluetoothDeviceDialog::on_actionCopy_Cell_triggered() { QTableWidgetItem *current_item = ui->tableWidget->currentItem(); if (!current_item) return; QClipboard *clipboard = QApplication::clipboard(); QString copy; copy = QString(current_item->text()); clipboard->setText(copy); } void BluetoothDeviceDialog::on_actionCopy_Rows_triggered() { QClipboard *clipboard = QApplication::clipboard(); QString copy; QList<QTableWidgetItem *> items; QList<QTableWidgetItem *>::iterator i_item; items = ui->tableWidget->selectedItems(); for (i_item = items.begin(); i_item != items.end(); ++i_item) { copy += QString("%1 %2 %3\n") .arg(ui->tableWidget->verticalHeaderItem((*i_item)->row())->text(), -40) .arg(ui->tableWidget->item((*i_item)->row(), column_number_value)->text(), -50) .arg(ui->tableWidget->item((*i_item)->row(), column_number_changes)->text(), -10); } clipboard->setText(copy); } void BluetoothDeviceDialog::on_actionCopy_All_triggered() { QClipboard *clipboard = QApplication::clipboard(); QString copy; copy += QString("%1 %2 %3\n") .arg("Headers", -40) .arg(ui->tableWidget->horizontalHeaderItem(column_number_value)->text(), -50) .arg(ui->tableWidget->horizontalHeaderItem(column_number_changes)->text(), -10); for (int i_row = 0; i_row < ui->tableWidget->rowCount(); i_row += 1) { for (int i_column = 0; i_column < ui->tableWidget->columnCount(); i_column += 1) { copy += QString("%1 %2 %3\n") .arg(ui->tableWidget->verticalHeaderItem(i_row)->text(), -40) .arg(ui->tableWidget->item(i_row, column_number_value)->text(), -50) .arg(ui->tableWidget->item(i_row, column_number_changes)->text(), -10); } } clipboard->setText(copy); } void BluetoothDeviceDialog::tapReset(void *tapinfo_ptr) { bluetooth_device_tapinfo_t *tapinfo = (bluetooth_device_tapinfo_t *) tapinfo_ptr; BluetoothDeviceDialog *dialog = static_cast<BluetoothDeviceDialog *>(tapinfo->ui); for (int i_row = 0; i_row < dialog->ui->tableWidget->rowCount(); i_row += 1) { for (int i_column = 0; i_column < dialog->ui->tableWidget->columnCount(); i_column += 1) { QTableWidgetItem *item = new QTableWidgetItem(); dialog->ui->tableWidget->setItem(i_row, i_column, item); } } *tapinfo->changes = 0; } void BluetoothDeviceDialog::updateChanges(QTableWidget *tableWidget, QString value, const int row, guint *changes, packet_info *pinfo) { QTableWidgetItem *item = tableWidget->item(row, column_number_value); bluetooth_item_data_t *item_data = VariantPointer<bluetooth_item_data_t>::asPtr(item->data(Qt::UserRole)); if (item->text() == value) return; if (item_data->changes == -1) { item_data->changes = 0; } else { *changes += 1; item_data->changes += 1; item_data->frame_number = pinfo->fd->num; tableWidget->item(row, column_number_changes)->setText(QString::number(item_data->changes)); } } void BluetoothDeviceDialog::saveItemData(QTableWidgetItem *item, bluetooth_device_tap_t *tap_device, packet_info *pinfo) { if (item->data(Qt::UserRole).isValid()) return; bluetooth_item_data_t *item_data = wmem_new(wmem_file_scope(), bluetooth_item_data_t); item_data->interface_id = tap_device->interface_id; item_data->adapter_id = tap_device->adapter_id; item_data->changes = -1; item_data->frame_number = pinfo->fd->num; item->setData(Qt::UserRole, VariantPointer<bluetooth_item_data_t>::asQVariant(item_data)); } tap_packet_status BluetoothDeviceDialog::tapPacket(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *, const void *data, tap_flags_t) { bluetooth_device_tapinfo_t *tapinfo = static_cast<bluetooth_device_tapinfo_t *>(tapinfo_ptr); BluetoothDeviceDialog *dialog = static_cast<BluetoothDeviceDialog *>(tapinfo->ui); bluetooth_device_tap_t *tap_device = static_cast<bluetooth_device_tap_t *>(const_cast<void *>(data)); QString bd_addr; QString bd_addr_oui; const gchar *manuf; QTableWidget *tableWidget; QTableWidgetItem *item; QString field; tableWidget = dialog->ui->tableWidget; if (!((!tap_device->is_local && tap_device->has_bd_addr) || (tap_device->is_local && tapinfo->is_local && tap_device->interface_id == tapinfo->interface_id && tap_device->adapter_id == tapinfo->adapter_id))) { return TAP_PACKET_REDRAW; } if (tap_device->has_bd_addr) { for (int i = 0; i < 6; ++i) { bd_addr += QString("%1:").arg(tap_device->bd_addr[i], 2, 16, QChar('0')); } bd_addr.chop(1); // remove extra character ":" from the end of the string if (!tap_device->is_local && bd_addr != tapinfo->bdAddr) return TAP_PACKET_REDRAW; manuf = get_ether_name(tap_device->bd_addr); if (manuf) { int pos; bd_addr_oui = QString(manuf); pos = static_cast<int>(bd_addr_oui.indexOf('_')); if (pos < 0) { manuf = NULL; } else { bd_addr_oui.remove(pos, bd_addr_oui.size()); } } if (!manuf) bd_addr_oui = ""; item = tableWidget->item(row_number_bd_addr, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, bd_addr, row_number_bd_addr, tapinfo->changes, pinfo); item->setText(bd_addr); item = tableWidget->item(row_number_bd_addr_oui, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, bd_addr_oui, row_number_bd_addr_oui, tapinfo->changes, pinfo); item->setText(bd_addr_oui); dialog->setTitle(bd_addr, tableWidget->item(row_number_name, column_number_value)->text()); } switch (tap_device->type) { case BLUETOOTH_DEVICE_LOCAL_ADAPTER: case BLUETOOTH_DEVICE_BD_ADDR: break; case BLUETOOTH_DEVICE_NAME: item = tableWidget->item(row_number_name, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, QString(tap_device->data.name), row_number_name, tapinfo->changes, pinfo); item->setText(tap_device->data.name); dialog->setTitle(tableWidget->item(row_number_bd_addr, column_number_value)->text(), tap_device->data.name); break; case BLUETOOTH_DEVICE_RESET: for (int i_row = 0; i_row < dialog->ui->tableWidget->rowCount(); i_row += 1) { bluetooth_item_data_t *item_data; item = dialog->ui->tableWidget->item(i_row, column_number_value); saveItemData(item, tap_device, pinfo); item_data = VariantPointer<bluetooth_item_data_t>::asPtr(item->data(Qt::UserRole)); if (item_data->changes > -1) { item_data->changes += 1; item_data->frame_number = pinfo->fd->num; dialog->ui->tableWidget->item(i_row, column_number_changes)->setText(QString::number(item_data->changes)); } else { item_data->changes = 0; } dialog->ui->tableWidget->item(i_row, column_number_value)->setText(""); } *tapinfo->changes += 1; break; case BLUETOOTH_DEVICE_SCAN: field = QString(val_to_str_const(tap_device->data.scan, bthci_cmd_scan_enable_values, "Unknown 0x%02x")); item = tableWidget->item(row_number_scan, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_scan, tapinfo->changes, pinfo); item->setText(field); break; case BLUETOOTH_DEVICE_LOCAL_VERSION: field = QString(val_to_str_const(tap_device->data.local_version.hci_version, bthci_evt_hci_version, "Unknown 0x%02x")); item = tableWidget->item(row_number_hci_version, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_hci_version, tapinfo->changes, pinfo); item->setText(field); field = QString::number(tap_device->data.local_version.hci_revision); item = tableWidget->item(row_number_hci_revision, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_hci_revision, tapinfo->changes, pinfo); item->setText(field); field = QString(val_to_str_const(tap_device->data.local_version.lmp_version, bthci_evt_lmp_version, "Unknown 0x%02x")); item = tableWidget->item(row_number_lmp_version, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_lmp_version, tapinfo->changes, pinfo); item->setText(field); field = QString(val_to_str_const(tap_device->data.local_version.lmp_version, bthci_evt_lmp_version, "Unknown 0x%02x")); item = tableWidget->item(row_number_lmp_version, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_lmp_version, tapinfo->changes, pinfo); item->setText(field); field = QString::number(tap_device->data.local_version.lmp_subversion); item = tableWidget->item(row_number_lmp_subversion, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_lmp_subversion, tapinfo->changes, pinfo); item->setText(field); field = QString(val_to_str_ext_const(tap_device->data.local_version.manufacturer, &bluetooth_company_id_vals_ext, "Unknown 0x%04x")); item = tableWidget->item(row_number_manufacturer, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_manufacturer, tapinfo->changes, pinfo); item->setText(field); break; case BLUETOOTH_DEVICE_REMOTE_VERSION: field = QString(val_to_str_const(tap_device->data.remote_version.lmp_version, bthci_evt_lmp_version, "Unknown 0x%02x")); item = tableWidget->item(row_number_lmp_version, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_lmp_version, tapinfo->changes, pinfo); item->setText(field); field = QString::number(tap_device->data.remote_version.lmp_subversion); item = tableWidget->item(row_number_lmp_subversion, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_lmp_subversion, tapinfo->changes, pinfo); item->setText(field); field = QString(val_to_str_ext_const(tap_device->data.remote_version.manufacturer, &bluetooth_company_id_vals_ext, "Unknown 0x%04x")); item = tableWidget->item(row_number_manufacturer, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_manufacturer, tapinfo->changes, pinfo); item->setText(field); break; case BLUETOOTH_DEVICE_VOICE_SETTING: field = QString("%1").arg(tap_device->data.voice_setting, 4, 16, QChar('0')); item = tableWidget->item(row_number_voice_setting, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_voice_setting, tapinfo->changes, pinfo); item->setText(field); break; case BLUETOOTH_DEVICE_CLASS_OF_DEVICE: field = QString("%1").arg(tap_device->data.class_of_device, 6, 16, QChar('0')); item = tableWidget->item(row_number_class_of_device, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_class_of_device, tapinfo->changes, pinfo); item->setText(field); break; case BLUETOOTH_DEVICE_AUTHENTICATION: field = QString(val_to_str_const(tap_device->data.authentication, bthci_cmd_authentication_enable_values, "Unknown 0x%02x")); item = tableWidget->item(row_number_authentication, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_authentication, tapinfo->changes, pinfo); item->setText(field); break; case BLUETOOTH_DEVICE_ENCRYPTION: field = QString(val_to_str_const(tap_device->data.encryption, bthci_cmd_encrypt_mode_vals, "Unknown 0x%02x")); item = tableWidget->item(row_number_encryption, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_encryption, tapinfo->changes, pinfo); item->setText(field); break; case BLUETOOTH_DEVICE_SIMPLE_PAIRING_MODE: field = QString(tap_device->data.encryption ? tr("enabled") : tr("disabled")); item = tableWidget->item(row_number_simple_pairing_mode, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_simple_pairing_mode, tapinfo->changes, pinfo); item->setText(field); break; case BLUETOOTH_DEVICE_PAGE_TIMEOUT: field = QString(tr("%1 ms (%2 slots)")).arg(tap_device->data.page_timeout * 0.625).arg(tap_device->data.page_timeout); item = tableWidget->item(row_number_page_timeout, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_page_timeout, tapinfo->changes, pinfo); item->setText(field); break; case BLUETOOTH_DEVICE_INQUIRY_MODE: field = QString(val_to_str_const(tap_device->data.inquiry_mode, bthci_cmd_inq_modes, "Unknown 0x%02x")); item = tableWidget->item(row_number_inquiry_mode, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_inquiry_mode, tapinfo->changes, pinfo); item->setText(field); break; case BLUETOOTH_DEVICE_MTUS: field = QString::number(tap_device->data.mtus.acl_mtu); item = tableWidget->item(row_number_acl_mtu, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_acl_mtu, tapinfo->changes, pinfo); item->setText(field); field = QString::number(tap_device->data.mtus.acl_packets); item = tableWidget->item(row_number_acl_packets, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_acl_packets, tapinfo->changes, pinfo); item->setText(field); field = QString::number(tap_device->data.mtus.sco_mtu); item = tableWidget->item(row_number_sco_mtu, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_sco_mtu, tapinfo->changes, pinfo); item->setText(field); field = QString::number(tap_device->data.mtus.sco_packets); item = tableWidget->item(row_number_sco_packets, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_sco_packets, tapinfo->changes, pinfo); item->setText(field); break; case BLUETOOTH_DEVICE_LE_MTU: field = QString::number(tap_device->data.le_mtus.acl_mtu); item = tableWidget->item(row_number_le_acl_mtu, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_le_acl_mtu, tapinfo->changes, pinfo); item->setText(field); field = QString::number(tap_device->data.le_mtus.acl_packets); item = tableWidget->item(row_number_le_acl_packets, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_le_acl_packets, tapinfo->changes, pinfo); item->setText(field); field = QString::number(tap_device->data.le_mtus.iso_mtu); item = tableWidget->item(row_number_le_iso_mtu, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_le_iso_mtu, tapinfo->changes, pinfo); item->setText(field); field = QString::number(tap_device->data.le_mtus.iso_packets); item = tableWidget->item(row_number_le_iso_packets, column_number_value); saveItemData(item, tap_device, pinfo); updateChanges(tableWidget, field, row_number_le_iso_packets, tapinfo->changes, pinfo); item->setText(field); break; } dialog->ui->hintLabel->setText(QString(tr("%1 changes")).arg(*tapinfo->changes)); return TAP_PACKET_REDRAW; } void BluetoothDeviceDialog::interfaceCurrentIndexChanged(int) { cap_file_.retapPackets(); } void BluetoothDeviceDialog::showInformationStepsChanged(int) { cap_file_.retapPackets(); } void BluetoothDeviceDialog::on_tableWidget_itemActivated(QTableWidgetItem *item) { if (!cap_file_.isValid()) return; if (!item->data(Qt::UserRole).isValid()) return; bluetooth_item_data_t *item_data = VariantPointer<bluetooth_item_data_t>::asPtr(item->data(Qt::UserRole)); emit goToPacket(item_data->frame_number); } void BluetoothDeviceDialog::on_actionSave_as_image_triggered() { QPixmap image; QString fileName = WiresharkFileDialog::getSaveFileName(this, tr("Save Table Image"), "bluetooth_device_table.png", tr("PNG Image (*.png)")); if (fileName.isEmpty()) return; image = ui->tableWidget->grab(); image.save(fileName, "PNG"); } void BluetoothDeviceDialog::on_buttonBox_clicked(QAbstractButton *) { }
C/C++
wireshark/ui/qt/bluetooth_device_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef BLUETOOTH_DEVICE_DIALOG_H #define BLUETOOTH_DEVICE_DIALOG_H #include "config.h" #include <glib.h> #include "wireshark_dialog.h" #include "cfile.h" #include "epan/tap.h" #include "epan/dissectors/packet-bluetooth.h" #include <QMenu> #include <QTableWidget> class QAbstractButton; class QPushButton; class QTreeWidgetItem; typedef struct _bluetooth_device_tapinfo_t { tap_reset_cb tap_reset; tap_packet_cb tap_packet; QString bdAddr; guint32 interface_id; guint32 adapter_id; gboolean is_local; void *ui; guint *changes; } bluetooth_device_tapinfo_t; typedef struct _bluetooth_item_data_t { guint32 interface_id; guint32 adapter_id; guint32 frame_number; gint changes; } bluetooth_item_data_t; namespace Ui { class BluetoothDeviceDialog; } class BluetoothDeviceDialog : public WiresharkDialog { Q_OBJECT public: explicit BluetoothDeviceDialog(QWidget &parent, CaptureFile &cf, QString bdAddr, QString name, guint32 interface_id, guint32 adapter_id, gboolean is_local); ~BluetoothDeviceDialog(); public slots: signals: void updateFilter(QString &filter, bool force = false); void captureFileChanged(capture_file *cf); void goToPacket(int packet_num); protected: void keyPressEvent(QKeyEvent *event); void captureFileClosing(); protected slots: void changeEvent(QEvent* event); private: Ui::BluetoothDeviceDialog *ui; bluetooth_device_tapinfo_t tapinfo_; QMenu context_menu_; guint changes_; static void tapReset(void *tapinfo_ptr); static tap_packet_status tapPacket(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *, const void *data, tap_flags_t flags); static void updateChanges(QTableWidget *tableWidget, QString value, const int row, guint *changes, packet_info *pinfo); static void saveItemData(QTableWidgetItem *item, bluetooth_device_tap_t *tap_device, packet_info *pinfo); private slots: void setTitle(QString bdAddr, QString name); void on_tableWidget_itemActivated(QTableWidgetItem *item); void on_buttonBox_clicked(QAbstractButton *button); void on_actionMark_Unmark_Cell_triggered(); void on_actionMark_Unmark_Row_triggered(); void on_actionCopy_Cell_triggered(); void on_actionCopy_Rows_triggered(); void on_actionCopy_All_triggered(); void on_actionSave_as_image_triggered(); void tableContextMenu(const QPoint &pos); void interfaceCurrentIndexChanged(int index); void showInformationStepsChanged(int state); }; #endif // BLUETOOTH_DEVICE_DIALOG_H
User Interface
wireshark/ui/qt/bluetooth_device_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>BluetoothDeviceDialog</class> <widget class="QDialog" name="BluetoothDeviceDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>544</width> <height>679</height> </rect> </property> <property name="baseSize"> <size> <width>0</width> <height>0</height> </size> </property> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="windowTitle"> <string>Bluetooth Device</string> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QTableWidget" name="tableWidget"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="horizontalScrollBarPolicy"> <enum>Qt::ScrollBarAsNeeded</enum> </property> <property name="editTriggers"> <set>QAbstractItemView::NoEditTriggers</set> </property> <property name="dragDropOverwriteMode"> <bool>false</bool> </property> <property name="verticalScrollMode"> <enum>QAbstractItemView::ScrollPerPixel</enum> </property> <property name="horizontalScrollMode"> <enum>QAbstractItemView::ScrollPerPixel</enum> </property> <property name="showGrid"> <bool>true</bool> </property> <property name="gridStyle"> <enum>Qt::SolidLine</enum> </property> <property name="sortingEnabled"> <bool>false</bool> </property> <attribute name="horizontalHeaderDefaultSectionSize"> <number>100</number> </attribute> <attribute name="horizontalHeaderHighlightSections"> <bool>true</bool> </attribute> <attribute name="horizontalHeaderShowSortIndicator" stdset="0"> <bool>false</bool> </attribute> <attribute name="horizontalHeaderStretchLastSection"> <bool>false</bool> </attribute> <attribute name="verticalHeaderCascadingSectionResizes"> <bool>false</bool> </attribute> <attribute name="verticalHeaderStretchLastSection"> <bool>false</bool> </attribute> <row> <property name="text"> <string>BD_ADDR</string> </property> </row> <row> <property name="text"> <string>OUI</string> </property> </row> <row> <property name="text"> <string>Name</string> </property> </row> <row> <property name="text"> <string>Class of Device</string> </property> </row> <row> <property name="text"> <string>LMP Version</string> </property> </row> <row> <property name="text"> <string>LMP Subversion</string> </property> </row> <row> <property name="text"> <string>Manufacturer</string> </property> </row> <row> <property name="text"> <string>HCI Version</string> </property> </row> <row> <property name="text"> <string>HCI Revision</string> </property> </row> <row> <property name="text"> <string>Scan</string> </property> </row> <row> <property name="text"> <string>Authentication</string> </property> </row> <row> <property name="text"> <string>Encryption</string> </property> </row> <row> <property name="text"> <string>ACL MTU</string> </property> </row> <row> <property name="text"> <string>ACL Total Packets</string> </property> </row> <row> <property name="text"> <string>SCO MTU</string> </property> </row> <row> <property name="text"> <string>SCO Total Packets</string> </property> </row> <row> <property name="text"> <string>LE ACL MTU</string> </property> </row> <row> <property name="text"> <string>LE ACL Total Packets</string> </property> </row> <row> <property name="text"> <string>LE ISO MTU</string> </property> </row> <row> <property name="text"> <string>LE ISO Total Packets</string> </property> </row> <row> <property name="text"> <string>Inquiry Mode</string> </property> </row> <row> <property name="text"> <string>Page Timeout</string> </property> </row> <row> <property name="text"> <string>Simple Pairing Mode</string> </property> </row> <row> <property name="text"> <string>Voice Setting</string> </property> </row> <column> <property name="text"> <string>Value</string> </property> </column> <column> <property name="text"> <string>Changes</string> </property> </column> <item row="0" column="1"> <property name="text"> <string/> </property> </item> </widget> </item> <item> <widget class="QLabel" name="hintLabel"> <property name="text"> <string>%1 changes</string> </property> </widget> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Close</set> </property> </widget> </item> </layout> <action name="actionCopy_Cell"> <property name="text"> <string>Copy Cell</string> </property> </action> <action name="actionCopy_Rows"> <property name="text"> <string>Copy Rows</string> </property> </action> <action name="actionCopy_All"> <property name="text"> <string>Copy All</string> </property> </action> <action name="actionSave_as_image"> <property name="text"> <string>Save as image</string> </property> </action> <action name="actionMark_Unmark_Row"> <property name="text"> <string>Mark/Unmark Row</string> </property> <property name="toolTip"> <string>Mark/Unmark Row</string> </property> <property name="shortcut"> <string>Ctrl+M</string> </property> </action> <action name="actionMark_Unmark_Cell"> <property name="text"> <string>Mark/Unmark Cell</string> </property> </action> </widget> <resources/> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>BluetoothDeviceDialog</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>374</x> <y>407</y> </hint> <hint type="destinationlabel"> <x>374</x> <y>214</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>BluetoothDeviceDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>374</x> <y>407</y> </hint> <hint type="destinationlabel"> <x>374</x> <y>214</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/bluetooth_hci_summary_dialog.cpp
/* bluetooth_hci_summary_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "bluetooth_hci_summary_dialog.h" #include <ui_bluetooth_hci_summary_dialog.h> #include "bluetooth_device_dialog.h" #include <ui/qt/utils/color_utils.h> #include "epan/epan.h" #include "epan/addr_resolv.h" #include "epan/to_str.h" #include "epan/epan_dissect.h" #include "epan/prefs.h" #include "epan/dissectors/packet-bluetooth.h" #include "epan/dissectors/packet-bthci_cmd.h" #include "epan/dissectors/packet-bthci_evt.h" #include <ui/qt/utils/variant_pointer.h> #include "ui/simple_dialog.h" #include "ui/qt/widgets/wireshark_file_dialog.h" #include <QClipboard> #include <QContextMenuEvent> #include <QPushButton> #include <QTreeWidget> static const int column_number_name = 0; static const int column_number_ogf = 1; static const int column_number_ocf = 2; static const int column_number_opcode = 3; static const int column_number_event = 4; static const int column_number_subevent = 5; static const int column_number_status = 6; static const int column_number_reason = 7; static const int column_number_hardware_error = 8; static const int column_number_occurrence = 9; static tap_packet_status bluetooth_hci_summary_tap_packet(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *edt, const void* data, tap_flags_t flags) { bluetooth_hci_summary_tapinfo_t *tapinfo = (bluetooth_hci_summary_tapinfo_t *) tapinfo_ptr; if (tapinfo->tap_packet) tapinfo->tap_packet(tapinfo, pinfo, edt, data, flags); return TAP_PACKET_REDRAW; } static void bluetooth_hci_summary_tap_reset(void *tapinfo_ptr) { bluetooth_hci_summary_tapinfo_t *tapinfo = (bluetooth_hci_summary_tapinfo_t *) tapinfo_ptr; if (tapinfo->tap_reset) tapinfo->tap_reset(tapinfo); } static void bluetooth_hci_summary_tap_init(void *data) { GString *error_string; error_string = register_tap_listener("bluetooth.hci_summary", data, NULL, 0, bluetooth_hci_summary_tap_reset, bluetooth_hci_summary_tap_packet, NULL, NULL ); if (error_string != NULL) { simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", error_string->str); g_string_free(error_string, TRUE); } } BluetoothHciSummaryDialog::BluetoothHciSummaryDialog(QWidget &parent, CaptureFile &cf) : WiresharkDialog(parent, cf), ui(new Ui::BluetoothHciSummaryDialog) { ui->setupUi(this); loadGeometry(parent.width() * 4 / 5, parent.height() * 2 / 3); connect(ui->tableTreeWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(tableContextMenu(const QPoint &))); connect(ui->tableTreeWidget, SIGNAL(itemExpanded(QTreeWidgetItem *)), this, SLOT(tableItemExpanded(QTreeWidgetItem *))); connect(ui->tableTreeWidget, SIGNAL(itemCollapsed(QTreeWidgetItem *)), this, SLOT(tableItemCollapsed(QTreeWidgetItem *))); connect(ui->interfaceComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(interfaceCurrentIndexChanged(int))); connect(ui->adapterComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(adapterCurrentIndexChanged(int))); connect(ui->displayFilterLineEdit, SIGNAL(returnPressed()), this, SLOT(displayFilterLineEditAccepted())); connect(ui->resultsFilterLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(resultsFilterLineEditChanged(const QString &))); for (int i = 0; i < ui->tableTreeWidget->columnCount(); i++) { ui->tableTreeWidget->resizeColumnToContents(i); } ui->tableTreeWidget->setStyleSheet("QTreeView::item:hover{background-color:lightyellow; color:black;}"); context_menu_.addActions(QList<QAction *>() << ui->actionMark_Unmark_Cell); context_menu_.addActions(QList<QAction *>() << ui->actionMark_Unmark_Row); context_menu_.addActions(QList<QAction *>() << ui->actionCopy_Cell); context_menu_.addActions(QList<QAction *>() << ui->actionCopy_Rows); context_menu_.addActions(QList<QAction *>() << ui->actionCopy_All); context_menu_.addActions(QList<QAction *>() << ui->actionSave_as_image); tapinfo_.tap_packet = tapPacket; tapinfo_.tap_reset = tapReset; tapinfo_.ui = this; item_link_control_ = ui->tableTreeWidget->topLevelItem(0); item_link_policy_ = ui->tableTreeWidget->topLevelItem(1); item_controller_and_baseband_ = ui->tableTreeWidget->topLevelItem(2); item_informational_ = ui->tableTreeWidget->topLevelItem(3); item_status_parameters_ = ui->tableTreeWidget->topLevelItem(4); item_testing_ = ui->tableTreeWidget->topLevelItem(5); item_low_energy_ = ui->tableTreeWidget->topLevelItem(6); item_logo_testing_ = ui->tableTreeWidget->topLevelItem(7); item_vendor_ = ui->tableTreeWidget->topLevelItem(8); item_unknown_ogf_ = ui->tableTreeWidget->topLevelItem(9); item_events_ = ui->tableTreeWidget->topLevelItem(10); item_status_ = ui->tableTreeWidget->topLevelItem(11); item_reason_ = ui->tableTreeWidget->topLevelItem(12); item_hardware_errors_ = ui->tableTreeWidget->topLevelItem(13); bluetooth_hci_summary_tap_init(&tapinfo_); cap_file_.retapPackets(); } BluetoothHciSummaryDialog::~BluetoothHciSummaryDialog() { delete ui; remove_tap_listener(&tapinfo_); } void BluetoothHciSummaryDialog::captureFileClosing() { remove_tap_listener(&tapinfo_); WiresharkDialog::captureFileClosing(); } void BluetoothHciSummaryDialog::captureFileClosed() { ui->interfaceComboBox->setEnabled(FALSE); ui->adapterComboBox->setEnabled(FALSE); WiresharkDialog::captureFileClosed(); } void BluetoothHciSummaryDialog::changeEvent(QEvent *event) { if (0 != event) { switch (event->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } QDialog::changeEvent(event); } void BluetoothHciSummaryDialog::keyPressEvent(QKeyEvent *event) { /* NOTE: Do nothing*, but in real it "takes focus" from button_box so allow user * to use Enter button to jump to frame from tree widget */ /* * - reimplement shortcuts from contex menu */ if (event->modifiers() & Qt::ControlModifier && event->key()== Qt::Key_M) on_actionMark_Unmark_Row_triggered(); } void BluetoothHciSummaryDialog::tableContextMenu(const QPoint &pos) { context_menu_.popup(ui->tableTreeWidget->viewport()->mapToGlobal(pos)); } void BluetoothHciSummaryDialog::tableItemExpanded(QTreeWidgetItem *) { for (int i = 0; i < ui->tableTreeWidget->columnCount(); i++) { ui->tableTreeWidget->resizeColumnToContents(i); } } void BluetoothHciSummaryDialog::tableItemCollapsed(QTreeWidgetItem *) { for (int i = 0; i < ui->tableTreeWidget->columnCount(); i++) { ui->tableTreeWidget->resizeColumnToContents(i); } } void BluetoothHciSummaryDialog::on_actionMark_Unmark_Cell_triggered() { QBrush fg; QBrush bg; if (ui->tableTreeWidget->currentItem()->background(ui->tableTreeWidget->currentColumn()) == QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg))) { fg = QBrush(); bg = QBrush(); } else { fg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_fg)); bg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg)); } ui->tableTreeWidget->currentItem()->setForeground(ui->tableTreeWidget->currentColumn(), fg); ui->tableTreeWidget->currentItem()->setBackground(ui->tableTreeWidget->currentColumn(), bg); } void BluetoothHciSummaryDialog::on_actionMark_Unmark_Row_triggered() { QBrush fg; QBrush bg; bool is_marked = TRUE; for (int i = 0; i < ui->tableTreeWidget->columnCount(); i += 1) { if (ui->tableTreeWidget->currentItem()->background(i) != QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg))) is_marked = FALSE; } if (is_marked) { fg = QBrush(); bg = QBrush(); } else { fg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_fg)); bg = QBrush(ColorUtils::fromColorT(&prefs.gui_marked_bg)); } for (int i = 0; i < ui->tableTreeWidget->columnCount(); i += 1) { ui->tableTreeWidget->currentItem()->setForeground(i, fg); ui->tableTreeWidget->currentItem()->setBackground(i, bg); } } void BluetoothHciSummaryDialog::on_actionCopy_Cell_triggered() { QClipboard *clipboard = QApplication::clipboard(); QString copy; copy = QString(ui->tableTreeWidget->currentItem()->text(ui->tableTreeWidget->currentColumn())); clipboard->setText(copy); } void BluetoothHciSummaryDialog::on_actionCopy_Rows_triggered() { QClipboard *clipboard = QApplication::clipboard(); QString copy; QList<QTreeWidgetItem *> items; QList<QTreeWidgetItem *>::iterator i_item; items = ui->tableTreeWidget->selectedItems(); for (i_item = items.begin(); i_item != items.end(); ++i_item) { copy += QString("%1 %2 %3 %4 %5 %6 %7 %8 %9\n") .arg((*i_item)->text(column_number_name), -60) .arg((*i_item)->text(column_number_ogf), -10) .arg((*i_item)->text(column_number_ocf), -10) .arg((*i_item)->text(column_number_opcode), -10) .arg((*i_item)->text(column_number_event), -10) .arg((*i_item)->text(column_number_subevent), -10) .arg((*i_item)->text(column_number_status), -10) .arg((*i_item)->text(column_number_reason), -10) .arg((*i_item)->text(column_number_hardware_error), -15) .arg((*i_item)->text(column_number_occurrence), -10); } clipboard->setText(copy); } void BluetoothHciSummaryDialog::tapReset(void *tapinfo_ptr) { bluetooth_hci_summary_tapinfo_t *tapinfo = (bluetooth_hci_summary_tapinfo_t *) tapinfo_ptr; BluetoothHciSummaryDialog *dialog = static_cast<BluetoothHciSummaryDialog *>(tapinfo->ui); dialog->item_link_control_->takeChildren(); dialog->item_link_control_->setText(column_number_occurrence, "0"); dialog->item_link_policy_->takeChildren(); dialog->item_link_policy_->setText(column_number_occurrence, "0"); dialog->item_controller_and_baseband_->takeChildren(); dialog->item_controller_and_baseband_->setText(column_number_occurrence, "0"); dialog->item_informational_->takeChildren(); dialog->item_informational_->setText(column_number_occurrence, "0"); dialog->item_status_parameters_->takeChildren(); dialog->item_status_parameters_->setText(column_number_occurrence, "0"); dialog->item_testing_->takeChildren(); dialog->item_testing_->setText(column_number_occurrence, "0"); dialog->item_low_energy_->takeChildren(); dialog->item_low_energy_->setText(column_number_occurrence, "0"); dialog->item_logo_testing_->takeChildren(); dialog->item_logo_testing_->setText(column_number_occurrence, "0"); dialog->item_vendor_->takeChildren(); dialog->item_vendor_->setText(column_number_occurrence, "0"); dialog->item_unknown_ogf_->takeChildren(); dialog->item_unknown_ogf_->setText(column_number_occurrence, "0"); dialog->item_events_->takeChildren(); dialog->item_events_->setText(column_number_occurrence, "0"); dialog->item_status_->takeChildren(); dialog->item_status_->setText(column_number_occurrence, "0"); dialog->item_reason_->takeChildren(); dialog->item_reason_->setText(column_number_occurrence, "0"); dialog->item_hardware_errors_->takeChildren(); dialog->item_hardware_errors_->setText(column_number_occurrence, "0"); } tap_packet_status BluetoothHciSummaryDialog::tapPacket(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *, const void *data, tap_flags_t) { bluetooth_hci_summary_tapinfo_t *tapinfo = static_cast<bluetooth_hci_summary_tapinfo_t *>(tapinfo_ptr); BluetoothHciSummaryDialog *dialog = static_cast<BluetoothHciSummaryDialog *>(tapinfo->ui); bluetooth_hci_summary_tap_t *tap_hci = static_cast<bluetooth_hci_summary_tap_t *>(const_cast<void *>(data)); QTreeWidgetItem *main_item = NULL; QTreeWidgetItem *item = NULL; QTreeWidgetItem *frame_item = NULL; QTreeWidgetItem *meta_item = NULL; bluetooth_item_data_t *item_data = NULL; QString adapter; QString name; if (dialog->file_closed_) return TAP_PACKET_DONT_REDRAW; if (pinfo->rec->rec_type != REC_TYPE_PACKET) return TAP_PACKET_DONT_REDRAW; name = tr("Unknown"); if (pinfo->rec->presence_flags & WTAP_HAS_INTERFACE_ID) { gchar *interface; const char *interface_name; interface_name = epan_get_interface_name(pinfo->epan, pinfo->rec->rec_header.packet_header.interface_id); interface = wmem_strdup_printf(pinfo->pool, "%u: %s", pinfo->rec->rec_header.packet_header.interface_id, interface_name); if (dialog->ui->interfaceComboBox->findText(interface) == -1) dialog->ui->interfaceComboBox->addItem(interface); if (interface && dialog->ui->interfaceComboBox->currentIndex() > 0) { if (dialog->ui->interfaceComboBox->currentText() != interface) return TAP_PACKET_REDRAW; } } adapter = QString(tr("Adapter %1")).arg(tap_hci->adapter_id); if (dialog->ui->adapterComboBox->findText(adapter) == -1) { dialog->ui->adapterComboBox->addItem(adapter); } if (dialog->ui->adapterComboBox->currentIndex() > 0) { if (dialog->ui->adapterComboBox->currentText() != adapter) return TAP_PACKET_REDRAW; } switch (tap_hci->type) { case BLUETOOTH_HCI_SUMMARY_OPCODE: case BLUETOOTH_HCI_SUMMARY_EVENT_OPCODE: case BLUETOOTH_HCI_SUMMARY_VENDOR_OPCODE: case BLUETOOTH_HCI_SUMMARY_VENDOR_EVENT_OPCODE: switch (tap_hci->ogf) { case HCI_OGF_LINK_CONTROL: main_item = dialog->item_link_control_; break; case HCI_OGF_LINK_POLICY: main_item = dialog->item_link_policy_; break; case HCI_OGF_HOST_CONTROLLER: main_item = dialog->item_controller_and_baseband_; break; case HCI_OGF_INFORMATIONAL: main_item = dialog->item_informational_; break; case HCI_OGF_STATUS: main_item = dialog->item_status_parameters_; break; case HCI_OGF_TESTING: main_item = dialog->item_testing_; break; case HCI_OGF_LOW_ENERGY: main_item = dialog->item_low_energy_; break; case HCI_OGF_LOGO_TESTING: main_item = dialog->item_logo_testing_; break; case HCI_OGF_VENDOR_SPECIFIC: main_item = dialog->item_vendor_; break; default: main_item = dialog->item_unknown_ogf_; } for (int i_item = 0; i_item < main_item->childCount(); i_item +=1) { if (main_item->child(i_item)->text(column_number_opcode) == QString("0x%1").arg(tap_hci->ogf << 10 | tap_hci->ocf, 4, 16, QChar('0'))) { item = main_item->child(i_item); if (tap_hci->type == BLUETOOTH_HCI_SUMMARY_VENDOR_OPCODE && tap_hci->name) { item->setText(column_number_name, tap_hci->name); item->setText(column_number_occurrence, QString::number(item->text(column_number_occurrence).toInt() - 1)); } break; } } if (!item) { item = new QTreeWidgetItem(); if (tap_hci->name) name = tap_hci->name; item->setText(column_number_name, name); item->setText(column_number_ogf, QString("0x%1").arg(tap_hci->ogf, 2, 16, QChar('0'))); item->setText(column_number_ocf, QString("0x%1").arg(tap_hci->ocf, 4, 16, QChar('0'))); item->setText(column_number_opcode, QString("0x%1").arg(tap_hci->ogf << 10 | tap_hci->ocf, 4, 16, QChar('0'))); if (tap_hci->type == BLUETOOTH_HCI_SUMMARY_OPCODE) item->setText(column_number_occurrence, "0"); else item->setText(column_number_occurrence, "1"); main_item->addChild(item); item->setHidden(!name.contains(dialog->ui->resultsFilterLineEdit->text(), Qt::CaseInsensitive)); main_item->sortChildren(column_number_opcode, Qt::AscendingOrder); main_item->setText(column_number_occurrence, QString::number(main_item->text(column_number_occurrence).toInt() + 1)); } if (tap_hci->type != BLUETOOTH_HCI_SUMMARY_EVENT_OPCODE && tap_hci->type != BLUETOOTH_HCI_SUMMARY_VENDOR_EVENT_OPCODE) item->setText(column_number_occurrence, QString::number(item->text(column_number_occurrence).toInt() + 1)); /* I believe bthci_cmd/bthci_evt already add frame item */ if (tap_hci->type == BLUETOOTH_HCI_SUMMARY_VENDOR_OPCODE || tap_hci->type == BLUETOOTH_HCI_SUMMARY_VENDOR_EVENT_OPCODE) break; frame_item = new QTreeWidgetItem(); frame_item->setText(column_number_name, QString(tr("Frame %1")).arg(pinfo->num)); frame_item->setText(column_number_ogf, QString("0x%1").arg(tap_hci->ogf, 2, 16, QChar('0'))); frame_item->setText(column_number_ocf, QString("0x%1").arg(tap_hci->ocf, 4, 16, QChar('0'))); frame_item->setText(column_number_opcode, QString("0x%1") .arg(tap_hci->ogf << 10 | tap_hci->ocf, 4, 16, QChar('0'))); if (tap_hci->type == BLUETOOTH_HCI_SUMMARY_EVENT_OPCODE) frame_item->setText(column_number_event, QString("0x%1").arg(tap_hci->event, 2, 16, QChar('0'))); item->addChild(frame_item); item_data = wmem_new(wmem_file_scope(), bluetooth_item_data_t); item_data->interface_id = tap_hci->interface_id; item_data->adapter_id = tap_hci->adapter_id; item_data->frame_number = pinfo->num; frame_item->setData(0, Qt::UserRole, VariantPointer<bluetooth_item_data_t>::asQVariant(item_data)); break; case BLUETOOTH_HCI_SUMMARY_EVENT: case BLUETOOTH_HCI_SUMMARY_VENDOR_EVENT: main_item = dialog->item_events_; for (int i_item = 0; i_item < main_item->childCount(); i_item +=1) { if (main_item->child(i_item)->text(column_number_event) == QString("0x%1").arg(tap_hci->event, 2, 16, QChar('0'))) { item = main_item->child(i_item); if (tap_hci->type == BLUETOOTH_HCI_SUMMARY_VENDOR_EVENT && tap_hci->name) item->setText(column_number_name, tap_hci->name); break; } } if (!item) { item = new QTreeWidgetItem(); if (tap_hci->name) name = tap_hci->name; item->setText(column_number_name, name); item->setText(column_number_event, QString("0x%1").arg(tap_hci->event, 2, 16, QChar('0'))); item->setText(column_number_occurrence, QString::number(0)); main_item->addChild(item); item->setHidden(!name.contains(dialog->ui->resultsFilterLineEdit->text(), Qt::CaseInsensitive)); main_item->sortChildren(column_number_event, Qt::AscendingOrder); main_item->setText(column_number_occurrence, QString::number(main_item->text(column_number_occurrence).toInt() + 1)); } /* I believe bthci_cmd/bthci_evt already add frame item */ if (tap_hci->type == BLUETOOTH_HCI_SUMMARY_VENDOR_EVENT) break; if (tap_hci->event == 0x3E) { /* LE Meta */ int i_item; for (i_item = 0; i_item < item->childCount(); i_item +=1) { if (item->child(i_item)->text(column_number_name) != QString(tr("Unknown"))) continue; } if (i_item >= item->childCount()) { frame_item = new QTreeWidgetItem(); frame_item->setText(column_number_name, QString(tr("Unknown"))); frame_item->setText(column_number_occurrence, QString::number(1)); item->addChild(frame_item); item->setText(column_number_occurrence, QString::number(item->text(column_number_occurrence).toInt() + 1)); item = frame_item; } else { item = item->child(i_item); item->setText(column_number_occurrence, QString::number(item->text(column_number_occurrence).toInt() + 1)); } } else { item->setText(column_number_occurrence, QString::number(item->text(column_number_occurrence).toInt() + 1)); } frame_item = new QTreeWidgetItem(); frame_item->setText(column_number_name, QString(tr("Frame %1")).arg(pinfo->num)); frame_item->setText(column_number_event, QString("0x%1").arg(tap_hci->event, 2, 16, QChar('0'))); item->addChild(frame_item); item_data = wmem_new(wmem_file_scope(), bluetooth_item_data_t); item_data->interface_id = tap_hci->interface_id; item_data->adapter_id = tap_hci->adapter_id; item_data->frame_number = pinfo->num; frame_item->setData(0, Qt::UserRole, VariantPointer<bluetooth_item_data_t>::asQVariant(item_data)); break; case BLUETOOTH_HCI_SUMMARY_SUBEVENT: main_item = dialog->item_events_; meta_item = NULL; for (int i_item = 0; i_item < main_item->childCount(); i_item +=1) { if (main_item->child(i_item)->text(column_number_event) != QString("0x%1").arg(tap_hci->event, 2, 16, QChar('0'))) { continue; } meta_item = main_item->child(i_item); break; } if (meta_item == NULL) break; item = NULL; for (int i_item = 0; i_item < meta_item->childCount(); i_item +=1) { if (meta_item->child(i_item)->text(column_number_subevent) != QString("0x%1").arg(tap_hci->subevent, 2, 16, QChar('0'))) { continue; } item = meta_item->child(i_item); item->setText(column_number_occurrence, QString::number(item->text(column_number_occurrence).toInt() + 1)); break; } if (item == NULL) { item = new QTreeWidgetItem(); item->setText(column_number_name, tap_hci->name); item->setText(column_number_subevent, QString("0x%1").arg(tap_hci->subevent, 2, 16, QChar('0'))); item->setText(column_number_occurrence, QString::number(1)); meta_item->addChild(item); meta_item->setText(column_number_occurrence, QString::number(meta_item->text(column_number_occurrence).toInt() + 1)); meta_item->sortChildren(column_number_subevent, Qt::AscendingOrder); } frame_item = new QTreeWidgetItem(); frame_item->setText(column_number_name, QString(tr("Frame %1")).arg(pinfo->num)); frame_item->setText(column_number_event, QString("0x%1").arg(tap_hci->event, 2, 16, QChar('0'))); frame_item->setText(column_number_subevent, QString("0x%1").arg(tap_hci->subevent, 2, 16, QChar('0'))); item_data = wmem_new(wmem_file_scope(), bluetooth_item_data_t); item_data->interface_id = tap_hci->interface_id; item_data->adapter_id = tap_hci->adapter_id; item_data->frame_number = pinfo->num; frame_item->setData(0, Qt::UserRole, VariantPointer<bluetooth_item_data_t>::asQVariant(item_data)); item->addChild(frame_item); /* Remove item that is known now */ for (int i_item = 0; i_item < meta_item->childCount(); i_item +=1) { if (meta_item->child(i_item)->text(column_number_name) != QString(tr("Unknown"))) continue; item = meta_item->child(i_item); for (int ii_item = 0; ii_item < item->childCount(); ii_item +=1) { if (item->child(ii_item)->text(column_number_name) != QString(tr("Frame %1")).arg(pinfo->num)) continue; delete item->child(ii_item); item->setText(column_number_occurrence, QString::number(item->text(column_number_occurrence).toInt() - 1)); if (item->childCount() == 0) { delete item; meta_item->setText(column_number_occurrence, QString::number(meta_item->text(column_number_occurrence).toInt() - 1)); } break; } break; } break; case BLUETOOTH_HCI_SUMMARY_STATUS: main_item = dialog->item_status_; for (int i_item = 0; i_item < main_item->childCount(); i_item +=1) { if (main_item->child(i_item)->text(column_number_status) == QString("0x%1").arg(tap_hci->status, 2, 16, QChar('0'))) { item = main_item->child(i_item); break; } } if (!item) { if (tap_hci->name) name = tap_hci->name; item = new QTreeWidgetItem(); item->setText(column_number_name, name); item->setText(column_number_status, QString("0x%1").arg(tap_hci->status, 2, 16, QChar('0'))); main_item->addChild(item); item->setHidden(!name.contains(dialog->ui->resultsFilterLineEdit->text(), Qt::CaseInsensitive)); main_item->sortChildren(column_number_event, Qt::AscendingOrder); main_item->setText(column_number_occurrence, QString::number(main_item->text(column_number_occurrence).toInt() + 1)); } item->setText(column_number_occurrence, QString::number(item->text(column_number_occurrence).toInt() + 1)); frame_item = new QTreeWidgetItem(); frame_item->setText(column_number_name, QString(tr("Frame %1")).arg(pinfo->num)); frame_item->setText(column_number_status, QString("0x%1").arg(tap_hci->status, 2, 16, QChar('0'))); item->addChild(frame_item); item_data = wmem_new(wmem_file_scope(), bluetooth_item_data_t); item_data->interface_id = tap_hci->interface_id; item_data->adapter_id = tap_hci->adapter_id; item_data->frame_number = pinfo->num; frame_item->setData(0, Qt::UserRole, VariantPointer<bluetooth_item_data_t>::asQVariant(item_data)); break; case BLUETOOTH_HCI_SUMMARY_STATUS_PENDING: main_item = dialog->item_status_; for (int i_item = 0; i_item < main_item->childCount(); i_item +=1) { if (main_item->child(i_item)->text(column_number_status) == QString::number(tap_hci->status)) { item = main_item->child(i_item); break; } } if (!item) { item = new QTreeWidgetItem(); item->setText(column_number_name, tr("Pending")); item->setText(column_number_status, QString::number(tap_hci->status)); main_item->addChild(item); item->setHidden(!name.contains(dialog->ui->resultsFilterLineEdit->text(), Qt::CaseInsensitive)); main_item->sortChildren(column_number_event, Qt::AscendingOrder); main_item->setText(column_number_occurrence, QString::number(main_item->text(column_number_occurrence).toInt() + 1)); } item->setText(column_number_occurrence, QString::number(item->text(column_number_occurrence).toInt() + 1)); frame_item = new QTreeWidgetItem(); frame_item->setText(column_number_name, QString(tr("Frame %1")).arg(pinfo->num)); frame_item->setText(column_number_status, QString::number(tap_hci->status)); item->addChild(frame_item); item_data = wmem_new(wmem_file_scope(), bluetooth_item_data_t); item_data->interface_id = tap_hci->interface_id; item_data->adapter_id = tap_hci->adapter_id; item_data->frame_number = pinfo->num; frame_item->setData(0, Qt::UserRole, VariantPointer<bluetooth_item_data_t>::asQVariant(item_data)); break; case BLUETOOTH_HCI_SUMMARY_REASON: main_item = dialog->item_reason_; for (int i_item = 0; i_item < main_item->childCount(); i_item +=1) { if (main_item->child(i_item)->text(column_number_reason) == QString("0x%1").arg(tap_hci->reason, 2, 16, QChar('0'))) { item = main_item->child(i_item); break; } } if (!item) { if (tap_hci->name) name = tap_hci->name; item = new QTreeWidgetItem(); item->setText(column_number_name, name); item->setText(column_number_reason, QString("0x%1").arg(tap_hci->reason, 2, 16, QChar('0'))); main_item->addChild(item); item->setHidden(!name.contains(dialog->ui->resultsFilterLineEdit->text(), Qt::CaseInsensitive)); main_item->sortChildren(column_number_event, Qt::AscendingOrder); main_item->setText(column_number_occurrence, QString::number(main_item->text(column_number_occurrence).toInt() + 1)); } item->setText(column_number_occurrence, QString::number(item->text(column_number_occurrence).toInt() + 1)); frame_item = new QTreeWidgetItem(); frame_item->setText(column_number_name, QString(tr("Frame %1")).arg(pinfo->num)); frame_item->setText(column_number_reason, QString("0x%1").arg(tap_hci->reason, 2, 16, QChar('0'))); item->addChild(frame_item); item_data = wmem_new(wmem_file_scope(), bluetooth_item_data_t); item_data->interface_id = tap_hci->interface_id; item_data->adapter_id = tap_hci->adapter_id; item_data->frame_number = pinfo->num; frame_item->setData(0, Qt::UserRole, VariantPointer<bluetooth_item_data_t>::asQVariant(item_data)); break; case BLUETOOTH_HCI_SUMMARY_HARDWARE_ERROR: main_item = dialog->item_hardware_errors_; for (int i_item = 0; i_item < main_item->childCount(); i_item +=1) { if (main_item->child(i_item)->text(column_number_hardware_error) == QString("0x%1").arg(tap_hci->hardware_error, 2, 16, QChar('0'))) { item = main_item->child(i_item); break; } } if (!item) { item = new QTreeWidgetItem(); const QString error = QString("0x%1").arg(tap_hci->hardware_error, 2, 16, QChar('0')); item->setText(column_number_name, QString("Hardware error %1").arg(error)); item->setText(column_number_hardware_error, error); main_item->addChild(item); item->setHidden(!name.contains(dialog->ui->resultsFilterLineEdit->text(), Qt::CaseInsensitive)); main_item->sortChildren(column_number_event, Qt::AscendingOrder); main_item->setText(column_number_occurrence, QString::number(main_item->text(column_number_occurrence).toInt() + 1)); } item->setText(column_number_occurrence, QString::number(item->text(column_number_occurrence).toInt() + 1)); frame_item = new QTreeWidgetItem(); frame_item->setText(column_number_name, QString(tr("Frame %1")).arg(pinfo->num)); frame_item->setText(column_number_hardware_error, QString("0x%1").arg(tap_hci->hardware_error, 2, 16, QChar('0'))); item->addChild(frame_item); item_data = wmem_new(wmem_file_scope(), bluetooth_item_data_t); item_data->interface_id = tap_hci->interface_id; item_data->adapter_id = tap_hci->adapter_id; item_data->frame_number = pinfo->num; frame_item->setData(0, Qt::UserRole, VariantPointer<bluetooth_item_data_t>::asQVariant(item_data)); break; } for (int i = 0; i < dialog->ui->tableTreeWidget->columnCount(); i++) { dialog->ui->tableTreeWidget->resizeColumnToContents(i); } return TAP_PACKET_REDRAW; } void BluetoothHciSummaryDialog::interfaceCurrentIndexChanged(int) { cap_file_.retapPackets(); } void BluetoothHciSummaryDialog::adapterCurrentIndexChanged(int) { cap_file_.retapPackets(); } void BluetoothHciSummaryDialog::on_tableTreeWidget_itemActivated(QTreeWidgetItem *item, int) { if (file_closed_) return; bluetooth_item_data_t *item_data = VariantPointer<bluetooth_item_data_t>::asPtr(item->data(0, Qt::UserRole)); if (item_data) emit goToPacket(item_data->frame_number); } void BluetoothHciSummaryDialog::recursiveCopyTreeItems(QTreeWidgetItem *item, QString &copy, int ident_level) { QTreeWidgetItem *child_item; if (!item->isExpanded()) return; for (int i_item = 0; i_item < item->childCount(); i_item += 1) { child_item = item->child(i_item); copy.append(QString(" ").repeated(ident_level)); copy += QString("%1 %2 %3 %4 %5 %6 %7 %8 %9\n") .arg(child_item->text(column_number_name), -60 + 4 * ident_level) .arg(child_item->text(column_number_ogf), -10) .arg(child_item->text(column_number_ocf), -10) .arg(child_item->text(column_number_opcode), -10) .arg(child_item->text(column_number_event), -10) .arg(child_item->text(column_number_subevent), -10) .arg(child_item->text(column_number_status), -10) .arg(child_item->text(column_number_reason), -10) .arg(child_item->text(column_number_hardware_error), -15) .arg(child_item->text(column_number_occurrence), -10); recursiveCopyTreeItems(child_item, copy, ident_level + 1); } } void BluetoothHciSummaryDialog::on_actionCopy_All_triggered() { QClipboard *clipboard = QApplication::clipboard(); QString copy; QTreeWidgetItem *item; item = ui->tableTreeWidget->headerItem(); copy += QString("%1 %2 %3 %4 %5 %6 %7 %8 %9 %10\n") .arg(item->text(column_number_name), -60) .arg(item->text(column_number_ogf), -10) .arg(item->text(column_number_ocf), -10) .arg(item->text(column_number_opcode), -10) .arg(item->text(column_number_event), -10) .arg(item->text(column_number_subevent), -10) .arg(item->text(column_number_status), -10) .arg(item->text(column_number_reason), -10) .arg(item->text(column_number_hardware_error), -15) .arg(item->text(column_number_occurrence), -10); for (int i_item = 0; i_item < ui->tableTreeWidget->topLevelItemCount(); ++i_item) { item = ui->tableTreeWidget->topLevelItem(i_item); copy += QString("%1 %2 %3 %4 %5 %6 %7 %8 %9 %10\n") .arg(item->text(column_number_name), -60) .arg(item->text(column_number_ogf), -10) .arg(item->text(column_number_ocf), -10) .arg(item->text(column_number_opcode), -10) .arg(item->text(column_number_event), -10) .arg(item->text(column_number_subevent), -10) .arg(item->text(column_number_status), -10) .arg(item->text(column_number_reason), -10) .arg(item->text(column_number_hardware_error), -15) .arg(item->text(column_number_occurrence), -10); recursiveCopyTreeItems(ui->tableTreeWidget->topLevelItem(i_item), copy, 1); } clipboard->setText(copy); } void BluetoothHciSummaryDialog::on_actionSave_as_image_triggered() { QPixmap image; QString fileName = WiresharkFileDialog::getSaveFileName(this, tr("Save Table Image"), "bluetooth_hci_summary.png", tr("PNG Image (*.png)")); if (fileName.isEmpty()) return; image = ui->tableTreeWidget->grab(); image.save(fileName, "PNG"); } void BluetoothHciSummaryDialog::on_buttonBox_clicked(QAbstractButton *) { /* if (button == foo_button_) */ } void BluetoothHciSummaryDialog::displayFilterLineEditAccepted() { GString *error_string; remove_tap_listener(&tapinfo_); error_string = register_tap_listener("bluetooth.hci_summary", &tapinfo_, ui->displayFilterLineEdit->text().toUtf8().constData(), 0, bluetooth_hci_summary_tap_reset, bluetooth_hci_summary_tap_packet, NULL, NULL ); if (error_string != NULL) { simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", error_string->str); g_string_free(error_string, TRUE); } cap_file_.retapPackets(); } void BluetoothHciSummaryDialog::resultsFilterLineEditChanged(const QString &text) { for (int i_item = 0; i_item < ui->tableTreeWidget->topLevelItemCount(); ++i_item) { QTreeWidgetItem *item = ui->tableTreeWidget->topLevelItem(i_item); for (int i_child = 0; i_child < item->childCount(); i_child += 1) { QTreeWidgetItem *child_item = item->child(i_child); QString name = child_item->text(column_number_name); child_item->setHidden(!name.contains(text, Qt::CaseInsensitive)); } } }
C/C++
wireshark/ui/qt/bluetooth_hci_summary_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef BLUETOOTH_HCI_SUMMARY_DIALOG_H #define BLUETOOTH_HCI_SUMMARY_DIALOG_H #include "config.h" #include <glib.h> #include "wireshark_dialog.h" #include "cfile.h" #include "packet_list.h" #include "epan/tap.h" #include <QMenu> class QAbstractButton; class QPushButton; class QTreeWidgetItem; typedef struct _bluetooth_hci_summary_tapinfo_t { tap_reset_cb tap_reset; tap_packet_cb tap_packet; void *ui; } bluetooth_hci_summary_tapinfo_t; namespace Ui { class BluetoothHciSummaryDialog; } class BluetoothHciSummaryDialog : public WiresharkDialog { Q_OBJECT public: explicit BluetoothHciSummaryDialog(QWidget &parent, CaptureFile &cf); ~BluetoothHciSummaryDialog(); public slots: signals: void updateFilter(QString filter, bool force = false); void captureFileChanged(capture_file *cf); void goToPacket(int packet_num); protected: void keyPressEvent(QKeyEvent *event); void captureFileClosing(); void captureFileClosed(); protected slots: void changeEvent(QEvent* event); private: Ui::BluetoothHciSummaryDialog *ui; bluetooth_hci_summary_tapinfo_t tapinfo_; QMenu context_menu_; QTreeWidgetItem *item_link_control_; QTreeWidgetItem *item_link_policy_; QTreeWidgetItem *item_controller_and_baseband_; QTreeWidgetItem *item_informational_; QTreeWidgetItem *item_status_parameters_; QTreeWidgetItem *item_testing_; QTreeWidgetItem *item_low_energy_; QTreeWidgetItem *item_logo_testing_; QTreeWidgetItem *item_vendor_; QTreeWidgetItem *item_unknown_ogf_; QTreeWidgetItem *item_events_; QTreeWidgetItem *item_status_; QTreeWidgetItem *item_reason_; QTreeWidgetItem *item_hardware_errors_; static void tapReset(void *tapinfo_ptr); static tap_packet_status tapPacket(void *tapinfo_ptr, packet_info *pinfo, epan_dissect_t *, const void *data, tap_flags_t flags); private slots: void recursiveCopyTreeItems(QTreeWidgetItem *item, QString &copy, int ident_level); void on_tableTreeWidget_itemActivated(QTreeWidgetItem *item, int); void on_buttonBox_clicked(QAbstractButton *button); void on_actionMark_Unmark_Cell_triggered(); void on_actionMark_Unmark_Row_triggered(); void on_actionCopy_Cell_triggered(); void on_actionCopy_Rows_triggered(); void on_actionCopy_All_triggered(); void on_actionSave_as_image_triggered(); void tableContextMenu(const QPoint &pos); void tableItemExpanded(QTreeWidgetItem *item); void tableItemCollapsed(QTreeWidgetItem *item); void interfaceCurrentIndexChanged(int index); void adapterCurrentIndexChanged(int index); void displayFilterLineEditAccepted(); void resultsFilterLineEditChanged(const QString &text); }; #endif // BLUETOOTH_HCI_SUMMARY_DIALOG_H
User Interface
wireshark/ui/qt/bluetooth_hci_summary_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>BluetoothHciSummaryDialog</class> <widget class="QDialog" name="BluetoothHciSummaryDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>880</width> <height>477</height> </rect> </property> <property name="baseSize"> <size> <width>0</width> <height>0</height> </size> </property> <property name="windowTitle"> <string>Bluetooth HCI Summary</string> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QTreeWidget" name="tableTreeWidget"> <property name="contextMenuPolicy"> <enum>Qt::CustomContextMenu</enum> </property> <property name="editTriggers"> <set>QAbstractItemView::NoEditTriggers</set> </property> <property name="showDropIndicator" stdset="0"> <bool>false</bool> </property> <property name="selectionMode"> <enum>QAbstractItemView::ExtendedSelection</enum> </property> <property name="textElideMode"> <enum>Qt::ElideMiddle</enum> </property> <property name="indentation"> <number>30</number> </property> <property name="rootIsDecorated"> <bool>true</bool> </property> <property name="uniformRowHeights"> <bool>false</bool> </property> <property name="itemsExpandable"> <bool>true</bool> </property> <property name="sortingEnabled"> <bool>false</bool> </property> <property name="animated"> <bool>false</bool> </property> <property name="allColumnsShowFocus"> <bool>false</bool> </property> <property name="headerHidden"> <bool>false</bool> </property> <attribute name="headerCascadingSectionResizes"> <bool>false</bool> </attribute> <attribute name="headerMinimumSectionSize"> <number>100</number> </attribute> <attribute name="headerDefaultSectionSize"> <number>100</number> </attribute> <attribute name="headerHighlightSections"> <bool>false</bool> </attribute> <attribute name="headerShowSortIndicator" stdset="0"> <bool>false</bool> </attribute> <attribute name="headerStretchLastSection"> <bool>true</bool> </attribute> <column> <property name="text"> <string>Name</string> </property> </column> <column> <property name="text"> <string>OGF</string> </property> </column> <column> <property name="text"> <string>OCF</string> </property> </column> <column> <property name="text"> <string>Opcode</string> </property> </column> <column> <property name="text"> <string>Event</string> </property> </column> <column> <property name="text"> <string>Subevent</string> </property> </column> <column> <property name="text"> <string>Status</string> </property> </column> <column> <property name="text"> <string>Reason</string> </property> </column> <column> <property name="text"> <string>Hardware Error</string> </property> </column> <column> <property name="text"> <string>Occurrence</string> </property> </column> <item> <property name="text"> <string>Link Control Commands</string> </property> <property name="text"> <string>0x01</string> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string>0</string> </property> </item> <item> <property name="text"> <string>Link Policy Commands</string> </property> <property name="text"> <string>0x02</string> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string>0</string> </property> </item> <item> <property name="text"> <string>Controller &amp; Baseband Commands</string> </property> <property name="text"> <string>0x03</string> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string>0</string> </property> </item> <item> <property name="text"> <string>Informational Parameters</string> </property> <property name="text"> <string>0x04</string> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string>0</string> </property> </item> <item> <property name="text"> <string>Status Parameters</string> </property> <property name="text"> <string>0x05</string> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string>0</string> </property> </item> <item> <property name="text"> <string>Testing Commands</string> </property> <property name="text"> <string>0x06</string> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string>0</string> </property> </item> <item> <property name="text"> <string>LE Controller Commands</string> </property> <property name="text"> <string>0x08</string> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string>0</string> </property> </item> <item> <property name="text"> <string>Bluetooth Logo Testing Commands</string> </property> <property name="text"> <string>0x3E</string> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string>0</string> </property> </item> <item> <property name="text"> <string>Vendor-Specific Commands</string> </property> <property name="text"> <string>0x3F</string> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string>0</string> </property> </item> <item> <property name="text"> <string>Unknown OGF</string> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string>0</string> </property> </item> <item> <property name="text"> <string>Events</string> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string>0</string> </property> </item> <item> <property name="text"> <string>Status</string> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string>0</string> </property> </item> <item> <property name="text"> <string>Reason</string> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string>0</string> </property> </item> <item> <property name="text"> <string>Hardware Errors</string> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string/> </property> <property name="text"> <string>0</string> </property> </item> </widget> </item> <item> <layout class="QHBoxLayout" name="resultsFilterHorizontalLayout"> <property name="topMargin"> <number>0</number> </property> <item> <widget class="QLabel" name="resultsFilterLabel"> <property name="text"> <string>Results filter:</string> </property> </widget> </item> <item> <widget class="QLineEdit" name="resultsFilterLineEdit"/> </item> </layout> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0,0,0"> <property name="spacing"> <number>6</number> </property> <property name="sizeConstraint"> <enum>QLayout::SetDefaultConstraint</enum> </property> <property name="bottomMargin"> <number>0</number> </property> <item> <widget class="QLabel" name="label"> <property name="text"> <string>Display filter:</string> </property> </widget> </item> <item> <widget class="DisplayFilterEdit" name="displayFilterLineEdit"/> </item> <item> <widget class="QComboBox" name="interfaceComboBox"> <property name="sizePolicy"> <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="minimumSize"> <size> <width>350</width> <height>0</height> </size> </property> <item> <property name="text"> <string>All Interfaces</string> </property> </item> </widget> </item> <item> <widget class="QComboBox" name="adapterComboBox"> <property name="minimumSize"> <size> <width>320</width> <height>0</height> </size> </property> <item> <property name="text"> <string>All Adapters</string> </property> </item> </widget> </item> </layout> </item> <item> <widget class="QLabel" name="hintLabel"> <property name="text"> <string/> </property> </widget> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Close</set> </property> </widget> </item> </layout> <action name="actionCopy_Cell"> <property name="text"> <string>Copy Cell</string> </property> </action> <action name="actionCopy_Rows"> <property name="text"> <string>Copy Rows</string> </property> </action> <action name="actionCopy_All"> <property name="text"> <string>Copy All</string> </property> </action> <action name="actionSave_as_image"> <property name="text"> <string>Save as image</string> </property> </action> <action name="actionMark_Unmark_Row"> <property name="text"> <string>Mark/Unmark Row</string> </property> <property name="toolTip"> <string>Mark/Unmark Row</string> </property> <property name="shortcut"> <string>Ctrl+M</string> </property> </action> <action name="actionMark_Unmark_Cell"> <property name="text"> <string>Mark/Unmark Cell</string> </property> </action> </widget> <customwidgets> <customwidget> <class>DisplayFilterEdit</class> <extends>QLineEdit</extends> <header>widgets/display_filter_edit.h</header> </customwidget> </customwidgets> <resources/> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>BluetoothHciSummaryDialog</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>374</x> <y>407</y> </hint> <hint type="destinationlabel"> <x>374</x> <y>214</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>BluetoothHciSummaryDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>374</x> <y>407</y> </hint> <hint type="destinationlabel"> <x>374</x> <y>214</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/byte_view_tab.cpp
/* byte_view_tab.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "byte_view_tab.h" #include <QApplication> #include <QClipboard> #include <QMimeData> #include <QTabBar> #include "cfile.h" #include "epan/epan_dissect.h" #include "epan/tvbuff-int.h" #include <main_application.h> #include <ui/qt/utils/variant_pointer.h> #include <ui/qt/widgets/byte_view_text.h> #define tvb_data_property "tvb_data_property" // To do: // - We might want to add a callback to free_data_sources in so that we // don't have to blindly call clear(). ByteViewTab::ByteViewTab(QWidget *parent, epan_dissect_t *edt_fixed) : QTabWidget(parent), cap_file_(0), is_fixed_packet_(edt_fixed != NULL), edt_(edt_fixed), disable_hover_(false) { setAccessibleName(tr("Packet bytes")); setTabPosition(QTabWidget::South); setDocumentMode(true); // Shrink down to a small but nonzero size in the main splitter. int one_em = fontMetrics().height(); setMinimumSize(one_em, one_em); if (!edt_fixed) { connect(mainApp, SIGNAL(appInitialized()), this, SLOT(connectToMainWindow())); } } // Connects the byte view with the main window, acting on changes to the packet // list selection. It MUST NOT be used with the packet dialog as that is // independent of the selection in the packet list. void ByteViewTab::connectToMainWindow() { connect(this, SIGNAL(fieldSelected(FieldInformation *)), mainApp->mainWindow(), SIGNAL(fieldSelected(FieldInformation *))); connect(this, SIGNAL(fieldHighlight(FieldInformation *)), mainApp->mainWindow(), SIGNAL(fieldHighlight(FieldInformation *))); /* Connect change of packet selection */ connect(mainApp->mainWindow(), SIGNAL(framesSelected(QList<int>)), this, SLOT(selectedFrameChanged(QList<int>))); connect(mainApp->mainWindow(), SIGNAL(setCaptureFile(capture_file*)), this, SLOT(setCaptureFile(capture_file*))); connect(mainApp->mainWindow(), SIGNAL(fieldSelected(FieldInformation *)), this, SLOT(selectedFieldChanged(FieldInformation *))); connect(mainApp->mainWindow(), SIGNAL(captureActive(int)), this, SLOT(captureActive(int))); } void ByteViewTab::captureActive(int cap) { if (cap == 0) { QList<ByteViewText *> allBVTs = findChildren<ByteViewText *>(); if (allBVTs.count() > 0) { ByteViewText * bvt = allBVTs.at(0); tvbuff_t * stored = VariantPointer<tvbuff_t>::asPtr(bvt->property(tvb_data_property)); if (! stored) selectedFrameChanged(QList<int>()); } } } void ByteViewTab::addTab(const char *name, tvbuff_t *tvb) { if (count() == 1) { // Remove empty placeholder. ByteViewText *cur_text = qobject_cast<ByteViewText *>(currentWidget()); if (cur_text && cur_text->isEmpty()) delete currentWidget(); } packet_char_enc encoding = PACKET_CHAR_ENC_CHAR_ASCII; if (cap_file_ && cap_file_->current_frame) encoding = (packet_char_enc)cap_file_->current_frame->encoding; QByteArray data; if (tvb) { int data_len = (int) tvb_captured_length(tvb); if (data_len > 0) { // Note: this does not copy the data and will be invalidated // when the tvbuff's real data becomes invalid (which is not // necessarily when the tvb itself becomes invalid.) data = QByteArray::fromRawData((const char *) tvb_get_ptr(tvb, 0, data_len), data_len); } } ByteViewText * byte_view_text = new ByteViewText(data, encoding, this); byte_view_text->setAccessibleName(name); byte_view_text->setMonospaceFont(mainApp->monospaceFont(true)); if (tvb) { // There are some secondary data source tvbuffs whose datais not freed // when the epan_dissect_t is freed, but at some other point expected // to outlive the packet, generally when the capture file is closed. // If this is a PacketDialog, it can break that assumption. // To get around this, we deep copy their data when the file is closed. // // XXX: We could add a function to the tvbuff API and only do this if // there is no free_cb (a free_cb implies the data is freed at the // same time as the tvb, i.e. when leaving the packet.) if (is_fixed_packet_ && count() > 0) { connect(this, &ByteViewTab::detachData, byte_view_text, &ByteViewText::detachData); } // See above - this tvb is (expected to be) scoped to the packet, but // the real data is not necessarily so. If this is a PacketDialog // and such a secondary data source, then we MUST NOT use any tvb // function that accesses the real data after the capture file closes. // That includes via the ds_tvb item of a field_info in the tree. // proto_find_field_from_offset() is OK. See #14363. // // XXX: It sounds appealing to clone the secondary data source tvbs // and set them to be freed when the byte_view_text is freed, perhaps // even doing so only when the capture file is closing. However, while // relatively simple for the few number of secondary data sources, it // would be a pain to change the pointers for every field_info. byte_view_text->setProperty(tvb_data_property, VariantPointer<tvbuff_t>::asQVariant(tvb)); connect(mainApp, SIGNAL(zoomMonospaceFont(QFont)), byte_view_text, SLOT(setMonospaceFont(QFont))); connect(byte_view_text, SIGNAL(byteHovered(int)), this, SLOT(byteViewTextHovered(int))); connect(byte_view_text, SIGNAL(byteSelected(int)), this, SLOT(byteViewTextMarked(int))); connect(byte_view_text, SIGNAL(byteViewSettingsChanged()), this, SIGNAL(byteViewSettingsChanged())); connect(this, SIGNAL(byteViewSettingsChanged()), byte_view_text, SLOT(updateByteViewSettings())); } int idx = QTabWidget::addTab(byte_view_text, name); byte_view_text->setProperty("tab_index", QVariant::fromValue(idx)); QTabWidget::setTabToolTip(idx, name); } void ByteViewTab::byteViewTextHovered(int idx) { if (idx >= 0 && edt_) { tvbuff_t * tvb = VariantPointer<tvbuff_t>::asPtr(sender()->property(tvb_data_property)); proto_tree * tree = edt_->tree; if (tvb && tree) { field_info * fi = proto_find_field_from_offset(tree, idx, tvb); if (fi) { FieldInformation finfo(fi, this); highlightedFieldChanged(&finfo); emit fieldHighlight(&finfo); return; } } } emit fieldHighlight((FieldInformation *)0); } void ByteViewTab::byteViewTextMarked(int idx) { if (idx >= 0 && edt_) { tvbuff_t * tvb = VariantPointer<tvbuff_t>::asPtr(sender()->property(tvb_data_property)); proto_tree * tree = edt_->tree; if (tvb && tree) { field_info * fi = proto_find_field_from_offset(tree, idx, tvb); if (fi) { FieldInformation finfo(fi, this); emit fieldSelected(&finfo); return; } } } emit fieldSelected((FieldInformation *)0); } ByteViewText * ByteViewTab::findByteViewTextForTvb(tvbuff_t * search_tvb, int * idx) { ByteViewText * item = 0; if (! search_tvb) return item; bool found = false; QList<ByteViewText *> allBVTs = findChildren<ByteViewText *>(); for (int i = 0; i < allBVTs.size() && ! found; ++i) { ByteViewText * bvt = allBVTs.at(i); tvbuff_t * stored = VariantPointer<tvbuff_t>::asPtr(bvt->property(tvb_data_property)); if (stored == search_tvb) { found = true; int wdgIdx = bvt->property("tab_index").toInt(); if (idx) { *idx = wdgIdx; } item = (ByteViewText *)widget(wdgIdx); } } return item; } void ByteViewTab::tabInserted(int tab_index) { setTabsVisible(); QTabWidget::tabInserted(tab_index); } void ByteViewTab::tabRemoved(int tab_index) { setTabsVisible(); QTabWidget::tabRemoved(tab_index); } void ByteViewTab::setTabsVisible() { if (count() > 1) tabBar()->show(); else tabBar()->hide(); } void ByteViewTab::selectedFrameChanged(QList<int> frames) { clear(); qDeleteAll(findChildren<ByteViewText *>()); if (!is_fixed_packet_) { /* If this is not a fixed packet (not the packet dialog), it must be the * byte view associated with the packet list. */ if (cap_file_ && cap_file_->edt) { /* Assumes that this function is called as a result of selecting a * packet in the packet list (PacketList::selectionChanged). That * invokes "cf_select_packet" which will update "cap_file_->edt". */ edt_ = cap_file_->edt; } else { /* capture file is closing or packet is deselected. */ edt_ = NULL; } } /* only show the bytes for single selections */ if (frames.count() == 1) { if (! cap_file_ || ! cap_file_->edt) return; /* This code relies on a dissection, which had happened somewhere else. It also does not * really check, if the dissection happened for the correct frame. In the future we might * rewrite this for directly calling the dissection engine here. */ GSList *src_le; for (src_le = edt_->pi.data_src; src_le != NULL; src_le = src_le->next) { struct data_source *source; char* source_name; source = (struct data_source *)src_le->data; source_name = get_data_source_name(source); addTab(source_name, get_data_source_tvb(source)); wmem_free(NULL, source_name); } } else addTab("PlaceHolder", 0); setCurrentIndex(0); } void ByteViewTab::selectedFieldChanged(FieldInformation *selected) { // We need to handle both selection and deselection. ByteViewText * byte_view_text = qobject_cast<ByteViewText *>(currentWidget()); int f_start = -1, f_length = -1; int p_start = -1, p_length = -1; int fa_start = -1, fa_length = -1; if (selected) { if (selected->parent() == this) { // We only want inbound signals. return; } const field_info *fi = selected->fieldInfo(); int idx = 0; if (fi) byte_view_text = findByteViewTextForTvb(fi->ds_tvb, &idx); if (cap_file_->search_in_progress && (cap_file_->hex || (cap_file_->string && cap_file_->packet_data))) { // In the hex view, only highlight the target bytes or string. The entire // field can then be displayed by clicking on any of the bytes in the field. f_start = cap_file_->search_pos - cap_file_->search_len + 1; f_length = (int) cap_file_->search_len; } else { f_start = selected->position().start; f_length = selected->position().length; } setCurrentIndex(idx); FieldInformation *parentField = selected->parentField(); p_start = parentField->position().start; p_length = parentField->position().length; fa_start = selected->appendix().start; fa_length = selected->appendix().length; delete parentField; } if (byte_view_text) { byte_view_text->markField(f_start, f_length); byte_view_text->markProtocol(p_start, p_length); byte_view_text->markAppendix(fa_start, fa_length); } } void ByteViewTab::highlightedFieldChanged(FieldInformation *highlighted) { ByteViewText * byte_view_text = qobject_cast<ByteViewText *>(currentWidget()); if (!highlighted || !byte_view_text) { return; } int f_start = -1, f_length = -1; if (cap_file_->search_in_progress && (cap_file_->hex || (cap_file_->string && cap_file_->packet_data))) { // In the hex view, only highlight the target bytes or string. The entire // field can then be displayed by clicking on any of the bytes in the field. f_start = cap_file_->search_pos - cap_file_->search_len + 1; f_length = (int) cap_file_->search_len; } else { f_start = highlighted->position().start; f_length = highlighted->position().length; } byte_view_text->markField(f_start, f_length, false); byte_view_text->markProtocol(-1, -1); byte_view_text->markAppendix(-1, -1); } void ByteViewTab::setCaptureFile(capture_file *cf) { selectedFrameChanged(QList<int>()); cap_file_ = cf; } void ByteViewTab::captureFileClosing() { emit detachData(); }
C/C++
wireshark/ui/qt/byte_view_tab.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef BYTE_VIEW_TAB_H #define BYTE_VIEW_TAB_H #include <config.h> #include <epan/packet.h> #include <epan/proto.h> #include <epan/tvbuff.h> #include <ui/qt/utils/field_information.h> #include "cfile.h" #include <QTabWidget> #include <ui/qt/widgets/byte_view_text.h> class ByteViewTab : public QTabWidget { Q_OBJECT public: explicit ByteViewTab(QWidget *parent = 0, epan_dissect_t *edt_fixed = 0); public slots: /* Set the capture file */ void setCaptureFile(capture_file *cf); /* Creates the tabs and data, depends on an dissection which has already run */ void selectedFrameChanged(QList<int>); /* Selects or marks a field */ void selectedFieldChanged(FieldInformation *); /* Highlights field */ void highlightedFieldChanged(FieldInformation *); void captureFileClosing(void); signals: void fieldSelected(FieldInformation *); void fieldHighlight(FieldInformation *); void byteViewSettingsChanged(void); void detachData(void); private: capture_file *cap_file_; bool is_fixed_packet_; /* true if this byte view is related to a single packet in the packet dialog and false if the packet dissection context can change. */ epan_dissect_t *edt_; /* Packet dissection result for the currently selected packet. */ bool disable_hover_; void setTabsVisible(); ByteViewText * findByteViewTextForTvb(tvbuff_t * search, int * idx = 0); void addTab(const char *name = "", tvbuff_t *tvb = NULL); protected: void tabInserted(int); void tabRemoved(int); private slots: void byteViewTextHovered(int); void byteViewTextMarked(int); void connectToMainWindow(); void captureActive(int); }; #endif // BYTE_VIEW_TAB_H
C/C++
wireshark/ui/qt/capture_event.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef CAPTURE_EVENT_H #define CAPTURE_EVENT_H #include <QEvent> typedef struct _capture_session capture_session; struct _packet_info; class CaptureEvent { public: enum Context { #ifdef HAVE_LIBPCAP Capture = 0x0001, Update = 0x0100 | Capture, Fixed = 0x0200 | Capture, #endif File = 0x0002, Reload = 0x0100 | File, Rescan = 0x0200 | File, Save = 0x0400 | File, Retap = 0x0800 | File, Merge = 0x1000 | File }; enum EventType { Opened = 0x0001, Started = 0x0002, Finished = 0x0004, Closing = 0x0008, Closed = 0x0010, Failed = 0x0020, Stopped = 0x0040, Flushed = 0x0080, Prepared = 0x0100, Continued = 0x0200, Stopping = 0x0400 }; CaptureEvent(Context ctx, EventType evt); CaptureEvent(Context ctx, EventType evt, QString file); CaptureEvent(Context ctx, EventType evt, capture_session * session); CaptureEvent(const CaptureEvent &ce); Context captureContext() const; EventType eventType() const; QString filePath() const; capture_session * capSession() const; private: Context _ctx; EventType _evt; QString _filePath; capture_session * _session; }; #endif // CAPTURE_EVENT_H
C++
wireshark/ui/qt/capture_file.cpp
/* capture_file.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "capture_file.h" /* * @file Capture file class * * Wraps the capture_file struct, cfile global, and callbacks. */ #include "globals.h" capture_file cfile; #include "file.h" #include "epan/epan_dissect.h" #include "ui/capture.h" #include <QFileInfo> #include <QTimer> #include <QDebug> CaptureEvent::CaptureEvent(Context ctx, EventType evt) : _ctx(ctx), _evt(evt), _session(Q_NULLPTR) { } CaptureEvent::CaptureEvent(Context ctx, EventType evt, QString file) : _ctx(ctx), _evt(evt), _filePath(file), _session(Q_NULLPTR) { } CaptureEvent::CaptureEvent(Context ctx, EventType evt, capture_session * session) : _ctx(ctx), _evt(evt), _session(session) { } CaptureEvent::CaptureEvent(const CaptureEvent &ce) : _ctx(ce._ctx), _evt(ce._evt), _filePath(ce._filePath), _session(ce._session) { } CaptureEvent::Context CaptureEvent::captureContext() const { return _ctx; } CaptureEvent::EventType CaptureEvent::eventType() const { return _evt; } QString CaptureEvent::filePath() const { return _filePath; } capture_session * CaptureEvent::capSession() const { return _session; } // To do: // - Add getters and (if needed) setters: // - Full filename // - Capture state (stopped, prepared, running). // - Call common_create_progress_dlg. This would let us manage the stop // flag here as well as emit progress signals. QString CaptureFile::no_capture_file_ = QObject::tr("[no capture file]"); CaptureFile::CaptureFile(QObject *parent, capture_file *cap_file) : QObject(parent), cap_file_(cap_file), file_state_(QString()) { #ifdef HAVE_LIBPCAP capture_callback_add(captureCallback, (gpointer) this); #endif cf_callback_add(captureFileCallback, (gpointer) this); } CaptureFile::~CaptureFile() { cf_callback_remove(captureFileCallback, this); } bool CaptureFile::isValid() const { if (cap_file_ && cap_file_->state != FILE_CLOSED && cap_file_->state != FILE_READ_PENDING) { // XXX FILE_READ_IN_PROGRESS as well? return true; } return false; } const QString CaptureFile::filePath() { QString path; if (isValid()) { // // Sadly, some UN*Xes don't necessarily use UTF-8 // for their file names, so we have to map the // file path to UTF-8. If that fails, we're somewhat // stuck. // char *utf8_filename = g_filename_to_utf8(cap_file_->filename, -1, NULL, NULL, NULL); if (utf8_filename) { path = QString::fromUtf8(utf8_filename); g_free(utf8_filename); } else { // So what the heck else can we do here? path = QString(); } } else { path = QString(); } return path; } const QString CaptureFile::fileName() { QString path, name; path = filePath(); if (!path.isEmpty()) { QFileInfo cfi(path); name = cfi.fileName(); } else { name = QString(); } return name; } const QString CaptureFile::fileBaseName() { QString baseName; if (isValid()) { char *basename = cf_get_basename(cap_file_); baseName = basename; g_free(basename); } else { baseName = QString(); } return baseName; } const QString CaptureFile::fileDisplayName() { QString displayName; if (isValid()) { char *display_name = cf_get_display_name(cap_file_); displayName = display_name; g_free(display_name); } else { displayName = QString(); } return displayName; } const QString CaptureFile::fileTitle() { QString title; if (isValid()) { title = fileDisplayName() + file_state_; } else { title = no_capture_file_; } return title; } struct _packet_info *CaptureFile::packetInfo() { if (capFile() && capFile()->edt) { return &(capFile()->edt->pi); } return NULL; } int CaptureFile::timestampPrecision() { if (capFile() && capFile()->provider.wth) { return wtap_file_tsprec(capFile()->provider.wth); } return WTAP_TSPREC_UNKNOWN; } void CaptureFile::retapPackets() { if (cap_file_) { cf_retap_packets(cap_file_); } } void CaptureFile::delayedRetapPackets() { QTimer::singleShot(0, this, SLOT(retapPackets())); } void CaptureFile::reload() { if (cap_file_ && cap_file_->state == FILE_READ_DONE) { cf_reload(cap_file_); } } void CaptureFile::stopLoading() { setCaptureStopFlag(true); } QString CaptureFile::displayFilter() const { if (isValid()) return QString(cap_file_->dfilter); return QString(); } capture_file *CaptureFile::globalCapFile() { return &cfile; } gpointer CaptureFile::window() { if (cap_file_) return cap_file_->window; return NULL; } void CaptureFile::setCaptureStopFlag(bool stop_flag) { if (cap_file_) cap_file_->stop_flag = stop_flag; } void CaptureFile::captureFileCallback(gint event, gpointer data, gpointer user_data) { CaptureFile *capture_file = static_cast<CaptureFile *>(user_data); if (!capture_file) return; capture_file->captureFileEvent(event, data); } #ifdef HAVE_LIBPCAP void CaptureFile::captureCallback(gint event, capture_session *cap_session, gpointer user_data) { CaptureFile *capture_file = static_cast<CaptureFile *>(user_data); if (!capture_file) return; capture_file->captureSessionEvent(event, cap_session); } #endif void CaptureFile::captureFileEvent(int event, gpointer data) { switch(event) { case(cf_cb_file_opened): cap_file_ = (capture_file *) data; emit captureEvent(CaptureEvent(CaptureEvent::File, CaptureEvent::Opened)); break; case(cf_cb_file_closing): file_state_ = tr(" [closing]"); emit captureEvent(CaptureEvent(CaptureEvent::File, CaptureEvent::Closing)); break; case(cf_cb_file_closed): file_state_ = tr(" [closed]"); emit captureEvent(CaptureEvent(CaptureEvent::File, CaptureEvent::Closed)); cap_file_ = NULL; file_state_ = QString(); break; case(cf_cb_file_read_started): emit captureEvent(CaptureEvent(CaptureEvent::File, CaptureEvent::Started)); break; case(cf_cb_file_read_finished): emit captureEvent(CaptureEvent(CaptureEvent::File, CaptureEvent::Finished)); break; case(cf_cb_file_reload_started): emit captureEvent(CaptureEvent(CaptureEvent::Reload, CaptureEvent::Started)); break; case(cf_cb_file_reload_finished): emit captureEvent(CaptureEvent(CaptureEvent::Reload, CaptureEvent::Finished)); break; case(cf_cb_file_rescan_started): emit captureEvent(CaptureEvent(CaptureEvent::Rescan, CaptureEvent::Started)); break; case(cf_cb_file_rescan_finished): emit captureEvent(CaptureEvent(CaptureEvent::Rescan, CaptureEvent::Finished)); break; case(cf_cb_file_retap_started): emit captureEvent(CaptureEvent(CaptureEvent::Retap, CaptureEvent::Started)); break; case(cf_cb_file_retap_finished): /* Flush any pending tapped packet before emitting captureFileRetapFinished() */ emit captureEvent(CaptureEvent(CaptureEvent::Retap, CaptureEvent::Finished)); emit captureEvent(CaptureEvent(CaptureEvent::Retap, CaptureEvent::Flushed)); break; case(cf_cb_file_merge_started): emit captureEvent(CaptureEvent(CaptureEvent::Merge, CaptureEvent::Started)); break; case(cf_cb_file_merge_finished): emit captureEvent(CaptureEvent(CaptureEvent::Merge, CaptureEvent::Finished)); break; case(cf_cb_file_fast_save_finished): // gtk/main.c calls main_cf_cb_file_rescan_finished. Should we do // the equivalent? break; case(cf_cb_file_save_started): { emit captureEvent(CaptureEvent(CaptureEvent::Save, CaptureEvent::Started, QString((const char *)data))); break; } case(cf_cb_file_save_finished): emit captureEvent(CaptureEvent(CaptureEvent::Save, CaptureEvent::Finished)); break; case(cf_cb_file_save_failed): emit captureEvent(CaptureEvent(CaptureEvent::Save, CaptureEvent::Failed)); break; case(cf_cb_file_save_stopped): emit captureEvent(CaptureEvent(CaptureEvent::Save, CaptureEvent::Stopped)); break; default: qWarning() << "CaptureFile::captureFileCallback: event " << event << " unknown"; Q_ASSERT(false); break; } } #ifdef HAVE_LIBPCAP void CaptureFile::captureSessionEvent(int event, capture_session *cap_session) { switch(event) { case(capture_cb_capture_prepared): emit captureEvent(CaptureEvent(CaptureEvent::Capture, CaptureEvent::Prepared, cap_session)); cap_file_ = cap_session->cf; break; case(capture_cb_capture_update_started): emit captureEvent(CaptureEvent(CaptureEvent::Update, CaptureEvent::Started, cap_session)); break; case(capture_cb_capture_update_continue): emit captureEvent(CaptureEvent(CaptureEvent::Update, CaptureEvent::Continued, cap_session)); break; case(capture_cb_capture_update_finished): emit captureEvent(CaptureEvent(CaptureEvent::Update, CaptureEvent::Finished, cap_session)); break; case(capture_cb_capture_fixed_started): emit captureEvent(CaptureEvent(CaptureEvent::Fixed, CaptureEvent::Started, cap_session)); break; case(capture_cb_capture_fixed_continue): emit captureEvent(CaptureEvent(CaptureEvent::Fixed, CaptureEvent::Continued, cap_session)); break; case(capture_cb_capture_fixed_finished): emit captureEvent(CaptureEvent(CaptureEvent::Fixed, CaptureEvent::Finished, cap_session)); break; case(capture_cb_capture_stopping): /* Beware: this state won't be called, if the capture child * closes the capturing on it's own! */ emit captureEvent(CaptureEvent(CaptureEvent::Capture, CaptureEvent::Stopping, cap_session)); break; case(capture_cb_capture_failed): emit captureEvent(CaptureEvent(CaptureEvent::Capture, CaptureEvent::Failed, cap_session)); break; default: qWarning() << "main_capture_callback: event " << event << " unknown"; } } #endif // HAVE_LIBPCAP
C/C++
wireshark/ui/qt/capture_file.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef CAPTURE_FILE_H #define CAPTURE_FILE_H #include <QObject> #include <config.h> #include <glib.h> #include "cfile.h" #include "capture_event.h" class CaptureFile : public QObject { Q_OBJECT public: explicit CaptureFile(QObject *parent = 0, capture_file *cap_file = NULL); ~CaptureFile(); capture_file *capFile() const { return isValid() ? cap_file_ : NULL; } void setCapFile(capture_file *cap_file) { cap_file_ = cap_file; } /** Check capture file validity * * @return true if the file is open, readable, and tappable. false if the file * is closed. */ bool isValid() const; /** Return the full pathname. * * @return The entire pathname, converted from the native OS's encoding * to Unicode if necessary, or a null string if the conversion can't * be done. */ const QString filePath(); /** Return the plain filename. * * @return The last component of the pathname, including the extension, * converted from the native OS's encoding to Unicode if necessary, or * a null string if the conversion can't be done. */ const QString fileName(); /** Return the plain filename without an extension. * * @return The last component of the pathname, without the extension, * converted from the native OS's encoding to Unicode if necessary, or * a null string if the conversion can't be done. */ const QString fileBaseName(); /** Return a string representing the file suitable for use for * display in the UI in places such as a main window title. * * @return One of: * * the devices on which the capture was done, if the file is a * temporary file for a capture; * * the last component of the capture file's name, converted * from the native OS's encoding to Unicode if necessary (and * with REPLACEMENT CHARACTER inserted if the string can't * be converted). * * a null string, if there is no capture file. */ const QString fileDisplayName(); /** Return a string representing the file suitable for use in an * auxiliary window title. * * @return One of: * * the result of fileDisplayName(), if the file is open; * * the result of fileDisplayName() followed by [closing], if * the file is being closed; * * the result of fileDisplayName() followed by [closed], if * the file has been closed; * * [no capture file], if there is no capture file. */ const QString fileTitle(); /** Return the current packet information. * * @return A pointer to the current packet_info struct or NULL. */ struct _packet_info *packetInfo(); /** Timestamp precision for the current file. * @return One of the WTAP_TSPREC_x values defined in wiretap/wtap.h, * or WTAP_TSPREC_UNKNOWN if no file is open. */ int timestampPrecision(); /** Reload the capture file */ void reload(); /** Return any set display filter */ QString displayFilter() const; // XXX This shouldn't be needed. static capture_file *globalCapFile(); gpointer window(); signals: void captureEvent(CaptureEvent); public slots: /** Retap the capture file. Convenience wrapper for cf_retap_packets. * Application events are processed periodically via update_progress_dlg. */ void retapPackets(); /** Retap the capture file after the current batch of application events * is processed. If you call this instead of retapPackets or * cf_retap_packets in a dialog's constructor it will be displayed before * tapping starts. */ void delayedRetapPackets(); /** Cancel any tapping that might be in progress. */ void stopLoading(); /** Sets the capture file's "stop_flag" member. * * @param stop_flag If true, stops the current capture file operation. */ void setCaptureStopFlag(bool stop_flag = true); private: static void captureFileCallback(gint event, gpointer data, gpointer user_data); #ifdef HAVE_LIBPCAP static void captureCallback(gint event, capture_session *cap_session, gpointer user_data); #endif void captureFileEvent(int event, gpointer data); void captureSessionEvent(int event, capture_session *cap_session); const QString &getFileBasename(); static QString no_capture_file_; capture_file *cap_file_; QString file_state_; }; #endif // CAPTURE_FILE_H
C++
wireshark/ui/qt/capture_file_dialog.cpp
/* capture_file_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "file.h" #include <wiretap/wtap.h> #include "packet_range_group_box.h" #include "capture_file_dialog.h" #ifdef Q_OS_WIN #include <windows.h> #include "ui/packet_range.h" #include "ui/win32/file_dlg_win32.h" #else // Q_OS_WIN #include <errno.h> #include "wsutil/filesystem.h" #include "wsutil/nstime.h" #include "wsutil/str_util.h" #include "wsutil/utf8_entities.h" #include "ui/all_files_wildcard.h" #include <QCheckBox> #include <QFileInfo> #include <QGridLayout> #include <QHBoxLayout> #include <QLabel> #include <QLineEdit> #include <QSortFilterProxyModel> #include <QSpacerItem> #include <QVBoxLayout> #endif // ! Q_OS_WIN #include <QPushButton> #include <QMessageBox> #include "epan/prefs.h" #include <ui/qt/utils/qt_ui_utils.h> #include <main_application.h> static const double WIDTH_SCALE_FACTOR = 1.4; static const double HEIGHT_SCALE_FACTOR = 1.4; CaptureFileDialog::CaptureFileDialog(QWidget *parent, capture_file *cf) : WiresharkFileDialog(parent), cap_file_(cf), #if !defined(Q_OS_WIN) display_filter_edit_(NULL), default_ft_(-1), save_bt_(NULL), help_topic_(TOPIC_ACTION_NONE) #else file_type_(-1) #endif { switch (prefs.gui_fileopen_style) { case FO_STYLE_LAST_OPENED: /* The user has specified that we should start out in the last directory * we looked in. If we've already opened a file, use its containing * directory, if we could determine it, as the directory, otherwise * use the "last opened" directory saved in the preferences file if * there was one. */ setDirectory(mainApp->lastOpenDir()); break; case FO_STYLE_SPECIFIED: /* The user has specified that we should always start out in a * specified directory; if they've specified that directory, * start out by showing the files in that dir. */ if (prefs.gui_fileopen_dir[0] != '\0') setDirectory(prefs.gui_fileopen_dir); break; } #if !defined(Q_OS_WIN) // Add extra widgets // https://wiki.qt.io/Qt_project_org_faq#How_can_I_add_widgets_to_my_QFileDialog_instance.3F setOption(QFileDialog::DontUseNativeDialog, true); setOption(QFileDialog::HideNameFilterDetails, true); QGridLayout *fd_grid = qobject_cast<QGridLayout*>(layout()); QHBoxLayout *h_box = new QHBoxLayout(); last_row_ = fd_grid->rowCount(); fd_grid->addItem(new QSpacerItem(1, 1), last_row_, 0); fd_grid->addLayout(h_box, last_row_, 0, 1, 2); last_row_++; // Left and right boxes for controls and preview h_box->addLayout(&left_v_box_); h_box->addLayout(&right_v_box_); #else // Q_OS_WIN merge_type_ = 0; #endif // Q_OS_WIN } check_savability_t CaptureFileDialog::checkSaveAsWithComments(QWidget *parent, capture_file *cf, int file_type) { guint32 comment_types; bool all_comment_types_supported = true; /* What types of comments do we have? */ comment_types = cf_comment_types(cf); /* Does the file's format support all the comments we have? */ if (comment_types & WTAP_COMMENT_PER_SECTION) { if (wtap_file_type_subtype_supports_option(file_type, WTAP_BLOCK_SECTION, OPT_COMMENT) == OPTION_NOT_SUPPORTED) all_comment_types_supported = false; } if (comment_types & WTAP_COMMENT_PER_INTERFACE) { if (wtap_file_type_subtype_supports_option(file_type, WTAP_BLOCK_IF_ID_AND_INFO, OPT_COMMENT) == OPTION_NOT_SUPPORTED) all_comment_types_supported = false; } if (comment_types & WTAP_COMMENT_PER_PACKET) { if (wtap_file_type_subtype_supports_option(file_type, WTAP_BLOCK_PACKET, OPT_COMMENT) == OPTION_NOT_SUPPORTED) all_comment_types_supported = false; } if (all_comment_types_supported) { /* Yes. Let the save happen; we can save all the comments, so there's no need to delete them. */ return SAVE; } QMessageBox msg_dialog(parent); QPushButton *save_button; QPushButton *discard_button; msg_dialog.setIcon(QMessageBox::Question); msg_dialog.setText(tr("This capture file contains comments.")); msg_dialog.setStandardButtons(QMessageBox::Cancel); /* No. Are there formats in which we can write this file that supports all the comments in this file? */ if (wtap_dump_can_write(cf->linktypes, comment_types)) { /* Yes. Offer the user a choice of "Save in a format that supports comments", "Discard comments and save in the format you selected", or "Cancel", meaning "don't bother saving the file at all". */ msg_dialog.setInformativeText(tr("The file format you chose doesn't support comments. " "Do you want to save the capture in a format that supports comments " "or discard the comments and save in the format you chose?")); // The predefined roles don't really match the tasks at hand... discard_button = msg_dialog.addButton(tr("Discard comments and save"), QMessageBox::DestructiveRole); save_button = msg_dialog.addButton(tr("Save in another format"), QMessageBox::AcceptRole); msg_dialog.setDefaultButton(save_button); } else { /* No. Offer the user a choice of "Discard comments and save in the format you selected" or "Cancel". */ msg_dialog.setInformativeText(tr("No file format in which it can be saved supports comments. " "Do you want to discard the comments and save in the format you chose?")); save_button = NULL; discard_button = msg_dialog.addButton(tr("Discard comments and save"), QMessageBox::DestructiveRole); msg_dialog.setDefaultButton(QMessageBox::Cancel); } #if defined(Q_OS_MAC) /* * In macOS, the "default button" is not necessarily the button that * has the input focus; Enter/Return activates the default button, and * the spacebar activates the button that has the input focus, and * they might be different buttons. * * In a "do you want to save" dialog, for example, the "save" button * is the default button, and the "don't save" button has the input * focus, so you can press Enter/Return to save or space not to save * (or Escape to dismiss the dialog). * * In Qt terms, this means "no auto-default", as auto-default makes the * button with the input focus the default button, so that Enter/Return * will activate it. */ QList<QAbstractButton *> buttons = msg_dialog.buttons(); for (int i = 0; i < buttons.size(); ++i) { QPushButton *button = static_cast<QPushButton *>(buttons.at(i));; button->setAutoDefault(false); } /* * It also means that the "don't save" button should be the one * initially given the focus. */ discard_button->setFocus(); #endif msg_dialog.exec(); /* According to the Qt doc: * when using QMessageBox with custom buttons, exec() function returns an opaque value. * * Therefore we should use clickedButton() to determine which button was clicked. */ if (msg_dialog.clickedButton() == save_button) { /* OK, the only other format we support is pcapng. Make that the one and only format in the combo box, and return to let the user continue with the dialog. XXX - removing all the formats from the combo box will clear the compressed checkbox; get the current value and restore it. XXX - we know pcapng can be compressed; if we ever end up supporting saving comments in a format that *can't* be compressed, such as NetMon format, we must check this. */ /* XXX - need a compressed checkbox here! */ return SAVE_IN_ANOTHER_FORMAT; } else if (msg_dialog.clickedButton() == discard_button) { /* Save without the comments and, if that succeeds, delete the comments. */ return SAVE_WITHOUT_COMMENTS; } /* Just give up. */ return CANCELLED; } #ifndef Q_OS_WIN void CaptureFileDialog::accept() { // // If this is a dialog for writing files, we want to ensure that // the filename has a valid extension before performing file // existence checks and before closing the dialog. // This isn't necessary for dialogs for reading files; the name // has to exactly match the name of the file you want to open, // and doesn't need to be, and shouldn't be, modified. // // XXX also useful for Windows, but that uses a different dialog... // if (acceptMode() == QFileDialog::AcceptSave) { // HACK: ensure that the filename field does not have the focus, // otherwise selectFile will not change the filename. setFocus(); fixFilenameExtension(); } WiresharkFileDialog::accept(); } #endif // ! Q_OS_WIN // You have to use open, merge, saveAs, or exportPackets. We should // probably just make each type a subclass. int CaptureFileDialog::exec() { return QDialog::Rejected; } // Windows // We use native file dialogs here, rather than the Qt dialog #ifdef Q_OS_WIN int CaptureFileDialog::selectedFileType() { return file_type_; } wtap_compression_type CaptureFileDialog::compressionType() { return compression_type_; } int CaptureFileDialog::open(QString &file_name, unsigned int &type, QString &display_filter) { QString title_str = mainApp->windowTitleString(tr("Open Capture File")); GString *fname = g_string_new(file_name.toUtf8().constData()); GString *dfilter = g_string_new(display_filter.toUtf8().constData()); gboolean wof_status; // XXX Add a widget->HWND routine to qt_ui_utils and use it instead. wof_status = win32_open_file((HWND)parentWidget()->effectiveWinId(), title_str.toStdWString().c_str(), fname, &type, dfilter); file_name = fname->str; display_filter = dfilter->str; g_string_free(fname, TRUE); g_string_free(dfilter, TRUE); return (int) wof_status; } check_savability_t CaptureFileDialog::saveAs(QString &file_name, bool must_support_all_comments) { QString title_str = mainApp->windowTitleString(tr("Save Capture File As")); GString *fname = g_string_new(file_name.toUtf8().constData()); gboolean wsf_status; wsf_status = win32_save_as_file((HWND)parentWidget()->effectiveWinId(), title_str.toStdWString().c_str(), cap_file_, fname, &file_type_, &compression_type_, must_support_all_comments); file_name = fname->str; g_string_free(fname, TRUE); if (wsf_status) { return checkSaveAsWithComments(parentWidget(), cap_file_, file_type_); } return CANCELLED; } check_savability_t CaptureFileDialog::exportSelectedPackets(QString &file_name, packet_range_t *range, QString selRange) { QString title_str = mainApp->windowTitleString(tr("Export Specified Packets")); GString *fname = g_string_new(file_name.toUtf8().constData()); gboolean wespf_status; if (selRange.length() > 0) { packet_range_convert_selection_str(range, selRange.toUtf8().constData()); } wespf_status = win32_export_specified_packets_file((HWND)parentWidget()->effectiveWinId(), title_str.toStdWString().c_str(), cap_file_, fname, &file_type_, &compression_type_, range); file_name = fname->str; g_string_free(fname, TRUE); if (wespf_status) { return checkSaveAsWithComments(parentWidget(), cap_file_, file_type_); } return CANCELLED; } int CaptureFileDialog::merge(QString &file_name, QString &display_filter) { QString title_str = mainApp->windowTitleString(tr("Merge Capture File")); GString *fname = g_string_new(file_name.toUtf8().constData()); GString *dfilter = g_string_new(display_filter.toUtf8().constData()); gboolean wmf_status; wmf_status = win32_merge_file((HWND)parentWidget()->effectiveWinId(), title_str.toStdWString().c_str(), fname, dfilter, &merge_type_); file_name = fname->str; display_filter = dfilter->str; g_string_free(fname, TRUE); g_string_free(dfilter, TRUE); return (int) wmf_status; } int CaptureFileDialog::mergeType() { return merge_type_; } #else // ! Q_OS_WIN // Not Windows // We use the Qt dialogs here QString CaptureFileDialog::fileExtensionType(int et, bool extension_globs) { QString extension_type_name; QStringList all_wildcards; QStringList no_compression_suffix_wildcards; GSList *extensions_list; GSList *extension; extension_type_name = wtap_get_file_extension_type_name(et); if (!extension_globs) { return extension_type_name; } extensions_list = wtap_get_file_extension_type_extensions(et); // Get the list of compression-type extensions. GSList *compression_type_extensions = wtap_get_all_compression_type_extensions_list(); /* Construct the list of patterns. */ for (extension = extensions_list; extension != NULL; extension = g_slist_next(extension)) { QString bare_wc = QString("*.%1").arg((char *)extension->data); all_wildcards << bare_wc; // Does this end with a compression suffix? bool ends_with_compression_suffix = false; for (GSList *compression_type_extension = compression_type_extensions; compression_type_extension != NULL; compression_type_extension = g_slist_next(compression_type_extension)) { QString suffix = QString(".") + (char *)compression_type_extension->data; if (bare_wc.endsWith(suffix)) { ends_with_compression_suffix = true; break; } } // If it doesn't, add it to the list of wildcards-without- // compression-suffixes. if (!ends_with_compression_suffix) no_compression_suffix_wildcards << bare_wc; } g_slist_free(compression_type_extensions); wtap_free_extensions_list(extensions_list); // We set HideNameFilterDetails so that "All Files" and "All Capture // Files" don't show a wildcard list. We want to show the associated // wildcards for individual file types so we add them twice. return QString("%1 (%2) (%3)") .arg(extension_type_name) .arg(no_compression_suffix_wildcards.join(" ")) .arg(all_wildcards.join(" ")); } // Returns " (...)", containing the suffix list suitable for setNameFilters. // All extensions ("pcap", "pcap.gz", etc.) are also returned in "suffixes". QString CaptureFileDialog::fileType(int ft, QStringList &suffixes) { QString filter; GSList *extensions_list; filter = " ("; extensions_list = wtap_get_file_extensions_list(ft, TRUE); if (extensions_list == NULL) { /* This file type doesn't have any particular extension conventionally used for it, so we'll just use a wildcard that matches all file names - even those with no extension, so we don't need to worry about compressed file extensions. */ filter += ALL_FILES_WILDCARD; } else { // HACK: at least for Qt 5.10 and before, if the first extension is // empty ("."), it will prevent the default (broken) extension // replacement from being applied in the non-native Save file dialog. filter += '.'; /* Construct the list of patterns. */ for (GSList *extension = extensions_list; extension != NULL; extension = g_slist_next(extension)) { QString suffix((char *)extension->data); filter += " *." + suffix;; suffixes << suffix; } wtap_free_extensions_list(extensions_list); } filter += ')'; return filter; } QStringList CaptureFileDialog::buildFileOpenTypeList() { QStringList filters; QString filter, sep; GSList *extensions_list; GSList *extension; int et; /* * Microsoft's UI guidelines say, of the file filters in open and * save dialogs: * * For meta-filters, remove the file extension list to eliminate * clutter. Examples: "All files," "All pictures," "All music," * and "All videos." * * On both Windows XP and Windows 7, Wordpad doesn't do that, but * Paint does. * * XXX - on Windows, does Qt do that here? For "All Capture Files", * the filter will be a bit long, so it *really* shouldn't be shown. * What about other platforms? */ filters << QString(tr("All Files (" ALL_FILES_WILDCARD ")")); /* * Add an "All Capture Files" entry, with all the capture file * extensions we know about. */ filter = tr("All Capture Files"); /* * Construct its list of patterns. */ extensions_list = wtap_get_all_capture_file_extensions_list(); sep = " ("; for (extension = extensions_list; extension != NULL; extension = g_slist_next(extension)) { filter += sep; filter += "*."; filter += (char *)extension->data; sep = " "; } wtap_free_extensions_list(extensions_list); filter += ")"; filters << filter; /* Include all the file types Wireshark supports. */ for (et = 0; et < wtap_get_num_file_type_extensions(); et++) { filters << fileExtensionType(et); } return filters; } // Replaces or appends an extension based on the current file filter // and compression setting. // Used in dialogs that select a file to write. void CaptureFileDialog::fixFilenameExtension() { QFileInfo fi(selectedFiles()[0]); QString filename = fi.fileName(); if (fi.isDir() || filename.isEmpty()) { // no file selected, or a directory was selected. Ignore. return; } QString old_suffix; QString new_suffix(wtap_default_file_extension(selectedFileType())); QStringList valid_extensions = type_suffixes_.value(selectedNameFilter()); // Find suffixes such as "pcap" or "pcap.gz" if any if (!fi.suffix().isEmpty()) { QStringList current_suffixes(fi.suffix()); int pos = static_cast<int>(filename.lastIndexOf('.', -2 - current_suffixes.at(0).size())); if (pos > 0) { current_suffixes.prepend(filename.right(filename.size() - (pos + 1))); } // If the current suffix is valid for the current file type, try to // preserve it. Otherwise use the default file extension (if available). foreach (const QString &current_suffix, current_suffixes) { if (valid_extensions.contains(current_suffix)) { old_suffix = current_suffix; new_suffix = current_suffix; break; } } if (old_suffix.isEmpty()) { foreach (const QString &current_suffix, current_suffixes) { foreach (const QStringList &suffixes, type_suffixes_.values()) { if (suffixes.contains(current_suffix)) { old_suffix = current_suffix; break; } } if (!old_suffix.isEmpty()) { break; } } } } // Fixup the new suffix based on whether we're compressing or not. if (compressionType() == WTAP_UNCOMPRESSED) { // Not compressing; strip off any compression suffix GSList *compression_type_extensions = wtap_get_all_compression_type_extensions_list(); for (GSList *compression_type_extension = compression_type_extensions; compression_type_extension != NULL; compression_type_extension = g_slist_next(compression_type_extension)) { QString suffix = QString(".") + (char *)compression_type_extension->data; if (new_suffix.endsWith(suffix)) { // // It ends with this compression suffix; chop it off. // new_suffix.chop(suffix.size()); break; } } g_slist_free(compression_type_extensions); } else { // Compressing; append the appropriate compression suffix. QString compressed_file_extension = QString(".") + wtap_compression_type_extension(compressionType()); if (valid_extensions.contains(new_suffix + compressed_file_extension)) { new_suffix += compressed_file_extension; } } if (!new_suffix.isEmpty() && old_suffix != new_suffix) { filename.chop(old_suffix.size()); if (old_suffix.isEmpty()) { filename += '.'; } filename += new_suffix; selectFile(filename); } } void CaptureFileDialog::addPreview(QVBoxLayout &v_box) { QGridLayout *preview_grid = new QGridLayout(); QLabel *lbl; preview_labels_.clear(); v_box.addLayout(preview_grid); preview_grid->setColumnStretch(0, 0); preview_grid->setColumnStretch(1, 10); lbl = new QLabel(tr("Format:")); preview_grid->addWidget(lbl, 0, 0); preview_grid->addWidget(&preview_format_, 0, 1); preview_labels_ << lbl << &preview_format_; lbl = new QLabel(tr("Size:")); preview_grid->addWidget(lbl, 1, 0); preview_grid->addWidget(&preview_size_, 1, 1); preview_labels_ << lbl << &preview_size_; lbl = new QLabel(tr("Start / elapsed:")); preview_grid->addWidget(lbl, 3, 0); preview_grid->addWidget(&preview_first_elapsed_, 3, 1); preview_labels_ << lbl << &preview_first_elapsed_; connect(this, &CaptureFileDialog::currentChanged, this, &CaptureFileDialog::preview); preview(""); } void CaptureFileDialog::addMergeControls(QVBoxLayout &v_box) { merge_prepend_.setText(tr("Prepend packets")); merge_prepend_.setToolTip(tr("Insert packets from the selected file before the current file. Packet timestamps will be ignored.")); v_box.addWidget(&merge_prepend_, 0, Qt::AlignTop); merge_chrono_.setText(tr("Merge chronologically")); merge_chrono_.setToolTip(tr("Insert packets in chronological order.")); merge_chrono_.setChecked(true); v_box.addWidget(&merge_chrono_, 0, Qt::AlignTop); merge_append_.setText(tr("Append packets")); merge_append_.setToolTip(tr("Insert packets from the selected file after the current file. Packet timestamps will be ignored.")); v_box.addWidget(&merge_append_, 0, Qt::AlignTop); } int CaptureFileDialog::selectedFileType() { return type_hash_.value(selectedNameFilter(), WTAP_FILE_TYPE_SUBTYPE_UNKNOWN); } wtap_compression_type CaptureFileDialog::compressionType() { return compress_.isChecked() ? WTAP_GZIP_COMPRESSED : WTAP_UNCOMPRESSED; } void CaptureFileDialog::addDisplayFilterEdit(QString &display_filter) { QGridLayout *fd_grid = qobject_cast<QGridLayout*>(layout()); fd_grid->addWidget(new QLabel(tr("Read filter:")), last_row_, 0); display_filter_edit_ = new DisplayFilterEdit(this, ReadFilterToApply); display_filter_edit_->setText(display_filter); fd_grid->addWidget(display_filter_edit_, last_row_, 1); last_row_++; } void CaptureFileDialog::addFormatTypeSelector(QVBoxLayout &v_box) { int i; /* Put Auto, as well as pcap and pcapng (which are the first two entries in open_routines), at the top of the file type list. */ format_type_.addItem(tr("Automatically detect file type")); for (i = 0; i < 2; i += 1) { format_type_.addItem(open_routines[i].name); } /* Generate a sorted list of the remaining file types. */ QStringList routine_names; for ( /* keep using i */ ; open_routines[i].name != NULL; i += 1) { routine_names += QString(open_routines[i].name); } routine_names.sort(Qt::CaseInsensitive); for (i = 0; i < routine_names.size(); i += 1) { format_type_.addItem(routine_names.at(i)); } v_box.addWidget(&format_type_, 0, Qt::AlignTop); } void CaptureFileDialog::addGzipControls(QVBoxLayout &v_box) { compress_.setText(tr("Compress with g&zip")); if (cap_file_->compression_type == WTAP_GZIP_COMPRESSED && wtap_dump_can_compress(default_ft_)) { compress_.setChecked(true); } else { compress_.setChecked(false); } v_box.addWidget(&compress_, 0, Qt::AlignTop); connect(&compress_, &QCheckBox::stateChanged, this, &CaptureFileDialog::fixFilenameExtension); } void CaptureFileDialog::addRangeControls(QVBoxLayout &v_box, packet_range_t *range, QString selRange) { packet_range_group_box_.initRange(range, selRange); v_box.addWidget(&packet_range_group_box_, 0, Qt::AlignTop); } QDialogButtonBox *CaptureFileDialog::addHelpButton(topic_action_e help_topic) { // This doesn't appear to be documented anywhere but it seems pretty obvious // and it works. QDialogButtonBox *button_box = findChild<QDialogButtonBox *>(); help_topic_ = help_topic; if (button_box) { button_box->addButton(QDialogButtonBox::Help); connect(button_box, &QDialogButtonBox::helpRequested, this, &CaptureFileDialog::on_buttonBox_helpRequested); } return button_box; } int CaptureFileDialog::open(QString &file_name, unsigned int &type, QString &display_filter) { setWindowTitle(mainApp->windowTitleString(tr("Open Capture File"))); QStringList open_type_filters(buildFileOpenTypeList()); setNameFilters(open_type_filters); selectNameFilter(open_type_filters.at(1)); setFileMode(QFileDialog::ExistingFile); addFormatTypeSelector(left_v_box_); addDisplayFilterEdit(display_filter); addPreview(right_v_box_); addHelpButton(HELP_OPEN_DIALOG); // Grow the dialog to account for the extra widgets. resize(width() * WIDTH_SCALE_FACTOR, height() * HEIGHT_SCALE_FACTOR + left_v_box_.minimumSize().height() + display_filter_edit_->minimumSize().height()); display_filter.clear(); if (!file_name.isEmpty()) { selectFile(file_name); } if (WiresharkFileDialog::exec() && selectedFiles().length() > 0) { file_name = selectedFiles()[0]; type = open_info_name_to_type(qPrintable(format_type_.currentText())); display_filter.append(display_filter_edit_->text()); return QDialog::Accepted; } else { return QDialog::Rejected; } } check_savability_t CaptureFileDialog::saveAs(QString &file_name, bool must_support_all_comments) { setWindowTitle(mainApp->windowTitleString(tr("Save Capture File As"))); // XXX There doesn't appear to be a way to use setNameFilters without restricting // what the user can select. We might want to use our own combobox instead and // let the user select anything. setNameFilters(buildFileSaveAsTypeList(must_support_all_comments)); setAcceptMode(QFileDialog::AcceptSave); setLabelText(FileType, tr("Save as:")); addGzipControls(left_v_box_); addHelpButton(HELP_SAVE_DIALOG); // Grow the dialog to account for the extra widgets. resize(width() * WIDTH_SCALE_FACTOR, height() * HEIGHT_SCALE_FACTOR + left_v_box_.minimumSize().height()); if (!file_name.isEmpty()) { selectFile(file_name); } connect(this, &QFileDialog::filterSelected, this, &CaptureFileDialog::fixFilenameExtension); if (WiresharkFileDialog::exec() && selectedFiles().length() > 0) { int file_type; file_name = selectedFiles()[0]; file_type = selectedFileType(); /* Is the file type bogus? */ if (file_type == WTAP_FILE_TYPE_SUBTYPE_UNKNOWN) { /* This "should not happen". */ QMessageBox msg_dialog; msg_dialog.setIcon(QMessageBox::Critical); msg_dialog.setText(tr("Unknown file type returned by save as dialog.")); msg_dialog.setInformativeText(tr("Please report this as a Wireshark issue at https://gitlab.com/wireshark/wireshark/-/issues.")); msg_dialog.exec(); return CANCELLED; } return checkSaveAsWithComments(this, cap_file_, file_type); } return CANCELLED; } check_savability_t CaptureFileDialog::exportSelectedPackets(QString &file_name, packet_range_t *range, QString selRange) { QDialogButtonBox *button_box; setWindowTitle(mainApp->windowTitleString(tr("Export Specified Packets"))); // XXX See comment in ::saveAs regarding setNameFilters setNameFilters(buildFileSaveAsTypeList(false)); setAcceptMode(QFileDialog::AcceptSave); setLabelText(FileType, tr("Export as:")); addRangeControls(left_v_box_, range, selRange); addGzipControls(right_v_box_); button_box = addHelpButton(HELP_EXPORT_FILE_DIALOG); if (button_box) { save_bt_ = button_box->button(QDialogButtonBox::Save); if (save_bt_) { connect(&packet_range_group_box_, &PacketRangeGroupBox::validityChanged, save_bt_, &QPushButton::setEnabled); } } // Grow the dialog to account for the extra widgets. resize(width() * WIDTH_SCALE_FACTOR, height() * HEIGHT_SCALE_FACTOR + (packet_range_group_box_.height() * 2 / 3)); if (!file_name.isEmpty()) { selectFile(file_name); } connect(this, &QFileDialog::filterSelected, this, &CaptureFileDialog::fixFilenameExtension); if (WiresharkFileDialog::exec() && selectedFiles().length() > 0) { int file_type; file_name = selectedFiles()[0]; file_type = selectedFileType(); /* Is the file type bogus? */ if (file_type == WTAP_FILE_TYPE_SUBTYPE_UNKNOWN) { /* This "should not happen". */ QMessageBox msg_dialog; msg_dialog.setIcon(QMessageBox::Critical); msg_dialog.setText(tr("Unknown file type returned by save as dialog.")); msg_dialog.setInformativeText(tr("Please report this as a Wireshark issue at https://gitlab.com/wireshark/wireshark/-/issues.")); msg_dialog.exec(); return CANCELLED; } return checkSaveAsWithComments(this, cap_file_, file_type); } return CANCELLED; } int CaptureFileDialog::merge(QString &file_name, QString &display_filter) { setWindowTitle(mainApp->windowTitleString(tr("Merge Capture File"))); setNameFilters(buildFileOpenTypeList()); setFileMode(QFileDialog::ExistingFile); addDisplayFilterEdit(display_filter); addMergeControls(left_v_box_); addPreview(right_v_box_); addHelpButton(HELP_MERGE_DIALOG); file_name.clear(); display_filter.clear(); // Grow the dialog to account for the extra widgets. resize(width() * WIDTH_SCALE_FACTOR, height() * HEIGHT_SCALE_FACTOR + right_v_box_.minimumSize().height() + display_filter_edit_->minimumSize().height()); if (WiresharkFileDialog::exec() && selectedFiles().length() > 0) { file_name.append(selectedFiles()[0]); display_filter.append(display_filter_edit_->text()); return QDialog::Accepted; } else { return QDialog::Rejected; } } QStringList CaptureFileDialog::buildFileSaveAsTypeList(bool must_support_all_comments) { QStringList filters; guint32 required_comment_types; GArray *savable_file_types_subtypes; guint i; type_hash_.clear(); type_suffixes_.clear(); /* What types of comments do we have to support? */ if (must_support_all_comments) required_comment_types = cf_comment_types(cap_file_); /* all the ones the file has */ else required_comment_types = 0; /* none of them */ /* What types of file can we save this file as? */ savable_file_types_subtypes = wtap_get_savable_file_types_subtypes_for_file(cap_file_->cd_t, cap_file_->linktypes, required_comment_types, FT_SORT_BY_DESCRIPTION); if (savable_file_types_subtypes != NULL) { int ft; /* OK, we have at least one file type we can save this file as. (If we didn't, we shouldn't have gotten here in the first place.) Add them all to the combo box. */ for (i = 0; i < savable_file_types_subtypes->len; i++) { ft = g_array_index(savable_file_types_subtypes, int, i); if (default_ft_ < 1) default_ft_ = ft; /* first file type is the default */ QString type_name(wtap_file_type_subtype_description(ft)); filters << type_name + fileType(ft, type_suffixes_[type_name]); type_hash_[type_name] = ft; } g_array_free(savable_file_types_subtypes, TRUE); } return filters; } int CaptureFileDialog::mergeType() { if (merge_prepend_.isChecked()) return -1; else if (merge_append_.isChecked()) return 1; return 0; } // Slots /* do a preview run on the currently selected capture file */ void CaptureFileDialog::preview(const QString & path) { wtap *wth; int err; gchar *err_info; ws_file_preview_stats stats; ws_file_preview_stats_status status; time_t ti_time; struct tm *ti_tm; unsigned int elapsed_time; foreach (QLabel *lbl, preview_labels_) { lbl->setEnabled(false); } preview_format_.setText(tr(UTF8_EM_DASH)); preview_size_.setText(tr(UTF8_EM_DASH)); preview_first_elapsed_.setText(tr(UTF8_EM_DASH)); if (path.length() < 1) { return; } if (test_for_directory(path.toUtf8().data()) == EISDIR) { preview_format_.setText(tr("directory")); return; } wth = wtap_open_offline(path.toUtf8().data(), WTAP_TYPE_AUTO, &err, &err_info, TRUE); if (wth == NULL) { if (err == WTAP_ERR_FILE_UNKNOWN_FORMAT) { preview_format_.setText(tr("unknown file format")); } else { preview_format_.setText(tr("error opening file")); } return; } // Success! foreach (QLabel *lbl, preview_labels_) { lbl->setEnabled(true); } // Format preview_format_.setText(QString::fromUtf8(wtap_file_type_subtype_description(wtap_file_type_subtype(wth)))); // Size gint64 filesize = wtap_file_size(wth, &err); // Finder and Windows Explorer use IEC. What do the various Linux file managers use? QString size_str(gchar_free_to_qstring(format_size(filesize, FORMAT_SIZE_UNIT_BYTES, FORMAT_SIZE_PREFIX_IEC))); status = get_stats_for_preview(wth, &stats, &err, &err_info); if (status == PREVIEW_READ_ERROR) { // XXX - give error details? g_free(err_info); preview_size_.setText(tr("%1, error after %Ln data record(s)", "", stats.records) .arg(size_str)); return; } // Packet count if (status == PREVIEW_TIMED_OUT) { preview_size_.setText(tr("%1, timed out at %Ln data record(s)", "", stats.data_records) .arg(size_str)); } else { preview_size_.setText(tr("%1, %Ln data record(s)", "", stats.data_records) .arg(size_str)); } // First packet + elapsed time QString first_elapsed; if (stats.have_times) { // // We saw at least one record with a time stamp, so we can give // a start time (if we have a mix of records with and without // time stamps, and there were records without time stamps // before the first one with a time stamp, this may be inaccurate). // ti_time = (long)stats.start_time; ti_tm = localtime(&ti_time); first_elapsed = "?"; if (ti_tm) { first_elapsed = QString("%1-%2-%3 %4:%5:%6") .arg(ti_tm->tm_year + 1900, 4, 10, QChar('0')) .arg(ti_tm->tm_mon + 1, 2, 10, QChar('0')) .arg(ti_tm->tm_mday, 2, 10, QChar('0')) .arg(ti_tm->tm_hour, 2, 10, QChar('0')) .arg(ti_tm->tm_min, 2, 10, QChar('0')) .arg(ti_tm->tm_sec, 2, 10, QChar('0')); } } else { first_elapsed = tr("unknown"); } // Elapsed time first_elapsed += " / "; if (status == PREVIEW_SUCCEEDED && stats.have_times) { // // We didn't time out, so we looked at all packets, and we got // at least one packet with a time stamp, so we can calculate // an elapsed time from the time stamp of the last packet with // with a time stamp (if we have a mix of records with and without // time stamps, and there were records without time stamps after // the last one with a time stamp, this may be inaccurate). // elapsed_time = (unsigned int)(stats.stop_time-stats.start_time); if (elapsed_time/86400) { first_elapsed += QString("%1 days ").arg(elapsed_time/86400, 2, 10, QChar('0')); elapsed_time = elapsed_time % 86400; } first_elapsed += QString("%2:%3:%4") .arg(elapsed_time%86400/3600, 2, 10, QChar('0')) .arg(elapsed_time%3600/60, 2, 10, QChar('0')) .arg(elapsed_time%60, 2, 10, QChar('0')); } else { first_elapsed += tr("unknown"); } preview_first_elapsed_.setText(first_elapsed); wtap_close(wth); } void CaptureFileDialog::on_buttonBox_helpRequested() { if (help_topic_ != TOPIC_ACTION_NONE) mainApp->helpTopicAction(help_topic_); } #endif // ! Q_OS_WIN
C/C++
wireshark/ui/qt/capture_file_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef CAPTURE_FILE_DIALOG_H #define CAPTURE_FILE_DIALOG_H #include <ui/qt/widgets/wireshark_file_dialog.h> #ifndef Q_OS_WIN #include <ui/qt/widgets/display_filter_edit.h> #include "packet_range_group_box.h" #include "ui/help_url.h" #endif // Q_OS_WIN #include <ui/packet_range.h> #include <ui/qt/models/packet_list_record.h> #include "cfile.h" #include "ui/file_dialog.h" #include <QVBoxLayout> #include <QLabel> #include <QRadioButton> #include <QCheckBox> #include <QDialogButtonBox> #include <QComboBox> class CaptureFileDialog : public WiresharkFileDialog { // The GTK+ Open Capture File dialog has the following elements and features: // - The ability to select a capture file from a list of known extensions // - A display filter entry // - Name resolution checkboxes // - Capture file preview information // Ideally we should provide similar functionality here. // // You can subclass QFileDialog (which we've done here) and add widgets as // described at // https://web.archive.org/web/20100528190736/http://developer.qt.nokia.com/faq/answer/how_can_i_add_widgets_to_my_qfiledialog_instance // However, Qt's idea of what a file dialog looks like isn't what Microsoft // and Apple think a file dialog looks like. // // On Windows Vista and later we should probably use IFileOpenDialog. On earlier // versions of Windows (including XP) we should use GetOpenFileName, which is // what we do in ui/win32/file_dlg_win32.c. macOS we should use NSOpenPanel. On // other platforms we should fall back to QFileDialog. // // Yes, that's four implementations of the same window. // // If a plain native open file dialog is good enough we can just the static // version of QFileDialog::getOpenFileName. (Commenting out Q_OBJECT and // "explicit" below has the same effect.) Q_OBJECT public: explicit CaptureFileDialog(QWidget *parent = NULL, capture_file *cf = NULL); static check_savability_t checkSaveAsWithComments(QWidget * #if defined(Q_OS_WIN) parent #endif // Q_OS_WIN , capture_file *cf, int file_type); int mergeType(); int selectedFileType(); wtap_compression_type compressionType(); private: capture_file *cap_file_; #if !defined(Q_OS_WIN) void addMergeControls(QVBoxLayout &v_box); void addFormatTypeSelector(QVBoxLayout &v_box); void addDisplayFilterEdit(QString &display_filter); void addPreview(QVBoxLayout &v_box); QString fileExtensionType(int et, bool extension_globs = true); QString fileType(int ft, QStringList &suffixes); QStringList buildFileOpenTypeList(void); QVBoxLayout left_v_box_; QVBoxLayout right_v_box_; DisplayFilterEdit* display_filter_edit_; int last_row_; QLabel preview_format_; QLabel preview_size_; QLabel preview_first_elapsed_; QList<QLabel *> preview_labels_; QRadioButton merge_prepend_; QRadioButton merge_chrono_; QRadioButton merge_append_; QComboBox format_type_; QHash<QString, int> type_hash_; QHash<QString, QStringList> type_suffixes_; void addGzipControls(QVBoxLayout &v_box); void addRangeControls(QVBoxLayout &v_box, packet_range_t *range, QString selRange = QString()); QDialogButtonBox *addHelpButton(topic_action_e help_topic); QStringList buildFileSaveAsTypeList(bool must_support_comments); int default_ft_; QCheckBox compress_; PacketRangeGroupBox packet_range_group_box_; QPushButton *save_bt_; topic_action_e help_topic_; #else // Q_OS_WIN int file_type_; int merge_type_; wtap_compression_type compression_type_; #endif // Q_OS_WIN signals: public slots: #ifndef Q_OS_WIN void accept() Q_DECL_OVERRIDE; #endif int exec() Q_DECL_OVERRIDE; int open(QString &file_name, unsigned int &type, QString &display_filter); check_savability_t saveAs(QString &file_name, bool must_support_comments); check_savability_t exportSelectedPackets(QString &file_name, packet_range_t *range, QString selRange = QString()); int merge(QString &file_name, QString &display_filter); private slots: #if !defined(Q_OS_WIN) void fixFilenameExtension(); void preview(const QString & path); void on_buttonBox_helpRequested(); #endif // Q_OS_WIN }; #endif // CAPTURE_FILE_DIALOG_H
C++
wireshark/ui/qt/capture_file_properties_dialog.cpp
/* capture_file_properties_dialog.cpp * * GSoC 2013 - QtShark * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "capture_file_properties_dialog.h" #include <ui_capture_file_properties_dialog.h> #include "ui/simple_dialog.h" #include "ui/summary.h" #include "wsutil/str_util.h" #include "wsutil/utf8_entities.h" #include "wsutil/version_info.h" #include <ui/qt/utils/qt_ui_utils.h> #include "main_application.h" #include <QPushButton> #include <QScrollBar> #include <QTextStream> // To do: // - Add file hashes // - Add formats (HTML, plain text, YAML)? CaptureFilePropertiesDialog::CaptureFilePropertiesDialog(QWidget &parent, CaptureFile &capture_file) : WiresharkDialog(parent, capture_file), ui(new Ui::CaptureFilePropertiesDialog) { ui->setupUi(this); loadGeometry(parent.width() * 2 / 3, parent.height()); ui->detailsTextEdit->setAcceptRichText(true); // make the details box larger than the comments ui->splitter->setStretchFactor(0, 6); ui->splitter->setStretchFactor(1, 1); QPushButton *button = ui->buttonBox->button(QDialogButtonBox::Reset); if (button) { button->setText(tr("Refresh")); } button = ui->buttonBox->button(QDialogButtonBox::Apply); if (button) { button->setText(tr("Copy To Clipboard")); } button = ui->buttonBox->button(QDialogButtonBox::Save); if (button) { button->setText(tr("Save Comments")); } button = ui->buttonBox->button(QDialogButtonBox::Close); if (button) { button->setDefault(true); } setWindowSubtitle(tr("Capture File Properties")); QTimer::singleShot(0, this, SLOT(updateWidgets())); } /* * Slots */ CaptureFilePropertiesDialog::~CaptureFilePropertiesDialog() { delete ui; } /**/ void CaptureFilePropertiesDialog::updateWidgets() { QPushButton *refresh_bt = ui->buttonBox->button(QDialogButtonBox::Reset); QPushButton *save_bt = ui->buttonBox->button(QDialogButtonBox::Save); if (file_closed_ || !cap_file_.isValid()) { if (refresh_bt) { refresh_bt->setEnabled(false); } ui->commentsTextEdit->setReadOnly(true); if (save_bt) { save_bt->setEnabled(false); } WiresharkDialog::updateWidgets(); return; } bool enable = wtap_dump_can_write(cap_file_.capFile()->linktypes, WTAP_COMMENT_PER_SECTION); save_bt->setEnabled(enable); ui->commentsTextEdit->setEnabled(enable); fillDetails(); // XXX - this just handles the first comment in the first section; // add support for multiple sections with multiple comments. wtap_block_t shb = wtap_file_get_shb(cap_file_.capFile()->provider.wth, 0); char *shb_comment; if (wtap_block_get_nth_string_option_value(shb, OPT_COMMENT, 0, &shb_comment) == WTAP_OPTTYPE_SUCCESS) ui->commentsTextEdit->setText(shb_comment); else ui->commentsTextEdit->setText(NULL); WiresharkDialog::updateWidgets(); } static const QString section_tmpl_ = "<p><strong>%1</strong></p>\n"; static const QString para_tmpl_ = "<p>%1</p>\n"; QString CaptureFilePropertiesDialog::summaryToHtml() { summary_tally summary; double seconds = 0.0; double disp_seconds = 0.0; double marked_seconds = 0.0; memset(&summary, 0, sizeof(summary_tally)); QString table_begin, table_end; QString table_row_begin, table_ul_row_begin, table_row_end; QString table_vheader_tmpl, table_hheader20_tmpl, table_hheader25_tmpl; QString table_data_tmpl; table_begin = "<p><table>\n"; table_end = "</table></p>\n"; table_row_begin = "<tr>\n"; table_ul_row_begin = "<tr style=\"border-bottom: 1px solid gray;\">\n"; table_row_end = "</tr>\n"; table_vheader_tmpl = "<td width=\"20%\">%1:</td>"; // <th align="left"> looked odd table_hheader20_tmpl = "<td width=\"20%\"><u>%1</u></td>"; table_hheader25_tmpl = "<td width=\"25%\"><u>%1</u></td>"; table_data_tmpl = "<td>%1</td>"; if (!file_closed_) { /* initial computations */ summary_fill_in(cap_file_.capFile(), &summary); #ifdef HAVE_LIBPCAP summary_fill_in_capture(cap_file_.capFile(), &global_capture_opts, &summary); #endif } seconds = summary.stop_time - summary.start_time; disp_seconds = summary.filtered_stop - summary.filtered_start; marked_seconds = summary.marked_stop - summary.marked_start; QString summary_str; QTextStream out(&summary_str); QString unknown = tr("Unknown"); // File Section out << section_tmpl_.arg(tr("File")); out << table_begin; out << table_row_begin << table_vheader_tmpl.arg(tr("Name")) << table_data_tmpl.arg(summary.filename) << table_row_end; out << table_row_begin << table_vheader_tmpl.arg(tr("Length")) << table_data_tmpl.arg(file_size_to_qstring(summary.file_length)) << table_row_end; out << table_row_begin << table_vheader_tmpl.arg(tr("Hash (SHA256)")) << table_data_tmpl.arg(summary.file_sha256) << table_row_end; out << table_row_begin << table_vheader_tmpl.arg(tr("Hash (SHA1)")) << table_data_tmpl.arg(summary.file_sha1) << table_row_end; QString format_str = wtap_file_type_subtype_description(summary.file_type); const char *compression_type_description = wtap_compression_type_description(summary.compression_type); if (compression_type_description != nullptr) { format_str += QString(" (%1)").arg(compression_type_description); } out << table_row_begin << table_vheader_tmpl.arg(tr("Format")) << table_data_tmpl.arg(format_str) << table_row_end; QString encaps_str; if (summary.file_encap_type == WTAP_ENCAP_PER_PACKET) { for (guint i = 0; i < summary.packet_encap_types->len; i++) { encaps_str = QString(wtap_encap_description(g_array_index(summary.packet_encap_types, int, i))); } } else { encaps_str = QString(wtap_encap_description(summary.file_encap_type)); } out << table_row_begin << table_vheader_tmpl.arg(tr("Encapsulation")) << table_data_tmpl.arg(encaps_str) << table_row_end; if (summary.snap != 0) { out << table_row_begin << table_vheader_tmpl.arg(tr("Snapshot length")) << table_data_tmpl.arg(summary.snap) << table_row_end; } out << table_end; // Time Section if (summary.packet_count_ts == summary.packet_count && summary.packet_count >= 1) { out << section_tmpl_.arg(tr("Time")); out << table_begin; // start time out << table_row_begin << table_vheader_tmpl.arg(tr("First packet")) << table_data_tmpl.arg(time_t_to_qstring((time_t)summary.start_time)) << table_row_end; // stop time out << table_row_begin << table_vheader_tmpl.arg(tr("Last packet")) << table_data_tmpl.arg(time_t_to_qstring((time_t)summary.stop_time)) << table_row_end; // elapsed seconds (capture duration) if (summary.packet_count_ts >= 2) { /* elapsed seconds */ QString elapsed_str; unsigned int elapsed_time = (unsigned int)summary.elapsed_time; if (elapsed_time/86400) { elapsed_str = QString("%1 days ").arg(elapsed_time / 86400); } elapsed_str += QString("%1:%2:%3") .arg(elapsed_time % 86400 / 3600, 2, 10, QChar('0')) .arg(elapsed_time % 3600 / 60, 2, 10, QChar('0')) .arg(elapsed_time % 60, 2, 10, QChar('0')); out << table_row_begin << table_vheader_tmpl.arg(tr("Elapsed")) << table_data_tmpl.arg(elapsed_str) << table_row_end; } out << table_end; } // Information from file sections. for (guint section_number = 0; section_number < wtap_file_get_num_shbs(cap_file_.capFile()->provider.wth); section_number++) { // If we have more than one section, add headers for each section. if (wtap_file_get_num_shbs(cap_file_.capFile()->provider.wth) > 1) out << section_tmpl_.arg(QString(tr("Section %1")) .arg(section_number)); // Capture Section out << section_tmpl_.arg(tr("Capture")); out << table_begin; wtap_block_t shb_inf = wtap_file_get_shb(cap_file_.capFile()->provider.wth, section_number); char *str; if (shb_inf != nullptr) { QString capture_hardware(unknown); if (wtap_block_get_string_option_value(shb_inf, OPT_SHB_HARDWARE, &str) == WTAP_OPTTYPE_SUCCESS) { if (str[0] != '\0') { capture_hardware = str; } } // capture HW out << table_row_begin << table_vheader_tmpl.arg(tr("Hardware")) << table_data_tmpl.arg(capture_hardware) << table_row_end; QString capture_os(unknown); if (wtap_block_get_string_option_value(shb_inf, OPT_SHB_OS, &str) == WTAP_OPTTYPE_SUCCESS) { if (str[0] != '\0') { capture_os = str; } } out << table_row_begin << table_vheader_tmpl.arg(tr("OS")) << table_data_tmpl.arg(capture_os) << table_row_end; QString capture_app(unknown); if (wtap_block_get_string_option_value(shb_inf, OPT_SHB_USERAPPL, &str) == WTAP_OPTTYPE_SUCCESS) { if (str[0] != '\0') { capture_app = str; } } out << table_row_begin << table_vheader_tmpl.arg(tr("Application")) << table_data_tmpl.arg(capture_app) << table_row_end; } out << table_end; // capture interfaces info if (summary.ifaces->len > 0) { out << section_tmpl_.arg(tr("Interfaces")); out << table_begin; out << table_ul_row_begin << table_hheader20_tmpl.arg(tr("Interface")) << table_hheader20_tmpl.arg(tr("Dropped packets")) << table_hheader20_tmpl.arg(tr("Capture filter")) << table_hheader20_tmpl.arg(tr("Link type")) << table_hheader20_tmpl.arg(tr("Packet size limit (snaplen)")) << table_row_end; } for (guint i = 0; i < summary.ifaces->len; i++) { iface_summary_info iface; iface = g_array_index(summary.ifaces, iface_summary_info, i); /* interface */ QString interface_name(unknown); if (iface.descr) { interface_name = iface.descr; } else if (iface.name) { interface_name = iface.name; } /* Dropped count */ QString interface_drops(unknown); if (iface.drops_known) { interface_drops = QString("%1 (%2%)").arg(iface.drops).arg(QString::number( /* MSVC cannot convert from unsigned __int64 to float, so first convert to signed __int64 */ summary.packet_count ? (100.0 * (gint64)iface.drops)/summary.packet_count : 0, 'f', 1)); } /* Capture filter */ QString interface_cfilter(unknown); if (iface.cfilter && iface.cfilter[0] != '\0') { interface_cfilter = iface.cfilter; } else if (iface.name) { interface_cfilter = QString(tr("none")); } QString interface_snaplen = QString(tr("%1 bytes").arg(iface.snap)); out << table_row_begin << table_data_tmpl.arg(interface_name) << table_data_tmpl.arg(interface_drops) << table_data_tmpl.arg(interface_cfilter) << table_data_tmpl.arg(wtap_encap_description(iface.encap_type)) << table_data_tmpl.arg(interface_snaplen) << table_row_end; } if (summary.ifaces->len > 0) { out << table_end; } } // Statistics Section out << section_tmpl_.arg(tr("Statistics")); out << table_begin; out << table_ul_row_begin << table_hheader25_tmpl.arg(tr("Measurement")) << table_hheader25_tmpl.arg(tr("Captured")) << table_hheader25_tmpl.arg(tr("Displayed")) << table_hheader25_tmpl.arg(tr("Marked")) << table_row_end; QString n_a = UTF8_EM_DASH; QString captured_str, displayed_str, marked_str; // Packets displayed_str = marked_str = n_a; if (summary.filtered_count > 0 && summary.packet_count > 0) { displayed_str = QString("%1 (%2%)") .arg(summary.filtered_count) .arg(100.0 * summary.filtered_count / summary.packet_count, 1, 'f', 1); } if (summary.packet_count > 0 && summary.marked_count > 0) { marked_str = QString("%1 (%2%)") .arg(summary.marked_count) .arg(100.0 * summary.marked_count / summary.packet_count, 1, 'f', 1); } out << table_row_begin << table_data_tmpl.arg(tr("Packets")) << table_data_tmpl.arg(summary.packet_count) << table_data_tmpl.arg(displayed_str) << table_data_tmpl.arg(marked_str) << table_row_end; // Time between first and last captured_str = displayed_str = marked_str = n_a; if (seconds > 0) { captured_str = QString("%1").arg(seconds, 1, 'f', 3); } if (disp_seconds > 0) { displayed_str = QString("%1").arg(disp_seconds, 1, 'f', 3); } if (marked_seconds > 0) { marked_str = QString("%1").arg(marked_seconds, 1, 'f', 3); } out << table_row_begin << table_data_tmpl.arg(tr("Time span, s")) << table_data_tmpl.arg(captured_str) << table_data_tmpl.arg(displayed_str) << table_data_tmpl.arg(marked_str) << table_row_end; // Average packets per second captured_str = displayed_str = marked_str = n_a; if (seconds > 0) { captured_str = QString("%1").arg(summary.packet_count/seconds, 1, 'f', 1); } if (disp_seconds > 0) { displayed_str = QString("%1").arg(summary.filtered_count/disp_seconds, 1, 'f', 1); } if (marked_seconds > 0) { marked_str = QString("%1").arg(summary.marked_count/marked_seconds, 1, 'f', 1); } out << table_row_begin << table_data_tmpl.arg(tr("Average pps")) << table_data_tmpl.arg(captured_str) << table_data_tmpl.arg(displayed_str) << table_data_tmpl.arg(marked_str) << table_row_end; // Average packet size captured_str = displayed_str = marked_str = n_a; if (summary.packet_count > 0) { captured_str = QString::number((guint64) ((double)summary.bytes/summary.packet_count + 0.5)); } if (summary.filtered_count > 0) { displayed_str = QString::number((guint64) ((double)summary.filtered_bytes/summary.filtered_count + 0.5)); } if (summary.marked_count > 0) { marked_str = QString::number((guint64) ((double)summary.marked_bytes/summary.marked_count + 0.5)); } out << table_row_begin << table_data_tmpl.arg(tr("Average packet size, B")) << table_data_tmpl.arg(captured_str) << table_data_tmpl.arg(displayed_str) << table_data_tmpl.arg(marked_str) << table_row_end; // Byte count displayed_str = marked_str = "0"; if (summary.bytes > 0 && summary.filtered_bytes > 0) { displayed_str = QString("%1 (%2%)") .arg(summary.filtered_bytes) .arg(100.0 * summary.filtered_bytes / summary.bytes, 1, 'f', 1); } if (summary.bytes > 0 && summary.marked_bytes > 0) { marked_str = QString("%1 (%2%)") .arg(summary.marked_bytes) .arg(100.0 * summary.marked_bytes / summary.bytes, 1, 'f', 1); } out << table_row_begin << table_data_tmpl.arg(tr("Bytes")) << table_data_tmpl.arg(summary.bytes) << table_data_tmpl.arg(displayed_str) << table_data_tmpl.arg(marked_str) << table_row_end; // Bytes per second captured_str = displayed_str = marked_str = n_a; if (seconds > 0) { captured_str = gchar_free_to_qstring(format_size(summary.bytes / seconds, FORMAT_SIZE_UNIT_NONE, FORMAT_SIZE_PREFIX_SI)); } if (disp_seconds > 0) { displayed_str = gchar_free_to_qstring(format_size(summary.filtered_bytes / disp_seconds, FORMAT_SIZE_UNIT_NONE, FORMAT_SIZE_PREFIX_SI)); } if (marked_seconds > 0) { marked_str = gchar_free_to_qstring(format_size(summary.marked_bytes / marked_seconds, FORMAT_SIZE_UNIT_NONE, FORMAT_SIZE_PREFIX_SI)); } out << table_row_begin << table_data_tmpl.arg(tr("Average bytes/s")) << table_data_tmpl.arg(captured_str) << table_data_tmpl.arg(displayed_str) << table_data_tmpl.arg(marked_str) << table_row_end; // Bits per second captured_str = displayed_str = marked_str = n_a; if (seconds > 0) { captured_str = gchar_free_to_qstring(format_size(summary.bytes * 8 / seconds, FORMAT_SIZE_UNIT_NONE, FORMAT_SIZE_PREFIX_SI)); } if (disp_seconds > 0) { displayed_str = gchar_free_to_qstring(format_size(summary.filtered_bytes * 8 / disp_seconds, FORMAT_SIZE_UNIT_NONE, FORMAT_SIZE_PREFIX_SI)); } if (marked_seconds > 0) { marked_str = gchar_free_to_qstring(format_size(summary.marked_bytes * 8 / marked_seconds, FORMAT_SIZE_UNIT_NONE, FORMAT_SIZE_PREFIX_SI)); } out << table_row_begin << table_data_tmpl.arg(tr("Average bits/s")) << table_data_tmpl.arg(captured_str) << table_data_tmpl.arg(displayed_str) << table_data_tmpl.arg(marked_str) << table_row_end; out << table_end; return summary_str; } void CaptureFilePropertiesDialog::fillDetails() { if (!cap_file_.isValid()) return; ui->detailsTextEdit->clear(); QTextCursor cursor = ui->detailsTextEdit->textCursor(); QString summary = summaryToHtml(); cursor.insertHtml(summary); cursor.insertBlock(); // Work around rendering oddity. // XXX - this just shows the first comment in the first section; // add support for multiple sections with multiple comments. wtap_block_t shb = wtap_file_get_shb(cap_file_.capFile()->provider.wth, 0); char *shb_comment; if (wtap_block_get_nth_string_option_value(shb, OPT_COMMENT, 0, &shb_comment) == WTAP_OPTTYPE_SUCCESS) { QString section_comment = shb_comment; QString section_comment_html; if (!section_comment.isEmpty()) { QString comment_escaped = html_escape(section_comment).replace('\n', "<br>"); section_comment_html += section_tmpl_.arg(QString(tr("Section Comment"))); section_comment_html += para_tmpl_.arg(comment_escaped); cursor.insertBlock(); cursor.insertHtml(section_comment_html); } } if (cap_file_.capFile()->packet_comment_count > 0) { cursor.insertBlock(); cursor.insertHtml(section_tmpl_.arg(tr("Packet Comments"))); for (guint32 framenum = 1; framenum <= cap_file_.capFile()->count ; framenum++) { frame_data *fdata = frame_data_sequence_find(cap_file_.capFile()->provider.frames, framenum); wtap_block_t pkt_block = cf_get_packet_block(cap_file_.capFile(), fdata); if (pkt_block) { guint n_comments = wtap_block_count_option(pkt_block, OPT_COMMENT); for (guint i = 0; i < n_comments; i++) { char *comment_text; if (WTAP_OPTTYPE_SUCCESS == wtap_block_get_nth_string_option_value(pkt_block, OPT_COMMENT, i, &comment_text)) { QString frame_comment_html = tr("<p>Frame %1: ").arg(framenum); QString raw_comment = comment_text; frame_comment_html += html_escape(raw_comment).replace('\n', "<br>"); frame_comment_html += "</p>\n"; cursor.insertBlock(); cursor.insertHtml(frame_comment_html); } } } wtap_block_unref(pkt_block); } } ui->detailsTextEdit->verticalScrollBar()->setValue(0); } void CaptureFilePropertiesDialog::changeEvent(QEvent* event) { if (event != nullptr) { switch (event->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); updateWidgets(); break; default: break; } } QDialog::changeEvent(event); } void CaptureFilePropertiesDialog::on_buttonBox_helpRequested() { mainApp->helpTopicAction(HELP_STATS_SUMMARY_DIALOG); } void CaptureFilePropertiesDialog::on_buttonBox_accepted() { if (file_closed_ || !cap_file_.capFile()->filename) { return; } if (wtap_dump_can_write(cap_file_.capFile()->linktypes, WTAP_COMMENT_PER_SECTION)) { gchar *str = qstring_strdup(ui->commentsTextEdit->toPlainText()); /* * Make sure this would fit in a pcapng option. * * XXX - 65535 is the maximum size for an option in pcapng; * what if another capture file format supports larger * comments? */ if (strlen(str) > 65535) { /* It doesn't fit. Tell the user and give up. */ simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "That comment is too large to save in a capture file."); return; } cf_update_section_comment(cap_file_.capFile(), str); emit captureCommentChanged(); fillDetails(); } } void CaptureFilePropertiesDialog::on_buttonBox_clicked(QAbstractButton *button) { if (button == ui->buttonBox->button(QDialogButtonBox::Apply)) { QClipboard *clipboard = QApplication::clipboard(); QString details = tr("Created by Wireshark %1\n\n").arg(get_ws_vcs_version_info()); details.append(ui->detailsTextEdit->toPlainText()); clipboard->setText(details); } else if (button == ui->buttonBox->button(QDialogButtonBox::Reset)) { updateWidgets(); } } void CaptureFilePropertiesDialog::on_buttonBox_rejected() { reject(); }
C/C++
wireshark/ui/qt/capture_file_properties_dialog.h
/** @file * * GSoC 2013 - QtShark * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef CAPTURE_FILE_PROPERTIES_DIALOG_H #define CAPTURE_FILE_PROPERTIES_DIALOG_H #include <config.h> #include <glib.h> #include <string.h> #include <time.h> #include <epan/strutil.h> #include <wiretap/wtap.h> #include "file.h" #ifdef HAVE_LIBPCAP #include "ui/capture.h" #include "ui/capture_globals.h" #endif #include "wireshark_dialog.h" #include <QClipboard> namespace Ui { class CaptureFilePropertiesDialog; } class QAbstractButton; class CaptureFilePropertiesDialog : public WiresharkDialog { Q_OBJECT public: explicit CaptureFilePropertiesDialog(QWidget &parent, CaptureFile& capture_file); ~CaptureFilePropertiesDialog(); signals: void captureCommentChanged(); protected slots: void changeEvent(QEvent* event); private: Ui::CaptureFilePropertiesDialog *ui; QString summaryToHtml(); void fillDetails(); private slots: void updateWidgets(); void on_buttonBox_helpRequested(); void on_buttonBox_accepted(); void on_buttonBox_clicked(QAbstractButton *button); void on_buttonBox_rejected(); }; #endif
User Interface
wireshark/ui/qt/capture_file_properties_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>CaptureFilePropertiesDialog</class> <widget class="QDialog" name="CaptureFilePropertiesDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>799</width> <height>585</height> </rect> </property> <property name="sizePolicy"> <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="locale"> <locale language="English" country="UnitedStates"/> </property> <layout class="QVBoxLayout" name="verticalLayout_3"> <item> <widget class="QSplitter" name="splitter"> <property name="orientation"> <enum>Qt::Vertical</enum> </property> <property name="opaqueResize"> <bool>false</bool> </property> <property name="childrenCollapsible"> <bool>false</bool> </property> <widget class="QWidget" name=""> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QLabel" name="detailsLabel"> <property name="text"> <string>Details</string> </property> </widget> </item> <item> <widget class="QTextEdit" name="detailsTextEdit"> <property name="readOnly"> <bool>true</bool> </property> </widget> </item> </layout> </widget> <widget class="QWidget" name=""> <layout class="QVBoxLayout" name="verticalLayout_2"> <item> <widget class="QLabel" name="commentsLabel"> <property name="text"> <string>Capture file comments</string> </property> </widget> </item> <item> <widget class="QTextEdit" name="commentsTextEdit"> <property name="sizeIncrement"> <size> <width>0</width> <height>10</height> </size> </property> </widget> </item> </layout> </widget> </widget> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="standardButtons"> <set>QDialogButtonBox::Apply|QDialogButtonBox::Close|QDialogButtonBox::Help|QDialogButtonBox::Reset|QDialogButtonBox::Save</set> </property> </widget> </item> </layout> </widget> <resources/> <connections/> </ui>
C++
wireshark/ui/qt/capture_filter_syntax_worker.cpp
/* capture_filter_syntax_worker.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #ifdef HAVE_LIBPCAP #include <glib.h> #ifdef __MINGW32__ #include <_bsd_types.h> #endif #include <pcap.h> #include "capture_opts.h" #include "ui/capture_globals.h" #endif #include "extcap.h" #include "capture_filter_syntax_worker.h" #include <ui/qt/widgets/syntax_line_edit.h> #include <QMutexLocker> #include <QSet> // We use a global mutex to protect pcap_compile since it calls gethostbyname. // This probably isn't needed on Windows (where pcap_comple calls // EnterCriticalSection + LeaveCriticalSection) or *BSD or macOS where // gethostbyname(3) claims that it's thread safe. static QMutex pcap_compile_mtx_; #if 0 #include <QDebug> #include <QThread> #define DEBUG_SYNTAX_CHECK(state1, state2) qDebug() << "CF state" << QThread::currentThreadId() << state1 << "->" << state2 << ":" << filter #define DEBUG_SLEEP_TIME 5000 // ms #else #define DEBUG_SYNTAX_CHECK(state1, state2) #define DEBUG_SLEEP_TIME 0 // ms #endif #define DUMMY_SNAPLENGTH 65535 #define DUMMY_NETMASK 0xFF000000 void CaptureFilterSyntaxWorker::checkFilter(const QString filter) { #ifdef HAVE_LIBPCAP QSet<gint> active_dlts; QSet<guint> active_extcap; struct bpf_program fcode; pcap_t *pd; int pc_err; enum SyntaxLineEdit::SyntaxState state = SyntaxLineEdit::Valid; QString err_str; DEBUG_SYNTAX_CHECK("received", "?"); if (global_capture_opts.num_selected < 1) { emit syntaxResult(filter, SyntaxLineEdit::Invalid, QString("No interfaces selected")); DEBUG_SYNTAX_CHECK("unknown", "no interfaces"); return; } for (guint if_idx = 0; if_idx < global_capture_opts.all_ifaces->len; if_idx++) { interface_t *device; device = &g_array_index(global_capture_opts.all_ifaces, interface_t, if_idx); if (device->selected) { if (device->if_info.extcap == NULL || strlen(device->if_info.extcap) == 0) { if (device->active_dlt >= DLT_USER0 && device->active_dlt <= DLT_USER15) { // Capture filter for DLT_USER is unknown state = SyntaxLineEdit::Deprecated; err_str = "Unable to check capture filter"; } else { active_dlts.insert(device->active_dlt); } } else { active_extcap.insert(if_idx); } } } foreach(gint dlt, active_dlts.values()) { pcap_compile_mtx_.lock(); pd = pcap_open_dead(dlt, DUMMY_SNAPLENGTH); if (pd == NULL) { //don't have ability to verify capture filter break; } #ifdef PCAP_NETMASK_UNKNOWN pc_err = pcap_compile(pd, &fcode, filter.toUtf8().data(), 1 /* Do optimize */, PCAP_NETMASK_UNKNOWN); #else pc_err = pcap_compile(pd, &fcode, filter.toUtf8().data(), 1 /* Do optimize */, 0); #endif #if DEBUG_SLEEP_TIME > 0 QThread::msleep(DEBUG_SLEEP_TIME); #endif if (pc_err) { DEBUG_SYNTAX_CHECK("unknown", "known bad"); state = SyntaxLineEdit::Invalid; err_str = pcap_geterr(pd); } else { DEBUG_SYNTAX_CHECK("unknown", "known good"); } pcap_close(pd); pcap_compile_mtx_.unlock(); if (state == SyntaxLineEdit::Invalid) break; } // If it's already invalid, don't bother to check extcap if (state != SyntaxLineEdit::Invalid) { foreach(guint extcapif, active_extcap.values()) { interface_t *device; gchar *error = NULL; device = &g_array_index(global_capture_opts.all_ifaces, interface_t, extcapif); extcap_filter_status status = extcap_verify_capture_filter(device->name, filter.toUtf8().constData(), &error); if (status == EXTCAP_FILTER_VALID) { DEBUG_SYNTAX_CHECK("unknown", "known good"); } else if (status == EXTCAP_FILTER_INVALID) { DEBUG_SYNTAX_CHECK("unknown", "known bad"); state = SyntaxLineEdit::Invalid; err_str = error; break; } else { state = SyntaxLineEdit::Deprecated; err_str = "Unable to check capture filter"; } g_free(error); } } emit syntaxResult(filter, state, err_str); DEBUG_SYNTAX_CHECK("known", "idle"); #else emit syntaxResult(filter, SyntaxLineEdit::Deprecated, QString("Syntax checking unavailable")); #endif // HAVE_LIBPCAP }
C/C++
wireshark/ui/qt/capture_filter_syntax_worker.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef CAPTURE_FILTER_SYNTAX_WORKER_H #define CAPTURE_FILTER_SYNTAX_WORKER_H #include <QMutex> #include <QObject> #include <QWaitCondition> class CaptureFilterSyntaxWorker : public QObject { Q_OBJECT public: CaptureFilterSyntaxWorker(QObject *parent = 0) : QObject(parent) {} public slots: void checkFilter(const QString filter); signals: void syntaxResult(QString filter, int state, QString err_msg); }; #endif // CAPTURE_FILTER_SYNTAX_WORKER_H
C++
wireshark/ui/qt/capture_info_dialog.cpp
/* capture_info_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "wireshark.h" #include "ui/capture_info.h" #include "epan/capture_dissectors.h" #include "epan/proto.h" #include "ui/capture.h" #include "capture_info_dialog.h" #include "ui_capture_info_dialog.h" #include "main_application.h" #include "ui/qt/models/sparkline_delegate.h" #include "utils/qt_ui_utils.h" #include <QMainWindow> #include <QPushButton> // The GTK+ version of this dialog showed a list of protocols and a simple bar graph // (progress bars) showing their portion of the total number of packets. We show a // a time series for each protocol using a sparkline. If we wanted to show bar graphs // instead we could do so using QProgressBars or using PercentBarDelegates. extern "C" { // Callbacks defined in ui/capture_info.h. /* create the capture info dialog */ /* will keep pointers to the fields in the counts parameter */ void capture_info_ui_create( capture_info *cinfo, capture_session *cap_session) { // cinfo->ui should have three values: // - The main window, set in MainWindow::startCapture. // - This dialog, set below. // - NULL, set in our destructor. if (!cinfo || !cinfo->ui) return; if (!cap_session) return; QMainWindow *main_window = qobject_cast<QMainWindow *>((QObject *)cinfo->ui); if (!main_window) return; // ...and we take it over from here. CaptureInfoDialog *ci_dlg = new CaptureInfoDialog(cinfo, cap_session, main_window); cinfo->ui = ci_dlg; ci_dlg->show(); } /* update the capture info dialog */ /* As this function is a bit time critical while capturing, */ /* prepare everything possible in the capture_info_ui_create() function above! */ void capture_info_ui_update( capture_info *cinfo) { CaptureInfoDialog *ci_dlg = qobject_cast<CaptureInfoDialog *>((QObject *)cinfo->ui); if (!ci_dlg) return; ci_dlg->updateInfo(); } /* destroy the capture info dialog again */ void capture_info_ui_destroy( capture_info *cinfo) { CaptureInfoDialog *ci_dlg = qobject_cast<CaptureInfoDialog *>((QObject *)cinfo->ui); if (!ci_dlg) return; cinfo->ui = NULL; delete ci_dlg; } } // extern "C" CaptureInfoDialog::CaptureInfoDialog(struct _capture_info *cap_info, struct _capture_session *cap_session, QWidget *parent) : GeometryStateDialog(parent), ui(new Ui::CaptureInfoDialog), cap_info_(cap_info), cap_session_(cap_session) { ui->setupUi(this); loadGeometry(); setWindowTitle(mainApp->windowTitleString(tr("Capture Information"))); QPushButton *button = ui->buttonBox->button(QDialogButtonBox::Abort); button->setText(tr("Stop Capture")); connect(button, &QPushButton::clicked, this, &CaptureInfoDialog::stopCapture); ci_model_ = new CaptureInfoModel(cap_info, this); ui->treeView->setModel(ci_model_); ui->treeView->setItemDelegateForColumn(1, new SparkLineDelegate(this)); duration_.start(); } CaptureInfoDialog::~CaptureInfoDialog() { delete ui; cap_info_->ui = NULL; } void CaptureInfoDialog::updateInfo() { int secs = int(duration_.elapsed() / 1000); QString duration = tr("%1 packets, %2:%3:%4") .arg(cap_info_->counts->total) .arg(secs / 3600, 2, 10, QChar('0')) .arg(secs % 3600 / 60, 2, 10, QChar('0')) .arg(secs % 60, 2, 10, QChar('0')); ui->infoLabel->setText(duration); ci_model_->updateInfo(); ui->treeView->resizeColumnToContents(0); } void CaptureInfoDialog::stopCapture() { #ifdef HAVE_LIBPCAP capture_stop(cap_session_); // ...or we could connect to MainWindow::stopCapture. #endif // HAVE_LIBPCAP } CaptureInfoModel::CaptureInfoModel(struct _capture_info *cap_info, QObject *parent) : QAbstractTableModel(parent), cap_info_(cap_info), samples_(0), last_other_(0) { } void CaptureInfoModel::updateInfo() { if (!cap_info_) return; GHashTableIter iter; gpointer key, value; samples_++; other_points_.append(cap_info_->counts->other - last_other_); last_other_ = cap_info_->counts->other; g_hash_table_iter_init (&iter, cap_info_->counts->counts_hash); while (g_hash_table_iter_next (&iter, &key, &value)) { int proto_id = GPOINTER_TO_INT(key); int cur_count = (int) capture_dissector_get_count(cap_info_->counts, proto_id); if (!points_.contains(proto_id)) { emit beginInsertRows(QModelIndex(), rowCount(), rowCount()); QVector<int> zeroes = QVector<int>(samples_, 0); points_[proto_id] = zeroes.toList(); last_count_[proto_id] = 0; emit endInsertRows(); } else { points_[proto_id].append(cur_count - last_count_[proto_id]); last_count_[proto_id] = cur_count; } } emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1)); } int CaptureInfoModel::rowCount(const QModelIndex &) const { if (!cap_info_) return 0; return static_cast<int>(points_.keys().size()) + 1; } int CaptureInfoModel::columnCount(const QModelIndex &) const { return 2; } QVariant CaptureInfoModel::data(const QModelIndex &index, int role) const { QList<int> proto_ids = points_.keys(); int row = index.row(); if (role == Qt::DisplayRole && index.column() == 0) { if (row < proto_ids.size()) { int proto_id = proto_ids.at(row); return QString(proto_get_protocol_short_name(find_protocol_by_id(proto_id))); } else { return tr("Other"); } } else if (role == Qt::UserRole && index.column() == 1) { if (row < proto_ids.size()) { int proto_id = proto_ids.at(row); return QVariant::fromValue(points_[proto_id]); } else { return QVariant::fromValue(other_points_); } } return QVariant(); }
C/C++
wireshark/ui/qt/capture_info_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef CAPTURE_INFO_DIALOG_H #define CAPTURE_INFO_DIALOG_H #include "geometry_state_dialog.h" #include <QAbstractTableModel> #include <QElapsedTimer> struct _capture_info; struct _capture_session; namespace Ui { class CaptureInfoDialog; } class CaptureInfoModel : public QAbstractTableModel { Q_OBJECT public: explicit CaptureInfoModel(struct _capture_info *cap_info, QObject * parent = Q_NULLPTR); virtual ~CaptureInfoModel() {} void updateInfo(); virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; virtual int columnCount(const QModelIndex &parent = QModelIndex()) const; virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; // virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; private: struct _capture_info *cap_info_; int samples_; QMap<int, int> last_count_; QMap<int, QList<int> > points_; int last_other_; QList<int> other_points_; }; class CaptureInfoDialog : public GeometryStateDialog { Q_OBJECT public: explicit CaptureInfoDialog(struct _capture_info *cap_info, struct _capture_session *cap_session, QWidget *parent = 0); ~CaptureInfoDialog(); void updateInfo(void); signals: public slots: private slots: void stopCapture(); private: Ui::CaptureInfoDialog *ui; struct _capture_info *cap_info_; struct _capture_session *cap_session_; CaptureInfoModel *ci_model_; QElapsedTimer duration_; }; #endif // CAPTURE_INFO_DIALOG_H
User Interface
wireshark/ui/qt/capture_info_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>CaptureInfoDialog</class> <widget class="QDialog" name="CaptureInfoDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>400</width> <height>275</height> </rect> </property> <property name="sizeGripEnabled"> <bool>true</bool> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QTreeView" name="treeView"> <property name="rootIsDecorated"> <bool>false</bool> </property> <property name="uniformRowHeights"> <bool>true</bool> </property> <property name="itemsExpandable"> <bool>false</bool> </property> <property name="sortingEnabled"> <bool>false</bool> </property> <attribute name="headerVisible"> <bool>false</bool> </attribute> </widget> </item> <item> <widget class="QLabel" name="infoLabel"> <property name="alignment"> <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> </property> </widget> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Abort|QDialogButtonBox::Close</set> </property> </widget> </item> </layout> </widget> <resources/> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>CaptureInfoDialog</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>248</x> <y>254</y> </hint> <hint type="destinationlabel"> <x>157</x> <y>274</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>CaptureInfoDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>316</x> <y>260</y> </hint> <hint type="destinationlabel"> <x>286</x> <y>274</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/capture_options_dialog.cpp
/* capture_options_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include <wireshark.h> #include "capture_options_dialog.h" #include <ui/qt/widgets/capture_filter_combo.h> #include <ui_capture_options_dialog.h> #include "compiled_filter_output.h" #include "manage_interfaces_dialog.h" #include "main_application.h" #include "extcap.h" #ifdef HAVE_LIBPCAP #include <QAbstractItemModel> #include <QMessageBox> #include <QTimer> #include "ringbuffer.h" #include "ui/capture_ui_utils.h" #include "ui/capture_globals.h" #include "ui/iface_lists.h" #include "ui/last_open_dir.h" #include "ui/ws_ui_util.h" #include "ui/util.h" #include <wsutil/utf8_entities.h> #include "ui/preference_utils.h" #include "ui/recent.h" #include <cstdio> #include <epan/prefs.h> #include <epan/prefs-int.h> #include <epan/addr_resolv.h> #include <wsutil/filesystem.h> #include <wiretap/wtap.h> #include <ui/qt/utils/qt_ui_utils.h> #include <ui/qt/utils/stock_icon.h> #include <ui/qt/models/sparkline_delegate.h> #include "ui/qt/widgets/wireshark_file_dialog.h" // To do: // - Set a size hint for item delegates. // - Make promiscuous and monitor mode checkboxes. // - Fix InterfaceTreeDelegate method names. // - You can edit filters via the main CaptureFilterCombo and via each // individual interface row. We should probably do one or the other. const int stat_update_interval_ = 1000; // ms #ifdef CAN_SET_CAPTURE_BUFFER_SIZE #define SHOW_BUFFER_COLUMN 1 #endif #if defined(HAVE_PCAP_CREATE) #define SHOW_MONITOR_COLUMN 1 #endif /* * Symbolic names for column indices. */ enum { col_extcap_ = 0, col_interface_, col_traffic_, col_link_, col_pmode_, col_snaplen_, col_buffer_, col_monitor_, col_filter_, col_num_columns_ }; static interface_t *find_device_by_if_name(const QString &interface_name) { interface_t *device; guint i; for (i = 0; i < global_capture_opts.all_ifaces->len; i++) { device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i); if (!interface_name.compare(device->display_name) && !device->hidden && device->type != IF_PIPE) { return device; } } return NULL; } class InterfaceTreeWidgetItem : public QTreeWidgetItem { public: InterfaceTreeWidgetItem(QTreeWidget *tree) : QTreeWidgetItem(tree) {} bool operator< (const QTreeWidgetItem &other) const; QVariant data(int column, int role) const; void setData(int column, int role, const QVariant &value); QList<int> points; void updateInterfaceColumns(interface_t *device) { if (!device) return; QString default_str = QObject::tr("default"); // XXX - this is duplicated in InterfaceTreeModel::data; // it should be done in common code somewhere. QString linkname; if (device->active_dlt == -1) linkname = "Unknown"; else { linkname = QObject::tr("DLT %1").arg(device->active_dlt); for (GList *list = device->links; list != NULL; list = gxx_list_next(list)) { link_row *linkr = gxx_list_data(link_row *, list); if (linkr->dlt == device->active_dlt) { linkname = linkr->name; break; } } } setText(col_link_, linkname); if (device->if_info.type == IF_EXTCAP) { /* extcap interfaces does not have this settings */ setApplicable(col_pmode_, false); setApplicable(col_snaplen_, false); #ifdef SHOW_BUFFER_COLUMN setApplicable(col_buffer_, false); #endif } else { setApplicable(col_pmode_, true); setCheckState(col_pmode_, device->pmode ? Qt::Checked : Qt::Unchecked); QString snaplen_string = device->has_snaplen ? QString::number(device->snaplen) : default_str; setText(col_snaplen_, snaplen_string); #ifdef SHOW_BUFFER_COLUMN setText(col_buffer_, QString::number(device->buffer)); #endif } setText(col_filter_, device->cfilter); #ifdef SHOW_MONITOR_COLUMN if (device->monitor_mode_supported) { setApplicable(col_monitor_, true); setCheckState(col_monitor_, device->monitor_mode_enabled ? Qt::Checked : Qt::Unchecked); } else { setApplicable(col_monitor_, false); } #endif } void setApplicable(int column, bool applicable = false) { QPalette palette = mainApp->palette(); if (applicable) { setText(column, QString()); } else { setData(column, Qt::CheckStateRole, QVariant()); palette.setCurrentColorGroup(QPalette::Disabled); setText(column, UTF8_EM_DASH); } setForeground(column, palette.text().color()); } }; CaptureOptionsDialog::CaptureOptionsDialog(QWidget *parent) : GeometryStateDialog(parent), ui(new Ui::CaptureOptionsDialog) { ui->setupUi(this); loadGeometry(); setWindowTitle(mainApp->windowTitleString(tr("Capture Options"))); stat_timer_ = NULL; stat_cache_ = NULL; ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Start")); // Start out with the list *not* sorted, so they show up in the order // in which they were provided ui->interfaceTree->sortByColumn(-1, Qt::AscendingOrder); ui->interfaceTree->setItemDelegateForColumn(col_extcap_, &interface_item_delegate_); ui->interfaceTree->setItemDelegateForColumn(col_interface_, &interface_item_delegate_); ui->interfaceTree->setItemDelegateForColumn(col_traffic_, new SparkLineDelegate(this)); ui->interfaceTree->setItemDelegateForColumn(col_link_, &interface_item_delegate_); ui->interfaceTree->setItemDelegateForColumn(col_snaplen_, &interface_item_delegate_); #ifdef SHOW_BUFFER_COLUMN ui->interfaceTree->setItemDelegateForColumn(col_buffer_, &interface_item_delegate_); #else ui->interfaceTree->setColumnHidden(col_buffer_, true); #endif #ifndef SHOW_MONITOR_COLUMN ui->interfaceTree->setColumnHidden(col_monitor_, true); #endif ui->interfaceTree->setItemDelegateForColumn(col_filter_, &interface_item_delegate_); interface_item_delegate_.setTree(ui->interfaceTree); ui->filenameLineEdit->setPlaceholderText(tr("Leave blank to use a temporary file")); ui->rbCompressionNone->setChecked(true); ui->tempDirLineEdit->setPlaceholderText(g_get_tmp_dir()); ui->tempDirLineEdit->setText(global_capture_opts.temp_dir); // Changes in interface selections or capture filters should be propagated // to the main welcome screen where they will be applied to the global // capture options. connect(this, SIGNAL(interfacesChanged()), ui->captureFilterComboBox, SIGNAL(interfacesChanged())); connect(ui->captureFilterComboBox, SIGNAL(captureFilterSyntaxChanged(bool)), this, SLOT(updateWidgets())); connect(ui->captureFilterComboBox->lineEdit(), SIGNAL(textEdited(QString)), this, SLOT(filterEdited())); connect(ui->captureFilterComboBox->lineEdit(), SIGNAL(textEdited(QString)), this, SIGNAL(captureFilterTextEdited(QString))); connect(&interface_item_delegate_, SIGNAL(filterChanged(QString)), ui->captureFilterComboBox->lineEdit(), SLOT(setText(QString))); connect(&interface_item_delegate_, SIGNAL(filterChanged(QString)), this, SIGNAL(captureFilterTextEdited(QString))); connect(this, SIGNAL(ifsChanged()), this, SLOT(refreshInterfaceList())); connect(mainApp, SIGNAL(localInterfaceListChanged()), this, SLOT(updateLocalInterfaces())); connect(ui->browseButton, SIGNAL(clicked()), this, SLOT(browseButtonClicked())); connect(ui->interfaceTree, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(itemClicked(QTreeWidgetItem*,int))); connect(ui->interfaceTree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this, SLOT(itemDoubleClicked(QTreeWidgetItem*,int))); connect(ui->tempDirBrowseButton, SIGNAL(clicked()), this, SLOT(tempDirBrowseButtonClicked())); ui->tabWidget->setCurrentIndex(0); updateWidgets(); } CaptureOptionsDialog::~CaptureOptionsDialog() { delete ui; } /* Update global device selections based on the TreeWidget selection. */ void CaptureOptionsDialog::updateGlobalDeviceSelections() { #ifdef HAVE_LIBPCAP QTreeWidgetItemIterator iter(ui->interfaceTree); global_capture_opts.num_selected = 0; while (*iter) { QString device_name = (*iter)->data(col_interface_, Qt::UserRole).value<QString>(); for (guint i = 0; i < global_capture_opts.all_ifaces->len; i++) { interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i); if (device_name.compare(QString().fromUtf8(device->name)) == 0) { if ((*iter)->isSelected()) { device->selected = TRUE; global_capture_opts.num_selected++; } else { device->selected = FALSE; } break; } } ++iter; } #endif } /* Update TreeWidget selection based on global device selections. */ void CaptureOptionsDialog::updateFromGlobalDeviceSelections() { #ifdef HAVE_LIBPCAP QTreeWidgetItemIterator iter(ui->interfaceTree); // Prevent recursive interface interfaceSelected signals ui->interfaceTree->blockSignals(true); while (*iter) { QString device_name = (*iter)->data(col_interface_, Qt::UserRole).value<QString>(); for (guint i = 0; i < global_capture_opts.all_ifaces->len; i++) { interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i); if (device_name.compare(QString().fromUtf8(device->name)) == 0) { if ((bool)device->selected != (*iter)->isSelected()) { (*iter)->setSelected(device->selected); } break; } } ++iter; } ui->interfaceTree->blockSignals(false); #endif } void CaptureOptionsDialog::interfaceSelected() { if (sender() == ui->interfaceTree) { // Local changes, propagate our changes updateGlobalDeviceSelections(); emit interfacesChanged(); } else { // Changes from the welcome screen, adjust to its state. updateFromGlobalDeviceSelections(); } updateSelectedFilter(); updateWidgets(); } void CaptureOptionsDialog::filterEdited() { QList<QTreeWidgetItem*> si = ui->interfaceTree->selectedItems(); foreach (QTreeWidgetItem *ti, si) { ti->setText(col_filter_, ui->captureFilterComboBox->lineEdit()->text()); } if (si.count() > 0) { QModelIndex col_filter_idx = ui->interfaceTree->model()->index(ui->interfaceTree->indexOfTopLevelItem(si[0]), col_filter_); ui->interfaceTree->scrollTo(col_filter_idx); } } void CaptureOptionsDialog::updateWidgets() { SyntaxLineEdit *sle = qobject_cast<SyntaxLineEdit *>(ui->captureFilterComboBox->lineEdit()); if (!sle) { return; } bool can_capture = false; if (ui->interfaceTree->selectedItems().count() > 0 && sle->syntaxState() != SyntaxLineEdit::Invalid) { can_capture = true; } ui->compileBPF->setEnabled(can_capture); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(can_capture); } void CaptureOptionsDialog::on_capturePromModeCheckBox_toggled(bool checked) { interface_t *device; prefs.capture_prom_mode = checked; for (int row = 0; row < ui->interfaceTree->topLevelItemCount(); row++) { InterfaceTreeWidgetItem *ti = dynamic_cast<InterfaceTreeWidgetItem *>(ui->interfaceTree->topLevelItem(row)); if (!ti) continue; QString device_name = ti->data(col_interface_, Qt::UserRole).toString(); device = getDeviceByName(device_name); if (!device) continue; device->pmode = checked; ti->updateInterfaceColumns(device); } } void CaptureOptionsDialog::browseButtonClicked() { char *open_dir = NULL; switch (prefs.gui_fileopen_style) { case FO_STYLE_LAST_OPENED: open_dir = get_last_open_dir(); break; case FO_STYLE_SPECIFIED: if (prefs.gui_fileopen_dir[0] != '\0') open_dir = prefs.gui_fileopen_dir; break; } QString file_name = WiresharkFileDialog::getSaveFileName(this, tr("Specify a Capture File"), open_dir); ui->filenameLineEdit->setText(file_name); } void CaptureOptionsDialog::tempDirBrowseButtonClicked() { QString specified_dir = WiresharkFileDialog::getExistingDirectory(this, tr("Specify temporary directory")); ui->tempDirLineEdit->setText(specified_dir); } void CaptureOptionsDialog::interfaceItemChanged(QTreeWidgetItem *item, int column) { QWidget* editor = ui->interfaceTree->indexWidget(ui->interfaceTree->currentIndex()); if (editor) { ui->interfaceTree->closePersistentEditor(item, ui->interfaceTree->currentColumn()); } InterfaceTreeWidgetItem *ti = dynamic_cast<InterfaceTreeWidgetItem *>(item); if (!ti) return; interface_t *device; QString interface_name = ti->text(col_interface_); device = find_device_by_if_name(interface_name); if (!device) return; switch(column) { case col_pmode_: device->pmode = item->checkState(col_pmode_) == Qt::Checked ? TRUE : FALSE; ti->updateInterfaceColumns(device); break; #ifdef SHOW_MONITOR_COLUMN case col_monitor_: { gboolean monitor_mode = FALSE; if (ti->checkState(col_monitor_) == Qt::Checked) monitor_mode = TRUE; if_capabilities_t *caps; char *auth_str = NULL; QString active_dlt_name; set_active_dlt(device, global_capture_opts.default_options.linktype); #ifdef HAVE_PCAP_REMOTE if (device->remote_opts.remote_host_opts.auth_type == CAPTURE_AUTH_PWD) { auth_str = ws_strdup_printf("%s:%s", device->remote_opts.remote_host_opts.auth_username, device->remote_opts.remote_host_opts.auth_password); } #endif caps = capture_get_if_capabilities(device->name, monitor_mode, auth_str, NULL, NULL, main_window_update); g_free(auth_str); if (caps != Q_NULLPTR) { for (int i = static_cast<int>(g_list_length(device->links)) - 1; i >= 0; i--) { GList* rem = g_list_nth(device->links, static_cast<guint>(i)); device->links = g_list_remove_link(device->links, rem); g_list_free_1(rem); } device->active_dlt = -1; device->monitor_mode_supported = caps->can_set_rfmon; device->monitor_mode_enabled = monitor_mode; for (GList *lt_entry = caps->data_link_types; lt_entry != Q_NULLPTR; lt_entry = gxx_list_next(lt_entry)) { link_row *linkr = new link_row(); data_link_info_t *data_link_info = gxx_list_data(data_link_info_t *, lt_entry); /* * For link-layer types libpcap/WinPcap/Npcap doesn't know * about, the name will be "DLT n", and the description will * be null. * We mark those as unsupported, and don't allow them to be * used - capture filters won't work on them, for example. */ if (data_link_info->description != Q_NULLPTR) { linkr->dlt = data_link_info->dlt; if (active_dlt_name.isEmpty()) { device->active_dlt = data_link_info->dlt; active_dlt_name = data_link_info->description; } linkr->name = g_strdup(data_link_info->description); } else { gchar *str; /* XXX - should we just omit them? */ str = ws_strdup_printf("%s (not supported)", data_link_info->name); linkr->dlt = -1; linkr->name = g_strdup(str); g_free(str); } device->links = g_list_append(device->links, linkr); } free_if_capabilities(caps); } else { /* We don't know whether this supports monitor mode or not; don't ask for monitor mode. */ device->monitor_mode_enabled = FALSE; device->monitor_mode_supported = FALSE; } ti->updateInterfaceColumns(device); break; } #endif // SHOW_MONITOR_COLUMN default: break; } } void CaptureOptionsDialog::itemClicked(QTreeWidgetItem *item, int column) { InterfaceTreeWidgetItem *ti = dynamic_cast<InterfaceTreeWidgetItem *>(item); if (!ti) return; #ifdef HAVE_LIBPCAP interface_t *device; QString interface_name = ti->text(col_interface_); device = find_device_by_if_name(interface_name); if (!device) return; switch(column) { case col_extcap_: if (device->if_info.type == IF_EXTCAP) { /* this checks if configuration is required and not yet provided or saved via prefs */ QString device_name = ti->data(col_extcap_, Qt::UserRole).value<QString>(); if (extcap_has_configuration((const char *)(device_name.toStdString().c_str()))) { emit showExtcapOptions(device_name, false); return; } } break; default: break; } #endif /* HAVE_LIBPCAP */ } void CaptureOptionsDialog::itemDoubleClicked(QTreeWidgetItem *item, int column) { InterfaceTreeWidgetItem *ti = dynamic_cast<InterfaceTreeWidgetItem *>(item); if (!ti) return; switch(column) { // Double click starts capture just on columns which are not editable case col_interface_: case col_traffic_: { #ifdef HAVE_LIBPCAP interface_t *device; QString interface_name = ti->text(col_interface_); device = find_device_by_if_name(interface_name); if (!device) return; if (device->if_info.type == IF_EXTCAP) { /* this checks if configuration is required and not yet provided or saved via prefs */ QString device_name = ti->data(col_extcap_, Qt::UserRole).value<QString>(); if (extcap_requires_configuration((const char *)(device_name.toStdString().c_str()))) { emit showExtcapOptions(device_name, true); return; } } #endif /* HAVE_LIBPCAP */ emit startCapture(); close(); break; } default: break; } } void CaptureOptionsDialog::on_gbStopCaptureAuto_toggled(bool checked) { global_capture_opts.has_file_interval = checked; } void CaptureOptionsDialog::on_gbNewFileAuto_toggled(bool checked) { global_capture_opts.multi_files_on = checked; ui->stopMBCheckBox->setEnabled(checked?false:true); ui->stopMBSpinBox->setEnabled(checked?false:true); ui->stopMBComboBox->setEnabled(checked?false:true); ui->gbCompression->setEnabled(checked); ui->rbCompressionNone->setEnabled(checked); #ifdef HAVE_ZLIB ui->rbCompressionGzip->setEnabled(checked); #else ui->rbCompressionGzip->setEnabled(false); #endif } void CaptureOptionsDialog::on_cbUpdatePacketsRT_toggled(bool checked) { global_capture_opts.real_time_mode = checked; } void CaptureOptionsDialog::on_cbAutoScroll_toggled(bool checked) { recent.capture_auto_scroll = checked; } void CaptureOptionsDialog::on_cbExtraCaptureInfo_toggled(bool checked) { global_capture_opts.show_info = checked; } void CaptureOptionsDialog::on_cbResolveMacAddresses_toggled(bool checked) { gbl_resolv_flags.mac_name = checked; } void CaptureOptionsDialog::on_cbResolveNetworkNames_toggled(bool checked) { gbl_resolv_flags.network_name = checked; } void CaptureOptionsDialog::on_cbResolveTransportNames_toggled(bool checked) { gbl_resolv_flags.transport_name = checked; } void CaptureOptionsDialog::on_buttonBox_accepted() { if (saveOptionsToPreferences()) { #ifdef HAVE_LIBPCAP InterfaceTreeWidgetItem *ti = dynamic_cast<InterfaceTreeWidgetItem *>(ui->interfaceTree->currentItem()); if (ti) { interface_t *device; QString interface_name = ti->text(col_interface_); device = find_device_by_if_name(interface_name); if (device && device->if_info.type == IF_EXTCAP) { /* this checks if configuration is required and not yet provided or saved via prefs */ QString device_name = ti->data(col_extcap_, Qt::UserRole).value<QString>(); if (extcap_requires_configuration((const char *)(device_name.toStdString().c_str()))) { emit showExtcapOptions(device_name, true); return; } } } #endif /* HAVE_LIBPCAP */ emit setFilterValid(true, ui->captureFilterComboBox->lineEdit()->text()); accept(); } } // Not sure why we have to do this manually. void CaptureOptionsDialog::on_buttonBox_rejected() { if (saveOptionsToPreferences()) { reject(); } } void CaptureOptionsDialog::on_buttonBox_helpRequested() { // Probably the wrong URL. mainApp->helpTopicAction(HELP_CAPTURE_OPTIONS_DIALOG); } void CaptureOptionsDialog::updateInterfaces() { if (prefs.capture_pcap_ng) { ui->rbPcapng->setChecked(true); } else { ui->rbPcap->setChecked(true); } ui->capturePromModeCheckBox->setChecked(prefs.capture_prom_mode); if (global_capture_opts.saving_to_file) { ui->filenameLineEdit->setText(QString(global_capture_opts.orig_save_file)); } ui->gbNewFileAuto->setChecked(global_capture_opts.multi_files_on); ui->PktCheckBox->setChecked(global_capture_opts.has_file_packets); if (global_capture_opts.has_file_packets) { ui->PktSpinBox->setValue(global_capture_opts.file_packets); } ui->MBCheckBox->setChecked(global_capture_opts.has_autostop_filesize); if (global_capture_opts.has_autostop_filesize) { int value = global_capture_opts.autostop_filesize; if (value > 1000000) { if (global_capture_opts.multi_files_on) { ui->MBSpinBox->setValue(value / 1000000); ui->MBComboBox->setCurrentIndex(2); } else { ui->stopMBCheckBox->setChecked(true); ui->stopMBSpinBox->setValue(value / 1000000); ui->stopMBComboBox->setCurrentIndex(2); } } else if (value > 1000 && value % 1000 == 0) { if (global_capture_opts.multi_files_on) { ui->MBSpinBox->setValue(value / 1000); ui->MBComboBox->setCurrentIndex(1); } else { ui->stopMBCheckBox->setChecked(true); ui->stopMBSpinBox->setValue(value / 1000); ui->stopMBComboBox->setCurrentIndex(1); } } else { if (global_capture_opts.multi_files_on) { ui->MBSpinBox->setValue(value); ui->MBComboBox->setCurrentIndex(0); } else { ui->stopMBCheckBox->setChecked(true); ui->stopMBSpinBox->setValue(value); ui->stopMBComboBox->setCurrentIndex(0); } } } ui->SecsCheckBox->setChecked(global_capture_opts.has_file_duration); if (global_capture_opts.has_file_duration) { int value = global_capture_opts.file_duration; if (value > 3600 && value % 3600 == 0) { ui->SecsSpinBox->setValue(value / 3600); ui->SecsComboBox->setCurrentIndex(2); } else if (value > 60 && value % 60 == 0) { ui->SecsSpinBox->setValue(value / 60); ui->SecsComboBox->setCurrentIndex(1); } else { ui->SecsSpinBox->setValue(value); ui->SecsComboBox->setCurrentIndex(0); } } ui->IntervalSecsCheckBox->setChecked(global_capture_opts.has_file_interval); if (global_capture_opts.has_file_interval) { int value = global_capture_opts.file_interval; if (value > 3600 && value % 3600 == 0) { ui->IntervalSecsSpinBox->setValue(value / 3600); ui->IntervalSecsComboBox->setCurrentIndex(2); } else if (value > 60 && value % 60 == 0) { ui->IntervalSecsSpinBox->setValue(value / 60); ui->IntervalSecsComboBox->setCurrentIndex(1); } else { ui->IntervalSecsSpinBox->setValue(value); ui->IntervalSecsComboBox->setCurrentIndex(0); } } if (global_capture_opts.has_ring_num_files) { ui->RbSpinBox->setValue(global_capture_opts.ring_num_files); ui->RbCheckBox->setCheckState(Qt::Checked); } if (global_capture_opts.has_autostop_duration) { ui->stopSecsCheckBox->setChecked(true); int value = global_capture_opts.autostop_duration; if (value > 3600 && value % 3600 == 0) { ui->stopSecsSpinBox->setValue(value / 3600); ui->stopSecsComboBox->setCurrentIndex(2); } else if (value > 60 && value % 60 == 0) { ui->stopSecsSpinBox->setValue(value / 60); ui->stopSecsComboBox->setCurrentIndex(1); } else { ui->stopSecsSpinBox->setValue(value); ui->stopSecsComboBox->setCurrentIndex(0); } } if (global_capture_opts.has_autostop_packets) { ui->stopPktCheckBox->setChecked(true); ui->stopPktSpinBox->setValue(global_capture_opts.autostop_packets); } if (global_capture_opts.has_autostop_files) { ui->stopFilesCheckBox->setChecked(true); ui->stopFilesSpinBox->setValue(global_capture_opts.autostop_files); } ui->cbUpdatePacketsRT->setChecked(global_capture_opts.real_time_mode); ui->cbAutoScroll->setChecked(recent.capture_auto_scroll); ui->cbExtraCaptureInfo->setChecked(global_capture_opts.show_info); ui->cbResolveMacAddresses->setChecked(gbl_resolv_flags.mac_name); ui->cbResolveNetworkNames->setChecked(gbl_resolv_flags.network_name); ui->cbResolveTransportNames->setChecked(gbl_resolv_flags.transport_name); // Rebuild the interface list without disturbing the main welcome screen. disconnect(ui->interfaceTree, SIGNAL(itemSelectionChanged()), this, SLOT(interfaceSelected())); ui->interfaceTree->clear(); #ifdef SHOW_BUFFER_COLUMN gint buffer; #endif gint snaplen; gboolean hassnap, pmode; QList<QTreeWidgetItem *> selected_interfaces; disconnect(ui->interfaceTree, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(interfaceItemChanged(QTreeWidgetItem*,int))); if (global_capture_opts.all_ifaces->len > 0) { interface_t *device; for (guint device_idx = 0; device_idx < global_capture_opts.all_ifaces->len; device_idx++) { device = &g_array_index(global_capture_opts.all_ifaces, interface_t, device_idx); /* Continue if capture device is hidden */ if (device->hidden) { continue; } // Traffic sparklines InterfaceTreeWidgetItem *ti = new InterfaceTreeWidgetItem(ui->interfaceTree); ti->setFlags(ti->flags() | Qt::ItemIsEditable); if (device->if_info.type == IF_EXTCAP) { ti->setIcon(col_extcap_, QIcon(StockIcon("x-capture-options"))); ti->setData(col_extcap_, Qt::UserRole, QString(device->if_info.name)); ti->setToolTip(col_extcap_, QString("Extcap interface settings")); } ti->setText(col_interface_, device->display_name); ti->setData(col_interface_, Qt::UserRole, QString(device->name)); if (device->if_info.type != IF_EXTCAP) ti->setData(col_traffic_, Qt::UserRole, QVariant::fromValue(ti->points)); if (device->no_addresses > 0) { QString addr_str = tr("%1: %2").arg(device->no_addresses > 1 ? tr("Addresses") : tr("Address")).arg(device->addresses); QTreeWidgetItem *addr_ti = new QTreeWidgetItem(ti); addr_str.replace('\n', ", "); addr_ti->setText(0, addr_str); addr_ti->setFlags(addr_ti->flags() ^ Qt::ItemIsSelectable); addr_ti->setFirstColumnSpanned(true); addr_ti->setToolTip(col_interface_, QString("<span>%1</span>").arg(addr_str)); ti->setToolTip(col_interface_, QString("<span>%1</span>").arg(addr_str)); } else { ti->setToolTip(col_interface_, tr("no addresses")); } if (capture_dev_user_pmode_find(device->name, &pmode)) { device->pmode = pmode; } if (capture_dev_user_snaplen_find(device->name, &hassnap, &snaplen)) { /* Default snap length set in preferences */ device->snaplen = snaplen; device->has_snaplen = snaplen == WTAP_MAX_PACKET_SIZE_STANDARD ? FALSE : hassnap; } else { /* No preferences set yet, use default values */ device->snaplen = WTAP_MAX_PACKET_SIZE_STANDARD; device->has_snaplen = FALSE; } #ifdef SHOW_BUFFER_COLUMN if (capture_dev_user_buffersize_find(device->name) != -1) { buffer = capture_dev_user_buffersize_find(device->name); device->buffer = buffer; } else { device->buffer = DEFAULT_CAPTURE_BUFFER_SIZE; } #endif ti->updateInterfaceColumns(device); if (device->selected) { selected_interfaces << ti; } } } connect(ui->interfaceTree, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(interfaceItemChanged(QTreeWidgetItem*,int))); foreach (QTreeWidgetItem *ti, selected_interfaces) { ti->setSelected(true); } connect(ui->interfaceTree, SIGNAL(itemSelectionChanged()), this, SLOT(interfaceSelected())); updateSelectedFilter(); // Manually or automatically size some columns as needed. int one_em = fontMetrics().height(); for (int col = 0; col < ui->interfaceTree->topLevelItemCount(); col++) { switch (col) { case col_pmode_: ui->interfaceTree->setColumnWidth(col, one_em * 3.25); break; case col_snaplen_: ui->interfaceTree->setColumnWidth(col, one_em * 4.25); break; case col_buffer_: ui->interfaceTree->setColumnWidth(col, one_em * 4.25); break; case col_monitor_: ui->interfaceTree->setColumnWidth(col, one_em * 3.25); break; default: ui->interfaceTree->resizeColumnToContents(col); } } updateWidgets(); if (!stat_timer_) { updateStatistics(); stat_timer_ = new QTimer(this); connect(stat_timer_, SIGNAL(timeout()), this, SLOT(updateStatistics())); stat_timer_->start(stat_update_interval_); } } void CaptureOptionsDialog::showEvent(QShowEvent *) { updateInterfaces(); } void CaptureOptionsDialog::refreshInterfaceList() { updateInterfaces(); emit interfaceListChanged(); } void CaptureOptionsDialog::updateLocalInterfaces() { updateInterfaces(); } void CaptureOptionsDialog::updateStatistics(void) { interface_t *device; disconnect(ui->interfaceTree, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(interfaceItemChanged(QTreeWidgetItem*,int))); for (int row = 0; row < ui->interfaceTree->topLevelItemCount(); row++) { for (guint if_idx = 0; if_idx < global_capture_opts.all_ifaces->len; if_idx++) { QTreeWidgetItem *ti = ui->interfaceTree->topLevelItem(row); if (!ti) { continue; } device = &g_array_index(global_capture_opts.all_ifaces, interface_t, if_idx); QString device_name = ti->text(col_interface_); if (device_name.compare(device->display_name) || device->hidden || device->type == IF_PIPE) { continue; } QList<int> points = ti->data(col_traffic_, Qt::UserRole).value<QList<int> >(); points.append(device->packet_diff); ti->setData(col_traffic_, Qt::UserRole, QVariant::fromValue(points)); } } connect(ui->interfaceTree, SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(interfaceItemChanged(QTreeWidgetItem*,int))); ui->interfaceTree->viewport()->update(); } void CaptureOptionsDialog::on_compileBPF_clicked() { QStringList interfaces; foreach (QTreeWidgetItem *ti, ui->interfaceTree->selectedItems()) { interfaces.append(ti->text(col_interface_)); } QString filter = ui->captureFilterComboBox->currentText(); CompiledFilterOutput *cfo = new CompiledFilterOutput(this, interfaces, filter); cfo->show(); } bool CaptureOptionsDialog::saveOptionsToPreferences() { if (ui->rbPcapng->isChecked()) { global_capture_opts.use_pcapng = true; prefs.capture_pcap_ng = true; } else { global_capture_opts.use_pcapng = false; prefs.capture_pcap_ng = false; } g_free(global_capture_opts.save_file); g_free(global_capture_opts.orig_save_file); QString filename = ui->filenameLineEdit->text(); if (filename.length() > 0) { /* User specified a file to which the capture should be written. */ global_capture_opts.saving_to_file = true; global_capture_opts.save_file = qstring_strdup(filename); global_capture_opts.orig_save_file = qstring_strdup(filename); /* Save the directory name for future file dialogs. */ set_last_open_dir(get_dirname(filename.toUtf8().data())); } else { /* User didn't specify a file; save to a temporary file. */ global_capture_opts.saving_to_file = false; global_capture_opts.save_file = NULL; global_capture_opts.orig_save_file = NULL; } QString tempdir = ui->tempDirLineEdit->text(); if (tempdir.length() > 0) { global_capture_opts.temp_dir = qstring_strdup(tempdir); } else { global_capture_opts.temp_dir = NULL; } global_capture_opts.has_ring_num_files = ui->RbCheckBox->isChecked(); if (global_capture_opts.has_ring_num_files) { global_capture_opts.ring_num_files = ui->RbSpinBox->value(); if (global_capture_opts.ring_num_files > RINGBUFFER_MAX_NUM_FILES) global_capture_opts.ring_num_files = RINGBUFFER_MAX_NUM_FILES; #if RINGBUFFER_MIN_NUM_FILES > 0 else if (global_capture_opts.ring_num_files < RINGBUFFER_MIN_NUM_FILES) global_capture_opts.ring_num_files = RINGBUFFER_MIN_NUM_FILES; #endif } global_capture_opts.multi_files_on = ui->gbNewFileAuto->isChecked(); if (global_capture_opts.multi_files_on) { global_capture_opts.has_file_duration = ui->SecsCheckBox->isChecked(); if (global_capture_opts.has_file_duration) { global_capture_opts.file_duration = ui->SecsSpinBox->value(); int index = ui->SecsComboBox->currentIndex(); switch (index) { case 1: global_capture_opts.file_duration *= 60; break; case 2: global_capture_opts.file_duration *= 3600; break; } } global_capture_opts.has_file_interval = ui->IntervalSecsCheckBox->isChecked(); if (global_capture_opts.has_file_interval) { global_capture_opts.file_interval = ui->IntervalSecsSpinBox->value(); int index = ui->IntervalSecsComboBox->currentIndex(); switch (index) { case 1: global_capture_opts.file_interval *= 60; break; case 2: global_capture_opts.file_interval *= 3600; break; } } global_capture_opts.has_file_packets = ui->PktCheckBox->isChecked(); if (global_capture_opts.has_file_packets) { global_capture_opts.file_packets = ui->PktSpinBox->value(); } global_capture_opts.has_autostop_filesize = ui->MBCheckBox->isChecked(); if (global_capture_opts.has_autostop_filesize) { global_capture_opts.autostop_filesize = ui->MBSpinBox->value(); int index = ui->MBComboBox->currentIndex(); switch (index) { case 1: if (global_capture_opts.autostop_filesize > 2000) { QMessageBox::warning(this, tr("Error"), tr("Multiple files: Requested filesize too large. The filesize cannot be greater than 2 GiB.")); return false; } else { global_capture_opts.autostop_filesize *= 1000; } break; case 2: if (global_capture_opts.autostop_filesize > 2) { QMessageBox::warning(this, tr("Error"), tr("Multiple files: Requested filesize too large. The filesize cannot be greater than 2 GiB.")); return false; } else { global_capture_opts.autostop_filesize *= 1000000; } break; } } /* test if the settings are ok for a ringbuffer */ if (global_capture_opts.save_file == NULL) { QMessageBox::warning(this, tr("Error"), tr("Multiple files: No capture file name given. You must specify a filename if you want to use multiple files.")); return false; } else if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_interval && !global_capture_opts.has_file_duration && !global_capture_opts.has_file_packets) { QMessageBox::warning(this, tr("Error"), tr("Multiple files: No file limit given. You must specify a file size, interval, or number of packets for each file.")); g_free(global_capture_opts.save_file); global_capture_opts.save_file = NULL; return false; } } else { global_capture_opts.has_autostop_filesize = ui->stopMBCheckBox->isChecked(); if (global_capture_opts.has_autostop_filesize) { global_capture_opts.autostop_filesize = ui->stopMBSpinBox->value(); int index = ui->stopMBComboBox->currentIndex(); switch (index) { case 1: if (global_capture_opts.autostop_filesize > 2000) { QMessageBox::warning(this, tr("Error"), tr("Multiple files: Requested filesize too large. The filesize cannot be greater than 2 GiB.")); return false; } else { global_capture_opts.autostop_filesize *= 1000; } break; case 2: if (global_capture_opts.autostop_filesize > 2) { QMessageBox::warning(this, tr("Error"), tr("Multiple files: Requested filesize too large. The filesize cannot be greater than 2 GiB.")); return false; } else { global_capture_opts.autostop_filesize *= 1000000; } break; } } } global_capture_opts.has_autostop_duration = ui->stopSecsCheckBox->isChecked(); if (global_capture_opts.has_autostop_duration) { global_capture_opts.autostop_duration = ui->stopSecsSpinBox->value(); int index = ui->stopSecsComboBox->currentIndex(); switch (index) { case 1: global_capture_opts.autostop_duration *= 60; break; case 2: global_capture_opts.autostop_duration *= 3600; break; } } global_capture_opts.has_autostop_packets = ui->stopPktCheckBox->isChecked(); if (global_capture_opts.has_autostop_packets) { global_capture_opts.autostop_packets = ui->stopPktSpinBox->value(); } global_capture_opts.has_autostop_files = ui->stopFilesCheckBox->isChecked(); if (global_capture_opts.has_autostop_files) { global_capture_opts.autostop_files = ui->stopFilesSpinBox->value(); } interface_t *device; for (int col = col_link_; col <= col_filter_; col++) { if (ui->interfaceTree->isColumnHidden(col)) { continue; } /* All entries are separated by comma. There is also one before the first interface to be able to identify word boundaries. As 'lo' is part of 'nflog' an exact match is necessary. */ switch (col) { case col_link_: { QStringList link_list; for (int row = 0; row < ui->interfaceTree->topLevelItemCount(); row++) { QTreeWidgetItem *ti = ui->interfaceTree->topLevelItem(row); QString device_name = ti->data(col_interface_, Qt::UserRole).toString(); device = getDeviceByName(device_name); if (!device || device->active_dlt == -1) { continue; } link_list << QString("%1(%2)").arg(device->name).arg(device->active_dlt); } g_free(prefs.capture_devices_linktypes); prefs.capture_devices_linktypes = qstring_strdup(link_list.join(",")); break; } #ifdef SHOW_BUFFER_COLUMN case col_buffer_: { QStringList buffer_size_list; for (int row = 0; row < ui->interfaceTree->topLevelItemCount(); row++) { QTreeWidgetItem *ti = ui->interfaceTree->topLevelItem(row); QString device_name = ti->data(col_interface_, Qt::UserRole).toString(); device = getDeviceByName(device_name); if (!device || device->buffer == -1) { continue; } buffer_size_list << QString("%1(%2)").arg(device->name).arg(device->buffer); } g_free(prefs.capture_devices_buffersize); prefs.capture_devices_buffersize = qstring_strdup(buffer_size_list.join(",")); break; } #endif // HAVE_BUFFER_SETTING case col_snaplen_: { QStringList snaplen_list; for (int row = 0; row < ui->interfaceTree->topLevelItemCount(); row++) { QTreeWidgetItem *ti = ui->interfaceTree->topLevelItem(row); QString device_name = ti->data(col_interface_, Qt::UserRole).toString(); device = getDeviceByName(device_name); if (!device) continue; snaplen_list << QString("%1:%2(%3)") .arg(device->name) .arg(device->has_snaplen) .arg(device->has_snaplen ? device->snaplen : WTAP_MAX_PACKET_SIZE_STANDARD); } g_free(prefs.capture_devices_snaplen); prefs.capture_devices_snaplen = qstring_strdup(snaplen_list.join(",")); break; } case col_pmode_: { QStringList pmode_list; for (int row = 0; row < ui->interfaceTree->topLevelItemCount(); row++) { QTreeWidgetItem *ti = ui->interfaceTree->topLevelItem(row); QString device_name = ti->data(col_interface_, Qt::UserRole).toString(); device = getDeviceByName(device_name); if (!device || device->pmode == -1) { continue; } pmode_list << QString("%1(%2)").arg(device->name).arg(device->pmode); } g_free(prefs.capture_devices_pmode); prefs.capture_devices_pmode = qstring_strdup(pmode_list.join(",")); break; } #ifdef SHOW_MONITOR_COLUMN case col_monitor_: { QStringList monitor_list; for (int row = 0; row < ui->interfaceTree->topLevelItemCount(); row++) { QTreeWidgetItem *ti = ui->interfaceTree->topLevelItem(row); QString device_name = ti->data(col_interface_, Qt::UserRole).toString(); device = getDeviceByName(device_name); if (!device || !device->monitor_mode_supported || (device->monitor_mode_supported && !device->monitor_mode_enabled)) { continue; } monitor_list << device->name; } g_free(prefs.capture_devices_monitor_mode); prefs.capture_devices_monitor_mode = qstring_strdup(monitor_list.join(",")); break; } #endif // HAVE_MONITOR_SETTING #if 0 // The device cfilter should have been applied at this point. // We shouldn't change it here. case col_filter_: { // XXX Update selected interfaces only? for (int row = 0; row < ui->interfaceTree->topLevelItemCount(); row++) { QTreeWidgetItem *ti = ui->interfaceTree->topLevelItem(row); QString device_name = ti->data(col_interface_, Qt::UserRole).toString(); device = getDeviceByName(device_name); if (!device) continue; g_free(device->cfilter); if (ti->text(col_filter_).isEmpty()) { device->cfilter = NULL; } else { device->cfilter = qstring_strdup(ti->text(col_filter_)); } } } #endif } } g_free(global_capture_opts.compress_type); if (ui->rbCompressionNone->isChecked() ) { global_capture_opts.compress_type = NULL; } else if (ui->rbCompressionGzip->isChecked() ) { global_capture_opts.compress_type = qstring_strdup("gzip"); } else { global_capture_opts.compress_type = NULL; } prefs_main_write(); return true; } void CaptureOptionsDialog::updateSelectedFilter() { // Should match MainWelcome::interfaceSelected. QPair <const QString, bool> sf_pair = CaptureFilterEdit::getSelectedFilter(); const QString user_filter = sf_pair.first; bool conflict = sf_pair.second; if (conflict) { ui->captureFilterComboBox->lineEdit()->clear(); ui->captureFilterComboBox->setConflict(true); } else { ui->captureFilterComboBox->lineEdit()->setText(user_filter); } } void CaptureOptionsDialog::on_manageButton_clicked() { if (saveOptionsToPreferences()) { ManageInterfacesDialog *dlg = new ManageInterfacesDialog(this); dlg->show(); } } void CaptureOptionsDialog::changeEvent(QEvent* event) { if (0 != event) { switch (event->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } QDialog::changeEvent(event); } interface_t *CaptureOptionsDialog::getDeviceByName(const QString device_name) { for (guint i = 0; i < global_capture_opts.all_ifaces->len; i++) { interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i); if (device_name.compare(QString().fromUtf8(device->name)) == 0) { return device; } } return NULL; } // // InterfaceTreeItem // bool InterfaceTreeWidgetItem::operator< (const QTreeWidgetItem &other) const { if (treeWidget()->sortColumn() == col_traffic_) { QList<int> points = data(col_traffic_, Qt::UserRole).value<QList<int> >(); QList<int> other_points = other.data(col_traffic_, Qt::UserRole).value<QList<int> >(); double avg = 0, other_avg = 0; foreach (int point, points) { avg += (double) point / points.length(); } foreach (int point, other_points) { other_avg += (double) point / other_points.length(); } return avg < other_avg; } return QTreeWidgetItem::operator<(other); } QVariant InterfaceTreeWidgetItem::data(int column, int role) const { // See setData for the special col_traffic_ treatment. if (column == col_traffic_ && role == Qt::UserRole) { return QVariant::fromValue(points); } return QTreeWidgetItem::data(column, role); } void InterfaceTreeWidgetItem::setData(int column, int role, const QVariant &value) { // Workaround for closing editors on updates to the points list: normally // QTreeWidgetItem::setData emits dataChanged when the value (list) changes. // We could store a pointer to the list, or just have this hack that does // not emit dataChanged. if (column == col_traffic_ && role == Qt::UserRole) { points = value.value<QList<int> >(); return; } QTreeWidgetItem::setData(column, role, value); } // // InterfaceTreeDelegate // #include <QComboBox> InterfaceTreeDelegate::InterfaceTreeDelegate(QObject *parent) : QStyledItemDelegate(parent), tree_(NULL) { } InterfaceTreeDelegate::~InterfaceTreeDelegate() { } QWidget* InterfaceTreeDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &idx) const { QWidget *w = NULL; #ifdef SHOW_BUFFER_COLUMN gint buffer = DEFAULT_CAPTURE_BUFFER_SIZE; #endif guint snap = WTAP_MAX_PACKET_SIZE_STANDARD; GList *links = NULL; if (idx.column() > 1 && idx.data().toString().compare(UTF8_EM_DASH)) { QTreeWidgetItem *ti = tree_->topLevelItem(idx.row()); QString interface_name = ti->text(col_interface_); interface_t *device = find_device_by_if_name(interface_name); if (device) { #ifdef SHOW_BUFFER_COLUMN buffer = device->buffer; #endif snap = device->snaplen; links = device->links; } switch (idx.column()) { case col_extcap_: case col_interface_: case col_traffic_: break; case col_link_: { GList *list; link_row *linkr; QStringList valid_link_types; // XXX The GTK+ UI fills in all link types, valid or not. We add // only the valid ones. If we *do* wish to include invalid link // types we'll have to jump through the hoops necessary to disable // QComboBox items. for (list = links; list != Q_NULLPTR; list = gxx_list_next(list)) { linkr = gxx_list_data(link_row*, list); if (linkr->dlt >= 0) { valid_link_types << linkr->name; } } if (valid_link_types.size() < 2) { break; } QComboBox *cb = new QComboBox(parent); cb->addItems(valid_link_types); connect(cb, &QComboBox::currentTextChanged, this, &InterfaceTreeDelegate::linkTypeChanged); w = (QWidget*) cb; break; } case col_snaplen_: { QSpinBox *sb = new QSpinBox(parent); sb->setRange(1, WTAP_MAX_PACKET_SIZE_STANDARD); sb->setValue(snap); sb->setWrapping(true); connect(sb, SIGNAL(valueChanged(int)), this, SLOT(snapshotLengthChanged(int))); w = (QWidget*) sb; break; } #ifdef SHOW_BUFFER_COLUMN case col_buffer_: { QSpinBox *sb = new QSpinBox(parent); sb->setRange(1, WTAP_MAX_PACKET_SIZE_STANDARD); sb->setValue(buffer); sb->setWrapping(true); connect(sb, SIGNAL(valueChanged(int)), this, SLOT(bufferSizeChanged(int))); w = (QWidget*) sb; break; } #endif case col_filter_: { CaptureFilterCombo *cf = new CaptureFilterCombo(parent, true); connect(cf->lineEdit(), SIGNAL(textEdited(QString)), this, SIGNAL(filterChanged(QString))); w = (QWidget*) cf; } default: break; } } if (w) w->setAutoFillBackground(true); return w; } bool InterfaceTreeDelegate::eventFilter(QObject *object, QEvent *event) { QComboBox * comboBox = dynamic_cast<QComboBox*>(object); if (comboBox) { if (event->type() == QEvent::MouseButtonRelease) { comboBox->showPopup(); return true; } } else { return QStyledItemDelegate::eventFilter(object, event); } return false; } void InterfaceTreeDelegate::linkTypeChanged(const QString selected_link_type) { GList *list; link_row *temp; interface_t *device; QTreeWidgetItem *ti = tree_->currentItem(); if (!ti) { return; } QString interface_name = ti->text(col_interface_); device = find_device_by_if_name(interface_name); if (!device) { return; } for (list = device->links; list != Q_NULLPTR; list = gxx_list_next(list)) { temp = gxx_list_data(link_row*, list); if (!selected_link_type.compare(temp->name)) { device->active_dlt = temp->dlt; } } // XXX We might want to verify that active_dlt is valid at this point. } void InterfaceTreeDelegate::snapshotLengthChanged(int value) { interface_t *device; QTreeWidgetItem *ti = tree_->currentItem(); if (!ti) { return; } QString interface_name = ti->text(col_interface_); device = find_device_by_if_name(interface_name); if (!device) { return; } if (value != WTAP_MAX_PACKET_SIZE_STANDARD) { device->has_snaplen = true; device->snaplen = value; } else { device->has_snaplen = false; device->snaplen = WTAP_MAX_PACKET_SIZE_STANDARD; } } #ifdef SHOW_BUFFER_COLUMN void InterfaceTreeDelegate::bufferSizeChanged(int value) { interface_t *device; QTreeWidgetItem *ti = tree_->currentItem(); if (!ti) { return; } QString interface_name = ti->text(col_interface_); device = find_device_by_if_name(interface_name); if (!device) { return; } device->buffer = value; } #endif #endif /* HAVE_LIBPCAP */
C/C++
wireshark/ui/qt/capture_options_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef CAPTURE_OPTIONS_DIALOG_H #define CAPTURE_OPTIONS_DIALOG_H #include <config.h> #ifdef HAVE_LIBPCAP #include <ui/qt/models/interface_tree_model.h> #include "geometry_state_dialog.h" #include <QPushButton> #include <QTreeWidget> typedef struct if_stat_cache_s if_stat_cache_t; namespace Ui { class CaptureOptionsDialog; } #include <QStyledItemDelegate> class InterfaceTreeDelegate : public QStyledItemDelegate { Q_OBJECT private: QTreeWidget* tree_; public: InterfaceTreeDelegate(QObject *parent = 0); ~InterfaceTreeDelegate(); QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &idx) const; void setTree(QTreeWidget* tree) { tree_ = tree; } bool eventFilter(QObject *object, QEvent *event); signals: void filterChanged(const QString filter); private slots: void linkTypeChanged(const QString selected_link_type); void snapshotLengthChanged(int value); void bufferSizeChanged(int value); }; class CaptureOptionsDialog : public GeometryStateDialog { Q_OBJECT public: explicit CaptureOptionsDialog(QWidget *parent = 0); ~CaptureOptionsDialog(); void updateInterfaces(); public slots: void interfaceSelected(); protected: virtual void showEvent(QShowEvent *); private slots: void on_capturePromModeCheckBox_toggled(bool checked); void on_gbStopCaptureAuto_toggled(bool checked); void on_cbUpdatePacketsRT_toggled(bool checked); void on_cbAutoScroll_toggled(bool checked); void on_gbNewFileAuto_toggled(bool checked); void on_cbExtraCaptureInfo_toggled(bool checked); void on_cbResolveMacAddresses_toggled(bool checked); void on_compileBPF_clicked(); void on_manageButton_clicked(); void on_cbResolveNetworkNames_toggled(bool checked); void on_cbResolveTransportNames_toggled(bool checked); void on_buttonBox_accepted(); void on_buttonBox_rejected(); void on_buttonBox_helpRequested(); void filterEdited(); void updateWidgets(); void updateStatistics(void); void refreshInterfaceList(); void updateLocalInterfaces(); void browseButtonClicked(); void interfaceItemChanged(QTreeWidgetItem *item, int column); void itemClicked(QTreeWidgetItem *item, int column); void itemDoubleClicked(QTreeWidgetItem *item, int column); void changeEvent(QEvent* event); void tempDirBrowseButtonClicked(); signals: void startCapture(); void stopCapture(); void setSelectedInterfaces(); void setFilterValid(bool valid, const QString capture_filter); void interfacesChanged(); void ifsChanged(); void interfaceListChanged(); void captureFilterTextEdited(const QString & text); void showExtcapOptions(QString &device_name, bool startCaptureOnClose); private: Ui::CaptureOptionsDialog *ui; if_stat_cache_t *stat_cache_; QTimer *stat_timer_; InterfaceTreeDelegate interface_item_delegate_; interface_t *getDeviceByName(const QString device_name); bool saveOptionsToPreferences(); void updateSelectedFilter(); void updateGlobalDeviceSelections(); void updateFromGlobalDeviceSelections(); }; #endif /* HAVE_LIBPCAP */ #endif // CAPTURE_OPTIONS_DIALOG_H
User Interface
wireshark/ui/qt/capture_options_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>CaptureOptionsDialog</class> <widget class="QDialog" name="CaptureOptionsDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>950</width> <height>440</height> </rect> </property> <layout class="QVBoxLayout" name="verticalLayout_12"> <item> <widget class="QTabWidget" name="tabWidget"> <property name="currentIndex"> <number>0</number> </property> <widget class="QWidget" name="inputTab"> <attribute name="title"> <string>Input</string> </attribute> <layout class="QVBoxLayout" name="verticalLayout_2"> <item> <widget class="QTreeWidget" name="interfaceTree"> <property name="sizePolicy"> <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="selectionMode"> <enum>QAbstractItemView::ExtendedSelection</enum> </property> <property name="textElideMode"> <enum>Qt::ElideMiddle</enum> </property> <property name="sortingEnabled"> <bool>true</bool> </property> <column> <property name="text"> <string></string> </property> </column> <column> <property name="text"> <string>Interface</string> </property> </column> <column> <property name="text"> <string>Traffic</string> </property> </column> <column> <property name="text"> <string>Link-layer Header</string> </property> </column> <column> <property name="text"> <string>Promiscuous</string> </property> </column> <column> <property name="text"> <string>Snaplen (B)</string> </property> </column> <column> <property name="text"> <string>Buffer (MB)</string> </property> </column> <column> <property name="text"> <string>Monitor Mode</string> </property> </column> <column> <property name="text"> <string>Capture Filter</string> </property> </column> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <widget class="QCheckBox" name="capturePromModeCheckBox"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;You probably want to enable this. Usually a network card will only capture the traffic sent to its own network address. If you want to capture all traffic that the network card can &amp;quot;see&amp;quot;, mark this option. See the FAQ for some more details of capturing packets from a switched network.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="text"> <string>Enable promiscuous mode on all interfaces</string> </property> </widget> </item> <item> <spacer name="horizontalSpacer_2"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> <item> <widget class="QPushButton" name="manageButton"> <property name="enabled"> <bool>true</bool> </property> <property name="toolTip"> <string>Show and hide interfaces, add comments, and manage pipes and remote interfaces.</string> </property> <property name="text"> <string>Manage Interfaces…</string> </property> </widget> </item> </layout> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout_2" stretch="0,1,0,0"> <item> <widget class="QLabel" name="label_4"> <property name="text"> <string>Capture filter for selected interfaces:</string> </property> </widget> </item> <item> <widget class="CaptureFilterCombo" name="captureFilterComboBox"> <property name="sizePolicy"> <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> </widget> </item> <item> <spacer name="horizontalSpacer_4"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> <item> <widget class="QPushButton" name="compileBPF"> <property name="text"> <string>Compile BPFs</string> </property> </widget> </item> </layout> </item> </layout> </widget> <widget class="QWidget" name="outputTab"> <attribute name="title"> <string>Output</string> </attribute> <layout class="QVBoxLayout" name="verticalLayout_9"> <item> <widget class="QGroupBox" name="gbCaptureToFile"> <property name="enabled"> <bool>true</bool> </property> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Enter the file name to which captured data will be written. By default, a temporary file will be used.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="autoFillBackground"> <bool>false</bool> </property> <property name="title"> <string>Capture to a permanent file</string> </property> <property name="flat"> <bool>true</bool> </property> <property name="checkable"> <bool>false</bool> </property> <layout class="QGridLayout" name="gridLayout_3"> <item row="0" column="0"> <widget class="QLabel" name="label_2"> <property name="text"> <string>File:</string> </property> </widget> </item> <item row="0" column="1"> <widget class="QLineEdit" name="filenameLineEdit"/> </item> <item row="0" column="2"> <widget class="QPushButton" name="browseButton"> <property name="text"> <string>Browse…</string> </property> </widget> </item> </layout> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout_3"> <item> <widget class="QLabel" name="label"> <property name="text"> <string>Output format:</string> </property> </widget> </item> <item> <widget class="QRadioButton" name="rbPcapng"> <property name="text"> <string>pcapng</string> </property> </widget> </item> <item> <widget class="QRadioButton" name="rbPcap"> <property name="text"> <string>pcap</string> </property> </widget> </item> <item> <spacer name="horizontalSpacer_7"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> </layout> </item> <item> <widget class="QGroupBox" name="gbNewFileAuto"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Instead of using a single capture file, multiple files will be created.&lt;/p&gt;&lt;p&gt;The generated file names will contain an incrementing number and the start time of the capture.&lt;/p&gt;&lt;p&gt;NOTE: If enabled, at least one of the new-file criteria MUST be selected.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="title"> <string>Create a new file automatically…</string> </property> <property name="flat"> <bool>true</bool> </property> <property name="checkable"> <bool>true</bool> </property> <layout class="QGridLayout" name="gridLayout"> <item row="1" column="0"> <widget class="QCheckBox" name="PktCheckBox"> <property name="toolTip"> <string>Switch to the next file after the specified number of packets have been captured.</string> </property> <property name="text"> <string>after</string> </property> </widget> </item> <item row="1" column="1"> <widget class="QSpinBox" name="PktSpinBox"> <property name="toolTip"> <string>Switch to the next file after the specified number of packets have been captured.</string> </property> <property name="buttonSymbols"> <enum>QAbstractSpinBox::PlusMinus</enum> </property> <property name="maximum"> <number>2147483647</number> </property> <property name="value"> <number>100000</number> </property> </widget> </item> <item row="1" column="2"> <widget class="QLabel" name="PktLabel"> <property name="text"> <string>packets</string> </property> </widget> </item> <item row="2" column="0"> <widget class="QCheckBox" name="MBCheckBox"> <property name="toolTip"> <string>Switch to the next file after the file size exceeds the specified file size.</string> </property> <property name="text"> <string>after</string> </property> </widget> </item> <item row="2" column="1"> <widget class="QSpinBox" name="MBSpinBox"> <property name="toolTip"> <string>Switch to the next file after the file size exceeds the specified file size.</string> </property> <property name="wrapping"> <bool>true</bool> </property> <property name="buttonSymbols"> <enum>QAbstractSpinBox::PlusMinus</enum> </property> <property name="minimum"> <number>1</number> </property> <property name="maximum"> <number>1000000</number> </property> <property name="value"> <number>1</number> </property> </widget> </item> <item row="2" column="2"> <widget class="QComboBox" name="MBComboBox"> <property name="toolTip"> <string>Switch to the next file after the file size exceeds the specified file size.</string> </property> <item> <property name="text"> <string>kilobytes</string> </property> </item> <item> <property name="text"> <string>megabytes</string> </property> </item> <item> <property name="text"> <string>gigabytes</string> </property> </item> </widget> </item> <item row="3" column="0"> <widget class="QCheckBox" name="SecsCheckBox"> <property name="toolTip"> <string>Switch to the next file when the time capturing to the current file exceeds the specified time.</string> </property> <property name="text"> <string>after</string> </property> </widget> </item> <item row="3" column="1"> <widget class="QSpinBox" name="SecsSpinBox"> <property name="toolTip"> <string>Switch to the next file when the time capturing to the current file exceeds the specified time.</string> </property> <property name="wrapping"> <bool>true</bool> </property> <property name="buttonSymbols"> <enum>QAbstractSpinBox::PlusMinus</enum> </property> <property name="minimum"> <number>1</number> </property> <property name="maximum"> <number>1000000</number> </property> <property name="value"> <number>1</number> </property> </widget> </item> <item row="3" column="2"> <widget class="QComboBox" name="SecsComboBox"> <property name="toolTip"> <string>Switch to the next file when the time capturing to the current file exceeds the specified time.</string> </property> <item> <property name="text"> <string>seconds</string> </property> </item> <item> <property name="text"> <string>minutes</string> </property> </item> <item> <property name="text"> <string>hours</string> </property> </item> </widget> </item> <item row="4" column="0"> <widget class="QCheckBox" name="IntervalSecsCheckBox"> <property name="toolTip"> <string>Switch to the next file when the (wall clock) time is an even multiple of the specified interval. For example, use 1 hour to have a new file created every hour on the hour.</string> </property> <property name="text"> <string>when time is a multiple of</string> </property> </widget> </item> <item row="4" column="1"> <widget class="QSpinBox" name="IntervalSecsSpinBox"> <property name="toolTip"> <string>Switch to the next file when the (wall clock) time is an even multiple of the specified interval. For example, use 1 hour to have a new file created every hour on the hour.</string> </property> <property name="wrapping"> <bool>true</bool> </property> <property name="buttonSymbols"> <enum>QAbstractSpinBox::PlusMinus</enum> </property> <property name="minimum"> <number>1</number> </property> <property name="maximum"> <number>1000000</number> </property> <property name="value"> <number>1</number> </property> </widget> </item> <item row="4" column="2"> <widget class="QComboBox" name="IntervalSecsComboBox"> <property name="toolTip"> <string>Switch to the next file when the (wall clock) time is an even multiple of the specified interval. For example, use 1 hour to have a new file created every hour on the hour.</string> </property> <property name="currentIndex"> <number>2</number> </property> <item> <property name="text"> <string>seconds</string> </property> </item> <item> <property name="text"> <string>minutes</string> </property> </item> <item> <property name="text"> <string>hours</string> </property> </item> </widget> </item> <item row="5" column="0"> <widget class="QGroupBox" name="gbCompression"> <property name="title"> <string>compression</string> </property> <layout class="QVBoxLayout" name="verticalLayout_5"> <item> <widget class="QRadioButton" name="rbCompressionNone"> <property name="text"> <string>None</string> </property> <attribute name="buttonGroup"> <string notr="true">buttonGroup</string> </attribute> </widget> </item> <item> <widget class="QRadioButton" name="rbCompressionGzip"> <property name="text"> <string>gzip</string> </property> <attribute name="buttonGroup"> <string notr="true">buttonGroup</string> </attribute> </widget> </item> </layout> </widget> </item> <item row="0" column="3" rowspan="4"> <spacer name="horizontalSpacer_8"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> </layout> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout_4"> <item> <widget class="QCheckBox" name="RbCheckBox"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;After capturing has switched to the next file and the given number of files has exceeded, the oldest file will be removed.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="text"> <string>Use a ring buffer with </string> </property> </widget> </item> <item> <widget class="QSpinBox" name="RbSpinBox"> <property name="wrapping"> <bool>true</bool> </property> <property name="minimum"> <number>2</number> </property> <property name="maximum"> <number>65535</number> </property> <property name="value"> <number>2</number> </property> </widget> </item> <item> <widget class="QLabel" name="label_3"> <property name="text"> <string>files</string> </property> </widget> </item> <item> <spacer name="horizontalSpacer_9"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> </layout> </item> <item> <spacer name="verticalSpacer_2"> <property name="orientation"> <enum>Qt::Vertical</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>20</width> <height>40</height> </size> </property> </spacer> </item> </layout> <zorder>gbNewFileAuto</zorder> <zorder>gbCaptureToFile</zorder> </widget> <widget class="QWidget" name="optionsTab"> <attribute name="title"> <string>Options</string> </attribute> <layout class="QFormLayout" name="formLayout"> <item row="0" column="0"> <layout class="QHBoxLayout" name="horizontalLayout_8"> <item> <widget class="QGroupBox" name="groupBox"> <property name="title"> <string>Display Options</string> </property> <property name="flat"> <bool>true</bool> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QCheckBox" name="cbUpdatePacketsRT"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Using this option will show the captured packets immediately on the main screen. Please note: this will slow down capturing, so increased packet drops might appear.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="text"> <string>Update list of packets in real-time</string> </property> </widget> </item> <item> <widget class="QCheckBox" name="cbAutoScroll"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;This will scroll the &amp;quot;Packet List&amp;quot; automatically to the latest captured packet, when the &amp;quot;Update list of packets in real-time&amp;quot; option is used.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="text"> <string>Automatically scroll during live capture</string> </property> </widget> </item> <item> <widget class="QCheckBox" name="cbExtraCaptureInfo"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Show the capture info dialog while capturing.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="text"> <string>Show capture information during live capture</string> </property> </widget> </item> <item> <spacer name="horizontalSpacer_3"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> </layout> </widget> </item> <item> <widget class="QGroupBox" name="groupBox_2"> <property name="title"> <string>Name Resolution</string> </property> <property name="flat"> <bool>true</bool> </property> <layout class="QVBoxLayout" name="verticalLayout_3"> <item> <widget class="QCheckBox" name="cbResolveMacAddresses"> <property name="toolTip"> <string>Perform MAC layer name resolution while capturing.</string> </property> <property name="text"> <string>Resolve MAC addresses</string> </property> </widget> </item> <item> <widget class="QCheckBox" name="cbResolveNetworkNames"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Perform network layer name resolution while capturing.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="text"> <string>Resolve network names</string> </property> </widget> </item> <item> <widget class="QCheckBox" name="cbResolveTransportNames"> <property name="toolTip"> <string>Perform transport layer name resolution while capturing.</string> </property> <property name="text"> <string>Resolve transport names</string> </property> </widget> </item> <item> <spacer name="horizontalSpacer_5"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> </layout> </widget> </item> </layout> </item> <item row="1" column="0"> <widget class="QGroupBox" name="gbStopCaptureAuto"> <property name="enabled"> <bool>true</bool> </property> <property name="title"> <string>Stop capture automatically after…</string> </property> <property name="flat"> <bool>true</bool> </property> <layout class="QGridLayout" name="gridLayout_2"> <item row="0" column="3" rowspan="4"> <spacer name="horizontalSpacer"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> <item row="0" column="0"> <widget class="QCheckBox" name="stopPktCheckBox"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Stop capturing after the specified number of packets have been captured.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="text"> <string/> </property> </widget> </item> <item row="0" column="1"> <widget class="QSpinBox" name="stopPktSpinBox"> <property name="sizePolicy"> <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="toolTip"> <string>Stop capturing after the specified number of packets have been captured.</string> </property> <property name="buttonSymbols"> <enum>QAbstractSpinBox::PlusMinus</enum> </property> <property name="maximum"> <number>2147483647</number> </property> <property name="value"> <number>1</number> </property> </widget> </item> <item row="0" column="2"> <widget class="QLabel" name="label_7"> <property name="text"> <string>packets</string> </property> </widget> </item> <item row="1" column="0"> <widget class="QCheckBox" name="stopFilesCheckBox"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Stop capturing after the specified number of files have been created.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="text"> <string/> </property> </widget> </item> <item row="1" column="1"> <widget class="QSpinBox" name="stopFilesSpinBox"> <property name="sizePolicy"> <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="toolTip"> <string>Stop capturing after the specified number of packets have been captured.</string> </property> <property name="buttonSymbols"> <enum>QAbstractSpinBox::PlusMinus</enum> </property> <property name="maximum"> <number>2147483647</number> </property> <property name="value"> <number>1</number> </property> </widget> </item> <item row="1" column="2"> <widget class="QLabel" name="label_8"> <property name="text"> <string>files</string> </property> </widget> </item> <item row="2" column="0"> <widget class="QCheckBox" name="stopMBCheckBox"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Stop capturing after the specified amount of data has been captured.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="text"> <string/> </property> </widget> </item> <item row="2" column="1"> <widget class="QSpinBox" name="stopMBSpinBox"> <property name="toolTip"> <string>Stop capturing after the specified amount of data has been captured.</string> </property> <property name="buttonSymbols"> <enum>QAbstractSpinBox::PlusMinus</enum> </property> <property name="maximum"> <number>2147483647</number> </property> <property name="value"> <number>1</number> </property> </widget> </item> <item row="2" column="2"> <widget class="QComboBox" name="stopMBComboBox"> <property name="toolTip"> <string>Stop capturing after the specified amount of data has been captured.</string> </property> <item> <property name="text"> <string>kilobytes</string> </property> </item> <item> <property name="text"> <string>megabytes</string> </property> </item> <item> <property name="text"> <string>gigabytes</string> </property> </item> </widget> </item> <item row="3" column="0"> <widget class="QCheckBox" name="stopSecsCheckBox"> <property name="toolTip"> <string>Stop capturing after the specified amount of time has passed.</string> </property> <property name="text"> <string/> </property> </widget> </item> <item row="3" column="1"> <widget class="QSpinBox" name="stopSecsSpinBox"> <property name="toolTip"> <string>Stop capturing after the specified amount of time has passed.</string> </property> <property name="buttonSymbols"> <enum>QAbstractSpinBox::PlusMinus</enum> </property> <property name="maximum"> <number>2147483647</number> </property> <property name="value"> <number>1</number> </property> </widget> </item> <item row="3" column="2"> <widget class="QComboBox" name="stopSecsComboBox"> <property name="toolTip"> <string>Stop capturing after the specified amount of time has passed.</string> </property> <item> <property name="text"> <string>seconds</string> </property> </item> <item> <property name="text"> <string>minutes</string> </property> </item> <item> <property name="text"> <string>hours</string> </property> </item> </widget> </item> </layout> </widget> </item> <item row="2" column="0"> <widget class="QGroupBox" name="gbTempDir"> <property name="enabled"> <bool>true</bool> </property> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Optionally specify a temporary directory for unnamed capture files.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="autoFillBackground"> <bool>false</bool> </property> <property name="title"> <string>Directory for temporary files</string> </property> <property name="flat"> <bool>true</bool> </property> <property name="checkable"> <bool>false</bool> </property> <layout class="QGridLayout" name="gridLayout_4"> <item row="0" column="0"> <widget class="QLineEdit" name="tempDirLineEdit"/> </item> <item row="0" column="1"> <widget class="QPushButton" name="tempDirBrowseButton"> <property name="text"> <string>Browse…</string> </property> </widget> </item> </layout> </widget> </item> <item row="3" column="0"> <spacer name="verticalSpacer_3"> <property name="orientation"> <enum>Qt::Vertical</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>20</width> <height>40</height> </size> </property> </spacer> </item> </layout> </widget> </widget> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="standardButtons"> <set>QDialogButtonBox::Close|QDialogButtonBox::Help|QDialogButtonBox::Ok</set> </property> </widget> </item> </layout> </widget> <customwidgets> <customwidget> <class>CaptureFilterCombo</class> <extends>QComboBox</extends> <header>widgets/capture_filter_combo.h</header> </customwidget> </customwidgets> <resources/> <connections/> <buttongroups> <buttongroup name="buttonGroup"/> </buttongroups> </ui>
C++
wireshark/ui/qt/capture_preferences_frame.cpp
/* capture_preferences_frame.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include <wireshark.h> #ifdef HAVE_LIBPCAP #include "ui/capture_globals.h" #endif #include "capture_preferences_frame.h" #include <ui/qt/models/pref_models.h> #include <ui/qt/widgets/syntax_line_edit.h> #include <ui_capture_preferences_frame.h> #include "main_application.h" #include <QSpacerItem> #include "ui/capture_ui_utils.h" #include "ui/ws_ui_util.h" #include <epan/prefs-int.h> CapturePreferencesFrame::CapturePreferencesFrame(QWidget *parent) : QFrame(parent), ui(new Ui::CapturePreferencesFrame) { ui->setupUi(this); pref_device_ = prefFromPrefPtr(&prefs.capture_device); pref_prom_mode_ = prefFromPrefPtr(&prefs.capture_prom_mode); pref_pcap_ng_ = prefFromPrefPtr(&prefs.capture_pcap_ng); pref_real_time_ = prefFromPrefPtr(&prefs.capture_real_time); pref_update_interval_ = prefFromPrefPtr(&prefs.capture_update_interval); pref_no_interface_load_ = prefFromPrefPtr(&prefs.capture_no_interface_load); pref_no_extcap_ = prefFromPrefPtr(&prefs.capture_no_extcap); // Setting the left margin via a style sheet clobbers its // appearance. int margin = style()->pixelMetric(QStyle::PM_LayoutLeftMargin); QRect geom = ui->defaultInterfaceSpacer->geometry(); geom.setWidth(margin); ui->defaultInterfaceSpacer->setGeometry(geom); } CapturePreferencesFrame::~CapturePreferencesFrame() { delete ui; } void CapturePreferencesFrame::showEvent(QShowEvent *) { updateWidgets(); } void CapturePreferencesFrame::updateWidgets() { #ifdef HAVE_LIBPCAP interface_t *device; QString default_device_string; if (prefs_get_string_value(pref_device_, pref_stashed)) { default_device_string = prefs_get_string_value(pref_device_, pref_stashed); } ui->defaultInterfaceComboBox->clear(); if ((global_capture_opts.all_ifaces->len == 0) && (prefs_get_bool_value(pref_no_interface_load_, pref_stashed) == FALSE)) { /* * No interfaces - try refreshing the local interfaces, to * see whether any have showed up (or privileges have changed * to allow us to access them). */ mainApp->refreshLocalInterfaces(); } for (guint i = 0; i < global_capture_opts.all_ifaces->len; i++) { device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i); /* Continue if capture device is hidden */ if (device->hidden) { continue; } // InterfaceTree matches against device->name (the device name) // when selecting the default interface, so add it here if needed. // // On UN*Xes, the display name includes the device name, as // interface names are generally short simple names that // are somewhat human-recognizable; if there's a description, // it precedes the device name, which is followed by a colon // and a space, e.g. "Wi-Fi: en0". This means that we do not // need to add the device name. // // On Windows, the display name does not include the device // name, as it begins with \\Device and ends with a GUID, // with nothing much human-recognizable. Therefore, the // display name is just the "friendly name" that Windows // provides. This means that we *do* need to add the device // name, which means that, in the drop-down list, we show // the user a big ugly UUID-laden device path. // // We might be able to work around that by passing device->name as // the userData argument to addItem instead. // // This also means that the capture.device QString item_text = device->display_name; if (!item_text.contains(device->name)) { item_text.append(QString(" (%1)").arg(device->name)); } ui->defaultInterfaceComboBox->addItem(item_text); } if (!default_device_string.isEmpty()) { ui->defaultInterfaceComboBox->setEditText(default_device_string); } else { ui->defaultInterfaceComboBox->clearEditText(); } ui->capturePromModeCheckBox->setChecked(prefs_get_bool_value(pref_prom_mode_, pref_stashed)); ui->capturePcapNgCheckBox->setChecked(prefs_get_bool_value(pref_pcap_ng_, pref_stashed)); ui->captureRealTimeCheckBox->setChecked(prefs_get_bool_value(pref_real_time_, pref_stashed)); ui->captureUpdateIntervalLineEdit->setText(QString::number(prefs_get_uint_value_real(pref_update_interval_, pref_stashed))); ui->captureUpdateIntervalLineEdit->setPlaceholderText(QString::number(prefs_get_uint_value_real(pref_update_interval_, pref_default))); ui->captureUpdateIntervalLineEdit->setSyntaxState(SyntaxLineEdit::Empty); #endif // HAVE_LIBPCAP ui->captureNoInterfaceLoad->setChecked(prefs_get_bool_value(pref_no_interface_load_, pref_stashed)); ui->captureNoExtcapCheckBox->setChecked(prefs_get_bool_value(pref_no_extcap_, pref_stashed)); } void CapturePreferencesFrame::on_defaultInterfaceComboBox_editTextChanged(const QString &new_iface) { prefs_set_string_value(pref_device_, new_iface.toUtf8().constData(), pref_stashed); } void CapturePreferencesFrame::on_capturePromModeCheckBox_toggled(bool checked) { prefs_set_bool_value(pref_prom_mode_, checked, pref_stashed); } void CapturePreferencesFrame::on_capturePcapNgCheckBox_toggled(bool checked) { prefs_set_bool_value(pref_pcap_ng_, checked, pref_stashed); } void CapturePreferencesFrame::on_captureRealTimeCheckBox_toggled(bool checked) { prefs_set_bool_value(pref_real_time_, checked, pref_stashed); } void CapturePreferencesFrame::on_captureUpdateIntervalLineEdit_textChanged(const QString &new_str) { uint new_uint; if (new_str.isEmpty()) { new_uint = prefs_get_uint_value_real(pref_update_interval_, pref_default); prefs_set_uint_value(pref_update_interval_, new_uint, pref_stashed); ui->captureUpdateIntervalLineEdit->setSyntaxState(SyntaxLineEdit::Empty); return; } bool ok; new_uint = new_str.toUInt(&ok, 0); if (ok) { ui->captureUpdateIntervalLineEdit->setSyntaxState(SyntaxLineEdit::Valid); } else { new_uint = prefs_get_uint_value_real(pref_update_interval_, pref_current); ui->captureUpdateIntervalLineEdit->setSyntaxState(SyntaxLineEdit::Invalid); } prefs_set_uint_value(pref_update_interval_, new_uint, pref_stashed); } void CapturePreferencesFrame::on_captureNoInterfaceLoad_toggled(bool checked) { prefs_set_bool_value(pref_no_interface_load_, checked, pref_stashed); } void CapturePreferencesFrame::on_captureNoExtcapCheckBox_toggled(bool checked) { prefs_set_bool_value(pref_no_extcap_, checked, pref_stashed); }
C/C++
wireshark/ui/qt/capture_preferences_frame.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef CAPTURE_PREFERENCES_FRAME_H #define CAPTURE_PREFERENCES_FRAME_H #include <QFrame> #include <epan/prefs.h> namespace Ui { class CapturePreferencesFrame; } class CapturePreferencesFrame : public QFrame { Q_OBJECT public: explicit CapturePreferencesFrame(QWidget *parent = 0); ~CapturePreferencesFrame(); protected: void showEvent(QShowEvent *evt); private slots: void on_defaultInterfaceComboBox_editTextChanged(const QString &new_iface); void on_capturePromModeCheckBox_toggled(bool checked); void on_capturePcapNgCheckBox_toggled(bool checked); void on_captureRealTimeCheckBox_toggled(bool checked); void on_captureUpdateIntervalLineEdit_textChanged(const QString &new_str); void on_captureNoInterfaceLoad_toggled(bool checked); void on_captureNoExtcapCheckBox_toggled(bool checked); private: Ui::CapturePreferencesFrame *ui; pref_t *pref_device_; pref_t *pref_prom_mode_; pref_t *pref_pcap_ng_; pref_t *pref_real_time_; pref_t *pref_update_interval_; pref_t *pref_no_interface_load_; pref_t *pref_no_extcap_; void updateWidgets(); }; #endif // CAPTURE_PREFERENCES_FRAME_H
User Interface
wireshark/ui/qt/capture_preferences_frame.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>CapturePreferencesFrame</class> <widget class="QFrame" name="CapturePreferencesFrame"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>354</width> <height>220</height> </rect> </property> <property name="minimumSize"> <size> <width>0</width> <height>191</height> </size> </property> <property name="windowTitle"> <string>Frame</string> </property> <property name="lineWidth"> <number>0</number> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QLabel" name="label"> <property name="text"> <string>Default interface</string> </property> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <spacer name="defaultInterfaceSpacer"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeType"> <enum>QSizePolicy::Fixed</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>18</width> <height>20</height> </size> </property> </spacer> </item> <item> <widget class="QComboBox" name="defaultInterfaceComboBox"> <property name="editable"> <bool>true</bool> </property> </widget> </item> </layout> </item> <item> <widget class="QCheckBox" name="capturePromModeCheckBox"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;You probably want to enable this. Usually a network card will only capture the traffic sent to its own network address. If you want to capture all traffic that the network card can &amp;quot;see&amp;quot;, mark this option. See the FAQ for some more details of capturing packets from a switched network.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="text"> <string>Capture packets in promiscuous mode</string> </property> </widget> </item> <item> <widget class="QCheckBox" name="capturePcapNgCheckBox"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Capture packets in the next-generation capture file format.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="text"> <string>Capture packets in pcapng format</string> </property> </widget> </item> <item> <widget class="QCheckBox" name="captureRealTimeCheckBox"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Update the list of packets while capture is in progress. This can result in dropped packets on high-speed networks.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="text"> <string>Update list of packets in real time</string> </property> </widget> </item> <item> <layout class="QHBoxLayout" name="captureUpdateInterval"> <item> <widget class="QLabel" name="captureUpdateIntervalLabel"> <property name="text"> <string>Interval between updates (ms)</string> </property> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;How often the capture notifies the GUI of new packets. Affects how often the GUI updates and the granularity of timers.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> </widget> </item> <item> <widget class="SyntaxLineEdit" name="captureUpdateIntervalLineEdit"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;The interval between new packet updates. Affects how often the GUI updates and the granularity of timers.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> </widget> </item> <item> <spacer name="captureUpdateIntervalHorizontalSpacer"> <property name="orientation"> <enum>Qt:Horizontal</enum> </property> </spacer> </item> </layout> </item> <item> <widget class="QCheckBox" name="captureNoInterfaceLoad"> <property name="text"> <string>Don't load interfaces on startup</string> </property> </widget> </item> <item> <widget class="QCheckBox" name="captureNoExtcapCheckBox"> <property name="text"> <string>Disable external capture interfaces</string> </property> </widget> </item> <item> <spacer name="verticalSpacer"> <property name="orientation"> <enum>Qt::Vertical</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>20</width> <height>3</height> </size> </property> </spacer> </item> </layout> </widget> <customwidgets> <customwidget> <class>SyntaxLineEdit</class> <extends>QLineEdit</extends> <header>widgets/syntax_line_edit.h</header> </customwidget> </customwidgets> <resources/> <connections/> </ui>
Text
wireshark/ui/qt/CMakeLists.txt
# CMakeLists.txt # # Wireshark - Network traffic analyzer # By Gerald Combs <[email protected]> # Copyright 1998 Gerald Combs # # SPDX-License-Identifier: GPL-2.0-or-later # if(USE_qt6) set(qtver "6") else() set(qtver "5") endif() ADD_CUSTOM_CMAKE_INCLUDE() set(WIRESHARK_WIDGET_HEADERS widgets/additional_toolbar.h widgets/apply_line_edit.h widgets/byte_view_text.h widgets/capture_filter_combo.h widgets/capture_filter_edit.h widgets/clickable_label.h widgets/copy_from_profile_button.h widgets/detachable_tabwidget.h widgets/display_filter_combo.h widgets/display_filter_edit.h widgets/dissector_syntax_line_edit.h widgets/dissector_tables_view.h widgets/drag_drop_toolbar.h widgets/drag_label.h widgets/editor_file_dialog.h widgets/elided_label.h widgets/expert_info_view.h widgets/export_objects_view.h widgets/field_filter_edit.h widgets/filter_expression_toolbar.h widgets/find_line_edit.h widgets/follow_stream_text.h widgets/interface_toolbar_lineedit.h widgets/label_stack.h widgets/overlay_scroll_bar.h widgets/packet_list_header.h widgets/path_selection_edit.h widgets/pref_module_view.h widgets/profile_tree_view.h widgets/range_syntax_lineedit.h widgets/rtp_audio_graph.h widgets/splash_overlay.h widgets/stock_icon_tool_button.h widgets/syntax_line_edit.h widgets/tabnav_tree_view.h widgets/traffic_tab.h widgets/traffic_tree.h widgets/traffic_types_list.h widgets/wireless_timeline.h widgets/wireshark_file_dialog.h ) set(WIRESHARK_3RD_PARTY_WIDGET_HEADERS widgets/qcustomplot.h ) set(WIRESHARK_MANAGER_HEADERS manager/preference_manager.h manager/wireshark_preference.h ) set(WIRESHARK_UTILS_HEADERS utils/color_utils.h utils/data_printer.h utils/field_information.h utils/frame_information.h utils/idata_printable.h utils/proto_node.h utils/qt_ui_utils.h utils/rtp_audio_file.h utils/rtp_audio_routing_filter.h utils/rtp_audio_routing.h utils/rtp_audio_silence_generator.h utils/stock_icon.h utils/tango_colors.h utils/variant_pointer.h utils/wireshark_mime_data.h utils/wireshark_zip_helper.h ) set(WIRESHARK_MODEL_HEADERS models/astringlist_list_model.h models/atap_data_model.h models/cache_proxy_model.h models/coloring_rules_delegate.h models/coloring_rules_model.h models/column_list_model.h models/credentials_model.h models/decode_as_delegate.h models/decode_as_model.h models/dissector_tables_model.h models/enabled_protocols_model.h models/expert_info_model.h models/expert_info_proxy_model.h models/export_objects_model.h models/fileset_entry_model.h models/filter_list_model.h models/info_proxy_model.h models/interface_sort_filter_model.h models/interface_tree_cache_model.h models/interface_tree_model.h models/manuf_table_model.h models/numeric_value_chooser_delegate.h models/packet_list_model.h models/packet_list_record.h models/path_selection_delegate.h models/percent_bar_delegate.h models/pref_delegate.h models/pref_models.h models/profile_model.h models/proto_tree_model.h models/related_packet_delegate.h models/resolved_addresses_models.h models/sparkline_delegate.h models/supported_protocols_model.h models/timeline_delegate.h models/tree_model_helpers.h models/uat_delegate.h models/uat_model.h models/url_link_delegate.h models/voip_calls_info_model.h ) # All .h files which inherit from QObject aka which use the Q_OBJECT macro # need to go here. set(WIRESHARK_QT_HEADERS about_dialog.h accordion_frame.h address_editor_frame.h bluetooth_att_server_attributes_dialog.h bluetooth_device_dialog.h bluetooth_devices_dialog.h bluetooth_hci_summary_dialog.h byte_view_tab.h capture_file_dialog.h capture_file_properties_dialog.h capture_file.h capture_filter_syntax_worker.h capture_options_dialog.h capture_preferences_frame.h coloring_rules_dialog.h column_editor_frame.h column_preferences_frame.h compiled_filter_output.h conversation_colorize_action.h conversation_dialog.h conversation_hash_tables_dialog.h credentials_dialog.h decode_as_dialog.h display_filter_expression_dialog.h dissector_tables_dialog.h enabled_protocols_dialog.h endpoint_dialog.h expert_info_dialog.h export_dissection_dialog.h export_object_action.h export_object_dialog.h export_pdu_dialog.h extcap_argument_file.h extcap_argument_multiselect.h extcap_argument.h extcap_options_dialog.h file_set_dialog.h filter_action.h filter_dialog.h filter_dialog.h filter_expression_frame.h firewall_rules_dialog.h follow_stream_action.h follow_stream_dialog.h font_color_preferences_frame.h funnel_statistics.h funnel_string_dialog.h funnel_text_dialog.h geometry_state_dialog.h glib_mainloop_on_qeventloop.h gsm_map_summary_dialog.h iax2_analysis_dialog.h import_text_dialog.h interface_frame.h interface_toolbar_reader.h interface_toolbar.h io_console_dialog.h io_graph_dialog.h layout_preferences_frame.h lbm_lbtrm_transport_dialog.h lbm_lbtru_transport_dialog.h lbm_stream_dialog.h lte_mac_statistics_dialog.h lte_rlc_graph_dialog.h lte_rlc_statistics_dialog.h main_application.h main_status_bar.h main_window_preferences_frame.h main_window.h manage_interfaces_dialog.h manuf_dialog.h module_preferences_scroll_area.h mtp3_summary_dialog.h multicast_statistics_dialog.h packet_comment_dialog.h packet_diagram.h packet_dialog.h packet_format_group_box.h packet_list.h packet_range_group_box.h preference_editor_frame.h preferences_dialog.h print_dialog.h profile_dialog.h progress_frame.h proto_tree.h protocol_hierarchy_dialog.h protocol_preferences_menu.h recent_file_status.h resolved_addresses_dialog.h response_time_delay_dialog.h rpc_service_response_time_dialog.h rsa_keys_frame.h rtp_analysis_dialog.h rtp_audio_stream.h rtp_player_dialog.h rtp_stream_dialog.h scsi_service_response_time_dialog.h sctp_all_assocs_dialog.h sctp_assoc_analyse_dialog.h sctp_chunk_statistics_dialog.h sctp_graph_arwnd_dialog.h sctp_graph_byte_dialog.h sctp_graph_dialog.h search_frame.h sequence_diagram.h sequence_dialog.h service_response_time_dialog.h show_packet_bytes_dialog.h simple_statistics_dialog.h stats_tree_dialog.h strip_headers_dialog.h supported_protocols_dialog.h tabnav_tree_widget.h tap_parameter_dialog.h tcp_stream_dialog.h time_shift_dialog.h traffic_table_dialog.h uat_dialog.h uat_frame.h voip_calls_dialog.h welcome_page.h wireless_frame.h wireshark_application.h wireshark_dialog.h wireshark_main_window.h wlan_statistics_dialog.h ${WIRESHARK_CUSTOM_QT_HEADERS} ) if(ENABLE_PCAP) list(APPEND WIRESHARK_QT_HEADERS capture_info_dialog.h ) if(HAVE_PCAP_REMOTE) list(APPEND WIRESHARK_QT_HEADERS remote_capture_dialog.h remote_settings_dialog.h ) endif() endif() set(WIRESHARK_WIDGET_SRCS widgets/additional_toolbar.cpp widgets/apply_line_edit.cpp widgets/byte_view_text.cpp widgets/capture_filter_combo.cpp widgets/capture_filter_edit.cpp widgets/clickable_label.cpp widgets/copy_from_profile_button.cpp widgets/detachable_tabwidget.cpp widgets/display_filter_combo.cpp widgets/display_filter_edit.cpp widgets/dissector_syntax_line_edit.cpp widgets/dissector_tables_view.cpp widgets/drag_drop_toolbar.cpp widgets/drag_label.cpp widgets/editor_file_dialog.cpp widgets/elided_label.cpp widgets/expert_info_view.cpp widgets/export_objects_view.cpp widgets/field_filter_edit.cpp widgets/filter_expression_toolbar.cpp widgets/find_line_edit.cpp widgets/follow_stream_text.cpp widgets/interface_toolbar_lineedit.cpp widgets/label_stack.cpp widgets/overlay_scroll_bar.cpp widgets/packet_list_header.cpp widgets/path_selection_edit.cpp widgets/pref_module_view.cpp widgets/profile_tree_view.cpp widgets/range_syntax_lineedit.cpp widgets/rtp_audio_graph.cpp widgets/splash_overlay.cpp widgets/stock_icon_tool_button.cpp widgets/syntax_line_edit.cpp widgets/tabnav_tree_view.cpp widgets/traffic_tab.cpp widgets/traffic_tree.cpp widgets/traffic_types_list.cpp widgets/wireless_timeline.cpp widgets/wireshark_file_dialog.cpp ) set(WIRESHARK_3RD_PARTY_WIDGET_SRCS widgets/qcustomplot.cpp ) set(WIRESHARK_MANAGER_SRCS manager/preference_manager.cpp manager/wireshark_preference.cpp ) set(WIRESHARK_UTILS_SRCS utils/color_utils.cpp utils/data_printer.cpp utils/field_information.cpp utils/frame_information.cpp utils/proto_node.cpp utils/qt_ui_utils.cpp utils/rtp_audio_file.cpp utils/rtp_audio_routing_filter.cpp utils/rtp_audio_routing.cpp utils/rtp_audio_silence_generator.cpp utils/stock_icon.cpp utils/wireshark_mime_data.cpp utils/wireshark_zip_helper.cpp ) set(WIRESHARK_MODEL_SRCS models/astringlist_list_model.cpp models/atap_data_model.cpp models/cache_proxy_model.cpp models/coloring_rules_delegate.cpp models/coloring_rules_model.cpp models/column_list_model.cpp models/credentials_model.cpp models/decode_as_delegate.cpp models/decode_as_model.cpp models/dissector_tables_model.cpp models/enabled_protocols_model.cpp models/expert_info_model.cpp models/expert_info_proxy_model.cpp models/export_objects_model.cpp models/fileset_entry_model.cpp models/filter_list_model.cpp models/info_proxy_model.cpp models/interface_sort_filter_model.cpp models/interface_tree_cache_model.cpp models/interface_tree_model.cpp models/manuf_table_model.cpp models/numeric_value_chooser_delegate.cpp models/packet_list_model.cpp models/packet_list_record.cpp models/path_selection_delegate.cpp models/percent_bar_delegate.cpp models/pref_delegate.cpp models/pref_models.cpp models/profile_model.cpp models/proto_tree_model.cpp models/related_packet_delegate.cpp models/resolved_addresses_models.cpp models/sparkline_delegate.cpp models/supported_protocols_model.cpp models/timeline_delegate.cpp models/uat_delegate.cpp models/uat_model.cpp models/url_link_delegate.cpp models/voip_calls_info_model.cpp ) set(WIRESHARK_QT_SRC about_dialog.cpp accordion_frame.cpp address_editor_frame.cpp bluetooth_att_server_attributes_dialog.cpp bluetooth_device_dialog.cpp bluetooth_devices_dialog.cpp bluetooth_hci_summary_dialog.cpp byte_view_tab.cpp capture_file_dialog.cpp capture_file_properties_dialog.cpp capture_file.cpp capture_filter_syntax_worker.cpp capture_options_dialog.cpp capture_preferences_frame.cpp coloring_rules_dialog.cpp column_editor_frame.cpp column_preferences_frame.cpp compiled_filter_output.cpp conversation_colorize_action.cpp conversation_dialog.cpp conversation_hash_tables_dialog.cpp credentials_dialog.cpp decode_as_dialog.cpp display_filter_expression_dialog.cpp dissector_tables_dialog.cpp enabled_protocols_dialog.cpp endpoint_dialog.cpp export_dissection_dialog.cpp export_object_action.cpp export_object_dialog.cpp export_pdu_dialog.cpp extcap_argument_file.cpp extcap_argument_multiselect.cpp extcap_argument.cpp extcap_options_dialog.cpp file_set_dialog.cpp filter_action.cpp filter_dialog.cpp filter_expression_frame.cpp firewall_rules_dialog.cpp follow_stream_action.cpp follow_stream_dialog.cpp font_color_preferences_frame.cpp funnel_string_dialog.cpp funnel_text_dialog.cpp geometry_state_dialog.cpp glib_mainloop_on_qeventloop.cpp iax2_analysis_dialog.cpp import_text_dialog.cpp interface_frame.cpp interface_toolbar_reader.cpp interface_toolbar.cpp io_console_dialog.cpp layout_preferences_frame.cpp lbm_lbtrm_transport_dialog.cpp lbm_lbtru_transport_dialog.cpp lbm_stream_dialog.cpp lte_mac_statistics_dialog.cpp lte_rlc_graph_dialog.cpp lte_rlc_statistics_dialog.cpp main_application.cpp main_status_bar.cpp main_window_layout.cpp main_window_preferences_frame.cpp main_window.cpp main.cpp manage_interfaces_dialog.cpp manuf_dialog.cpp module_preferences_scroll_area.cpp packet_comment_dialog.cpp packet_diagram.cpp packet_dialog.cpp packet_format_group_box.cpp packet_list.cpp packet_range_group_box.cpp preference_editor_frame.cpp preferences_dialog.cpp print_dialog.cpp profile_dialog.cpp progress_frame.cpp proto_tree.cpp protocol_hierarchy_dialog.cpp protocol_preferences_menu.cpp recent_file_status.cpp resolved_addresses_dialog.cpp response_time_delay_dialog.cpp rpc_service_response_time_dialog.cpp rsa_keys_frame.cpp rtp_analysis_dialog.cpp rtp_audio_stream.cpp rtp_player_dialog.cpp rtp_stream_dialog.cpp scsi_service_response_time_dialog.cpp sctp_all_assocs_dialog.cpp sctp_assoc_analyse_dialog.cpp sctp_chunk_statistics_dialog.cpp sctp_graph_arwnd_dialog.cpp sctp_graph_byte_dialog.cpp sctp_graph_dialog.cpp search_frame.cpp sequence_diagram.cpp sequence_dialog.cpp service_response_time_dialog.cpp show_packet_bytes_dialog.cpp simple_dialog.cpp simple_statistics_dialog.cpp supported_protocols_dialog.cpp strip_headers_dialog.cpp tabnav_tree_widget.cpp tap_parameter_dialog.cpp tcp_stream_dialog.cpp time_shift_dialog.cpp traffic_table_dialog.cpp uat_dialog.cpp uat_frame.cpp voip_calls_dialog.cpp welcome_page.cpp wireless_frame.cpp wireshark_application.cpp wireshark_dialog.cpp wireshark_main_window.cpp wireshark_main_window_slots.cpp ${WIRESHARK_CUSTOM_QT_SRCS} ) if(ENABLE_PCAP) list(APPEND WIRESHARK_QT_SRC capture_info_dialog.cpp ) if(HAVE_PCAP_REMOTE) list(APPEND WIRESHARK_QT_SRC remote_capture_dialog.cpp remote_settings_dialog.cpp ) endif() endif() set(WIRESHARK_QT_TAP_SRC ${CMAKE_CURRENT_SOURCE_DIR}/expert_info_dialog.cpp ${CMAKE_CURRENT_SOURCE_DIR}/funnel_statistics.cpp ${CMAKE_CURRENT_SOURCE_DIR}/gsm_map_summary_dialog.cpp ${CMAKE_CURRENT_SOURCE_DIR}/io_graph_dialog.cpp ${CMAKE_CURRENT_SOURCE_DIR}/lte_mac_statistics_dialog.cpp ${CMAKE_CURRENT_SOURCE_DIR}/lte_rlc_statistics_dialog.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mtp3_summary_dialog.cpp ${CMAKE_CURRENT_SOURCE_DIR}/multicast_statistics_dialog.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rtp_stream_dialog.cpp ${CMAKE_CURRENT_SOURCE_DIR}/sctp_all_assocs_dialog.cpp ${CMAKE_CURRENT_SOURCE_DIR}/sctp_assoc_analyse_dialog.cpp ${CMAKE_CURRENT_SOURCE_DIR}/stats_tree_dialog.cpp ${CMAKE_CURRENT_SOURCE_DIR}/wlan_statistics_dialog.cpp ${WIRESHARK_CUSTOM_TAP_SRC} ) set(WIRESHARK_QT_NONGENERATED_SRC ${WIRESHARK_QT_SRC} ${WIRESHARK_QT_TAP_SRC} ${WIRESHARK_MODEL_SRCS} ${WIRESHARK_UTILS_SRCS} ${WIRESHARK_MANAGER_SRCS} ${WIRESHARK_3RD_PARTY_WIDGET_SRCS} ${WIRESHARK_WIDGET_SRCS} ) set(WIRESHARK_QT_UI about_dialog.ui address_editor_frame.ui bluetooth_att_server_attributes_dialog.ui bluetooth_device_dialog.ui bluetooth_devices_dialog.ui bluetooth_hci_summary_dialog.ui capture_file_properties_dialog.ui capture_info_dialog.ui capture_options_dialog.ui capture_preferences_frame.ui coloring_rules_dialog.ui column_editor_frame.ui column_preferences_frame.ui compiled_filter_output.ui conversation_hash_tables_dialog.ui credentials_dialog.ui decode_as_dialog.ui display_filter_expression_dialog.ui dissector_tables_dialog.ui enabled_protocols_dialog.ui expert_info_dialog.ui export_object_dialog.ui export_pdu_dialog.ui extcap_options_dialog.ui file_set_dialog.ui filter_dialog.ui filter_expression_frame.ui firewall_rules_dialog.ui follow_stream_dialog.ui font_color_preferences_frame.ui funnel_string_dialog.ui funnel_text_dialog.ui gsm_map_summary_dialog.ui iax2_analysis_dialog.ui import_text_dialog.ui interface_frame.ui interface_toolbar.ui io_console_dialog.ui io_graph_dialog.ui layout_preferences_frame.ui lbm_lbtrm_transport_dialog.ui lbm_lbtru_transport_dialog.ui lbm_stream_dialog.ui lte_rlc_graph_dialog.ui main_window_preferences_frame.ui manage_interfaces_dialog.ui manuf_dialog.ui module_preferences_scroll_area.ui mtp3_summary_dialog.ui packet_comment_dialog.ui packet_dialog.ui packet_format_group_box.ui packet_range_group_box.ui preference_editor_frame.ui preferences_dialog.ui print_dialog.ui profile_dialog.ui progress_frame.ui protocol_hierarchy_dialog.ui resolved_addresses_dialog.ui rsa_keys_frame.ui rtp_analysis_dialog.ui rtp_player_dialog.ui rtp_stream_dialog.ui sctp_all_assocs_dialog.ui sctp_assoc_analyse_dialog.ui sctp_chunk_statistics_dialog.ui sctp_graph_arwnd_dialog.ui sctp_graph_byte_dialog.ui sctp_graph_dialog.ui search_frame.ui sequence_dialog.ui show_packet_bytes_dialog.ui strip_headers_dialog.ui supported_protocols_dialog.ui tap_parameter_dialog.ui tcp_stream_dialog.ui time_shift_dialog.ui traffic_table_dialog.ui uat_dialog.ui uat_frame.ui voip_calls_dialog.ui welcome_page.ui widgets/splash_overlay.ui wireless_frame.ui wireshark_main_window.ui ) if(HAVE_PCAP_REMOTE) list(APPEND WIRESHARK_QT_UI remote_capture_dialog.ui remote_settings_dialog.ui ) endif() set(WIRESHARK_QT_TS wireshark_de.ts wireshark_en.ts # lupdate -pluralonly wireshark_es.ts wireshark_fr.ts wireshark_it.ts wireshark_ja_JP.ts wireshark_pl.ts wireshark_ru.ts wireshark_sv.ts wireshark_tr_TR.ts wireshark_uk.ts wireshark_zh_CN.ts ) foreach(_file ${WIRESHARK_QT_TS}) get_filename_component(_qresource ${_file} NAME_WE) set(_qresource_qm "${_qresource}.qm") set(i18n_qresource "${i18n_qresource}\n <file>${_qresource_qm}</file>") endforeach() configure_file(${CMAKE_CURRENT_SOURCE_DIR}/i18n.qrc.in ${CMAKE_CURRENT_BINARY_DIR}/i18n.qrc) file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/authors.qrc" "<RCC>\n" " <qresource prefix=\"/about\">\n" " <file compress-algo=\"zstd\">authors.csv</file>\n" " </qresource>\n" "</RCC>\n" ) add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/authors.csv COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tools/make-authors-csv.py < ${CMAKE_SOURCE_DIR}/AUTHORS > ${CMAKE_CURRENT_BINARY_DIR}/authors.csv DEPENDS ${CMAKE_SOURCE_DIR}/tools/make-authors-csv.py ${CMAKE_SOURCE_DIR}/AUTHORS ) set(WIRESHARK_QT_QRC ../../resources/about.qrc ../../resources/languages/languages.qrc ../../resources/layout.qrc ../../resources/stock_icons.qrc ../../resources/wsicon.qrc ${CMAKE_CURRENT_BINARY_DIR}/i18n.qrc ${CMAKE_CURRENT_BINARY_DIR}/authors.qrc ${CMAKE_CURRENT_BINARY_DIR}/authors.csv ) if(NOT Qt${qtver}Widgets_VERSION VERSION_LESS "5.9") # Drop the file modification time of source files from generated files # to help with reproducible builds. We do not use QFileInfo.lastModified # so this has no unwanted side effects. This mtime started appearing in # Qt 5.8. The option to force the old file format without mtime was # added in Qt 5.9. See https://bugreports.qt.io/browse/QTBUG-58769. # Force the compression algorithm to zlib, since zstd requires format # version 3. See https://gitlab.com/wireshark/wireshark/-/issues/18100. # Use the number of dashes for each argument as documented at # https://doc.qt.io/qt-6/rcc.html. set(CMAKE_AUTORCC_OPTIONS --format-version 1) if(Qt${qtver}Widgets_VERSION VERSION_GREATER_EQUAL "5.13") list(APPEND CMAKE_AUTORCC_OPTIONS -compress-algo zlib) endif() endif() if (USE_qt6) QT6_ADD_TRANSLATION(WIRESHARK_QT_QM ${WIRESHARK_QT_TS} OPTIONS -silent) elseif(NOT Qt${qtver}Widgets_VERSION VERSION_LESS "5.11") QT5_ADD_TRANSLATION(WIRESHARK_QT_QM ${WIRESHARK_QT_TS} OPTIONS -silent) else() QT5_ADD_TRANSLATION(WIRESHARK_QT_QM ${WIRESHARK_QT_TS}) endif() if (WIN32) add_custom_target(copy_qt_translations ALL) add_custom_command(TARGET copy_qt_translations POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory $<TARGET_FILE_DIR:wireshark>/translations COMMAND ${CMAKE_COMMAND} -E copy_if_different ${WIRESHARK_QT_QM} $<TARGET_FILE_DIR:wireshark>/translations ) endif() add_custom_target( translations DEPENDS ${WIRESHARK_QT_QM} ) set_target_properties(translations PROPERTIES FOLDER "UI") set_source_files_properties( ${WIRESHARK_QT_NONGENERATED_SRC} PROPERTIES COMPILE_FLAGS "${WERROR_COMMON_FLAGS}" ) set_source_files_properties( wireshark-tap-register.c PROPERTIES SKIP_AUTOGEN ON ) add_definitions(${QT5_DEFINITIONS}) register_tap_files(wireshark-tap-register.c ${WIRESHARK_QT_TAP_SRC} ) source_group("ui\\UIC Files" FILES ${WIRESHARK_QT_UI}) source_group("ui\\qrc" FILES ${WIRESHARK_QT_QRC}) source_group("ui\\Header" FILES ${WIRESHARK_QT_HEADERS}) source_group("ui\\Widget Header" FILES ${WIRESHARK_WIDGET_HEADERS}) source_group("ui\\Widget Source" FILES ${WIRESHARK_WIDGET_SRCS}) source_group("ui\\Utils Headers Files" FILES ${WIRESHARK_UTILS_HEADERS}) source_group("ui\\Utils Source" FILES ${WIRESHARK_UTILS_SRCS}) source_group("ui\\Models Headers" FILES ${WIRESHARK_MODEL_HEADERS}) source_group("ui\\Models Source" FILES ${WIRESHARK_MODEL_SRCS}) source_group("ui\\Manager Headers" FILES ${WIRESHARK_MANAGER_HEADERS}) source_group("ui\\Manager Source" FILES ${WIRESHARK_MANAGER_SRCS}) add_library(qtui OBJECT #Included so that Visual Studio can properly put header files in solution ${WIRESHARK_QT_HEADERS} ${WIRESHARK_WIDGET_HEADERS} ${WIRESHARK_3RD_PARTY_WIDGET_HEADERS} ${WIRESHARK_MANAGER_HEADERS} ${WIRESHARK_UTILS_HEADERS} ${WIRESHARK_MODEL_HEADERS} ${WIRESHARK_QT_NONGENERATED_SRC} # For AUTOUIC and AUTORCC. ${WIRESHARK_QT_UI} ${WIRESHARK_QT_QRC} ${WIRESHARK_QT_TAP_SRC} wireshark-tap-register.c ) if(USE_qt6) target_link_libraries(qtui PUBLIC Qt6::Widgets Qt6::Core5Compat Qt6::Concurrent Qt6::PrintSupport ) if(Qt6Multimedia_FOUND) target_link_libraries(qtui PUBLIC Qt6::Multimedia) endif() endif() target_include_directories(qtui SYSTEM PRIVATE # Include Qt before anything else, see the comment about # QT5_INCLUDE_DIRS in the top-level CMakeLists.txt # Basically, qt@5 headers should be prioritized over qt@6 which # would be found due to GCRYPT_INCLUDE_DIRS=/usr/local/include ${QT5_INCLUDE_DIRS} ${GCRYPT_INCLUDE_DIRS} ${MINIZIP_INCLUDE_DIRS} ${PCAP_INCLUDE_DIRS} ${SPEEXDSP_INCLUDE_DIRS} ${WINSPARKLE_INCLUDE_DIRS} PRIVATE ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ) target_compile_definitions(qtui PUBLIC ${QT5_COMPILE_DEFINITIONS} ) set_target_properties(qtui PROPERTIES LINK_FLAGS "${WS_LINK_FLAGS}" FOLDER "UI" AUTOMOC ON AUTOUIC ON AUTORCC ON # Ensure .qm files are generated before autogenerating i18n.qrc AUTOGEN_TARGET_DEPENDS "${WIRESHARK_QT_QM}" ) if(MSVC) set_target_properties(qtui PROPERTIES LINK_FLAGS_DEBUG "${WS_MSVC_DEBUG_LINK_FLAGS}") endif() CHECKAPI( NAME ui-qt SWITCHES --nocheck-shadow SOURCES # QCustomPlot (WIRESHARK_3RD_PARTY_WIDGET_{HEADERS,SRCS}) uses # prohibited APIs. ${WIRESHARK_QT_HEADERS} ${WIRESHARK_WIDGET_HEADERS} ${WIRESHARK_MANAGER_HEADERS} ${WIRESHARK_UTILS_HEADERS} ${WIRESHARK_MODEL_HEADERS} ${WIRESHARK_QT_SRC} ${WIRESHARK_WIDGET_SRCS} ${WIRESHARK_MANAGER_SRCS} ${WIRESHARK_UTILS_SRCS} ${WIRESHARK_MODEL_SRCS} ${WIRESHARK_QT_TAP_SRC} ) # # Editor modelines - https://www.wireshark.org/tools/modelines.html # # Local variables: # c-basic-offset: 8 # tab-width: 8 # indent-tabs-mode: t # End: # # vi: set shiftwidth=8 tabstop=8 noexpandtab: # :indentSize=8:tabSize=8:noTabs=false: #
wireshark/ui/qt/CMakeListsCustom.txt.example
# CMakeListsCustom.txt # # Wireshark - Network traffic analyzer # By Gerald Combs <[email protected]> # Copyright 1998 Gerald Combs # # SPDX-License-Identifier: GPL-2.0-or-later # # You can add custom GUI files here by replacing the commented out file foo with your file. #Add GUI source files here set(WIRESHARK_CUSTOM_QT_HEADERS # foo.h ) set(WIRESHARK_CUSTOM_QT_SRCS # foo.c ) #Add your tap source files here: set(WIRESHARK_CUSTOM_TAP_SRC # tap_foo.c )
C++
wireshark/ui/qt/coloring_rules_dialog.cpp
/* coloring_rules_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "coloring_rules_dialog.h" #include <ui_coloring_rules_dialog.h> #include "ui/simple_dialog.h" #include "epan/prefs.h" #include <wsutil/utf8_entities.h> #include "wsutil/filesystem.h" #include "epan/dfilter/dfilter.h" #include "main_application.h" #include "ui/qt/utils/qt_ui_utils.h" #include "ui/qt/widgets/copy_from_profile_button.h" #include "ui/qt/widgets/wireshark_file_dialog.h" #include <functional> #include <QColorDialog> #include <QMessageBox> #include <QPushButton> #include <QUrl> /* * @file Coloring Rules dialog * * Coloring rule editor for the current profile. */ // To do: // - Make the filter column narrower? It's easy to run into Qt's annoying // habit of horizontally scrolling QTreeWidgets here. ColoringRulesDialog::ColoringRulesDialog(QWidget *parent, QString add_filter) : GeometryStateDialog(parent), ui(new Ui::ColoringRulesDialog), colorRuleModel_(palette().color(QPalette::Text), palette().color(QPalette::Base), this), colorRuleDelegate_(this) { ui->setupUi(this); if (parent) loadGeometry(parent->width() * 2 / 3, parent->height() * 4 / 5); setWindowTitle(mainApp->windowTitleString(tr("Coloring Rules %1").arg(get_profile_name()))); ui->coloringRulesTreeView->setModel(&colorRuleModel_); ui->coloringRulesTreeView->setItemDelegate(&colorRuleDelegate_); ui->coloringRulesTreeView->viewport()->setAcceptDrops(true); for (int i = 0; i < colorRuleModel_.columnCount(); i++) { ui->coloringRulesTreeView->resizeColumnToContents(i); } ui->newToolButton->setStockIcon("list-add"); ui->deleteToolButton->setStockIcon("list-remove"); ui->copyToolButton->setStockIcon("list-copy"); ui->clearToolButton->setStockIcon("list-clear"); #ifdef Q_OS_MAC ui->newToolButton->setAttribute(Qt::WA_MacSmallSize, true); ui->deleteToolButton->setAttribute(Qt::WA_MacSmallSize, true); ui->copyToolButton->setAttribute(Qt::WA_MacSmallSize, true); ui->clearToolButton->setAttribute(Qt::WA_MacSmallSize, true); ui->pathLabel->setAttribute(Qt::WA_MacSmallSize, true); #endif connect(ui->coloringRulesTreeView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), this, SLOT(colorRuleSelectionChanged(const QItemSelection &, const QItemSelection &))); connect(&colorRuleDelegate_, SIGNAL(invalidField(const QModelIndex&, const QString&)), this, SLOT(invalidField(const QModelIndex&, const QString&))); connect(&colorRuleDelegate_, SIGNAL(validField(const QModelIndex&)), this, SLOT(validField(const QModelIndex&))); connect(ui->coloringRulesTreeView, &QTreeView::clicked, this, &ColoringRulesDialog::treeItemClicked); connect(&colorRuleModel_, SIGNAL(rowsInserted(const QModelIndex &, int, int)), this, SLOT(rowCountChanged())); connect(&colorRuleModel_, SIGNAL(rowsRemoved(const QModelIndex &, int, int)), this, SLOT(rowCountChanged())); rowCountChanged(); import_button_ = ui->buttonBox->addButton(tr("Import…"), QDialogButtonBox::ApplyRole); import_button_->setToolTip(tr("Select a file and add its filters to the end of the list.")); export_button_ = ui->buttonBox->addButton(tr("Export…"), QDialogButtonBox::ApplyRole); export_button_->setToolTip(tr("Save filters in a file.")); CopyFromProfileButton * copy_button = new CopyFromProfileButton(this, COLORFILTERS_FILE_NAME, tr("Copy coloring rules from another profile.")); ui->buttonBox->addButton(copy_button, QDialogButtonBox::ActionRole); connect(copy_button, &CopyFromProfileButton::copyProfile, this, &ColoringRulesDialog::copyFromProfile); QString abs_path = gchar_free_to_qstring(get_persconffile_path(COLORFILTERS_FILE_NAME, TRUE)); if (file_exists(abs_path.toUtf8().constData())) { ui->pathLabel->setText(abs_path); ui->pathLabel->setUrl(QUrl::fromLocalFile(abs_path).toString()); ui->pathLabel->setToolTip(tr("Open ") + COLORFILTERS_FILE_NAME); ui->pathLabel->setEnabled(true); } if (!add_filter.isEmpty()) { colorRuleModel_.addColor(false, add_filter, palette().color(QPalette::Text), palette().color(QPalette::Base)); //setup the buttons appropriately ui->coloringRulesTreeView->setCurrentIndex(colorRuleModel_.index(0, 0)); //set edit on display filter ui->coloringRulesTreeView->edit(colorRuleModel_.index(0, 1)); }else { ui->coloringRulesTreeView->setCurrentIndex(QModelIndex()); } updateHint(); } ColoringRulesDialog::~ColoringRulesDialog() { delete ui; } void ColoringRulesDialog::copyFromProfile(QString filename) { QString err; if (!colorRuleModel_.importColors(filename, err)) { simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err.toUtf8().constData()); } for (int i = 0; i < colorRuleModel_.columnCount(); i++) { ui->coloringRulesTreeView->resizeColumnToContents(i); } } void ColoringRulesDialog::showEvent(QShowEvent *) { ui->fGPushButton->setFixedHeight(ui->copyToolButton->geometry().height()); ui->bGPushButton->setFixedHeight(ui->copyToolButton->geometry().height()); #ifndef Q_OS_MAC ui->displayFilterPushButton->setFixedHeight(ui->copyToolButton->geometry().height()); #endif } void ColoringRulesDialog::rowCountChanged() { ui->clearToolButton->setEnabled(colorRuleModel_.rowCount() > 0); } bool ColoringRulesDialog::isValidFilter(QString filter, QString * error) { dfilter_t *dfp = NULL; df_error_t *df_err = NULL; if (dfilter_compile(filter.toUtf8().constData(), &dfp, &df_err)) { dfilter_free(dfp); return true; } if (df_err) { error->append(df_err->msg); df_error_free(&df_err); } return false; } void ColoringRulesDialog::treeItemClicked(const QModelIndex &index) { QModelIndex idx = ui->coloringRulesTreeView->model()->index(index.row(), ColoringRulesModel::colFilter); QString filter = idx.data(Qt::DisplayRole).toString(); QString err; if (! isValidFilter(filter, &err) && index.data(Qt::CheckStateRole).toInt() == Qt::Checked) { errors_.insert(index, err); updateHint(index); } else { QList<QModelIndex> keys = errors_.keys(); bool update = false; foreach (QModelIndex key, keys) { if (key.row() == index.row()) { errors_.remove(key); update = true; } } if (update) updateHint(index); } } void ColoringRulesDialog::invalidField(const QModelIndex &index, const QString& errMessage) { errors_.insert(index, errMessage); updateHint(index); } void ColoringRulesDialog::validField(const QModelIndex &index) { QList<QModelIndex> keys = errors_.keys(); bool update = false; foreach (QModelIndex key, keys) { if (key.row() == index.row()) { errors_.remove(key); update = true; } } if (update) updateHint(index); } void ColoringRulesDialog::updateHint(QModelIndex idx) { QString hint = "<small><i>"; QString error_text; bool enable_save = true; if (errors_.count() > 0) { //take the list of QModelIndexes and sort them so first color rule error is displayed //This isn't the most efficent algorithm, but the list shouldn't be large to matter QList<QModelIndex> keys = errors_.keys(); //list is not guaranteed to be sorted, so force it std::sort(keys.begin(), keys.end()); const QModelIndex& error_key = keys[0]; error_text = QString("%1: %2") .arg(colorRuleModel_.data(colorRuleModel_.index(error_key.row(), ColoringRulesModel::colName), Qt::DisplayRole).toString()) .arg(errors_[error_key]); } if (error_text.isEmpty()) { hint += tr("Double click to edit. Drag to move. Rules are processed in order until a match is found."); } else { hint += error_text; if (idx.isValid()) { QModelIndex fiIdx = ui->coloringRulesTreeView->model()->index(idx.row(), ColoringRulesModel::colName); if (fiIdx.data(Qt::CheckStateRole).toInt() == Qt::Checked) enable_save = false; } else enable_save = false; } hint += "</i></small>"; ui->hintLabel->setText(hint); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(enable_save); } void ColoringRulesDialog::setColorButtons(QModelIndex &index) { QString color_button_ss = "QPushButton {" " border: 1px solid palette(Dark);" " padding-left: %1px;" " padding-right: %1px;" " color: %2;" " background-color: %3;" "}"; int one_em = fontMetrics().height(); QVariant fg = colorRuleModel_.data(index, Qt::ForegroundRole); QVariant bg = colorRuleModel_.data(index, Qt::BackgroundRole); if (fg.isNull() || bg.isNull()) { //should never happen ui->fGPushButton->setVisible(false); ui->bGPushButton->setVisible(false); } else { QString fg_color = fg.toString(); QString bg_color = bg.toString(); ui->fGPushButton->setStyleSheet(color_button_ss.arg(one_em).arg(bg_color).arg(fg_color)); ui->bGPushButton->setStyleSheet(color_button_ss.arg(one_em).arg(fg_color).arg(bg_color)); } } void ColoringRulesDialog::colorRuleSelectionChanged(const QItemSelection&, const QItemSelection&) { QModelIndexList selectedList = ui->coloringRulesTreeView->selectionModel()->selectedIndexes(); //determine the number of unique rows QHash<int, QModelIndex> selectedRows; foreach (const QModelIndex &index, selectedList) { selectedRows.insert(index.row(), index); } qsizetype num_selected = selectedRows.count(); if (num_selected == 1) { setColorButtons(selectedList[0]); } ui->copyToolButton->setEnabled(num_selected == 1); ui->deleteToolButton->setEnabled(num_selected > 0); ui->fGPushButton->setVisible(num_selected == 1); ui->bGPushButton->setVisible(num_selected == 1); ui->displayFilterPushButton->setVisible(num_selected == 1); } void ColoringRulesDialog::changeColor(bool foreground) { QModelIndex current = ui->coloringRulesTreeView->currentIndex(); if (!current.isValid()) return; QColorDialog *color_dlg = new QColorDialog(); color_dlg->setCurrentColor(colorRuleModel_.data(current, foreground ? Qt::ForegroundRole : Qt::BackgroundRole).toString()); connect(color_dlg, &QColorDialog::colorSelected, std::bind(&ColoringRulesDialog::colorChanged, this, foreground, std::placeholders::_1)); color_dlg->setWindowModality(Qt::ApplicationModal); color_dlg->setAttribute(Qt::WA_DeleteOnClose); color_dlg->show(); } void ColoringRulesDialog::colorChanged(bool foreground, const QColor &cc) { QModelIndex current = ui->coloringRulesTreeView->currentIndex(); if (!current.isValid()) return; colorRuleModel_.setData(current, cc, foreground ? Qt::ForegroundRole : Qt::BackgroundRole); setColorButtons(current); } void ColoringRulesDialog::on_fGPushButton_clicked() { changeColor(); } void ColoringRulesDialog::on_bGPushButton_clicked() { changeColor(false); } void ColoringRulesDialog::on_displayFilterPushButton_clicked() { QModelIndex current = ui->coloringRulesTreeView->currentIndex(); if (!current.isValid()) return; QString filter = colorRuleModel_.data(colorRuleModel_.index(current.row(), ColoringRulesModel::colFilter), Qt::DisplayRole).toString(); emit filterAction(filter, FilterAction::ActionApply, FilterAction::ActionTypePlain); } void ColoringRulesDialog::addRule(bool copy_from_current) { const QModelIndex &current = ui->coloringRulesTreeView->currentIndex(); if (copy_from_current && !current.isValid()) return; //always add rules at the top of the list if (copy_from_current) { colorRuleModel_.copyRow(colorRuleModel_.index(0, 0).row(), current.row()); } else { if (!colorRuleModel_.insertRows(0, 1)) { return; } } //set edit on display filter ui->coloringRulesTreeView->edit(colorRuleModel_.index(0, 1)); } void ColoringRulesDialog::on_newToolButton_clicked() { addRule(); } void ColoringRulesDialog::on_deleteToolButton_clicked() { QModelIndexList selectedList = ui->coloringRulesTreeView->selectionModel()->selectedIndexes(); qsizetype num_selected = selectedList.count() / colorRuleModel_.columnCount(); if (num_selected > 0) { //list is not guaranteed to be sorted, so force it std::sort(selectedList.begin(), selectedList.end()); //walk the list from the back because deleting a value in //the middle will leave the selectedList out of sync and //delete the wrong elements for (int i = static_cast<int>(selectedList.count()) - 1; i >= 0; i--) { QModelIndex deleteIndex = selectedList[i]; //selectedList includes all cells, use first column as key to remove row if (deleteIndex.isValid() && (deleteIndex.column() == 0)) { colorRuleModel_.removeRows(deleteIndex.row(), 1); } } } } void ColoringRulesDialog::on_copyToolButton_clicked() { addRule(true); } void ColoringRulesDialog::on_clearToolButton_clicked() { colorRuleModel_.removeRows(0, colorRuleModel_.rowCount()); } void ColoringRulesDialog::on_buttonBox_clicked(QAbstractButton *button) { QString err; if (button == import_button_) { QString file_name = WiresharkFileDialog::getOpenFileName(this, mainApp->windowTitleString(tr("Import Coloring Rules")), mainApp->lastOpenDir().path()); if (!file_name.isEmpty()) { if (!colorRuleModel_.importColors(file_name, err)) { simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err.toUtf8().constData()); } } } else if (button == export_button_) { int num_items = static_cast<int>(ui->coloringRulesTreeView->selectionModel()->selectedIndexes().count()) / colorRuleModel_.columnCount(); if (num_items < 1) { num_items = colorRuleModel_.rowCount(); } if (num_items < 1) return; QString caption = mainApp->windowTitleString(tr("Export %1 Coloring Rules").arg(num_items)); QString file_name = WiresharkFileDialog::getSaveFileName(this, caption, mainApp->lastOpenDir().path()); if (!file_name.isEmpty()) { if (!colorRuleModel_.exportColors(file_name, err)) { simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err.toUtf8().constData()); } } } } void ColoringRulesDialog::on_buttonBox_accepted() { QString err; int ret = QDialog::Accepted; if (!colorRuleModel_.writeColors(err)) { simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err.toUtf8().constData()); ret = QDialog::Rejected; } done(ret); } void ColoringRulesDialog::on_buttonBox_helpRequested() { mainApp->helpTopicAction(HELP_COLORING_RULES_DIALOG); }
C/C++
wireshark/ui/qt/coloring_rules_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef COLORING_RULES_DIALOG_H #define COLORING_RULES_DIALOG_H #include "geometry_state_dialog.h" #include "filter_action.h" #include <ui/qt/models/coloring_rules_model.h> #include <ui/qt/models/coloring_rules_delegate.h> #include <QMap> class QAbstractButton; namespace Ui { class ColoringRulesDialog; } class ColoringRulesDialog : public GeometryStateDialog { Q_OBJECT public: explicit ColoringRulesDialog(QWidget *parent = 0, QString add_filter = QString()); ~ColoringRulesDialog(); signals: void filterAction(QString filter, FilterAction::Action action, FilterAction::ActionType type); protected: void showEvent(QShowEvent *); private slots: void copyFromProfile(QString fileName); void colorRuleSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected); void colorChanged(bool foreground, const QColor &cc); void on_fGPushButton_clicked(); void on_bGPushButton_clicked(); void on_displayFilterPushButton_clicked(); void on_newToolButton_clicked(); void on_deleteToolButton_clicked(); void on_copyToolButton_clicked(); void on_clearToolButton_clicked(); void on_buttonBox_clicked(QAbstractButton *button); void on_buttonBox_accepted(); void on_buttonBox_helpRequested(); void rowCountChanged(); void invalidField(const QModelIndex &index, const QString& errMessage); void validField(const QModelIndex &index); void treeItemClicked(const QModelIndex &index); private: Ui::ColoringRulesDialog *ui; QPushButton *import_button_; QPushButton *export_button_; ColoringRulesModel colorRuleModel_; ColoringRulesDelegate colorRuleDelegate_; QMap<QModelIndex, QString> errors_; void checkUnknownColorfilters(); void setColorButtons(QModelIndex &index); void updateHint(QModelIndex idx = QModelIndex()); void addRule(bool copy_from_current = false); void changeColor(bool foreground = true); bool isValidFilter(QString filter, QString *error); }; #endif // COLORING_RULES_DIALOG_H
User Interface
wireshark/ui/qt/coloring_rules_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>ColoringRulesDialog</class> <widget class="QDialog" name="ColoringRulesDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>650</width> <height>480</height> </rect> </property> <property name="windowTitle"> <string>Dialog</string> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="TabnavTreeView" name="coloringRulesTreeView"> <property name="dragEnabled"> <bool>true</bool> </property> <property name="dragDropMode"> <enum>QAbstractItemView::InternalMove</enum> </property> <property name="selectionMode"> <enum>QAbstractItemView::ExtendedSelection</enum> </property> <property name="textElideMode"> <enum>Qt::ElideMiddle</enum> </property> <property name="rootIsDecorated"> <bool>false</bool> </property> <property name="uniformRowHeights"> <bool>true</bool> </property> <property name="itemsExpandable"> <bool>false</bool> </property> <property name="expandsOnDoubleClick"> <bool>false</bool> </property> <property name="DropIndicatorShown" stdset="0"> <bool>true</bool> </property> </widget> </item> <item> <widget class="QLabel" name="hintLabel"> <property name="text"> <string>&lt;small&gt;&lt;i&gt;A hint.&lt;/i&gt;&lt;/small&gt;</string> </property> <property name="wordWrap"> <bool>true</bool> </property> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0,0,0,0,0,0,0,1"> <item> <widget class="StockIconToolButton" name="newToolButton"> <property name="toolTip"> <string>Add a new coloring rule.</string> </property> <property name="text"> <string/> </property> </widget> </item> <item> <widget class="StockIconToolButton" name="deleteToolButton"> <property name="enabled"> <bool>false</bool> </property> <property name="toolTip"> <string>Delete this coloring rule.</string> </property> <property name="text"> <string/> </property> </widget> </item> <item> <widget class="StockIconToolButton" name="copyToolButton"> <property name="enabled"> <bool>false</bool> </property> <property name="toolTip"> <string>Duplicate this coloring rule.</string> </property> </widget> </item> <item> <widget class="StockIconToolButton" name="clearToolButton"> <property name="enabled"> <bool>false</bool> </property> <property name="toolTip"> <string>Clear all coloring rules.</string> </property> </widget> </item> <item> <widget class="QPushButton" name="fGPushButton"> <property name="visible"> <bool>false</bool> </property> <property name="toolTip"> <string>Set the foreground color for this rule.</string> </property> <property name="styleSheet"> <string notr="true">QPushButton { border: 1px solid palette(Dark); }</string> </property> <property name="text"> <string>Foreground</string> </property> <property name="autoDefault"> <bool>false</bool> </property> <property name="flat"> <bool>true</bool> </property> </widget> </item> <item> <widget class="QPushButton" name="bGPushButton"> <property name="visible"> <bool>false</bool> </property> <property name="toolTip"> <string>Set the background color for this rule.</string> </property> <property name="styleSheet"> <string notr="true">QPushButton { border: 1px solid palette(Dark); }</string> </property> <property name="text"> <string>Background</string> </property> <property name="autoDefault"> <bool>false</bool> </property> <property name="flat"> <bool>true</bool> </property> </widget> </item> <item> <widget class="QPushButton" name="displayFilterPushButton"> <property name="visible"> <bool>false</bool> </property> <property name="toolTip"> <string>Set the display filter using this rule.</string> </property> <property name="text"> <string>Apply as filter</string> </property> <property name="autoDefault"> <bool>false</bool> </property> </widget> </item> <item> <spacer name="horizontalSpacer"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> <item> <widget class="ElidedLabel" name="pathLabel"> <property name="sizePolicy"> <sizepolicy hsizetype="Expanding" vsizetype="Preferred"> <horstretch>1</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="text"> <string/> </property> <property name="alignment"> <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> </property> <property name="openExternalLinks"> <bool>true</bool> </property> </widget> </item> </layout> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Cancel|QDialogButtonBox::Help|QDialogButtonBox::Ok</set> </property> </widget> </item> </layout> </widget> <customwidgets> <customwidget> <class>ElidedLabel</class> <extends>QLabel</extends> <header>widgets/elided_label.h</header> </customwidget> <customwidget> <class>TabnavTreeView</class> <extends>QTreeView</extends> <header>widgets/tabnav_tree_view.h</header> </customwidget> <customwidget> <class>StockIconToolButton</class> <extends>QToolButton</extends> <header>widgets/stock_icon_tool_button.h</header> </customwidget> </customwidgets> <resources/> <connections> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>ColoringRulesDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>316</x> <y>260</y> </hint> <hint type="destinationlabel"> <x>286</x> <y>274</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/column_editor_frame.cpp
/* column_editor_frame.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include <glib.h> #include <epan/column.h> #include <epan/prefs.h> #include <ui/recent.h> #include <ui/preference_utils.h> #include "main_application.h" #include "column_editor_frame.h" #include <ui_column_editor_frame.h> #include <QPushButton> #include <QComboBox> #include <QKeyEvent> ColumnEditorFrame::ColumnEditorFrame(QWidget *parent) : AccordionFrame(parent), ui(new Ui::ColumnEditorFrame), cur_column_(-1) { ui->setupUi(this); #ifdef Q_OS_MAC foreach (QWidget *w, findChildren<QWidget *>()) { w->setAttribute(Qt::WA_MacSmallSize, true); } #endif for (int i = 0; i < NUM_COL_FMTS; i++) { ui->typeComboBox->addItem(col_format_desc(i), QVariant(i)); } connect(ui->fieldsNameLineEdit, &FieldFilterEdit::textChanged, ui->fieldsNameLineEdit, &FieldFilterEdit::checkCustomColumn); connect(ui->fieldsNameLineEdit, &FieldFilterEdit::textChanged, this, &ColumnEditorFrame::checkCanResolve); } ColumnEditorFrame::~ColumnEditorFrame() { delete ui; } bool ColumnEditorFrame::syntaxIsValid(void) { // Fields must be a valid filter. // Occurrence must be empty or valid. return ((ui->fieldsNameLineEdit->syntaxState() == SyntaxLineEdit::Valid) && (ui->occurrenceLineEdit->syntaxState() != SyntaxLineEdit::Invalid)); } void ColumnEditorFrame::setFields(int index) { bool ok = true; if (index == COL_CUSTOM) { ui->fieldsNameLineEdit->setText(saved_fields_); ui->fieldsNameLineEdit->checkCustomColumn(saved_fields_); ui->occurrenceLineEdit->setText(saved_occurrence_); ui->occurrenceLineEdit->checkInteger(saved_occurrence_); ok = syntaxIsValid(); } else { ui->fieldsNameLineEdit->clear(); ui->fieldsNameLineEdit->setSyntaxState(SyntaxLineEdit::Empty); ui->occurrenceLineEdit->clear(); ui->occurrenceLineEdit->setSyntaxState(SyntaxLineEdit::Empty); ui->resolvedCheckBox->setEnabled(false); } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ok); } void ColumnEditorFrame::editColumn(int column) { cur_column_ = column; ui->titleLineEdit->setText(get_column_title(column)); saved_fields_ = get_column_custom_fields(column); saved_occurrence_ = QString::number(get_column_custom_occurrence(column)); ui->typeComboBox->setCurrentIndex(get_column_format(column)); ui->resolvedCheckBox->setChecked(get_column_resolved(column)); setFields(ui->typeComboBox->currentIndex()); } void ColumnEditorFrame::showEvent(QShowEvent *event) { ui->titleLineEdit->setFocus(); ui->titleLineEdit->selectAll(); AccordionFrame::showEvent(event); } void ColumnEditorFrame::on_typeComboBox_activated(int index) { setFields(index); } void ColumnEditorFrame::on_fieldsNameLineEdit_textEdited(const QString &fields) { ui->fieldsNameLineEdit->checkCustomColumn(fields); if (ui->typeComboBox->currentIndex() != COL_CUSTOM) { ui->typeComboBox->setCurrentIndex(COL_CUSTOM); ui->occurrenceLineEdit->setText(saved_occurrence_); } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(syntaxIsValid()); saved_fields_ = fields; } void ColumnEditorFrame::on_occurrenceLineEdit_textEdited(const QString &occurrence) { ui->occurrenceLineEdit->checkInteger(occurrence); if (ui->typeComboBox->currentIndex() != COL_CUSTOM) { ui->typeComboBox->setCurrentIndex(COL_CUSTOM); ui->fieldsNameLineEdit->setText(saved_fields_); } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(syntaxIsValid()); saved_occurrence_ = occurrence; } void ColumnEditorFrame::on_buttonBox_rejected() { cur_column_ = -1; animatedHide(); } void ColumnEditorFrame::on_buttonBox_accepted() { QByteArray col_str; if (cur_column_ >= 0) { col_str = ui->titleLineEdit->text().toUtf8(); set_column_title(cur_column_, col_str.constData()); set_column_format(cur_column_, ui->typeComboBox->currentIndex()); if (ui->typeComboBox->currentIndex() == COL_CUSTOM) { gint width = recent_get_column_width(cur_column_); gchar xalign = recent_get_column_xalign(cur_column_); col_str = ui->fieldsNameLineEdit->text().toUtf8(); set_column_custom_fields(cur_column_, col_str.constData()); recent_set_column_width(cur_column_, width); recent_set_column_xalign(cur_column_, xalign); if (!ui->occurrenceLineEdit->text().isEmpty()) { set_column_custom_occurrence(cur_column_, ui->occurrenceLineEdit->text().toInt()); } if (ui->resolvedCheckBox->isEnabled()) { set_column_resolved(cur_column_, ui->resolvedCheckBox->isChecked()); } } prefs_main_write(); emit columnEdited(); } on_buttonBox_rejected(); } void ColumnEditorFrame::keyPressEvent(QKeyEvent *event) { if (event->modifiers() == Qt::NoModifier) { if (event->key() == Qt::Key_Escape) { on_buttonBox_rejected(); } else if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) { if (ui->buttonBox->button(QDialogButtonBox::Ok)->isEnabled()) { on_buttonBox_accepted(); } else if (ui->fieldsNameLineEdit->syntaxState() == SyntaxLineEdit::Empty) { mainApp->pushStatus(MainApplication::FilterSyntax, tr("Missing fields.")); } else if (ui->fieldsNameLineEdit->syntaxState() != SyntaxLineEdit::Valid) { mainApp->pushStatus(MainApplication::FilterSyntax, tr("Invalid fields.")); } else if (ui->occurrenceLineEdit->syntaxState() == SyntaxLineEdit::Invalid) { mainApp->pushStatus(MainApplication::FilterSyntax, tr("Invalid occurrence value.")); } } } AccordionFrame::keyPressEvent(event); } void ColumnEditorFrame::checkCanResolve() { if (ui->fieldsNameLineEdit->syntaxState() == SyntaxLineEdit::Valid && column_prefs_custom_resolve(ui->fieldsNameLineEdit->text().toUtf8().constData())) { ui->resolvedCheckBox->setEnabled(true); } else { ui->resolvedCheckBox->setEnabled(false); ui->resolvedCheckBox->setChecked(false); } }
C/C++
wireshark/ui/qt/column_editor_frame.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef COLUMN_EDITOR_FRAME_H #define COLUMN_EDITOR_FRAME_H #include "accordion_frame.h" namespace Ui { class ColumnEditorFrame; } class ColumnEditorFrame : public AccordionFrame { Q_OBJECT public: explicit ColumnEditorFrame(QWidget *parent = nullptr); ~ColumnEditorFrame(); void editColumn(int column); signals: void columnEdited(); protected: virtual void showEvent(QShowEvent *event); virtual void keyPressEvent(QKeyEvent *event); private slots: void on_typeComboBox_activated(int index); void on_fieldsNameLineEdit_textEdited(const QString &fields); void on_occurrenceLineEdit_textEdited(const QString &occurrence); void on_buttonBox_rejected(); void on_buttonBox_accepted(); void checkCanResolve(void); private: bool syntaxIsValid(void); Ui::ColumnEditorFrame *ui; int cur_column_; QString saved_fields_; QString saved_occurrence_; void setFields(int index); }; #endif // COLUMN_EDITOR_FRAME_H
User Interface
wireshark/ui/qt/column_editor_frame.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>ColumnEditorFrame</class> <widget class="AccordionFrame" name="ColumnEditorFrame"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>1018</width> <height>34</height> </rect> </property> <property name="windowTitle"> <string>Frame</string> </property> <property name="frameShape"> <enum>QFrame::NoFrame</enum> </property> <property name="frameShadow"> <enum>QFrame::Plain</enum> </property> <layout class="QHBoxLayout" name="horizontalLayout" stretch="0,1,0,0,0,0,0,2,0,0,0,0,0"> <property name="topMargin"> <number>0</number> </property> <property name="bottomMargin"> <number>0</number> </property> <item> <widget class="QLabel" name="label"> <property name="text"> <string>Title:</string> </property> </widget> </item> <item> <widget class="QLineEdit" name="titleLineEdit"/> </item> <item> <spacer name="horizontalSpacer_2"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>20</width> <height>5</height> </size> </property> </spacer> </item> <item> <widget class="QLabel" name="label_2"> <property name="text"> <string>Type:</string> </property> </widget> </item> <item> <widget class="QComboBox" name="typeComboBox"/> </item> <item> <spacer name="horizontalSpacer_3"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>20</width> <height>5</height> </size> </property> </spacer> </item> <item> <widget class="QLabel" name="label_3"> <property name="text"> <string>Fields:</string> </property> </widget> </item> <item> <widget class="FieldFilterEdit" name="fieldsNameLineEdit"/> </item> <item> <spacer name="horizontalSpacer_4"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>20</width> <height>5</height> </size> </property> </spacer> </item> <item> <widget class="QLabel" name="label_4"> <property name="text"> <string>Occurrence:</string> </property> </widget> </item> <item> <widget class="SyntaxLineEdit" name="occurrenceLineEdit"/> </item> <item> <widget class="QCheckBox" name="resolvedCheckBox"> <property name="text"> <string>Resolve Names:</string> </property> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;p&gt;Show human-readable strings instead of raw values for fields. Only applicable to custom columns with fields that have value strings.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="layoutDirection"> <enum>Qt::RightToLeft</enum> </property> </widget> </item> <item> <spacer name="horizontalSpacer"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>20</width> <height>5</height> </size> </property> </spacer> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="maximumSize"> <size> <width>16777215</width> <height>27</height> </size> </property> <property name="standardButtons"> <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set> </property> </widget> </item> </layout> </widget> <customwidgets> <customwidget> <class>AccordionFrame</class> <extends>QFrame</extends> <header>accordion_frame.h</header> <container>1</container> </customwidget> <customwidget> <class>FieldFilterEdit</class> <extends>QLineEdit</extends> <header>widgets/field_filter_edit.h</header> </customwidget> <customwidget> <class>SyntaxLineEdit</class> <extends>QLineEdit</extends> <header>widgets/syntax_line_edit.h</header> </customwidget> </customwidgets> <resources/> <connections/> </ui>
C++
wireshark/ui/qt/column_preferences_frame.cpp
/* column_preferences_frame.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include <glib.h> #include <epan/column.h> #include <epan/prefs.h> #include <epan/proto.h> #include <ui/preference_utils.h> #include <ui/qt/utils/qt_ui_utils.h> #include "column_preferences_frame.h" #include <ui_column_preferences_frame.h> #include <ui/qt/widgets/syntax_line_edit.h> #include <ui/qt/widgets/field_filter_edit.h> #include <ui/qt/models/column_list_model.h> #include "main_application.h" #include <QComboBox> #include <QTreeWidgetItemIterator> #include <QLineEdit> #include <QKeyEvent> #include <QMenu> #include <QAction> ColumnPreferencesFrame::ColumnPreferencesFrame(QWidget *parent) : QFrame(parent), ui(new Ui::ColumnPreferencesFrame) { ui->setupUi(this); model_ = new ColumnListModel(); proxyModel_ = new ColumnProxyModel(); proxyModel_->setSourceModel(model_); int one_em = ui->columnTreeView->fontMetrics().height(); ui->columnTreeView->setColumnWidth(ColumnListModel::COL_FIELDS, one_em * 10); ui->columnTreeView->setColumnWidth(ColumnListModel::COL_OCCURRENCE, one_em * 5); ui->columnTreeView->setMinimumWidth(one_em * 20); ui->columnTreeView->setMinimumHeight(one_em * 12); ui->columnTreeView->setSelectionMode(QAbstractItemView::SingleSelection); ui->columnTreeView->setDragEnabled(true); ui->columnTreeView->viewport()->setAcceptDrops(true); ui->columnTreeView->setDropIndicatorShown(true); ui->columnTreeView->setDragDropMode(QAbstractItemView::InternalMove); ui->columnTreeView->setContextMenuPolicy(Qt::CustomContextMenu); ui->newToolButton->setStockIcon("list-add"); ui->deleteToolButton->setStockIcon("list-remove"); ui->columnTreeView->setModel(proxyModel_); delegate_ = new ColumnTypeDelegate(); ui->columnTreeView->setItemDelegate(delegate_); ui->columnTreeView->setSortingEnabled(false); ui->columnTreeView->resizeColumnToContents(ColumnListModel::COL_DISPLAYED); ui->columnTreeView->resizeColumnToContents(ColumnListModel::COL_TITLE); ui->columnTreeView->resizeColumnToContents(ColumnListModel::COL_TYPE); ui->columnTreeView->resizeColumnToContents(ColumnListModel::COL_OCCURRENCE); ui->columnTreeView->resizeColumnToContents(ColumnListModel::COL_RESOLVED); connect(ui->columnTreeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ColumnPreferencesFrame::selectionChanged); } ColumnPreferencesFrame::~ColumnPreferencesFrame() { delete delegate_; delete proxyModel_; delete model_; delete ui; } void ColumnPreferencesFrame::unstash() { model_->saveColumns(); mainApp->emitAppSignal(MainApplication::ColumnsChanged); } void ColumnPreferencesFrame::on_newToolButton_clicked() { model_->addEntry(); } void ColumnPreferencesFrame::on_deleteToolButton_clicked() { if (ui->columnTreeView->selectionModel()->selectedIndexes().count() > 0) { QModelIndex selIndex = ui->columnTreeView->selectionModel()->selectedIndexes().at(0); model_->deleteEntry(proxyModel_->mapToSource(selIndex).row()); } } void ColumnPreferencesFrame::selectionChanged(const QItemSelection &/*selected*/, const QItemSelection &/*deselected*/) { ui->deleteToolButton->setEnabled(ui->columnTreeView->selectionModel()->selectedIndexes().count() > 0); } void ColumnPreferencesFrame::on_chkShowDisplayedOnly_stateChanged(int /*state*/) { proxyModel_->setShowDisplayedOnly(ui->chkShowDisplayedOnly->checkState() == Qt::Checked ? true : false); } void ColumnPreferencesFrame::on_columnTreeView_customContextMenuRequested(const QPoint &pos) { QMenu * contextMenu = new QMenu(this); contextMenu->setAttribute(Qt::WA_DeleteOnClose); QAction * action = contextMenu->addAction(tr("Reset all changes")); connect(action, &QAction::triggered, this, &ColumnPreferencesFrame::resetAction); contextMenu->popup(mapToGlobal(pos)); } void ColumnPreferencesFrame::resetAction(bool /*checked*/) { model_->reset(); }
C/C++
wireshark/ui/qt/column_preferences_frame.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef COLUMN_PREFERENCES_FRAME_H #define COLUMN_PREFERENCES_FRAME_H #include <ui/qt/models/column_list_model.h> #include <QFrame> #include <QItemSelection> namespace Ui { class ColumnPreferencesFrame; } class ColumnPreferencesFrame : public QFrame { Q_OBJECT public: explicit ColumnPreferencesFrame(QWidget *parent = Q_NULLPTR); ~ColumnPreferencesFrame(); void unstash(); private: Ui::ColumnPreferencesFrame *ui; ColumnListModel * model_; ColumnProxyModel * proxyModel_; ColumnTypeDelegate * delegate_; private slots: void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); void on_newToolButton_clicked(); void on_deleteToolButton_clicked(); void on_chkShowDisplayedOnly_stateChanged(int); void on_columnTreeView_customContextMenuRequested(const QPoint &pos); void resetAction(bool checked = false); }; #endif // COLUMN_PREFERENCES_FRAME_H
User Interface
wireshark/ui/qt/column_preferences_frame.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>ColumnPreferencesFrame</class> <widget class="QFrame" name="ColumnPreferencesFrame"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>550</width> <height>456</height> </rect> </property> <property name="sizePolicy"> <sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="windowTitle"> <string>Frame</string> </property> <property name="lineWidth"> <number>0</number> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QTreeView" name="columnTreeView"> <property name="dragEnabled"> <bool>true</bool> </property> <property name="dragDropMode"> <enum>QAbstractItemView::InternalMove</enum> </property> <property name="rootIsDecorated"> <bool>false</bool> </property> <property name="sortingEnabled"> <bool>false</bool> </property> <attribute name="headerShowSortIndicator" stdset="0"> <bool>false</bool> </attribute> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <widget class="StockIconToolButton" name="newToolButton"> <property name="toolTip"> <string>Add a new column</string> </property> <property name="text"> <string/> </property> </widget> </item> <item> <widget class="StockIconToolButton" name="deleteToolButton"> <property name="toolTip"> <string>Delete selected column</string> </property> <property name="text"> <string/> </property> </widget> </item> <item> <widget class="QCheckBox" name="chkShowDisplayedOnly"> <property name="text"> <string>Show displayed columns only</string> </property> </widget> </item> <item> <spacer name="horizontalSpacer"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> </layout> </item> </layout> </widget> <customwidgets> <customwidget> <class>StockIconToolButton</class> <extends>QToolButton</extends> <header>widgets/stock_icon_tool_button.h</header> </customwidget> </customwidgets> <resources/> <connections/> </ui>
C++
wireshark/ui/qt/compiled_filter_output.cpp
/* compiled_filter_output.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include <ui_compiled_filter_output.h> #include "compiled_filter_output.h" #ifdef HAVE_LIBPCAP #ifdef __MINGW32__ #include <_bsd_types.h> #endif #include <pcap.h> #endif #include "capture_opts.h" #include <wiretap/wtap.h> #include "ui/capture_globals.h" #include "main_application.h" #include <QClipboard> #include <QPushButton> CompiledFilterOutput::CompiledFilterOutput(QWidget *parent, QStringList &intList, QString &compile_filter) : GeometryStateDialog(parent), intList_(intList), compile_filter_(compile_filter), ui(new Ui::CompiledFilterOutput) { ui->setupUi(this); loadGeometry(); setAttribute(Qt::WA_DeleteOnClose, true); ui->filterList->setCurrentFont(mainApp->monospaceFont()); copy_bt_ = ui->buttonBox->addButton(tr("Copy"), QDialogButtonBox::ActionRole); copy_bt_->setToolTip(tr("Copy filter text to the clipboard.")); connect(copy_bt_, &QPushButton::clicked, this, &CompiledFilterOutput::copyFilterText); QPushButton *close_bt = ui->buttonBox->button(QDialogButtonBox::Close); close_bt->setDefault(true); interface_list_ = ui->interfaceList; pcap_compile_mtx = g_new(GMutex,1); g_mutex_init(pcap_compile_mtx); #ifdef HAVE_LIBPCAP compileFilter(); #endif } CompiledFilterOutput::~CompiledFilterOutput() { // For some reason closing this dialog either lowers the Capture Options dialog // or raises the main window. Work around the problem for now by manually raising // and activating our parent (presumably the Capture Options dialog). if (parentWidget()) { parentWidget()->raise(); parentWidget()->activateWindow(); } delete ui; } #ifdef HAVE_LIBPCAP void CompiledFilterOutput::compileFilter() { struct bpf_program fcode; foreach (QString interfaces, intList_) { for (guint i = 0; i < global_capture_opts.all_ifaces->len; i++) { interface_t *device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i); if (interfaces.compare(device->display_name)) { continue; } else { pcap_t *pd = pcap_open_dead(device->active_dlt, WTAP_MAX_PACKET_SIZE_STANDARD); if (pd == NULL) break; g_mutex_lock(pcap_compile_mtx); if (pcap_compile(pd, &fcode, compile_filter_.toUtf8().data(), 1, 0) < 0) { compile_results.insert(interfaces, QString(pcap_geterr(pd))); g_mutex_unlock(pcap_compile_mtx); ui->interfaceList->addItem(new QListWidgetItem(QIcon(":expert/expert_error.png"),interfaces)); } else { GString *bpf_code_dump = g_string_new(""); struct bpf_insn *insn = fcode.bf_insns; int ii, n = fcode.bf_len; for (ii = 0; ii < n; ++insn, ++ii) { g_string_append(bpf_code_dump, bpf_image(insn, ii)); g_string_append(bpf_code_dump, "\n"); } g_mutex_unlock(pcap_compile_mtx); compile_results.insert(interfaces, QString(bpf_code_dump->str)); g_string_free(bpf_code_dump, TRUE); ui->interfaceList->addItem(new QListWidgetItem(interfaces)); } break; } } } } #endif void CompiledFilterOutput::on_interfaceList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *) { QString interface = current->text(); QHash<QString, QString>::const_iterator iter = compile_results.find(interface); ui->filterList->clear(); ui->filterList->setPlainText(iter.value()); } void CompiledFilterOutput::copyFilterText() { mainApp->clipboard()->setText(ui->filterList->toPlainText()); }
C/C++
wireshark/ui/qt/compiled_filter_output.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef COMPILEDFILTEROUTPUT_H #define COMPILEDFILTEROUTPUT_H #include "geometry_state_dialog.h" #include <config.h> #include <QList> #include <QHash> #include <QListWidgetItem> #include <glib.h> namespace Ui { class CompiledFilterOutput; } class CompiledFilterOutput : public GeometryStateDialog { Q_OBJECT private: QStringList intList_; QString &compile_filter_; Ui::CompiledFilterOutput *ui; GMutex *pcap_compile_mtx; QHash<QString, QString> compile_results; QListWidget *interface_list_; QPushButton *copy_bt_; #ifdef HAVE_LIBPCAP void compileFilter(); #endif public: explicit CompiledFilterOutput(QWidget *parent = 0, QStringList &intList = *new QStringList(), QString &filter = *new QString()); ~CompiledFilterOutput(); private slots: void on_interfaceList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous); void copyFilterText(); }; #endif // COMPILEDFILTEROUTPUT_H
User Interface
wireshark/ui/qt/compiled_filter_output.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>CompiledFilterOutput</class> <widget class="QDialog" name="CompiledFilterOutput"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>654</width> <height>380</height> </rect> </property> <property name="windowTitle"> <string>Compiled Filter Output</string> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <layout class="QHBoxLayout" name="horizontalLayout" stretch="2,5"> <item> <widget class="QListWidget" name="interfaceList"> <property name="editTriggers"> <set>QAbstractItemView::NoEditTriggers</set> </property> </widget> </item> <item> <widget class="QTextBrowser" name="filterList"/> </item> </layout> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Close</set> </property> <property name="centerButtons"> <bool>false</bool> </property> </widget> </item> </layout> </widget> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>CompiledFilterOutput</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>248</x> <y>254</y> </hint> <hint type="destinationlabel"> <x>157</x> <y>274</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>CompiledFilterOutput</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>316</x> <y>260</y> </hint> <hint type="destinationlabel"> <x>286</x> <y>274</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/conversation_colorize_action.cpp
/* conversation_colorize_action.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "conversation_colorize_action.h" #include <config.h> #include <glib.h> #include "epan/conversation_filter.h" #include <QMenu> #include <ui/qt/utils/qt_ui_utils.h> ConversationAction::ConversationAction(QObject *parent, conversation_filter_s *conv_filter) : QAction(parent), color_number_(-1) { conv_filter_ = conv_filter; if (conv_filter_) { setText(conv_filter_->display_name); } } void ConversationAction::setPacketInfo(struct _packet_info *pinfo) { bool enable = false; if (conv_filter_ && pinfo) { enable = conv_filter_->is_filter_valid(pinfo, conv_filter_->user_data); if (enable) { filter_ba_ = gchar_free_to_qbytearray(conv_filter_->build_filter_string(pinfo, conv_filter_->user_data)); } } setEnabled(enable); // If we're the "New Coloring Rule" item, enable or disable our parent menu. QMenu *parent_submenu = qobject_cast<QMenu *>(parent()); if (color_number_ < 0 || !parent_submenu) return; parent_submenu->setEnabled(enable); } void ConversationAction::setFieldFilter(const QByteArray field_filter) { filter_ba_ = field_filter; setEnabled(!filter_ba_.isEmpty()); } bool ConversationAction::isFilterValid(struct _packet_info *pinfo) { bool valid = false; if (conv_filter_ && pinfo) { valid = conv_filter_->is_filter_valid(pinfo, conv_filter_->user_data); } return valid; }
C/C++
wireshark/ui/qt/conversation_colorize_action.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef CONVERSATIONCOLORIZEACTION_H #define CONVERSATIONCOLORIZEACTION_H #include <QAction> struct conversation_filter_s; struct _packet_info; // Actions for "Conversation Filter" and "Colorize with Filter" menu items. class ConversationAction : public QAction { Q_OBJECT public: ConversationAction(QObject *parent, struct conversation_filter_s *conv_filter = NULL); bool isFilterValid(struct _packet_info *pinfo); const QByteArray filter() { return filter_ba_; } void setColorNumber(int color_number) { color_number_ = color_number; } int colorNumber() { return color_number_; } public slots: // Exactly one of these should be connected. void setPacketInfo(struct _packet_info *pinfo); void setFieldFilter(const QByteArray field_filter); private: struct conversation_filter_s *conv_filter_; QByteArray filter_ba_; int color_number_; }; class ColorizeAction : public QAction { Q_OBJECT public: ColorizeAction(QObject *parent) : QAction(parent), color_number_(-1) {} const QByteArray filter() { return filter_ba_; } void setColorNumber(int color_number) { color_number_ = color_number; } int colorNumber() { return color_number_; } public slots: void setFieldFilter(const QByteArray field_filter) { filter_ba_ = field_filter; } private: QByteArray filter_ba_; int color_number_; }; #endif // CONVERSATIONCOLORIZEACTION_H
C++
wireshark/ui/qt/conversation_dialog.cpp
/* conversation_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "conversation_dialog.h" #include <epan/prefs.h> #include <epan/to_str.h> #include <epan/dissectors/packet-tcp.h> #include "ui/recent.h" #include "ui/tap-tcp-stream.h" #include "wsutil/str_util.h" #include <ui/qt/utils/qt_ui_utils.h> #include <ui/qt/models/timeline_delegate.h> #include <ui/qt/models/atap_data_model.h> #include <ui/qt/widgets/traffic_tab.h> #include <ui/qt/widgets/traffic_types_list.h> #include "main_application.h" #include <QCheckBox> #include <QDateTime> #include <QDialogButtonBox> #include <QPushButton> #include <QString> // To do: // - https://gitlab.com/wireshark/wireshark/-/issues/6727 // - Wide last column? // - Improper wildcard handling https://gitlab.com/wireshark/wireshark/-/issues/8010 // - TShark consolidation https://gitlab.com/wireshark/wireshark/-/issues/6310 // - Display filter entry? // - Add follow, copy & graph actions to context menu. // Bugs: // - Slow for large numbers of items. // - Name resolution doesn't do anything if its preference is disabled. // Fixed bugs: // - Friendly unit displays https://gitlab.com/wireshark/wireshark/-/issues/9231 // - Misleading bps calculation https://gitlab.com/wireshark/wireshark/-/issues/8703 // - Show Absolute time in conversation tables https://gitlab.com/wireshark/wireshark/-/issues/11618 // - The value of 'Rel start' and 'Duration' in "Conversations" no need too precise https://gitlab.com/wireshark/wireshark/-/issues/12803 static const QString table_name_ = QObject::tr("Conversation"); static ATapDataModel * createModel(int protoId, QString filter) { return new ConversationDataModel(protoId, filter); } static QAbstractItemDelegate * createDelegate(QWidget * parent) { TimelineDelegate * delegate = new TimelineDelegate(parent); delegate->setDataRole(ATapDataModel::TIMELINE_DATA); return delegate; } ConversationDialog::ConversationDialog(QWidget &parent, CaptureFile &cf) : TrafficTableDialog(parent, cf, table_name_), tcp_graph_requested_(false) { trafficList()->setProtocolInfo(table_name_, &(recent.conversation_tabs)); trafficTab()->setProtocolInfo(table_name_, trafficList(), &(recent.conversation_tabs_columns), &createModel); trafficTab()->setDelegate(&createDelegate); trafficTab()->setDelegate(&createDelegate); trafficTab()->setFilter(cf.displayFilter()); connect(trafficTab(), &TrafficTab::filterAction, this, &ConversationDialog::filterAction); connect(trafficTab()->tabBar(), &QTabBar::currentChanged, this, &ConversationDialog::tabChanged); connect(trafficTab(), &TrafficTab::tabDataChanged, this, &ConversationDialog::tabChanged); follow_bt_ = buttonBox()->addButton(tr("Follow Stream…"), QDialogButtonBox::ActionRole); follow_bt_->setToolTip(tr("Follow a TCP or UDP stream.")); connect(follow_bt_, SIGNAL(clicked()), this, SLOT(followStream())); graph_bt_ = buttonBox()->addButton(tr("Graph…"), QDialogButtonBox::ActionRole); graph_bt_->setToolTip(tr("Graph a TCP conversation.")); connect(graph_bt_, SIGNAL(clicked()), this, SLOT(graphTcp())); connect(mainApp->mainWindow(), SIGNAL(displayFilterSuccess(bool)), this, SLOT(displayFilterSuccess(bool))); absoluteTimeCheckBox()->show(); updateWidgets(); } void ConversationDialog::captureFileClosing() { trafficTab()->disableTap(); displayFilterCheckBox()->setEnabled(false); follow_bt_->setEnabled(false); graph_bt_->setEnabled(false); TrafficTableDialog::captureFileClosing(); } void ConversationDialog::followStream() { if (file_closed_) return; QVariant protoIdData = trafficTab()->currentItemData(ATapDataModel::PROTO_ID); if (protoIdData.isNull()) return; int protoId = protoIdData.toInt(); if (get_follow_by_proto_id(protoId) == nullptr) return; int convId = trafficTab()->currentItemData(ATapDataModel::CONVERSATION_ID).toInt(); // ATapDataModel doesn't support a substream ID (XXX: yet), so set it to a // dummy value. emit openFollowStreamDialog(protoId, convId, 0); } void ConversationDialog::graphTcp() { if (file_closed_) return; int endpointType = trafficTab()->currentItemData(ATapDataModel::ENDPOINT_DATATYPE).toInt(); if (endpointType != CONVERSATION_TCP) return; int convId = trafficTab()->currentItemData(ATapDataModel::CONVERSATION_ID).toInt(); // XXX The GTK+ code opens the TCP Stream dialog. We might want // to open the I/O Graphs dialog instead. QString filter = QString("tcp.stream eq %1").arg(convId); tcp_graph_requested_ = true; // Apply the filter for this conversation. When the filter is active, we // can draw the TCP graph. emit filterAction(filter, FilterAction::ActionApply, FilterAction::ActionTypePlain); } void ConversationDialog::tabChanged(int) { bool follow = false; bool graph = false; if (!file_closed_) { QVariant proto_id = trafficTab()->currentItemData(ATapDataModel::PROTO_ID); if (!proto_id.isNull()) { follow = (get_follow_by_proto_id(proto_id.toInt()) != nullptr); } int endpointType = trafficTab()->currentItemData(ATapDataModel::ENDPOINT_DATATYPE).toInt(); switch(endpointType) { case CONVERSATION_TCP: graph = true; break; } } follow_bt_->setEnabled(follow); graph_bt_->setEnabled(graph); TrafficTableDialog::currentTabChanged(); } void ConversationDialog::on_buttonBox_helpRequested() { mainApp->helpTopicAction(HELP_STATS_CONVERSATIONS_DIALOG); } void ConversationDialog::displayFilterSuccess(bool success) { if (tcp_graph_requested_) { if (success) { // The display filter was applied successfully, i.e. the current // packet is now part of our selected tcp conversation. openTcpStreamGraph(GRAPH_TSEQ_TCPTRACE); } tcp_graph_requested_ = false; } } void init_conversation_table(struct register_ct* ct, const char *filter) { mainApp->emitStatCommandSignal("Conversations", filter, GINT_TO_POINTER(get_conversation_proto_id(ct))); }
C/C++
wireshark/ui/qt/conversation_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef CONVERSATION_DIALOG_H #define CONVERSATION_DIALOG_H #include "traffic_table_dialog.h" class ConversationDialog : public TrafficTableDialog { Q_OBJECT public: /** Create a new conversation window. * * @param parent Parent widget. * @param cf Capture file. No statistics will be calculated if this is NULL. */ explicit ConversationDialog(QWidget &parent, CaptureFile &cf); protected: void captureFileClosing(); signals: void openFollowStreamDialog(int proto_id, guint stream_num, guint sub_stream_num); private: QPushButton *follow_bt_; QPushButton *graph_bt_; bool tcp_graph_requested_; private slots: void followStream(); void graphTcp(); void on_buttonBox_helpRequested(); void displayFilterSuccess(bool success); void tabChanged(int idx); }; void init_conversation_table(struct register_ct* ct, const char *filter); #endif // CONVERSATION_DIALOG_H
C++
wireshark/ui/qt/conversation_hash_tables_dialog.cpp
/* conversation_hash_tables_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "conversation_hash_tables_dialog.h" #include <ui_conversation_hash_tables_dialog.h> #include "config.h" #include <glib.h> #include <epan/conversation.h> #include <epan/conversation_debug.h> #include <ui/qt/utils/qt_ui_utils.h> #include "main_application.h" static void fill_named_table(gpointer key, gpointer value _U_, gpointer user_data) { const conversation_element_t *elements = static_cast<const conversation_element_t *>(key); QString* html_table = static_cast<QString *>(user_data); if (!elements || !html_table) { return; } if (html_table->isEmpty()) { html_table->append("<tr>"); int addr_count = 1; int port_count = 1; int string_count = 1; int uint_count = 1; int uint64_count = 1; int int_count = 1; for (const conversation_element_t *cur_el = elements; ; cur_el++) { QString title; switch (cur_el->type) { case CE_ADDRESS: title = QString("Address %1").arg(addr_count++); break; case CE_PORT: title = QString("Port %1").arg(port_count++); break; case CE_STRING: title = QString("String %1").arg(string_count++); break; case CE_UINT: title = QString("UInt %1").arg(uint_count++); break; case CE_UINT64: title = QString("UInt64 %1").arg(uint64_count++); break; case CE_INT: title = QString("Int %1").arg(int_count++); break; case CE_CONVERSATION_TYPE: html_table->append(QString("<th>Endpoint</th>")); goto title_done; break; } html_table->append(QString("<th>%1</th>").arg(title)); } title_done: html_table->append("</tr>\n"); } html_table->append("<tr>"); for (const conversation_element_t *cur_el = elements; ; cur_el++) { QString val; switch (cur_el->type) { case CE_ADDRESS: val = address_to_qstring(&cur_el->addr_val); break; case CE_PORT: val = QString::number(cur_el->port_val); break; case CE_STRING: val = cur_el->str_val; break; case CE_UINT: val = QString::number(cur_el->uint_val); break; case CE_UINT64: val = QString::number(cur_el->uint64_val); break; case CE_INT: val = QString::number(cur_el->int_val); break; case CE_CONVERSATION_TYPE: html_table->append(QString("<td>%1</td>").arg(QString::number(cur_el->conversation_type_val))); goto val_done; break; } html_table->append(QString("<td>%1</td>").arg(val)); } val_done: html_table->append("</tr>\n"); } ConversationHashTablesDialog::ConversationHashTablesDialog(QWidget *parent) : GeometryStateDialog(parent), ui(new Ui::ConversationHashTablesDialog) { ui->setupUi(this); if (parent) loadGeometry(parent->width() * 3 / 4, parent->height() * 3 / 4); setAttribute(Qt::WA_DeleteOnClose, true); setWindowTitle(mainApp->windowTitleString(tr("Conversation Hash Tables"))); QString html; html += "<h2>Conversation Hash Tables</h2>\n"; wmem_map_t *conversation_tables = get_conversation_hashtables(); wmem_list_t *table_names = wmem_map_get_keys(NULL, conversation_tables); for (wmem_list_frame_t *cur_frame = wmem_list_head(table_names); cur_frame; cur_frame = wmem_list_frame_next(cur_frame)) { const char *table_name = static_cast<const char *>(wmem_list_frame_data(cur_frame)); wmem_map_t *table = static_cast<wmem_map_t *>(wmem_map_lookup(conversation_tables, table_name)); if (!table) { html += QString("<h3>%1, Error: table not found</h3>\n").arg(table_name); continue; } html += QString("<h3>%1, %2 entries</h3>\n").arg(table_name).arg(wmem_map_size(table)); QString html_table; html += "<table>\n"; wmem_map_foreach(table, fill_named_table, &html_table); html += html_table; html += "</table>\n"; } wmem_destroy_list(table_names); ui->conversationTextEdit->setHtml(html); } ConversationHashTablesDialog::~ConversationHashTablesDialog() { delete ui; }
C/C++
wireshark/ui/qt/conversation_hash_tables_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef CONVERSATION_HASH_TABLES_DIALOG_H #define CONVERSATION_HASH_TABLES_DIALOG_H #include "geometry_state_dialog.h" #include <epan/wmem_scopes.h> namespace Ui { class ConversationHashTablesDialog; } class ConversationHashTablesDialog : public GeometryStateDialog { Q_OBJECT public: explicit ConversationHashTablesDialog(QWidget *parent = 0); ~ConversationHashTablesDialog(); private: Ui::ConversationHashTablesDialog *ui; const QString hashTableToHtmlTable(const QString table_name, wmem_map_t *hash_table); }; #endif // CONVERSATION_HASH_TABLES_DIALOG_H
User Interface
wireshark/ui/qt/conversation_hash_tables_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>ConversationHashTablesDialog</class> <widget class="QDialog" name="ConversationHashTablesDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>640</width> <height>450</height> </rect> </property> <property name="windowTitle"> <string>Dialog</string> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QTextEdit" name="conversationTextEdit"/> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Close</set> </property> </widget> </item> </layout> </widget> <resources/> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>ConversationHashTablesDialog</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>248</x> <y>254</y> </hint> <hint type="destinationlabel"> <x>157</x> <y>274</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>ConversationHashTablesDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>316</x> <y>260</y> </hint> <hint type="destinationlabel"> <x>286</x> <y>274</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/credentials_dialog.cpp
/* * credentials_dialog.c * * Copyright 2019 - Dario Lombardo <[email protected]> * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include <config.h> #include "file.h" #include "credentials_dialog.h" #include <ui_credentials_dialog.h> #include <ui/tap-credentials.h> #include "main_application.h" #include "ui/qt/widgets/wireshark_file_dialog.h" #include "ui/qt/models/credentials_model.h" #include <ui/qt/models/url_link_delegate.h> #include <QClipboard> #include <QMessageBox> #include <QPushButton> #include <QTextCursor> #include <QSortFilterProxyModel> class CredentialsUrlDelegate : public UrlLinkDelegate { public: CredentialsUrlDelegate(QObject * parent) : UrlLinkDelegate(parent) {} virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { bool ok = false; int val = index.data(Qt::UserRole).toInt(&ok); if (!ok || val <= 0) QStyledItemDelegate::paint(painter, option, index); else UrlLinkDelegate::paint(painter, option, index); } }; CredentialsDialog::CredentialsDialog(QWidget &parent, CaptureFile &cf, PacketList *packet_list) : WiresharkDialog(parent, cf), ui(new Ui::CredentialsDialog) { ui->setupUi(this); loadGeometry(); packet_list_ = packet_list; model_ = new CredentialsModel(this); QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model_); ui->auths->setModel(proxyModel); setWindowSubtitle(tr("Credentials")); ui->auths->setRootIsDecorated(false); ui->auths->setItemDelegateForColumn(CredentialsModel::COL_NUM, new CredentialsUrlDelegate(this)); ui->auths->setItemDelegateForColumn(CredentialsModel::COL_USERNAME, new CredentialsUrlDelegate(this)); ui->auths->resizeColumnToContents(CredentialsModel::COL_NUM); ui->auths->resizeColumnToContents(CredentialsModel::COL_PROTO); ui->auths->resizeColumnToContents(CredentialsModel::COL_USERNAME); ui->auths->setSortingEnabled(true); ui->auths->sortByColumn(CredentialsModel::COL_NUM, Qt::AscendingOrder); connect(ui->auths, &QTreeView::clicked, this, &CredentialsDialog::actionGoToPacket); registerTapListener("credentials", this, "", 0, tapReset, tapPacket, Q_NULLPTR); cf.retapPackets(); } CredentialsDialog::~CredentialsDialog() { delete ui; } void CredentialsDialog::tapReset(void *tapdata) { CredentialsDialog * d = (CredentialsDialog*) tapdata; d->model_->clear(); } tap_packet_status CredentialsDialog::tapPacket(void *tapdata, _packet_info *, epan_dissect *, const void *data, tap_flags_t) { CredentialsDialog * d = (CredentialsDialog*) tapdata; d->model_->addRecord((const tap_credential_t*)data); return TAP_PACKET_REDRAW; } void CredentialsDialog::actionGoToPacket(const QModelIndex& idx) { if (!idx.isValid()) return; QVariant packet_data = idx.data(Qt::UserRole); QVariant hf_id = idx.data(CredentialsModel::ColumnHFID); #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) if (!hf_id.canConvert<int>()) hf_id = QVariant::fromValue(0); if (packet_data.canConvert<int>()) packet_list_->goToPacket(packet_data.toInt(), hf_id.toInt()); #else if (!hf_id.canConvert(QVariant::Int)) hf_id = QVariant::fromValue(0); if (packet_data.canConvert(QVariant::Int)) packet_list_->goToPacket(packet_data.toInt(), hf_id.toInt()); #endif }
C/C++
wireshark/ui/qt/credentials_dialog.h
/** @file * * Copyright 2019 - Dario Lombardo <[email protected]> * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef CREDENTIALS_DIALOG_H #define CREDENTIALS_DIALOG_H #include "config.h" #include <wireshark_dialog.h> #include "packet_list.h" #include <ui/tap-credentials.h> class CredentialsModel; namespace Ui { class CredentialsDialog; } class CredentialsDialog : public WiresharkDialog { Q_OBJECT public: explicit CredentialsDialog(QWidget &parent, CaptureFile &cf, PacketList *packet_list); ~CredentialsDialog(); private slots: void actionGoToPacket(const QModelIndex&); private: Ui::CredentialsDialog *ui; PacketList *packet_list_; CredentialsModel * model_; static void tapReset(void *tapdata); static tap_packet_status tapPacket(void *tapdata, struct _packet_info *pinfo, struct epan_dissect *edt, const void *data, tap_flags_t flags); }; #endif // CREDENTIALS_DIALOG_H
User Interface
wireshark/ui/qt/credentials_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>CredentialsDialog</class> <widget class="QDialog" name="CredentialsDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>634</width> <height>454</height> </rect> </property> <property name="windowTitle"> <string>Wireshark - Credentials</string> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QTreeView" name="auths"/> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Close</set> </property> </widget> </item> </layout> </widget> <resources/> <connections> <connection> <sender>buttonBox</sender> <signal>clicked(QAbstractButton*)</signal> <receiver>CredentialsDialog</receiver> <slot>close()</slot> <hints> <hint type="sourcelabel"> <x>248</x> <y>254</y> </hint> <hint type="destinationlabel"> <x>157</x> <y>274</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/decode_as_dialog.cpp
/* decode_as_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "decode_as_dialog.h" #include <ui_decode_as_dialog.h> #include "epan/decode_as.h" #include "epan/epan_dissect.h" #include "ui/decode_as_utils.h" #include "ui/simple_dialog.h" #include "wsutil/filesystem.h" #include <wsutil/utf8_entities.h> #include <ui/qt/widgets/copy_from_profile_button.h> #include <ui/qt/utils/qt_ui_utils.h> #include "main_application.h" #include <ui/qt/utils/variant_pointer.h> #include <QComboBox> #include <QFont> #include <QFontMetrics> #include <QLineEdit> #include <QUrl> #include <QDebug> // To do: // - Ranges // - Add DCERPC support (or make DCERPC use a regular dissector table?) DecodeAsDialog::DecodeAsDialog(QWidget *parent, capture_file *cf, bool create_new) : GeometryStateDialog(parent), ui(new Ui::DecodeAsDialog), model_(new DecodeAsModel(this, cf)), delegate_(NULL) { ui->setupUi(this); loadGeometry(); delegate_ = new DecodeAsDelegate(ui->decodeAsTreeView, cf); ui->decodeAsTreeView->setModel(model_); ui->decodeAsTreeView->setItemDelegate(delegate_); ui->newToolButton->setStockIcon("list-add"); ui->deleteToolButton->setStockIcon("list-remove"); ui->copyToolButton->setStockIcon("list-copy"); ui->clearToolButton->setStockIcon("list-clear"); #ifdef Q_OS_MAC ui->newToolButton->setAttribute(Qt::WA_MacSmallSize, true); ui->deleteToolButton->setAttribute(Qt::WA_MacSmallSize, true); ui->copyToolButton->setAttribute(Qt::WA_MacSmallSize, true); ui->clearToolButton->setAttribute(Qt::WA_MacSmallSize, true); ui->pathLabel->setAttribute(Qt::WA_MacSmallSize, true); #endif setWindowTitle(mainApp->windowTitleString(tr("Decode As…"))); QString abs_path = gchar_free_to_qstring(get_persconffile_path(DECODE_AS_ENTRIES_FILE_NAME, TRUE)); if (file_exists(abs_path.toUtf8().constData())) { ui->pathLabel->setText(abs_path); ui->pathLabel->setUrl(QUrl::fromLocalFile(abs_path).toString()); ui->pathLabel->setToolTip(tr("Open ") + DECODE_AS_ENTRIES_FILE_NAME); ui->pathLabel->setEnabled(true); } CopyFromProfileButton *copy_button = new CopyFromProfileButton(this, DECODE_AS_ENTRIES_FILE_NAME); ui->buttonBox->addButton(copy_button, QDialogButtonBox::ActionRole); connect(copy_button, &CopyFromProfileButton::copyProfile, this, &DecodeAsDialog::copyFromProfile); fillTable(); connect(model_, &DecodeAsModel::modelReset, this, &DecodeAsDialog::modelRowsReset); ui->clearToolButton->setEnabled(model_->rowCount() > 0); if (create_new) on_newToolButton_clicked(); } DecodeAsDialog::~DecodeAsDialog() { delete ui; delete model_; delete delegate_; } void DecodeAsDialog::fillTable() { model_->fillTable(); resizeColumns(); //set selection as first row if (model_->rowCount() > 0) { const QModelIndex &new_index = model_->index(0, 0); ui->decodeAsTreeView->setCurrentIndex(new_index); } } void DecodeAsDialog::resizeColumns() { if (model_->rowCount() > 0) { for (int i = 0; i < model_->columnCount(); i++) { ui->decodeAsTreeView->resizeColumnToContents(i); } } } void DecodeAsDialog::modelRowsReset() { ui->deleteToolButton->setEnabled(false); ui->copyToolButton->setEnabled(false); ui->clearToolButton->setEnabled(false); } void DecodeAsDialog::on_decodeAsTreeView_currentItemChanged(const QModelIndex &current, const QModelIndex&) { if (current.isValid()) { ui->deleteToolButton->setEnabled(true); ui->copyToolButton->setEnabled(true); ui->clearToolButton->setEnabled(true); } else { ui->deleteToolButton->setEnabled(false); ui->copyToolButton->setEnabled(false); ui->clearToolButton->setEnabled(false); } } void DecodeAsDialog::copyFromProfile(QString filename) { const gchar *err = NULL; if (!model_->copyFromProfile(filename, &err)) { simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "Error while loading %s: %s", filename.toUtf8().constData(), err); } resizeColumns(); ui->clearToolButton->setEnabled(model_->rowCount() > 0); } void DecodeAsDialog::addRecord(bool copy_from_current) { const QModelIndex &current = ui->decodeAsTreeView->currentIndex(); if (copy_from_current && !current.isValid()) return; // XXX - This doesn't appear to work as intended to give "edit triggers on demand" ui->decodeAsTreeView->setEditTriggers(ui->decodeAsTreeView->editTriggers() | QAbstractItemView::CurrentChanged | QAbstractItemView::AnyKeyPressed); // should not fail, but you never know. if (!model_->insertRows(model_->rowCount(), 1)) { qDebug() << "Failed to add a new record"; return; } const QModelIndex &new_index = model_->index(model_->rowCount() - 1, 0); if (copy_from_current) { model_->copyRow(new_index.row(), current.row()); } resizeColumns(); // due to an EditTrigger, this will also start editing. ui->decodeAsTreeView->setCurrentIndex(new_index); } void DecodeAsDialog::on_newToolButton_clicked() { addRecord(); } void DecodeAsDialog::on_deleteToolButton_clicked() { const QModelIndex &current = ui->decodeAsTreeView->currentIndex(); if (model_ && current.isValid()) { if (!model_->removeRows(current.row(), 1)) { qDebug() << "Failed to remove row"; } } } void DecodeAsDialog::on_copyToolButton_clicked() { addRecord(true); } void DecodeAsDialog::on_clearToolButton_clicked() { model_->clearAll(); } void DecodeAsDialog::applyChanges() { model_->applyChanges(); mainApp->queueAppSignal(MainApplication::PacketDissectionChanged); } void DecodeAsDialog::on_buttonBox_clicked(QAbstractButton *button) { ui->buttonBox->setFocus(); switch (ui->buttonBox->standardButton(button)) { case QDialogButtonBox::Ok: applyChanges(); break; case QDialogButtonBox::Save: { gchar* err = NULL; applyChanges(); if (save_decode_as_entries(&err) < 0) { simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err); g_free(err); } } break; case QDialogButtonBox::Help: mainApp->helpTopicAction(HELP_DECODE_AS_SHOW_DIALOG); break; default: break; } }
C/C++
wireshark/ui/qt/decode_as_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef DECODE_AS_DIALOG_H #define DECODE_AS_DIALOG_H #include <config.h> #include <glib.h> #include "cfile.h" #include <ui/qt/models/decode_as_model.h> #include <ui/qt/models/decode_as_delegate.h> #include "geometry_state_dialog.h" #include <QMap> #include <QAbstractButton> class QComboBox; namespace Ui { class DecodeAsDialog; } class DecodeAsDialog : public GeometryStateDialog { Q_OBJECT public: explicit DecodeAsDialog(QWidget *parent = 0, capture_file *cf = NULL, bool create_new = false); ~DecodeAsDialog(); private: Ui::DecodeAsDialog *ui; DecodeAsModel* model_; DecodeAsDelegate* delegate_; void addRecord(bool copy_from_current = false); void applyChanges(); void fillTable(); void resizeColumns(); public slots: void modelRowsReset(); private slots: void copyFromProfile(QString filename); void on_decodeAsTreeView_currentItemChanged(const QModelIndex &current, const QModelIndex &previous); void on_newToolButton_clicked(); void on_deleteToolButton_clicked(); void on_copyToolButton_clicked(); void on_clearToolButton_clicked(); void on_buttonBox_clicked(QAbstractButton *button); }; #endif // DECODE_AS_DIALOG_H
User Interface
wireshark/ui/qt/decode_as_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>DecodeAsDialog</class> <widget class="QDialog" name="DecodeAsDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>750</width> <height>460</height> </rect> </property> <layout class="QVBoxLayout" name="verticalLayout_2"> <item> <widget class="TabnavTreeView" name="decodeAsTreeView"> <property name="indentation"> <number>0</number> </property> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0,0,0,0,1"> <item> <widget class="StockIconToolButton" name="newToolButton"> <property name="toolTip"> <string>Change the dissection behavior for a protocol.</string> </property> <property name="text"> <string/> </property> </widget> </item> <item> <widget class="StockIconToolButton" name="deleteToolButton"> <property name="enabled"> <bool>false</bool> </property> <property name="toolTip"> <string>Remove this dissection behavior.</string> </property> </widget> </item> <item> <widget class="StockIconToolButton" name="copyToolButton"> <property name="toolTip"> <string>Copy this dissection behavior.</string> </property> <property name="text"> <string/> </property> </widget> </item> <item> <widget class="StockIconToolButton" name="clearToolButton"> <property name="enabled"> <bool>false</bool> </property> <property name="toolTip"> <string>Clear all dissection behaviors.</string> </property> </widget> </item> <item> <spacer name="horizontalSpacer"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> <item> <widget class="ElidedLabel" name="pathLabel"> <property name="sizePolicy"> <sizepolicy hsizetype="Expanding" vsizetype="Preferred"> <horstretch>1</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> <property name="text"> <string/> </property> <property name="alignment"> <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> </property> <property name="openExternalLinks"> <bool>true</bool> </property> </widget> </item> </layout> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Cancel|QDialogButtonBox::Help|QDialogButtonBox::Ok|QDialogButtonBox::Save</set> </property> </widget> </item> </layout> </widget> <customwidgets> <customwidget> <class>ElidedLabel</class> <extends>QLabel</extends> <header>widgets/elided_label.h</header> </customwidget> <customwidget> <class>TabnavTreeView</class> <extends>QTreeView</extends> <header>widgets/tabnav_tree_view.h</header> </customwidget> <customwidget> <class>StockIconToolButton</class> <extends>QToolButton</extends> <header>widgets/stock_icon_tool_button.h</header> </customwidget> </customwidgets> <resources/> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>DecodeAsDialog</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>248</x> <y>254</y> </hint> <hint type="destinationlabel"> <x>157</x> <y>274</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>DecodeAsDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>316</x> <y>260</y> </hint> <hint type="destinationlabel"> <x>286</x> <y>274</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/display_filter_expression_dialog.cpp
/* display_filter_expression_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include <algorithm> #include "display_filter_expression_dialog.h" #include <ui_display_filter_expression_dialog.h> #include <epan/proto.h> #include <epan/range.h> #include <epan/tfs.h> #include <epan/value_string.h> #include <wsutil/utf8_entities.h> #include <ui/qt/utils/qt_ui_utils.h> #include "main_application.h" #include <ui/qt/utils/variant_pointer.h> #include <QPushButton> #include <QDialogButtonBox> #include <QListWidgetItem> #include <QTreeWidgetItem> #include <QRegularExpression> #include <QtConcurrent> // To do: // - Speed up search. enum { proto_type_ = 1000, field_type_ }; enum { present_op_ = 1000, any_eq_op_, all_eq_op_, any_ne_op_, all_ne_op_, gt_op_, lt_op_, ge_op_, le_op_, contains_op_, matches_op_, in_op_ }; static inline bool compareTreeWidgetItems(const QTreeWidgetItem *it1, const QTreeWidgetItem *it2) { return *it1 < *it2; } #ifdef DISPLAY_FILTER_EXPRESSION_DIALOG_USE_QPROMISE static void generateProtocolTreeItems(QPromise<QTreeWidgetItem *> &promise) { QList<QTreeWidgetItem *> proto_list; QList<QTreeWidgetItem *> *ptr_proto_list = &proto_list; #else static QList<QTreeWidgetItem *> *generateProtocolTreeItems() { QList<QTreeWidgetItem *> *ptr_proto_list = new QList<QTreeWidgetItem *>(); #endif void *proto_cookie; for (int proto_id = proto_get_first_protocol(&proto_cookie); proto_id != -1; proto_id = proto_get_next_protocol(&proto_cookie)) { protocol_t *protocol = find_protocol_by_id(proto_id); if (!proto_is_protocol_enabled(protocol)) continue; QTreeWidgetItem *proto_ti = new QTreeWidgetItem(proto_type_); QString label = QString("%1 " UTF8_MIDDLE_DOT " %3") .arg(proto_get_protocol_short_name(protocol)) .arg(proto_get_protocol_long_name(protocol)); proto_ti->setText(0, label); proto_ti->setData(0, Qt::UserRole, QVariant::fromValue(proto_id)); ptr_proto_list->append(proto_ti); } std::stable_sort(ptr_proto_list->begin(), ptr_proto_list->end(), compareTreeWidgetItems); foreach (QTreeWidgetItem *proto_ti, *ptr_proto_list) { #ifdef DISPLAY_FILTER_EXPRESSION_DIALOG_USE_QPROMISE if (promise.isCanceled()) { delete proto_ti; continue; } promise.suspendIfRequested(); #endif void *field_cookie; int proto_id = proto_ti->data(0, Qt::UserRole).toInt(); QList <QTreeWidgetItem *> field_list; for (header_field_info *hfinfo = proto_get_first_protocol_field(proto_id, &field_cookie); hfinfo != NULL; hfinfo = proto_get_next_protocol_field(proto_id, &field_cookie)) { if (hfinfo->same_name_prev_id != -1) continue; // Ignore duplicate names. QTreeWidgetItem *field_ti = new QTreeWidgetItem(field_type_); QString label = QString("%1 " UTF8_MIDDLE_DOT " %3").arg(hfinfo->abbrev).arg(hfinfo->name); field_ti->setText(0, label); field_ti->setData(0, Qt::UserRole, VariantPointer<header_field_info>::asQVariant(hfinfo)); field_list << field_ti; } std::stable_sort(field_list.begin(), field_list.end(), compareTreeWidgetItems); proto_ti->addChildren(field_list); #ifdef DISPLAY_FILTER_EXPRESSION_DIALOG_USE_QPROMISE if (!promise.addResult(proto_ti)) delete proto_ti; } #else } return ptr_proto_list; #endif } DisplayFilterExpressionDialog::DisplayFilterExpressionDialog(QWidget *parent) : GeometryStateDialog(parent), #ifdef DISPLAY_FILTER_EXPRESSION_DIALOG_USE_QPROMISE watcher(new QFutureWatcher<QTreeWidgetItem *>(nullptr)), #else watcher(new QFutureWatcher<QList<QTreeWidgetItem *> *>(nullptr)), #endif ui(new Ui::DisplayFilterExpressionDialog), ftype_(FT_NONE), field_(NULL) { ui->setupUi(this); if (parent) loadGeometry(parent->width() * 2 / 3, parent->height()); setAttribute(Qt::WA_DeleteOnClose, true); setWindowTitle(mainApp->windowTitleString(tr("Display Filter Expression"))); setWindowIcon(mainApp->normalIcon()); proto_initialize_all_prefixes(); auto future = QtConcurrent::run(generateProtocolTreeItems); ui->fieldTreeWidget->setToolTip(ui->fieldLabel->toolTip()); ui->searchLineEdit->setToolTip(ui->searchLabel->toolTip()); ui->relationListWidget->setToolTip(ui->relationLabel->toolTip()); ui->valueLineEdit->setToolTip(ui->valueLabel->toolTip()); ui->enumListWidget->setToolTip(ui->enumLabel->toolTip()); ui->rangeLineEdit->setToolTip(ui->rangeLabel->toolTip()); // Relation list new QListWidgetItem("is present", ui->relationListWidget, present_op_); new QListWidgetItem("==", ui->relationListWidget, any_eq_op_); new QListWidgetItem("!=", ui->relationListWidget, all_ne_op_); new QListWidgetItem("===", ui->relationListWidget, all_eq_op_); new QListWidgetItem("!==", ui->relationListWidget, any_ne_op_); new QListWidgetItem(">", ui->relationListWidget, gt_op_); new QListWidgetItem("<", ui->relationListWidget, lt_op_); new QListWidgetItem(">=", ui->relationListWidget, ge_op_); new QListWidgetItem("<=", ui->relationListWidget, le_op_); new QListWidgetItem("contains", ui->relationListWidget, contains_op_); new QListWidgetItem("matches", ui->relationListWidget, matches_op_); new QListWidgetItem("in", ui->relationListWidget, in_op_); value_label_pfx_ = ui->valueLabel->text(); connect(ui->anyRadioButton, &QAbstractButton::toggled, this, &DisplayFilterExpressionDialog::updateWidgets); connect(ui->allRadioButton, &QAbstractButton::toggled, this, &DisplayFilterExpressionDialog::updateWidgets); connect(ui->valueLineEdit, &QLineEdit::textEdited, this, &DisplayFilterExpressionDialog::updateWidgets); connect(ui->rangeLineEdit, &QLineEdit::textEdited, this, &DisplayFilterExpressionDialog::updateWidgets); updateWidgets(); ui->searchLineEdit->setReadOnly(true); #ifdef DISPLAY_FILTER_EXPRESSION_DIALOG_USE_QPROMISE connect(watcher, &QFutureWatcher<QTreeWidgetItem *>::resultReadyAt, this, &DisplayFilterExpressionDialog::addTreeItem); connect(watcher, &QFutureWatcher<QTreeWidgetItem *>::finished, this, &DisplayFilterExpressionDialog::fillTree); #else connect(watcher, &QFutureWatcher<QList<QTreeWidgetItem *> *>::finished, this, &DisplayFilterExpressionDialog::fillTree); // If window is closed before future finishes, DisplayFilterExpressionDialog fillTree slot won't run // Register lambda to free up the list container and tree entries (if not consumed by fillTree()) auto captured_watcher = this->watcher; connect(watcher, &QFutureWatcher<QList<QTreeWidgetItem *> *>::finished, [captured_watcher]() { QList<QTreeWidgetItem *> *items = captured_watcher->future().result(); qDeleteAll(*items); delete items; }); #endif watcher->setFuture(future); } DisplayFilterExpressionDialog::~DisplayFilterExpressionDialog() { if (watcher) { #ifdef DISPLAY_FILTER_EXPRESSION_DIALOG_USE_QPROMISE watcher->future().cancel(); qDeleteAll(watcher->future().results()); #endif watcher->waitForFinished(); watcher->deleteLater(); } delete ui; } #ifdef DISPLAY_FILTER_EXPRESSION_DIALOG_USE_QPROMISE void DisplayFilterExpressionDialog::addTreeItem(int result) { QTreeWidgetItem *item = watcher->future().resultAt(result); ui->fieldTreeWidget->invisibleRootItem()->addChild(item); } #endif void DisplayFilterExpressionDialog::fillTree() { #ifndef DISPLAY_FILTER_EXPRESSION_DIALOG_USE_QPROMISE QList<QTreeWidgetItem *> *items = watcher->future().result(); ui->fieldTreeWidget->invisibleRootItem()->addChildren(*items); // fieldTreeWidget now owns all items items->clear(); #endif watcher->deleteLater(); watcher = nullptr; ui->searchLineEdit->setReadOnly(false); } void DisplayFilterExpressionDialog::updateWidgets() { bool rel_enable = field_ != NULL; ui->relationLabel->setEnabled(rel_enable); ui->relationListWidget->setEnabled(rel_enable); ui->hintLabel->clear(); bool quantity_enable = false; bool value_enable = false; bool enum_enable = false; bool enum_multi_enable = false; bool range_enable = false; QString filter; if (field_) { filter = field_; QListWidgetItem *rli = ui->relationListWidget->currentItem(); if (rli && rli->type() > all_ne_op_) { quantity_enable = true; if (ui->anyRadioButton->isChecked()) { filter.prepend("any "); } else if (ui->allRadioButton->isChecked()) { filter.prepend("all "); } else { ws_assert_not_reached(); } } if (rli && rli->type() != present_op_) { value_enable = true; if (ftype_can_slice(ftype_)) { range_enable = true; } enum_enable = ui->enumListWidget->count() > 0; filter.append(QString(" %1").arg(rli->text())); } if (value_enable && !ui->valueLineEdit->text().isEmpty()) { if (rli && rli->type() == in_op_) { filter.append(QString(" {%1}").arg(ui->valueLineEdit->text())); enum_multi_enable = enum_enable; } else { if (ftype_ == FT_STRING) { filter.append(QString(" \"%1\"").arg(ui->valueLineEdit->text())); } else { filter.append(QString(" %1").arg(ui->valueLineEdit->text())); } } } } ui->quantityLabel->setEnabled(quantity_enable); ui->allRadioButton->setEnabled(quantity_enable); ui->anyRadioButton->setEnabled(quantity_enable); ui->valueLabel->setEnabled(value_enable); ui->valueLineEdit->setEnabled(value_enable); ui->enumLabel->setEnabled(enum_enable); ui->enumListWidget->setEnabled(enum_enable); ui->enumListWidget->setSelectionMode(enum_multi_enable ? QAbstractItemView::ExtendedSelection : QAbstractItemView::SingleSelection); ui->rangeLabel->setEnabled(range_enable); ui->rangeLineEdit->setEnabled(range_enable); ui->displayFilterLineEdit->setText(filter); QString hint = "<small><i>"; if (ui->fieldTreeWidget->selectedItems().count() < 1) { hint.append(tr("Select a field name to get started")); } else if (ui->displayFilterLineEdit->syntaxState() != SyntaxLineEdit::Valid) { hint.append(ui->displayFilterLineEdit->syntaxErrorMessage()); } else { hint.append(tr("Click OK to insert this filter")); } hint.append("</i></small>"); ui->hintLabel->setText(hint); QPushButton *ok_bt = ui->buttonBox->button(QDialogButtonBox::Ok); if (ok_bt) { bool ok_enable = !(ui->displayFilterLineEdit->text().isEmpty() || (ui->displayFilterLineEdit->syntaxState() == SyntaxLineEdit::Invalid)); ok_bt->setEnabled(ok_enable); } } void DisplayFilterExpressionDialog::fillEnumBooleanValues(const true_false_string *tfs) { if (!tfs) tfs = &tfs_true_false; QListWidgetItem *eli = new QListWidgetItem(tfs->true_string, ui->enumListWidget); eli->setData(Qt::UserRole, QString("1")); eli = new QListWidgetItem(tfs->false_string, ui->enumListWidget); eli->setData(Qt::UserRole, QString("0")); } void DisplayFilterExpressionDialog::fillEnumIntValues(const _value_string *vals, int base) { if (!vals) return; for (int i = 0; vals[i].strptr != NULL; i++) { QListWidgetItem *eli = new QListWidgetItem(vals[i].strptr, ui->enumListWidget); eli->setData(Qt::UserRole, int_to_qstring(vals[i].value, 0, base)); } } void DisplayFilterExpressionDialog::fillEnumInt64Values(const _val64_string *vals64, int base) { if (!vals64) return; for (int i = 0; vals64[i].strptr != NULL; i++) { QListWidgetItem *eli = new QListWidgetItem(vals64[i].strptr, ui->enumListWidget); eli->setData(Qt::UserRole, int_to_qstring(vals64[i].value, 0, base)); } } void DisplayFilterExpressionDialog::fillEnumRangeValues(const _range_string *rvals) { if (!rvals) return; for (int i = 0; rvals[i].strptr != NULL; i++) { QString range_text = rvals[i].strptr; // Tell the user which values are valid here. Default to value_min below. if (rvals[i].value_min != rvals[i].value_max) { range_text.append(QString(" (%1 valid)").arg(range_to_qstring(&rvals[i]))); } QListWidgetItem *eli = new QListWidgetItem(range_text, ui->enumListWidget); eli->setData(Qt::UserRole, QString::number(rvals[i].value_min)); } } void DisplayFilterExpressionDialog::on_fieldTreeWidget_itemSelectionChanged() { ftype_ = FT_NONE; field_ = NULL; QTreeWidgetItem *cur_fti = NULL; if (ui->fieldTreeWidget->selectedItems().count() > 0) { cur_fti = ui->fieldTreeWidget->selectedItems()[0]; } ui->valueLineEdit->clear(); ui->enumListWidget->clear(); ui->rangeLineEdit->clear(); if (cur_fti && cur_fti->type() == proto_type_) { ftype_ = FT_PROTOCOL; field_ = proto_get_protocol_filter_name(cur_fti->data(0, Qt::UserRole).toInt()); } else if (cur_fti && cur_fti->type() == field_type_) { header_field_info *hfinfo = VariantPointer<header_field_info>::asPtr(cur_fti->data(0, Qt::UserRole)); if (hfinfo) { ftype_ = hfinfo->type; field_ = hfinfo->abbrev; switch(ftype_) { case FT_BOOLEAN: // Let the user select the "True" and "False" values. fillEnumBooleanValues((const true_false_string *)hfinfo->strings); break; case FT_UINT8: case FT_UINT16: case FT_UINT24: case FT_UINT32: case FT_INT8: case FT_INT16: case FT_INT24: case FT_INT32: { int base; switch (hfinfo->display & FIELD_DISPLAY_E_MASK) { case BASE_HEX: case BASE_HEX_DEC: base = 16; break; case BASE_OCT: base = 8; break; default: base = 10; break; } // Let the user select from a list of value_string or range_string values. if (hfinfo->strings && ! ((hfinfo->display & FIELD_DISPLAY_E_MASK) == BASE_CUSTOM)) { if (hfinfo->display & BASE_RANGE_STRING) { fillEnumRangeValues((const range_string *)hfinfo->strings); } else if (hfinfo->display & BASE_VAL64_STRING) { const val64_string *vals = (const val64_string *)hfinfo->strings; fillEnumInt64Values(vals, base); } else { // Plain old value_string / VALS const value_string *vals = (const value_string *)hfinfo->strings; if (hfinfo->display & BASE_EXT_STRING) vals = VALUE_STRING_EXT_VS_P((const value_string_ext *)vals); fillEnumIntValues(vals, base); } } break; } default: break; } } } if (ui->enumListWidget->count() > 0) { ui->enumListWidget->setCurrentRow(0); } bool all_show = field_ != NULL; for (int i = 0; i < ui->relationListWidget->count(); i++) { QListWidgetItem *li = ui->relationListWidget->item(i); switch (li->type()) { case any_eq_op_: case all_eq_op_: case any_ne_op_: case all_ne_op_: li->setHidden(!ftype_can_eq(ftype_) && !(ftype_can_slice(ftype_) && ftype_can_eq(FT_BYTES))); break; case gt_op_: case lt_op_: case ge_op_: case le_op_: case in_op_: li->setHidden(!ftype_can_cmp(ftype_) && !(ftype_can_slice(ftype_) && ftype_can_cmp(FT_BYTES))); break; case contains_op_: li->setHidden(!ftype_can_contains(ftype_) && !(ftype_can_slice(ftype_) && ftype_can_contains(FT_BYTES))); break; case matches_op_: li->setHidden(!ftype_can_matches(ftype_) && !(ftype_can_slice(ftype_) && ftype_can_matches(FT_BYTES))); break; default: li->setHidden(!all_show); break; } } if (all_show) { // Select "==" if it's present and we have a value, "is present" otherwise int row = ui->relationListWidget->count() > 1 && ui->enumListWidget->count() > 0 ? 1 : 0; ui->relationListWidget->setCurrentRow(row); } if (ftype_ != FT_NONE) { ui->valueLabel->setText(QString("%1 (%2)") .arg(value_label_pfx_) .arg(ftype_pretty_name(ftype_))); } else { ui->valueLabel->setText(value_label_pfx_); } updateWidgets(); } void DisplayFilterExpressionDialog::on_relationListWidget_itemSelectionChanged() { updateWidgets(); } void DisplayFilterExpressionDialog::on_enumListWidget_itemSelectionChanged() { QStringList values; QList<QListWidgetItem *> items = ui->enumListWidget->selectedItems(); QList<QListWidgetItem *>::const_iterator it = items.constBegin(); while (it != items.constEnd()) { values << (*it)->data(Qt::UserRole).toString(); ++it; } ui->valueLineEdit->setText(values.join(" ")); updateWidgets(); } void DisplayFilterExpressionDialog::on_searchLineEdit_textChanged(const QString &search_re) { ui->fieldTreeWidget->setUpdatesEnabled(false); QTreeWidgetItemIterator it(ui->fieldTreeWidget); QRegularExpression regex(search_re, QRegularExpression::CaseInsensitiveOption); if (! regex.isValid()) return; while (*it) { bool hidden = true; if (search_re.isEmpty() || (*it)->text(0).contains(regex)) { hidden = false; if ((*it)->type() == field_type_) { (*it)->parent()->setHidden(false); } } (*it)->setHidden(hidden); ++it; } ui->fieldTreeWidget->setUpdatesEnabled(true); } void DisplayFilterExpressionDialog::on_buttonBox_accepted() { emit insertDisplayFilter(ui->displayFilterLineEdit->text()); } void DisplayFilterExpressionDialog::on_buttonBox_helpRequested() { mainApp->helpTopicAction(HELP_FILTER_EXPRESSION_DIALOG); }
C/C++
wireshark/ui/qt/display_filter_expression_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef DISPLAY_FILTER_EXPRESSION_DIALOG_H #define DISPLAY_FILTER_EXPRESSION_DIALOG_H #include "config.h" #include <epan/ftypes/ftypes.h> #include "geometry_state_dialog.h" #include <QFutureWatcher> #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) /* Qt6 introduces QPromise interface that makes it possible to add tree entries * protocol by protocol instead of all at once. */ #define DISPLAY_FILTER_EXPRESSION_DIALOG_USE_QPROMISE #endif class QTreeWidgetItem; struct true_false_string; struct _value_string; struct _val64_string; namespace Ui { class DisplayFilterExpressionDialog; } class DisplayFilterExpressionDialog : public GeometryStateDialog { Q_OBJECT public: explicit DisplayFilterExpressionDialog(QWidget *parent = 0); ~DisplayFilterExpressionDialog(); signals: void insertDisplayFilter(const QString &filter); private slots: #ifdef DISPLAY_FILTER_EXPRESSION_DIALOG_USE_QPROMISE void addTreeItem(int result); #endif void fillTree(); void updateWidgets(); void on_fieldTreeWidget_itemSelectionChanged(); void on_relationListWidget_itemSelectionChanged(); void on_enumListWidget_itemSelectionChanged(); void on_searchLineEdit_textChanged(const QString &search_re); void on_buttonBox_accepted(); void on_buttonBox_helpRequested(); private: #ifdef DISPLAY_FILTER_EXPRESSION_DIALOG_USE_QPROMISE QFutureWatcher<QTreeWidgetItem *> *watcher; #else QFutureWatcher<QList<QTreeWidgetItem *> *> *watcher; #endif Ui::DisplayFilterExpressionDialog *ui; void fillEnumBooleanValues(const struct true_false_string *tfs); void fillEnumIntValues(const struct _value_string *vals, int base); void fillEnumInt64Values(const struct _val64_string *vals64, int base); void fillEnumRangeValues(const struct _range_string *rvals); enum ftenum ftype_; const char *field_; QString value_label_pfx_; }; #endif // DISPLAY_FILTER_EXPRESSION_DIALOG_H
User Interface
wireshark/ui/qt/display_filter_expression_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>DisplayFilterExpressionDialog</class> <widget class="QDialog" name="DisplayFilterExpressionDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>657</width> <height>588</height> </rect> </property> <property name="windowTitle"> <string>Dialog</string> </property> <layout class="QVBoxLayout" name="verticalLayout_2"> <item> <layout class="QHBoxLayout" name="horizontalLayout_2"> <item> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QLabel" name="fieldLabel"> <property name="toolTip"> <string>Select a field to start building a display filter.</string> </property> <property name="text"> <string>Field Name</string> </property> </widget> </item> <item> <widget class="QTreeWidget" name="fieldTreeWidget"> <property name="uniformRowHeights"> <bool>true</bool> </property> <property name="headerHidden"> <bool>true</bool> </property> <column> <property name="text"> <string notr="true">1</string> </property> </column> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <widget class="QLabel" name="searchLabel"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Search the list of field names.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string> </property> <property name="text"> <string>Search:</string> </property> </widget> </item> <item> <widget class="QLineEdit" name="searchLineEdit"/> </item> </layout> </item> </layout> </item> <item> <layout class="QVBoxLayout" name="verticalLayout_6" stretch="0,0,1,0,4,1,0"> <item> <layout class="QVBoxLayout" name="relationLayout"> <item> <widget class="QLabel" name="relationLabel"> <property name="toolTip"> <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Relations can be used to restrict fields to specific values. Each relation does the following:&lt;/p&gt;&lt;table border=&quot;0&quot; style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px;&quot; cellspacing=&quot;2&quot; cellpadding=&quot;0&quot;&gt;&lt;tr&gt;&lt;td&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;is present&lt;/span&gt;&lt;/p&gt;&lt;/td&gt;&lt;td&gt;&lt;p&gt;Match any packet that contains this field&lt;/p&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;==, !=, etc.&lt;/span&gt;&lt;/p&gt;&lt;/td&gt;&lt;td&gt;&lt;p&gt;Compare the field to a specific value.&lt;/p&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;contains, matches&lt;/span&gt;&lt;/p&gt;&lt;/td&gt;&lt;td&gt;&lt;p&gt;Check the field against a string (contains) or a regular expression (matches)&lt;/p&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;in&lt;/span&gt;&lt;/p&gt;&lt;/td&gt;&lt;td&gt;&lt;p&gt;Compare the field to a specific set of values&lt;/p&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/body&gt;&lt;/html&gt; </string> </property> <property name="text"> <string>Relation</string> </property> </widget> </item> <item> <widget class="QListWidget" name="relationListWidget"/> </item> </layout> </item> <item> <layout class="QVBoxLayout" name="quantityLayout"> <item> <widget class="QLabel" name="quantityLabel"> <property name="toolTip"> <string>By default order comparisons and contains/matches/in relations are true if any value matches. The quantifier &quot;all&quot; can be used to apply the test to all values in a frame.</string> </property> <property name="text"> <string>Quantifier</string> </property> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout_3"> <item> <widget class="QRadioButton" name="anyRadioButton"> <property name="text"> <string>Any</string> </property> <property name="checked"> <bool>true</bool> </property> </widget> </item> <item> <widget class="QRadioButton" name="allRadioButton"> <property name="text"> <string>All</string> </property> <property name="checked"> <bool>false</bool> </property> </widget> </item> <item> <spacer name="horizontalSpacer"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> </layout> </item> </layout> </item> <item> <spacer name="verticalSpacer"> <property name="orientation"> <enum>Qt::Vertical</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>20</width> <height>12</height> </size> </property> </spacer> </item> <item> <layout class="QVBoxLayout" name="valueLayout"> <item> <widget class="QLabel" name="valueLabel"> <property name="toolTip"> <string>Match against this value.</string> </property> <property name="text"> <string>Value</string> </property> </widget> </item> <item> <widget class="QLineEdit" name="valueLineEdit"/> </item> </layout> </item> <item> <layout class="QVBoxLayout" name="enumLayout"> <item> <widget class="QLabel" name="enumLabel"> <property name="toolTip"> <string>If the field you have selected has a known set of valid values they will be listed here.</string> </property> <property name="text"> <string>Predefined Values</string> </property> </widget> </item> <item> <widget class="QListWidget" name="enumListWidget"/> </item> </layout> </item> <item> <spacer name="verticalSpacer_2"> <property name="orientation"> <enum>Qt::Vertical</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>20</width> <height>12</height> </size> </property> </spacer> </item> <item> <layout class="QVBoxLayout" name="rangeLayout"> <item> <widget class="QLabel" name="rangeLabel"> <property name="toolTip"> <string>If the field you have selected covers a range of bytes (e.g. you have selected a protocol) you can restrict the match to a range of bytes here.</string> </property> <property name="text"> <string>Range (offset:length)</string> </property> </widget> </item> <item> <widget class="QLineEdit" name="rangeLineEdit"/> </item> </layout> </item> </layout> </item> </layout> </item> <item> <widget class="DisplayFilterEdit" name="displayFilterLineEdit"> <property name="readOnly"> <bool>true</bool> </property> <property name="placeholderText"> <string>No display filter</string> </property> </widget> </item> <item> <widget class="QLabel" name="hintLabel"> <property name="text"> <string>&lt;small&gt;&lt;i&gt;A hint.&lt;/i&gt;&lt;/small&gt;</string> </property> <property name="wordWrap"> <bool>true</bool> </property> </widget> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Cancel|QDialogButtonBox::Help|QDialogButtonBox::Ok</set> </property> </widget> </item> </layout> </widget> <customwidgets> <customwidget> <class>DisplayFilterEdit</class> <extends>QLineEdit</extends> <header>widgets/display_filter_edit.h</header> </customwidget> </customwidgets> <resources/> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>DisplayFilterExpressionDialog</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>248</x> <y>254</y> </hint> <hint type="destinationlabel"> <x>157</x> <y>274</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>DisplayFilterExpressionDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>316</x> <y>260</y> </hint> <hint type="destinationlabel"> <x>286</x> <y>274</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/dissector_tables_dialog.cpp
/* dissector_tables_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include <ui/qt/dissector_tables_dialog.h> #include <ui_dissector_tables_dialog.h> #include "main_application.h" DissectorTablesDialog::DissectorTablesDialog(QWidget *parent) : GeometryStateDialog(parent), ui(new Ui::DissectorTablesDialog) { ui->setupUi(this); if (parent) loadGeometry(parent->width() * 3 / 4, parent->height() * 3 / 4); setAttribute(Qt::WA_DeleteOnClose, true); setWindowTitle(mainApp->windowTitleString(tr("Dissector Tables"))); proxyModel_ = new DissectorTablesProxyModel(this); proxyModel_->setSourceModel(new DissectorTablesModel(this)); //it's recommended to sort after list is populated proxyModel_->sort(DissectorTablesModel::colTableName); ui->tableTree->setModel(proxyModel_); //expand the "type" tables ui->tableTree->expandToDepth(0); ui->tableTree->resizeColumnToContents(DissectorTablesModel::colTableName); ui->txtSearchLine->setFocus(); } DissectorTablesDialog::~DissectorTablesDialog() { delete ui; } void DissectorTablesDialog::on_txtSearchLine_textChanged(const QString &search_re) { proxyModel_->setFilter(search_re); /* If items are filtered out, then filtered back in, the tree remains collapsed Force an expansion */ ui->tableTree->expandToDepth(0); }
C/C++
wireshark/ui/qt/dissector_tables_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef DISSECTOR_TABLES_DIALOG_H #define DISSECTOR_TABLES_DIALOG_H #include <ui/qt/geometry_state_dialog.h> #include <ui/qt/models/dissector_tables_model.h> namespace Ui { class DissectorTablesDialog; } class DissectorTablesDialog : public GeometryStateDialog { Q_OBJECT public: explicit DissectorTablesDialog(QWidget *parent = 0); ~DissectorTablesDialog(); private slots: void on_txtSearchLine_textChanged(const QString &search_re); private: Ui::DissectorTablesDialog *ui; DissectorTablesProxyModel* proxyModel_; }; #endif // DISSECTOR_TABLES_DIALOG_H
User Interface
wireshark/ui/qt/dissector_tables_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>DissectorTablesDialog</class> <widget class="QDialog" name="DissectorTablesDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>400</width> <height>351</height> </rect> </property> <property name="windowTitle"> <string>Dialog</string> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <widget class="QLabel" name="label"> <property name="text"> <string>Search:</string> </property> </widget> </item> <item> <widget class="QLineEdit" name="txtSearchLine"/> </item> </layout> </item> <item> <widget class="DissectorTablesTreeView" name="tableTree"> <property name="uniformRowHeights"> <bool>true</bool> </property> </widget> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Close</set> </property> </widget> </item> </layout> </widget> <customwidgets> <customwidget> <class>DissectorTablesTreeView</class> <extends>QTreeView</extends> <header>widgets/dissector_tables_view.h</header> </customwidget> </customwidgets> <resources/> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>DissectorTablesDialog</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>248</x> <y>254</y> </hint> <hint type="destinationlabel"> <x>157</x> <y>274</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>DissectorTablesDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>316</x> <y>260</y> </hint> <hint type="destinationlabel"> <x>286</x> <y>274</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/enabled_protocols_dialog.cpp
/* enabled_protocols_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "enabled_protocols_dialog.h" #include <ui_enabled_protocols_dialog.h> #include <QElapsedTimer> #include <epan/prefs.h> #include "main_application.h" EnabledProtocolsDialog::EnabledProtocolsDialog(QWidget *parent) : GeometryStateDialog(parent), ui(new Ui::EnabledProtocolsDialog), enabled_protocols_model_(new EnabledProtocolsModel()), proxyModel_(new EnabledProtocolsProxyModel(this)) { ui->setupUi(this); loadGeometry(); proxyModel_->setSourceModel(enabled_protocols_model_); ui->protocol_tree_->setModel(proxyModel_); setWindowTitle(mainApp->windowTitleString(tr("Enabled Protocols"))); // Some protocols have excessively long names. Instead of calling // resizeColumnToContents, pick a reasonable-ish em width and apply it. int one_em = ui->protocol_tree_->fontMetrics().height(); ui->protocol_tree_->setColumnWidth(EnabledProtocolsModel::colProtocol, one_em * 18); ui->cmbSearchType->addItem(tr("Everywhere"), QVariant::fromValue(EnabledProtocolsProxyModel::EveryWhere)); ui->cmbSearchType->addItem(tr("Only Protocols"), QVariant::fromValue(EnabledProtocolsProxyModel::OnlyProtocol)); ui->cmbSearchType->addItem(tr("Only Description"), QVariant::fromValue(EnabledProtocolsProxyModel::OnlyDescription)); ui->cmbSearchType->addItem(tr("Only enabled protocols"), QVariant::fromValue(EnabledProtocolsProxyModel::EnabledItems)); ui->cmbSearchType->addItem(tr("Only disabled protocols"), QVariant::fromValue(EnabledProtocolsProxyModel::DisabledItems)); ui->cmbProtocolType->addItem(tr("any protocol"), QVariant::fromValue(EnabledProtocolItem::Any)); ui->cmbProtocolType->addItem(tr("non-heuristic protocols"), QVariant::fromValue(EnabledProtocolItem::Standard)); ui->cmbProtocolType->addItem(tr("heuristic protocols"), QVariant::fromValue(EnabledProtocolItem::Heuristic)); fillTree(); } EnabledProtocolsDialog::~EnabledProtocolsDialog() { delete ui; delete proxyModel_; delete enabled_protocols_model_; } void EnabledProtocolsDialog::fillTree() { enabled_protocols_model_->populate(); //it's recommended to sort after list is populated proxyModel_->sort(EnabledProtocolsModel::colProtocol); ui->protocol_tree_->expandAll(); } void EnabledProtocolsDialog::on_invert_button__clicked() { proxyModel_->setItemsEnable(EnabledProtocolsProxyModel::Invert); ui->protocol_tree_->expandAll(); } void EnabledProtocolsDialog::on_enable_all_button__clicked() { proxyModel_->setItemsEnable(EnabledProtocolsProxyModel::Enable); ui->protocol_tree_->expandAll(); } void EnabledProtocolsDialog::on_disable_all_button__clicked() { proxyModel_->setItemsEnable(EnabledProtocolsProxyModel::Disable); ui->protocol_tree_->expandAll(); } void EnabledProtocolsDialog::searchFilterChange() { EnabledProtocolsProxyModel::SearchType type = EnabledProtocolsProxyModel::EveryWhere; EnabledProtocolItem::EnableProtocolType protocol = EnabledProtocolItem::Any; QString search_re = ui->search_line_edit_->text(); if (ui->cmbSearchType->currentData().canConvert<EnabledProtocolsProxyModel::SearchType>()) type = ui->cmbSearchType->currentData().value<EnabledProtocolsProxyModel::SearchType>(); if (ui->cmbProtocolType->currentData().canConvert<EnabledProtocolItem::EnableProtocolType>()) protocol = ui->cmbProtocolType->currentData().value<EnabledProtocolItem::EnableProtocolType>(); proxyModel_->setFilter(search_re, type, protocol); /* If items are filtered out, then filtered back in, the tree remains collapsed Force an expansion */ ui->protocol_tree_->expandAll(); } void EnabledProtocolsDialog::on_search_line_edit__textChanged(const QString &) { searchFilterChange(); } void EnabledProtocolsDialog::on_cmbSearchType_currentIndexChanged(int) { searchFilterChange(); } void EnabledProtocolsDialog::on_cmbProtocolType_currentIndexChanged(int) { searchFilterChange(); } void EnabledProtocolsDialog::on_buttonBox_accepted() { enabled_protocols_model_->applyChanges(); } void EnabledProtocolsDialog::on_buttonBox_helpRequested() { mainApp->helpTopicAction(HELP_ENABLED_PROTOCOLS_DIALOG); }
C/C++
wireshark/ui/qt/enabled_protocols_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef ENABLED_PROTOCOLS_DIALOG_H #define ENABLED_PROTOCOLS_DIALOG_H #include "geometry_state_dialog.h" #include "wireshark_dialog.h" #include <ui/qt/models/enabled_protocols_model.h> namespace Ui { class EnabledProtocolsDialog; } class EnabledProtocolsDialog : public GeometryStateDialog { Q_OBJECT public: explicit EnabledProtocolsDialog(QWidget *parent); virtual ~EnabledProtocolsDialog(); private slots: void on_invert_button__clicked(); void on_enable_all_button__clicked(); void on_disable_all_button__clicked(); void on_search_line_edit__textChanged(const QString &); void on_cmbSearchType_currentIndexChanged(int); void on_cmbProtocolType_currentIndexChanged(int); void on_buttonBox_accepted(); void on_buttonBox_helpRequested(); void fillTree(); private: Ui::EnabledProtocolsDialog *ui; EnabledProtocolsModel* enabled_protocols_model_; EnabledProtocolsProxyModel* proxyModel_; void searchFilterChange(); }; #endif // ENABLED_PROTOCOLS_DIALOG_H
User Interface
wireshark/ui/qt/enabled_protocols_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>EnabledProtocolsDialog</class> <widget class="QDialog" name="EnabledProtocolsDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>987</width> <height>595</height> </rect> </property> <property name="windowTitle"> <string>Dialog</string> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <layout class="QHBoxLayout" name="horizontalLayout_2"> <item> <widget class="QLabel" name="label"> <property name="text"> <string>Search:</string> </property> </widget> </item> <item> <widget class="QLineEdit" name="search_line_edit_"/> </item> <item> <widget class="QComboBox" name="cmbSearchType"/> </item> <item> <widget class="QLabel" name="label_2"> <property name="text"> <string>in</string> </property> </widget> </item> <item> <widget class="QComboBox" name="cmbProtocolType"/> </item> </layout> </item> <item> <widget class="QTreeView" name="protocol_tree_"> <property name="sortingEnabled"> <bool>true</bool> </property> </widget> </item> <item> <widget class="QLabel" name="disable_notice_text_"> <property name="text"> <string>&lt;small&gt;&lt;i&gt;Disabling a protocol prevents higher layer protocols from being displayed&lt;/i&gt;&lt;/small&gt;</string> </property> <property name="alignment"> <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set> </property> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <widget class="QPushButton" name="enable_all_button_"> <property name="text"> <string>Enable All</string> </property> </widget> </item> <item> <widget class="QPushButton" name="disable_all_button_"> <property name="text"> <string>Disable All</string> </property> </widget> </item> <item> <widget class="QPushButton" name="invert_button_"> <property name="text"> <string>Invert</string> </property> </widget> </item> <item> <spacer name="horizontalSpacer"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>20</height> </size> </property> </spacer> </item> </layout> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Cancel|QDialogButtonBox::Help|QDialogButtonBox::Ok</set> </property> </widget> </item> </layout> </widget> <resources/> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>EnabledProtocolsDialog</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>6</x> <y>559</y> </hint> <hint type="destinationlabel"> <x>157</x> <y>274</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>EnabledProtocolsDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>32</x> <y>559</y> </hint> <hint type="destinationlabel"> <x>286</x> <y>274</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/endpoint_dialog.cpp
/* endpoint_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "endpoint_dialog.h" #include <epan/maxmind_db.h> #include <epan/prefs.h> #include <epan/to_str.h> #include "ui/recent.h" #include "wsutil/filesystem.h" #include "wsutil/file_util.h" #include "wsutil/pint.h" #include "wsutil/str_util.h" #include <wsutil/utf8_entities.h> #include <ui/qt/utils/qt_ui_utils.h> #include <ui/qt/utils/variant_pointer.h> #include <ui/qt/widgets/wireshark_file_dialog.h> #include <ui/qt/widgets/traffic_tab.h> #include <ui/qt/widgets/traffic_types_list.h> #include "main_application.h" #include <QCheckBox> #include <QDesktopServices> #include <QDialogButtonBox> #include <QMessageBox> #include <QPushButton> #include <QUrl> #include <QTemporaryFile> #include <QTreeView> #include <QSortFilterProxyModel> typedef enum { ENDP_COLUMN_ADDR, ENDP_COLUMN_PORT, ENDP_COLUMN_PACKETS, ENDP_COLUMN_BYTES, ENDP_COLUMN_PKT_AB, ENDP_COLUMN_BYTES_AB, ENDP_COLUMN_PKT_BA, ENDP_COLUMN_BYTES_BA, ENDP_NUM_COLUMNS, ENDP_COLUMN_GEO_COUNTRY = ENDP_NUM_COLUMNS, ENDP_COLUMN_GEO_CITY, ENDP_COLUMN_GEO_AS_NUM, ENDP_COLUMN_GEO_AS_ORG, ENDP_NUM_GEO_COLUMNS } endpoint_column_type_e; static const QString table_name_ = QObject::tr("Endpoint"); static ATapDataModel * createModel(int protoId, QString filter) { return new EndpointDataModel(protoId, filter); } EndpointDialog::EndpointDialog(QWidget &parent, CaptureFile &cf) : TrafficTableDialog(parent, cf, table_name_) { trafficList()->setProtocolInfo(table_name_, &(recent.endpoint_tabs)); trafficTab()->setProtocolInfo(table_name_, trafficList(), &(recent.endpoint_tabs_columns), &createModel); trafficTab()->setFilter(cf.displayFilter()); connect(trafficTab(), &TrafficTab::filterAction, this, &EndpointDialog::filterAction); connect(trafficTab()->tabBar(), &QTabBar::currentChanged, this, &EndpointDialog::tabChanged); connect(trafficTab(), &TrafficTab::tabDataChanged, this, &EndpointDialog::tabChanged); #ifdef HAVE_MAXMINDDB map_bt_ = buttonBox()->addButton(tr("Map"), QDialogButtonBox::ActionRole); map_bt_->setToolTip(tr("Draw IPv4 or IPv6 endpoints on a map.")); QMenu *map_menu_ = new QMenu(map_bt_); QAction *action; action = map_menu_->addAction(tr("Open in browser")); connect(action, &QAction::triggered, this, &EndpointDialog::openMap); action = map_menu_->addAction(tr("Save As…")); connect(action, &QAction::triggered, this, &EndpointDialog::saveMap); map_bt_->setMenu(map_menu_); #endif updateWidgets(); } void EndpointDialog::captureFileClosing() { trafficTab()->disableTap(); displayFilterCheckBox()->setEnabled(false); TrafficTableDialog::captureFileClosing(); } void EndpointDialog::tabChanged(int idx) { #ifdef HAVE_MAXMINDDB if (idx == trafficTab()->currentIndex()) { bool geoIp = trafficTab()->hasGeoIPData(idx); map_bt_->setEnabled(geoIp); } #else Q_UNUSED(idx); #endif TrafficTableDialog::currentTabChanged(); } #ifdef HAVE_MAXMINDDB void EndpointDialog::openMap() { QUrl map_file = trafficTab()->createGeoIPMap(false); if (!map_file.isEmpty()) { QDesktopServices::openUrl(map_file); } } void EndpointDialog::saveMap() { QString destination_file = WiresharkFileDialog::getSaveFileName(this, tr("Save Endpoints Map"), "ipmap.html", "HTML files (*.html);;GeoJSON files (*.json)"); if (destination_file.isEmpty()) { return; } QUrl map_file = trafficTab()->createGeoIPMap(destination_file.endsWith(".json")); if (!map_file.isEmpty()) { QString source_file = map_file.toLocalFile(); QFile::remove(destination_file); if (!QFile::rename(source_file, destination_file)) { QMessageBox::warning(this, tr("Map file error"), tr("Failed to save map file %1.").arg(destination_file)); QFile::remove(source_file); } } } #endif void EndpointDialog::on_buttonBox_helpRequested() { mainApp->helpTopicAction(HELP_STATS_ENDPOINTS_DIALOG); } void init_endpoint_table(struct register_ct* ct, const char *filter) { mainApp->emitStatCommandSignal("Endpoints", filter, GINT_TO_POINTER(get_conversation_proto_id(ct))); }
C/C++
wireshark/ui/qt/endpoint_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef ENDPOINT_DIALOG_H #define ENDPOINT_DIALOG_H #include <QFile> #include "traffic_table_dialog.h" #include <ui/qt/models/atap_data_model.h> class EndpointDialog : public TrafficTableDialog { Q_OBJECT public: /** Create a new endpoint window. * * @param parent Parent widget. * @param cf Capture file. No statistics will be calculated if this is NULL. */ explicit EndpointDialog(QWidget &parent, CaptureFile &cf); signals: protected: void captureFileClosing(); private: #ifdef HAVE_MAXMINDDB QPushButton * map_bt_; #endif private slots: #ifdef HAVE_MAXMINDDB void openMap(); void saveMap(); #endif void tabChanged(int idx); void on_buttonBox_helpRequested(); }; void init_endpoint_table(struct register_ct* ct, const char *filter); #endif // ENDPOINT_DIALOG_H
C++
wireshark/ui/qt/expert_info_dialog.cpp
/* expert_info_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "expert_info_dialog.h" #include <ui_expert_info_dialog.h> #include "file.h" #include <epan/epan_dissect.h> #include <epan/expert.h> #include <epan/stat_tap_ui.h> #include <epan/tap.h> #include "progress_frame.h" #include "main_application.h" #include <QAction> #include <QHash> #include <QMenu> #include <QMessageBox> #include <QPushButton> // To do: // - Test with custom expert levels (Preferences -> Expert). // - Test with large captures. // - Promote to a fourth pane in the main window? // - Make colors configurable? In theory we could condense image/expert_indicators.svg, // down to one item, make sure it uses a single (or a few) base color(s), and generate // icons on the fly. ExpertInfoDialog::ExpertInfoDialog(QWidget &parent, CaptureFile &capture_file, QString displayFilter) : WiresharkDialog(parent, capture_file), ui(new Ui::ExpertInfoDialog), expert_info_model_(new ExpertInfoModel(capture_file)), proxyModel_(new ExpertInfoProxyModel(this)), display_filter_(displayFilter) { ui->setupUi(this); ui->hintLabel->setSmallText(); ui->limitCheckBox->setChecked(! display_filter_.isEmpty()); connect(ui->limitCheckBox, &QCheckBox::toggled, this, &ExpertInfoDialog::limitCheckBoxToggled); proxyModel_->setSourceModel(expert_info_model_); ui->expertInfoTreeView->setModel(proxyModel_); setWindowSubtitle(tr("Expert Information")); // Clicking on an item jumps to its associated packet. Make the dialog // narrow so that we avoid obscuring the packet list. int dlg_width = parent.width() * 3 / 5; if (dlg_width < width()) dlg_width = width(); loadGeometry(dlg_width, parent.height()); int one_em = fontMetrics().height(); ui->expertInfoTreeView->setColumnWidth(ExpertInfoProxyModel::colProxySummary, one_em * 25); // Arbitrary //Unfortunately this has to be done manually and not through .ui ui->severitiesPushButton->setMenu(ui->menuShowExpert); ui->expertInfoTreeView->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->expertInfoTreeView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(showExpertInfoMenu(QPoint))); QMenu *submenu; FilterAction::Action cur_action = FilterAction::ActionApply; submenu = ctx_menu_.addMenu(FilterAction::actionName(cur_action)); foreach (FilterAction::ActionType at, FilterAction::actionTypes()) { FilterAction *fa = new FilterAction(submenu, cur_action, at); submenu->addAction(fa); connect(fa, SIGNAL(triggered()), this, SLOT(filterActionTriggered())); } cur_action = FilterAction::ActionPrepare; submenu = ctx_menu_.addMenu(FilterAction::actionName(cur_action)); foreach (FilterAction::ActionType at, FilterAction::actionTypes()) { FilterAction *fa = new FilterAction(submenu, cur_action, at); submenu->addAction(fa); connect(fa, SIGNAL(triggered()), this, SLOT(filterActionTriggered())); } FilterAction *fa; QList<FilterAction::Action> extra_actions = QList<FilterAction::Action>() << FilterAction::ActionFind << FilterAction::ActionColorize << FilterAction::ActionWebLookup << FilterAction::ActionCopy; foreach (FilterAction::Action extra_action, extra_actions) { fa = new FilterAction(&ctx_menu_, extra_action); ctx_menu_.addAction(fa); connect(fa, SIGNAL(triggered()), this, SLOT(filterActionTriggered())); } //Add collapse/expand all menu options QAction *collapse = new QAction(tr("Collapse All"), this); ctx_menu_.addAction(collapse); connect(collapse, SIGNAL(triggered()), this, SLOT(collapseTree())); QAction *expand = new QAction(tr("Expand All"), this); ctx_menu_.addAction(expand); connect(expand, SIGNAL(triggered()), this, SLOT(expandTree())); connect(&cap_file_, SIGNAL(captureEvent(CaptureEvent)), this, SLOT(captureEvent(CaptureEvent))); ProgressFrame::addToButtonBox(ui->buttonBox, &parent); updateWidgets(); QTimer::singleShot(0, this, SLOT(retapPackets())); } ExpertInfoDialog::~ExpertInfoDialog() { delete ui; delete proxyModel_; delete expert_info_model_; } void ExpertInfoDialog::clearAllData() { expert_info_model_->clear(); } ExpertInfoTreeView* ExpertInfoDialog::getExpertInfoView() { return ui->expertInfoTreeView; } void ExpertInfoDialog::retapPackets() { if (file_closed_) return; clearAllData(); removeTapListeners(); if (!registerTapListener("expert", expert_info_model_, ui->limitCheckBox->isChecked() ? display_filter_.toUtf8().constData(): NULL, TL_REQUIRES_COLUMNS, ExpertInfoModel::tapReset, ExpertInfoModel::tapPacket, ExpertInfoModel::tapDraw)) { return; } cap_file_.retapPackets(); } void ExpertInfoDialog::captureEvent(CaptureEvent e) { if (e.captureContext() == CaptureEvent::Retap) { switch (e.eventType()) { case CaptureEvent::Started: ui->limitCheckBox->setEnabled(false); ui->groupBySummaryCheckBox->setEnabled(false); break; case CaptureEvent::Finished: updateWidgets(); break; default: break; } } } void ExpertInfoDialog::updateWidgets() { ui->limitCheckBox->setEnabled(! file_closed_ && ! display_filter_.isEmpty()); ui->actionShowError->setEnabled(expert_info_model_->numEvents(ExpertInfoModel::severityError) > 0); ui->actionShowWarning->setEnabled(expert_info_model_->numEvents(ExpertInfoModel::severityWarn) > 0); ui->actionShowNote->setEnabled(expert_info_model_->numEvents(ExpertInfoModel::severityNote) > 0); ui->actionShowChat->setEnabled(expert_info_model_->numEvents(ExpertInfoModel::severityChat) > 0); ui->actionShowComment->setEnabled(expert_info_model_->numEvents(ExpertInfoModel::severityComment) > 0); QString tooltip; QString hint; if (file_closed_) { tooltip = tr("Capture file closed."); hint = tr("Capture file closed."); } else if (display_filter_.isEmpty()) { tooltip = tr("No display filter"); hint = tr("No display filter set."); } else { tooltip = tr("Limit information to \"%1\".").arg(display_filter_); hint = tr("Display filter: \"%1\"").arg(display_filter_); } ui->limitCheckBox->setToolTip(tooltip); ui->hintLabel->setText(hint); ui->groupBySummaryCheckBox->setEnabled(!file_closed_); } void ExpertInfoDialog::on_actionShowError_toggled(bool checked) { proxyModel_->setSeverityFilter(PI_ERROR, !checked); updateWidgets(); } void ExpertInfoDialog::on_actionShowWarning_toggled(bool checked) { proxyModel_->setSeverityFilter(PI_WARN, !checked); updateWidgets(); } void ExpertInfoDialog::on_actionShowNote_toggled(bool checked) { proxyModel_->setSeverityFilter(PI_NOTE, !checked); updateWidgets(); } void ExpertInfoDialog::on_actionShowChat_toggled(bool checked) { proxyModel_->setSeverityFilter(PI_CHAT, !checked); updateWidgets(); } void ExpertInfoDialog::on_actionShowComment_toggled(bool checked) { proxyModel_->setSeverityFilter(PI_COMMENT, !checked); updateWidgets(); } void ExpertInfoDialog::showExpertInfoMenu(QPoint pos) { bool enable = true; QModelIndex expertIndex = ui->expertInfoTreeView->indexAt(pos); if (!expertIndex.isValid()) { return; } if (proxyModel_->data(expertIndex.sibling(expertIndex.row(), ExpertInfoModel::colHf), Qt::DisplayRole).toInt() < 0) { enable = false; } foreach (QMenu *submenu, ctx_menu_.findChildren<QMenu*>()) { submenu->setEnabled(enable && !file_closed_); } foreach (QAction *action, ctx_menu_.actions()) { FilterAction *fa = qobject_cast<FilterAction *>(action); bool action_enable = enable && !file_closed_; if (fa && (fa->action() == FilterAction::ActionWebLookup || fa->action() == FilterAction::ActionCopy)) { action_enable = enable; } action->setEnabled(action_enable); } ctx_menu_.popup(ui->expertInfoTreeView->viewport()->mapToGlobal(pos)); } void ExpertInfoDialog::filterActionTriggered() { QModelIndex modelIndex = ui->expertInfoTreeView->currentIndex(); FilterAction *fa = qobject_cast<FilterAction *>(QObject::sender()); if (!fa || !modelIndex.isValid()) { return; } int hf_index = proxyModel_->data(modelIndex.sibling(modelIndex.row(), ExpertInfoModel::colHf), Qt::DisplayRole).toInt(); if (hf_index > -1) { QString filter_string; if (fa->action() == FilterAction::ActionWebLookup) { filter_string = QString("%1 %2") .arg(proxyModel_->data(modelIndex.sibling(modelIndex.row(), ExpertInfoModel::colProtocol), Qt::DisplayRole).toString()) .arg(proxyModel_->data(modelIndex.sibling(modelIndex.row(), ExpertInfoModel::colSummary), Qt::DisplayRole).toString()); } else if (fa->action() == FilterAction::ActionCopy) { filter_string = QString("%1 %2: %3") .arg(proxyModel_->data(modelIndex.sibling(modelIndex.row(), ExpertInfoModel::colPacket), Qt::DisplayRole).toUInt()) .arg(proxyModel_->data(modelIndex.sibling(modelIndex.row(), ExpertInfoModel::colProtocol), Qt::DisplayRole).toString()) .arg(proxyModel_->data(modelIndex.sibling(modelIndex.row(), ExpertInfoModel::colSummary), Qt::DisplayRole).toString()); } else { filter_string = proto_registrar_get_abbrev(hf_index); } if (! filter_string.isEmpty()) { emit filterAction(filter_string, fa->action(), fa->actionType()); } } } void ExpertInfoDialog::collapseTree() { ui->expertInfoTreeView->collapseAll(); } void ExpertInfoDialog::expandTree() { ui->expertInfoTreeView->expandAll(); } void ExpertInfoDialog::limitCheckBoxToggled(bool) { retapPackets(); } void ExpertInfoDialog::on_groupBySummaryCheckBox_toggled(bool) { expert_info_model_->setGroupBySummary(ui->groupBySummaryCheckBox->isChecked()); } // Show child (packet list) items that match the contents of searchLineEdit. void ExpertInfoDialog::on_searchLineEdit_textChanged(const QString &search_re) { proxyModel_->setSummaryFilter(search_re); } void ExpertInfoDialog::on_buttonBox_helpRequested() { mainApp->helpTopicAction(HELP_EXPERT_INFO_DIALOG); } // Stat command + args static void expert_info_init(const char *, void*) { mainApp->emitStatCommandSignal("ExpertInfo", NULL, NULL); } static stat_tap_ui expert_info_stat_ui = { REGISTER_STAT_GROUP_GENERIC, NULL, "expert", expert_info_init, 0, NULL }; extern "C" { void register_tap_listener_qt_expert_info(void); void register_tap_listener_qt_expert_info(void) { register_stat_tap_ui(&expert_info_stat_ui, NULL); } }
C/C++
wireshark/ui/qt/expert_info_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef EXPERT_INFO_DIALOG_H #define EXPERT_INFO_DIALOG_H #include <config.h> #include <glib.h> #include "filter_action.h" #include "wireshark_dialog.h" #include <ui/qt/models/expert_info_model.h> #include <ui/qt/models/expert_info_proxy_model.h> #include <ui/qt/widgets/expert_info_view.h> #include <QMenu> namespace Ui { class ExpertInfoDialog; } class ExpertInfoDialog : public WiresharkDialog { Q_OBJECT public: explicit ExpertInfoDialog(QWidget &parent, CaptureFile& capture_file, QString displayFilter); ~ExpertInfoDialog(); void clearAllData(); ExpertInfoTreeView* getExpertInfoView(); signals: void filterAction(QString filter, FilterAction::Action action, FilterAction::ActionType type); private: Ui::ExpertInfoDialog *ui; ExpertInfoModel* expert_info_model_; ExpertInfoProxyModel* proxyModel_; QMenu ctx_menu_; QString display_filter_; private slots: void retapPackets(); void captureEvent(CaptureEvent e); void updateWidgets(); void on_actionShowError_toggled(bool checked); void on_actionShowWarning_toggled(bool checked); void on_actionShowNote_toggled(bool checked); void on_actionShowChat_toggled(bool checked); void on_actionShowComment_toggled(bool checked); void showExpertInfoMenu(QPoint pos); void filterActionTriggered(); void collapseTree(); void expandTree(); void limitCheckBoxToggled(bool); void on_groupBySummaryCheckBox_toggled(bool); void on_searchLineEdit_textChanged(const QString &search_re); void on_buttonBox_helpRequested(); }; #endif // EXPERT_INFO_DIALOG_H
User Interface
wireshark/ui/qt/expert_info_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>ExpertInfoDialog</class> <widget class="QDialog" name="ExpertInfoDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>620</width> <height>540</height> </rect> </property> <property name="windowTitle"> <string>Dialog</string> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="ExpertInfoTreeView" name="expertInfoTreeView"> <property name="uniformRowHeights"> <bool>true</bool> </property> <property name="sortingEnabled"> <bool>true</bool> </property> </widget> </item> <item> <widget class="ElidedLabel" name="hintLabel"> <property name="text"> <string>&lt;small&gt;&lt;i&gt;A hint.&lt;/i&gt;&lt;/small&gt;</string> </property> </widget> </item> <item> <layout class="QHBoxLayout" name="horizontalLayout_2" stretch="0,0,0,0,0,1,0,0"> <item> <widget class="QCheckBox" name="limitCheckBox"> <property name="text"> <string>Limit to Display Filter</string> </property> </widget> </item> <item> <spacer name="horizontalSpacer_2"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>20</width> <height>20</height> </size> </property> </spacer> </item> <item> <widget class="QCheckBox" name="groupBySummaryCheckBox"> <property name="text"> <string>Group by summary</string> </property> <property name="checked"> <bool>true</bool> </property> </widget> </item> <item> <spacer name="horizontalSpacer"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>20</width> <height>10</height> </size> </property> </spacer> </item> <item> <widget class="QLabel" name="label"> <property name="toolTip"> <string>Search expert summaries.</string> </property> <property name="text"> <string>Search:</string> </property> </widget> </item> <item> <widget class="QLineEdit" name="searchLineEdit"> <property name="toolTip"> <string>Search expert summaries.</string> </property> </widget> </item> <item> <spacer name="horizontalSpacer_3"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>40</width> <height>10</height> </size> </property> </spacer> </item> <item> <widget class="QPushButton" name="severitiesPushButton"> <property name="text"> <string>Show…</string> </property> <widget class="QMenu" name="menuShowExpert"> <addaction name="actionShowError"/> <addaction name="actionShowWarning"/> <addaction name="actionShowChat"/> <addaction name="actionShowNote"/> <addaction name="actionShowComment"/> </widget> </widget> </item> </layout> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Close|QDialogButtonBox::Help</set> </property> </widget> </item> </layout> <action name="actionShowError"> <property name="checkable"> <bool>true</bool> </property> <property name="checked"> <bool>true</bool> </property> <property name="text"> <string>Error</string> </property> <property name="toolTip"> <string>Show error packets.</string> </property> </action> <action name="actionShowWarning"> <property name="checkable"> <bool>true</bool> </property> <property name="checked"> <bool>true</bool> </property> <property name="text"> <string>Warning</string> </property> <property name="toolTip"> <string>Show warning packets.</string> </property> </action> <action name="actionShowNote"> <property name="checkable"> <bool>true</bool> </property> <property name="checked"> <bool>true</bool> </property> <property name="text"> <string>Note</string> </property> <property name="toolTip"> <string>Show note packets.</string> </property> </action> <action name="actionShowChat"> <property name="checkable"> <bool>true</bool> </property> <property name="checked"> <bool>true</bool> </property> <property name="text"> <string>Chat</string> </property> <property name="toolTip"> <string>Show chat packets.</string> </property> </action> <action name="actionShowComment"> <property name="checkable"> <bool>true</bool> </property> <property name="checked"> <bool>true</bool> </property> <property name="text"> <string>Comment</string> </property> <property name="toolTip"> <string>Show comment packets.</string> </property> </action> </widget> <customwidgets> <customwidget> <class>ElidedLabel</class> <extends>QLabel</extends> <header>widgets/elided_label.h</header> </customwidget> <customwidget> <class>ExpertInfoTreeView</class> <extends>QTreeView</extends> <header>widgets/expert_info_view.h</header> </customwidget> </customwidgets> <resources/> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>ExpertInfoDialog</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>248</x> <y>254</y> </hint> <hint type="destinationlabel"> <x>157</x> <y>274</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>ExpertInfoDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>316</x> <y>260</y> </hint> <hint type="destinationlabel"> <x>286</x> <y>274</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/export_dissection_dialog.cpp
/* export_dissection_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "export_dissection_dialog.h" #ifdef Q_OS_WIN #include <windows.h> #include "ui/packet_range.h" #include "ui/win32/file_dlg_win32.h" #else // Q_OS_WIN #include "ui/alert_box.h" #include "ui/help_url.h" #include "ui/util.h" #include <epan/print.h> #include <wsutil/filesystem.h> #include <ui/qt/utils/qt_ui_utils.h> #include <QDialogButtonBox> #include <QGridLayout> #include <QPushButton> #endif // Q_OS_WIN #include <epan/prefs.h> #include "main_application.h" #if !defined(Q_OS_WIN) static const QStringList export_extensions = QStringList() << "" << "txt" << "" << "csv" << "psml" << "pdml" << "c" << "json"; #endif ExportDissectionDialog::ExportDissectionDialog(QWidget *parent, capture_file *cap_file, export_type_e export_type, QString selRange): WiresharkFileDialog(parent), export_type_(export_type), cap_file_(cap_file) #if !defined(Q_OS_WIN) , save_bt_(NULL) #else , sel_range_(selRange) #endif /* Q_OS_WIN */ { setWindowTitle(mainApp->windowTitleString(tr("Export Packet Dissections"))); switch (prefs.gui_fileopen_style) { case FO_STYLE_LAST_OPENED: /* The user has specified that we should start out in the last directory * we looked in. If we've already opened a file, use its containing * directory, if we could determine it, as the directory, otherwise * use the "last opened" directory saved in the preferences file if * there was one. */ setDirectory(mainApp->lastOpenDir()); break; case FO_STYLE_SPECIFIED: /* The user has specified that we should always start out in a * specified directory; if they've specified that directory, * start out by showing the files in that dir. */ if (prefs.gui_fileopen_dir[0] != '\0') setDirectory(prefs.gui_fileopen_dir); break; } #if !defined(Q_OS_WIN) QDialogButtonBox *button_box = findChild<QDialogButtonBox *>(); // Add extra widgets // https://wiki.qt.io/Qt_project_org_faq#How_can_I_add_widgets_to_my_QFileDialog_instance.3F setOption(QFileDialog::DontUseNativeDialog, true); QGridLayout *fd_grid = qobject_cast<QGridLayout*>(layout()); QHBoxLayout *h_box = new QHBoxLayout(); QStringList name_filters; int last_row; setAcceptMode(QFileDialog::AcceptSave); setLabelText(FileType, tr("Export As:")); // export_type_map_keys() sorts alphabetically. We don't want that. name_filters << tr("Plain text (*.txt)") << tr("Comma Separated Values - summary (*.csv)") << tr("PSML - summary (*.psml, *.xml)") << tr("PDML - details (*.pdml, *.xml)") << tr("JSON (*.json)") << tr("C Arrays - bytes (*.c, *.h)"); export_type_map_[name_filters[0]] = export_type_text; export_type_map_[name_filters[1]] = export_type_csv; export_type_map_[name_filters[2]] = export_type_psml; export_type_map_[name_filters[3]] = export_type_pdml; export_type_map_[name_filters[4]] = export_type_json; export_type_map_[name_filters[5]] = export_type_carrays; setNameFilters(name_filters); selectNameFilter(export_type_map_.key(export_type)); exportTypeChanged(export_type_map_.key(export_type)); last_row = fd_grid->rowCount(); fd_grid->addItem(new QSpacerItem(1, 1), last_row, 0); fd_grid->addLayout(h_box, last_row, 1); print_args_.file = NULL; /* Init the export range */ packet_range_init(&print_args_.range, cap_file_); /* Default to displayed packets */ print_args_.range.process_filtered = TRUE; packet_range_group_box_.initRange(&print_args_.range, selRange); h_box->addWidget(&packet_range_group_box_); h_box->addWidget(&packet_format_group_box_, 0, Qt::AlignTop); if (button_box) { button_box->addButton(QDialogButtonBox::Help); connect(button_box, SIGNAL(helpRequested()), this, SLOT(on_buttonBox_helpRequested())); save_bt_ = button_box->button(QDialogButtonBox::Save); } if (save_bt_) { connect(&packet_range_group_box_, SIGNAL(validityChanged(bool)), this, SLOT(checkValidity())); connect(&packet_format_group_box_, SIGNAL(formatChanged()), this, SLOT(checkValidity())); } connect(this, SIGNAL(filterSelected(QString)), this, SLOT(exportTypeChanged(QString))); // Grow the dialog to account for the extra widgets. resize(width(), height() + (packet_range_group_box_.height() * 2 / 3)); connect(this, SIGNAL(filesSelected(QStringList)), this, SLOT(dialogAccepted(QStringList))); #else // Q_OS_WIN #endif // Q_OS_WIN } ExportDissectionDialog::~ExportDissectionDialog() { #if !defined(Q_OS_WIN) g_free(print_args_.file); packet_range_cleanup(&print_args_.range); #endif } void ExportDissectionDialog::show() { #if !defined(Q_OS_WIN) if (cap_file_) { WiresharkFileDialog::show(); } #else // Q_OS_WIN win32_export_file((HWND)parentWidget()->effectiveWinId(), windowTitle().toStdWString().c_str(), cap_file_, export_type_, sel_range_.toStdString().c_str()); #endif // Q_OS_WIN } #ifndef Q_OS_WIN void ExportDissectionDialog::dialogAccepted(const QStringList &selected) { if (selected.length() > 0) { cf_print_status_t status; QString file_name = selected[0]; /* Fill in our print (and export) args */ print_args_.file = qstring_strdup(file_name); print_args_.format = PR_FMT_TEXT; print_args_.to_file = TRUE; print_args_.cmd = NULL; print_args_.print_summary = TRUE; print_args_.print_col_headings = TRUE; print_args_.print_dissections = print_dissections_as_displayed; print_args_.print_hex = FALSE; print_args_.print_formfeed = FALSE; switch (export_type_) { case export_type_text: /* Text */ print_args_.print_summary = packet_format_group_box_.summaryEnabled(); print_args_.print_col_headings = packet_format_group_box_.includeColumnHeadingsEnabled(); print_args_.print_dissections = print_dissections_none; if (packet_format_group_box_.detailsEnabled()) { if (packet_format_group_box_.allCollapsedEnabled()) print_args_.print_dissections = print_dissections_collapsed; else if (packet_format_group_box_.asDisplayedEnabled()) print_args_.print_dissections = print_dissections_as_displayed; else if (packet_format_group_box_.allExpandedEnabled()) print_args_.print_dissections = print_dissections_expanded; } print_args_.print_hex = packet_format_group_box_.bytesEnabled(); print_args_.hexdump_options = packet_format_group_box_.getHexdumpOptions(); print_args_.stream = print_stream_text_new(TRUE, print_args_.file); if (print_args_.stream == NULL) { open_failure_alert_box(print_args_.file, errno, TRUE); return; } status = cf_print_packets(cap_file_, &print_args_, TRUE); break; case export_type_csv: /* CSV */ status = cf_write_csv_packets(cap_file_, &print_args_); break; case export_type_carrays: /* C Arrays */ status = cf_write_carrays_packets(cap_file_, &print_args_); break; case export_type_psml: /* PSML */ status = cf_write_psml_packets(cap_file_, &print_args_); break; case export_type_pdml: /* PDML */ status = cf_write_pdml_packets(cap_file_, &print_args_); break; case export_type_json: /* JSON */ status = cf_write_json_packets(cap_file_, &print_args_); break; default: return; } switch (status) { case CF_PRINT_OK: break; case CF_PRINT_OPEN_ERROR: open_failure_alert_box(print_args_.file, errno, TRUE); break; case CF_PRINT_WRITE_ERROR: write_failure_alert_box(print_args_.file, errno); break; } gchar *dirname; /* Save the directory name for future file dialogs. */ dirname = get_dirname(print_args_.file); /* Overwrites file_name data */ set_last_open_dir(dirname); } } void ExportDissectionDialog::exportTypeChanged(QString name_filter) { export_type_ = export_type_map_.value(name_filter); if (export_type_ == export_type_text) { packet_format_group_box_.setEnabled(true); print_args_.format = PR_FMT_TEXT; } else { packet_format_group_box_.setEnabled(false); } checkValidity(); setDefaultSuffix(export_extensions[export_type_]); } void ExportDissectionDialog::checkValidity() { bool enable = true; if (!save_bt_) return; if (!packet_range_group_box_.isValid()) enable = false; if (export_type_ == export_type_text) { if (! packet_format_group_box_.summaryEnabled() && ! packet_format_group_box_.detailsEnabled() && ! packet_format_group_box_.bytesEnabled()) { enable = false; } } save_bt_->setEnabled(enable); } void ExportDissectionDialog::on_buttonBox_helpRequested() { mainApp->helpTopicAction(HELP_EXPORT_FILE_DIALOG); } #endif // Q_OS_WIN
C/C++
wireshark/ui/qt/export_dissection_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef EXPORT_DISSECTION_DIALOG_H #define EXPORT_DISSECTION_DIALOG_H #include <config.h> #include <glib.h> #include "file.h" #include "epan/print.h" #include "ui/file_dialog.h" #include <ui/qt/widgets/wireshark_file_dialog.h> #ifndef Q_OS_WIN #include "packet_range_group_box.h" #include "packet_format_group_box.h" #endif // Q_OS_WIN #include <QMap> class ExportDissectionDialog : public WiresharkFileDialog { Q_OBJECT public: explicit ExportDissectionDialog(QWidget *parent, capture_file *cap_file, export_type_e export_type, QString selRange = QString()); ~ExportDissectionDialog(); public slots: void show(); private slots: #ifndef Q_OS_WIN void dialogAccepted(const QStringList &selected); void exportTypeChanged(QString name_filter); void checkValidity(); void on_buttonBox_helpRequested(); #endif // Q_OS_WIN private: export_type_e export_type_; capture_file *cap_file_; #ifndef Q_OS_WIN print_args_t print_args_; QMap<QString, export_type_e> export_type_map_; PacketRangeGroupBox packet_range_group_box_; PacketFormatGroupBox packet_format_group_box_; QPushButton *save_bt_; #else QString sel_range_; #endif // Q_OS_WIN }; #endif // EXPORT_DISSECTION_DIALOG_H
C++
wireshark/ui/qt/export_object_action.cpp
/* conversation_colorize_action.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include <config.h> #include <glib.h> #include <epan/packet_info.h> #include <epan/proto_data.h> #include <epan/packet.h> #include <wsutil/utf8_entities.h> #include "export_object_action.h" #include <QMenu> #include <ui/qt/utils/qt_ui_utils.h> ExportObjectAction::ExportObjectAction(QObject *parent, register_eo_t *eo) : QAction(parent), eo_(eo) { if (eo_) { setText(QString("%1%2").arg(proto_get_protocol_short_name(find_protocol_by_id(get_eo_proto_id(eo)))).arg(UTF8_HORIZONTAL_ELLIPSIS)); } } void ExportObjectAction::captureFileEvent(CaptureEvent e) { if (e.captureContext() == CaptureEvent::File) { if (e.eventType() == CaptureEvent::Opened) setEnabled(true); else if (e.eventType() == CaptureEvent::Closed) setEnabled(false); } }
C/C++
wireshark/ui/qt/export_object_action.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef EXPORTOBJECTACTION_H #define EXPORTOBJECTACTION_H #include "config.h" #include <glib.h> #include <epan/packet_info.h> #include <epan/export_object.h> #include <QAction> #include <ui/qt/capture_file.h> // Actions for "Export Objects" menu items. class ExportObjectAction : public QAction { Q_OBJECT public: ExportObjectAction(QObject *parent, register_eo_t *eo = NULL); register_eo_t* exportObject() {return eo_;} public slots: void captureFileEvent(CaptureEvent e); private: register_eo_t *eo_; }; #endif // EXPORTOBJECTACTION_H
C++
wireshark/ui/qt/export_object_dialog.cpp
/* export_object_dialog.cpp * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "export_object_dialog.h" #include <ui_export_object_dialog.h> #include <ui/alert_box.h> #include <wsutil/utf8_entities.h> #include "main_application.h" #include "ui/qt/widgets/wireshark_file_dialog.h" #include <ui/qt/widgets/export_objects_view.h> #include <ui/qt/models/export_objects_model.h> #include <ui/qt/utils/qt_ui_utils.h> #include <QDialogButtonBox> #include <QMessageBox> #include <QMimeDatabase> #include <QPushButton> #include <QComboBox> #include <QDir> #include <QFile> #include <QFileInfo> #include <QDesktopServices> ExportObjectDialog::ExportObjectDialog(QWidget &parent, CaptureFile &cf, register_eo_t* eo) : WiresharkDialog(parent, cf), eo_ui_(new Ui::ExportObjectDialog), save_bt_(NULL), save_all_bt_(NULL), model_(eo, this), proxyModel_(this) { QPushButton *close_bt; eo_ui_->setupUi(this); setAttribute(Qt::WA_DeleteOnClose, true); proxyModel_.setSourceModel(&model_); eo_ui_->objectTree->setModel(&proxyModel_); proxyModel_.setFilterFixedString(""); proxyModel_.setFilterCaseSensitivity(Qt::CaseInsensitive); proxyModel_.setFilterKeyColumn(-1); #if defined(Q_OS_MAC) eo_ui_->progressLabel->setAttribute(Qt::WA_MacSmallSize, true); eo_ui_->progressBar->setAttribute(Qt::WA_MacSmallSize, true); #endif connect(&model_, &ExportObjectModel::rowsInserted, this, &ExportObjectDialog::modelDataChanged); connect(&model_, &ExportObjectModel::modelReset, this, &ExportObjectDialog::modelRowsReset); connect(eo_ui_->filterLine, &QLineEdit::textChanged, &proxyModel_, &ExportObjectProxyModel::setTextFilterString); connect(eo_ui_->objectTree, &ExportObjectsTreeView::currentIndexChanged, this, &ExportObjectDialog::currentHasChanged); save_bt_ = eo_ui_->buttonBox->button(QDialogButtonBox::Save); save_all_bt_ = eo_ui_->buttonBox->button(QDialogButtonBox::SaveAll); close_bt = eo_ui_->buttonBox->button(QDialogButtonBox::Close); if (eo_ui_->buttonBox->button(QDialogButtonBox::Open)) { QPushButton * open = eo_ui_->buttonBox->button(QDialogButtonBox::Open); open->setText(tr("Preview")); open->setEnabled(false); } contentTypes << tr("All Content-Types"); eo_ui_->cmbContentType->addItems(contentTypes); setWindowTitle(mainApp->windowTitleString(QStringList() << tr("Export") << tr("%1 object list").arg(proto_get_protocol_short_name(find_protocol_by_id(get_eo_proto_id(eo)))))); if (save_bt_) save_bt_->setEnabled(false); if (save_all_bt_) save_all_bt_->setEnabled(false); if (close_bt) close_bt->setDefault(true); connect(&cap_file_, &CaptureFile::captureEvent, this, &ExportObjectDialog::captureEvent); } ExportObjectDialog::~ExportObjectDialog() { delete eo_ui_; model_.removeTap(); removeTapListeners(); } void ExportObjectDialog::currentHasChanged(QModelIndex current) { if (current.isValid()) { QModelIndex sibl = current.sibling(current.row(), ExportObjectModel::colPacket); if (eo_ui_->buttonBox->button(QDialogButtonBox::Open)) { QString mime_type = sibl.sibling(current.row(), ExportObjectModel::colContent).data().toString(); eo_ui_->buttonBox->button(QDialogButtonBox::Open)->setEnabled(mimeTypeIsPreviewable(mime_type)); } mainApp->gotoFrame(sibl.data().toInt()); } } bool ExportObjectDialog::mimeTypeIsPreviewable(QString mime_type) { // XXX This excludes everything except HTTP. Maybe that's a good thing? // Take care when adding to this, e.g. text/html or image/svg might contain JavaScript. QStringList previewable_mime_types = QStringList() << "text/plain" << "image/gif" << "image/jpeg" << "image/png"; if (previewable_mime_types.contains(mime_type)) { return true; } return false; } void ExportObjectDialog::modelDataChanged(const QModelIndex&, int from, int to) { bool contentTypes_changed = false; bool enabled = (model_.rowCount() > 0); if (save_bt_) save_bt_->setEnabled(enabled); if (save_all_bt_) save_all_bt_->setEnabled(enabled); for (int row = from; row <= to; row++) { QModelIndex idx = model_.index(row, ExportObjectModel::colContent); if (idx.isValid()) { QString dataType = idx.data().toString(); if (dataType.length() > 0 && ! contentTypes.contains(dataType)) { contentTypes << dataType; contentTypes_changed = true; } } } if (contentTypes_changed) { contentTypes.sort(Qt::CaseInsensitive); QString selType = eo_ui_->cmbContentType->currentText(); eo_ui_->cmbContentType->clear(); eo_ui_->cmbContentType->addItem(tr("All Content-Types")); eo_ui_->cmbContentType->addItems(contentTypes); if (contentTypes.contains(selType) ) eo_ui_->cmbContentType->setCurrentText(selType); } } void ExportObjectDialog::modelRowsReset() { contentTypes.clear(); eo_ui_->cmbContentType->clear(); eo_ui_->cmbContentType->addItem(tr("All Content-Types")); if (save_bt_) save_bt_->setEnabled(false); if (save_all_bt_) save_all_bt_->setEnabled(false); } void ExportObjectDialog::show() { /* Data will be gathered via a tap callback */ if (!registerTapListener(model_.getTapListenerName(), model_.getTapData(), NULL, 0, ExportObjectModel::resetTap, model_.getTapPacketFunc(), NULL)) { return; } QDialog::show(); cap_file_.retapPackets(); eo_ui_->progressFrame->hide(); for (int i = 0; i < eo_ui_->objectTree->model()->columnCount(); i++) eo_ui_->objectTree->resizeColumnToContents(i); eo_ui_->objectTree->sortByColumn(ExportObjectModel::colPacket, Qt::AscendingOrder); } void ExportObjectDialog::keyPressEvent(QKeyEvent *evt) { if(evt->key() == Qt::Key_Enter || evt->key() == Qt::Key_Return) return; QDialog::keyPressEvent(evt); } void ExportObjectDialog::accept() { // Don't close the dialog. } void ExportObjectDialog::captureEvent(CaptureEvent e) { if ((e.captureContext() == CaptureEvent::File) && (e.eventType() == CaptureEvent::Closing)) { close(); } } void ExportObjectDialog::on_buttonBox_helpRequested() { mainApp->helpTopicAction(HELP_EXPORT_OBJECT_LIST); } void ExportObjectDialog::on_buttonBox_clicked(QAbstractButton *button) { switch (eo_ui_->buttonBox->standardButton(button)) { case QDialogButtonBox::Save: saveCurrentEntry(); break; case QDialogButtonBox::SaveAll: saveAllEntries(); break; case QDialogButtonBox::Open: { QString temp; saveCurrentEntry(&temp); if (temp.length() > 0) { QMimeDatabase mime_db; QMimeType mime_type = mime_db.mimeTypeForFile(temp, QMimeDatabase::MatchContent); if (mimeTypeIsPreviewable(mime_type.name())) { QDesktopServices::openUrl(QUrl(QString("file:///").append(temp), QUrl::TolerantMode)); } else { desktop_show_in_folder(temp); } } break; } default: // Help, Cancel break; } } void ExportObjectDialog::on_cmbContentType_currentIndexChanged(int index) { QString filterString = index <= 0 ? "" : eo_ui_->cmbContentType->currentText(); proxyModel_.setContentFilterString(filterString); } void ExportObjectDialog::saveCurrentEntry(QString *tempFile) { QDir path(mainApp->lastOpenDir()); QModelIndex proxyIndex = eo_ui_->objectTree->currentIndex(); if (!proxyIndex.isValid()) return; QModelIndex current = proxyModel_.mapToSource(proxyIndex); if (!current.isValid()) return; QString entry_filename = current.sibling(current.row(), ExportObjectModel::colFilename).data().toString(); if (entry_filename.isEmpty()) return; QString file_name; if (!tempFile) { GString *safe_filename = eo_massage_str(entry_filename.toUtf8().constData(), EXPORT_OBJECT_MAXFILELEN, 0); file_name = WiresharkFileDialog::getSaveFileName(this, mainApp->windowTitleString(tr("Save Object As…")), safe_filename->str); g_string_free(safe_filename, TRUE); } else { QString path = QDir::tempPath().append("/").append(entry_filename); /* This means, the system must remove the file! */ file_name = path; if (QFileInfo::exists(path)) QFile::remove(path); *tempFile = path; } model_.saveEntry(current, file_name); } void ExportObjectDialog::saveAllEntries() { QDir save_in_dir(mainApp->lastOpenDir()); QString save_in_path; // // We want the user to be able to specify a directory in which // to drop files for all the objects, not a file name. // // XXX - what we *really* want is something that asks the user // for an existing directory *but* lets them create a new // directory in the process. That's what we get on macOS, // as the native dialog is used, and it supports that; does // that also work on Windows and with Qt's own dialog? // save_in_path = WiresharkFileDialog::getExistingDirectory(this, mainApp->windowTitleString(tr("Save All Objects In…")), save_in_dir.canonicalPath(), QFileDialog::ShowDirsOnly); if (save_in_path.length() < 1) return; model_.saveAllEntries(save_in_path); }
C/C++
wireshark/ui/qt/export_object_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef EXPORT_OBJECT_DIALOG_H #define EXPORT_OBJECT_DIALOG_H #include <config.h> #include <file.h> #include <ui/qt/models/export_objects_model.h> #include <ui/qt/widgets/export_objects_view.h> #include "wireshark_dialog.h" #include <QKeyEvent> class QTreeWidgetItem; class QAbstractButton; namespace Ui { class ExportObjectDialog; } class ExportObjectDialog : public WiresharkDialog { Q_OBJECT public: explicit ExportObjectDialog(QWidget &parent, CaptureFile &cf, register_eo_t* eo); ~ExportObjectDialog(); public slots: void show(); protected: virtual void keyPressEvent(QKeyEvent *evt); private slots: void accept(); void captureEvent(CaptureEvent e); void on_buttonBox_helpRequested(); void on_buttonBox_clicked(QAbstractButton *button); void on_cmbContentType_currentIndexChanged(int index); void modelDataChanged(const QModelIndex &topLeft, int from, int to); void modelRowsReset(); void currentHasChanged(QModelIndex current); private: bool mimeTypeIsPreviewable(QString mime_type); void saveCurrentEntry(QString *tempFile = Q_NULLPTR); void saveAllEntries(); Ui::ExportObjectDialog *eo_ui_; QPushButton *save_bt_; QPushButton *save_all_bt_; ExportObjectModel model_; ExportObjectProxyModel proxyModel_; QStringList contentTypes; void updateContentTypes(); }; #endif // EXPORT_OBJECT_DIALOG_H
User Interface
wireshark/ui/qt/export_object_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>ExportObjectDialog</class> <widget class="QDialog" name="ExportObjectDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>750</width> <height>520</height> </rect> </property> <property name="windowTitle"> <string>Dialog</string> </property> <property name="sizeGripEnabled"> <bool>true</bool> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <layout class="QHBoxLayout" name="horizontalLayout_2"> <item> <widget class="QLabel" name="label"> <property name="text"> <string>Text Filter:</string> </property> </widget> </item> <item> <widget class="QLineEdit" name="filterLine"> <property name="toolTip"> <string>Only display entries containing this string</string> </property> </widget> </item> <item> <widget class="QLabel" name="label_2"> <property name="text"> <string>Content Type:</string> </property> </widget> </item> <item> <widget class="QComboBox" name="cmbContentType"/> </item> </layout> </item> <item> <widget class="ExportObjectsTreeView" name="objectTree"> <property name="rootIsDecorated"> <bool>false</bool> </property> <property name="uniformRowHeights"> <bool>true</bool> </property> <property name="itemsExpandable"> <bool>false</bool> </property> <property name="sortingEnabled"> <bool>true</bool> </property> <property name="expandsOnDoubleClick"> <bool>false</bool> </property> </widget> </item> <item> <widget class="QFrame" name="progressFrame"> <property name="enabled"> <bool>true</bool> </property> <property name="frameShape"> <enum>QFrame::NoFrame</enum> </property> <property name="frameShadow"> <enum>QFrame::Plain</enum> </property> <property name="lineWidth"> <number>0</number> </property> <layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0,1"> <property name="topMargin"> <number>0</number> </property> <property name="bottomMargin"> <number>0</number> </property> <item> <widget class="QLabel" name="progressLabel"> <property name="text"> <string>Searching for objects</string> </property> </widget> </item> <item> <widget class="QProgressBar" name="progressBar"> <property name="styleSheet"> <string notr="true">QProgressBar { width: 10em; }</string> </property> <property name="maximum"> <number>0</number> </property> <property name="value"> <number>-1</number> </property> <property name="textVisible"> <bool>false</bool> </property> </widget> </item> <item> <spacer name="horizontalSpacer"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="sizeHint" stdset="0"> <size> <width>387</width> <height>20</height> </size> </property> </spacer> </item> </layout> </widget> </item> <item> <widget class="QDialogButtonBox" name="buttonBox"> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Close|QDialogButtonBox::Help|QDialogButtonBox::Open|QDialogButtonBox::Save|QDialogButtonBox::SaveAll</set> </property> </widget> </item> </layout> </widget> <customwidgets> <customwidget> <class>ExportObjectsTreeView</class> <extends>QTreeView</extends> <header>widgets/export_objects_view.h</header> </customwidget> </customwidgets> <resources/> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>ExportObjectDialog</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>248</x> <y>254</y> </hint> <hint type="destinationlabel"> <x>157</x> <y>274</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>ExportObjectDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>316</x> <y>260</y> </hint> <hint type="destinationlabel"> <x>286</x> <y>274</y> </hint> </hints> </connection> </connections> </ui>
C++
wireshark/ui/qt/export_pdu_dialog.cpp
/* export_pdu_dialog.cpp * Dialog for exporting PDUs to file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include "export_pdu_dialog.h" #include <ui_export_pdu_dialog.h> #include <epan/tap.h> #include <epan/exported_pdu.h> #include "ui/export_pdu_ui_utils.h" #include "ui/capture_globals.h" ExportPDUDialog::ExportPDUDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ExportPDUDialog) { GSList *tap_name_list; ui->setupUi(this); for (tap_name_list = get_export_pdu_tap_list(); tap_name_list; tap_name_list = g_slist_next(tap_name_list)) { if (export_pdu_tap_get_encap((const char*)tap_name_list->data) == WTAP_ENCAP_WIRESHARK_UPPER_PDU) { ui->comboBox->addItem((const char*)(tap_name_list->data)); } } } void ExportPDUDialog::on_buttonBox_accepted() { const QByteArray& filter = ui->displayFilterLineEdit->text().toUtf8(); const QByteArray& tap_name = ui->comboBox->currentText().toUtf8(); do_export_pdu(filter.constData(), global_capture_opts.temp_dir, tap_name.constData()); } ExportPDUDialog::~ExportPDUDialog() { delete ui; }
C/C++
wireshark/ui/qt/export_pdu_dialog.h
/** @file * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef EXPORT_PDU_DIALOG_H #define EXPORT_PDU_DIALOG_H #include <QDialog> #include <QDebug> namespace Ui { class ExportPDUDialog; } class ExportPDUDialog : public QDialog { Q_OBJECT public: explicit ExportPDUDialog(QWidget *parent = 0); ~ExportPDUDialog(); private: Ui::ExportPDUDialog *ui; private slots: void on_buttonBox_accepted(); }; #endif // EXPORT_PDU_DIALOG_H
User Interface
wireshark/ui/qt/export_pdu_dialog.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>ExportPDUDialog</class> <widget class="QDialog" name="ExportPDUDialog"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>393</width> <height>158</height> </rect> </property> <property name="windowTitle"> <string>Dialog</string> </property> <widget class="QDialogButtonBox" name="buttonBox"> <property name="geometry"> <rect> <x>30</x> <y>100</y> <width>341</width> <height>32</height> </rect> </property> <property name="orientation"> <enum>Qt::Horizontal</enum> </property> <property name="standardButtons"> <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set> </property> </widget> <widget class="QWidget" name="layoutWidget"> <property name="geometry"> <rect> <x>16</x> <y>20</y> <width>361</width> <height>29</height> </rect> </property> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <widget class="QLabel" name="label"> <property name="text"> <string>Display filter:</string> </property> </widget> </item> <item> <widget class="DisplayFilterEdit" name="displayFilterLineEdit"/> </item> </layout> </widget> <widget class="QComboBox" name="comboBox"> <property name="geometry"> <rect> <x>10</x> <y>60</y> <width>120</width> <height>30</height> </rect> </property> </widget> </widget> <customwidgets> <customwidget> <class>DisplayFilterEdit</class> <extends>QLineEdit</extends> <header>widgets/display_filter_edit.h</header> </customwidget> </customwidgets> <connections> <connection> <sender>buttonBox</sender> <signal>accepted()</signal> <receiver>ExportPDUDialog</receiver> <slot>accept()</slot> <hints> <hint type="sourcelabel"> <x>248</x> <y>254</y> </hint> <hint type="destinationlabel"> <x>157</x> <y>274</y> </hint> </hints> </connection> <connection> <sender>buttonBox</sender> <signal>rejected()</signal> <receiver>ExportPDUDialog</receiver> <slot>reject()</slot> <hints> <hint type="sourcelabel"> <x>316</x> <y>260</y> </hint> <hint type="destinationlabel"> <x>286</x> <y>274</y> </hint> </hints> </connection> </connections> </ui>