feat: boot-экран, стабильность Windows и оптимизация Pixi/пульта
- Экран загрузки (boot.html, bootWindow): статусы, ensureRoots и проверка лицензии, редактор после готовности; закрытие через destroy при closable:false. - Упакованное приложение на Windows: disableHardwareAcceleration, sandbox выкл. вне dev, отложенный показ редактора, ensureWindowBecomesVisible, фокус на splash при second-instance. - Vite: вход boot.html; eslint: игнор release/; тесты boot и maxFPS тикера. - Пульт: позиция курсора кисти через ref/DOM без setState на каждый move; черновик эффекта через rAF; Pixi: maxFPS 32, resolution cap, antialias off, debounce ResizeObserver, меньше частиц poisonCloud, contain на хосте. Made-with: Cursor
This commit is contained in:
+79
-4
@@ -9,16 +9,32 @@ import { ZipProjectStore } from './project/zipStore';
|
||||
import { registerDndAssetProtocol } from './protocol/dndAssetProtocol';
|
||||
import { getAppSemanticVersion, getOptionalBuildNumber } from './versionInfo';
|
||||
import { VideoPlaybackStore } from './video/videoPlaybackStore';
|
||||
import {
|
||||
createBootWindow,
|
||||
destroyBootWindow,
|
||||
setBootWindowStatus,
|
||||
waitForBootWindowReady,
|
||||
} from './windows/bootWindow';
|
||||
import {
|
||||
applyDockIconIfNeeded,
|
||||
closeMultiWindow,
|
||||
createEditorWindowDeferred,
|
||||
createWindows,
|
||||
focusEditorWindow,
|
||||
markAppQuitting,
|
||||
openMultiWindow,
|
||||
togglePresentationFullscreen,
|
||||
waitForEditorWindowReady,
|
||||
} from './windows/createWindows';
|
||||
|
||||
/**
|
||||
* На части конфигураций Windows окно Electron с `file://` остаётся чёрным из‑за GPU/композитора.
|
||||
* Отключаем аппаратное ускорение в упакованном приложении; отключить обход: `DND_DISABLE_GPU=0`.
|
||||
*/
|
||||
if (process.platform === 'win32' && app.isPackaged && process.env.DND_DISABLE_GPU !== '0') {
|
||||
app.disableHardwareAcceleration();
|
||||
}
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
app.setAppUserModelId('com.dndplayer.app');
|
||||
}
|
||||
@@ -89,6 +105,68 @@ function emitSessionState(): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Упакованное приложение: экран загрузки → проверки → редактор.
|
||||
* В dev по умолчанию без экрана; тест: `DND_SHOW_BOOT=1`. Отключить везде: `DND_SKIP_BOOT=1`.
|
||||
*/
|
||||
async function runStartupAfterHandlers(licenseService: LicenseService): Promise<void> {
|
||||
const useBootSequence =
|
||||
process.env.DND_SKIP_BOOT !== '1' && (app.isPackaged || process.env.DND_SHOW_BOOT === '1');
|
||||
|
||||
if (!useBootSequence) {
|
||||
createWindows();
|
||||
emitSessionState();
|
||||
emitEffectsState();
|
||||
emitVideoState();
|
||||
return;
|
||||
}
|
||||
|
||||
const splash = createBootWindow();
|
||||
try {
|
||||
await waitForBootWindowReady(splash);
|
||||
} catch (err) {
|
||||
console.error('[boot] splash load failed', err);
|
||||
destroyBootWindow(splash);
|
||||
createWindows();
|
||||
emitSessionState();
|
||||
emitEffectsState();
|
||||
emitVideoState();
|
||||
return;
|
||||
}
|
||||
|
||||
splash.show();
|
||||
setBootWindowStatus(splash, 'Инициализация…');
|
||||
|
||||
try {
|
||||
setBootWindowStatus(splash, 'Подготовка данных…');
|
||||
await projectStore.ensureRoots();
|
||||
} catch (e) {
|
||||
console.error('[boot] ensureRoots', e);
|
||||
}
|
||||
|
||||
setBootWindowStatus(splash, 'Устанавливаем связь…');
|
||||
setBootWindowStatus(splash, 'Проверка лицензии…');
|
||||
try {
|
||||
await licenseService.getStatus();
|
||||
} catch (e) {
|
||||
console.error('[boot] license getStatus', e);
|
||||
}
|
||||
|
||||
setBootWindowStatus(splash, 'Загрузка редактора…');
|
||||
const editor = createEditorWindowDeferred();
|
||||
await waitForEditorWindowReady(editor);
|
||||
setBootWindowStatus(splash, 'Готово');
|
||||
destroyBootWindow(splash);
|
||||
if (!editor.isDestroyed()) {
|
||||
editor.show();
|
||||
editor.focus();
|
||||
}
|
||||
|
||||
emitSessionState();
|
||||
emitEffectsState();
|
||||
emitVideoState();
|
||||
}
|
||||
|
||||
async function main() {
|
||||
await app.whenReady();
|
||||
const licenseService = new LicenseService(app.getPath('userData'));
|
||||
@@ -334,10 +412,7 @@ async function main() {
|
||||
|
||||
installIpcRouter();
|
||||
applyDockIconIfNeeded();
|
||||
createWindows();
|
||||
emitSessionState();
|
||||
emitEffectsState();
|
||||
emitVideoState();
|
||||
await runStartupAfterHandlers(licenseService);
|
||||
|
||||
app.on('activate', () => {
|
||||
focusEditorWindow();
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
function readBootWindow(): string {
|
||||
return fs.readFileSync(path.join(here, 'bootWindow.ts'), 'utf8');
|
||||
}
|
||||
|
||||
void test('bootWindow: экран загрузки без preload, статус из main', () => {
|
||||
const src = readBootWindow();
|
||||
assert.ok(src.includes('createBootWindow'));
|
||||
assert.ok(src.includes('destroyBootWindow'));
|
||||
assert.ok(src.includes('setBootWindowStatus'));
|
||||
assert.ok(src.includes('waitForBootWindowReady'));
|
||||
assert.ok(src.includes('executeJavaScript'));
|
||||
});
|
||||
|
||||
void test('createWindows: отложенный показ редактора для boot', () => {
|
||||
const src = fs.readFileSync(path.join(here, 'createWindows.ts'), 'utf8');
|
||||
assert.ok(src.includes('deferVisibility'));
|
||||
assert.ok(src.includes('createEditorWindowDeferred'));
|
||||
assert.ok(src.includes('waitForEditorWindowReady'));
|
||||
assert.ok(src.includes('getBootSplashWindow'));
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import path from 'node:path';
|
||||
|
||||
import { app, BrowserWindow } from 'electron';
|
||||
|
||||
import { getAppSemanticVersion } from '../versionInfo';
|
||||
|
||||
let bootSplashRef: BrowserWindow | null = null;
|
||||
|
||||
export function getBootSplashWindow(): BrowserWindow | null {
|
||||
return bootSplashRef;
|
||||
}
|
||||
|
||||
function loadBootPage(win: BrowserWindow): void {
|
||||
const dev = process.env.VITE_DEV_SERVER_URL;
|
||||
if (dev) {
|
||||
void win.loadURL(new URL('boot.html', dev).toString());
|
||||
return;
|
||||
}
|
||||
const htmlPath = path.join(app.getAppPath(), 'dist', 'renderer', 'boot.html');
|
||||
void win.loadFile(htmlPath);
|
||||
}
|
||||
|
||||
/** Без preload: только статический экран; статус задаётся из main через executeJavaScript. */
|
||||
function bootWebPreferences(): Electron.WebPreferences {
|
||||
const dev = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
return {
|
||||
contextIsolation: true,
|
||||
sandbox: dev ? true : process.platform !== 'win32',
|
||||
nodeIntegration: false,
|
||||
devTools: dev || process.env.DND_OPEN_DEVTOOLS === '1',
|
||||
webSecurity: dev,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Окно без системного заголовка: логотип, название, строка статуса.
|
||||
* Показывать после `waitForBootWindowReady`.
|
||||
*/
|
||||
export function createBootWindow(): BrowserWindow {
|
||||
const win = new BrowserWindow({
|
||||
width: 440,
|
||||
height: 420,
|
||||
show: false,
|
||||
frame: false,
|
||||
resizable: false,
|
||||
maximizable: false,
|
||||
minimizable: false,
|
||||
closable: false,
|
||||
center: true,
|
||||
transparent: false,
|
||||
backgroundColor: '#09090B',
|
||||
roundedCorners: true,
|
||||
webPreferences: bootWebPreferences(),
|
||||
});
|
||||
|
||||
bootSplashRef = win;
|
||||
win.once('closed', () => {
|
||||
if (bootSplashRef === win) {
|
||||
bootSplashRef = null;
|
||||
}
|
||||
});
|
||||
|
||||
loadBootPage(win);
|
||||
return win;
|
||||
}
|
||||
|
||||
/**
|
||||
* Закрыть splash: при `closable: false` на Windows `close()` из main часто не срабатывает — используем `destroy()`.
|
||||
*/
|
||||
export function destroyBootWindow(win: BrowserWindow): void {
|
||||
if (win.isDestroyed()) return;
|
||||
win.destroy();
|
||||
}
|
||||
|
||||
export function setBootWindowStatus(win: BrowserWindow, text: string): void {
|
||||
if (win.isDestroyed()) return;
|
||||
const escaped = JSON.stringify(text);
|
||||
void win.webContents.executeJavaScript(
|
||||
`(() => { const el = document.getElementById('boot-status'); if (el) el.textContent = ${escaped}; })()`,
|
||||
);
|
||||
}
|
||||
|
||||
export function applyBootWindowBranding(win: BrowserWindow): void {
|
||||
if (win.isDestroyed()) return;
|
||||
const name = app.getName();
|
||||
const version = getAppSemanticVersion();
|
||||
const versionLabel = version.trim().length > 0 ? `v${version.trim()}` : '';
|
||||
void win.webContents.executeJavaScript(
|
||||
`(() => {
|
||||
const t = document.querySelector('[data-boot-title]');
|
||||
if (t) t.textContent = ${JSON.stringify(name)};
|
||||
const v = document.querySelector('[data-boot-version]');
|
||||
if (v) v.textContent = ${JSON.stringify(versionLabel)};
|
||||
})()`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Дождаться загрузки разметки экрана загрузки. */
|
||||
export function waitForBootWindowReady(win: BrowserWindow): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (win.isDestroyed()) {
|
||||
reject(new Error('boot window destroyed'));
|
||||
return;
|
||||
}
|
||||
const onFail = (): void => {
|
||||
reject(new Error('boot window failed to load'));
|
||||
};
|
||||
win.webContents.once('did-fail-load', onFail);
|
||||
win.webContents.once('did-finish-load', () => {
|
||||
win.webContents.removeListener('did-fail-load', onFail);
|
||||
applyBootWindowBranding(win);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -33,3 +33,15 @@ void test('createWindows: пульт поверх экрана просмотр
|
||||
assert.ok(src.includes('parent: presentation'));
|
||||
assert.ok(src.includes("createWindow('control'"));
|
||||
});
|
||||
|
||||
void test('createWindows: production — loadFile для HTML (не только file://)', () => {
|
||||
const src = readCreateWindows();
|
||||
assert.ok(src.includes('loadFile'));
|
||||
assert.ok(src.includes('loadWindowPage'));
|
||||
});
|
||||
|
||||
void test('createWindows: показ окна — не только ready-to-show (холодный старт Windows)', () => {
|
||||
const src = readCreateWindows();
|
||||
assert.ok(src.includes('ensureWindowBecomesVisible'));
|
||||
assert.ok(src.includes('did-finish-load'));
|
||||
});
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
import { app, BrowserWindow, nativeImage, screen } from 'electron';
|
||||
|
||||
import { getBootSplashWindow } from './bootWindow';
|
||||
|
||||
type WindowKind = 'editor' | 'presentation' | 'control';
|
||||
|
||||
const windows = new Map<WindowKind, BrowserWindow>();
|
||||
@@ -24,15 +25,29 @@ function isDev() {
|
||||
return process.env.NODE_ENV === 'development' || process.env.VITE_DEV_SERVER_URL !== undefined;
|
||||
}
|
||||
|
||||
function getRendererUrl(kind: WindowKind): string {
|
||||
/** Вне dev-сервера на Windows с `loadFile` + preload иногда ломается sandbox; оставляем изоляцию через preload/contextBridge. */
|
||||
function shouldUseRendererSandbox(): boolean {
|
||||
if (process.env.VITE_DEV_SERVER_URL) return true;
|
||||
return process.platform !== 'win32';
|
||||
}
|
||||
|
||||
function getRendererHtmlPath(kind: WindowKind): string {
|
||||
return path.join(app.getAppPath(), 'dist', 'renderer', `${kind}.html`);
|
||||
}
|
||||
|
||||
/**
|
||||
* В production `loadURL(file://…)` на Windows с asar иногда даёт чёрный экран;
|
||||
* `loadFile` корректно открывает HTML из asar и на Windows, и на macOS.
|
||||
*/
|
||||
function loadWindowPage(win: BrowserWindow, kind: WindowKind): void {
|
||||
const dev = process.env.VITE_DEV_SERVER_URL;
|
||||
if (dev) {
|
||||
const page =
|
||||
kind === 'editor' ? 'editor.html' : kind === 'presentation' ? 'presentation.html' : 'control.html';
|
||||
return new URL(page, dev).toString();
|
||||
void win.loadURL(new URL(page, dev).toString());
|
||||
return;
|
||||
}
|
||||
const filePath = path.join(app.getAppPath(), 'dist', 'renderer', `${kind}.html`);
|
||||
return pathToFileURL(filePath).toString();
|
||||
void win.loadFile(getRendererHtmlPath(kind));
|
||||
}
|
||||
|
||||
function getPreloadPath(): string {
|
||||
@@ -121,9 +136,35 @@ export function applyDockIconIfNeeded(): void {
|
||||
type CreateWindowOpts = {
|
||||
/** Дочернее окно (например пульт) держится над родителем (экран просмотра). */
|
||||
parent?: BrowserWindow;
|
||||
/** Только редактор: не показывать окно до `show()` (экран загрузки). */
|
||||
deferVisibility?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Только `ready-to-show` на части систем (первый холодный старт Windows) не приходит вовремя —
|
||||
* окно остаётся с `show: false` и кажется «зависшим». Дублируем показ по `did-finish-load` и таймауту.
|
||||
*/
|
||||
function ensureWindowBecomesVisible(win: BrowserWindow): void {
|
||||
let shown = false;
|
||||
const showOnce = (): void => {
|
||||
if (shown) return;
|
||||
if (win.isDestroyed()) return;
|
||||
shown = true;
|
||||
win.show();
|
||||
};
|
||||
|
||||
win.once('ready-to-show', showOnce);
|
||||
win.webContents.once('did-finish-load', () => {
|
||||
showOnce();
|
||||
});
|
||||
const safetyTimer = setTimeout(showOnce, 8000);
|
||||
win.once('closed', () => {
|
||||
clearTimeout(safetyTimer);
|
||||
});
|
||||
}
|
||||
|
||||
function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow {
|
||||
const deferEditor = kind === 'editor' && opts?.deferVisibility === true;
|
||||
const icon = resolveWindowIcon();
|
||||
const win = new BrowserWindow({
|
||||
width: kind === 'editor' ? 1280 : kind === 'control' ? 1200 : 1280,
|
||||
@@ -134,11 +175,13 @@ function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow
|
||||
...(opts?.parent ? { parent: opts.parent } : {}),
|
||||
webPreferences: {
|
||||
contextIsolation: true,
|
||||
sandbox: true,
|
||||
sandbox: shouldUseRendererSandbox(),
|
||||
nodeIntegration: false,
|
||||
devTools: isDev(),
|
||||
devTools: isDev() || process.env.DND_OPEN_DEVTOOLS === '1',
|
||||
preload: getPreloadPath(),
|
||||
autoplayPolicy: 'no-user-gesture-required',
|
||||
// file:// + бандл Vite: без этого на Windows часто не грузятся чанки; http:// (dev server) оставляем строгим.
|
||||
webSecurity: Boolean(process.env.VITE_DEV_SERVER_URL),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -148,9 +191,14 @@ function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow
|
||||
win.webContents.on('did-fail-load', (_event, errorCode, errorDescription, validatedURL) => {
|
||||
console.error(`[did-fail-load] ${String(errorCode)} ${errorDescription} ${validatedURL}`);
|
||||
});
|
||||
win.webContents.on('render-process-gone', (_event, details) => {
|
||||
console.error('[render-process-gone]', details.reason, details.exitCode);
|
||||
});
|
||||
|
||||
win.once('ready-to-show', () => win.show());
|
||||
void win.loadURL(getRendererUrl(kind));
|
||||
if (!deferEditor) {
|
||||
ensureWindowBecomesVisible(win);
|
||||
}
|
||||
loadWindowPage(win, kind);
|
||||
if (kind === 'editor') {
|
||||
win.on('close', (e) => {
|
||||
if (appQuitting) return;
|
||||
@@ -169,7 +217,47 @@ export function createWindows() {
|
||||
}
|
||||
}
|
||||
|
||||
/** Редактор создаётся скрытым до окончания экрана загрузки. */
|
||||
export function createEditorWindowDeferred(): BrowserWindow {
|
||||
const existing = windows.get('editor');
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
return createWindow('editor', { deferVisibility: true });
|
||||
}
|
||||
|
||||
/** Дождаться первой отрисовки редактора (готовность к показу без чёрного экрана). */
|
||||
export function waitForEditorWindowReady(win: BrowserWindow): Promise<void> {
|
||||
return new Promise<void>((resolve) => {
|
||||
let settled = false;
|
||||
const timer = setTimeout(() => {
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
resolve(undefined);
|
||||
}
|
||||
}, 35000);
|
||||
const finish = (): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve(undefined);
|
||||
};
|
||||
win.once('ready-to-show', finish);
|
||||
win.webContents.once('did-finish-load', finish);
|
||||
}).then(
|
||||
() =>
|
||||
new Promise<void>((r) => {
|
||||
setTimeout(r, 120);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function focusEditorWindow(): void {
|
||||
const splash = getBootSplashWindow();
|
||||
if (splash && !splash.isDestroyed()) {
|
||||
splash.focus();
|
||||
return;
|
||||
}
|
||||
const win = windows.get('editor');
|
||||
if (win) {
|
||||
if (win.isMinimized()) win.restore();
|
||||
|
||||
Reference in New Issue
Block a user