A full-featured download manager.
feat: tray speedometer
Dr_rOot8a6beda3359a
diff --git a/.electron-vue/webpack.renderer.config.js b/.electron-vue/webpack.renderer.config.jsindex 41fd49b1..ed4830db 100644--- a/.electron-vue/webpack.renderer.config.js+++ b/.electron-vue/webpack.renderer.config.js@@ -32,6 +32,13 @@ let rendererConfig = {],module: {rules: [+ {+ test: /\.worker\.js$/,+ use: {+ loader: 'worker-loader',+ options: { name: '[name].js' }+ }+ },{test: /\.(js|vue)$/,enforce: 'pre',@@ -194,7 +201,8 @@ let rendererConfig = {output: {filename: '[name].js',libraryTarget: 'commonjs2',- path: path.join(__dirname, '../dist/electron')+ path: path.join(__dirname, '../dist/electron'),+ globalObject: 'this'},resolve: {alias: {diff --git a/.electron-vue/webpack.web.config.js b/.electron-vue/webpack.web.config.jsindex 5842df74..e4380f62 100644--- a/.electron-vue/webpack.web.config.js+++ b/.electron-vue/webpack.web.config.js@@ -32,6 +32,13 @@ let webConfig = {],module: {rules: [+ {+ test: /\.worker\.js$/,+ use: {+ loader: 'worker-loader',+ options: { name: '[name].js' }+ }+ },{test: /\.(js|vue)$/,enforce: 'pre',@@ -181,7 +188,8 @@ let webConfig = {],output: {filename: '[name].js',- path: path.join(__dirname, '../dist/web')+ path: path.join(__dirname, '../dist/web'),+ globalObject: 'this'},resolve: {alias: {diff --git a/package.json b/package.jsonindex aa1f6768..1422dca2 100644--- a/package.json+++ b/package.json@@ -258,6 +258,7 @@"webpack-cli": "^3.3.11","webpack-dev-server": "^3.11.0","webpack-hot-middleware": "^2.25.0",- "webpack-merge": "^4.2.2"+ "webpack-merge": "^4.2.2",+ "worker-loader": "^2.0.0"}}diff --git a/src/main/Application.js b/src/main/Application.jsindex 546ff770..b609478c 100644--- a/src/main/Application.js+++ b/src/main/Application.js@@ -145,7 +145,34 @@ export default class Application extends EventEmitter {initTrayManager () {this.trayManager = new TrayManager({- theme: this.configManager.getUserConfig('tray-theme')+ theme: this.configManager.getUserConfig('tray-theme'),+ systemTheme: this.themeManager.getSystemTheme(),+ speedometer: this.configManager.getUserConfig('tray-speedometer')+ })++ this.watchTraySpeedometerEnabledChange()++ this.trayManager.on('mouse-down', ({ focused }) => {+ this.sendCommandToAll('application:update-tray-focused', { focused })+ })++ this.trayManager.on('mouse-up', ({ focused }) => {+ this.sendCommandToAll('application:update-tray-focused', { focused })+ })++ this.trayManager.on('drop-files', (files = []) => {+ this.handleFile(files[0])+ })++ this.trayManager.on('drop-text', (text) => {+ this.handleProtocol(text)+ })+ }++ watchTraySpeedometerEnabledChange () {+ this.configManager.userConfig.onDidChange('tray-speedometer', async (newValue, oldValue) => {+ logger.info('[Motrix] detected tray speedometer value change event:', newValue, oldValue)+ this.trayManager.handleSpeedometerEnableChange(newValue)})}@@ -411,7 +438,7 @@ export default class Application extends EventEmitter {initThemeManager () {this.themeManager = new ThemeManager()this.themeManager.on('system-theme-change', (theme) => {- this.trayManager.changeIconTheme(theme)+ this.trayManager.handleSystemThemeChange(theme)this.sendCommandToAll('application:update-system-theme', { theme })})}@@ -533,6 +560,10 @@ export default class Application extends EventEmitter {handleCommands () {this.on('application:save-preference', this.savePreference)+ this.on('application:update-tray', (tray) => {+ this.trayManager.updateTrayByImage(tray)+ })+this.on('application:relaunch', () => {this.relaunch()})@@ -578,8 +609,8 @@ export default class Application extends EventEmitter {this.on('application:change-locale', (locale) => {this.localeManager.changeLanguageByLocale(locale).then(() => {- this.trayManager.setup(locale)this.menuManager.handleLocaleChange(locale)+ this.trayManager.handleLocaleChange(locale)})})@@ -675,7 +706,7 @@ export default class Application extends EventEmitter {this.configManager.systemConfig.onDidAnyChange(() => this.handleConfigChange('system'))this.on('download-status-change', (downloading) => {- this.trayManager.updateTrayByStatus(downloading)+ this.trayManager.handleDownloadStatusChange(downloading)if (downloading) {this.energyManager.startPowerSaveBlocker()} else {@@ -683,8 +714,9 @@ export default class Application extends EventEmitter {}})- this.on('download-speed-change', (speed) => {- this.dockManager.setBadge(speed)+ this.on('speed-change', (speed) => {+ this.dockManager.handleSpeedChange(speed)+ this.trayManager.handleSpeedChange(speed)})this.on('task-download-complete', (task, path) => {diff --git a/src/main/core/ConfigManager.js b/src/main/core/ConfigManager.jsindex f5a5cdb5..4daf1090 100644--- a/src/main/core/ConfigManager.js+++ b/src/main/core/ConfigManager.js@@ -117,6 +117,7 @@ export default class ConfigManager {NGOSANG_TRACKERS_BEST_URL],'tray-theme': APP_THEME.AUTO,+ 'tray-speedometer': is.macOS(),'update-channel': 'latest','use-proxy': false,'window-state': {}diff --git a/src/main/ui/TrayManager.js b/src/main/ui/TrayManager.jsindex 2a59a9d0..9d9b075c 100644--- a/src/main/ui/TrayManager.js+++ b/src/main/ui/TrayManager.js@@ -1,54 +1,154 @@import { EventEmitter } from 'events'import { join } from 'path'-import { Tray, Menu, nativeTheme } from 'electron'+import { Tray, Menu, nativeImage } from 'electron'import is from 'electron-is'+import { APP_THEME } from '@shared/constants'+import { getInverseTheme } from '@shared/utils'+import { getI18n } from './Locale'import {translateTemplate,flattenMenuItems,updateStates} from '../utils/menu'-import { getI18n } from '@/ui/Locale'-import { APP_THEME } from '@shared/constants'+import { convertArrayBufferToBuffer } from '../utils/index'+// import logger from '../core/Logger'let tray = null+const { platform } = processexport default class TrayManager extends EventEmitter {constructor (options = {}) {super()+ this.options = optionsthis.theme = options.theme || APP_THEME.AUTO++ this.systemTheme = options.systemTheme+ this.inverseSystemTheme = getInverseTheme(this.systemTheme)++ this.speedometer = options.speedometer+this.i18n = getI18n()this.menu = null+ this.cache = {}++ this.uploadSpeed = 0+ this.downloadSpeed = 0+ this.status = false+ this.focused = false- this.load()this.init()- this.setup()+ }++ init () {+ this.loadTemplate()++ this.loadImages()++ this.initTray()++ this.setupMenu()+this.handleEvents()}- load () {+ loadTemplate () {this.template = require('../menus/tray.json')+ }++ loadImages () {+ switch (platform) {+ case 'darwin':+ this.loadImagesForMacOS()+ break+ case 'win32':+ this.loadImagesForWindows()+ break+ case 'linux':+ this.loadImagesForLinux()+ break++ default:+ this.loadImagesForDefault()+ break+ }+ }++ loadImagesForMacOS () {+ const { systemTheme, inverseSystemTheme } = this++ this.normalIcon = this.getFromCacheOrCreateImage(`mo-tray-${systemTheme}-normal.png`)+ this.activeIcon = this.getFromCacheOrCreateImage(`mo-tray-${systemTheme}-active.png`)++ // if (systemTheme === APP_THEME.DARK) {+ // this.inverseNormalIcon = this.normalIcon+ // this.inverseActiveIcon = this.activeIcon+ // } else {+ this.inverseNormalIcon = this.getFromCacheOrCreateImage(`mo-tray-${inverseSystemTheme}-normal.png`)+ this.inverseActiveIcon = this.getFromCacheOrCreateImage(`mo-tray-${inverseSystemTheme}-active.png`)+ // }+ }++ loadImagesForWindows () {+ this.normalIcon = this.getFromCacheOrCreateImage('mo-tray-colorful-normal.png')+ this.activeIcon = this.getFromCacheOrCreateImage('mo-tray-colorful-active.png')+ }++ loadImagesForLinux () {+ const { theme } = this+ if (theme === APP_THEME.AUTO) {+ this.normalIcon = this.getFromCacheOrCreateImage('mo-tray-dark-normal.png')+ this.activeIcon = this.getFromCacheOrCreateImage('mo-tray-dark-active.png')+ } else {+ this.normalIcon = this.getFromCacheOrCreateImage(`mo-tray-${theme}-normal.png`)+ this.activeIcon = this.getFromCacheOrCreateImage(`mo-tray-${theme}-active.png`)+ }+ }- let theme = APP_THEME.LIGHT+ loadImagesForDefault () {+ this.normalIcon = this.getFromCacheOrCreateImage('mo-tray-light-normal.png')+ this.activeIcon = this.getFromCacheOrCreateImage('mo-tray-light-active.png')+ }- if (is.windows()) {- theme = 'colorful'- } else if (is.macOS()) {- theme = nativeTheme.shouldUseDarkColors ? APP_THEME.DARK : APP_THEME.LIGHT- } else if (is.linux()) {- theme = (this.theme === APP_THEME.AUTO) ? APP_THEME.DARK : this.theme+ getFromCacheOrCreateImage (key) {+ let file = this.getCache(key)+ if (file) {+ return file}- this.setIcons(theme)+ file = nativeImage.createFromPath(join(__static, `./${key}`))+ this.setCache(key, file)+ return file+ }++ getCache (key) {+ return this.cache[key]}- setIcons (theme) {- this.normalIcon = join(__static, `./mo-tray-${theme}-normal.png`)- this.activeIcon = join(__static, `./mo-tray-${theme}-active.png`)+ setCache (key, value) {+ this.cache[key] = value}- build () {+ loadIcon (theme, scale) {+ const status = this.status ? 'active' : 'normal'+ const fileName = `mo-tray-${theme}-${status}@${scale}x.png`+ const bufferKey = `buffer-${fileName}`+ const buffer = this.getCache(bufferKey)++ if (buffer) {+ return buffer+ }++ const image = this.getFromCacheOrCreateImage(fileName)+ const result = image.toPNG()++ this.setCache(bufferKey, result)++ return result+ }++ buildMenu () {const keystrokesByCommand = {}for (const item in this.keymap) {keystrokesByCommand[this.keymap[item]] = item@@ -61,14 +161,17 @@ export default class TrayManager extends EventEmitter {this.items = flattenMenuItems(this.menu)}- setup () {- this.build()+ setupMenu () {+ this.buildMenu()this.updateContextMenu()}- init () {- tray = new Tray(this.normalIcon)+ initTray () {+ const { icon } = this.getIcons()+ tray = new Tray(icon)+ // tray.setPressedImage(inverseIcon)+tray.setToolTip('Motrix')}@@ -77,11 +180,15 @@ export default class TrayManager extends EventEmitter {tray.on('click', this.handleTrayClick)// macOS, Windows- tray.on('double-click', this.handleTrayDbClick)+ // tray.on('double-click', this.handleTrayDbClick)tray.on('right-click', this.handleTrayRightClick)+ tray.on('mouse-down', this.handleTrayMouseDown)+ tray.on('mouse-up', this.handleTrayMouseUp)// macOS only- tray.on('drop-files', this.handleTrayDropFile)+ tray.setIgnoreDoubleClickEvents(true)+ tray.on('drop-files', this.handleTrayDropFiles)+ tray.on('drop-text', this.handleTrayDropText)}handleTrayClick = (event) => {@@ -99,31 +206,83 @@ export default class TrayManager extends EventEmitter {tray.popUpContextMenu(this.menu)}- handleTrayDropFile = (event, files) => {- global.application.show()- global.application.handleFile(files[0])+ handleTrayMouseDown = (event) => {+ event.preventDefault()++ this.focused = true+ this.emit('mouse-down', {+ focused: true,+ theme: this.inverseSystemTheme+ })+ this.renderTray()}- updateTrayByStatus (status) {- this.status = status- this.updateTray()+ handleTrayMouseUp = (event) => {+ event.preventDefault()++ this.focused = false+ this.emit('mouse-up', {+ focused: false,+ theme: this.theme+ })+ this.renderTray()+ }++ handleTrayDropFiles = (event, files) => {+ event.preventDefault()+ this.emit('drop-files', files)+ }++ handleTrayDropText = (event, text) => {+ event.preventDefault()+ this.emit('drop-text', text)+ }++ toggleSpeedometer (enabled) {+ this.speedometer = enabled}- updateTray () {- const icon = this.status ? this.activeIcon : this.normalIcon+ async renderTray () {+ if (this.speedometer) {+ return+ }++ const { icon } = this.getIcons()+tray.setImage(icon)+ // tray.setPressedImage(inverseIcon)this.updateContextMenu()}- changeIconTheme (theme = APP_THEME.LIGHT) {- if (!is.macOS()) {- return+ getIcons () {+ const { focused, status, systemTheme } = this++ const icon = status ? this.activeIcon : this.normalIcon+ if (systemTheme === APP_THEME.DARK) {+ return {+ icon+ }}- this.setIcons(theme)+ const inverseIcon = status ? this.inverseActiveIcon : this.inverseNormalIcon++ return {+ icon: focused ? inverseIcon : icon+ // inverseIcon: focused ? icon : inverseIcon+ }+ }++ updateContextMenu () {+ /**+ * Linux requires setContextMenu to be called+ * in order for the context menu to populate correctly+ */+ if (process.platform !== 'linux') {+ return+ }- this.updateTray()+ tray.setContextMenu(this.menu)}updateMenuStates (visibleStates, enabledStates, checkedStates) {@@ -146,24 +305,75 @@ export default class TrayManager extends EventEmitter {this.updateMenuStates(null, enabledStates, null)}- updateContextMenu () {- /**- * Linux requires setContextMenu to be called- * in order for the context menu to populate correctly- */- if (process.platform !== 'linux') {+ updateTrayFromDataURL (trayDataURL) {+ const tempImage = nativeImage.createFromDataURL(trayDataURL)+ const pngData = tempImage.toPNG()+ const image = nativeImage.createFromBuffer(pngData, {+ scaleFactor: 2+ })++ tray.setImage(image)+ }++ handleLocaleChange (locale) {+ this.setupMenu()+ }++ handleSpeedometerEnableChange (enabled) {+ this.toggleSpeedometer(enabled)++ this.renderTray()+ }++ handleSystemThemeChange (systemTheme = APP_THEME.LIGHT) {+ if (!is.macOS()) {return}- tray.setContextMenu(this.menu)+ this.systemTheme = systemTheme+ this.inverseSystemTheme = getInverseTheme(systemTheme)++ this.loadImages()++ this.renderTray()+ }++ handleDownloadStatusChange (status) {+ this.status = status++ this.renderTray()+ }++ async handleSpeedChange ({ uploadSpeed, downloadSpeed }) {+ if (!this.speedometer) {+ return+ }++ this.uploadSpeed = uploadSpeed+ this.downloadSpeed = downloadSpeed++ await this.renderTray()+ }++ async updateTrayByImage (ab) {+ const buffer = convertArrayBufferToBuffer(ab)+ const image = nativeImage.createFromBuffer(buffer, {+ scaleFactor: 2+ })++ tray.setImage(image)}destroy () {if (tray) {tray.removeListener('click', this.handleTrayClick)- tray.removeListener('double-click', this.handleTrayDbClick)+ // tray.removeListener('double-click', this.handleTrayDbClick)tray.removeListener('right-click', this.handleTrayRightClick)- tray.removeListener('drop-files', this.handleTrayDropFile)+ tray.removeListener('mouse-down', this.handleTrayMouseDown)+ tray.removeListener('mouse-up', this.handleTrayMouseUp)++ tray.removeListener('drop-files', this.handleTrayDropFiles)+ tray.removeListener('drop-text', this.handleTrayDropText)}tray.destroy()diff --git a/src/main/utils/index.js b/src/main/utils/index.jsindex c304951f..4faeae4c 100644--- a/src/main/utils/index.js+++ b/src/main/utils/index.js@@ -141,3 +141,12 @@ export const getSystemTheme = () => {result = nativeTheme.shouldUseDarkColors ? APP_THEME.DARK : APP_THEME.LIGHTreturn result}++export const convertArrayBufferToBuffer = (arrayBuffer) => {+ const buffer = Buffer.alloc(arrayBuffer.byteLength)+ const view = new Uint8Array(arrayBuffer)+ for (var i = 0; i < buffer.length; ++i) {+ buffer[i] = view[i]+ }+ return buffer+}diff --git a/src/renderer/components/Native/DynamicTray.vue b/src/renderer/components/Native/DynamicTray.vuenew file mode 100644index 00000000..a0cbade3--- /dev/null+++ b/src/renderer/components/Native/DynamicTray.vue@@ -0,0 +1,118 @@+<template>+<div style="display: none;">+ <img+ id="tray-icon-light-normal"+ src="static/[email protected]"+ srcset="static/[email protected] 1x, static/[email protected]"+ >+ <img+ id="tray-icon-light-active"+ src="static/[email protected]"+ srcset="static/[email protected] 1x, static/[email protected]"+ >+ <img+ id="tray-icon-dark-normal"+ src="static/[email protected]"+ srcset="static/[email protected] 1x, static/[email protected]"+ >+ <img+ id="tray-icon-dark-active"+ src="static/[email protected]"+ srcset="static/[email protected] 1x, static/[email protected]"+ >+</div>+</template>++<script>+ import { mapState } from 'vuex'++ import { getInverseTheme } from '@shared/utils'+ import { APP_THEME } from '@shared/constants'++ const cache = {}++ export default {+ name: 'mo-dynamic-tray',+ data () {+ return {+ width: 66,+ height: 16,+ icon: null+ }+ },+ computed: {+ ...mapState('app', {+ iconStatus: state => state.stat.numActive > 0 ? 'active' : 'normal',+ theme: state => state.systemTheme,+ focused: state => state.trayFocused,+ uploadSpeed: state => state.stat.uploadSpeed,+ downloadSpeed: state => state.stat.downloadSpeed,+ speed: state => state.stat.uploadSpeed + state.stat.downloadSpeed+ }),+ scale () {+ return window.devicePixelRatio > 1 ? 2 : 1+ },+ currentTheme () {+ const { theme, focused } = this+ if (theme === APP_THEME.DARK) {+ return theme+ }++ return focused ? getInverseTheme(theme) : theme+ },+ iconKey () {+ const { iconStatus, currentTheme } = this+ return `tray-icon-${currentTheme}-${iconStatus}`+ }+ },+ watch: {+ async speed (val) {+ await this.drawTray()+ },+ async iconKey (val) {+ await this.drawTray()+ }+ },+ mounted () {+ setTimeout(async () => {+ await this.drawTray()+ }, 200)+ },+ methods: {+ async getIcon (key) {+ if (cache[key]) {+ return cache[key]+ }++ const iconImage = document.getElementById(key)+ const result = await createImageBitmap(iconImage)+ cache[key] = result++ return result+ },+ async drawTray () {+ const {+ currentTheme: theme,+ uploadSpeed,+ downloadSpeed,+ scale,+ iconKey+ } = this+ console.log('currentTheme====>', theme, iconKey)++ const icon = await this.getIcon(iconKey)++ global.app.trayWorker.postMessage({+ type: 'tray:draw',+ payload: {+ theme,+ icon,+ uploadSpeed,+ downloadSpeed,+ scale+ }+ })+ }+ }+ }+</script>diff --git a/src/renderer/pages/index/App.vue b/src/renderer/pages/index/App.vueindex 408cf137..1428e49a 100644--- a/src/renderer/pages/index/App.vue+++ b/src/renderer/pages/index/App.vue@@ -9,6 +9,7 @@:secret="rpcSecret"/><mo-ipc v-if="isRenderer" />+ <mo-dynamic-tray v-if="enableTraySpeedometer" /></div></template>@@ -17,18 +18,21 @@import { mapState } from 'vuex'import { getLangDirection } from '@shared/utils'import { APP_THEME } from '@shared/constants'- import TitleBar from '@/components/Native/TitleBar'+ import DynamicTray from '@/components/Native/DynamicTray'import EngineClient from '@/components/Native/EngineClient'import Ipc from '@/components/Native/Ipc'+ import TitleBar from '@/components/Native/TitleBar'export default {name: 'Motrix',components: {- [TitleBar.name]: TitleBar,+ [DynamicTray.name]: DynamicTray,[EngineClient.name]: EngineClient,- [Ipc.name]: Ipc+ [Ipc.name]: Ipc,+ [TitleBar.name]: TitleBar},computed: {+ isMac: () => is.macOS(),isRenderer: () => is.renderer(),...mapState('app', {systemTheme: state => state.systemTheme@@ -37,6 +41,7 @@showWindowActions: state => {return (is.windows() || is.linux()) && state.config.hideAppMenu},+ traySpeedometer: state => state.config.traySpeedometer,rpcSecret: state => state.config.rpcSecret,theme: state => state.config.theme,locale: state => state.config.locale,@@ -54,6 +59,10 @@},dirClass () {return `dir-${this.dir}`+ },+ enableTraySpeedometer () {+ const { traySpeedometer, isMac, isRenderer } = this+ return traySpeedometer && isMac && isRenderer}},methods: {diff --git a/src/renderer/pages/index/commands.js b/src/renderer/pages/index/commands.jsindex e5d3c881..0480daa8 100644--- a/src/renderer/pages/index/commands.js+++ b/src/renderer/pages/index/commands.js@@ -25,6 +25,11 @@ const updateTheme = (payload = {}) => {store.dispatch('preference/updateThemeConfig', theme)}+const updateTrayFocused = (payload = {}) => {+ const { focused } = payload+ store.dispatch('app/updateTrayFocused', focused)+}+const showAboutPanel = () => {store.dispatch('app/showAboutPanel')}@@ -178,3 +183,4 @@ commands.register('application:select-all-task', selectAllTask)commands.register('application:update-preference-config', fetchPreference)commands.register('application:update-system-theme', updateSystemTheme)commands.register('application:update-theme', updateTheme)+commands.register('application:update-tray-focused', updateTrayFocused)diff --git a/src/renderer/pages/index/main.js b/src/renderer/pages/index/main.jsindex 6e483736..dc3f514d 100644--- a/src/renderer/pages/index/main.js+++ b/src/renderer/pages/index/main.js@@ -1,4 +1,5 @@import is from 'electron-is'+import { ipcRenderer } from 'electron'import Vue from 'vue'import VueI18Next from '@panter/vue-i18next'import { sync } from 'vuex-router-sync'@@ -13,9 +14,42 @@ import { getLocaleManager } from '@/components/Locale'import Icon from '@/components/Icons/Icon'import Msg from '@/components/Msg'import { commands } from '@/components/CommandManager/instance'+import TrayWorker from '@/workers/tray.worker'import '@/components/Theme/Index.scss'+const updateTray = is.renderer() ? async (payload) => {+ const { tray } = payload+ if (!tray) {+ return+ }++ const ab = await tray.arrayBuffer()+ ipcRenderer.send('command', 'application:update-tray', ab)+} : () => {}++function initTrayWorker () {+ const worker = new TrayWorker()++ worker.addEventListener('message', (event) => {+ const { type, payload } = event.data++ switch (type) {+ case 'initialized':+ case 'log':+ console.log('[Motrix] Log from Tray Worker: ', payload)+ break+ case 'tray:drawed':+ updateTray(payload)+ break+ default:+ console.warn('[Motrix] Tray Worker unhandled message type:', type, payload)+ }+ })++ return worker+}+function init (config) {if (is.renderer()) {Vue.use(require('vue-electron'))@@ -58,6 +92,8 @@ function init (config) {global.app.commands = commandsrequire('./commands')+ global.app.trayWorker = initTrayWorker()+setTimeout(() => {loading.close()}, 400)diff --git a/src/renderer/store/modules/app.js b/src/renderer/store/modules/app.jsindex 4ec6fa3a..974d0529 100644--- a/src/renderer/store/modules/app.js+++ b/src/renderer/store/modules/app.js@@ -9,6 +9,7 @@ const MAX_INTERVAL = 6000const state = {systemTheme: getSystemTheme(),+ trayFocused: false,aboutPanelVisible: false,engineInfo: {version: '',@@ -37,6 +38,9 @@ const mutations = {UPDATE_SYSTEM_THEME (state, theme) {state.systemTheme = theme},+ UPDATE_TRAY_FOCUSED (state, focused) {+ state.trayFocused = focused+ },UPDATE_ABOUT_PANEL_VISIBLE (state, visible) {state.aboutPanelVisible = visible},@@ -95,6 +99,9 @@ const actions = {updateSystemTheme ({ commit }, theme) {commit('UPDATE_SYSTEM_THEME', theme)},+ updateTrayFocused ({ commit }, focused) {+ commit('UPDATE_TRAY_FOCUSED', focused)+ },showAboutPanel ({ commit }) {commit('UPDATE_ABOUT_PANEL_VISIBLE', true)},diff --git a/src/renderer/workers/tray.worker.js b/src/renderer/workers/tray.worker.jsnew file mode 100644index 00000000..9c0b466b--- /dev/null+++ b/src/renderer/workers/tray.worker.js@@ -0,0 +1,68 @@+/* eslint no-unused-vars: 'off' */+import { TRAY_CANVAS_CONFIG } from '@shared/constants'+import { draw } from '@shared/utils/tray'++let idx = 0+let canvas++const initCanvas = () => {+ if (canvas) {+ return canvas+ }++ const { WIDTH, HEIGHT } = TRAY_CANVAS_CONFIG+ return new OffscreenCanvas(WIDTH, HEIGHT)+}++const drawTray = async (payload) => {+ self.postMessage({+ type: 'log',+ payload+ })++ if (!canvas) {+ canvas = initCanvas()+ }++ try {+ const tray = await draw({+ canvas,+ ...payload+ })++ self.postMessage({+ type: 'tray:drawed',+ payload: {+ idx,+ tray+ }+ })++ idx += 1+ } catch (error) {+ logger(error.message)+ }+}++const logger = (text) => {+ self.postMessage({+ type: 'log',+ payload: text+ })+}++self.postMessage({+ type: 'initialized',+ payload: Date.now()+})++self.addEventListener('message', (event) => {+ const { type, payload } = event.data+ switch (type) {+ case 'tray:draw':+ drawTray(payload)+ break+ default:+ logger(JSON.stringify(event.data))+ }+})diff --git a/src/shared/configKeys.js b/src/shared/configKeys.jsindex aea16a61..306c5687 100644--- a/src/shared/configKeys.js+++ b/src/shared/configKeys.js@@ -23,6 +23,7 @@ const userKeys = ['task-notification','theme','tracker-source',+ 'tray-speedometer','use-proxy']diff --git a/src/shared/constants.js b/src/shared/constants.jsindex 7ad5b142..803baa1c 100644--- a/src/shared/constants.js+++ b/src/shared/constants.js@@ -115,3 +115,12 @@ export const LOGIN_SETTING_OPTIONS = {'--opened-at-login=1']}++export const TRAY_CANVAS_CONFIG = {+ WIDTH: 66,+ HEIGHT: 16,+ ICON_WIDTH: 16,+ ICON_HEIGHT: 16,+ TEXT_WIDTH: 46,+ TEXT_FONT_SIZE: 8+}diff --git a/src/shared/utils/index.js b/src/shared/utils/index.jsindex 54f62eac..fe32e90a 100644--- a/src/shared/utils/index.js+++ b/src/shared/utils/index.js@@ -13,11 +13,11 @@ import {} from 'lodash'import { userKeys, systemKeys, needRestartKeys } from '@shared/configKeys'-import { ENGINE_RPC_HOST } from '@shared/constants'+import { APP_THEME, ENGINE_RPC_HOST } from '@shared/constants'export function bytesToSize (bytes) {const b = parseInt(bytes, 10)- const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']+ const sizes = ['B', 'KB', 'MB', 'GB', 'TB']if (b === 0) { return '0 KB' }const i = parseInt(Math.floor(Math.log(b) / Math.log(1024)), 10)if (i === 0) { return `${b} ${sizes[i]}` }@@ -593,3 +593,7 @@ export const intersection = (array1 = [], array2 = []) => {return array1.filter(value => array2.includes(value))}++export const getInverseTheme = (theme) => {+ return (theme === APP_THEME.LIGHT) ? APP_THEME.DARK : APP_THEME.LIGHT+}diff --git a/src/shared/utils/tray.js b/src/shared/utils/tray.jsnew file mode 100644index 00000000..dab7344c--- /dev/null+++ b/src/shared/utils/tray.js@@ -0,0 +1,80 @@+import { APP_THEME, TRAY_CANVAS_CONFIG } from '@shared/constants'+import { bytesToSize } from '@shared/utils'++const lightTextColor = '#000'+const darkTextColor = '#fff'+const baseWidth = TRAY_CANVAS_CONFIG.WIDTH+const baseHeight = TRAY_CANVAS_CONFIG.HEIGHT+const baseIconWidth = TRAY_CANVAS_CONFIG.ICON_WIDTH+const baseIconHeight = TRAY_CANVAS_CONFIG.ICON_HEIGHT+const baseTextWidth = TRAY_CANVAS_CONFIG.TEXT_WIDTH+const baseFontSize = TRAY_CANVAS_CONFIG.TEXT_FONT_SIZE+const fontFamily = 'Arial'++export const draw = async ({+ canvas,+ theme,+ icon,+ uploadSpeed,+ downloadSpeed,+ scale,+ resultType+}) => {+ if (!canvas) {+ throw new Error('canvas is required')+ }++ const width = baseWidth * scale+ const height = baseHeight * scale+ const textColor = (theme === APP_THEME.LIGHT) ? lightTextColor : darkTextColor+ const fontSize = (baseFontSize * scale) + 1+ const textFont = `${fontSize}px "${fontFamily}"`+ const iconWidth = baseIconWidth * scale+ const iconHeight = baseIconHeight * scale+ const textWidth = baseTextWidth * scale++ if (canvas.width !== width) {+ canvas.width = width+ }++ if (canvas.height !== height) {+ canvas.height = height+ }++ const ctx = canvas.getContext('2d')+ ctx.clearRect(0, 0, canvas.width, canvas.height)++ if (icon) {+ ctx.drawImage(icon, 0, 0, iconWidth, iconHeight)+ }++ ctx.font = textFont+ ctx.textBaseline = 'top'+ ctx.textAlign = 'right'+ ctx.fillStyle = textColor++ const uploadText = `${bytesToSize(uploadSpeed)}/s`+ const uploadTextY = 0+ ctx.fillText(uploadText, width, uploadTextY, textWidth)++ const downloadText = `${bytesToSize(downloadSpeed)}/s`+ const downloadTextY = baseFontSize * scale + 0.5+ ctx.fillText(downloadText, width, downloadTextY, textWidth)++ const result = transferCanvasTo(canvas, resultType)++ return result+}++export const transferCanvasTo = (canvas, type) => {+ switch (type) {+ case 'DATA_URL':+ return canvas.toDataURL()+ case 'BLOB':+ return canvas.convertToBlob()+ case 'BITMAP':+ return canvas.transferToImageBitmap()+ default:+ return canvas.convertToBlob()+ }+}