Files
planet/client/src/main/window.ts
T
linkong 5fc698d738
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release / images (push) Canceled after 0s
release / client_release (push) Canceled after 0s
release: bump version to 0.78.0
2026-11-23 22:40:11 +08:00

549 lines
18 KiB
TypeScript

import fs from 'node:fs'
import path from 'node:path'
import { BrowserWindow, ipcMain, nativeTheme, screen, shell, type Display } from 'electron'
import { createSoloAltMenuTracker } from './alt-menu'
import { DEFAULT_ENDPOINTS, type DesktopConfigStore, type DesktopRuntimeConfig } from './config'
import { resolveExternalTargetUrl } from './external-links'
import { createWindowShowGate } from './show-gate'
import {
computeLandscapeBounds,
computePortraitBounds,
DEFAULT_LANDSCAPE_HEIGHT,
DEFAULT_LANDSCAPE_WIDTH,
detectWindowOrientation,
MIN_WINDOW_HEIGHT,
MIN_WINDOW_WIDTH,
type Rect,
type WindowOrientation,
} from './orientation'
import { EARTH_ENTRY_URL, EARTH_ORIGIN } from './protocol'
const resetAltMenuTrackers = new WeakMap<BrowserWindow, () => void>()
interface OrientationWindowState {
lastLandscapeBounds: Rect | null
lastPortraitBounds: Rect | null
restoreMaximizedOnLandscape: boolean
restoreFullScreenOnLandscape: boolean
}
const windowOrientationStates = new WeakMap<BrowserWindow, OrientationWindowState>()
export function dismissMenuBarOnPointerDown(win: BrowserWindow | null): void {
if (!win || win.isDestroyed() || process.platform === 'darwin') return
resetAltMenuTrackers.get(win)?.()
if (win.isMenuBarVisible()) {
win.setMenuBarVisibility(false)
}
}
export function toggleWindowOrientation(win: BrowserWindow): WindowOrientation {
if (win.isDestroyed()) return 'landscape'
const state = windowOrientationStates.get(win) ?? {
lastLandscapeBounds: null,
lastPortraitBounds: null,
restoreMaximizedOnLandscape: false,
restoreFullScreenOnLandscape: false,
}
windowOrientationStates.set(win, state)
const wasFullScreen = win.isFullScreen()
const wasMaximized = win.isMaximized()
const currentBounds = win.getBounds()
const currentOrientation = detectWindowOrientation(currentBounds, {
isMaximized: wasMaximized,
isFullScreen: wasFullScreen,
})
const workArea = screen.getDisplayMatching(currentBounds).workArea
if (currentOrientation === 'landscape') {
state.restoreFullScreenOnLandscape = wasFullScreen
state.restoreMaximizedOnLandscape = wasMaximized
if (!wasFullScreen && !wasMaximized && currentBounds.width >= currentBounds.height) {
state.lastLandscapeBounds = { ...currentBounds }
}
if (wasFullScreen) {
win.setFullScreen(false)
}
if (wasMaximized) {
win.unmaximize()
}
const portraitBounds = computePortraitBounds({
workArea,
anchorBounds: currentBounds,
savedPortraitBounds: state.lastPortraitBounds,
})
win.setBounds(portraitBounds)
state.lastPortraitBounds = portraitBounds
return 'portrait'
}
state.lastPortraitBounds = { ...currentBounds }
const landscapeBounds = computeLandscapeBounds({
workArea,
anchorBounds: currentBounds,
savedLandscapeBounds: state.lastLandscapeBounds,
})
win.setBounds(landscapeBounds)
state.lastLandscapeBounds = landscapeBounds
if (state.restoreMaximizedOnLandscape) {
win.maximize()
}
if (state.restoreFullScreenOnLandscape) {
win.setFullScreen(true)
}
state.restoreMaximizedOnLandscape = false
state.restoreFullScreenOnLandscape = false
return 'landscape'
}
export interface SavedWindowState {
x?: number
y?: number
width: number
height: number
isMaximized?: boolean
isFullScreen?: boolean
}
function loadWindowState(statePath: string, ignoreSaved = false): SavedWindowState {
const workArea = screen.getPrimaryDisplay().workAreaSize
const fallback: SavedWindowState = {
width: Math.min(DEFAULT_LANDSCAPE_WIDTH, workArea.width),
height: Math.min(DEFAULT_LANDSCAPE_HEIGHT, workArea.height),
isMaximized: false,
isFullScreen: false,
}
if (ignoreSaved) return fallback
try {
if (!fs.existsSync(statePath)) return fallback
const parsed = JSON.parse(fs.readFileSync(statePath, 'utf8')) as Partial<SavedWindowState>
const width = Math.max(MIN_WINDOW_WIDTH, Number(parsed.width) || fallback.width)
const height = Math.max(MIN_WINDOW_HEIGHT, Number(parsed.height) || fallback.height)
const x = typeof parsed.x === 'number' && Number.isFinite(parsed.x) ? parsed.x : undefined
const y = typeof parsed.y === 'number' && Number.isFinite(parsed.y) ? parsed.y : undefined
if (x !== undefined && y !== undefined) {
const visibleOnDisplay = screen.getAllDisplays().some((display: Display) => {
const b = display.workArea
return x + 100 > b.x && x < b.x + b.width - 100 && y + 60 > b.y && y < b.y + b.height - 60
})
if (!visibleOnDisplay) {
return { ...fallback, isMaximized: Boolean(parsed.isMaximized), isFullScreen: Boolean(parsed.isFullScreen) }
}
}
return {
x,
y,
width,
height,
isMaximized: Boolean(parsed.isMaximized),
isFullScreen: Boolean(parsed.isFullScreen),
}
} catch {
return fallback
}
}
function saveWindowState(statePath: string, win: BrowserWindow, normalBounds: Electron.Rectangle): void {
try {
const payload: SavedWindowState = {
x: normalBounds.x,
y: normalBounds.y,
width: Math.max(MIN_WINDOW_WIDTH, normalBounds.width),
height: Math.max(MIN_WINDOW_HEIGHT, normalBounds.height),
isMaximized: win.isMaximized(),
isFullScreen: win.isFullScreen(),
}
fs.mkdirSync(path.dirname(statePath), { recursive: true })
fs.writeFileSync(statePath, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
} catch {
// Ignore non-critical window state write errors.
}
}
export function createMainWindow(options: {
preloadPath: string
iconPath: string
userDataDir: string
configStore: DesktopConfigStore
}): BrowserWindow {
nativeTheme.themeSource = 'dark'
const statePath = path.join(options.userDataDir, 'window-state.json')
const runtimeConfig: DesktopRuntimeConfig = options.configStore.get()
const saved = loadWindowState(statePath, runtimeConfig.headlessSmoke)
const win = new BrowserWindow({
x: saved.x,
y: saved.y,
width: saved.width,
height: saved.height,
minWidth: MIN_WINDOW_WIDTH,
minHeight: MIN_WINDOW_HEIGHT,
show: false,
frame: true,
autoHideMenuBar: process.platform !== 'darwin',
backgroundColor: '#02040a',
icon: fs.existsSync(options.iconPath) ? options.iconPath : undefined,
webPreferences: {
preload: options.preloadPath,
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
backgroundThrottling: false,
webgl: true,
},
})
if (process.platform !== 'darwin') {
const altTracker = createSoloAltMenuTracker()
resetAltMenuTrackers.set(win, () => altTracker.reset())
win.on('blur', () => {
altTracker.reset()
})
// Toggle menu bar visibility directly on solo Alt release instead of letting
// Electron's RootView focus MenuBar button 0 (whose clipped outset FocusRing
// draws a spurious blue vertical bar next to the first menu item).
win.webContents.on('before-input-event', (event, input) => {
// Intercept Ctrl+Shift+M before controls.js resolves it to Ctrl+M (toggleMediaPanel)
// because getShortcutChordFromEvent ignores Shift on single-character keys.
if (
input.type === 'keyDown' &&
!input.isAutoRepeat &&
input.control &&
input.shift &&
!input.alt &&
!input.meta &&
input.key.toLowerCase() === 'm'
) {
altTracker.reset()
event.preventDefault()
toggleWindowOrientation(win)
return
}
if (
input.type === 'keyDown' &&
!input.isAutoRepeat &&
input.control &&
input.shift &&
!input.alt &&
!input.meta &&
input.key.toLowerCase() === 's'
) {
altTracker.reset()
event.preventDefault()
if (!win.isDestroyed()) {
win.webContents.send('planet:replay-splash', {})
}
return
}
const action = altTracker.handleInput(input)
if (action === 'toggle') {
event.preventDefault()
if (!win.isDestroyed()) {
const nextVisible = !win.isMenuBarVisible()
win.setMenuBarVisibility(nextVisible)
if (nextVisible) {
win.webContents.focus()
}
}
} else if (action === 'hide-if-visible') {
if (!win.isDestroyed() && win.isMenuBarVisible()) {
win.setMenuBarVisibility(false)
}
}
})
}
let lastNormalBounds: Electron.Rectangle = {
x: saved.x ?? 0,
y: saved.y ?? 0,
width: saved.width,
height: saved.height,
}
const savedValidRect: Rect | null =
saved.x !== undefined && saved.y !== undefined
? { x: saved.x, y: saved.y, width: saved.width, height: saved.height }
: null
windowOrientationStates.set(win, {
lastLandscapeBounds: savedValidRect && savedValidRect.width >= savedValidRect.height ? savedValidRect : null,
lastPortraitBounds: savedValidRect && savedValidRect.height > savedValidRect.width ? savedValidRect : null,
restoreMaximizedOnLandscape: Boolean(saved.isMaximized),
restoreFullScreenOnLandscape: Boolean(saved.isFullScreen),
})
const captureNormalBounds = () => {
if (!win.isDestroyed() && !win.isMaximized() && !win.isMinimized() && !win.isFullScreen()) {
lastNormalBounds = win.getBounds()
const orientState = windowOrientationStates.get(win)
if (orientState) {
if (lastNormalBounds.height > lastNormalBounds.width) {
orientState.lastPortraitBounds = { ...lastNormalBounds }
} else {
orientState.lastLandscapeBounds = { ...lastNormalBounds }
}
}
}
}
win.on('resize', captureNormalBounds)
win.on('move', captureNormalBounds)
win.on('close', () => {
captureNormalBounds()
if (!runtimeConfig.headlessSmoke) {
saveWindowState(statePath, win, lastNormalBounds)
}
})
win.on('minimize', () => {
if (!win.isDestroyed()) {
win.webContents.send('planet:visibility', { minimized: true })
}
})
win.on('restore', () => {
if (!win.isDestroyed()) {
win.webContents.send('planet:visibility', { minimized: false })
}
})
win.on('enter-full-screen', () => {
if (!win.isDestroyed()) {
win.webContents.send('planet:fullscreen', { fullscreen: true })
}
})
win.on('leave-full-screen', () => {
if (!win.isDestroyed()) {
win.webContents.send('planet:fullscreen', { fullscreen: false })
}
})
const revealMainWindow = () => {
if (win.isDestroyed() || runtimeConfig.headlessSmoke) return
if (saved.isMaximized) {
win.maximize()
}
win.show()
if (runtimeConfig.kiosk) {
win.setKiosk(true)
} else if (runtimeConfig.fullscreen || saved.isFullScreen) {
win.setFullScreen(true)
}
if (runtimeConfig.devtools) {
win.webContents.openDevTools({ mode: 'detach' })
}
}
const showGate = createWindowShowGate({
requireSplashFirstPaint: !runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off',
fallbackDelayMs: 1500,
onReveal: revealMainWindow,
})
const onSplashFirstPaint = (event: Electron.IpcMainEvent) => {
if (!win.isDestroyed() && event.sender.id === win.webContents.id) {
showGate.markSplashFirstPainted()
}
}
ipcMain.on('planet:splash-first-paint', onSplashFirstPaint)
win.once('closed', () => {
showGate.dispose()
ipcMain.removeListener('planet:splash-first-paint', onSplashFirstPaint)
})
win.once('ready-to-show', () => {
if (runtimeConfig.headlessSmoke) return
showGate.markReadyToShow()
})
win.webContents.on('preload-error', (_event, preloadFile, error) => {
process.stderr.write(`Preload error in ${preloadFile}: ${String(error)}\n`)
})
win.webContents.on('console-message', (event) => {
if (runtimeConfig.headlessSmoke && (event.level === 'error' || event.level === 'warning')) {
process.stderr.write(`[renderer:${event.level}] ${event.message}\n`)
}
})
win.webContents.on('did-finish-load', () => {
void win.webContents.setVisualZoomLevelLimits(1, 1)
})
win.webContents.setWindowOpenHandler(({ url }) => {
const externalUrl = resolveExternalTargetUrl(url, {
earthOrigin: EARTH_ORIGIN,
adminUrl: options.configStore.get().adminUrl,
})
if (externalUrl) {
void shell.openExternal(externalUrl)
}
return { action: 'deny' }
})
win.webContents.on('will-navigate', (event, url) => {
if (url.startsWith(`${EARTH_ORIGIN}/earth`)) return
const externalUrl = resolveExternalTargetUrl(url, {
earthOrigin: EARTH_ORIGIN,
adminUrl: options.configStore.get().adminUrl,
})
event.preventDefault()
if (externalUrl) {
void shell.openExternal(externalUrl)
}
})
void win.loadURL(EARTH_ENTRY_URL)
return win
}
export function openServerSettingsDialog(
parentWindow: BrowserWindow,
configStore: DesktopConfigStore,
onUpdated: () => void,
): void {
const current = configStore.get()
const modal = new BrowserWindow({
parent: parentWindow,
modal: true,
width: 520,
height: 370,
resizable: false,
minimizable: false,
maximizable: false,
autoHideMenuBar: true,
backgroundColor: '#091522',
title: 'Planet Earth — Server Connection',
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
},
})
modal.removeMenu()
const escapeAttr = (value: string) =>
value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
const html = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<style>
body { margin: 0; padding: 20px; font-family: system-ui, -apple-system, sans-serif; background: #091522; color: #e2eeff; }
h2 { margin: 0 0 14px; font-size: 16px; font-weight: 600; }
label { display: block; margin-bottom: 11px; font-size: 12px; color: #9ab3cc; }
input { width: 100%; box-sizing: border-box; margin-top: 4px; padding: 8px 10px; border: 1px solid #26415c; border-radius: 4px; background: #0f2134; color: #f5f9ff; font-size: 13px; outline: none; }
input:focus { border-color: #4da3ff; }
.error { min-height: 16px; margin-top: 2px; font-size: 12px; color: #ff8a8a; }
.actions { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-top: 14px; }
.actions-right { display: flex; gap: 10px; }
button { padding: 7px 14px; font-size: 13px; border: 1px solid #2d4d6d; border-radius: 4px; background: #13283d; color: #e2eeff; cursor: pointer; }
button:hover { background: #19344f; }
button.primary { background: #1d6feb; border-color: #3687ff; color: #fff; }
button.primary:hover { background: #2679f5; }
</style>
</head>
<body>
<h2>服务端连接配置 / Server Connection</h2>
<form id="cfg">
<label>后端服务地址 (Backend API URL)
<input name="backendUrl" type="url" required value="${escapeAttr(current.backendUrl)}">
</label>
<label>运维控制台地址 (Admin Console URL)
<input name="adminUrl" type="url" required value="${escapeAttr(current.adminUrl)}">
</label>
<label>本地动捕 WebSocket (Motion Agent WS URL)
<input name="motionWsUrl" type="text" required value="${escapeAttr(current.motionWsUrl)}">
</label>
<div id="err" class="error" aria-live="polite"></div>
<div class="actions">
<button type="button" id="defaults">恢复默认 / Defaults</button>
<div class="actions-right">
<button type="button" id="cancel">取消 / Cancel</button>
<button type="submit" class="primary">保存并重连 / Save</button>
</div>
</div>
</form>
<script>
const form = document.getElementById('cfg');
const errEl = document.getElementById('err');
const isValidUrl = (value, protocols) => {
try {
const parsed = new URL(String(value || '').trim());
return protocols.includes(parsed.protocol);
} catch {
return false;
}
};
document.getElementById('defaults').addEventListener('click', () => {
form.elements.backendUrl.value = ${JSON.stringify(DEFAULT_ENDPOINTS.backendUrl)};
form.elements.adminUrl.value = ${JSON.stringify(DEFAULT_ENDPOINTS.adminUrl)};
form.elements.motionWsUrl.value = ${JSON.stringify(DEFAULT_ENDPOINTS.motionWsUrl)};
errEl.textContent = '';
});
document.getElementById('cancel').addEventListener('click', () => {
window.location.href = 'planet://settings-action/cancel';
});
form.addEventListener('submit', (e) => {
e.preventDefault();
const backendUrl = String(form.elements.backendUrl.value || '').trim();
const adminUrl = String(form.elements.adminUrl.value || '').trim();
const motionWsUrl = String(form.elements.motionWsUrl.value || '').trim();
if (
!isValidUrl(backendUrl, ['http:', 'https:']) ||
!isValidUrl(adminUrl, ['http:', 'https:']) ||
!isValidUrl(motionWsUrl, ['ws:', 'wss:'])
) {
errEl.textContent = '请输入有效地址 (http/https 与 ws/wss) / Enter valid URLs.';
return;
}
const q = new URLSearchParams({ backendUrl, adminUrl, motionWsUrl });
window.location.href = 'planet://settings-action/save?' + q.toString();
});
</script>
</body>
</html>`
modal.webContents.on('before-input-event', (event, input) => {
if (input.type === 'keyDown' && input.key === 'Escape') {
event.preventDefault()
if (!modal.isDestroyed()) {
modal.close()
}
}
})
modal.webContents.on('will-navigate', (event, url) => {
event.preventDefault()
if (url.startsWith('planet://settings-action/cancel')) {
modal.close()
return
}
if (url.startsWith('planet://settings-action/save')) {
const parsed = new URL(url)
configStore.updateEndpoints({
backendUrl: parsed.searchParams.get('backendUrl') ?? undefined,
adminUrl: parsed.searchParams.get('adminUrl') ?? undefined,
motionWsUrl: parsed.searchParams.get('motionWsUrl') ?? undefined,
})
modal.close()
onUpdated()
}
})
void modal.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`)
}