17 Commits
Author SHA1 Message Date
Jokul 6b59848f0a 更新 README.md 2026-09-12 00:20:19 +08:00
Jokul 8ad2ad71c3 docs: 重写 CHANGELOG 去除开发过程 bug 修复
版本更新清单只保留新功能、优化、重构,不包含新功能自身的调试修复
2026-08-09 09:34:28 +08:00
Jokul 0bf771b6b0 release: v2.1.0 版本更新
修复会话总量与今日累计不一致、流量统计裁剪上限调整
2026-08-09 09:27:15 +08:00
Jokul 83f1a2002a fix: 流量统计裁剪上限改为按日30天、按月12个月
MAX_DAY_ENTRIES 90->30, MAX_MONTH_ENTRIES 24->12
2026-08-09 09:22:24 +08:00
Jokul f50a3fe8e5 fix: 会话总量改回本次运行累计(累加差值)
网卡开机累计值与今日累计不一致让用户困惑,改回累加差值模式:
本次会话 = dde-shell 启动至今的流量,重启清零,不再超过今日累计
2026-08-09 09:19:20 +08:00
Jokul b27f96b31d release: v2.0.0 版本更新
弹窗重新设计、日/月流量统计、TCP连接清单、链路速率/WiFi信号/包统计、
可配置刷新间隔、流量图时间窗口、性能优化、架构重构、多项 bug 修复
2026-08-09 09:12:51 +08:00
Jokul 8a984eac59 fix: TCP连接清单刷新间隔文案改为动态显示
'每5秒刷新'写死改为读取 applet.refreshInterval 动态显示实际间隔
2026-08-09 09:09:02 +08:00
Jokul e75f56a0ba fix: 流量统计和TCP连接清单刷新间隔去掉5倍降频
直接使用用户设置的刷新间隔,不再叠加5倍降频
2026-08-09 09:06:49 +08:00
Jokul 4186357380 style: 右键菜单顺序调整,设置移到 TCP 连接下面
新顺序:流量波动图 -> 流量统计 -> TCP 连接 -> 设置 -> 分隔线 -> 关于
2026-08-09 09:01:48 +08:00
Jokul 3bec5b156e fix: 右键菜单 TCP Connections 国际化 + 刷新间隔影响所有定时
补全 networkview context 中缺失的 TCP Connections 翻译;
TrafficStatsWindow 和 TcpConnectionsWindow 的数据刷新 Timer 改为
跟随 applet.refreshInterval(5 倍降频),设置中改刷新间隔后所有定时同步生效
2026-08-09 08:59:09 +08:00
Jokul c61542574c fix: 补全 TCP 连接清单窗口国际化翻译
新增 12 条翻译:TCP Connections/Active connections/Search/Local Address
/Remote Address/State/Process/No active/No matching/Total/connections
等,中文系统下不再显示英文
2026-08-09 08:54:06 +08:00
Jokul 1c6d31a169 fix: TextField rightItem 属性不存在导致插件加载失败
QtQuick.Controls TextField 无 rightItem 属性(DTK 专有),
清除按钮从 TextField 内部移到外部 RowLayout 中
2026-08-09 08:50:42 +08:00
Jokul f09ef2b424 feat: TCP 连接清单增加搜索筛选
顶部加搜索框,实时筛选匹配本地/远程地址、端口、进程名的连接;
连接数显示筛选后/总数,空状态区分无连接和无匹配
2026-08-09 08:49:10 +08:00
Jokul 5665e0b522 fix: TCP 进程名反查改用 ss 命令,修复普通用户权限限制 2026-08-09 08:40:29 +08:00
Jokul 089a11207a feat: 新增 TCP 连接清单窗口 2026-08-09 08:09:03 +08:00
Jokul 77e2276e99 fix: 会话总量改为网卡开机累计值
会话总量不再累加差值,改为直接读取活动接口累计字节数(开机至今):
切换网卡后立即显示新网卡累计值,无流量网卡显示 0
2026-08-09 07:48:00 +08:00
Jokul beb13fc33d fix: 切换网卡后会话流量重置为 0
setActiveInterface 重置会话总量 m_totalDownload/m_totalUpload 为 0,
与包统计重置逻辑一致,切换后显示当前网卡的会话流量
2026-08-09 07:41:58 +08:00
9 changed files with 641 additions and 21 deletions
+49
View File
@@ -0,0 +1,49 @@
# 更新日志
## v2.1.0 - 2026-08-09
v2.0.0 后的优化版本。
### 优化
- 流量统计裁剪上限调整:按日保留 30 天,按月保留 12 个月
## v2.0.0 - 2026-08-09
本次为大版本更新,涵盖弹窗重新设计、多个新功能窗口、性能优化和架构重构。
### 新功能
- **左键弹窗重新设计**:通透分区布局(分隔线+留白),速度数字 24px 视觉锚点,适配 Deepin 原生毛玻璃风格
- **IPv4/IPv6 一键复制**:地址旁加复制图标,点击写入剪贴板,复制后显示 ✓ 反馈
- **日/月流量统计**(持久化):右键菜单新增"流量统计"窗口,按日/按月展示累计流量,跨重启累加,JSON 持久化到磁盘
- **TCP 连接清单**:右键菜单新增"TCP 连接"窗口,展示所有 ESTABLISHED 连接的本地/远程地址端口、状态、进程名,支持搜索筛选
- **链路速率显示**:弹窗接口信息区显示协商速率(Gbps/Mbps)
- **WiFi 信号强度**:无线接口显示信号 dBm
- **包统计/错误/丢包**:弹窗累计流量区展示收发包数、错误数、丢包数
- **TCP 连接数**:弹窗显示整机活跃 TCP 连接数
- **可配置刷新间隔**:设置窗口新增 1/2/5 秒刷新间隔选项,影响全项目所有定时器
- **流量波动图时间窗口**:1/5/30 分钟可切换
- **任务栏数值小数点对齐**:双行网速数值小数点垂直对齐,箭头间距固定
### 优化
- 弹窗文字颜色改用 dock 上下文调色板,深色模式文字清晰可见
- 弹窗高度固定,切换网卡时不再跳动
- IPv4/IPv6 地址行固定宽度标签对齐,不再随地址长度错位
- 流量波动图曲线 5 点滑动平均,抑制亚秒混叠尖峰
- C++ 后端性能优化:正则预编译、信号脏标记、IP 检测降频、历史 QVariantList 缓存
- TCP 进程名反查改用 ss 命令(netlink),不受 /proc 权限限制
### 重构
- 提取 WindowTheme + TitleBar 组件,消除三个独立窗口约 150 行样板重复
- 提取 interfaceIcon/interfaceDescription 到 NetCommon,消除跨组件重复
- 清理 fontScale 死代码,移除 30+ 处乘法噪声
- CMake Test 改为可选依赖,解决无 Qt6 Test 开发包环境构建失败
### 其他
- 右键菜单顺序调整:流量波动图 -> 流量统计 -> TCP 连接 -> 设置 -> 关于
- 全项目国际化翻译补全(77 条翻译)
- 任务栏数值右侧留边距
+1 -1
View File
@@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 3.16)
project(JNetApplet VERSION 1.2.0 LANGUAGES CXX)
project(JNetApplet VERSION 2.1.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
+7
View File
@@ -1,3 +1,10 @@
> **📦 本仓库已迁移至 GitHub:[GershonWang/JNetApplet](https://github.com/GershonWang/JNetApplet)**
>
> 此仓库代码已停止更新,最新源码、Issue 与版本发布请前往:
> <https://github.com/GershonWang/JNetApplet>
---
# JNetApplet
基于 dde-shell 的**深度系统任务栏网络速率监控插件**,使用 C++ 后端采集数据、
+359
View File
@@ -0,0 +1,359 @@
// SPDX-FileCopyrightText: 2026 Jokul
//
// SPDX-License-Identifier: LGPL-3.0-or-later
// TCP 连接清单窗口:屏幕居中的独立顶层窗口,展示当前所有 ESTABLISHED 状态的
// TCP 连接详情(本地地址:端口、远程地址:端口、状态、进程名),数据来自 C++ 后端
// 解析 /proc/net/tcp 与 tcp6(含进程名反查)。
// 设计要点:
// - 视觉风格复用 TrafficStatsWindow.qml(圆角卡片 12px、1px 边框、44px 标题栏、
// 28x28 圆形关闭按钮 hover 淡红底);深/浅主题由 isDarkMode 切换
// (networkview.qml 依据 DockPalette 检测任务栏深浅后传入),默认浅色保证独立预览可用
// - 数据通过属性注入:applet 即 networkview.qml 的 root.applet(C++ 后端对象),
// applet.tcpConnectionList 为 QVariantList of QVariantMap,每项含
// {localAddress, localPort, remoteAddress, remotePort, state, processName},
// 为 null 时组件可独立预览(显示空状态)
// - 定时刷新:窗口可见时每 5 秒重建清单(与 C++ 后端降频周期一致),关闭时停止
// 触发方式:右键菜单"TCP 连接清单" -> show()/raise()/requestActivate()
// 公共能力复用:主题色取自 WindowTheme,标题栏(含关闭按钮)取自 TitleBar
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtQuick.Window 2.15
import "."
Window {
id: root
// 公共主题色:集中定义于 WindowTheme.qml,随 isDarkMode 切换深浅
WindowTheme {
id: theme
isDarkMode: root.isDarkMode
}
// 对外依赖:关闭按钮 hover 态文字高亮色,由父组件传入
// 默认值与 networkview.qml 中 root.accentRed 一致,确保独立可用
property color accentColor: Qt.rgba(220 / 255, 38 / 255, 38 / 255, 1)
// 对外依赖:C++ 后端对象(NetworkMonitorApplet),由 networkview.qml 传入
// 提供 tcpConnectionList(QVariantList of QVariantMap);为 null 时可独立预览(显示空状态)
property var applet: null
// 深色模式标记:由 networkview.qml 根据 DockPalette 检测后传入;
// 默认 false(浅色)保证组件独立预览时与原版视觉一致
property bool isDarkMode: false
// 表格模型:由 refreshModel() 生成的连接记录数组,每项
// {localAddress, localPort, remoteAddress, remotePort, state, processName}
property var connModel: []
// 搜索关键字:非空时筛选匹配本地/远程地址、端口、进程名的连接
property string searchText: ""
// 筛选后的模型:searchText 为空时返回全部,否则按关键字过滤
// 匹配字段:localAddress/localPort/remoteAddress/remotePort/processName
readonly property var filteredModel: {
var list = root.connModel
if (root.searchText.length === 0) return list
var key = root.searchText.toLowerCase()
var result = []
for (var i = 0; i < list.length; i++) {
var c = list[i]
if (String(c.localAddress).toLowerCase().indexOf(key) >= 0
|| String(c.localPort).indexOf(key) >= 0
|| String(c.remoteAddress).toLowerCase().indexOf(key) >= 0
|| String(c.remotePort).indexOf(key) >= 0
|| String(c.processName).toLowerCase().indexOf(key) >= 0) {
result.push(c)
}
}
return result
}
// 当前连接总数,底部汇总与顶部状态条共用
property int connCount: 0
// 表格列宽:与表头/行/底部汇总共用同一组固定宽度,保证各列垂直对齐
readonly property int colLocal: 180
readonly property int colRemote: 180
readonly property int colState: 90
readonly property int colSpacing: 6
// 从 applet.tcpConnectionList 重建表格模型
// 设计原因:连接清单数量随时变化,每次读取重建数组供 ListView 展示;
// applet 为 null 时置空模型,保证独立预览可用
function refreshModel() {
var list = root.applet ? (root.applet.tcpConnectionList || []) : []
root.connModel = list
root.connCount = list.length
}
width: 680
height: 420
visible: false
flags: Qt.FramelessWindowHint | Qt.Window
modality: Qt.NonModal
color: "transparent"
onVisibleChanged: {
if (visible) {
// 居中到当前屏幕(任务栏所在屏幕),加 virtualX/virtualY 偏移
// 避免多显示器下窗口出现在非预期屏幕
x = Screen.virtualX + (Screen.width - width) / 2
y = Screen.virtualY + (Screen.height - height) / 2
// 窗口显示时立即刷新一次,确保数据最新
refreshModel()
}
}
// 定时刷新:窗口可见时按刷新间隔的 5 倍重建清单(与 C++ 后端降频周期一致),
// 不依赖 C++ 信号;关闭时停止,兼顾实时性与性能
Timer {
interval: root.applet ? root.applet.refreshInterval : 1000
repeat: true
running: root.visible
onTriggered: refreshModel()
}
// 窗口主体:圆角卡片(背景与边框随 isDarkMode 切换深浅),1px 边框模拟 DTK 窗口描边
Rectangle {
anchors.fill: parent
color: theme.winBg
radius: 12
border.width: 1
border.color: theme.lineColor
ColumnLayout {
anchors.fill: parent
spacing: 0
// 公共标题栏:标题文字 + 关闭按钮,整栏可拖动
TitleBar {
Layout.fillWidth: true
titleText: qsTr("TCP Connections")
textColor: theme.textPrimary
secondaryTextColor: theme.textSecondary
closeHoverColor: root.accentColor
}
// 顶部状态条:当前连接数 + 搜索框 + 刷新间隔说明
RowLayout {
Layout.fillWidth: true
Layout.preferredHeight: 34
Layout.leftMargin: 16
Layout.rightMargin: 16
spacing: 8
Text {
// 动态刷新连接总数,显示筛选后数量/总数
text: qsTr("Active connections: ") + root.filteredModel.length + "/" + root.connCount
font.pixelSize: 12
font.weight: Font.Medium
color: theme.textPrimary
}
// 搜索框:输入关键字筛选匹配地址/端口/进程名的连接
TextField {
Layout.preferredWidth: 200
placeholderText: qsTr("Search address, port, process...")
font.pixelSize: 12
color: theme.textPrimary
selectByMouse: true
text: root.searchText
onTextChanged: root.searchText = text
}
// 清除按钮:有输入时显示 ×,点击清空搜索
Rectangle {
visible: root.searchText.length > 0
width: 20; height: 20
radius: 10
color: clearSearchMouse.containsMouse ? theme.hoverBg : "transparent"
Text {
anchors.centerIn: parent
text: "×"
font.pixelSize: 14
color: clearSearchMouse.containsMouse ? root.accentColor : theme.textTertiary
}
MouseArea {
id: clearSearchMouse
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: root.searchText = ""
}
}
Item { Layout.fillWidth: true }
Text {
text: qsTr("Refreshes every ") + ((root.applet ? root.applet.refreshInterval : 1000) / 1000) + qsTr(" seconds")
font.pixelSize: 11
color: theme.textTertiary
}
}
// 表头行:本地地址:端口 | 远程地址:端口 | 状态 | 进程名
RowLayout {
Layout.fillWidth: true
Layout.leftMargin: 16
Layout.rightMargin: 16
Layout.topMargin: 2
spacing: root.colSpacing
Text {
Layout.preferredWidth: root.colLocal
text: qsTr("Local Address:Port")
font.pixelSize: 11
font.weight: Font.Bold
color: theme.textSecondary
}
Text {
Layout.preferredWidth: root.colRemote
text: qsTr("Remote Address:Port")
font.pixelSize: 11
font.weight: Font.Bold
color: theme.textSecondary
}
Text {
Layout.preferredWidth: root.colState
text: qsTr("State")
font.pixelSize: 11
font.weight: Font.Bold
color: theme.textSecondary
}
Text {
Layout.fillWidth: true
text: qsTr("Process")
font.pixelSize: 11
font.weight: Font.Bold
color: theme.textSecondary
}
}
// 表头与内容间的分隔线
Rectangle {
Layout.fillWidth: true
Layout.preferredHeight: 1
Layout.leftMargin: 16
Layout.rightMargin: 16
Layout.topMargin: 4
color: theme.lineColor
}
// 表格区:ListView 展示每条连接记录,行 hover 高亮
ListView {
Layout.fillWidth: true
Layout.fillHeight: true
Layout.leftMargin: 16
Layout.rightMargin: 16
Layout.topMargin: 2
Layout.bottomMargin: 2
clip: true
model: root.filteredModel
onCountChanged: emptyHint.visible = root.filteredModel.length === 0
// 空状态提示(当筛选结果为空时显示)
Item {
id: emptyHint
anchors.fill: parent
visible: root.filteredModel.length === 0
Text {
anchors.centerIn: parent
text: root.searchText.length > 0 ? qsTr("No matching connections") : qsTr("No active TCP connections")
font.pixelSize: 13
color: theme.textTertiary
}
}
delegate: Rectangle {
required property int index
required property var modelData
width: ListView.view.width
height: 28
radius: 4
// 行 hover 高亮:浅色用淡黑、深色用淡白,保证两种卡片背景上均可见
color: rowMouse.containsMouse ? theme.hoverBg : "transparent"
RowLayout {
anchors.fill: parent
anchors.leftMargin: 8
anchors.rightMargin: 8
spacing: root.colSpacing
Text {
Layout.preferredWidth: root.colLocal
text: modelData.localAddress + ":" + modelData.localPort
font.pixelSize: 12
color: theme.textPrimary
elide: Text.ElideRight
}
Text {
Layout.preferredWidth: root.colRemote
text: modelData.remoteAddress + ":" + modelData.remotePort
font.pixelSize: 12
color: theme.textPrimary
elide: Text.ElideRight
}
Text {
Layout.preferredWidth: root.colState
text: modelData.state
font.pixelSize: 12
color: theme.textSecondary
elide: Text.ElideRight
}
Text {
Layout.fillWidth: true
// 进程名可能为空(反查失败),显示占位符避免空白行
text: modelData.processName.length > 0 ? modelData.processName : "-"
font.pixelSize: 12
color: modelData.processName.length > 0 ? theme.textPrimary : theme.textTertiary
elide: Text.ElideRight
}
}
MouseArea {
id: rowMouse
anchors.fill: parent
hoverEnabled: true
}
}
}
// 表头与底部汇总间的分隔线
Rectangle {
Layout.fillWidth: true
Layout.preferredHeight: 1
Layout.leftMargin: 16
Layout.rightMargin: 16
color: theme.lineColor
}
// 底部汇总行:连接总数
RowLayout {
Layout.fillWidth: true
Layout.preferredHeight: 34
Layout.leftMargin: 24
Layout.rightMargin: 16
spacing: root.colSpacing
Text {
Layout.fillWidth: true
text: qsTr("Total: ") + root.filteredModel.length + "/" + root.connCount + qsTr(" connections")
font.pixelSize: 12
font.weight: Font.Bold
color: theme.textPrimary
}
}
}
}
// 数据刷新:C++ 每 5 秒更新并发射 tcpConnectionListChanged,据此重建清单;
// 本窗口自身的 Timer 兜底,避免依赖信号时序
Connections {
target: root.applet
function onTcpConnectionListChanged() {
refreshModel()
}
}
}
+3 -3
View File
@@ -116,11 +116,11 @@ Window {
onCurrentTabChanged: buildStatsModel()
Component.onCompleted: buildStatsModel()
// 定时刷新:窗口可见时每 5 秒重建表格,不依赖 C++ 30 秒信号
// 定时刷新:窗口可见时按刷新间隔的 5 倍重建表格,不依赖 C++ 30 秒信号
// 设计原因:C++ 降频 30 秒通知,用户打开窗口期间看不到实时更新;
// 窗口可见时主动 5 秒刷新,关闭时停止,兼顾实时性与性能
// 窗口可见时主动刷新,间隔跟随设置中的刷新间隔(5 倍降频),关闭时停止
Timer {
interval: 5000
interval: root.applet ? root.applet.refreshInterval : 1000
repeat: true
running: root.visible
onTriggered: buildStatsModel()
+29 -9
View File
@@ -355,15 +355,6 @@ AppletItem {
Platform.Menu {
id: contextMenu
Platform.MenuItem {
text: qsTr("Settings")
onTriggered: {
settingsWindow.show()
settingsWindow.raise()
settingsWindow.requestActivate()
}
}
// 流量波动图:屏幕居中独立窗口,展示活动接口最近 30 分钟网速趋势
Platform.MenuItem {
text: qsTr("Traffic Chart")
@@ -384,6 +375,25 @@ AppletItem {
}
}
// TCP 连接清单:屏幕居中独立窗口,展示当前所有 ESTABLISHED 状态的 TCP 连接
Platform.MenuItem {
text: qsTr("TCP Connections")
onTriggered: {
tcpConnectionsWindow.show()
tcpConnectionsWindow.raise()
tcpConnectionsWindow.requestActivate()
}
}
Platform.MenuItem {
text: qsTr("Settings")
onTriggered: {
settingsWindow.show()
settingsWindow.raise()
settingsWindow.requestActivate()
}
}
Platform.MenuSeparator {}
Platform.MenuItem {
@@ -426,6 +436,16 @@ AppletItem {
isDarkMode: root.isDarkMode
}
// TCP 连接清单窗口:屏幕居中独立窗口,展示当前所有 ESTABLISHED 状态的 TCP 连接
// 依赖通过属性传入:accentColor = root.accentRed,applet = root.applet,
// isDarkMode 取自上方 DockPalette 检测结果
TcpConnectionsWindow {
id: tcpConnectionsWindow
accentColor: root.accentRed
applet: root.applet
isDarkMode: root.isDarkMode
}
// 设置窗口:独立顶层窗口,在桌面中间弹出
// 设计原因:Dialog 使用父窗口(dock layer-surface)的 overlay,仅覆盖任务栏区域,
// 无法在桌面中间显示。改用 Window 创建独立顶层窗口,可在桌面任意位置弹出。
+91 -3
View File
@@ -285,6 +285,12 @@ QJsonObject NetworkMonitorApplet::trafficLog() const
return m_trafficLog;
}
// 返回 TCP 连接详情列表(QVariantList of QVariantMap),供 QML 连接清单窗口展示
QVariantList NetworkMonitorApplet::tcpConnectionList() const
{
return m_tcpConnectionList;
}
// 返回当前活动接口的下行速度历史,转换为 QVariantList of QPointF 供 QML 使用
// 设计原因:QPointF 仅携带 x/y 两个值,上传与下载分别对应两个列表;
// 结果缓存于成员变量,仅当 m_historyDirty 时重建,避免 QML 每次读取都重新构造 300 个点
@@ -500,6 +506,11 @@ void NetworkMonitorApplet::readNetworkStats()
m_lowFreqCounter = 0;
detectLowFreqStats();
}
// TCP 连接清单同样每 5 秒更新一次(进程名反查需遍历 /proc 开销大,不能每秒执行)
if (++m_tcpListCounter >= 5) {
m_tcpListCounter = 0;
buildTcpConnectionList();
}
}
void NetworkMonitorApplet::calculateSpeed()
@@ -534,10 +545,12 @@ void NetworkMonitorApplet::calculateSpeed()
const qint64 txDeltaClamped = txDelta > 0 ? txDelta : 0;
m_downloadSpeed = rxDeltaClamped / elapsedSec;
m_uploadSpeed = txDeltaClamped / elapsedSec;
// 累加会话总量:总量 = 本次会话期间所有活动接口的流量总和
// 会话总量:累加差值(dde-shell 启动至今的流量),重启清零
// 设计原因:用户期望"本次会话"是本次 dde-shell 运行期间的流量,
// 与流量统计窗口的"今日累计"(从0点起)区分,数值不会超过今日累计
m_totalDownload += rxDeltaClamped;
m_totalUpload += txDeltaClamped;
// 累加日/月流量日志(仅活动接口,与总量口径一致,避免多接口重复计数)
// 累加日/月流量日志(仅活动接口增量,与速度计算口径一致)
appendToTrafficLog(rxDeltaClamped, txDeltaClamped);
m_lastRxBytes = currentRxBytes;
m_lastTxBytes = currentTxBytes;
@@ -799,6 +812,81 @@ int NetworkMonitorApplet::countTcpConnections() const
return count;
}
// 构建 TCP 连接详情列表(调用 ss 命令获取 ESTABLISHED 连接,含进程名反查)
// 结果存入 m_tcpConnectionList(QVariantList of QVariantMap)并发射 tcpConnectionListChanged;
// 仅保留 ESTABLISHED 状态连接。优雅降级:ss 命令不存在/执行失败时返回空列表,不崩溃
// 设计原因:原先通过遍历 /proc/<pid>/fd 反查进程名,但 dde-shell 以普通用户运行,
// 无权 readlink 其他进程的 fd(lr-x------ 权限),导致进程名全空;改用 ss 命令一次
// 获取全部 ESTABLISHED 连接的地址/端口/进程名,ss 通过 netlink 获取信息不受 /proc 权限限制,
// 且仍由 readNetworkStats 降频至每 5 秒调用一次(ss 启动子进程仍有开销)
void NetworkMonitorApplet::buildTcpConnectionList()
{
QVariantList list;
// 用 ss 命令获取 ESTABLISHED 连接(含进程名),通过 netlink 不受 /proc 权限限制
// -t TCP, -n 不解析服务名(显示端口), -p 显示进程信息, state established 仅已建立连接
QProcess process;
process.start(QStringLiteral("ss"), {QStringLiteral("-tnp"), QStringLiteral("state"), QStringLiteral("established")});
// ss 命令不存在或启动失败(如精简系统未安装 iproute2)时优雅降级:返回空列表,不崩溃
if (!process.waitForStarted(1000)) {
m_tcpConnectionList = list;
emit tcpConnectionListChanged();
return;
}
process.waitForFinished(3000); // 3 秒超时,ss 卡住时不阻塞主线程过久
const QString output = QString::fromUtf8(process.readAllStandardOutput());
const QStringList lines = output.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
for (int i = 0; i < lines.size(); ++i) {
if (i == 0) continue; // 跳过表头(Recv-Q Send-Q ...)
const QString line = lines[i].trimmed();
if (line.isEmpty()) continue;
// ss 输出按多空格分割:Recv-Q Send-Q Local:Port Peer:Port [Process]
// 注意 Process 列可能为空,且 IPv6 地址形如 [::1]:port(方括号内无空格),
// 用正则提取更可靠,可容忍列之间任意空白
QRegularExpression re(QStringLiteral("(\\S+)\\s+(\\S+)\\s+(\\S+):(\\d+)\\s+(\\S+):(\\d+)\\s*(.*)"));
QRegularExpressionMatch match = re.match(line);
if (!match.hasMatch()) continue;
QString localAddress = match.captured(3);
const QString localPort = match.captured(4);
QString remoteAddress = match.captured(5);
const QString remotePort = match.captured(6);
const QString processField = match.captured(7).trimmed();
// 去掉地址中的接口后缀(如 192.168.3.83%wlp3s0 -> 192.168.3.83)
localAddress = localAddress.split(QLatin1Char('%')).first();
remoteAddress = remoteAddress.split(QLatin1Char('%')).first();
// 去掉 IPv6 地址的方括号([::1] -> ::1)
if (localAddress.startsWith(QLatin1Char('['))) localAddress = localAddress.mid(1, localAddress.size() - 2);
if (remoteAddress.startsWith(QLatin1Char('['))) remoteAddress = remoteAddress.mid(1, remoteAddress.size() - 2);
// 提取进程名:users:(("进程名",pid=xxx,fd=xxx)),取第一个双引号内的内容
QString processName;
if (processField.startsWith(QStringLiteral("users:"))) {
QRegularExpression nameRe(QStringLiteral("\\(\"([^\"]+)\""));
QRegularExpressionMatch nameMatch = nameRe.match(processField);
if (nameMatch.hasMatch()) {
processName = nameMatch.captured(1);
}
}
QVariantMap item;
item[QStringLiteral("localAddress")] = localAddress;
item[QStringLiteral("localPort")] = localPort.toInt();
item[QStringLiteral("remoteAddress")] = remoteAddress;
item[QStringLiteral("remotePort")] = remotePort.toInt();
item[QStringLiteral("state")] = QStringLiteral("ESTABLISHED");
item[QStringLiteral("processName")] = processName;
list.append(item);
}
m_tcpConnectionList = list;
emit tcpConnectionListChanged();
}
// 读取指定接口的 WiFi 信号强度(dBm)
// 仅无线接口(wlp/wlan)有效;/proc/net/wireless 桌面环境可能不存在(返回 0)
// 该文件每行形如 "wlp3s0: 60. -65. -256 0 ...",level(dBm)为第 3 个数值字段
@@ -939,7 +1027,7 @@ void NetworkMonitorApplet::appendToTrafficLog(qint64 rxDelta, qint64 txDelta)
m_trafficLog[QStringLiteral("byMonth")] = byMonth;
}
// 裁剪超期记录:按日最多 90 天、按月最多 24 个月,超出删除最旧记录
// 裁剪超期记录:按日最多 30 天、按月最多 12 个月,超出删除最旧记录
// 日期/月份均为 ISO 格式("yyyy-MM-dd"/"yyyy-MM"),字典序即时间序,
// 排序后取最小的超量个删除,保证始终保留最近的记录
void NetworkMonitorApplet::pruneTrafficLog()
+28 -4
View File
@@ -17,6 +17,8 @@
#include <QColor>
#include <QSettings>
#include <QJsonObject>
#include <QMetaType>
#include <QVariantMap>
DS_BEGIN_NAMESPACE
@@ -92,6 +94,12 @@ class NetworkMonitorApplet : public DApplet
// 保存频率:累加每秒执行(内存操作),写盘与通知 QML 降频(每 30 秒一次),
// 避免每秒磁盘 IO 与 QML 重绘
Q_PROPERTY(QJsonObject trafficLog READ trafficLog NOTIFY trafficLogChanged)
// TCP 连接详情列表,供 QML 连接清单窗口展示
// 每项为 QVariantMap(键:localAddress/localPort/remoteAddress/remotePort/state/processName)
// 仅包含 ESTABLISHED 状态连接,含进程名反查
// 设计原因:用 ss 命令反查进程名,通过 netlink 获取不受 /proc 权限限制,
// 但仍需启动子进程开销较大,故降频至每 5 秒更新一次
Q_PROPERTY(QVariantList tcpConnectionList READ tcpConnectionList NOTIFY tcpConnectionListChanged)
public:
explicit NetworkMonitorApplet(QObject *parent = nullptr);
@@ -138,6 +146,8 @@ public:
void setTextColor(const QString &color);
// 返回流量统计日志(JSON 对象),结构见 trafficLog 属性注释,供 QML 流量统计窗口读取
QJsonObject trafficLog() const;
// 返回 TCP 连接详情列表(QVariantList of QVariantMap),供 QML 连接清单窗口展示
QVariantList tcpConnectionList() const;
// 定时器回调,由 m_refreshTimer 每秒调用。非 Q_INVOKABLE(QML 不应直接调用,
// 否则会打破 1 秒定时间隔导致速度计算失真)
@@ -167,6 +177,8 @@ signals:
void textColorChanged();
// 流量统计日志变化时通知 QML 更新(降频,每 30 秒发射一次)
void trafficLogChanged();
// TCP 连接详情列表变化时通知 QML 更新(降频,每 5 秒发射一次)
void tcpConnectionListChanged();
private:
void readNetworkStats();
@@ -182,6 +194,9 @@ private:
int parseIwBitrate(const QString &output) const;
// 统计 /proc/net/tcp 与 tcp6 中 ESTABLISHED(状态 01)的连接数
int countTcpConnections() const;
// 构建 TCP 连接详情列表(调用 ss 命令获取 ESTABLISHED 连接,含进程名反查)
// 结果存入 m_tcpConnectionList 并发射 tcpConnectionListChanged;仅 ESTABLISHED
void buildTcpConnectionList();
// 读取指定接口的 WiFi 信号强度(dBm),非无线接口或不可用时返回 0
int detectWifiSignal(const QString &iface);
// 判断是否为物理网卡(无线 wlp/wlan,有线 enp/eth),
@@ -197,7 +212,7 @@ private:
void saveTrafficLog();
// 将本次流量增量累加到当日/当月/当前活动接口的日志记录中(每秒调用,内存操作)
void appendToTrafficLog(qint64 rxDelta, qint64 txDelta);
// 裁剪超期记录:按日最多 90 天、按月最多 24 个月,超出删除最旧记录
// 裁剪超期记录:按日最多 30 天、按月最多 12 个月,超出删除最旧记录
void pruneTrafficLog();
QTimer *m_refreshTimer;
@@ -288,9 +303,18 @@ private:
// 降频保存计数器:每 30 秒(按刷新间隔折算)写盘一次并通知 QML,
// 避免每秒磁盘 IO 与 QML 重绘;析构函数再兜底保存一次
int m_trafficSaveCounter;
// 按日记录最多保留 90 天、按月最多保留 24 个月,超出自动裁剪最旧记录
static constexpr int MAX_DAY_ENTRIES = 90;
static constexpr int MAX_MONTH_ENTRIES = 24;
// 按日记录最多保留 30 天、按月最多保留 12 个月,超出自动裁剪最旧记录
static constexpr int MAX_DAY_ENTRIES = 30;
static constexpr int MAX_MONTH_ENTRIES = 12;
// ---- TCP 连接清单成员 ----
// TCP 连接详情列表(QVariantList of QVariantMap),供 QML 连接清单窗口读取
// 设计原因:QVariantMap 便于 QML 以 JS 对象直接访问各字段,
// 不暴露中间结构体(需注册元类型,QML 访问繁琐)
QVariantList m_tcpConnectionList;
// TCP 连接清单降频计数器:ss 命令需启动子进程开销大,每 5 次 refresh 更新一次
// 初始化 4 使首次 refresh 立即更新
int m_tcpListCounter = 4;
};
DS_END_NAMESPACE
+73
View File
@@ -275,6 +275,11 @@
<source>Traffic Statistics</source>
<translation>流量统计</translation>
</message>
<message>
<location filename="../package/networkview.qml" line="389"/>
<source>TCP Connections</source>
<translation>TCP 连接</translation>
</message>
</context>
<context>
<name>TrafficStatsWindow</name>
@@ -339,4 +344,72 @@
<translation>暂无流量记录</translation>
</message>
</context>
<context>
<name>TcpConnectionsWindow</name>
<message>
<location filename="../package/components/TcpConnectionsWindow.qml" line="132"/>
<source>TCP Connections</source>
<translation>TCP 连接</translation>
</message>
<message>
<location filename="../package/components/TcpConnectionsWindow.qml" line="148"/>
<source>Active connections: </source>
<translation>活跃连接:</translation>
</message>
<message>
<location filename="../package/components/TcpConnectionsWindow.qml" line="159"/>
<source>Search address, port, process...</source>
<translation>搜索地址、端口、进程...</translation>
</message>
<message>
<location filename="../package/components/TcpConnectionsWindow.qml" line="191"/>
<source>Refreshes every </source>
<translation>每 </translation>
</message>
<message>
<location filename="../package/components/TcpConnectionsWindow.qml" line="190"/>
<source> seconds</source>
<translation> 秒刷新</translation>
</message>
<message>
<location filename="../package/components/TcpConnectionsWindow.qml" line="204"/>
<source>Local Address:Port</source>
<translation>本地地址:端口</translation>
</message>
<message>
<location filename="../package/components/TcpConnectionsWindow.qml" line="211"/>
<source>Remote Address:Port</source>
<translation>远程地址:端口</translation>
</message>
<message>
<location filename="../package/components/TcpConnectionsWindow.qml" line="218"/>
<source>State</source>
<translation>状态</translation>
</message>
<message>
<location filename="../package/components/TcpConnectionsWindow.qml" line="225"/>
<source>Process</source>
<translation>进程</translation>
</message>
<message>
<location filename="../package/components/TcpConnectionsWindow.qml" line="265"/>
<source>No active TCP connections</source>
<translation>无活跃 TCP 连接</translation>
</message>
<message>
<location filename="../package/components/TcpConnectionsWindow.qml" line="265"/>
<source>No matching connections</source>
<translation>无匹配连接</translation>
</message>
<message>
<location filename="../package/components/TcpConnectionsWindow.qml" line="340"/>
<source>Total: </source>
<translation>共计:</translation>
</message>
<message>
<location filename="../package/components/TcpConnectionsWindow.qml" line="340"/>
<source> connections</source>
<translation> 个连接</translation>
</message>
</context>
</TS>