Files
OpenTerminal/src/main/tray.ts
T
Bill 4e5377f49c
CI / typecheck + test + build (windows) (push) Canceled after 0s
fix: hardening round from code review (4 P1 + 15 P2)
P1:
- settingsStore: back up an unparseable settings.json to .bak before
  falling back to defaults, so the next mutation can no longer silently
  wipe custom themes/highlight rules
- ptyDispatcher: fan out per-session data/exit handlers (Set instead of
  a single slot) so SSH split panes stop stealing each other's stream
- FilePanel: monotonic refresh token keeps stale listings from painting
  over a newer navigation; upload finish no longer yanks the panel back
- settings.css: active settings-tab label derives from --chrome-fg so it
  stays visible on the shipped light themes

P2 (main/renderer):
- paste guard: a paste ending in a newline always confirms
- Workspace: closing an SSH pane no longer seeds the local cwd with a
  remote path
- tray: skip close-dialog continuation on a destroyed window
- commands: close zombie 'in-progress' session logs at hydrate
- zmodem: clear the stale offer timer before arming a new one
- connectionsStore: coerce/validate renderer input before persisting
- sftp: OperationError marker class keeps translated errors out of the
  transport-retry classifier
- CommandsPanel: surface save failures inside the dialog
- ConnectionSidebar: drop a tautological tooltip condition

P2 (i18n/tooling/tests):
- localize the 16 ANSI color labels and the highlight sample text
  (21 new keys across zh-CN/zh-TW/en/ja)
- sync-changelog: keep ### subheadings, normalize CRLF notes
- release.cjs: GitHub release reuse-by-tag (idempotent re-runs); fail
  loudly on a failed Gitea asset listing
- commands-store test: absent historyEnabled now truly tests absence
2026-09-27 22:25:03 +08:00

147 lines
5.1 KiB
TypeScript

import { app, BrowserWindow, dialog, Menu, nativeImage, Tray } from 'electron'
import type { SystemSettings } from '@shared/settings'
import { t } from '@shared/i18n'
import { loadSettings, mutateSettings } from './settingsStore'
import trayIconPath from './assets/tray.png?asset'
export type CloseAction = NonNullable<SystemSettings['closeAction']>
let tray: Tray | null = null
let quitting = false
let balloonShown = false
/** Window-restore callback handed to initTray; kept so the menu can be rebuilt. */
let showOrCreateRef: (() => void) | null = null
/** Once true, window close events pass through and the app really quits. */
export function markQuitting(): void {
quitting = true
}
function persistCloseAction(action: CloseAction): void {
// Serialized read-modify-write on the latest state: must not stomp (or be
// stomped by) a concurrent full-snapshot save from the settings UI.
void mutateSettings((current) => {
current.system.closeAction = action
return current
})
}
function showMainWindow(showOrCreate: () => void): void {
const win = BrowserWindow.getAllWindows()[0]
if (win) {
if (win.isMinimized()) win.restore()
win.show()
win.focus()
} else {
showOrCreate()
}
}
/** Rebuild the context menu so the close-action radio items reflect settings. */
function refreshContextMenu(showOrCreate: () => void): void {
if (!tray) return
const action = loadSettings().system.closeAction ?? 'tray'
const setAction = (value: CloseAction) => (): void => {
persistCloseAction(value)
refreshContextMenu(showOrCreate)
}
// Labels are resolved while the template is built, so rebuilding the menu
// after a language change picks up the new strings.
tray.setContextMenu(
Menu.buildFromTemplate([
{ label: t('main.tray.showWindow'), click: (): void => showMainWindow(showOrCreate) },
{ type: 'separator' },
{ label: t('main.tray.closeAction'), enabled: false },
{ label: t('main.tray.askEveryTime'), type: 'radio', checked: action === 'ask', click: setAction('ask') },
{ label: t('main.tray.minimizeToTray'), type: 'radio', checked: action === 'tray', click: setAction('tray') },
{ label: t('main.tray.exitDirectly'), type: 'radio', checked: action === 'exit', click: setAction('exit') },
{ type: 'separator' },
{
label: t('main.tray.exit'),
click: (): void => {
markQuitting()
app.quit()
}
}
])
)
}
/**
* Rebuild the tray menu (after a language change, or any time the labels must
* be current). Safe to call before the tray exists.
*/
export function refreshTrayMenu(): void {
if (!tray || !showOrCreateRef) return
refreshContextMenu(showOrCreateRef)
}
/** Create the tray icon and wire left-click to window restore. */
export function initTray(showOrCreate: () => void): void {
const icon = nativeImage.createFromPath(trayIconPath)
tray = new Tray(icon)
showOrCreateRef = showOrCreate
tray.setToolTip('OpenTerminal')
tray.on('click', (): void => showMainWindow(showOrCreate))
refreshContextMenu(showOrCreate)
}
function hideToTray(win: BrowserWindow): void {
// A quit started while the close dialog was pending destroys the window
// before its resolution runs; touching a destroyed window throws.
if (win.isDestroyed()) return
win.hide()
if (process.platform === 'win32' && tray && !balloonShown) {
balloonShown = true
tray.displayBalloon({
iconType: 'info',
// The Windows toast already prints the app name as its header, so the
// balloon title carries the state only — no "OpenTerminal" twice.
title: t('main.tray.balloonTitle'),
content: t('main.tray.balloonContent')
})
}
}
/**
* Window close interception. Must be called synchronously from the 'close'
* event: preventDefault happens before any await on every branch.
*/
export async function onMainWindowClose(win: BrowserWindow, e: Electron.Event, showOrCreate: () => void): Promise<void> {
if (quitting) return
const action = loadSettings().system.closeAction ?? 'tray'
if (action === 'tray') {
e.preventDefault()
hideToTray(win)
return
}
if (action === 'exit') return // fall through: close proceeds, app quits
e.preventDefault()
const { response, checkboxChecked } = await dialog.showMessageBox(win, {
type: 'question',
title: t('main.tray.closeTitle'),
message: t('main.tray.closeMessage'),
detail: t('main.tray.closeDetail'),
buttons: [t('main.tray.minimizeToTray'), t('main.tray.exitDirectly')],
defaultId: 0,
cancelId: 1,
checkboxLabel: t('main.tray.rememberChoice'),
checkboxChecked: false,
noLink: true
})
// The dialog resolves when the window is destroyed underneath it (tray exit
// or OS shutdown called app.quit() while it was open): the quit is already
// underway, so neither branch may run — and must not persist a choice the
// user never made.
if (win.isDestroyed()) return
if (response === 0) {
if (checkboxChecked) persistCloseAction('tray')
hideToTray(win)
} else {
if (checkboxChecked) persistCloseAction('exit')
markQuitting()
app.quit()
}
refreshContextMenu(showOrCreate)
}