Compare commits
60 Commits
8f8eef53c9
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| a96e1f8465 | |||
| 80103a00e7 | |||
| b017155eaf | |||
| 5706355c5f | |||
| 428fa09224 | |||
| 1cda87fe13 | |||
| 10de99bb06 | |||
| 0ae3c39333 | |||
| d07dcae626 | |||
| dd0dd646f6 | |||
| 8ec830cdb5 | |||
| 02b3131f19 | |||
| cfa067519d | |||
| 4e5d320c36 | |||
| 411ac634f4 | |||
| ece48fe53d | |||
| 744ead383d | |||
| 9f82a541fc | |||
| 963a1f0790 | |||
| 394b42e845 | |||
| 6204359330 | |||
| 7c858ba633 | |||
| 2c03921d23 | |||
| 285a1a9667 | |||
| 0e14180044 | |||
| cd3ba5fe07 | |||
| 26f8a81631 | |||
| 2dc7015f53 | |||
| 0eadfdce30 | |||
| 7e7827224d | |||
| 8fa8467db7 | |||
| af4c2616f2 | |||
| 3877a6f2a6 | |||
| 1c6f06b278 | |||
| 064592d4d4 | |||
| e923de350d | |||
| 07641be2d2 | |||
| 8bc2e5bd49 | |||
| 2037144a5c | |||
| 1840227be6 | |||
| a15adfc3b1 | |||
| 82baef2b04 | |||
| e4b989c60f | |||
| e165a41180 | |||
| cd1f6dcc7e | |||
| 06ffe9bb29 | |||
| 0ba4b8379e | |||
| d3cdc468b5 | |||
| 875f8cbb3b | |||
| 93dad8a80d | |||
| a583859f62 | |||
| e76386ddb9 | |||
| 7fc952cc39 | |||
| 600b8f8321 | |||
| 30b57d842a | |||
| f462e65581 | |||
| 36776f4c5d | |||
| c9cad4dafd | |||
| d94a11d466 | |||
| a24e87035a |
@@ -1,35 +0,0 @@
|
|||||||
---
|
|
||||||
name: frontend-senior
|
|
||||||
description: Senior frontend engineer
|
|
||||||
model: auto
|
|
||||||
tools: all
|
|
||||||
---
|
|
||||||
|
|
||||||
Ты senior frontend engineer.
|
|
||||||
|
|
||||||
Задача:
|
|
||||||
- реализовать feature или fix
|
|
||||||
- писать production-quality React + TypeScript код
|
|
||||||
|
|
||||||
Правила:
|
|
||||||
|
|
||||||
- сначала изучи nearby components
|
|
||||||
- следуй существующим patterns
|
|
||||||
- не делай лишних изменений
|
|
||||||
- избегай overengineering
|
|
||||||
- используй composition
|
|
||||||
|
|
||||||
UI:
|
|
||||||
|
|
||||||
- учитывай loading / error / empty / disabled
|
|
||||||
- соблюдай accessibility
|
|
||||||
|
|
||||||
Не делай:
|
|
||||||
|
|
||||||
- large refactors без запроса
|
|
||||||
- новые dependencies без причины
|
|
||||||
|
|
||||||
Output:
|
|
||||||
|
|
||||||
- список изменённых файлов
|
|
||||||
- краткое описание изменений
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
---
|
|
||||||
name: reviewer
|
|
||||||
description: Strict code reviewer
|
|
||||||
model: auto
|
|
||||||
tools: all
|
|
||||||
---
|
|
||||||
|
|
||||||
Ты строгий reviewer.
|
|
||||||
|
|
||||||
Цель:
|
|
||||||
- найти проблемы в изменениях
|
|
||||||
|
|
||||||
Проверяй:
|
|
||||||
|
|
||||||
- correctness
|
|
||||||
- regressions
|
|
||||||
- type safety
|
|
||||||
- accessibility
|
|
||||||
- performance
|
|
||||||
- edge cases
|
|
||||||
- missing tests
|
|
||||||
|
|
||||||
Формат:
|
|
||||||
|
|
||||||
- Severity: high / medium / low
|
|
||||||
- Problem
|
|
||||||
- Why
|
|
||||||
- Fix
|
|
||||||
|
|
||||||
Правила:
|
|
||||||
|
|
||||||
- не переписывай код без причины
|
|
||||||
- предлагай minimal fixes
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
---
|
|
||||||
name: unit-tests
|
|
||||||
description: Unit test specialist
|
|
||||||
model: auto
|
|
||||||
tools: all
|
|
||||||
---
|
|
||||||
|
|
||||||
Ты unit-test specialist.
|
|
||||||
|
|
||||||
Задача:
|
|
||||||
|
|
||||||
- добавить/обновить tests
|
|
||||||
- добиться green status
|
|
||||||
|
|
||||||
Подход:
|
|
||||||
|
|
||||||
- test behavior, not implementation
|
|
||||||
- follow existing patterns
|
|
||||||
- избегай flaky tests
|
|
||||||
|
|
||||||
Покрытие:
|
|
||||||
|
|
||||||
- happy path
|
|
||||||
- edge case
|
|
||||||
- error case
|
|
||||||
|
|
||||||
Workflow:
|
|
||||||
|
|
||||||
- сначала run relevant tests:
|
|
||||||
`npm run test -- <file>`
|
|
||||||
- затем при необходимости весь suite
|
|
||||||
|
|
||||||
Output:
|
|
||||||
|
|
||||||
- какие тесты добавлены
|
|
||||||
- что они проверяют
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
{
|
|
||||||
"version": 1,
|
|
||||||
"hooks": {
|
|
||||||
"stop": [
|
|
||||||
{
|
|
||||||
"command": "node .cursor/hooks/final-verify.cjs"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
const fs = require("fs");
|
|
||||||
const path = require("path");
|
|
||||||
const { execSync } = require("child_process");
|
|
||||||
|
|
||||||
const statePath = path.join(process.cwd(), ".cursor", "pipeline-state.json");
|
|
||||||
|
|
||||||
function readState() {
|
|
||||||
if (!fs.existsSync(statePath)) {
|
|
||||||
return {
|
|
||||||
implementation: "pending",
|
|
||||||
review: "pending",
|
|
||||||
tests: "pending"
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return JSON.parse(fs.readFileSync(statePath, "utf8"));
|
|
||||||
}
|
|
||||||
|
|
||||||
function fail(msg) {
|
|
||||||
process.stdout.write(JSON.stringify({ followup_message: msg }));
|
|
||||||
process.exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
const state = readState();
|
|
||||||
|
|
||||||
if (state.implementation !== "done") {
|
|
||||||
fail("Run frontend-senior stage");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (state.review !== "done") {
|
|
||||||
fail("Run reviewer stage");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (state.tests !== "done") {
|
|
||||||
fail("Run unit-tests stage");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
execSync("npm run lint", { stdio: "pipe" });
|
|
||||||
} catch {
|
|
||||||
fail("Lint failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
execSync("npm run typecheck", { stdio: "pipe" });
|
|
||||||
} catch {
|
|
||||||
fail("Typecheck failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
execSync("npm run test", { stdio: "pipe" });
|
|
||||||
} catch {
|
|
||||||
fail("Tests failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
process.exit(0);
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
{
|
|
||||||
"version": 1,
|
|
||||||
"hooks": {
|
|
||||||
"stop": [
|
|
||||||
{
|
|
||||||
"command": "node .cursor/hooks/final-verify.cjs"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"implementation": "done",
|
|
||||||
"review": "done",
|
|
||||||
"tests": "done",
|
|
||||||
"verify": "done"
|
|
||||||
}
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
# PR: UI — выравнивание под макеты (редактор + пульт)
|
|
||||||
|
|
||||||
Связь с **feature-pipeline** (`.cursor/skills/feature-pipeline/SKILL.md`): критерии ниже сгруппированы по стадиям; после merge обновляют `.cursor/pipeline-state.json` по мере прохождения стадий.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Мета PR
|
|
||||||
|
|
||||||
| Поле | Значение |
|
|
||||||
|------|----------|
|
|
||||||
| **Цель** | Визуальная и UX-полировка существующих экранов без новых продуктовых фич из макета |
|
|
||||||
| **Область** | `EditorApp`, `SceneGraph`, `ControlApp`, общие токены/мелкие UI-баги |
|
|
||||||
| **Вне скоупа** | Новые пункты меню, новые типы сцен, новые каналы микшера, если их нет в коде |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stage 1 — Implementation (subagent: `frontend-senior`)
|
|
||||||
|
|
||||||
### Чеклист PR
|
|
||||||
|
|
||||||
- [ ] **P0-A** Карточка узла графа: статусы «Авто / Цикл / Аудио» отражают **реальные** поля сцены (`previewVideoAutostart`, `settings.loopVideo`, наличие `media.audios`), а не статичный текст.
|
|
||||||
- [ ] **P0-B** Пульт: для сцены с видео-превью явно подписано, что **кисть эффектов** недоступна (согласовано с `PresentationView`: эффекты только для image).
|
|
||||||
- [ ] **P1-A** Пульт: порядок секций **Предпросмотр → Варианты ветвления → Музыка сцены → Быстрый микшер** (вертикальный поток как в референсе).
|
|
||||||
- [ ] **P1-B** Сетка «Варианты ветвления» без «дыр»: `repeat(auto-fit, minmax(...))` **или** фиксированные слоты с disabled/placeholder **без новых сценариев** — только визуальная сетка.
|
|
||||||
- [ ] **P2-A** Редактор: меню «Файл» — цвет текста пункта на валидном токене (`--text0` / `--text1`), без несуществующего `--text`.
|
|
||||||
- [ ] **P2-B** Список сцен: убрать пустой статус-ряд у неактивных карточек (без лишнего вертикального зазора).
|
|
||||||
|
|
||||||
### Критерии приёмки (Stage 1)
|
|
||||||
|
|
||||||
1. На графе для сцены **без видео-превью** не отображаются вводящие в заблуждение чипы «Авто/Цикл» видео-превью; при наличии аудио — корректный индикатор аудио.
|
|
||||||
2. Для сцены с **видео-превью** чипы «Авто»/«Цикл» совпадают с `previewVideoAutostart` и `scene.settings.loopVideo`.
|
|
||||||
3. В пульте при `previewAssetType === 'video'` пользователь видит **одну строку-пояснение** (вторичный текст), почему нет панели эффектов.
|
|
||||||
4. Визуальный порядок блоков пульта соответствует чеклисту P1-A; отступы между `Surface` единообразны (`gap` 16).
|
|
||||||
5. Нет регрессий drag-and-drop сцен на граф и переключения веток.
|
|
||||||
|
|
||||||
**Definition of Done (Stage 1):** все пункты чеклиста Stage 1 отмечены; `npm run build` успешен.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stage 2 — Review (subagent: `reviewer`)
|
|
||||||
|
|
||||||
### Чеклист PR
|
|
||||||
|
|
||||||
- [ ] Нет «мёртвых» веток UI и ложных состояний (чипы/подписи соответствуют данным).
|
|
||||||
- [ ] a11y: фокус/клавиатура на интерактивах не сломаны; `aria-*` не ухудшены.
|
|
||||||
- [ ] Нет лишнего diff вне файлов задачи.
|
|
||||||
|
|
||||||
### Критерии приёмки (Stage 2)
|
|
||||||
|
|
||||||
1. Reviewer фиксирует замечания с **Severity**; все **high** устранены или явно отклонены с причиной в PR.
|
|
||||||
2. После правок по review снова выполняется `npm run build`.
|
|
||||||
|
|
||||||
**Definition of Done (Stage 2):** review-замечания закрыты; state `review: done`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stage 3 — Tests (subagent: `unit-tests`)
|
|
||||||
|
|
||||||
### Чеклист PR
|
|
||||||
|
|
||||||
- [ ] Добавлены или обновлены тесты на **чистую логику** (например, хелпер разметки чипов по `Scene`, если вынесен в `app/shared`).
|
|
||||||
- [ ] Либо задокументировано в PR, что изменения только презентационные и покрыты smoke-тестом пайплайна.
|
|
||||||
|
|
||||||
### Критерии приёмки (Stage 3)
|
|
||||||
|
|
||||||
1. `npm run test` завершается с кодом 0.
|
|
||||||
2. Новые тесты не flaky, не зависят от Electron UI.
|
|
||||||
|
|
||||||
**Definition of Done (Stage 3):** `tests: done` в `.cursor/pipeline-state.json`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stage 4 — Verify (локально / hook `final-verify.cjs`)
|
|
||||||
|
|
||||||
Выполнить подряд:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm run lint
|
|
||||||
npm run typecheck
|
|
||||||
npm run test
|
|
||||||
```
|
|
||||||
|
|
||||||
**Если `npm run lint` падает на массовых `Delete ␍` (CRLF/LF) в файлах вне PR** — до отдельного chore-PR с нормализацией строк для этого чеклиста достаточно:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx eslint app/renderer/control/ControlApp.tsx app/renderer/editor/graph/SceneGraph.tsx app/renderer/shared/ui/sceneGraphChips.ts app/renderer/shared/ui/sceneGraphChips.test.ts --max-warnings 0
|
|
||||||
npm run typecheck
|
|
||||||
npm run test
|
|
||||||
npm run build
|
|
||||||
```
|
|
||||||
|
|
||||||
### Критерии приёмки (Stage 4)
|
|
||||||
|
|
||||||
1. `npm run typecheck`, `npm run test`, `npm run build` — **exit 0**.
|
|
||||||
2. Линт: либо полный `npm run lint` — **exit 0**, либо (при известном eol-долге репозитория) scoped-ESLint по файлам PR — **exit 0**, как в блоке выше.
|
|
||||||
3. `node .cursor/hooks/final-verify.cjs` — успешное завершение пайплайна только когда полный `npm run lint` зелёный (хук вызывает полный lint; при падении lint хук пишет `followup_message` в stdout).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Синхронизация с `.cursor/pipeline-state.json`
|
|
||||||
|
|
||||||
После каждой стадии обновлять файл:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"implementation": "done",
|
|
||||||
"review": "done",
|
|
||||||
"tests": "done"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
До начала работы — все `"pending"`.
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
---
|
|
||||||
description: Project-wide workflow and conventions
|
|
||||||
alwaysApply: true
|
|
||||||
---
|
|
||||||
|
|
||||||
# DNDGamePlayer — правила работы над задачами (future-pipeline)
|
|
||||||
|
|
||||||
Эти правила применяются **только** когда запрос пользователя требует **изменений в репозитории** (код/конфиги/тесты). Для чисто текстовых задач (описания, маркетинг, переписка) pipeline не запускаем.
|
|
||||||
|
|
||||||
## future-pipeline (обязательный порядок)
|
|
||||||
|
|
||||||
### 1) Implementation
|
|
||||||
- Прочитать релевантный код (минимум 1 файл), найти реальную причину бага/задачи.
|
|
||||||
- Делать **minimal, review-friendly diff** и следовать текущим паттернам проекта.
|
|
||||||
- Не добавлять зависимости без явной причины.
|
|
||||||
|
|
||||||
### 2) Review
|
|
||||||
- Самопроверка изменений: edge-cases, состояние UI (loading/error/empty/disabled), a11y, регрессии.
|
|
||||||
- Если задача нетривиальная: запустить внутренний “строгий ревью” (под-агент reviewer).
|
|
||||||
|
|
||||||
### 3) Tests
|
|
||||||
- Обновить/добавить тест(ы), если поведение изменилось или был баг.
|
|
||||||
- Для мелких правок допускается “облегчённый режим” без под-агентов, но тесты всё равно должны проходить.
|
|
||||||
|
|
||||||
### 4) Verify (всегда, перед ответом)
|
|
||||||
Обязательно выполнить:
|
|
||||||
- `npm run lint`
|
|
||||||
- `npm run typecheck`
|
|
||||||
- `npm run test`
|
|
||||||
|
|
||||||
Если что-то упало — исправить и повторить до green.
|
|
||||||
|
|
||||||
## Команды проекта (справка)
|
|
||||||
- install: `npm install`
|
|
||||||
- dev: `npm run dev`
|
|
||||||
- build: `npm run build`
|
|
||||||
- lint: `npm run lint`
|
|
||||||
- typecheck: `npm run typecheck`
|
|
||||||
- test: `npm run test`
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
---
|
|
||||||
name: feature-pipeline
|
|
||||||
description: Implementation → Review → Tests → Verify
|
|
||||||
---
|
|
||||||
|
|
||||||
# Workflow
|
|
||||||
|
|
||||||
## Stage 1 — Implementation
|
|
||||||
|
|
||||||
Используй subagent: frontend-senior
|
|
||||||
|
|
||||||
- реализуй задачу
|
|
||||||
- сделай minimal diff
|
|
||||||
|
|
||||||
Обнови state:
|
|
||||||
|
|
||||||
{
|
|
||||||
"implementation": "done"
|
|
||||||
}
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stage 2 — Review
|
|
||||||
|
|
||||||
Используй subagent: reviewer
|
|
||||||
|
|
||||||
- проверь изменения
|
|
||||||
- найди проблемы
|
|
||||||
- исправь минимально
|
|
||||||
|
|
||||||
Обнови state:
|
|
||||||
|
|
||||||
{
|
|
||||||
"implementation": "done",
|
|
||||||
"review": "done"
|
|
||||||
}
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stage 3 — Tests
|
|
||||||
|
|
||||||
Используй subagent: unit-tests
|
|
||||||
|
|
||||||
- добавь/обнови tests
|
|
||||||
- добейся green status
|
|
||||||
|
|
||||||
Обнови state:
|
|
||||||
|
|
||||||
{
|
|
||||||
"implementation": "done",
|
|
||||||
"review": "done",
|
|
||||||
"tests": "done"
|
|
||||||
}
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stage 4 — Verify
|
|
||||||
|
|
||||||
Выполни:
|
|
||||||
|
|
||||||
- `npm run lint`
|
|
||||||
- `npm run typecheck`
|
|
||||||
- `npm run test`
|
|
||||||
|
|
||||||
Если ошибка:
|
|
||||||
- исправь
|
|
||||||
- повтори
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Final Output
|
|
||||||
|
|
||||||
- implementation summary
|
|
||||||
- review summary
|
|
||||||
- test summary
|
|
||||||
- verification status
|
|
||||||
|
|
||||||
## PR-чеклисты (приёмка по задаче)
|
|
||||||
|
|
||||||
Готовые чеклисты с критериями по стадиям лежат в `.cursor/pr-checklists/`. Для UI-выравнивания под макеты: `ui-mock-alignment.md`.
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
*.sh text eol=lf
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
|
# Cursor: канонический `.cursor/` в репозитории cursorAi; локально — junction на ../cursorAi/.cursor
|
||||||
|
.cursor/
|
||||||
|
|
||||||
release/
|
release/
|
||||||
build/
|
build/
|
||||||
mcps/
|
mcps/
|
||||||
|
|||||||
+54
-12
@@ -1,12 +1,21 @@
|
|||||||
import { app, BrowserWindow, dialog, Menu, protocol } from 'electron';
|
import { app, BrowserWindow, dialog, Menu, protocol } from 'electron';
|
||||||
|
|
||||||
import { ipcChannels, type SessionState } from '../shared/ipc/contracts';
|
import { ipcChannels, type SessionState } from '../shared/ipc/contracts';
|
||||||
|
import {
|
||||||
|
PROJECT_ZIP_OPEN_DIALOG_FILTER,
|
||||||
|
PROJECT_ZIP_SAVE_DIALOG_FILTER,
|
||||||
|
isProjectZipFileName,
|
||||||
|
normalizeSaveProjectZipPath,
|
||||||
|
projectZipFileNameFromBase,
|
||||||
|
stripProjectZipExtension,
|
||||||
|
} from '../shared/project/projectZipExtension';
|
||||||
|
|
||||||
import { EffectsStore } from './effects/effectsStore';
|
import { EffectsStore } from './effects/effectsStore';
|
||||||
import { installIpcRouter, registerHandler, setLicenseAssert } from './ipc/router';
|
import { installIpcRouter, registerHandler, setLicenseAssert } from './ipc/router';
|
||||||
import { LicenseService } from './license/licenseService';
|
import { LicenseService } from './license/licenseService';
|
||||||
import { ZipProjectStore } from './project/zipStore';
|
import { ZipProjectStore } from './project/zipStore';
|
||||||
import { registerDndAssetProtocol } from './protocol/dndAssetProtocol';
|
import { registerDndAssetProtocol } from './protocol/dndAssetProtocol';
|
||||||
|
import { installAutoUpdater } from './update/installAutoUpdater';
|
||||||
import { getAppSemanticVersion, getOptionalBuildNumber } from './versionInfo';
|
import { getAppSemanticVersion, getOptionalBuildNumber } from './versionInfo';
|
||||||
import { VideoPlaybackStore } from './video/videoPlaybackStore';
|
import { VideoPlaybackStore } from './video/videoPlaybackStore';
|
||||||
import {
|
import {
|
||||||
@@ -21,6 +30,7 @@ import {
|
|||||||
createEditorWindowDeferred,
|
createEditorWindowDeferred,
|
||||||
createWindows,
|
createWindows,
|
||||||
focusEditorWindow,
|
focusEditorWindow,
|
||||||
|
isMultiWindowOpen,
|
||||||
markAppQuitting,
|
markAppQuitting,
|
||||||
openMultiWindow,
|
openMultiWindow,
|
||||||
togglePresentationFullscreen,
|
togglePresentationFullscreen,
|
||||||
@@ -50,7 +60,7 @@ if (process.platform === 'win32' && app.isPackaged && process.env.DND_DISABLE_GP
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (process.platform === 'win32') {
|
if (process.platform === 'win32') {
|
||||||
app.setAppUserModelId('com.dndplayer.app');
|
app.setAppUserModelId('com.ttrpgplayer.app');
|
||||||
}
|
}
|
||||||
// Не вызывать app.setName() с другим именем: на Windows/macOS меняется каталог userData,
|
// Не вызывать app.setName() с другим именем: на Windows/macOS меняется каталог userData,
|
||||||
// и проекты в …/userData/projects «пропадают» из списка (остаются в старой папке).
|
// и проекты в …/userData/projects «пропадают» из списка (остаются в старой папке).
|
||||||
@@ -77,6 +87,35 @@ if (!gotTheLock) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const projectStore = new ZipProjectStore();
|
const projectStore = new ZipProjectStore();
|
||||||
|
|
||||||
|
/** Без меню Electron не вешает горячие клавиши DevTools (Ctrl+Shift+I / F12). */
|
||||||
|
function wantsDevToolsMenu(): boolean {
|
||||||
|
return (
|
||||||
|
process.env.NODE_ENV === 'development' ||
|
||||||
|
Boolean(process.env.VITE_DEV_SERVER_URL) ||
|
||||||
|
process.env.DND_OPEN_DEVTOOLS === '1'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function installAppMenuForSession(): void {
|
||||||
|
if (!wantsDevToolsMenu()) {
|
||||||
|
Menu.setApplicationMenu(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const template: Electron.MenuItemConstructorOptions[] = [];
|
||||||
|
if (process.platform === 'darwin') {
|
||||||
|
template.push({
|
||||||
|
label: app.name,
|
||||||
|
submenu: [{ role: 'about' }, { type: 'separator' }, { role: 'quit' }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
template.push({
|
||||||
|
label: 'Вид',
|
||||||
|
submenu: [{ role: 'reload' }, { role: 'forceReload' }, { type: 'separator' }, { role: 'toggleDevTools' }],
|
||||||
|
});
|
||||||
|
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
|
||||||
|
}
|
||||||
|
|
||||||
const effectsStore = new EffectsStore();
|
const effectsStore = new EffectsStore();
|
||||||
const videoStore = new VideoPlaybackStore();
|
const videoStore = new VideoPlaybackStore();
|
||||||
|
|
||||||
@@ -211,7 +250,7 @@ async function main() {
|
|||||||
setLicenseAssert(() => {
|
setLicenseAssert(() => {
|
||||||
licenseService.assertForIpc();
|
licenseService.assertForIpc();
|
||||||
});
|
});
|
||||||
Menu.setApplicationMenu(null);
|
installAppMenuForSession();
|
||||||
registerDndAssetProtocol(projectStore);
|
registerDndAssetProtocol(projectStore);
|
||||||
registerHandler(ipcChannels.app.quit, () => {
|
registerHandler(ipcChannels.app.quit, () => {
|
||||||
markAppQuitting();
|
markAppQuitting();
|
||||||
@@ -221,6 +260,7 @@ async function main() {
|
|||||||
registerHandler(ipcChannels.app.getVersion, () => ({
|
registerHandler(ipcChannels.app.getVersion, () => ({
|
||||||
version: getAppSemanticVersion(),
|
version: getAppSemanticVersion(),
|
||||||
buildNumber: getOptionalBuildNumber(),
|
buildNumber: getOptionalBuildNumber(),
|
||||||
|
packaged: app.isPackaged,
|
||||||
}));
|
}));
|
||||||
registerHandler(ipcChannels.license.getStatus, () => licenseService.getStatus());
|
registerHandler(ipcChannels.license.getStatus, () => licenseService.getStatus());
|
||||||
registerHandler(ipcChannels.license.setToken, async ({ token }) => licenseService.setToken(token));
|
registerHandler(ipcChannels.license.setToken, async ({ token }) => licenseService.setToken(token));
|
||||||
@@ -238,6 +278,9 @@ async function main() {
|
|||||||
const isFullScreen = togglePresentationFullscreen();
|
const isFullScreen = togglePresentationFullscreen();
|
||||||
return { ok: true, isFullScreen };
|
return { ok: true, isFullScreen };
|
||||||
});
|
});
|
||||||
|
registerHandler(ipcChannels.windows.getMultiWindowState, () => {
|
||||||
|
return { open: isMultiWindowOpen() };
|
||||||
|
});
|
||||||
|
|
||||||
registerHandler(ipcChannels.project.list, async () => {
|
registerHandler(ipcChannels.project.list, async () => {
|
||||||
const projects = await projectStore.listProjects();
|
const projects = await projectStore.listProjects();
|
||||||
@@ -412,7 +455,7 @@ async function main() {
|
|||||||
registerHandler(ipcChannels.project.importZip, async () => {
|
registerHandler(ipcChannels.project.importZip, async () => {
|
||||||
const { canceled, filePaths } = await dialog.showOpenDialog({
|
const { canceled, filePaths } = await dialog.showOpenDialog({
|
||||||
properties: ['openFile'],
|
properties: ['openFile'],
|
||||||
filters: [{ name: 'Проект DND (*.dnd.zip)', extensions: ['dnd.zip'] }],
|
filters: [PROJECT_ZIP_OPEN_DIALOG_FILTER],
|
||||||
});
|
});
|
||||||
if (canceled || !filePaths[0]) {
|
if (canceled || !filePaths[0]) {
|
||||||
return { canceled: true as const };
|
return { canceled: true as const };
|
||||||
@@ -438,21 +481,19 @@ async function main() {
|
|||||||
if (!entry) {
|
if (!entry) {
|
||||||
throw new Error('Проект не найден');
|
throw new Error('Проект не найден');
|
||||||
}
|
}
|
||||||
const defaultName = entry.fileName.toLowerCase().endsWith('.dnd.zip')
|
const defaultName = isProjectZipFileName(entry.fileName)
|
||||||
? entry.fileName
|
? entry.fileName.toLowerCase().endsWith('.ttrpg.zip')
|
||||||
: `${entry.fileName}.dnd.zip`;
|
? entry.fileName
|
||||||
|
: projectZipFileNameFromBase(stripProjectZipExtension(entry.fileName))
|
||||||
|
: projectZipFileNameFromBase(stripProjectZipExtension(entry.fileName));
|
||||||
const { canceled, filePath } = await dialog.showSaveDialog({
|
const { canceled, filePath } = await dialog.showSaveDialog({
|
||||||
defaultPath: defaultName,
|
defaultPath: defaultName,
|
||||||
filters: [{ name: 'Проект DND (*.dnd.zip)', extensions: ['dnd.zip'] }],
|
filters: [PROJECT_ZIP_SAVE_DIALOG_FILTER],
|
||||||
});
|
});
|
||||||
if (canceled || !filePath) {
|
if (canceled || !filePath) {
|
||||||
return { canceled: true as const };
|
return { canceled: true as const };
|
||||||
}
|
}
|
||||||
let dest = filePath;
|
const dest = normalizeSaveProjectZipPath(filePath);
|
||||||
const lower = dest.toLowerCase();
|
|
||||||
if (!lower.endsWith('.dnd.zip')) {
|
|
||||||
dest = lower.endsWith('.zip') ? dest.replace(/\.zip$/iu, '.dnd.zip') : `${dest}.dnd.zip`;
|
|
||||||
}
|
|
||||||
emitZipProgress({ kind: 'export', stage: 'copy', percent: 0, detail: 'Экспорт…' });
|
emitZipProgress({ kind: 'export', stage: 'copy', percent: 0, detail: 'Экспорт…' });
|
||||||
await projectStore.exportProjectZipToPath(projectId, dest, (p) => {
|
await projectStore.exportProjectZipToPath(projectId, dest, (p) => {
|
||||||
emitZipProgress({
|
emitZipProgress({
|
||||||
@@ -492,6 +533,7 @@ async function main() {
|
|||||||
return { ok: true };
|
return { ok: true };
|
||||||
});
|
});
|
||||||
|
|
||||||
|
installAutoUpdater(licenseService, registerHandler);
|
||||||
installIpcRouter();
|
installIpcRouter();
|
||||||
applyDockIconIfNeeded();
|
applyDockIconIfNeeded();
|
||||||
await runStartupAfterHandlers(licenseService);
|
await runStartupAfterHandlers(licenseService);
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ function channelRequiresLicense(channel: string): boolean {
|
|||||||
if (channel.startsWith('app.')) return false;
|
if (channel.startsWith('app.')) return false;
|
||||||
if (channel === ipcChannels.windows.closeMultiWindow) return false;
|
if (channel === ipcChannels.windows.closeMultiWindow) return false;
|
||||||
if (channel === ipcChannels.windows.togglePresentationFullscreen) return false;
|
if (channel === ipcChannels.windows.togglePresentationFullscreen) return false;
|
||||||
|
// Список файлов в %userData%/projects — только чтение; без лицензии список не должен «пропадать».
|
||||||
|
if (channel === ipcChannels.project.list) return false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,6 +36,8 @@ export function registerHandler<K extends keyof IpcInvokeMap>(channel: K, handle
|
|||||||
handlers.set(channelStr, inner);
|
handlers.set(channelStr, inner);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type IpcRegisterHandler = typeof registerHandler;
|
||||||
|
|
||||||
export function installIpcRouter(): void {
|
export function installIpcRouter(): void {
|
||||||
for (const [channel, handler] of handlers.entries()) {
|
for (const [channel, handler] of handlers.entries()) {
|
||||||
ipcMain.handle(channel, async (_event, payload: unknown) => handler(payload));
|
ipcMain.handle(channel, async (_event, payload: unknown) => handler(payload));
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import crypto from 'node:crypto';
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
|
|
||||||
import { BrowserWindow, safeStorage } from 'electron';
|
import { BrowserWindow, safeStorage } from 'electron';
|
||||||
@@ -6,17 +7,41 @@ import { ipcChannels } from '../../shared/ipc/contracts';
|
|||||||
import { EULA_CURRENT_VERSION } from '../../shared/license/eulaVersion';
|
import { EULA_CURRENT_VERSION } from '../../shared/license/eulaVersion';
|
||||||
import type { LicenseSnapshot } from '../../shared/license/licenseSnapshot';
|
import type { LicenseSnapshot } from '../../shared/license/licenseSnapshot';
|
||||||
import type { LicensePayloadV1 } from '../../shared/license/payloadV1';
|
import type { LicensePayloadV1 } from '../../shared/license/payloadV1';
|
||||||
import { isDndProductKey } from '../../shared/license/productKey';
|
import { isProductKey } from '../../shared/license/productKey';
|
||||||
import { normalizeLicenseTokenInput } from '../../shared/license/tokenFormat';
|
import { normalizeLicenseTokenInput } from '../../shared/license/tokenFormat';
|
||||||
|
|
||||||
import { getOrCreateDeviceId } from './deviceId';
|
import { getOrCreateDeviceId } from './deviceId';
|
||||||
import { licenseEncryptedPath, preferencesPath } from './paths';
|
import { licenseEncryptedPath, licenseFallbackSealedPath, preferencesPath } from './paths';
|
||||||
import { verifyLicenseToken } from './verifyLicenseToken';
|
import { verifyLicenseToken } from './verifyLicenseToken';
|
||||||
|
|
||||||
type Preferences = {
|
type Preferences = {
|
||||||
eulaAcceptedVersion?: number;
|
eulaAcceptedVersion?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type LicenseChangeListener = () => void;
|
||||||
|
|
||||||
|
const FALLBACK_MAGIC = Buffer.from('DNDLF1', 'ascii');
|
||||||
|
|
||||||
|
const licenseChangeListeners = new Set<LicenseChangeListener>();
|
||||||
|
|
||||||
|
/** Слушатели вызываются после смены состояния лицензии (сохранённый токен, EULA, отзыв). */
|
||||||
|
export function addLicenseChangeListener(fn: LicenseChangeListener): () => void {
|
||||||
|
licenseChangeListeners.add(fn);
|
||||||
|
return () => {
|
||||||
|
licenseChangeListeners.delete(fn);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function notifyLicenseChangeListeners(): void {
|
||||||
|
for (const fn of licenseChangeListeners) {
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[license] change listener failed', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function readPreferences(userData: string): Preferences {
|
function readPreferences(userData: string): Preferences {
|
||||||
try {
|
try {
|
||||||
const raw = fs.readFileSync(preferencesPath(userData), 'utf8');
|
const raw = fs.readFileSync(preferencesPath(userData), 'utf8');
|
||||||
@@ -35,6 +60,7 @@ function emitLicenseStatusChanged(): void {
|
|||||||
for (const win of BrowserWindow.getAllWindows()) {
|
for (const win of BrowserWindow.getAllWindows()) {
|
||||||
win.webContents.send(ipcChannels.license.statusChanged, {});
|
win.webContents.send(ipcChannels.license.statusChanged, {});
|
||||||
}
|
}
|
||||||
|
notifyLicenseChangeListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
export class LicenseService {
|
export class LicenseService {
|
||||||
@@ -52,23 +78,93 @@ export class LicenseService {
|
|||||||
return process.env.DND_SKIP_LICENSE === '1' || process.env.DND_SKIP_LICENSE === 'true';
|
return process.env.DND_SKIP_LICENSE === '1' || process.env.DND_SKIP_LICENSE === 'true';
|
||||||
}
|
}
|
||||||
|
|
||||||
private readSealedToken(): string | null {
|
/** Только для окружений без OS keychain (WSL и т.п.); слабее safeStorage — см. licensing-spec. */
|
||||||
const p = licenseEncryptedPath(this.userData);
|
private isInsecureFileStorageAllowed(): boolean {
|
||||||
if (!fs.existsSync(p)) return null;
|
const v = process.env.DND_LICENSE_INSECURE_FILE_STORAGE?.trim().toLowerCase();
|
||||||
if (!safeStorage.isEncryptionAvailable()) {
|
return v === '1' || v === 'true' || v === 'yes';
|
||||||
throw new Error('safeStorage недоступен: нельзя расшифровать лицензию на этой системе');
|
}
|
||||||
}
|
|
||||||
|
private deriveFallbackKey(): Buffer {
|
||||||
|
return crypto
|
||||||
|
.createHash('sha256')
|
||||||
|
.update('TTRPGPlayer.license.fallback.v1\0', 'utf8')
|
||||||
|
.update(this.deviceId, 'utf8')
|
||||||
|
.digest();
|
||||||
|
}
|
||||||
|
|
||||||
|
private readFallbackSealedToken(): string {
|
||||||
|
const p = licenseFallbackSealedPath(this.userData);
|
||||||
const buf = fs.readFileSync(p);
|
const buf = fs.readFileSync(p);
|
||||||
return safeStorage.decryptString(buf);
|
if (buf.length < FALLBACK_MAGIC.length + 12 + 16 + 1) {
|
||||||
|
throw new Error('license.fallback: файл повреждён или слишком короткий');
|
||||||
|
}
|
||||||
|
if (!buf.subarray(0, FALLBACK_MAGIC.length).equals(FALLBACK_MAGIC)) {
|
||||||
|
throw new Error('license.fallback: неверный формат');
|
||||||
|
}
|
||||||
|
const iv = buf.subarray(FALLBACK_MAGIC.length, FALLBACK_MAGIC.length + 12);
|
||||||
|
const tag = buf.subarray(FALLBACK_MAGIC.length + 12, FALLBACK_MAGIC.length + 12 + 16);
|
||||||
|
const data = buf.subarray(FALLBACK_MAGIC.length + 12 + 16);
|
||||||
|
const key = this.deriveFallbackKey();
|
||||||
|
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
||||||
|
decipher.setAuthTag(tag);
|
||||||
|
return Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
private writeFallbackSealedToken(token: string): void {
|
||||||
|
const key = this.deriveFallbackKey();
|
||||||
|
const iv = crypto.randomBytes(12);
|
||||||
|
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
||||||
|
const enc = Buffer.concat([cipher.update(token, 'utf8'), cipher.final()]);
|
||||||
|
const tag = cipher.getAuthTag();
|
||||||
|
const payload = Buffer.concat([FALLBACK_MAGIC, iv, tag, enc]);
|
||||||
|
fs.writeFileSync(licenseFallbackSealedPath(this.userData), payload, { mode: 0o600 });
|
||||||
|
}
|
||||||
|
|
||||||
|
private readSealedToken(): string | null {
|
||||||
|
const sealedPath = licenseEncryptedPath(this.userData);
|
||||||
|
const fallbackPath = licenseFallbackSealedPath(this.userData);
|
||||||
|
|
||||||
|
if (fs.existsSync(sealedPath)) {
|
||||||
|
if (!safeStorage.isEncryptionAvailable()) {
|
||||||
|
throw new Error(
|
||||||
|
'safeStorage недоступен: есть license.sealed, но расшифровать нельзя (часто перенос профиля или WSL без keyring). Удалите файл лицензии в настройках приложения или используйте DND_LICENSE_INSECURE_FILE_STORAGE=1 и активируйте заново.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const buf = fs.readFileSync(sealedPath);
|
||||||
|
return safeStorage.decryptString(buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fs.existsSync(fallbackPath)) {
|
||||||
|
return this.readFallbackSealedToken();
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private writeSealedToken(token: string): void {
|
private writeSealedToken(token: string): void {
|
||||||
if (!safeStorage.isEncryptionAvailable()) {
|
|
||||||
throw new Error('safeStorage недоступен: нельзя сохранить лицензию на этой системе');
|
|
||||||
}
|
|
||||||
fs.mkdirSync(this.userData, { recursive: true });
|
fs.mkdirSync(this.userData, { recursive: true });
|
||||||
const enc = safeStorage.encryptString(token);
|
if (safeStorage.isEncryptionAvailable()) {
|
||||||
fs.writeFileSync(licenseEncryptedPath(this.userData), enc);
|
const enc = safeStorage.encryptString(token);
|
||||||
|
fs.writeFileSync(licenseEncryptedPath(this.userData), enc);
|
||||||
|
try {
|
||||||
|
fs.unlinkSync(licenseFallbackSealedPath(this.userData));
|
||||||
|
} catch {
|
||||||
|
/* ok */
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this.isInsecureFileStorageAllowed()) {
|
||||||
|
this.writeFallbackSealedToken(token);
|
||||||
|
try {
|
||||||
|
fs.unlinkSync(licenseEncryptedPath(this.userData));
|
||||||
|
} catch {
|
||||||
|
/* ok */
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new Error(
|
||||||
|
'safeStorage недоступен: нельзя сохранить лицензию на этой системе (типично WSL без gnome-keyring). Запустите с переменной DND_LICENSE_INSECURE_FILE_STORAGE=1 — токен будет сохранён в зашифрованном файле (слабее OS-хранилища); либо настройте Secret Service / gnome-keyring.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private clearSealedTokenFile(): void {
|
private clearSealedTokenFile(): void {
|
||||||
@@ -77,6 +173,11 @@ export class LicenseService {
|
|||||||
} catch {
|
} catch {
|
||||||
/* ok */
|
/* ok */
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
fs.unlinkSync(licenseFallbackSealedPath(this.userData));
|
||||||
|
} catch {
|
||||||
|
/* ok */
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** База для `POST /v1/activate` (и при желании совпадает с сервером отзыва). */
|
/** База для `POST /v1/activate` (и при желании совпадает с сервером отзыва). */
|
||||||
@@ -241,7 +342,7 @@ export class LicenseService {
|
|||||||
return this.getStatusSync();
|
return this.getStatusSync();
|
||||||
}
|
}
|
||||||
let trimmed = normalizeLicenseTokenInput(token);
|
let trimmed = normalizeLicenseTokenInput(token);
|
||||||
if (isDndProductKey(trimmed)) {
|
if (isProductKey(trimmed)) {
|
||||||
trimmed = await this.activateWithProductKey(trimmed);
|
trimmed = await this.activateWithProductKey(trimmed);
|
||||||
}
|
}
|
||||||
const nowSec = Math.floor(Date.now() / 1000);
|
const nowSec = Math.floor(Date.now() / 1000);
|
||||||
|
|||||||
@@ -4,6 +4,11 @@ export function licenseEncryptedPath(userData: string): string {
|
|||||||
return path.join(userData, 'license.sealed');
|
return path.join(userData, 'license.sealed');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Fallback, если нет OS keychain (WSL без gnome-keyring и т.п.); только при DND_LICENSE_INSECURE_FILE_STORAGE=1. */
|
||||||
|
export function licenseFallbackSealedPath(userData: string): string {
|
||||||
|
return path.join(userData, 'license.sealed.fallback');
|
||||||
|
}
|
||||||
|
|
||||||
export function deviceIdPath(userData: string): string {
|
export function deviceIdPath(userData: string): string {
|
||||||
return path.join(userData, 'device.id');
|
return path.join(userData, 'device.id');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import crypto from 'node:crypto';
|
||||||
|
import fs from 'node:fs/promises';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
import {
|
||||||
|
PROJECT_ZIP_EXTENSION,
|
||||||
|
PROJECT_ZIP_EXTENSION_LEGACY,
|
||||||
|
isProjectZipFileName,
|
||||||
|
} from '../../shared/project/projectZipExtension';
|
||||||
|
|
||||||
|
import { readProjectJsonFromZip } from './yauzlProjectZip';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Подменяет файл `finalPath` готовым `completedSrc` (обычно `*.ttrpg.zip.tmp` / `*.dnd.zip.tmp`).
|
||||||
|
* Нельзя сначала удалять `finalPath`: при сбое rename после rm проект теряется (Windows/антивирус).
|
||||||
|
*/
|
||||||
|
export async function replaceFileAtomic(completedSrc: string, finalPath: string): Promise<void> {
|
||||||
|
if (completedSrc === finalPath) return;
|
||||||
|
|
||||||
|
const stSrc = await fs.stat(completedSrc).catch(() => null);
|
||||||
|
if (!stSrc?.isFile() || stSrc.size === 0) {
|
||||||
|
throw new Error(`replaceFileAtomic: нет или пустой источник: ${completedSrc}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fs.rename(completedSrc, finalPath);
|
||||||
|
return;
|
||||||
|
} catch (first: unknown) {
|
||||||
|
const c = (first as NodeJS.ErrnoException).code;
|
||||||
|
if (c === 'EXDEV') {
|
||||||
|
await fs.copyFile(completedSrc, finalPath);
|
||||||
|
await fs.unlink(completedSrc).catch(() => undefined);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Windows: чаще всего EEXIST — целевой файл есть, rename не перезаписывает; идём через backup ниже.
|
||||||
|
}
|
||||||
|
|
||||||
|
const stFinal = await fs.stat(finalPath).catch(() => null);
|
||||||
|
if (!stFinal?.isFile()) {
|
||||||
|
try {
|
||||||
|
await fs.rename(completedSrc, finalPath);
|
||||||
|
return;
|
||||||
|
} catch (again: unknown) {
|
||||||
|
throw again instanceof Error ? again : new Error(String(again));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const backupPath = `${finalPath}.bak.${Date.now().toString(36)}_${crypto.randomBytes(4).toString('hex')}`;
|
||||||
|
await fs.rename(finalPath, backupPath);
|
||||||
|
try {
|
||||||
|
await fs.rename(completedSrc, finalPath);
|
||||||
|
} catch (place: unknown) {
|
||||||
|
await fs.rename(backupPath, finalPath).catch(() => undefined);
|
||||||
|
throw place instanceof Error ? place : new Error(String(place));
|
||||||
|
}
|
||||||
|
await fs.unlink(backupPath).catch(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ZIP_TMP_SUFFIXES = [`${PROJECT_ZIP_EXTENSION}.tmp`, `${PROJECT_ZIP_EXTENSION_LEGACY}.tmp`] as const;
|
||||||
|
|
||||||
|
/** Если сохранение оборвалось, остаётся `*.ttrpg.zip.tmp` / `*.dnd.zip.tmp` — восстанавливаем финальный архив. */
|
||||||
|
export async function recoverOrphanProjectZipTmpInRoot(root: string): Promise<void> {
|
||||||
|
let names: string[];
|
||||||
|
try {
|
||||||
|
names = await fs.readdir(root);
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const name of names) {
|
||||||
|
const matchedSuffix = ZIP_TMP_SUFFIXES.find((s) => name.endsWith(s));
|
||||||
|
if (!matchedSuffix) continue;
|
||||||
|
const tmpPath = path.join(root, name);
|
||||||
|
const finalName = name.slice(0, -'.tmp'.length);
|
||||||
|
if (!isProjectZipFileName(finalName)) continue;
|
||||||
|
const finalPath = path.join(root, finalName);
|
||||||
|
try {
|
||||||
|
await fs.access(finalPath);
|
||||||
|
continue;
|
||||||
|
} catch {
|
||||||
|
/* final отсутствует — пробуем поднять из tmp */
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const st = await fs.stat(tmpPath);
|
||||||
|
if (!st.isFile() || st.size < 22) continue;
|
||||||
|
await readProjectJsonFromZip(tmpPath);
|
||||||
|
await fs.rename(tmpPath, finalPath);
|
||||||
|
} catch {
|
||||||
|
/* битый tmp не трогаем */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @deprecated Используйте {@link recoverOrphanProjectZipTmpInRoot}. */
|
||||||
|
export const recoverOrphanDndZipTmpInRoot = recoverOrphanProjectZipTmpInRoot;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* Visually lossless re-encode for imported raster images (same pixel dimensions).
|
* Visually lossless re-encode for imported raster images (same pixel dimensions).
|
||||||
* Node-only; shared by the main app and tools/project-converter.
|
* Node-only; shared by the main app and ../project-converter (monorepo sibling).
|
||||||
*/
|
*/
|
||||||
import sharp from 'sharp';
|
import sharp from 'sharp';
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,14 @@ export function getProjectsCacheRootDir(): string {
|
|||||||
export function getLegacyProjectsRootDirs(): string[] {
|
export function getLegacyProjectsRootDirs(): string[] {
|
||||||
const cur = getProjectsRootDir();
|
const cur = getProjectsRootDir();
|
||||||
const parent = path.dirname(app.getPath('userData'));
|
const parent = path.dirname(app.getPath('userData'));
|
||||||
const siblingNames = ['DnD Player', 'dnd-player', 'DNDGamePlayer', 'dnd_player'];
|
const siblingNames = [
|
||||||
|
'TTRPG Player',
|
||||||
|
'TTRPGPlayer',
|
||||||
|
'DnD Player',
|
||||||
|
'dnd-player',
|
||||||
|
'DNDGamePlayer',
|
||||||
|
'dnd_player',
|
||||||
|
];
|
||||||
const out: string[] = [];
|
const out: string[] = [];
|
||||||
for (const n of siblingNames) {
|
for (const n of siblingNames) {
|
||||||
const p = path.join(parent, n, 'projects');
|
const p = path.join(parent, n, 'projects');
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs/promises';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import test from 'node:test';
|
||||||
|
|
||||||
|
import { replaceFileAtomic } from './atomicReplace';
|
||||||
|
|
||||||
|
void test('replaceFileAtomic: replaces existing file without deleting before rename succeeds', async () => {
|
||||||
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-replace-'));
|
||||||
|
const finalPath = path.join(dir, 'out.bin');
|
||||||
|
const tmpPath = path.join(dir, 'out.bin.tmp');
|
||||||
|
await fs.writeFile(finalPath, 'previous', 'utf8');
|
||||||
|
await fs.writeFile(tmpPath, 'updated-content', 'utf8');
|
||||||
|
await replaceFileAtomic(tmpPath, finalPath);
|
||||||
|
assert.equal(await fs.readFile(finalPath, 'utf8'), 'updated-content');
|
||||||
|
await assert.rejects(() => fs.stat(tmpPath));
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('replaceFileAtomic: rejects empty source', async () => {
|
||||||
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-replace-'));
|
||||||
|
const finalPath = path.join(dir, 'out.bin');
|
||||||
|
const tmpPath = path.join(dir, 'out.bin.tmp');
|
||||||
|
await fs.writeFile(finalPath, 'x', 'utf8');
|
||||||
|
await fs.writeFile(tmpPath, '', 'utf8');
|
||||||
|
await assert.rejects(() => replaceFileAtomic(tmpPath, finalPath));
|
||||||
|
assert.equal(await fs.readFile(finalPath, 'utf8'), 'x');
|
||||||
|
});
|
||||||
@@ -13,7 +13,7 @@ import { readProjectJsonFromZip } from './yauzlProjectZip';
|
|||||||
|
|
||||||
void test('readProjectJsonFromZip: sequential reads close yauzl (no EMFILE)', async () => {
|
void test('readProjectJsonFromZip: sequential reads close yauzl (no EMFILE)', async () => {
|
||||||
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-zip-read-'));
|
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-zip-read-'));
|
||||||
const zipPath = path.join(tmp, 'test.dnd.zip');
|
const zipPath = path.join(tmp, 'test.ttrpg.zip');
|
||||||
const minimal = {
|
const minimal = {
|
||||||
id: 'p1',
|
id: 'p1',
|
||||||
meta: {
|
meta: {
|
||||||
@@ -54,7 +54,7 @@ void test('readProjectJsonFromZip: sequential reads close yauzl (no EMFILE)', as
|
|||||||
|
|
||||||
void test('readProjectJsonFromZip: campaignAudios round-trips inside project.json', async () => {
|
void test('readProjectJsonFromZip: campaignAudios round-trips inside project.json', async () => {
|
||||||
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-zip-campaign-'));
|
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dnd-zip-campaign-'));
|
||||||
const zipPath = path.join(tmp, 'test.dnd.zip');
|
const zipPath = path.join(tmp, 'test.ttrpg.zip');
|
||||||
const assetId = 'audio_asset_1';
|
const assetId = 'audio_asset_1';
|
||||||
const minimal = {
|
const minimal = {
|
||||||
id: 'p1',
|
id: 'p1',
|
||||||
|
|||||||
@@ -45,3 +45,22 @@ void test('zipStore: normalizeScene defaults previewThumbAssetId for older proje
|
|||||||
assert.match(src, /previewThumbAssetId/);
|
assert.match(src, /previewThumbAssetId/);
|
||||||
assert.match(src, /function normalizeScene\(/);
|
assert.match(src, /function normalizeScene\(/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
void test('zipStore: listProjects skips unreadable archives', () => {
|
||||||
|
const src = fs.readFileSync(path.join(here, 'zipStore.ts'), 'utf8');
|
||||||
|
assert.match(
|
||||||
|
src,
|
||||||
|
/async listProjects[\s\S]+?for \(const filePath of files\)[\s\S]+?try \{[\s\S]+?readProjectJsonFromZip/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('atomicReplace: replaceFileAtomic must not rm destination before successful commit', () => {
|
||||||
|
const src = fs.readFileSync(path.join(here, 'atomicReplace.ts'), 'utf8');
|
||||||
|
const i = src.indexOf('export async function replaceFileAtomic');
|
||||||
|
assert.ok(i >= 0);
|
||||||
|
const j = src.indexOf('export async function recoverOrphanProjectZipTmpInRoot', i);
|
||||||
|
assert.ok(j > i);
|
||||||
|
const block = src.slice(i, j);
|
||||||
|
assert.match(block, /rename\(finalPath, backupPath\)/);
|
||||||
|
assert.doesNotMatch(block, /\.rm\(\s*finalPath/);
|
||||||
|
});
|
||||||
|
|||||||
@@ -8,6 +8,11 @@ import { ZipFile } from 'yazl';
|
|||||||
|
|
||||||
import { isSceneGraphEdgeRejected } from '../../shared/graph/sceneGraphEdgeRules';
|
import { isSceneGraphEdgeRejected } from '../../shared/graph/sceneGraphEdgeRules';
|
||||||
import type { ScenePatch } from '../../shared/ipc/contracts';
|
import type { ScenePatch } from '../../shared/ipc/contracts';
|
||||||
|
import {
|
||||||
|
isProjectZipFileName,
|
||||||
|
projectZipFileNameFromBase,
|
||||||
|
stripProjectZipExtension,
|
||||||
|
} from '../../shared/project/projectZipExtension';
|
||||||
import type {
|
import type {
|
||||||
MediaAsset,
|
MediaAsset,
|
||||||
MediaAssetType,
|
MediaAssetType,
|
||||||
@@ -24,6 +29,7 @@ import { asAssetId, asGraphNodeId, asProjectId } from '../../shared/types/ids';
|
|||||||
import { getAppSemanticVersion } from '../versionInfo';
|
import { getAppSemanticVersion } from '../versionInfo';
|
||||||
|
|
||||||
import { reconcileAssetFiles } from './assetPrune';
|
import { reconcileAssetFiles } from './assetPrune';
|
||||||
|
import { recoverOrphanProjectZipTmpInRoot, replaceFileAtomic } from './atomicReplace';
|
||||||
import { rmWithRetries } from './fsRetry';
|
import { rmWithRetries } from './fsRetry';
|
||||||
import { optimizeImageBufferVisuallyLossless } from './optimizeImageImport.lib.mjs';
|
import { optimizeImageBufferVisuallyLossless } from './optimizeImageImport.lib.mjs';
|
||||||
import { getLegacyProjectsRootDirs, getProjectsCacheRootDir, getProjectsRootDir } from './paths';
|
import { getLegacyProjectsRootDirs, getProjectsCacheRootDir, getProjectsRootDir } from './paths';
|
||||||
@@ -75,9 +81,10 @@ export class ZipProjectStore {
|
|||||||
await fs.mkdir(getProjectsRootDir(), { recursive: true });
|
await fs.mkdir(getProjectsRootDir(), { recursive: true });
|
||||||
await fs.mkdir(getProjectsCacheRootDir(), { recursive: true });
|
await fs.mkdir(getProjectsCacheRootDir(), { recursive: true });
|
||||||
await this.migrateLegacyProjectZipsIfNeeded();
|
await this.migrateLegacyProjectZipsIfNeeded();
|
||||||
|
await recoverOrphanProjectZipTmpInRoot(getProjectsRootDir());
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Копирует .dnd.zip из каталогов с «чужим» app name, если в текущем каталоге такого файла ещё нет. */
|
/** Копирует архивы проектов из каталогов с «чужим» app name, если в текущем каталоге такого файла ещё нет. */
|
||||||
private async migrateLegacyProjectZipsIfNeeded(): Promise<void> {
|
private async migrateLegacyProjectZipsIfNeeded(): Promise<void> {
|
||||||
const dest = getProjectsRootDir();
|
const dest = getProjectsRootDir();
|
||||||
let destNames: string[];
|
let destNames: string[];
|
||||||
@@ -86,7 +93,7 @@ export class ZipProjectStore {
|
|||||||
} catch {
|
} catch {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const destZips = new Set(destNames.filter((n) => n.endsWith('.dnd.zip')));
|
const destZips = new Set(destNames.filter((n) => isProjectZipFileName(n)));
|
||||||
for (const legacyRoot of getLegacyProjectsRootDirs()) {
|
for (const legacyRoot of getLegacyProjectsRootDirs()) {
|
||||||
let legacyNames: string[];
|
let legacyNames: string[];
|
||||||
try {
|
try {
|
||||||
@@ -95,7 +102,7 @@ export class ZipProjectStore {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
for (const name of legacyNames) {
|
for (const name of legacyNames) {
|
||||||
if (!name.endsWith('.dnd.zip')) continue;
|
if (!isProjectZipFileName(name)) continue;
|
||||||
if (destZips.has(name)) continue;
|
if (destZips.has(name)) continue;
|
||||||
const from = path.join(legacyRoot, name);
|
const from = path.join(legacyRoot, name);
|
||||||
const to = path.join(dest, name);
|
const to = path.join(dest, name);
|
||||||
@@ -130,18 +137,22 @@ export class ZipProjectStore {
|
|||||||
const root = getProjectsRootDir();
|
const root = getProjectsRootDir();
|
||||||
const entries = await fs.readdir(root, { withFileTypes: true });
|
const entries = await fs.readdir(root, { withFileTypes: true });
|
||||||
const files = entries
|
const files = entries
|
||||||
.filter((e) => e.isFile() && e.name.endsWith('.dnd.zip'))
|
.filter((e) => e.isFile() && isProjectZipFileName(e.name))
|
||||||
.map((e) => path.join(root, e.name));
|
.map((e) => path.join(root, e.name));
|
||||||
|
|
||||||
const out: ProjectIndexEntry[] = [];
|
const out: ProjectIndexEntry[] = [];
|
||||||
for (const filePath of files) {
|
for (const filePath of files) {
|
||||||
const project = await readProjectJsonFromZip(filePath);
|
try {
|
||||||
out.push({
|
const project = await readProjectJsonFromZip(filePath);
|
||||||
id: project.id,
|
out.push({
|
||||||
name: project.meta.name,
|
id: project.id,
|
||||||
updatedAt: project.meta.updatedAt,
|
name: project.meta.name,
|
||||||
fileName: path.basename(filePath),
|
updatedAt: project.meta.updatedAt,
|
||||||
});
|
fileName: path.basename(filePath),
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Один битый архив не должен скрывать остальные проекты в списке.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
out.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
out.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
||||||
return out;
|
return out;
|
||||||
@@ -174,7 +185,7 @@ export class ZipProjectStore {
|
|||||||
sceneGraphEdges: [],
|
sceneGraphEdges: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
const zipPath = path.join(getProjectsRootDir(), `${fileBaseName}.dnd.zip`);
|
const zipPath = path.join(getProjectsRootDir(), projectZipFileNameFromBase(fileBaseName));
|
||||||
const cacheDir = path.join(getProjectsCacheRootDir(), id);
|
const cacheDir = path.join(getProjectsCacheRootDir(), id);
|
||||||
const projectPath = path.join(cacheDir, 'project.json');
|
const projectPath = path.join(cacheDir, 'project.json');
|
||||||
this.openProject = { id, zipPath, cacheDir, projectPath, project };
|
this.openProject = { id, zipPath, cacheDir, projectPath, project };
|
||||||
@@ -772,7 +783,7 @@ export class ZipProjectStore {
|
|||||||
const list = await this.listProjects();
|
const list = await this.listProjects();
|
||||||
|
|
||||||
const oldBase = open.project.meta.fileBaseName;
|
const oldBase = open.project.meta.fileBaseName;
|
||||||
const nextFileName = `${sanitizedBase}.dnd.zip`;
|
const nextFileName = projectZipFileNameFromBase(sanitizedBase);
|
||||||
|
|
||||||
const nameClash = list.some(
|
const nameClash = list.some(
|
||||||
(p) => p.id !== open.id && p.name.trim().toLowerCase() === nextName.toLowerCase(),
|
(p) => p.id !== open.id && p.name.trim().toLowerCase() === nextName.toLowerCase(),
|
||||||
@@ -868,6 +879,11 @@ export class ZipProjectStore {
|
|||||||
const tmpPath = `${zipPath}.tmp`;
|
const tmpPath = `${zipPath}.tmp`;
|
||||||
await fs.mkdir(path.dirname(zipPath), { recursive: true });
|
await fs.mkdir(path.dirname(zipPath), { recursive: true });
|
||||||
await zipDir(cacheDir, tmpPath);
|
await zipDir(cacheDir, tmpPath);
|
||||||
|
const st = await fs.stat(tmpPath).catch(() => null);
|
||||||
|
if (!st?.isFile() || st.size < 22) {
|
||||||
|
await fs.unlink(tmpPath).catch(() => undefined);
|
||||||
|
throw new Error('Сборка архива проекта не удалась (пустой или повреждённый временный файл)');
|
||||||
|
}
|
||||||
await replaceFileAtomic(tmpPath, zipPath);
|
await replaceFileAtomic(tmpPath, zipPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -886,8 +902,8 @@ export class ZipProjectStore {
|
|||||||
if (!st?.isFile()) {
|
if (!st?.isFile()) {
|
||||||
throw new Error('Файл проекта не найден');
|
throw new Error('Файл проекта не найден');
|
||||||
}
|
}
|
||||||
if (!resolved.toLowerCase().endsWith('.dnd.zip')) {
|
if (!isProjectZipFileName(resolved)) {
|
||||||
throw new Error('Ожидается файл с расширением .dnd.zip');
|
throw new Error('Ожидается файл проекта с расширением .ttrpg.zip или .dnd.zip');
|
||||||
}
|
}
|
||||||
|
|
||||||
const root = getProjectsRootDir();
|
const root = getProjectsRootDir();
|
||||||
@@ -898,11 +914,11 @@ export class ZipProjectStore {
|
|||||||
let destPath: string;
|
let destPath: string;
|
||||||
let destFileName: string;
|
let destFileName: string;
|
||||||
|
|
||||||
if (dirNorm === rootNorm && baseName.toLowerCase().endsWith('.dnd.zip')) {
|
if (dirNorm === rootNorm && isProjectZipFileName(baseName)) {
|
||||||
destPath = resolved;
|
destPath = resolved;
|
||||||
destFileName = baseName;
|
destFileName = baseName;
|
||||||
} else {
|
} else {
|
||||||
destFileName = await uniqueDndZipFileName(root, baseName);
|
destFileName = await uniqueProjectZipFileNameInRoot(root, baseName);
|
||||||
destPath = path.join(root, destFileName);
|
destPath = path.join(root, destFileName);
|
||||||
if (onProgress) onProgress({ stage: 'copy', percent: 1, detail: 'Копирование…' });
|
if (onProgress) onProgress({ stage: 'copy', percent: 1, detail: 'Копирование…' });
|
||||||
await copyFileWithProgress(resolved, destPath, (pct) => {
|
await copyFileWithProgress(resolved, destPath, (pct) => {
|
||||||
@@ -919,7 +935,7 @@ export class ZipProjectStore {
|
|||||||
const othersWithSameId = entries.filter((e) => e.id === project.id && e.fileName !== destFileName);
|
const othersWithSameId = entries.filter((e) => e.id === project.id && e.fileName !== destFileName);
|
||||||
if (othersWithSameId.length > 0) {
|
if (othersWithSameId.length > 0) {
|
||||||
const newId = asProjectId(this.randomId());
|
const newId = asProjectId(this.randomId());
|
||||||
const stem = destFileName.replace(/\.dnd\.zip$/iu, '');
|
const stem = stripProjectZipExtension(destFileName);
|
||||||
project = {
|
project = {
|
||||||
...project,
|
...project,
|
||||||
id: newId,
|
id: newId,
|
||||||
@@ -1206,40 +1222,21 @@ function sanitizeFileName(name: string): string {
|
|||||||
return safe.length > 0 ? safe : 'Untitled';
|
return safe.length > 0 ? safe : 'Untitled';
|
||||||
}
|
}
|
||||||
|
|
||||||
async function uniqueDndZipFileName(root: string, preferredBaseFileName: string): Promise<string> {
|
async function uniqueProjectZipFileNameInRoot(root: string, preferredBaseFileName: string): Promise<string> {
|
||||||
let base = preferredBaseFileName;
|
const stem = sanitizeFileName(stripProjectZipExtension(path.basename(preferredBaseFileName)) || 'project');
|
||||||
if (!base.toLowerCase().endsWith('.dnd.zip')) {
|
let candidate = projectZipFileNameFromBase(stem);
|
||||||
const stem = sanitizeFileName(path.basename(base, path.extname(base)) || 'project');
|
|
||||||
base = `${stem}.dnd.zip`;
|
|
||||||
}
|
|
||||||
const stem = base.replace(/\.dnd\.zip$/iu, '');
|
|
||||||
let candidate = base;
|
|
||||||
let n = 0;
|
let n = 0;
|
||||||
for (;;) {
|
for (;;) {
|
||||||
try {
|
try {
|
||||||
await fs.access(path.join(root, candidate));
|
await fs.access(path.join(root, candidate));
|
||||||
n += 1;
|
n += 1;
|
||||||
candidate = `${stem}_${String(n)}.dnd.zip`;
|
candidate = projectZipFileNameFromBase(`${stem}_${String(n)}`);
|
||||||
} catch {
|
} catch {
|
||||||
return candidate;
|
return candidate;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function replaceFileAtomic(srcPath: string, destPath: string): Promise<void> {
|
|
||||||
try {
|
|
||||||
await fs.rename(srcPath, destPath);
|
|
||||||
} catch {
|
|
||||||
try {
|
|
||||||
await fs.rm(destPath, { force: true });
|
|
||||||
await fs.rename(srcPath, destPath);
|
|
||||||
} catch (second: unknown) {
|
|
||||||
await fs.unlink(srcPath).catch(() => undefined);
|
|
||||||
throw second instanceof Error ? second : new Error(String(second));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function copyFileWithProgress(
|
async function copyFileWithProgress(
|
||||||
src: string,
|
src: string,
|
||||||
dest: string,
|
dest: string,
|
||||||
@@ -1339,17 +1336,7 @@ async function atomicWriteFile(filePath: string, contents: string): Promise<void
|
|||||||
await fs.mkdir(dir, { recursive: true });
|
await fs.mkdir(dir, { recursive: true });
|
||||||
const tmp = path.join(dir, `.tmp_${path.basename(filePath)}_${crypto.randomBytes(8).toString('hex')}`);
|
const tmp = path.join(dir, `.tmp_${path.basename(filePath)}_${crypto.randomBytes(8).toString('hex')}`);
|
||||||
await fs.writeFile(tmp, contents, 'utf8');
|
await fs.writeFile(tmp, contents, 'utf8');
|
||||||
try {
|
await replaceFileAtomic(tmp, filePath);
|
||||||
await fs.rename(tmp, filePath);
|
|
||||||
} catch {
|
|
||||||
try {
|
|
||||||
await fs.rm(filePath, { force: true });
|
|
||||||
await fs.rename(tmp, filePath);
|
|
||||||
} catch (second: unknown) {
|
|
||||||
await fs.unlink(tmp).catch(() => undefined);
|
|
||||||
throw second instanceof Error ? second : new Error(String(second));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Уже сжатые контейнеры/кодеки — в ZIP кладём без deflate, качество не трогаем; project.json и сырьё — deflate 9. */
|
/** Уже сжатые контейнеры/кодеки — в ZIP кладём без deflate, качество не трогаем; project.json и сырьё — deflate 9. */
|
||||||
|
|||||||
@@ -0,0 +1,250 @@
|
|||||||
|
import { app, BrowserWindow, dialog } from 'electron';
|
||||||
|
import { autoUpdater } from 'electron-updater';
|
||||||
|
|
||||||
|
import { appDisplayNameForLocale } from '../../shared/appBranding';
|
||||||
|
import {
|
||||||
|
ipcChannels,
|
||||||
|
type UpdaterCheckResponse,
|
||||||
|
type UpdaterDownloadResponse,
|
||||||
|
type UpdaterProgressEvent,
|
||||||
|
} from '../../shared/ipc/contracts';
|
||||||
|
import type { IpcRegisterHandler } from '../ipc/router';
|
||||||
|
import { addLicenseChangeListener } from '../license/licenseService';
|
||||||
|
import type { LicenseService } from '../license/licenseService';
|
||||||
|
|
||||||
|
const STARTUP_CHECK_DELAY_MS = 12_000;
|
||||||
|
/** Не дёргать сервер чаще (смена лицензии / повторные emit). */
|
||||||
|
const RE_CHECK_COOLDOWN_MS = 30_000;
|
||||||
|
/** Ручная загрузка из модалки — не зависать бесконечно на «Загрузка…». */
|
||||||
|
const MANUAL_DOWNLOAD_TIMEOUT_MS = 30 * 60 * 1000;
|
||||||
|
|
||||||
|
function withTimeout<T>(promise: Promise<T>, ms: number, code: string): Promise<T> {
|
||||||
|
return new Promise<T>((resolve, reject) => {
|
||||||
|
const timer = setTimeout(() => reject(new Error(code)), ms);
|
||||||
|
promise.then(
|
||||||
|
(v) => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
resolve(v);
|
||||||
|
},
|
||||||
|
(e: unknown) => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
reject(e instanceof Error ? e : new Error(String(e)));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* На macOS Squirrel.Mac может уже получить update-downloaded к моменту quitAndInstall.
|
||||||
|
* При autoInstallOnAppQuit=true MacUpdater не вызывает checkForUpdates повторно и зависает.
|
||||||
|
*/
|
||||||
|
function quitAndInstallForPlatform(): void {
|
||||||
|
if (process.platform === 'darwin') {
|
||||||
|
autoUpdater.autoInstallOnAppQuit = false;
|
||||||
|
}
|
||||||
|
autoUpdater.quitAndInstall(false, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatUpdaterError(e: unknown): string {
|
||||||
|
const raw = e instanceof Error ? e.message : String(e);
|
||||||
|
if (raw === 'UPDATE_DOWNLOAD_TIMEOUT') {
|
||||||
|
return 'Превышено время ожидания загрузки обновления';
|
||||||
|
}
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
let lastCheckAt = 0;
|
||||||
|
/** Ручная установка: не показывать второй диалог из `update-downloaded`. */
|
||||||
|
let suppressAutoInstallDialog = false;
|
||||||
|
/** Версия, уже скачанная Squirrel/electron-updater (в т.ч. фоном). */
|
||||||
|
let downloadedUpdateVersion: string | null = null;
|
||||||
|
|
||||||
|
type RegisterFn = IpcRegisterHandler;
|
||||||
|
|
||||||
|
function emitUpdaterProgress(ev: UpdaterProgressEvent): void {
|
||||||
|
for (const win of BrowserWindow.getAllWindows()) {
|
||||||
|
if (win.isDestroyed() || win.webContents.isDestroyed()) continue;
|
||||||
|
try {
|
||||||
|
win.webContents.send(ipcChannels.updater.progress, ev);
|
||||||
|
} catch {
|
||||||
|
/* окно закрылось */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isLicensedForUpdates(licenseService: LicenseService): boolean {
|
||||||
|
const snap = licenseService.getStatusSync();
|
||||||
|
return snap.active;
|
||||||
|
}
|
||||||
|
|
||||||
|
function maybeCheckForUpdates(licenseService: LicenseService, ignoreCooldown: boolean): void {
|
||||||
|
if (!app.isPackaged) return;
|
||||||
|
if (!isLicensedForUpdates(licenseService)) return;
|
||||||
|
const now = Date.now();
|
||||||
|
if (!ignoreCooldown && now - lastCheckAt < RE_CHECK_COOLDOWN_MS) return;
|
||||||
|
lastCheckAt = now;
|
||||||
|
emitUpdaterProgress({ phase: 'checking' });
|
||||||
|
void autoUpdater.checkForUpdates().catch(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runManualUpdaterCheck(licenseService: LicenseService): Promise<UpdaterCheckResponse> {
|
||||||
|
if (!app.isPackaged) {
|
||||||
|
return { outcome: 'not_packaged' };
|
||||||
|
}
|
||||||
|
if (!isLicensedForUpdates(licenseService)) {
|
||||||
|
return { outcome: 'no_license' };
|
||||||
|
}
|
||||||
|
const prevAutoDownload = autoUpdater.autoDownload;
|
||||||
|
autoUpdater.autoDownload = false;
|
||||||
|
emitUpdaterProgress({ phase: 'checking' });
|
||||||
|
try {
|
||||||
|
const result = await autoUpdater.checkForUpdates();
|
||||||
|
if (result && result.isUpdateAvailable && result.updateInfo.version) {
|
||||||
|
emitUpdaterProgress({ phase: 'available', version: result.updateInfo.version });
|
||||||
|
return { outcome: 'available', version: result.updateInfo.version };
|
||||||
|
}
|
||||||
|
emitUpdaterProgress({ phase: 'not-available', version: app.getVersion() });
|
||||||
|
return { outcome: 'current', currentVersion: app.getVersion() };
|
||||||
|
} catch (e) {
|
||||||
|
const message = e instanceof Error ? e.message : String(e);
|
||||||
|
emitUpdaterProgress({ phase: 'error', message });
|
||||||
|
return { outcome: 'error', message };
|
||||||
|
} finally {
|
||||||
|
autoUpdater.autoDownload = prevAutoDownload;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isUpdateAlreadyDownloaded(targetVersion: string): boolean {
|
||||||
|
return downloadedUpdateVersion !== null && downloadedUpdateVersion === targetVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runManualDownloadAndRestart(targetVersion: string): Promise<UpdaterDownloadResponse> {
|
||||||
|
if (!app.isPackaged) {
|
||||||
|
return { ok: false, message: 'NOT_PACKAGED' };
|
||||||
|
}
|
||||||
|
const prevAutoInstallOnAppQuit = autoUpdater.autoInstallOnAppQuit;
|
||||||
|
try {
|
||||||
|
suppressAutoInstallDialog = true;
|
||||||
|
if (process.platform === 'darwin') {
|
||||||
|
autoUpdater.autoInstallOnAppQuit = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isUpdateAlreadyDownloaded(targetVersion)) {
|
||||||
|
emitUpdaterProgress({ phase: 'downloading', version: targetVersion, percent: 0 });
|
||||||
|
await withTimeout(
|
||||||
|
autoUpdater.downloadUpdate(),
|
||||||
|
MANUAL_DOWNLOAD_TIMEOUT_MS,
|
||||||
|
'UPDATE_DOWNLOAD_TIMEOUT',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
emitUpdaterProgress({ phase: 'installing', version: targetVersion });
|
||||||
|
quitAndInstallForPlatform();
|
||||||
|
return { ok: true };
|
||||||
|
} catch (e) {
|
||||||
|
suppressAutoInstallDialog = false;
|
||||||
|
const message = formatUpdaterError(e);
|
||||||
|
emitUpdaterProgress({ phase: 'error', message });
|
||||||
|
if (process.platform === 'darwin') {
|
||||||
|
autoUpdater.autoInstallOnAppQuit = prevAutoInstallOnAppQuit;
|
||||||
|
}
|
||||||
|
return { ok: false, message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function registerUpdaterHandlers(register: RegisterFn, licenseService: LicenseService): void {
|
||||||
|
register(ipcChannels.updater.check, () => runManualUpdaterCheck(licenseService));
|
||||||
|
register(ipcChannels.updater.downloadAndRestart, (req: { version: string }) =>
|
||||||
|
runManualDownloadAndRestart(req.version),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function wireAutoUpdaterEvents(licenseService: LicenseService): void {
|
||||||
|
autoUpdater.on('checking-for-update', () => {
|
||||||
|
emitUpdaterProgress({ phase: 'checking' });
|
||||||
|
});
|
||||||
|
|
||||||
|
autoUpdater.on('update-available', (info) => {
|
||||||
|
emitUpdaterProgress({ phase: 'available', version: info.version });
|
||||||
|
});
|
||||||
|
|
||||||
|
autoUpdater.on('update-not-available', (info) => {
|
||||||
|
emitUpdaterProgress({ phase: 'not-available', version: info.version });
|
||||||
|
});
|
||||||
|
|
||||||
|
autoUpdater.on('download-progress', (progress) => {
|
||||||
|
const percent =
|
||||||
|
typeof progress.percent === 'number' && Number.isFinite(progress.percent)
|
||||||
|
? Math.round(progress.percent)
|
||||||
|
: undefined;
|
||||||
|
const ev: UpdaterProgressEvent = { phase: 'downloading' };
|
||||||
|
if (percent !== undefined) ev.percent = percent;
|
||||||
|
emitUpdaterProgress(ev);
|
||||||
|
});
|
||||||
|
|
||||||
|
autoUpdater.on('update-downloaded', (info) => {
|
||||||
|
downloadedUpdateVersion = info.version;
|
||||||
|
emitUpdaterProgress({ phase: 'downloading', version: info.version, percent: 100 });
|
||||||
|
if (suppressAutoInstallDialog) {
|
||||||
|
suppressAutoInstallDialog = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void dialog
|
||||||
|
.showMessageBox({
|
||||||
|
type: 'info',
|
||||||
|
title: appDisplayNameForLocale(app.getLocale()),
|
||||||
|
message: `Доступна новая версия ${info.version}. Установить и перезапустить?`,
|
||||||
|
buttons: ['Перезапустить сейчас', 'Позже'],
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: 1,
|
||||||
|
})
|
||||||
|
.then((r) => {
|
||||||
|
if (r.response === 0) {
|
||||||
|
emitUpdaterProgress({ phase: 'installing', version: info.version });
|
||||||
|
quitAndInstallForPlatform();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
autoUpdater.on('error', (e) => {
|
||||||
|
const message = e instanceof Error ? e.message : String(e);
|
||||||
|
emitUpdaterProgress({ phase: 'error', message });
|
||||||
|
});
|
||||||
|
|
||||||
|
addLicenseChangeListener(() => {
|
||||||
|
maybeCheckForUpdates(licenseService, false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Проверка обновлений: только упакованное приложение, только при активной лицензии.
|
||||||
|
* Канал и URL задаются при сборке (`publish` → `app-update.yml` внутри установки).
|
||||||
|
* Дифференциальное скачивание (HTTP Range / blockmap) по умолчанию **выключено**: за nginx у Gitea raw часто **400** на multi-Range, updater всё равно уходит в полный файл. Включить снова: **`DND_UPDATE_ENABLE_DIFFERENTIAL=1`** (имеет смысл только если на сервере починили Range).
|
||||||
|
*/
|
||||||
|
export function installAutoUpdater(licenseService: LicenseService, register: RegisterFn): void {
|
||||||
|
registerUpdaterHandlers(register, licenseService);
|
||||||
|
|
||||||
|
if (!app.isPackaged) return;
|
||||||
|
|
||||||
|
const feedOverride = process.env.DND_UPDATE_FEED_URL?.trim();
|
||||||
|
if (feedOverride) {
|
||||||
|
const url = feedOverride.endsWith('/') ? feedOverride : `${feedOverride}/`;
|
||||||
|
autoUpdater.setFeedURL({ provider: 'generic', url });
|
||||||
|
}
|
||||||
|
|
||||||
|
const enableDiff = process.env.DND_UPDATE_ENABLE_DIFFERENTIAL?.trim().toLowerCase();
|
||||||
|
autoUpdater.disableDifferentialDownload = !(
|
||||||
|
enableDiff === '1' ||
|
||||||
|
enableDiff === 'true' ||
|
||||||
|
enableDiff === 'yes'
|
||||||
|
);
|
||||||
|
|
||||||
|
autoUpdater.autoDownload = true;
|
||||||
|
autoUpdater.autoInstallOnAppQuit = true;
|
||||||
|
|
||||||
|
wireAutoUpdaterEvents(licenseService);
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
maybeCheckForUpdates(licenseService, true);
|
||||||
|
}, STARTUP_CHECK_DELAY_MS);
|
||||||
|
}
|
||||||
@@ -2,8 +2,11 @@ import path from 'node:path';
|
|||||||
|
|
||||||
import { app, BrowserWindow } from 'electron';
|
import { app, BrowserWindow } from 'electron';
|
||||||
|
|
||||||
|
import { appDisplayNameForLocale, windowChromeTitle } from '../../shared/appBranding';
|
||||||
import { getAppSemanticVersion } from '../versionInfo';
|
import { getAppSemanticVersion } from '../versionInfo';
|
||||||
|
|
||||||
|
import { loadBrandingWindowIcon } from './brandingIcon';
|
||||||
|
|
||||||
let bootSplashRef: BrowserWindow | null = null;
|
let bootSplashRef: BrowserWindow | null = null;
|
||||||
|
|
||||||
export function getBootSplashWindow(): BrowserWindow | null {
|
export function getBootSplashWindow(): BrowserWindow | null {
|
||||||
@@ -37,6 +40,7 @@ function bootWebPreferences(): Electron.WebPreferences {
|
|||||||
* Показывать после `waitForBootWindowReady`.
|
* Показывать после `waitForBootWindowReady`.
|
||||||
*/
|
*/
|
||||||
export function createBootWindow(): BrowserWindow {
|
export function createBootWindow(): BrowserWindow {
|
||||||
|
const icon = loadBrandingWindowIcon();
|
||||||
const win = new BrowserWindow({
|
const win = new BrowserWindow({
|
||||||
width: 440,
|
width: 440,
|
||||||
height: 420,
|
height: 420,
|
||||||
@@ -50,8 +54,17 @@ export function createBootWindow(): BrowserWindow {
|
|||||||
transparent: false,
|
transparent: false,
|
||||||
backgroundColor: '#09090B',
|
backgroundColor: '#09090B',
|
||||||
roundedCorners: true,
|
roundedCorners: true,
|
||||||
|
...(icon ? { icon } : {}),
|
||||||
webPreferences: bootWebPreferences(),
|
webPreferences: bootWebPreferences(),
|
||||||
});
|
});
|
||||||
|
if (icon) {
|
||||||
|
try {
|
||||||
|
win.setIcon(icon);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
win.setTitle(windowChromeTitle('boot', app.getLocale()));
|
||||||
|
|
||||||
bootSplashRef = win;
|
bootSplashRef = win;
|
||||||
win.once('closed', () => {
|
win.once('closed', () => {
|
||||||
@@ -82,7 +95,7 @@ export function setBootWindowStatus(win: BrowserWindow, text: string): void {
|
|||||||
|
|
||||||
export function applyBootWindowBranding(win: BrowserWindow): void {
|
export function applyBootWindowBranding(win: BrowserWindow): void {
|
||||||
if (win.isDestroyed()) return;
|
if (win.isDestroyed()) return;
|
||||||
const name = app.getName();
|
const name = appDisplayNameForLocale(app.getLocale());
|
||||||
const version = getAppSemanticVersion();
|
const version = getAppSemanticVersion();
|
||||||
const versionLabel = version.trim().length > 0 ? `v${version.trim()}` : '';
|
const versionLabel = version.trim().length > 0 ? `v${version.trim()}` : '';
|
||||||
void win.webContents.executeJavaScript(
|
void win.webContents.executeJavaScript(
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
import { app, nativeImage } from 'electron';
|
||||||
|
|
||||||
|
let resolved = false;
|
||||||
|
let cached: Electron.NativeImage | undefined;
|
||||||
|
|
||||||
|
/** ICO рядом с exe (вне asar): надёжно для `nativeImage` / панели задач на Windows. */
|
||||||
|
function getPackagedBrandingIcoPath(): string | undefined {
|
||||||
|
if (!app.isPackaged) return undefined;
|
||||||
|
const p = path.join(process.resourcesPath, 'branding', 'icon.ico');
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(p)) return p;
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function brandingPngPaths(): string[] {
|
||||||
|
const root = app.getAppPath();
|
||||||
|
const relPack = path.join('dist', 'renderer', 'app-pack-icon.png');
|
||||||
|
const relWindow = path.join('dist', 'renderer', 'app-window-icon.png');
|
||||||
|
const paths: string[] = [];
|
||||||
|
if (app.isPackaged) {
|
||||||
|
const unpacked = path.join(process.resourcesPath, 'app.asar.unpacked');
|
||||||
|
paths.push(path.join(unpacked, relPack), path.join(unpacked, relWindow));
|
||||||
|
}
|
||||||
|
paths.push(
|
||||||
|
path.join(root, relPack),
|
||||||
|
path.join(root, relWindow),
|
||||||
|
path.join(root, 'build', 'icon.png'),
|
||||||
|
path.join(root, 'app', 'renderer', 'public', 'app-window-icon.png'),
|
||||||
|
);
|
||||||
|
return paths;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryLoadImageFile(filePath: string): Electron.NativeImage | undefined {
|
||||||
|
try {
|
||||||
|
const buf = fs.readFileSync(filePath);
|
||||||
|
const fromBuf = nativeImage.createFromBuffer(buf);
|
||||||
|
if (!fromBuf.isEmpty()) return fromBuf;
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const fromPath = nativeImage.createFromPath(filePath);
|
||||||
|
if (!fromPath.isEmpty()) return fromPath;
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryLoadSvgFile(filePath: string): Electron.NativeImage | undefined {
|
||||||
|
try {
|
||||||
|
const fromPath = nativeImage.createFromPath(filePath);
|
||||||
|
if (!fromPath.isEmpty()) return fromPath;
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryDarwinSvgPaths(): Electron.NativeImage | undefined {
|
||||||
|
if (process.platform !== 'darwin') return undefined;
|
||||||
|
const root = app.getAppPath();
|
||||||
|
for (const p of [
|
||||||
|
path.join(root, 'dist', 'renderer', 'app-logo.svg'),
|
||||||
|
path.join(root, 'app', 'renderer', 'public', 'app-logo.svg'),
|
||||||
|
]) {
|
||||||
|
if (!fs.existsSync(p)) continue;
|
||||||
|
const img = tryLoadSvgFile(p);
|
||||||
|
if (img) return img;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Иконка окна / дока. Сначала ICO из `extraResources` (реальный путь на диске), затем PNG
|
||||||
|
* через буфер — `createFromPath` к файлам внутри `app.asar` на Windows часто даёт пустой `NativeImage`.
|
||||||
|
*/
|
||||||
|
export function loadBrandingWindowIcon(): Electron.NativeImage | undefined {
|
||||||
|
if (resolved) return cached;
|
||||||
|
resolved = true;
|
||||||
|
|
||||||
|
const ico = getPackagedBrandingIcoPath();
|
||||||
|
if (ico) {
|
||||||
|
const img = tryLoadImageFile(ico);
|
||||||
|
if (img) {
|
||||||
|
cached = img;
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const p of brandingPngPaths()) {
|
||||||
|
if (!fs.existsSync(p)) continue;
|
||||||
|
const img = tryLoadImageFile(p);
|
||||||
|
if (img) {
|
||||||
|
cached = img;
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const svgIcon = tryDarwinSvgPaths();
|
||||||
|
if (svgIcon) {
|
||||||
|
cached = svgIcon;
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
cached = undefined;
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
@@ -22,10 +22,11 @@ void test('createWindows: закрытие редактора завершает
|
|||||||
|
|
||||||
void test('createWindows: иконка окна (pack PNG, затем window PNG; SVG только вне win32)', () => {
|
void test('createWindows: иконка окна (pack PNG, затем window PNG; SVG только вне win32)', () => {
|
||||||
const src = readCreateWindows();
|
const src = readCreateWindows();
|
||||||
assert.ok(src.includes('resolveWindowIconPath'));
|
assert.ok(src.includes('loadBrandingWindowIcon'));
|
||||||
assert.ok(src.includes('app-pack-icon.png'));
|
const branding = fs.readFileSync(path.join(here, 'brandingIcon.ts'), 'utf8');
|
||||||
assert.ok(src.includes('app-window-icon.png'));
|
assert.ok(branding.includes('app-pack-icon.png'));
|
||||||
assert.ok(src.includes('app-logo.svg'));
|
assert.ok(branding.includes('app-window-icon.png'));
|
||||||
|
assert.ok(branding.includes('tryDarwinSvgPaths'));
|
||||||
});
|
});
|
||||||
|
|
||||||
void test('createWindows: пульт поверх экрана просмотра (дочернее окно)', () => {
|
void test('createWindows: пульт поверх экрана просмотра (дочернее окно)', () => {
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
import fs from 'node:fs';
|
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
|
|
||||||
import { app, BrowserWindow, nativeImage, screen } from 'electron';
|
import { app, BrowserWindow, screen } from 'electron';
|
||||||
|
|
||||||
|
import { windowChromeTitle } from '../../shared/appBranding';
|
||||||
|
import { ipcChannels } from '../../shared/ipc/contracts';
|
||||||
|
|
||||||
import { getBootSplashWindow } from './bootWindow';
|
import { getBootSplashWindow } from './bootWindow';
|
||||||
|
import { loadBrandingWindowIcon } from './brandingIcon';
|
||||||
|
|
||||||
type WindowKind = 'editor' | 'presentation' | 'control';
|
type WindowKind = 'editor' | 'presentation' | 'control';
|
||||||
|
|
||||||
@@ -11,6 +14,19 @@ const windows = new Map<WindowKind, BrowserWindow>();
|
|||||||
|
|
||||||
let appQuitting = false;
|
let appQuitting = false;
|
||||||
|
|
||||||
|
/** Учитываем окна, которые уже уничтожены при каскадном закрытии (родитель → дочернее). */
|
||||||
|
function broadcastMultiWindowStateChanged(open: boolean): void {
|
||||||
|
for (const w of BrowserWindow.getAllWindows()) {
|
||||||
|
if (w.isDestroyed()) continue;
|
||||||
|
if (w.webContents.isDestroyed()) continue;
|
||||||
|
try {
|
||||||
|
w.webContents.send(ipcChannels.windows.multiWindowStateChanged, { open });
|
||||||
|
} catch {
|
||||||
|
/* окно могло закрыться между проверкой и send */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Разрешает реальное закрытие окна редактора (выход из приложения). */
|
/** Разрешает реальное закрытие окна редактора (выход из приложения). */
|
||||||
export function markAppQuitting(): void {
|
export function markAppQuitting(): void {
|
||||||
appQuitting = true;
|
appQuitting = true;
|
||||||
@@ -54,82 +70,15 @@ function getPreloadPath(): string {
|
|||||||
return path.join(app.getAppPath(), 'dist', 'preload', 'index.cjs');
|
return path.join(app.getAppPath(), 'dist', 'preload', 'index.cjs');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** macOS: в Dock — тот же растр, что и у окон (ICO/PNG из brandingIcon). */
|
||||||
* PNG для иконки окна / дока: тот же растр, что electron-builder берёт из `build/icon.png`
|
|
||||||
* (копия в dist после сборки), затем окно 256px, затем dev-пути. SVG не используем для
|
|
||||||
* nativeImage на Windows — иначе пустая картинка и дефолтная иконка Electron вместо exe.
|
|
||||||
*/
|
|
||||||
function resolveBrandingPngPaths(): string[] {
|
|
||||||
const root = app.getAppPath();
|
|
||||||
return [
|
|
||||||
path.join(root, 'dist', 'renderer', 'app-pack-icon.png'),
|
|
||||||
path.join(root, 'dist', 'renderer', 'app-window-icon.png'),
|
|
||||||
path.join(root, 'build', 'icon.png'),
|
|
||||||
path.join(root, 'app', 'renderer', 'public', 'app-window-icon.png'),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveWindowIconPath(): string | undefined {
|
|
||||||
for (const p of resolveBrandingPngPaths()) {
|
|
||||||
try {
|
|
||||||
if (fs.existsSync(p)) return p;
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const root = app.getAppPath();
|
|
||||||
const svgFallback = [
|
|
||||||
path.join(root, 'dist', 'renderer', 'app-logo.svg'),
|
|
||||||
path.join(root, 'app', 'renderer', 'public', 'app-logo.svg'),
|
|
||||||
];
|
|
||||||
for (const p of svgFallback) {
|
|
||||||
try {
|
|
||||||
if (fs.existsSync(p)) return p;
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveWindowIcon(): Electron.NativeImage | undefined {
|
|
||||||
const tryPath = (filePath: string): Electron.NativeImage | undefined => {
|
|
||||||
try {
|
|
||||||
const img = nativeImage.createFromPath(filePath);
|
|
||||||
if (!img.isEmpty()) return img;
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
if (process.platform === 'win32' || process.platform === 'linux') {
|
|
||||||
for (const p of resolveBrandingPngPaths()) {
|
|
||||||
if (!fs.existsSync(p)) continue;
|
|
||||||
const img = tryPath(p);
|
|
||||||
if (img) return img;
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
const p = resolveWindowIconPath();
|
|
||||||
if (!p) return undefined;
|
|
||||||
return tryPath(p);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** macOS: в Dock показываем тот же PNG, что и у упакованного приложения на Windows (иконка exe). */
|
|
||||||
export function applyDockIconIfNeeded(): void {
|
export function applyDockIconIfNeeded(): void {
|
||||||
if (process.platform !== 'darwin' || !app.dock) return;
|
if (process.platform !== 'darwin' || !app.dock) return;
|
||||||
for (const p of resolveBrandingPngPaths()) {
|
const icon = loadBrandingWindowIcon();
|
||||||
if (!fs.existsSync(p)) continue;
|
if (!icon || icon.isEmpty()) return;
|
||||||
try {
|
try {
|
||||||
const img = nativeImage.createFromPath(p);
|
app.dock.setIcon(icon);
|
||||||
if (img.isEmpty()) continue;
|
} catch {
|
||||||
app.dock.setIcon(img);
|
/* ignore */
|
||||||
return;
|
|
||||||
} catch {
|
|
||||||
/* try next */
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,7 +114,7 @@ function ensureWindowBecomesVisible(win: BrowserWindow): void {
|
|||||||
|
|
||||||
function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow {
|
function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow {
|
||||||
const deferEditor = kind === 'editor' && opts?.deferVisibility === true;
|
const deferEditor = kind === 'editor' && opts?.deferVisibility === true;
|
||||||
const icon = resolveWindowIcon();
|
const icon = loadBrandingWindowIcon();
|
||||||
const win = new BrowserWindow({
|
const win = new BrowserWindow({
|
||||||
width: kind === 'editor' ? 1280 : kind === 'control' ? 1200 : 1280,
|
width: kind === 'editor' ? 1280 : kind === 'control' ? 1200 : 1280,
|
||||||
height: 800,
|
height: 800,
|
||||||
@@ -184,6 +133,15 @@ function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow
|
|||||||
webSecurity: Boolean(process.env.VITE_DEV_SERVER_URL),
|
webSecurity: Boolean(process.env.VITE_DEV_SERVER_URL),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
if (icon) {
|
||||||
|
try {
|
||||||
|
win.setIcon(icon);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
win.setTitle(windowChromeTitle(kind, app.getLocale()));
|
||||||
|
|
||||||
win.webContents.on('preload-error', (_event, preloadPath, error) => {
|
win.webContents.on('preload-error', (_event, preloadPath, error) => {
|
||||||
console.error(`[preload-error] ${preloadPath}:`, error);
|
console.error(`[preload-error] ${preloadPath}:`, error);
|
||||||
@@ -207,6 +165,11 @@ function createWindow(kind: WindowKind, opts?: CreateWindowOpts): BrowserWindow
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
win.on('closed', () => windows.delete(kind));
|
win.on('closed', () => windows.delete(kind));
|
||||||
|
win.on('closed', () => {
|
||||||
|
if (kind !== 'presentation' && kind !== 'control') return;
|
||||||
|
const open = windows.has('presentation') || windows.has('control');
|
||||||
|
broadcastMultiWindowStateChanged(open);
|
||||||
|
});
|
||||||
windows.set(kind, win);
|
windows.set(kind, win);
|
||||||
return win;
|
return win;
|
||||||
}
|
}
|
||||||
@@ -279,8 +242,11 @@ export function openMultiWindow() {
|
|||||||
presentation.maximize();
|
presentation.maximize();
|
||||||
}
|
}
|
||||||
if (!windows.has('control')) {
|
if (!windows.has('control')) {
|
||||||
createWindow('control', { parent: presentation });
|
// macOS: parent-child window binding moves child with the parent (unlike Windows behavior we want).
|
||||||
|
// Keep control window independent on darwin.
|
||||||
|
createWindow('control', process.platform === 'darwin' ? undefined : { parent: presentation });
|
||||||
}
|
}
|
||||||
|
broadcastMultiWindowStateChanged(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function closeMultiWindow(): void {
|
export function closeMultiWindow(): void {
|
||||||
@@ -290,6 +256,10 @@ export function closeMultiWindow(): void {
|
|||||||
if (ctrl) ctrl.close();
|
if (ctrl) ctrl.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isMultiWindowOpen(): boolean {
|
||||||
|
return windows.has('presentation') || windows.has('control');
|
||||||
|
}
|
||||||
|
|
||||||
export function togglePresentationFullscreen(): boolean {
|
export function togglePresentationFullscreen(): boolean {
|
||||||
const pres = windows.get('presentation');
|
const pres = windows.get('presentation');
|
||||||
if (!pres) return false;
|
if (!pres) return false;
|
||||||
|
|||||||
@@ -113,7 +113,7 @@
|
|||||||
<div class="wrap">
|
<div class="wrap">
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<img class="logo" src="./app-window-icon.png" width="72" height="72" alt="" />
|
<img class="logo" src="./app-window-icon.png" width="72" height="72" alt="" />
|
||||||
<h1 class="title" data-boot-title>DNDGamePlayer</h1>
|
<h1 class="title" data-boot-title>TTRPG Player</h1>
|
||||||
<p class="subtitle">редактор и проигрыватель</p>
|
<p class="subtitle">редактор и проигрыватель</p>
|
||||||
<p class="version" data-boot-version></p>
|
<p class="version" data-boot-version></p>
|
||||||
<p class="status" id="boot-status">Запуск…</p>
|
<p class="status" id="boot-status">Запуск…</p>
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<link rel="icon" href="/app-window-icon.png" type="image/png" />
|
<link rel="icon" href="/app-window-icon.png" type="image/png" />
|
||||||
<title>DnD Player — Control</title>
|
<title>TTRPG - Control</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { pickEraseTargetId } from '../../shared/effectEraserHitTest';
|
|||||||
import { ipcChannels } from '../../shared/ipc/contracts';
|
import { ipcChannels } from '../../shared/ipc/contracts';
|
||||||
import type { SessionState } from '../../shared/ipc/contracts';
|
import type { SessionState } from '../../shared/ipc/contracts';
|
||||||
import type { GraphNodeId, Scene, SceneId } from '../../shared/types';
|
import type { GraphNodeId, Scene, SceneId } from '../../shared/types';
|
||||||
|
import { useEditorI18n } from '../editor/i18n/EditorI18nContext';
|
||||||
import { getDndApi } from '../shared/dndApi';
|
import { getDndApi } from '../shared/dndApi';
|
||||||
import { PixiEffectsOverlay } from '../shared/effects/PxiEffectsOverlay';
|
import { PixiEffectsOverlay } from '../shared/effects/PxiEffectsOverlay';
|
||||||
import { useEffectsState } from '../shared/effects/useEffectsState';
|
import { useEffectsState } from '../shared/effects/useEffectsState';
|
||||||
@@ -44,6 +45,9 @@ function playLightningEffectSound(): void {
|
|||||||
|
|
||||||
export function ControlApp() {
|
export function ControlApp() {
|
||||||
const api = getDndApi();
|
const api = getDndApi();
|
||||||
|
const { t } = useEditorI18n();
|
||||||
|
const tRef = useRef(t);
|
||||||
|
tRef.current = t;
|
||||||
const [fxState, fx] = useEffectsState();
|
const [fxState, fx] = useEffectsState();
|
||||||
const [session, setSession] = useState<SessionState | null>(null);
|
const [session, setSession] = useState<SessionState | null>(null);
|
||||||
const historyRef = useRef<GraphNodeId[]>([]);
|
const historyRef = useRef<GraphNodeId[]>([]);
|
||||||
@@ -278,8 +282,7 @@ export function ControlApp() {
|
|||||||
const m = sceneAudioMetaRef.current.get(ref.assetId) ?? { lastPlayError: null };
|
const m = sceneAudioMetaRef.current.get(ref.assetId) ?? { lastPlayError: null };
|
||||||
sceneAudioMetaRef.current.set(ref.assetId, {
|
sceneAudioMetaRef.current.set(ref.assetId, {
|
||||||
...m,
|
...m,
|
||||||
lastPlayError:
|
lastPlayError: tRef.current('control.audioAutoplayBlocked'),
|
||||||
'Автозапуск заблокирован (нужно действие пользователя) или ошибка воспроизведения.',
|
|
||||||
});
|
});
|
||||||
setSceneAudioStateTick((x) => x + 1);
|
setSceneAudioStateTick((x) => x + 1);
|
||||||
try {
|
try {
|
||||||
@@ -382,8 +385,7 @@ export function ControlApp() {
|
|||||||
const m = campaignAudioMetaRef.current.get(ref.assetId) ?? { lastPlayError: null };
|
const m = campaignAudioMetaRef.current.get(ref.assetId) ?? { lastPlayError: null };
|
||||||
campaignAudioMetaRef.current.set(ref.assetId, {
|
campaignAudioMetaRef.current.set(ref.assetId, {
|
||||||
...m,
|
...m,
|
||||||
lastPlayError:
|
lastPlayError: tRef.current('control.audioAutoplayBlocked'),
|
||||||
'Автозапуск заблокирован (нужно действие пользователя) или ошибка воспроизведения.',
|
|
||||||
});
|
});
|
||||||
setCampaignAudioStateTick((x) => x + 1);
|
setCampaignAudioStateTick((x) => x + 1);
|
||||||
try {
|
try {
|
||||||
@@ -546,21 +548,21 @@ export function ControlApp() {
|
|||||||
group === 'scene'
|
group === 'scene'
|
||||||
? (sceneAudioElsRef.current.get(assetId) ?? null)
|
? (sceneAudioElsRef.current.get(assetId) ?? null)
|
||||||
: (campaignAudioElsRef.current.get(assetId) ?? null);
|
: (campaignAudioElsRef.current.get(assetId) ?? null);
|
||||||
if (!el) return { label: 'URL не получен', detail: 'Не удалось получить dnd://asset URL для аудио.' };
|
if (!el) return { label: t('control.audioNoUrl'), detail: t('control.audioNoUrlDetail') };
|
||||||
const meta =
|
const meta =
|
||||||
group === 'scene'
|
group === 'scene'
|
||||||
? (sceneAudioMetaRef.current.get(assetId) ?? { lastPlayError: null })
|
? (sceneAudioMetaRef.current.get(assetId) ?? { lastPlayError: null })
|
||||||
: (campaignAudioMetaRef.current.get(assetId) ?? { lastPlayError: null });
|
: (campaignAudioMetaRef.current.get(assetId) ?? { lastPlayError: null });
|
||||||
if (meta.lastPlayError) return { label: 'Ошибка/блок', detail: meta.lastPlayError };
|
if (meta.lastPlayError) return { label: t('control.audioBlocked'), detail: meta.lastPlayError };
|
||||||
if (el.error)
|
if (el.error)
|
||||||
return {
|
return {
|
||||||
label: 'Ошибка',
|
label: t('control.audioError'),
|
||||||
detail: `MediaError code=${String(el.error.code)} (1=ABORTED, 2=NETWORK, 3=DECODE, 4=SRC_NOT_SUPPORTED)`,
|
detail: t('control.audioMediaError', { code: String(el.error.code) }),
|
||||||
};
|
};
|
||||||
if (el.readyState < 2) return { label: 'Загрузка…' };
|
if (el.readyState < 2) return { label: t('control.audioLoading') };
|
||||||
if (!el.paused) return { label: 'Играет' };
|
if (!el.paused) return { label: t('control.audioPlaying') };
|
||||||
if (el.currentTime > 0) return { label: 'Пауза' };
|
if (el.currentTime > 0) return { label: t('control.audioPaused') };
|
||||||
return { label: 'Остановлено' };
|
return { label: t('control.audioStopped') };
|
||||||
}
|
}
|
||||||
const nextScenes = useMemo(() => {
|
const nextScenes = useMemo(() => {
|
||||||
if (!project) return [];
|
if (!project) return [];
|
||||||
@@ -955,21 +957,21 @@ export function ControlApp() {
|
|||||||
return (
|
return (
|
||||||
<div className={styles.page}>
|
<div className={styles.page}>
|
||||||
<Surface className={styles.remote}>
|
<Surface className={styles.remote}>
|
||||||
<div className={styles.remoteTitle}>ПУЛЬТ УПРАВЛЕНИЯ</div>
|
<div className={styles.remoteTitle}>{t('control.remoteTitle')}</div>
|
||||||
<div className={styles.spacer12} />
|
<div className={styles.spacer12} />
|
||||||
{!isVideoPreviewScene ? (
|
{!isVideoPreviewScene ? (
|
||||||
<>
|
<>
|
||||||
<div className={styles.sectionLabel}>ЭФФЕКТЫ</div>
|
<div className={styles.sectionLabel}>{t('control.effects')}</div>
|
||||||
<div className={styles.spacer8} />
|
<div className={styles.spacer8} />
|
||||||
<div className={styles.effectsStack}>
|
<div className={styles.effectsStack}>
|
||||||
<div className={styles.effectsGroup}>
|
<div className={styles.effectsGroup}>
|
||||||
<div className={styles.subsectionLabel}>Инструменты</div>
|
<div className={styles.subsectionLabel}>{t('control.tools')}</div>
|
||||||
<div className={styles.iconRow}>
|
<div className={styles.iconRow}>
|
||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'eraser' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'eraser' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Ластик"
|
title={t('control.eraser')}
|
||||||
ariaLabel="Ластик"
|
ariaLabel={t('control.eraser')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'eraser' } })}
|
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'eraser' } })}
|
||||||
>
|
>
|
||||||
<span className={styles.iconGlyph}>🧹</span>
|
<span className={styles.iconGlyph}>🧹</span>
|
||||||
@@ -977,8 +979,8 @@ export function ControlApp() {
|
|||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Очистить эффекты"
|
title={t('control.clearEffects')}
|
||||||
ariaLabel="Очистить эффекты"
|
ariaLabel={t('control.clearEffects')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'instances.clear' })}
|
onClick={() => void fx.dispatch({ kind: 'instances.clear' })}
|
||||||
>
|
>
|
||||||
<span className={styles.clearIcon}>
|
<span className={styles.clearIcon}>
|
||||||
@@ -999,13 +1001,13 @@ export function ControlApp() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.effectsGroup}>
|
<div className={styles.effectsGroup}>
|
||||||
<div className={styles.subsectionLabel}>Эффекты поля</div>
|
<div className={styles.subsectionLabel}>{t('control.fieldEffects')}</div>
|
||||||
<div className={styles.iconRow}>
|
<div className={styles.iconRow}>
|
||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'fog' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'fog' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Туман"
|
title={t('control.fog')}
|
||||||
ariaLabel="Туман"
|
ariaLabel={t('control.fog')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'fog' } })}
|
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'fog' } })}
|
||||||
>
|
>
|
||||||
<span className={styles.iconGlyph}>🌫️</span>
|
<span className={styles.iconGlyph}>🌫️</span>
|
||||||
@@ -1013,8 +1015,8 @@ export function ControlApp() {
|
|||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'rain' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'rain' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Дождь"
|
title={t('control.rain')}
|
||||||
ariaLabel="Дождь"
|
ariaLabel={t('control.rain')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'rain' } })}
|
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'rain' } })}
|
||||||
>
|
>
|
||||||
<span className={styles.iconGlyph}>🌧️</span>
|
<span className={styles.iconGlyph}>🌧️</span>
|
||||||
@@ -1022,8 +1024,8 @@ export function ControlApp() {
|
|||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'fire' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'fire' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Огонь"
|
title={t('control.fire')}
|
||||||
ariaLabel="Огонь"
|
ariaLabel={t('control.fire')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'fire' } })}
|
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'fire' } })}
|
||||||
>
|
>
|
||||||
<span className={styles.iconGlyph}>🔥</span>
|
<span className={styles.iconGlyph}>🔥</span>
|
||||||
@@ -1031,8 +1033,8 @@ export function ControlApp() {
|
|||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'water' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'water' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Вода"
|
title={t('control.water')}
|
||||||
ariaLabel="Вода"
|
ariaLabel={t('control.water')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'water' } })}
|
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'water' } })}
|
||||||
>
|
>
|
||||||
<span className={styles.iconGlyph}>💧</span>
|
<span className={styles.iconGlyph}>💧</span>
|
||||||
@@ -1040,13 +1042,13 @@ export function ControlApp() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.effectsGroup}>
|
<div className={styles.effectsGroup}>
|
||||||
<div className={styles.subsectionLabel}>Эффекты действий</div>
|
<div className={styles.subsectionLabel}>{t('control.actionEffects')}</div>
|
||||||
<div className={styles.iconRow}>
|
<div className={styles.iconRow}>
|
||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'lightning' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'lightning' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Молния"
|
title={t('control.lightning')}
|
||||||
ariaLabel="Молния"
|
ariaLabel={t('control.lightning')}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'lightning' } })
|
void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'lightning' } })
|
||||||
}
|
}
|
||||||
@@ -1056,8 +1058,8 @@ export function ControlApp() {
|
|||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'sunbeam' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'sunbeam' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Луч света"
|
title={t('control.sunbeam')}
|
||||||
ariaLabel="Луч света"
|
ariaLabel={t('control.sunbeam')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'sunbeam' } })}
|
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'sunbeam' } })}
|
||||||
>
|
>
|
||||||
<span className={styles.iconGlyph}>☀️</span>
|
<span className={styles.iconGlyph}>☀️</span>
|
||||||
@@ -1065,8 +1067,8 @@ export function ControlApp() {
|
|||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'freeze' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'freeze' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Заморозка"
|
title={t('control.freeze')}
|
||||||
ariaLabel="Заморозка"
|
ariaLabel={t('control.freeze')}
|
||||||
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'freeze' } })}
|
onClick={() => void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'freeze' } })}
|
||||||
>
|
>
|
||||||
<span className={styles.iconGlyph}>❄️</span>
|
<span className={styles.iconGlyph}>❄️</span>
|
||||||
@@ -1074,8 +1076,8 @@ export function ControlApp() {
|
|||||||
<Button
|
<Button
|
||||||
variant={tool.tool === 'poisonCloud' ? 'primary' : 'ghost'}
|
variant={tool.tool === 'poisonCloud' ? 'primary' : 'ghost'}
|
||||||
iconOnly
|
iconOnly
|
||||||
title="Облако яда"
|
title={t('control.poisonCloud')}
|
||||||
ariaLabel="Облако яда"
|
ariaLabel={t('control.poisonCloud')}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'poisonCloud' } })
|
void fx.dispatch({ kind: 'tool.set', tool: { ...tool, tool: 'poisonCloud' } })
|
||||||
}
|
}
|
||||||
@@ -1085,7 +1087,7 @@ export function ControlApp() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.radiusRow}>
|
<div className={styles.radiusRow}>
|
||||||
<div className={styles.radiusLabel}>Радиус кисти</div>
|
<div className={styles.radiusLabel}>{t('control.brushRadius')}</div>
|
||||||
<input
|
<input
|
||||||
type="range"
|
type="range"
|
||||||
min={0.015}
|
min={0.015}
|
||||||
@@ -1098,7 +1100,7 @@ export function ControlApp() {
|
|||||||
void fx.dispatch({ kind: 'tool.set', tool: { ...tool, radiusN: next } });
|
void fx.dispatch({ kind: 'tool.set', tool: { ...tool, radiusN: next } });
|
||||||
}}
|
}}
|
||||||
className={styles.range}
|
className={styles.range}
|
||||||
aria-label="Радиус кисти"
|
aria-label={t('control.brushRadius')}
|
||||||
/>
|
/>
|
||||||
<div className={styles.radiusValue}>{Math.round(tool.radiusN * 100)}</div>
|
<div className={styles.radiusValue}>{Math.round(tool.radiusN * 100)}</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -1107,7 +1109,7 @@ export function ControlApp() {
|
|||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
<div className={styles.storyWrap}>
|
<div className={styles.storyWrap}>
|
||||||
<div className={styles.sectionLabel}>СЮЖЕТНАЯ ЛИНИЯ</div>
|
<div className={styles.sectionLabel}>{t('control.storyLine')}</div>
|
||||||
<div className={styles.spacer10} />
|
<div className={styles.spacer10} />
|
||||||
<div className={styles.storyScroll}>
|
<div className={styles.storyScroll}>
|
||||||
{history.map((gnId, idx) => {
|
{history.map((gnId, idx) => {
|
||||||
@@ -1122,7 +1124,7 @@ export function ControlApp() {
|
|||||||
className={[styles.historyBtn, isCurrent ? styles.historyBtnCurrent : '']
|
className={[styles.historyBtn, isCurrent ? styles.historyBtnCurrent : '']
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(' ')}
|
.join(' ')}
|
||||||
title={project && !isCurrent ? 'Перейти к этой сцене' : undefined}
|
title={project && !isCurrent ? t('control.gotoScene') : undefined}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!project) return;
|
if (!project) return;
|
||||||
if (isCurrent) return;
|
if (isCurrent) return;
|
||||||
@@ -1132,15 +1134,17 @@ export function ControlApp() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{isCurrent ? (
|
{isCurrent ? (
|
||||||
<div className={styles.historyBadge}>ТЕКУЩАЯ СЦЕНА</div>
|
<div className={styles.historyBadge}>{t('control.currentSceneBadge')}</div>
|
||||||
) : (
|
) : (
|
||||||
<div className={styles.historyMuted}>Пройдено</div>
|
<div className={styles.historyMuted}>{t('control.passed')}</div>
|
||||||
)}
|
)}
|
||||||
<div className={styles.historyTitle}>{s?.title ?? (gn ? String(gn.sceneId) : gnId)}</div>
|
<div className={styles.historyTitle}>{s?.title ?? (gn ? String(gn.sceneId) : gnId)}</div>
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
{history.length === 0 ? <div className={styles.emptyStory}>Нет активной сцены.</div> : null}
|
{history.length === 0 ? (
|
||||||
|
<div className={styles.emptyStory}>{t('control.noActiveScene')}</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Surface>
|
</Surface>
|
||||||
@@ -1148,20 +1152,15 @@ export function ControlApp() {
|
|||||||
<div className={styles.rightStack}>
|
<div className={styles.rightStack}>
|
||||||
<Surface className={styles.surfacePad}>
|
<Surface className={styles.surfacePad}>
|
||||||
<div className={styles.previewHeader}>
|
<div className={styles.previewHeader}>
|
||||||
<div className={styles.previewTitle}>Предпросмотр экрана</div>
|
<div className={styles.previewTitle}>{t('control.screenPreview')}</div>
|
||||||
<div className={styles.previewActions}>
|
<div className={styles.previewActions}>
|
||||||
<Button onClick={() => void api.invoke(ipcChannels.windows.closeMultiWindow, {})}>
|
<Button onClick={() => void api.invoke(ipcChannels.windows.closeMultiWindow, {})}>
|
||||||
Выключить демонстрацию
|
{t('control.stopPresentation')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.spacer10} />
|
<div className={styles.spacer10} />
|
||||||
{isVideoPreviewScene ? (
|
{isVideoPreviewScene ? <div className={styles.videoHint}>{t('control.videoBrushHint')}</div> : null}
|
||||||
<div className={styles.videoHint}>
|
|
||||||
Видео-превью: кисть эффектов отключена (как на экране демонстрации — оверлей только для
|
|
||||||
изображения).
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
<div className={styles.spacer10} />
|
<div className={styles.spacer10} />
|
||||||
<div className={styles.previewFrame}>
|
<div className={styles.previewFrame}>
|
||||||
<div ref={previewHostRef} className={styles.previewHost}>
|
<div ref={previewHostRef} className={styles.previewHost}>
|
||||||
@@ -1258,33 +1257,33 @@ export function ControlApp() {
|
|||||||
</Surface>
|
</Surface>
|
||||||
|
|
||||||
<Surface className={styles.surfacePad}>
|
<Surface className={styles.surfacePad}>
|
||||||
<div className={styles.branchTitle}>Варианты ветвления</div>
|
<div className={styles.branchTitle}>{t('control.branches')}</div>
|
||||||
<div className={styles.branchGrid}>
|
<div className={styles.branchGrid}>
|
||||||
{nextScenes.map((o, i) => (
|
{nextScenes.map((o, i) => (
|
||||||
<div key={o.graphNodeId} className={styles.branchCard}>
|
<div key={o.graphNodeId} className={styles.branchCard}>
|
||||||
<div className={styles.branchCardHeader}>
|
<div className={styles.branchCardHeader}>
|
||||||
<div className={styles.branchOption}>ОПЦИЯ {String(i + 1)}</div>
|
<div className={styles.branchOption}>{t('control.option', { n: String(i + 1) })}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.branchName}>{o.scene.title || 'Без названия'}</div>
|
<div className={styles.branchName}>{o.scene.title || t('control.unnamed')}</div>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
void api.invoke(ipcChannels.project.setCurrentGraphNode, { graphNodeId: o.graphNodeId })
|
void api.invoke(ipcChannels.project.setCurrentGraphNode, { graphNodeId: o.graphNodeId })
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
Переключить
|
{t('control.switchScene')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
{nextScenes.length === 0 ? (
|
{nextScenes.length === 0 ? (
|
||||||
<div className={styles.branchEmpty}>
|
<div className={styles.branchEmpty}>
|
||||||
<div>Нет вариантов перехода.</div>
|
<div>{t('control.noBranches')}</div>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
disabled={!session?.project?.currentGraphNodeId}
|
disabled={!session?.project?.currentGraphNodeId}
|
||||||
onClick={() => void api.invoke(ipcChannels.windows.closeMultiWindow, {})}
|
onClick={() => void api.invoke(ipcChannels.windows.closeMultiWindow, {})}
|
||||||
>
|
>
|
||||||
Завершить показ
|
{t('control.endPresentation')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -1293,13 +1292,13 @@ export function ControlApp() {
|
|||||||
|
|
||||||
<Surface className={styles.surfacePad}>
|
<Surface className={styles.surfacePad}>
|
||||||
<div className={styles.musicHeader}>
|
<div className={styles.musicHeader}>
|
||||||
<div className={styles.previewTitle}>Музыка</div>
|
<div className={styles.previewTitle}>{t('control.music')}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.spacer10} />
|
<div className={styles.spacer10} />
|
||||||
<div className={styles.sectionLabel}>МУЗЫКА СЦЕНЫ</div>
|
<div className={styles.sectionLabel}>{t('control.sceneMusic')}</div>
|
||||||
<div className={styles.spacer10} />
|
<div className={styles.spacer10} />
|
||||||
{sceneAudios.length === 0 ? (
|
{sceneAudios.length === 0 ? (
|
||||||
<div className={styles.musicEmpty}>В текущей сцене нет аудио.</div>
|
<div className={styles.musicEmpty}>{t('control.noSceneAudio')}</div>
|
||||||
) : null}
|
) : null}
|
||||||
{sceneAudios.length > 0 ? (
|
{sceneAudios.length > 0 ? (
|
||||||
<div className={styles.audioList}>
|
<div className={styles.audioList}>
|
||||||
@@ -1314,8 +1313,8 @@ export function ControlApp() {
|
|||||||
<div className={styles.audioMeta}>
|
<div className={styles.audioMeta}>
|
||||||
<div className={styles.audioName}>{asset.originalName}</div>
|
<div className={styles.audioName}>{asset.originalName}</div>
|
||||||
<div className={styles.audioBadges}>
|
<div className={styles.audioBadges}>
|
||||||
<div>{ref.autoplay ? 'Авто' : 'Ручн.'}</div>
|
<div>{ref.autoplay ? t('control.modeAuto') : t('control.modeManual')}</div>
|
||||||
<div>{ref.loop ? 'Цикл' : 'Один раз'}</div>
|
<div>{ref.loop ? t('control.loop') : t('control.once')}</div>
|
||||||
<div title={st.detail}>{st.label}</div>
|
<div title={st.detail}>{st.label}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.spacer10} />
|
<div className={styles.spacer10} />
|
||||||
@@ -1344,7 +1343,7 @@ export function ControlApp() {
|
|||||||
styles.audioScrub,
|
styles.audioScrub,
|
||||||
dur > 0 ? styles.audioScrubPointer : styles.audioScrubDefault,
|
dur > 0 ? styles.audioScrubPointer : styles.audioScrubDefault,
|
||||||
].join(' ')}
|
].join(' ')}
|
||||||
title={dur > 0 ? 'Клик — перемотка' : 'Длительность неизвестна'}
|
title={dur > 0 ? t('control.scrubSeek') : t('control.durationUnknown')}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className={styles.scrubFill}
|
className={styles.scrubFill}
|
||||||
@@ -1369,7 +1368,7 @@ export function ControlApp() {
|
|||||||
({ lastPlayError: null } as const);
|
({ lastPlayError: null } as const);
|
||||||
sceneAudioMetaRef.current.set(ref.assetId, {
|
sceneAudioMetaRef.current.set(ref.assetId, {
|
||||||
...mm,
|
...mm,
|
||||||
lastPlayError: 'Не удалось запустить.',
|
lastPlayError: t('control.playFailed'),
|
||||||
});
|
});
|
||||||
setSceneAudioStateTick((x) => x + 1);
|
setSceneAudioStateTick((x) => x + 1);
|
||||||
});
|
});
|
||||||
@@ -1403,10 +1402,10 @@ export function ControlApp() {
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<div className={styles.spacer12} />
|
<div className={styles.spacer12} />
|
||||||
<div className={styles.sectionLabel}>МУЗЫКА ИГРЫ</div>
|
<div className={styles.sectionLabel}>{t('control.gameMusic')}</div>
|
||||||
<div className={styles.spacer10} />
|
<div className={styles.spacer10} />
|
||||||
{campaignAudios.length === 0 ? (
|
{campaignAudios.length === 0 ? (
|
||||||
<div className={styles.musicEmpty}>В игре нет аудио.</div>
|
<div className={styles.musicEmpty}>{t('control.noGameAudio')}</div>
|
||||||
) : (
|
) : (
|
||||||
<div className={styles.audioList}>
|
<div className={styles.audioList}>
|
||||||
{campaignAudios.map(({ ref, asset }) => {
|
{campaignAudios.map(({ ref, asset }) => {
|
||||||
@@ -1420,10 +1419,12 @@ export function ControlApp() {
|
|||||||
<div className={styles.audioMeta}>
|
<div className={styles.audioMeta}>
|
||||||
<div className={styles.audioName}>{asset.originalName}</div>
|
<div className={styles.audioName}>{asset.originalName}</div>
|
||||||
<div className={styles.audioBadges}>
|
<div className={styles.audioBadges}>
|
||||||
<div>{ref.autoplay ? 'Авто' : 'Ручн.'}</div>
|
<div>{ref.autoplay ? t('control.modeAuto') : t('control.modeManual')}</div>
|
||||||
<div>{ref.loop ? 'Цикл' : 'Один раз'}</div>
|
<div>{ref.loop ? t('control.loop') : t('control.once')}</div>
|
||||||
<div title={st.detail}>{st.label}</div>
|
<div title={st.detail}>{st.label}</div>
|
||||||
{!allowCampaignAudio ? <div title="В сцене есть музыка">Пауза (сцена)</div> : null}
|
{!allowCampaignAudio ? (
|
||||||
|
<div title={t('control.pauseSceneMusicTitle')}>{t('control.pauseSceneMusic')}</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.spacer10} />
|
<div className={styles.spacer10} />
|
||||||
<div
|
<div
|
||||||
@@ -1451,7 +1452,7 @@ export function ControlApp() {
|
|||||||
styles.audioScrub,
|
styles.audioScrub,
|
||||||
dur > 0 ? styles.audioScrubPointer : styles.audioScrubDefault,
|
dur > 0 ? styles.audioScrubPointer : styles.audioScrubDefault,
|
||||||
].join(' ')}
|
].join(' ')}
|
||||||
title={dur > 0 ? 'Клик — перемотка' : 'Длительность неизвестна'}
|
title={dur > 0 ? t('control.scrubSeek') : t('control.durationUnknown')}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className={styles.scrubFill}
|
className={styles.scrubFill}
|
||||||
@@ -1466,7 +1467,7 @@ export function ControlApp() {
|
|||||||
<div className={styles.audioTransport}>
|
<div className={styles.audioTransport}>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
title={!allowCampaignAudio ? 'Пауза: в сцене есть музыка' : undefined}
|
title={!allowCampaignAudio ? t('control.pauseCampaignTitle') : undefined}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!el) return;
|
if (!el) return;
|
||||||
const m = campaignAudioMetaRef.current.get(ref.assetId) ?? { lastPlayError: null };
|
const m = campaignAudioMetaRef.current.get(ref.assetId) ?? { lastPlayError: null };
|
||||||
@@ -1484,7 +1485,7 @@ export function ControlApp() {
|
|||||||
({ lastPlayError: null } as const);
|
({ lastPlayError: null } as const);
|
||||||
campaignAudioMetaRef.current.set(ref.assetId, {
|
campaignAudioMetaRef.current.set(ref.assetId, {
|
||||||
...mm,
|
...mm,
|
||||||
lastPlayError: 'Не удалось запустить.',
|
lastPlayError: t('control.playFailed'),
|
||||||
});
|
});
|
||||||
setCampaignAudioStateTick((x) => x + 1);
|
setCampaignAudioStateTick((x) => x + 1);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import React, { useEffect, useMemo, useState } from 'react';
|
|||||||
|
|
||||||
import { computeTimeSec } from '../../main/video/videoPlaybackStore';
|
import { computeTimeSec } from '../../main/video/videoPlaybackStore';
|
||||||
import type { SessionState } from '../../shared/ipc/contracts';
|
import type { SessionState } from '../../shared/ipc/contracts';
|
||||||
|
import { useEditorI18n } from '../editor/i18n/EditorI18nContext';
|
||||||
import { RotatedImage } from '../shared/RotatedImage';
|
import { RotatedImage } from '../shared/RotatedImage';
|
||||||
import { useAssetUrl } from '../shared/useAssetImageUrl';
|
import { useAssetUrl } from '../shared/useAssetImageUrl';
|
||||||
import { useVideoPlaybackState } from '../shared/video/useVideoPlaybackState';
|
import { useVideoPlaybackState } from '../shared/video/useVideoPlaybackState';
|
||||||
@@ -23,6 +24,7 @@ function fmt(sec: number): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function ControlScenePreview({ session, videoRef, onContentRectChange }: Props) {
|
export function ControlScenePreview({ session, videoRef, onContentRectChange }: Props) {
|
||||||
|
const { t } = useEditorI18n();
|
||||||
const [vp, video] = useVideoPlaybackState();
|
const [vp, video] = useVideoPlaybackState();
|
||||||
const scene =
|
const scene =
|
||||||
session?.project && session.currentSceneId ? session.project.scenes[session.currentSceneId] : undefined;
|
session?.project && session.currentSceneId ? session.project.scenes[session.currentSceneId] : undefined;
|
||||||
@@ -102,7 +104,7 @@ export function ControlScenePreview({ session, videoRef, onContentRectChange }:
|
|||||||
onTimeUpdate={() => setTick((x) => x + 1)}
|
onTimeUpdate={() => setTick((x) => x + 1)}
|
||||||
onLoadedMetadata={() => setTick((x) => x + 1)}
|
onLoadedMetadata={() => setTick((x) => x + 1)}
|
||||||
>
|
>
|
||||||
<track kind="captions" srcLang="ru" label="Превью без субтитров" />
|
<track kind="captions" srcLang="ru" label={t('control.previewTrackLabel')} />
|
||||||
</video>
|
</video>
|
||||||
) : (
|
) : (
|
||||||
<div className={styles.placeholder} />
|
<div className={styles.placeholder} />
|
||||||
@@ -132,7 +134,7 @@ export function ControlScenePreview({ session, videoRef, onContentRectChange }:
|
|||||||
void video.dispatch({ kind: 'seek', timeSec: Math.min(dur, cur + 5) });
|
void video.dispatch({ kind: 'seek', timeSec: Math.min(dur, cur + 5) });
|
||||||
if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') setTick((x) => x + 1);
|
if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') setTick((x) => x + 1);
|
||||||
}}
|
}}
|
||||||
title="Клик — перемотка"
|
title={t('control.scrubSeek')}
|
||||||
>
|
>
|
||||||
<div className={styles.scrubFill} style={{ width: `${String(Math.round(pct * 100))}%` }} />
|
<div className={styles.scrubFill} style={{ width: `${String(Math.round(pct * 100))}%` }} />
|
||||||
</div>
|
</div>
|
||||||
@@ -142,7 +144,7 @@ export function ControlScenePreview({ session, videoRef, onContentRectChange }:
|
|||||||
type="button"
|
type="button"
|
||||||
className={styles.transportBtn}
|
className={styles.transportBtn}
|
||||||
onClick={() => void video.dispatch({ kind: 'play' })}
|
onClick={() => void video.dispatch({ kind: 'play' })}
|
||||||
title="Play"
|
title={t('control.transportPlay')}
|
||||||
>
|
>
|
||||||
▶
|
▶
|
||||||
</button>
|
</button>
|
||||||
@@ -150,7 +152,7 @@ export function ControlScenePreview({ session, videoRef, onContentRectChange }:
|
|||||||
type="button"
|
type="button"
|
||||||
className={styles.transportBtn}
|
className={styles.transportBtn}
|
||||||
onClick={() => void video.dispatch({ kind: 'pause' })}
|
onClick={() => void video.dispatch({ kind: 'pause' })}
|
||||||
title="Pause"
|
title={t('control.transportPause')}
|
||||||
>
|
>
|
||||||
❚❚
|
❚❚
|
||||||
</button>
|
</button>
|
||||||
@@ -161,7 +163,7 @@ export function ControlScenePreview({ session, videoRef, onContentRectChange }:
|
|||||||
void video.dispatch({ kind: 'stop' });
|
void video.dispatch({ kind: 'stop' });
|
||||||
setTick((x) => x + 1);
|
setTick((x) => x + 1);
|
||||||
}}
|
}}
|
||||||
title="Stop"
|
title={t('control.transportStop')}
|
||||||
>
|
>
|
||||||
■
|
■
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -47,28 +47,28 @@ void test('ControlApp: звук облака яда (public/oblako-yada.mp3)', (
|
|||||||
|
|
||||||
void test('ControlApp: эффекты в пульте, иконки с тултипами и подписью для a11y', () => {
|
void test('ControlApp: эффекты в пульте, иконки с тултипами и подписью для a11y', () => {
|
||||||
const src = readControlApp();
|
const src = readControlApp();
|
||||||
assert.ok(src.includes('ЭФФЕКТЫ'));
|
assert.ok(src.includes("t('control.effects')"));
|
||||||
assert.ok(src.includes('Инструменты'));
|
assert.ok(src.includes("t('control.tools')"));
|
||||||
assert.ok(src.includes('Эффекты поля'));
|
assert.ok(src.includes("t('control.fieldEffects')"));
|
||||||
assert.ok(src.includes('Эффекты действий'));
|
assert.ok(src.includes("t('control.actionEffects')"));
|
||||||
assert.ok(src.includes('Луч света'));
|
assert.ok(src.includes("t('control.sunbeam')"));
|
||||||
assert.ok(src.includes('title="Вода"'));
|
assert.ok(src.includes("title={t('control.water')}"));
|
||||||
assert.ok(src.includes('title="Облако яда"'));
|
assert.ok(src.includes("title={t('control.poisonCloud')}"));
|
||||||
assert.ok(src.includes('title="Туман"'));
|
assert.ok(src.includes("title={t('control.fog')}"));
|
||||||
assert.ok(src.includes('ariaLabel="Туман"'));
|
assert.ok(src.includes("ariaLabel={t('control.fog')}"));
|
||||||
assert.ok(src.includes('iconOnly'));
|
assert.ok(src.includes('iconOnly'));
|
||||||
assert.ok(src.includes('title="Очистить эффекты"'));
|
assert.ok(src.includes("title={t('control.clearEffects')}"));
|
||||||
assert.ok(src.includes('ariaLabel="Очистить эффекты"'));
|
assert.ok(src.includes("ariaLabel={t('control.clearEffects')}"));
|
||||||
assert.ok(src.includes('#e5484d'));
|
assert.ok(src.includes('#e5484d'));
|
||||||
const fx = src.indexOf('ЭФФЕКТЫ');
|
const fx = src.indexOf("t('control.effects')");
|
||||||
const story = src.indexOf('СЮЖЕТНАЯ ЛИНИЯ');
|
const story = src.indexOf("t('control.storyLine')");
|
||||||
assert.ok(fx !== -1 && story !== -1 && fx < story, 'Блок эффектов должен быть выше сюжетной линии');
|
assert.ok(fx !== -1 && story !== -1 && fx < story, 'Блок эффектов должен быть выше сюжетной линии');
|
||||||
});
|
});
|
||||||
|
|
||||||
void test('ControlApp: сюжетная линия — колонка сверху вниз и фон как у карточек ветвления', () => {
|
void test('ControlApp: сюжетная линия — колонка сверху вниз и фон как у карточек ветвления', () => {
|
||||||
const src = readControlApp();
|
const src = readControlApp();
|
||||||
const css = readControlAppCss();
|
const css = readControlAppCss();
|
||||||
const story = src.indexOf('СЮЖЕТНАЯ ЛИНИЯ');
|
const story = src.indexOf("t('control.storyLine')");
|
||||||
assert.ok(story !== -1);
|
assert.ok(story !== -1);
|
||||||
assert.ok(src.includes('className={styles.storyScroll}'));
|
assert.ok(src.includes('className={styles.storyScroll}'));
|
||||||
assert.match(css, /\.storyScroll[\s\S]*?justify-content:\s*flex-start/);
|
assert.match(css, /\.storyScroll[\s\S]*?justify-content:\s*flex-start/);
|
||||||
@@ -86,8 +86,8 @@ void test('ControlApp: слой кисти не использует курсо
|
|||||||
|
|
||||||
void test('ControlApp: радиус кисти не в блоке предпросмотра', () => {
|
void test('ControlApp: радиус кисти не в блоке предпросмотра', () => {
|
||||||
const src = readControlApp();
|
const src = readControlApp();
|
||||||
const previewLabel = src.indexOf('Предпросмотр экрана');
|
const previewLabel = src.indexOf("t('control.screenPreview')");
|
||||||
const radius = src.indexOf('Радиус кисти');
|
const radius = src.indexOf("t('control.brushRadius')");
|
||||||
assert.ok(previewLabel !== -1 && radius !== -1);
|
assert.ok(previewLabel !== -1 && radius !== -1);
|
||||||
assert.ok(
|
assert.ok(
|
||||||
radius < previewLabel,
|
radius < previewLabel,
|
||||||
@@ -97,8 +97,8 @@ void test('ControlApp: радиус кисти не в блоке предпро
|
|||||||
|
|
||||||
void test('ControlApp: музыка разделена на сцену и кампанию', () => {
|
void test('ControlApp: музыка разделена на сцену и кампанию', () => {
|
||||||
const src = readControlApp();
|
const src = readControlApp();
|
||||||
assert.ok(src.includes('МУЗЫКА СЦЕНЫ'));
|
assert.ok(src.includes("t('control.sceneMusic')"));
|
||||||
assert.ok(src.includes('МУЗЫКА ИГРЫ'));
|
assert.ok(src.includes("t('control.gameMusic')"));
|
||||||
// при музыке сцены — кампанию ставим на паузу
|
// при музыке сцены — кампанию ставим на паузу
|
||||||
assert.ok(src.includes('allowCampaignAudio'));
|
assert.ok(src.includes('allowCampaignAudio'));
|
||||||
assert.ok(
|
assert.ok(
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import React from 'react';
|
|||||||
import { createRoot } from 'react-dom/client';
|
import { createRoot } from 'react-dom/client';
|
||||||
|
|
||||||
import '../shared/ui/globals.css';
|
import '../shared/ui/globals.css';
|
||||||
|
import { EditorI18nProvider } from '../editor/i18n/EditorI18nContext';
|
||||||
|
|
||||||
import { ControlApp } from './ControlApp';
|
import { ControlApp } from './ControlApp';
|
||||||
|
|
||||||
const rootEl = document.getElementById('root');
|
const rootEl = document.getElementById('root');
|
||||||
@@ -11,6 +13,8 @@ if (!rootEl) {
|
|||||||
|
|
||||||
createRoot(rootEl).render(
|
createRoot(rootEl).render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<ControlApp />
|
<EditorI18nProvider>
|
||||||
|
<ControlApp />
|
||||||
|
</EditorI18nProvider>
|
||||||
</React.StrictMode>,
|
</React.StrictMode>,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<link rel="icon" href="/app-window-icon.png" type="image/png" />
|
<link rel="icon" href="/app-window-icon.png" type="image/png" />
|
||||||
<title>DnD Player — Editor</title>
|
<title>TTRPG - Editor</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
@@ -134,6 +134,38 @@
|
|||||||
z-index: 10000;
|
z-index: 10000;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.editorLockOverlay {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.35);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
z-index: 11000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editorLockModal {
|
||||||
|
width: min(520px, calc(100vw - 32px));
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 14px;
|
||||||
|
background: rgba(25, 28, 38, 0.92);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||||
|
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.55);
|
||||||
|
display: grid;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editorLockTitle {
|
||||||
|
font-weight: 800;
|
||||||
|
opacity: 0.95;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editorLockText {
|
||||||
|
opacity: 0.85;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
.progressModal {
|
.progressModal {
|
||||||
width: min(520px, calc(100vw - 32px));
|
width: min(520px, calc(100vw - 32px));
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
@@ -211,6 +243,33 @@
|
|||||||
font: inherit;
|
font: inherit;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.fileMenuSubHost {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.fileMenuItemExpand {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.fileMenuSub {
|
||||||
|
position: absolute;
|
||||||
|
left: calc(100% + 6px);
|
||||||
|
top: 0;
|
||||||
|
min-width: 200px;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
border: 1px solid var(--stroke);
|
||||||
|
background: var(--color-surface-elevated-2);
|
||||||
|
box-shadow: var(--shadow-lg);
|
||||||
|
padding: 6px;
|
||||||
|
display: grid;
|
||||||
|
gap: 4px;
|
||||||
|
z-index: calc(var(--z-file-menu) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
.modalBackdrop {
|
.modalBackdrop {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
inset: 0;
|
inset: 0;
|
||||||
@@ -462,6 +521,51 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.previewFill {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.previewBusyOverlay {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.55);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.previewBusyModal {
|
||||||
|
display: grid;
|
||||||
|
justify-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
color: var(--text1);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.previewBusyText {
|
||||||
|
font-size: var(--text-xs);
|
||||||
|
font-weight: 700;
|
||||||
|
color: rgba(255, 255, 255, 0.92);
|
||||||
|
}
|
||||||
|
|
||||||
|
.previewSpinner {
|
||||||
|
width: 26px;
|
||||||
|
height: 26px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 3px solid rgba(255, 255, 255, 0.25);
|
||||||
|
border-top-color: rgba(255, 255, 255, 0.9);
|
||||||
|
animation: previewSpin 0.9s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes previewSpin {
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.videoCover {
|
.videoCover {
|
||||||
|
|||||||
+710
-143
File diff suppressed because it is too large
Load Diff
@@ -20,8 +20,10 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.cardActive {
|
.cardActive {
|
||||||
border-color: var(--graph-node-active-border);
|
border-color: rgba(167, 139, 250, 0.95);
|
||||||
box-shadow: 0 25px 50px -12px rgba(139, 92, 246, 0.1);
|
box-shadow:
|
||||||
|
0 0 0 2px rgba(167, 139, 250, 0.35),
|
||||||
|
0 25px 50px -12px rgba(167, 139, 250, 0.12);
|
||||||
}
|
}
|
||||||
|
|
||||||
.previewShell {
|
.previewShell {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
|
||||||
import { createPortal } from 'react-dom';
|
import { createPortal } from 'react-dom';
|
||||||
import ReactFlow, {
|
import ReactFlow, {
|
||||||
Background,
|
Background,
|
||||||
@@ -50,11 +50,53 @@ export const DND_SCENE_ID_MIME = 'application/x-dnd-scene-id';
|
|||||||
const SCENE_CARD_W = 220;
|
const SCENE_CARD_W = 220;
|
||||||
const SCENE_CARD_H = 248;
|
const SCENE_CARD_H = 248;
|
||||||
|
|
||||||
|
/** UI strings for the scene graph (passed from editor i18n). */
|
||||||
|
export type SceneGraphUiStrings = {
|
||||||
|
badgeStart: string;
|
||||||
|
untitled: string;
|
||||||
|
videoBadge: string;
|
||||||
|
audioBadge: string;
|
||||||
|
loop: string;
|
||||||
|
autoplay: string;
|
||||||
|
previewAutostart: string;
|
||||||
|
videoLoop: string;
|
||||||
|
zoomBar: string;
|
||||||
|
zoomIn: string;
|
||||||
|
zoomOut: string;
|
||||||
|
fitAll: string;
|
||||||
|
closeMenu: string;
|
||||||
|
startScene: string;
|
||||||
|
unsetStartScene: string;
|
||||||
|
delete: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_SCENE_GRAPH_UI: SceneGraphUiStrings = {
|
||||||
|
badgeStart: 'НАЧАЛО',
|
||||||
|
untitled: 'Без названия',
|
||||||
|
videoBadge: 'Видео',
|
||||||
|
audioBadge: 'Аудио',
|
||||||
|
loop: 'Цикл',
|
||||||
|
autoplay: 'Автостарт',
|
||||||
|
previewAutostart: 'Авто превью',
|
||||||
|
videoLoop: 'Цикл видео',
|
||||||
|
zoomBar: 'Масштаб графа',
|
||||||
|
zoomIn: 'Увеличить',
|
||||||
|
zoomOut: 'Уменьшить',
|
||||||
|
fitAll: 'Показать всё',
|
||||||
|
closeMenu: 'Закрыть меню',
|
||||||
|
startScene: 'Начальная сцена',
|
||||||
|
unsetStartScene: 'Снять метку «Начальная сцена»',
|
||||||
|
delete: 'Удалить',
|
||||||
|
};
|
||||||
|
|
||||||
|
const GraphUiContext = createContext<SceneGraphUiStrings>(DEFAULT_SCENE_GRAPH_UI);
|
||||||
|
|
||||||
export type SceneGraphProps = {
|
export type SceneGraphProps = {
|
||||||
sceneGraphNodes: SceneGraphNode[];
|
sceneGraphNodes: SceneGraphNode[];
|
||||||
sceneGraphEdges: SceneGraphEdge[];
|
sceneGraphEdges: SceneGraphEdge[];
|
||||||
sceneCardById: Record<SceneId, SceneGraphSceneCard>;
|
sceneCardById: Record<SceneId, SceneGraphSceneCard>;
|
||||||
currentSceneId: SceneId | null;
|
currentSceneId: SceneId | null;
|
||||||
|
graphUi?: SceneGraphUiStrings;
|
||||||
onCurrentSceneChange: (id: SceneId) => void;
|
onCurrentSceneChange: (id: SceneId) => void;
|
||||||
onConnect: (sourceGraphNodeId: GraphNodeId, targetGraphNodeId: GraphNodeId) => void;
|
onConnect: (sourceGraphNodeId: GraphNodeId, targetGraphNodeId: GraphNodeId) => void;
|
||||||
onDisconnect: (edgeId: string) => void;
|
onDisconnect: (edgeId: string) => void;
|
||||||
@@ -131,6 +173,7 @@ function IconVideoPreviewAutostart() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function SceneCardNode({ data }: NodeProps<SceneCardData>) {
|
function SceneCardNode({ data }: NodeProps<SceneCardData>) {
|
||||||
|
const ui = useContext(GraphUiContext);
|
||||||
const thumbUrl = useAssetUrl(data.previewThumbAssetId);
|
const thumbUrl = useAssetUrl(data.previewThumbAssetId);
|
||||||
const previewUrl = useAssetUrl(data.previewAssetId);
|
const previewUrl = useAssetUrl(data.previewAssetId);
|
||||||
const cardClass = [styles.card, data.active ? styles.cardActive : ''].filter(Boolean).join(' ');
|
const cardClass = [styles.card, data.active ? styles.cardActive : ''].filter(Boolean).join(' ');
|
||||||
@@ -141,7 +184,7 @@ function SceneCardNode({ data }: NodeProps<SceneCardData>) {
|
|||||||
<Handle type="target" position={Position.Top} className={styles.handle} />
|
<Handle type="target" position={Position.Top} className={styles.handle} />
|
||||||
<div className={cardClass}>
|
<div className={cardClass}>
|
||||||
<div className={styles.previewShell}>
|
<div className={styles.previewShell}>
|
||||||
{data.isStartScene ? <div className={styles.badgeStart}>НАЧАЛО</div> : null}
|
{data.isStartScene ? <div className={styles.badgeStart}>{ui.badgeStart}</div> : null}
|
||||||
{thumbUrl ? (
|
{thumbUrl ? (
|
||||||
<div className={styles.previewFill}>
|
<div className={styles.previewFill}>
|
||||||
{data.previewRotationDeg === 0 ? (
|
{data.previewRotationDeg === 0 ? (
|
||||||
@@ -209,12 +252,12 @@ function SceneCardNode({ data }: NodeProps<SceneCardData>) {
|
|||||||
{showCornerVideo || showCornerAudio ? (
|
{showCornerVideo || showCornerAudio ? (
|
||||||
<div className={styles.cornerBadges}>
|
<div className={styles.cornerBadges}>
|
||||||
{showCornerVideo ? (
|
{showCornerVideo ? (
|
||||||
<span className={styles.mediaBadge} title="Видео">
|
<span className={styles.mediaBadge} title={ui.videoBadge}>
|
||||||
<IconVideoBadge />
|
<IconVideoBadge />
|
||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
{showCornerAudio ? (
|
{showCornerAudio ? (
|
||||||
<span className={styles.mediaBadge} title="Аудио">
|
<span className={styles.mediaBadge} title={ui.audioBadge}>
|
||||||
<IconAudioBadge />
|
<IconAudioBadge />
|
||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -222,19 +265,19 @@ function SceneCardNode({ data }: NodeProps<SceneCardData>) {
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.nodeBody}>
|
<div className={styles.nodeBody}>
|
||||||
<div className={styles.title}>{data.title || 'Без названия'}</div>
|
<div className={styles.title}>{data.title || ui.untitled}</div>
|
||||||
{data.hasAnyAudioLoop || data.hasAnyAudioAutoplay ? (
|
{data.hasAnyAudioLoop || data.hasAnyAudioAutoplay ? (
|
||||||
<div className={styles.musicParams}>
|
<div className={styles.musicParams}>
|
||||||
{data.hasAnyAudioLoop ? (
|
{data.hasAnyAudioLoop ? (
|
||||||
<div className={styles.musicParam}>
|
<div className={styles.musicParam}>
|
||||||
<IconLoopParam />
|
<IconLoopParam />
|
||||||
<span>Цикл</span>
|
<span>{ui.loop}</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
{data.hasAnyAudioAutoplay ? (
|
{data.hasAnyAudioAutoplay ? (
|
||||||
<div className={styles.musicParam}>
|
<div className={styles.musicParam}>
|
||||||
<IconAutoplayParam />
|
<IconAutoplayParam />
|
||||||
<span>Автостарт</span>
|
<span>{ui.autoplay}</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
@@ -244,13 +287,13 @@ function SceneCardNode({ data }: NodeProps<SceneCardData>) {
|
|||||||
{data.showPreviewVideoAutostart ? (
|
{data.showPreviewVideoAutostart ? (
|
||||||
<div className={styles.musicParam}>
|
<div className={styles.musicParam}>
|
||||||
<IconVideoPreviewAutostart />
|
<IconVideoPreviewAutostart />
|
||||||
<span>Авто превью</span>
|
<span>{ui.previewAutostart}</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
{data.showPreviewVideoLoop ? (
|
{data.showPreviewVideoLoop ? (
|
||||||
<div className={styles.musicParam}>
|
<div className={styles.musicParam}>
|
||||||
<IconLoopParam />
|
<IconLoopParam />
|
||||||
<span>Цикл видео</span>
|
<span>{ui.videoLoop}</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
@@ -265,18 +308,19 @@ function SceneCardNode({ data }: NodeProps<SceneCardData>) {
|
|||||||
const nodeTypes = { sceneCard: SceneCardNode };
|
const nodeTypes = { sceneCard: SceneCardNode };
|
||||||
|
|
||||||
function GraphZoomToolbar() {
|
function GraphZoomToolbar() {
|
||||||
|
const ui = useContext(GraphUiContext);
|
||||||
const { zoomIn, zoomOut, fitView } = useReactFlow();
|
const { zoomIn, zoomOut, fitView } = useReactFlow();
|
||||||
const zoom = useStore((s) => s.transform[2]);
|
const zoom = useStore((s) => s.transform[2]);
|
||||||
const pct = Math.max(1, Math.round(zoom * 100));
|
const pct = Math.max(1, Math.round(zoom * 100));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Panel position="bottom-center" className={styles.zoomPanel}>
|
<Panel position="bottom-center" className={styles.zoomPanel}>
|
||||||
<div className={styles.zoomBar} role="toolbar" aria-label="Масштаб графа">
|
<div className={styles.zoomBar} role="toolbar" aria-label={ui.zoomBar}>
|
||||||
<button type="button" className={styles.zoomBtn} onClick={() => zoomIn()} aria-label="Увеличить">
|
<button type="button" className={styles.zoomBtn} onClick={() => zoomIn()} aria-label={ui.zoomIn}>
|
||||||
+
|
+
|
||||||
</button>
|
</button>
|
||||||
<span className={styles.zoomPct}>{pct}%</span>
|
<span className={styles.zoomPct}>{pct}%</span>
|
||||||
<button type="button" className={styles.zoomBtn} onClick={() => zoomOut()} aria-label="Уменьшить">
|
<button type="button" className={styles.zoomBtn} onClick={() => zoomOut()} aria-label={ui.zoomOut}>
|
||||||
−
|
−
|
||||||
</button>
|
</button>
|
||||||
<span className={styles.zoomDivider} aria-hidden />
|
<span className={styles.zoomDivider} aria-hidden />
|
||||||
@@ -284,8 +328,8 @@ function GraphZoomToolbar() {
|
|||||||
type="button"
|
type="button"
|
||||||
className={styles.zoomBtn}
|
className={styles.zoomBtn}
|
||||||
onClick={() => fitView({ padding: 0.25 })}
|
onClick={() => fitView({ padding: 0.25 })}
|
||||||
aria-label="Показать всё"
|
aria-label={ui.fitAll}
|
||||||
title="Показать всё"
|
title={ui.fitAll}
|
||||||
>
|
>
|
||||||
<svg className={styles.zoomFitIcon} viewBox="0 0 24 24" width={18} height={18} aria-hidden>
|
<svg className={styles.zoomFitIcon} viewBox="0 0 24 24" width={18} height={18} aria-hidden>
|
||||||
<path
|
<path
|
||||||
@@ -307,6 +351,7 @@ function SceneGraphCanvas({
|
|||||||
sceneGraphEdges,
|
sceneGraphEdges,
|
||||||
sceneCardById,
|
sceneCardById,
|
||||||
currentSceneId,
|
currentSceneId,
|
||||||
|
graphUi,
|
||||||
onCurrentSceneChange,
|
onCurrentSceneChange,
|
||||||
onConnect,
|
onConnect,
|
||||||
onDisconnect,
|
onDisconnect,
|
||||||
@@ -316,6 +361,7 @@ function SceneGraphCanvas({
|
|||||||
onSetGraphNodeStart,
|
onSetGraphNodeStart,
|
||||||
onDropSceneFromList,
|
onDropSceneFromList,
|
||||||
}: SceneGraphProps) {
|
}: SceneGraphProps) {
|
||||||
|
const ui = graphUi ?? DEFAULT_SCENE_GRAPH_UI;
|
||||||
const { screenToFlowPosition } = useReactFlow();
|
const { screenToFlowPosition } = useReactFlow();
|
||||||
const [menu, setMenu] = useState<{ x: number; y: number; graphNodeId: GraphNodeId } | null>(null);
|
const [menu, setMenu] = useState<{ x: number; y: number; graphNodeId: GraphNodeId } | null>(null);
|
||||||
|
|
||||||
@@ -365,16 +411,36 @@ function SceneGraphCanvas({
|
|||||||
}, [currentSceneId, sceneCardById, sceneGraphNodes]);
|
}, [currentSceneId, sceneCardById, sceneGraphNodes]);
|
||||||
|
|
||||||
const desiredEdges = useMemo<Edge[]>(() => {
|
const desiredEdges = useMemo<Edge[]>(() => {
|
||||||
|
const selectedGraphNodeIds = new Set<GraphNodeId>();
|
||||||
|
if (currentSceneId) {
|
||||||
|
for (const gn of sceneGraphNodes) {
|
||||||
|
if (gn.sceneId === currentSceneId) selectedGraphNodeIds.add(gn.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const hasSelection = selectedGraphNodeIds.size > 0;
|
||||||
return sceneGraphEdges.map((e) => ({
|
return sceneGraphEdges.map((e) => ({
|
||||||
|
...(hasSelection
|
||||||
|
? {
|
||||||
|
style:
|
||||||
|
selectedGraphNodeIds.has(e.sourceGraphNodeId) || selectedGraphNodeIds.has(e.targetGraphNodeId)
|
||||||
|
? { stroke: 'rgba(167,139,250,0.95)', strokeWidth: 3 }
|
||||||
|
: { stroke: 'rgba(255,255,255,0.10)', strokeWidth: 2 },
|
||||||
|
markerEnd:
|
||||||
|
selectedGraphNodeIds.has(e.sourceGraphNodeId) || selectedGraphNodeIds.has(e.targetGraphNodeId)
|
||||||
|
? { type: MarkerType.ArrowClosed, color: 'rgba(167,139,250,0.95)', strokeWidth: 2 }
|
||||||
|
: { type: MarkerType.ArrowClosed, color: 'rgba(255,255,255,0.18)', strokeWidth: 2 },
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
style: { stroke: 'rgba(167,139,250,0.55)', strokeWidth: 2 },
|
||||||
|
markerEnd: { type: MarkerType.ArrowClosed, color: 'rgba(167,139,250,0.85)', strokeWidth: 2 },
|
||||||
|
}),
|
||||||
id: e.id,
|
id: e.id,
|
||||||
source: e.sourceGraphNodeId,
|
source: e.sourceGraphNodeId,
|
||||||
target: e.targetGraphNodeId,
|
target: e.targetGraphNodeId,
|
||||||
type: 'smoothstep',
|
type: 'smoothstep',
|
||||||
animated: false,
|
animated: false,
|
||||||
style: { stroke: 'rgba(167,139,250,0.55)', strokeWidth: 2 },
|
|
||||||
markerEnd: { type: MarkerType.ArrowClosed, color: 'rgba(167,139,250,0.85)', strokeWidth: 2 },
|
|
||||||
}));
|
}));
|
||||||
}, [sceneGraphEdges]);
|
}, [currentSceneId, sceneGraphEdges, sceneGraphNodes]);
|
||||||
|
|
||||||
const [nodes, setNodes, onNodesChange] = useNodesState<Node<SceneCardData>>([]);
|
const [nodes, setNodes, onNodesChange] = useNodesState<Node<SceneCardData>>([]);
|
||||||
const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>([]);
|
const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>([]);
|
||||||
@@ -426,109 +492,111 @@ function SceneGraphCanvas({
|
|||||||
}, [menu]);
|
}, [menu]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.canvasWrap}>
|
<GraphUiContext.Provider value={ui}>
|
||||||
<ReactFlow
|
<div className={styles.canvasWrap}>
|
||||||
nodes={nodes}
|
<ReactFlow
|
||||||
edges={edges}
|
nodes={nodes}
|
||||||
nodeTypes={nodeTypes}
|
edges={edges}
|
||||||
onNodesChange={onNodesChange}
|
nodeTypes={nodeTypes}
|
||||||
onNodeDragStop={(_, node) => {
|
onNodesChange={onNodesChange}
|
||||||
onNodePositionCommit(node.id as GraphNodeId, node.position.x, node.position.y);
|
onNodeDragStop={(_, node) => {
|
||||||
}}
|
onNodePositionCommit(node.id as GraphNodeId, node.position.x, node.position.y);
|
||||||
onEdgesChange={onEdgesChange}
|
}}
|
||||||
isValidConnection={isValidConnection}
|
onEdgesChange={onEdgesChange}
|
||||||
onConnect={onConnectInternal}
|
isValidConnection={isValidConnection}
|
||||||
onEdgesDelete={(eds) => {
|
onConnect={onConnectInternal}
|
||||||
for (const ed of eds) {
|
onEdgesDelete={(eds) => {
|
||||||
onDisconnect(ed.id);
|
for (const ed of eds) {
|
||||||
}
|
onDisconnect(ed.id);
|
||||||
}}
|
}
|
||||||
onEdgeClick={(_, edge) => {
|
}}
|
||||||
onDisconnect(edge.id);
|
onEdgeClick={(_, edge) => {
|
||||||
}}
|
onDisconnect(edge.id);
|
||||||
onNodesDelete={(nds) => {
|
}}
|
||||||
onRemoveGraphNodes(nds.map((n) => n.id as GraphNodeId));
|
onNodesDelete={(nds) => {
|
||||||
}}
|
onRemoveGraphNodes(nds.map((n) => n.id as GraphNodeId));
|
||||||
onNodeClick={(_, node) => {
|
}}
|
||||||
setMenu(null);
|
onNodeClick={(_, node) => {
|
||||||
const d = node.data as SceneCardData;
|
setMenu(null);
|
||||||
onCurrentSceneChange(d.sceneId);
|
const d = node.data as SceneCardData;
|
||||||
}}
|
onCurrentSceneChange(d.sceneId);
|
||||||
onNodeContextMenu={(e, node) => {
|
}}
|
||||||
e.preventDefault();
|
onNodeContextMenu={(e, node) => {
|
||||||
setMenu({ x: e.clientX, y: e.clientY, graphNodeId: node.id as GraphNodeId });
|
e.preventDefault();
|
||||||
}}
|
setMenu({ x: e.clientX, y: e.clientY, graphNodeId: node.id as GraphNodeId });
|
||||||
onPaneClick={() => {
|
}}
|
||||||
setMenu(null);
|
onPaneClick={() => {
|
||||||
}}
|
setMenu(null);
|
||||||
onPaneContextMenu={(e) => {
|
}}
|
||||||
e.preventDefault();
|
onPaneContextMenu={(e) => {
|
||||||
setMenu(null);
|
e.preventDefault();
|
||||||
}}
|
setMenu(null);
|
||||||
onInit={(instance) => {
|
}}
|
||||||
instance.fitView({ padding: 0.25 });
|
onInit={(instance) => {
|
||||||
}}
|
instance.fitView({ padding: 0.25 });
|
||||||
onDragOver={onDragOver}
|
}}
|
||||||
onDrop={onDrop}
|
onDragOver={onDragOver}
|
||||||
panOnScroll
|
onDrop={onDrop}
|
||||||
selectionOnDrag={false}
|
panOnScroll
|
||||||
deleteKeyCode={['Backspace', 'Delete']}
|
selectionOnDrag={false}
|
||||||
proOptions={{ hideAttribution: true }}
|
deleteKeyCode={['Backspace', 'Delete']}
|
||||||
>
|
proOptions={{ hideAttribution: true }}
|
||||||
<Background gap={18} size={1} color="rgba(255,255,255,0.06)" />
|
>
|
||||||
<GraphZoomToolbar />
|
<Background gap={18} size={1} color="rgba(255,255,255,0.06)" />
|
||||||
</ReactFlow>
|
<GraphZoomToolbar />
|
||||||
{menu && menuPosition
|
</ReactFlow>
|
||||||
? createPortal(
|
{menu && menuPosition
|
||||||
<>
|
? createPortal(
|
||||||
<button
|
<>
|
||||||
type="button"
|
|
||||||
aria-label="Закрыть меню"
|
|
||||||
className={styles.menuBackdrop}
|
|
||||||
onClick={() => setMenu(null)}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
role="menu"
|
|
||||||
tabIndex={-1}
|
|
||||||
className={styles.ctxMenu}
|
|
||||||
style={{ left: menuPosition.x, top: menuPosition.y }}
|
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === 'Escape') setMenu(null);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
role="menuitem"
|
aria-label={ui.closeMenu}
|
||||||
className={styles.ctxItem}
|
className={styles.menuBackdrop}
|
||||||
onClick={() => {
|
onClick={() => setMenu(null)}
|
||||||
if (menuNodeIsStart) {
|
/>
|
||||||
onSetGraphNodeStart(null);
|
<div
|
||||||
} else {
|
role="menu"
|
||||||
onSetGraphNodeStart(menu.graphNodeId);
|
tabIndex={-1}
|
||||||
}
|
className={styles.ctxMenu}
|
||||||
setMenu(null);
|
style={{ left: menuPosition.x, top: menuPosition.y }}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Escape') setMenu(null);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{menuNodeIsStart ? 'Снять метку «Начальная сцена»' : 'Начальная сцена'}
|
<button
|
||||||
</button>
|
type="button"
|
||||||
<button
|
role="menuitem"
|
||||||
type="button"
|
className={styles.ctxItem}
|
||||||
role="menuitem"
|
onClick={() => {
|
||||||
className={styles.ctxItemDanger}
|
if (menuNodeIsStart) {
|
||||||
onClick={() => {
|
onSetGraphNodeStart(null);
|
||||||
onRemoveGraphNode(menu.graphNodeId);
|
} else {
|
||||||
setMenu(null);
|
onSetGraphNodeStart(menu.graphNodeId);
|
||||||
}}
|
}
|
||||||
>
|
setMenu(null);
|
||||||
Удалить
|
}}
|
||||||
</button>
|
>
|
||||||
</div>
|
{menuNodeIsStart ? ui.unsetStartScene : ui.startScene}
|
||||||
</>,
|
</button>
|
||||||
document.body,
|
<button
|
||||||
)
|
type="button"
|
||||||
: null}
|
role="menuitem"
|
||||||
</div>
|
className={styles.ctxItemDanger}
|
||||||
|
onClick={() => {
|
||||||
|
onRemoveGraphNode(menu.graphNodeId);
|
||||||
|
setMenu(null);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{ui.delete}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</>,
|
||||||
|
document.body,
|
||||||
|
)
|
||||||
|
: null}
|
||||||
|
</div>
|
||||||
|
</GraphUiContext.Provider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import React, { createContext, useCallback, useContext, useMemo, useState } from 'react';
|
||||||
|
|
||||||
|
import {
|
||||||
|
EDITOR_LOCALE_STORAGE_KEY,
|
||||||
|
inferEditorLocaleFromSystem,
|
||||||
|
normalizeEditorLocale,
|
||||||
|
translateEditorMessage,
|
||||||
|
type EditorLocale,
|
||||||
|
} from './editorMessages';
|
||||||
|
|
||||||
|
type EditorI18nContextValue = {
|
||||||
|
locale: EditorLocale;
|
||||||
|
setLocale: (next: EditorLocale) => void;
|
||||||
|
t: (key: string, vars?: Record<string, string | number>) => string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const EditorI18nContext = createContext<EditorI18nContextValue | null>(null);
|
||||||
|
|
||||||
|
function readInitialLocale(): EditorLocale {
|
||||||
|
try {
|
||||||
|
return normalizeEditorLocale(localStorage.getItem(EDITOR_LOCALE_STORAGE_KEY));
|
||||||
|
} catch {
|
||||||
|
return inferEditorLocaleFromSystem();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EditorI18nProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
const [locale, setLocaleState] = useState<EditorLocale>(readInitialLocale);
|
||||||
|
|
||||||
|
const setLocale = useCallback((next: EditorLocale) => {
|
||||||
|
setLocaleState(next);
|
||||||
|
try {
|
||||||
|
localStorage.setItem(EDITOR_LOCALE_STORAGE_KEY, next);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const t = useCallback(
|
||||||
|
(key: string, vars?: Record<string, string | number>) => translateEditorMessage(locale, key, vars),
|
||||||
|
[locale],
|
||||||
|
);
|
||||||
|
|
||||||
|
const value = useMemo<EditorI18nContextValue>(() => ({ locale, setLocale, t }), [locale, setLocale, t]);
|
||||||
|
|
||||||
|
return <EditorI18nContext.Provider value={value}>{children}</EditorI18nContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useEditorI18n(): EditorI18nContextValue {
|
||||||
|
const ctx = useContext(EditorI18nContext);
|
||||||
|
if (!ctx) {
|
||||||
|
throw new Error('useEditorI18n must be used within EditorI18nProvider');
|
||||||
|
}
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
|
||||||
|
import { inferEditorLocaleFromSystem, normalizeEditorLocale } from './editorMessages';
|
||||||
|
|
||||||
|
void test('inferEditorLocaleFromSystem: en-* wins when listed first', () => {
|
||||||
|
assert.equal(inferEditorLocaleFromSystem(['en-GB', 'ru-RU']), 'en');
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('inferEditorLocaleFromSystem: ru-* wins when listed first', () => {
|
||||||
|
assert.equal(inferEditorLocaleFromSystem(['ru-RU', 'en-US']), 'ru');
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('inferEditorLocaleFromSystem: unknown tags fall back to ru', () => {
|
||||||
|
assert.equal(inferEditorLocaleFromSystem(['de-DE', 'fr']), 'ru');
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('inferEditorLocaleFromSystem: empty list → ru', () => {
|
||||||
|
assert.equal(inferEditorLocaleFromSystem([]), 'ru');
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('normalizeEditorLocale: trims stored en/ru', () => {
|
||||||
|
assert.equal(normalizeEditorLocale(' EN '), 'en');
|
||||||
|
assert.equal(normalizeEditorLocale('ru '), 'ru');
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('normalizeEditorLocale: blank or invalid defers to infer (explicit list)', () => {
|
||||||
|
assert.equal(normalizeEditorLocale(''), inferEditorLocaleFromSystem([]));
|
||||||
|
assert.equal(normalizeEditorLocale('xx'), inferEditorLocaleFromSystem([]));
|
||||||
|
});
|
||||||
@@ -0,0 +1,542 @@
|
|||||||
|
export type EditorLocale = 'ru' | 'en';
|
||||||
|
|
||||||
|
export const EDITOR_LOCALE_STORAGE_KEY = 'dnd_editor_locale';
|
||||||
|
|
||||||
|
function primaryLanguageTag(lang: string): string {
|
||||||
|
const trimmed = lang.trim().toLowerCase();
|
||||||
|
if (!trimmed) return '';
|
||||||
|
const sep = trimmed.search(/[-_]/);
|
||||||
|
return sep === -1 ? trimmed : trimmed.slice(0, sep);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Выбор `ru` / `en` по языку ОС/браузера, если пользователь ещё не сохранил язык в `localStorage`.
|
||||||
|
* В Electron совпадает с локалью системы (Chromium подставляет `navigator.languages`).
|
||||||
|
*/
|
||||||
|
export function inferEditorLocaleFromSystem(languages?: readonly string[]): EditorLocale {
|
||||||
|
let list: string[];
|
||||||
|
if (languages !== undefined) {
|
||||||
|
list = [...languages];
|
||||||
|
} else if (typeof navigator !== 'undefined') {
|
||||||
|
list = [...navigator.languages];
|
||||||
|
if (navigator.language) {
|
||||||
|
list.push(navigator.language);
|
||||||
|
}
|
||||||
|
list = list.filter((x) => x.trim() !== '');
|
||||||
|
} else {
|
||||||
|
list = [];
|
||||||
|
}
|
||||||
|
for (const lang of list) {
|
||||||
|
const tag = primaryLanguageTag(lang);
|
||||||
|
if (tag === 'en') return 'en';
|
||||||
|
if (tag === 'ru') return 'ru';
|
||||||
|
}
|
||||||
|
return 'ru';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeEditorLocale(raw: string | null | undefined): EditorLocale {
|
||||||
|
if (raw == null) {
|
||||||
|
return inferEditorLocaleFromSystem();
|
||||||
|
}
|
||||||
|
const trimmed = raw.trim();
|
||||||
|
if (trimmed === '') {
|
||||||
|
return inferEditorLocaleFromSystem();
|
||||||
|
}
|
||||||
|
const s = trimmed.toLowerCase();
|
||||||
|
if (s === 'en') return 'en';
|
||||||
|
if (s === 'ru') return 'ru';
|
||||||
|
return inferEditorLocaleFromSystem();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Flat message table; `{name}` placeholders supported in `translate`. */
|
||||||
|
export const EDITOR_MESSAGES: Record<EditorLocale, Record<string, string>> = {
|
||||||
|
ru: {
|
||||||
|
'common.close': 'Закрыть',
|
||||||
|
'common.cancel': 'Отмена',
|
||||||
|
'common.save': 'Сохранить',
|
||||||
|
'common.understood': 'Понятно',
|
||||||
|
'common.message': 'Сообщение',
|
||||||
|
'common.error': 'Ошибка',
|
||||||
|
'common.delete': 'Удалить',
|
||||||
|
'common.closeMenu': 'Закрыть меню',
|
||||||
|
|
||||||
|
'app.brandTitle': 'НРИ Плеер',
|
||||||
|
|
||||||
|
'notice.campaignAudioEmpty': 'Аудио не добавлено. Проверьте формат файла.',
|
||||||
|
|
||||||
|
'license.checkingTitle': 'Проверка лицензии…',
|
||||||
|
'license.checkingWait': 'Подождите.',
|
||||||
|
'license.requiredTitle': 'Требуется лицензия',
|
||||||
|
'license.requiredHint':
|
||||||
|
'Укажите ключ в меню «Настройки» → «Указать ключ». До активации доступно только меню «Настройки».',
|
||||||
|
'license.tokenTitle': 'Указать ключ',
|
||||||
|
'license.tokenKey': 'КЛЮЧ',
|
||||||
|
'license.tokenPlaceholder': 'Продуктовый ключ TTRPG-... или DND-...',
|
||||||
|
'license.tokenSaving': 'Сохранение…',
|
||||||
|
'license.eulaTitle': 'Лицензионное соглашение',
|
||||||
|
'license.eulaReject': 'Не принимаю',
|
||||||
|
'license.eulaAccept': 'Принимаю условия',
|
||||||
|
'license.eulaNoteEn':
|
||||||
|
'The binding legal text below is in Russian. If you need an English summary, contact support.',
|
||||||
|
'license.aboutTitle': 'О лицензии',
|
||||||
|
'license.aboutDevSkip': 'Режим разработки: проверка лицензии отключена (DND_SKIP_LICENSE).',
|
||||||
|
'license.aboutStatus': 'СТАТУС',
|
||||||
|
'license.aboutProduct': 'ПРОДУКТ',
|
||||||
|
'license.aboutLicenseId': 'ID ЛИЦЕНЗИИ',
|
||||||
|
'license.aboutExpiry': 'ОКОНЧАНИЕ',
|
||||||
|
'license.aboutDevice': 'УСТРОЙСТВО',
|
||||||
|
'license.aboutNoData': 'Нет данных лицензии.',
|
||||||
|
'license.reason.ok': 'Активна',
|
||||||
|
'license.reason.none': 'Ключ не указан',
|
||||||
|
'license.reason.expired': 'Срок действия истёк',
|
||||||
|
'license.reason.bad_signature': 'Недействительная подпись',
|
||||||
|
'license.reason.bad_payload': 'Неверный формат токена',
|
||||||
|
'license.reason.malformed': 'Повреждённый токен',
|
||||||
|
'license.reason.not_yet_valid': 'Ещё не действует',
|
||||||
|
'license.reason.wrong_device': 'Другой привязанный компьютер',
|
||||||
|
'license.reason.revoked_remote': 'Отозвана на сервере',
|
||||||
|
|
||||||
|
'presentation.overlay': 'Презентация запущена',
|
||||||
|
'presentation.title': 'Презентация запущена',
|
||||||
|
'presentation.body':
|
||||||
|
'Редактор заблокирован. Закройте окна «Презентация» и «Панель управления», чтобы продолжить.',
|
||||||
|
|
||||||
|
'zip.progress': 'Прогресс операции',
|
||||||
|
'zip.importTitle': 'Импорт проекта',
|
||||||
|
'zip.exportTitle': 'Экспорт проекта',
|
||||||
|
|
||||||
|
'top.settings': 'Настройки',
|
||||||
|
'top.project': 'Проект',
|
||||||
|
'top.file': 'Файл',
|
||||||
|
'top.backToProjects': 'К списку проектов',
|
||||||
|
'top.appVersion': 'Версия приложения',
|
||||||
|
'top.run': 'Запустить',
|
||||||
|
'top.afterLicense': 'Доступно после активации лицензии',
|
||||||
|
'top.setStartScene': 'Назначьте начальную сцену на графе (ПКМ по узлу)',
|
||||||
|
|
||||||
|
'menu.enterKey': 'Указать ключ',
|
||||||
|
'menu.aboutLicense': 'О лицензии',
|
||||||
|
'menu.checkUpdates': 'Проверить обновления',
|
||||||
|
'menu.language': 'Язык',
|
||||||
|
'menu.langRu': 'Русский',
|
||||||
|
'menu.langEn': 'English',
|
||||||
|
|
||||||
|
'updates.dialogTitle': 'Обновления',
|
||||||
|
'updates.checking': 'Проверка наличия обновлений…',
|
||||||
|
'updates.available': 'Доступна новая версия {version}.',
|
||||||
|
'updates.current': 'У вас установлена актуальная версия ({version}).',
|
||||||
|
'updates.error': 'Не удалось проверить обновления: {message}',
|
||||||
|
'updates.notPackaged': 'Проверка доступна только в установленной версии приложения.',
|
||||||
|
'updates.noLicense': 'Нужна активная лицензия.',
|
||||||
|
'updates.download': 'Обновить',
|
||||||
|
'updates.downloading': 'Загрузка…',
|
||||||
|
'updates.stageLine': 'Этап: {stage}',
|
||||||
|
'updates.stage.checking': 'проверка обновлений',
|
||||||
|
'updates.stage.available': 'доступна версия {version}',
|
||||||
|
'updates.stage.not-available': 'актуальная версия',
|
||||||
|
'updates.stage.downloading': 'загрузка{percent}',
|
||||||
|
'updates.stage.installing': 'установка и перезапуск',
|
||||||
|
'updates.stage.error': 'ошибка',
|
||||||
|
'updates.stagePercent': ' ({percent}%)',
|
||||||
|
|
||||||
|
'projectMenu.home': 'Начальный экран',
|
||||||
|
'projectMenu.import': 'Импорт',
|
||||||
|
'projectMenu.export': 'Экспорт',
|
||||||
|
'projectMenu.noProjects': 'Нет сохранённых проектов',
|
||||||
|
|
||||||
|
'fileMenu.rename': 'Переименовать проект',
|
||||||
|
|
||||||
|
'scenes.search': 'Поиск сцен…',
|
||||||
|
'scenes.new': '+ Новая сцена',
|
||||||
|
'scenes.inspectorGame': 'Свойства игры',
|
||||||
|
'scenes.inspectorScene': 'Свойства сцены',
|
||||||
|
'scenes.selectHint': 'Выберите сцену слева, чтобы редактировать её свойства.',
|
||||||
|
'scenes.openProjectHint': 'Откройте проект, чтобы редактировать кампанию и сцены.',
|
||||||
|
|
||||||
|
'rename.title': 'Переименовать проект',
|
||||||
|
'rename.projectName': 'НАЗВАНИЕ ПРОЕКТА',
|
||||||
|
'rename.projectPlaceholder': 'Название проекта…',
|
||||||
|
'rename.projectMin': 'Минимум 3 символа.',
|
||||||
|
'rename.projectDup': 'Проект с таким названием уже существует.',
|
||||||
|
'rename.fileName': 'НАЗВАНИЕ ФАЙЛА ПРОЕКТА',
|
||||||
|
'rename.fileInvalid': 'Минимум 3 символа, без символов <>:"/\\|?*',
|
||||||
|
'rename.fileDup': 'Файл проекта с таким названием уже существует.',
|
||||||
|
'rename.saving': 'Сохранение…',
|
||||||
|
|
||||||
|
'export.title': 'Экспорт проекта',
|
||||||
|
'export.project': 'ПРОЕКТ',
|
||||||
|
'export.hint':
|
||||||
|
'Далее откроется окно сохранения: укажите имя и папку для файла .ttrpg.zip — будет создана копия архива проекта.',
|
||||||
|
'export.exporting': 'Экспорт…',
|
||||||
|
'export.saveAs': 'Сохранить как…',
|
||||||
|
|
||||||
|
'confirmDelete.title': 'Удаление проекта',
|
||||||
|
'confirmDelete.body': 'Удалить проект «{name}» безвозвратно? Файл и кэш будут стёрты с диска.',
|
||||||
|
'confirmDelete.failedTitle': 'Не удалось удалить',
|
||||||
|
|
||||||
|
'picker.title': 'Проекты',
|
||||||
|
'picker.newPlaceholder': 'Название нового проекта…',
|
||||||
|
'picker.create': 'Создать проект',
|
||||||
|
'picker.existing': 'СУЩЕСТВУЮЩИЕ',
|
||||||
|
'picker.lockedHint':
|
||||||
|
'Открытие и создание — после активации лицензии. Список показывает файлы в папке приложения.',
|
||||||
|
'picker.empty': 'Пока нет проектов.',
|
||||||
|
'picker.projectMenu': 'Меню проекта',
|
||||||
|
'picker.openDisabled': 'Открытие проекта — после активации лицензии',
|
||||||
|
'picker.defaultName': 'Моя кампания',
|
||||||
|
|
||||||
|
'campaign.label': 'АУДИО ИГРЫ',
|
||||||
|
'campaign.noFiles': 'Файлов пока нет. Добавьте аудио.',
|
||||||
|
'campaign.auto': 'Авто',
|
||||||
|
'campaign.loop': 'Цикл',
|
||||||
|
'campaign.removeTitle': 'Убрать из кампании',
|
||||||
|
'campaign.upload': 'Загрузить',
|
||||||
|
|
||||||
|
'scene.title': 'НАЗВАНИЕ СЦЕНЫ',
|
||||||
|
'scene.description': 'ОПИСАНИЕ',
|
||||||
|
'scene.preview': 'ПРЕВЬЮ СЦЕНЫ',
|
||||||
|
'scene.previewHint': 'Файл изображения (PNG, JPG, WebP, GIF и т.д.).',
|
||||||
|
'scene.previewEmpty': 'Превью не задано',
|
||||||
|
'scene.previewBusy': 'Загрузка и оптимизация изображения…',
|
||||||
|
'scene.change': 'Изменить',
|
||||||
|
'scene.clear': 'Очистить',
|
||||||
|
'scene.autostart': 'Автостарт',
|
||||||
|
'scene.rotate': 'Повернуть',
|
||||||
|
'scene.audio': 'АУДИО СЦЕНЫ',
|
||||||
|
'scene.removeTitle': 'Убрать из сцены',
|
||||||
|
'scene.branching': 'ВЕТВЛЕНИЯ',
|
||||||
|
'scene.branchingHint':
|
||||||
|
'Перетащите сцену из списка на граф. С одной карточки можно задать несколько вариантов — по одной связи на каждую целевую сцену. Повторно к той же сцене (включая вторую карточку той же сцены на графе) подключить нельзя.',
|
||||||
|
|
||||||
|
'sceneCard.current': 'ТЕКУЩАЯ',
|
||||||
|
'sceneCard.menu': 'Меню сцены',
|
||||||
|
|
||||||
|
'graph.badgeStart': 'НАЧАЛО',
|
||||||
|
'graph.untitled': 'Без названия',
|
||||||
|
'graph.videoBadge': 'Видео',
|
||||||
|
'graph.audioBadge': 'Аудио',
|
||||||
|
'graph.loop': 'Цикл',
|
||||||
|
'graph.autoplay': 'Автостарт',
|
||||||
|
'graph.previewAutostart': 'Авто превью',
|
||||||
|
'graph.videoLoop': 'Цикл видео',
|
||||||
|
'graph.zoomBar': 'Масштаб графа',
|
||||||
|
'graph.zoomIn': 'Увеличить',
|
||||||
|
'graph.zoomOut': 'Уменьшить',
|
||||||
|
'graph.fitAll': 'Показать всё',
|
||||||
|
'graph.startScene': 'Начальная сцена',
|
||||||
|
'graph.unsetStartScene': 'Снять метку «Начальная сцена»',
|
||||||
|
|
||||||
|
'control.remoteTitle': 'ПУЛЬТ УПРАВЛЕНИЯ',
|
||||||
|
'control.effects': 'ЭФФЕКТЫ',
|
||||||
|
'control.tools': 'Инструменты',
|
||||||
|
'control.fieldEffects': 'Эффекты поля',
|
||||||
|
'control.actionEffects': 'Эффекты действий',
|
||||||
|
'control.eraser': 'Ластик',
|
||||||
|
'control.clearEffects': 'Очистить эффекты',
|
||||||
|
'control.fog': 'Туман',
|
||||||
|
'control.rain': 'Дождь',
|
||||||
|
'control.fire': 'Огонь',
|
||||||
|
'control.water': 'Вода',
|
||||||
|
'control.lightning': 'Молния',
|
||||||
|
'control.sunbeam': 'Луч света',
|
||||||
|
'control.freeze': 'Заморозка',
|
||||||
|
'control.poisonCloud': 'Облако яда',
|
||||||
|
'control.brushRadius': 'Радиус кисти',
|
||||||
|
'control.storyLine': 'СЮЖЕТНАЯ ЛИНИЯ',
|
||||||
|
'control.gotoScene': 'Перейти к этой сцене',
|
||||||
|
'control.currentSceneBadge': 'ТЕКУЩАЯ СЦЕНА',
|
||||||
|
'control.passed': 'Пройдено',
|
||||||
|
'control.noActiveScene': 'Нет активной сцены.',
|
||||||
|
'control.screenPreview': 'Предпросмотр экрана',
|
||||||
|
'control.stopPresentation': 'Выключить демонстрацию',
|
||||||
|
'control.videoBrushHint':
|
||||||
|
'Видео-превью: кисть эффектов отключена (как на экране демонстрации — оверлей только для изображения).',
|
||||||
|
'control.branches': 'Варианты ветвления',
|
||||||
|
'control.option': 'ОПЦИЯ {n}',
|
||||||
|
'control.unnamed': 'Без названия',
|
||||||
|
'control.switchScene': 'Переключить',
|
||||||
|
'control.noBranches': 'Нет вариантов перехода.',
|
||||||
|
'control.endPresentation': 'Завершить показ',
|
||||||
|
'control.music': 'Музыка',
|
||||||
|
'control.sceneMusic': 'МУЗЫКА СЦЕНЫ',
|
||||||
|
'control.gameMusic': 'МУЗЫКА ИГРЫ',
|
||||||
|
'control.noSceneAudio': 'В текущей сцене нет аудио.',
|
||||||
|
'control.noGameAudio': 'В игре нет аудио.',
|
||||||
|
'control.modeAuto': 'Авто',
|
||||||
|
'control.modeManual': 'Ручн.',
|
||||||
|
'control.once': 'Один раз',
|
||||||
|
'control.loop': 'Цикл',
|
||||||
|
'control.scrubSeek': 'Клик — перемотка',
|
||||||
|
'control.durationUnknown': 'Длительность неизвестна',
|
||||||
|
'control.pauseSceneMusic': 'Пауза (сцена)',
|
||||||
|
'control.pauseSceneMusicTitle': 'В сцене есть музыка',
|
||||||
|
'control.pauseCampaignTitle': 'Пауза: в сцене есть музыка',
|
||||||
|
'control.playFailed': 'Не удалось запустить.',
|
||||||
|
'control.audioAutoplayBlocked':
|
||||||
|
'Автозапуск заблокирован (нужно действие пользователя) или ошибка воспроизведения.',
|
||||||
|
'control.audioNoUrl': 'URL не получен',
|
||||||
|
'control.audioNoUrlDetail': 'Не удалось получить dnd://asset URL для аудио.',
|
||||||
|
'control.audioBlocked': 'Ошибка/блок',
|
||||||
|
'control.audioError': 'Ошибка',
|
||||||
|
'control.audioMediaError': 'MediaError code={code} (1=ABORTED, 2=NETWORK, 3=DECODE, 4=SRC_NOT_SUPPORTED)',
|
||||||
|
'control.audioLoading': 'Загрузка…',
|
||||||
|
'control.audioPlaying': 'Играет',
|
||||||
|
'control.audioPaused': 'Пауза',
|
||||||
|
'control.audioStopped': 'Остановлено',
|
||||||
|
'control.previewTrackLabel': 'Превью без субтитров',
|
||||||
|
'control.transportPlay': 'Воспроизведение',
|
||||||
|
'control.transportPause': 'Пауза',
|
||||||
|
'control.transportStop': 'Стоп',
|
||||||
|
},
|
||||||
|
en: {
|
||||||
|
'common.close': 'Close',
|
||||||
|
'common.cancel': 'Cancel',
|
||||||
|
'common.save': 'Save',
|
||||||
|
'common.understood': 'OK',
|
||||||
|
'common.message': 'Message',
|
||||||
|
'common.error': 'Error',
|
||||||
|
'common.delete': 'Delete',
|
||||||
|
'common.closeMenu': 'Close menu',
|
||||||
|
|
||||||
|
'app.brandTitle': 'TTRPG Player',
|
||||||
|
|
||||||
|
'notice.campaignAudioEmpty': 'No audio was added. Check the file format.',
|
||||||
|
|
||||||
|
'license.checkingTitle': 'Checking license…',
|
||||||
|
'license.checkingWait': 'Please wait.',
|
||||||
|
'license.requiredTitle': 'License required',
|
||||||
|
'license.requiredHint':
|
||||||
|
'Enter your key via Settings → Enter license key. Until activation, only Settings is available.',
|
||||||
|
'license.tokenTitle': 'Enter license key',
|
||||||
|
'license.tokenKey': 'KEY',
|
||||||
|
'license.tokenPlaceholder': 'TTRPG- or DND- product key…',
|
||||||
|
'license.tokenSaving': 'Saving…',
|
||||||
|
'license.eulaTitle': 'End User License Agreement',
|
||||||
|
'license.eulaReject': 'Decline',
|
||||||
|
'license.eulaAccept': 'I accept the terms',
|
||||||
|
'license.eulaNoteEn':
|
||||||
|
'The binding legal text below is in Russian. If you need an English summary, contact support.',
|
||||||
|
'license.aboutTitle': 'About license',
|
||||||
|
'license.aboutDevSkip': 'Development mode: license checks are disabled (DND_SKIP_LICENSE).',
|
||||||
|
'license.aboutStatus': 'STATUS',
|
||||||
|
'license.aboutProduct': 'PRODUCT',
|
||||||
|
'license.aboutLicenseId': 'LICENSE ID',
|
||||||
|
'license.aboutExpiry': 'EXPIRES',
|
||||||
|
'license.aboutDevice': 'DEVICE',
|
||||||
|
'license.aboutNoData': 'No license data.',
|
||||||
|
'license.reason.ok': 'Active',
|
||||||
|
'license.reason.none': 'No key provided',
|
||||||
|
'license.reason.expired': 'Expired',
|
||||||
|
'license.reason.bad_signature': 'Invalid signature',
|
||||||
|
'license.reason.bad_payload': 'Invalid token format',
|
||||||
|
'license.reason.malformed': 'Malformed token',
|
||||||
|
'license.reason.not_yet_valid': 'Not yet valid',
|
||||||
|
'license.reason.wrong_device': 'Wrong bound device',
|
||||||
|
'license.reason.revoked_remote': 'Revoked on server',
|
||||||
|
|
||||||
|
'presentation.overlay': 'Presentation running',
|
||||||
|
'presentation.title': 'Presentation running',
|
||||||
|
'presentation.body': 'The editor is locked. Close the Presentation and Control windows to continue.',
|
||||||
|
|
||||||
|
'zip.progress': 'Operation progress',
|
||||||
|
'zip.importTitle': 'Import project',
|
||||||
|
'zip.exportTitle': 'Export project',
|
||||||
|
|
||||||
|
'top.settings': 'Settings',
|
||||||
|
'top.project': 'Project',
|
||||||
|
'top.file': 'File',
|
||||||
|
'top.backToProjects': 'Back to projects',
|
||||||
|
'top.appVersion': 'App version',
|
||||||
|
'top.run': 'Run',
|
||||||
|
'top.afterLicense': 'Available after license activation',
|
||||||
|
'top.setStartScene': 'Set a start scene on the graph (right‑click a node)',
|
||||||
|
|
||||||
|
'menu.enterKey': 'Enter license key',
|
||||||
|
'menu.aboutLicense': 'About license',
|
||||||
|
'menu.checkUpdates': 'Check for updates',
|
||||||
|
'menu.language': 'Language',
|
||||||
|
'menu.langRu': 'Русский',
|
||||||
|
'menu.langEn': 'English',
|
||||||
|
|
||||||
|
'updates.dialogTitle': 'Updates',
|
||||||
|
'updates.checking': 'Checking for updates…',
|
||||||
|
'updates.available': 'A new version is available: {version}.',
|
||||||
|
'updates.current': 'You have the latest version ({version}).',
|
||||||
|
'updates.error': 'Could not check for updates: {message}',
|
||||||
|
'updates.notPackaged': 'Updates can only be checked in the installed application.',
|
||||||
|
'updates.noLicense': 'An active license is required.',
|
||||||
|
'updates.download': 'Update',
|
||||||
|
'updates.downloading': 'Downloading…',
|
||||||
|
'updates.stageLine': 'Stage: {stage}',
|
||||||
|
'updates.stage.checking': 'checking for updates',
|
||||||
|
'updates.stage.available': 'version {version} available',
|
||||||
|
'updates.stage.not-available': 'up to date',
|
||||||
|
'updates.stage.downloading': 'downloading{percent}',
|
||||||
|
'updates.stage.installing': 'installing and restarting',
|
||||||
|
'updates.stage.error': 'error',
|
||||||
|
'updates.stagePercent': ' ({percent}%)',
|
||||||
|
|
||||||
|
'projectMenu.home': 'Home',
|
||||||
|
'projectMenu.import': 'Import',
|
||||||
|
'projectMenu.export': 'Export',
|
||||||
|
'projectMenu.noProjects': 'No saved projects',
|
||||||
|
|
||||||
|
'fileMenu.rename': 'Rename project',
|
||||||
|
|
||||||
|
'scenes.search': 'Search scenes…',
|
||||||
|
'scenes.new': '+ New scene',
|
||||||
|
'scenes.inspectorGame': 'Game properties',
|
||||||
|
'scenes.inspectorScene': 'Scene properties',
|
||||||
|
'scenes.selectHint': 'Select a scene on the left to edit its properties.',
|
||||||
|
'scenes.openProjectHint': 'Open a project to edit the campaign and scenes.',
|
||||||
|
|
||||||
|
'rename.title': 'Rename project',
|
||||||
|
'rename.projectName': 'PROJECT NAME',
|
||||||
|
'rename.projectPlaceholder': 'Project name…',
|
||||||
|
'rename.projectMin': 'At least 3 characters.',
|
||||||
|
'rename.projectDup': 'A project with this name already exists.',
|
||||||
|
'rename.fileName': 'PROJECT FILE NAME',
|
||||||
|
'rename.fileInvalid': 'At least 3 characters; forbidden characters <>:"/\\|?*',
|
||||||
|
'rename.fileDup': 'A project file with this name already exists.',
|
||||||
|
'rename.saving': 'Saving…',
|
||||||
|
|
||||||
|
'export.title': 'Export project',
|
||||||
|
'export.project': 'PROJECT',
|
||||||
|
'export.hint':
|
||||||
|
'A save dialog will open: choose a name and folder for the .ttrpg.zip file — a copy of the project archive will be created.',
|
||||||
|
'export.exporting': 'Exporting…',
|
||||||
|
'export.saveAs': 'Save as…',
|
||||||
|
|
||||||
|
'confirmDelete.title': 'Delete project',
|
||||||
|
'confirmDelete.body':
|
||||||
|
'Permanently delete project “{name}”? The file and cache will be removed from disk.',
|
||||||
|
'confirmDelete.failedTitle': 'Could not delete',
|
||||||
|
|
||||||
|
'picker.title': 'Projects',
|
||||||
|
'picker.newPlaceholder': 'New project name…',
|
||||||
|
'picker.create': 'Create project',
|
||||||
|
'picker.existing': 'EXISTING',
|
||||||
|
'picker.lockedHint':
|
||||||
|
'Opening and creating projects require an active license. The list still shows files in the app folder.',
|
||||||
|
'picker.empty': 'No projects yet.',
|
||||||
|
'picker.projectMenu': 'Project menu',
|
||||||
|
'picker.openDisabled': 'Open project — after license activation',
|
||||||
|
'picker.defaultName': 'My campaign',
|
||||||
|
|
||||||
|
'campaign.label': 'GAME AUDIO',
|
||||||
|
'campaign.noFiles': 'No files yet. Add audio.',
|
||||||
|
'campaign.auto': 'Auto',
|
||||||
|
'campaign.loop': 'Loop',
|
||||||
|
'campaign.removeTitle': 'Remove from campaign',
|
||||||
|
'campaign.upload': 'Upload',
|
||||||
|
|
||||||
|
'scene.title': 'SCENE TITLE',
|
||||||
|
'scene.description': 'DESCRIPTION',
|
||||||
|
'scene.preview': 'SCENE PREVIEW',
|
||||||
|
'scene.previewHint': 'Image file (PNG, JPG, WebP, GIF, etc.).',
|
||||||
|
'scene.previewEmpty': 'No preview',
|
||||||
|
'scene.previewBusy': 'Loading and optimizing image…',
|
||||||
|
'scene.change': 'Change',
|
||||||
|
'scene.clear': 'Clear',
|
||||||
|
'scene.autostart': 'Autostart',
|
||||||
|
'scene.rotate': 'Rotate',
|
||||||
|
'scene.audio': 'SCENE AUDIO',
|
||||||
|
'scene.removeTitle': 'Remove from scene',
|
||||||
|
'scene.branching': 'BRANCHING',
|
||||||
|
'scene.branchingHint':
|
||||||
|
'Drag a scene from the list onto the graph. One card can branch to several targets — one link per target scene. You cannot link twice to the same target (including a second card of the same scene).',
|
||||||
|
|
||||||
|
'sceneCard.current': 'CURRENT',
|
||||||
|
'sceneCard.menu': 'Scene menu',
|
||||||
|
|
||||||
|
'graph.badgeStart': 'START',
|
||||||
|
'graph.untitled': 'Untitled',
|
||||||
|
'graph.videoBadge': 'Video',
|
||||||
|
'graph.audioBadge': 'Audio',
|
||||||
|
'graph.loop': 'Loop',
|
||||||
|
'graph.autoplay': 'Autoplay',
|
||||||
|
'graph.previewAutostart': 'Preview autostart',
|
||||||
|
'graph.videoLoop': 'Video loop',
|
||||||
|
'graph.zoomBar': 'Graph zoom',
|
||||||
|
'graph.zoomIn': 'Zoom in',
|
||||||
|
'graph.zoomOut': 'Zoom out',
|
||||||
|
'graph.fitAll': 'Fit view',
|
||||||
|
'graph.startScene': 'Start scene',
|
||||||
|
'graph.unsetStartScene': 'Clear start scene mark',
|
||||||
|
|
||||||
|
'control.remoteTitle': 'CONTROL PANEL',
|
||||||
|
'control.effects': 'EFFECTS',
|
||||||
|
'control.tools': 'Tools',
|
||||||
|
'control.fieldEffects': 'Field effects',
|
||||||
|
'control.actionEffects': 'Action effects',
|
||||||
|
'control.eraser': 'Eraser',
|
||||||
|
'control.clearEffects': 'Clear effects',
|
||||||
|
'control.fog': 'Fog',
|
||||||
|
'control.rain': 'Rain',
|
||||||
|
'control.fire': 'Fire',
|
||||||
|
'control.water': 'Water',
|
||||||
|
'control.lightning': 'Lightning',
|
||||||
|
'control.sunbeam': 'Sunbeam',
|
||||||
|
'control.freeze': 'Freeze',
|
||||||
|
'control.poisonCloud': 'Poison cloud',
|
||||||
|
'control.brushRadius': 'Brush radius',
|
||||||
|
'control.storyLine': 'STORYLINE',
|
||||||
|
'control.gotoScene': 'Go to this scene',
|
||||||
|
'control.currentSceneBadge': 'CURRENT SCENE',
|
||||||
|
'control.passed': 'Visited',
|
||||||
|
'control.noActiveScene': 'No active scene.',
|
||||||
|
'control.screenPreview': 'Screen preview',
|
||||||
|
'control.stopPresentation': 'Stop presentation',
|
||||||
|
'control.videoBrushHint':
|
||||||
|
'Video preview: effect brush is disabled (like on the presentation screen — overlay is for images only).',
|
||||||
|
'control.branches': 'Branch options',
|
||||||
|
'control.option': 'OPTION {n}',
|
||||||
|
'control.unnamed': 'Untitled',
|
||||||
|
'control.switchScene': 'Switch',
|
||||||
|
'control.noBranches': 'No transitions available.',
|
||||||
|
'control.endPresentation': 'End presentation',
|
||||||
|
'control.music': 'Music',
|
||||||
|
'control.sceneMusic': 'SCENE MUSIC',
|
||||||
|
'control.gameMusic': 'GAME MUSIC',
|
||||||
|
'control.noSceneAudio': 'No audio in the current scene.',
|
||||||
|
'control.noGameAudio': 'No game audio.',
|
||||||
|
'control.modeAuto': 'Auto',
|
||||||
|
'control.modeManual': 'Manual',
|
||||||
|
'control.once': 'Once',
|
||||||
|
'control.loop': 'Loop',
|
||||||
|
'control.scrubSeek': 'Click to seek',
|
||||||
|
'control.durationUnknown': 'Duration unknown',
|
||||||
|
'control.pauseSceneMusic': 'Paused (scene)',
|
||||||
|
'control.pauseSceneMusicTitle': 'Scene has music',
|
||||||
|
'control.pauseCampaignTitle': 'Paused: scene has music',
|
||||||
|
'control.playFailed': 'Could not start playback.',
|
||||||
|
'control.audioAutoplayBlocked': 'Autoplay was blocked (user gesture required) or playback failed.',
|
||||||
|
'control.audioNoUrl': 'No URL',
|
||||||
|
'control.audioNoUrlDetail': 'Could not get dnd://asset URL for audio.',
|
||||||
|
'control.audioBlocked': 'Error / blocked',
|
||||||
|
'control.audioError': 'Error',
|
||||||
|
'control.audioMediaError': 'MediaError code={code} (1=ABORTED, 2=NETWORK, 3=DECODE, 4=SRC_NOT_SUPPORTED)',
|
||||||
|
'control.audioLoading': 'Loading…',
|
||||||
|
'control.audioPlaying': 'Playing',
|
||||||
|
'control.audioPaused': 'Paused',
|
||||||
|
'control.audioStopped': 'Stopped',
|
||||||
|
'control.previewTrackLabel': 'Preview (no captions)',
|
||||||
|
'control.transportPlay': 'Play',
|
||||||
|
'control.transportPause': 'Pause',
|
||||||
|
'control.transportStop': 'Stop',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export function translateEditorMessage(
|
||||||
|
locale: EditorLocale,
|
||||||
|
key: string,
|
||||||
|
vars?: Record<string, string | number>,
|
||||||
|
): string {
|
||||||
|
let s = EDITOR_MESSAGES[locale][key] ?? EDITOR_MESSAGES.ru[key] ?? key;
|
||||||
|
if (vars) {
|
||||||
|
for (const [k, v] of Object.entries(vars)) {
|
||||||
|
s = s.split(`{${k}}`).join(String(v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import { EULA_RU_MARKDOWN } from '../../legal/eulaRu';
|
|||||||
import { getDndApi } from '../../shared/dndApi';
|
import { getDndApi } from '../../shared/dndApi';
|
||||||
import { Button } from '../../shared/ui/controls';
|
import { Button } from '../../shared/ui/controls';
|
||||||
import styles from '../EditorApp.module.css';
|
import styles from '../EditorApp.module.css';
|
||||||
|
import { useEditorI18n } from '../i18n/EditorI18nContext';
|
||||||
|
|
||||||
type LicenseTokenModalProps = {
|
type LicenseTokenModalProps = {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
@@ -16,6 +17,7 @@ type LicenseTokenModalProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function LicenseTokenModal({ open, onClose, onSaved }: LicenseTokenModalProps) {
|
export function LicenseTokenModal({ open, onClose, onSaved }: LicenseTokenModalProps) {
|
||||||
|
const { t } = useEditorI18n();
|
||||||
const [token, setToken] = useState('');
|
const [token, setToken] = useState('');
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -40,28 +42,38 @@ export function LicenseTokenModal({ open, onClose, onSaved }: LicenseTokenModalP
|
|||||||
|
|
||||||
return createPortal(
|
return createPortal(
|
||||||
<>
|
<>
|
||||||
<button type="button" aria-label="Закрыть" onClick={onClose} className={styles.modalBackdrop} />
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={t('common.close')}
|
||||||
|
onClick={onClose}
|
||||||
|
className={styles.modalBackdrop}
|
||||||
|
/>
|
||||||
<div role="dialog" aria-modal="true" className={styles.modalDialog}>
|
<div role="dialog" aria-modal="true" className={styles.modalDialog}>
|
||||||
<div className={styles.modalHeader}>
|
<div className={styles.modalHeader}>
|
||||||
<div className={styles.modalTitle}>Указать ключ</div>
|
<div className={styles.modalTitle}>{t('license.tokenTitle')}</div>
|
||||||
<button type="button" aria-label="Закрыть" onClick={onClose} className={styles.modalClose}>
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={t('common.close')}
|
||||||
|
onClick={onClose}
|
||||||
|
className={styles.modalClose}
|
||||||
|
>
|
||||||
×
|
×
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.fieldGrid}>
|
<div className={styles.fieldGrid}>
|
||||||
<div className={styles.fieldLabel}>КЛЮЧ</div>
|
<div className={styles.fieldLabel}>{t('license.tokenKey')}</div>
|
||||||
<textarea
|
<textarea
|
||||||
className={styles.licenseTextarea}
|
className={styles.licenseTextarea}
|
||||||
value={token}
|
value={token}
|
||||||
onChange={(e) => setToken(e.target.value)}
|
onChange={(e) => setToken(e.target.value)}
|
||||||
placeholder="Продуктовый ключ DND-..."
|
placeholder={t('license.tokenPlaceholder')}
|
||||||
spellCheck={false}
|
spellCheck={false}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{error ? <div className={styles.fieldError}>{error}</div> : null}
|
{error ? <div className={styles.fieldError}>{error}</div> : null}
|
||||||
<div className={styles.modalFooter}>
|
<div className={styles.modalFooter}>
|
||||||
<Button onClick={onClose} disabled={saving}>
|
<Button onClick={onClose} disabled={saving}>
|
||||||
Отмена
|
{t('common.cancel')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
@@ -82,7 +94,7 @@ export function LicenseTokenModal({ open, onClose, onSaved }: LicenseTokenModalP
|
|||||||
})();
|
})();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Сохранить
|
{t('common.save')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -98,6 +110,7 @@ type EulaModalProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function EulaModal({ open, onClose, onAccepted }: EulaModalProps) {
|
export function EulaModal({ open, onClose, onAccepted }: EulaModalProps) {
|
||||||
|
const { t, locale } = useEditorI18n();
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -113,18 +126,29 @@ export function EulaModal({ open, onClose, onAccepted }: EulaModalProps) {
|
|||||||
|
|
||||||
return createPortal(
|
return createPortal(
|
||||||
<>
|
<>
|
||||||
<button type="button" aria-label="Закрыть" onClick={onClose} className={styles.modalBackdrop} />
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={t('common.close')}
|
||||||
|
onClick={onClose}
|
||||||
|
className={styles.modalBackdrop}
|
||||||
|
/>
|
||||||
<div role="dialog" aria-modal="true" className={styles.modalDialog}>
|
<div role="dialog" aria-modal="true" className={styles.modalDialog}>
|
||||||
<div className={styles.modalHeader}>
|
<div className={styles.modalHeader}>
|
||||||
<div className={styles.modalTitle}>Лицензионное соглашение</div>
|
<div className={styles.modalTitle}>{t('license.eulaTitle')}</div>
|
||||||
<button type="button" aria-label="Закрыть" onClick={onClose} className={styles.modalClose}>
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={t('common.close')}
|
||||||
|
onClick={onClose}
|
||||||
|
className={styles.modalClose}
|
||||||
|
>
|
||||||
×
|
×
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
{locale === 'en' ? <div className={styles.muted}>{t('license.eulaNoteEn')}</div> : null}
|
||||||
<div className={styles.eulaScroll}>{EULA_RU_MARKDOWN}</div>
|
<div className={styles.eulaScroll}>{EULA_RU_MARKDOWN}</div>
|
||||||
<div className={styles.modalFooter}>
|
<div className={styles.modalFooter}>
|
||||||
<Button onClick={onClose} disabled={saving}>
|
<Button onClick={onClose} disabled={saving}>
|
||||||
Не принимаю
|
{t('license.eulaReject')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
@@ -144,7 +168,7 @@ export function EulaModal({ open, onClose, onAccepted }: EulaModalProps) {
|
|||||||
})();
|
})();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Принимаю условия
|
{t('license.eulaAccept')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -159,32 +183,16 @@ type LicenseAboutModalProps = {
|
|||||||
snapshot: LicenseSnapshot | null;
|
snapshot: LicenseSnapshot | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
function reasonLabel(reason: LicenseSnapshot['reason']): string {
|
function licenseReasonLabel(t: (key: string) => string, reason: LicenseSnapshot['reason']): string {
|
||||||
switch (reason) {
|
const key = `license.reason.${reason}`;
|
||||||
case 'ok':
|
const label = t(key);
|
||||||
return 'Активна';
|
return label === key ? reason : label;
|
||||||
case 'none':
|
|
||||||
return 'Ключ не указан';
|
|
||||||
case 'expired':
|
|
||||||
return 'Срок действия истёк';
|
|
||||||
case 'bad_signature':
|
|
||||||
return 'Недействительная подпись';
|
|
||||||
case 'bad_payload':
|
|
||||||
return 'Неверный формат токена';
|
|
||||||
case 'malformed':
|
|
||||||
return 'Повреждённый токен';
|
|
||||||
case 'not_yet_valid':
|
|
||||||
return 'Ещё не действует';
|
|
||||||
case 'wrong_device':
|
|
||||||
return 'Другой привязанный компьютер';
|
|
||||||
case 'revoked_remote':
|
|
||||||
return 'Отозвана на сервере';
|
|
||||||
default:
|
|
||||||
return reason;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function LicenseAboutModal({ open, onClose, snapshot }: LicenseAboutModalProps) {
|
export function LicenseAboutModal({ open, onClose, snapshot }: LicenseAboutModalProps) {
|
||||||
|
const { t, locale } = useEditorI18n();
|
||||||
|
const dateLocale = locale === 'en' ? 'en-US' : 'ru-RU';
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
const onKey = (e: KeyboardEvent) => {
|
const onKey = (e: KeyboardEvent) => {
|
||||||
@@ -198,7 +206,7 @@ export function LicenseAboutModal({ open, onClose, snapshot }: LicenseAboutModal
|
|||||||
|
|
||||||
const expText =
|
const expText =
|
||||||
snapshot?.summary?.exp != null
|
snapshot?.summary?.exp != null
|
||||||
? new Date(snapshot.summary.exp * 1000).toLocaleString('ru-RU', {
|
? new Date(snapshot.summary.exp * 1000).toLocaleString(dateLocale, {
|
||||||
dateStyle: 'long',
|
dateStyle: 'long',
|
||||||
timeStyle: 'short',
|
timeStyle: 'short',
|
||||||
})
|
})
|
||||||
@@ -206,48 +214,54 @@ export function LicenseAboutModal({ open, onClose, snapshot }: LicenseAboutModal
|
|||||||
|
|
||||||
return createPortal(
|
return createPortal(
|
||||||
<>
|
<>
|
||||||
<button type="button" aria-label="Закрыть" onClick={onClose} className={styles.modalBackdrop} />
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={t('common.close')}
|
||||||
|
onClick={onClose}
|
||||||
|
className={styles.modalBackdrop}
|
||||||
|
/>
|
||||||
<div role="dialog" aria-modal="true" className={styles.modalDialog}>
|
<div role="dialog" aria-modal="true" className={styles.modalDialog}>
|
||||||
<div className={styles.modalHeader}>
|
<div className={styles.modalHeader}>
|
||||||
<div className={styles.modalTitle}>О лицензии</div>
|
<div className={styles.modalTitle}>{t('license.aboutTitle')}</div>
|
||||||
<button type="button" aria-label="Закрыть" onClick={onClose} className={styles.modalClose}>
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={t('common.close')}
|
||||||
|
onClick={onClose}
|
||||||
|
className={styles.modalClose}
|
||||||
|
>
|
||||||
×
|
×
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{snapshot?.devSkip ? (
|
{snapshot?.devSkip ? <div className={styles.fieldError}>{t('license.aboutDevSkip')}</div> : null}
|
||||||
<div className={styles.fieldError}>
|
|
||||||
Режим разработки: проверка лицензии отключена (DND_SKIP_LICENSE).
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
<div className={styles.fieldGrid}>
|
<div className={styles.fieldGrid}>
|
||||||
<div className={styles.fieldLabel}>СТАТУС</div>
|
<div className={styles.fieldLabel}>{t('license.aboutStatus')}</div>
|
||||||
<div>{snapshot ? reasonLabel(snapshot.reason) : '—'}</div>
|
<div>{snapshot ? licenseReasonLabel(t, snapshot.reason) : '—'}</div>
|
||||||
</div>
|
</div>
|
||||||
{snapshot?.summary ? (
|
{snapshot?.summary ? (
|
||||||
<>
|
<>
|
||||||
<div className={styles.fieldGrid}>
|
<div className={styles.fieldGrid}>
|
||||||
<div className={styles.fieldLabel}>ПРОДУКТ</div>
|
<div className={styles.fieldLabel}>{t('license.aboutProduct')}</div>
|
||||||
<div>{snapshot.summary.pid}</div>
|
<div>{snapshot.summary.pid}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.fieldGrid}>
|
<div className={styles.fieldGrid}>
|
||||||
<div className={styles.fieldLabel}>ID ЛИЦЕНЗИИ</div>
|
<div className={styles.fieldLabel}>{t('license.aboutLicenseId')}</div>
|
||||||
<div style={{ wordBreak: 'break-all' }}>{snapshot.summary.sub}</div>
|
<div style={{ wordBreak: 'break-all' }}>{snapshot.summary.sub}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.fieldGrid}>
|
<div className={styles.fieldGrid}>
|
||||||
<div className={styles.fieldLabel}>ОКОНЧАНИЕ</div>
|
<div className={styles.fieldLabel}>{t('license.aboutExpiry')}</div>
|
||||||
<div>{expText}</div>
|
<div>{expText}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.fieldGrid}>
|
<div className={styles.fieldGrid}>
|
||||||
<div className={styles.fieldLabel}>УСТРОЙСТВО</div>
|
<div className={styles.fieldLabel}>{t('license.aboutDevice')}</div>
|
||||||
<div style={{ wordBreak: 'break-all' }}>{snapshot.deviceId}</div>
|
<div style={{ wordBreak: 'break-all' }}>{snapshot.deviceId}</div>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<div className={styles.muted}>Нет данных лицензии.</div>
|
<div className={styles.muted}>{t('license.aboutNoData')}</div>
|
||||||
)}
|
)}
|
||||||
<div className={styles.modalFooter}>
|
<div className={styles.modalFooter}>
|
||||||
<Button variant="primary" onClick={onClose}>
|
<Button variant="primary" onClick={onClose}>
|
||||||
Закрыть
|
{t('common.close')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client';
|
|||||||
|
|
||||||
import '../shared/ui/globals.css';
|
import '../shared/ui/globals.css';
|
||||||
import { EditorApp } from './EditorApp';
|
import { EditorApp } from './EditorApp';
|
||||||
|
import { EditorI18nProvider } from './i18n/EditorI18nContext';
|
||||||
|
|
||||||
const rootEl = document.getElementById('root');
|
const rootEl = document.getElementById('root');
|
||||||
if (!rootEl) {
|
if (!rootEl) {
|
||||||
@@ -11,6 +12,8 @@ if (!rootEl) {
|
|||||||
|
|
||||||
createRoot(rootEl).render(
|
createRoot(rootEl).render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<EditorApp />
|
<EditorI18nProvider>
|
||||||
|
<EditorApp />
|
||||||
|
</EditorI18nProvider>
|
||||||
</React.StrictMode>,
|
</React.StrictMode>,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ const here = path.dirname(fileURLToPath(import.meta.url));
|
|||||||
void test('projectState: list/get after delete invalidates in-flight initial load (epoch guard)', () => {
|
void test('projectState: list/get after delete invalidates in-flight initial load (epoch guard)', () => {
|
||||||
const src = fs.readFileSync(path.join(here, 'projectState.ts'), 'utf8');
|
const src = fs.readFileSync(path.join(here, 'projectState.ts'), 'utf8');
|
||||||
assert.match(src, /projectDataEpochRef/);
|
assert.match(src, /projectDataEpochRef/);
|
||||||
assert.match(src, /const epoch = projectDataEpochRef\.current/);
|
assert.match(src, /const epoch = \+\+projectDataEpochRef\.current/);
|
||||||
assert.match(src, /if \(projectDataEpochRef\.current !== epoch\) return/);
|
assert.match(src, /if \(projectDataEpochRef\.current !== epoch\) return/);
|
||||||
assert.match(
|
assert.match(
|
||||||
src,
|
src,
|
||||||
@@ -21,3 +21,8 @@ void test('projectState: list/get after delete invalidates in-flight initial loa
|
|||||||
);
|
);
|
||||||
assert.match(src, /const refreshProjects = async \(\) => \{[\s\S]+?projectDataEpochRef\.current \+= 1/);
|
assert.match(src, /const refreshProjects = async \(\) => \{[\s\S]+?projectDataEpochRef\.current \+= 1/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
void test('ipc router: project.list does not require license', () => {
|
||||||
|
const routerSrc = fs.readFileSync(path.join(here, '..', '..', '..', 'main', 'ipc', 'router.ts'), 'utf8');
|
||||||
|
assert.match(routerSrc, /if \(channel === ipcChannels\.project\.list\) return false/);
|
||||||
|
});
|
||||||
|
|||||||
@@ -58,8 +58,18 @@ function randomId(prefix: string): string {
|
|||||||
return `${prefix}_${Math.random().toString(16).slice(2)}_${Date.now().toString(16)}`;
|
return `${prefix}_${Math.random().toString(16).slice(2)}_${Date.now().toString(16)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useProjectState(licenseActive: boolean): readonly [State, Actions] {
|
export type ProjectNoticeCode = 'campaign_audio_empty';
|
||||||
|
|
||||||
|
export type ProjectStateOpts = {
|
||||||
|
onNotice?: (code: ProjectNoticeCode) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useProjectState(licenseActive: boolean, opts?: ProjectStateOpts): readonly [State, Actions] {
|
||||||
const api = getDndApi();
|
const api = getDndApi();
|
||||||
|
const onNoticeRef = useRef(opts?.onNotice);
|
||||||
|
useEffect(() => {
|
||||||
|
onNoticeRef.current = opts?.onNotice;
|
||||||
|
}, [opts?.onNotice]);
|
||||||
const [state, setState] = useState<State>({
|
const [state, setState] = useState<State>({
|
||||||
projects: [],
|
projects: [],
|
||||||
project: null,
|
project: null,
|
||||||
@@ -131,7 +141,7 @@ export function useProjectState(licenseActive: boolean): readonly [State, Action
|
|||||||
|
|
||||||
const closeProject = async () => {
|
const closeProject = async () => {
|
||||||
setState((s) => ({ ...s, project: null, selectedSceneId: null }));
|
setState((s) => ({ ...s, project: null, selectedSceneId: null }));
|
||||||
if (licenseActive) await refreshProjects();
|
await refreshProjects();
|
||||||
};
|
};
|
||||||
|
|
||||||
const createScene = async () => {
|
const createScene = async () => {
|
||||||
@@ -180,7 +190,7 @@ export function useProjectState(licenseActive: boolean): readonly [State, Action
|
|||||||
const res = await api.invoke(ipcChannels.project.importCampaignAudio, {});
|
const res = await api.invoke(ipcChannels.project.importCampaignAudio, {});
|
||||||
if (res.canceled) return;
|
if (res.canceled) return;
|
||||||
if (res.imported.length === 0) {
|
if (res.imported.length === 0) {
|
||||||
window.alert('Аудио не добавлено. Проверьте формат файла.');
|
onNoticeRef.current?.('campaign_audio_empty');
|
||||||
}
|
}
|
||||||
setState((s) => ({ ...s, project: res.project }));
|
setState((s) => ({ ...s, project: res.project }));
|
||||||
await refreshProjects();
|
await refreshProjects();
|
||||||
@@ -385,24 +395,37 @@ export function useProjectState(licenseActive: boolean): readonly [State, Action
|
|||||||
exportProject,
|
exportProject,
|
||||||
deleteProject,
|
deleteProject,
|
||||||
};
|
};
|
||||||
}, [api, licenseActive]);
|
}, [api]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!licenseActive) {
|
const epoch = ++projectDataEpochRef.current;
|
||||||
queueMicrotask(() => {
|
|
||||||
projectDataEpochRef.current += 1;
|
|
||||||
setState({ projects: [], project: null, selectedSceneId: null, zipProgress: null });
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
void (async () => {
|
void (async () => {
|
||||||
const epoch = projectDataEpochRef.current;
|
try {
|
||||||
const listRes = await api.invoke(ipcChannels.project.list, {});
|
const listRes = await api.invoke(ipcChannels.project.list, {});
|
||||||
if (projectDataEpochRef.current !== epoch) return;
|
if (projectDataEpochRef.current !== epoch) return;
|
||||||
setState((s) => ({ ...s, projects: listRes.projects }));
|
if (!licenseActive) {
|
||||||
const res = await api.invoke(ipcChannels.project.get, {});
|
setState((s) => ({
|
||||||
if (projectDataEpochRef.current !== epoch) return;
|
...s,
|
||||||
setState((s) => ({ ...s, project: res.project, selectedSceneId: res.project?.currentSceneId ?? null }));
|
projects: listRes.projects,
|
||||||
|
project: null,
|
||||||
|
selectedSceneId: null,
|
||||||
|
}));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState((s) => ({ ...s, projects: listRes.projects }));
|
||||||
|
const res = await api.invoke(ipcChannels.project.get, {});
|
||||||
|
if (projectDataEpochRef.current !== epoch) return;
|
||||||
|
setState((s) => ({
|
||||||
|
...s,
|
||||||
|
project: res.project,
|
||||||
|
selectedSceneId: res.project?.currentSceneId ?? null,
|
||||||
|
}));
|
||||||
|
} catch {
|
||||||
|
if (projectDataEpochRef.current !== epoch) return;
|
||||||
|
if (!licenseActive) {
|
||||||
|
setState((s) => ({ ...s, project: null, selectedSceneId: null }));
|
||||||
|
}
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
}, [licenseActive, api]);
|
}, [licenseActive, api]);
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
export const EULA_RU_MARKDOWN = `
|
export const EULA_RU_MARKDOWN = `
|
||||||
# Лицензионное соглашение с конечным пользователем (EULA)
|
# Лицензионное соглашение с конечным пользователем (EULA)
|
||||||
|
|
||||||
Используя DNDGamePlayer («Программу»), вы соглашаетесь с условиями ниже.
|
Используя НРИ Плеер («Программу»), вы соглашаетесь с условиями ниже.
|
||||||
|
|
||||||
## 1. Предоставление прав
|
## 1. Предоставление прав
|
||||||
Правообладатель предоставляет вам неисключическую, непередаваемую лицензию на использование Программы в пределах приобретённой лицензии (активации).
|
Правообладатель предоставляет вам неисключическую, непередаваемую лицензию на использование Программы в пределах приобретённой лицензии (активации).
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<link rel="icon" href="/app-window-icon.png" type="image/png" />
|
<link rel="icon" href="/app-window-icon.png" type="image/png" />
|
||||||
<title>DnD Player — Presentation</title>
|
<title>TTRPG - Presentation</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
|
||||||
import styles from './RotatedImage.module.css';
|
import styles from './RotatedImage.module.css';
|
||||||
|
|
||||||
@@ -24,13 +24,15 @@ function useElementSize<T extends HTMLElement>() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const el = ref.current;
|
const el = ref.current;
|
||||||
if (!el) return;
|
if (!el) return;
|
||||||
|
// clientWidth/Height — локальная вёрстка; getBoundingClientRect учитывает transform предков (React Flow zoom).
|
||||||
|
const readLayoutSize = () => {
|
||||||
|
setSize({ w: el.clientWidth, h: el.clientHeight });
|
||||||
|
};
|
||||||
const ro = new ResizeObserver(() => {
|
const ro = new ResizeObserver(() => {
|
||||||
const r = el.getBoundingClientRect();
|
readLayoutSize();
|
||||||
setSize({ w: r.width, h: r.height });
|
|
||||||
});
|
});
|
||||||
ro.observe(el);
|
ro.observe(el);
|
||||||
const r = el.getBoundingClientRect();
|
readLayoutSize();
|
||||||
setSize({ w: r.width, h: r.height });
|
|
||||||
return () => ro.disconnect();
|
return () => ro.disconnect();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
@@ -49,18 +51,19 @@ export function RotatedImage({
|
|||||||
}: RotatedImageProps) {
|
}: RotatedImageProps) {
|
||||||
const [ref, size] = useElementSize<HTMLDivElement>();
|
const [ref, size] = useElementSize<HTMLDivElement>();
|
||||||
const [imgSize, setImgSize] = useState<{ w: number; h: number } | null>(null);
|
const [imgSize, setImgSize] = useState<{ w: number; h: number } | null>(null);
|
||||||
|
const imgRef = useRef<HTMLImageElement | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useLayoutEffect(() => {
|
||||||
let cancelled = false;
|
// If the image is served from cache, onLoad may fire before listeners attach.
|
||||||
const img = new Image();
|
// Reading from the <img> element itself is the most reliable source.
|
||||||
img.onload = () => {
|
const el = imgRef.current;
|
||||||
if (cancelled) return;
|
if (!el) return;
|
||||||
setImgSize({ w: img.naturalWidth || 1, h: img.naturalHeight || 1 });
|
if (!el.complete) return;
|
||||||
};
|
const w0 = el.naturalWidth || 0;
|
||||||
img.src = url;
|
const h0 = el.naturalHeight || 0;
|
||||||
return () => {
|
if (w0 <= 0 || h0 <= 0) return;
|
||||||
cancelled = true;
|
// eslint-disable-next-line react-hooks/set-state-in-effect, @typescript-eslint/prefer-optional-chain -- read cached <img> dimensions when onLoad may not fire
|
||||||
};
|
setImgSize((prev) => (prev && prev.w === w0 && prev.h === h0 ? prev : { w: w0, h: h0 }));
|
||||||
}, [url]);
|
}, [url]);
|
||||||
|
|
||||||
const scale = useMemo(() => {
|
const scale = useMemo(() => {
|
||||||
@@ -93,11 +96,23 @@ export function RotatedImage({
|
|||||||
return (
|
return (
|
||||||
<div ref={ref} className={styles.root} style={style}>
|
<div ref={ref} className={styles.root} style={style}>
|
||||||
<img
|
<img
|
||||||
|
ref={imgRef}
|
||||||
alt={alt}
|
alt={alt}
|
||||||
src={url}
|
src={url}
|
||||||
loading={loading}
|
loading={loading}
|
||||||
decoding={decoding}
|
decoding={decoding}
|
||||||
className={styles.img}
|
className={styles.img}
|
||||||
|
onLoad={(e) => {
|
||||||
|
const el = e.currentTarget;
|
||||||
|
const w0 = el.naturalWidth || 0;
|
||||||
|
const h0 = el.naturalHeight || 0;
|
||||||
|
if (w0 <= 0 || h0 <= 0) return;
|
||||||
|
setImgSize((prev) => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain -- rule can misfire on React state unions
|
||||||
|
if (prev && prev.w === w0 && prev.h === h0) return prev;
|
||||||
|
return { w: w0, h: h0 };
|
||||||
|
});
|
||||||
|
}}
|
||||||
style={{
|
style={{
|
||||||
width: w ?? '100%',
|
width: w ?? '100%',
|
||||||
height: h ?? '100%',
|
height: h ?? '100%',
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
/** Отображаемое имя продукта (с пробелом), не путать с `productName` сборки (`TTRPGPlayer`). */
|
||||||
|
export const APP_DISPLAY_NAME_EN = 'TTRPG Player';
|
||||||
|
export const APP_DISPLAY_NAME_RU = 'НРИ Плеер';
|
||||||
|
|
||||||
|
/** Системный идентификатор приложения (exe, AppImage, appId). */
|
||||||
|
export const APP_PRODUCT_NAME = 'TTRPGPlayer';
|
||||||
|
export const APP_BUNDLE_ID = 'com.ttrpgplayer.app';
|
||||||
|
|
||||||
|
export function appDisplayNameForLocale(localeTag: string): string {
|
||||||
|
const tag = localeTag.trim().toLowerCase();
|
||||||
|
if (tag.startsWith('ru')) return APP_DISPLAY_NAME_RU;
|
||||||
|
return APP_DISPLAY_NAME_EN;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Префикс заголовка окон: `TTRPG - Редактор`. */
|
||||||
|
export const APP_WINDOW_BRAND = 'TTRPG';
|
||||||
|
|
||||||
|
export type AppWindowKind = 'editor' | 'presentation' | 'control' | 'boot';
|
||||||
|
|
||||||
|
const WINDOW_SUFFIX: Record<AppWindowKind, { ru: string; en: string }> = {
|
||||||
|
editor: { ru: 'Редактор', en: 'Editor' },
|
||||||
|
presentation: { ru: 'Презентация', en: 'Presentation' },
|
||||||
|
control: { ru: 'Пульт', en: 'Control' },
|
||||||
|
boot: { ru: 'Загрузка', en: 'Loading' },
|
||||||
|
};
|
||||||
|
|
||||||
|
export function windowChromeTitle(kind: AppWindowKind, localeTag: string): string {
|
||||||
|
const tag = localeTag.trim().toLowerCase();
|
||||||
|
const suffix = tag.startsWith('ru') ? WINDOW_SUFFIX[kind].ru : WINDOW_SUFFIX[kind].en;
|
||||||
|
return `${APP_WINDOW_BRAND} - ${suffix}`;
|
||||||
|
}
|
||||||
@@ -18,6 +18,11 @@ export const ipcChannels = {
|
|||||||
quit: 'app.quit',
|
quit: 'app.quit',
|
||||||
getVersion: 'app.getVersion',
|
getVersion: 'app.getVersion',
|
||||||
},
|
},
|
||||||
|
updater: {
|
||||||
|
check: 'updater.check',
|
||||||
|
downloadAndRestart: 'updater.downloadAndRestart',
|
||||||
|
progress: 'updater.progress',
|
||||||
|
},
|
||||||
project: {
|
project: {
|
||||||
list: 'project.list',
|
list: 'project.list',
|
||||||
create: 'project.create',
|
create: 'project.create',
|
||||||
@@ -52,6 +57,8 @@ export const ipcChannels = {
|
|||||||
openMultiWindow: 'windows.openMultiWindow',
|
openMultiWindow: 'windows.openMultiWindow',
|
||||||
closeMultiWindow: 'windows.closeMultiWindow',
|
closeMultiWindow: 'windows.closeMultiWindow',
|
||||||
togglePresentationFullscreen: 'windows.togglePresentationFullscreen',
|
togglePresentationFullscreen: 'windows.togglePresentationFullscreen',
|
||||||
|
getMultiWindowState: 'windows.getMultiWindowState',
|
||||||
|
multiWindowStateChanged: 'windows.multiWindowStateChanged',
|
||||||
},
|
},
|
||||||
session: {
|
session: {
|
||||||
stateChanged: 'session.stateChanged',
|
stateChanged: 'session.stateChanged',
|
||||||
@@ -82,13 +89,40 @@ export type ZipProgressEvent = {
|
|||||||
detail?: string;
|
detail?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type UpdaterCheckResponse =
|
||||||
|
| { outcome: 'not_packaged' }
|
||||||
|
| { outcome: 'no_license' }
|
||||||
|
| { outcome: 'current'; currentVersion: string }
|
||||||
|
| { outcome: 'available'; version: string }
|
||||||
|
| { outcome: 'error'; message: string };
|
||||||
|
|
||||||
|
export type UpdaterDownloadResponse = { ok: true } | { ok: false; message: string };
|
||||||
|
|
||||||
|
export type UpdaterProgressPhase =
|
||||||
|
| 'checking'
|
||||||
|
| 'available'
|
||||||
|
| 'not-available'
|
||||||
|
| 'downloading'
|
||||||
|
| 'installing'
|
||||||
|
| 'error';
|
||||||
|
|
||||||
|
export type UpdaterProgressEvent = {
|
||||||
|
phase: UpdaterProgressPhase;
|
||||||
|
/** 0..100 при phase=downloading */
|
||||||
|
percent?: number;
|
||||||
|
version?: string;
|
||||||
|
message?: string;
|
||||||
|
};
|
||||||
|
|
||||||
export type IpcEventMap = {
|
export type IpcEventMap = {
|
||||||
[ipcChannels.session.stateChanged]: { state: SessionState };
|
[ipcChannels.session.stateChanged]: { state: SessionState };
|
||||||
[ipcChannels.effects.stateChanged]: { state: EffectsState };
|
[ipcChannels.effects.stateChanged]: { state: EffectsState };
|
||||||
[ipcChannels.video.stateChanged]: { state: VideoPlaybackState };
|
[ipcChannels.video.stateChanged]: { state: VideoPlaybackState };
|
||||||
[ipcChannels.license.statusChanged]: { snapshot: LicenseSnapshot };
|
[ipcChannels.license.statusChanged]: { snapshot: LicenseSnapshot };
|
||||||
|
[ipcChannels.windows.multiWindowStateChanged]: { open: boolean };
|
||||||
[ipcChannels.project.importZipProgress]: ZipProgressEvent;
|
[ipcChannels.project.importZipProgress]: ZipProgressEvent;
|
||||||
[ipcChannels.project.exportZipProgress]: ZipProgressEvent;
|
[ipcChannels.project.exportZipProgress]: ZipProgressEvent;
|
||||||
|
[ipcChannels.updater.progress]: UpdaterProgressEvent;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type IpcInvokeMap = {
|
export type IpcInvokeMap = {
|
||||||
@@ -98,7 +132,15 @@ export type IpcInvokeMap = {
|
|||||||
};
|
};
|
||||||
[ipcChannels.app.getVersion]: {
|
[ipcChannels.app.getVersion]: {
|
||||||
req: Record<string, never>;
|
req: Record<string, never>;
|
||||||
res: { version: string; buildNumber: string | null };
|
res: { version: string; buildNumber: string | null; packaged: boolean };
|
||||||
|
};
|
||||||
|
[ipcChannels.updater.check]: {
|
||||||
|
req: Record<string, never>;
|
||||||
|
res: UpdaterCheckResponse;
|
||||||
|
};
|
||||||
|
[ipcChannels.updater.downloadAndRestart]: {
|
||||||
|
req: { version: string };
|
||||||
|
res: UpdaterDownloadResponse;
|
||||||
};
|
};
|
||||||
[ipcChannels.project.list]: {
|
[ipcChannels.project.list]: {
|
||||||
req: Record<string, never>;
|
req: Record<string, never>;
|
||||||
@@ -216,6 +258,10 @@ export type IpcInvokeMap = {
|
|||||||
req: Record<string, never>;
|
req: Record<string, never>;
|
||||||
res: { ok: true; isFullScreen: boolean };
|
res: { ok: true; isFullScreen: boolean };
|
||||||
};
|
};
|
||||||
|
[ipcChannels.windows.getMultiWindowState]: {
|
||||||
|
req: Record<string, never>;
|
||||||
|
res: { open: boolean };
|
||||||
|
};
|
||||||
[ipcChannels.effects.getState]: {
|
[ipcChannels.effects.getState]: {
|
||||||
req: Record<string, never>;
|
req: Record<string, never>;
|
||||||
res: { state: EffectsState };
|
res: { state: EffectsState };
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
|
|
||||||
import { isDndProductKey } from './productKey';
|
import { isProductKey } from './productKey';
|
||||||
|
|
||||||
void test('isDndProductKey: пример пользователя', () => {
|
void test('isProductKey: legacy DND prefix', () => {
|
||||||
assert.equal(isDndProductKey('DND-CEBEC1BF-AD0B-4312-BFDD-675AFF5955FD'), true);
|
assert.equal(isProductKey('DND-CEBEC1BF-AD0B-4312-BFDD-675AFF5955FD'), true);
|
||||||
});
|
});
|
||||||
|
|
||||||
void test('isDndProductKey: токен с точкой — нет', () => {
|
void test('isProductKey: TTRPG prefix', () => {
|
||||||
assert.equal(isDndProductKey('eyJ.xxx'), false);
|
assert.equal(isProductKey('TTRPG-CEBEC1BF-AD0B-4312-BFDD-675AFF5955FD'), true);
|
||||||
});
|
});
|
||||||
|
|
||||||
void test('isDndProductKey: пробелы по краям', () => {
|
void test('isProductKey: token with dot — no', () => {
|
||||||
assert.equal(isDndProductKey(' DND-CEBEC1BF-AD0B-4312-BFDD-675AFF5955FD '), true);
|
assert.equal(isProductKey('eyJ.xxx'), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('isProductKey: trimmed', () => {
|
||||||
|
assert.equal(isProductKey(' TTRPG-CEBEC1BF-AD0B-4312-BFDD-675AFF5955FD '), true);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,13 @@
|
|||||||
/** Продуктовый ключ активации (не путать с лицензионным токеном `base64.base64`). */
|
/** Продуктовый ключ активации (не путать с лицензионным токеном `base64.base64`). */
|
||||||
|
const TTRPG_PRODUCT_KEY_RE = /^TTRPG-[0-9A-F]{8}-(?:[0-9A-F]{4}-){3}[0-9A-F]{12}$/iu;
|
||||||
const DND_PRODUCT_KEY_RE = /^DND-[0-9A-F]{8}-(?:[0-9A-F]{4}-){3}[0-9A-F]{12}$/iu;
|
const DND_PRODUCT_KEY_RE = /^DND-[0-9A-F]{8}-(?:[0-9A-F]{4}-){3}[0-9A-F]{12}$/iu;
|
||||||
|
|
||||||
export function isDndProductKey(s: string): boolean {
|
export function isProductKey(s: string): boolean {
|
||||||
return DND_PRODUCT_KEY_RE.test(s.trim());
|
const t = s.trim();
|
||||||
|
return TTRPG_PRODUCT_KEY_RE.test(t) || DND_PRODUCT_KEY_RE.test(t);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @deprecated Используйте {@link isProductKey}. */
|
||||||
|
export function isDndProductKey(s: string): boolean {
|
||||||
|
return isProductKey(s);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,21 +6,61 @@ import { fileURLToPath } from 'node:url';
|
|||||||
|
|
||||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
|
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
|
||||||
|
|
||||||
void test('package.json: конфиг electron-builder (mac/win)', () => {
|
void test('package.json: конфиг electron-builder (mac/win/linux)', () => {
|
||||||
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')) as {
|
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')) as {
|
||||||
build: {
|
build: {
|
||||||
appId: string;
|
appId: string;
|
||||||
asar: boolean;
|
asar: boolean;
|
||||||
asarUnpack: string[];
|
asarUnpack: string[];
|
||||||
mac: { target: unknown };
|
extraResources: { from: string; to: string }[];
|
||||||
|
mac: { target: unknown; artifactName?: string };
|
||||||
|
linux: { target: unknown };
|
||||||
|
appImage?: { artifactName?: string };
|
||||||
|
nsis?: { artifactName?: string };
|
||||||
|
dmg?: { artifactName?: string };
|
||||||
files: string[];
|
files: string[];
|
||||||
|
toolsets?: { appimage?: string };
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
assert.ok(pkg.build);
|
assert.ok(pkg.build);
|
||||||
assert.equal(pkg.build.appId, 'com.dndplayer.app');
|
assert.equal(pkg.build.appId, 'com.ttrpgplayer.app');
|
||||||
assert.equal(pkg.build.asar, true, 'релизный артефакт: app.asar без «голого» дерева dist в .app/.exe');
|
assert.equal(pkg.build.asar, true, 'релизный артефакт: app.asar без «голого» дерева dist в .app/.exe');
|
||||||
assert.ok(Array.isArray(pkg.build.asarUnpack));
|
assert.ok(Array.isArray(pkg.build.asarUnpack));
|
||||||
assert.ok(pkg.build.asarUnpack.some((p) => p.includes('preload')));
|
assert.ok(pkg.build.asarUnpack.some((p) => p.includes('preload')));
|
||||||
|
assert.ok(Array.isArray(pkg.build.extraResources));
|
||||||
|
assert.ok(
|
||||||
|
pkg.build.extraResources.some(
|
||||||
|
(e: unknown) =>
|
||||||
|
typeof e === 'object' &&
|
||||||
|
e !== null &&
|
||||||
|
'to' in e &&
|
||||||
|
typeof (e as { to: unknown }).to === 'string' &&
|
||||||
|
(e as { to: string }).to.includes('branding'),
|
||||||
|
),
|
||||||
|
);
|
||||||
assert.ok(Array.isArray(pkg.build.mac.target));
|
assert.ok(Array.isArray(pkg.build.mac.target));
|
||||||
|
assert.equal(pkg.build.mac.artifactName, '${productName}-${arch}.${ext}');
|
||||||
|
assert.ok(!pkg.build.mac.artifactName?.includes('version'));
|
||||||
|
assert.equal(pkg.build.toolsets?.appimage, '1.0.2');
|
||||||
|
assert.ok(Array.isArray(pkg.build.linux.target));
|
||||||
|
const linuxTargets = pkg.build.linux.target as { target: string; arch: string[] }[];
|
||||||
|
assert.ok(linuxTargets.some((t) => t.target === 'AppImage'));
|
||||||
|
assert.ok(linuxTargets.some((t) => t.arch.includes('x64') && t.arch.includes('arm64')));
|
||||||
|
assert.equal(pkg.build.appImage?.artifactName, '${productName}-${arch}.${ext}');
|
||||||
|
assert.equal(pkg.build.nsis?.artifactName, '${productName}-Setup.${ext}');
|
||||||
|
assert.equal(pkg.build.dmg?.artifactName, '${productName}-${arch}.${ext}');
|
||||||
|
assert.ok(!pkg.build.appImage?.artifactName?.includes('version'));
|
||||||
|
assert.ok(!pkg.build.nsis?.artifactName?.includes('version'));
|
||||||
assert.ok(pkg.build.files.includes('dist/**/*'));
|
assert.ok(pkg.build.files.includes('dist/**/*'));
|
||||||
|
assert.ok(
|
||||||
|
pkg.build.asarUnpack.some((p) => p.includes('@img')),
|
||||||
|
'sharp native binaries live under node_modules/@img',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('package.json: pack:mac runs release-mac-prep before electron-builder', () => {
|
||||||
|
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')) as {
|
||||||
|
scripts: { 'pack:mac': string };
|
||||||
|
};
|
||||||
|
assert.match(pkg.scripts['pack:mac'], /release-mac-prep\.mjs/);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
/** Текущий формат архива проекта (новые сохранения). */
|
||||||
|
export const PROJECT_ZIP_EXTENSION = '.ttrpg.zip';
|
||||||
|
|
||||||
|
/** Устаревший формат — только открытие / импорт (вариант B). */
|
||||||
|
export const PROJECT_ZIP_EXTENSION_LEGACY = '.dnd.zip';
|
||||||
|
|
||||||
|
export function isProjectZipFileName(fileName: string): boolean {
|
||||||
|
const lower = fileName.toLowerCase();
|
||||||
|
return lower.endsWith(PROJECT_ZIP_EXTENSION) || lower.endsWith(PROJECT_ZIP_EXTENSION_LEGACY);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isLegacyProjectZipFileName(fileName: string): boolean {
|
||||||
|
return fileName.toLowerCase().endsWith(PROJECT_ZIP_EXTENSION_LEGACY);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function projectZipFileNameFromBase(stem: string): string {
|
||||||
|
return `${stem}${PROJECT_ZIP_EXTENSION}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Имя файла для сохранения/экспорта — всегда `.ttrpg.zip`. */
|
||||||
|
export function normalizeSaveProjectZipPath(filePath: string): string {
|
||||||
|
const lower = filePath.toLowerCase();
|
||||||
|
if (lower.endsWith(PROJECT_ZIP_EXTENSION)) return filePath;
|
||||||
|
if (lower.endsWith(PROJECT_ZIP_EXTENSION_LEGACY)) {
|
||||||
|
return filePath.slice(0, -PROJECT_ZIP_EXTENSION_LEGACY.length) + PROJECT_ZIP_EXTENSION;
|
||||||
|
}
|
||||||
|
if (lower.endsWith('.zip')) {
|
||||||
|
return filePath.replace(/\.zip$/iu, PROJECT_ZIP_EXTENSION);
|
||||||
|
}
|
||||||
|
return `${filePath}${PROJECT_ZIP_EXTENSION}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function stripProjectZipExtension(fileName: string): string {
|
||||||
|
const lower = fileName.toLowerCase();
|
||||||
|
if (lower.endsWith(PROJECT_ZIP_EXTENSION)) {
|
||||||
|
return fileName.slice(0, -PROJECT_ZIP_EXTENSION.length);
|
||||||
|
}
|
||||||
|
if (lower.endsWith(PROJECT_ZIP_EXTENSION_LEGACY)) {
|
||||||
|
return fileName.slice(0, -PROJECT_ZIP_EXTENSION_LEGACY.length);
|
||||||
|
}
|
||||||
|
return fileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PROJECT_ZIP_OPEN_DIALOG_FILTER: Electron.FileFilter = {
|
||||||
|
name: 'Проект TTRPG (*.ttrpg.zip, *.dnd.zip)',
|
||||||
|
extensions: ['ttrpg.zip', 'dnd.zip'],
|
||||||
|
};
|
||||||
|
|
||||||
|
export const PROJECT_ZIP_SAVE_DIALOG_FILTER: Electron.FileFilter = {
|
||||||
|
name: 'Проект TTRPG (*.ttrpg.zip)',
|
||||||
|
extensions: ['ttrpg.zip'],
|
||||||
|
};
|
||||||
@@ -98,7 +98,7 @@ export type Scene = {
|
|||||||
|
|
||||||
export type ProjectMeta = {
|
export type ProjectMeta = {
|
||||||
name: string;
|
name: string;
|
||||||
/** Имя файла проекта без суффикса `.dnd.zip` (то, что пользователь редактирует). */
|
/** Имя файла проекта без суффикса `.ttrpg.zip` (то, что пользователь редактирует). */
|
||||||
fileBaseName: string;
|
fileBaseName: string;
|
||||||
createdAt: IsoDateTimeString;
|
createdAt: IsoDateTimeString;
|
||||||
updatedAt: IsoDateTimeString;
|
updatedAt: IsoDateTimeString;
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# Автообновления TTRPG Player
|
||||||
|
|
||||||
|
## Сборка и публикация
|
||||||
|
|
||||||
|
- Релизы собираются **локально** (CI отключён).
|
||||||
|
- Артефакты кладутся в `D:\TTRPG-Release\` (или копируются из `release\` после сборки).
|
||||||
|
- Подготовка релиза: **`D:\TTRPG-Release\prepare-release.cmd`** (версия, git, сборка Win/Linux, копирование в папку).
|
||||||
|
- Публикация на VPS: **`D:\TTRPG-Release\publish.cmd`** (проверка + `scp`). Копия в репо: `scripts/ttrpg-release/`
|
||||||
|
- **Имена файлов без версии** — версия только в `latest*.yml`.
|
||||||
|
|
||||||
|
## Feed URL
|
||||||
|
|
||||||
|
В `package.json` → `build.publish.url`:
|
||||||
|
|
||||||
|
`https://updates.mailib.ru/`
|
||||||
|
|
||||||
|
Обязателен **слэш в конце**. URL вшивается в установщик при `npm run pack:win`.
|
||||||
|
|
||||||
|
## Фиксированные имена артефактов
|
||||||
|
|
||||||
|
| Платформа | Файлы |
|
||||||
|
|-----------|--------|
|
||||||
|
| Windows | `latest.yml`, `TTRPGPlayer-Setup.exe`, `TTRPGPlayer-Setup.exe.blockmap` |
|
||||||
|
| Linux | `latest-linux.yml`, `TTRPGPlayer-x64.AppImage`, `TTRPGPlayer-arm64.AppImage` |
|
||||||
|
| macOS | `latest-mac.yml`, `TTRPGPlayer-x64.dmg`, `TTRPGPlayer-arm64.dmg` |
|
||||||
|
|
||||||
|
## Локальная сборка
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm ci
|
||||||
|
npm run build
|
||||||
|
npm run release:info
|
||||||
|
```
|
||||||
|
|
||||||
|
| Команда | Где | Результат |
|
||||||
|
|---------|-----|-----------|
|
||||||
|
| `npm run pack:win` | Windows | `release\` — Win + `latest.yml` |
|
||||||
|
| `npm run pack:linux` | Linux / WSL | AppImage + `latest-linux*.yml` |
|
||||||
|
| `npm run pack:mac` | macOS | dmg + `latest-mac.yml` |
|
||||||
|
|
||||||
|
Linux из PowerShell напрямую не собирается — только WSL/Linux (`scripts/release-linux-pack.mjs`).
|
||||||
|
|
||||||
|
После `pack:win` скопируйте из `release\` в `D:\TTRPG-Release\` файлы из таблицы выше.
|
||||||
|
|
||||||
|
## Сервер
|
||||||
|
|
||||||
|
- Домен: `https://updates.mailib.ru/`
|
||||||
|
- nginx `root`: `/var/www/updates_mailib_ru`
|
||||||
|
- Проверка: `curl https://updates.mailib.ru/latest.yml`
|
||||||
|
|
||||||
|
## Лицензия
|
||||||
|
|
||||||
|
Обновления доступны при активной лицензии. Ключи: `TTRPG-…` и устаревшие `DND-…`.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# macOS: сборка и выкладка обновлений
|
||||||
|
|
||||||
|
## Сборка на Mac
|
||||||
|
|
||||||
|
```bash
|
||||||
|
FFMPEG_BINARIES_URL=https://cdn.npmmirror.com/binaries/ffmpeg-static npm ci
|
||||||
|
npm run pack:mac
|
||||||
|
```
|
||||||
|
|
||||||
|
`pack:mac` сам вызывает `build` и `scripts/release-mac-prep.mjs` — подтягивает **оба** набора нативных бинарников sharp (x64 и arm64). Без этого x64-сборка с Apple Silicon падает при старте с ошибкой `Could not load the "sharp" module using the darwin-x64 runtime`.
|
||||||
|
Переменная `FFMPEG_BINARIES_URL` нужна только чтобы `ffmpeg-static` не падал из-за временных 5xx на GitHub при `npm ci`.
|
||||||
|
|
||||||
|
В `release/` (имена **без версии**):
|
||||||
|
|
||||||
|
- `latest-mac.yml` — сгенерирован electron-builder, не копируйте старый с Windows
|
||||||
|
- `TTRPGPlayer-x64.zip` и `TTRPGPlayer-arm64.zip` — **нужны для автообновления** (поле `path` в yml)
|
||||||
|
- `TTRPGPlayer-x64.dmg`, `TTRPGPlayer-arm64.dmg` — опционально, для ручной установки
|
||||||
|
|
||||||
|
Скопируйте эти файлы на Windows в общую папку релиза (вместе с Win/Linux) и залейте на VPS вместе с остальными.
|
||||||
|
|
||||||
|
## Проверка после выкладки
|
||||||
|
|
||||||
|
`https://updates.mailib.ru/latest-mac.yml` (подставьте свой feed URL)
|
||||||
Binary file not shown.
Binary file not shown.
+14
-2
@@ -1,4 +1,4 @@
|
|||||||
# Спецификация лицензирования DNDGamePlayer (этап D1)
|
# Спецификация лицензирования TTRPG Player (этап D1)
|
||||||
|
|
||||||
Документ фиксирует модель **D1**: онлайн-активация, срок, число устройств, отзыв, и как это согласуется с клиентом и сервером лицензий.
|
Документ фиксирует модель **D1**: онлайн-активация, срок, число устройств, отзыв, и как это согласуется с клиентом и сервером лицензий.
|
||||||
|
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
## Модель
|
## Модель
|
||||||
|
|
||||||
1. **Продуктовый ключ** — секрет покупателя, известен только ему и серверу. Обменивается на **лицензионный токен** через `POST /v1/activate` (онлайн-активация). В поле «Указать ключ» приложение принимает **продуктовый ключ** `DND-…` (клиент сам вызывает `POST /v1/activate` с `deviceId`) или уже готовый **токен** (две части base64url через одну точку).
|
1. **Продуктовый ключ** — секрет покупателя, известен только ему и серверу. Обменивается на **лицензионный токен** через `POST /v1/activate` (онлайн-активация). В поле «Указать ключ» приложение принимает **продуктовый ключ** `TTRPG-…` или устаревший `DND-…` (клиент сам вызывает `POST /v1/activate` с `deviceId`) или уже готовый **токен** (две части base64url через одну точку). Новые ключи на сервере — только `TTRPG-…` (см. репозиторий лицензий).
|
||||||
2. **Лицензионный токен** — публичная полезная нагрузка (`sub`, `pid`, `iat`, `exp`, `did`) + подпись **Ed25519**. Клиент хранит только токен и **публичный** ключ (вшит в приложение); подделать валидный токен без приватного ключа сервера невозможно.
|
2. **Лицензионный токен** — публичная полезная нагрузка (`sub`, `pid`, `iat`, `exp`, `did`) + подпись **Ed25519**. Клиент хранит только токен и **публичный** ключ (вшит в приложение); подделать валидный токен без приватного ключа сервера невозможно.
|
||||||
3. **Срок** — поле `exp` (unix секунды). Клиент отклоняет истёкший токен без сети.
|
3. **Срок** — поле `exp` (unix секунды). Клиент отклоняет истёкший токен без сети.
|
||||||
4. **Устройства** — поле `did` в токене: при активации сервер привязывает токен к `deviceId` клиента и ведёт учёт списка устройств на `sub` в `data.json` (`maxDevices`).
|
4. **Устройства** — поле `did` в токене: при активации сервер привязывает токен к `deviceId` клиента и ведёт учёт списка устройств на `sub` в `data.json` (`maxDevices`).
|
||||||
@@ -20,6 +20,18 @@
|
|||||||
|
|
||||||
Токен не хранится открытым текстом в JSON userData: используется **Electron `safeStorage`** (на macOS — связка с Keychain, на Windows — DPAPI). Идентификатор устройства — отдельный файл `device.id` (не секрет). Принятие EULA — `preferences.json` (версия текста).
|
Токен не хранится открытым текстом в JSON userData: используется **Electron `safeStorage`** (на macOS — связка с Keychain, на Windows — DPAPI). Идентификатор устройства — отдельный файл `device.id` (не секрет). Принятие EULA — `preferences.json` (версия текста).
|
||||||
|
|
||||||
|
### Linux / WSL без keyring
|
||||||
|
|
||||||
|
На Linux `safeStorage` обычно требует **Secret Service** (например `gnome-keyring` + D-Bus). В **WSL** без keyring `safeStorage.isEncryptionAvailable()` часто **false**, и сохранить токен нельзя.
|
||||||
|
|
||||||
|
Явный обход (только если осознанно нужен запуск без OS-хранилища): переменная окружения **`DND_LICENSE_INSECURE_FILE_STORAGE=1`**. Тогда токен пишется в файл **`license.sealed.fallback`** (AES-256-GCM, ключ от `deviceId` + константа приложения). Это **слабее**, чем связка с ОС: при копировании `userData` + знании формата теоретически проще атаковать офлайн. Для обычного десктопа Linux с рабочим сеансом переменную не задавайте.
|
||||||
|
|
||||||
|
Пример запуска AppImage:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
DND_LICENSE_INSECURE_FILE_STORAGE=1 ./TTRPGPlayer-1.0.12-x64.AppImage --no-sandbox --appimage-extract-and-run
|
||||||
|
```
|
||||||
|
|
||||||
## Юридическое (D9)
|
## Юридическое (D9)
|
||||||
|
|
||||||
Текст EULA в приложении (`app/renderer/legal/eulaRu.ts`) и формулировки про активацию/отзыв/устройства. Перед первым вводом ключа пользователь принимает EULA (версия `EULA_CURRENT_VERSION` в `app/shared/license/eulaVersion.ts`).
|
Текст EULA в приложении (`app/renderer/legal/eulaRu.ts`) и формулировки про активацию/отзыв/устройства. Перед первым вводом ключа пользователь принимает EULA (версия `EULA_CURRENT_VERSION` в `app/shared/license/eulaVersion.ts`).
|
||||||
|
|||||||
+1
-2
@@ -18,9 +18,8 @@ export default tseslint.config(
|
|||||||
'node_modules/**',
|
'node_modules/**',
|
||||||
'.cursor/**',
|
'.cursor/**',
|
||||||
'scripts/**',
|
'scripts/**',
|
||||||
'tools/**',
|
|
||||||
'eslint.config.js',
|
'eslint.config.js',
|
||||||
// Plain ESM; shared with tools/project-converter (not parsed as TS project file).
|
// Plain ESM; shared with sibling ../project-converter (not parsed as TS project file).
|
||||||
'app/main/project/optimizeImageImport.lib.mjs',
|
'app/main/project/optimizeImageImport.lib.mjs',
|
||||||
'app/main/project/optimizeImageImport.lib.d.mts',
|
'app/main/project/optimizeImageImport.lib.d.mts',
|
||||||
],
|
],
|
||||||
|
|||||||
Generated
+1331
-38
File diff suppressed because it is too large
Load Diff
+57
-10
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "DndGamePlayer",
|
"name": "TTRPGPlayer",
|
||||||
"version": "1.0.0",
|
"version": "1.0.22",
|
||||||
"description": "DNDGamePlayer — редактор и проигрыватель игр",
|
"description": "TTRPG Player — редактор и проигрыватель НРИ",
|
||||||
"main": "dist/main/index.cjs",
|
"main": "dist/main/index.cjs",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "node scripts/dev.mjs",
|
"dev": "node scripts/dev.mjs",
|
||||||
@@ -10,14 +10,20 @@
|
|||||||
"build:obfuscate": "node scripts/build.mjs --production --obfuscate",
|
"build:obfuscate": "node scripts/build.mjs --production --obfuscate",
|
||||||
"lint": "eslint . --max-warnings 0",
|
"lint": "eslint . --max-warnings 0",
|
||||||
"typecheck": "tsc -p tsconfig.eslint.json --noEmit",
|
"typecheck": "tsc -p tsconfig.eslint.json --noEmit",
|
||||||
"test": "tsx --test app/renderer/shared/ui/controls.tooltip.test.ts app/renderer/editor/state/projectState.race.test.ts app/renderer/editor/graph/sceneCardById.test.ts app/shared/ipc/contracts.mediaRemoval.test.ts app/shared/effectEraserHitTest.test.ts app/renderer/control/controlApp.effectsPanel.test.ts app/renderer/shared/effects/PxiEffectsOverlay.pointer.test.ts app/main/windows/createWindows.editorClose.test.ts app/main/windows/bootWindow.test.ts app/main/effects/effectsStore.test.ts app/main/project/assetPrune.test.ts app/main/project/optimizeImageImport.test.ts app/main/project/scenePreviewThumbnail.test.ts app/main/project/fsRetry.test.ts app/main/project/zipRead.test.ts app/main/project/zipStore.legacyContract.test.ts app/shared/package.build.test.ts app/shared/license/canonicalJson.test.ts app/shared/license/productKey.test.ts app/shared/license/licenseService.networkRegression.test.ts app/shared/video/videoPlaybackPerf.networkRegression.test.ts app/shared/video/videoPlaybackLoop.networkRegression.test.ts app/main/license/verifyLicenseToken.test.ts && node --test scripts/build-env.test.mjs scripts/obfuscate-main.test.mjs",
|
"test": "tsx --test app/renderer/shared/ui/controls.tooltip.test.ts app/renderer/editor/state/projectState.race.test.ts app/renderer/editor/graph/sceneCardById.test.ts app/renderer/editor/i18n/editorMessages.locale.test.ts app/shared/ipc/contracts.mediaRemoval.test.ts app/shared/effectEraserHitTest.test.ts app/renderer/control/controlApp.effectsPanel.test.ts app/renderer/shared/effects/PxiEffectsOverlay.pointer.test.ts app/main/windows/createWindows.editorClose.test.ts app/main/windows/bootWindow.test.ts app/main/effects/effectsStore.test.ts app/main/project/assetPrune.test.ts app/main/project/optimizeImageImport.test.ts app/main/project/scenePreviewThumbnail.test.ts app/main/project/fsRetry.test.ts app/main/project/zipRead.test.ts app/main/project/replaceFileAtomic.test.ts app/main/project/zipStore.legacyContract.test.ts app/shared/package.build.test.ts app/shared/license/canonicalJson.test.ts app/shared/license/productKey.test.ts app/shared/license/licenseService.networkRegression.test.ts app/shared/video/videoPlaybackPerf.networkRegression.test.ts app/shared/video/videoPlaybackLoop.networkRegression.test.ts app/main/license/verifyLicenseToken.test.ts && node --test scripts/build-env.test.mjs scripts/obfuscate-main.test.mjs scripts/release-mac-prep.test.mjs",
|
||||||
"format": "prettier . --check",
|
"format": "prettier . --check",
|
||||||
"format:write": "prettier . --write",
|
"format:write": "prettier . --write",
|
||||||
|
"postinstall": "patch-package",
|
||||||
"release:info": "node scripts/print-release-info.mjs",
|
"release:info": "node scripts/print-release-info.mjs",
|
||||||
"pack": "npm run build && node scripts/release-win-prep.mjs && electron-builder",
|
"pack": "npm run build && node scripts/release-win-prep.mjs && electron-builder",
|
||||||
"pack:dir": "npm run build && node scripts/release-win-prep.mjs && electron-builder --dir",
|
"pack:dir": "npm run build && node scripts/release-win-prep.mjs && electron-builder --dir",
|
||||||
"pack:mac": "npm run build && electron-builder --mac",
|
"pack:mac": "npm run build && node scripts/release-mac-prep.mjs && electron-builder --mac",
|
||||||
"pack:win": "npm run build && node scripts/release-win-prep.mjs && electron-builder --win"
|
"pack:win": "npm run build && node scripts/release-win-prep.mjs && electron-builder --win",
|
||||||
|
"pack:linux": "node scripts/release-linux-pack.mjs",
|
||||||
|
"release": "powershell -ExecutionPolicy Bypass -File scripts/ttrpg-release/release.ps1",
|
||||||
|
"release:all": "powershell -ExecutionPolicy Bypass -File scripts/ttrpg-release/release-all.ps1",
|
||||||
|
"prepare:release": "powershell -ExecutionPolicy Bypass -File scripts/ttrpg-release/prepare-release.ps1",
|
||||||
|
"publish:updates": "powershell -ExecutionPolicy Bypass -File scripts/ttrpg-release/publish.ps1"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "",
|
||||||
@@ -25,6 +31,7 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fontsource/inter": "^5.2.8",
|
"@fontsource/inter": "^5.2.8",
|
||||||
|
"electron-updater": "^6.6.2",
|
||||||
"ffmpeg-static": "^5.3.0",
|
"ffmpeg-static": "^5.3.0",
|
||||||
"pixi.js": "^8.18.1",
|
"pixi.js": "^8.18.1",
|
||||||
"react": "^19.2.5",
|
"react": "^19.2.5",
|
||||||
@@ -56,7 +63,9 @@
|
|||||||
"eslint-plugin-react-hooks": "^7.0.1",
|
"eslint-plugin-react-hooks": "^7.0.1",
|
||||||
"eslint-plugin-unicorn": "^64.0.0",
|
"eslint-plugin-unicorn": "^64.0.0",
|
||||||
"javascript-obfuscator": "^4.2.2",
|
"javascript-obfuscator": "^4.2.2",
|
||||||
|
"patch-package": "^8.0.1",
|
||||||
"prettier": "^3.8.3",
|
"prettier": "^3.8.3",
|
||||||
|
"to-ico": "^1.1.2",
|
||||||
"tsx": "^4.21.0",
|
"tsx": "^4.21.0",
|
||||||
"typescript": "^6.0.2",
|
"typescript": "^6.0.2",
|
||||||
"typescript-eslint": "^8.58.2",
|
"typescript-eslint": "^8.58.2",
|
||||||
@@ -65,13 +74,19 @@
|
|||||||
"yazl": "^3.3.1"
|
"yazl": "^3.3.1"
|
||||||
},
|
},
|
||||||
"build": {
|
"build": {
|
||||||
"appId": "com.dndplayer.app",
|
"appId": "com.ttrpgplayer.app",
|
||||||
"productName": "DNDGamePlayer",
|
"productName": "TTRPGPlayer",
|
||||||
"copyright": "Copyright © DNDGamePlayer",
|
"copyright": "Copyright © TTRPGPlayer",
|
||||||
"directories": {
|
"directories": {
|
||||||
"output": "release",
|
"output": "release",
|
||||||
"buildResources": "build"
|
"buildResources": "build"
|
||||||
},
|
},
|
||||||
|
"extraResources": [
|
||||||
|
{
|
||||||
|
"from": "build/icon.ico",
|
||||||
|
"to": "branding/icon.ico"
|
||||||
|
}
|
||||||
|
],
|
||||||
"files": [
|
"files": [
|
||||||
"dist/**/*",
|
"dist/**/*",
|
||||||
"package.json"
|
"package.json"
|
||||||
@@ -79,12 +94,18 @@
|
|||||||
"asar": true,
|
"asar": true,
|
||||||
"asarUnpack": [
|
"asarUnpack": [
|
||||||
"dist/preload/**",
|
"dist/preload/**",
|
||||||
|
"dist/renderer/app-pack-icon.png",
|
||||||
|
"dist/renderer/app-window-icon.png",
|
||||||
"node_modules/sharp/**",
|
"node_modules/sharp/**",
|
||||||
"node_modules/@img/**",
|
"node_modules/@img/**",
|
||||||
"node_modules/ffmpeg-static/**"
|
"node_modules/ffmpeg-static/**"
|
||||||
],
|
],
|
||||||
|
"toolsets": {
|
||||||
|
"appimage": "1.0.2"
|
||||||
|
},
|
||||||
"mac": {
|
"mac": {
|
||||||
"category": "public.app-category.games",
|
"category": "public.app-category.games",
|
||||||
|
"artifactName": "${productName}-${arch}.${ext}",
|
||||||
"target": [
|
"target": [
|
||||||
{
|
{
|
||||||
"target": "dmg",
|
"target": "dmg",
|
||||||
@@ -118,12 +139,38 @@
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
"icon": "build/icon.ico"
|
||||||
|
},
|
||||||
|
"linux": {
|
||||||
|
"target": [
|
||||||
|
{
|
||||||
|
"target": "AppImage",
|
||||||
|
"arch": [
|
||||||
|
"x64",
|
||||||
|
"arm64"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"category": "Game",
|
||||||
|
"maintainer": "TTRPGPlayer",
|
||||||
|
"synopsis": "TTRPG Player — tabletop RPG editor and player",
|
||||||
"icon": "build/icon.png"
|
"icon": "build/icon.png"
|
||||||
},
|
},
|
||||||
|
"appImage": {
|
||||||
|
"artifactName": "${productName}-${arch}.${ext}"
|
||||||
|
},
|
||||||
|
"dmg": {
|
||||||
|
"artifactName": "${productName}-${arch}.${ext}"
|
||||||
|
},
|
||||||
"nsis": {
|
"nsis": {
|
||||||
"oneClick": false,
|
"oneClick": false,
|
||||||
"allowToChangeInstallationDirectory": true,
|
"allowToChangeInstallationDirectory": true,
|
||||||
"deleteAppDataOnUninstall": false
|
"deleteAppDataOnUninstall": false,
|
||||||
|
"artifactName": "${productName}-Setup.${ext}"
|
||||||
|
},
|
||||||
|
"publish": {
|
||||||
|
"provider": "generic",
|
||||||
|
"url": "https://updates.mailib.ru/"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
diff --git a/node_modules/app-builder-lib/out/targets/nsis/NsisTarget.js b/node_modules/app-builder-lib/out/targets/nsis/NsisTarget.js
|
||||||
|
index 1e4ef94..5f64a59 100644
|
||||||
|
--- a/node_modules/app-builder-lib/out/targets/nsis/NsisTarget.js
|
||||||
|
+++ b/node_modules/app-builder-lib/out/targets/nsis/NsisTarget.js
|
||||||
|
@@ -367,7 +367,12 @@ class NsisTarget extends core_1.Target {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
- await (0, wine_1.execWine)(installerPath, null, [], { env: { __COMPAT_LAYER: "RunAsInvoker" } });
|
||||||
|
+ try {
|
||||||
|
+ await nsisUtil_1.UninstallerReader.exec(installerPath, uninstallerPath);
|
||||||
|
+ }
|
||||||
|
+ catch (_error) {
|
||||||
|
+ await (0, wine_1.execWine)(installerPath, null, [], { env: { __COMPAT_LAYER: "RunAsInvoker" } });
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
await packager.signIf(uninstallerPath);
|
||||||
|
delete defines.BUILD_UNINSTALLER;
|
||||||
+1
-1
@@ -62,7 +62,7 @@ async function buildNodeTargets() {
|
|||||||
bundle: true,
|
bundle: true,
|
||||||
minify: isProd,
|
minify: isProd,
|
||||||
sourcemap: !isProd,
|
sourcemap: !isProd,
|
||||||
external: ['electron', 'sharp', 'ffmpeg-static'],
|
external: ['electron', 'electron-updater', 'sharp', 'ffmpeg-static'],
|
||||||
define,
|
define,
|
||||||
drop: isProd ? ['console', 'debugger'] : [],
|
drop: isProd ? ['console', 'debugger'] : [],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* Растеризует app-logo.svg в app-window-icon.png для nativeImage (Windows).
|
* Растеризует app-logo.svg в app-window-icon.png для nativeImage (Windows).
|
||||||
|
* Пишет build/icon.png (macOS / fallback) и build/icon.ico — для exe/NSIS и «Программы и компоненты».
|
||||||
* Запуск: node scripts/gen-window-icon.mjs
|
* Запуск: node scripts/gen-window-icon.mjs
|
||||||
*/
|
*/
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
@@ -7,6 +8,7 @@ import path from 'node:path';
|
|||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
import { Resvg } from '@resvg/resvg-js';
|
import { Resvg } from '@resvg/resvg-js';
|
||||||
|
import toIco from 'to-ico';
|
||||||
|
|
||||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
const root = path.join(__dirname, '..');
|
const root = path.join(__dirname, '..');
|
||||||
@@ -29,4 +31,18 @@ const resvg512 = new Resvg(svg, {
|
|||||||
});
|
});
|
||||||
const packOut = resvg512.render();
|
const packOut = resvg512.render();
|
||||||
fs.writeFileSync(packIconPath, packOut.asPng());
|
fs.writeFileSync(packIconPath, packOut.asPng());
|
||||||
console.log('wrote', packIconPath, packOut.width, 'x', packOut.height, '(electron-builder)');
|
console.log('wrote', packIconPath, packOut.width, 'x', packOut.height, '(electron-builder mac / fallback)');
|
||||||
|
|
||||||
|
function renderPngForWidth(width) {
|
||||||
|
const r = new Resvg(svg, {
|
||||||
|
fitTo: { mode: 'width', value: width },
|
||||||
|
});
|
||||||
|
return Buffer.from(r.render().asPng());
|
||||||
|
}
|
||||||
|
|
||||||
|
const icoSizes = [16, 24, 32, 48, 64, 128, 256];
|
||||||
|
const icoPngs = icoSizes.map((w) => renderPngForWidth(w));
|
||||||
|
const icoBuf = await toIco(icoPngs);
|
||||||
|
const icoPath = path.join(buildDir, 'icon.ico');
|
||||||
|
fs.writeFileSync(icoPath, icoBuf);
|
||||||
|
console.log('wrote', icoPath, '(electron-builder win)');
|
||||||
|
|||||||
@@ -0,0 +1,298 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Generate TTRPG-License-Key-Instructions.docx (run: python scripts/generate-license-key-docx.py)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from docx import Document
|
||||||
|
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||||
|
from docx.shared import Pt
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
OUT_PATHS = [
|
||||||
|
ROOT / "docs" / "TTRPG-License-Key-Instructions.docx",
|
||||||
|
Path(r"D:\TTRPG-Release\TTRPG-License-Key-Instructions.docx"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def add_bullet(doc: Document, text: str, level: int = 0) -> None:
|
||||||
|
style = "List Bullet" if level == 0 else "List Bullet 2"
|
||||||
|
doc.add_paragraph(text, style=style)
|
||||||
|
|
||||||
|
|
||||||
|
def add_step(doc: Document, n: int, title: str, body: str) -> None:
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.add_run(f"Шаг {n}. {title}. ").bold = True
|
||||||
|
p.add_run(body)
|
||||||
|
|
||||||
|
|
||||||
|
def add_code(doc: Document, text: str) -> None:
|
||||||
|
for line in text.strip().splitlines():
|
||||||
|
p = doc.add_paragraph(line)
|
||||||
|
p.style = "No Spacing"
|
||||||
|
for run in p.runs:
|
||||||
|
run.font.name = "Consolas"
|
||||||
|
run.font.size = Pt(9)
|
||||||
|
|
||||||
|
|
||||||
|
def build_document() -> Document:
|
||||||
|
doc = Document()
|
||||||
|
normal = doc.styles["Normal"]
|
||||||
|
normal.font.name = "Calibri"
|
||||||
|
normal.font.size = Pt(11)
|
||||||
|
|
||||||
|
title = doc.add_heading("TTRPG Player — выдача нового лицензионного ключа", level=0)
|
||||||
|
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
|
||||||
|
doc.add_paragraph(
|
||||||
|
"Инструкция для администратора: добавление нового продуктового ключа в базу "
|
||||||
|
"сервера лицензий. Пользователь вводит этот ключ в приложении; сервер выдаёт "
|
||||||
|
"подписанный лицензионный токен при активации."
|
||||||
|
)
|
||||||
|
|
||||||
|
doc.add_heading("Термины", level=1)
|
||||||
|
doc_terms = [
|
||||||
|
(
|
||||||
|
"Продуктовый ключ",
|
||||||
|
"строка вида TTRPG-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX — выдаётся покупателю, "
|
||||||
|
"хранится в data.json на сервере.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Лицензионный токен",
|
||||||
|
"выдаётся автоматически при активации в приложении; вручную создавать не нужно.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"sub",
|
||||||
|
"внутренний идентификатор лицензии на сервере (отзыв, учёт устройств).",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
for term, desc in doc_terms:
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.add_run(f"{term} — ").bold = True
|
||||||
|
p.add_run(desc)
|
||||||
|
|
||||||
|
doc.add_heading("Где лежит сервер (продакшен)", level=1)
|
||||||
|
srv = doc.add_table(rows=6, cols=2)
|
||||||
|
srv.style = "Table Grid"
|
||||||
|
srv.rows[0].cells[0].text = "Параметр"
|
||||||
|
srv.rows[0].cells[1].text = "Значение"
|
||||||
|
server_rows = [
|
||||||
|
("Домен", "https://license.mailib.ru/"),
|
||||||
|
("VPS", "185.173.94.234"),
|
||||||
|
("Папка проекта", "/var/www/license_mailib_ru"),
|
||||||
|
("Файл ключей", "/var/www/license_mailib_ru/data.json"),
|
||||||
|
("Пользователь Linux", "dndlicense"),
|
||||||
|
]
|
||||||
|
for i, (k, v) in enumerate(server_rows, start=1):
|
||||||
|
srv.rows[i].cells[0].text = k
|
||||||
|
srv.rows[i].cells[1].text = v
|
||||||
|
|
||||||
|
doc.add_heading("Редактирование data.json (удобный редактор)", level=1)
|
||||||
|
doc.add_paragraph(
|
||||||
|
"Не используйте nano, если нужны выделение мышью и привычное копирование. "
|
||||||
|
"Рекомендуется Cursor или VS Code с расширением Remote - SSH."
|
||||||
|
)
|
||||||
|
add_step(
|
||||||
|
doc,
|
||||||
|
1,
|
||||||
|
"Настроить SSH",
|
||||||
|
"В %USERPROFILE%\\.ssh\\config добавьте хост (ключ ttrpg_updates_root — тот же, "
|
||||||
|
"что для публикации обновлений):",
|
||||||
|
)
|
||||||
|
add_code(
|
||||||
|
doc,
|
||||||
|
"""Host mailib-vps
|
||||||
|
HostName 185.173.94.234
|
||||||
|
User root
|
||||||
|
IdentityFile C:\\Users\\Administrator\\.ssh\\ttrpg_updates_root""",
|
||||||
|
)
|
||||||
|
add_step(
|
||||||
|
doc,
|
||||||
|
2,
|
||||||
|
"Подключиться",
|
||||||
|
"F1 → Remote-SSH: Connect to Host… → mailib-vps.",
|
||||||
|
)
|
||||||
|
add_step(
|
||||||
|
doc,
|
||||||
|
3,
|
||||||
|
"Открыть папку",
|
||||||
|
"File → Open Folder → /var/www/license_mailib_ru → открыть data.json.",
|
||||||
|
)
|
||||||
|
add_bullet(doc, "Альтернатива: WinSCP (SFTP) → правый клик по data.json → Edit.")
|
||||||
|
add_bullet(
|
||||||
|
doc,
|
||||||
|
"Альтернатива: scp скачать файл на ПК, править в Cursor, scp залить обратно.",
|
||||||
|
)
|
||||||
|
|
||||||
|
doc.add_heading("Выдача нового ключа", level=1)
|
||||||
|
|
||||||
|
add_step(
|
||||||
|
doc,
|
||||||
|
1,
|
||||||
|
"Резервная копия",
|
||||||
|
"На сервере (SSH или терминал в Remote SSH):",
|
||||||
|
)
|
||||||
|
add_code(
|
||||||
|
doc,
|
||||||
|
"cd /var/www/license_mailib_ru\n"
|
||||||
|
"cp data.json \"data.json.bak.$(date +%F-%H%M%S)\"",
|
||||||
|
)
|
||||||
|
|
||||||
|
add_step(
|
||||||
|
doc,
|
||||||
|
2,
|
||||||
|
"Сгенерировать запись (Node.js на сервере)",
|
||||||
|
"Выполнить в каталоге /var/www/license_mailib_ru. Скрипт добавит запись в "
|
||||||
|
"productKeys и выведет новый ключ в консоль. Срок и лимит устройств — в начале скрипта.",
|
||||||
|
)
|
||||||
|
add_code(
|
||||||
|
doc,
|
||||||
|
r"""node -e "
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const crypto = require('node:crypto');
|
||||||
|
|
||||||
|
const dataPath = process.env.DND_LICENSE_DATA_PATH || './data.json';
|
||||||
|
const data = JSON.parse(fs.readFileSync(dataPath, 'utf8'));
|
||||||
|
|
||||||
|
const maxDevices = 3;
|
||||||
|
const expiresAtSec = Math.floor(new Date('2027-12-31T23:59:59Z').getTime() / 1000);
|
||||||
|
|
||||||
|
const key = 'TTRPG-' + crypto.randomUUID().toUpperCase();
|
||||||
|
const sub = 'lic_' + crypto.randomUUID().replace(/-/g, '');
|
||||||
|
|
||||||
|
data.productKeys ??= [];
|
||||||
|
data.productKeys.push({
|
||||||
|
key,
|
||||||
|
sub,
|
||||||
|
pid: 'dnd_player',
|
||||||
|
maxDevices,
|
||||||
|
expiresAtSec
|
||||||
|
});
|
||||||
|
|
||||||
|
fs.writeFileSync(dataPath, JSON.stringify(data, null, 2) + '\n');
|
||||||
|
console.log('NEW PRODUCT KEY:', key);
|
||||||
|
console.log('sub:', sub);
|
||||||
|
console.log('expiresAtSec:', expiresAtSec);
|
||||||
|
console.log('maxDevices:', maxDevices);
|
||||||
|
"
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
doc.add_paragraph(
|
||||||
|
"Сохраните выведенный NEW PRODUCT KEY — его передаёте пользователю. "
|
||||||
|
"Формат ключа должен соответствовать шаблону TTRPG-… (заглавные hex-символы)."
|
||||||
|
)
|
||||||
|
|
||||||
|
add_step(
|
||||||
|
doc,
|
||||||
|
3,
|
||||||
|
"Или добавить вручную в data.json",
|
||||||
|
"В массив productKeys добавьте объект (пример):",
|
||||||
|
)
|
||||||
|
add_code(
|
||||||
|
doc,
|
||||||
|
"""{
|
||||||
|
"key": "TTRPG-12345678-1234-1234-1234-123456789ABC",
|
||||||
|
"sub": "lic_unique_id",
|
||||||
|
"pid": "dnd_player",
|
||||||
|
"maxDevices": 3,
|
||||||
|
"expiresAtSec": 1830268799
|
||||||
|
}""",
|
||||||
|
)
|
||||||
|
fields = doc.add_table(rows=6, cols=2)
|
||||||
|
fields.style = "Table Grid"
|
||||||
|
fields.rows[0].cells[0].text = "Поле"
|
||||||
|
fields.rows[0].cells[1].text = "Описание"
|
||||||
|
field_rows = [
|
||||||
|
("key", "Продуктовый ключ для пользователя (уникальный)"),
|
||||||
|
("sub", "Уникальный ID лицензии на сервере"),
|
||||||
|
("pid", "Обычно dnd_player"),
|
||||||
|
("maxDevices", "Сколько разных deviceId можно активировать"),
|
||||||
|
("expiresAtSec", "Срок действия (Unix time, секунды)"),
|
||||||
|
]
|
||||||
|
for i, (k, v) in enumerate(field_rows, start=1):
|
||||||
|
fields.rows[i].cells[0].text = k
|
||||||
|
fields.rows[i].cells[1].text = v
|
||||||
|
|
||||||
|
add_step(
|
||||||
|
doc,
|
||||||
|
4,
|
||||||
|
"Права на файл (если правили от root)",
|
||||||
|
"chown dndlicense:dndlicense /var/www/license_mailib_ru/data.json",
|
||||||
|
)
|
||||||
|
|
||||||
|
add_step(
|
||||||
|
doc,
|
||||||
|
5,
|
||||||
|
"Перезапуск сервиса",
|
||||||
|
"После изменения data.json:",
|
||||||
|
)
|
||||||
|
add_code(doc, "sudo -u dndlicense pm2 restart dnd-license")
|
||||||
|
|
||||||
|
doc.add_heading("Проверка", level=1)
|
||||||
|
add_bullet(doc, "Сервер жив: curl https://license.mailib.ru/health → {\"ok\":true}")
|
||||||
|
add_bullet(
|
||||||
|
doc,
|
||||||
|
"В приложении TTRPG Player: «Указать ключ» → вставить продуктовый ключ → активация.",
|
||||||
|
)
|
||||||
|
add_bullet(
|
||||||
|
doc,
|
||||||
|
"При ошибке unknown_product_key — ключ не в data.json или опечатка; "
|
||||||
|
"too_many_devices — превышен maxDevices.",
|
||||||
|
)
|
||||||
|
|
||||||
|
doc.add_heading("Отзыв лицензии", level=1)
|
||||||
|
doc.add_paragraph(
|
||||||
|
"Чтобы отозвать лицензию по sub, добавьте sub в массив revokedSubs в data.json "
|
||||||
|
"и перезапустите pm2. Либо POST /v1/admin/revoke с Bearer-токеном администратора "
|
||||||
|
"(токен хранится только на сервере, в эту инструкцию не включён)."
|
||||||
|
)
|
||||||
|
|
||||||
|
doc.add_heading("Локальная разработка", level=1)
|
||||||
|
add_bullet(
|
||||||
|
doc,
|
||||||
|
"Исходники сервера на ПК: D:\\Work\\my_projects\\dnd_project\\DndGamePlayerLicenseServer",
|
||||||
|
)
|
||||||
|
add_bullet(doc, "Локальный data.json: скопировать из data.example.json")
|
||||||
|
add_bullet(doc, "Запуск: npm start (нужен LICENSE_PRIVATE_KEY_PEM)")
|
||||||
|
add_bullet(doc, "Порт по умолчанию: 3847")
|
||||||
|
|
||||||
|
doc.add_heading("Частые проблемы", level=1)
|
||||||
|
problems = [
|
||||||
|
(
|
||||||
|
"Ключ не принимается в приложении",
|
||||||
|
"Проверьте формат TTRPG-… (8-4-4-4-12 hex), что запись есть в productKeys, "
|
||||||
|
"сервер перезапущен после правки data.json.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"JSON сломан после правки",
|
||||||
|
"Восстановите из data.json.bak.*; проверьте запятые и кавычки.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Нет прав на запись",
|
||||||
|
"Правьте от root или chown на dndlicense; файл не должен быть только для чтения.",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
for prob, fix in problems:
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.add_run(f"{prob}. ").bold = True
|
||||||
|
p.add_run(fix)
|
||||||
|
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
p.add_run(
|
||||||
|
"Репозиторий сервера: git.mailib.ru/ifontosh/DndGamePlayerLicenseServer"
|
||||||
|
).italic = True
|
||||||
|
|
||||||
|
return doc
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
doc = build_document()
|
||||||
|
for path in OUT_PATHS:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
doc.save(str(path))
|
||||||
|
print(f"Wrote {path}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Generate TTRPG-Release-Instructions.docx (run: python scripts/generate-release-docx.py)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from docx import Document
|
||||||
|
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||||
|
from docx.shared import Pt
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
OUT_PATHS = [
|
||||||
|
ROOT / "docs" / "TTRPG-Release-Instructions.docx",
|
||||||
|
Path(r"D:\TTRPG-Release\TTRPG-Release-Instructions.docx"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def add_bullet(doc: Document, text: str, level: int = 0) -> None:
|
||||||
|
style = "List Bullet" if level == 0 else "List Bullet 2"
|
||||||
|
doc.add_paragraph(text, style=style)
|
||||||
|
|
||||||
|
|
||||||
|
def add_step(doc: Document, title: str, body: str) -> None:
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.add_run(f"{title}. ").bold = True
|
||||||
|
p.add_run(body)
|
||||||
|
|
||||||
|
|
||||||
|
def build_document() -> Document:
|
||||||
|
doc = Document()
|
||||||
|
normal = doc.styles["Normal"]
|
||||||
|
normal.font.name = "Calibri"
|
||||||
|
normal.font.size = Pt(11)
|
||||||
|
|
||||||
|
title = doc.add_heading("TTRPG Player — сборка и публикация обновлений", level=0)
|
||||||
|
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
|
||||||
|
doc.add_paragraph(
|
||||||
|
"Одна версия на все платформы. Сначала вручную поднимается версия и собирается macOS; "
|
||||||
|
"затем на Windows скрипт собирает Win/Linux без повторного bump и выкладывает на "
|
||||||
|
"https://updates.mailib.ru/"
|
||||||
|
)
|
||||||
|
|
||||||
|
doc.add_heading("Рекомендуемый порядок", level=1)
|
||||||
|
|
||||||
|
add_step(
|
||||||
|
doc,
|
||||||
|
"Шаг 1. Поднять версию",
|
||||||
|
"В каталоге проекта dnd_player: bump-version.cmd (D:\\TTRPG-Release) "
|
||||||
|
"или npm version patch --no-git-tag-version. "
|
||||||
|
"Закоммитить package.json при необходимости до сборки на Mac.",
|
||||||
|
)
|
||||||
|
add_step(
|
||||||
|
doc,
|
||||||
|
"Шаг 2. Собрать macOS (только на Mac)",
|
||||||
|
"FFMPEG_BINARIES_URL=https://cdn.npmmirror.com/binaries/ffmpeg-static npm ci && "
|
||||||
|
"npm run build && npm run pack:mac",
|
||||||
|
)
|
||||||
|
add_step(
|
||||||
|
doc,
|
||||||
|
"Шаг 3. Скопировать Mac-артефакты в D:\\TTRPG-Release",
|
||||||
|
"latest-mac.yml (только свежий с Mac), TTRPGPlayer-x64.zip, TTRPGPlayer-arm64.zip; "
|
||||||
|
"опционально TTRPGPlayer-x64.dmg, TTRPGPlayer-arm64.dmg. "
|
||||||
|
"Версия в latest-mac.yml должна совпадать с package.json.",
|
||||||
|
)
|
||||||
|
add_step(
|
||||||
|
doc,
|
||||||
|
"Шаг 4. Сборка Win/Linux и публикация (Windows)",
|
||||||
|
"release-all.cmd — по умолчанию режим -AfterMac: без bump, проверка Mac-файлов, "
|
||||||
|
"сборка Windows и Linux (WSL), копирование в D:\\TTRPG-Release, upload на сервер.",
|
||||||
|
)
|
||||||
|
|
||||||
|
doc.add_heading("Скрипты (D:\\TTRPG-Release)", level=1)
|
||||||
|
table = doc.add_table(rows=7, cols=2)
|
||||||
|
table.style = "Table Grid"
|
||||||
|
table.rows[0].cells[0].text = "Команда"
|
||||||
|
table.rows[0].cells[1].text = "Назначение"
|
||||||
|
rows = [
|
||||||
|
("bump-version.cmd", "Только patch в package.json (шаг 1)"),
|
||||||
|
("release-all.cmd", "Шаг 4: Win/Linux + publish, без bump (-AfterMac)"),
|
||||||
|
("prepare-release.cmd -AfterMac", "Только сборка Win/Linux и копирование"),
|
||||||
|
("publish.cmd", "Только проверка и upload на VPS"),
|
||||||
|
("publish.cmd -SkipMac", "Выложить Win/Linux, если Mac ещё не готов"),
|
||||||
|
("release-all-bump.cmd", "Устаревший режим: bump в скрипте, Mac потом"),
|
||||||
|
]
|
||||||
|
for i, (cmd, desc) in enumerate(rows, start=1):
|
||||||
|
table.rows[i].cells[0].text = cmd
|
||||||
|
table.rows[i].cells[1].text = desc
|
||||||
|
|
||||||
|
doc.add_heading("Флаги prepare-release", level=2)
|
||||||
|
for line in [
|
||||||
|
"-AfterMac — не менять версию; требовать Mac-файлы в папке релиза (по умолчанию в release-all)",
|
||||||
|
"-Bump — поднять patch и собрать (старый порядок)",
|
||||||
|
"-SkipGit, -SkipLinux, -NoBump, -Version X.Y.Z, -Minor",
|
||||||
|
]:
|
||||||
|
add_bullet(doc, line)
|
||||||
|
|
||||||
|
doc.add_heading("Флаги publish", level=2)
|
||||||
|
add_bullet(doc, "-CheckOnly — проверить файлы, без upload")
|
||||||
|
add_bullet(doc, "-SkipMac — не проверять и не заливать macOS")
|
||||||
|
|
||||||
|
doc.add_heading("Артефакты (имена без версии)", level=1)
|
||||||
|
art = doc.add_table(rows=4, cols=2)
|
||||||
|
art.style = "Table Grid"
|
||||||
|
art.rows[0].cells[0].text = "Платформа"
|
||||||
|
art.rows[0].cells[1].text = "Файлы"
|
||||||
|
artifacts = [
|
||||||
|
(
|
||||||
|
"Windows",
|
||||||
|
"latest.yml, TTRPGPlayer-Setup.exe, TTRPGPlayer-Setup.exe.blockmap",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Linux",
|
||||||
|
"latest-linux.yml, latest-linux-arm64.yml, "
|
||||||
|
"TTRPGPlayer-x64.AppImage, TTRPGPlayer-arm64.AppImage",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"macOS",
|
||||||
|
"latest-mac.yml, TTRPGPlayer-x64.zip, TTRPGPlayer-arm64.zip "
|
||||||
|
"(zip — автообновление; dmg — опционально, вручную)",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
for i, (plat, files) in enumerate(artifacts, start=1):
|
||||||
|
art.rows[i].cells[0].text = plat
|
||||||
|
art.rows[i].cells[1].text = files
|
||||||
|
|
||||||
|
doc.add_heading("Требования", level=1)
|
||||||
|
for line in [
|
||||||
|
"Windows: Node.js 20.19+ (или 22.12+), git, OpenSSH, WSL2 с nvm (Node 22, .nvmrc в проекте)",
|
||||||
|
"Проект: D:\\Work\\my_projects\\dnd_project\\dnd_player",
|
||||||
|
"Папка релиза: D:\\TTRPG-Release",
|
||||||
|
"SSH: %USERPROFILE%\\.ssh\\ttrpg_updates_root → root@185.173.94.234",
|
||||||
|
"Mac: Node 20+, сборка только на macOS",
|
||||||
|
]:
|
||||||
|
add_bullet(doc, line)
|
||||||
|
|
||||||
|
doc.add_heading("Проверка после выкладки", level=1)
|
||||||
|
for url in [
|
||||||
|
"https://updates.mailib.ru/latest.yml",
|
||||||
|
"https://updates.mailib.ru/latest-linux.yml",
|
||||||
|
"https://updates.mailib.ru/latest-mac.yml",
|
||||||
|
]:
|
||||||
|
add_bullet(doc, url)
|
||||||
|
|
||||||
|
doc.add_heading("Частые проблемы", level=1)
|
||||||
|
problems = [
|
||||||
|
(
|
||||||
|
"Win/Linux на версию выше Mac",
|
||||||
|
"Не использовать release-all-bump.cmd. Сначала bump + Mac, потом release-all.cmd.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"macOS: missing TTRPGPlayer-1.0.xx-mac.zip",
|
||||||
|
"Устаревший latest-mac.yml — пересобрать на Mac или publish.cmd -SkipMac.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"git push Failed to authenticate",
|
||||||
|
"Скрипт повторит push с токеном Gitea; или настроить credentials для git.mailib.ru.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"WSL Linux build / Node 18",
|
||||||
|
"Нужен nvm и Node 22 (scripts/wsl-pack-linux.sh).",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"npm ci / ffmpeg-static / GitHub 5xx",
|
||||||
|
"Win-скрипт повторит npm ci через FFMPEG_BINARIES_URL; на Mac используйте эту переменную вручную.",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"AfterMac: version mismatch",
|
||||||
|
"Версии в package.json и latest-mac.yml должны совпадать до запуска release-all.",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
for prob, fix in problems:
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.add_run(f"{prob}. ").bold = True
|
||||||
|
p.add_run(fix)
|
||||||
|
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
p.add_run("Конфиг: release-config.json, publish-config.json в D:\\TTRPG-Release").italic = True
|
||||||
|
|
||||||
|
return doc
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
doc = build_document()
|
||||||
|
for path in OUT_PATHS:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
doc.save(str(path))
|
||||||
|
print(f"Wrote {path}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
/**
|
||||||
|
* Build Linux release artifacts.
|
||||||
|
*
|
||||||
|
* AppImage packaging uses Linux tooling (mksquashfs). Running it from
|
||||||
|
* Windows PowerShell reaches linux-unpacked, then fails while creating
|
||||||
|
* the AppImage. Build from Linux/WSL instead.
|
||||||
|
*/
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import process from 'node:process';
|
||||||
|
|
||||||
|
function run(command, args) {
|
||||||
|
const result = spawnSync(command, args, {
|
||||||
|
stdio: 'inherit',
|
||||||
|
shell: process.platform === 'win32',
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.status !== 0) {
|
||||||
|
process.exit(result.status ?? 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** electron-builder для AppImage x64 часто даёт `x86_64` в имени — выравниваем под feed. */
|
||||||
|
function normalizeLinuxReleaseNames() {
|
||||||
|
const releaseDir = path.resolve('release');
|
||||||
|
if (!fs.existsSync(releaseDir)) return;
|
||||||
|
|
||||||
|
for (const name of fs.readdirSync(releaseDir)) {
|
||||||
|
if (!name.includes('x86_64')) continue;
|
||||||
|
const from = path.join(releaseDir, name);
|
||||||
|
const to = path.join(releaseDir, name.replaceAll('x86_64', 'x64'));
|
||||||
|
if (from !== to && !fs.existsSync(to)) {
|
||||||
|
fs.renameSync(from, to);
|
||||||
|
console.log(`[pack:linux] renamed ${name} -> ${path.basename(to)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const ymlName of fs.readdirSync(releaseDir)) {
|
||||||
|
if (!ymlName.startsWith('latest-linux') || !ymlName.endsWith('.yml')) continue;
|
||||||
|
const ymlPath = path.join(releaseDir, ymlName);
|
||||||
|
const text = fs.readFileSync(ymlPath, 'utf8');
|
||||||
|
const next = text.replaceAll('x86_64', 'x64');
|
||||||
|
if (next !== text) {
|
||||||
|
fs.writeFileSync(ymlPath, next);
|
||||||
|
console.log(`[pack:linux] patched ${ymlName} (x86_64 -> x64)`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.platform === 'win32') {
|
||||||
|
console.error(
|
||||||
|
[
|
||||||
|
'[pack:linux] AppImage нельзя собрать напрямую из Windows PowerShell.',
|
||||||
|
'Запустите команду внутри Linux/WSL из папки проекта:',
|
||||||
|
'',
|
||||||
|
' cd /mnt/d/Work/my_projects/dnd_project/dnd_player',
|
||||||
|
' npm ci',
|
||||||
|
' npm run pack:linux',
|
||||||
|
].join('\n'),
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
run('npm', ['run', 'build']);
|
||||||
|
run('electron-builder', ['--linux']);
|
||||||
|
normalizeLinuxReleaseNames();
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
/**
|
||||||
|
* Перед `electron-builder --mac`: npm ставит sharp только под CPU хоста.
|
||||||
|
* В release идут x64 и arm64 — в .app должны быть оба набора @img/sharp-darwin-*.
|
||||||
|
*/
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const MAC_SHARP_IMG_PACKAGES = [
|
||||||
|
'@img/sharp-darwin-arm64',
|
||||||
|
'@img/sharp-libvips-darwin-arm64',
|
||||||
|
'@img/sharp-darwin-x64',
|
||||||
|
'@img/sharp-libvips-darwin-x64',
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} root
|
||||||
|
* @returns {string[]} entries like `@img/sharp-darwin-x64@0.34.5` missing under node_modules
|
||||||
|
*/
|
||||||
|
export function macSharpImgPackagesToInstall(root) {
|
||||||
|
const sharpPkgPath = path.join(root, 'node_modules', 'sharp', 'package.json');
|
||||||
|
if (!fs.existsSync(sharpPkgPath)) {
|
||||||
|
throw new Error('[release-mac-prep] sharp is not installed — run npm ci first');
|
||||||
|
}
|
||||||
|
|
||||||
|
const sharpPkg = JSON.parse(fs.readFileSync(sharpPkgPath, 'utf8'));
|
||||||
|
const versions = sharpPkg.optionalDependencies ?? {};
|
||||||
|
const missing = [];
|
||||||
|
|
||||||
|
for (const name of MAC_SHARP_IMG_PACKAGES) {
|
||||||
|
const version = versions[name];
|
||||||
|
if (!version) {
|
||||||
|
throw new Error(`[release-mac-prep] sharp optionalDependency missing: ${name}`);
|
||||||
|
}
|
||||||
|
if (!fs.existsSync(path.join(root, 'node_modules', name))) {
|
||||||
|
missing.push(`${name}@${version}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return missing;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} root
|
||||||
|
* @param {{ runInstall?: boolean }} [opts]
|
||||||
|
*/
|
||||||
|
export function ensureMacSharpBinaries(root, opts = {}) {
|
||||||
|
const { runInstall = true } = opts;
|
||||||
|
const toInstall = macSharpImgPackagesToInstall(root);
|
||||||
|
|
||||||
|
if (toInstall.length === 0) {
|
||||||
|
console.log('[release-mac-prep] all macOS sharp binaries present');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('[release-mac-prep] installing', toInstall.join(', '));
|
||||||
|
if (!runInstall) return;
|
||||||
|
|
||||||
|
execFileSync('npm', ['install', '--no-save', '--force', ...toInstall], {
|
||||||
|
cwd: root,
|
||||||
|
stdio: 'inherit',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
|
||||||
|
if (isMain) {
|
||||||
|
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
if (process.platform !== 'darwin') {
|
||||||
|
console.warn('[release-mac-prep] skipped: not macOS (no dual-arch sharp prep needed here)');
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
ensureMacSharpBinaries(root);
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
import { macSharpImgPackagesToInstall } from './release-mac-prep.mjs';
|
||||||
|
|
||||||
|
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
|
||||||
|
void test('macSharpImgPackagesToInstall: empty when all four @img darwin packages exist', () => {
|
||||||
|
const missing = macSharpImgPackagesToInstall(root);
|
||||||
|
assert.deepEqual(missing, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
void test('macSharpImgPackagesToInstall: lists missing darwin-x64 on arm64-only tree', () => {
|
||||||
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'mac-sharp-prep-'));
|
||||||
|
try {
|
||||||
|
const sharpOpt = {
|
||||||
|
'@img/sharp-darwin-arm64': '0.34.5',
|
||||||
|
'@img/sharp-libvips-darwin-arm64': '1.2.4',
|
||||||
|
'@img/sharp-darwin-x64': '0.34.5',
|
||||||
|
'@img/sharp-libvips-darwin-x64': '1.2.4',
|
||||||
|
};
|
||||||
|
fs.mkdirSync(path.join(tmp, 'node_modules', 'sharp'), { recursive: true });
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(tmp, 'node_modules', 'sharp', 'package.json'),
|
||||||
|
JSON.stringify({ optionalDependencies: sharpOpt }),
|
||||||
|
);
|
||||||
|
for (const name of ['@img/sharp-darwin-arm64', '@img/sharp-libvips-darwin-arm64']) {
|
||||||
|
const dir = path.join(tmp, 'node_modules', name);
|
||||||
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
|
fs.writeFileSync(path.join(dir, 'package.json'), '{}');
|
||||||
|
}
|
||||||
|
|
||||||
|
const missing = macSharpImgPackagesToInstall(tmp);
|
||||||
|
assert.deepEqual(missing, ['@img/sharp-darwin-x64@0.34.5', '@img/sharp-libvips-darwin-x64@1.2.4']);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(tmp, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -17,7 +17,7 @@ function sleep(ms) {
|
|||||||
function tryKillDndPlayer() {
|
function tryKillDndPlayer() {
|
||||||
if (process.platform !== 'win32') return;
|
if (process.platform !== 'win32') return;
|
||||||
try {
|
try {
|
||||||
execFileSync('taskkill', ['/F', '/IM', 'DNDGamePlayer.exe', '/T'], {
|
execFileSync('taskkill', ['/F', '/IM', 'TTRPGPlayer.exe', '/T'], {
|
||||||
stdio: 'ignore',
|
stdio: 'ignore',
|
||||||
windowsHide: true,
|
windowsHide: true,
|
||||||
});
|
});
|
||||||
@@ -37,7 +37,7 @@ async function tryRmWinUnpacked() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
console.warn(
|
console.warn(
|
||||||
'[release-win-prep] Не удалось удалить release/win-unpacked. Закройте DNDGamePlayer и повторите pack.',
|
'[release-win-prep] Не удалось удалить release/win-unpacked. Закройте TTRPGPlayer и повторите pack.',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
TTRPG Release folder
|
||||||
|
|
||||||
|
====================
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
RECOMMENDED WORKFLOW (same version on all platforms)
|
||||||
|
|
||||||
|
----------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
1) bump-version.cmd
|
||||||
|
|
||||||
|
OR in project: npm version patch --no-git-tag-version
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
2) On Mac: npm ci && npm run build && npm run pack:mac
|
||||||
|
|
||||||
|
Copy to D:\TTRPG-Release:
|
||||||
|
|
||||||
|
latest-mac.yml, TTRPGPlayer-x64.zip, TTRPGPlayer-arm64.zip (+ dmg optional)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
3) release-all.cmd
|
||||||
|
|
||||||
|
- does NOT bump version (default -AfterMac)
|
||||||
|
|
||||||
|
- checks Mac files match package.json version
|
||||||
|
|
||||||
|
- builds Windows + Linux, copies artifacts, publishes to updates.mailib.ru
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
LEGACY (Win/Linux ahead of Mac)
|
||||||
|
|
||||||
|
-------------------------------
|
||||||
|
|
||||||
|
release-all-bump.cmd - bumps patch in script, build Win/Linux, publish with -SkipMac or add Mac later
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
SCRIPTS
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
@echo off
|
||||||
|
REM Bump patch in package.json only (no git tag). Run BEFORE Mac build.
|
||||||
|
cd /d "D:\Work\my_projects\dnd_project\dnd_player"
|
||||||
|
call npm version patch --no-git-tag-version
|
||||||
|
if errorlevel 1 pause & exit /b 1
|
||||||
|
echo.
|
||||||
|
echo Version bumped. Next:
|
||||||
|
echo 1) npm run pack:mac on Mac
|
||||||
|
echo 2) Copy latest-mac.yml + TTRPGPlayer-*.zip to D:\TTRPG-Release
|
||||||
|
echo 3) release-all.cmd
|
||||||
|
pause
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0"
|
||||||
|
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0prepare-release.ps1" %*
|
||||||
|
if errorlevel 1 pause
|
||||||
@@ -0,0 +1,466 @@
|
|||||||
|
# Prepare TTRPG release: build Win/Linux, copy to release folder.
|
||||||
|
# Run: prepare-release.cmd
|
||||||
|
#
|
||||||
|
# Recommended (Mac first, same version on all platforms):
|
||||||
|
# 1) Bump version in package.json manually (npm version patch --no-git-tag-version)
|
||||||
|
# 2) pack:mac on Mac, copy latest-mac.yml + *.zip to release folder
|
||||||
|
# 3) prepare-release.cmd -AfterMac (or release-all.cmd)
|
||||||
|
#
|
||||||
|
# Options:
|
||||||
|
# -AfterMac do not bump; require Mac files in release folder (default in release-all)
|
||||||
|
# -Bump bump patch before build (Mac can be added later)
|
||||||
|
# -Version 1.0.17 set explicit version (with -Bump workflow)
|
||||||
|
# -Minor bump minor (with -Bump)
|
||||||
|
# -SkipGit skip commit/push
|
||||||
|
# -SkipLinux skip Linux build (WSL)
|
||||||
|
# -NoBump do not change package.json (same as -AfterMac without Mac check)
|
||||||
|
|
||||||
|
param(
|
||||||
|
[string]$Version = '',
|
||||||
|
[switch]$Patch,
|
||||||
|
[switch]$Minor,
|
||||||
|
[switch]$Bump,
|
||||||
|
[switch]$AfterMac,
|
||||||
|
[switch]$SkipGit,
|
||||||
|
[switch]$SkipLinux,
|
||||||
|
[switch]$NoBump
|
||||||
|
)
|
||||||
|
|
||||||
|
Set-StrictMode -Version Latest
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
$ToolDir = $PSScriptRoot
|
||||||
|
$ConfigPath = Join-Path $ToolDir 'release-config.json'
|
||||||
|
|
||||||
|
function Write-Step([int]$n, [string]$text) {
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host "----- Step $n : $text -----" -ForegroundColor Cyan
|
||||||
|
}
|
||||||
|
|
||||||
|
function Write-Ok([string]$text) {
|
||||||
|
Write-Host " [OK] $text" -ForegroundColor Green
|
||||||
|
}
|
||||||
|
|
||||||
|
function Write-Fail([string]$text) {
|
||||||
|
Write-Host " [!!] $text" -ForegroundColor Red
|
||||||
|
}
|
||||||
|
|
||||||
|
$FfmpegStaticMirror = 'https://cdn.npmmirror.com/binaries/ffmpeg-static'
|
||||||
|
|
||||||
|
function Test-IsNpmCi([string[]]$NpmArgs) {
|
||||||
|
return ($NpmArgs.Count -eq 1 -and $NpmArgs[0] -eq 'ci')
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-NpmRaw {
|
||||||
|
param(
|
||||||
|
[string[]]$NpmArgs,
|
||||||
|
[string]$WorkingDirectory
|
||||||
|
)
|
||||||
|
$prevEap = $ErrorActionPreference
|
||||||
|
$ErrorActionPreference = 'Continue'
|
||||||
|
Push-Location $WorkingDirectory
|
||||||
|
try {
|
||||||
|
& npm @NpmArgs 2>&1 | ForEach-Object {
|
||||||
|
if ($_ -is [System.Management.Automation.ErrorRecord]) {
|
||||||
|
Write-Host $_.ToString()
|
||||||
|
} else {
|
||||||
|
Write-Host ([string]$_)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $LASTEXITCODE
|
||||||
|
} finally {
|
||||||
|
Pop-Location
|
||||||
|
$ErrorActionPreference = $prevEap
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-NpmCiWithFfmpegMirror {
|
||||||
|
param(
|
||||||
|
[string]$WorkingDirectory
|
||||||
|
)
|
||||||
|
$prevMirror = $env:FFMPEG_BINARIES_URL
|
||||||
|
$env:FFMPEG_BINARIES_URL = $FfmpegStaticMirror
|
||||||
|
try {
|
||||||
|
Write-Host " > npm ci (retry with FFMPEG_BINARIES_URL=$FfmpegStaticMirror)"
|
||||||
|
return (Invoke-NpmRaw -NpmArgs @('ci') -WorkingDirectory $WorkingDirectory)
|
||||||
|
} finally {
|
||||||
|
if ($null -eq $prevMirror) {
|
||||||
|
Remove-Item Env:\FFMPEG_BINARIES_URL -ErrorAction SilentlyContinue
|
||||||
|
} else {
|
||||||
|
$env:FFMPEG_BINARIES_URL = $prevMirror
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-Npm {
|
||||||
|
param(
|
||||||
|
[string]$Label,
|
||||||
|
[string[]]$NpmArgs,
|
||||||
|
[string]$WorkingDirectory
|
||||||
|
)
|
||||||
|
Write-Host " > $Label"
|
||||||
|
$exitCode = Invoke-NpmRaw -NpmArgs $NpmArgs -WorkingDirectory $WorkingDirectory
|
||||||
|
if ($exitCode -ne 0 -and (Test-IsNpmCi $NpmArgs)) {
|
||||||
|
Write-Host " [--] npm ci failed (exit $exitCode). Retrying via ffmpeg-static mirror..." -ForegroundColor Yellow
|
||||||
|
$exitCode = Invoke-NpmCiWithFfmpegMirror $WorkingDirectory
|
||||||
|
}
|
||||||
|
if ($exitCode -ne 0) {
|
||||||
|
throw "$Label failed (exit $exitCode)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Convert-ToWslPath([string]$winPath) {
|
||||||
|
$full = [System.IO.Path]::GetFullPath($winPath)
|
||||||
|
$p = $full -replace '\\', '/'
|
||||||
|
if ($p -match '^([A-Za-z]):(.*)$') {
|
||||||
|
$drive = $Matches[1].ToLower()
|
||||||
|
return "/mnt/$drive$($Matches[2])"
|
||||||
|
}
|
||||||
|
return $p
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-WslLinuxBuildCommand([string]$WslProjectPath) {
|
||||||
|
# WSL Debian often has node 18 on PATH; scripts/wsl-pack-linux.sh uses nvm + .nvmrc.
|
||||||
|
return "cd '$WslProjectPath' && bash scripts/wsl-pack-linux.sh"
|
||||||
|
}
|
||||||
|
|
||||||
|
function Read-PackageVersion([string]$packageJsonPath) {
|
||||||
|
$json = Get-Content -LiteralPath $packageJsonPath -Raw -Encoding UTF8 | ConvertFrom-Json
|
||||||
|
return [string]$json.version
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-NpmVersion {
|
||||||
|
param(
|
||||||
|
[string]$ProjectRoot,
|
||||||
|
[string]$Spec
|
||||||
|
)
|
||||||
|
Invoke-Npm "npm version $Spec" @('version', $Spec, '--no-git-tag-version', '--allow-same-version') $ProjectRoot
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-GiteaPushUrl([string]$mcpConfigPath) {
|
||||||
|
if (-not (Test-Path -LiteralPath $mcpConfigPath)) {
|
||||||
|
return $null
|
||||||
|
}
|
||||||
|
$raw = Get-Content -LiteralPath $mcpConfigPath -Raw -Encoding UTF8 | ConvertFrom-Json
|
||||||
|
$token = $raw.mcpServers.'gitea-mailib'.env.GITEA_ACCESS_TOKEN
|
||||||
|
if (-not $token) {
|
||||||
|
return $null
|
||||||
|
}
|
||||||
|
return "https://ifontosh:${token}@git.mailib.ru/ifontosh/DndGamePlayer.git"
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-Git {
|
||||||
|
param(
|
||||||
|
[string]$ProjectRoot,
|
||||||
|
[string[]]$GitArgs
|
||||||
|
)
|
||||||
|
& git -C $ProjectRoot @GitArgs
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
throw "git $($GitArgs -join ' ') failed (exit $LASTEXITCODE)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-GitTextOutput {
|
||||||
|
param(
|
||||||
|
[string]$ProjectRoot,
|
||||||
|
[string[]]$GitArgs
|
||||||
|
)
|
||||||
|
$prevEap = $ErrorActionPreference
|
||||||
|
$ErrorActionPreference = 'Continue'
|
||||||
|
try {
|
||||||
|
$output = & git -C $ProjectRoot @GitArgs 2>&1
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
throw "git $($GitArgs -join ' ') failed (exit $LASTEXITCODE)"
|
||||||
|
}
|
||||||
|
if ($null -eq $output) {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
return (@($output | ForEach-Object {
|
||||||
|
if ($_ -is [System.Management.Automation.ErrorRecord]) {
|
||||||
|
$_.ToString()
|
||||||
|
} else {
|
||||||
|
[string]$_
|
||||||
|
}
|
||||||
|
}) -join "`n").Trim()
|
||||||
|
} finally {
|
||||||
|
$ErrorActionPreference = $prevEap
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Write-GitLines($lines) {
|
||||||
|
foreach ($line in $lines) {
|
||||||
|
if ($line -is [System.Management.Automation.ErrorRecord]) {
|
||||||
|
Write-Host $line.ToString()
|
||||||
|
} else {
|
||||||
|
Write-Host ([string]$line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-GitPush {
|
||||||
|
param(
|
||||||
|
[string]$ProjectRoot,
|
||||||
|
[string[]]$PushArgs
|
||||||
|
)
|
||||||
|
$prevEap = $ErrorActionPreference
|
||||||
|
$ErrorActionPreference = 'Continue'
|
||||||
|
try {
|
||||||
|
$output = & git -C $ProjectRoot push @PushArgs 2>&1
|
||||||
|
Write-GitLines $output
|
||||||
|
return $LASTEXITCODE
|
||||||
|
} finally {
|
||||||
|
$ErrorActionPreference = $prevEap
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Push-Git([string]$ProjectRoot, [string]$Remote, [string]$McpConfigPath) {
|
||||||
|
$branch = Get-GitTextOutput $ProjectRoot @('rev-parse', '--abbrev-ref', 'HEAD')
|
||||||
|
Write-Host " > git push $Remote $branch"
|
||||||
|
$exitCode = Invoke-GitPush $ProjectRoot @($Remote, $branch)
|
||||||
|
if ($exitCode -eq 0) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
$pushUrl = Get-GiteaPushUrl $McpConfigPath
|
||||||
|
if (-not $pushUrl) {
|
||||||
|
throw "git push failed (exit $exitCode) and no Gitea token in mcp config ($McpConfigPath)"
|
||||||
|
}
|
||||||
|
Write-Host " > git push via Gitea token URL"
|
||||||
|
$exitCode = Invoke-GitPush $ProjectRoot @($pushUrl, "HEAD:${branch}")
|
||||||
|
if ($exitCode -ne 0) {
|
||||||
|
throw "git push failed (exit $exitCode)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-YmlField([string]$ymlPath, [string]$fieldName) {
|
||||||
|
$content = Get-Content -LiteralPath $ymlPath -Raw -Encoding UTF8
|
||||||
|
$m = [regex]::Match($content, "(?m)^${fieldName}:\s*(\S+)\s*$")
|
||||||
|
if ($m.Success) {
|
||||||
|
return $m.Groups[1].Value.Trim()
|
||||||
|
}
|
||||||
|
return $null
|
||||||
|
}
|
||||||
|
|
||||||
|
function Test-MacReleaseReady {
|
||||||
|
param(
|
||||||
|
[string]$ReleaseDir,
|
||||||
|
[string]$ExpectedVersion
|
||||||
|
)
|
||||||
|
$macYml = Join-Path $ReleaseDir 'latest-mac.yml'
|
||||||
|
if (-not (Test-Path -LiteralPath $macYml)) {
|
||||||
|
throw @"
|
||||||
|
AfterMac: missing latest-mac.yml in $ReleaseDir
|
||||||
|
1) Bump version in package.json (now $ExpectedVersion)
|
||||||
|
2) npm run pack:mac on Mac
|
||||||
|
3) Copy latest-mac.yml + TTRPGPlayer-*.zip into release folder
|
||||||
|
4) Run prepare-release.cmd -AfterMac again
|
||||||
|
"@
|
||||||
|
}
|
||||||
|
$macVersion = Get-YmlField $macYml 'version'
|
||||||
|
if ($macVersion -and $macVersion -ne $ExpectedVersion) {
|
||||||
|
throw "AfterMac: latest-mac.yml is v$macVersion but package.json is v$ExpectedVersion. Align versions before building Win/Linux."
|
||||||
|
}
|
||||||
|
$primary = Get-YmlField $macYml 'path'
|
||||||
|
if (-not $primary) {
|
||||||
|
throw 'AfterMac: latest-mac.yml has no path: entry'
|
||||||
|
}
|
||||||
|
$primaryPath = Join-Path $ReleaseDir $primary
|
||||||
|
if (-not (Test-Path -LiteralPath $primaryPath)) {
|
||||||
|
throw "AfterMac: missing Mac update file $primary (path in latest-mac.yml). Copy zip from Mac build."
|
||||||
|
}
|
||||||
|
Write-Ok "Mac feed v$ExpectedVersion, primary: $primary"
|
||||||
|
}
|
||||||
|
|
||||||
|
function Copy-ReleaseArtifacts {
|
||||||
|
param(
|
||||||
|
[string]$BuildReleaseDir,
|
||||||
|
[string]$TargetDir
|
||||||
|
)
|
||||||
|
|
||||||
|
if (-not (Test-Path -LiteralPath $TargetDir)) {
|
||||||
|
New-Item -ItemType Directory -Path $TargetDir | Out-Null
|
||||||
|
}
|
||||||
|
|
||||||
|
$names = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
|
||||||
|
|
||||||
|
$fixed = @(
|
||||||
|
'latest.yml',
|
||||||
|
'TTRPGPlayer-Setup.exe',
|
||||||
|
'TTRPGPlayer-Setup.exe.blockmap'
|
||||||
|
)
|
||||||
|
foreach ($n in $fixed) {
|
||||||
|
[void]$names.Add($n)
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($yml in Get-ChildItem -LiteralPath $BuildReleaseDir -Filter 'latest-linux*.yml' -File -ErrorAction SilentlyContinue) {
|
||||||
|
[void]$names.Add($yml.Name)
|
||||||
|
$content = Get-Content -LiteralPath $yml.FullName -Raw -Encoding UTF8
|
||||||
|
foreach ($m in [regex]::Matches($content, '(?m)^(?:\s*-\s*)?(?:url|path):\s*(\S+)\s*$')) {
|
||||||
|
[void]$names.Add($m.Groups[1].Value.Trim())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($img in Get-ChildItem -LiteralPath $BuildReleaseDir -Filter 'TTRPGPlayer-*.AppImage' -File -ErrorAction SilentlyContinue) {
|
||||||
|
[void]$names.Add($img.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
$copied = 0
|
||||||
|
foreach ($name in ($names | Sort-Object)) {
|
||||||
|
$src = Join-Path $BuildReleaseDir $name
|
||||||
|
if (-not (Test-Path -LiteralPath $src)) {
|
||||||
|
if ($name -match 'x64' -and $name -notmatch 'x86_64') {
|
||||||
|
$alt = $name -replace 'x64', 'x86_64'
|
||||||
|
$src = Join-Path $BuildReleaseDir $alt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (-not (Test-Path -LiteralPath $src)) {
|
||||||
|
Write-Host " [--] skip (not built): $name" -ForegroundColor Yellow
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
$dest = Join-Path $TargetDir ([System.IO.Path]::GetFileName($src))
|
||||||
|
Copy-Item -LiteralPath $src -Destination $dest -Force
|
||||||
|
Write-Ok "copied $([System.IO.Path]::GetFileName($src))"
|
||||||
|
$copied += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($copied -eq 0) {
|
||||||
|
throw 'No release artifacts copied - check build output in project release folder'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not (Test-Path -LiteralPath $ConfigPath)) {
|
||||||
|
throw "Missing release-config.json: $ConfigPath"
|
||||||
|
}
|
||||||
|
|
||||||
|
$config = Get-Content -LiteralPath $ConfigPath -Raw -Encoding UTF8 | ConvertFrom-Json
|
||||||
|
$projectRoot = [System.IO.Path]::GetFullPath([string]$config.projectRoot)
|
||||||
|
$releaseDir = [System.IO.Path]::GetFullPath([string]$config.releaseDir)
|
||||||
|
$gitRemote = [string]$config.gitRemote
|
||||||
|
$mcpConfig = [string]$config.giteaMcpConfig
|
||||||
|
$wslDistro = [string]$config.wslDistro
|
||||||
|
|
||||||
|
$packageJson = Join-Path $projectRoot 'package.json'
|
||||||
|
$buildReleaseDir = Join-Path $projectRoot 'release'
|
||||||
|
|
||||||
|
if (-not (Test-Path -LiteralPath $packageJson)) {
|
||||||
|
throw "package.json not found: $packageJson"
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host '=== TTRPG Prepare Release ===' -ForegroundColor Cyan
|
||||||
|
Write-Host "Project: $projectRoot"
|
||||||
|
Write-Host "Release folder: $releaseDir"
|
||||||
|
|
||||||
|
if ($AfterMac) {
|
||||||
|
$NoBump = $true
|
||||||
|
}
|
||||||
|
if ($Bump -and $AfterMac) {
|
||||||
|
throw 'Use either -Bump or -AfterMac, not both'
|
||||||
|
}
|
||||||
|
if ($Bump) {
|
||||||
|
$Patch = $true
|
||||||
|
}
|
||||||
|
|
||||||
|
$currentVersion = Read-PackageVersion $packageJson
|
||||||
|
|
||||||
|
if ($AfterMac) {
|
||||||
|
Write-Step 0 'Mac artifacts check'
|
||||||
|
Test-MacReleaseReady $releaseDir $currentVersion
|
||||||
|
}
|
||||||
|
|
||||||
|
# Step 1 - version
|
||||||
|
if ($AfterMac) {
|
||||||
|
Write-Step 1 'Version (unchanged, Mac-first workflow)'
|
||||||
|
$newVersion = $currentVersion
|
||||||
|
Write-Ok "building Win/Linux at v$newVersion (same as Mac feed)"
|
||||||
|
} else {
|
||||||
|
Write-Step 1 'Bump version'
|
||||||
|
$newVersion = $currentVersion
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($AfterMac) {
|
||||||
|
# version step done above
|
||||||
|
} elseif ($NoBump) {
|
||||||
|
Write-Ok "version unchanged: $currentVersion"
|
||||||
|
$newVersion = $currentVersion
|
||||||
|
} elseif ($Version) {
|
||||||
|
Invoke-NpmVersion $projectRoot $Version.Trim()
|
||||||
|
$newVersion = Read-PackageVersion $packageJson
|
||||||
|
Write-Ok "version set to $newVersion (was $currentVersion)"
|
||||||
|
} elseif ($Minor) {
|
||||||
|
Invoke-NpmVersion $projectRoot 'minor'
|
||||||
|
$newVersion = Read-PackageVersion $packageJson
|
||||||
|
Write-Ok "version $currentVersion -> $newVersion (minor)"
|
||||||
|
} else {
|
||||||
|
Invoke-NpmVersion $projectRoot 'patch'
|
||||||
|
$newVersion = Read-PackageVersion $packageJson
|
||||||
|
Write-Ok "version $currentVersion -> $newVersion (patch)"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Step 2 - git
|
||||||
|
if ($SkipGit) {
|
||||||
|
Write-Step 2 'Git commit and push (skipped)'
|
||||||
|
} else {
|
||||||
|
Write-Step 2 'Git commit and push'
|
||||||
|
Invoke-Git $projectRoot @('add', 'package.json')
|
||||||
|
if (Test-Path -LiteralPath (Join-Path $projectRoot 'package-lock.json')) {
|
||||||
|
Invoke-Git $projectRoot @('add', 'package-lock.json')
|
||||||
|
}
|
||||||
|
$commitMsg = "chore: release v$newVersion"
|
||||||
|
$status = Get-GitTextOutput $projectRoot @('status', '--porcelain')
|
||||||
|
if ($status) {
|
||||||
|
Invoke-Git $projectRoot @('commit', '-m', $commitMsg)
|
||||||
|
Write-Ok "committed: $commitMsg"
|
||||||
|
} else {
|
||||||
|
Write-Ok 'nothing to commit (version may already be committed)'
|
||||||
|
}
|
||||||
|
Push-Git $projectRoot $gitRemote $mcpConfig
|
||||||
|
Write-Ok 'pushed to remote'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Step 3 - Windows build
|
||||||
|
Write-Step 3 'Build Windows (npm ci + pack:win)'
|
||||||
|
Invoke-Npm 'npm ci' @('ci') $projectRoot
|
||||||
|
Invoke-Npm 'npm run pack:win' @('run', 'pack:win') $projectRoot
|
||||||
|
Write-Ok 'Windows build finished'
|
||||||
|
|
||||||
|
# Step 4 - Linux build
|
||||||
|
if ($SkipLinux) {
|
||||||
|
Write-Step 4 'Build Linux (skipped)'
|
||||||
|
} else {
|
||||||
|
Write-Step 4 'Build Linux via WSL (npm ci + pack:linux)'
|
||||||
|
$wslProject = Convert-ToWslPath $projectRoot
|
||||||
|
$wslCmd = Get-WslLinuxBuildCommand $wslProject
|
||||||
|
$wslArgs = @()
|
||||||
|
if ($wslDistro) {
|
||||||
|
$wslArgs += '-d', $wslDistro
|
||||||
|
}
|
||||||
|
$wslArgs += '-e', 'bash', '-lc', $wslCmd
|
||||||
|
Write-Host " > wsl $($wslArgs -join ' ')"
|
||||||
|
& wsl @wslArgs
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
throw "WSL Linux build failed (exit $LASTEXITCODE). Install WSL or use -SkipLinux"
|
||||||
|
}
|
||||||
|
Write-Ok 'Linux build finished'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Step 5 - copy
|
||||||
|
Write-Step 5 'Copy artifacts to release folder'
|
||||||
|
if (-not (Test-Path -LiteralPath $buildReleaseDir)) {
|
||||||
|
throw "Build output missing: $buildReleaseDir"
|
||||||
|
}
|
||||||
|
Copy-ReleaseArtifacts $buildReleaseDir $releaseDir
|
||||||
|
Write-Ok "release folder updated: $releaseDir"
|
||||||
|
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host '=== Prepare release done ===' -ForegroundColor Green
|
||||||
|
Write-Host "Version: $newVersion"
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host 'Next steps:' -ForegroundColor Yellow
|
||||||
|
if ($AfterMac) {
|
||||||
|
Write-Host ' Run publish.cmd (release-all continues to publish automatically)'
|
||||||
|
} else {
|
||||||
|
Write-Host ' 1) Copy Mac files (latest-mac.yml, TTRPGPlayer-*.zip) from Mac into release folder'
|
||||||
|
Write-Host ' 2) Run release-all.cmd (default -AfterMac) or publish.cmd'
|
||||||
|
}
|
||||||
|
Write-Host ''
|
||||||
|
|
||||||
|
exit 0
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"sshKey": "%USERPROFILE%\\.ssh\\ttrpg_updates_root",
|
||||||
|
"sshTarget": "root@185.173.94.234",
|
||||||
|
"remoteDir": "/var/www/updates_mailib_ru",
|
||||||
|
"feedUrl": "https://updates.mailib.ru/"
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0"
|
||||||
|
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0publish.ps1" %*
|
||||||
|
if errorlevel 1 pause
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
# Copy of D:\TTRPG-Release\publish.ps1 - keep in sync when updating the release folder tool.
|
||||||
|
|
||||||
|
param(
|
||||||
|
[switch]$CheckOnly,
|
||||||
|
[switch]$SkipMac
|
||||||
|
)
|
||||||
|
|
||||||
|
Set-StrictMode -Version Latest
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
$ReleaseDir = $PSScriptRoot
|
||||||
|
$ConfigPath = Join-Path $ReleaseDir 'publish-config.json'
|
||||||
|
|
||||||
|
function Expand-ConfigPath([string]$value) {
|
||||||
|
if ($value -match '%([^%]+)%') {
|
||||||
|
$envName = $Matches[1]
|
||||||
|
$envVal = [Environment]::GetEnvironmentVariable($envName)
|
||||||
|
if ($null -ne $envVal) {
|
||||||
|
return $value.Replace("%$envName%", $envVal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $value
|
||||||
|
}
|
||||||
|
|
||||||
|
function Write-Title([string]$text) {
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host "=== $text ===" -ForegroundColor Cyan
|
||||||
|
}
|
||||||
|
|
||||||
|
function Write-Ok([string]$text) {
|
||||||
|
Write-Host " [OK] $text" -ForegroundColor Green
|
||||||
|
}
|
||||||
|
|
||||||
|
function Write-Fail([string]$text) {
|
||||||
|
Write-Host " [!!] $text" -ForegroundColor Red
|
||||||
|
}
|
||||||
|
|
||||||
|
function Write-Warn([string]$text) {
|
||||||
|
Write-Host " [--] $text" -ForegroundColor Yellow
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-YmlVersion([string]$ymlPath) {
|
||||||
|
$content = Get-Content -LiteralPath $ymlPath -Raw -Encoding UTF8
|
||||||
|
$m = [regex]::Match($content, '(?m)^version:\s*(\S+)\s*$')
|
||||||
|
if ($m.Success) {
|
||||||
|
return $m.Groups[1].Value.Trim()
|
||||||
|
}
|
||||||
|
return $null
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-YmlPrimaryPath([string]$ymlPath) {
|
||||||
|
$content = Get-Content -LiteralPath $ymlPath -Raw -Encoding UTF8
|
||||||
|
$m = [regex]::Match($content, '(?m)^path:\s*(\S+)\s*$')
|
||||||
|
if ($m.Success) {
|
||||||
|
return $m.Groups[1].Value.Trim()
|
||||||
|
}
|
||||||
|
return $null
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-YmlReferencedFiles([string]$ymlPath) {
|
||||||
|
$names = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
|
||||||
|
$content = Get-Content -LiteralPath $ymlPath -Raw -Encoding UTF8
|
||||||
|
foreach ($m in [regex]::Matches($content, '(?m)^(?:\s*-\s*)?(?:url|path):\s*(\S+)\s*$')) {
|
||||||
|
[void]$names.Add($m.Groups[1].Value.Trim())
|
||||||
|
}
|
||||||
|
return @($names)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-YmlOptionalUrls([string]$ymlPath) {
|
||||||
|
$primary = Get-YmlPrimaryPath $ymlPath
|
||||||
|
$names = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
|
||||||
|
$content = Get-Content -LiteralPath $ymlPath -Raw -Encoding UTF8
|
||||||
|
foreach ($m in [regex]::Matches($content, '(?m)^\s*-\s*url:\s*(\S+)\s*$')) {
|
||||||
|
$name = $m.Groups[1].Value.Trim()
|
||||||
|
if ($primary -and $name.Equals($primary, [StringComparison]::OrdinalIgnoreCase)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
[void]$names.Add($name)
|
||||||
|
}
|
||||||
|
return @($names)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Resolve-ReleaseFile([string]$name) {
|
||||||
|
$direct = Join-Path $ReleaseDir $name
|
||||||
|
if (Test-Path -LiteralPath $direct) {
|
||||||
|
return Get-Item -LiteralPath $direct
|
||||||
|
}
|
||||||
|
if ($name -match 'x64' -and $name -notmatch 'x86_64') {
|
||||||
|
$alt = $name -replace 'x64', 'x86_64'
|
||||||
|
$altPath = Join-Path $ReleaseDir $alt
|
||||||
|
if (Test-Path -LiteralPath $altPath) {
|
||||||
|
return Get-Item -LiteralPath $altPath
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($name -match 'x86_64') {
|
||||||
|
$alt = $name -replace 'x86_64', 'x64'
|
||||||
|
$altPath = Join-Path $ReleaseDir $alt
|
||||||
|
if (Test-Path -LiteralPath $altPath) {
|
||||||
|
return Get-Item -LiteralPath $altPath
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $null
|
||||||
|
}
|
||||||
|
|
||||||
|
function Add-FileToUploadSet {
|
||||||
|
param(
|
||||||
|
[System.Collections.Generic.HashSet[string]]$set,
|
||||||
|
[System.IO.FileInfo]$file
|
||||||
|
)
|
||||||
|
[void]$set.Add($file.FullName)
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Title 'TTRPG Release Publisher'
|
||||||
|
Write-Host "Release folder: $ReleaseDir"
|
||||||
|
|
||||||
|
if (-not (Test-Path -LiteralPath $ConfigPath)) {
|
||||||
|
throw "Missing publish-config.json: $ConfigPath"
|
||||||
|
}
|
||||||
|
|
||||||
|
$config = Get-Content -LiteralPath $ConfigPath -Raw -Encoding UTF8 | ConvertFrom-Json
|
||||||
|
$sshKey = Expand-ConfigPath $config.sshKey
|
||||||
|
$sshTarget = [string]$config.sshTarget
|
||||||
|
$remoteDir = [string]$config.remoteDir
|
||||||
|
$feedUrl = [string]$config.feedUrl
|
||||||
|
|
||||||
|
if (-not (Test-Path -LiteralPath $sshKey)) {
|
||||||
|
throw "SSH key not found: $sshKey"
|
||||||
|
}
|
||||||
|
|
||||||
|
$errors = [System.Collections.Generic.List[string]]::new()
|
||||||
|
$warnings = [System.Collections.Generic.List[string]]::new()
|
||||||
|
$uploadFiles = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
|
||||||
|
|
||||||
|
Write-Title 'Windows (required)'
|
||||||
|
$winYml = Join-Path $ReleaseDir 'latest.yml'
|
||||||
|
if (-not (Test-Path -LiteralPath $winYml)) {
|
||||||
|
$errors.Add('Missing latest.yml')
|
||||||
|
} else {
|
||||||
|
Write-Ok 'latest.yml'
|
||||||
|
[void]$uploadFiles.Add($winYml)
|
||||||
|
foreach ($name in (Get-YmlReferencedFiles $winYml)) {
|
||||||
|
$file = Resolve-ReleaseFile $name
|
||||||
|
if ($null -eq $file) {
|
||||||
|
$errors.Add("Windows: missing file $name (from latest.yml)")
|
||||||
|
} else {
|
||||||
|
Write-Ok $file.Name
|
||||||
|
Add-FileToUploadSet $uploadFiles $file
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$blockmap = Resolve-ReleaseFile 'TTRPGPlayer-Setup.exe.blockmap'
|
||||||
|
if ($null -eq $blockmap) {
|
||||||
|
$warnings.Add('Missing TTRPGPlayer-Setup.exe.blockmap (recommended)')
|
||||||
|
} else {
|
||||||
|
Write-Ok $blockmap.Name
|
||||||
|
Add-FileToUploadSet $uploadFiles $blockmap
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Title 'Linux (if latest-linux*.yml present)'
|
||||||
|
$linuxYmls = Get-ChildItem -LiteralPath $ReleaseDir -Filter 'latest-linux*.yml' -File -ErrorAction SilentlyContinue
|
||||||
|
if ($linuxYmls.Count -eq 0) {
|
||||||
|
Write-Warn 'No latest-linux*.yml - skipping Linux'
|
||||||
|
} else {
|
||||||
|
foreach ($yml in $linuxYmls) {
|
||||||
|
Write-Ok $yml.Name
|
||||||
|
[void]$uploadFiles.Add($yml.FullName)
|
||||||
|
foreach ($name in (Get-YmlReferencedFiles $yml.FullName)) {
|
||||||
|
$file = Resolve-ReleaseFile $name
|
||||||
|
if ($null -eq $file) {
|
||||||
|
$errors.Add("Linux ($($yml.Name)): missing file $name")
|
||||||
|
} else {
|
||||||
|
if ($file.Name -ne $name) {
|
||||||
|
Write-Warn "$($yml.Name): yml expects $name, disk has $($file.Name) - will upload $($file.Name)"
|
||||||
|
} else {
|
||||||
|
Write-Ok "$($yml.Name) -> $name"
|
||||||
|
}
|
||||||
|
Add-FileToUploadSet $uploadFiles $file
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Title 'macOS (if latest-mac.yml present)'
|
||||||
|
$macYml = Join-Path $ReleaseDir 'latest-mac.yml'
|
||||||
|
if ($SkipMac) {
|
||||||
|
Write-Warn 'macOS skipped (-SkipMac)'
|
||||||
|
} elseif (-not (Test-Path -LiteralPath $macYml)) {
|
||||||
|
Write-Warn 'No latest-mac.yml - skipping macOS'
|
||||||
|
} else {
|
||||||
|
Write-Ok 'latest-mac.yml'
|
||||||
|
[void]$uploadFiles.Add($macYml)
|
||||||
|
|
||||||
|
$macVersion = Get-YmlVersion $macYml
|
||||||
|
$winYml = Join-Path $ReleaseDir 'latest.yml'
|
||||||
|
$winVersion = $null
|
||||||
|
if (Test-Path -LiteralPath $winYml) {
|
||||||
|
$winVersion = Get-YmlVersion $winYml
|
||||||
|
}
|
||||||
|
if ($macVersion -and $winVersion -and $macVersion -ne $winVersion) {
|
||||||
|
$errors.Add(
|
||||||
|
"macOS: latest-mac.yml is v$macVersion but latest.yml is v$winVersion (stale Mac feed). " +
|
||||||
|
'On Mac run: npm run pack:mac, then copy latest-mac.yml + TTRPGPlayer-*.zip (+ optional *.dmg). ' +
|
||||||
|
'Or publish Win/Linux only: publish.cmd -SkipMac'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
$primaryName = Get-YmlPrimaryPath $macYml
|
||||||
|
if (-not $primaryName) {
|
||||||
|
$errors.Add('macOS: latest-mac.yml has no path: entry')
|
||||||
|
} else {
|
||||||
|
$primaryFile = Resolve-ReleaseFile $primaryName
|
||||||
|
if ($null -eq $primaryFile) {
|
||||||
|
$errors.Add(
|
||||||
|
"macOS: missing primary update file $primaryName (path in latest-mac.yml). " +
|
||||||
|
'electron-updater on macOS needs the .zip from pack:mac, not only .dmg. Rebuild on Mac or use -SkipMac.'
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Write-Ok "primary update: $($primaryFile.Name)"
|
||||||
|
Add-FileToUploadSet $uploadFiles $primaryFile
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($name in (Get-YmlOptionalUrls $macYml)) {
|
||||||
|
$file = Resolve-ReleaseFile $name
|
||||||
|
if ($null -eq $file) {
|
||||||
|
$warnings.Add("macOS: optional file missing (not uploaded): $name")
|
||||||
|
} else {
|
||||||
|
Write-Ok "optional: $($file.Name)"
|
||||||
|
Add-FileToUploadSet $uploadFiles $file
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Title 'Summary'
|
||||||
|
foreach ($w in $warnings) {
|
||||||
|
Write-Warn $w
|
||||||
|
}
|
||||||
|
if ($errors.Count -gt 0) {
|
||||||
|
foreach ($e in $errors) {
|
||||||
|
Write-Fail $e
|
||||||
|
}
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host 'Upload cancelled. Fix the release folder and run again.' -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host "Files to upload: $($uploadFiles.Count)" -ForegroundColor Green
|
||||||
|
foreach ($path in ($uploadFiles | Sort-Object)) {
|
||||||
|
Write-Host " - $([System.IO.Path]::GetFileName($path))"
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($CheckOnly) {
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host 'CheckOnly: upload skipped.' -ForegroundColor Yellow
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Title 'Upload'
|
||||||
|
Write-Host "Target: ${sshTarget}:${remoteDir}"
|
||||||
|
Write-Host "Feed: $feedUrl"
|
||||||
|
|
||||||
|
foreach ($path in ($uploadFiles | Sort-Object)) {
|
||||||
|
$name = [System.IO.Path]::GetFileName($path)
|
||||||
|
Write-Host " -> $name"
|
||||||
|
& scp -i $sshKey -q $path "${sshTarget}:${remoteDir}/"
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
throw "scp failed for $name (exit $LASTEXITCODE)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host 'Setting www-data ownership on server...'
|
||||||
|
& ssh -i $sshKey $sshTarget "chown -R www-data:www-data '$remoteDir'"
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
throw "ssh chown failed (exit $LASTEXITCODE)"
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Title 'Done'
|
||||||
|
Write-Host 'Verify:'
|
||||||
|
Write-Host " ${feedUrl}latest.yml"
|
||||||
|
if (Test-Path -LiteralPath (Join-Path $ReleaseDir 'latest-linux.yml')) {
|
||||||
|
Write-Host " ${feedUrl}latest-linux.yml"
|
||||||
|
}
|
||||||
|
if (Test-Path -LiteralPath (Join-Path $ReleaseDir 'latest-mac.yml')) {
|
||||||
|
Write-Host " ${feedUrl}latest-mac.yml"
|
||||||
|
}
|
||||||
|
|
||||||
|
exit 0
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
@echo off
|
||||||
|
REM Legacy: bump version in script, then Win/Linux (Mac files added later).
|
||||||
|
cd /d "%~dp0"
|
||||||
|
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0release-all.ps1" -Bump %*
|
||||||
|
if errorlevel 1 pause
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0"
|
||||||
|
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0release-all.ps1" %*
|
||||||
|
if errorlevel 1 pause
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
# Full release: prepare (build Win/Linux, copy) then publish (validate + upload).
|
||||||
|
# Run: release-all.cmd (default: -AfterMac, version already set, Mac files in release folder)
|
||||||
|
# release-all-bump.cmd (bump version first, Mac later)
|
||||||
|
|
||||||
|
param(
|
||||||
|
[string]$Version = '',
|
||||||
|
[switch]$Bump,
|
||||||
|
[switch]$AfterMac,
|
||||||
|
[switch]$Minor,
|
||||||
|
[switch]$SkipGit,
|
||||||
|
[switch]$SkipLinux,
|
||||||
|
[switch]$NoBump,
|
||||||
|
[switch]$CheckOnlyPublish,
|
||||||
|
[switch]$SkipMac
|
||||||
|
)
|
||||||
|
|
||||||
|
Set-StrictMode -Version Latest
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
$ToolDir = $PSScriptRoot
|
||||||
|
$PrepareScript = Join-Path $ToolDir 'prepare-release.ps1'
|
||||||
|
$PublishScript = Join-Path $ToolDir 'publish.ps1'
|
||||||
|
|
||||||
|
if (-not (Test-Path -LiteralPath $PrepareScript)) {
|
||||||
|
throw "Missing prepare-release.ps1: $PrepareScript"
|
||||||
|
}
|
||||||
|
if (-not (Test-Path -LiteralPath $PublishScript)) {
|
||||||
|
throw "Missing publish.ps1: $PublishScript"
|
||||||
|
}
|
||||||
|
|
||||||
|
$useAfterMac = $AfterMac
|
||||||
|
if ($Bump -and $AfterMac) {
|
||||||
|
throw 'Use either -Bump or -AfterMac, not both'
|
||||||
|
}
|
||||||
|
if (-not $Bump -and -not $PSBoundParameters.ContainsKey('AfterMac')) {
|
||||||
|
$useAfterMac = $true
|
||||||
|
}
|
||||||
|
|
||||||
|
$prepareArgs = @()
|
||||||
|
if ($Version) { $prepareArgs += '-Version', $Version }
|
||||||
|
if ($Bump) { $prepareArgs += '-Bump' }
|
||||||
|
if ($useAfterMac) { $prepareArgs += '-AfterMac' }
|
||||||
|
if ($Minor) { $prepareArgs += '-Minor' }
|
||||||
|
if ($SkipGit) { $prepareArgs += '-SkipGit' }
|
||||||
|
if ($SkipLinux) { $prepareArgs += '-SkipLinux' }
|
||||||
|
if ($NoBump) { $prepareArgs += '-NoBump' }
|
||||||
|
|
||||||
|
$publishArgs = @()
|
||||||
|
if ($CheckOnlyPublish) { $publishArgs += '-CheckOnly' }
|
||||||
|
if ($SkipMac) { $publishArgs += '-SkipMac' }
|
||||||
|
|
||||||
|
Write-Host '=== TTRPG Full Release ===' -ForegroundColor Cyan
|
||||||
|
Write-Host ''
|
||||||
|
|
||||||
|
Write-Host '>>> Phase 1/2: Prepare release' -ForegroundColor Yellow
|
||||||
|
& powershell -NoProfile -ExecutionPolicy Bypass -File $PrepareScript @prepareArgs
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
throw "Prepare release failed (exit $LASTEXITCODE). Publish not started."
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host '>>> Phase 2/2: Publish to server' -ForegroundColor Yellow
|
||||||
|
& powershell -NoProfile -ExecutionPolicy Bypass -File $PublishScript @publishArgs
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
throw "Publish failed (exit $LASTEXITCODE)"
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host '=== Full release completed ===' -ForegroundColor Green
|
||||||
|
exit 0
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"projectRoot": "D:\\Work\\my_projects\\dnd_project\\dnd_player",
|
||||||
|
"releaseDir": "D:\\TTRPG-Release",
|
||||||
|
"gitRemote": "origin",
|
||||||
|
"giteaMcpConfig": "C:\\Users\\Administrator\\.cursor\\mcp.json",
|
||||||
|
"wslDistro": ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0"
|
||||||
|
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0release.ps1" %*
|
||||||
|
if errorlevel 1 pause
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# Full release: prepare (version, git, build, copy) then publish (validate + upload).
|
||||||
|
# Run: release.cmd
|
||||||
|
|
||||||
|
param(
|
||||||
|
[string]$Version = '',
|
||||||
|
[switch]$Minor,
|
||||||
|
[switch]$SkipGit,
|
||||||
|
[switch]$SkipLinux,
|
||||||
|
[switch]$NoBump,
|
||||||
|
[switch]$CheckOnly
|
||||||
|
)
|
||||||
|
|
||||||
|
Set-StrictMode -Version Latest
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
$ToolDir = $PSScriptRoot
|
||||||
|
$PrepareScript = Join-Path $ToolDir 'prepare-release.ps1'
|
||||||
|
$PublishScript = Join-Path $ToolDir 'publish.ps1'
|
||||||
|
|
||||||
|
if (-not (Test-Path -LiteralPath $PrepareScript)) {
|
||||||
|
throw "Missing prepare-release.ps1 in $ToolDir"
|
||||||
|
}
|
||||||
|
if (-not (Test-Path -LiteralPath $PublishScript)) {
|
||||||
|
throw "Missing publish.ps1 in $ToolDir"
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host '=== TTRPG Full Release ===' -ForegroundColor Cyan
|
||||||
|
Write-Host 'Step A: prepare-release'
|
||||||
|
Write-Host 'Step B: publish (after prepare succeeds)'
|
||||||
|
Write-Host ''
|
||||||
|
|
||||||
|
$prepareArgs = @('-File', $PrepareScript)
|
||||||
|
if ($Version) { $prepareArgs += '-Version', $Version }
|
||||||
|
if ($Minor) { $prepareArgs += '-Minor' }
|
||||||
|
if ($SkipGit) { $prepareArgs += '-SkipGit' }
|
||||||
|
if ($SkipLinux) { $prepareArgs += '-SkipLinux' }
|
||||||
|
if ($NoBump) { $prepareArgs += '-NoBump' }
|
||||||
|
|
||||||
|
& powershell -NoProfile -ExecutionPolicy Bypass @prepareArgs
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host 'Prepare failed. Publish was not started.' -ForegroundColor Red
|
||||||
|
exit $LASTEXITCODE
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host 'Prepare finished. Starting publish...' -ForegroundColor Green
|
||||||
|
Write-Host ''
|
||||||
|
|
||||||
|
$publishArgs = @('-File', $PublishScript)
|
||||||
|
if ($CheckOnly) { $publishArgs += '-CheckOnly' }
|
||||||
|
|
||||||
|
& powershell -NoProfile -ExecutionPolicy Bypass @publishArgs
|
||||||
|
exit $LASTEXITCODE
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
export NVM_DIR="${HOME}/.nvm"
|
||||||
|
if [[ -s "${NVM_DIR}/nvm.sh" ]]; then
|
||||||
|
# shellcheck source=/dev/null
|
||||||
|
. "${NVM_DIR}/nvm.sh"
|
||||||
|
nvm install
|
||||||
|
nvm use
|
||||||
|
else
|
||||||
|
echo "nvm not found at ${NVM_DIR}/nvm.sh (install nvm or use Node 20.19+ / 22.12+ for Vite)" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Using $(node -v) ($(command -v node))"
|
||||||
|
export FFMPEG_BINARIES_URL="${FFMPEG_BINARIES_URL:-https://cdn.npmmirror.com/binaries/ffmpeg-static}"
|
||||||
|
echo "Using ffmpeg-static mirror: ${FFMPEG_BINARIES_URL}"
|
||||||
|
npm ci
|
||||||
|
npm run pack:linux
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
## Project Converter (DNDGamePlayer)
|
|
||||||
|
|
||||||
Мини-приложение для конвертации `.dnd.zip` проектов в новый формат, добавляя **миниатюры превью сцен** (thumbnail) для ускорения редактора.
|
|
||||||
|
|
||||||
### Что делает
|
|
||||||
|
|
||||||
- Открывает исходный `.dnd.zip`
|
|
||||||
- Читает `project.json`
|
|
||||||
- Для каждой сцены с `previewAssetId`:
|
|
||||||
- генерирует `previewThumbAssetId` (WebP, max 320px по длинной стороне)
|
|
||||||
- кладёт файл миниатюры в `assets/` и добавляет `MediaAsset` в `project.assets`
|
|
||||||
- Пишет новый `.dnd.zip` (исходник не трогает)
|
|
||||||
|
|
||||||
Оригинальные ассеты (изображения/видео) **не перекодируются** — меняется только `project.json` + добавляются миниатюры.
|
|
||||||
|
|
||||||
### Запуск
|
|
||||||
|
|
||||||
Из папки `tools/project-converter/`:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install
|
|
||||||
npm run dev
|
|
||||||
```
|
|
||||||
|
|
||||||
### Почему не попадает в сборку DNDGamePlayer
|
|
||||||
|
|
||||||
Это отдельный пакет со своим `package.json` в `tools/`. Сборка основного приложения берёт только `dist/**/*` и корневой `package.json`.
|
|
||||||
|
|
||||||
-1547
File diff suppressed because it is too large
Load Diff
@@ -1,21 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "dnd-project-converter",
|
|
||||||
"private": true,
|
|
||||||
"version": "0.1.0",
|
|
||||||
"description": "Simple UI tool to convert .dnd.zip projects (add scene preview thumbnails).",
|
|
||||||
"type": "module",
|
|
||||||
"main": "src/main.js",
|
|
||||||
"scripts": {
|
|
||||||
"dev": "node src/run-electron.mjs",
|
|
||||||
"start": "node src/run-electron.mjs",
|
|
||||||
"lint": "node -e \"console.log('no lint')\""
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"electron": "^41.2.0",
|
|
||||||
"ffmpeg-static": "^5.3.0",
|
|
||||||
"sharp": "^0.34.5",
|
|
||||||
"yauzl": "^3.3.0",
|
|
||||||
"yazl": "^3.3.1"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html lang="ru">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
||||||
<title>DND Project Converter</title>
|
|
||||||
<style>
|
|
||||||
:root {
|
|
||||||
color-scheme: dark;
|
|
||||||
}
|
|
||||||
body {
|
|
||||||
margin: 0;
|
|
||||||
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
|
|
||||||
background: #0b0f19;
|
|
||||||
color: #e6e8ee;
|
|
||||||
}
|
|
||||||
.wrap {
|
|
||||||
max-width: 760px;
|
|
||||||
margin: 24px auto;
|
|
||||||
padding: 20px;
|
|
||||||
}
|
|
||||||
h1 {
|
|
||||||
font-size: 18px;
|
|
||||||
margin: 0 0 12px 0;
|
|
||||||
}
|
|
||||||
.card {
|
|
||||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
|
||||||
background: rgba(255, 255, 255, 0.03);
|
|
||||||
border-radius: 12px;
|
|
||||||
padding: 14px;
|
|
||||||
}
|
|
||||||
.row {
|
|
||||||
display: flex;
|
|
||||||
gap: 10px;
|
|
||||||
align-items: center;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
margin: 10px 0;
|
|
||||||
}
|
|
||||||
button {
|
|
||||||
appearance: none;
|
|
||||||
border: 1px solid rgba(255, 255, 255, 0.16);
|
|
||||||
background: rgba(255, 255, 255, 0.06);
|
|
||||||
color: inherit;
|
|
||||||
padding: 10px 12px;
|
|
||||||
border-radius: 10px;
|
|
||||||
cursor: pointer;
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
button.primary {
|
|
||||||
border-color: rgba(167, 139, 250, 0.55);
|
|
||||||
background: rgba(167, 139, 250, 0.16);
|
|
||||||
}
|
|
||||||
button:disabled {
|
|
||||||
opacity: 0.55;
|
|
||||||
cursor: not-allowed;
|
|
||||||
}
|
|
||||||
.path {
|
|
||||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
|
|
||||||
font-size: 12px;
|
|
||||||
opacity: 0.9;
|
|
||||||
word-break: break-all;
|
|
||||||
}
|
|
||||||
.log {
|
|
||||||
margin-top: 12px;
|
|
||||||
height: 320px;
|
|
||||||
overflow: auto;
|
|
||||||
border-radius: 10px;
|
|
||||||
padding: 10px;
|
|
||||||
background: rgba(0, 0, 0, 0.35);
|
|
||||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
|
||||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
|
|
||||||
font-size: 12px;
|
|
||||||
white-space: pre-wrap;
|
|
||||||
}
|
|
||||||
.muted {
|
|
||||||
opacity: 0.8;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div class="wrap">
|
|
||||||
<h1>DND Project Converter</h1>
|
|
||||||
<div class="card">
|
|
||||||
<div class="muted">Конвертация: добавление миниатюр превью сцен (WebP 320px) в новый `.dnd.zip`.</div>
|
|
||||||
<div class="row">
|
|
||||||
<button id="pick">Выбрать .dnd.zip</button>
|
|
||||||
<button id="convert" class="primary" disabled>Конвертировать</button>
|
|
||||||
</div>
|
|
||||||
<div class="row">
|
|
||||||
<div class="muted">Вход:</div>
|
|
||||||
<div id="in" class="path">—</div>
|
|
||||||
</div>
|
|
||||||
<div class="row">
|
|
||||||
<div class="muted">Выход:</div>
|
|
||||||
<div id="out" class="path">—</div>
|
|
||||||
</div>
|
|
||||||
<div id="log" class="log"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script type="module" src="./renderer.js"></script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
|
|
||||||
@@ -1,346 +0,0 @@
|
|||||||
import crypto from 'node:crypto';
|
|
||||||
import fs from 'node:fs/promises';
|
|
||||||
import path from 'node:path';
|
|
||||||
import { fileURLToPath } from 'node:url';
|
|
||||||
|
|
||||||
import { app, BrowserWindow, dialog, ipcMain } from 'electron';
|
|
||||||
import sharp from 'sharp';
|
|
||||||
import ffmpegStatic from 'ffmpeg-static';
|
|
||||||
import { execFile } from 'node:child_process';
|
|
||||||
import { promisify } from 'node:util';
|
|
||||||
import fsSync from 'node:fs';
|
|
||||||
|
|
||||||
import yauzl from 'yauzl';
|
|
||||||
import { ZipFile } from 'yazl';
|
|
||||||
|
|
||||||
import { optimizeImageBufferVisuallyLossless } from '../../../app/main/project/optimizeImageImport.lib.mjs';
|
|
||||||
|
|
||||||
const execFileAsync = promisify(execFile);
|
|
||||||
|
|
||||||
const THUMB_MAX_PX = 320;
|
|
||||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
||||||
|
|
||||||
function isDndZip(p) {
|
|
||||||
return typeof p === 'string' && p.toLowerCase().endsWith('.dnd.zip');
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fileExists(p) {
|
|
||||||
try {
|
|
||||||
const st = await fs.stat(p);
|
|
||||||
return st.isFile();
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function asBuffer(x) {
|
|
||||||
return Buffer.isBuffer(x) ? x : Buffer.from(x);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function generateImageThumbWebp(absPath) {
|
|
||||||
return await sharp(absPath)
|
|
||||||
.rotate()
|
|
||||||
.resize(THUMB_MAX_PX, THUMB_MAX_PX, { fit: 'inside', withoutEnlargement: true })
|
|
||||||
.webp({ quality: 82 })
|
|
||||||
.toBuffer();
|
|
||||||
}
|
|
||||||
|
|
||||||
async function extractVideoFrameToPng(absVideo, absPng) {
|
|
||||||
const ffmpegPath = ffmpegStatic;
|
|
||||||
if (!ffmpegPath) throw new Error('ffmpeg-static not available');
|
|
||||||
const seekSeconds = ['0.5', '0.25', '0'];
|
|
||||||
for (const ss of seekSeconds) {
|
|
||||||
try {
|
|
||||||
await fs.rm(absPng, { force: true }).catch(() => undefined);
|
|
||||||
await execFileAsync(
|
|
||||||
ffmpegPath,
|
|
||||||
['-hide_banner', '-loglevel', 'error', '-y', '-ss', ss, '-i', absVideo, '-frames:v', '1', absPng],
|
|
||||||
{ maxBuffer: 16 * 1024 * 1024 },
|
|
||||||
);
|
|
||||||
const st = await fs.stat(absPng).catch(() => null);
|
|
||||||
if (st && st.isFile() && st.size > 0) return true;
|
|
||||||
} catch {
|
|
||||||
// try next seek
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function generateVideoThumbWebp(absVideo) {
|
|
||||||
const tmpDir = await fs.mkdtemp(path.join(app.getPath('temp'), 'dnd-thumb-'));
|
|
||||||
const tmpPng = path.join(tmpDir, 'frame.png');
|
|
||||||
try {
|
|
||||||
const ok = await extractVideoFrameToPng(absVideo, tmpPng);
|
|
||||||
if (!ok) return null;
|
|
||||||
return await sharp(tmpPng)
|
|
||||||
.resize(THUMB_MAX_PX, THUMB_MAX_PX, { fit: 'inside', withoutEnlargement: true })
|
|
||||||
.webp({ quality: 82 })
|
|
||||||
.toBuffer();
|
|
||||||
} finally {
|
|
||||||
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => undefined);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function openZip(zipPath) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
yauzl.open(zipPath, { lazyEntries: true }, (err, zip) => {
|
|
||||||
if (err || !zip) reject(err ?? new Error('Failed to open zip'));
|
|
||||||
else resolve(zip);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function readEntryBuffer(zip, entry) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
zip.openReadStream(entry, (err, rs) => {
|
|
||||||
if (err || !rs) return reject(err ?? new Error('No stream'));
|
|
||||||
const chunks = [];
|
|
||||||
rs.on('data', (c) => chunks.push(c));
|
|
||||||
rs.on('end', () => resolve(Buffer.concat(chunks)));
|
|
||||||
rs.on('error', reject);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function readZipAll(zipPath) {
|
|
||||||
const zip = await openZip(zipPath);
|
|
||||||
try {
|
|
||||||
const files = new Map(); // name -> Buffer
|
|
||||||
await new Promise((resolve, reject) => {
|
|
||||||
zip.on('error', reject);
|
|
||||||
zip.on('entry', (entry) => {
|
|
||||||
// Process each entry sequentially; calling openReadStream after 'end' can fail with 'closed'.
|
|
||||||
void (async () => {
|
|
||||||
if (!entry.fileName.endsWith('/')) {
|
|
||||||
const buf = await readEntryBuffer(zip, entry);
|
|
||||||
files.set(entry.fileName, buf);
|
|
||||||
}
|
|
||||||
zip.readEntry();
|
|
||||||
})().catch(reject);
|
|
||||||
});
|
|
||||||
zip.on('end', resolve);
|
|
||||||
zip.readEntry();
|
|
||||||
});
|
|
||||||
return files;
|
|
||||||
} finally {
|
|
||||||
zip.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function sha256(buf) {
|
|
||||||
return crypto.createHash('sha256').update(buf).digest('hex');
|
|
||||||
}
|
|
||||||
|
|
||||||
function sanitizeFileName(name) {
|
|
||||||
return String(name).replace(/[<>:"/\\|?*\u0000-\u001F]+/g, '_').slice(0, 180);
|
|
||||||
}
|
|
||||||
|
|
||||||
function newAssetId() {
|
|
||||||
return crypto.randomBytes(16).toString('hex');
|
|
||||||
}
|
|
||||||
|
|
||||||
function guessMimeFromWebp() {
|
|
||||||
return 'image/webp';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Re-encode raster image assets to visually lossless smaller files; updates `files` and `project.assets` in place.
|
|
||||||
* @param {Map<string, Buffer>} files
|
|
||||||
* @param {Record<string, unknown>} project
|
|
||||||
* @param {(s: string) => void} [onLog]
|
|
||||||
*/
|
|
||||||
async function optimizeProjectImageAssets(files, project, onLog) {
|
|
||||||
const assets = project.assets && typeof project.assets === 'object' ? project.assets : {};
|
|
||||||
let n = 0;
|
|
||||||
for (const aid of Object.keys(assets)) {
|
|
||||||
const asset = assets[aid];
|
|
||||||
if (!asset || typeof asset !== 'object') continue;
|
|
||||||
if (asset.type !== 'image' || typeof asset.relPath !== 'string') continue;
|
|
||||||
const rel = asset.relPath.replace(/^\//u, '');
|
|
||||||
if (!rel.startsWith('assets/')) continue;
|
|
||||||
const bytes = files.get(rel);
|
|
||||||
if (!bytes || bytes.length === 0) continue;
|
|
||||||
|
|
||||||
onLog?.(`Optimize image: ${rel}…`);
|
|
||||||
const opt = await optimizeImageBufferVisuallyLossless(bytes);
|
|
||||||
if (opt.passthrough) {
|
|
||||||
onLog?.(` skip (passthrough)`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const newName = `${path.parse(path.basename(rel)).name}.${opt.ext}`;
|
|
||||||
const newRel = `assets/${newName}`;
|
|
||||||
files.delete(rel);
|
|
||||||
files.set(newRel, asBuffer(opt.buffer));
|
|
||||||
|
|
||||||
const origName = typeof asset.originalName === 'string' ? asset.originalName : path.basename(rel);
|
|
||||||
const stem = path.parse(origName).name;
|
|
||||||
asset.relPath = newRel;
|
|
||||||
asset.mime = opt.mime;
|
|
||||||
asset.originalName = `${stem}.${opt.ext}`;
|
|
||||||
asset.sha256 = sha256(opt.buffer);
|
|
||||||
asset.sizeBytes = opt.buffer.length;
|
|
||||||
n += 1;
|
|
||||||
onLog?.(` OK → ${newRel} (${bytes.length} → ${opt.buffer.length} bytes)`);
|
|
||||||
}
|
|
||||||
if (n > 0) onLog?.(`Optimized image assets: ${n}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function convertZip({ inputPath, outputPath, onLog }) {
|
|
||||||
if (!(await fileExists(inputPath))) throw new Error('Input file not found');
|
|
||||||
if (!isDndZip(inputPath)) throw new Error('Expected .dnd.zip');
|
|
||||||
if (!outputPath || !isDndZip(outputPath)) throw new Error('Output path must end with .dnd.zip');
|
|
||||||
|
|
||||||
const files = await readZipAll(inputPath);
|
|
||||||
const projectBuf = files.get('project.json');
|
|
||||||
if (!projectBuf) throw new Error('project.json not found in zip');
|
|
||||||
|
|
||||||
const project = JSON.parse(projectBuf.toString('utf8'));
|
|
||||||
project.scenes = project.scenes ?? {};
|
|
||||||
project.assets = project.assets ?? {};
|
|
||||||
|
|
||||||
onLog?.('Optimizing image assets…');
|
|
||||||
await optimizeProjectImageAssets(files, project, onLog);
|
|
||||||
|
|
||||||
let added = 0;
|
|
||||||
for (const sid of Object.keys(project.scenes)) {
|
|
||||||
const sc = project.scenes[sid];
|
|
||||||
if (!sc) continue;
|
|
||||||
if (sc.previewThumbAssetId) continue;
|
|
||||||
const assetId = sc.previewAssetId ?? null;
|
|
||||||
const assetType = sc.previewAssetType ?? null;
|
|
||||||
if (!assetId || !assetType) continue;
|
|
||||||
|
|
||||||
const asset = project.assets[assetId] ?? null;
|
|
||||||
if (!asset || typeof asset.relPath !== 'string') continue;
|
|
||||||
const assetRel = asset.relPath.replace(/^\//, '');
|
|
||||||
const assetBytes = files.get(assetRel);
|
|
||||||
if (!assetBytes) continue;
|
|
||||||
|
|
||||||
onLog?.(`Scene ${sid}: generating thumb…`);
|
|
||||||
const kind = assetType === 'video' ? 'video' : 'image';
|
|
||||||
|
|
||||||
// Write source to temp to allow sharp/ffmpeg to read it.
|
|
||||||
const tmpDir = await fs.mkdtemp(path.join(app.getPath('temp'), 'dnd-conv-'));
|
|
||||||
const tmpSrc = path.join(tmpDir, sanitizeFileName(path.basename(assetRel)));
|
|
||||||
await fs.writeFile(tmpSrc, assetBytes);
|
|
||||||
try {
|
|
||||||
const thumbBytes =
|
|
||||||
kind === 'image' ? await generateImageThumbWebp(tmpSrc) : await generateVideoThumbWebp(tmpSrc);
|
|
||||||
if (!thumbBytes) {
|
|
||||||
onLog?.(`Scene ${sid}: thumb skipped (failed).`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const thumbId = newAssetId();
|
|
||||||
const thumbName = `${thumbId}_preview_thumb.webp`;
|
|
||||||
const thumbRel = `assets/${thumbName}`;
|
|
||||||
|
|
||||||
files.set(thumbRel, asBuffer(thumbBytes));
|
|
||||||
project.assets[thumbId] = {
|
|
||||||
id: thumbId,
|
|
||||||
type: 'image',
|
|
||||||
mime: guessMimeFromWebp(),
|
|
||||||
originalName: thumbName,
|
|
||||||
relPath: thumbRel,
|
|
||||||
sha256: sha256(thumbBytes),
|
|
||||||
sizeBytes: thumbBytes.length,
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
};
|
|
||||||
sc.previewThumbAssetId = thumbId;
|
|
||||||
added += 1;
|
|
||||||
onLog?.(`Scene ${sid}: OK`);
|
|
||||||
} finally {
|
|
||||||
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => undefined);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
files.set('project.json', Buffer.from(JSON.stringify(project, null, 2), 'utf8'));
|
|
||||||
|
|
||||||
const zipfile = new ZipFile();
|
|
||||||
for (const [name, buf] of files) {
|
|
||||||
const isProjectJson = name === 'project.json';
|
|
||||||
zipfile.addBuffer(buf, name, { compressionLevel: isProjectJson ? 9 : 0 });
|
|
||||||
}
|
|
||||||
|
|
||||||
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
|
||||||
const tmpOut = `${outputPath}.tmp`;
|
|
||||||
await fs.rm(tmpOut, { force: true }).catch(() => undefined);
|
|
||||||
|
|
||||||
await new Promise((resolve, reject) => {
|
|
||||||
const out = fsSync.createWriteStream(tmpOut);
|
|
||||||
out.on('close', resolve);
|
|
||||||
out.on('error', reject);
|
|
||||||
zipfile.outputStream.pipe(out);
|
|
||||||
zipfile.end();
|
|
||||||
});
|
|
||||||
await fs.rm(outputPath, { force: true }).catch(() => undefined);
|
|
||||||
await fs.rename(tmpOut, outputPath);
|
|
||||||
|
|
||||||
onLog?.(`Added thumbnails: ${added}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
function createWindow() {
|
|
||||||
const win = new BrowserWindow({
|
|
||||||
width: 860,
|
|
||||||
height: 640,
|
|
||||||
backgroundColor: '#0b0f19',
|
|
||||||
webPreferences: {
|
|
||||||
preload: path.join(here, 'preload.cjs'),
|
|
||||||
contextIsolation: true,
|
|
||||||
nodeIntegration: false,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
win.removeMenu();
|
|
||||||
void win.loadFile(path.join(here, 'index.html'));
|
|
||||||
}
|
|
||||||
|
|
||||||
app.whenReady().then(() => {
|
|
||||||
createWindow();
|
|
||||||
|
|
||||||
ipcMain.handle('converter.pickInputZip', async () => {
|
|
||||||
const res = await dialog.showOpenDialog({
|
|
||||||
title: 'Выберите файл проекта (.dnd.zip)',
|
|
||||||
filters: [{ name: 'DND Project', extensions: ['zip'] }],
|
|
||||||
properties: ['openFile'],
|
|
||||||
});
|
|
||||||
if (res.canceled || res.filePaths.length === 0) return { canceled: true };
|
|
||||||
const p = res.filePaths[0];
|
|
||||||
if (!isDndZip(p)) return { canceled: false, path: p }; // allow, but user should pick correct
|
|
||||||
return { canceled: false, path: p };
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.handle('converter.pickOutputZip', async (_e, { inputPath }) => {
|
|
||||||
const suggested = inputPath && typeof inputPath === 'string' ? inputPath.replace(/\.dnd\.zip$/i, '.thumbs.dnd.zip') : 'converted.dnd.zip';
|
|
||||||
const res = await dialog.showSaveDialog({
|
|
||||||
title: 'Сохранить конвертированный проект',
|
|
||||||
defaultPath: suggested,
|
|
||||||
filters: [{ name: 'DND Project', extensions: ['zip'] }],
|
|
||||||
});
|
|
||||||
if (res.canceled || !res.filePath) return { canceled: true };
|
|
||||||
return { canceled: false, path: res.filePath };
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.handle('converter.convert', async (_e, { inputPath, outputPath }) => {
|
|
||||||
try {
|
|
||||||
await convertZip({
|
|
||||||
inputPath,
|
|
||||||
outputPath,
|
|
||||||
onLog: (line) => {
|
|
||||||
const win = BrowserWindow.getAllWindows()[0];
|
|
||||||
if (win && !win.isDestroyed()) win.webContents.send('converter.log', { line });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return { ok: true };
|
|
||||||
} catch (err) {
|
|
||||||
const msg = err instanceof Error ? err.message : String(err);
|
|
||||||
const stack = err instanceof Error ? err.stack : null;
|
|
||||||
return { ok: false, error: stack ? `${msg}\n${stack}` : msg };
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.on('converter.log', () => undefined);
|
|
||||||
});
|
|
||||||
|
|
||||||
app.on('window-all-closed', () => {
|
|
||||||
app.quit();
|
|
||||||
});
|
|
||||||
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
const { contextBridge, ipcRenderer } = require('electron');
|
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld('converter', {
|
|
||||||
pickInputZip: () => ipcRenderer.invoke('converter.pickInputZip'),
|
|
||||||
pickOutputZip: (inputPath) => ipcRenderer.invoke('converter.pickOutputZip', { inputPath }),
|
|
||||||
convert: ({ inputPath, outputPath }) =>
|
|
||||||
ipcRenderer.invoke('converter.convert', { inputPath, outputPath }),
|
|
||||||
onLog: (cb) => {
|
|
||||||
ipcRenderer.removeAllListeners('converter.log');
|
|
||||||
ipcRenderer.on('converter.log', (_e, { line }) => cb(line));
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
let inputPath = null;
|
|
||||||
let outputPath = null;
|
|
||||||
|
|
||||||
const $pick = document.getElementById('pick');
|
|
||||||
const $convert = document.getElementById('convert');
|
|
||||||
const $in = document.getElementById('in');
|
|
||||||
const $out = document.getElementById('out');
|
|
||||||
const $log = document.getElementById('log');
|
|
||||||
|
|
||||||
function log(line) {
|
|
||||||
$log.textContent += `${line}\n`;
|
|
||||||
$log.scrollTop = $log.scrollHeight;
|
|
||||||
}
|
|
||||||
|
|
||||||
window.addEventListener('error', (e) => {
|
|
||||||
try {
|
|
||||||
log(`JS error: ${String(e.message || e.error || 'unknown')}`);
|
|
||||||
} catch {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!window.converter) {
|
|
||||||
log('Ошибка: window.converter не найден.');
|
|
||||||
log('Похоже, preload не подключился. Перезапустите утилиту.');
|
|
||||||
$pick.disabled = true;
|
|
||||||
$convert.disabled = true;
|
|
||||||
} else {
|
|
||||||
window.converter.onLog((line) => log(line));
|
|
||||||
log('Готово. Нажмите "Выбрать .dnd.zip".');
|
|
||||||
}
|
|
||||||
|
|
||||||
function setPaths() {
|
|
||||||
$in.textContent = inputPath ?? '—';
|
|
||||||
$out.textContent = outputPath ?? '—';
|
|
||||||
$convert.disabled = !inputPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
$pick.addEventListener('click', async () => {
|
|
||||||
$log.textContent = '';
|
|
||||||
if (!window.converter) {
|
|
||||||
log('Ошибка: preload не подключился (window.converter отсутствует).');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const res = await window.converter.pickInputZip();
|
|
||||||
if (!res || res.canceled) return;
|
|
||||||
inputPath = res.path;
|
|
||||||
outputPath = null;
|
|
||||||
setPaths();
|
|
||||||
log(`Выбран файл: ${inputPath}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
$convert.addEventListener('click', async () => {
|
|
||||||
if (!inputPath) return;
|
|
||||||
if (!window.converter) {
|
|
||||||
log('Ошибка: preload не подключился (window.converter отсутствует).');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
$convert.disabled = true;
|
|
||||||
try {
|
|
||||||
log('Готовлю выходной файл…');
|
|
||||||
const dest = await window.converter.pickOutputZip(inputPath);
|
|
||||||
if (!dest || dest.canceled) {
|
|
||||||
log('Отмена.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
outputPath = dest.path;
|
|
||||||
setPaths();
|
|
||||||
|
|
||||||
log('Конвертация…');
|
|
||||||
const res = await window.converter.convert({ inputPath, outputPath });
|
|
||||||
if (res.ok) {
|
|
||||||
log('Готово.');
|
|
||||||
} else {
|
|
||||||
log(`Ошибка: ${res.error}`);
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
$convert.disabled = !inputPath;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
setPaths();
|
|
||||||
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
import path from 'node:path';
|
|
||||||
import { fileURLToPath } from 'node:url';
|
|
||||||
import { spawn } from 'node:child_process';
|
|
||||||
|
|
||||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
||||||
const root = path.resolve(here, '..');
|
|
||||||
const electronBin = path.resolve(root, 'node_modules', '.bin', process.platform === 'win32' ? 'electron.cmd' : 'electron');
|
|
||||||
|
|
||||||
const child = spawn(electronBin, ['.'], {
|
|
||||||
cwd: root,
|
|
||||||
stdio: 'inherit',
|
|
||||||
shell: process.platform === 'win32',
|
|
||||||
});
|
|
||||||
|
|
||||||
child.on('exit', (code) => {
|
|
||||||
process.exitCode = code ?? 0;
|
|
||||||
});
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user