4 Commits
Author SHA1 Message Date
Jokul 18e433ea06 fix: UI 语义区分会话总量与日月累计 + 修复 onVisibleChanged 重复
弹窗'流量总计'改为'本次会话',明确是本次 dde-shell 运行期间累计;
流量统计窗口'按接口累计'改为'今日累计/本月累计',明确是跨重启持久化。
修复 TrafficStatsWindow onVisibleChanged 重复设置导致插件加载失败
2026-08-09 07:21:13 +08:00
Jokul 6671bb0bd2 fix: TrafficStatsWindow onVisibleChanged 重复设置导致插件加载失败
窗口已有 onVisibleChanged(居中定位),新增刷新逻辑时又写了一个,
QML 不允许同一属性设置两次,运行时报错导致 applet 加载失败。
合并到现有的 onVisibleChanged 中
2026-08-09 07:10:09 +08:00
Jokul e5b2060ff0 fix: 流量统计窗口四个问题
1. 窗口宽度 560->620 容纳列宽,关闭按钮不再被遮挡
2. tab 切换无效:onCurrentTabChanged 已生效,补充窗口可见时立即刷新
3. 数值不刷新:新增 5 秒定时器(窗口可见时运行),不依赖 C++ 30 秒信号
4. 国际化:补全 TrafficStatistics/ByDay/ByMonth 等 12 条翻译
2026-08-09 07:07:29 +08:00
Jokul b0cf2150f4 feat: 新增日/月流量统计功能(持久化) 2026-08-09 00:49:44 +08:00
6 changed files with 711 additions and 3 deletions
+1 -1
View File
@@ -454,7 +454,7 @@ Control {
Item { Layout.fillWidth: true }
Text {
text: qsTr("Total")
text: qsTr("Session Total")
font.pixelSize: 12
color: popup.tertiaryText
}
+424
View File
@@ -0,0 +1,424 @@
// SPDX-FileCopyrightText: 2026 Jokul
//
// SPDX-License-Identifier: LGPL-3.0-or-later
// 流量统计窗口:屏幕居中的独立顶层窗口,展示按日/按月持久化的累计流量
// (下载/上传/总计),数据来自 C++ 后端持久化的 traffic_log.json,
// 跨重启累加,让用户了解长期流量趋势。
// 设计要点:
// - 视觉风格复用 TrafficChartWindow.qml(圆角卡片 12px、1px 边框、44px 标题栏、
// 28x28 圆形关闭按钮 hover 淡红底);深/浅主题由 isDarkMode 切换
// (networkview.qml 依据 DockPalette 检测任务栏深浅后传入),默认浅色保证独立预览可用
// - 数据通过属性注入:applet 即 networkview.qml 的 root.applet(C++ 后端对象),
// applet.trafficLog 为 JSON 对象 {"byDay": {日期: {接口: {rx, tx}}},
// "byMonth": {月份: {接口: {rx, tx}}}},为 null 时组件可独立预览(显示空状态)
// - 顶部 tab 切换按日/按月;表格按日期/月份降序(最新在上)展示,每行一个
// (日期, 接口)记录;底部汇总所有显示记录的总下载/总上传/总流量
// - 数据刷新:C++ 每 30 秒保存并发射 trafficLogChanged,本窗口据此重建表格
// 触发方式:右键菜单"流量统计" -> show()/raise()/requestActivate()
// 公共能力复用:主题色取自 WindowTheme,标题栏(含关闭按钮)取自 TitleBar,
// 格式化函数取自 NetCommon.formatTotal
import QtQuick 2.15
import QtQuick.Layouts 1.15
import QtQuick.Window 2.15
import "."
Window {
id: root
// 公共格式化函数:集中定义于同目录 NetCommon.qml,
// 与 networkview.qml、TrafficChartWindow 共享同一份实现
NetCommon { id: common }
// 公共主题色:集中定义于 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 传入
// 提供 trafficLog(JSON 对象,见文件头注释);为 null 时组件可独立预览(显示空状态)
property var applet: null
// 深色模式标记:由 networkview.qml 根据 DockPalette 检测后传入;
// 默认 false(浅色)保证组件独立预览时与原版视觉一致
property bool isDarkMode: false
// 当前 tab:0=按日, 1=按月,切换后重建表格模型
property int currentTab: 0
// 表格模型:由 buildStatsModel() 生成的扁平记录数组,每项
// {date, iface, rx, tx, total},按日期/月份降序(最新在上)排列
property var statsModel: []
// 底部汇总:所有显示记录的 rx/tx/total 累加值
property var totals: ({ rx: 0, tx: 0, total: 0 })
// 表格列宽:与表头/行/底部汇总共用同一组固定宽度,保证各列垂直对齐
readonly property int colDate: 118
readonly property int colIface: 108
readonly property int colNum: 102
readonly property int colSpacing: 6
// 依据 currentTab 与 applet.trafficLog 重建表格模型
// 设计原因:trafficLog 为 {日期/月份: {接口: {rx, tx}}} 的嵌套对象,
// 需展平为每行一个(键, 接口)记录并按日期降序排序,才能直接供 ListView 展示;
// 同时累加所有记录得到底部汇总
function buildStatsModel() {
var log = root.applet ? root.applet.trafficLog : {}
var key = root.currentTab === 0 ? "byDay" : "byMonth"
var entries = (log && log[key]) || {}
var rows = []
var tRx = 0, tTx = 0
for (var d in entries) {
var ifaces = entries[d]
for (var i in ifaces) {
var rec = ifaces[i]
var rx = rec ? (rec.rx || 0) : 0
var tx = rec ? (rec.tx || 0) : 0
rows.push({ date: d, iface: i, rx: rx, tx: tx, total: rx + tx })
tRx += rx
tTx += tx
}
}
// 按日期/月份降序(最新在上),同键内按接口名升序
rows.sort(function (a, b) {
if (a.date !== b.date) return a.date < b.date ? 1 : -1
return a.iface < b.iface ? -1 : 1
})
root.statsModel = rows
root.totals = { rx: tRx, tx: tTx, total: tRx + tTx }
}
width: 620
height: 440
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
// 窗口显示时立即刷新一次,确保数据最新
buildStatsModel()
}
}
// 切换 tab 或首次创建时重建表格模型
onCurrentTabChanged: buildStatsModel()
Component.onCompleted: buildStatsModel()
// 定时刷新:窗口可见时每 5 秒重建表格,不依赖 C++ 30 秒信号
// 设计原因:C++ 降频 30 秒通知,用户打开窗口期间看不到实时更新;
// 窗口可见时主动 5 秒刷新,关闭时停止,兼顾实时性与性能
Timer {
interval: 5000
repeat: true
running: root.visible
onTriggered: buildStatsModel()
}
// 窗口主体:圆角卡片(背景与边框随 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("Traffic Statistics")
textColor: theme.textPrimary
secondaryTextColor: theme.textSecondary
closeHoverColor: root.accentColor
}
// 顶部 tab 切换:按日 / 按月
RowLayout {
Layout.fillWidth: true
Layout.preferredHeight: 34
Layout.leftMargin: 16
Layout.rightMargin: 16
spacing: 8
// 按日 tab
Rectangle {
property bool sel: root.currentTab === 0
width: 80
height: 24
radius: 5
color: sel ? common.accentBlue : "transparent"
border.width: 1
border.color: sel ? common.accentBlue
: (dayMouse.containsMouse ? common.accentBlue : theme.lineColor)
Text {
anchors.centerIn: parent
text: qsTr("By Day")
font.pixelSize: 12
font.weight: sel ? Font.Bold : Font.Normal
color: sel ? "white" : (dayMouse.containsMouse ? common.accentBlue : theme.textSecondary)
}
MouseArea {
id: dayMouse
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: root.currentTab = 0
}
}
// 按月 tab
Rectangle {
property bool sel: root.currentTab === 1
width: 90
height: 24
radius: 5
color: sel ? common.accentBlue : "transparent"
border.width: 1
border.color: sel ? common.accentBlue
: (monthMouse.containsMouse ? common.accentBlue : theme.lineColor)
Text {
anchors.centerIn: parent
text: qsTr("By Month")
font.pixelSize: 12
font.weight: sel ? Font.Bold : Font.Normal
color: sel ? "white" : (monthMouse.containsMouse ? common.accentBlue : theme.textSecondary)
}
MouseArea {
id: monthMouse
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: root.currentTab = 1
}
}
Item { Layout.fillWidth: true }
// 右侧数据说明:按接口累计
Text {
text: root.currentTab === 0 ? qsTr("Today accumulated") : qsTr("This month accumulated")
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.colDate
text: root.currentTab === 0 ? qsTr("Date") : qsTr("Month")
font.pixelSize: 11
font.weight: Font.Bold
color: theme.textSecondary
}
Text {
Layout.preferredWidth: root.colIface
text: qsTr("Interface")
font.pixelSize: 11
font.weight: Font.Bold
color: theme.textSecondary
}
Text {
Layout.preferredWidth: root.colNum
text: qsTr("Download")
font.pixelSize: 11
font.weight: Font.Bold
color: theme.textSecondary
}
Text {
Layout.preferredWidth: root.colNum
text: qsTr("Upload")
font.pixelSize: 11
font.weight: Font.Bold
color: theme.textSecondary
}
Text {
Layout.preferredWidth: root.colNum
text: qsTr("Total")
font.pixelSize: 11
font.weight: Font.Bold
color: theme.textSecondary
}
Item { Layout.fillWidth: true }
}
// 表头与内容间的分隔线
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.statsModel
onCountChanged: emptyHint.visible = root.statsModel.length === 0
// 空状态提示(当 statsModel 为空时显示)
Item {
id: emptyHint
anchors.fill: parent
visible: root.statsModel.length === 0
Text {
anchors.centerIn: parent
text: qsTr("No traffic records yet")
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.colDate
text: modelData.date
font.pixelSize: 12
color: theme.textPrimary
elide: Text.ElideRight
}
Text {
Layout.preferredWidth: root.colIface
text: modelData.iface
font.pixelSize: 12
color: theme.textSecondary
elide: Text.ElideRight
}
Text {
Layout.preferredWidth: root.colNum
text: common.formatTotal(modelData.rx)
font.pixelSize: 12
color: theme.textPrimary
elide: Text.ElideRight
}
Text {
Layout.preferredWidth: root.colNum
text: common.formatTotal(modelData.tx)
font.pixelSize: 12
color: theme.textPrimary
elide: Text.ElideRight
}
Text {
Layout.preferredWidth: root.colNum
text: common.formatTotal(modelData.total)
font.pixelSize: 12
font.weight: Font.Medium
color: theme.textPrimary
elide: Text.ElideRight
}
Item { Layout.fillWidth: true }
}
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.preferredWidth: root.colDate + root.colIface
text: qsTr("Total")
font.pixelSize: 12
font.weight: Font.Bold
color: theme.textPrimary
}
Text {
Layout.preferredWidth: root.colNum
text: common.formatTotal(root.totals.rx)
font.pixelSize: 12
font.weight: Font.Bold
color: common.accentBlue
elide: Text.ElideRight
}
Text {
Layout.preferredWidth: root.colNum
text: common.formatTotal(root.totals.tx)
font.pixelSize: 12
font.weight: Font.Bold
color: common.accentGreen
elide: Text.ElideRight
}
Text {
Layout.preferredWidth: root.colNum
text: common.formatTotal(root.totals.total)
font.pixelSize: 12
font.weight: Font.Bold
color: theme.textPrimary
elide: Text.ElideRight
}
Item { Layout.fillWidth: true }
}
}
}
// 数据刷新:C++ 每 30 秒保存并发射 trafficLogChanged,据此重建表格;
// 接口切换不影响日志(日志按活动接口累计,切接口后数据仍完整)
Connections {
target: root.applet
function onTrafficLogChanged() {
buildStatsModel()
}
}
}
+20
View File
@@ -374,6 +374,16 @@ AppletItem {
}
}
// 流量统计:屏幕居中独立窗口,展示按日/按月持久化的累计流量
Platform.MenuItem {
text: qsTr("Traffic Statistics")
onTriggered: {
trafficStatsWindow.show()
trafficStatsWindow.raise()
trafficStatsWindow.requestActivate()
}
}
Platform.MenuSeparator {}
Platform.MenuItem {
@@ -406,6 +416,16 @@ AppletItem {
isDarkMode: root.isDarkMode
}
// 流量统计窗口:屏幕居中独立窗口,展示按日/按月持久化的累计流量
// 依赖通过属性传入:accentColor = root.accentRed,applet = root.applet,
// isDarkMode 取自上方 DockPalette 检测结果
TrafficStatsWindow {
id: trafficStatsWindow
accentColor: root.accentRed
applet: root.applet
isDarkMode: root.isDarkMode
}
// 设置窗口:独立顶层窗口,在桌面中间弹出
// 设计原因:Dialog 使用父窗口(dock layer-surface)的 overlay,仅覆盖任务栏区域,
// 无法在桌面中间显示。改用 Window 创建独立顶层窗口,可在桌面任意位置弹出。
+157
View File
@@ -18,6 +18,10 @@
#include <QLocale>
#include <QCoreApplication>
#include <QProcess>
#include <QJsonDocument>
#include <QJsonObject>
#include <QFileInfo>
#include <QDate>
DS_BEGIN_NAMESPACE
@@ -47,6 +51,7 @@ NetworkMonitorApplet::NetworkMonitorApplet(QObject *parent)
, m_firstUpdate(true)
, m_textColor()
, m_historyDirty(true)
, m_trafficSaveCounter(0)
{
// 从独立配置文件读取持久化的字体颜色
// 设计原因:使用独立配置文件避免污染 dde-shell 的共享配置,
@@ -81,6 +86,10 @@ NetworkMonitorApplet::NetworkMonitorApplet(QObject *parent)
NetworkMonitorApplet::~NetworkMonitorApplet()
{
// 析构时兜底保存流量日志,确保进程退出前最后一段累加数据不丢失
// 设计原因:降频保存每 30 秒才写一次盘,若用户在两次保存之间退出,
// 这段增量会丢失;析构保存保证数据完整性
saveTrafficLog();
}
bool NetworkMonitorApplet::load()
@@ -103,6 +112,15 @@ bool NetworkMonitorApplet::init()
detectInterfaces();
// 初始化流量日志持久化
// 设计原因:日志与设置共用 ~/.config/jnetapplet 目录;
// 启动时记录当前日期/月份用于跨日跨月检测,并从 JSON 文件加载历史累计数据
m_trafficLogPath = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)
+ QStringLiteral("/jnetapplet/traffic_log.json");
m_currentDate = QDate::currentDate().toString(QStringLiteral("yyyy-MM-dd"));
m_currentMonth = QDate::currentDate().toString(QStringLiteral("yyyy-MM"));
loadTrafficLog();
// 启动定时刷新
m_refreshTimer = new QTimer(this);
connect(m_refreshTimer, &QTimer::timeout, this, &NetworkMonitorApplet::refresh);
@@ -260,6 +278,13 @@ void NetworkMonitorApplet::setTextColor(const QString &color)
emit textColorChanged();
}
// 返回流量统计日志(JSON 对象),结构见 trafficLog 属性注释
// QJsonObject 可直接暴露给 QML 作为 JS 对象读取,无需额外转换
QJsonObject NetworkMonitorApplet::trafficLog() const
{
return m_trafficLog;
}
// 返回当前活动接口的下行速度历史,转换为 QVariantList of QPointF 供 QML 使用
// 设计原因:QPointF 仅携带 x/y 两个值,上传与下载分别对应两个列表;
// 结果缓存于成员变量,仅当 m_historyDirty 时重建,避免 QML 每次读取都重新构造 300 个点
@@ -302,6 +327,18 @@ void NetworkMonitorApplet::rebuildHistoryCache() const
void NetworkMonitorApplet::refresh()
{
readNetworkStats();
// 流量日志降频保存:每 30 秒写盘一次并通知 QML
// 设计原因:累加在 calculateSpeed 中每秒执行(纯内存操作开销低),
// 而写盘与 QML 重绘若每秒执行会造成不必要的磁盘 IO 与界面刷新;
// 计数器按刷新间隔折算(1s=30 次,2s=15 次,5s=6 次)保证实际每 30 秒保存一次
const int saveEveryMs = 30000;
const int saveThreshold = qMax(1, saveEveryMs / m_refreshInterval);
if (++m_trafficSaveCounter >= saveThreshold) {
m_trafficSaveCounter = 0;
saveTrafficLog();
emit trafficLogChanged();
}
}
void NetworkMonitorApplet::setActiveInterface(const QString &interface)
@@ -500,6 +537,8 @@ void NetworkMonitorApplet::calculateSpeed()
// 累加会话总量:总量 = 本次会话期间所有活动接口的流量总和
m_totalDownload += rxDeltaClamped;
m_totalUpload += txDeltaClamped;
// 累加日/月流量日志(仅活动接口,与总量口径一致,避免多接口重复计数)
appendToTrafficLog(rxDeltaClamped, txDeltaClamped);
m_lastRxBytes = currentRxBytes;
m_lastTxBytes = currentTxBytes;
}
@@ -806,6 +845,124 @@ bool NetworkMonitorApplet::isPhysicalInterface(const QString &name) const
|| name.startsWith("enp") || name.startsWith("eth");
}
// ---- 流量日志(日/月持久化)----
// 启动时从 traffic_log.json 加载流量日志
// 优雅降级:文件不存在、读取失败或 JSON 解析失败时均使用空结构,不崩溃不抛异常;
// 首次运行(文件不存在)时先创建空的 byDay/byMonth 结构,由后续保存写盘创建文件
void NetworkMonitorApplet::loadTrafficLog()
{
QFile file(m_trafficLogPath);
if (!file.exists()) {
m_trafficLog = QJsonObject();
m_trafficLog[QStringLiteral("byDay")] = QJsonObject();
m_trafficLog[QStringLiteral("byMonth")] = QJsonObject();
return;
}
if (file.open(QIODevice::ReadOnly)) {
QJsonParseError err;
const QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &err);
file.close();
if (err.error == QJsonParseError::NoError && doc.isObject()) {
m_trafficLog = doc.object();
} else {
// 解析失败(如文件被外部写坏):降级为空结构,避免后续累加异常
m_trafficLog = QJsonObject();
m_trafficLog[QStringLiteral("byDay")] = QJsonObject();
m_trafficLog[QStringLiteral("byMonth")] = QJsonObject();
}
}
}
// 将流量日志写入 traffic_log.json
// 先裁剪超期记录再写盘,避免日志无限膨胀;
// 写前 mkpath 确保目录存在(首次运行时目录尚未创建)
void NetworkMonitorApplet::saveTrafficLog()
{
// 测试等场景未初始化日志路径时直接跳过,避免对空路径 mkpath/写文件产生告警
if (m_trafficLogPath.isEmpty()) {
return;
}
pruneTrafficLog();
QDir dir;
dir.mkpath(QFileInfo(m_trafficLogPath).absolutePath());
QFile file(m_trafficLogPath);
if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
// 用 Indented 缩进格式便于用户手动查看/调试日志文件
file.write(QJsonDocument(m_trafficLog).toJson(QJsonDocument::Indented));
file.close();
}
}
// 将本次流量增量累加到当日/当月/当前活动接口的日志记录中(每秒调用,纯内存操作)
// 跨日/跨月检测:日期或月份与上次记录不同时切换当前记录,不累加到昨天的记录;
// 只累加活动接口(与 m_totalDownload 口径一致),避免多接口重复计数
void NetworkMonitorApplet::appendToTrafficLog(qint64 rxDelta, qint64 txDelta)
{
if (rxDelta <= 0 && txDelta <= 0) {
return;
}
if (m_activeInterface.isEmpty()) {
return;
}
// 跨日/跨月检测:更新当前日期/月份,切换记录(旧记录保留不再累加)
const QString date = QDate::currentDate().toString(QStringLiteral("yyyy-MM-dd"));
const QString month = QDate::currentDate().toString(QStringLiteral("yyyy-MM"));
m_currentDate = date;
m_currentMonth = month;
// 累加到按日记录:byDay[date][iface] = {rx, tx}
// 用 toVariant().toLongLong() 读取并写回 qint64,保留整数精度
//(直接赋值 double 会导致超过 2^53 的字节数精度丢失)
QJsonObject byDay = m_trafficLog.value(QStringLiteral("byDay")).toObject();
QJsonObject dayEntry = byDay.value(date).toObject();
QJsonObject ifaceDay = dayEntry.value(m_activeInterface).toObject();
ifaceDay[QStringLiteral("rx")] =
ifaceDay.value(QStringLiteral("rx")).toVariant().toLongLong() + rxDelta;
ifaceDay[QStringLiteral("tx")] =
ifaceDay.value(QStringLiteral("tx")).toVariant().toLongLong() + txDelta;
dayEntry[m_activeInterface] = ifaceDay;
byDay[date] = dayEntry;
m_trafficLog[QStringLiteral("byDay")] = byDay;
// 累加到按月记录:byMonth[month][iface] = {rx, tx}
QJsonObject byMonth = m_trafficLog.value(QStringLiteral("byMonth")).toObject();
QJsonObject monthEntry = byMonth.value(month).toObject();
QJsonObject ifaceMonth = monthEntry.value(m_activeInterface).toObject();
ifaceMonth[QStringLiteral("rx")] =
ifaceMonth.value(QStringLiteral("rx")).toVariant().toLongLong() + rxDelta;
ifaceMonth[QStringLiteral("tx")] =
ifaceMonth.value(QStringLiteral("tx")).toVariant().toLongLong() + txDelta;
monthEntry[m_activeInterface] = ifaceMonth;
byMonth[month] = monthEntry;
m_trafficLog[QStringLiteral("byMonth")] = byMonth;
}
// 裁剪超期记录:按日最多 90 天、按月最多 24 个月,超出删除最旧记录
// 日期/月份均为 ISO 格式("yyyy-MM-dd"/"yyyy-MM"),字典序即时间序,
// 排序后取最小的超量个删除,保证始终保留最近的记录
void NetworkMonitorApplet::pruneTrafficLog()
{
QJsonObject byDay = m_trafficLog.value(QStringLiteral("byDay")).toObject();
QStringList dayKeys = byDay.keys();
dayKeys.sort();
while (dayKeys.size() > MAX_DAY_ENTRIES) {
byDay.remove(dayKeys.first());
dayKeys.removeFirst();
}
m_trafficLog[QStringLiteral("byDay")] = byDay;
QJsonObject byMonth = m_trafficLog.value(QStringLiteral("byMonth")).toObject();
QStringList monthKeys = byMonth.keys();
monthKeys.sort();
while (monthKeys.size() > MAX_MONTH_ENTRIES) {
byMonth.remove(monthKeys.first());
monthKeys.removeFirst();
}
m_trafficLog[QStringLiteral("byMonth")] = byMonth;
}
D_APPLET_CLASS(NetworkMonitorApplet)
DS_END_NAMESPACE
+39
View File
@@ -16,6 +16,7 @@
#include <QDateTime>
#include <QColor>
#include <QSettings>
#include <QJsonObject>
DS_BEGIN_NAMESPACE
@@ -84,6 +85,13 @@ class NetworkMonitorApplet : public DApplet
Q_PROPERTY(QVariantList speedHistoryDownload READ speedHistoryDownload NOTIFY speedHistoryChanged)
// 当前活动接口的上行速度历史采样点,结构同 speedHistoryDownload
Q_PROPERTY(QVariantList speedHistoryUpload READ speedHistoryUpload NOTIFY speedHistoryChanged)
// 流量统计日志(JSON 对象),供 QML 流量统计窗口读取展示
// 结构:{"byDay": {日期: {接口: {rx, tx}}}, "byMonth": {月份: {接口: {rx, tx}}}}
// 设计原因:会话总量重启清零,用户无法了解长期趋势;按日/月聚合让用户看
// 每日使用量和月度汇总,按接口分让多网卡各自独立统计。
// 保存频率:累加每秒执行(内存操作),写盘与通知 QML 降频(每 30 秒一次),
// 避免每秒磁盘 IO 与 QML 重绘
Q_PROPERTY(QJsonObject trafficLog READ trafficLog NOTIFY trafficLogChanged)
public:
explicit NetworkMonitorApplet(QObject *parent = nullptr);
@@ -128,6 +136,8 @@ public:
QString textColor() const;
// 设置任务栏网速字体颜色,空串表示跟随系统主题
void setTextColor(const QString &color);
// 返回流量统计日志(JSON 对象),结构见 trafficLog 属性注释,供 QML 流量统计窗口读取
QJsonObject trafficLog() const;
// 定时器回调,由 m_refreshTimer 每秒调用。非 Q_INVOKABLE(QML 不应直接调用,
// 否则会打破 1 秒定时间隔导致速度计算失真)
@@ -155,6 +165,8 @@ signals:
void speedHistoryChanged();
// 任务栏网速字体颜色变化时通知 QML 更新
void textColorChanged();
// 流量统计日志变化时通知 QML 更新(降频,每 30 秒发射一次)
void trafficLogChanged();
private:
void readNetworkStats();
@@ -178,6 +190,16 @@ private:
qint64 getActiveRxBytes() const;
qint64 getActiveTxBytes() const;
// ---- 流量日志(日/月持久化)----
// 启动时从 traffic_log.json 加载日志;文件不存在或解析失败时降级为空结构,不崩溃
void loadTrafficLog();
// 将日志写入 traffic_log.json(先裁剪超期记录再写盘),供析构与降频保存调用
void saveTrafficLog();
// 将本次流量增量累加到当日/当月/当前活动接口的日志记录中(每秒调用,内存操作)
void appendToTrafficLog(qint64 rxDelta, qint64 txDelta);
// 裁剪超期记录:按日最多 90 天、按月最多 24 个月,超出删除最旧记录
void pruneTrafficLog();
QTimer *m_refreshTimer;
QMap<QString, NetworkInterface> m_interfaces;
QStringList m_interfaceList;
@@ -252,6 +274,23 @@ private:
mutable bool m_historyDirty;
// 重建历史缓存:仅当 m_historyDirty 时由两个 getter 调用
void rebuildHistoryCache() const;
// ---- 流量日志成员 ----
// 完整流量日志 JSON:{"byDay": {日期: {接口: {rx, tx}}}, "byMonth": {月份: {接口: {rx, tx}}}}
// 设计原因:会话总量重启清零,用户无法了解长期趋势;按日/月聚合让用户看
// 每日使用量和月度汇总,按接口分让多网卡各自独立统计
QJsonObject m_trafficLog;
// 日志文件路径(~/.config/jnetapplet/traffic_log.json)
QString m_trafficLogPath;
// 当前日期 "yyyy-MM-dd" 与月份 "yyyy-MM",用于跨日/跨月检测
QString m_currentDate;
QString m_currentMonth;
// 降频保存计数器:每 30 秒(按刷新间隔折算)写盘一次并通知 QML,
// 避免每秒磁盘 IO 与 QML 重绘;析构函数再兜底保存一次
int m_trafficSaveCounter;
// 按日记录最多保留 90 天、按月最多保留 24 个月,超出自动裁剪最旧记录
static constexpr int MAX_DAY_ENTRIES = 90;
static constexpr int MAX_MONTH_ENTRIES = 24;
};
DS_END_NAMESPACE
+70 -2
View File
@@ -78,8 +78,8 @@
</message>
<message>
<location filename="../package/components/NetworkPopup.qml" line="427"/>
<source>Total</source>
<translation>流量总计</translation>
<source>Session Total</source>
<translation>本次会话</translation>
</message>
<message>
<location filename="../package/components/NetworkPopup.qml" line="474"/>
@@ -270,5 +270,73 @@
<source>About</source>
<translation>关于</translation>
</message>
<message>
<location filename="../package/networkview.qml" line="314"/>
<source>Traffic Statistics</source>
<translation>流量统计</translation>
</message>
</context>
<context>
<name>TrafficStatsWindow</name>
<message>
<location filename="../package/components/TrafficStatsWindow.qml" line="132"/>
<source>Traffic Statistics</source>
<translation>流量统计</translation>
</message>
<message>
<location filename="../package/components/TrafficStatsWindow.qml" line="158"/>
<source>By Day</source>
<translation>按日</translation>
</message>
<message>
<location filename="../package/components/TrafficStatsWindow.qml" line="184"/>
<source>By Month</source>
<translation>按月</translation>
</message>
<message>
<location filename="../package/components/TrafficStatsWindow.qml" line="202"/>
<source>Today accumulated</source>
<translation>今日累计</translation>
</message>
<message>
<location filename="../package/components/TrafficStatsWindow.qml" line="214"/>
<source>This month accumulated</source>
<translation>本月累计</translation>
</message>
<message>
<location filename="../package/components/TrafficStatsWindow.qml" line="218"/>
<source>Date</source>
<translation>日期</translation>
</message>
<message>
<location filename="../package/components/TrafficStatsWindow.qml" line="218"/>
<source>Month</source>
<translation>月份</translation>
</message>
<message>
<location filename="../package/components/TrafficStatsWindow.qml" line="225"/>
<source>Interface</source>
<translation>接口</translation>
</message>
<message>
<location filename="../package/components/TrafficStatsWindow.qml" line="232"/>
<source>Download</source>
<translation>下载</translation>
</message>
<message>
<location filename="../package/components/TrafficStatsWindow.qml" line="239"/>
<source>Upload</source>
<translation>上传</translation>
</message>
<message>
<location filename="../package/components/TrafficStatsWindow.qml" line="246"/>
<source>Total</source>
<translation>总计</translation>
</message>
<message>
<location filename="../package/components/TrafficStatsWindow.qml" line="283"/>
<source>No traffic records yet</source>
<translation>暂无流量记录</translation>
</message>
</context>
</TS>