-
Notifications
You must be signed in to change notification settings - Fork 521
fix: keep Windows notification badge state in sync #12451
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
huhuanming
wants to merge
3
commits into
x
Choose a base branch
from
codex/fix-windows-notification-badge-state
base: x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
104 changes: 104 additions & 0 deletions
104
packages/kit-bg/src/desktopApis/WindowsTaskbarBadge.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| import { EventEmitter } from 'events'; | ||
|
|
||
| import { systemPreferences } from 'electron'; | ||
|
|
||
| import WindowsTaskbarBadge from './WindowsTaskbarBadge'; | ||
|
|
||
| import type { BrowserWindow } from 'electron'; | ||
|
|
||
| jest.mock('electron-log/main', () => ({ | ||
| __esModule: true, | ||
| default: { | ||
| error: jest.fn(), | ||
| warn: jest.fn(), | ||
| }, | ||
| })); | ||
|
|
||
| jest.mock('electron', () => { | ||
| const { EventEmitter: MockEventEmitter } = | ||
| jest.requireActual<typeof import('events')>('events'); | ||
| return { | ||
| nativeImage: { | ||
| createFromDataURL: jest.fn(() => ({ | ||
| isEmpty: jest.fn(() => false), | ||
| })), | ||
| }, | ||
| systemPreferences: Object.assign(new MockEventEmitter(), { | ||
| getAccentColor: jest.fn(() => '4cc2ffff'), | ||
| }), | ||
| }; | ||
| }); | ||
|
|
||
| const electronMock = jest.requireMock('electron') as { | ||
| nativeImage: { | ||
| createFromDataURL: jest.Mock; | ||
| }; | ||
| }; | ||
|
|
||
| class FakeWindow extends EventEmitter { | ||
| destroyed = false; | ||
|
|
||
| setOverlayIcon = jest.fn(); | ||
|
|
||
| webContents = { | ||
| executeJavaScript: jest.fn<Promise<string>, [string]>(), | ||
| }; | ||
|
|
||
| isDestroyed = () => this.destroyed; | ||
| } | ||
|
|
||
| function createBadge(window: FakeWindow): WindowsTaskbarBadge { | ||
| return new WindowsTaskbarBadge(window as unknown as BrowserWindow); | ||
| } | ||
|
|
||
| async function flushPromises(): Promise<void> { | ||
| await new Promise<void>((resolve) => { | ||
| setImmediate(resolve); | ||
| }); | ||
| } | ||
|
|
||
| describe('WindowsTaskbarBadge', () => { | ||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| systemPreferences.removeAllListeners(); | ||
| }); | ||
|
|
||
| test('keeps the badge cleared across window show and accent changes', async () => { | ||
| const window = new FakeWindow(); | ||
| window.webContents.executeJavaScript.mockResolvedValue( | ||
| 'data:image/png;base64,badge', | ||
| ); | ||
| const badge = createBadge(window); | ||
|
|
||
| await badge.update(7); | ||
| await badge.update(0); | ||
| window.emit('show'); | ||
| systemPreferences.emit('accent-color-changed', 'ffffffff'); | ||
| await flushPromises(); | ||
|
|
||
| expect(window.webContents.executeJavaScript).toHaveBeenCalledTimes(1); | ||
| expect(window.setOverlayIcon).toHaveBeenLastCalledWith(null, ''); | ||
| }); | ||
|
|
||
| test('ignores a stale render that finishes after the badge is cleared', async () => { | ||
| let resolveRender: ((dataUrl: string) => void) | undefined; | ||
| const window = new FakeWindow(); | ||
| window.webContents.executeJavaScript.mockImplementation( | ||
| () => | ||
| new Promise<string>((resolve) => { | ||
| resolveRender = resolve; | ||
| }), | ||
| ); | ||
| const badge = createBadge(window); | ||
|
|
||
| const pendingRender = badge.update(7); | ||
| await badge.update(0); | ||
| resolveRender?.('data:image/png;base64,badge'); | ||
| await pendingRender; | ||
|
|
||
| expect(electronMock.nativeImage.createFromDataURL.mock.calls).toHaveLength( | ||
| 0, | ||
| ); | ||
| expect(window.setOverlayIcon).toHaveBeenLastCalledWith(null, ''); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,166 @@ | ||
| import { nativeImage, systemPreferences } from 'electron'; | ||
| import logger from 'electron-log/main'; | ||
|
|
||
| import type { BrowserWindow } from 'electron'; | ||
|
|
||
| const BADGE_SIZE = 96; | ||
| const BADGE_RADIUS = 44; | ||
| const MAX_BADGE_COUNT = 99; | ||
| const DEFAULT_ACCENT_COLOR = '#4cc2ff'; | ||
|
|
||
| function normalizeAccentColor(value: string): string { | ||
| const hex = value.replace(/^#/, ''); | ||
| if (/^[0-9a-f]{6}(?:[0-9a-f]{2})?$/i.test(hex)) { | ||
| return `#${hex.slice(0, 6)}`; | ||
| } | ||
| return DEFAULT_ACCENT_COLOR; | ||
| } | ||
|
|
||
| function getAccentColor(): string { | ||
| try { | ||
| return normalizeAccentColor(systemPreferences.getAccentColor()); | ||
| } catch (error) { | ||
| logger.warn('Failed to read Windows accent color', error); | ||
| return DEFAULT_ACCENT_COLOR; | ||
| } | ||
| } | ||
|
|
||
| function getTextColor(backgroundColor: string): string { | ||
| const red = Number.parseInt(backgroundColor.slice(1, 3), 16); | ||
| const green = Number.parseInt(backgroundColor.slice(3, 5), 16); | ||
| const blue = Number.parseInt(backgroundColor.slice(5, 7), 16); | ||
| const brightness = red * 0.2126 + green * 0.7152 + blue * 0.0722; | ||
| return brightness > 160 ? '#000000' : '#ffffff'; | ||
| } | ||
|
|
||
| function buildBadgeScript(count: number): string { | ||
| const label = count > MAX_BADGE_COUNT ? `${MAX_BADGE_COUNT}+` : `${count}`; | ||
| const backgroundColor = getAccentColor(); | ||
| const textColor = getTextColor(backgroundColor); | ||
| const fontSize = label.length > 2 ? 42 : 62; | ||
|
|
||
| return `(() => { | ||
| const canvas = document.createElement('canvas'); | ||
| canvas.width = ${BADGE_SIZE}; | ||
| canvas.height = ${BADGE_SIZE}; | ||
| const context = canvas.getContext('2d'); | ||
| if (!context) return ''; | ||
| context.fillStyle = ${JSON.stringify(backgroundColor)}; | ||
| context.beginPath(); | ||
| context.arc(${BADGE_SIZE / 2}, ${BADGE_SIZE / 2}, ${BADGE_RADIUS}, 0, Math.PI * 2); | ||
| context.fill(); | ||
| context.fillStyle = ${JSON.stringify(textColor)}; | ||
| context.font = ${JSON.stringify(`600 ${fontSize}px "Segoe UI"`)}; | ||
| context.textAlign = 'center'; | ||
| context.textBaseline = 'middle'; | ||
| context.fillText(${JSON.stringify(label)}, ${BADGE_SIZE / 2}, ${BADGE_SIZE / 2}); | ||
| return canvas.toDataURL('image/png'); | ||
| })()`; | ||
| } | ||
|
|
||
| class WindowsTaskbarBadge { | ||
| private window: BrowserWindow | undefined; | ||
|
|
||
| private currentCount = 0; | ||
|
|
||
| private currentOverlayIcon: ReturnType< | ||
| typeof nativeImage.createFromDataURL | ||
| > | null = null; | ||
|
|
||
| private updateVersion = 0; | ||
|
|
||
| constructor(window: BrowserWindow) { | ||
| this.window = window; | ||
| window.on('show', this.handleWindowShow); | ||
| window.once('closed', this.handleWindowClosed); | ||
| systemPreferences.on('accent-color-changed', this.handleAccentColorChanged); | ||
| } | ||
|
|
||
| private getDescription(): string { | ||
| return this.currentCount > 0 | ||
| ? `Unread notifications: ${this.currentCount}` | ||
| : ''; | ||
| } | ||
|
|
||
| private handleWindowShow = () => { | ||
| const window = this.window; | ||
| if (!window || window.isDestroyed()) { | ||
| return; | ||
| } | ||
| window.setOverlayIcon(this.currentOverlayIcon, this.getDescription()); | ||
| }; | ||
|
|
||
| private handleWindowClosed = () => { | ||
| this.updateVersion += 1; | ||
| const window = this.window; | ||
| window?.removeListener('show', this.handleWindowShow); | ||
| systemPreferences.removeListener( | ||
| 'accent-color-changed', | ||
| this.handleAccentColorChanged, | ||
| ); | ||
| this.window = undefined; | ||
| this.currentOverlayIcon = null; | ||
| }; | ||
|
|
||
| private handleAccentColorChanged = () => { | ||
| if (this.currentCount > 0) { | ||
| void this.update(this.currentCount); | ||
| } | ||
| }; | ||
|
|
||
| async update(badgeNumber: number): Promise<void> { | ||
| const count = | ||
| Number.isFinite(badgeNumber) && badgeNumber > 0 | ||
| ? Math.floor(badgeNumber) | ||
| : 0; | ||
| this.updateVersion += 1; | ||
| const updateVersion = this.updateVersion; | ||
| this.currentCount = count; | ||
|
|
||
| const window = this.window; | ||
| if (!window || window.isDestroyed()) { | ||
| return; | ||
| } | ||
|
|
||
| if (count === 0) { | ||
| this.currentOverlayIcon = null; | ||
| window.setOverlayIcon(null, ''); | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| const dataUrl = await window.webContents.executeJavaScript( | ||
| buildBadgeScript(count), | ||
| ); | ||
| if ( | ||
| updateVersion !== this.updateVersion || | ||
| this.window !== window || | ||
| window.isDestroyed() | ||
| ) { | ||
| return; | ||
| } | ||
| if ( | ||
| typeof dataUrl !== 'string' || | ||
| !dataUrl.startsWith('data:image/png;base64,') | ||
| ) { | ||
| logger.warn( | ||
| 'Windows taskbar badge renderer returned invalid image data', | ||
| ); | ||
| return; | ||
| } | ||
|
|
||
| const image = nativeImage.createFromDataURL(dataUrl); | ||
| if (image.isEmpty()) { | ||
| logger.warn('Windows taskbar badge renderer returned an empty image'); | ||
| return; | ||
| } | ||
|
|
||
| this.currentOverlayIcon = image; | ||
| window.setOverlayIcon(image, this.getDescription()); | ||
| } catch (error) { | ||
| logger.error('Failed to update Windows taskbar badge', error); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export default WindowsTaskbarBadge; | ||
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
当窗口已有旧 badge,而新的非零更新在
executeJavaScript、data URL 校验或nativeImage校验任一阶段失败时,这里已经把currentCount更新为新值,但currentOverlayIcon和任务栏仍保留旧图片。之后触发show会再次挂载旧数字,并使用新计数 description,导致可见 badge 与内部状态长期不一致。请把 count 与 overlay icon 作为一次原子提交:仅在最新版本成功生成图片后同时写入;若最新版本渲染失败,则明确清空 overlay 状态,不能继续保留旧图标。