From 73f39f8760e054b0a9528bc9624959a0aadfcf2c Mon Sep 17 00:00:00 2001 From: pompurin404 Date: Mon, 26 Aug 2024 12:17:17 +0800 Subject: [PATCH] complete tray traffic --- src/main/core/mihomoApi.ts | 16 ++++++++++++---- src/main/utils/calc.ts | 28 ++++++++++++++++++++-------- 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/src/main/core/mihomoApi.ts b/src/main/core/mihomoApi.ts index 90e9644..20f0e77 100644 --- a/src/main/core/mihomoApi.ts +++ b/src/main/core/mihomoApi.ts @@ -12,6 +12,7 @@ import svg2img from 'svg2img' const icon = nativeImage.createFromPath(templateIcon) icon.setTemplateImage(true) const base64 = icon.toPNG().toString('base64') +let hasShowTraffic = false let axiosIns: AxiosInstance = null! let mihomoTrafficWs: WebSocket | null = null let trafficRetry = 10 @@ -192,10 +193,12 @@ const mihomoTraffic = async (): Promise => { if (process.platform === 'darwin') { if (showTraffic) { const svgContent = ` - + - ↑ ${calcTraffic(json.up)}/s - ↓ ${calcTraffic(json.down)}/s + + + ${calcTraffic(json.up)}/s + ${calcTraffic(json.down)}/s ` svg2img(svgContent, {}, (error, buffer) => { if (error) return @@ -203,8 +206,13 @@ const mihomoTraffic = async (): Promise => { image.setTemplateImage(true) tray?.setImage(image) }) + hasShowTraffic = true } else { - tray?.setImage(icon) + if (hasShowTraffic) { + hasShowTraffic = false + icon.resize({ height: 16 }) + tray?.setImage(icon) + } } } if (process.platform !== 'linux') { diff --git a/src/main/utils/calc.ts b/src/main/utils/calc.ts index c5e1c11..b2429a9 100644 --- a/src/main/utils/calc.ts +++ b/src/main/utils/calc.ts @@ -1,19 +1,31 @@ export function calcTraffic(byte: number): string { if (byte < 1024) return `${byte} B` byte /= 1024 - if (byte < 1024) return `${Math.round(byte)} KB` + if (byte < 1024) return `${formatNumString(byte)} KB` byte /= 1024 - if (byte < 1024) return `${Math.round(byte)} MB` + if (byte < 1024) return `${formatNumString(byte)} MB` byte /= 1024 - if (byte < 1024) return `${Math.round(byte)} GB` + if (byte < 1024) return `${formatNumString(byte)} GB` byte /= 1024 - if (byte < 1024) return `${Math.round(byte)} TB` + if (byte < 1024) return `${formatNumString(byte)} TB` byte /= 1024 - if (byte < 1024) return `${Math.round(byte)} PB` + if (byte < 1024) return `${formatNumString(byte)} PB` byte /= 1024 - if (byte < 1024) return `${Math.round(byte)} EB` + if (byte < 1024) return `${formatNumString(byte)} EB` byte /= 1024 - if (byte < 1024) return `${Math.round(byte)} ZB` + if (byte < 1024) return `${formatNumString(byte)} ZB` byte /= 1024 - return `${Math.round(byte)} YB` + return `${formatNumString(byte)} YB` +} + +function formatNumString(num: number): string { + let str = num.toFixed(2) + if (str.length <= 5) return str + if (str.length == 6) { + str = num.toFixed(1) + return str + } else { + str = Math.round(num).toString() + return str + } }