release: bump version to 0.81.0
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s

This commit is contained in:
linkong committed 2026-11-30 19:39:29 +08:00
1 parent 6d310f4dbe
commit b3d2d9e9f1
156 files changed
+15910 -1385

No files matched your search

+41
View File
@@ -13,6 +13,8 @@ export interface ServerEndpoints {
export interface PersistedUserConfig extends Partial<ServerEndpoints> {
splashTheme?: SplashTheme
gpuMode?: GpuRenderMode
recordAudio?: boolean
recordHideCursor?: boolean
}
export type GpuHandoffTarget = 'default' | 'high-performance' | 'low-power' | 'software'
@@ -49,6 +51,18 @@ export interface DesktopRuntimeConfig extends ServerEndpoints, DesktopLaunchFlag
wsUrl: string
splashTheme: SplashTheme
gpuMode: GpuRenderMode
recordAudio: boolean
recordHideCursor: boolean
}
export function normalizeBooleanFlag(raw: unknown, fallback = false): boolean {
if (typeof raw === 'boolean') return raw
if (typeof raw === 'string') {
const normalized = raw.trim().toLowerCase()
if (normalized === 'true' || normalized === '1' || normalized === 'yes') return true
if (normalized === 'false' || normalized === '0' || normalized === 'no') return false
}
return fallback
}
const LEGACY_ACTIVE_THEMES: ReadonlySet<string> = new Set([
@@ -326,6 +340,11 @@ export class DesktopConfigStore {
userSaved.gpuMode,
'auto',
)
const recordAudio = normalizeBooleanFlag(portable.recordAudio ?? userSaved.recordAudio, false)
const recordHideCursor = normalizeBooleanFlag(
portable.recordHideCursor ?? userSaved.recordHideCursor,
false,
)
return {
backendUrl,
@@ -334,6 +353,8 @@ export class DesktopConfigStore {
wsUrl: deriveBackendWsUrl(backendUrl),
splashTheme,
gpuMode,
recordAudio,
recordHideCursor,
...this.launchFlags,
}
}
@@ -385,4 +406,24 @@ export class DesktopConfigStore {
}
return this.get()
}
updateRecordAudio(enabled: unknown): DesktopRuntimeConfig {
const nextRecordAudio = normalizeBooleanFlag(enabled, this.current.recordAudio)
this.writeUserConfig({ recordAudio: nextRecordAudio })
this.current = {
...this.current,
recordAudio: nextRecordAudio,
}
return this.get()
}
updateRecordHideCursor(enabled: unknown): DesktopRuntimeConfig {
const nextRecordHideCursor = normalizeBooleanFlag(enabled, this.current.recordHideCursor)
this.writeUserConfig({ recordHideCursor: nextRecordHideCursor })
this.current = {
...this.current,
recordHideCursor: nextRecordHideCursor,
}
return this.get()
}
}
+124
View File
@@ -0,0 +1,124 @@
import crypto from 'node:crypto'
export interface EarthDesktopAuth {
getToken(options?: { forceRefresh?: boolean }): Promise<string | null>
clear(): void
}
interface CachedEarthToken {
backendUrl: string
token: string
expiresAtMs: number
}
const REFRESH_MARGIN_MS = 120_000
const DEFAULT_TTL_SECONDS = 1800
const AUTH_TIMEOUT_MS = 8000
export function createEarthDesktopAuth(options: {
getBackendUrl: () => string
getAppVersion: () => string
handshakeSecret?: string
fetchImpl?: typeof fetch
nowMs?: () => number
}): EarthDesktopAuth {
const fetchImpl = options.fetchImpl ?? fetch
const nowMs = options.nowMs ?? (() => Date.now())
let cached: CachedEarthToken | null = null
let inFlight: Promise<string | null> | null = null
let inFlightBackendUrl = ''
const fetchFreshToken = async (backendUrl: string): Promise<string | null> => {
const version = (options.getAppVersion() || '0.0.0').trim() || '0.0.0'
const clientHeader = `planet-earth-desktop/${version}`
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'X-Planet-Client': clientHeader,
}
const secret = String(options.handshakeSecret || '').trim()
if (secret) {
const timestamp = String(Math.floor(nowMs() / 1000))
const nonce = crypto.randomBytes(16).toString('hex')
const signature = crypto
.createHmac('sha256', secret)
.update(`${timestamp}.${nonce}.${clientHeader}`)
.digest('hex')
headers['X-Planet-Client-Timestamp'] = timestamp
headers['X-Planet-Client-Nonce'] = nonce
headers['X-Planet-Client-Signature'] = signature
}
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), AUTH_TIMEOUT_MS)
try {
const targetUrl = new URL('/api/v1/auth/earth-session', backendUrl).toString()
const response = await fetchImpl(targetUrl, {
method: 'POST',
headers,
body: JSON.stringify({ client_type: 'desktop' }),
signal: controller.signal,
})
if (!response.ok) {
return null
}
const data = (await response.json()) as { token?: unknown; expires_in?: unknown }
if (typeof data?.token !== 'string' || !data.token.trim()) {
return null
}
const ttlSeconds =
typeof data.expires_in === 'number' && Number.isFinite(data.expires_in) && data.expires_in > 0
? data.expires_in
: DEFAULT_TTL_SECONDS
cached = {
backendUrl,
token: data.token.trim(),
expiresAtMs: nowMs() + ttlSeconds * 1000,
}
return cached.token
} catch {
return null
} finally {
clearTimeout(timer)
}
}
return {
async getToken(getOpts) {
const backendUrl = String(options.getBackendUrl() || '').trim().replace(/\/+$/, '')
if (!backendUrl) return null
if (cached && cached.backendUrl !== backendUrl) {
cached = null
}
if (
!getOpts?.forceRefresh &&
cached &&
cached.expiresAtMs - nowMs() > REFRESH_MARGIN_MS
) {
return cached.token
}
if (inFlight && inFlightBackendUrl === backendUrl && !getOpts?.forceRefresh) {
return inFlight
}
const promise = fetchFreshToken(backendUrl).finally(() => {
if (inFlight === promise) {
inFlight = null
inFlightBackendUrl = ''
}
})
inFlight = promise
inFlightBackendUrl = backendUrl
return promise
},
clear() {
cached = null
inFlight = null
inFlightBackendUrl = ''
},
}
}
+84 -1
View File
@@ -1,16 +1,18 @@
import fs from 'node:fs'
import path from 'node:path'
import { app, BrowserWindow, dialog, ipcMain, Menu, session, shell } from 'electron'
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()
@@ -106,6 +108,24 @@ function resolvePreloadPath(): string {
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
@@ -211,6 +231,8 @@ if (!singleInstanceLock) {
}
}
let screenRecorder: ReturnType<typeof createScreenRecorderController> | null = null
const refreshApplicationMenu = () => {
if (!mainWindow || mainWindow.isDestroyed()) return
Menu.setApplicationMenu(
@@ -242,14 +264,65 @@ if (!singleInstanceLock) {
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', () => {
@@ -338,6 +411,7 @@ if (!singleInstanceLock) {
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()
}
@@ -363,6 +437,15 @@ if (!singleInstanceLock) {
iconPath: resolveIconPath(),
userDataDir: app.getPath('userData'),
configStore,
onToggleRecording: () => {
void screenRecorder?.toggleRecording({ fromMenu: false })
},
})
mainWindow.on('close', (event) => {
if (mainWindow) {
screenRecorder?.handleWindowClose(mainWindow, event)
}
})
refreshApplicationMenu()
+53
View File
@@ -3,6 +3,7 @@ import { app, Menu, shell, type BrowserWindow, type MenuItemConstructorOptions }
import type { DesktopConfigStore, GpuRenderMode, SplashTheme } from './config'
import type { GpuRuntimeSummary } from './gpu-monitor'
import type { HotUpdateVersionInfo } from './hot-updater'
import type { RecordingStatusSnapshot } from './recording-core'
import { openServerSettingsDialog, toggleWindowOrientation } from './window'
function formatGpuSummaryLabel(summary: GpuRuntimeSummary): string {
@@ -28,6 +29,11 @@ export function buildApplicationMenu(options: {
onCheckForUpdates?: () => void
getGpuStatus?: () => GpuRuntimeSummary
onSelectGpuMode?: (mode: GpuRenderMode) => void | Promise<void>
getRecordingState?: () => RecordingStatusSnapshot
onToggleRecording?: (fromMenu?: boolean) => void
onToggleRecordAudio?: (enabled: boolean) => void
onToggleRecordHideCursor?: (enabled: boolean) => void
onOpenRecordingsFolder?: () => void
}): Menu {
const sendAction = (action: string) => {
if (!options.mainWindow.isDestroyed()) {
@@ -42,7 +48,12 @@ export function buildApplicationMenu(options: {
const currentSplashTheme = options.configStore.get().splashTheme
const currentGpuMode = options.configStore.get().gpuMode
const currentRecordAudio = options.configStore.get().recordAudio
const currentRecordHideCursor = options.configStore.get().recordHideCursor
const gpuSummary = options.getGpuStatus?.()
const recordingSnapshot = options.getRecordingState?.()
const recordingState = recordingSnapshot?.state ?? 'idle'
const isRecordingOrStopping = recordingState === 'recording' || recordingState === 'stopping'
const selectSplashTheme = (theme: SplashTheme) => {
options.configStore.updateSplashTheme(theme)
@@ -158,6 +169,48 @@ export function buildApplicationMenu(options: {
},
],
},
{
label: '录屏 / Screen Recording',
submenu: [
{
label: isRecordingOrStopping
? '停止录屏 / Stop Recording'
: recordingState === 'starting'
? '正在启动录屏… / Starting…'
: '开始录屏 / Start Recording',
accelerator: 'CmdOrCtrl+Shift+F9',
enabled: recordingState === 'idle' || recordingState === 'recording',
click: () => {
options.onToggleRecording?.(true)
},
},
{
label: '录制声音 / Include Audio',
type: 'checkbox',
checked: currentRecordAudio,
enabled: recordingState === 'idle',
click: (item) => {
options.onToggleRecordAudio?.(item.checked)
},
},
{
label: '隐藏光标 / Hide Cursor',
type: 'checkbox',
checked: currentRecordHideCursor,
enabled: recordingState === 'idle',
click: (item) => {
options.onToggleRecordHideCursor?.(item.checked)
},
},
{ type: 'separator' },
{
label: '打开录屏目录 / Open Recordings Folder',
click: () => {
options.onOpenRecordingsFolder?.()
},
},
],
},
{ type: 'separator' },
{
label: '打开运维控制台 / Open Admin Console',
+46 -15
View File
@@ -158,6 +158,7 @@ export function createEarthProtocolHandler(options: {
earthBundleRoot: string
getEarthOverlayRoot?: () => string | null
getBackendUrl: () => string
getEarthAuthToken?: (opts?: { forceRefresh?: boolean }) => Promise<string | null>
fetchImpl?: typeof fetch
}): (request: Request) => Promise<Response> {
const fetchImpl = options.fetchImpl ?? fetch
@@ -170,28 +171,58 @@ export function createEarthProtocolHandler(options: {
if (isProxiedBackendPath(parsedUrl.pathname)) {
const targetUrl = new URL(`${parsedUrl.pathname}${parsedUrl.search}`, options.getBackendUrl())
const forwardHeaders = new Headers(request.headers)
forwardHeaders.delete('host')
forwardHeaders.delete('content-length')
if (!forwardHeaders.has('accept-encoding')) {
forwardHeaders.set('accept-encoding', 'gzip, deflate, br')
const buildForwardHeaders = async (forceRefresh = false): Promise<Headers> => {
const headers = new Headers(request.headers)
headers.delete('host')
headers.delete('content-length')
if (!headers.has('accept-encoding')) {
headers.set('accept-encoding', 'gzip, deflate, br')
}
if (
options.getEarthAuthToken &&
parsedUrl.pathname !== '/api/v1/auth/earth-session' &&
(forceRefresh || !headers.has('x-planet-earth-token'))
) {
const token = await options.getEarthAuthToken({ forceRefresh })
if (token) {
headers.set('x-planet-earth-token', token)
}
}
return headers
}
const method = request.method.toUpperCase()
const hasBody = method !== 'GET' && method !== 'HEAD'
try {
const init: RequestInit & { duplex?: 'half' } = {
method,
headers: forwardHeaders,
const makeInit = (headers: Headers): RequestInit & { duplex?: 'half' } => {
const init: RequestInit & { duplex?: 'half' } = {
method,
headers,
}
if (request.signal) {
init.signal = request.signal
}
if (hasBody && request.body) {
init.body = request.body
init.duplex = 'half'
}
return init
}
if (request.signal) {
init.signal = request.signal
let upstream = await fetchImpl(targetUrl.toString(), makeInit(await buildForwardHeaders(false)))
if (
upstream.status === 401 &&
!hasBody &&
options.getEarthAuthToken &&
parsedUrl.pathname !== '/api/v1/auth/earth-session'
) {
try {
await upstream.body?.cancel()
} catch {
// Ignore cancel errors on drained/aborted streams.
}
upstream = await fetchImpl(targetUrl.toString(), makeInit(await buildForwardHeaders(true)))
}
if (hasBody && request.body) {
init.body = request.body
init.duplex = 'half'
}
const upstream = await fetchImpl(targetUrl.toString(), init)
const responseHeaders = new Headers(upstream.headers)
responseHeaders.delete('content-encoding')
responseHeaders.delete('content-length')
+2
View File
@@ -31,12 +31,14 @@ export function installEarthSessionHandlers(
earthBundleRoot: string
getEarthOverlayRoot?: () => string | null
getBackendUrl: () => string
getEarthAuthToken?: (opts?: { forceRefresh?: boolean }) => Promise<string | null>
},
): void {
const handler = createEarthProtocolHandler({
earthBundleRoot: options.earthBundleRoot,
getEarthOverlayRoot: options.getEarthOverlayRoot,
getBackendUrl: options.getBackendUrl,
getEarthAuthToken: options.getEarthAuthToken,
fetchImpl: (input, init) => net.fetch(input as string, init),
})
+329
View File
@@ -0,0 +1,329 @@
export type RecordingState = 'idle' | 'starting' | 'recording' | 'stopping'
export interface RecordingStatusSnapshot {
state: RecordingState
elapsedMs: number
includeAudio: boolean
hideCursor: boolean
filePath: string | null
}
export type RecordingCursorShape = 'default' | 'pointer' | 'grab' | 'grabbing' | 'text'
export interface RecordingCursorPayload {
visible: boolean
x: number
y: number
shape: RecordingCursorShape
}
export interface RectBounds {
x: number
y: number
width: number
height: number
}
const INDICATOR_BASE_WIDTH = 120
const INDICATOR_LONG_WIDTH = 136
const INDICATOR_HEIGHT = 36
/**
* Format elapsed recording duration as MM:SS (or HH:MM:SS once >= 1 hour).
*/
export function formatRecordingDuration(elapsedMs: number): string {
const safeSeconds = Number.isFinite(elapsedMs) && elapsedMs > 0 ? Math.floor(elapsedMs / 1000) : 0
const hours = Math.floor(safeSeconds / 3600)
const minutes = Math.floor((safeSeconds % 3600) / 60)
const seconds = safeSeconds % 60
const pad = (value: number) => String(value).padStart(2, '0')
return hours > 0 ? `${pad(hours)}:${pad(minutes)}:${pad(seconds)}` : `${pad(minutes)}:${pad(seconds)}`
}
/**
* Map a MediaRecorder MIME type to an output video container extension.
*/
export function resolveRecordingExtension(mimeType?: string): 'mp4' | 'webm' {
return typeof mimeType === 'string' && mimeType.toLowerCase().includes('mp4') ? 'mp4' : 'webm'
}
/**
* Build a collision-safe output filename for saved screen recordings.
*/
export function buildRecordingFilename(now: Date, ext: 'mp4' | 'webm', suffixIndex = 0): string {
const pad = (value: number) => String(value).padStart(2, '0')
const stamp = [
now.getFullYear(),
pad(now.getMonth() + 1),
pad(now.getDate()),
'-',
pad(now.getHours()),
pad(now.getMinutes()),
pad(now.getSeconds()),
].join('')
const suffix = suffixIndex > 0 ? `-${suffixIndex + 1}` : ''
return `Planet-Earth-${stamp}${suffix}.${ext}`
}
/**
* Return ordered MediaRecorder MIME candidates, preferring H.264 MP4 before WebM fallbacks.
*/
export function pickSupportedRecordingMimeTypes(includeAudio: boolean): string[] {
if (includeAudio) {
return [
'video/mp4;codecs=avc1.42E01E,mp4a.40.2',
'video/mp4;codecs=avc1.4d401f,mp4a.40.2',
'video/mp4;codecs=avc1.42E01E',
'video/mp4',
'video/webm;codecs=vp9,opus',
'video/webm;codecs=vp8,opus',
'video/webm;codecs=vp9',
'video/webm;codecs=vp8',
'video/webm',
]
}
return [
'video/mp4;codecs=avc1.42E01E',
'video/mp4;codecs=avc1.4d401f',
'video/mp4',
'video/webm;codecs=vp9',
'video/webm;codecs=vp8',
'video/webm',
]
}
/**
* Compute centered top-overlay indicator bounds anchored safely inside mainWindow content area.
*/
export function computeIndicatorBounds(options: {
contentBounds: RectBounds
elapsedMs: number
}): RectBounds {
const { contentBounds, elapsedMs } = options
const desiredWidth = elapsedMs >= 3_600_000 ? INDICATOR_LONG_WIDTH : INDICATOR_BASE_WIDTH
const width = Math.max(60, Math.min(desiredWidth, Math.max(60, contentBounds.width - 16)))
const height = Math.min(INDICATOR_HEIGHT, Math.max(24, contentBounds.height - 8))
const rawX = contentBounds.x + Math.round((contentBounds.width - width) / 2)
const topOffset = Math.min(56, Math.max(10, Math.round(contentBounds.height * 0.08)))
const rawY = contentBounds.y + topOffset
const maxX = contentBounds.x + Math.max(0, contentBounds.width - width)
const maxY = contentBounds.y + Math.max(0, contentBounds.height - height)
return {
x: Math.max(contentBounds.x, Math.min(rawX, maxX)),
y: Math.max(contentBounds.y, Math.min(rawY, maxY)),
width,
height,
}
}
/**
* Render self-contained HTML for the transparent floating recording indicator pill.
*/
export function buildRecordingIndicatorHtml(): string {
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<style>
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: transparent;
overflow: hidden;
user-select: none;
-webkit-user-select: none;
display: flex;
align-items: center;
justify-content: center;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
}
.rec-pill {
appearance: none;
height: 30px;
padding: 0 12px 0 10px;
border-radius: 999px;
border: 1px solid rgba(201, 225, 247, 0.22);
background: rgba(8, 16, 28, 0.8);
backdrop-filter: blur(14px) saturate(130%);
-webkit-backdrop-filter: blur(14px) saturate(130%);
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.42), inset 0 1px 0 rgba(255, 255, 255, 0.14);
color: #eef5ff;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
cursor: pointer;
outline: none;
transition: border-color 0.16s ease, background 0.16s ease, box-shadow 0.16s ease, transform 0.14s ease;
}
.rec-pill:hover {
border-color: rgba(248, 113, 113, 0.56);
background: rgba(24, 18, 28, 0.88);
box-shadow: 0 6px 20px rgba(239, 68, 68, 0.22), inset 0 1px 0 rgba(255, 255, 255, 0.18);
}
.rec-pill:active {
transform: scale(0.96);
}
.rec-glyph-wrap {
width: 12px;
height: 12px;
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.rec-glyph {
width: 9px;
height: 9px;
border-radius: 50%;
background: #ef4444;
box-shadow: 0 0 8px rgba(239, 68, 68, 0.72);
animation: recPulse 1.4s ease-in-out infinite;
transition: width 0.15s ease, height 0.15s ease, border-radius 0.15s ease, background 0.15s ease, box-shadow 0.15s ease;
}
.rec-pill:hover .rec-glyph {
width: 10px;
height: 10px;
border-radius: 2px;
background: #f87171;
box-shadow: 0 0 10px rgba(248, 113, 113, 0.8);
animation: none;
opacity: 1;
transform: none;
}
.rec-time {
font-size: 12px;
font-weight: 600;
line-height: 1;
letter-spacing: 0.03em;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
@keyframes recPulse {
0%, 100% {
opacity: 1;
transform: scale(1);
}
50% {
opacity: 0.32;
transform: scale(0.8);
}
}
</style>
</head>
<body>
<button id="rec-stop-btn" class="rec-pill" type="button" title="点击停止录屏 (Ctrl+Shift+F9)" aria-label="停止录屏">
<span class="rec-glyph-wrap" aria-hidden="true"><span class="rec-glyph"></span></span>
<span id="rec-timer" class="rec-time">00:00</span>
</button>
<script>
const btn = document.getElementById('rec-stop-btn');
const timerEl = document.getElementById('rec-timer');
if (window.planetRecordingIndicator?.onTick) {
window.planetRecordingIndicator.onTick((formatted) => {
if (typeof formatted === 'string' && timerEl) {
timerEl.textContent = formatted;
}
});
}
btn?.addEventListener('click', () => {
window.planetRecordingIndicator?.requestStop?.();
});
</script>
</body>
</html>`
}
/**
* Render self-contained HTML for the transparent click-through custom cursor overlay window.
*/
export function buildCursorOverlayHtml(): string {
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<style>
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: transparent;
overflow: hidden;
pointer-events: none;
user-select: none;
-webkit-user-select: none;
}
#cursor-root {
position: fixed;
left: 0;
top: 0;
width: 24px;
height: 24px;
opacity: 0;
will-change: transform;
pointer-events: none;
}
.cursor-svg {
display: none;
width: 24px;
height: 24px;
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.55));
}
#cursor-root[data-shape="default"] .cursor-svg--default,
#cursor-root[data-shape="pointer"] .cursor-svg--pointer,
#cursor-root[data-shape="grab"] .cursor-svg--grab,
#cursor-root[data-shape="grabbing"] .cursor-svg--grabbing,
#cursor-root[data-shape="text"] .cursor-svg--text {
display: block;
}
</style>
</head>
<body>
<div id="cursor-root" data-shape="default" aria-hidden="true">
<svg class="cursor-svg cursor-svg--default" viewBox="0 0 24 24" fill="none">
<path d="M2 1.5L2 19.5L6.8 14.9L10.3 21.8L13.1 20.4L9.7 13.6L16.3 13.6L2 1.5Z" fill="#ffffff" stroke="#0f172a" stroke-width="1.5" stroke-linejoin="round"/>
</svg>
<svg class="cursor-svg cursor-svg--pointer" viewBox="0 0 24 24" fill="none">
<path d="M8.5 1.8C9.6 1.8 10.5 2.7 10.5 3.8V10.1C11 9.6 11.7 9.4 12.4 9.7C13.1 9.9 13.6 10.5 13.7 11.1C14.2 10.7 15 10.5 15.7 10.8C16.4 11.1 16.9 11.8 17 12.6C17.5 12.3 18.2 12.3 18.8 12.6C19.5 12.9 20 13.6 20 14.5V16.8C20 19.7 17.8 22 14.9 22H11.5C9.6 22 7.9 21 6.9 19.4L4.7 15.7C4.2 14.9 4.5 13.8 5.3 13.4C6 13 6.9 13.2 7.4 13.9L6.5 15.3V3.8C6.5 2.7 7.4 1.8 8.5 1.8Z" fill="#ffffff" stroke="#0f172a" stroke-width="1.45" stroke-linejoin="round"/>
</svg>
<svg class="cursor-svg cursor-svg--grab" viewBox="0 0 24 24" fill="none">
<path d="M7 11V5.5C7 4.7 7.7 4 8.5 4C9.3 4 10 4.7 10 5.5V10.5M10 10V4.5C10 3.7 10.7 3 11.5 3C12.3 3 13 3.7 13 4.5V10.5M13 10.5V5.5C13 4.7 13.7 4 14.5 4C15.3 4 16 4.7 16 5.5V11.5M16 11.5V7.5C16 6.7 16.7 6 17.5 6C18.3 6 19 6.7 19 7.5V15C19 18.6 16.3 21 12.8 21H10.5C8.5 21 6.7 20 5.7 18.3L4.2 15.7C3.7 14.9 4 13.9 4.8 13.4C5.5 13 6.4 13.2 6.9 13.9L7 14V11Z" fill="#ffffff" stroke="#0f172a" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<svg class="cursor-svg cursor-svg--grabbing" viewBox="0 0 24 24" fill="none">
<path d="M6.5 11.5C6.5 9.8 7.8 8.8 9.2 9.2V8.2C9.2 7 10.2 6.2 11.3 6.5C11.9 6.7 12.4 7.1 12.6 7.7C13.2 7 14.3 6.8 15.2 7.3C15.8 7.6 16.2 8.2 16.3 8.9C17.2 8.7 18.2 9.4 18.2 10.4V15C18.2 18.4 15.7 21 12.4 21H10.4C8.4 21 6.7 19.8 5.9 18L4.9 15.6C4.6 14.9 4.9 14 5.7 13.7L6.5 13.4V11.5Z" fill="#ffffff" stroke="#0f172a" stroke-width="1.45" stroke-linejoin="round"/>
</svg>
<svg class="cursor-svg cursor-svg--text" viewBox="0 0 24 24" fill="none">
<path d="M6 4H14M6 20H14M10 4V20" stroke="#0f172a" stroke-width="3.2" stroke-linecap="round"/>
<path d="M6 4H14M6 20H14M10 4V20" stroke="#ffffff" stroke-width="1.6" stroke-linecap="round"/>
</svg>
</div>
<script>
const root = document.getElementById('cursor-root');
const HOTSPOTS = {
default: [0, 0],
pointer: [-8, -2],
grab: [-10, -10],
grabbing: [-10, -10],
text: [-10, -12],
};
if (window.planetRecordingCursor?.onUpdate) {
window.planetRecordingCursor.onUpdate((payload) => {
if (!root || !payload) return;
if (!payload.visible) {
root.style.opacity = '0';
return;
}
const shape = HOTSPOTS[payload.shape] ? payload.shape : 'default';
const [ox, oy] = HOTSPOTS[shape];
root.dataset.shape = shape;
root.style.transform = 'translate3d(' + (Math.round(payload.x) + ox) + 'px, ' + (Math.round(payload.y) + oy) + 'px, 0)';
root.style.opacity = '1';
});
}
</script>
</body>
</html>`
}
+225
View File
@@ -0,0 +1,225 @@
import { BrowserWindow } from 'electron'
import { buildCursorOverlayHtml, type RecordingCursorPayload } from './recording-core'
export interface RecordingCursorOverlayController {
show: () => void
updateCursor: (payload: RecordingCursorPayload) => void
hide: () => void
destroy: () => void
}
const HIDDEN_CURSOR_PAYLOAD: RecordingCursorPayload = {
visible: false,
x: 0,
y: 0,
shape: 'default',
}
/**
* Manage a stationary, transparent, click-through overlay window that renders a custom
* pointer for the user while the OS cursor is hidden in mainFrame screen recordings.
*/
export function createRecordingCursorOverlayController(options: {
getMainWindow: () => BrowserWindow | null
preloadPath: string
}): RecordingCursorOverlayController {
let overlayWin: BrowserWindow | null = null
let boundMainWin: BrowserWindow | null = null
let blurHideTimer: ReturnType<typeof setTimeout> | null = null
let visible = false
let destroyed = false
let readyToShow = false
const clearBlurHideTimer = () => {
if (blurHideTimer) {
clearTimeout(blurHideTimer)
blurHideTimer = null
}
}
const pushCursor = (payload: RecordingCursorPayload) => {
if (!overlayWin || overlayWin.isDestroyed() || overlayWin.webContents.isDestroyed()) return
overlayWin.webContents.send('planet:recording-cursor-update', payload)
}
const syncBoundsAndLevel = () => {
const mainWin = options.getMainWindow()
if (
destroyed ||
!visible ||
!overlayWin ||
overlayWin.isDestroyed() ||
!mainWin ||
mainWin.isDestroyed()
) {
return
}
if (mainWin.isMinimized() || !mainWin.isVisible() || !mainWin.isFocused()) {
pushCursor(HIDDEN_CURSOR_PAYLOAD)
if (overlayWin.isVisible()) {
overlayWin.hide()
}
return
}
const contentBounds = mainWin.getContentBounds()
if (contentBounds.width > 0 && contentBounds.height > 0) {
overlayWin.setBounds(contentBounds)
}
overlayWin.setAlwaysOnTop(true, mainWin.isFullScreen() ? 'screen-saver' : 'floating')
if (readyToShow && !overlayWin.isVisible()) {
overlayWin.showInactive()
}
}
const handleMainFocus = () => {
clearBlurHideTimer()
syncBoundsAndLevel()
}
const handleMainBlur = () => {
clearBlurHideTimer()
blurHideTimer = setTimeout(() => {
blurHideTimer = null
const mainWin = options.getMainWindow()
if (!mainWin || mainWin.isDestroyed() || !mainWin.isFocused()) {
pushCursor(HIDDEN_CURSOR_PAYLOAD)
if (overlayWin && !overlayWin.isDestroyed() && overlayWin.isVisible()) {
overlayWin.hide()
}
}
}, 60)
}
const unbindMainWindowListeners = () => {
clearBlurHideTimer()
if (!boundMainWin || boundMainWin.isDestroyed()) {
boundMainWin = null
return
}
boundMainWin.removeListener('move', syncBoundsAndLevel)
boundMainWin.removeListener('resize', syncBoundsAndLevel)
boundMainWin.removeListener('maximize', syncBoundsAndLevel)
boundMainWin.removeListener('unmaximize', syncBoundsAndLevel)
boundMainWin.removeListener('minimize', syncBoundsAndLevel)
boundMainWin.removeListener('restore', syncBoundsAndLevel)
boundMainWin.removeListener('enter-full-screen', syncBoundsAndLevel)
boundMainWin.removeListener('leave-full-screen', syncBoundsAndLevel)
boundMainWin.removeListener('show', syncBoundsAndLevel)
boundMainWin.removeListener('hide', syncBoundsAndLevel)
boundMainWin.removeListener('focus', handleMainFocus)
boundMainWin.removeListener('blur', handleMainBlur)
boundMainWin.removeListener('closed', hide)
boundMainWin = null
}
const bindMainWindowListeners = (mainWin: BrowserWindow) => {
if (boundMainWin === mainWin) return
unbindMainWindowListeners()
boundMainWin = mainWin
mainWin.on('move', syncBoundsAndLevel)
mainWin.on('resize', syncBoundsAndLevel)
mainWin.on('maximize', syncBoundsAndLevel)
mainWin.on('unmaximize', syncBoundsAndLevel)
mainWin.on('minimize', syncBoundsAndLevel)
mainWin.on('restore', syncBoundsAndLevel)
mainWin.on('enter-full-screen', syncBoundsAndLevel)
mainWin.on('leave-full-screen', syncBoundsAndLevel)
mainWin.on('show', syncBoundsAndLevel)
mainWin.on('hide', syncBoundsAndLevel)
mainWin.on('focus', handleMainFocus)
mainWin.on('blur', handleMainBlur)
mainWin.on('closed', hide)
}
const ensureOverlayWindow = (mainWin: BrowserWindow): BrowserWindow => {
if (overlayWin && !overlayWin.isDestroyed()) {
return overlayWin
}
readyToShow = false
const contentBounds = mainWin.getContentBounds()
overlayWin = new BrowserWindow({
x: contentBounds.x,
y: contentBounds.y,
width: Math.max(1, contentBounds.width),
height: Math.max(1, contentBounds.height),
transparent: true,
backgroundColor: '#00000000',
frame: false,
thickFrame: false,
roundedCorners: false,
resizable: false,
movable: false,
minimizable: false,
maximizable: false,
closable: false,
focusable: false,
skipTaskbar: true,
hasShadow: false,
show: false,
webPreferences: {
preload: options.preloadPath,
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
},
})
overlayWin.setMenuBarVisibility(false)
overlayWin.setIgnoreMouseEvents(true)
overlayWin.webContents.once('did-finish-load', () => {
if (!overlayWin || overlayWin.isDestroyed()) return
void overlayWin.webContents.setVisualZoomLevelLimits(1, 1)
readyToShow = true
pushCursor(HIDDEN_CURSOR_PAYLOAD)
if (visible) {
syncBoundsAndLevel()
}
})
void overlayWin.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(buildCursorOverlayHtml())}`)
return overlayWin
}
const show = () => {
if (destroyed) return
const mainWin = options.getMainWindow()
if (!mainWin || mainWin.isDestroyed()) return
clearBlurHideTimer()
visible = true
bindMainWindowListeners(mainWin)
ensureOverlayWindow(mainWin)
syncBoundsAndLevel()
}
const updateCursor = (payload: RecordingCursorPayload) => {
if (destroyed || !visible || !readyToShow) return
pushCursor(payload)
}
function hide() {
clearBlurHideTimer()
visible = false
pushCursor(HIDDEN_CURSOR_PAYLOAD)
if (overlayWin && !overlayWin.isDestroyed() && overlayWin.isVisible()) {
overlayWin.hide()
}
}
const destroy = () => {
destroyed = true
visible = false
unbindMainWindowListeners()
if (overlayWin && !overlayWin.isDestroyed()) {
overlayWin.destroy()
}
overlayWin = null
}
return {
show,
updateCursor,
hide,
destroy,
}
}
+213
View File
@@ -0,0 +1,213 @@
import { BrowserWindow } from 'electron'
import { buildRecordingIndicatorHtml, computeIndicatorBounds, formatRecordingDuration } from './recording-core'
export interface RecordingIndicatorController {
show: (elapsedMs?: number) => void
updateElapsed: (elapsedMs: number) => void
hide: () => void
destroy: () => void
}
export function createRecordingIndicatorController(options: {
getMainWindow: () => BrowserWindow | null
preloadPath: string
}): RecordingIndicatorController {
let indicatorWin: BrowserWindow | null = null
let boundMainWin: BrowserWindow | null = null
let blurHideTimer: ReturnType<typeof setTimeout> | null = null
let visible = false
let lastElapsedMs = 0
let destroyed = false
let readyToShow = false
const clearBlurHideTimer = () => {
if (blurHideTimer) {
clearTimeout(blurHideTimer)
blurHideTimer = null
}
}
const syncBoundsAndLevel = () => {
const mainWin = options.getMainWindow()
if (
destroyed ||
!visible ||
!indicatorWin ||
indicatorWin.isDestroyed() ||
!mainWin ||
mainWin.isDestroyed()
) {
return
}
if (mainWin.isMinimized() || !mainWin.isVisible() || !mainWin.isFocused()) {
if (indicatorWin.isVisible()) {
indicatorWin.hide()
}
return
}
const contentBounds = mainWin.getContentBounds()
const nextBounds = computeIndicatorBounds({ contentBounds, elapsedMs: lastElapsedMs })
indicatorWin.setBounds(nextBounds)
indicatorWin.setAlwaysOnTop(true, mainWin.isFullScreen() ? 'screen-saver' : 'pop-up-menu')
if (readyToShow && !indicatorWin.isVisible()) {
indicatorWin.showInactive()
}
}
const handleMainFocus = () => {
clearBlurHideTimer()
syncBoundsAndLevel()
}
const handleMainBlur = () => {
clearBlurHideTimer()
blurHideTimer = setTimeout(() => {
blurHideTimer = null
const mainWin = options.getMainWindow()
if (!mainWin || mainWin.isDestroyed() || !mainWin.isFocused()) {
if (indicatorWin && !indicatorWin.isDestroyed() && indicatorWin.isVisible()) {
indicatorWin.hide()
}
}
}, 60)
}
const pushTick = (elapsedMs: number) => {
if (!indicatorWin || indicatorWin.isDestroyed() || indicatorWin.webContents.isDestroyed()) return
indicatorWin.webContents.send('planet:recording-indicator-tick', formatRecordingDuration(elapsedMs))
}
const unbindMainWindowListeners = () => {
clearBlurHideTimer()
if (!boundMainWin || boundMainWin.isDestroyed()) {
boundMainWin = null
return
}
boundMainWin.removeListener('move', syncBoundsAndLevel)
boundMainWin.removeListener('resize', syncBoundsAndLevel)
boundMainWin.removeListener('maximize', syncBoundsAndLevel)
boundMainWin.removeListener('unmaximize', syncBoundsAndLevel)
boundMainWin.removeListener('minimize', syncBoundsAndLevel)
boundMainWin.removeListener('restore', syncBoundsAndLevel)
boundMainWin.removeListener('enter-full-screen', syncBoundsAndLevel)
boundMainWin.removeListener('leave-full-screen', syncBoundsAndLevel)
boundMainWin.removeListener('show', syncBoundsAndLevel)
boundMainWin.removeListener('hide', syncBoundsAndLevel)
boundMainWin.removeListener('focus', handleMainFocus)
boundMainWin.removeListener('blur', handleMainBlur)
boundMainWin.removeListener('closed', hide)
boundMainWin = null
}
const bindMainWindowListeners = (mainWin: BrowserWindow) => {
if (boundMainWin === mainWin) return
unbindMainWindowListeners()
boundMainWin = mainWin
mainWin.on('move', syncBoundsAndLevel)
mainWin.on('resize', syncBoundsAndLevel)
mainWin.on('maximize', syncBoundsAndLevel)
mainWin.on('unmaximize', syncBoundsAndLevel)
mainWin.on('minimize', syncBoundsAndLevel)
mainWin.on('restore', syncBoundsAndLevel)
mainWin.on('enter-full-screen', syncBoundsAndLevel)
mainWin.on('leave-full-screen', syncBoundsAndLevel)
mainWin.on('show', syncBoundsAndLevel)
mainWin.on('hide', syncBoundsAndLevel)
mainWin.on('focus', handleMainFocus)
mainWin.on('blur', handleMainBlur)
mainWin.on('closed', hide)
}
const ensureIndicatorWindow = (mainWin: BrowserWindow): BrowserWindow => {
if (indicatorWin && !indicatorWin.isDestroyed()) {
return indicatorWin
}
readyToShow = false
const initialBounds = computeIndicatorBounds({
contentBounds: mainWin.getContentBounds(),
elapsedMs: lastElapsedMs,
})
indicatorWin = new BrowserWindow({
...initialBounds,
transparent: true,
backgroundColor: '#00000000',
frame: false,
thickFrame: false,
roundedCorners: false,
resizable: false,
movable: false,
minimizable: false,
maximizable: false,
closable: false,
focusable: false,
skipTaskbar: true,
hasShadow: false,
show: false,
webPreferences: {
preload: options.preloadPath,
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
},
})
indicatorWin.setMenuBarVisibility(false)
indicatorWin.webContents.once('did-finish-load', () => {
if (!indicatorWin || indicatorWin.isDestroyed()) return
void indicatorWin.webContents.setVisualZoomLevelLimits(1, 1)
readyToShow = true
pushTick(lastElapsedMs)
if (visible) {
syncBoundsAndLevel()
}
})
void indicatorWin.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(buildRecordingIndicatorHtml())}`)
return indicatorWin
}
const show = (elapsedMs = 0) => {
if (destroyed) return
const mainWin = options.getMainWindow()
if (!mainWin || mainWin.isDestroyed()) return
clearBlurHideTimer()
visible = true
lastElapsedMs = Math.max(0, elapsedMs)
bindMainWindowListeners(mainWin)
ensureIndicatorWindow(mainWin)
pushTick(lastElapsedMs)
syncBoundsAndLevel()
}
const updateElapsed = (elapsedMs: number) => {
lastElapsedMs = Math.max(0, elapsedMs)
if (!visible) return
pushTick(lastElapsedMs)
syncBoundsAndLevel()
}
function hide() {
clearBlurHideTimer()
visible = false
if (indicatorWin && !indicatorWin.isDestroyed() && indicatorWin.isVisible()) {
indicatorWin.hide()
}
}
const destroy = () => {
destroyed = true
visible = false
unbindMainWindowListeners()
if (indicatorWin && !indicatorWin.isDestroyed()) {
indicatorWin.destroy()
}
indicatorWin = null
}
return {
show,
updateElapsed,
hide,
destroy,
}
}
+465
View File
@@ -0,0 +1,465 @@
import fs from 'node:fs'
import path from 'node:path'
import {
app,
ipcMain,
shell,
type BrowserWindow,
type Event as ElectronEvent,
type Session,
} from 'electron'
import type { DesktopConfigStore } from './config'
import {
buildRecordingFilename,
resolveRecordingExtension,
type RecordingCursorShape,
type RecordingState,
type RecordingStatusSnapshot,
} from './recording-core'
import { createRecordingCursorOverlayController } from './recording-cursor-overlay'
import { createRecordingIndicatorController } from './recording-indicator'
export interface RecordingStatusToastOptions {
message: string
type?: 'info' | 'success' | 'error'
fullText?: boolean
durationMs?: number
actionLabel?: string
action?: 'open-recordings-folder'
}
const VALID_CURSOR_SHAPES = new Set<RecordingCursorShape>(['default', 'pointer', 'grab', 'grabbing', 'text'])
export interface ScreenRecorderController {
getState: () => RecordingStatusSnapshot
isActive: () => boolean
startRecording: (options?: { fromMenu?: boolean }) => Promise<void>
stopRecording: (options?: { timeoutMs?: number }) => Promise<void>
toggleRecording: (options?: { fromMenu?: boolean }) => Promise<RecordingStatusSnapshot>
openRecordingsFolder: () => Promise<void>
handleWindowClose: (win: BrowserWindow, event: ElectronEvent) => void
destroy: () => void
}
export function createScreenRecorderController(options: {
getMainWindow: () => BrowserWindow | null
configStore: DesktopConfigStore
session: Session
indicatorPreloadPath: string
cursorOverlayPreloadPath: string
dismissMenuBar: (win: BrowserWindow | null) => void
onStateChanged: () => void
}): ScreenRecorderController {
let state: RecordingState = 'idle'
let includeAudio = options.configStore.get().recordAudio
let hideCursor = options.configStore.get().recordHideCursor
let activeFilePath: string | null = null
let activeFileName: string | null = null
let lastSavedFilePath: string | null = null
let writeStream: fs.WriteStream | null = null
let writeChain: Promise<void> = Promise.resolve()
let bytesWritten = 0
let startedAtMs = 0
let elapsedTimer: ReturnType<typeof setInterval> | null = null
let pendingCaptureExpiresAt = 0
let pendingCaptureIncludeAudio = false
let finishPromise: Promise<void> | null = null
let resolveFinish: (() => void) | null = null
let lastToggleAt = 0
let forceAllowWindowClose = false
let destroyed = false
const cursorOverlay = createRecordingCursorOverlayController({
getMainWindow: options.getMainWindow,
preloadPath: options.cursorOverlayPreloadPath,
})
const indicator = createRecordingIndicatorController({
getMainWindow: options.getMainWindow,
preloadPath: options.indicatorPreloadPath,
})
const notifyStatus = (
messageOrOptions: string | RecordingStatusToastOptions,
type: 'info' | 'success' | 'error' = 'info',
) => {
const win = options.getMainWindow()
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) return
const payload: RecordingStatusToastOptions =
typeof messageOrOptions === 'string'
? { message: messageOrOptions, type }
: { type: 'info', ...messageOrOptions }
win.webContents.send('planet:update-status', payload)
}
const resolveRecordingsDir = (): string => {
try {
return path.join(app.getPath('videos'), 'Planet Earth')
} catch {
return path.join(app.getPath('userData'), 'recordings')
}
}
const allocateOutputFile = (mimeType?: string): { filePath: string; fileName: string } => {
const dir = resolveRecordingsDir()
fs.mkdirSync(dir, { recursive: true })
const ext = resolveRecordingExtension(mimeType)
const now = new Date()
for (let suffix = 0; suffix < 100; suffix += 1) {
const fileName = buildRecordingFilename(now, ext, suffix)
const filePath = path.join(dir, fileName)
if (!fs.existsSync(filePath)) {
return { filePath, fileName }
}
}
const fallbackName = buildRecordingFilename(now, ext, Math.floor(Math.random() * 10000))
return { filePath: path.join(dir, fallbackName), fileName: fallbackName }
}
const clearElapsedTimer = () => {
if (elapsedTimer) {
clearInterval(elapsedTimer)
elapsedTimer = null
}
}
const resolvePendingFinish = () => {
const resolver = resolveFinish
resolveFinish = null
finishPromise = null
resolver?.()
}
const closeWriteStream = async (): Promise<{ savedPath: string | null; savedName: string | null; hadData: boolean }> => {
const targetStream = writeStream
const targetPath = activeFilePath
const targetName = activeFileName
const wroteBytes = bytesWritten
writeStream = null
activeFilePath = null
activeFileName = null
bytesWritten = 0
await writeChain.catch(() => {})
if (targetStream) {
await new Promise<void>((resolve) => {
if (targetStream.closed || targetStream.writableEnded) {
resolve()
return
}
targetStream.once('finish', resolve)
targetStream.once('error', () => resolve())
targetStream.end()
})
}
if (targetPath && wroteBytes === 0) {
try {
if (fs.existsSync(targetPath)) {
fs.unlinkSync(targetPath)
}
} catch {
// Ignore empty file cleanup error.
}
return { savedPath: null, savedName: null, hadData: false }
}
return { savedPath: targetPath, savedName: targetName, hadData: wroteBytes > 0 }
}
const resetToIdle = () => {
clearElapsedTimer()
pendingCaptureExpiresAt = 0
startedAtMs = 0
cursorOverlay.hide()
indicator.hide()
state = 'idle'
options.onStateChanged()
resolvePendingFinish()
}
const getState = (): RecordingStatusSnapshot => ({
state,
elapsedMs: startedAtMs > 0 && (state === 'recording' || state === 'stopping') ? Date.now() - startedAtMs : 0,
includeAudio,
hideCursor,
filePath: activeFilePath ?? lastSavedFilePath,
})
const isActive = () => state !== 'idle'
// Capture Planet Earth's mainFrame directly so external floating overlays never appear in recordings.
options.session.setDisplayMediaRequestHandler((_request, callback) => {
if (destroyed || Date.now() > pendingCaptureExpiresAt) {
callback({})
return
}
const win = options.getMainWindow()
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) {
callback({})
return
}
const mainFrame = win.webContents.mainFrame
if (!mainFrame) {
callback({})
return
}
callback(
pendingCaptureIncludeAudio
? { video: mainFrame, audio: mainFrame, enableLocalEcho: true }
: { video: mainFrame },
)
})
const onOpenFile = (
_event: Electron.IpcMainInvokeEvent,
payload: { mimeType?: string; includeAudio?: boolean; hideCursor?: boolean } = {},
) => {
if (destroyed || state === 'idle' || state === 'stopping') {
throw new Error('Recording is not active')
}
pendingCaptureExpiresAt = 0
includeAudio = Boolean(payload?.includeAudio)
hideCursor = Boolean(payload?.hideCursor)
const { filePath, fileName } = allocateOutputFile(payload?.mimeType)
activeFilePath = filePath
activeFileName = fileName
bytesWritten = 0
writeChain = Promise.resolve()
writeStream = fs.createWriteStream(filePath)
writeStream.on('error', (err) => {
notifyStatus(`录屏写入失败:${err.message}`, 'error')
})
startedAtMs = Date.now()
state = 'recording'
if (hideCursor) {
cursorOverlay.show()
} else {
cursorOverlay.hide()
}
// Show stop indicator after cursor overlay so the clickable pill stays above the cursor layer.
indicator.show(0)
clearElapsedTimer()
elapsedTimer = setInterval(() => {
if (state === 'recording' || state === 'stopping') {
indicator.updateElapsed(Date.now() - startedAtMs)
}
}, 250)
options.onStateChanged()
return { filePath, fileName }
}
const onChunk = (_event: Electron.IpcMainEvent, rawChunk: unknown) => {
if (!writeStream || !(rawChunk instanceof Uint8Array || Buffer.isBuffer(rawChunk))) return
const buffer = Buffer.from(rawChunk)
if (buffer.byteLength === 0) return
bytesWritten += buffer.byteLength
const targetStream = writeStream
writeChain = writeChain.then(
() =>
new Promise<void>((resolve) => {
if (!targetStream || targetStream.destroyed) {
resolve()
return
}
const ok = targetStream.write(buffer, () => resolve())
if (!ok) {
targetStream.once('drain', resolve)
}
}),
)
}
const onCursorMove = (_event: Electron.IpcMainEvent, rawPayload: unknown) => {
if (destroyed || !hideCursor || (state !== 'recording' && state !== 'stopping')) return
if (!rawPayload || typeof rawPayload !== 'object') return
const candidate = rawPayload as { visible?: unknown; x?: unknown; y?: unknown; shape?: unknown }
const x = Number(candidate.x)
const y = Number(candidate.y)
if (!Number.isFinite(x) || !Number.isFinite(y)) return
const shape: RecordingCursorShape =
typeof candidate.shape === 'string' && VALID_CURSOR_SHAPES.has(candidate.shape as RecordingCursorShape)
? (candidate.shape as RecordingCursorShape)
: 'default'
cursorOverlay.updateCursor({
visible: Boolean(candidate.visible),
x,
y,
shape,
})
}
const onFinish = async () => {
clearElapsedTimer()
const result = await closeWriteStream()
if (result.savedPath && result.savedName && result.hadData) {
lastSavedFilePath = result.savedPath
notifyStatus({
message: `已保存录屏:${result.savedPath}`,
type: 'success',
fullText: true,
durationMs: 6000,
actionLabel: '打开目录',
action: 'open-recordings-folder',
})
} else if (state !== 'idle') {
notifyStatus('录屏已停止(未采集到有效画面帧)', 'info')
}
resetToIdle()
return result
}
const onAbort = async (_event: Electron.IpcMainInvokeEvent, payload?: { error?: string }) => {
await closeWriteStream()
if (payload?.error) {
notifyStatus(`启动录屏失败:${payload.error}`, 'error')
}
resetToIdle()
}
const onAudioFallback = () => {
includeAudio = false
notifyStatus('当前设备不支持内录音频,已切换为静音录屏', 'info')
}
const onIndicatorStop = () => {
void stopRecording()
}
const onIpcToggle = async () => {
return toggleRecording({ fromMenu: false })
}
const onIpcOpenFolder = async () => {
await openRecordingsFolder()
}
ipcMain.handle('planet:recording-open-file', onOpenFile)
ipcMain.on('planet:recording-chunk', onChunk)
ipcMain.on('planet:recording-cursor-move', onCursorMove)
ipcMain.handle('planet:recording-finish', onFinish)
ipcMain.handle('planet:recording-abort', onAbort)
ipcMain.on('planet:recording-audio-fallback', onAudioFallback)
ipcMain.on('planet:recording-indicator-stop', onIndicatorStop)
ipcMain.handle('planet:recording-toggle', onIpcToggle)
ipcMain.handle('planet:recording-open-folder', onIpcOpenFolder)
const startRecording = async (startOpts?: { fromMenu?: boolean }): Promise<void> => {
if (destroyed || state !== 'idle') return
const win = options.getMainWindow()
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) return
state = 'starting'
includeAudio = options.configStore.get().recordAudio
hideCursor = options.configStore.get().recordHideCursor
options.onStateChanged()
if (startOpts?.fromMenu) {
options.dismissMenuBar(win)
await new Promise((resolve) => setTimeout(resolve, 140))
}
if (destroyed || win.isDestroyed() || win.webContents.isDestroyed() || state !== 'starting') {
resetToIdle()
return
}
pendingCaptureIncludeAudio = includeAudio
pendingCaptureExpiresAt = Date.now() + 8000
win.webContents.send('planet:recording-start', { includeAudio, hideCursor })
}
const stopRecording = async (stopOpts?: { timeoutMs?: number }): Promise<void> => {
if (destroyed || state === 'idle') return
if (finishPromise) return finishPromise
const win = options.getMainWindow()
state = 'stopping'
options.onStateChanged()
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) {
await onFinish()
return
}
finishPromise = new Promise<void>((resolve) => {
resolveFinish = resolve
})
const timeoutMs = stopOpts?.timeoutMs ?? 4000
const timeoutHandle = setTimeout(() => {
void onFinish()
}, timeoutMs)
win.webContents.send('planet:recording-stop')
await finishPromise
clearTimeout(timeoutHandle)
}
const toggleRecording = async (toggleOpts?: { fromMenu?: boolean }): Promise<RecordingStatusSnapshot> => {
const now = Date.now()
if (now - lastToggleAt < 250) {
return getState()
}
lastToggleAt = now
if (state === 'idle') {
await startRecording(toggleOpts)
} else if (state === 'recording') {
await stopRecording()
}
return getState()
}
const openRecordingsFolder = async (): Promise<void> => {
const dir = resolveRecordingsDir()
fs.mkdirSync(dir, { recursive: true })
if (lastSavedFilePath && fs.existsSync(lastSavedFilePath)) {
shell.showItemInFolder(lastSavedFilePath)
return
}
await shell.openPath(dir)
}
const handleWindowClose = (win: BrowserWindow, event: ElectronEvent): void => {
if (forceAllowWindowClose || state === 'idle') return
event.preventDefault()
void stopRecording({ timeoutMs: 3000 }).finally(() => {
forceAllowWindowClose = true
if (!win.isDestroyed()) {
win.close()
}
})
}
const destroy = () => {
if (destroyed) return
destroyed = true
clearElapsedTimer()
pendingCaptureExpiresAt = 0
void closeWriteStream()
cursorOverlay.destroy()
indicator.destroy()
ipcMain.removeHandler('planet:recording-open-file')
ipcMain.removeListener('planet:recording-chunk', onChunk)
ipcMain.removeListener('planet:recording-cursor-move', onCursorMove)
ipcMain.removeHandler('planet:recording-finish')
ipcMain.removeHandler('planet:recording-abort')
ipcMain.removeListener('planet:recording-audio-fallback', onAudioFallback)
ipcMain.removeListener('planet:recording-indicator-stop', onIndicatorStop)
ipcMain.removeHandler('planet:recording-toggle')
ipcMain.removeHandler('planet:recording-open-folder')
resolvePendingFinish()
}
return {
getState,
isActive,
startRecording,
stopRecording,
toggleRecording,
openRecordingsFolder,
handleWindowClose,
destroy,
}
}
+16
View File
@@ -180,6 +180,7 @@ export function createMainWindow(options: {
iconPath: string
userDataDir: string
configStore: DesktopConfigStore
onToggleRecording?: () => void
}): BrowserWindow {
nativeTheme.themeSource = 'dark'
@@ -266,6 +267,21 @@ export function createMainWindow(options: {
return
}
if (
input.type === 'keyDown' &&
!input.isAutoRepeat &&
input.control &&
input.shift &&
!input.alt &&
!input.meta &&
input.key.toLowerCase() === 'f9'
) {
altTracker.reset()
event.preventDefault()
options.onToggleRecording?.()
return
}
const action = altTracker.handleInput(input)
if (action === 'toggle') {
event.preventDefault()
+9
View File
@@ -1,6 +1,7 @@
import { contextBridge, ipcRenderer } from 'electron'
import { startDesktopLowFpsWatcher } from './fps-watcher'
import { initDesktopScreenRecorder, openDesktopRecordingsFolder, toggleDesktopRecording } from './screen-recorder'
import { createDesktopSplashController, type SplashTheme } from './splash'
interface PreloadRuntimeConfig {
@@ -72,6 +73,10 @@ if (
})
}
if (!runtimeConfig.headlessSmoke) {
initDesktopScreenRecorder()
}
contextBridge.exposeInMainWorld('__PLANET_RUNTIME_CONFIG__', runtimeConfig)
contextBridge.exposeInMainWorld('planetDesktop', {
@@ -93,8 +98,12 @@ contextBridge.exposeInMainWorld('planetDesktop', {
replaySplash: (theme?: SplashTheme) => {
splashController.replay(theme)
},
toggleRecording: () => toggleDesktopRecording(),
openRecordingsFolder: () => openDesktopRecordingsFolder(),
checkForUpdates: () => ipcRenderer.invoke('planet:check-for-updates') as Promise<void>,
getVersionInfo: () => ipcRenderer.invoke('planet:get-version-info'),
getEarthSessionToken: (opts?: { forceRefresh?: boolean }) =>
ipcRenderer.invoke('planet:get-earth-session-token', opts) as Promise<string | null>,
})
ipcRenderer.on('planet:visibility', (_event, detail) => {
+17
View File
@@ -0,0 +1,17 @@
import { contextBridge, ipcRenderer } from 'electron'
import type { RecordingCursorPayload } from '../main/recording-core'
contextBridge.exposeInMainWorld('planetRecordingCursor', {
onUpdate: (callback: (payload: RecordingCursorPayload) => void) => {
const listener = (_event: Electron.IpcRendererEvent, payload: unknown) => {
if (payload && typeof payload === 'object') {
callback(payload as RecordingCursorPayload)
}
}
ipcRenderer.on('planet:recording-cursor-update', listener)
return () => {
ipcRenderer.removeListener('planet:recording-cursor-update', listener)
}
},
})
+18
View File
@@ -0,0 +1,18 @@
import { contextBridge, ipcRenderer } from 'electron'
contextBridge.exposeInMainWorld('planetRecordingIndicator', {
onTick: (callback: (formattedElapsed: string) => void) => {
const listener = (_event: Electron.IpcRendererEvent, formatted: unknown) => {
if (typeof formatted === 'string') {
callback(formatted)
}
}
ipcRenderer.on('planet:recording-indicator-tick', listener)
return () => {
ipcRenderer.removeListener('planet:recording-indicator-tick', listener)
}
},
requestStop: () => {
ipcRenderer.send('planet:recording-indicator-stop')
},
})
+324
View File
@@ -0,0 +1,324 @@
import { ipcRenderer } from 'electron'
import {
pickSupportedRecordingMimeTypes,
type RecordingCursorPayload,
type RecordingCursorShape,
type RecordingStatusSnapshot,
} from '../main/recording-core'
interface ActiveCaptureSession {
stream: MediaStream
recorder: MediaRecorder
mimeType: string
includeAudio: boolean
hideCursor: boolean
pendingChunkWrites: Set<Promise<void>>
stoppedByRenderer: boolean
}
const HIDE_CURSOR_STYLE_ID = 'planet-recording-hide-cursor-style'
const HIDE_CURSOR_CLASS = 'planet-recording-hide-cursor'
function chooseSupportedMimeType(includeAudio: boolean): string {
if (typeof MediaRecorder === 'undefined' || typeof MediaRecorder.isTypeSupported !== 'function') {
return ''
}
for (const candidate of pickSupportedRecordingMimeTypes(includeAudio)) {
if (MediaRecorder.isTypeSupported(candidate)) {
return candidate
}
}
return ''
}
function resolveCursorShape(target: EventTarget | null, buttons: number): RecordingCursorShape {
if (!(target instanceof Element)) return 'default'
if ((buttons & 1) !== 0 && target.tagName === 'CANVAS') {
return 'grabbing'
}
if (
target.closest(
'input:not([type="checkbox"]):not([type="radio"]):not([type="range"]), textarea, [contenteditable="true"]',
)
) {
return 'text'
}
if (
target.closest(
'a, button, summary, select, label, [role="button"], [tabindex], .hud-panel__action, .news-region-card__header',
)
) {
return 'pointer'
}
return 'default'
}
export function initDesktopScreenRecorder(): void {
let activeSession: ActiveCaptureSession | null = null
let stoppingPromise: Promise<void> | null = null
let cursorMaskActive = false
let pendingCursorPayload: RecordingCursorPayload | null = null
let cursorRafId: number | null = null
const sendCursorPayload = (payload: RecordingCursorPayload) => {
ipcRenderer.send('planet:recording-cursor-move', payload)
}
const flushCursorPayload = () => {
cursorRafId = null
if (!cursorMaskActive || !pendingCursorPayload) return
const next = pendingCursorPayload
pendingCursorPayload = null
sendCursorPayload(next)
}
const scheduleCursorPayload = (payload: RecordingCursorPayload) => {
if (!cursorMaskActive) return
pendingCursorPayload = payload
if (cursorRafId === null) {
cursorRafId = window.requestAnimationFrame(flushCursorPayload)
}
}
const onPointerMove = (event: PointerEvent) => {
scheduleCursorPayload({
visible: true,
x: event.clientX,
y: event.clientY,
shape: resolveCursorShape(event.target, event.buttons),
})
}
const onPointerButton = (event: PointerEvent) => {
if (!cursorMaskActive) return
sendCursorPayload({
visible: true,
x: event.clientX,
y: event.clientY,
shape: resolveCursorShape(event.target, event.buttons),
})
}
const onPointerHide = () => {
if (cursorRafId !== null) {
window.cancelAnimationFrame(cursorRafId)
cursorRafId = null
}
pendingCursorPayload = null
sendCursorPayload({ visible: false, x: 0, y: 0, shape: 'default' })
}
const setCursorMaskEnabled = (enabled: boolean) => {
const root = document.documentElement
if (!root) return
if (enabled === cursorMaskActive) return
cursorMaskActive = enabled
if (enabled) {
if (!document.getElementById(HIDE_CURSOR_STYLE_ID)) {
const styleEl = document.createElement('style')
styleEl.id = HIDE_CURSOR_STYLE_ID
styleEl.textContent = `html.${HIDE_CURSOR_CLASS}, html.${HIDE_CURSOR_CLASS} * { cursor: none !important; }`
;(document.head || root).appendChild(styleEl)
}
root.classList.add(HIDE_CURSOR_CLASS)
root.addEventListener('pointermove', onPointerMove, { capture: true, passive: true })
root.addEventListener('pointerdown', onPointerButton, { capture: true, passive: true })
root.addEventListener('pointerup', onPointerButton, { capture: true, passive: true })
root.addEventListener('pointerleave', onPointerHide, { capture: true, passive: true })
window.addEventListener('blur', onPointerHide)
} else {
root.classList.remove(HIDE_CURSOR_CLASS)
root.removeEventListener('pointermove', onPointerMove, { capture: true })
root.removeEventListener('pointerdown', onPointerButton, { capture: true })
root.removeEventListener('pointerup', onPointerButton, { capture: true })
root.removeEventListener('pointerleave', onPointerHide, { capture: true })
window.removeEventListener('blur', onPointerHide)
onPointerHide()
}
}
window.addEventListener('beforeunload', () => {
setCursorMaskEnabled(false)
})
const cleanupStreamTracks = (stream: MediaStream | null) => {
if (!stream) return
for (const track of stream.getTracks()) {
try {
track.stop()
} catch {
// Ignore already-ended track stop errors.
}
}
}
const finalizeActiveSession = async (reason: string): Promise<void> => {
if (stoppingPromise) return stoppingPromise
const session = activeSession
if (!session) return
stoppingPromise = (async () => {
try {
if (session.recorder.state !== 'inactive') {
await new Promise<void>((resolve) => {
const timeout = setTimeout(resolve, 2500)
session.recorder.addEventListener(
'stop',
() => {
clearTimeout(timeout)
resolve()
},
{ once: true },
)
try {
session.recorder.stop()
} catch {
clearTimeout(timeout)
resolve()
}
})
}
if (session.pendingChunkWrites.size > 0) {
await Promise.allSettled([...session.pendingChunkWrites])
}
await ipcRenderer.invoke('planet:recording-finish', { reason })
} finally {
setCursorMaskEnabled(false)
cleanupStreamTracks(session.stream)
if (activeSession === session) {
activeSession = null
}
stoppingPromise = null
}
})()
return stoppingPromise
}
ipcRenderer.on(
'planet:recording-start',
(_event, payload?: { includeAudio?: boolean; hideCursor?: boolean }) => {
void (async () => {
if (activeSession || stoppingPromise) return
const wantAudio = Boolean(payload?.includeAudio)
const hideCursor = Boolean(payload?.hideCursor)
let stream: MediaStream | null = null
let includeAudio = wantAudio
try {
const videoConstraints = { frameRate: { ideal: 60, max: 60 } } as unknown as MediaTrackConstraints
if (wantAudio) {
try {
stream = await navigator.mediaDevices.getDisplayMedia({
video: videoConstraints,
audio: true,
})
if (stream.getAudioTracks().length === 0) {
includeAudio = false
ipcRenderer.send('planet:recording-audio-fallback')
}
} catch {
includeAudio = false
ipcRenderer.send('planet:recording-audio-fallback')
stream = await navigator.mediaDevices.getDisplayMedia({
video: videoConstraints,
audio: false,
})
}
} else {
stream = await navigator.mediaDevices.getDisplayMedia({
video: videoConstraints,
audio: false,
})
}
if (!stream) {
throw new Error('Display capture returned no stream')
}
const mimeType = chooseSupportedMimeType(includeAudio && stream.getAudioTracks().length > 0)
const recorderOptions: MediaRecorderOptions = {
videoBitsPerSecond: 8_000_000,
...(includeAudio ? { audioBitsPerSecond: 128_000 } : {}),
...(mimeType ? { mimeType } : {}),
}
await ipcRenderer.invoke('planet:recording-open-file', {
mimeType,
includeAudio,
hideCursor,
})
setCursorMaskEnabled(hideCursor)
const recorder = new MediaRecorder(stream, recorderOptions)
const pendingChunkWrites = new Set<Promise<void>>()
const session: ActiveCaptureSession = {
stream,
recorder,
mimeType: recorder.mimeType || mimeType,
includeAudio,
hideCursor,
pendingChunkWrites,
stoppedByRenderer: false,
}
activeSession = session
recorder.addEventListener('dataavailable', (event: BlobEvent) => {
if (!event.data || event.data.size === 0) return
const task = event.data
.arrayBuffer()
.then((buffer) => {
ipcRenderer.send('planet:recording-chunk', new Uint8Array(buffer))
})
.catch(() => {})
.finally(() => {
pendingChunkWrites.delete(task)
})
pendingChunkWrites.add(task)
})
const [videoTrack] = stream.getVideoTracks()
if (videoTrack) {
videoTrack.addEventListener(
'ended',
() => {
if (activeSession === session && !session.stoppedByRenderer) {
session.stoppedByRenderer = true
void finalizeActiveSession('track-ended')
}
},
{ once: true },
)
}
recorder.start(1000)
} catch (error) {
setCursorMaskEnabled(false)
cleanupStreamTracks(stream)
activeSession = null
await ipcRenderer.invoke('planet:recording-abort', {
error: error instanceof Error ? error.message : String(error),
})
}
})()
},
)
ipcRenderer.on('planet:recording-stop', () => {
if (activeSession) {
activeSession.stoppedByRenderer = true
}
void finalizeActiveSession('requested-stop')
})
}
export async function toggleDesktopRecording(): Promise<RecordingStatusSnapshot> {
return (await ipcRenderer.invoke('planet:recording-toggle')) as RecordingStatusSnapshot
}
export async function openDesktopRecordingsFolder(): Promise<void> {
await ipcRenderer.invoke('planet:recording-open-folder')
}