Files
planet/client/src/main/index.ts
T

624 lines
23 KiB
TypeScript

import fs from 'node:fs'
import path from 'node:path'
import { app, BrowserWindow, dialog, ipcMain, Menu, net, session, shell } from 'electron'
import { DesktopConfigStore, normalizeSplashTheme, readPreReadyGpuHandoff, readPreReadyGpuMode, type GpuRenderMode, type ServerEndpoints } from './config'
import { DESKTOP_SCHEME, registerDesktopLink } from './desktop-link'
import { createEarthDesktopAuth } from './earth-auth'
import { createAdaptiveGpuMonitor, probeWindowsGpuEnvironmentSync } from './gpu-monitor'
import { buildGpuHandoffArgs, chooseStartupGpuTarget, isGpuProcessCrash, resolveChromiumGpuSwitches, stripGpuOverrideArgs, type ResolvedGpuTarget } from './gpu-policy'
import { PERIODIC_UPDATE_CHECK_INTERVAL_MS } from './hot-update-core'
import { createHotUpdateController } from './hot-updater'
import { buildApplicationMenu } from './menu'
import { EARTH_ORIGIN, installEarthSessionHandlers, registerEarthScheme } from './protocol'
import { createScreenRecorderController } from './screen-recorder'
import { createMainWindow, dismissMenuBarOnPointerDown, flushWindowState, toggleWindowOrientation } from './window'
registerEarthScheme()
const isHeadlessSmoke = process.argv.includes('--headless-smoke')
let preReadyUserDataDir = ''
let preReadyExeDir = process.cwd()
try {
preReadyUserDataDir = app.getPath('userData')
} catch {
preReadyUserDataDir = ''
}
try {
preReadyExeDir = path.dirname(app.getPath('exe'))
} catch {
preReadyExeDir = process.cwd()
}
const requestedGpuMode = readPreReadyGpuMode({
userDataDir: preReadyUserDataDir,
exeDir: preReadyExeDir,
resourcesDir: process.resourcesPath,
argv: process.argv,
})
const preReadyHandoff = readPreReadyGpuHandoff(process.argv)
const preReadyGpuEnv =
!isHeadlessSmoke &&
!preReadyHandoff.gpuHandoffTarget &&
requestedGpuMode === 'auto' &&
process.platform === 'win32'
? probeWindowsGpuEnvironmentSync()
: { vramSample: null, hasIntegratedGpu: false }
const startupGpuDecision = chooseStartupGpuTarget({
platform: process.platform,
headlessSmoke: isHeadlessSmoke,
requestedMode: requestedGpuMode,
handoffTarget: preReadyHandoff.gpuHandoffTarget,
vramSample: preReadyGpuEnv.vramSample,
hasIntegratedGpu: preReadyGpuEnv.hasIntegratedGpu,
})
if (startupGpuDecision.reason === 'low-vram-igpu' || startupGpuDecision.reason === 'low-vram-software') {
console.info(
`[planet-client] Adaptive GPU selected ${startupGpuDecision.target} (reason=${startupGpuDecision.reason}, freeMiB=${startupGpuDecision.vramSample?.freeMiB ?? 'unknown'})`,
)
}
for (const sw of resolveChromiumGpuSwitches({
platform: process.platform,
headlessSmoke: isHeadlessSmoke,
target: startupGpuDecision.target,
})) {
if (sw.value !== undefined) {
app.commandLine.appendSwitch(sw.name, sw.value)
} else {
app.commandLine.appendSwitch(sw.name)
}
}
function resolveEarthBundleRoot(): string {
const candidates = [
path.join(process.resourcesPath, 'earth'),
path.join(app.getAppPath(), '.earth-bundle/earth'),
path.resolve(app.getAppPath(), '../../.earth-bundle/earth'),
path.resolve(process.cwd(), '.earth-bundle/earth'),
]
for (const candidate of candidates) {
if (fs.existsSync(path.join(candidate, 'index.html'))) {
return candidate
}
}
return candidates[candidates.length - 1]
}
function resolveIconPath(): string {
const fileName = process.platform === 'win32' ? 'icon.ico' : 'icon.png'
const candidates = [
path.join(process.resourcesPath, 'resources', fileName),
path.join(app.getAppPath(), 'resources', fileName),
path.resolve(app.getAppPath(), '../../resources', fileName),
path.resolve(process.cwd(), 'resources', fileName),
]
return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0]
}
function resolvePreloadPath(): string {
const candidates = [
path.join(app.getAppPath(), 'dist-electron/preload/index.cjs'),
path.resolve(app.getAppPath(), '../preload/index.cjs'),
path.resolve(process.cwd(), 'dist-electron/preload/index.cjs'),
]
return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0]
}
function resolveIndicatorPreloadPath(): string {
const candidates = [
path.join(app.getAppPath(), 'dist-electron/preload/recording-indicator.cjs'),
path.resolve(app.getAppPath(), '../preload/recording-indicator.cjs'),
path.resolve(process.cwd(), 'dist-electron/preload/recording-indicator.cjs'),
]
return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0]
}
function resolveCursorOverlayPreloadPath(): string {
const candidates = [
path.join(app.getAppPath(), 'dist-electron/preload/recording-cursor.cjs'),
path.resolve(app.getAppPath(), '../preload/recording-cursor.cjs'),
path.resolve(process.cwd(), 'dist-electron/preload/recording-cursor.cjs'),
]
return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0]
}
let mainWindow: BrowserWindow | null = null
let launchWindow: (() => void) | undefined
function showEarthWindow() {
if (!mainWindow || mainWindow.isDestroyed()) {
launchWindow?.()
return
}
if (mainWindow.isMinimized()) mainWindow.restore()
mainWindow.show()
mainWindow.focus()
}
const singleInstanceLock = isHeadlessSmoke ? true : app.requestSingleInstanceLock()
if (!singleInstanceLock) {
app.quit()
} else {
app.on('open-url', (event, url) => {
if (url !== `${DESKTOP_SCHEME}://open` && url !== `${DESKTOP_SCHEME}://open/`) return
event.preventDefault()
showEarthWindow()
})
app.on('second-instance', showEarthWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('child-process-gone', (_event, details) => {
if (!isGpuProcessCrash(details)) return
console.warn('[planet-client] GPU process exited unexpectedly', {
reason: details.reason,
exitCode: details.exitCode,
})
if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.webContents.isDestroyed()) {
mainWindow.webContents.send('planet:gpu-process-gone', {
reason: details.reason,
exitCode: details.exitCode,
})
}
})
void app.whenReady().then(async () => {
if (!isHeadlessSmoke) {
void registerDesktopLink().catch(error => console.warn('Planet Earth protocol registration failed', error))
}
const configStore = new DesktopConfigStore({
userDataDir: app.getPath('userData'),
exeDir: path.dirname(app.getPath('exe')),
resourcesDir: process.resourcesPath,
argv: process.argv,
})
const earthBundleRoot = resolveEarthBundleRoot()
const relaunchDesktopApp = (relaunchOptions?: {
gpuHandoff?: boolean
gpuHandoffTarget?: ResolvedGpuTarget
}) => {
flushWindowState(mainWindow)
if (singleInstanceLock) {
app.releaseSingleInstanceLock()
}
const rawArgs = process.argv.slice(1)
const args = relaunchOptions?.gpuHandoff
? buildGpuHandoffArgs(rawArgs, relaunchOptions.gpuHandoffTarget)
: stripGpuOverrideArgs(rawArgs)
app.relaunch({ args })
app.exit(0)
}
const hotUpdater = createHotUpdateController({
userDataDir: app.getPath('userData'),
shellVersion: app.getVersion(),
getBackendUrl: () => configStore.get().backendUrl,
getMainWindow: () => mainWindow,
onOverlayChanged: () => {
refreshApplicationMenu()
},
})
const gpuMonitor = createAdaptiveGpuMonitor({
userDataDir: app.getPath('userData'),
startupDecision: startupGpuDecision,
getConfiguredMode: () => configStore.get().gpuMode,
getMainWindow: () => mainWindow,
onAutoSwitch: (nextTarget) => {
relaunchDesktopApp({ gpuHandoff: true, gpuHandoffTarget: nextTarget })
},
onStatusUpdated: () => {
refreshApplicationMenu()
},
})
const sendPendingHandoffToast = () => {
if (isHeadlessSmoke || !mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) {
return
}
const toast = gpuMonitor.consumePendingHandoffToast()
if (toast) {
mainWindow.webContents.send('planet:update-status', toast)
}
}
let screenRecorder: ReturnType<typeof createScreenRecorderController> | null = null
const refreshApplicationMenu = () => {
if (!mainWindow || mainWindow.isDestroyed()) return
Menu.setApplicationMenu(
buildApplicationMenu({
mainWindow,
configStore,
getVersionInfo: () => hotUpdater.getVersionInfo(),
onCheckForUpdates: () => {
void hotUpdater.checkForUpdates({ manual: true })
},
getGpuStatus: () => gpuMonitor.getRuntimeSummary(),
onSelectGpuMode: async (nextMode: GpuRenderMode) => {
configStore.updateGpuMode(nextMode)
refreshApplicationMenu()
const targetWin = mainWindow && !mainWindow.isDestroyed() ? mainWindow : undefined
const boxOptions = {
type: 'info' as const,
title: '渲染设备设置 / GPU Mode',
message: '渲染设备模式已更新,需重启客户端生效',
detail: '是否立即重启 Planet Earth?(重启约需 1-2 秒,将保留全部视觉特效)',
buttons: ['立即重启 / Restart Now', '稍后手动重启 / Later'],
defaultId: 0,
cancelId: 1,
}
const { response } = targetWin
? await dialog.showMessageBox(targetWin, boxOptions)
: await dialog.showMessageBox(boxOptions)
if (response === 0) {
relaunchDesktopApp({ gpuHandoff: true })
}
},
getRecordingState: () => screenRecorder?.getState() ?? {
state: 'idle',
elapsedMs: 0,
includeAudio: configStore.get().recordAudio,
hideCursor: configStore.get().recordHideCursor,
filePath: null,
},
onToggleRecording: (fromMenu = false) => {
void screenRecorder?.toggleRecording({ fromMenu })
},
onToggleRecordAudio: (enabled: boolean) => {
configStore.updateRecordAudio(enabled)
refreshApplicationMenu()
},
onToggleRecordHideCursor: (enabled: boolean) => {
configStore.updateRecordHideCursor(enabled)
refreshApplicationMenu()
},
onOpenRecordingsFolder: () => {
void screenRecorder?.openRecordingsFolder()
},
}),
)
}
screenRecorder = createScreenRecorderController({
getMainWindow: () => mainWindow,
configStore,
session: session.defaultSession,
indicatorPreloadPath: resolveIndicatorPreloadPath(),
cursorOverlayPreloadPath: resolveCursorOverlayPreloadPath(),
dismissMenuBar: dismissMenuBarOnPointerDown,
onStateChanged: () => {
refreshApplicationMenu()
},
})
app.on('will-quit', () => {
screenRecorder?.destroy()
})
const earthAuth = createEarthDesktopAuth({
getBackendUrl: () => configStore.get().backendUrl,
getAppVersion: () => app.getVersion(),
handshakeSecret: process.env.PLANET_EARTH_DESKTOP_HANDSHAKE_SECRET || '',
fetchImpl: (input, init) => net.fetch(input as string, init),
})
installEarthSessionHandlers(session.defaultSession, {
earthBundleRoot,
getEarthOverlayRoot: () => hotUpdater.getOverlayRoot(),
getBackendUrl: () => configStore.get().backendUrl,
getEarthAuthToken: (opts) => earthAuth.getToken(opts),
})
ipcMain.handle('planet:get-earth-session-token', (_event, opts: unknown) => {
const forceRefresh = Boolean(
opts && typeof opts === 'object' && (opts as { forceRefresh?: unknown }).forceRefresh,
)
return earthAuth.getToken({ forceRefresh })
})
ipcMain.on('planet:earth-startup-ready', () => {
if (!isHeadlessSmoke) {
hotUpdater.markStartupReady()
sendPendingHandoffToast()
}
})
ipcMain.on('planet:low-fps-report', (_event, payload: unknown) => {
if (isHeadlessSmoke || !payload || typeof payload !== 'object') return
const candidate = payload as { avgFps?: unknown; sustainedMs?: unknown }
const avgFps = Number(candidate.avgFps)
const sustainedMs = Number(candidate.sustainedMs)
if (!Number.isFinite(avgFps) || avgFps <= 0 || !Number.isFinite(sustainedMs) || sustainedMs <= 0) {
return
}
void gpuMonitor.handleLowFpsReport({ avgFps, sustainedMs })
})
ipcMain.handle('planet:check-for-updates', async () => {
await hotUpdater.checkForUpdates({ manual: true })
})
ipcMain.handle('planet:get-version-info', () => hotUpdater.getVersionInfo())
ipcMain.on('planet:get-runtime-config', (event) => {
const cfg = configStore.get()
event.returnValue = {
backendUrl: cfg.backendUrl,
adminUrl: cfg.adminUrl,
motionWsUrl: cfg.motionWsUrl,
wsUrl: cfg.wsUrl,
forceShowFps: cfg.forceShowFps,
splashTheme: cfg.splashTheme,
gpuMode: cfg.gpuMode,
gpuTarget: startupGpuDecision.target,
gpuHandoff: cfg.gpuHandoff,
headlessSmoke: cfg.headlessSmoke,
isElectron: true,
platform: process.platform,
localMediaPipeBaseUrl: `${EARTH_ORIGIN}/earth/vendor/mediapipe`,
localPoseModelUrl: `${EARTH_ORIGIN}/earth/vendor/mediapipe/pose_landmarker_lite.task`,
}
})
ipcMain.handle('planet:toggle-fullscreen', () => {
if (!mainWindow || mainWindow.isDestroyed()) return false
const next = !mainWindow.isFullScreen()
mainWindow.setFullScreen(next)
return next
})
ipcMain.handle('planet:is-fullscreen', () => {
return Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFullScreen())
})
ipcMain.handle('planet:toggle-orientation', () => {
if (!mainWindow || mainWindow.isDestroyed()) return 'landscape'
return toggleWindowOrientation(mainWindow)
})
ipcMain.handle('planet:minimize', () => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.minimize()
}
})
ipcMain.handle('planet:toggle-maximize', () => {
if (!mainWindow || mainWindow.isDestroyed()) return false
if (mainWindow.isMaximized()) {
mainWindow.unmaximize()
} else {
mainWindow.maximize()
}
return mainWindow.isMaximized()
})
ipcMain.handle('planet:open-admin', (_event, routePath: unknown) => {
const rawPath = typeof routePath === 'string' && routePath.startsWith('/') ? routePath : '/admin'
const target = `${configStore.get().adminUrl.replace(/\/+$/, '')}${rawPath}`
return shell.openExternal(target)
})
ipcMain.handle('planet:get-server-config', () => configStore.get())
ipcMain.handle('planet:set-server-config', (_event, partial: unknown) => {
const next = configStore.updateEndpoints((partial || {}) as Partial<ServerEndpoints>)
earthAuth.clear()
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.reload()
}
return next
})
ipcMain.handle('planet:get-splash-theme', () => configStore.get().splashTheme)
ipcMain.handle('planet:set-splash-theme', (_event, rawTheme: unknown) => {
const next = configStore.updateSplashTheme(normalizeSplashTheme(rawTheme, configStore.get().splashTheme))
refreshApplicationMenu()
return next.splashTheme
})
ipcMain.on('planet:content-pointerdown', () => {
dismissMenuBarOnPointerDown(mainWindow)
})
launchWindow = () => {
const preloadPath = resolvePreloadPath()
mainWindow = createMainWindow({
preloadPath,
iconPath: resolveIconPath(),
userDataDir: app.getPath('userData'),
configStore,
onToggleRecording: () => {
void screenRecorder?.toggleRecording({ fromMenu: false })
},
})
mainWindow.on('close', (event) => {
if (mainWindow) {
screenRecorder?.handleWindowClose(mainWindow, event)
}
})
refreshApplicationMenu()
if (process.platform !== 'darwin') {
mainWindow.setMenuBarVisibility(false)
}
if (!isHeadlessSmoke) {
let autoUpdateTimer: ReturnType<typeof setTimeout> | null = null
let periodicUpdateTimer: ReturnType<typeof setInterval> | null = null
mainWindow.webContents.on('render-process-gone', () => {
hotUpdater.handleRendererCrash()
})
hotUpdater.startStartupWatchdog()
mainWindow.webContents.once('did-finish-load', () => {
gpuMonitor.start()
autoUpdateTimer = setTimeout(() => {
autoUpdateTimer = null
if (mainWindow && !mainWindow.isDestroyed()) {
void hotUpdater.checkForUpdates({ manual: false })
}
}, 4000)
if (!periodicUpdateTimer) {
periodicUpdateTimer = setInterval(() => {
if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.isMinimized()) {
void hotUpdater.checkForUpdates({ manual: false })
}
}, PERIODIC_UPDATE_CHECK_INTERVAL_MS)
}
})
mainWindow.once('closed', () => {
gpuMonitor.stop()
if (autoUpdateTimer) {
clearTimeout(autoUpdateTimer)
autoUpdateTimer = null
}
if (periodicUpdateTimer) {
clearInterval(periodicUpdateTimer)
periodicUpdateTimer = null
}
hotUpdater.stopStartupWatchdog()
})
}
if (isHeadlessSmoke) {
const smokeTimeout = setTimeout(() => {
app.exit(1)
}, 22000)
mainWindow.webContents.once('did-finish-load', async () => {
try {
const earthStartup = await mainWindow!.webContents.executeJavaScript(`new Promise((resolve) => {
const deadline = performance.now() + 8000;
const poll = () => {
const ready = document.documentElement.dataset.earthStartupReady === '1';
const progress = document.documentElement.dataset.earthStartupProgress || '';
if (ready || performance.now() >= deadline) {
resolve({ ready, progress });
return;
}
setTimeout(poll, 60);
};
poll();
})`) as { ready: boolean; progress: string }
const report = await mainWindow?.webContents.executeJavaScript(`({
href: window.location.href,
title: document.title,
isElectron: Boolean(window.planetDesktop?.isElectron),
wsUrl: window.__PLANET_RUNTIME_CONFIG__?.wsUrl || null,
hasLayerPanel: Boolean(document.getElementById('layer-toggles')),
hasToolbar: Boolean(document.getElementById('right-toolbar-group')),
hasNoDesktopDomPatch: !document.querySelector('[data-desktop-server-settings]'),
})`)
const appMenu = Menu.getApplicationMenu()
const hasApplicationMenu = Boolean(appMenu && appMenu.items.length >= 2)
const menuBarInitiallyHidden =
process.platform === 'darwin' ? true : !mainWindow?.isMenuBarVisible()
const waitForLayoutMode = (predicateSource: string) =>
mainWindow!.webContents.executeJavaScript(`new Promise((resolve) => {
const deadline = performance.now() + 1500;
const check = () => {
const mode = document.documentElement.dataset.earthLayoutMode || '';
const width = window.innerWidth;
if (${predicateSource} || performance.now() >= deadline) {
resolve({ mode, width });
return;
}
requestAnimationFrame(check);
};
requestAnimationFrame(check);
})`) as Promise<{ mode: string; width: number }>
const afterPortraitToggle = toggleWindowOrientation(mainWindow!)
const portraitBounds = mainWindow!.getBounds()
const portraitDom = await waitForLayoutMode("mode === 'mobile' && width <= 820")
const afterLandscapeToggle = toggleWindowOrientation(mainWindow!)
const landscapeDom = await waitForLayoutMode("mode !== 'mobile' && width > 820")
const splashCheck = await mainWindow!.webContents.executeJavaScript(`new Promise((resolve) => {
window.planetDesktop.replaySplash('singularity');
requestAnimationFrame(() => {
const host = document.getElementById('planet-desktop-splash-host');
const sr = host?.shadowRoot;
const img = sr?.querySelector('.splash-zju-emblem');
const copy = sr?.querySelector('.splash-presenter-copy')?.textContent || '';
const finishCheck = () => {
const activeTheme = host?.dataset.splashTheme || '';
const hasNoThemeSwitcher = !sr?.querySelector('.splash-switcher');
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
resolve({
mounted: Boolean(host && sr),
hasPresentedBy: copy.includes('PRESENTED BY'),
hasPresenterZh: copy.includes('临空智能媒体研究院'),
hasPresenterEn: copy.includes('Intelligent Media Institute'),
emblemLoaded: Boolean(img && img.complete && img.naturalWidth > 0),
emblemWidth: img ? img.naturalWidth : 0,
activeTheme,
hasNoThemeSwitcher,
});
};
if (!img || img.complete) {
finishCheck();
} else {
img.addEventListener('load', finishCheck, { once: true });
img.addEventListener('error', finishCheck, { once: true });
setTimeout(finishCheck, 1200);
}
});
})`)
const enrichedReport = {
...report,
earthStartupReady: earthStartup.ready,
earthStartupProgress: earthStartup.progress,
hasApplicationMenu,
menuBarInitiallyHidden,
afterPortraitToggle,
portraitBounds,
portraitLayoutMode: portraitDom.mode,
portraitInnerWidth: portraitDom.width,
afterLandscapeToggle,
restoredLayoutMode: landscapeDom.mode,
restoredInnerWidth: landscapeDom.width,
splashCheck,
}
const cfg = configStore.get()
if (cfg.smokeOutputPath) {
fs.mkdirSync(path.dirname(cfg.smokeOutputPath), { recursive: true })
fs.writeFileSync(cfg.smokeOutputPath, JSON.stringify(enrichedReport, null, 2), 'utf8')
} else {
process.stdout.write(`${JSON.stringify(enrichedReport)}\n`)
}
clearTimeout(smokeTimeout)
app.exit(0)
} catch (error) {
clearTimeout(smokeTimeout)
process.stderr.write(`Headless smoke failed: ${String(error)}\n`)
app.exit(1)
}
})
}
}
launchWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
launchWindow?.()
}
})
})
}