desktopTray.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import { app, Menu, nativeImage, Tray } from "electron";
  2. import type { NativeImage } from "electron";
  3. import { join } from "node:path";
  4. import {
  5. DesktopCommandIds,
  6. desktopMenuMessageIds,
  7. getDesktopMenuMessage,
  8. ZCODE_PRODUCT_FLAVOR,
  9. type DesktopCommandId,
  10. type Locale,
  11. } from "@zcode/shared";
  12. import {
  13. blendBadgeIntoBitmap,
  14. renderAntialiasedStatusDotPixels,
  15. resolveBadgeOverlayLabel,
  16. } from "./unreadBadge.js";
  17. let desktopTray: Tray | null = null;
  18. let rebuildDesktopTrayContextMenu: (() => void) | null = null;
  19. let trayLogger: { warn: (...args: unknown[]) => void } | null = null;
  20. // 托盘图在 Windows 通知区域实际显示约 16px。为避免把普通 32px 合成图交给 Shell
  21. // 盲缩导致红点发糊,分别合成原生 1x(16px) 与 2x(32px) 表示;红点尺寸独立于任务栏。
  22. // spec 见 docs/desktop/windows-taskbar-unread-badge.md
  23. const TRAY_LOGICAL_SIZE = 16;
  24. let trayBaseImage: NativeImage | null = null;
  25. const trayBadgeImageCache = new Map<string, NativeImage>();
  26. export function resolveDesktopTrayIconPath(platform: NodeJS.Platform = process.platform) {
  27. // Linux 托盘只接受 PNG(.ico 不会渲染);打包态 icon.png 已由 extraResources 无条件放入
  28. // resources 目录(electron-builder.config.js),Windows 继续用独立托盘 .ico 避免高 DPI 模糊。
  29. if (platform === "linux") {
  30. return app.isPackaged
  31. ? join(process.resourcesPath, "icon.png")
  32. : join(import.meta.dirname, "../../build/icon.png");
  33. }
  34. return app.isPackaged
  35. ? join(process.resourcesPath, "tray_icon.ico")
  36. : join(import.meta.dirname, "../../build/icon.ico");
  37. }
  38. export function createDesktopTray(options: {
  39. platform?: NodeJS.Platform;
  40. getLocale: () => Locale;
  41. showCurrentWindow: () => Promise<void> | void;
  42. executeDesktopCommand: (command: DesktopCommandId) => Promise<unknown>;
  43. quitApp: () => void;
  44. logger: { warn: (...args: unknown[]) => void };
  45. }) {
  46. const platform = options.platform ?? process.platform;
  47. // Linux 驻留能力由 createCloseToTrayCapabilityMonitor 探测决定(spec:
  48. // docs/desktop/linux-close-to-tray.md);这里只挡平台,能力不过关时调用方不应传入 linux。
  49. if (platform !== "win32" && platform !== "linux") {
  50. return null;
  51. }
  52. if (desktopTray) {
  53. return desktopTray;
  54. }
  55. try {
  56. desktopTray = new Tray(resolveDesktopTrayIconPath(platform));
  57. } catch (error) {
  58. options.logger.warn("[desktop-tray] failed to create tray icon", error);
  59. return null;
  60. }
  61. trayLogger = options.logger;
  62. const getLabel = (id: (typeof desktopMenuMessageIds)[keyof typeof desktopMenuMessageIds]) =>
  63. getDesktopMenuMessage(options.getLocale(), id);
  64. const showTrayWindow = () => {
  65. void Promise.resolve(options.showCurrentWindow()).catch((error) => {
  66. options.logger.warn("[desktop-tray] failed to show current window", error);
  67. });
  68. };
  69. const executeTrayCommand = (command: DesktopCommandId) => {
  70. void Promise.resolve(options.showCurrentWindow())
  71. .then(() => options.executeDesktopCommand(command))
  72. .catch((error) => {
  73. options.logger.warn(`[desktop-tray] failed to execute tray command ${command}`, error);
  74. });
  75. };
  76. const rebuildContextMenu = () => {
  77. desktopTray?.setToolTip(getLabel(desktopMenuMessageIds.trayTooltip));
  78. desktopTray?.setContextMenu(
  79. Menu.buildFromTemplate([
  80. {
  81. label: getLabel(desktopMenuMessageIds.trayOpenZCode),
  82. click: showTrayWindow,
  83. },
  84. { type: "separator" },
  85. {
  86. label: getLabel(desktopMenuMessageIds.fileNewTask),
  87. click: () => executeTrayCommand(DesktopCommandIds.NewTask),
  88. },
  89. {
  90. label: getLabel(desktopMenuMessageIds.fileOpenWorkspace),
  91. click: () => executeTrayCommand(DesktopCommandIds.OpenWorkspace),
  92. },
  93. { type: "separator" },
  94. // 更新入口跟随产品身份:Preview(含生产后端的 Preview)禁用更新器,托盘也不能露出入口。
  95. ...(ZCODE_PRODUCT_FLAVOR === "production"
  96. ? [
  97. {
  98. label: getLabel(desktopMenuMessageIds.helpCheckForUpdates),
  99. click: () => executeTrayCommand(DesktopCommandIds.CheckForUpdates),
  100. },
  101. ]
  102. : []),
  103. {
  104. label: getLabel(desktopMenuMessageIds.helpAbout),
  105. click: () => executeTrayCommand(DesktopCommandIds.ShowAbout),
  106. },
  107. {
  108. // 托盘只提供日志诊断入口,避免右键菜单暴露清除全部数据操作;复用应用菜单导出命令。
  109. label: getLabel(desktopMenuMessageIds.helpExportLogs),
  110. click: () => executeTrayCommand(DesktopCommandIds.ExportLogs),
  111. },
  112. { type: "separator" },
  113. {
  114. label: getLabel(desktopMenuMessageIds.trayQuit),
  115. click: () => options.quitApp(),
  116. },
  117. ]),
  118. );
  119. };
  120. rebuildDesktopTrayContextMenu = rebuildContextMenu;
  121. desktopTray.on("click", showTrayWindow);
  122. desktopTray.on("double-click", showTrayWindow);
  123. rebuildContextMenu();
  124. return desktopTray;
  125. }
  126. export function updateWindowsDesktopTrayMenu() {
  127. rebuildDesktopTrayContextMenu?.();
  128. }
  129. function loadTrayBaseImage(): NativeImage | null {
  130. if (trayBaseImage && !trayBaseImage.isEmpty()) {
  131. return trayBaseImage;
  132. }
  133. try {
  134. trayBaseImage = nativeImage.createFromPath(resolveDesktopTrayIconPath());
  135. } catch (error) {
  136. trayLogger?.warn("[desktop-tray] failed to load tray base image for badge", error);
  137. return null;
  138. }
  139. return trayBaseImage.isEmpty() ? null : trayBaseImage;
  140. }
  141. function composeTrayBadgeRepresentation(
  142. label: string,
  143. baseImage: NativeImage,
  144. scale: 1 | 2,
  145. ): Buffer | null {
  146. const size = TRAY_LOGICAL_SIZE * scale;
  147. const resized = baseImage.resize({ width: size, height: size });
  148. const bitmap = resized.toBitmap();
  149. if (bitmap.length !== size * size * 4) {
  150. trayLogger?.warn(
  151. `[desktop-tray] unexpected tray bitmap size ${bitmap.length}, skip badge compose`,
  152. );
  153. return null;
  154. }
  155. const canvas = new Uint8Array(bitmap);
  156. // 托盘保持约 8px 逻辑直径,右上角完整圆;4× 超采样后按原生尺寸合成。
  157. const dotSize = 5 * scale;
  158. const badge = renderAntialiasedStatusDotPixels({
  159. size: dotSize,
  160. centerX: 2.75 * scale,
  161. centerY: 2.25 * scale,
  162. radius: 1.875 * scale,
  163. });
  164. blendBadgeIntoBitmap({
  165. base: canvas,
  166. size,
  167. badge,
  168. badgeSize: dotSize,
  169. originX: size - dotSize,
  170. originY: 0,
  171. });
  172. return Buffer.from(canvas);
  173. }
  174. function composeTrayBadgeImage(label: string, baseImage: NativeImage): NativeImage | null {
  175. const cached = trayBadgeImageCache.get(label);
  176. if (cached) return cached;
  177. const oneX = composeTrayBadgeRepresentation(label, baseImage, 1);
  178. const twoX = composeTrayBadgeRepresentation(label, baseImage, 2);
  179. if (!oneX || !twoX) return null;
  180. const image = nativeImage.createEmpty();
  181. image.addRepresentation({
  182. scaleFactor: 1,
  183. width: 16,
  184. height: 16,
  185. buffer: oneX,
  186. });
  187. image.addRepresentation({
  188. scaleFactor: 2,
  189. width: 32,
  190. height: 32,
  191. buffer: twoX,
  192. });
  193. trayBadgeImageCache.set(label, image);
  194. return image;
  195. }
  196. // 未读计数变化时同步托盘角标:非零在图标右上角贴数字徽章,零恢复原图。
  197. // macOS 无托盘(createDesktopTray 返回 null),由 Dock 角标承担,这里天然 no-op。
  198. export function applyDesktopTrayUnreadBadge(totalUnreadCount: number): void {
  199. if (!desktopTray) {
  200. return;
  201. }
  202. const label = resolveBadgeOverlayLabel(totalUnreadCount);
  203. if (!label) {
  204. const base = loadTrayBaseImage();
  205. if (base) {
  206. desktopTray.setImage(base);
  207. }
  208. return;
  209. }
  210. const base = loadTrayBaseImage();
  211. if (!base) {
  212. return;
  213. }
  214. const image = composeTrayBadgeImage(label, base);
  215. if (image) {
  216. desktopTray.setImage(image);
  217. }
  218. }