From 0f1a81d7977a8cc9b5d40ec9859686bb58591fb3 Mon Sep 17 00:00:00 2001 From: Aleksei Vorobev Date: Fri, 13 Nov 2026 02:37:49 +0400 Subject: [PATCH] Release ReaUI Builder 2.2.3 and upgrade export gate to v13 --- .github/workflows/export-gate.yml | 45 +- CHANGELOG.md | 21 + README.md | 6 +- RELEASE_NOTES_2_2_3.md | 19 + ReaUI_Builder.html | 504 +- ReaUI_Builder_2_2_3.html | 27568 ++++++++++++++++ docs/Export_Gate_v13_QA_EN.md | 53 + docs/index.html | 504 +- tools/export-gate/export_gate.js | 2606 +- tools/export-gate/export_gate_README.md | 56 +- .../examples/example_01_batch_rename.json | 244 + .../examples/example_02_item_fade_tool.json | 295 + .../examples/example_03_render_loudness.json | 496 + .../examples/example_04_midi_humanizer.json | 280 + .../examples/example_05_marker_palette.json | 447 + .../export-gate/historical/export_gate_v12.js | 2607 ++ 16 files changed, 35464 insertions(+), 287 deletions(-) create mode 100644 RELEASE_NOTES_2_2_3.md create mode 100644 ReaUI_Builder_2_2_3.html create mode 100644 docs/Export_Gate_v13_QA_EN.md create mode 100644 tools/export-gate/fixtures/examples/example_01_batch_rename.json create mode 100644 tools/export-gate/fixtures/examples/example_02_item_fade_tool.json create mode 100644 tools/export-gate/fixtures/examples/example_03_render_loudness.json create mode 100644 tools/export-gate/fixtures/examples/example_04_midi_humanizer.json create mode 100644 tools/export-gate/fixtures/examples/example_05_marker_palette.json create mode 100644 tools/export-gate/historical/export_gate_v12.js diff --git a/.github/workflows/export-gate.yml b/.github/workflows/export-gate.yml index a199161..e4fde79 100644 --- a/.github/workflows/export-gate.yml +++ b/.github/workflows/export-gate.yml @@ -4,15 +4,18 @@ on: push: paths: - 'ReaUI_Builder.html' - - 'tools/export-gate/export_gate.js' + - 'tools/export-gate/**' + - '.github/workflows/export-gate.yml' pull_request: paths: - 'ReaUI_Builder.html' - - 'tools/export-gate/export_gate.js' + - 'tools/export-gate/**' + - '.github/workflows/export-gate.yml' jobs: gate: runs-on: ubuntu-latest + timeout-minutes: 20 steps: - uses: actions/checkout@v4 with: @@ -24,35 +27,25 @@ jobs: - name: Install jsdom working-directory: tools/export-gate - run: npm install jsdom + run: npm install --no-save jsdom@26.1.0 - # Push to main (or any push with no prior version to diff against): smoke-test only. - # Fails the build on SCRIPT/GENERATOR THROW or non-deterministic generator output. - - name: Smoke check current build - if: github.event_name == 'push' + - name: Run full export gate on current build run: node tools/export-gate/export_gate.js ReaUI_Builder.html - # PR: diff the PR's version of the file against main's version. A diff is expected - # for a feature/fix PR — this step only fails on SCRIPT/GENERATOR THROW, not on - # CHANGED. Read the log for what actually differs; only an *unintended* widget - # changing is a regression. - - name: Fetch base version of the build + - name: Compare PR against base build if: github.event_name == 'pull_request' - run: git show origin/${{ github.base_ref }}:ReaUI_Builder.html > base_ReaUI_Builder.html - - - name: Diff against base branch - if: github.event_name == 'pull_request' - # CHANGED (exit 1, no THROW text) is expected for most PRs — logged for a human to - # read, not a CI failure. SCRIPT THROW / GENERATOR THROW is a real failure and must - # still fail the job even though both cases share exit code 1, so check the output - # text rather than the exit code alone. + shell: bash run: | + git show origin/${{ github.base_ref }}:ReaUI_Builder.html > base_ReaUI_Builder.html set +e - OUTPUT=$(node tools/export-gate/export_gate.js base_ReaUI_Builder.html ReaUI_Builder.html 2>&1) + node tools/export-gate/export_gate.js base_ReaUI_Builder.html ReaUI_Builder.html > export_gate_diff.log 2>&1 STATUS=$? - echo "$OUTPUT" - if echo "$OUTPUT" | grep -q "THROW"; then - echo "::error::export_gate reported a THROW — this is a real failure, not an expected export diff." - exit 1 + set -e + cat export_gate_diff.log + if [ "$STATUS" -ge 2 ]; then + echo "::error::Export gate encountered a failure (exit $STATUS)" + exit "$STATUS" + fi + if [ "$STATUS" -eq 1 ]; then + echo "::warning::Export/model outputs changed relative to base. Review the diff above." fi - exit 0 diff --git a/CHANGELOG.md b/CHANGELOG.md index ed08f01..364a13e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,27 @@ e.g. `1.0.70`). ## [Unreleased] +## [2.2.3] - 2026-11-13 + +Stability and audit-remediation release. No project format migration or intended new widget families. + +### Fixed +- F01: Ignore stale asynchronous project loads instead of overwriting newer work or history. +- F02: Detect undersized or negative-width adaptive controls inside Table cells, improve geometry diagnostics, and correct nested Table padding in generated Lua. +- F03: Validate Table column sizing consistently on project load and before export, rejecting invalid and surplus configurations. +- F04: Keep Copy/Download disabled after failed generation, even when Preflight is rerun. +- Restore unsaved-change detection, fallback file-read failure handling, and tab presence after back/forward-cache restore. + +### Improved +- Cache repeated adaptive geometry work during Preflight and render large diagnostic lists progressively (200 initial rows, all issues retained). +- Add regression coverage for load/recovery, column validation, nested Tables, export gating, and responsive layouts. +- Update export-gate fixture ordering in v13 to recalculate Table cell geometry after changing Table properties; preserves original v12 for historical reproduction. This is a test-harness fix, not a change to the exported Lua engine. + +### Verification and remaining scope +- The accepted v2.2.3 HTML differs from dev.6 only in its build-version string. +- Manual browser and REAPER acceptance completed; Chromium-adapted export gate v13 reports 36/36 tested scenes and cross-checks PASS. +- The unmodified Node/jsdom gate and Windows-specific native checks had not been executed in the local release QA environment; GitHub Actions is configured to run the full gate with five repository example fixtures. + ## [2.2.0] - 2026-10-15 ### Added diff --git a/README.md b/README.md index e7f9b1f..34233ec 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ The editor runs from a single local HTML file. No installation, server, or build ReaUI Builder -**Version 2.2.0** · [Builder HTML](ReaUI_Builder.html) · [English manual](manuals/ReaUI_Builder_Manual_en.md) · [Русское руководство](manuals/ReaUI_Builder_Manual_ru.md) · [Web version](https://patch-34.github.io/reauibuilder) +**Version 2.2.3** · [Release notes](RELEASE_NOTES_2_2_3.md) · [Builder HTML](ReaUI_Builder.html) · [English manual](manuals/ReaUI_Builder_Manual_en.md) · [Русское руководство](manuals/ReaUI_Builder_Manual_ru.md) · [Web version](https://patch-34.github.io/reauibuilder) ## Contents @@ -171,7 +171,7 @@ See REAPER's [ReaScript documentation](https://www.reaper.fm/sdk/reascript/reasc ## Current limitations -Version 2.2.0 has the following limitations: +Version 2.2.3 has the following limitations: - **Preview is approximate.** Group, Table, ColorPicker, and TextWrapped use placeholders. ColorEdit does not reflect all display flags in Preview. - **Combo and ListBox use placeholder items.** Replace their item strings in the generated code. @@ -190,6 +190,6 @@ Check the exported interface in REAPER before distributing your script. The manu - [English user guide — version 2.2.0](manuals/ReaUI_Builder_Manual_en.md) - [Русское руководство — версия 2.2.0](manuals/ReaUI_Builder_Manual_ru.md) -Read the Markdown manuals directly on GitHub. They include the full widget catalog, inspector reference, flags, keyboard shortcuts, and export examples. The same manual is also available inside Builder through **Help → User Manual ↗**. +The manuals document the interface through v2.2.0; v2.2.3 is a stability release with no new widget families. Read the Markdown manuals directly on GitHub. They include the full widget catalog, inspector reference, flags, keyboard shortcuts, and export examples. The same manual is also available inside Builder through **Help → User Manual ↗**. Use **Help → Report a Bug…** in Builder when preparing a report. It assembles a ready-to-send report from the last 50 logged actions, the build number, and the current window size; add a short description of what happened and, optionally, check **Include my layout** to attach the whole project. Copy the report and send it to the listed address. For export problems, also mention the REAPER and ReaImGui versions. diff --git a/RELEASE_NOTES_2_2_3.md b/RELEASE_NOTES_2_2_3.md new file mode 100644 index 0000000..4d3b958 --- /dev/null +++ b/RELEASE_NOTES_2_2_3.md @@ -0,0 +1,19 @@ +# ReaUI Builder v2.2.3 + +This maintenance release focuses on reliability, predictable export, and safer project handling. + +**Highlights** + +- Protects unsaved work from stale asynchronous project loads. +- Detects invalid adaptive TableCell geometry before a broken Lua script can be exported. +- Validates Table column configurations consistently during load and Preflight. +- Prevents Copy/Download from reopening after a failed generation. +- Improves table diagnostics and fixes nested-table padding in exported Lua. +- Speeds up repeated Preflight and displays large diagnostic lists progressively. +- Strengthens recovery and file-handling behavior across browser lifecycle events. + +The project JSON format is unchanged. Existing projects can be opened in the new version. As always, retain backups of important projects and test generated UI in REAPER. + +**Verification:** 11/11 independent Chromium regression suites passed; 12 Lua syntax checks passed. Manual browser and REAPER acceptance was reported as passed. The historical export-gate tool and Windows native matrix were not rerun in this package's automated validation; details are recorded in the technical report. + +Download the single `ReaUI_Builder_2_2_3.html` file and open it locally. No build step or server is needed. diff --git a/ReaUI_Builder.html b/ReaUI_Builder.html index 8f7dd0e..011b25b 100644 --- a/ReaUI_Builder.html +++ b/ReaUI_Builder.html @@ -1239,6 +1239,9 @@ .preflight-msg{display:block;font-size:11.5px;font-weight:600;line-height:1.35} .preflight-detail{display:block;margin-top:2px;font-size:10.5px;line-height:1.4;color:var(--text-2)} .preflight-target{max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:var(--font-mono);font-size:9.5px;color:var(--text-2)} +.preflight-more{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:8px 10px;color:var(--text-2);font-size:11px} +.preflight-more button{padding:5px 9px;border:1px solid var(--color-border-soft);border-radius:4px;background:transparent;color:var(--text-0);font:inherit;cursor:pointer} +.preflight-more button:hover{background:var(--accent-bg)} #cbtn:disabled,#dlbtn:disabled{opacity:.42;cursor:not-allowed} /* ═══════════════════════════════════════════════════════════════════════════ END EXPORT PREFLIGHT — STYLES @@ -2746,7 +2749,7 @@ // ── Dictionary (built lazily, so an English session never allocates it) ─────────────── function dictionary(){ if(D) return D; - const UI = {"Start in ReaUI Builder":"Начало работы в ReaUI Builder","Choose the interface mode, then create a new project or open an existing one.":"Выберите режим интерфейса, затем создайте новый проект или откройте существующий.","Basic":"Базовый","Advanced":"Расширенный","A simpler workspace with the core components and settings.":"Упрощённая рабочая область с основными компонентами и настройками.","The complete editor with all components, tools and settings.":"Полный редактор со всеми компонентами, инструментами и параметрами.","The display mode can be changed at any time from":"Режим интерфейса можно в любой момент изменить через","View":"Вид",". It does not change the project file.":". Это не изменяет файл проекта.","Restore unsaved project…":"Восстановить несохранённый проект…","Open project…":"Открыть проект…","Create new project":"Создать проект","Interface mode":"Режим интерфейса","File":"Файл","New Project":"Создать проект","Save Project":"Сохранить проект","Save As…":"Сохранить как…","Restore projects…":"Восстановить проекты…","Load Project":"Открытие проекта","Edit":"Правка","Undo":"Отменить","Redo":"Повторить","Copy":"Копировать","Paste":"Вставить","Delete":"Удалить","Duplicate":"Дублировать","Group selection":"Сгруппировать выделенное","Ungroup selection":"Разгруппировать","Select All":"Выделить всё","Deselect All":"Снять выделение","Clear All":"Очистить всё","Dark mode":"Тёмная тема","Theme Studio…":"Редактор тем…","Grid":"Сетка","Snap to grid":"Привязка к сетке","Reference grid in export":"Сетка в экспортируемом интерфейсе","Hide widget names":"Скрыть имена виджетов","Hide draw objects names":"Скрыть имена графических объектов","Widget footprints":"Границы виджетов","Show hints":"Показывать подсказки","Panels":"Панели","Canvas":"Холст","Properties":"Свойства","Elements":"Элементы","Tools":"Инструменты","Zoom to fit":"Вписать в окно","Actual size (100%)":"Фактический размер (100 %)","Help":"Справка","User Manual ↗":"Руководство пользователя ↗","Keyboard Shortcuts":"Сочетания клавиш","Report a Bug…":"Сообщить об ошибке…","About":"О программе","Export":"Экспорт","Buttons & Toggles":"Кнопки и переключатели","Display":"Отображение","Fields":"Поля ввода","Sliders & Drags":"Ползунки и числовые поля","Selection":"Выбор","Color":"Цвет","Layout":"Компоновка","Add":"Добавить","Choose a component":"Выберите компонент","Then click or drag on the canvas to place it.":"Затем щёлкните или протяните указатель на холсте, чтобы разместить его.","Text Input":"Текстовое поле","Number Input":"Числовое поле","Dropdown":"Выпадающий список","Progress":"Выполнение","More components…":"Другие компоненты…","Select":"Выделение","Hand":"Рука","Zoom":"Масштаб","Rectangle":"Прямоугольник","Circle":"Окружность","Polygon":"Многоугольник","Line":"Линия","Triangle":"Треугольник","Arc":"Дуга","Header":"Заголовок","Tree":"Дерево","Default":"По умолчанию","Themes":"Темы","Choose a theme for the ReaImGui UI you will export.":"Выберите тему для экспортируемого интерфейса ReaImGui.","+ New":"+ Создать","Import":"Импорт","Edit…":"Изменить…","Editor":"Редактор","Preview":"Предпросмотр","Preview is approximate — hatched widgets are shown schematically":"Предпросмотр приблизительный — заштрихованные виджеты показаны схематично","Advanced canvas settings are active":"Используются расширенные параметры холста","Some canvas settings are hidden in Basic mode but remain part of this project.":"Некоторые параметры холста скрыты в базовом режиме, но сохранены в проекте.","Edit in Advanced":"Изменить в расширенном режиме","size":"размер","Width":"Ширина","Height":"Высота","background":"фон","grid":"сетка","Show grid":"Показывать сетку","Audit grid":"Контрольная сетка","color":"цвет","Opacity":"Прозрачность","Snap":"Привязка","Step":"Шаг","title bar":"строка заголовка","ImGui default":"По умолчанию ImGui","Theme colours":"Цвета темы","window":"окно","Resizable window":"Изменяемый размер окна","Min width":"Мин. ширина","Min height":"Мин. высота","Max width":"Макс. ширина","Max height":"Макс. высота","menu bar":"строка меню","+ Add menu":"+ Добавить меню","No menu bar. Add a menu to give the window a menu bar; the canvas keeps its size and nothing on it moves.":"Строка меню отсутствует. Добавьте меню, чтобы оно появилось в окне. Размер холста и расположение объектов не изменятся.","No element selected":"Элемент не выбран","Select one object on the canvas to edit its properties here.":"Выберите объект на холсте, чтобы изменить его свойства.","Multiple selection":"Выделено несколько объектов","Edit shared properties together.":"Редактируйте общие свойства объектов одновременно.","Move selection":"Переместить выделенное","move":"Переместить","Common properties":"Общие свойства","Mixed fields stay unchanged until you enter a value. Each edit is one undo step.":"Поля с различающимися значениями не изменяются, пока вы не введёте новое значение. Каждое изменение можно отменить отдельно.","delete selected":"Удалить выделенное","Advanced component":"Расширенный компонент","Some settings are available in Advanced mode.":"Некоторые настройки доступны только в расширенном режиме.","Configuring":"Настройка","Reset":"Сбросить","Click on canvas to place":"Щёлкните на холсте, чтобы разместить","Select a widget to preview":"Выберите виджет для предпросмотра","variant":"вариант","name":"имя","parent":"родительский объект","tabs":"вкладки","+ add tab":"+ добавить вкладку","table grid":"сетка таблицы","columns":"столбцы","row heights":"высота строк","label / text":"подпись / текст","placeholder":"замещающий текст","value":"значение","url":"URL","direction":"направление","value components":"компоненты значения","array size":"размер массива","min":"мин.","max":"макс.","speed":"скорость","step":"шаг","step fast":"ускоренный шаг","format":"формат","format min":"формат минимума","format max":"формат максимума","flags":"флаги","Clamp":"Ограничить","Log":"Логарифм.","NoInput":"Без ввода","Wrap":"Зациклить","hint":"подсказка","prefix bullet":"маркер в начале","highlight":"подсветка","disabled (BeginDisabled)":"отключено (BeginDisabled)","look":"вид","tree lines":"линии дерева","None":"Нет","Full":"Full","To nodes":"До узлов","tab button":"кнопка вкладки","Leading":"В начале","Trailing":"В конце","button label":"подпись кнопки","text tone":"цвет текста","Auto":"Авто","Dark":"Тёмный","Light":"Светлый","border":"граница","draw border":"рисовать границу","h-scroll":"горизонтальная прокрутка","horizontal scrollbar":"горизонтальная полоса прокрутки","text color":"цвет текста","frame bg":"фон элемента","button color":"цвет кнопки","rounding":"скругление","frame padding":"внутренние отступы","selectable align":"выравнивание элемента","font":"шрифт","sans-serif":"без засечек","serif":"с засечками","monospace":"моноширинный","cursive":"курсивный","fantasy":"декоративный","alpha":"альфа-канал","overlay":"наложенный текст","indeterminate":"неопределённый прогресс","animate":"анимация","EEL2 callback":"обработчик EEL2","group":"группа","flag group":"группа флагов","bit (0–30)":"бит (0–30)","values":"значения","scale min":"мин. шкалы","scale max":"макс. шкалы","text align":"выравнивание текста","left":"слева","center":"по центру","right":"справа","text size":"размер текста","vertical align":"выравнивание по вертикали","top":"сверху","middle":"по центру","bottom":"снизу","fill & stroke":"заливка и обводка","fill":"заливка","disable":"отключить","stroke":"обводка","thickness":"толщина","opacity":"прозрачность","hdr color":"цвет заголовка","default":"по умолчанию","custom":"пользовательский","hdr color val":"цвет заголовка","orient":"ориентация","angles (°)":"углы (°)","start":"начало","end":"конец","Link":"Связать","mode":"режим","ring":"кольцо","pie":"сектор","position":"положение","poly points":"вершины многоугольника","primitive order":"порядок отрисовки","back":"на задний план","backward":"назад","forward":"вперёд","front":"на передний план","delete":"удалить","select":"выделение","On":"Вкл.","Off":"Выкл.","0 elements":"0 элементов","No unsaved changes":"Нет несохранённых изменений","copy":"копировать","download .lua":"скачать .lua","Show code":"Показать код","Hide code":"Скрыть код","close":"закрыть","ReaUI Builder checks the project first, then exports the same ReaImGui Lua script as Advanced mode.":"Сначала ReaUI Builder проверит проект, затем экспортирует тот же Lua-скрипт ReaImGui, что и в расширенном режиме.","Checking export…":"Проверка перед экспортом…","Run again":"Проверить снова","Requires ReaImGui — install it via ReaPack.":"Требуется ReaImGui — установите его через ReaPack.","Colours of the exported plugin — not the builder's own look":"Цвета экспортируемого плагина, а не самого редактора","Hide service names of widgets in Editor":"Скрыть служебные имена виджетов в редакторе","Hide service names of draw objects in Editor":"Скрыть служебные имена графических объектов в редакторе","Open the online user manual in your browser":"Открыть руководство пользователя в браузере","Add components":"Добавить компоненты","Hand — drag to pan":"Рука — перетаскивайте для перемещения по холсту","Zoom — click to zoom in, Alt/Option + click to zoom out":"Масштаб — щелчок для увеличения, Alt/Option + щелчок для уменьшения","More widgets in the top-bar categories":"Другие виджеты в категориях верхней панели","Make a new theme, starting from the active one":"Создать тему на основе текущей","Add a theme from a .reaui-theme.json file":"Импортировать тему из файла .reaui-theme.json","Editor - schematic editing view":"Редактор — схематичный вид для редактирования","Preview - approximate ImGui look (view-only)":"Предпросмотр — приблизительный вид ImGui (без редактирования)","Drag to resize canvas":"Перетащите, чтобы изменить размер холста","Drag to try another window width (view only). Double-click: design size":"Перетащите, чтобы изменить ширину окна в предпросмотре. Двойной щелчок — размер макета","Drag to try another window height (view only). Double-click: design size":"Перетащите, чтобы изменить высоту окна в предпросмотре. Двойной щелчок — размер макета","Drag to try another window size (view only). Double-click: design size":"Перетащите, чтобы изменить размер окна в предпросмотре. Двойной щелчок — размер макета","Collapse or expand this panel":"Свернуть или развернуть панель","Pick a colour from the screen":"Выбрать цвет с экрана","Menu bar entries":"Элементы строки меню","Properties actions":"Действия со свойствами","placeholder text…":"Текст подсказки…","value text…":"Текст значения…","hover text…":"Текст при наведении…","Prefix bullet":"Маркер в начале","Highlight":"Подсветка","Disabled":"Отключено","Draw panel border":"Рисовать границу панели","Enable horizontal scrollbar":"Включить горизонтальную прокрутку","Frame padding X (0 to 32)":"Внутренний отступ по X (0–32)","Frame padding Y (0 to 32)":"Внутренний отступ по Y (0–32)","Selectable text align X (0 to 1)":"Выравнивание текста по X (0–1)","Selectable text align Y (0 to 1)":"Выравнивание текста по Y (0–1)","Font size in pixels":"Размер шрифта в пикселях","Bold":"Полужирный","Italic":"Курсив","empty = no text":"пусто — без текста","Animate indeterminate progress bar":"Анимировать индикатор выполнения","Plot values, comma-separated":"Значения графика через запятую","Link start and end angles":"Связать начальный и конечный углы","Expand Elements panel":"Развернуть панель «Элементы»","Zoom level":"Масштаб","Zoom out":"Уменьшить масштаб","Zoom in":"Увеличить масштаб","Button":"Кнопка","SmallButton":"Компактная кнопка","InvisibleButton":"Невидимая кнопка","ArrowButton":"Кнопка со стрелкой","Checkbox":"Флажок","CheckboxFlags":"Битовый флажок","RadioButton":"Переключатель","RadioButtonEx":"Переключатель","Text":"Текст","BulletText":"Маркированный текст","TextWrapped":"Текст с переносом","TextColored":"Цветной текст","TextDisabled":"Неактивный текст","SeparatorText":"Разделитель с текстом","Separator":"Разделитель","Hint":"Подсказка","HelpMarker":"Значок подсказки","LabelText":"Подпись со значением","TextLinkOpenURL":"Ссылка (URL)","TextLink":"Текстовая ссылка","Slider":"Ползунок","VSlider":"Вертикальный ползунок","SliderAngle":"Угловой ползунок","Drag":"Поле перетаскивания","DragRange":"Диапазон","Input":"Числовое поле","InputText":"Текстовое поле","InputTextMultiline":"Многострочное поле","Multiline":"Многострочное поле","SliderN":"Многокомпонентный ползунок","DragN":"Многокомпонентное поле","InputN":"Многокомпонентный ввод","ProgressBar":"Индикатор выполнения","Plot":"График","InputTextWithHint":"Поле с подсказкой","Combo":"Выпадающий список","ListBox":"Список","Selectable":"Выбираемый элемент","ColorEdit":"Редактор цвета","ColorPicker":"Выбор цвета","ColorButton":"Кнопка цвета","Panel":"Панель","Group":"Группа","StyleRegion":"Область стиля","Style":"Стиль","CollapsingHeader":"Сворачиваемый заголовок","TreeNode":"Узел дерева","TabBar":"Панель вкладок","Tabs":"Вкладки","Table":"Таблица","Main":"Основная","Appearance":"Оформление","Details":"Подробности","Options":"Параметры","Settings":"Настройки","Add widget":"Добавить виджет","Add menu":"Добавить меню","Delete selected":"Удалить выделенное","Duplicate selected":"Дублировать выделенное","Select group":"Выделить группу","Clear selection":"Снять выделение","Enter name":"Введите имя","No selection":"Ничего не выделено","Custom":"Пользовательский","Light mode":"Светлая тема","Theme Studio":"Редактор тем","Close Theme Studio":"Закрыть редактор тем","Plugin preview":"Предпросмотр","Hold to compare":"Сравнить","Editing":"Редактирование","Theme name":"Название темы","Click to rename":"Щёлкните для переименования","Theme actions":"Действия с темой","Collection":"Коллекция","My themes":"Мои темы","My Theme":"Моя тема","New theme":"Новая тема","Imported theme":"Импортированная тема","Not saved yet":"Ещё не сохранена","Built-in":"Встроенная","From Collection":"Из коллекции","From this project":"Из этого проекта","This project only":"Только в проекте","My theme":"Моя тема","Unsaved edits":"Несохранённые изменения","Saved":"Сохранено","Apply":"Применить","Apply to use it, or Save as… to keep it":"Нажмите «Применить», чтобы использовать, или «Сохранить как…», чтобы сохранить","Apply, or Save as… to keep edits":"Примените или сохраните изменения через «Сохранить как…»","Edits become a new theme":"Изменения будут сохранены как новая тема","Differs from the copy in My themes":"Отличается от копии в «Моих темах»","Save to add it to My themes":"Сохраните, чтобы добавить в «Мои темы»","Discard changes":"Не сохранять","Save theme":"Сохранить тему","Theme already saved":"Тема уже сохранена","Save another copy":"Сохранить ещё одну копию","Save":"Сохранить","Save as…":"Сохранить как…","Save edits to this theme in My themes":"Сохранить изменения темы в «Моих темах»","Save as a new theme in My themes":"Сохранить новую тему в «Моих темах»","Reset edits":"Сбросить изменения","Restore this theme to its last saved or starting colours":"Восстановить последние сохранённые или исходные цвета темы","Export…":"Экспорт…","Export Theme":"Экспортировать тему","Edit a copy":"Изменить копию","Change the colours of this theme":"Изменить цвета темы","Change the colours; saving makes a new theme":"Изменить цвета; при сохранении будет создана новая тема","In theme menu":"В меню тем","Show in theme menu":"Показывать в меню тем","Show or hide this theme in the quick theme menu; the active theme stays visible":"Показать или скрыть тему в быстром меню. Активная тема остаётся видимой.","Remove from project":"Удалить из проекта","Rename theme":"Переименовать тему","Manual":"Вручную","Click a colour to change it. The other colours follow automatically; colours set by hand in Full keep their values.":"Нажмите на цвет для изменения. Остальные цвета обновятся автоматически; вручную заданные цвета в полном наборе сохранят свои значения.","Default uses REAPER’s colours. Use Save as… to keep this palette as a custom theme.":"Тема по умолчанию использует цвета REAPER. Чтобы сохранить палитру как пользовательскую тему, выберите «Сохранить как…».","Background":"Фон","Controls":"Элементы управления","Accent":"Акцент","Header opacity":"Прозрачность заголовка","Rebuild all colours":"Пересоздать все цвета","Replace all manual RGB colours with the generated palette?":"Заменить все вручную заданные цвета RGB автоматически созданной палитрой?","Rebuild palette":"Пересоздать палитру","Rebuild":"Пересоздать","Label text":"Текст подписи","Window background":"Фон окна","Field":"Поле","Field · hovered":"Поле · наведение","Field · active":"Поле · активное","Button · hovered":"Кнопка · наведение","Button · active":"Кнопка · активная","Header · hovered":"Заголовок · наведение","Header · active":"Заголовок · активный","Check mark":"Галочка","Slider grab":"Ползунок","Slider grab · active":"Ползунок · активный","Automatically generated colours":"Автоматически созданные цвета","These colours are calculated from your palette and cannot be edited separately.":"Эти цвета вычисляются из палитры; редактировать их по отдельности нельзя.","Title colours are used when the project’s Title bar option is Theme colours. Menu bar colour is used with a menu bar.":"Цвета заголовка применяются при параметре «Строка заголовка → Цвета темы». Цвет строки меню используется при наличии меню.","ImGui colour":"Цвет ImGui","Value":"Значение","Rule":"Правило","Palette collection":"Коллекция палитр","Click a palette to load it into the editor. Your project changes only when you press Apply.":"Выберите палитру, чтобы загрузить её в редактор. Проект изменится только после нажатия «Применить».","Palettes from":"Палитры из","Import…":"Импорт…","No themes here yet.":"Здесь пока нет тем.","Active":"Активная","Select theme":"Выбрать тему","Close":"Закрыть","OK":"ОК","Cancel":"Отмена","Yes":"Да","No":"Нет","Continue":"Продолжить","Confirm":"Подтвердить","Delete Theme":"Удаление темы","Delete theme":"Удалить тему","Delete failed":"Ошибка удаления","Import failed":"Ошибка импорта","Import Theme":"Импорт темы","Export Lua":"Экспорт Lua","Export Lua Script":"Экспорт Lua-скрипта","Export ReaImGui Lua":"Экспорт Lua для ReaImGui","Preflight":"Предэкспортная проверка","Preflight check":"Проверка перед экспортом","Check":"Проверить","Run checks":"Запустить проверку","Checking…":"Проверка…","Passed":"Успешно","Warnings":"Предупреждения","Errors":"Ошибки","Error":"Ошибка","Warning":"Предупреждение","Info":"Информация","Valid":"Допустимо","Invalid":"Недопустимо","Failed":"Не удалось","Ready":"Готово","Done":"Готово","Copy to clipboard":"Копировать в буфер обмена","Copied":"Скопировано","Download":"Скачать","Download Lua":"Скачать Lua","All checks passed":"Все проверки пройдены","Print":"Печать","Show details":"Подробнее","Hide details":"Скрыть подробности","Show more":"Показать ещё","Show less":"Скрыть","ReaUI project":"Проект ReaUI","Untitled project":"Безымянный проект","No unsaved projects to restore.":"Нет несохранённых проектов для восстановления.","Restore projects":"Восстановление проектов","Restore":"Восстановить","Save project as":"Сохранить проект как","Load failed":"Ошибка открытия","Save failed":"Ошибка сохранения","Recovery failed":"Ошибка восстановления","Unsaved changes":"Несохранённые изменения","Saving…":"Сохранение…","Autosave failed":"Ошибка автосохранения","Loaded":"Загружено","Failed to load project":"Не удалось загрузить проект","Recovery draft saved locally in this browser at":"Резервная копия проекта сохранена в этом браузере:","Saving a local recovery draft":"Сохранение локальной резервной копии","Changes are waiting to be saved locally":"Изменения ожидают локального сохранения","New project has no unsaved changes":"В новом проекте нет несохранённых изменений","Loaded project has no unsaved changes":"В открытом проекте нет несохранённых изменений","The recovery draft could not be applied. It has not been deleted.":"Не удалось восстановить резервную копию. Она не удалена.","Stored projects could not be read.":"Не удалось прочитать сохранённые проекты.","Save the current project before restoring another one?":"Сохранить текущий проект перед восстановлением другого?","Save the current project before loading another one?":"Сохранить текущий проект перед открытием другого?","The project root must be an object.":"Корневой элемент проекта должен быть объектом.","The project shapes field is required and must be an array.":"Поле shapes обязательно и должно быть массивом.","This project version is not supported.":"Эта версия проекта не поддерживается.","This file is not valid JSON.":"Файл содержит некорректный JSON.","This file is not a ReaUI theme: it is not a JSON object.":"Это не тема ReaUI: содержимое не является объектом JSON.","This file is not a ReaUI theme: \"format\" is not \"reaui-theme\".":"Это не тема ReaUI: значение \"format\" отличается от \"reaui-theme\".","This theme file has no valid format version.":"В файле темы отсутствует корректная версия формата.","The file contains no theme.":"Файл не содержит темы.","The theme has no colours.":"В теме отсутствуют цвета.","The theme needs a valid \"childBg\" and a valid \"text\" colour.":"В теме должны быть корректные цвета \"childBg\" и \"text\".","The theme could not be added.":"Не удалось добавить тему.","The file could not be read.":"Не удалось прочитать файл.","Nothing was imported.":"Импорт не выполнен.","It is in the theme list now - click it to apply. The current theme is unchanged.":"Тема добавлена в список. Выберите её для применения. Текущая тема не изменилась.","Could not change the theme menu. Check browser storage and try again.":"Не удалось изменить меню тем. Проверьте хранилище браузера и повторите попытку.","Could not save the theme. Check browser storage and try again.":"Не удалось сохранить тему. Проверьте хранилище браузера и повторите попытку.","Could not apply the theme.":"Не удалось применить тему.","The theme could not be deleted. Check browser storage and try again.":"Не удалось удалить тему. Проверьте хранилище браузера и повторите попытку.","no callback event selected — this code will never run":"Не выбрано событие обработчика — этот код не будет выполняться","compiled once at startup via CreateFunctionFromEEL":"Компилируется один раз при запуске через CreateFunctionFromEEL","radio group":"группа переключателей","radio value":"значение переключателя","bullet (tree: replaces arrow)":"маркер (в дереве вместо стрелки)","start angle":"начальный угол","end angle":"конечный угол","link angles":"связать углы","arc mode":"режим дуги","header color":"цвет заголовка","header value":"значение заголовка","blocked: shape needs at least one of fill/stroke":"Невозможно: фигуре нужна хотя бы заливка или обводка","value must be finite":"Значение должно быть конечным числом","value must be an integer":"Значение должно быть целым числом","value is below the native API range":"Значение меньше допустимого диапазона API","value is above the native API range":"Значение больше допустимого диапазона API","callback events":"события обработчика","data type":"тип данных","ReadOnly":"Только чтение","Password":"Пароль","Pass":"Пароль","CharsDecimal":"Десятичные символы","Dec":"Дес.","CharsHexadecimal":"Шестнадцатеричные символы","Hex":"HEX","EnterReturnsTrue":"Подтверждение Enter","AllowTabInput":"Ввод Tab","CtrlEnterForNewLine":"Новая строка по Ctrl+Enter","CallbackEdit":"При изменении","CallbackAlways":"Всегда","CallbackCharFilter":"Фильтр символов","CallbackCompletion":"Автодополнение","CallbackHistory":"История","OnEdit":"Изменение","Always":"Всегда","CharFilter":"Фильтр","OnTab":"По Tab","OnUp/Down":"По ↑/↓","NoAlpha":"Без альфа","NoPicker":"Без палитры","NoInputs":"Без полей","NoTooltip":"Без подсказки","NoTip":"Без подсказки","NoLabel":"Без подписи","NoSidePreview":"Без бокового образца","NoSidePrev":"Без бокового образца","NoSmallPreview":"Без маленького образца","NoSmallPrev":"Без мини-образца","NoOptions":"Без параметров","NoDragDrop":"Без перетаскивания","NoBorder":"Без границы","DisplayRGB":"Показать RGB","DisplayHSV":"Показать HSV","DisplayHex":"Показать HEX","Uint8":"0–255","Float":"Дробные","InputRGB":"Ввод RGB","InputHSV":"Ввод HSV","PickerHueBar":"Полоса оттенка","HueBar":"Полоса оттенка","PickerHueWheel":"Цветовой круг","HueWheel":"Цветовой круг","AlphaBar":"Шкала альфа","AlphaPreviewHalf":"Полупрозрачный образец","HalfPrev":"Полуобразец","AlphaNoBg":"Без фона","NoBg":"Без фона","AlphaOpaque":"Непрозрачный образец","Opaque":"Непрозрачный","No elements yet":"Элементов пока нет","Add a widget or draw object, then click the canvas.":"Добавьте виджет или графический объект, затем щёлкните на холсте.","↑ height fixed by ImGui":"↑ высота задаётся ImGui","↑ size fixed by ImGui":"↑ размер задаётся ImGui","⊞ Snap:":"⊞ Привязка:","click=select Shift=range Cmd/Ctrl=toggle":"щелчок — выделить; Shift — диапазон; Cmd/Ctrl — переключить","click=select Shift=range Cmd/Ctrl=toggle":"щелчок — выделить; Shift — диапазон; Cmd/Ctrl — переключить","drag to place (or click for default size)":"протяните для размещения (или щёлкните для стандартного размера)","Structure":"Структура","Constraints":"Привязки","Constraints apply when the window is resizable":"Привязки работают при изменяемом размере окна","Make the window resizable":"Разрешить изменение размера окна","Pinned to":"Привязка к","Left":"Слева","Right":"Справа","Center":"Центр","Top":"Сверху","Bottom":"Снизу","Left+Right":"Слева + справа","Top+Bottom":"Сверху + снизу","Left · Top":"Слева · сверху","Horizontal":"По горизонтали","Vertical":"По вертикали","Name":"Имя","Enable loop":"Включить цикл","custom look (size, border, colours, click area)":"Пользовательский вид (размер, границы, цвета, область нажатия)","Constraint presets":"Шаблоны привязок","Pin left top":"Привязать слева сверху","Pin center top":"Привязать по центру сверху","Pin right top":"Привязать справа сверху","Pin left center":"Привязать слева по центру","Pin center":"Привязать к центру","Pin right center":"Привязать справа по центру","Pin left bottom":"Привязать слева снизу","Pin center bottom":"Привязать по центру снизу","Pin right bottom":"Привязать справа снизу","Horizontal constraint":"Горизонтальная привязка","Vertical constraint":"Вертикальная привязка","Select and edit this element":"Выделить и изменить этот элемент","Built-in · in use":"Встроенная · используется","Built-in · active":"Встроенная · активна","Vintage":"Винтажные","Cold":"Холодные","Warm":"Тёплые","Earth":"Землистые","Vintage palettes":"Винтажные палитры","Dark palettes":"Тёмные палитры","Cold palettes":"Холодные палитры","Warm palettes":"Тёплые палитры","Earth palettes":"Землистые палитры","Default — built-in":"Default — встроенная","Edit a copy of Light":"Изменить копию Light","Use this theme in the project and close. Edits stay in this project until you save them.":"Применить тему к проекту и закрыть редактор. Изменения останутся в проекте, пока вы не сохраните тему отдельно.","none":"нет","sample data":"пример данных","// EEL2 — runs on the selected Callback* event":"// EEL2 — выполняется при выбранном событии Callback*","Normal":"Обычный","Hovered":"Наведение","Active header":"Активный заголовок","Hovered header":"Заголовок при наведении","Parameter":"Параметр","Gain":"Усиление","Mix":"Смешивание","More":"Ещё","Sample plugin":"Пример плагина","Enable processing":"Включить обработку","Instruments":"Инструменты","Popup / tooltip selected text":"Всплывающая подсказка и выделенный текст","Documentation ↗":"Документация ↗","Documentation":"Документация","Current theme":"Текущая тема","New Theme":"Новая тема","View → Interface mode":"Вид → Режим интерфейса","File Edit View":"Файл Правка Вид","▾ Header":"▾ Заголовок","▾ Hovered header":"▾ Заголовок при наведении","▾ Active header":"▾ Активный заголовок","Popup / tooltip":"Всплывающее окно / подсказка","selected text":"выделенный текст","Disable":"Отключить","Basic layout":"Базовая компоновка","Title bar":"Строка заголовка","Edited":"Изменено","Edit theme":"Изменить тему","Edit a copy of":"Изменить копию","Theme":"Тема","Root":"Корень","Insert":"Вставить","Delete all":"Удалить всё","Clear All?":"Очистить всё?","ReaUI Builder — About":"ReaUI Builder — О программе","Keyboard shortcuts":"Сочетания клавиш","About ReaUI Builder":"О ReaUI Builder","Report a bug":"Сообщить об ошибке","Ready to export":"Готово к экспорту","No export blockers or warnings detected.":"Ошибок и предупреждений, препятствующих экспорту, нет.","Arrow keys":"Клавиши со стрелками","Nudge selection (grid step, or 1 px with Snap off)":"Переместить выделенное на шаг сетки (или на 1 пиксель без привязки)","Shift + Arrow keys":"Shift + стрелки","Nudge selection by 10 steps":"Переместить выделенное на 10 шагов","Copy selection":"Копировать выделенное","Duplicate selection":"Дублировать выделенное","Delete selection":"Удалить выделенное","Escape":"Esc","Deselect, cancel tool/polygon, or close an open dialog/menu":"Снять выделение, отменить инструмент/многоугольник или закрыть окно/меню","Enter (Polygon)":"Enter (многоугольник)","Finish polygon":"Завершить многоугольник","Shift + click object":"Shift + щелчок по объекту","Extend selection from the anchor object":"Расширить выделение от опорного объекта","⌘/Ctrl + click object":"⌘/Ctrl + щелчок по объекту","Toggle object in selection":"Добавить объект к выделению или снять выделение","Shift + marquee":"Shift + рамка выделения","Add objects intersecting the marquee to selection":"Добавить объекты, пересекаемые рамкой, к выделению","Toggle objects intersecting the marquee":"Переключить выделение объектов, пересекаемых рамкой","Alt + drag object":"Alt + перетаскивание объекта","Drag a copy":"Перетащить копию объекта","U + drag container":"U + перетаскивание контейнера","Unlock for this move: leave its contents behind and ignore widgets underneath":"Временно разблокировать перемещение: оставить содержимое на месте и игнорировать виджеты под контейнером","Space + drag canvas":"Пробел + перетаскивание холста","Pan canvas":"Переместить холст","Zoom to cursor":"Масштабировать относительно указателя","Right-click canvas":"Правая кнопка мыши на холсте","Open the widget menu at the pointer":"Открыть меню виджетов у указателя","Shift + drawing tool button":"Shift + кнопка инструмента рисования","Keep Rectangle, Circle, Line, Triangle, or Arc active":"Оставить активными «Прямоугольник», «Окружность», «Линия», «Треугольник» или «Дуга»","Polygon: double-click / first point":"Многоугольник: двойной щелчок / первая вершина","Visual layout tool for ReaImGui (REAPER DAW).":"Визуальный редактор интерфейсов ReaImGui (REAPER).","Generates Lua code using the ReaImGui API.":"Генерирует Lua-код на основе API ReaImGui.","Single-file Vanilla HTML/CSS/JS — no build tools.":"Один HTML-файл с CSS и JavaScript, без сборки и зависимостей.","Report a Bug":"Сообщить об ошибке","Describe what happened, what you expected, and how to reproduce it.":"Опишите, что произошло, как должно было работать и как воспроизвести ошибку.","Copy Report":"Копировать отчёт","Download Report":"Скачать отчёт","Send the report to:":"Отправьте отчёт по адресу:","Copied ✓":"Скопировано ✓","Include my layout (helps reproduce it; sends the whole project)":"Включить мой макет (для воспроизведения ошибки; прикладывается весь проект)","The text below is everything that gets sent - the last 50 actions plus your build and window size. Nothing else is collected.":"Ниже приведён полный состав отчёта: последние 50 действий, версия сборки и размер окна. Другие данные не собираются.","Popups / text":"Всплывающие окна и текст","Borders / scrollbars":"Границы и прокрутка","Tables":"Таблицы","Window / menu":"Окно и меню","Plots / tree":"Графики и дерево","7 colours set by hand":"7 цветов заданы вручную","shift(Background, 3% away from background)":"shift(Фон, 3% от исходного фона)","mix(Background, Text, 55%)":"mix(Фон, Текст, 55%)","mix(Background, Check mark, 45%)":"mix(Фон, Галочка, 45%)","= Check mark":"= Галочка","= Text":"= Текст","mix(Background, Text, 30%)":"mix(Фон, Текст, 30%)","mix(Background, Field, 35%)":"mix(Фон, Поле, 35%)","= Field":"= Поле","= Hovered field":"= Поле при наведении","= Active field":"= Активное поле","= Header (opaque)":"= Заголовок (непрозрачный)","mix(Background, Text, 35%)":"mix(Фон, Текст, 35%)","mix(Background, Text, 18%)":"mix(Фон, Текст, 18%)","= Background":"= Фон","shift(Background, 5% away from background)":"shift(Фон, 5% от исходного фона)","mix(Background, Field, 60%)":"mix(Фон, Поле, 60%)","mix(Background, Header, 80%)":"mix(Фон, Заголовок, 80%)","mix(Background, Field, 40%)":"mix(Фон, Поле, 40%)","mix(Background, Field, 50%)":"mix(Фон, Поле, 50%)","shift(Check mark, 12% away from background)":"shift(Галочка, 12% от исходного фона)","mix(Background, Text, 65%)":"mix(Фон, Текст, 65%)","= Border":"= Граница","= Active header (fallback: Active button, Header)":"= Активный заголовок (иначе: Активная кнопка, Заголовок)","= Hovered header (fallback: Hovered button)":"= Заголовок при наведении (иначе: Кнопка при наведении)","= Check mark (fallback: Slider grab)":"= Галочка (иначе: Ползунок)","Visual layout tool for ReaImGui (REAPER DAW).\nGenerates Lua code using the ReaImGui API.\nSingle-file Vanilla HTML/CSS/JS — no build tools.":"Визуальный редактор интерфейсов ReaImGui для REAPER.\nГенерирует Lua-код через API ReaImGui.\nРаботает как единый HTML-файл с CSS и JavaScript, без сборки.","Popup / tooltip ":"Всплывающее окно / подсказка ","Project":"Проект","Element":"Элемент","Project background colour is invalid":"Некорректный цвет фона проекта","Use a hexadecimal colour in #RRGGBB format.":"Укажите цвет в шестнадцатеричном формате #RRGGBB.","Element has no ID":"У элемента отсутствует ID","Export maps and parent relationships require a stable element ID.":"Для экспорта и связей родительских объектов необходим постоянный ID элемента.","Duplicate element ID:":"Повторяющийся ID элемента:","IDs must be unique; the exporter uses them as map keys.":"ID должны быть уникальны: генератор использует их как ключи.","Unknown element type:":"Неизвестный тип элемента:","The Lua exporter supports widgets and the documented drawing primitives only.":"Экспорт Lua поддерживает только виджеты и описанные графические примитивы.","Parent ID is ambiguous":"Неоднозначный ID родительского объекта","Parent element is missing":"Родительский объект отсутствует","Cyclic parent relationship":"Циклическая вложенность","The parent chain loops back to an element already visited.":"Цепочка родительских объектов содержит цикл.","Invalid position or size":"Некорректные координаты или размер","X, Y, width and height must be finite numbers; width and height must be greater than zero.":"X, Y, ширина и высота должны быть конечными числами; ширина и высота — больше нуля.","Unknown widget type:":"Неизвестный тип виджета:","The Lua exporter has no contract for this widget.":"Генератор Lua не поддерживает этот тип виджета.","Choose Left, Right, Up or Down.":"Выберите Left, Right, Up или Down.","Arrow direction is not supported":"Неподдерживаемое направление стрелки","Polygon has fewer than three points":"У многоугольника менее трёх вершин","A polygon needs at least three points to export.":"Для экспорта многоугольнику необходимо минимум три вершины.","Polygon contains a nonnumeric point":"У многоугольника есть некорректная вершина","Every polygon point needs finite numeric X and Y coordinates.":"У каждой вершины должны быть конечные числовые координаты X и Y.","Polygon outline crosses itself":"Контур многоугольника пересекает сам себя","ImGui fills only a polygon whose outline does not cross, touch or turn back on itself. Move a point, split the shape into separate polygons, or disable its fill to export the outline only.":"ImGui может заливать только многоугольник без самопересечений и касаний контура. Переместите вершину, разделите фигуру или отключите заливку.","Polygon fill cannot be exported":"Не удалось экспортировать заливку многоугольника","Builder could not split this polygon into triangles for ImGui. Remove repeated points, or disable its fill to export the outline only.":"Не удалось разбить многоугольник на треугольники для ImGui. Удалите повторяющиеся вершины либо отключите заливку.","Line points are invalid":"Некорректные точки линии","A line needs exactly two points with finite numeric X and Y coordinates.":"Линии нужны ровно две точки с конечными числовыми координатами X и Y.","Invalid numeric property:":"Некорректный числовой параметр:","The value must be a finite number.":"Значение должно быть конечным числом.","Invalid StyleRegion property:":"Некорректный параметр StyleRegion:","Use a finite value inside the supported range.":"Укажите конечное число в допустимом диапазоне.","Invalid colour property:":"Некорректный параметр цвета:","Invalid colour flags":"Некорректные флаги цвета","Could not resolve export bounds":"Не удалось определить границы экспорта","Check the element parent chain and geometry.":"Проверьте геометрию и вложенность элемента.","Widget will not be exported":"Виджет не будет экспортирован","Draw object will not be exported":"Графический объект не будет экспортирован","It does not intersect the canvas, so it is omitted from the Lua.":"Объект не пересекает холст и исключён из экспорта Lua.","Draw object crosses the canvas edge":"Графический объект пересекает границу холста","Only the intersecting part will be visible in the exported plugin.":"В экспортированном интерфейсе будет видна только часть объекта внутри холста.","Link URL is empty":"Адрес ссылки не указан","The exporter will use https://example.com as a fallback.":"Генератор использует резервный адрес https://example.com.","Callback flags require EEL callback code":"Для флагов Callback необходим код обработчика EEL","Add a non-empty EEL callback or disable all Callback* flags.":"Добавьте код обработчика EEL или отключите все флаги Callback*.","Minimum is not numeric":"Минимум не является числом","Maximum is not numeric":"Максимум не является числом","Enter a finite number or clear the field.":"Введите конечное число или очистите поле.","Minimum is greater than maximum":"Минимум больше максимума","Swap the values or correct the numeric range.":"Поменяйте значения местами или исправьте диапазон.","Minimum equals maximum":"Минимум равен максимуму","The control has no usable value range.":"У элемента нет допустимого диапазона значений.","Step should be zero or positive":"Шаг должен быть неотрицательным","Negative or non-numeric step values can behave unexpectedly.":"Отрицательный или нечисловой шаг может вызвать некорректную работу.","Speed should be greater than zero":"Скорость должна быть больше нуля","Drag controls need a positive finite speed.":"Для элементов Drag требуется положительная конечная скорость.","Component count must be 1–4":"Число компонентов должно быть от 1 до 4","The selected widget family only supports one to four components.":"Этот тип виджета поддерживает от одного до четырёх компонентов.","Array size must be 2–64":"Размер массива должен быть от 2 до 64","N-wide controls allocate a ReaScript array of this size.":"Многокомпонентные элементы создают массив ReaScript указанного размера.","Color alpha must be 0–255":"Альфа-канал должен быть в диапазоне 0–255","The Lua color packer expects an 8-bit alpha value.":"Упаковка цвета в Lua требует 8-битного значения альфа-канала.","Will not be exported with its container":"Не экспортируется вместе с контейнером","Widget is unreachable by the exporter":"Виджет недоступен генератору","Its parent chain is not traversed by the generated Lua.":"Сгенерированный Lua-код не обходит цепочку родительских объектов виджета.","Widget overlaps":"Виджет перекрывает","Their occupied areas intersect on the canvas. Move or resize one of the widgets before export.":"Области виджетов на холсте пересекаются. Перед экспортом переместите один из виджетов или измените его размер.","Overlaps":"Перекрывает","Leaves the window":"Выходит за границы окна","Too small at the minimum window size":"Слишком мал при минимальном размере окна","Export name collides after sanitizing":"Совпадение экспортируемого имени после нормализации","Radio value is not numeric":"Значение переключателя не является числом","RadioButtonEx requires a finite numeric value.":"Для RadioButtonEx требуется конечное числовое значение.","Duplicate radio value in group":"Повторяющееся значение в группе переключателей","Flag bit must be an integer 0–":"Номер бита должен быть целым числом от 0 до","Duplicate bit in flag group":"Повторяющийся бит в группе флагов","Plot values are invalid":"Некорректные значения графика","Enter a number or clear the field for automatic scaling.":"Введите число или оставьте поле пустым для автоматического масштаба.","Scale min is not below scale max":"Минимум шкалы не меньше максимума","The plot has no usable value range.":"У графика нет допустимого диапазона значений.","PlotLines needs at least two values":"PlotLines требует минимум два значения","With one value ImGui draws an empty frame.":"При одном значении ImGui рисует пустую рамку.","TabBar has no tabs":"В TabBar отсутствуют вкладки","The exported tab bar will have no visible tab items.":"В экспортированной панели не будет видимых вкладок.","Active tab does not exist":"Активная вкладка отсутствует","Choose one of the TabItems contained by this TabBar.":"Выберите одну из вкладок TabItem этой панели TabBar.","TabItem is not inside a TabBar":"TabItem находится вне TabBar","Standalone TabItems are not emitted correctly.":"Отдельные TabItem вне TabBar экспортируются некорректно.","Table rows and columns must be positive integers":"Число строк и столбцов таблицы должно быть положительным целым числом","Correct rowCount and columnCount before export.":"Перед экспортом исправьте rowCount и columnCount.","Table cell is outside the table grid":"Ячейка выходит за границы таблицы","Row and column indices must fit the parent table dimensions.":"Индексы строки и столбца должны соответствовать размеру родительской таблицы.","Duplicate table cell":"Повторяющаяся ячейка таблицы","Only one TableCell can occupy each row and column.":"Каждую позицию строки и столбца может занимать только одна TableCell.","Table has missing structural cells":"В таблице отсутствуют структурные ячейки","TableCell is not inside a Table":"TableCell находится вне Table","Standalone structural cells are not emitted correctly.":"Отдельные структурные ячейки экспортируются некорректно.","Menus past the right edge are cut off in REAPER":"Меню, выходящее за правую границу, будет обрезано в REAPER","Frame padding Y is":"Внутренний отступ рамки по Y равен","Copy generated Lua":"Копировать сгенерированный Lua","Download generated Lua":"Скачать сгенерированный Lua","Resolve the errors above to enable copy":"Исправьте ошибки выше, чтобы разблокировать копирование","Resolve the errors above to enable download":"Исправьте ошибки выше, чтобы разблокировать скачивание","Ready with":"Готово, но есть","Select this element on canvas":"Выделить этот элемент на холсте"}; + const UI = {"Start in ReaUI Builder":"Начало работы в ReaUI Builder","Choose the interface mode, then create a new project or open an existing one.":"Выберите режим интерфейса, затем создайте новый проект или откройте существующий.","Basic":"Базовый","Advanced":"Расширенный","A simpler workspace with the core components and settings.":"Упрощённая рабочая область с основными компонентами и настройками.","The complete editor with all components, tools and settings.":"Полный редактор со всеми компонентами, инструментами и параметрами.","The display mode can be changed at any time from":"Режим интерфейса можно в любой момент изменить через","View":"Вид",". It does not change the project file.":". Это не изменяет файл проекта.","Restore unsaved project…":"Восстановить несохранённый проект…","Open project…":"Открыть проект…","Create new project":"Создать проект","Interface mode":"Режим интерфейса","File":"Файл","New Project":"Создать проект","Save Project":"Сохранить проект","Save As…":"Сохранить как…","Restore projects…":"Восстановить проекты…","Load Project":"Открытие проекта","Edit":"Правка","Undo":"Отменить","Redo":"Повторить","Copy":"Копировать","Paste":"Вставить","Delete":"Удалить","Duplicate":"Дублировать","Group selection":"Сгруппировать выделенное","Ungroup selection":"Разгруппировать","Select All":"Выделить всё","Deselect All":"Снять выделение","Clear All":"Очистить всё","Dark mode":"Тёмная тема","Theme Studio…":"Редактор тем…","Grid":"Сетка","Snap to grid":"Привязка к сетке","Reference grid in export":"Сетка в экспортируемом интерфейсе","Hide widget names":"Скрыть имена виджетов","Hide draw objects names":"Скрыть имена графических объектов","Widget footprints":"Границы виджетов","Show hints":"Показывать подсказки","Panels":"Панели","Canvas":"Холст","Properties":"Свойства","Elements":"Элементы","Tools":"Инструменты","Zoom to fit":"Вписать в окно","Actual size (100%)":"Фактический размер (100 %)","Help":"Справка","User Manual ↗":"Руководство пользователя ↗","Keyboard Shortcuts":"Сочетания клавиш","Report a Bug…":"Сообщить об ошибке…","About":"О программе","Export":"Экспорт","Buttons & Toggles":"Кнопки и переключатели","Display":"Отображение","Fields":"Поля ввода","Sliders & Drags":"Ползунки и числовые поля","Selection":"Выбор","Color":"Цвет","Layout":"Компоновка","Add":"Добавить","Choose a component":"Выберите компонент","Then click or drag on the canvas to place it.":"Затем щёлкните или протяните указатель на холсте, чтобы разместить его.","Text Input":"Текстовое поле","Number Input":"Числовое поле","Dropdown":"Выпадающий список","Progress":"Выполнение","More components…":"Другие компоненты…","Select":"Выделение","Hand":"Рука","Zoom":"Масштаб","Rectangle":"Прямоугольник","Circle":"Окружность","Polygon":"Многоугольник","Line":"Линия","Triangle":"Треугольник","Arc":"Дуга","Header":"Заголовок","Tree":"Дерево","Default":"По умолчанию","Themes":"Темы","Choose a theme for the ReaImGui UI you will export.":"Выберите тему для экспортируемого интерфейса ReaImGui.","+ New":"+ Создать","Import":"Импорт","Edit…":"Изменить…","Editor":"Редактор","Preview":"Предпросмотр","Preview is approximate — hatched widgets are shown schematically":"Предпросмотр приблизительный — заштрихованные виджеты показаны схематично","Advanced canvas settings are active":"Используются расширенные параметры холста","Some canvas settings are hidden in Basic mode but remain part of this project.":"Некоторые параметры холста скрыты в базовом режиме, но сохранены в проекте.","Edit in Advanced":"Изменить в расширенном режиме","size":"размер","Width":"Ширина","Height":"Высота","background":"фон","grid":"сетка","Show grid":"Показывать сетку","Audit grid":"Контрольная сетка","color":"цвет","Opacity":"Прозрачность","Snap":"Привязка","Step":"Шаг","title bar":"строка заголовка","ImGui default":"По умолчанию ImGui","Theme colours":"Цвета темы","window":"окно","Resizable window":"Изменяемый размер окна","Min width":"Мин. ширина","Min height":"Мин. высота","Max width":"Макс. ширина","Max height":"Макс. высота","menu bar":"строка меню","+ Add menu":"+ Добавить меню","No menu bar. Add a menu to give the window a menu bar; the canvas keeps its size and nothing on it moves.":"Строка меню отсутствует. Добавьте меню, чтобы оно появилось в окне. Размер холста и расположение объектов не изменятся.","No element selected":"Элемент не выбран","Select one object on the canvas to edit its properties here.":"Выберите объект на холсте, чтобы изменить его свойства.","Multiple selection":"Выделено несколько объектов","Edit shared properties together.":"Редактируйте общие свойства объектов одновременно.","Move selection":"Переместить выделенное","move":"Переместить","Common properties":"Общие свойства","Mixed fields stay unchanged until you enter a value. Each edit is one undo step.":"Поля с различающимися значениями не изменяются, пока вы не введёте новое значение. Каждое изменение можно отменить отдельно.","delete selected":"Удалить выделенное","Advanced component":"Расширенный компонент","Some settings are available in Advanced mode.":"Некоторые настройки доступны только в расширенном режиме.","Configuring":"Настройка","Reset":"Сбросить","Click on canvas to place":"Щёлкните на холсте, чтобы разместить","Select a widget to preview":"Выберите виджет для предпросмотра","variant":"вариант","name":"имя","parent":"родительский объект","tabs":"вкладки","+ add tab":"+ добавить вкладку","table grid":"сетка таблицы","columns":"столбцы","row heights":"высота строк","label / text":"подпись / текст","placeholder":"замещающий текст","value":"значение","url":"URL","direction":"направление","value components":"компоненты значения","array size":"размер массива","min":"мин.","max":"макс.","speed":"скорость","step":"шаг","step fast":"ускоренный шаг","format":"формат","format min":"формат минимума","format max":"формат максимума","flags":"флаги","Clamp":"Ограничить","Log":"Логарифм.","NoInput":"Без ввода","Wrap":"Зациклить","hint":"подсказка","prefix bullet":"маркер в начале","highlight":"подсветка","disabled (BeginDisabled)":"отключено (BeginDisabled)","look":"вид","tree lines":"линии дерева","None":"Нет","Full":"Full","To nodes":"До узлов","tab button":"кнопка вкладки","Leading":"В начале","Trailing":"В конце","button label":"подпись кнопки","text tone":"цвет текста","Auto":"Авто","Dark":"Тёмный","Light":"Светлый","border":"граница","draw border":"рисовать границу","h-scroll":"горизонтальная прокрутка","horizontal scrollbar":"горизонтальная полоса прокрутки","text color":"цвет текста","frame bg":"фон элемента","button color":"цвет кнопки","rounding":"скругление","frame padding":"внутренние отступы","selectable align":"выравнивание элемента","font":"шрифт","sans-serif":"без засечек","serif":"с засечками","monospace":"моноширинный","cursive":"курсивный","fantasy":"декоративный","alpha":"альфа-канал","overlay":"наложенный текст","indeterminate":"неопределённый прогресс","animate":"анимация","EEL2 callback":"обработчик EEL2","group":"группа","flag group":"группа флагов","bit (0–30)":"бит (0–30)","values":"значения","scale min":"мин. шкалы","scale max":"макс. шкалы","text align":"выравнивание текста","left":"слева","center":"по центру","right":"справа","text size":"размер текста","vertical align":"выравнивание по вертикали","top":"сверху","middle":"по центру","bottom":"снизу","fill & stroke":"заливка и обводка","fill":"заливка","disable":"отключить","stroke":"обводка","thickness":"толщина","opacity":"прозрачность","hdr color":"цвет заголовка","default":"по умолчанию","custom":"пользовательский","hdr color val":"цвет заголовка","orient":"ориентация","angles (°)":"углы (°)","start":"начало","end":"конец","Link":"Связать","mode":"режим","ring":"кольцо","pie":"сектор","position":"положение","poly points":"вершины многоугольника","primitive order":"порядок отрисовки","back":"на задний план","backward":"назад","forward":"вперёд","front":"на передний план","delete":"удалить","select":"выделение","On":"Вкл.","Off":"Выкл.","0 elements":"0 элементов","No unsaved changes":"Нет несохранённых изменений","copy":"копировать","download .lua":"скачать .lua","Show code":"Показать код","Hide code":"Скрыть код","close":"закрыть","ReaUI Builder checks the project first, then exports the same ReaImGui Lua script as Advanced mode.":"Сначала ReaUI Builder проверит проект, затем экспортирует тот же Lua-скрипт ReaImGui, что и в расширенном режиме.","Checking export…":"Проверка перед экспортом…","Run again":"Проверить снова","Requires ReaImGui — install it via ReaPack.":"Требуется ReaImGui — установите его через ReaPack.","Colours of the exported plugin — not the builder's own look":"Цвета экспортируемого плагина, а не самого редактора","Hide service names of widgets in Editor":"Скрыть служебные имена виджетов в редакторе","Hide service names of draw objects in Editor":"Скрыть служебные имена графических объектов в редакторе","Open the online user manual in your browser":"Открыть руководство пользователя в браузере","Add components":"Добавить компоненты","Hand — drag to pan":"Рука — перетаскивайте для перемещения по холсту","Zoom — click to zoom in, Alt/Option + click to zoom out":"Масштаб — щелчок для увеличения, Alt/Option + щелчок для уменьшения","More widgets in the top-bar categories":"Другие виджеты в категориях верхней панели","Make a new theme, starting from the active one":"Создать тему на основе текущей","Add a theme from a .reaui-theme.json file":"Импортировать тему из файла .reaui-theme.json","Editor - schematic editing view":"Редактор — схематичный вид для редактирования","Preview - approximate ImGui look (view-only)":"Предпросмотр — приблизительный вид ImGui (без редактирования)","Drag to resize canvas":"Перетащите, чтобы изменить размер холста","Drag to try another window width (view only). Double-click: design size":"Перетащите, чтобы изменить ширину окна в предпросмотре. Двойной щелчок — размер макета","Drag to try another window height (view only). Double-click: design size":"Перетащите, чтобы изменить высоту окна в предпросмотре. Двойной щелчок — размер макета","Drag to try another window size (view only). Double-click: design size":"Перетащите, чтобы изменить размер окна в предпросмотре. Двойной щелчок — размер макета","Collapse or expand this panel":"Свернуть или развернуть панель","Pick a colour from the screen":"Выбрать цвет с экрана","Menu bar entries":"Элементы строки меню","Properties actions":"Действия со свойствами","placeholder text…":"Текст подсказки…","value text…":"Текст значения…","hover text…":"Текст при наведении…","Prefix bullet":"Маркер в начале","Highlight":"Подсветка","Disabled":"Отключено","Draw panel border":"Рисовать границу панели","Enable horizontal scrollbar":"Включить горизонтальную прокрутку","Frame padding X (0 to 32)":"Внутренний отступ по X (0–32)","Frame padding Y (0 to 32)":"Внутренний отступ по Y (0–32)","Selectable text align X (0 to 1)":"Выравнивание текста по X (0–1)","Selectable text align Y (0 to 1)":"Выравнивание текста по Y (0–1)","Font size in pixels":"Размер шрифта в пикселях","Bold":"Полужирный","Italic":"Курсив","empty = no text":"пусто — без текста","Animate indeterminate progress bar":"Анимировать индикатор выполнения","Plot values, comma-separated":"Значения графика через запятую","Link start and end angles":"Связать начальный и конечный углы","Expand Elements panel":"Развернуть панель «Элементы»","Zoom level":"Масштаб","Zoom out":"Уменьшить масштаб","Zoom in":"Увеличить масштаб","Button":"Кнопка","SmallButton":"Компактная кнопка","InvisibleButton":"Невидимая кнопка","ArrowButton":"Кнопка со стрелкой","Checkbox":"Флажок","CheckboxFlags":"Битовый флажок","RadioButton":"Переключатель","RadioButtonEx":"Переключатель","Text":"Текст","BulletText":"Маркированный текст","TextWrapped":"Текст с переносом","TextColored":"Цветной текст","TextDisabled":"Неактивный текст","SeparatorText":"Разделитель с текстом","Separator":"Разделитель","Hint":"Подсказка","HelpMarker":"Значок подсказки","LabelText":"Подпись со значением","TextLinkOpenURL":"Ссылка (URL)","TextLink":"Текстовая ссылка","Slider":"Ползунок","VSlider":"Вертикальный ползунок","SliderAngle":"Угловой ползунок","Drag":"Поле перетаскивания","DragRange":"Диапазон","Input":"Числовое поле","InputText":"Текстовое поле","InputTextMultiline":"Многострочное поле","Multiline":"Многострочное поле","SliderN":"Многокомпонентный ползунок","DragN":"Многокомпонентное поле","InputN":"Многокомпонентный ввод","ProgressBar":"Индикатор выполнения","Plot":"График","InputTextWithHint":"Поле с подсказкой","Combo":"Выпадающий список","ListBox":"Список","Selectable":"Выбираемый элемент","ColorEdit":"Редактор цвета","ColorPicker":"Выбор цвета","ColorButton":"Кнопка цвета","Panel":"Панель","Group":"Группа","StyleRegion":"Область стиля","Style":"Стиль","CollapsingHeader":"Сворачиваемый заголовок","TreeNode":"Узел дерева","TabBar":"Панель вкладок","Tabs":"Вкладки","Table":"Таблица","Main":"Основная","Appearance":"Оформление","Details":"Подробности","Options":"Параметры","Settings":"Настройки","Add widget":"Добавить виджет","Add menu":"Добавить меню","Delete selected":"Удалить выделенное","Duplicate selected":"Дублировать выделенное","Select group":"Выделить группу","Clear selection":"Снять выделение","Enter name":"Введите имя","No selection":"Ничего не выделено","Custom":"Пользовательский","Light mode":"Светлая тема","Theme Studio":"Редактор тем","Close Theme Studio":"Закрыть редактор тем","Plugin preview":"Предпросмотр","Hold to compare":"Сравнить","Editing":"Редактирование","Theme name":"Название темы","Click to rename":"Щёлкните для переименования","Theme actions":"Действия с темой","Collection":"Коллекция","My themes":"Мои темы","My Theme":"Моя тема","New theme":"Новая тема","Imported theme":"Импортированная тема","Not saved yet":"Ещё не сохранена","Built-in":"Встроенная","From Collection":"Из коллекции","From this project":"Из этого проекта","This project only":"Только в проекте","My theme":"Моя тема","Unsaved edits":"Несохранённые изменения","Saved":"Сохранено","Apply":"Применить","Apply to use it, or Save as… to keep it":"Нажмите «Применить», чтобы использовать, или «Сохранить как…», чтобы сохранить","Apply, or Save as… to keep edits":"Примените или сохраните изменения через «Сохранить как…»","Edits become a new theme":"Изменения будут сохранены как новая тема","Differs from the copy in My themes":"Отличается от копии в «Моих темах»","Save to add it to My themes":"Сохраните, чтобы добавить в «Мои темы»","Discard changes":"Не сохранять","Save theme":"Сохранить тему","Theme already saved":"Тема уже сохранена","Save another copy":"Сохранить ещё одну копию","Save":"Сохранить","Save as…":"Сохранить как…","Save edits to this theme in My themes":"Сохранить изменения темы в «Моих темах»","Save as a new theme in My themes":"Сохранить новую тему в «Моих темах»","Reset edits":"Сбросить изменения","Restore this theme to its last saved or starting colours":"Восстановить последние сохранённые или исходные цвета темы","Export…":"Экспорт…","Export Theme":"Экспортировать тему","Edit a copy":"Изменить копию","Change the colours of this theme":"Изменить цвета темы","Change the colours; saving makes a new theme":"Изменить цвета; при сохранении будет создана новая тема","In theme menu":"В меню тем","Show in theme menu":"Показывать в меню тем","Show or hide this theme in the quick theme menu; the active theme stays visible":"Показать или скрыть тему в быстром меню. Активная тема остаётся видимой.","Remove from project":"Удалить из проекта","Rename theme":"Переименовать тему","Manual":"Вручную","Click a colour to change it. The other colours follow automatically; colours set by hand in Full keep their values.":"Нажмите на цвет для изменения. Остальные цвета обновятся автоматически; вручную заданные цвета в полном наборе сохранят свои значения.","Default uses REAPER’s colours. Use Save as… to keep this palette as a custom theme.":"Тема по умолчанию использует цвета REAPER. Чтобы сохранить палитру как пользовательскую тему, выберите «Сохранить как…».","Background":"Фон","Controls":"Элементы управления","Accent":"Акцент","Header opacity":"Прозрачность заголовка","Rebuild all colours":"Пересоздать все цвета","Replace all manual RGB colours with the generated palette?":"Заменить все вручную заданные цвета RGB автоматически созданной палитрой?","Rebuild palette":"Пересоздать палитру","Rebuild":"Пересоздать","Label text":"Текст подписи","Window background":"Фон окна","Field":"Поле","Field · hovered":"Поле · наведение","Field · active":"Поле · активное","Button · hovered":"Кнопка · наведение","Button · active":"Кнопка · активная","Header · hovered":"Заголовок · наведение","Header · active":"Заголовок · активный","Check mark":"Галочка","Slider grab":"Ползунок","Slider grab · active":"Ползунок · активный","Automatically generated colours":"Автоматически созданные цвета","These colours are calculated from your palette and cannot be edited separately.":"Эти цвета вычисляются из палитры; редактировать их по отдельности нельзя.","Title colours are used when the project’s Title bar option is Theme colours. Menu bar colour is used with a menu bar.":"Цвета заголовка применяются при параметре «Строка заголовка → Цвета темы». Цвет строки меню используется при наличии меню.","ImGui colour":"Цвет ImGui","Value":"Значение","Rule":"Правило","Palette collection":"Коллекция палитр","Click a palette to load it into the editor. Your project changes only when you press Apply.":"Выберите палитру, чтобы загрузить её в редактор. Проект изменится только после нажатия «Применить».","Palettes from":"Палитры из","Import…":"Импорт…","No themes here yet.":"Здесь пока нет тем.","Active":"Активная","Select theme":"Выбрать тему","Close":"Закрыть","OK":"ОК","Cancel":"Отмена","Yes":"Да","No":"Нет","Continue":"Продолжить","Confirm":"Подтвердить","Delete Theme":"Удаление темы","Delete theme":"Удалить тему","Delete failed":"Ошибка удаления","Import failed":"Ошибка импорта","Import Theme":"Импорт темы","Export Lua":"Экспорт Lua","Export Lua Script":"Экспорт Lua-скрипта","Export ReaImGui Lua":"Экспорт Lua для ReaImGui","Preflight":"Предэкспортная проверка","Preflight check":"Проверка перед экспортом","Check":"Проверить","Run checks":"Запустить проверку","Checking…":"Проверка…","Passed":"Успешно","Warnings":"Предупреждения","Errors":"Ошибки","Error":"Ошибка","Warning":"Предупреждение","Info":"Информация","Valid":"Допустимо","Invalid":"Недопустимо","Failed":"Не удалось","Ready":"Готово","Done":"Готово","Copy to clipboard":"Копировать в буфер обмена","Copied":"Скопировано","Download":"Скачать","Download Lua":"Скачать Lua","All checks passed":"Все проверки пройдены","Print":"Печать","Show details":"Подробнее","Hide details":"Скрыть подробности","Show more":"Показать ещё","Show less":"Скрыть","ReaUI project":"Проект ReaUI","Untitled project":"Безымянный проект","No unsaved projects to restore.":"Нет несохранённых проектов для восстановления.","Restore projects":"Восстановление проектов","Restore":"Восстановить","Save project as":"Сохранить проект как","Load failed":"Ошибка открытия","Save failed":"Ошибка сохранения","Recovery failed":"Ошибка восстановления","Unsaved changes":"Несохранённые изменения","Saving…":"Сохранение…","Autosave failed":"Ошибка автосохранения","Loaded":"Загружено","Failed to load project":"Не удалось загрузить проект","Recovery draft saved locally in this browser at":"Резервная копия проекта сохранена в этом браузере:","Saving a local recovery draft":"Сохранение локальной резервной копии","Changes are waiting to be saved locally":"Изменения ожидают локального сохранения","New project has no unsaved changes":"В новом проекте нет несохранённых изменений","Loaded project has no unsaved changes":"В открытом проекте нет несохранённых изменений","The recovery draft could not be applied. It has not been deleted.":"Не удалось восстановить резервную копию. Она не удалена.","Stored projects could not be read.":"Не удалось прочитать сохранённые проекты.","Save the current project before restoring another one?":"Сохранить текущий проект перед восстановлением другого?","Save the current project before loading another one?":"Сохранить текущий проект перед открытием другого?","The project root must be an object.":"Корневой элемент проекта должен быть объектом.","The project shapes field is required and must be an array.":"Поле shapes обязательно и должно быть массивом.","This project version is not supported.":"Эта версия проекта не поддерживается.","This file is not valid JSON.":"Файл содержит некорректный JSON.","This file is not a ReaUI theme: it is not a JSON object.":"Это не тема ReaUI: содержимое не является объектом JSON.","This file is not a ReaUI theme: \"format\" is not \"reaui-theme\".":"Это не тема ReaUI: значение \"format\" отличается от \"reaui-theme\".","This theme file has no valid format version.":"В файле темы отсутствует корректная версия формата.","The file contains no theme.":"Файл не содержит темы.","The theme has no colours.":"В теме отсутствуют цвета.","The theme needs a valid \"childBg\" and a valid \"text\" colour.":"В теме должны быть корректные цвета \"childBg\" и \"text\".","The theme could not be added.":"Не удалось добавить тему.","The file could not be read.":"Не удалось прочитать файл.","Nothing was imported.":"Импорт не выполнен.","It is in the theme list now - click it to apply. The current theme is unchanged.":"Тема добавлена в список. Выберите её для применения. Текущая тема не изменилась.","Could not change the theme menu. Check browser storage and try again.":"Не удалось изменить меню тем. Проверьте хранилище браузера и повторите попытку.","Could not save the theme. Check browser storage and try again.":"Не удалось сохранить тему. Проверьте хранилище браузера и повторите попытку.","Could not apply the theme.":"Не удалось применить тему.","The theme could not be deleted. Check browser storage and try again.":"Не удалось удалить тему. Проверьте хранилище браузера и повторите попытку.","no callback event selected — this code will never run":"Не выбрано событие обработчика — этот код не будет выполняться","compiled once at startup via CreateFunctionFromEEL":"Компилируется один раз при запуске через CreateFunctionFromEEL","radio group":"группа переключателей","radio value":"значение переключателя","bullet (tree: replaces arrow)":"маркер (в дереве вместо стрелки)","start angle":"начальный угол","end angle":"конечный угол","link angles":"связать углы","arc mode":"режим дуги","header color":"цвет заголовка","header value":"значение заголовка","blocked: shape needs at least one of fill/stroke":"Невозможно: фигуре нужна хотя бы заливка или обводка","value must be finite":"Значение должно быть конечным числом","value must be an integer":"Значение должно быть целым числом","value is below the native API range":"Значение меньше допустимого диапазона API","value is above the native API range":"Значение больше допустимого диапазона API","callback events":"события обработчика","data type":"тип данных","ReadOnly":"Только чтение","Password":"Пароль","Pass":"Пароль","CharsDecimal":"Десятичные символы","Dec":"Дес.","CharsHexadecimal":"Шестнадцатеричные символы","Hex":"HEX","EnterReturnsTrue":"Подтверждение Enter","AllowTabInput":"Ввод Tab","CtrlEnterForNewLine":"Новая строка по Ctrl+Enter","CallbackEdit":"При изменении","CallbackAlways":"Всегда","CallbackCharFilter":"Фильтр символов","CallbackCompletion":"Автодополнение","CallbackHistory":"История","OnEdit":"Изменение","Always":"Всегда","CharFilter":"Фильтр","OnTab":"По Tab","OnUp/Down":"По ↑/↓","NoAlpha":"Без альфа","NoPicker":"Без палитры","NoInputs":"Без полей","NoTooltip":"Без подсказки","NoTip":"Без подсказки","NoLabel":"Без подписи","NoSidePreview":"Без бокового образца","NoSidePrev":"Без бокового образца","NoSmallPreview":"Без маленького образца","NoSmallPrev":"Без мини-образца","NoOptions":"Без параметров","NoDragDrop":"Без перетаскивания","NoBorder":"Без границы","DisplayRGB":"Показать RGB","DisplayHSV":"Показать HSV","DisplayHex":"Показать HEX","Uint8":"0–255","Float":"Дробные","InputRGB":"Ввод RGB","InputHSV":"Ввод HSV","PickerHueBar":"Полоса оттенка","HueBar":"Полоса оттенка","PickerHueWheel":"Цветовой круг","HueWheel":"Цветовой круг","AlphaBar":"Шкала альфа","AlphaPreviewHalf":"Полупрозрачный образец","HalfPrev":"Полуобразец","AlphaNoBg":"Без фона","NoBg":"Без фона","AlphaOpaque":"Непрозрачный образец","Opaque":"Непрозрачный","No elements yet":"Элементов пока нет","Add a widget or draw object, then click the canvas.":"Добавьте виджет или графический объект, затем щёлкните на холсте.","↑ height fixed by ImGui":"↑ высота задаётся ImGui","↑ size fixed by ImGui":"↑ размер задаётся ImGui","⊞ Snap:":"⊞ Привязка:","click=select Shift=range Cmd/Ctrl=toggle":"щелчок — выделить; Shift — диапазон; Cmd/Ctrl — переключить","click=select Shift=range Cmd/Ctrl=toggle":"щелчок — выделить; Shift — диапазон; Cmd/Ctrl — переключить","drag to place (or click for default size)":"протяните для размещения (или щёлкните для стандартного размера)","Structure":"Структура","Constraints":"Привязки","Constraints apply when the window is resizable":"Привязки работают при изменяемом размере окна","Make the window resizable":"Разрешить изменение размера окна","Pinned to":"Привязка к","Left":"Слева","Right":"Справа","Center":"Центр","Top":"Сверху","Bottom":"Снизу","Left+Right":"Слева + справа","Top+Bottom":"Сверху + снизу","Left · Top":"Слева · сверху","Horizontal":"По горизонтали","Vertical":"По вертикали","Name":"Имя","Enable loop":"Включить цикл","custom look (size, border, colours, click area)":"Пользовательский вид (размер, границы, цвета, область нажатия)","Constraint presets":"Шаблоны привязок","Pin left top":"Привязать слева сверху","Pin center top":"Привязать по центру сверху","Pin right top":"Привязать справа сверху","Pin left center":"Привязать слева по центру","Pin center":"Привязать к центру","Pin right center":"Привязать справа по центру","Pin left bottom":"Привязать слева снизу","Pin center bottom":"Привязать по центру снизу","Pin right bottom":"Привязать справа снизу","Horizontal constraint":"Горизонтальная привязка","Vertical constraint":"Вертикальная привязка","Select and edit this element":"Выделить и изменить этот элемент","Built-in · in use":"Встроенная · используется","Built-in · active":"Встроенная · активна","Vintage":"Винтажные","Cold":"Холодные","Warm":"Тёплые","Earth":"Землистые","Vintage palettes":"Винтажные палитры","Dark palettes":"Тёмные палитры","Cold palettes":"Холодные палитры","Warm palettes":"Тёплые палитры","Earth palettes":"Землистые палитры","Default — built-in":"Default — встроенная","Edit a copy of Light":"Изменить копию Light","Use this theme in the project and close. Edits stay in this project until you save them.":"Применить тему к проекту и закрыть редактор. Изменения останутся в проекте, пока вы не сохраните тему отдельно.","none":"нет","sample data":"пример данных","// EEL2 — runs on the selected Callback* event":"// EEL2 — выполняется при выбранном событии Callback*","Normal":"Обычный","Hovered":"Наведение","Active header":"Активный заголовок","Hovered header":"Заголовок при наведении","Parameter":"Параметр","Gain":"Усиление","Mix":"Смешивание","More":"Ещё","Sample plugin":"Пример плагина","Enable processing":"Включить обработку","Instruments":"Инструменты","Popup / tooltip selected text":"Всплывающая подсказка и выделенный текст","Documentation ↗":"Документация ↗","Documentation":"Документация","Current theme":"Текущая тема","New Theme":"Новая тема","View → Interface mode":"Вид → Режим интерфейса","File Edit View":"Файл Правка Вид","▾ Header":"▾ Заголовок","▾ Hovered header":"▾ Заголовок при наведении","▾ Active header":"▾ Активный заголовок","Popup / tooltip":"Всплывающее окно / подсказка","selected text":"выделенный текст","Disable":"Отключить","Basic layout":"Базовая компоновка","Title bar":"Строка заголовка","Edited":"Изменено","Edit theme":"Изменить тему","Edit a copy of":"Изменить копию","Theme":"Тема","Root":"Корень","Insert":"Вставить","Delete all":"Удалить всё","Clear All?":"Очистить всё?","ReaUI Builder — About":"ReaUI Builder — О программе","Keyboard shortcuts":"Сочетания клавиш","About ReaUI Builder":"О ReaUI Builder","Report a bug":"Сообщить об ошибке","Ready to export":"Готово к экспорту","Export failed: nothing was generated":"Экспорт не удался: ничего не сгенерировано","Nothing was generated, so there is nothing to copy":"Ничего не сгенерировано — копировать нечего","Nothing was generated, so there is nothing to download":"Ничего не сгенерировано — скачивать нечего","Load cancelled":"Загрузка отменена","Invalid table column settings":"Некорректные настройки столбцов таблицы","Adaptive table analysis is partial":"Проверка адаптивных таблиц выполнена частично","The project changed while the file was being read, so the file was not opened. Your current project is unchanged.":"Проект изменился, пока читался файл, поэтому файл не открыт. Текущий проект не изменён.","No export blockers or warnings detected.":"Ошибок и предупреждений, препятствующих экспорту, нет.","Arrow keys":"Клавиши со стрелками","Nudge selection (grid step, or 1 px with Snap off)":"Переместить выделенное на шаг сетки (или на 1 пиксель без привязки)","Shift + Arrow keys":"Shift + стрелки","Nudge selection by 10 steps":"Переместить выделенное на 10 шагов","Copy selection":"Копировать выделенное","Duplicate selection":"Дублировать выделенное","Delete selection":"Удалить выделенное","Escape":"Esc","Deselect, cancel tool/polygon, or close an open dialog/menu":"Снять выделение, отменить инструмент/многоугольник или закрыть окно/меню","Enter (Polygon)":"Enter (многоугольник)","Finish polygon":"Завершить многоугольник","Shift + click object":"Shift + щелчок по объекту","Extend selection from the anchor object":"Расширить выделение от опорного объекта","⌘/Ctrl + click object":"⌘/Ctrl + щелчок по объекту","Toggle object in selection":"Добавить объект к выделению или снять выделение","Shift + marquee":"Shift + рамка выделения","Add objects intersecting the marquee to selection":"Добавить объекты, пересекаемые рамкой, к выделению","Toggle objects intersecting the marquee":"Переключить выделение объектов, пересекаемых рамкой","Alt + drag object":"Alt + перетаскивание объекта","Drag a copy":"Перетащить копию объекта","U + drag container":"U + перетаскивание контейнера","Unlock for this move: leave its contents behind and ignore widgets underneath":"Временно разблокировать перемещение: оставить содержимое на месте и игнорировать виджеты под контейнером","Space + drag canvas":"Пробел + перетаскивание холста","Pan canvas":"Переместить холст","Zoom to cursor":"Масштабировать относительно указателя","Right-click canvas":"Правая кнопка мыши на холсте","Open the widget menu at the pointer":"Открыть меню виджетов у указателя","Shift + drawing tool button":"Shift + кнопка инструмента рисования","Keep Rectangle, Circle, Line, Triangle, or Arc active":"Оставить активными «Прямоугольник», «Окружность», «Линия», «Треугольник» или «Дуга»","Polygon: double-click / first point":"Многоугольник: двойной щелчок / первая вершина","Visual layout tool for ReaImGui (REAPER DAW).":"Визуальный редактор интерфейсов ReaImGui (REAPER).","Generates Lua code using the ReaImGui API.":"Генерирует Lua-код на основе API ReaImGui.","Single-file Vanilla HTML/CSS/JS — no build tools.":"Один HTML-файл с CSS и JavaScript, без сборки и зависимостей.","Report a Bug":"Сообщить об ошибке","Describe what happened, what you expected, and how to reproduce it.":"Опишите, что произошло, как должно было работать и как воспроизвести ошибку.","Copy Report":"Копировать отчёт","Download Report":"Скачать отчёт","Send the report to:":"Отправьте отчёт по адресу:","Copied ✓":"Скопировано ✓","Include my layout (helps reproduce it; sends the whole project)":"Включить мой макет (для воспроизведения ошибки; прикладывается весь проект)","The text below is everything that gets sent - the last 50 actions plus your build and window size. Nothing else is collected.":"Ниже приведён полный состав отчёта: последние 50 действий, версия сборки и размер окна. Другие данные не собираются.","Popups / text":"Всплывающие окна и текст","Borders / scrollbars":"Границы и прокрутка","Tables":"Таблицы","Window / menu":"Окно и меню","Plots / tree":"Графики и дерево","7 colours set by hand":"7 цветов заданы вручную","shift(Background, 3% away from background)":"shift(Фон, 3% от исходного фона)","mix(Background, Text, 55%)":"mix(Фон, Текст, 55%)","mix(Background, Check mark, 45%)":"mix(Фон, Галочка, 45%)","= Check mark":"= Галочка","= Text":"= Текст","mix(Background, Text, 30%)":"mix(Фон, Текст, 30%)","mix(Background, Field, 35%)":"mix(Фон, Поле, 35%)","= Field":"= Поле","= Hovered field":"= Поле при наведении","= Active field":"= Активное поле","= Header (opaque)":"= Заголовок (непрозрачный)","mix(Background, Text, 35%)":"mix(Фон, Текст, 35%)","mix(Background, Text, 18%)":"mix(Фон, Текст, 18%)","= Background":"= Фон","shift(Background, 5% away from background)":"shift(Фон, 5% от исходного фона)","mix(Background, Field, 60%)":"mix(Фон, Поле, 60%)","mix(Background, Header, 80%)":"mix(Фон, Заголовок, 80%)","mix(Background, Field, 40%)":"mix(Фон, Поле, 40%)","mix(Background, Field, 50%)":"mix(Фон, Поле, 50%)","shift(Check mark, 12% away from background)":"shift(Галочка, 12% от исходного фона)","mix(Background, Text, 65%)":"mix(Фон, Текст, 65%)","= Border":"= Граница","= Active header (fallback: Active button, Header)":"= Активный заголовок (иначе: Активная кнопка, Заголовок)","= Hovered header (fallback: Hovered button)":"= Заголовок при наведении (иначе: Кнопка при наведении)","= Check mark (fallback: Slider grab)":"= Галочка (иначе: Ползунок)","Visual layout tool for ReaImGui (REAPER DAW).\nGenerates Lua code using the ReaImGui API.\nSingle-file Vanilla HTML/CSS/JS — no build tools.":"Визуальный редактор интерфейсов ReaImGui для REAPER.\nГенерирует Lua-код через API ReaImGui.\nРаботает как единый HTML-файл с CSS и JavaScript, без сборки.","Popup / tooltip ":"Всплывающее окно / подсказка ","Project":"Проект","Element":"Элемент","Project background colour is invalid":"Некорректный цвет фона проекта","Use a hexadecimal colour in #RRGGBB format.":"Укажите цвет в шестнадцатеричном формате #RRGGBB.","Element has no ID":"У элемента отсутствует ID","Export maps and parent relationships require a stable element ID.":"Для экспорта и связей родительских объектов необходим постоянный ID элемента.","Duplicate element ID:":"Повторяющийся ID элемента:","IDs must be unique; the exporter uses them as map keys.":"ID должны быть уникальны: генератор использует их как ключи.","Unknown element type:":"Неизвестный тип элемента:","The Lua exporter supports widgets and the documented drawing primitives only.":"Экспорт Lua поддерживает только виджеты и описанные графические примитивы.","Parent ID is ambiguous":"Неоднозначный ID родительского объекта","Parent element is missing":"Родительский объект отсутствует","Cyclic parent relationship":"Циклическая вложенность","The parent chain loops back to an element already visited.":"Цепочка родительских объектов содержит цикл.","Invalid position or size":"Некорректные координаты или размер","X, Y, width and height must be finite numbers; width and height must be greater than zero.":"X, Y, ширина и высота должны быть конечными числами; ширина и высота — больше нуля.","Unknown widget type:":"Неизвестный тип виджета:","The Lua exporter has no contract for this widget.":"Генератор Lua не поддерживает этот тип виджета.","Choose Left, Right, Up or Down.":"Выберите Left, Right, Up или Down.","Arrow direction is not supported":"Неподдерживаемое направление стрелки","Polygon has fewer than three points":"У многоугольника менее трёх вершин","A polygon needs at least three points to export.":"Для экспорта многоугольнику необходимо минимум три вершины.","Polygon contains a nonnumeric point":"У многоугольника есть некорректная вершина","Every polygon point needs finite numeric X and Y coordinates.":"У каждой вершины должны быть конечные числовые координаты X и Y.","Polygon outline crosses itself":"Контур многоугольника пересекает сам себя","ImGui fills only a polygon whose outline does not cross, touch or turn back on itself. Move a point, split the shape into separate polygons, or disable its fill to export the outline only.":"ImGui может заливать только многоугольник без самопересечений и касаний контура. Переместите вершину, разделите фигуру или отключите заливку.","Polygon fill cannot be exported":"Не удалось экспортировать заливку многоугольника","Builder could not split this polygon into triangles for ImGui. Remove repeated points, or disable its fill to export the outline only.":"Не удалось разбить многоугольник на треугольники для ImGui. Удалите повторяющиеся вершины либо отключите заливку.","Line points are invalid":"Некорректные точки линии","A line needs exactly two points with finite numeric X and Y coordinates.":"Линии нужны ровно две точки с конечными числовыми координатами X и Y.","Invalid numeric property:":"Некорректный числовой параметр:","The value must be a finite number.":"Значение должно быть конечным числом.","Invalid StyleRegion property:":"Некорректный параметр StyleRegion:","Use a finite value inside the supported range.":"Укажите конечное число в допустимом диапазоне.","Invalid colour property:":"Некорректный параметр цвета:","Invalid colour flags":"Некорректные флаги цвета","Could not resolve export bounds":"Не удалось определить границы экспорта","Check the element parent chain and geometry.":"Проверьте геометрию и вложенность элемента.","Widget will not be exported":"Виджет не будет экспортирован","Draw object will not be exported":"Графический объект не будет экспортирован","It does not intersect the canvas, so it is omitted from the Lua.":"Объект не пересекает холст и исключён из экспорта Lua.","Draw object crosses the canvas edge":"Графический объект пересекает границу холста","Only the intersecting part will be visible in the exported plugin.":"В экспортированном интерфейсе будет видна только часть объекта внутри холста.","Link URL is empty":"Адрес ссылки не указан","The exporter will use https://example.com as a fallback.":"Генератор использует резервный адрес https://example.com.","Callback flags require EEL callback code":"Для флагов Callback необходим код обработчика EEL","Add a non-empty EEL callback or disable all Callback* flags.":"Добавьте код обработчика EEL или отключите все флаги Callback*.","Minimum is not numeric":"Минимум не является числом","Maximum is not numeric":"Максимум не является числом","Enter a finite number or clear the field.":"Введите конечное число или очистите поле.","Minimum is greater than maximum":"Минимум больше максимума","Swap the values or correct the numeric range.":"Поменяйте значения местами или исправьте диапазон.","Minimum equals maximum":"Минимум равен максимуму","The control has no usable value range.":"У элемента нет допустимого диапазона значений.","Step should be zero or positive":"Шаг должен быть неотрицательным","Negative or non-numeric step values can behave unexpectedly.":"Отрицательный или нечисловой шаг может вызвать некорректную работу.","Speed should be greater than zero":"Скорость должна быть больше нуля","Drag controls need a positive finite speed.":"Для элементов Drag требуется положительная конечная скорость.","Component count must be 1–4":"Число компонентов должно быть от 1 до 4","The selected widget family only supports one to four components.":"Этот тип виджета поддерживает от одного до четырёх компонентов.","Array size must be 2–64":"Размер массива должен быть от 2 до 64","N-wide controls allocate a ReaScript array of this size.":"Многокомпонентные элементы создают массив ReaScript указанного размера.","Color alpha must be 0–255":"Альфа-канал должен быть в диапазоне 0–255","The Lua color packer expects an 8-bit alpha value.":"Упаковка цвета в Lua требует 8-битного значения альфа-канала.","Will not be exported with its container":"Не экспортируется вместе с контейнером","Widget is unreachable by the exporter":"Виджет недоступен генератору","Its parent chain is not traversed by the generated Lua.":"Сгенерированный Lua-код не обходит цепочку родительских объектов виджета.","Widget overlaps":"Виджет перекрывает","Their occupied areas intersect on the canvas. Move or resize one of the widgets before export.":"Области виджетов на холсте пересекаются. Перед экспортом переместите один из виджетов или измените его размер.","Overlaps":"Перекрывает","Leaves the window":"Выходит за границы окна","Too small at the minimum window size":"Слишком мал при минимальном размере окна","Export name collides after sanitizing":"Совпадение экспортируемого имени после нормализации","Radio value is not numeric":"Значение переключателя не является числом","RadioButtonEx requires a finite numeric value.":"Для RadioButtonEx требуется конечное числовое значение.","Duplicate radio value in group":"Повторяющееся значение в группе переключателей","Flag bit must be an integer 0–":"Номер бита должен быть целым числом от 0 до","Duplicate bit in flag group":"Повторяющийся бит в группе флагов","Plot values are invalid":"Некорректные значения графика","Enter a number or clear the field for automatic scaling.":"Введите число или оставьте поле пустым для автоматического масштаба.","Scale min is not below scale max":"Минимум шкалы не меньше максимума","The plot has no usable value range.":"У графика нет допустимого диапазона значений.","PlotLines needs at least two values":"PlotLines требует минимум два значения","With one value ImGui draws an empty frame.":"При одном значении ImGui рисует пустую рамку.","TabBar has no tabs":"В TabBar отсутствуют вкладки","The exported tab bar will have no visible tab items.":"В экспортированной панели не будет видимых вкладок.","Active tab does not exist":"Активная вкладка отсутствует","Choose one of the TabItems contained by this TabBar.":"Выберите одну из вкладок TabItem этой панели TabBar.","TabItem is not inside a TabBar":"TabItem находится вне TabBar","Standalone TabItems are not emitted correctly.":"Отдельные TabItem вне TabBar экспортируются некорректно.","Table rows and columns must be positive integers":"Число строк и столбцов таблицы должно быть положительным целым числом","Correct rowCount and columnCount before export.":"Перед экспортом исправьте rowCount и columnCount.","Table cell is outside the table grid":"Ячейка выходит за границы таблицы","Row and column indices must fit the parent table dimensions.":"Индексы строки и столбца должны соответствовать размеру родительской таблицы.","Duplicate table cell":"Повторяющаяся ячейка таблицы","Only one TableCell can occupy each row and column.":"Каждую позицию строки и столбца может занимать только одна TableCell.","Table has missing structural cells":"В таблице отсутствуют структурные ячейки","TableCell is not inside a Table":"TableCell находится вне Table","Standalone structural cells are not emitted correctly.":"Отдельные структурные ячейки экспортируются некорректно.","Menus past the right edge are cut off in REAPER":"Меню, выходящее за правую границу, будет обрезано в REAPER","Frame padding Y is":"Внутренний отступ рамки по Y равен","Copy generated Lua":"Копировать сгенерированный Lua","Download generated Lua":"Скачать сгенерированный Lua","Resolve the errors above to enable copy":"Исправьте ошибки выше, чтобы разблокировать копирование","Resolve the errors above to enable download":"Исправьте ошибки выше, чтобы разблокировать скачивание","Ready with":"Готово, но есть","Select this element on canvas":"Выделить этот элемент на холсте"}; const HINTS = {"variant-row":"Вариант виджета: Int или Double, RGB или RGBA, Lines или Histogram. Выберите перед размещением; позднее сменить вариант нельзя.","name-row":"Имя элемента. У виджета используется в экспортируемом скрипте для переменных состояния и скрытого идентификатора ImGui. При настройке нового виджета задаётся автоматически. `state._…` `##`","parent-row":"Контейнеры, содержащие этот элемент, начиная с внешнего. Перетащите элемент в контейнер или за его пределы, чтобы изменить вложенность.","label-row":"Видимый текст: подпись виджета либо текст графического объекта. Дважды щёлкните по тексту, прямоугольнику или окружности на холсте для изменения на месте.","hint-row":"Серый замещающий текст, пока поле пусто. `InputTextWithHint`","value-row":"Текст значения в поле; подпись располагается справа. `LabelText`","url-row":"Адрес, открываемый браузером при нажатии на ссылку. `TextLinkOpenURL`","direction-row":"Направление стрелки. `ArrowButton` `Dir_Left` `Right` `Up` `Down`","component-count-row":"Количество значений, редактируемых рядом (1–4), например X/Y или XYZ. Для 2–4 компонентов используется соответствующая функция ImGui. `SliderInt3`","array-size-row":"Количество редактируемых значений (2–64) в одном массиве. `reaper_array` `SliderDoubleN` `DragDoubleN` `InputDoubleN`","min-row":"Нижняя граница значения. Перетаскивание ограничено ею, но ввод через Ctrl+щелчок может выйти за границу без флага Clamp. `v_min`","max-row":"Верхняя граница значения. Перетаскивание ограничено ею, но ввод через Ctrl+щелчок может выйти за границу без флага Clamp. `v_max`","speed-row":"Скорость изменения при перетаскивании в расчёте на пиксель движения мыши. При 0.2 для изменения на единицу требуется 5 пикселей. `v_speed`","step-row":"Шаг кнопок − / +. Значение 0 скрывает кнопки. `step`","step-fast-row":"Ускоренный шаг кнопок − / + при удержании Ctrl. Значение 0 означает обычный шаг. `step_fast`","format-row":"Формат отображения в стиле printf, например %.2f dB или %d%%. Также определяет точность редактирования. Пустое поле — формат по умолчанию. `%.2f dB` `%d%%`","format-min-row":"Формат отображения нижней границы, например Min: %d. `Min: %d` `format`","format-max-row":"Формат отображения верхней границы, например Max: %d. `Max: %d` `format_max`","numeric-flags-row":"Дополнительные параметры поведения числового поля или ползунка. `SliderFlags_*`","numeric-flags:AlwaysClamp":"Ограничить: значение, введённое через Ctrl+щелчок, также удерживается в пределах минимума и максимума. `SliderFlags_AlwaysClamp`","numeric-flags:Logarithmic":"Логарифмическая шкала с повышенной точностью на нижнем участке. `SliderFlags_Logarithmic`","numeric-flags:NoInput":"Отключает ввод значения через Ctrl+щелчок и клавишу Enter. `SliderFlags_NoInput`","numeric-flags:WrapAround":"Циклический переход с максимума на минимум и обратно при перетаскивании. Только для числовых полей Drag. `SliderFlags_WrapAround`","tooltip-row":"Текст подсказки в REAPER при наведении на виджет. Пустое поле — без подсказки. `SetItemTooltip`","bullet-row":"Добавляет маркер слева от виджета, не перемещая сам виджет. `DrawList_AddCircleFilled`","bullet-row:tree":"Показывает маркер вместо стрелки сворачивания. Узел по-прежнему можно раскрывать и сворачивать. `TreeNodeFlags_Bullet`","highlight-row":"Подсвечивает строку так, как при наведении указателя. `SelectableFlags_Highlight`","sr-disabled-row":"Делает содержимое области неактивным и блокирует ввод. `BeginDisabled` `EndDisabled`","tree-lines-row":"Направляющие линии от узла к дочерним узлам.","tree-lines:none":"Нет: направляющие линии отсутствуют (по умолчанию).","tree-lines:full":"Полные: линии соединяют дочерние узлы; вертикальная линия тянется до конца содержимого. `TreeNodeFlags_DrawLinesFull`","tree-lines:toNodes":"До узлов: линии соединяют дочерние узлы; вертикальная линия заканчивается на последнем дочернем узле. `TreeNodeFlags_DrawLinesToNodes`","tab-button-row":"Добавляет на одном из краёв панели вкладок кнопку (например, «+»), которую нельзя выбрать как вкладку. `TabItemButton`","tab-button:none":"Кнопка вкладки отсутствует (по умолчанию).","tab-button:leading":"В начале панели вкладок, слева. `TabItemFlags_Leading`","tab-button:trailing":"В конце панели вкладок, справа. `TabItemFlags_Trailing`","tab-button-label-row":"Текст кнопки на панели вкладок. Доступен при положении «В начале» или «В конце».","text-tone-row":"Цвет текста с переносом. «Авто» использует цвет темы, «Тёмный» и «Светлый» фиксируют цвет. `PushStyleColor(Col_Text)`","panel-bordered-row":"Рисует рамку вокруг панели и добавляет внутренние отступы. `ChildFlags_Borders`","panel-hscroll-row":"Показывает горизонтальную полосу прокрутки, когда содержимое шире панели. `WindowFlags_HorizontalScrollbar`","sr-text-row":"Цвет текста внутри области. Включается отдельным флажком. `PushStyleColor(Col_Text)`","sr-framebg-row":"Цвет фона полей ввода, ползунков и флажков внутри области. Включается отдельным флажком. `Col_FrameBg`","sr-button-row":"Цвет кнопок внутри области. Включается отдельным флажком. `Col_Button`","sr-rounding-row":"Радиус скругления рамок и кнопок внутри области в пикселях. Включается отдельным флажком. `StyleVar_FrameRounding`","sr-framepad-row":"Внутренние отступы между рамкой элемента и текстом по X и Y, в пикселях. В REAPER меняют высоту стандартных элементов управления. `StyleVar_FramePadding`","sr-selalign-row":"Положение текста Selectable внутри области по X и Y: от 0 (лево/верх) до 1 (право/низ). `StyleVar_SelectableTextAlign`","sr-font-row":"Гарнитура, размер и полужирное/курсивное начертание текста внутри области. Включается отдельным флажком. `CreateFont` `PushFont`","color-row":"Начальный цвет ColorEdit/ColorPicker, образец ColorButton или цвет текста TextColored.","color-alpha-row":"Прозрачность цвета: от 0 (прозрачный) до 255 (непрозрачный).","color-flags-row":"Параметры цветового виджета. В сегментированных группах можно выбрать только один вариант. `ColorEditFlags_*`","overlay-row":"Текст поверх индикатора выполнения или графика. По умолчанию ProgressBar показывает процент (кроме анимации), график — ничего. `overlay`","indeterminate-row":"Анимирует индикатор туда и обратно вместо фиксированного уровня. Экспортирует отрицательную долю. `-1.0 * GetTime()`","input-flags-row":"Параметры поведения текстового поля. Флаги Callback определяют события запуска обработчика EEL2. `InputTextFlags_*`","eel-callback-row":"Код EEL2, выполняемый при отмеченных выше событиях; компилируется один раз при запуске. Без выбранного события не запускается. `CreateFunctionFromEEL`","radio-group-row":"Переключатели с одинаковой группой используют одну переменную: выбор одного снимает выбор остальных.","radio-value-row":"Число, записываемое выбранным переключателем в переменную группы. `RadioButtonEx`","flag-group-row":"Флажки группы используют одно целое число; каждый переключает собственный бит. `CheckboxFlags`","flag-bit-row":"Номер переключаемого бита (0–30) общего целого числа. `1<_checked`","cb:size":"Размер квадрата в пикселях (6–64). Размер стандартного флажка зависит от высоты строки; пользовательский имеет указанный размер.","cb:mark":"Вид установленного флажка: галочка ImGui или закрашенный квадрат. × использует цвет галочки из темы. `Col_CheckMark`","cb:bg":"Заливка квадрата. × использует цвет поля из темы. `Col_FrameBg`","cb:border":"Граница квадрата толщиной 1 пиксель и её цвет. × использует цвет границы из темы. `Col_Border`","cb:checked":"Установить флажок при запуске. Предпросмотр показывает метку, а экспорт задаёт исходное состояние true. `state._checked = true`","cb:hit":"Область нажатия: только квадрат, вся строка таблицы или расширенная по горизонтали область. Она не часть квадрата: другие объекты могут её перекрывать и сохраняют собственные нажатия в REAPER. `Selectable` `SpanAllColumns` `AllowOverlap`","cb:hit-extend":"Расширение области нажатия влево и вправо от квадрата, в пикселях.","cb:hover":"Подсветка строки при наведении указателя. × использует цвет темы. Отключено — без подсветки. `Col_HeaderHovered`","table:row-bg":"Цвет фона строки таблицы; × сбрасывает его. `TableSetBgColor(TableBgTarget_RowBg0)`","table:highlight":"Цвет подсветки любой строки во время работы скрипта. Задайте соответствующий флаг состояния для строки (нумерация от 1). Отмеченные строки видны в предпросмотре и экспорте. `state._highlight[row] = true` `TableSetBgColor(TableBgTarget_RowBg1)`","color-flag:NoAlpha":"Не учитывать альфа-канал цвета. `ColorEditFlags_NoAlpha`","color-flag:NoPicker":"Нажатие на образец цвета не открывает палитру. `ColorEditFlags_NoPicker`","color-flag:NoInputs":"Скрывает числовые поля, оставляя только образец цвета. `ColorEditFlags_NoInputs`","color-flag:NoTooltip":"Отключает подсказку при наведении на образец. `ColorEditFlags_NoTooltip`","color-flag:NoLabel":"Скрывает подпись рядом с элементом, но оставляет её в подсказке и палитре. `ColorEditFlags_NoLabel`","color-flag:NoSidePreview":"Заменяет большой образец рядом с палитрой на маленький квадрат, чтобы палитра помещалась в поле. `ColorEditFlags_NoSidePreview`","color-flag:NoSmallPreview":"Скрывает маленький образец цвета рядом с полями. `ColorEditFlags_NoSmallPreview`","color-flag:NoOptions":"Запрещает открытие меню настроек правой кнопкой мыши. `ColorEditFlags_NoOptions`","color-flag:NoDragDrop":"Отключает перетаскивание цвета на элемент и с него. `ColorEditFlags_NoDragDrop`","color-flag:NoBorder":"Убирает границу кнопки. `ColorEditFlags_NoBorder`","color-flag:DisplayRGB":"Показывает значения как R, G, B. `ColorEditFlags_DisplayRGB`","color-flag:DisplayHSV":"Показывает значения как H, S, V. `ColorEditFlags_DisplayHSV`","color-flag:DisplayHex":"Показывает цвет в шестнадцатеричном формате. `ColorEditFlags_DisplayHex`","color-flag:Uint8":"Показывает значения в диапазоне 0–255. `ColorEditFlags_Uint8`","color-flag:Float":"Показывает значения в диапазоне 0.0–1.0. `ColorEditFlags_Float`","color-flag:InputRGB":"Скрипт читает и записывает цвет в формате RGB. `ColorEditFlags_InputRGB`","color-flag:InputHSV":"Скрипт читает и записывает цвет в формате HSV. `ColorEditFlags_InputHSV`","color-flag:PickerHueBar":"Палитра с полосой оттенка и квадратом насыщенности/яркости. `ColorEditFlags_PickerHueBar`","color-flag:PickerHueWheel":"Палитра с цветовым кругом и треугольником насыщенности/яркости. `ColorEditFlags_PickerHueWheel`","color-flag:AlphaBar":"Добавляет в палитру вертикальную шкалу альфа-канала. `ColorEditFlags_AlphaBar`","color-flag:AlphaPreviewHalf":"Половина образца непрозрачна, другая половина прозрачна. `ColorEditFlags_AlphaPreviewHalf`","color-flag:AlphaNoBg":"Убирает шахматный фон за прозрачным цветом. `ColorEditFlags_AlphaNoBg`","color-flag:AlphaOpaque":"Предпросмотр игнорирует альфа-канал, но его можно редактировать. `ColorEditFlags_AlphaOpaque`","input-flag:ReadOnly":"Текст можно выделять и копировать, но нельзя изменять. `InputTextFlags_ReadOnly`","input-flag:Password":"Показывает символы как * и запрещает копирование. `InputTextFlags_Password`","input-flag:CharsDecimal":"Принимает только 0–9 . + - * /. `InputTextFlags_CharsDecimal`","input-flag:CharsHexadecimal":"Принимает только 0–9 и A–F. `InputTextFlags_CharsHexadecimal`","input-flag:EnterReturnsTrue":"Функция сообщает об изменении только при нажатии Enter, а не на каждом вводимом символе. `InputTextFlags_EnterReturnsTrue`","input-flag:AllowTabInput":"Клавиша Tab вставляет символ табуляции вместо перехода к следующему полю. `InputTextFlags_AllowTabInput`","input-flag:CtrlEnterForNewLine":"Enter подтверждает ввод, Ctrl+Enter добавляет новую строку (по умолчанию наоборот). `InputTextFlags_CtrlEnterForNewLine`","input-flag:CallbackEdit":"Вызывает обработчик EEL2 при каждом изменении текста. `InputTextFlags_CallbackEdit`","input-flag:CallbackAlways":"Вызывает обработчик EEL2 каждый кадр, пока поле активно. `InputTextFlags_CallbackAlways`","input-flag:CallbackCharFilter":"Вызывает обработчик EEL2 при вводе каждого символа; обработчик может заменить или отклонить его. `InputTextFlags_CallbackCharFilter`","input-flag:CallbackCompletion":"Вызывает обработчик EEL2 при нажатии Tab, например для автодополнения. `InputTextFlags_CallbackCompletion`","input-flag:CallbackHistory":"Вызывает обработчик EEL2 при нажатии стрелок вверх/вниз, например для истории ввода. `InputTextFlags_CallbackHistory`","me-move":"Перемещает все выделенные элементы на ΔX / ΔY пикселей; при привязке значения округляются до шага сетки. Одна операция отмены. Enter в поле тоже перемещает.","cw":"Ширина области содержимого окна плагина в пикселях. В экспорте — W. `W`","ch":"Высота области содержимого окна плагина под строкой заголовка и меню, в пикселях. В экспорте — H. `H`","bg-mode-default":"По умолчанию: собственный фон не экспортируется, используется цвет окна из темы.","bg-mode-custom":"Пользовательский: экспорт заливает окно указанным ниже цветом. `PushStyleColor(Col_WindowBg)`","grid-toggle-btn":"Показать или скрыть сетку редактора. Только в билдере, не влияет на экспорт.","audit-grid-btn":"Добавляет контрольную сетку в экспортируемый интерфейс для проверки выравнивания в REAPER. Перед выпуском отключите.","cp-sv":"Выбрать насыщенность и яркость цвета фона. Выбор переключает фон в пользовательский режим.","cp-hue":"Выбрать оттенок фона. Выбор переключает фон в пользовательский режим.","cp-cur":"Текущий цвет фона.","cp-eye":"Взять цвет в любой точке экрана.","cp-recents":"Недавно использованные цвета; нажмите для повторного выбора.","bg-alpha":"Смешивает цвет фона с белым. В экспорт передаётся итоговый непрозрачный цвет.","snap-toggle-btn":"Привязка размещения, перемещения и изменения размеров к шагу сетки. Только в билдере, не влияет на экспорт.","grid-step-seg":"Шаг сетки редактора и привязки в пикселях. Только в билдере, не влияет на экспорт.","bg-color-field":"Цвет фона в шестнадцатеричном формате (#RRGGBB). В режиме «По умолчанию» обозначает тему, определяющую фон.","titlebar-option":"Цвета строки заголовка экспортируемого окна. Не действует с темой Default (неактивно).","titlebar-mode-default":"По умолчанию ImGui: собственные цвета строки заголовка.","titlebar-mode-theme":"Цвета темы: строка заголовка использует цвета заданной темы. `Col_TitleBg` `Col_TitleBgActive`","mbx-add-menu":"Добавляет меню в строку меню окна, не меняя размер холста. `BeginMenuBar` `BeginMenu`","mbx:label":"Текст, показываемый для пункта меню.","mbx:name":"Уникальный идентификатор пункта в экспортируемом скрипте: скрытый ID ImGui и, при наличии флажка, переменная состояния. `##` `state._checked`","mbx:shortcut":"Текст сочетания клавиш справа от пункта. Только отображение: ImGui не обрабатывает его автоматически. `MenuItem`","mbx:enabled":"При выключении пункт становится неактивным и не реагирует на нажатие. `MenuItem` `BeginMenu` `enabled`","mbx:checked":"Установлен ли флажок пункта при запуске экспортированного скрипта.","mbx:add-item":"Добавляет обычный пункт после выделенного или внутри выбранного меню. `MenuItem`","mbx:add-check":"Добавляет пункт с флажком, переключаемым нажатием. `MenuItem` `selected`","mbx:add-separator":"Добавляет разделительную линию. `Separator`","mbx:add-submenu":"Добавляет подменю. Максимальная глубина вложенности — 4 уровня. `BeginMenu`","mbx:up":"Перемещает пункт выше в текущем меню.","mbx:down":"Перемещает пункт ниже в текущем меню.","mbx:delete":"Удаляет пункт. Удаление меню также удаляет всё его содержимое.","del-btn":"Удаляет выделенный объект (также клавиша Delete). Для контейнера с виджетами предлагается сохранить содержимое. Удаление можно отменить.","me-delete":"Удаляет все выделенные объекты (также клавиша Delete). Для контейнеров с виджетами предлагается сохранить содержимое. Удаление можно отменить.","group-btn":"Объединяет выделенные объекты в группу: выделение одного выбирает всю группу, перемещение выполняется совместно. Только для редактора, не экспортируется.","ungroup-btn":"Расформировывает группу, оставляя элементы на прежних местах.","group-select-btn":"Добавляет остальные объекты этой группы к выделению.","editor-group-name-row":"Имя группы в списке «Элементы». Используется только редактором, не экспортируется.","window-resize-section":"Разрешение менять размер экспортируемого окна в REAPER и пределы изменения. В базовом режиме показывается краткая сводка.","wr-toggle":"Разрешает изменять размер экспортируемого окна в REAPER; объекты с привязками следуют за его границами. Выключено — фиксированный размер. `SetNextWindowSizeConstraints`","wr-min-w":"Минимальная ширина содержимого окна в пикселях: от 64 до ширины холста. Пустое поле — ширина холста. `SetNextWindowSizeConstraints`","wr-min-h":"Минимальная высота содержимого окна в пикселях (без заголовка и меню): от 64 до высоты холста. Пустое поле — высота холста.","wr-max-w":"Максимальная ширина содержимого окна в пикселях: не меньше ширины холста. Пустое поле — без ограничения. `SetNextWindowSizeConstraints`","wr-max-h":"Максимальная высота содержимого окна в пикселях: не меньше высоты холста. Пустое поле — без ограничения.","wr-basic-summary":"Размер окна можно изменять: диапазон ширины × диапазон высоты в пикселях (∞ — без ограничения). Изменение доступно в расширенном режиме.","pin-grid":"Готовые варианты привязки по двум осям: к углам, к краям или к центру родительского контейнера. Растяжение задаётся ниже.","pin-h:left":"Слева: сохраняет расстояние до левого края родителя (по умолчанию).","pin-h:right":"Справа: сохраняет расстояние до правого края при изменении ширины окна.","pin-h:center":"По центру: объект остаётся по центру родителя по горизонтали.","pin-h:stretch":"Слева и справа: сохраняет отступы от обоих краёв; ширина растёт и уменьшается вместе с родителем.","pin-h:stretch-off":"Растяжение по ширине для этого объекта недоступно: ширину задают ImGui, текст или связанные размеры.","pin-v:top":"Сверху: сохраняет расстояние до верхнего края родителя (по умолчанию).","pin-v:bottom":"Снизу: сохраняет расстояние до нижнего края при изменении высоты окна.","pin-v:center":"По центру: объект остаётся по центру родителя по вертикали.","pin-v:stretch":"Сверху и снизу: сохраняет отступы от обоих краёв; высота меняется вместе с родителем.","pin-v:stretch-off":"Растяжение по высоте для этого объекта недоступно: высоту задают ImGui или содержимое.","pin-grid:in-cell":"В ячейке таблицы привязки действуют относительно ячейки. Ячейка растягиваемого столбца увеличивается вместе с ним.","pin-make-resizable":"Включает «Изменяемый размер окна» на вкладке «Холст». Все привязки сохраняются и без этого режима.","constraints-basic-row":"К каким краям родителя привязан объект при изменении размера окна. Редактируется в расширенном режиме.","basic-edit-advanced":"Переключает билдер в расширенный режим для редактирования скрытых параметров. Проект и экспорт не изменяются."}; const WIDGETS = {"Button":{"what":"Кнопка, которая выполняет действие при нажатии.","use":"Для запуска команд: рендеринга, применения настроек, сброса или операции скрипта."},"SmallButton":{"what":"Компактная кнопка с уменьшенными отступами.","use":"Для дополнительных действий в условиях ограниченного пространства."},"InvisibleButton":{"what":"Невидимая в готовом интерфейсе область, реагирующая на нажатия.","use":"Для обработки щелчков по собственным графическим элементам."},"ArrowButton":{"what":"Небольшая квадратная кнопка со стрелкой.","use":"Для пошагового изменения значений и сворачивания разделов."},"Checkbox":{"what":"Флажок с подписью для включения и отключения параметра. Пользовательский стиль позволяет менять размер, границы и цвета, а также расширять область нажатия до строки таблицы.","use":"Для параметров «включено/выключено»: активации, приглушения, цикла или обхода эффекта."},"RadioButtonEx":{"what":"Группа взаимоисключающих переключателей: активен только один.","use":"Для выбора одного режима из небольшого набора вариантов."},"CheckboxFlags":{"what":"Флажок, переключающий отдельный бит общего целого числа.","use":"Для групп параметров, хранящихся как битовые флаги."},"Text":{"what":"Статическая однострочная текстовая надпись.","use":"Для названий полей, подписей и коротких сообщений состояния."},"LabelText":{"what":"Значение только для чтения с подписью справа.","use":"Для отображения значения и подписи в стандартном выравнивании Dear ImGui."},"BulletText":{"what":"Текстовая строка с маркером в начале.","use":"Для простых маркированных списков и заметок."},"TextWrapped":{"what":"Текст, автоматически переносимый по доступной ширине.","use":"Для длинных описаний и справочных абзацев."},"TextColored":{"what":"Текст заданного цвета.","use":"Для предупреждений, состояний и цветовых обозначений."},"TextDisabled":{"what":"Приглушённый текст неактивного элемента.","use":"Для подсказок и подписей недоступных параметров."},"TextLinkOpenURL":{"what":"Подчёркнутая ссылка, открывающая URL в браузере.","use":"Для документации, сайтов и страниц поддержки."},"TextLink":{"what":"Подчёркнутая текстовая ссылка, сообщающая о нажатии.","use":"Для текстовых команд, например «Подробнее». Место для обработчика отмечается при экспорте."},"Separator":{"what":"Тонкая горизонтальная разделительная линия.","use":"Для визуального разделения областей интерфейса."},"SeparatorText":{"what":"Разделительная линия с текстом по центру.","use":"Для заголовков разделов и отделения блоков."},"Slider":{"what":"Горизонтальный ползунок для числового значения.","use":"Для ограниченных диапазоном величин: усиления, баланса или порога."},"VSlider":{"what":"Вертикальный ползунок для числового значения.","use":"Для фейдеров, уровней и вертикальных регуляторов."},"SliderAngle":{"what":"Ползунок угла в градусах.","use":"Для поворота, панорамирования и фазы."},"SliderN":{"what":"Несколько ползунков для многокомпонентного значения.","use":"Для векторов и цветовых каналов, например RGB."},"Drag":{"what":"Числовое поле, изменяемое перетаскиванием влево или вправо.","use":"Для точной настройки значений, которым не нужен ползунок."},"DragN":{"what":"Несколько полей с изменением перетаскиванием.","use":"Для координат и многокомпонентных векторов X/Y/Z."},"DragRange":{"what":"Два связанных поля, задающих минимум и максимум.","use":"Для диапазонов: нижней и верхней границы, начала и конца."},"Input":{"what":"Поле числового ввода с кнопками уменьшения и увеличения.","use":"Для точного ввода целых и дробных чисел."},"InputN":{"what":"Группа числовых полей.","use":"Для точного ввода многокомпонентных значений."},"InputText":{"what":"Однострочное поле ввода текста.","use":"Для имён, путей и коротких текстовых значений."},"InputTextWithHint":{"what":"Текстовое поле с замещающей подсказкой.","use":"Для полей, где полезно показать пример ожидаемого ввода."},"InputTextMultiline":{"what":"Многострочное поле ввода текста.","use":"Для заметок, описаний и объёмных текстовых блоков."},"ProgressBar":{"what":"Горизонтальный индикатор выполнения от 0 до 100 %.","use":"Для отображения хода рендеринга, сканирования или длительной операции."},"Plot":{"what":"Компактный график числовых данных: линия или гистограмма.","use":"Для индикаторов, огибающих и истории значений. При экспорте массив заполняется вашими данными."},"Combo":{"what":"Выпадающий список с отображением выбранного пункта.","use":"Для компактного выбора одного варианта из списка."},"ListBox":{"what":"Список с прокруткой, показывающий несколько строк одновременно.","use":"Когда варианты должны оставаться видимыми без раскрытия списка."},"Selectable":{"what":"Строка во всю ширину, которую можно выделить.","use":"Для пользовательских списков, меню и интерактивных строк."},"ColorEdit":{"what":"Компактный редактор цвета с числовыми каналами RGB(A).","use":"Для точного задания цвета непосредственно в интерфейсе."},"ColorPicker":{"what":"Полный выбор цвета с полем насыщенности и полосой оттенка.","use":"Для визуального выбора цвета."},"ColorButton":{"what":"Небольшая кнопка с образцом цвета.","use":"Для индикации цвета или открытия выбора цвета по нажатию."},"Group":{"what":"Невидимый контейнер, объединяющий дочерние виджеты.","use":"Для совместного выравнивания, размещения и обработки нескольких виджетов."},"StyleRegion":{"what":"Невидимая область, переопределяющая стиль дочерних виджетов: цвета, скругление, выравнивание и шрифт. Сама область не занимает места; верхняя полоса на холсте служит только подписью.","use":"Для изменения оформления группы виджетов, включая гарнитуру, размер и начертание шрифта. Если область перекрыта дочерними объектами, выберите её на свободном участке или в панели «Элементы»."},"CollapsingHeader":{"what":"Заголовок во всю ширину, сворачивающий и разворачивающий содержимое.","use":"Для разделов с дополнительными и расширенными настройками."},"TreeNode":{"what":"Разворачиваемый узел с вложенными элементами.","use":"Для иерархий папок, дорожек и параметров."},"TabBar":{"what":"Панель вкладок, переключающая страницы содержимого.","use":"Для разделения интерфейса на вкладки, например «Главная / FX / MIDI»."},"Table":{"what":"Таблица строк и столбцов, содержащая другие виджеты.","use":"Для выровненных макетов, матриц и табличных данных."},"HelpMarker":{"what":"Значок вопроса, показывающий подсказку при наведении.","use":"Для пояснения элементов управления без перегрузки интерфейса."},"Panel":{"what":"Панель с границей, содержащая виджеты и поддерживающая прокрутку.","use":"Для боковых панелей, блоков настроек и списков."}}; const DRAWS = {"rect":{"what":"Прямоугольник с заливкой или обводкой, отрисованный через DrawList.","use":"Для панелей, фонов, рамок и шкал индикаторов."},"circle":{"what":"Окружность с заливкой или обводкой.","use":"Для индикаторов, ручек управления и сигнальных точек."},"poly":{"what":"Произвольный многоугольник, заданный вершинами.","use":"Для пользовательских форм, меток и указателей."},"line":{"what":"Прямой отрезок между двумя точками.","use":"Для разделителей, соединений и осей графика."},"text":{"what":"Текст с произвольным расположением в DrawList.","use":"Для надписей с точным положением."},"triangle":{"what":"Треугольник с заливкой или обводкой.","use":"Для стрелок, значков воспроизведения и указателей."},"arc":{"what":"Дуговой сегмент окружности.","use":"Для круговых шкал, регуляторов и индикаторов."}}; @@ -2754,6 +2757,8 @@ // Entries added after the Russian branch was cut (dev.3): File > Language (dev.6) and the dev.4 / dev.5 additions // (checkbox row highlight, text-input frame border, hit-area choice, the new Preflight note). Merged over the table above. const UI_ADDED = { + "Failed to read project: The selected file could not be read.":"Не удалось прочитать проект: Не удалось прочитать выбранный файл.", + "Show more issues":"Показать ещё", "Language":"Язык", "Highlight row when checked":"Подсвечивать строку, когда флажок установлен", "Checked-row colour":"Цвет строки с установленным флажком", @@ -2771,6 +2776,7 @@ "Move it into a table cell, or turn the option off.":"Переместите его в ячейку таблицы или отключите параметр." }; Object.assign(UI, UI_ADDED); + PATTERNS.push([/^Failed to read project:/,'Не удалось прочитать проект:']); const HINTS_ADDED = { "cb:hit":"Область нажатия: только квадрат, вся строка таблицы (доступна, когда флажок находится в ячейке таблицы) или расширенная по горизонтали область. Она не часть квадрата: другие объекты могут её перекрывать и сохраняют собственные нажатия в REAPER. `Selectable` `SpanAllColumns` `AllowOverlap`", "frame-border-row":"Граница вокруг поля ввода: толщина и цвет. Выключено — как в теме (без границы). `PushStyleVar(StyleVar_FrameBorderSize)` `PushStyleColor(Col_Border)`", @@ -3095,7 +3101,7 @@ const rulerVCtx = rulerVEl ? rulerVEl.getContext('2d') : null; const canvasAreaEl = document.getElementById('canvas-area'); // Single source of truth for the semantic release version. Bump this line only. -const BUILD_VERSION='2.2.0'; +const BUILD_VERSION='2.2.3'; // Online user manual (English page; it links to the Russian version itself). // Paste the full https:// address between the quotes. Empty string hides Help > User Manual. const MANUAL_URL='https://reauibuilder.patch34.workers.dev/ReaUI_Builder_Manual_en'; @@ -3952,7 +3958,18 @@ return r; } // R(v) = floor(v + 0.5): JS Math.floor and Lua math.floor agree on every integer d (AD5). -function adaptiveRound(v){ return Math.floor(v + 0.5); } +const adaptiveFloor=Math.floor; +function adaptiveRound(v){ return adaptiveFloor(v + 0.5); } +// Shared cell-local arithmetic for Preview and the preflight interval resolver. +function resolveAdaptiveCellBox(s,cell,offset,k,delta){ + // C07: a fixed axis is overwhelmingly common while scanning the other one. + // Coefficients are finite contract values; retain the original arithmetic + // when the cell changes on that axis, including fractional cell deltas. + const fixedW=delta.dw===0,fixedH=delta.dh===0; + return {x:cell.x+offset.x+(fixedW?0:adaptiveFloor(k.kx*delta.dw+0.5)), + y:cell.y+offset.y+(fixedH?0:adaptiveFloor(k.ky*delta.dh+0.5)), + w:s.w+(fixedW?0:adaptiveFloor(k.kw*delta.dw+0.5)),h:s.h+(fixedH?0:adaptiveFloor(k.kh*delta.dh+0.5))}; +} // Resolved geometry of the whole scene for a canvas of CW x CH (design = cw x ch): // parent-relative x / y (what s.x / s.y mean) plus w / h. Never mutates shapes. // Absolute x' = absX + R(kx*dW); parent-relative = x' - parent's resolved absolute x. As @@ -3962,24 +3979,32 @@ // a cell is placed from the cell's resolved rect plus R(k*dWc) / R(k*dHc), with its // cell-relative coefficients (adaptiveCellCoeffsIn) and the cell's own size change // dWc = colW'(c) - colW(c), dHc = rowH'(r) - rowH(r). -function resolveAdaptiveView(CW, CH){ +// 2.2.3-dev.1 (audit 2.2.2 F02): opts.absolute returns the ABSOLUTE boxes {x, y, w, h} instead +// (Preflight measures shapes inside table cells on exactly the geometry Preview draws). +function resolveAdaptiveView(CW, CH, opts){ const dW = Math.floor(CW) - cw, dH = Math.floor(CH) - ch; - const byId = new Map(shapes.map(q => [q.id, q])); - const memo = new Map(), cellMemo = new Map(), abs = new Map(), cellDelta = new Map(), out = new Map(); + // C02: Preflight may resolve many sizes of the same immutable scene. Its private + // context reuses identity, coefficients and design positions, never resolved boxes. + const context=opts&&opts.context; + const byId = context?context.byId:new Map(shapes.map(q => [q.id, q])); + const memo = context?context.memo:new Map(), cellMemo = context?context.cellMemo:new Map(); + const abs = new Map(), cellDelta = new Map(), out = new Map(), tableLayouts=new Map(); + const design=s=>context?context.design.get(s.id):{x:getAbsoluteX(s),y:getAbsoluteY(s)}; // Resolved ABSOLUTE box of s (x, y absolute; w, h size). The design absolute box is the start. const absOf = s => { let r = abs.get(s.id); if(r) return r; - const ax = getAbsoluteX(s), ay = getAbsoluteY(s); + const {x:ax,y:ay}=design(s); abs.set(s.id, {x:ax, y:ay, w:s.w, h:s.h}); // cycle guard: a cyclic chain resolves as static const parent = s.parentId ? (byId.get(s.parentId) || null) : null; if(s.type === 'widget' && s.widgetType === 'TableCell' && parent && parent.type === 'widget' && parent.widgetType === 'Table'){ const t = absOf(parent); if(t.w === parent.w && t.h === parent.h){ - r = {x:t.x + (ax - getAbsoluteX(parent)), y:t.y + (ay - getAbsoluteY(parent)), w:s.w, h:s.h}; + const p=design(parent); + r = {x:t.x + (ax - p.x), y:t.y + (ay - p.y), w:s.w, h:s.h}; } else { - const rect = computeTableCellRect({...parent, w:t.w, h:t.h}, s.tableRow, s.tableCol); - const des = computeTableCellRect(parent, s.tableRow, s.tableCol); + const rect = computeTableCellRect({...parent, w:t.w, h:t.h}, s.tableRow, s.tableCol,tableLayouts); + const des = computeTableCellRect(parent, s.tableRow, s.tableCol,tableLayouts); cellDelta.set(s.id, {dw:rect.w - des.w, dh:rect.h - des.h}); r = {x:t.x + rect.x, y:t.y + rect.y, w:rect.w, h:rect.h}; } @@ -3988,12 +4013,8 @@ const cell = lk ? byId.get(lk.cellId) : null; if(lk && cell){ const c = absOf(cell), d = cellDelta.get(cell.id) || {dw:0, dh:0}; - r = { - x: c.x + (ax - getAbsoluteX(cell)) + adaptiveRound(lk.kx * d.dw), - y: c.y + (ay - getAbsoluteY(cell)) + adaptiveRound(lk.ky * d.dh), - w: s.w + adaptiveRound(lk.kw * d.dw), - h: s.h + adaptiveRound(lk.kh * d.dh), - }; + const p=design(cell); + r=resolveAdaptiveCellBox(s,c,{x:ax-p.x,y:ay-p.y},lk,d); } else { const k = adaptiveCoeffsIn(s, byId, memo); r = {x:ax + adaptiveRound(k.kx * dW), y:ay + adaptiveRound(k.ky * dH), @@ -4003,6 +4024,7 @@ abs.set(s.id, r); return r; }; + if(opts && opts.absolute){ for(const s of (opts.targets||shapes)) absOf(s); return abs; } for(const s of shapes){ const r = absOf(s); const parent = s.parentId ? (byId.get(s.parentId) || null) : null; @@ -7722,12 +7744,18 @@ // Relative-to-table rect for cell (r,c). Body sits below the optional column-label // band only (c63: the editor strip left the box). Inspector column/row sizing is used // directly, so the canvas mirrors the generated table geometry. -function computeTableCellRect(table, r, c){ - const band=getTableHeaderBandHeight(table); // 1.5.0: 18 + predicted angled row (angled tables only) - const bodyY=band; - const bodyH=Math.max(GRID, table.h-bodyY); - const cols=getTableColumnLayout(table,table.w); // 2.1.0-dev.2 (A08 S1): ImGui's columns - const heights=getResolvedTableRowHeights(table,bodyH); +function computeTableCellRect(table, r, c, layoutCache){ + // C02: one resolver pass visits all cells of a table. Share its column/row + // distribution at this exact size; never retain it across scene mutations. + const key=layoutCache?table.id+':'+table.w+':'+table.h:null; + let layout=layoutCache&&layoutCache.get(key); + if(!layout){ + const bodyY=getTableHeaderBandHeight(table); + const bodyH=Math.max(GRID,table.h-bodyY); + layout={bodyY,cols:getTableColumnLayout(table,table.w),heights:getResolvedTableRowHeights(table,bodyH)}; + if(layoutCache)layoutCache.set(key,layout); + } + const {bodyY,cols,heights}=layout; const col=cols[c]||{x:0,w:1}; const cellY=heights.slice(0,r).reduce((sum,value)=>sum+value,0); return { @@ -9941,9 +9969,8 @@ // Replacing the canvas destroys unsaved work. A plain "are you sure?" makes the // only safe answer Cancel -> save by hand -> start the action again, so the // save is offered inline as a third choice instead. -// Note: the browser's own save dialog can still be dismissed after "Save -// project", and there is no way to observe that from here — proceeding anyway -// matches how saveProject() behaves everywhere else in the app. +// Continue only after a successful save. Download-only browsers retain a local +// recovery copy because they cannot report whether a requested download completed. function uiConfirmDiscard(message, proceed, opts){ opts=opts||{}; showDialog({ title:opts.title||'Unsaved work', body:message, buttons:[ @@ -14190,9 +14217,10 @@ let projectRecoveryId = makeRecoveryId(); const currentStorageKey = () => STORAGE_PREFIX + projectRecoveryId; const liveSessions=new Set([SESSION_ID]); - const presenceChannel=typeof BroadcastChannel==='function' - ? new BroadcastChannel('reaui_builder_autosave_presence_v1') : null; - if(presenceChannel){ + let presenceChannel=null; + function openPresenceChannel(){ + if(presenceChannel || typeof BroadcastChannel!=='function') return; + presenceChannel=new BroadcastChannel('reaui_builder_autosave_presence_v1'); presenceChannel.addEventListener('message',event=>{ const msg=event.data||{}; if(!msg.sessionId||msg.sessionId===SESSION_ID) return; @@ -14203,6 +14231,7 @@ } }); } + openPresenceChannel(); const ENVELOPE_VERSION = 1; const MODULE_VERSION = 1; const SAVE_DELAY_MS = 800; @@ -14469,8 +14498,16 @@ if(presenceChannel){ presenceChannel.postMessage({type:'bye',sessionId:SESSION_ID}); presenceChannel.close(); + presenceChannel=null; } }); + // A page restored from the back/forward cache resumes the same module. Its + // closed channel must rejoin presence before other tabs offer its live draft. + window.addEventListener('pageshow', event => { + if(!event.persisted) return; + openPresenceChannel(); + if(presenceChannel) presenceChannel.postMessage({type:'ping',sessionId:SESSION_ID}); + }); window.addEventListener('beforeunload', event => { scanForUncommittedChanges(); if(!dirty)return; @@ -14494,7 +14531,8 @@ }, acceptLoadedProject, acceptNewProject, - hasUnsavedChanges: () => dirty, + // New/Open must also see mutations made since the 500 ms safety scan. + hasUnsavedChanges: () => {scanForUncommittedChanges();return dirty;}, // 1.6.0-dev.12: read-only probe for the startup chooser; Restore re-reads on click. hasRestorableDrafts: () => readStoredDrafts().some(d=>d.storageKey!==currentStorageKey()), hasSafeRecoveryDraft: () => draftSafe, @@ -14507,6 +14545,25 @@ let projectFileHandle=null; let projectFilename='reaper-ui-project.json'; let projectDocumentEpoch=0; +// 2.2.3-dev.2 (audit 2.2.2 F01): a load is a request with an identity. Reading the file is +// asynchronous after the picker closes, so a slow read could land on a newer document or on +// edits made in the meantime, reset history and mark the result clean. A result applies only +// if it is the latest load, the document epoch is unchanged, and the content is still the one +// the user agreed to replace. +let projectLoadToken=0; +function projectContentSnapshot(){ + try{ return JSON.stringify(serializeProjectCore()); }catch(_){ return null; } +} +function beginProjectLoad(){ + return {token:++projectLoadToken, epoch:projectDocumentEpoch, content:projectContentSnapshot()}; +} +function projectLoadIsCurrent(req){ + return req.token===projectLoadToken && req.epoch===projectDocumentEpoch && req.content===projectContentSnapshot(); +} +function reportStaleProjectLoad(req){ + if(req.token!==projectLoadToken) return; // a newer load replaced this one; it reports for itself + uiAlert('The project changed while the file was being read, so the file was not opened. Your current project is unchanged.','Load cancelled'); +} let projectSavePromise=null; const PROJECT_FILE_TYPES=[{description:'ReaUI project',accept:{'application/json':['.json']}}]; function downloadProjectCopy(filename){ @@ -14565,14 +14622,17 @@ return projectSavePromise; } async function openProjectWithHandle(replacement={}){ + const req=beginProjectLoad(); // 2.2.3-dev.2 (F01) try{ const [handle]=await window.showOpenFilePicker({multiple:false,types:PROJECT_FILE_TYPES}); const file=await handle.getFile(),project=JSON.parse(await file.text()); + if(!projectLoadIsCurrent(req)){ reportStaleProjectLoad(req); return false; } if(applyLoadedProject(project)===false) return false; projectFileHandle=handle;projectFilename=handle.name;projectDocumentEpoch++; resetHistory();resetZoomToActualSize();AUTOSAVE.acceptLoadedProject(file.name,replacement); return true; }catch(error){ + if(req.token!==projectLoadToken) return false; // superseded: its failure is not news if(error.name!=='AbortError') uiAlert('Could not load project: '+error.message,'Load failed'); return false; } @@ -14585,6 +14645,7 @@ } function _loadProjectPick(replacement={}){ if(typeof window.showOpenFilePicker==='function') return openProjectWithHandle(replacement); + const req = beginProjectLoad(); // 2.2.3-dev.2 (F01): same contract as openProjectWithHandle const input = document.createElement('input'); input.type = 'file'; input.accept = '.json'; @@ -14596,16 +14657,24 @@ reader.onload = (ev) => { try { const project = JSON.parse(ev.target.result); + if(!projectLoadIsCurrent(req)){ reportStaleProjectLoad(req); return; } if(applyLoadedProject(project)===false) return; resetHistory(); resetZoomToActualSize(); projectFileHandle=null;projectFilename=file.name;projectDocumentEpoch++; AUTOSAVE.acceptLoadedProject(file.name, replacement); // AUTOSAVE INTEGRATION HOOK } catch(err){ + if(!projectLoadIsCurrent(req)) return; uiAlert('Failed to load project: ' + err.message, 'Load failed'); } }; - reader.readAsText(file); + reader.onerror = () => { + if(!projectLoadIsCurrent(req)) return; + uiAlert('Failed to read project: ' + (reader.error?.message || 'The selected file could not be read.'), 'Load failed'); + }; + try{reader.readAsText(file);}catch(err){ + if(projectLoadIsCurrent(req))uiAlert('Failed to read project: ' + err.message, 'Load failed'); + } }; document.body.appendChild(input); input.click(); @@ -14716,6 +14785,34 @@ return {...point,x,y}; } +// 2.2.3-dev.3 (C01 / audit F03): import and Preflight share this pure validation +// boundary. Do not coerce objects or booleans, and never retain settings outside +// the table grid. A successful result is a fresh, bounded array; callers decide +// whether to adopt it (import) or only inspect it (Preflight). +function validateTableColumnConfig(table){ + const config=table.columnConfig; + const fail=(message,columnIndex=null)=>({value:null,problem:{message,columnIndex}}); + if(config===undefined) return {value:undefined,problem:null}; + if(!Array.isArray(config)) return fail('columnConfig must be an array.'); + const count=Number(table.columnCount===undefined?1:table.columnCount); + if(!Number.isInteger(count)||count<1||count>16) return fail('Table column count must be an integer from 1 to 16.'); + if(config.length>count) return fail('columnConfig has '+config.length+' entries for '+count+' columns; the first excess column setting is at index '+count+'.',count); + const value=[]; + for(let i=0;ifail('Invalid column setting at index '+i+': use null or fixed/stretch sizing with a finite, nonnegative number.',i); + if(typeof item!=='object'||Array.isArray(item)) return bad(); + if(item.sizing!=='fixed'&&item.sizing!=='stretch') return bad(); + const raw=item.value; + if(raw!==undefined&&typeof raw!=='number'&&typeof raw!=='string') return bad(); + const number=raw===undefined?0:Number(raw); + if(!Number.isFinite(number)||number<0) return bad(); + value.push({sizing:item.sizing,value:number}); + } + return {value,problem:null}; +} + function normalizeLoadedShape(raw,index){ if(!raw || typeof raw!=='object' || Array.isArray(raw)){ throw new Error('Shape '+(index+1)+' must be an object.'); @@ -14746,6 +14843,16 @@ return n; }); } + // 2.2.3-dev.3 (C01): validate before load commits; keep dev.2's numeric-string, + // null-entry and omitted-value semantics. Excess entries reject the entire load. + if(shape.columnConfig!==undefined){ + if(shape.widgetType!=='Table') delete shape.columnConfig; + else{ + const config=validateTableColumnConfig(shape); + if(config.problem) throw new Error('Shape '+(index+1)+': '+config.problem.message); + shape.columnConfig=config.value; + } + } // Family/variant are derived data. Never trust display or inspector routing fields // supplied by project JSON; rebuild them from the canonical widget type (F01). if(shape.type==='widget'){ @@ -22377,7 +22484,7 @@ ctx.fillText(labelText,x,y-2); } } else if(geo.previewFrameKind==='color-button-square'){ - ctx.fillStyle=def.color; + ctx.fillStyle=(typeof s.color==='string'&&s.color)?s.color:def.color; ctx.fillRect(x,y,w,h); ctx.strokeStyle=strong; ctx.strokeRect(x+1,y+1,w-2,h-2); @@ -23162,11 +23269,20 @@ // a silent wrong-file export. Generation now owns both buttons: nothing is // downloadable unless this run produced it. let exportCodeReady=false; +// 2.2.3-dev.2 (audit 2.2.2 F04): true after genImGui() threw in this dialog run. Preflight +// reads it, so a rerun (switching the UI language with the dialog open reruns Preflight) +// cannot show "Ready to export" over a failed generation. +let exportGenerationFailed=false; function setExportAvailable(ok){ exportCodeReady=!!ok; const c=document.getElementById('cbtn'), d=document.getElementById('dlbtn'); if(c) c.disabled=!exportCodeReady; if(d) d.disabled=!exportCodeReady; + if(exportCodeReady){ + exportGenerationFailed=false; + if(c) c.title='Copy generated Lua'; + if(d) d.title='Download generated Lua'; + } } function switchTab(t){ activeTab='imgui'; @@ -23178,6 +23294,9 @@ }catch(err){ out.textContent='Export failed: '+((err&&err.message)?err.message:String(err))+ '\n\nNothing was generated. The previous export is not shown and cannot be downloaded.'; + exportGenerationFailed=true; + const panel=document.getElementById('preflight-panel'), heading=document.getElementById('preflight-title'); + if(panel&&heading){ panel.dataset.state='blocked'; heading.textContent='Export failed: nothing was generated'; } return; } out.textContent=code; @@ -23212,6 +23331,7 @@ document.getElementById('modal-bg').classList.add('show'); toggleBasicExportCode(false); setExportAvailable(false); // nothing from an earlier run stays downloadable + exportGenerationFailed=false; // 2.2.3-dev.2 (F04): this run has not failed yet const report=EXPORT_PREFLIGHT.run(); // Validate before generation: malformed state must not crash the dialog. if(report.stats.errors){ document.getElementById('code-out').textContent='Export is blocked until the errors above are resolved.'; @@ -23296,6 +23416,33 @@ let currentIssues = []; let currentStats = {checked:0, exportable:0, errors:0, warnings:0}; + // C07: keep one immutable-model report. Rendering still reads generation state + // on every run, so a cache hit cannot revive an unavailable export (F04). + let reportCache=null,watchedFonts=null,fontRevision=0; + function reportCacheKey(){ + try{ + const fonts=document.fonts; + if(fonts!==watchedFonts){ + watchedFonts=fonts;fontRevision++; + if(fonts&&typeof fonts.addEventListener==='function'){ + const invalidate=()=>{if(fonts===watchedFonts){fontRevision++;reportCache=null;}}; + fonts.addEventListener('loadingdone',invalidate); + fonts.addEventListener('loadingerror',invalidate); + } + } + if(fonts&&fonts.status==='loading')return null; + let safe=true; + // Use raw shapes as well as the save metadata: serializeProjectCore omits + // undefined/functions, which must never hide malformed live-state changes. + const model=JSON.stringify({...serializeProjectCore(),shapes},(_,value)=>{ + const type=typeof value; + if(value===undefined||type==='function'||type==='symbol'||type==='bigint'||(type==='number'&&!Number.isFinite(value)))safe=false; + return value; + }); + return safe?fontRevision+'|'+(fonts?fonts.size:0)+'|'+(window.devicePixelRatio||1)+'|'+model:null; + }catch(_){return null;} + } + const copyIssues=list=>list.map(item=>({...item})); const own = (obj,key) => Object.prototype.hasOwnProperty.call(obj||{},key); const finite = value => value !== '' && value !== null && value !== undefined && Number.isFinite(Number(value)); @@ -23383,6 +23530,17 @@ const duplicateIds=new Set(); const structurallyUnsafe=new Set(); + // 2.2.3-dev.3 (C01): malformed live column settings are a prerequisite + // failure. Diagnose every affected table before geometry can consume them; + // no scene or configuration is normalized or mutated by this check. + shapes.forEach(s=>{ + if(s.type!=='widget'||s.widgetType!=='Table') return; + const config=validateTableColumnConfig(s); + if(config.problem) found.push(issue('error','invalid-table-column-config',s, + 'Invalid table column settings',config.problem.message)); + }); + if(found.length) return {issues:found,checked:shapes.length,exportable:0}; + if(!isCanonicalHexColor(bgColor)){ found.push(issue('error','invalid-background-color',null,'Project background colour is invalid','Use a hexadecimal colour in #RRGGBB format.')); } @@ -23666,17 +23824,53 @@ } // 1.8.0-dev.3 (A05, ADR-009 AD8): the resolved layout over the whole allowed window size. - // Each edge moves by R(k·d) (k ∈ {0, ½, 1}), so on one axis the offset between two edges is - // monotone in d and "overlaps on this axis" holds on one interval of d. The intervals are - // solved exactly over the integers (bisection on monotone predicates), not sampled, and the - // two axes are independent. Pairs that already overlap at the design size are reported - // above (widget-overlap), so only overlaps that appear while resizing are reported here. + // Outside table cells, R(k·d) (k ∈ {0, ½, 1}) gives monotone edge differences, + // so bisection solves the intervals. C02 uses measured integer intervals when + // a table cell is involved: column distribution can change that monotonicity. + // Axes are independent. Design-size overlaps are reported above (widget-overlap). if(windowResize!==null){ + const adFloor=Math.floor,adMin=Math.min,adMax=Math.max; + const adRound=adaptiveRound,adCellBox=resolveAdaptiveCellBox,adResolve=resolveAdaptiveView; const lim=getPreviewWindowLimits(); const rangeW=[lim.minW-cw, (windowResize.maxW!==undefined?windowResize.maxW:cw+8192)-cw]; const rangeH=[lim.minH-ch, (windowResize.maxH!==undefined?windowResize.maxH:ch+8192)-ch]; const adById=new Map(shapes.map(q=>[q.id,q])), adMemo=new Map(); const K=s=>adaptiveCoeffsIn(s,adById,adMemo); + // 2.2.3-dev.1 (audit 2.2.2 F02): a TableCell is a local root. adaptiveCoeffsIn gives the + // cell and its whole subtree kw = kh = 0, so K() alone never sees a size or position change + // that comes from the cell's own resize (a stretched table redistributing its columns / + // rows). Shapes in a cell are measured on the geometry Preview draws (resolveAdaptiveView), + // one axis at a time: a cell's x / w follow the table width only, its y / h the height only. + // Resolved edges also cover nested tables and fixed/stretch transitions; + // C02 measures their intervals without assuming monotone edge differences. + const adCellMemo=new Map(), resolvedAt=new Map(); + const cellOf=s=>{ + if(!s) return null; + if(s.type==='widget'&&s.widgetType==='TableCell') return s.id; + const lk=adaptiveCellCoeffsIn(s,adById,adCellMemo); + return lk?lk.cellId:null; + }; + const resolverContext={byId:adById,memo:adMemo,cellMemo:adCellMemo, + design:new Map(shapes.map(s=>[s.id,{x:getAbsoluteX(s),y:getAbsoluteY(s)}]))}; + const resolvedBox=(s,axis,d)=>{ + const key=axis+d; + let view=resolvedAt.get(key); + if(!view){ view=adResolve(axis==='x'?cw+d:cw, axis==='y'?ch+d:ch, {absolute:true,context:resolverContext}); resolvedAt.set(key,view); } + return view.get(s.id)||null; + }; + // Same [start, end] contract as edges() below, driven by s's resolved geometry instead of + // R(k·d). box is s's design box on the canvas (a footprint or an interior rect); it moves + // and grows by exactly as much as s does. + const cellEdges=(s,box,axis)=>{ + const pos=axis==='x'?box.x:box.y, len=axis==='x'?box.w:box.h; + const a0=axis==='x'?getAbsoluteX(s):getAbsoluteY(s), l0=Number(axis==='x'?s.w:s.h); + return d=>{ + const r=d===0?null:resolvedBox(s,axis,d); + if(!r) return [pos,pos+len]; + const dp=(axis==='x'?r.x:r.y)-a0, dl=(axis==='x'?r.w:r.h)-l0; + return [pos+dp, pos+dp+len+dl]; + }; + }; // Integer sub-range of [r0, r1] where a monotone predicate holds, or null. const halfLine=(pred,r0,r1)=>{ const a=pred(r0), b=pred(r1); @@ -23691,7 +23885,7 @@ const edges=(box,k,axis)=>{ const pos=axis==='x'?box.x:box.y, len=axis==='x'?box.w:box.h; const kp=axis==='x'?k.kx:k.ky, kl=axis==='x'?k.kw:k.kh; - return d=>{ const s=pos+adaptiveRound(kp*d); return [s, s+len+adaptiveRound(kl*d)]; }; + return d=>{ const s=pos+adRound(kp*d); return [s, s+len+adRound(kl*d)]; }; }; const D0={x:cw,y:ch}; const sizeText=(axis,p,q,r)=>{ @@ -23701,23 +23895,149 @@ return p<=r[0] ? (base+q)+' px '+word+' or '+less : 'from '+(base+p)+' to '+(base+q)+' px '+word; }; const moving=k=>!!(k.kx||k.kw||k.ky||k.kh); + // C02: different cells and outside controls do not share one linear frame. + // Fixed/stretch transitions can reverse an edge difference, so halfLine is + // not a valid solver for these pairs. Enumerate integer sizes once per axis + // into compact edge arrays, then reuse them for every pair and container. + // A very large explicit range is reported as partial rather than freezing + // the UI or claiming that unexamined sizes are safe. The existing no-Max + // horizon (design + 8192) is unchanged. + const cellShapes=shapes.filter(s=>cellOf(s)!==null), sequences=new Map(), edgeDescriptors=new Map(); + const cellRoots=cellShapes.filter(s=>s.type==='widget'&&s.widgetType==='TableCell'); + const rootIndex=new Map(cellRoots.map((s,i)=>[s.id,i])),designLayouts=new Map(); + const roots=cellRoots.map(s=>{ + const parent=adById.get(s.parentId); + return {s,parent,rect:parent&&parent.widgetType==='Table'?computeTableCellRect(parent,s.tableRow,s.tableCol,designLayouts):s}; + }); + const cellSpecs=cellShapes.map(s=>{ + if(rootIndex.has(s.id))return {s,root:rootIndex.get(s.id),managed:true}; + const k=adaptiveCellCoeffsIn(s,adById,adCellMemo),p=resolverContext.design.get(s.id),c=resolverContext.design.get(k.cellId); + return {s,root:rootIndex.get(k.cellId),k,offset:{x:p.x-c.x,y:p.y-c.y}}; + }); + const TABLE_AXIS_SCAN_MAX=32768; + const scanRange=axis=>{ + const r=axis==='x'?rangeW:rangeH; + return [r[0],Math.min(r[1],r[0]+TABLE_AXIS_SCAN_MAX-1)]; + }; + const prepareAxis=axis=>{ + if(sequences.has(axis)) return sequences.get(axis); + const r=scanRange(axis), count=r[1]-r[0]+1, data=new Map(); + for(const s of cellShapes) data.set(s.id,{start:new Float64Array(count),end:new Float64Array(count)}); + const rootBoxes=[],deltas=roots.map(()=>({dw:0,dh:0})); + for(let i=0;i{ + let b; + if(lo===hi)b=q.blocks[lo]; + else{ + const mid=adFloor((lo+hi)/2),a=build(node*2,lo,mid),c=build(node*2+1,mid+1,hi); + b=[adMin(a[0],c[0]),adMax(a[1],c[1]),adMin(a[2],c[2]),adMax(a[3],c[3])]; + } + q.tree.set(b,node*4);return b; + }; + build(1,0,q.blocks.length-1); + } + const all=axis==='x'?rangeW:rangeH; + if(r[1]{ + const cacheKey=axis+'|'+s.id+'|'+box.x+'|'+box.y+'|'+box.w+'|'+box.h; + if(edgeDescriptors.has(cacheKey))return edgeDescriptors.get(cacheKey); + const keep=edge=>{ + const node=edge.node,cache=new Map(); + edge.node=(i,lo,hi)=>{if(!cache.has(i))cache.set(i,node(i,lo,hi));return cache.get(i);}; + edgeDescriptors.set(cacheKey,edge);return edge; + }; + const r=scanRange(axis); + if(cellOf(s)===null){ + const k=K(s),pos=axis==='x'?box.x:box.y,len=axis==='x'?box.w:box.h; + const kp=axis==='x'?k.kx:k.ky,kl=axis==='x'?k.kw:k.kh; + const start=d=>pos+adRound(kp*d),end=d=>start(d)+len+adRound(kl*d); + const bounds=(a,b)=>[adMin(start(a),start(b)),adMax(start(a),start(b)),adMin(end(a),end(b)),adMax(end(a),end(b))]; + return keep({start,end,node:(i,lo,hi)=>bounds(r[0]+lo*64,Math.min(r[1],r[0]+hi*64+63))}); + } + const q=prepareAxis(axis).data.get(s.id), p=resolverContext.design.get(s.id); + const shift=(axis==='x'?box.x-p.x:box.y-p.y), tail=shift+(axis==='x'?box.w-s.w:box.h-s.h); + const start=d=>q.start[d-r[0]]+shift,end=d=>q.end[d-r[0]]+tail; + return keep({start,end,node:i=>{const k=i*4,b=q.tree;return [b[k]+shift,b[k+1]+shift,b[k+2]+tail,b[k+3]+tail];}}); + }; + const measuredRelation=(x,y,axis,outside=false)=>{ + const r=scanRange(axis),out=[]; + const add=(lo,hi)=>{const last=out[out.length-1];if(last&&last[1]+1===lo)last[1]=hi;else out.push([lo,hi]);}; + const classify=(p,q)=>outside + ? (p[0]>=q[1]&&p[3]<=q[2]?0:p[1]q[3]?1:-1) + : (p[0]>=q[3]||q[0]>=p[3]?0:p[1]{ + const a=r[0]+lo*64,b=adMin(r[1],r[0]+hi*64+63),state=classify(x.node(node,lo,hi),y.node(node,lo,hi)); + if(state===0)return; + if(state===1){add(a,b);return;} + if(lo!==hi){const mid=adFloor((lo+hi)/2);visit(node*2,lo,mid);visit(node*2+1,mid+1,hi);return;} + let first=null; + for(let d=a;d<=b;d++){ + const hit=outside?x.start(d)y.end(d):x.start(d)measuredRelation(measuredEdges(A,a,axis),measuredEdges(B,b,axis),axis); + const describeIntervals=(axis,list,r)=>{ + const text=list.map(p=>sizeText(axis,p[0],p[1],r)).join(' or '); + return list.length>1?'('+text+')':text; + }; + const covers=(list,r)=>list.length===1&&list[0][0]===r[0]&&list[0][1]===r[1]; // adaptive-overlap for(let i=0;iax(d)[0]bx(d)[0]ay(d)[0]by(d)[0]{ + if(cellDriven)return measuredOverlap(A,boxA,B,boxB,axis); + const a=edges(boxA,kA,axis),b=edges(boxB,kB,axis),r=axis==='x'?rangeW:rangeH; + const p=meet(halfLine(d=>a(d)[0]b(d)[0]{ const a=box.x+adaptiveRound(kS.kx*d); return [a, a+GRID]; }) - : edges(box,kS,axis); - const pe=edges(frame,kP,axis); + ? (d=>{ const a=sEdges(d)[0]; return [a, a+GRID]; }) + : sEdges; + const pe=inCell?cellEdges(parent,frame,axis):edges(frame,kP,axis); if(!(se(0)[0]>=pe(0)[0]&&se(0)[1]<=pe(0)[1])) return; // not inside at the design size: not ours + if(inCell){ + let a=measuredEdges(s,box,axis);const b=measuredEdges(parent,frame,axis); + if(axis==='x'&&s.widgetType==='CollapsingHeader'){ + const original=a;a={...a,end:d=>original.start(d)+GRID,node:(...args)=>{const p=original.node(...args);return [p[0],p[1],p[0]+GRID,p[1]+GRID];}}; + } + const outside=measuredRelation(a,b,axis,true); + if(outside.length)parts.push(describeIntervals(axis,outside,r)); + continue; + } const inside=meet(halfLine(d=>se(d)[0]>=pe(d)[0],...r), halfLine(d=>se(d)[1]<=pe(d)[1],...r)); if(!inside) continue; if(inside[0]>r[0]) parts.push(sizeText(axis,r[0],inside[0]-1,r)); @@ -23779,6 +24111,22 @@ 'Too small at the minimum window size', 'Stretched with the window, it is ' + wMin + ' × ' + hMin + ' px at ' + lim.minW + ' × ' + lim.minH + ', below its minimum of ' + mn.minW + ' × ' + mn.minH + ' px. Raise Min width / height, or make it larger at the design size.')); }); + // 2.2.3-dev.1 (audit 2.2.2 F02): the same floor for shapes a table cell resizes. K() is + // zero for them, so the check above never reached them, and a button stretched in a + // shrinking cell exported a negative width. Measured on the resolved geometry (Preview's). + exportableShapes.forEach(s=>{ + if(isParentManagedShape(s)||cellOf(s)===null) return; + if(!(isWidgetShape(s) || (isPrimitiveShape(s) && (s.type==='rect' || s.type==='text')))) return; + const rx=resolvedBox(s,'x',lim.minW-cw), ry=resolvedBox(s,'y',lim.minH-ch); + if(!rx||!ry) return; + const w0=Number(s.w), h0=Number(s.h), wMin=rx.w, hMin=ry.h; + const mn=(isWidgetShape(s) && isCanonicalWidgetContainer(s)) ? getContainerMinResize(s) : {minW:GRID,minH:GRID}; + // Only an axis the cell actually shrinks is subject to the floor. + if((wMin>=w0 || wMin>=mn.minW) && (hMin>=h0 || hMin>=mn.minH)) return; + found.push(issue('error','adaptive-too-small',s, + 'Too small at the minimum window size', + 'Stretched with its table cell, it is ' + wMin + ' × ' + hMin + ' px at ' + lim.minW + ' × ' + lim.minH + ', below its minimum of ' + mn.minW + ' × ' + mn.minH + ' px. Raise Min width / height, give its column or row more room, or reduce the space around it in the cell.')); + }); } } @@ -23952,10 +24300,14 @@ return {issues:found, checked:shapes.length, exportable}; } + // 2.2.3-dev.2 (audit 2.2.2 F04): a clean Preflight is not a generated script. Both are + // required. When Preflight runs first (openModal), the buttons stay off until switchTab() + // succeeds; setExportAvailable(true) then arms them and restores their titles. function setExportEnabled(enabled){ + const ready=enabled&&exportCodeReady; const copy=document.getElementById('cbtn'), download=document.getElementById('dlbtn'); - if(copy){ copy.disabled=!enabled; copy.title=enabled?'Copy generated Lua':'Resolve the errors above to enable copy'; } - if(download){ download.disabled=!enabled; download.title=enabled?'Download generated Lua':'Resolve the errors above to enable download'; } + if(copy){ copy.disabled=!ready; copy.title=ready?'Copy generated Lua':enabled?'Nothing was generated, so there is nothing to copy':'Resolve the errors above to enable copy'; } + if(download){ download.disabled=!ready; download.title=ready?'Download generated Lua':enabled?'Nothing was generated, so there is nothing to download':'Resolve the errors above to enable download'; } } function focusIssue(item){ @@ -24009,6 +24361,8 @@ else if(skipped){ panel.dataset.state='warning'; title.textContent=skipped+' element'+(skipped===1?'':'s')+' will not be exported'; } else if(warnings){ panel.dataset.state='warning'; title.textContent='Ready with '+warnings+' warning'+(warnings===1?'':'s'); } else { panel.dataset.state='ready'; title.textContent='Ready to export'; } + // 2.2.3-dev.2 (F04): Preflight passed, but this run's generation did not. + if(!blocked && exportGenerationFailed){ panel.dataset.state='blocked'; title.textContent='Export failed: nothing was generated'; } meta.textContent=exportable+' of '+checked+' element'+(checked===1?'':'s')+' will export'; setExportEnabled(!blocked); @@ -24017,7 +24371,16 @@ const empty=document.createElement('div'); empty.className='preflight-empty'; empty.textContent='No export blockers or warnings detected.'; list.appendChild(empty); return; } - currentIssues.forEach(item=>{ + // C07: retain every diagnostic in the model and progressively add DOM rows. + // Severity sorting keeps blockers first; counters always show the full total. + const issues=currentIssues;let visible=0,more=null; + const appendIssues=()=>{ + if(issues!==currentIssues)return; + if(more)more.remove(); + const limit=Math.min(issues.length,visible+Math.max(200,visible)); + const fragment=document.createDocumentFragment(); + for(;visiblefocusIssue(item); } @@ -24027,12 +24390,23 @@ const detail=document.createElement('span'); detail.className='preflight-detail'; detail.textContent=item.detail; copy.appendChild(msg); if(item.detail) copy.appendChild(detail); const target=document.createElement('span'); target.className='preflight-target'; target.textContent=item.target; - row.appendChild(sev); row.appendChild(copy); row.appendChild(target); list.appendChild(row); - }); + row.appendChild(sev); row.appendChild(copy); row.appendChild(target); fragment.appendChild(row); + } + if(visiblex.severity==='warning').length, }; renderReport(); - return {issues:currentIssues.slice(),stats:{...currentStats}}; + return {issues:copyIssues(currentIssues),stats:{...currentStats}}; } function open(){ run(); } document.getElementById('preflight-rerun').addEventListener('click',run); - return {open,run,getReport:()=>({issues:currentIssues.slice(),stats:{...currentStats}})}; + return {open,run,getReport:()=>({issues:copyIssues(currentIssues),stats:{...currentStats}})}; })(); // ════════════════════════════════════════════════════════════════════════════ // END EXPORT PREFLIGHT — SELF-CONTAINED MODULE @@ -26327,6 +26701,10 @@ L.push(_menuBarExport ? ` reaper.ImGui_PushStyleVar(ctx, reaper.ImGui_StyleVar_ItemSpacing(), 8, 0)` : ` reaper.ImGui_PushStyleVar(ctx, reaper.ImGui_StyleVar_ItemSpacing(), 0, 0)`); + // 2.2.1: no window border. With a 1px border the canvas child is clipped 1px inside the + // window on every side, while rects (clip rect intersect=false) paint over the border. + // Border 0 makes the exported canvas exactly W x H, like the editor. + L.push(` reaper.ImGui_PushStyleVar(ctx, reaper.ImGui_StyleVar_WindowBorderSize(), 0)`); if(_reaBgExport){ L.push(` reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_WindowBg(), BG)`); } @@ -26357,7 +26735,7 @@ L.push(` reaper.ImGui_PopStyleColor(ctx)`); }; if(chromePushes.length) L.push(` reaper.ImGui_PopStyleColor(ctx, ${chromePushes.length})`); - L.push(` reaper.ImGui_PopStyleVar(ctx, 2)`); + L.push(` reaper.ImGui_PopStyleVar(ctx, 3)`); L.push(` if visible then`); // 1.6.0 (ADR-007 M3/M5): the menu bar, before the canvas child. It is drawn in the // outer window, so it pushes ##Canvas down as a whole and no widget coordinate moves. @@ -26594,7 +26972,13 @@ const scrollY=!!(s.tableFlags&&s.tableFlags.ScrollY); // 2.1.0-dev.1 (A07): cell padding (S5), stretch (S2/S3), rows keep their height (S4), // row backgrounds and the highlight hook (S6). None of them = the 2.0.0 lines. - const cellPad=tableHasCustomCellPadding(s)?getTableCellPadding(s):null; + // C02: default padding is still a table-owned value. If an enclosing + // table pushed custom padding, explicitly restore this table's own + // pair so nested helpers and cell rebasing agree with Preview. + const ownCellPad=getTableCellPadding(s); + const enclosingTable=getParentChain(s).find(q=>q.widgetType==='Table'); + const enclosingPad=enclosingTable?getTableCellPadding(enclosingTable):null; + const cellPad=tableHasCustomCellPadding(s)||(enclosingPad&&(enclosingPad[0]!==ownCellPad[0]||enclosingPad[1]!==ownCellPad[1]))?ownCellPad:null; const tStretch=exportTableStretch(s), tStretched=tStretch.w||tStretch.h; const nofill=tableRowsKeepHeight(s); const hlCol=getTableHighlightColor(s); diff --git a/ReaUI_Builder_2_2_3.html b/ReaUI_Builder_2_2_3.html new file mode 100644 index 0000000..011b25b --- /dev/null +++ b/ReaUI_Builder_2_2_3.html @@ -0,0 +1,27568 @@ + + + + + + +ReaUI Builder + + + + + + + + + +
+ +
+ +
+ +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+
+
+ + + + + + + +
+
+ + +
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+ +
+
+ + +
+
+ + +
+ + +
+
+ +
⇲
+ +
+
+
⇲
+
+
+
Preview is approximate — hatched widgets are shown schematically
+
+ +
+
+ +
+
+ + − + + + ⤢ +
+
+
+ select + + +
+
+
X:—
+
Y:—
+
W:—
+
H:—
+
+
⊞ Snap:On
+
+ 0 elements + +
+
+ + No unsaved changes +
+
+ + + + +
+
+ + + + + + diff --git a/docs/Export_Gate_v13_QA_EN.md b/docs/Export_Gate_v13_QA_EN.md new file mode 100644 index 0000000..32c3a5a --- /dev/null +++ b/docs/Export_Gate_v13_QA_EN.md @@ -0,0 +1,53 @@ +# ReaUI Builder v2.2.3 — Export Gate v13 correction and verification + +Date: 2026-11-13 (Asia/Tbilisi) + +## Decision + +**PASS in the tested Chromium adaptation scope.** The v13 fixture correction resolves the pre-existing `tables-b` save/reload failure. All 36 runnable original scenes pass against both accepted `2.2.3-dev.6` and release `2.2.3`. An unmodified Node/jsdom v13 run remains unverified because the `jsdom` dependency is not installed and external package retrieval is blocked. Five external `examples.*` fixtures are missing, so full 41-scene acceptance cannot be claimed. + +## Identity and immutability + +| Artifact | SHA-256 | +| --- | --- | +| Original v12 gate (retained) | `67eb52214b372fe655ef9a4378789c8676ee331bcff6542d11812c4a95b98f6a` | +| Corrected v13 gate | `5f8f0301c90e15253516a646f8b47d25343a03e8371d6d72d32b9790a802ef0f` | +| Accepted dev.6 HTML (unchanged) | `8e7a9c67051af09d58b336c84e091dcdf6ce706351b257a4ad55dbbbffe9c659` | +| Release v2.2.3 HTML (unchanged) | `3515ee4f2f7f97e91e2c71dbe9c388d59a87a9e1ac92e55959a84367e62b9eff` | + +## Exact fixture change + +`buildTablesB()` originally called `H.resizeTable` only for a changed row count, **before** assigning the Table's feature values (`angledHeaders`, `scrollRows`). The live TableCell geometry could therefore be stale while `genImGui()` was called before save. Reload rebuilt that geometry and changed export positions. + +v13 removes that early conditional refresh and calls `H.resizeTable(t, rowCount)` **once for every table after all Table property assignments** and before placing the nested Button in `tb_angled_scroll`. This reuses the test bridge's existing `ensureTableCells` and `syncTableCellBounds` implementation. It is a fixture-order correction, not an HTML/JS exporter change. + +The sole modified scene is `tables-b`, whose export/model hashes now represent the refreshed geometry. `tables-b.explicit-defaults` and every other scene retain the same exports and model hashes as v12. + +## Evidence table + +| Test channel | Release 2.2.3 | Dev.6 | +| --- | --- | --- | +| Chromium-adapted original scenes | 36/36 PASS | 36/36 PASS | +| Same-state determinism | 36/36 PASS | 36/36 PASS | +| Save → Reset → Load → Lua equality | 36/36 PASS | 36/36 PASS | +| Four original-style pair checks (`wave-a`, `wave-b`, `tables-b`, `tables-c`) | 4/4 PASS | 4/4 PASS | +| Additional G5/cross-scene/theming checks | 7/7 PASS | 7/7 PASS | +| Original five `examples.*` scenes | NOT RUN | NOT RUN | +| Original Node/jsdom CLI v13 | NOT RUN | NOT RUN | + +Result parity: all 36 release/dev.6 scene hashes (`genImGui`, `genSeed`, serialized file) and verdicts are identical. No failures or page exceptions in these Chromium runs. + +A `v12` versus `v13` result comparison shows **one changed scene, `tables-b`**, and no other altered scene hashes. In `v12` its roundtrip was FAIL, in v13 PASS. The historical baseline 2.2.2 also passes the corrected `tables-b` fixture; this supports the interpretation that the original test fixture, rather than v2.2.3 release code, caused the historical difference. + +The seven additional Chromium checks cover `G5 alpha-255`, `G5 menus defaults`, `G5 menus empty-vs-none`, `G5 title`, `G5 adaptive`, `adaptive inert`, and theme-library separation. The adapter uses the original scene data and bridge, but the test runner, page navigation and storage shim differ from Node/jsdom; results are not described as exact Node-gate execution. + +## Remaining release conditions + +- Obtain the five original frozen example fixtures if 41/41 gate coverage is required. +- Run `export_gate_v13.js` in the intended Node.js/jsdom environment, first with `--scene tables-b`, then with all scenes and the original examples, to establish an exact native gate exit code. +- Preserve original `export_gate_v12.js` and its known FAIL as historical evidence; do not rewrite golden outputs silently. +- No further ReaUI Builder HTML changes are justified by this fixture-only correction; no GitHub/ReaPack publishing action has been taken. + +## Reproducibility + +See `README_RU.md`, `v12_to_v13.patch`, `results/verification_summary.json`, the two 36-scene JSON result files and the extended cross-check reports. Tests performed against the exact SHA-256 identities above. diff --git a/docs/index.html b/docs/index.html index 9a6bade..6f621bf 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1257,6 +1257,9 @@ .preflight-msg{display:block;font-size:11.5px;font-weight:600;line-height:1.35} .preflight-detail{display:block;margin-top:2px;font-size:10.5px;line-height:1.4;color:var(--text-2)} .preflight-target{max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:var(--font-mono);font-size:9.5px;color:var(--text-2)} +.preflight-more{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:8px 10px;color:var(--text-2);font-size:11px} +.preflight-more button{padding:5px 9px;border:1px solid var(--color-border-soft);border-radius:4px;background:transparent;color:var(--text-0);font:inherit;cursor:pointer} +.preflight-more button:hover{background:var(--accent-bg)} #cbtn:disabled,#dlbtn:disabled{opacity:.42;cursor:not-allowed} /* ═══════════════════════════════════════════════════════════════════════════ END EXPORT PREFLIGHT — STYLES @@ -2764,7 +2767,7 @@ // ── Dictionary (built lazily, so an English session never allocates it) ─────────────── function dictionary(){ if(D) return D; - const UI = {"Start in ReaUI Builder":"Начало работы в ReaUI Builder","Choose the interface mode, then create a new project or open an existing one.":"Выберите режим интерфейса, затем создайте новый проект или откройте существующий.","Basic":"Базовый","Advanced":"Расширенный","A simpler workspace with the core components and settings.":"Упрощённая рабочая область с основными компонентами и настройками.","The complete editor with all components, tools and settings.":"Полный редактор со всеми компонентами, инструментами и параметрами.","The display mode can be changed at any time from":"Режим интерфейса можно в любой момент изменить через","View":"Вид",". It does not change the project file.":". Это не изменяет файл проекта.","Restore unsaved project…":"Восстановить несохранённый проект…","Open project…":"Открыть проект…","Create new project":"Создать проект","Interface mode":"Режим интерфейса","File":"Файл","New Project":"Создать проект","Save Project":"Сохранить проект","Save As…":"Сохранить как…","Restore projects…":"Восстановить проекты…","Load Project":"Открытие проекта","Edit":"Правка","Undo":"Отменить","Redo":"Повторить","Copy":"Копировать","Paste":"Вставить","Delete":"Удалить","Duplicate":"Дублировать","Group selection":"Сгруппировать выделенное","Ungroup selection":"Разгруппировать","Select All":"Выделить всё","Deselect All":"Снять выделение","Clear All":"Очистить всё","Dark mode":"Тёмная тема","Theme Studio…":"Редактор тем…","Grid":"Сетка","Snap to grid":"Привязка к сетке","Reference grid in export":"Сетка в экспортируемом интерфейсе","Hide widget names":"Скрыть имена виджетов","Hide draw objects names":"Скрыть имена графических объектов","Widget footprints":"Границы виджетов","Show hints":"Показывать подсказки","Panels":"Панели","Canvas":"Холст","Properties":"Свойства","Elements":"Элементы","Tools":"Инструменты","Zoom to fit":"Вписать в окно","Actual size (100%)":"Фактический размер (100 %)","Help":"Справка","User Manual ↗":"Руководство пользователя ↗","Keyboard Shortcuts":"Сочетания клавиш","Report a Bug…":"Сообщить об ошибке…","About":"О программе","Export":"Экспорт","Buttons & Toggles":"Кнопки и переключатели","Display":"Отображение","Fields":"Поля ввода","Sliders & Drags":"Ползунки и числовые поля","Selection":"Выбор","Color":"Цвет","Layout":"Компоновка","Add":"Добавить","Choose a component":"Выберите компонент","Then click or drag on the canvas to place it.":"Затем щёлкните или протяните указатель на холсте, чтобы разместить его.","Text Input":"Текстовое поле","Number Input":"Числовое поле","Dropdown":"Выпадающий список","Progress":"Выполнение","More components…":"Другие компоненты…","Select":"Выделение","Hand":"Рука","Zoom":"Масштаб","Rectangle":"Прямоугольник","Circle":"Окружность","Polygon":"Многоугольник","Line":"Линия","Triangle":"Треугольник","Arc":"Дуга","Header":"Заголовок","Tree":"Дерево","Default":"По умолчанию","Themes":"Темы","Choose a theme for the ReaImGui UI you will export.":"Выберите тему для экспортируемого интерфейса ReaImGui.","+ New":"+ Создать","Import":"Импорт","Edit…":"Изменить…","Editor":"Редактор","Preview":"Предпросмотр","Preview is approximate — hatched widgets are shown schematically":"Предпросмотр приблизительный — заштрихованные виджеты показаны схематично","Advanced canvas settings are active":"Используются расширенные параметры холста","Some canvas settings are hidden in Basic mode but remain part of this project.":"Некоторые параметры холста скрыты в базовом режиме, но сохранены в проекте.","Edit in Advanced":"Изменить в расширенном режиме","size":"размер","Width":"Ширина","Height":"Высота","background":"фон","grid":"сетка","Show grid":"Показывать сетку","Audit grid":"Контрольная сетка","color":"цвет","Opacity":"Прозрачность","Snap":"Привязка","Step":"Шаг","title bar":"строка заголовка","ImGui default":"По умолчанию ImGui","Theme colours":"Цвета темы","window":"окно","Resizable window":"Изменяемый размер окна","Min width":"Мин. ширина","Min height":"Мин. высота","Max width":"Макс. ширина","Max height":"Макс. высота","menu bar":"строка меню","+ Add menu":"+ Добавить меню","No menu bar. Add a menu to give the window a menu bar; the canvas keeps its size and nothing on it moves.":"Строка меню отсутствует. Добавьте меню, чтобы оно появилось в окне. Размер холста и расположение объектов не изменятся.","No element selected":"Элемент не выбран","Select one object on the canvas to edit its properties here.":"Выберите объект на холсте, чтобы изменить его свойства.","Multiple selection":"Выделено несколько объектов","Edit shared properties together.":"Редактируйте общие свойства объектов одновременно.","Move selection":"Переместить выделенное","move":"Переместить","Common properties":"Общие свойства","Mixed fields stay unchanged until you enter a value. Each edit is one undo step.":"Поля с различающимися значениями не изменяются, пока вы не введёте новое значение. Каждое изменение можно отменить отдельно.","delete selected":"Удалить выделенное","Advanced component":"Расширенный компонент","Some settings are available in Advanced mode.":"Некоторые настройки доступны только в расширенном режиме.","Configuring":"Настройка","Reset":"Сбросить","Click on canvas to place":"Щёлкните на холсте, чтобы разместить","Select a widget to preview":"Выберите виджет для предпросмотра","variant":"вариант","name":"имя","parent":"родительский объект","tabs":"вкладки","+ add tab":"+ добавить вкладку","table grid":"сетка таблицы","columns":"столбцы","row heights":"высота строк","label / text":"подпись / текст","placeholder":"замещающий текст","value":"значение","url":"URL","direction":"направление","value components":"компоненты значения","array size":"размер массива","min":"мин.","max":"макс.","speed":"скорость","step":"шаг","step fast":"ускоренный шаг","format":"формат","format min":"формат минимума","format max":"формат максимума","flags":"флаги","Clamp":"Ограничить","Log":"Логарифм.","NoInput":"Без ввода","Wrap":"Зациклить","hint":"подсказка","prefix bullet":"маркер в начале","highlight":"подсветка","disabled (BeginDisabled)":"отключено (BeginDisabled)","look":"вид","tree lines":"линии дерева","None":"Нет","Full":"Full","To nodes":"До узлов","tab button":"кнопка вкладки","Leading":"В начале","Trailing":"В конце","button label":"подпись кнопки","text tone":"цвет текста","Auto":"Авто","Dark":"Тёмный","Light":"Светлый","border":"граница","draw border":"рисовать границу","h-scroll":"горизонтальная прокрутка","horizontal scrollbar":"горизонтальная полоса прокрутки","text color":"цвет текста","frame bg":"фон элемента","button color":"цвет кнопки","rounding":"скругление","frame padding":"внутренние отступы","selectable align":"выравнивание элемента","font":"шрифт","sans-serif":"без засечек","serif":"с засечками","monospace":"моноширинный","cursive":"курсивный","fantasy":"декоративный","alpha":"альфа-канал","overlay":"наложенный текст","indeterminate":"неопределённый прогресс","animate":"анимация","EEL2 callback":"обработчик EEL2","group":"группа","flag group":"группа флагов","bit (0–30)":"бит (0–30)","values":"значения","scale min":"мин. шкалы","scale max":"макс. шкалы","text align":"выравнивание текста","left":"слева","center":"по центру","right":"справа","text size":"размер текста","vertical align":"выравнивание по вертикали","top":"сверху","middle":"по центру","bottom":"снизу","fill & stroke":"заливка и обводка","fill":"заливка","disable":"отключить","stroke":"обводка","thickness":"толщина","opacity":"прозрачность","hdr color":"цвет заголовка","default":"по умолчанию","custom":"пользовательский","hdr color val":"цвет заголовка","orient":"ориентация","angles (°)":"углы (°)","start":"начало","end":"конец","Link":"Связать","mode":"режим","ring":"кольцо","pie":"сектор","position":"положение","poly points":"вершины многоугольника","primitive order":"порядок отрисовки","back":"на задний план","backward":"назад","forward":"вперёд","front":"на передний план","delete":"удалить","select":"выделение","On":"Вкл.","Off":"Выкл.","0 elements":"0 элементов","No unsaved changes":"Нет несохранённых изменений","copy":"копировать","download .lua":"скачать .lua","Show code":"Показать код","Hide code":"Скрыть код","close":"закрыть","ReaUI Builder checks the project first, then exports the same ReaImGui Lua script as Advanced mode.":"Сначала ReaUI Builder проверит проект, затем экспортирует тот же Lua-скрипт ReaImGui, что и в расширенном режиме.","Checking export…":"Проверка перед экспортом…","Run again":"Проверить снова","Requires ReaImGui — install it via ReaPack.":"Требуется ReaImGui — установите его через ReaPack.","Colours of the exported plugin — not the builder's own look":"Цвета экспортируемого плагина, а не самого редактора","Hide service names of widgets in Editor":"Скрыть служебные имена виджетов в редакторе","Hide service names of draw objects in Editor":"Скрыть служебные имена графических объектов в редакторе","Open the online user manual in your browser":"Открыть руководство пользователя в браузере","Add components":"Добавить компоненты","Hand — drag to pan":"Рука — перетаскивайте для перемещения по холсту","Zoom — click to zoom in, Alt/Option + click to zoom out":"Масштаб — щелчок для увеличения, Alt/Option + щелчок для уменьшения","More widgets in the top-bar categories":"Другие виджеты в категориях верхней панели","Make a new theme, starting from the active one":"Создать тему на основе текущей","Add a theme from a .reaui-theme.json file":"Импортировать тему из файла .reaui-theme.json","Editor - schematic editing view":"Редактор — схематичный вид для редактирования","Preview - approximate ImGui look (view-only)":"Предпросмотр — приблизительный вид ImGui (без редактирования)","Drag to resize canvas":"Перетащите, чтобы изменить размер холста","Drag to try another window width (view only). Double-click: design size":"Перетащите, чтобы изменить ширину окна в предпросмотре. Двойной щелчок — размер макета","Drag to try another window height (view only). Double-click: design size":"Перетащите, чтобы изменить высоту окна в предпросмотре. Двойной щелчок — размер макета","Drag to try another window size (view only). Double-click: design size":"Перетащите, чтобы изменить размер окна в предпросмотре. Двойной щелчок — размер макета","Collapse or expand this panel":"Свернуть или развернуть панель","Pick a colour from the screen":"Выбрать цвет с экрана","Menu bar entries":"Элементы строки меню","Properties actions":"Действия со свойствами","placeholder text…":"Текст подсказки…","value text…":"Текст значения…","hover text…":"Текст при наведении…","Prefix bullet":"Маркер в начале","Highlight":"Подсветка","Disabled":"Отключено","Draw panel border":"Рисовать границу панели","Enable horizontal scrollbar":"Включить горизонтальную прокрутку","Frame padding X (0 to 32)":"Внутренний отступ по X (0–32)","Frame padding Y (0 to 32)":"Внутренний отступ по Y (0–32)","Selectable text align X (0 to 1)":"Выравнивание текста по X (0–1)","Selectable text align Y (0 to 1)":"Выравнивание текста по Y (0–1)","Font size in pixels":"Размер шрифта в пикселях","Bold":"Полужирный","Italic":"Курсив","empty = no text":"пусто — без текста","Animate indeterminate progress bar":"Анимировать индикатор выполнения","Plot values, comma-separated":"Значения графика через запятую","Link start and end angles":"Связать начальный и конечный углы","Expand Elements panel":"Развернуть панель «Элементы»","Zoom level":"Масштаб","Zoom out":"Уменьшить масштаб","Zoom in":"Увеличить масштаб","Button":"Кнопка","SmallButton":"Компактная кнопка","InvisibleButton":"Невидимая кнопка","ArrowButton":"Кнопка со стрелкой","Checkbox":"Флажок","CheckboxFlags":"Битовый флажок","RadioButton":"Переключатель","RadioButtonEx":"Переключатель","Text":"Текст","BulletText":"Маркированный текст","TextWrapped":"Текст с переносом","TextColored":"Цветной текст","TextDisabled":"Неактивный текст","SeparatorText":"Разделитель с текстом","Separator":"Разделитель","Hint":"Подсказка","HelpMarker":"Значок подсказки","LabelText":"Подпись со значением","TextLinkOpenURL":"Ссылка (URL)","TextLink":"Текстовая ссылка","Slider":"Ползунок","VSlider":"Вертикальный ползунок","SliderAngle":"Угловой ползунок","Drag":"Поле перетаскивания","DragRange":"Диапазон","Input":"Числовое поле","InputText":"Текстовое поле","InputTextMultiline":"Многострочное поле","Multiline":"Многострочное поле","SliderN":"Многокомпонентный ползунок","DragN":"Многокомпонентное поле","InputN":"Многокомпонентный ввод","ProgressBar":"Индикатор выполнения","Plot":"График","InputTextWithHint":"Поле с подсказкой","Combo":"Выпадающий список","ListBox":"Список","Selectable":"Выбираемый элемент","ColorEdit":"Редактор цвета","ColorPicker":"Выбор цвета","ColorButton":"Кнопка цвета","Panel":"Панель","Group":"Группа","StyleRegion":"Область стиля","Style":"Стиль","CollapsingHeader":"Сворачиваемый заголовок","TreeNode":"Узел дерева","TabBar":"Панель вкладок","Tabs":"Вкладки","Table":"Таблица","Main":"Основная","Appearance":"Оформление","Details":"Подробности","Options":"Параметры","Settings":"Настройки","Add widget":"Добавить виджет","Add menu":"Добавить меню","Delete selected":"Удалить выделенное","Duplicate selected":"Дублировать выделенное","Select group":"Выделить группу","Clear selection":"Снять выделение","Enter name":"Введите имя","No selection":"Ничего не выделено","Custom":"Пользовательский","Light mode":"Светлая тема","Theme Studio":"Редактор тем","Close Theme Studio":"Закрыть редактор тем","Plugin preview":"Предпросмотр","Hold to compare":"Сравнить","Editing":"Редактирование","Theme name":"Название темы","Click to rename":"Щёлкните для переименования","Theme actions":"Действия с темой","Collection":"Коллекция","My themes":"Мои темы","My Theme":"Моя тема","New theme":"Новая тема","Imported theme":"Импортированная тема","Not saved yet":"Ещё не сохранена","Built-in":"Встроенная","From Collection":"Из коллекции","From this project":"Из этого проекта","This project only":"Только в проекте","My theme":"Моя тема","Unsaved edits":"Несохранённые изменения","Saved":"Сохранено","Apply":"Применить","Apply to use it, or Save as… to keep it":"Нажмите «Применить», чтобы использовать, или «Сохранить как…», чтобы сохранить","Apply, or Save as… to keep edits":"Примените или сохраните изменения через «Сохранить как…»","Edits become a new theme":"Изменения будут сохранены как новая тема","Differs from the copy in My themes":"Отличается от копии в «Моих темах»","Save to add it to My themes":"Сохраните, чтобы добавить в «Мои темы»","Discard changes":"Не сохранять","Save theme":"Сохранить тему","Theme already saved":"Тема уже сохранена","Save another copy":"Сохранить ещё одну копию","Save":"Сохранить","Save as…":"Сохранить как…","Save edits to this theme in My themes":"Сохранить изменения темы в «Моих темах»","Save as a new theme in My themes":"Сохранить новую тему в «Моих темах»","Reset edits":"Сбросить изменения","Restore this theme to its last saved or starting colours":"Восстановить последние сохранённые или исходные цвета темы","Export…":"Экспорт…","Export Theme":"Экспортировать тему","Edit a copy":"Изменить копию","Change the colours of this theme":"Изменить цвета темы","Change the colours; saving makes a new theme":"Изменить цвета; при сохранении будет создана новая тема","In theme menu":"В меню тем","Show in theme menu":"Показывать в меню тем","Show or hide this theme in the quick theme menu; the active theme stays visible":"Показать или скрыть тему в быстром меню. Активная тема остаётся видимой.","Remove from project":"Удалить из проекта","Rename theme":"Переименовать тему","Manual":"Вручную","Click a colour to change it. The other colours follow automatically; colours set by hand in Full keep their values.":"Нажмите на цвет для изменения. Остальные цвета обновятся автоматически; вручную заданные цвета в полном наборе сохранят свои значения.","Default uses REAPER’s colours. Use Save as… to keep this palette as a custom theme.":"Тема по умолчанию использует цвета REAPER. Чтобы сохранить палитру как пользовательскую тему, выберите «Сохранить как…».","Background":"Фон","Controls":"Элементы управления","Accent":"Акцент","Header opacity":"Прозрачность заголовка","Rebuild all colours":"Пересоздать все цвета","Replace all manual RGB colours with the generated palette?":"Заменить все вручную заданные цвета RGB автоматически созданной палитрой?","Rebuild palette":"Пересоздать палитру","Rebuild":"Пересоздать","Label text":"Текст подписи","Window background":"Фон окна","Field":"Поле","Field · hovered":"Поле · наведение","Field · active":"Поле · активное","Button · hovered":"Кнопка · наведение","Button · active":"Кнопка · активная","Header · hovered":"Заголовок · наведение","Header · active":"Заголовок · активный","Check mark":"Галочка","Slider grab":"Ползунок","Slider grab · active":"Ползунок · активный","Automatically generated colours":"Автоматически созданные цвета","These colours are calculated from your palette and cannot be edited separately.":"Эти цвета вычисляются из палитры; редактировать их по отдельности нельзя.","Title colours are used when the project’s Title bar option is Theme colours. Menu bar colour is used with a menu bar.":"Цвета заголовка применяются при параметре «Строка заголовка → Цвета темы». Цвет строки меню используется при наличии меню.","ImGui colour":"Цвет ImGui","Value":"Значение","Rule":"Правило","Palette collection":"Коллекция палитр","Click a palette to load it into the editor. Your project changes only when you press Apply.":"Выберите палитру, чтобы загрузить её в редактор. Проект изменится только после нажатия «Применить».","Palettes from":"Палитры из","Import…":"Импорт…","No themes here yet.":"Здесь пока нет тем.","Active":"Активная","Select theme":"Выбрать тему","Close":"Закрыть","OK":"ОК","Cancel":"Отмена","Yes":"Да","No":"Нет","Continue":"Продолжить","Confirm":"Подтвердить","Delete Theme":"Удаление темы","Delete theme":"Удалить тему","Delete failed":"Ошибка удаления","Import failed":"Ошибка импорта","Import Theme":"Импорт темы","Export Lua":"Экспорт Lua","Export Lua Script":"Экспорт Lua-скрипта","Export ReaImGui Lua":"Экспорт Lua для ReaImGui","Preflight":"Предэкспортная проверка","Preflight check":"Проверка перед экспортом","Check":"Проверить","Run checks":"Запустить проверку","Checking…":"Проверка…","Passed":"Успешно","Warnings":"Предупреждения","Errors":"Ошибки","Error":"Ошибка","Warning":"Предупреждение","Info":"Информация","Valid":"Допустимо","Invalid":"Недопустимо","Failed":"Не удалось","Ready":"Готово","Done":"Готово","Copy to clipboard":"Копировать в буфер обмена","Copied":"Скопировано","Download":"Скачать","Download Lua":"Скачать Lua","All checks passed":"Все проверки пройдены","Print":"Печать","Show details":"Подробнее","Hide details":"Скрыть подробности","Show more":"Показать ещё","Show less":"Скрыть","ReaUI project":"Проект ReaUI","Untitled project":"Безымянный проект","No unsaved projects to restore.":"Нет несохранённых проектов для восстановления.","Restore projects":"Восстановление проектов","Restore":"Восстановить","Save project as":"Сохранить проект как","Load failed":"Ошибка открытия","Save failed":"Ошибка сохранения","Recovery failed":"Ошибка восстановления","Unsaved changes":"Несохранённые изменения","Saving…":"Сохранение…","Autosave failed":"Ошибка автосохранения","Loaded":"Загружено","Failed to load project":"Не удалось загрузить проект","Recovery draft saved locally in this browser at":"Резервная копия проекта сохранена в этом браузере:","Saving a local recovery draft":"Сохранение локальной резервной копии","Changes are waiting to be saved locally":"Изменения ожидают локального сохранения","New project has no unsaved changes":"В новом проекте нет несохранённых изменений","Loaded project has no unsaved changes":"В открытом проекте нет несохранённых изменений","The recovery draft could not be applied. It has not been deleted.":"Не удалось восстановить резервную копию. Она не удалена.","Stored projects could not be read.":"Не удалось прочитать сохранённые проекты.","Save the current project before restoring another one?":"Сохранить текущий проект перед восстановлением другого?","Save the current project before loading another one?":"Сохранить текущий проект перед открытием другого?","The project root must be an object.":"Корневой элемент проекта должен быть объектом.","The project shapes field is required and must be an array.":"Поле shapes обязательно и должно быть массивом.","This project version is not supported.":"Эта версия проекта не поддерживается.","This file is not valid JSON.":"Файл содержит некорректный JSON.","This file is not a ReaUI theme: it is not a JSON object.":"Это не тема ReaUI: содержимое не является объектом JSON.","This file is not a ReaUI theme: \"format\" is not \"reaui-theme\".":"Это не тема ReaUI: значение \"format\" отличается от \"reaui-theme\".","This theme file has no valid format version.":"В файле темы отсутствует корректная версия формата.","The file contains no theme.":"Файл не содержит темы.","The theme has no colours.":"В теме отсутствуют цвета.","The theme needs a valid \"childBg\" and a valid \"text\" colour.":"В теме должны быть корректные цвета \"childBg\" и \"text\".","The theme could not be added.":"Не удалось добавить тему.","The file could not be read.":"Не удалось прочитать файл.","Nothing was imported.":"Импорт не выполнен.","It is in the theme list now - click it to apply. The current theme is unchanged.":"Тема добавлена в список. Выберите её для применения. Текущая тема не изменилась.","Could not change the theme menu. Check browser storage and try again.":"Не удалось изменить меню тем. Проверьте хранилище браузера и повторите попытку.","Could not save the theme. Check browser storage and try again.":"Не удалось сохранить тему. Проверьте хранилище браузера и повторите попытку.","Could not apply the theme.":"Не удалось применить тему.","The theme could not be deleted. Check browser storage and try again.":"Не удалось удалить тему. Проверьте хранилище браузера и повторите попытку.","no callback event selected — this code will never run":"Не выбрано событие обработчика — этот код не будет выполняться","compiled once at startup via CreateFunctionFromEEL":"Компилируется один раз при запуске через CreateFunctionFromEEL","radio group":"группа переключателей","radio value":"значение переключателя","bullet (tree: replaces arrow)":"маркер (в дереве вместо стрелки)","start angle":"начальный угол","end angle":"конечный угол","link angles":"связать углы","arc mode":"режим дуги","header color":"цвет заголовка","header value":"значение заголовка","blocked: shape needs at least one of fill/stroke":"Невозможно: фигуре нужна хотя бы заливка или обводка","value must be finite":"Значение должно быть конечным числом","value must be an integer":"Значение должно быть целым числом","value is below the native API range":"Значение меньше допустимого диапазона API","value is above the native API range":"Значение больше допустимого диапазона API","callback events":"события обработчика","data type":"тип данных","ReadOnly":"Только чтение","Password":"Пароль","Pass":"Пароль","CharsDecimal":"Десятичные символы","Dec":"Дес.","CharsHexadecimal":"Шестнадцатеричные символы","Hex":"HEX","EnterReturnsTrue":"Подтверждение Enter","AllowTabInput":"Ввод Tab","CtrlEnterForNewLine":"Новая строка по Ctrl+Enter","CallbackEdit":"При изменении","CallbackAlways":"Всегда","CallbackCharFilter":"Фильтр символов","CallbackCompletion":"Автодополнение","CallbackHistory":"История","OnEdit":"Изменение","Always":"Всегда","CharFilter":"Фильтр","OnTab":"По Tab","OnUp/Down":"По ↑/↓","NoAlpha":"Без альфа","NoPicker":"Без палитры","NoInputs":"Без полей","NoTooltip":"Без подсказки","NoTip":"Без подсказки","NoLabel":"Без подписи","NoSidePreview":"Без бокового образца","NoSidePrev":"Без бокового образца","NoSmallPreview":"Без маленького образца","NoSmallPrev":"Без мини-образца","NoOptions":"Без параметров","NoDragDrop":"Без перетаскивания","NoBorder":"Без границы","DisplayRGB":"Показать RGB","DisplayHSV":"Показать HSV","DisplayHex":"Показать HEX","Uint8":"0–255","Float":"Дробные","InputRGB":"Ввод RGB","InputHSV":"Ввод HSV","PickerHueBar":"Полоса оттенка","HueBar":"Полоса оттенка","PickerHueWheel":"Цветовой круг","HueWheel":"Цветовой круг","AlphaBar":"Шкала альфа","AlphaPreviewHalf":"Полупрозрачный образец","HalfPrev":"Полуобразец","AlphaNoBg":"Без фона","NoBg":"Без фона","AlphaOpaque":"Непрозрачный образец","Opaque":"Непрозрачный","No elements yet":"Элементов пока нет","Add a widget or draw object, then click the canvas.":"Добавьте виджет или графический объект, затем щёлкните на холсте.","↑ height fixed by ImGui":"↑ высота задаётся ImGui","↑ size fixed by ImGui":"↑ размер задаётся ImGui","⊞ Snap:":"⊞ Привязка:","click=select Shift=range Cmd/Ctrl=toggle":"щелчок — выделить; Shift — диапазон; Cmd/Ctrl — переключить","click=select Shift=range Cmd/Ctrl=toggle":"щелчок — выделить; Shift — диапазон; Cmd/Ctrl — переключить","drag to place (or click for default size)":"протяните для размещения (или щёлкните для стандартного размера)","Structure":"Структура","Constraints":"Привязки","Constraints apply when the window is resizable":"Привязки работают при изменяемом размере окна","Make the window resizable":"Разрешить изменение размера окна","Pinned to":"Привязка к","Left":"Слева","Right":"Справа","Center":"Центр","Top":"Сверху","Bottom":"Снизу","Left+Right":"Слева + справа","Top+Bottom":"Сверху + снизу","Left · Top":"Слева · сверху","Horizontal":"По горизонтали","Vertical":"По вертикали","Name":"Имя","Enable loop":"Включить цикл","custom look (size, border, colours, click area)":"Пользовательский вид (размер, границы, цвета, область нажатия)","Constraint presets":"Шаблоны привязок","Pin left top":"Привязать слева сверху","Pin center top":"Привязать по центру сверху","Pin right top":"Привязать справа сверху","Pin left center":"Привязать слева по центру","Pin center":"Привязать к центру","Pin right center":"Привязать справа по центру","Pin left bottom":"Привязать слева снизу","Pin center bottom":"Привязать по центру снизу","Pin right bottom":"Привязать справа снизу","Horizontal constraint":"Горизонтальная привязка","Vertical constraint":"Вертикальная привязка","Select and edit this element":"Выделить и изменить этот элемент","Built-in · in use":"Встроенная · используется","Built-in · active":"Встроенная · активна","Vintage":"Винтажные","Cold":"Холодные","Warm":"Тёплые","Earth":"Землистые","Vintage palettes":"Винтажные палитры","Dark palettes":"Тёмные палитры","Cold palettes":"Холодные палитры","Warm palettes":"Тёплые палитры","Earth palettes":"Землистые палитры","Default — built-in":"Default — встроенная","Edit a copy of Light":"Изменить копию Light","Use this theme in the project and close. Edits stay in this project until you save them.":"Применить тему к проекту и закрыть редактор. Изменения останутся в проекте, пока вы не сохраните тему отдельно.","none":"нет","sample data":"пример данных","// EEL2 — runs on the selected Callback* event":"// EEL2 — выполняется при выбранном событии Callback*","Normal":"Обычный","Hovered":"Наведение","Active header":"Активный заголовок","Hovered header":"Заголовок при наведении","Parameter":"Параметр","Gain":"Усиление","Mix":"Смешивание","More":"Ещё","Sample plugin":"Пример плагина","Enable processing":"Включить обработку","Instruments":"Инструменты","Popup / tooltip selected text":"Всплывающая подсказка и выделенный текст","Documentation ↗":"Документация ↗","Documentation":"Документация","Current theme":"Текущая тема","New Theme":"Новая тема","View → Interface mode":"Вид → Режим интерфейса","File Edit View":"Файл Правка Вид","▾ Header":"▾ Заголовок","▾ Hovered header":"▾ Заголовок при наведении","▾ Active header":"▾ Активный заголовок","Popup / tooltip":"Всплывающее окно / подсказка","selected text":"выделенный текст","Disable":"Отключить","Basic layout":"Базовая компоновка","Title bar":"Строка заголовка","Edited":"Изменено","Edit theme":"Изменить тему","Edit a copy of":"Изменить копию","Theme":"Тема","Root":"Корень","Insert":"Вставить","Delete all":"Удалить всё","Clear All?":"Очистить всё?","ReaUI Builder — About":"ReaUI Builder — О программе","Keyboard shortcuts":"Сочетания клавиш","About ReaUI Builder":"О ReaUI Builder","Report a bug":"Сообщить об ошибке","Ready to export":"Готово к экспорту","No export blockers or warnings detected.":"Ошибок и предупреждений, препятствующих экспорту, нет.","Arrow keys":"Клавиши со стрелками","Nudge selection (grid step, or 1 px with Snap off)":"Переместить выделенное на шаг сетки (или на 1 пиксель без привязки)","Shift + Arrow keys":"Shift + стрелки","Nudge selection by 10 steps":"Переместить выделенное на 10 шагов","Copy selection":"Копировать выделенное","Duplicate selection":"Дублировать выделенное","Delete selection":"Удалить выделенное","Escape":"Esc","Deselect, cancel tool/polygon, or close an open dialog/menu":"Снять выделение, отменить инструмент/многоугольник или закрыть окно/меню","Enter (Polygon)":"Enter (многоугольник)","Finish polygon":"Завершить многоугольник","Shift + click object":"Shift + щелчок по объекту","Extend selection from the anchor object":"Расширить выделение от опорного объекта","⌘/Ctrl + click object":"⌘/Ctrl + щелчок по объекту","Toggle object in selection":"Добавить объект к выделению или снять выделение","Shift + marquee":"Shift + рамка выделения","Add objects intersecting the marquee to selection":"Добавить объекты, пересекаемые рамкой, к выделению","Toggle objects intersecting the marquee":"Переключить выделение объектов, пересекаемых рамкой","Alt + drag object":"Alt + перетаскивание объекта","Drag a copy":"Перетащить копию объекта","U + drag container":"U + перетаскивание контейнера","Unlock for this move: leave its contents behind and ignore widgets underneath":"Временно разблокировать перемещение: оставить содержимое на месте и игнорировать виджеты под контейнером","Space + drag canvas":"Пробел + перетаскивание холста","Pan canvas":"Переместить холст","Zoom to cursor":"Масштабировать относительно указателя","Right-click canvas":"Правая кнопка мыши на холсте","Open the widget menu at the pointer":"Открыть меню виджетов у указателя","Shift + drawing tool button":"Shift + кнопка инструмента рисования","Keep Rectangle, Circle, Line, Triangle, or Arc active":"Оставить активными «Прямоугольник», «Окружность», «Линия», «Треугольник» или «Дуга»","Polygon: double-click / first point":"Многоугольник: двойной щелчок / первая вершина","Visual layout tool for ReaImGui (REAPER DAW).":"Визуальный редактор интерфейсов ReaImGui (REAPER).","Generates Lua code using the ReaImGui API.":"Генерирует Lua-код на основе API ReaImGui.","Single-file Vanilla HTML/CSS/JS — no build tools.":"Один HTML-файл с CSS и JavaScript, без сборки и зависимостей.","Report a Bug":"Сообщить об ошибке","Describe what happened, what you expected, and how to reproduce it.":"Опишите, что произошло, как должно было работать и как воспроизвести ошибку.","Copy Report":"Копировать отчёт","Download Report":"Скачать отчёт","Send the report to:":"Отправьте отчёт по адресу:","Copied ✓":"Скопировано ✓","Include my layout (helps reproduce it; sends the whole project)":"Включить мой макет (для воспроизведения ошибки; прикладывается весь проект)","The text below is everything that gets sent - the last 50 actions plus your build and window size. Nothing else is collected.":"Ниже приведён полный состав отчёта: последние 50 действий, версия сборки и размер окна. Другие данные не собираются.","Popups / text":"Всплывающие окна и текст","Borders / scrollbars":"Границы и прокрутка","Tables":"Таблицы","Window / menu":"Окно и меню","Plots / tree":"Графики и дерево","7 colours set by hand":"7 цветов заданы вручную","shift(Background, 3% away from background)":"shift(Фон, 3% от исходного фона)","mix(Background, Text, 55%)":"mix(Фон, Текст, 55%)","mix(Background, Check mark, 45%)":"mix(Фон, Галочка, 45%)","= Check mark":"= Галочка","= Text":"= Текст","mix(Background, Text, 30%)":"mix(Фон, Текст, 30%)","mix(Background, Field, 35%)":"mix(Фон, Поле, 35%)","= Field":"= Поле","= Hovered field":"= Поле при наведении","= Active field":"= Активное поле","= Header (opaque)":"= Заголовок (непрозрачный)","mix(Background, Text, 35%)":"mix(Фон, Текст, 35%)","mix(Background, Text, 18%)":"mix(Фон, Текст, 18%)","= Background":"= Фон","shift(Background, 5% away from background)":"shift(Фон, 5% от исходного фона)","mix(Background, Field, 60%)":"mix(Фон, Поле, 60%)","mix(Background, Header, 80%)":"mix(Фон, Заголовок, 80%)","mix(Background, Field, 40%)":"mix(Фон, Поле, 40%)","mix(Background, Field, 50%)":"mix(Фон, Поле, 50%)","shift(Check mark, 12% away from background)":"shift(Галочка, 12% от исходного фона)","mix(Background, Text, 65%)":"mix(Фон, Текст, 65%)","= Border":"= Граница","= Active header (fallback: Active button, Header)":"= Активный заголовок (иначе: Активная кнопка, Заголовок)","= Hovered header (fallback: Hovered button)":"= Заголовок при наведении (иначе: Кнопка при наведении)","= Check mark (fallback: Slider grab)":"= Галочка (иначе: Ползунок)","Visual layout tool for ReaImGui (REAPER DAW).\nGenerates Lua code using the ReaImGui API.\nSingle-file Vanilla HTML/CSS/JS — no build tools.":"Визуальный редактор интерфейсов ReaImGui для REAPER.\nГенерирует Lua-код через API ReaImGui.\nРаботает как единый HTML-файл с CSS и JavaScript, без сборки.","Popup / tooltip ":"Всплывающее окно / подсказка ","Project":"Проект","Element":"Элемент","Project background colour is invalid":"Некорректный цвет фона проекта","Use a hexadecimal colour in #RRGGBB format.":"Укажите цвет в шестнадцатеричном формате #RRGGBB.","Element has no ID":"У элемента отсутствует ID","Export maps and parent relationships require a stable element ID.":"Для экспорта и связей родительских объектов необходим постоянный ID элемента.","Duplicate element ID:":"Повторяющийся ID элемента:","IDs must be unique; the exporter uses them as map keys.":"ID должны быть уникальны: генератор использует их как ключи.","Unknown element type:":"Неизвестный тип элемента:","The Lua exporter supports widgets and the documented drawing primitives only.":"Экспорт Lua поддерживает только виджеты и описанные графические примитивы.","Parent ID is ambiguous":"Неоднозначный ID родительского объекта","Parent element is missing":"Родительский объект отсутствует","Cyclic parent relationship":"Циклическая вложенность","The parent chain loops back to an element already visited.":"Цепочка родительских объектов содержит цикл.","Invalid position or size":"Некорректные координаты или размер","X, Y, width and height must be finite numbers; width and height must be greater than zero.":"X, Y, ширина и высота должны быть конечными числами; ширина и высота — больше нуля.","Unknown widget type:":"Неизвестный тип виджета:","The Lua exporter has no contract for this widget.":"Генератор Lua не поддерживает этот тип виджета.","Choose Left, Right, Up or Down.":"Выберите Left, Right, Up или Down.","Arrow direction is not supported":"Неподдерживаемое направление стрелки","Polygon has fewer than three points":"У многоугольника менее трёх вершин","A polygon needs at least three points to export.":"Для экспорта многоугольнику необходимо минимум три вершины.","Polygon contains a nonnumeric point":"У многоугольника есть некорректная вершина","Every polygon point needs finite numeric X and Y coordinates.":"У каждой вершины должны быть конечные числовые координаты X и Y.","Polygon outline crosses itself":"Контур многоугольника пересекает сам себя","ImGui fills only a polygon whose outline does not cross, touch or turn back on itself. Move a point, split the shape into separate polygons, or disable its fill to export the outline only.":"ImGui может заливать только многоугольник без самопересечений и касаний контура. Переместите вершину, разделите фигуру или отключите заливку.","Polygon fill cannot be exported":"Не удалось экспортировать заливку многоугольника","Builder could not split this polygon into triangles for ImGui. Remove repeated points, or disable its fill to export the outline only.":"Не удалось разбить многоугольник на треугольники для ImGui. Удалите повторяющиеся вершины либо отключите заливку.","Line points are invalid":"Некорректные точки линии","A line needs exactly two points with finite numeric X and Y coordinates.":"Линии нужны ровно две точки с конечными числовыми координатами X и Y.","Invalid numeric property:":"Некорректный числовой параметр:","The value must be a finite number.":"Значение должно быть конечным числом.","Invalid StyleRegion property:":"Некорректный параметр StyleRegion:","Use a finite value inside the supported range.":"Укажите конечное число в допустимом диапазоне.","Invalid colour property:":"Некорректный параметр цвета:","Invalid colour flags":"Некорректные флаги цвета","Could not resolve export bounds":"Не удалось определить границы экспорта","Check the element parent chain and geometry.":"Проверьте геометрию и вложенность элемента.","Widget will not be exported":"Виджет не будет экспортирован","Draw object will not be exported":"Графический объект не будет экспортирован","It does not intersect the canvas, so it is omitted from the Lua.":"Объект не пересекает холст и исключён из экспорта Lua.","Draw object crosses the canvas edge":"Графический объект пересекает границу холста","Only the intersecting part will be visible in the exported plugin.":"В экспортированном интерфейсе будет видна только часть объекта внутри холста.","Link URL is empty":"Адрес ссылки не указан","The exporter will use https://example.com as a fallback.":"Генератор использует резервный адрес https://example.com.","Callback flags require EEL callback code":"Для флагов Callback необходим код обработчика EEL","Add a non-empty EEL callback or disable all Callback* flags.":"Добавьте код обработчика EEL или отключите все флаги Callback*.","Minimum is not numeric":"Минимум не является числом","Maximum is not numeric":"Максимум не является числом","Enter a finite number or clear the field.":"Введите конечное число или очистите поле.","Minimum is greater than maximum":"Минимум больше максимума","Swap the values or correct the numeric range.":"Поменяйте значения местами или исправьте диапазон.","Minimum equals maximum":"Минимум равен максимуму","The control has no usable value range.":"У элемента нет допустимого диапазона значений.","Step should be zero or positive":"Шаг должен быть неотрицательным","Negative or non-numeric step values can behave unexpectedly.":"Отрицательный или нечисловой шаг может вызвать некорректную работу.","Speed should be greater than zero":"Скорость должна быть больше нуля","Drag controls need a positive finite speed.":"Для элементов Drag требуется положительная конечная скорость.","Component count must be 1–4":"Число компонентов должно быть от 1 до 4","The selected widget family only supports one to four components.":"Этот тип виджета поддерживает от одного до четырёх компонентов.","Array size must be 2–64":"Размер массива должен быть от 2 до 64","N-wide controls allocate a ReaScript array of this size.":"Многокомпонентные элементы создают массив ReaScript указанного размера.","Color alpha must be 0–255":"Альфа-канал должен быть в диапазоне 0–255","The Lua color packer expects an 8-bit alpha value.":"Упаковка цвета в Lua требует 8-битного значения альфа-канала.","Will not be exported with its container":"Не экспортируется вместе с контейнером","Widget is unreachable by the exporter":"Виджет недоступен генератору","Its parent chain is not traversed by the generated Lua.":"Сгенерированный Lua-код не обходит цепочку родительских объектов виджета.","Widget overlaps":"Виджет перекрывает","Their occupied areas intersect on the canvas. Move or resize one of the widgets before export.":"Области виджетов на холсте пересекаются. Перед экспортом переместите один из виджетов или измените его размер.","Overlaps":"Перекрывает","Leaves the window":"Выходит за границы окна","Too small at the minimum window size":"Слишком мал при минимальном размере окна","Export name collides after sanitizing":"Совпадение экспортируемого имени после нормализации","Radio value is not numeric":"Значение переключателя не является числом","RadioButtonEx requires a finite numeric value.":"Для RadioButtonEx требуется конечное числовое значение.","Duplicate radio value in group":"Повторяющееся значение в группе переключателей","Flag bit must be an integer 0–":"Номер бита должен быть целым числом от 0 до","Duplicate bit in flag group":"Повторяющийся бит в группе флагов","Plot values are invalid":"Некорректные значения графика","Enter a number or clear the field for automatic scaling.":"Введите число или оставьте поле пустым для автоматического масштаба.","Scale min is not below scale max":"Минимум шкалы не меньше максимума","The plot has no usable value range.":"У графика нет допустимого диапазона значений.","PlotLines needs at least two values":"PlotLines требует минимум два значения","With one value ImGui draws an empty frame.":"При одном значении ImGui рисует пустую рамку.","TabBar has no tabs":"В TabBar отсутствуют вкладки","The exported tab bar will have no visible tab items.":"В экспортированной панели не будет видимых вкладок.","Active tab does not exist":"Активная вкладка отсутствует","Choose one of the TabItems contained by this TabBar.":"Выберите одну из вкладок TabItem этой панели TabBar.","TabItem is not inside a TabBar":"TabItem находится вне TabBar","Standalone TabItems are not emitted correctly.":"Отдельные TabItem вне TabBar экспортируются некорректно.","Table rows and columns must be positive integers":"Число строк и столбцов таблицы должно быть положительным целым числом","Correct rowCount and columnCount before export.":"Перед экспортом исправьте rowCount и columnCount.","Table cell is outside the table grid":"Ячейка выходит за границы таблицы","Row and column indices must fit the parent table dimensions.":"Индексы строки и столбца должны соответствовать размеру родительской таблицы.","Duplicate table cell":"Повторяющаяся ячейка таблицы","Only one TableCell can occupy each row and column.":"Каждую позицию строки и столбца может занимать только одна TableCell.","Table has missing structural cells":"В таблице отсутствуют структурные ячейки","TableCell is not inside a Table":"TableCell находится вне Table","Standalone structural cells are not emitted correctly.":"Отдельные структурные ячейки экспортируются некорректно.","Menus past the right edge are cut off in REAPER":"Меню, выходящее за правую границу, будет обрезано в REAPER","Frame padding Y is":"Внутренний отступ рамки по Y равен","Copy generated Lua":"Копировать сгенерированный Lua","Download generated Lua":"Скачать сгенерированный Lua","Resolve the errors above to enable copy":"Исправьте ошибки выше, чтобы разблокировать копирование","Resolve the errors above to enable download":"Исправьте ошибки выше, чтобы разблокировать скачивание","Ready with":"Готово, но есть","Select this element on canvas":"Выделить этот элемент на холсте"}; + const UI = {"Start in ReaUI Builder":"Начало работы в ReaUI Builder","Choose the interface mode, then create a new project or open an existing one.":"Выберите режим интерфейса, затем создайте новый проект или откройте существующий.","Basic":"Базовый","Advanced":"Расширенный","A simpler workspace with the core components and settings.":"Упрощённая рабочая область с основными компонентами и настройками.","The complete editor with all components, tools and settings.":"Полный редактор со всеми компонентами, инструментами и параметрами.","The display mode can be changed at any time from":"Режим интерфейса можно в любой момент изменить через","View":"Вид",". It does not change the project file.":". Это не изменяет файл проекта.","Restore unsaved project…":"Восстановить несохранённый проект…","Open project…":"Открыть проект…","Create new project":"Создать проект","Interface mode":"Режим интерфейса","File":"Файл","New Project":"Создать проект","Save Project":"Сохранить проект","Save As…":"Сохранить как…","Restore projects…":"Восстановить проекты…","Load Project":"Открытие проекта","Edit":"Правка","Undo":"Отменить","Redo":"Повторить","Copy":"Копировать","Paste":"Вставить","Delete":"Удалить","Duplicate":"Дублировать","Group selection":"Сгруппировать выделенное","Ungroup selection":"Разгруппировать","Select All":"Выделить всё","Deselect All":"Снять выделение","Clear All":"Очистить всё","Dark mode":"Тёмная тема","Theme Studio…":"Редактор тем…","Grid":"Сетка","Snap to grid":"Привязка к сетке","Reference grid in export":"Сетка в экспортируемом интерфейсе","Hide widget names":"Скрыть имена виджетов","Hide draw objects names":"Скрыть имена графических объектов","Widget footprints":"Границы виджетов","Show hints":"Показывать подсказки","Panels":"Панели","Canvas":"Холст","Properties":"Свойства","Elements":"Элементы","Tools":"Инструменты","Zoom to fit":"Вписать в окно","Actual size (100%)":"Фактический размер (100 %)","Help":"Справка","User Manual ↗":"Руководство пользователя ↗","Keyboard Shortcuts":"Сочетания клавиш","Report a Bug…":"Сообщить об ошибке…","About":"О программе","Export":"Экспорт","Buttons & Toggles":"Кнопки и переключатели","Display":"Отображение","Fields":"Поля ввода","Sliders & Drags":"Ползунки и числовые поля","Selection":"Выбор","Color":"Цвет","Layout":"Компоновка","Add":"Добавить","Choose a component":"Выберите компонент","Then click or drag on the canvas to place it.":"Затем щёлкните или протяните указатель на холсте, чтобы разместить его.","Text Input":"Текстовое поле","Number Input":"Числовое поле","Dropdown":"Выпадающий список","Progress":"Выполнение","More components…":"Другие компоненты…","Select":"Выделение","Hand":"Рука","Zoom":"Масштаб","Rectangle":"Прямоугольник","Circle":"Окружность","Polygon":"Многоугольник","Line":"Линия","Triangle":"Треугольник","Arc":"Дуга","Header":"Заголовок","Tree":"Дерево","Default":"По умолчанию","Themes":"Темы","Choose a theme for the ReaImGui UI you will export.":"Выберите тему для экспортируемого интерфейса ReaImGui.","+ New":"+ Создать","Import":"Импорт","Edit…":"Изменить…","Editor":"Редактор","Preview":"Предпросмотр","Preview is approximate — hatched widgets are shown schematically":"Предпросмотр приблизительный — заштрихованные виджеты показаны схематично","Advanced canvas settings are active":"Используются расширенные параметры холста","Some canvas settings are hidden in Basic mode but remain part of this project.":"Некоторые параметры холста скрыты в базовом режиме, но сохранены в проекте.","Edit in Advanced":"Изменить в расширенном режиме","size":"размер","Width":"Ширина","Height":"Высота","background":"фон","grid":"сетка","Show grid":"Показывать сетку","Audit grid":"Контрольная сетка","color":"цвет","Opacity":"Прозрачность","Snap":"Привязка","Step":"Шаг","title bar":"строка заголовка","ImGui default":"По умолчанию ImGui","Theme colours":"Цвета темы","window":"окно","Resizable window":"Изменяемый размер окна","Min width":"Мин. ширина","Min height":"Мин. высота","Max width":"Макс. ширина","Max height":"Макс. высота","menu bar":"строка меню","+ Add menu":"+ Добавить меню","No menu bar. Add a menu to give the window a menu bar; the canvas keeps its size and nothing on it moves.":"Строка меню отсутствует. Добавьте меню, чтобы оно появилось в окне. Размер холста и расположение объектов не изменятся.","No element selected":"Элемент не выбран","Select one object on the canvas to edit its properties here.":"Выберите объект на холсте, чтобы изменить его свойства.","Multiple selection":"Выделено несколько объектов","Edit shared properties together.":"Редактируйте общие свойства объектов одновременно.","Move selection":"Переместить выделенное","move":"Переместить","Common properties":"Общие свойства","Mixed fields stay unchanged until you enter a value. Each edit is one undo step.":"Поля с различающимися значениями не изменяются, пока вы не введёте новое значение. Каждое изменение можно отменить отдельно.","delete selected":"Удалить выделенное","Advanced component":"Расширенный компонент","Some settings are available in Advanced mode.":"Некоторые настройки доступны только в расширенном режиме.","Configuring":"Настройка","Reset":"Сбросить","Click on canvas to place":"Щёлкните на холсте, чтобы разместить","Select a widget to preview":"Выберите виджет для предпросмотра","variant":"вариант","name":"имя","parent":"родительский объект","tabs":"вкладки","+ add tab":"+ добавить вкладку","table grid":"сетка таблицы","columns":"столбцы","row heights":"высота строк","label / text":"подпись / текст","placeholder":"замещающий текст","value":"значение","url":"URL","direction":"направление","value components":"компоненты значения","array size":"размер массива","min":"мин.","max":"макс.","speed":"скорость","step":"шаг","step fast":"ускоренный шаг","format":"формат","format min":"формат минимума","format max":"формат максимума","flags":"флаги","Clamp":"Ограничить","Log":"Логарифм.","NoInput":"Без ввода","Wrap":"Зациклить","hint":"подсказка","prefix bullet":"маркер в начале","highlight":"подсветка","disabled (BeginDisabled)":"отключено (BeginDisabled)","look":"вид","tree lines":"линии дерева","None":"Нет","Full":"Full","To nodes":"До узлов","tab button":"кнопка вкладки","Leading":"В начале","Trailing":"В конце","button label":"подпись кнопки","text tone":"цвет текста","Auto":"Авто","Dark":"Тёмный","Light":"Светлый","border":"граница","draw border":"рисовать границу","h-scroll":"горизонтальная прокрутка","horizontal scrollbar":"горизонтальная полоса прокрутки","text color":"цвет текста","frame bg":"фон элемента","button color":"цвет кнопки","rounding":"скругление","frame padding":"внутренние отступы","selectable align":"выравнивание элемента","font":"шрифт","sans-serif":"без засечек","serif":"с засечками","monospace":"моноширинный","cursive":"курсивный","fantasy":"декоративный","alpha":"альфа-канал","overlay":"наложенный текст","indeterminate":"неопределённый прогресс","animate":"анимация","EEL2 callback":"обработчик EEL2","group":"группа","flag group":"группа флагов","bit (0–30)":"бит (0–30)","values":"значения","scale min":"мин. шкалы","scale max":"макс. шкалы","text align":"выравнивание текста","left":"слева","center":"по центру","right":"справа","text size":"размер текста","vertical align":"выравнивание по вертикали","top":"сверху","middle":"по центру","bottom":"снизу","fill & stroke":"заливка и обводка","fill":"заливка","disable":"отключить","stroke":"обводка","thickness":"толщина","opacity":"прозрачность","hdr color":"цвет заголовка","default":"по умолчанию","custom":"пользовательский","hdr color val":"цвет заголовка","orient":"ориентация","angles (°)":"углы (°)","start":"начало","end":"конец","Link":"Связать","mode":"режим","ring":"кольцо","pie":"сектор","position":"положение","poly points":"вершины многоугольника","primitive order":"порядок отрисовки","back":"на задний план","backward":"назад","forward":"вперёд","front":"на передний план","delete":"удалить","select":"выделение","On":"Вкл.","Off":"Выкл.","0 elements":"0 элементов","No unsaved changes":"Нет несохранённых изменений","copy":"копировать","download .lua":"скачать .lua","Show code":"Показать код","Hide code":"Скрыть код","close":"закрыть","ReaUI Builder checks the project first, then exports the same ReaImGui Lua script as Advanced mode.":"Сначала ReaUI Builder проверит проект, затем экспортирует тот же Lua-скрипт ReaImGui, что и в расширенном режиме.","Checking export…":"Проверка перед экспортом…","Run again":"Проверить снова","Requires ReaImGui — install it via ReaPack.":"Требуется ReaImGui — установите его через ReaPack.","Colours of the exported plugin — not the builder's own look":"Цвета экспортируемого плагина, а не самого редактора","Hide service names of widgets in Editor":"Скрыть служебные имена виджетов в редакторе","Hide service names of draw objects in Editor":"Скрыть служебные имена графических объектов в редакторе","Open the online user manual in your browser":"Открыть руководство пользователя в браузере","Add components":"Добавить компоненты","Hand — drag to pan":"Рука — перетаскивайте для перемещения по холсту","Zoom — click to zoom in, Alt/Option + click to zoom out":"Масштаб — щелчок для увеличения, Alt/Option + щелчок для уменьшения","More widgets in the top-bar categories":"Другие виджеты в категориях верхней панели","Make a new theme, starting from the active one":"Создать тему на основе текущей","Add a theme from a .reaui-theme.json file":"Импортировать тему из файла .reaui-theme.json","Editor - schematic editing view":"Редактор — схематичный вид для редактирования","Preview - approximate ImGui look (view-only)":"Предпросмотр — приблизительный вид ImGui (без редактирования)","Drag to resize canvas":"Перетащите, чтобы изменить размер холста","Drag to try another window width (view only). Double-click: design size":"Перетащите, чтобы изменить ширину окна в предпросмотре. Двойной щелчок — размер макета","Drag to try another window height (view only). Double-click: design size":"Перетащите, чтобы изменить высоту окна в предпросмотре. Двойной щелчок — размер макета","Drag to try another window size (view only). Double-click: design size":"Перетащите, чтобы изменить размер окна в предпросмотре. Двойной щелчок — размер макета","Collapse or expand this panel":"Свернуть или развернуть панель","Pick a colour from the screen":"Выбрать цвет с экрана","Menu bar entries":"Элементы строки меню","Properties actions":"Действия со свойствами","placeholder text…":"Текст подсказки…","value text…":"Текст значения…","hover text…":"Текст при наведении…","Prefix bullet":"Маркер в начале","Highlight":"Подсветка","Disabled":"Отключено","Draw panel border":"Рисовать границу панели","Enable horizontal scrollbar":"Включить горизонтальную прокрутку","Frame padding X (0 to 32)":"Внутренний отступ по X (0–32)","Frame padding Y (0 to 32)":"Внутренний отступ по Y (0–32)","Selectable text align X (0 to 1)":"Выравнивание текста по X (0–1)","Selectable text align Y (0 to 1)":"Выравнивание текста по Y (0–1)","Font size in pixels":"Размер шрифта в пикселях","Bold":"Полужирный","Italic":"Курсив","empty = no text":"пусто — без текста","Animate indeterminate progress bar":"Анимировать индикатор выполнения","Plot values, comma-separated":"Значения графика через запятую","Link start and end angles":"Связать начальный и конечный углы","Expand Elements panel":"Развернуть панель «Элементы»","Zoom level":"Масштаб","Zoom out":"Уменьшить масштаб","Zoom in":"Увеличить масштаб","Button":"Кнопка","SmallButton":"Компактная кнопка","InvisibleButton":"Невидимая кнопка","ArrowButton":"Кнопка со стрелкой","Checkbox":"Флажок","CheckboxFlags":"Битовый флажок","RadioButton":"Переключатель","RadioButtonEx":"Переключатель","Text":"Текст","BulletText":"Маркированный текст","TextWrapped":"Текст с переносом","TextColored":"Цветной текст","TextDisabled":"Неактивный текст","SeparatorText":"Разделитель с текстом","Separator":"Разделитель","Hint":"Подсказка","HelpMarker":"Значок подсказки","LabelText":"Подпись со значением","TextLinkOpenURL":"Ссылка (URL)","TextLink":"Текстовая ссылка","Slider":"Ползунок","VSlider":"Вертикальный ползунок","SliderAngle":"Угловой ползунок","Drag":"Поле перетаскивания","DragRange":"Диапазон","Input":"Числовое поле","InputText":"Текстовое поле","InputTextMultiline":"Многострочное поле","Multiline":"Многострочное поле","SliderN":"Многокомпонентный ползунок","DragN":"Многокомпонентное поле","InputN":"Многокомпонентный ввод","ProgressBar":"Индикатор выполнения","Plot":"График","InputTextWithHint":"Поле с подсказкой","Combo":"Выпадающий список","ListBox":"Список","Selectable":"Выбираемый элемент","ColorEdit":"Редактор цвета","ColorPicker":"Выбор цвета","ColorButton":"Кнопка цвета","Panel":"Панель","Group":"Группа","StyleRegion":"Область стиля","Style":"Стиль","CollapsingHeader":"Сворачиваемый заголовок","TreeNode":"Узел дерева","TabBar":"Панель вкладок","Tabs":"Вкладки","Table":"Таблица","Main":"Основная","Appearance":"Оформление","Details":"Подробности","Options":"Параметры","Settings":"Настройки","Add widget":"Добавить виджет","Add menu":"Добавить меню","Delete selected":"Удалить выделенное","Duplicate selected":"Дублировать выделенное","Select group":"Выделить группу","Clear selection":"Снять выделение","Enter name":"Введите имя","No selection":"Ничего не выделено","Custom":"Пользовательский","Light mode":"Светлая тема","Theme Studio":"Редактор тем","Close Theme Studio":"Закрыть редактор тем","Plugin preview":"Предпросмотр","Hold to compare":"Сравнить","Editing":"Редактирование","Theme name":"Название темы","Click to rename":"Щёлкните для переименования","Theme actions":"Действия с темой","Collection":"Коллекция","My themes":"Мои темы","My Theme":"Моя тема","New theme":"Новая тема","Imported theme":"Импортированная тема","Not saved yet":"Ещё не сохранена","Built-in":"Встроенная","From Collection":"Из коллекции","From this project":"Из этого проекта","This project only":"Только в проекте","My theme":"Моя тема","Unsaved edits":"Несохранённые изменения","Saved":"Сохранено","Apply":"Применить","Apply to use it, or Save as… to keep it":"Нажмите «Применить», чтобы использовать, или «Сохранить как…», чтобы сохранить","Apply, or Save as… to keep edits":"Примените или сохраните изменения через «Сохранить как…»","Edits become a new theme":"Изменения будут сохранены как новая тема","Differs from the copy in My themes":"Отличается от копии в «Моих темах»","Save to add it to My themes":"Сохраните, чтобы добавить в «Мои темы»","Discard changes":"Не сохранять","Save theme":"Сохранить тему","Theme already saved":"Тема уже сохранена","Save another copy":"Сохранить ещё одну копию","Save":"Сохранить","Save as…":"Сохранить как…","Save edits to this theme in My themes":"Сохранить изменения темы в «Моих темах»","Save as a new theme in My themes":"Сохранить новую тему в «Моих темах»","Reset edits":"Сбросить изменения","Restore this theme to its last saved or starting colours":"Восстановить последние сохранённые или исходные цвета темы","Export…":"Экспорт…","Export Theme":"Экспортировать тему","Edit a copy":"Изменить копию","Change the colours of this theme":"Изменить цвета темы","Change the colours; saving makes a new theme":"Изменить цвета; при сохранении будет создана новая тема","In theme menu":"В меню тем","Show in theme menu":"Показывать в меню тем","Show or hide this theme in the quick theme menu; the active theme stays visible":"Показать или скрыть тему в быстром меню. Активная тема остаётся видимой.","Remove from project":"Удалить из проекта","Rename theme":"Переименовать тему","Manual":"Вручную","Click a colour to change it. The other colours follow automatically; colours set by hand in Full keep their values.":"Нажмите на цвет для изменения. Остальные цвета обновятся автоматически; вручную заданные цвета в полном наборе сохранят свои значения.","Default uses REAPER’s colours. Use Save as… to keep this palette as a custom theme.":"Тема по умолчанию использует цвета REAPER. Чтобы сохранить палитру как пользовательскую тему, выберите «Сохранить как…».","Background":"Фон","Controls":"Элементы управления","Accent":"Акцент","Header opacity":"Прозрачность заголовка","Rebuild all colours":"Пересоздать все цвета","Replace all manual RGB colours with the generated palette?":"Заменить все вручную заданные цвета RGB автоматически созданной палитрой?","Rebuild palette":"Пересоздать палитру","Rebuild":"Пересоздать","Label text":"Текст подписи","Window background":"Фон окна","Field":"Поле","Field · hovered":"Поле · наведение","Field · active":"Поле · активное","Button · hovered":"Кнопка · наведение","Button · active":"Кнопка · активная","Header · hovered":"Заголовок · наведение","Header · active":"Заголовок · активный","Check mark":"Галочка","Slider grab":"Ползунок","Slider grab · active":"Ползунок · активный","Automatically generated colours":"Автоматически созданные цвета","These colours are calculated from your palette and cannot be edited separately.":"Эти цвета вычисляются из палитры; редактировать их по отдельности нельзя.","Title colours are used when the project’s Title bar option is Theme colours. Menu bar colour is used with a menu bar.":"Цвета заголовка применяются при параметре «Строка заголовка → Цвета темы». Цвет строки меню используется при наличии меню.","ImGui colour":"Цвет ImGui","Value":"Значение","Rule":"Правило","Palette collection":"Коллекция палитр","Click a palette to load it into the editor. Your project changes only when you press Apply.":"Выберите палитру, чтобы загрузить её в редактор. Проект изменится только после нажатия «Применить».","Palettes from":"Палитры из","Import…":"Импорт…","No themes here yet.":"Здесь пока нет тем.","Active":"Активная","Select theme":"Выбрать тему","Close":"Закрыть","OK":"ОК","Cancel":"Отмена","Yes":"Да","No":"Нет","Continue":"Продолжить","Confirm":"Подтвердить","Delete Theme":"Удаление темы","Delete theme":"Удалить тему","Delete failed":"Ошибка удаления","Import failed":"Ошибка импорта","Import Theme":"Импорт темы","Export Lua":"Экспорт Lua","Export Lua Script":"Экспорт Lua-скрипта","Export ReaImGui Lua":"Экспорт Lua для ReaImGui","Preflight":"Предэкспортная проверка","Preflight check":"Проверка перед экспортом","Check":"Проверить","Run checks":"Запустить проверку","Checking…":"Проверка…","Passed":"Успешно","Warnings":"Предупреждения","Errors":"Ошибки","Error":"Ошибка","Warning":"Предупреждение","Info":"Информация","Valid":"Допустимо","Invalid":"Недопустимо","Failed":"Не удалось","Ready":"Готово","Done":"Готово","Copy to clipboard":"Копировать в буфер обмена","Copied":"Скопировано","Download":"Скачать","Download Lua":"Скачать Lua","All checks passed":"Все проверки пройдены","Print":"Печать","Show details":"Подробнее","Hide details":"Скрыть подробности","Show more":"Показать ещё","Show less":"Скрыть","ReaUI project":"Проект ReaUI","Untitled project":"Безымянный проект","No unsaved projects to restore.":"Нет несохранённых проектов для восстановления.","Restore projects":"Восстановление проектов","Restore":"Восстановить","Save project as":"Сохранить проект как","Load failed":"Ошибка открытия","Save failed":"Ошибка сохранения","Recovery failed":"Ошибка восстановления","Unsaved changes":"Несохранённые изменения","Saving…":"Сохранение…","Autosave failed":"Ошибка автосохранения","Loaded":"Загружено","Failed to load project":"Не удалось загрузить проект","Recovery draft saved locally in this browser at":"Резервная копия проекта сохранена в этом браузере:","Saving a local recovery draft":"Сохранение локальной резервной копии","Changes are waiting to be saved locally":"Изменения ожидают локального сохранения","New project has no unsaved changes":"В новом проекте нет несохранённых изменений","Loaded project has no unsaved changes":"В открытом проекте нет несохранённых изменений","The recovery draft could not be applied. It has not been deleted.":"Не удалось восстановить резервную копию. Она не удалена.","Stored projects could not be read.":"Не удалось прочитать сохранённые проекты.","Save the current project before restoring another one?":"Сохранить текущий проект перед восстановлением другого?","Save the current project before loading another one?":"Сохранить текущий проект перед открытием другого?","The project root must be an object.":"Корневой элемент проекта должен быть объектом.","The project shapes field is required and must be an array.":"Поле shapes обязательно и должно быть массивом.","This project version is not supported.":"Эта версия проекта не поддерживается.","This file is not valid JSON.":"Файл содержит некорректный JSON.","This file is not a ReaUI theme: it is not a JSON object.":"Это не тема ReaUI: содержимое не является объектом JSON.","This file is not a ReaUI theme: \"format\" is not \"reaui-theme\".":"Это не тема ReaUI: значение \"format\" отличается от \"reaui-theme\".","This theme file has no valid format version.":"В файле темы отсутствует корректная версия формата.","The file contains no theme.":"Файл не содержит темы.","The theme has no colours.":"В теме отсутствуют цвета.","The theme needs a valid \"childBg\" and a valid \"text\" colour.":"В теме должны быть корректные цвета \"childBg\" и \"text\".","The theme could not be added.":"Не удалось добавить тему.","The file could not be read.":"Не удалось прочитать файл.","Nothing was imported.":"Импорт не выполнен.","It is in the theme list now - click it to apply. The current theme is unchanged.":"Тема добавлена в список. Выберите её для применения. Текущая тема не изменилась.","Could not change the theme menu. Check browser storage and try again.":"Не удалось изменить меню тем. Проверьте хранилище браузера и повторите попытку.","Could not save the theme. Check browser storage and try again.":"Не удалось сохранить тему. Проверьте хранилище браузера и повторите попытку.","Could not apply the theme.":"Не удалось применить тему.","The theme could not be deleted. Check browser storage and try again.":"Не удалось удалить тему. Проверьте хранилище браузера и повторите попытку.","no callback event selected — this code will never run":"Не выбрано событие обработчика — этот код не будет выполняться","compiled once at startup via CreateFunctionFromEEL":"Компилируется один раз при запуске через CreateFunctionFromEEL","radio group":"группа переключателей","radio value":"значение переключателя","bullet (tree: replaces arrow)":"маркер (в дереве вместо стрелки)","start angle":"начальный угол","end angle":"конечный угол","link angles":"связать углы","arc mode":"режим дуги","header color":"цвет заголовка","header value":"значение заголовка","blocked: shape needs at least one of fill/stroke":"Невозможно: фигуре нужна хотя бы заливка или обводка","value must be finite":"Значение должно быть конечным числом","value must be an integer":"Значение должно быть целым числом","value is below the native API range":"Значение меньше допустимого диапазона API","value is above the native API range":"Значение больше допустимого диапазона API","callback events":"события обработчика","data type":"тип данных","ReadOnly":"Только чтение","Password":"Пароль","Pass":"Пароль","CharsDecimal":"Десятичные символы","Dec":"Дес.","CharsHexadecimal":"Шестнадцатеричные символы","Hex":"HEX","EnterReturnsTrue":"Подтверждение Enter","AllowTabInput":"Ввод Tab","CtrlEnterForNewLine":"Новая строка по Ctrl+Enter","CallbackEdit":"При изменении","CallbackAlways":"Всегда","CallbackCharFilter":"Фильтр символов","CallbackCompletion":"Автодополнение","CallbackHistory":"История","OnEdit":"Изменение","Always":"Всегда","CharFilter":"Фильтр","OnTab":"По Tab","OnUp/Down":"По ↑/↓","NoAlpha":"Без альфа","NoPicker":"Без палитры","NoInputs":"Без полей","NoTooltip":"Без подсказки","NoTip":"Без подсказки","NoLabel":"Без подписи","NoSidePreview":"Без бокового образца","NoSidePrev":"Без бокового образца","NoSmallPreview":"Без маленького образца","NoSmallPrev":"Без мини-образца","NoOptions":"Без параметров","NoDragDrop":"Без перетаскивания","NoBorder":"Без границы","DisplayRGB":"Показать RGB","DisplayHSV":"Показать HSV","DisplayHex":"Показать HEX","Uint8":"0–255","Float":"Дробные","InputRGB":"Ввод RGB","InputHSV":"Ввод HSV","PickerHueBar":"Полоса оттенка","HueBar":"Полоса оттенка","PickerHueWheel":"Цветовой круг","HueWheel":"Цветовой круг","AlphaBar":"Шкала альфа","AlphaPreviewHalf":"Полупрозрачный образец","HalfPrev":"Полуобразец","AlphaNoBg":"Без фона","NoBg":"Без фона","AlphaOpaque":"Непрозрачный образец","Opaque":"Непрозрачный","No elements yet":"Элементов пока нет","Add a widget or draw object, then click the canvas.":"Добавьте виджет или графический объект, затем щёлкните на холсте.","↑ height fixed by ImGui":"↑ высота задаётся ImGui","↑ size fixed by ImGui":"↑ размер задаётся ImGui","⊞ Snap:":"⊞ Привязка:","click=select Shift=range Cmd/Ctrl=toggle":"щелчок — выделить; Shift — диапазон; Cmd/Ctrl — переключить","click=select Shift=range Cmd/Ctrl=toggle":"щелчок — выделить; Shift — диапазон; Cmd/Ctrl — переключить","drag to place (or click for default size)":"протяните для размещения (или щёлкните для стандартного размера)","Structure":"Структура","Constraints":"Привязки","Constraints apply when the window is resizable":"Привязки работают при изменяемом размере окна","Make the window resizable":"Разрешить изменение размера окна","Pinned to":"Привязка к","Left":"Слева","Right":"Справа","Center":"Центр","Top":"Сверху","Bottom":"Снизу","Left+Right":"Слева + справа","Top+Bottom":"Сверху + снизу","Left · Top":"Слева · сверху","Horizontal":"По горизонтали","Vertical":"По вертикали","Name":"Имя","Enable loop":"Включить цикл","custom look (size, border, colours, click area)":"Пользовательский вид (размер, границы, цвета, область нажатия)","Constraint presets":"Шаблоны привязок","Pin left top":"Привязать слева сверху","Pin center top":"Привязать по центру сверху","Pin right top":"Привязать справа сверху","Pin left center":"Привязать слева по центру","Pin center":"Привязать к центру","Pin right center":"Привязать справа по центру","Pin left bottom":"Привязать слева снизу","Pin center bottom":"Привязать по центру снизу","Pin right bottom":"Привязать справа снизу","Horizontal constraint":"Горизонтальная привязка","Vertical constraint":"Вертикальная привязка","Select and edit this element":"Выделить и изменить этот элемент","Built-in · in use":"Встроенная · используется","Built-in · active":"Встроенная · активна","Vintage":"Винтажные","Cold":"Холодные","Warm":"Тёплые","Earth":"Землистые","Vintage palettes":"Винтажные палитры","Dark palettes":"Тёмные палитры","Cold palettes":"Холодные палитры","Warm palettes":"Тёплые палитры","Earth palettes":"Землистые палитры","Default — built-in":"Default — встроенная","Edit a copy of Light":"Изменить копию Light","Use this theme in the project and close. Edits stay in this project until you save them.":"Применить тему к проекту и закрыть редактор. Изменения останутся в проекте, пока вы не сохраните тему отдельно.","none":"нет","sample data":"пример данных","// EEL2 — runs on the selected Callback* event":"// EEL2 — выполняется при выбранном событии Callback*","Normal":"Обычный","Hovered":"Наведение","Active header":"Активный заголовок","Hovered header":"Заголовок при наведении","Parameter":"Параметр","Gain":"Усиление","Mix":"Смешивание","More":"Ещё","Sample plugin":"Пример плагина","Enable processing":"Включить обработку","Instruments":"Инструменты","Popup / tooltip selected text":"Всплывающая подсказка и выделенный текст","Documentation ↗":"Документация ↗","Documentation":"Документация","Current theme":"Текущая тема","New Theme":"Новая тема","View → Interface mode":"Вид → Режим интерфейса","File Edit View":"Файл Правка Вид","▾ Header":"▾ Заголовок","▾ Hovered header":"▾ Заголовок при наведении","▾ Active header":"▾ Активный заголовок","Popup / tooltip":"Всплывающее окно / подсказка","selected text":"выделенный текст","Disable":"Отключить","Basic layout":"Базовая компоновка","Title bar":"Строка заголовка","Edited":"Изменено","Edit theme":"Изменить тему","Edit a copy of":"Изменить копию","Theme":"Тема","Root":"Корень","Insert":"Вставить","Delete all":"Удалить всё","Clear All?":"Очистить всё?","ReaUI Builder — About":"ReaUI Builder — О программе","Keyboard shortcuts":"Сочетания клавиш","About ReaUI Builder":"О ReaUI Builder","Report a bug":"Сообщить об ошибке","Ready to export":"Готово к экспорту","Export failed: nothing was generated":"Экспорт не удался: ничего не сгенерировано","Nothing was generated, so there is nothing to copy":"Ничего не сгенерировано — копировать нечего","Nothing was generated, so there is nothing to download":"Ничего не сгенерировано — скачивать нечего","Load cancelled":"Загрузка отменена","Invalid table column settings":"Некорректные настройки столбцов таблицы","Adaptive table analysis is partial":"Проверка адаптивных таблиц выполнена частично","The project changed while the file was being read, so the file was not opened. Your current project is unchanged.":"Проект изменился, пока читался файл, поэтому файл не открыт. Текущий проект не изменён.","No export blockers or warnings detected.":"Ошибок и предупреждений, препятствующих экспорту, нет.","Arrow keys":"Клавиши со стрелками","Nudge selection (grid step, or 1 px with Snap off)":"Переместить выделенное на шаг сетки (или на 1 пиксель без привязки)","Shift + Arrow keys":"Shift + стрелки","Nudge selection by 10 steps":"Переместить выделенное на 10 шагов","Copy selection":"Копировать выделенное","Duplicate selection":"Дублировать выделенное","Delete selection":"Удалить выделенное","Escape":"Esc","Deselect, cancel tool/polygon, or close an open dialog/menu":"Снять выделение, отменить инструмент/многоугольник или закрыть окно/меню","Enter (Polygon)":"Enter (многоугольник)","Finish polygon":"Завершить многоугольник","Shift + click object":"Shift + щелчок по объекту","Extend selection from the anchor object":"Расширить выделение от опорного объекта","⌘/Ctrl + click object":"⌘/Ctrl + щелчок по объекту","Toggle object in selection":"Добавить объект к выделению или снять выделение","Shift + marquee":"Shift + рамка выделения","Add objects intersecting the marquee to selection":"Добавить объекты, пересекаемые рамкой, к выделению","Toggle objects intersecting the marquee":"Переключить выделение объектов, пересекаемых рамкой","Alt + drag object":"Alt + перетаскивание объекта","Drag a copy":"Перетащить копию объекта","U + drag container":"U + перетаскивание контейнера","Unlock for this move: leave its contents behind and ignore widgets underneath":"Временно разблокировать перемещение: оставить содержимое на месте и игнорировать виджеты под контейнером","Space + drag canvas":"Пробел + перетаскивание холста","Pan canvas":"Переместить холст","Zoom to cursor":"Масштабировать относительно указателя","Right-click canvas":"Правая кнопка мыши на холсте","Open the widget menu at the pointer":"Открыть меню виджетов у указателя","Shift + drawing tool button":"Shift + кнопка инструмента рисования","Keep Rectangle, Circle, Line, Triangle, or Arc active":"Оставить активными «Прямоугольник», «Окружность», «Линия», «Треугольник» или «Дуга»","Polygon: double-click / first point":"Многоугольник: двойной щелчок / первая вершина","Visual layout tool for ReaImGui (REAPER DAW).":"Визуальный редактор интерфейсов ReaImGui (REAPER).","Generates Lua code using the ReaImGui API.":"Генерирует Lua-код на основе API ReaImGui.","Single-file Vanilla HTML/CSS/JS — no build tools.":"Один HTML-файл с CSS и JavaScript, без сборки и зависимостей.","Report a Bug":"Сообщить об ошибке","Describe what happened, what you expected, and how to reproduce it.":"Опишите, что произошло, как должно было работать и как воспроизвести ошибку.","Copy Report":"Копировать отчёт","Download Report":"Скачать отчёт","Send the report to:":"Отправьте отчёт по адресу:","Copied ✓":"Скопировано ✓","Include my layout (helps reproduce it; sends the whole project)":"Включить мой макет (для воспроизведения ошибки; прикладывается весь проект)","The text below is everything that gets sent - the last 50 actions plus your build and window size. Nothing else is collected.":"Ниже приведён полный состав отчёта: последние 50 действий, версия сборки и размер окна. Другие данные не собираются.","Popups / text":"Всплывающие окна и текст","Borders / scrollbars":"Границы и прокрутка","Tables":"Таблицы","Window / menu":"Окно и меню","Plots / tree":"Графики и дерево","7 colours set by hand":"7 цветов заданы вручную","shift(Background, 3% away from background)":"shift(Фон, 3% от исходного фона)","mix(Background, Text, 55%)":"mix(Фон, Текст, 55%)","mix(Background, Check mark, 45%)":"mix(Фон, Галочка, 45%)","= Check mark":"= Галочка","= Text":"= Текст","mix(Background, Text, 30%)":"mix(Фон, Текст, 30%)","mix(Background, Field, 35%)":"mix(Фон, Поле, 35%)","= Field":"= Поле","= Hovered field":"= Поле при наведении","= Active field":"= Активное поле","= Header (opaque)":"= Заголовок (непрозрачный)","mix(Background, Text, 35%)":"mix(Фон, Текст, 35%)","mix(Background, Text, 18%)":"mix(Фон, Текст, 18%)","= Background":"= Фон","shift(Background, 5% away from background)":"shift(Фон, 5% от исходного фона)","mix(Background, Field, 60%)":"mix(Фон, Поле, 60%)","mix(Background, Header, 80%)":"mix(Фон, Заголовок, 80%)","mix(Background, Field, 40%)":"mix(Фон, Поле, 40%)","mix(Background, Field, 50%)":"mix(Фон, Поле, 50%)","shift(Check mark, 12% away from background)":"shift(Галочка, 12% от исходного фона)","mix(Background, Text, 65%)":"mix(Фон, Текст, 65%)","= Border":"= Граница","= Active header (fallback: Active button, Header)":"= Активный заголовок (иначе: Активная кнопка, Заголовок)","= Hovered header (fallback: Hovered button)":"= Заголовок при наведении (иначе: Кнопка при наведении)","= Check mark (fallback: Slider grab)":"= Галочка (иначе: Ползунок)","Visual layout tool for ReaImGui (REAPER DAW).\nGenerates Lua code using the ReaImGui API.\nSingle-file Vanilla HTML/CSS/JS — no build tools.":"Визуальный редактор интерфейсов ReaImGui для REAPER.\nГенерирует Lua-код через API ReaImGui.\nРаботает как единый HTML-файл с CSS и JavaScript, без сборки.","Popup / tooltip ":"Всплывающее окно / подсказка ","Project":"Проект","Element":"Элемент","Project background colour is invalid":"Некорректный цвет фона проекта","Use a hexadecimal colour in #RRGGBB format.":"Укажите цвет в шестнадцатеричном формате #RRGGBB.","Element has no ID":"У элемента отсутствует ID","Export maps and parent relationships require a stable element ID.":"Для экспорта и связей родительских объектов необходим постоянный ID элемента.","Duplicate element ID:":"Повторяющийся ID элемента:","IDs must be unique; the exporter uses them as map keys.":"ID должны быть уникальны: генератор использует их как ключи.","Unknown element type:":"Неизвестный тип элемента:","The Lua exporter supports widgets and the documented drawing primitives only.":"Экспорт Lua поддерживает только виджеты и описанные графические примитивы.","Parent ID is ambiguous":"Неоднозначный ID родительского объекта","Parent element is missing":"Родительский объект отсутствует","Cyclic parent relationship":"Циклическая вложенность","The parent chain loops back to an element already visited.":"Цепочка родительских объектов содержит цикл.","Invalid position or size":"Некорректные координаты или размер","X, Y, width and height must be finite numbers; width and height must be greater than zero.":"X, Y, ширина и высота должны быть конечными числами; ширина и высота — больше нуля.","Unknown widget type:":"Неизвестный тип виджета:","The Lua exporter has no contract for this widget.":"Генератор Lua не поддерживает этот тип виджета.","Choose Left, Right, Up or Down.":"Выберите Left, Right, Up или Down.","Arrow direction is not supported":"Неподдерживаемое направление стрелки","Polygon has fewer than three points":"У многоугольника менее трёх вершин","A polygon needs at least three points to export.":"Для экспорта многоугольнику необходимо минимум три вершины.","Polygon contains a nonnumeric point":"У многоугольника есть некорректная вершина","Every polygon point needs finite numeric X and Y coordinates.":"У каждой вершины должны быть конечные числовые координаты X и Y.","Polygon outline crosses itself":"Контур многоугольника пересекает сам себя","ImGui fills only a polygon whose outline does not cross, touch or turn back on itself. Move a point, split the shape into separate polygons, or disable its fill to export the outline only.":"ImGui может заливать только многоугольник без самопересечений и касаний контура. Переместите вершину, разделите фигуру или отключите заливку.","Polygon fill cannot be exported":"Не удалось экспортировать заливку многоугольника","Builder could not split this polygon into triangles for ImGui. Remove repeated points, or disable its fill to export the outline only.":"Не удалось разбить многоугольник на треугольники для ImGui. Удалите повторяющиеся вершины либо отключите заливку.","Line points are invalid":"Некорректные точки линии","A line needs exactly two points with finite numeric X and Y coordinates.":"Линии нужны ровно две точки с конечными числовыми координатами X и Y.","Invalid numeric property:":"Некорректный числовой параметр:","The value must be a finite number.":"Значение должно быть конечным числом.","Invalid StyleRegion property:":"Некорректный параметр StyleRegion:","Use a finite value inside the supported range.":"Укажите конечное число в допустимом диапазоне.","Invalid colour property:":"Некорректный параметр цвета:","Invalid colour flags":"Некорректные флаги цвета","Could not resolve export bounds":"Не удалось определить границы экспорта","Check the element parent chain and geometry.":"Проверьте геометрию и вложенность элемента.","Widget will not be exported":"Виджет не будет экспортирован","Draw object will not be exported":"Графический объект не будет экспортирован","It does not intersect the canvas, so it is omitted from the Lua.":"Объект не пересекает холст и исключён из экспорта Lua.","Draw object crosses the canvas edge":"Графический объект пересекает границу холста","Only the intersecting part will be visible in the exported plugin.":"В экспортированном интерфейсе будет видна только часть объекта внутри холста.","Link URL is empty":"Адрес ссылки не указан","The exporter will use https://example.com as a fallback.":"Генератор использует резервный адрес https://example.com.","Callback flags require EEL callback code":"Для флагов Callback необходим код обработчика EEL","Add a non-empty EEL callback or disable all Callback* flags.":"Добавьте код обработчика EEL или отключите все флаги Callback*.","Minimum is not numeric":"Минимум не является числом","Maximum is not numeric":"Максимум не является числом","Enter a finite number or clear the field.":"Введите конечное число или очистите поле.","Minimum is greater than maximum":"Минимум больше максимума","Swap the values or correct the numeric range.":"Поменяйте значения местами или исправьте диапазон.","Minimum equals maximum":"Минимум равен максимуму","The control has no usable value range.":"У элемента нет допустимого диапазона значений.","Step should be zero or positive":"Шаг должен быть неотрицательным","Negative or non-numeric step values can behave unexpectedly.":"Отрицательный или нечисловой шаг может вызвать некорректную работу.","Speed should be greater than zero":"Скорость должна быть больше нуля","Drag controls need a positive finite speed.":"Для элементов Drag требуется положительная конечная скорость.","Component count must be 1–4":"Число компонентов должно быть от 1 до 4","The selected widget family only supports one to four components.":"Этот тип виджета поддерживает от одного до четырёх компонентов.","Array size must be 2–64":"Размер массива должен быть от 2 до 64","N-wide controls allocate a ReaScript array of this size.":"Многокомпонентные элементы создают массив ReaScript указанного размера.","Color alpha must be 0–255":"Альфа-канал должен быть в диапазоне 0–255","The Lua color packer expects an 8-bit alpha value.":"Упаковка цвета в Lua требует 8-битного значения альфа-канала.","Will not be exported with its container":"Не экспортируется вместе с контейнером","Widget is unreachable by the exporter":"Виджет недоступен генератору","Its parent chain is not traversed by the generated Lua.":"Сгенерированный Lua-код не обходит цепочку родительских объектов виджета.","Widget overlaps":"Виджет перекрывает","Their occupied areas intersect on the canvas. Move or resize one of the widgets before export.":"Области виджетов на холсте пересекаются. Перед экспортом переместите один из виджетов или измените его размер.","Overlaps":"Перекрывает","Leaves the window":"Выходит за границы окна","Too small at the minimum window size":"Слишком мал при минимальном размере окна","Export name collides after sanitizing":"Совпадение экспортируемого имени после нормализации","Radio value is not numeric":"Значение переключателя не является числом","RadioButtonEx requires a finite numeric value.":"Для RadioButtonEx требуется конечное числовое значение.","Duplicate radio value in group":"Повторяющееся значение в группе переключателей","Flag bit must be an integer 0–":"Номер бита должен быть целым числом от 0 до","Duplicate bit in flag group":"Повторяющийся бит в группе флагов","Plot values are invalid":"Некорректные значения графика","Enter a number or clear the field for automatic scaling.":"Введите число или оставьте поле пустым для автоматического масштаба.","Scale min is not below scale max":"Минимум шкалы не меньше максимума","The plot has no usable value range.":"У графика нет допустимого диапазона значений.","PlotLines needs at least two values":"PlotLines требует минимум два значения","With one value ImGui draws an empty frame.":"При одном значении ImGui рисует пустую рамку.","TabBar has no tabs":"В TabBar отсутствуют вкладки","The exported tab bar will have no visible tab items.":"В экспортированной панели не будет видимых вкладок.","Active tab does not exist":"Активная вкладка отсутствует","Choose one of the TabItems contained by this TabBar.":"Выберите одну из вкладок TabItem этой панели TabBar.","TabItem is not inside a TabBar":"TabItem находится вне TabBar","Standalone TabItems are not emitted correctly.":"Отдельные TabItem вне TabBar экспортируются некорректно.","Table rows and columns must be positive integers":"Число строк и столбцов таблицы должно быть положительным целым числом","Correct rowCount and columnCount before export.":"Перед экспортом исправьте rowCount и columnCount.","Table cell is outside the table grid":"Ячейка выходит за границы таблицы","Row and column indices must fit the parent table dimensions.":"Индексы строки и столбца должны соответствовать размеру родительской таблицы.","Duplicate table cell":"Повторяющаяся ячейка таблицы","Only one TableCell can occupy each row and column.":"Каждую позицию строки и столбца может занимать только одна TableCell.","Table has missing structural cells":"В таблице отсутствуют структурные ячейки","TableCell is not inside a Table":"TableCell находится вне Table","Standalone structural cells are not emitted correctly.":"Отдельные структурные ячейки экспортируются некорректно.","Menus past the right edge are cut off in REAPER":"Меню, выходящее за правую границу, будет обрезано в REAPER","Frame padding Y is":"Внутренний отступ рамки по Y равен","Copy generated Lua":"Копировать сгенерированный Lua","Download generated Lua":"Скачать сгенерированный Lua","Resolve the errors above to enable copy":"Исправьте ошибки выше, чтобы разблокировать копирование","Resolve the errors above to enable download":"Исправьте ошибки выше, чтобы разблокировать скачивание","Ready with":"Готово, но есть","Select this element on canvas":"Выделить этот элемент на холсте"}; const HINTS = {"variant-row":"Вариант виджета: Int или Double, RGB или RGBA, Lines или Histogram. Выберите перед размещением; позднее сменить вариант нельзя.","name-row":"Имя элемента. У виджета используется в экспортируемом скрипте для переменных состояния и скрытого идентификатора ImGui. При настройке нового виджета задаётся автоматически. `state._…` `##`","parent-row":"Контейнеры, содержащие этот элемент, начиная с внешнего. Перетащите элемент в контейнер или за его пределы, чтобы изменить вложенность.","label-row":"Видимый текст: подпись виджета либо текст графического объекта. Дважды щёлкните по тексту, прямоугольнику или окружности на холсте для изменения на месте.","hint-row":"Серый замещающий текст, пока поле пусто. `InputTextWithHint`","value-row":"Текст значения в поле; подпись располагается справа. `LabelText`","url-row":"Адрес, открываемый браузером при нажатии на ссылку. `TextLinkOpenURL`","direction-row":"Направление стрелки. `ArrowButton` `Dir_Left` `Right` `Up` `Down`","component-count-row":"Количество значений, редактируемых рядом (1–4), например X/Y или XYZ. Для 2–4 компонентов используется соответствующая функция ImGui. `SliderInt3`","array-size-row":"Количество редактируемых значений (2–64) в одном массиве. `reaper_array` `SliderDoubleN` `DragDoubleN` `InputDoubleN`","min-row":"Нижняя граница значения. Перетаскивание ограничено ею, но ввод через Ctrl+щелчок может выйти за границу без флага Clamp. `v_min`","max-row":"Верхняя граница значения. Перетаскивание ограничено ею, но ввод через Ctrl+щелчок может выйти за границу без флага Clamp. `v_max`","speed-row":"Скорость изменения при перетаскивании в расчёте на пиксель движения мыши. При 0.2 для изменения на единицу требуется 5 пикселей. `v_speed`","step-row":"Шаг кнопок − / +. Значение 0 скрывает кнопки. `step`","step-fast-row":"Ускоренный шаг кнопок − / + при удержании Ctrl. Значение 0 означает обычный шаг. `step_fast`","format-row":"Формат отображения в стиле printf, например %.2f dB или %d%%. Также определяет точность редактирования. Пустое поле — формат по умолчанию. `%.2f dB` `%d%%`","format-min-row":"Формат отображения нижней границы, например Min: %d. `Min: %d` `format`","format-max-row":"Формат отображения верхней границы, например Max: %d. `Max: %d` `format_max`","numeric-flags-row":"Дополнительные параметры поведения числового поля или ползунка. `SliderFlags_*`","numeric-flags:AlwaysClamp":"Ограничить: значение, введённое через Ctrl+щелчок, также удерживается в пределах минимума и максимума. `SliderFlags_AlwaysClamp`","numeric-flags:Logarithmic":"Логарифмическая шкала с повышенной точностью на нижнем участке. `SliderFlags_Logarithmic`","numeric-flags:NoInput":"Отключает ввод значения через Ctrl+щелчок и клавишу Enter. `SliderFlags_NoInput`","numeric-flags:WrapAround":"Циклический переход с максимума на минимум и обратно при перетаскивании. Только для числовых полей Drag. `SliderFlags_WrapAround`","tooltip-row":"Текст подсказки в REAPER при наведении на виджет. Пустое поле — без подсказки. `SetItemTooltip`","bullet-row":"Добавляет маркер слева от виджета, не перемещая сам виджет. `DrawList_AddCircleFilled`","bullet-row:tree":"Показывает маркер вместо стрелки сворачивания. Узел по-прежнему можно раскрывать и сворачивать. `TreeNodeFlags_Bullet`","highlight-row":"Подсвечивает строку так, как при наведении указателя. `SelectableFlags_Highlight`","sr-disabled-row":"Делает содержимое области неактивным и блокирует ввод. `BeginDisabled` `EndDisabled`","tree-lines-row":"Направляющие линии от узла к дочерним узлам.","tree-lines:none":"Нет: направляющие линии отсутствуют (по умолчанию).","tree-lines:full":"Полные: линии соединяют дочерние узлы; вертикальная линия тянется до конца содержимого. `TreeNodeFlags_DrawLinesFull`","tree-lines:toNodes":"До узлов: линии соединяют дочерние узлы; вертикальная линия заканчивается на последнем дочернем узле. `TreeNodeFlags_DrawLinesToNodes`","tab-button-row":"Добавляет на одном из краёв панели вкладок кнопку (например, «+»), которую нельзя выбрать как вкладку. `TabItemButton`","tab-button:none":"Кнопка вкладки отсутствует (по умолчанию).","tab-button:leading":"В начале панели вкладок, слева. `TabItemFlags_Leading`","tab-button:trailing":"В конце панели вкладок, справа. `TabItemFlags_Trailing`","tab-button-label-row":"Текст кнопки на панели вкладок. Доступен при положении «В начале» или «В конце».","text-tone-row":"Цвет текста с переносом. «Авто» использует цвет темы, «Тёмный» и «Светлый» фиксируют цвет. `PushStyleColor(Col_Text)`","panel-bordered-row":"Рисует рамку вокруг панели и добавляет внутренние отступы. `ChildFlags_Borders`","panel-hscroll-row":"Показывает горизонтальную полосу прокрутки, когда содержимое шире панели. `WindowFlags_HorizontalScrollbar`","sr-text-row":"Цвет текста внутри области. Включается отдельным флажком. `PushStyleColor(Col_Text)`","sr-framebg-row":"Цвет фона полей ввода, ползунков и флажков внутри области. Включается отдельным флажком. `Col_FrameBg`","sr-button-row":"Цвет кнопок внутри области. Включается отдельным флажком. `Col_Button`","sr-rounding-row":"Радиус скругления рамок и кнопок внутри области в пикселях. Включается отдельным флажком. `StyleVar_FrameRounding`","sr-framepad-row":"Внутренние отступы между рамкой элемента и текстом по X и Y, в пикселях. В REAPER меняют высоту стандартных элементов управления. `StyleVar_FramePadding`","sr-selalign-row":"Положение текста Selectable внутри области по X и Y: от 0 (лево/верх) до 1 (право/низ). `StyleVar_SelectableTextAlign`","sr-font-row":"Гарнитура, размер и полужирное/курсивное начертание текста внутри области. Включается отдельным флажком. `CreateFont` `PushFont`","color-row":"Начальный цвет ColorEdit/ColorPicker, образец ColorButton или цвет текста TextColored.","color-alpha-row":"Прозрачность цвета: от 0 (прозрачный) до 255 (непрозрачный).","color-flags-row":"Параметры цветового виджета. В сегментированных группах можно выбрать только один вариант. `ColorEditFlags_*`","overlay-row":"Текст поверх индикатора выполнения или графика. По умолчанию ProgressBar показывает процент (кроме анимации), график — ничего. `overlay`","indeterminate-row":"Анимирует индикатор туда и обратно вместо фиксированного уровня. Экспортирует отрицательную долю. `-1.0 * GetTime()`","input-flags-row":"Параметры поведения текстового поля. Флаги Callback определяют события запуска обработчика EEL2. `InputTextFlags_*`","eel-callback-row":"Код EEL2, выполняемый при отмеченных выше событиях; компилируется один раз при запуске. Без выбранного события не запускается. `CreateFunctionFromEEL`","radio-group-row":"Переключатели с одинаковой группой используют одну переменную: выбор одного снимает выбор остальных.","radio-value-row":"Число, записываемое выбранным переключателем в переменную группы. `RadioButtonEx`","flag-group-row":"Флажки группы используют одно целое число; каждый переключает собственный бит. `CheckboxFlags`","flag-bit-row":"Номер переключаемого бита (0–30) общего целого числа. `1<_checked`","cb:size":"Размер квадрата в пикселях (6–64). Размер стандартного флажка зависит от высоты строки; пользовательский имеет указанный размер.","cb:mark":"Вид установленного флажка: галочка ImGui или закрашенный квадрат. × использует цвет галочки из темы. `Col_CheckMark`","cb:bg":"Заливка квадрата. × использует цвет поля из темы. `Col_FrameBg`","cb:border":"Граница квадрата толщиной 1 пиксель и её цвет. × использует цвет границы из темы. `Col_Border`","cb:checked":"Установить флажок при запуске. Предпросмотр показывает метку, а экспорт задаёт исходное состояние true. `state._checked = true`","cb:hit":"Область нажатия: только квадрат, вся строка таблицы или расширенная по горизонтали область. Она не часть квадрата: другие объекты могут её перекрывать и сохраняют собственные нажатия в REAPER. `Selectable` `SpanAllColumns` `AllowOverlap`","cb:hit-extend":"Расширение области нажатия влево и вправо от квадрата, в пикселях.","cb:hover":"Подсветка строки при наведении указателя. × использует цвет темы. Отключено — без подсветки. `Col_HeaderHovered`","table:row-bg":"Цвет фона строки таблицы; × сбрасывает его. `TableSetBgColor(TableBgTarget_RowBg0)`","table:highlight":"Цвет подсветки любой строки во время работы скрипта. Задайте соответствующий флаг состояния для строки (нумерация от 1). Отмеченные строки видны в предпросмотре и экспорте. `state._highlight[row] = true` `TableSetBgColor(TableBgTarget_RowBg1)`","color-flag:NoAlpha":"Не учитывать альфа-канал цвета. `ColorEditFlags_NoAlpha`","color-flag:NoPicker":"Нажатие на образец цвета не открывает палитру. `ColorEditFlags_NoPicker`","color-flag:NoInputs":"Скрывает числовые поля, оставляя только образец цвета. `ColorEditFlags_NoInputs`","color-flag:NoTooltip":"Отключает подсказку при наведении на образец. `ColorEditFlags_NoTooltip`","color-flag:NoLabel":"Скрывает подпись рядом с элементом, но оставляет её в подсказке и палитре. `ColorEditFlags_NoLabel`","color-flag:NoSidePreview":"Заменяет большой образец рядом с палитрой на маленький квадрат, чтобы палитра помещалась в поле. `ColorEditFlags_NoSidePreview`","color-flag:NoSmallPreview":"Скрывает маленький образец цвета рядом с полями. `ColorEditFlags_NoSmallPreview`","color-flag:NoOptions":"Запрещает открытие меню настроек правой кнопкой мыши. `ColorEditFlags_NoOptions`","color-flag:NoDragDrop":"Отключает перетаскивание цвета на элемент и с него. `ColorEditFlags_NoDragDrop`","color-flag:NoBorder":"Убирает границу кнопки. `ColorEditFlags_NoBorder`","color-flag:DisplayRGB":"Показывает значения как R, G, B. `ColorEditFlags_DisplayRGB`","color-flag:DisplayHSV":"Показывает значения как H, S, V. `ColorEditFlags_DisplayHSV`","color-flag:DisplayHex":"Показывает цвет в шестнадцатеричном формате. `ColorEditFlags_DisplayHex`","color-flag:Uint8":"Показывает значения в диапазоне 0–255. `ColorEditFlags_Uint8`","color-flag:Float":"Показывает значения в диапазоне 0.0–1.0. `ColorEditFlags_Float`","color-flag:InputRGB":"Скрипт читает и записывает цвет в формате RGB. `ColorEditFlags_InputRGB`","color-flag:InputHSV":"Скрипт читает и записывает цвет в формате HSV. `ColorEditFlags_InputHSV`","color-flag:PickerHueBar":"Палитра с полосой оттенка и квадратом насыщенности/яркости. `ColorEditFlags_PickerHueBar`","color-flag:PickerHueWheel":"Палитра с цветовым кругом и треугольником насыщенности/яркости. `ColorEditFlags_PickerHueWheel`","color-flag:AlphaBar":"Добавляет в палитру вертикальную шкалу альфа-канала. `ColorEditFlags_AlphaBar`","color-flag:AlphaPreviewHalf":"Половина образца непрозрачна, другая половина прозрачна. `ColorEditFlags_AlphaPreviewHalf`","color-flag:AlphaNoBg":"Убирает шахматный фон за прозрачным цветом. `ColorEditFlags_AlphaNoBg`","color-flag:AlphaOpaque":"Предпросмотр игнорирует альфа-канал, но его можно редактировать. `ColorEditFlags_AlphaOpaque`","input-flag:ReadOnly":"Текст можно выделять и копировать, но нельзя изменять. `InputTextFlags_ReadOnly`","input-flag:Password":"Показывает символы как * и запрещает копирование. `InputTextFlags_Password`","input-flag:CharsDecimal":"Принимает только 0–9 . + - * /. `InputTextFlags_CharsDecimal`","input-flag:CharsHexadecimal":"Принимает только 0–9 и A–F. `InputTextFlags_CharsHexadecimal`","input-flag:EnterReturnsTrue":"Функция сообщает об изменении только при нажатии Enter, а не на каждом вводимом символе. `InputTextFlags_EnterReturnsTrue`","input-flag:AllowTabInput":"Клавиша Tab вставляет символ табуляции вместо перехода к следующему полю. `InputTextFlags_AllowTabInput`","input-flag:CtrlEnterForNewLine":"Enter подтверждает ввод, Ctrl+Enter добавляет новую строку (по умолчанию наоборот). `InputTextFlags_CtrlEnterForNewLine`","input-flag:CallbackEdit":"Вызывает обработчик EEL2 при каждом изменении текста. `InputTextFlags_CallbackEdit`","input-flag:CallbackAlways":"Вызывает обработчик EEL2 каждый кадр, пока поле активно. `InputTextFlags_CallbackAlways`","input-flag:CallbackCharFilter":"Вызывает обработчик EEL2 при вводе каждого символа; обработчик может заменить или отклонить его. `InputTextFlags_CallbackCharFilter`","input-flag:CallbackCompletion":"Вызывает обработчик EEL2 при нажатии Tab, например для автодополнения. `InputTextFlags_CallbackCompletion`","input-flag:CallbackHistory":"Вызывает обработчик EEL2 при нажатии стрелок вверх/вниз, например для истории ввода. `InputTextFlags_CallbackHistory`","me-move":"Перемещает все выделенные элементы на ΔX / ΔY пикселей; при привязке значения округляются до шага сетки. Одна операция отмены. Enter в поле тоже перемещает.","cw":"Ширина области содержимого окна плагина в пикселях. В экспорте — W. `W`","ch":"Высота области содержимого окна плагина под строкой заголовка и меню, в пикселях. В экспорте — H. `H`","bg-mode-default":"По умолчанию: собственный фон не экспортируется, используется цвет окна из темы.","bg-mode-custom":"Пользовательский: экспорт заливает окно указанным ниже цветом. `PushStyleColor(Col_WindowBg)`","grid-toggle-btn":"Показать или скрыть сетку редактора. Только в билдере, не влияет на экспорт.","audit-grid-btn":"Добавляет контрольную сетку в экспортируемый интерфейс для проверки выравнивания в REAPER. Перед выпуском отключите.","cp-sv":"Выбрать насыщенность и яркость цвета фона. Выбор переключает фон в пользовательский режим.","cp-hue":"Выбрать оттенок фона. Выбор переключает фон в пользовательский режим.","cp-cur":"Текущий цвет фона.","cp-eye":"Взять цвет в любой точке экрана.","cp-recents":"Недавно использованные цвета; нажмите для повторного выбора.","bg-alpha":"Смешивает цвет фона с белым. В экспорт передаётся итоговый непрозрачный цвет.","snap-toggle-btn":"Привязка размещения, перемещения и изменения размеров к шагу сетки. Только в билдере, не влияет на экспорт.","grid-step-seg":"Шаг сетки редактора и привязки в пикселях. Только в билдере, не влияет на экспорт.","bg-color-field":"Цвет фона в шестнадцатеричном формате (#RRGGBB). В режиме «По умолчанию» обозначает тему, определяющую фон.","titlebar-option":"Цвета строки заголовка экспортируемого окна. Не действует с темой Default (неактивно).","titlebar-mode-default":"По умолчанию ImGui: собственные цвета строки заголовка.","titlebar-mode-theme":"Цвета темы: строка заголовка использует цвета заданной темы. `Col_TitleBg` `Col_TitleBgActive`","mbx-add-menu":"Добавляет меню в строку меню окна, не меняя размер холста. `BeginMenuBar` `BeginMenu`","mbx:label":"Текст, показываемый для пункта меню.","mbx:name":"Уникальный идентификатор пункта в экспортируемом скрипте: скрытый ID ImGui и, при наличии флажка, переменная состояния. `##` `state._checked`","mbx:shortcut":"Текст сочетания клавиш справа от пункта. Только отображение: ImGui не обрабатывает его автоматически. `MenuItem`","mbx:enabled":"При выключении пункт становится неактивным и не реагирует на нажатие. `MenuItem` `BeginMenu` `enabled`","mbx:checked":"Установлен ли флажок пункта при запуске экспортированного скрипта.","mbx:add-item":"Добавляет обычный пункт после выделенного или внутри выбранного меню. `MenuItem`","mbx:add-check":"Добавляет пункт с флажком, переключаемым нажатием. `MenuItem` `selected`","mbx:add-separator":"Добавляет разделительную линию. `Separator`","mbx:add-submenu":"Добавляет подменю. Максимальная глубина вложенности — 4 уровня. `BeginMenu`","mbx:up":"Перемещает пункт выше в текущем меню.","mbx:down":"Перемещает пункт ниже в текущем меню.","mbx:delete":"Удаляет пункт. Удаление меню также удаляет всё его содержимое.","del-btn":"Удаляет выделенный объект (также клавиша Delete). Для контейнера с виджетами предлагается сохранить содержимое. Удаление можно отменить.","me-delete":"Удаляет все выделенные объекты (также клавиша Delete). Для контейнеров с виджетами предлагается сохранить содержимое. Удаление можно отменить.","group-btn":"Объединяет выделенные объекты в группу: выделение одного выбирает всю группу, перемещение выполняется совместно. Только для редактора, не экспортируется.","ungroup-btn":"Расформировывает группу, оставляя элементы на прежних местах.","group-select-btn":"Добавляет остальные объекты этой группы к выделению.","editor-group-name-row":"Имя группы в списке «Элементы». Используется только редактором, не экспортируется.","window-resize-section":"Разрешение менять размер экспортируемого окна в REAPER и пределы изменения. В базовом режиме показывается краткая сводка.","wr-toggle":"Разрешает изменять размер экспортируемого окна в REAPER; объекты с привязками следуют за его границами. Выключено — фиксированный размер. `SetNextWindowSizeConstraints`","wr-min-w":"Минимальная ширина содержимого окна в пикселях: от 64 до ширины холста. Пустое поле — ширина холста. `SetNextWindowSizeConstraints`","wr-min-h":"Минимальная высота содержимого окна в пикселях (без заголовка и меню): от 64 до высоты холста. Пустое поле — высота холста.","wr-max-w":"Максимальная ширина содержимого окна в пикселях: не меньше ширины холста. Пустое поле — без ограничения. `SetNextWindowSizeConstraints`","wr-max-h":"Максимальная высота содержимого окна в пикселях: не меньше высоты холста. Пустое поле — без ограничения.","wr-basic-summary":"Размер окна можно изменять: диапазон ширины × диапазон высоты в пикселях (∞ — без ограничения). Изменение доступно в расширенном режиме.","pin-grid":"Готовые варианты привязки по двум осям: к углам, к краям или к центру родительского контейнера. Растяжение задаётся ниже.","pin-h:left":"Слева: сохраняет расстояние до левого края родителя (по умолчанию).","pin-h:right":"Справа: сохраняет расстояние до правого края при изменении ширины окна.","pin-h:center":"По центру: объект остаётся по центру родителя по горизонтали.","pin-h:stretch":"Слева и справа: сохраняет отступы от обоих краёв; ширина растёт и уменьшается вместе с родителем.","pin-h:stretch-off":"Растяжение по ширине для этого объекта недоступно: ширину задают ImGui, текст или связанные размеры.","pin-v:top":"Сверху: сохраняет расстояние до верхнего края родителя (по умолчанию).","pin-v:bottom":"Снизу: сохраняет расстояние до нижнего края при изменении высоты окна.","pin-v:center":"По центру: объект остаётся по центру родителя по вертикали.","pin-v:stretch":"Сверху и снизу: сохраняет отступы от обоих краёв; высота меняется вместе с родителем.","pin-v:stretch-off":"Растяжение по высоте для этого объекта недоступно: высоту задают ImGui или содержимое.","pin-grid:in-cell":"В ячейке таблицы привязки действуют относительно ячейки. Ячейка растягиваемого столбца увеличивается вместе с ним.","pin-make-resizable":"Включает «Изменяемый размер окна» на вкладке «Холст». Все привязки сохраняются и без этого режима.","constraints-basic-row":"К каким краям родителя привязан объект при изменении размера окна. Редактируется в расширенном режиме.","basic-edit-advanced":"Переключает билдер в расширенный режим для редактирования скрытых параметров. Проект и экспорт не изменяются."}; const WIDGETS = {"Button":{"what":"Кнопка, которая выполняет действие при нажатии.","use":"Для запуска команд: рендеринга, применения настроек, сброса или операции скрипта."},"SmallButton":{"what":"Компактная кнопка с уменьшенными отступами.","use":"Для дополнительных действий в условиях ограниченного пространства."},"InvisibleButton":{"what":"Невидимая в готовом интерфейсе область, реагирующая на нажатия.","use":"Для обработки щелчков по собственным графическим элементам."},"ArrowButton":{"what":"Небольшая квадратная кнопка со стрелкой.","use":"Для пошагового изменения значений и сворачивания разделов."},"Checkbox":{"what":"Флажок с подписью для включения и отключения параметра. Пользовательский стиль позволяет менять размер, границы и цвета, а также расширять область нажатия до строки таблицы.","use":"Для параметров «включено/выключено»: активации, приглушения, цикла или обхода эффекта."},"RadioButtonEx":{"what":"Группа взаимоисключающих переключателей: активен только один.","use":"Для выбора одного режима из небольшого набора вариантов."},"CheckboxFlags":{"what":"Флажок, переключающий отдельный бит общего целого числа.","use":"Для групп параметров, хранящихся как битовые флаги."},"Text":{"what":"Статическая однострочная текстовая надпись.","use":"Для названий полей, подписей и коротких сообщений состояния."},"LabelText":{"what":"Значение только для чтения с подписью справа.","use":"Для отображения значения и подписи в стандартном выравнивании Dear ImGui."},"BulletText":{"what":"Текстовая строка с маркером в начале.","use":"Для простых маркированных списков и заметок."},"TextWrapped":{"what":"Текст, автоматически переносимый по доступной ширине.","use":"Для длинных описаний и справочных абзацев."},"TextColored":{"what":"Текст заданного цвета.","use":"Для предупреждений, состояний и цветовых обозначений."},"TextDisabled":{"what":"Приглушённый текст неактивного элемента.","use":"Для подсказок и подписей недоступных параметров."},"TextLinkOpenURL":{"what":"Подчёркнутая ссылка, открывающая URL в браузере.","use":"Для документации, сайтов и страниц поддержки."},"TextLink":{"what":"Подчёркнутая текстовая ссылка, сообщающая о нажатии.","use":"Для текстовых команд, например «Подробнее». Место для обработчика отмечается при экспорте."},"Separator":{"what":"Тонкая горизонтальная разделительная линия.","use":"Для визуального разделения областей интерфейса."},"SeparatorText":{"what":"Разделительная линия с текстом по центру.","use":"Для заголовков разделов и отделения блоков."},"Slider":{"what":"Горизонтальный ползунок для числового значения.","use":"Для ограниченных диапазоном величин: усиления, баланса или порога."},"VSlider":{"what":"Вертикальный ползунок для числового значения.","use":"Для фейдеров, уровней и вертикальных регуляторов."},"SliderAngle":{"what":"Ползунок угла в градусах.","use":"Для поворота, панорамирования и фазы."},"SliderN":{"what":"Несколько ползунков для многокомпонентного значения.","use":"Для векторов и цветовых каналов, например RGB."},"Drag":{"what":"Числовое поле, изменяемое перетаскиванием влево или вправо.","use":"Для точной настройки значений, которым не нужен ползунок."},"DragN":{"what":"Несколько полей с изменением перетаскиванием.","use":"Для координат и многокомпонентных векторов X/Y/Z."},"DragRange":{"what":"Два связанных поля, задающих минимум и максимум.","use":"Для диапазонов: нижней и верхней границы, начала и конца."},"Input":{"what":"Поле числового ввода с кнопками уменьшения и увеличения.","use":"Для точного ввода целых и дробных чисел."},"InputN":{"what":"Группа числовых полей.","use":"Для точного ввода многокомпонентных значений."},"InputText":{"what":"Однострочное поле ввода текста.","use":"Для имён, путей и коротких текстовых значений."},"InputTextWithHint":{"what":"Текстовое поле с замещающей подсказкой.","use":"Для полей, где полезно показать пример ожидаемого ввода."},"InputTextMultiline":{"what":"Многострочное поле ввода текста.","use":"Для заметок, описаний и объёмных текстовых блоков."},"ProgressBar":{"what":"Горизонтальный индикатор выполнения от 0 до 100 %.","use":"Для отображения хода рендеринга, сканирования или длительной операции."},"Plot":{"what":"Компактный график числовых данных: линия или гистограмма.","use":"Для индикаторов, огибающих и истории значений. При экспорте массив заполняется вашими данными."},"Combo":{"what":"Выпадающий список с отображением выбранного пункта.","use":"Для компактного выбора одного варианта из списка."},"ListBox":{"what":"Список с прокруткой, показывающий несколько строк одновременно.","use":"Когда варианты должны оставаться видимыми без раскрытия списка."},"Selectable":{"what":"Строка во всю ширину, которую можно выделить.","use":"Для пользовательских списков, меню и интерактивных строк."},"ColorEdit":{"what":"Компактный редактор цвета с числовыми каналами RGB(A).","use":"Для точного задания цвета непосредственно в интерфейсе."},"ColorPicker":{"what":"Полный выбор цвета с полем насыщенности и полосой оттенка.","use":"Для визуального выбора цвета."},"ColorButton":{"what":"Небольшая кнопка с образцом цвета.","use":"Для индикации цвета или открытия выбора цвета по нажатию."},"Group":{"what":"Невидимый контейнер, объединяющий дочерние виджеты.","use":"Для совместного выравнивания, размещения и обработки нескольких виджетов."},"StyleRegion":{"what":"Невидимая область, переопределяющая стиль дочерних виджетов: цвета, скругление, выравнивание и шрифт. Сама область не занимает места; верхняя полоса на холсте служит только подписью.","use":"Для изменения оформления группы виджетов, включая гарнитуру, размер и начертание шрифта. Если область перекрыта дочерними объектами, выберите её на свободном участке или в панели «Элементы»."},"CollapsingHeader":{"what":"Заголовок во всю ширину, сворачивающий и разворачивающий содержимое.","use":"Для разделов с дополнительными и расширенными настройками."},"TreeNode":{"what":"Разворачиваемый узел с вложенными элементами.","use":"Для иерархий папок, дорожек и параметров."},"TabBar":{"what":"Панель вкладок, переключающая страницы содержимого.","use":"Для разделения интерфейса на вкладки, например «Главная / FX / MIDI»."},"Table":{"what":"Таблица строк и столбцов, содержащая другие виджеты.","use":"Для выровненных макетов, матриц и табличных данных."},"HelpMarker":{"what":"Значок вопроса, показывающий подсказку при наведении.","use":"Для пояснения элементов управления без перегрузки интерфейса."},"Panel":{"what":"Панель с границей, содержащая виджеты и поддерживающая прокрутку.","use":"Для боковых панелей, блоков настроек и списков."}}; const DRAWS = {"rect":{"what":"Прямоугольник с заливкой или обводкой, отрисованный через DrawList.","use":"Для панелей, фонов, рамок и шкал индикаторов."},"circle":{"what":"Окружность с заливкой или обводкой.","use":"Для индикаторов, ручек управления и сигнальных точек."},"poly":{"what":"Произвольный многоугольник, заданный вершинами.","use":"Для пользовательских форм, меток и указателей."},"line":{"what":"Прямой отрезок между двумя точками.","use":"Для разделителей, соединений и осей графика."},"text":{"what":"Текст с произвольным расположением в DrawList.","use":"Для надписей с точным положением."},"triangle":{"what":"Треугольник с заливкой или обводкой.","use":"Для стрелок, значков воспроизведения и указателей."},"arc":{"what":"Дуговой сегмент окружности.","use":"Для круговых шкал, регуляторов и индикаторов."}}; @@ -2772,6 +2775,8 @@ // Entries added after the Russian branch was cut (dev.3): File > Language (dev.6) and the dev.4 / dev.5 additions // (checkbox row highlight, text-input frame border, hit-area choice, the new Preflight note). Merged over the table above. const UI_ADDED = { + "Failed to read project: The selected file could not be read.":"Не удалось прочитать проект: Не удалось прочитать выбранный файл.", + "Show more issues":"Показать ещё", "Language":"Язык", "Highlight row when checked":"Подсвечивать строку, когда флажок установлен", "Checked-row colour":"Цвет строки с установленным флажком", @@ -2789,6 +2794,7 @@ "Move it into a table cell, or turn the option off.":"Переместите его в ячейку таблицы или отключите параметр." }; Object.assign(UI, UI_ADDED); + PATTERNS.push([/^Failed to read project:/,'Не удалось прочитать проект:']); const HINTS_ADDED = { "cb:hit":"Область нажатия: только квадрат, вся строка таблицы (доступна, когда флажок находится в ячейке таблицы) или расширенная по горизонтали область. Она не часть квадрата: другие объекты могут её перекрывать и сохраняют собственные нажатия в REAPER. `Selectable` `SpanAllColumns` `AllowOverlap`", "frame-border-row":"Граница вокруг поля ввода: толщина и цвет. Выключено — как в теме (без границы). `PushStyleVar(StyleVar_FrameBorderSize)` `PushStyleColor(Col_Border)`", @@ -3113,7 +3119,7 @@ const rulerVCtx = rulerVEl ? rulerVEl.getContext('2d') : null; const canvasAreaEl = document.getElementById('canvas-area'); // Single source of truth for the semantic release version. Bump this line only. -const BUILD_VERSION='2.2.0'; +const BUILD_VERSION='2.2.3'; // Online user manual (English page; it links to the Russian version itself). // Paste the full https:// address between the quotes. Empty string hides Help > User Manual. const MANUAL_URL='https://reauibuilder.patch34.workers.dev/ReaUI_Builder_Manual_en'; @@ -3970,7 +3976,18 @@ return r; } // R(v) = floor(v + 0.5): JS Math.floor and Lua math.floor agree on every integer d (AD5). -function adaptiveRound(v){ return Math.floor(v + 0.5); } +const adaptiveFloor=Math.floor; +function adaptiveRound(v){ return adaptiveFloor(v + 0.5); } +// Shared cell-local arithmetic for Preview and the preflight interval resolver. +function resolveAdaptiveCellBox(s,cell,offset,k,delta){ + // C07: a fixed axis is overwhelmingly common while scanning the other one. + // Coefficients are finite contract values; retain the original arithmetic + // when the cell changes on that axis, including fractional cell deltas. + const fixedW=delta.dw===0,fixedH=delta.dh===0; + return {x:cell.x+offset.x+(fixedW?0:adaptiveFloor(k.kx*delta.dw+0.5)), + y:cell.y+offset.y+(fixedH?0:adaptiveFloor(k.ky*delta.dh+0.5)), + w:s.w+(fixedW?0:adaptiveFloor(k.kw*delta.dw+0.5)),h:s.h+(fixedH?0:adaptiveFloor(k.kh*delta.dh+0.5))}; +} // Resolved geometry of the whole scene for a canvas of CW x CH (design = cw x ch): // parent-relative x / y (what s.x / s.y mean) plus w / h. Never mutates shapes. // Absolute x' = absX + R(kx*dW); parent-relative = x' - parent's resolved absolute x. As @@ -3980,24 +3997,32 @@ // a cell is placed from the cell's resolved rect plus R(k*dWc) / R(k*dHc), with its // cell-relative coefficients (adaptiveCellCoeffsIn) and the cell's own size change // dWc = colW'(c) - colW(c), dHc = rowH'(r) - rowH(r). -function resolveAdaptiveView(CW, CH){ +// 2.2.3-dev.1 (audit 2.2.2 F02): opts.absolute returns the ABSOLUTE boxes {x, y, w, h} instead +// (Preflight measures shapes inside table cells on exactly the geometry Preview draws). +function resolveAdaptiveView(CW, CH, opts){ const dW = Math.floor(CW) - cw, dH = Math.floor(CH) - ch; - const byId = new Map(shapes.map(q => [q.id, q])); - const memo = new Map(), cellMemo = new Map(), abs = new Map(), cellDelta = new Map(), out = new Map(); + // C02: Preflight may resolve many sizes of the same immutable scene. Its private + // context reuses identity, coefficients and design positions, never resolved boxes. + const context=opts&&opts.context; + const byId = context?context.byId:new Map(shapes.map(q => [q.id, q])); + const memo = context?context.memo:new Map(), cellMemo = context?context.cellMemo:new Map(); + const abs = new Map(), cellDelta = new Map(), out = new Map(), tableLayouts=new Map(); + const design=s=>context?context.design.get(s.id):{x:getAbsoluteX(s),y:getAbsoluteY(s)}; // Resolved ABSOLUTE box of s (x, y absolute; w, h size). The design absolute box is the start. const absOf = s => { let r = abs.get(s.id); if(r) return r; - const ax = getAbsoluteX(s), ay = getAbsoluteY(s); + const {x:ax,y:ay}=design(s); abs.set(s.id, {x:ax, y:ay, w:s.w, h:s.h}); // cycle guard: a cyclic chain resolves as static const parent = s.parentId ? (byId.get(s.parentId) || null) : null; if(s.type === 'widget' && s.widgetType === 'TableCell' && parent && parent.type === 'widget' && parent.widgetType === 'Table'){ const t = absOf(parent); if(t.w === parent.w && t.h === parent.h){ - r = {x:t.x + (ax - getAbsoluteX(parent)), y:t.y + (ay - getAbsoluteY(parent)), w:s.w, h:s.h}; + const p=design(parent); + r = {x:t.x + (ax - p.x), y:t.y + (ay - p.y), w:s.w, h:s.h}; } else { - const rect = computeTableCellRect({...parent, w:t.w, h:t.h}, s.tableRow, s.tableCol); - const des = computeTableCellRect(parent, s.tableRow, s.tableCol); + const rect = computeTableCellRect({...parent, w:t.w, h:t.h}, s.tableRow, s.tableCol,tableLayouts); + const des = computeTableCellRect(parent, s.tableRow, s.tableCol,tableLayouts); cellDelta.set(s.id, {dw:rect.w - des.w, dh:rect.h - des.h}); r = {x:t.x + rect.x, y:t.y + rect.y, w:rect.w, h:rect.h}; } @@ -4006,12 +4031,8 @@ const cell = lk ? byId.get(lk.cellId) : null; if(lk && cell){ const c = absOf(cell), d = cellDelta.get(cell.id) || {dw:0, dh:0}; - r = { - x: c.x + (ax - getAbsoluteX(cell)) + adaptiveRound(lk.kx * d.dw), - y: c.y + (ay - getAbsoluteY(cell)) + adaptiveRound(lk.ky * d.dh), - w: s.w + adaptiveRound(lk.kw * d.dw), - h: s.h + adaptiveRound(lk.kh * d.dh), - }; + const p=design(cell); + r=resolveAdaptiveCellBox(s,c,{x:ax-p.x,y:ay-p.y},lk,d); } else { const k = adaptiveCoeffsIn(s, byId, memo); r = {x:ax + adaptiveRound(k.kx * dW), y:ay + adaptiveRound(k.ky * dH), @@ -4021,6 +4042,7 @@ abs.set(s.id, r); return r; }; + if(opts && opts.absolute){ for(const s of (opts.targets||shapes)) absOf(s); return abs; } for(const s of shapes){ const r = absOf(s); const parent = s.parentId ? (byId.get(s.parentId) || null) : null; @@ -7740,12 +7762,18 @@ // Relative-to-table rect for cell (r,c). Body sits below the optional column-label // band only (c63: the editor strip left the box). Inspector column/row sizing is used // directly, so the canvas mirrors the generated table geometry. -function computeTableCellRect(table, r, c){ - const band=getTableHeaderBandHeight(table); // 1.5.0: 18 + predicted angled row (angled tables only) - const bodyY=band; - const bodyH=Math.max(GRID, table.h-bodyY); - const cols=getTableColumnLayout(table,table.w); // 2.1.0-dev.2 (A08 S1): ImGui's columns - const heights=getResolvedTableRowHeights(table,bodyH); +function computeTableCellRect(table, r, c, layoutCache){ + // C02: one resolver pass visits all cells of a table. Share its column/row + // distribution at this exact size; never retain it across scene mutations. + const key=layoutCache?table.id+':'+table.w+':'+table.h:null; + let layout=layoutCache&&layoutCache.get(key); + if(!layout){ + const bodyY=getTableHeaderBandHeight(table); + const bodyH=Math.max(GRID,table.h-bodyY); + layout={bodyY,cols:getTableColumnLayout(table,table.w),heights:getResolvedTableRowHeights(table,bodyH)}; + if(layoutCache)layoutCache.set(key,layout); + } + const {bodyY,cols,heights}=layout; const col=cols[c]||{x:0,w:1}; const cellY=heights.slice(0,r).reduce((sum,value)=>sum+value,0); return { @@ -9959,9 +9987,8 @@ // Replacing the canvas destroys unsaved work. A plain "are you sure?" makes the // only safe answer Cancel -> save by hand -> start the action again, so the // save is offered inline as a third choice instead. -// Note: the browser's own save dialog can still be dismissed after "Save -// project", and there is no way to observe that from here — proceeding anyway -// matches how saveProject() behaves everywhere else in the app. +// Continue only after a successful save. Download-only browsers retain a local +// recovery copy because they cannot report whether a requested download completed. function uiConfirmDiscard(message, proceed, opts){ opts=opts||{}; showDialog({ title:opts.title||'Unsaved work', body:message, buttons:[ @@ -14208,9 +14235,10 @@ let projectRecoveryId = makeRecoveryId(); const currentStorageKey = () => STORAGE_PREFIX + projectRecoveryId; const liveSessions=new Set([SESSION_ID]); - const presenceChannel=typeof BroadcastChannel==='function' - ? new BroadcastChannel('reaui_builder_autosave_presence_v1') : null; - if(presenceChannel){ + let presenceChannel=null; + function openPresenceChannel(){ + if(presenceChannel || typeof BroadcastChannel!=='function') return; + presenceChannel=new BroadcastChannel('reaui_builder_autosave_presence_v1'); presenceChannel.addEventListener('message',event=>{ const msg=event.data||{}; if(!msg.sessionId||msg.sessionId===SESSION_ID) return; @@ -14221,6 +14249,7 @@ } }); } + openPresenceChannel(); const ENVELOPE_VERSION = 1; const MODULE_VERSION = 1; const SAVE_DELAY_MS = 800; @@ -14487,8 +14516,16 @@ if(presenceChannel){ presenceChannel.postMessage({type:'bye',sessionId:SESSION_ID}); presenceChannel.close(); + presenceChannel=null; } }); + // A page restored from the back/forward cache resumes the same module. Its + // closed channel must rejoin presence before other tabs offer its live draft. + window.addEventListener('pageshow', event => { + if(!event.persisted) return; + openPresenceChannel(); + if(presenceChannel) presenceChannel.postMessage({type:'ping',sessionId:SESSION_ID}); + }); window.addEventListener('beforeunload', event => { scanForUncommittedChanges(); if(!dirty)return; @@ -14512,7 +14549,8 @@ }, acceptLoadedProject, acceptNewProject, - hasUnsavedChanges: () => dirty, + // New/Open must also see mutations made since the 500 ms safety scan. + hasUnsavedChanges: () => {scanForUncommittedChanges();return dirty;}, // 1.6.0-dev.12: read-only probe for the startup chooser; Restore re-reads on click. hasRestorableDrafts: () => readStoredDrafts().some(d=>d.storageKey!==currentStorageKey()), hasSafeRecoveryDraft: () => draftSafe, @@ -14525,6 +14563,25 @@ let projectFileHandle=null; let projectFilename='reaper-ui-project.json'; let projectDocumentEpoch=0; +// 2.2.3-dev.2 (audit 2.2.2 F01): a load is a request with an identity. Reading the file is +// asynchronous after the picker closes, so a slow read could land on a newer document or on +// edits made in the meantime, reset history and mark the result clean. A result applies only +// if it is the latest load, the document epoch is unchanged, and the content is still the one +// the user agreed to replace. +let projectLoadToken=0; +function projectContentSnapshot(){ + try{ return JSON.stringify(serializeProjectCore()); }catch(_){ return null; } +} +function beginProjectLoad(){ + return {token:++projectLoadToken, epoch:projectDocumentEpoch, content:projectContentSnapshot()}; +} +function projectLoadIsCurrent(req){ + return req.token===projectLoadToken && req.epoch===projectDocumentEpoch && req.content===projectContentSnapshot(); +} +function reportStaleProjectLoad(req){ + if(req.token!==projectLoadToken) return; // a newer load replaced this one; it reports for itself + uiAlert('The project changed while the file was being read, so the file was not opened. Your current project is unchanged.','Load cancelled'); +} let projectSavePromise=null; const PROJECT_FILE_TYPES=[{description:'ReaUI project',accept:{'application/json':['.json']}}]; function downloadProjectCopy(filename){ @@ -14583,14 +14640,17 @@ return projectSavePromise; } async function openProjectWithHandle(replacement={}){ + const req=beginProjectLoad(); // 2.2.3-dev.2 (F01) try{ const [handle]=await window.showOpenFilePicker({multiple:false,types:PROJECT_FILE_TYPES}); const file=await handle.getFile(),project=JSON.parse(await file.text()); + if(!projectLoadIsCurrent(req)){ reportStaleProjectLoad(req); return false; } if(applyLoadedProject(project)===false) return false; projectFileHandle=handle;projectFilename=handle.name;projectDocumentEpoch++; resetHistory();resetZoomToActualSize();AUTOSAVE.acceptLoadedProject(file.name,replacement); return true; }catch(error){ + if(req.token!==projectLoadToken) return false; // superseded: its failure is not news if(error.name!=='AbortError') uiAlert('Could not load project: '+error.message,'Load failed'); return false; } @@ -14603,6 +14663,7 @@ } function _loadProjectPick(replacement={}){ if(typeof window.showOpenFilePicker==='function') return openProjectWithHandle(replacement); + const req = beginProjectLoad(); // 2.2.3-dev.2 (F01): same contract as openProjectWithHandle const input = document.createElement('input'); input.type = 'file'; input.accept = '.json'; @@ -14614,16 +14675,24 @@ reader.onload = (ev) => { try { const project = JSON.parse(ev.target.result); + if(!projectLoadIsCurrent(req)){ reportStaleProjectLoad(req); return; } if(applyLoadedProject(project)===false) return; resetHistory(); resetZoomToActualSize(); projectFileHandle=null;projectFilename=file.name;projectDocumentEpoch++; AUTOSAVE.acceptLoadedProject(file.name, replacement); // AUTOSAVE INTEGRATION HOOK } catch(err){ + if(!projectLoadIsCurrent(req)) return; uiAlert('Failed to load project: ' + err.message, 'Load failed'); } }; - reader.readAsText(file); + reader.onerror = () => { + if(!projectLoadIsCurrent(req)) return; + uiAlert('Failed to read project: ' + (reader.error?.message || 'The selected file could not be read.'), 'Load failed'); + }; + try{reader.readAsText(file);}catch(err){ + if(projectLoadIsCurrent(req))uiAlert('Failed to read project: ' + err.message, 'Load failed'); + } }; document.body.appendChild(input); input.click(); @@ -14734,6 +14803,34 @@ return {...point,x,y}; } +// 2.2.3-dev.3 (C01 / audit F03): import and Preflight share this pure validation +// boundary. Do not coerce objects or booleans, and never retain settings outside +// the table grid. A successful result is a fresh, bounded array; callers decide +// whether to adopt it (import) or only inspect it (Preflight). +function validateTableColumnConfig(table){ + const config=table.columnConfig; + const fail=(message,columnIndex=null)=>({value:null,problem:{message,columnIndex}}); + if(config===undefined) return {value:undefined,problem:null}; + if(!Array.isArray(config)) return fail('columnConfig must be an array.'); + const count=Number(table.columnCount===undefined?1:table.columnCount); + if(!Number.isInteger(count)||count<1||count>16) return fail('Table column count must be an integer from 1 to 16.'); + if(config.length>count) return fail('columnConfig has '+config.length+' entries for '+count+' columns; the first excess column setting is at index '+count+'.',count); + const value=[]; + for(let i=0;ifail('Invalid column setting at index '+i+': use null or fixed/stretch sizing with a finite, nonnegative number.',i); + if(typeof item!=='object'||Array.isArray(item)) return bad(); + if(item.sizing!=='fixed'&&item.sizing!=='stretch') return bad(); + const raw=item.value; + if(raw!==undefined&&typeof raw!=='number'&&typeof raw!=='string') return bad(); + const number=raw===undefined?0:Number(raw); + if(!Number.isFinite(number)||number<0) return bad(); + value.push({sizing:item.sizing,value:number}); + } + return {value,problem:null}; +} + function normalizeLoadedShape(raw,index){ if(!raw || typeof raw!=='object' || Array.isArray(raw)){ throw new Error('Shape '+(index+1)+' must be an object.'); @@ -14764,6 +14861,16 @@ return n; }); } + // 2.2.3-dev.3 (C01): validate before load commits; keep dev.2's numeric-string, + // null-entry and omitted-value semantics. Excess entries reject the entire load. + if(shape.columnConfig!==undefined){ + if(shape.widgetType!=='Table') delete shape.columnConfig; + else{ + const config=validateTableColumnConfig(shape); + if(config.problem) throw new Error('Shape '+(index+1)+': '+config.problem.message); + shape.columnConfig=config.value; + } + } // Family/variant are derived data. Never trust display or inspector routing fields // supplied by project JSON; rebuild them from the canonical widget type (F01). if(shape.type==='widget'){ @@ -22395,7 +22502,7 @@ ctx.fillText(labelText,x,y-2); } } else if(geo.previewFrameKind==='color-button-square'){ - ctx.fillStyle=def.color; + ctx.fillStyle=(typeof s.color==='string'&&s.color)?s.color:def.color; ctx.fillRect(x,y,w,h); ctx.strokeStyle=strong; ctx.strokeRect(x+1,y+1,w-2,h-2); @@ -23180,11 +23287,20 @@ // a silent wrong-file export. Generation now owns both buttons: nothing is // downloadable unless this run produced it. let exportCodeReady=false; +// 2.2.3-dev.2 (audit 2.2.2 F04): true after genImGui() threw in this dialog run. Preflight +// reads it, so a rerun (switching the UI language with the dialog open reruns Preflight) +// cannot show "Ready to export" over a failed generation. +let exportGenerationFailed=false; function setExportAvailable(ok){ exportCodeReady=!!ok; const c=document.getElementById('cbtn'), d=document.getElementById('dlbtn'); if(c) c.disabled=!exportCodeReady; if(d) d.disabled=!exportCodeReady; + if(exportCodeReady){ + exportGenerationFailed=false; + if(c) c.title='Copy generated Lua'; + if(d) d.title='Download generated Lua'; + } } function switchTab(t){ activeTab='imgui'; @@ -23196,6 +23312,9 @@ }catch(err){ out.textContent='Export failed: '+((err&&err.message)?err.message:String(err))+ '\n\nNothing was generated. The previous export is not shown and cannot be downloaded.'; + exportGenerationFailed=true; + const panel=document.getElementById('preflight-panel'), heading=document.getElementById('preflight-title'); + if(panel&&heading){ panel.dataset.state='blocked'; heading.textContent='Export failed: nothing was generated'; } return; } out.textContent=code; @@ -23230,6 +23349,7 @@ document.getElementById('modal-bg').classList.add('show'); toggleBasicExportCode(false); setExportAvailable(false); // nothing from an earlier run stays downloadable + exportGenerationFailed=false; // 2.2.3-dev.2 (F04): this run has not failed yet const report=EXPORT_PREFLIGHT.run(); // Validate before generation: malformed state must not crash the dialog. if(report.stats.errors){ document.getElementById('code-out').textContent='Export is blocked until the errors above are resolved.'; @@ -23314,6 +23434,33 @@ let currentIssues = []; let currentStats = {checked:0, exportable:0, errors:0, warnings:0}; + // C07: keep one immutable-model report. Rendering still reads generation state + // on every run, so a cache hit cannot revive an unavailable export (F04). + let reportCache=null,watchedFonts=null,fontRevision=0; + function reportCacheKey(){ + try{ + const fonts=document.fonts; + if(fonts!==watchedFonts){ + watchedFonts=fonts;fontRevision++; + if(fonts&&typeof fonts.addEventListener==='function'){ + const invalidate=()=>{if(fonts===watchedFonts){fontRevision++;reportCache=null;}}; + fonts.addEventListener('loadingdone',invalidate); + fonts.addEventListener('loadingerror',invalidate); + } + } + if(fonts&&fonts.status==='loading')return null; + let safe=true; + // Use raw shapes as well as the save metadata: serializeProjectCore omits + // undefined/functions, which must never hide malformed live-state changes. + const model=JSON.stringify({...serializeProjectCore(),shapes},(_,value)=>{ + const type=typeof value; + if(value===undefined||type==='function'||type==='symbol'||type==='bigint'||(type==='number'&&!Number.isFinite(value)))safe=false; + return value; + }); + return safe?fontRevision+'|'+(fonts?fonts.size:0)+'|'+(window.devicePixelRatio||1)+'|'+model:null; + }catch(_){return null;} + } + const copyIssues=list=>list.map(item=>({...item})); const own = (obj,key) => Object.prototype.hasOwnProperty.call(obj||{},key); const finite = value => value !== '' && value !== null && value !== undefined && Number.isFinite(Number(value)); @@ -23401,6 +23548,17 @@ const duplicateIds=new Set(); const structurallyUnsafe=new Set(); + // 2.2.3-dev.3 (C01): malformed live column settings are a prerequisite + // failure. Diagnose every affected table before geometry can consume them; + // no scene or configuration is normalized or mutated by this check. + shapes.forEach(s=>{ + if(s.type!=='widget'||s.widgetType!=='Table') return; + const config=validateTableColumnConfig(s); + if(config.problem) found.push(issue('error','invalid-table-column-config',s, + 'Invalid table column settings',config.problem.message)); + }); + if(found.length) return {issues:found,checked:shapes.length,exportable:0}; + if(!isCanonicalHexColor(bgColor)){ found.push(issue('error','invalid-background-color',null,'Project background colour is invalid','Use a hexadecimal colour in #RRGGBB format.')); } @@ -23684,17 +23842,53 @@ } // 1.8.0-dev.3 (A05, ADR-009 AD8): the resolved layout over the whole allowed window size. - // Each edge moves by R(k·d) (k ∈ {0, ½, 1}), so on one axis the offset between two edges is - // monotone in d and "overlaps on this axis" holds on one interval of d. The intervals are - // solved exactly over the integers (bisection on monotone predicates), not sampled, and the - // two axes are independent. Pairs that already overlap at the design size are reported - // above (widget-overlap), so only overlaps that appear while resizing are reported here. + // Outside table cells, R(k·d) (k ∈ {0, ½, 1}) gives monotone edge differences, + // so bisection solves the intervals. C02 uses measured integer intervals when + // a table cell is involved: column distribution can change that monotonicity. + // Axes are independent. Design-size overlaps are reported above (widget-overlap). if(windowResize!==null){ + const adFloor=Math.floor,adMin=Math.min,adMax=Math.max; + const adRound=adaptiveRound,adCellBox=resolveAdaptiveCellBox,adResolve=resolveAdaptiveView; const lim=getPreviewWindowLimits(); const rangeW=[lim.minW-cw, (windowResize.maxW!==undefined?windowResize.maxW:cw+8192)-cw]; const rangeH=[lim.minH-ch, (windowResize.maxH!==undefined?windowResize.maxH:ch+8192)-ch]; const adById=new Map(shapes.map(q=>[q.id,q])), adMemo=new Map(); const K=s=>adaptiveCoeffsIn(s,adById,adMemo); + // 2.2.3-dev.1 (audit 2.2.2 F02): a TableCell is a local root. adaptiveCoeffsIn gives the + // cell and its whole subtree kw = kh = 0, so K() alone never sees a size or position change + // that comes from the cell's own resize (a stretched table redistributing its columns / + // rows). Shapes in a cell are measured on the geometry Preview draws (resolveAdaptiveView), + // one axis at a time: a cell's x / w follow the table width only, its y / h the height only. + // Resolved edges also cover nested tables and fixed/stretch transitions; + // C02 measures their intervals without assuming monotone edge differences. + const adCellMemo=new Map(), resolvedAt=new Map(); + const cellOf=s=>{ + if(!s) return null; + if(s.type==='widget'&&s.widgetType==='TableCell') return s.id; + const lk=adaptiveCellCoeffsIn(s,adById,adCellMemo); + return lk?lk.cellId:null; + }; + const resolverContext={byId:adById,memo:adMemo,cellMemo:adCellMemo, + design:new Map(shapes.map(s=>[s.id,{x:getAbsoluteX(s),y:getAbsoluteY(s)}]))}; + const resolvedBox=(s,axis,d)=>{ + const key=axis+d; + let view=resolvedAt.get(key); + if(!view){ view=adResolve(axis==='x'?cw+d:cw, axis==='y'?ch+d:ch, {absolute:true,context:resolverContext}); resolvedAt.set(key,view); } + return view.get(s.id)||null; + }; + // Same [start, end] contract as edges() below, driven by s's resolved geometry instead of + // R(k·d). box is s's design box on the canvas (a footprint or an interior rect); it moves + // and grows by exactly as much as s does. + const cellEdges=(s,box,axis)=>{ + const pos=axis==='x'?box.x:box.y, len=axis==='x'?box.w:box.h; + const a0=axis==='x'?getAbsoluteX(s):getAbsoluteY(s), l0=Number(axis==='x'?s.w:s.h); + return d=>{ + const r=d===0?null:resolvedBox(s,axis,d); + if(!r) return [pos,pos+len]; + const dp=(axis==='x'?r.x:r.y)-a0, dl=(axis==='x'?r.w:r.h)-l0; + return [pos+dp, pos+dp+len+dl]; + }; + }; // Integer sub-range of [r0, r1] where a monotone predicate holds, or null. const halfLine=(pred,r0,r1)=>{ const a=pred(r0), b=pred(r1); @@ -23709,7 +23903,7 @@ const edges=(box,k,axis)=>{ const pos=axis==='x'?box.x:box.y, len=axis==='x'?box.w:box.h; const kp=axis==='x'?k.kx:k.ky, kl=axis==='x'?k.kw:k.kh; - return d=>{ const s=pos+adaptiveRound(kp*d); return [s, s+len+adaptiveRound(kl*d)]; }; + return d=>{ const s=pos+adRound(kp*d); return [s, s+len+adRound(kl*d)]; }; }; const D0={x:cw,y:ch}; const sizeText=(axis,p,q,r)=>{ @@ -23719,23 +23913,149 @@ return p<=r[0] ? (base+q)+' px '+word+' or '+less : 'from '+(base+p)+' to '+(base+q)+' px '+word; }; const moving=k=>!!(k.kx||k.kw||k.ky||k.kh); + // C02: different cells and outside controls do not share one linear frame. + // Fixed/stretch transitions can reverse an edge difference, so halfLine is + // not a valid solver for these pairs. Enumerate integer sizes once per axis + // into compact edge arrays, then reuse them for every pair and container. + // A very large explicit range is reported as partial rather than freezing + // the UI or claiming that unexamined sizes are safe. The existing no-Max + // horizon (design + 8192) is unchanged. + const cellShapes=shapes.filter(s=>cellOf(s)!==null), sequences=new Map(), edgeDescriptors=new Map(); + const cellRoots=cellShapes.filter(s=>s.type==='widget'&&s.widgetType==='TableCell'); + const rootIndex=new Map(cellRoots.map((s,i)=>[s.id,i])),designLayouts=new Map(); + const roots=cellRoots.map(s=>{ + const parent=adById.get(s.parentId); + return {s,parent,rect:parent&&parent.widgetType==='Table'?computeTableCellRect(parent,s.tableRow,s.tableCol,designLayouts):s}; + }); + const cellSpecs=cellShapes.map(s=>{ + if(rootIndex.has(s.id))return {s,root:rootIndex.get(s.id),managed:true}; + const k=adaptiveCellCoeffsIn(s,adById,adCellMemo),p=resolverContext.design.get(s.id),c=resolverContext.design.get(k.cellId); + return {s,root:rootIndex.get(k.cellId),k,offset:{x:p.x-c.x,y:p.y-c.y}}; + }); + const TABLE_AXIS_SCAN_MAX=32768; + const scanRange=axis=>{ + const r=axis==='x'?rangeW:rangeH; + return [r[0],Math.min(r[1],r[0]+TABLE_AXIS_SCAN_MAX-1)]; + }; + const prepareAxis=axis=>{ + if(sequences.has(axis)) return sequences.get(axis); + const r=scanRange(axis), count=r[1]-r[0]+1, data=new Map(); + for(const s of cellShapes) data.set(s.id,{start:new Float64Array(count),end:new Float64Array(count)}); + const rootBoxes=[],deltas=roots.map(()=>({dw:0,dh:0})); + for(let i=0;i{ + let b; + if(lo===hi)b=q.blocks[lo]; + else{ + const mid=adFloor((lo+hi)/2),a=build(node*2,lo,mid),c=build(node*2+1,mid+1,hi); + b=[adMin(a[0],c[0]),adMax(a[1],c[1]),adMin(a[2],c[2]),adMax(a[3],c[3])]; + } + q.tree.set(b,node*4);return b; + }; + build(1,0,q.blocks.length-1); + } + const all=axis==='x'?rangeW:rangeH; + if(r[1]{ + const cacheKey=axis+'|'+s.id+'|'+box.x+'|'+box.y+'|'+box.w+'|'+box.h; + if(edgeDescriptors.has(cacheKey))return edgeDescriptors.get(cacheKey); + const keep=edge=>{ + const node=edge.node,cache=new Map(); + edge.node=(i,lo,hi)=>{if(!cache.has(i))cache.set(i,node(i,lo,hi));return cache.get(i);}; + edgeDescriptors.set(cacheKey,edge);return edge; + }; + const r=scanRange(axis); + if(cellOf(s)===null){ + const k=K(s),pos=axis==='x'?box.x:box.y,len=axis==='x'?box.w:box.h; + const kp=axis==='x'?k.kx:k.ky,kl=axis==='x'?k.kw:k.kh; + const start=d=>pos+adRound(kp*d),end=d=>start(d)+len+adRound(kl*d); + const bounds=(a,b)=>[adMin(start(a),start(b)),adMax(start(a),start(b)),adMin(end(a),end(b)),adMax(end(a),end(b))]; + return keep({start,end,node:(i,lo,hi)=>bounds(r[0]+lo*64,Math.min(r[1],r[0]+hi*64+63))}); + } + const q=prepareAxis(axis).data.get(s.id), p=resolverContext.design.get(s.id); + const shift=(axis==='x'?box.x-p.x:box.y-p.y), tail=shift+(axis==='x'?box.w-s.w:box.h-s.h); + const start=d=>q.start[d-r[0]]+shift,end=d=>q.end[d-r[0]]+tail; + return keep({start,end,node:i=>{const k=i*4,b=q.tree;return [b[k]+shift,b[k+1]+shift,b[k+2]+tail,b[k+3]+tail];}}); + }; + const measuredRelation=(x,y,axis,outside=false)=>{ + const r=scanRange(axis),out=[]; + const add=(lo,hi)=>{const last=out[out.length-1];if(last&&last[1]+1===lo)last[1]=hi;else out.push([lo,hi]);}; + const classify=(p,q)=>outside + ? (p[0]>=q[1]&&p[3]<=q[2]?0:p[1]q[3]?1:-1) + : (p[0]>=q[3]||q[0]>=p[3]?0:p[1]{ + const a=r[0]+lo*64,b=adMin(r[1],r[0]+hi*64+63),state=classify(x.node(node,lo,hi),y.node(node,lo,hi)); + if(state===0)return; + if(state===1){add(a,b);return;} + if(lo!==hi){const mid=adFloor((lo+hi)/2);visit(node*2,lo,mid);visit(node*2+1,mid+1,hi);return;} + let first=null; + for(let d=a;d<=b;d++){ + const hit=outside?x.start(d)y.end(d):x.start(d)measuredRelation(measuredEdges(A,a,axis),measuredEdges(B,b,axis),axis); + const describeIntervals=(axis,list,r)=>{ + const text=list.map(p=>sizeText(axis,p[0],p[1],r)).join(' or '); + return list.length>1?'('+text+')':text; + }; + const covers=(list,r)=>list.length===1&&list[0][0]===r[0]&&list[0][1]===r[1]; // adaptive-overlap for(let i=0;iax(d)[0]bx(d)[0]ay(d)[0]by(d)[0]{ + if(cellDriven)return measuredOverlap(A,boxA,B,boxB,axis); + const a=edges(boxA,kA,axis),b=edges(boxB,kB,axis),r=axis==='x'?rangeW:rangeH; + const p=meet(halfLine(d=>a(d)[0]b(d)[0]{ const a=box.x+adaptiveRound(kS.kx*d); return [a, a+GRID]; }) - : edges(box,kS,axis); - const pe=edges(frame,kP,axis); + ? (d=>{ const a=sEdges(d)[0]; return [a, a+GRID]; }) + : sEdges; + const pe=inCell?cellEdges(parent,frame,axis):edges(frame,kP,axis); if(!(se(0)[0]>=pe(0)[0]&&se(0)[1]<=pe(0)[1])) return; // not inside at the design size: not ours + if(inCell){ + let a=measuredEdges(s,box,axis);const b=measuredEdges(parent,frame,axis); + if(axis==='x'&&s.widgetType==='CollapsingHeader'){ + const original=a;a={...a,end:d=>original.start(d)+GRID,node:(...args)=>{const p=original.node(...args);return [p[0],p[1],p[0]+GRID,p[1]+GRID];}}; + } + const outside=measuredRelation(a,b,axis,true); + if(outside.length)parts.push(describeIntervals(axis,outside,r)); + continue; + } const inside=meet(halfLine(d=>se(d)[0]>=pe(d)[0],...r), halfLine(d=>se(d)[1]<=pe(d)[1],...r)); if(!inside) continue; if(inside[0]>r[0]) parts.push(sizeText(axis,r[0],inside[0]-1,r)); @@ -23797,6 +24129,22 @@ 'Too small at the minimum window size', 'Stretched with the window, it is ' + wMin + ' × ' + hMin + ' px at ' + lim.minW + ' × ' + lim.minH + ', below its minimum of ' + mn.minW + ' × ' + mn.minH + ' px. Raise Min width / height, or make it larger at the design size.')); }); + // 2.2.3-dev.1 (audit 2.2.2 F02): the same floor for shapes a table cell resizes. K() is + // zero for them, so the check above never reached them, and a button stretched in a + // shrinking cell exported a negative width. Measured on the resolved geometry (Preview's). + exportableShapes.forEach(s=>{ + if(isParentManagedShape(s)||cellOf(s)===null) return; + if(!(isWidgetShape(s) || (isPrimitiveShape(s) && (s.type==='rect' || s.type==='text')))) return; + const rx=resolvedBox(s,'x',lim.minW-cw), ry=resolvedBox(s,'y',lim.minH-ch); + if(!rx||!ry) return; + const w0=Number(s.w), h0=Number(s.h), wMin=rx.w, hMin=ry.h; + const mn=(isWidgetShape(s) && isCanonicalWidgetContainer(s)) ? getContainerMinResize(s) : {minW:GRID,minH:GRID}; + // Only an axis the cell actually shrinks is subject to the floor. + if((wMin>=w0 || wMin>=mn.minW) && (hMin>=h0 || hMin>=mn.minH)) return; + found.push(issue('error','adaptive-too-small',s, + 'Too small at the minimum window size', + 'Stretched with its table cell, it is ' + wMin + ' × ' + hMin + ' px at ' + lim.minW + ' × ' + lim.minH + ', below its minimum of ' + mn.minW + ' × ' + mn.minH + ' px. Raise Min width / height, give its column or row more room, or reduce the space around it in the cell.')); + }); } } @@ -23970,10 +24318,14 @@ return {issues:found, checked:shapes.length, exportable}; } + // 2.2.3-dev.2 (audit 2.2.2 F04): a clean Preflight is not a generated script. Both are + // required. When Preflight runs first (openModal), the buttons stay off until switchTab() + // succeeds; setExportAvailable(true) then arms them and restores their titles. function setExportEnabled(enabled){ + const ready=enabled&&exportCodeReady; const copy=document.getElementById('cbtn'), download=document.getElementById('dlbtn'); - if(copy){ copy.disabled=!enabled; copy.title=enabled?'Copy generated Lua':'Resolve the errors above to enable copy'; } - if(download){ download.disabled=!enabled; download.title=enabled?'Download generated Lua':'Resolve the errors above to enable download'; } + if(copy){ copy.disabled=!ready; copy.title=ready?'Copy generated Lua':enabled?'Nothing was generated, so there is nothing to copy':'Resolve the errors above to enable copy'; } + if(download){ download.disabled=!ready; download.title=ready?'Download generated Lua':enabled?'Nothing was generated, so there is nothing to download':'Resolve the errors above to enable download'; } } function focusIssue(item){ @@ -24027,6 +24379,8 @@ else if(skipped){ panel.dataset.state='warning'; title.textContent=skipped+' element'+(skipped===1?'':'s')+' will not be exported'; } else if(warnings){ panel.dataset.state='warning'; title.textContent='Ready with '+warnings+' warning'+(warnings===1?'':'s'); } else { panel.dataset.state='ready'; title.textContent='Ready to export'; } + // 2.2.3-dev.2 (F04): Preflight passed, but this run's generation did not. + if(!blocked && exportGenerationFailed){ panel.dataset.state='blocked'; title.textContent='Export failed: nothing was generated'; } meta.textContent=exportable+' of '+checked+' element'+(checked===1?'':'s')+' will export'; setExportEnabled(!blocked); @@ -24035,7 +24389,16 @@ const empty=document.createElement('div'); empty.className='preflight-empty'; empty.textContent='No export blockers or warnings detected.'; list.appendChild(empty); return; } - currentIssues.forEach(item=>{ + // C07: retain every diagnostic in the model and progressively add DOM rows. + // Severity sorting keeps blockers first; counters always show the full total. + const issues=currentIssues;let visible=0,more=null; + const appendIssues=()=>{ + if(issues!==currentIssues)return; + if(more)more.remove(); + const limit=Math.min(issues.length,visible+Math.max(200,visible)); + const fragment=document.createDocumentFragment(); + for(;visiblefocusIssue(item); } @@ -24045,12 +24408,23 @@ const detail=document.createElement('span'); detail.className='preflight-detail'; detail.textContent=item.detail; copy.appendChild(msg); if(item.detail) copy.appendChild(detail); const target=document.createElement('span'); target.className='preflight-target'; target.textContent=item.target; - row.appendChild(sev); row.appendChild(copy); row.appendChild(target); list.appendChild(row); - }); + row.appendChild(sev); row.appendChild(copy); row.appendChild(target); fragment.appendChild(row); + } + if(visiblex.severity==='warning').length, }; renderReport(); - return {issues:currentIssues.slice(),stats:{...currentStats}}; + return {issues:copyIssues(currentIssues),stats:{...currentStats}}; } function open(){ run(); } document.getElementById('preflight-rerun').addEventListener('click',run); - return {open,run,getReport:()=>({issues:currentIssues.slice(),stats:{...currentStats}})}; + return {open,run,getReport:()=>({issues:copyIssues(currentIssues),stats:{...currentStats}})}; })(); // ════════════════════════════════════════════════════════════════════════════ // END EXPORT PREFLIGHT — SELF-CONTAINED MODULE @@ -26345,6 +26719,10 @@ L.push(_menuBarExport ? ` reaper.ImGui_PushStyleVar(ctx, reaper.ImGui_StyleVar_ItemSpacing(), 8, 0)` : ` reaper.ImGui_PushStyleVar(ctx, reaper.ImGui_StyleVar_ItemSpacing(), 0, 0)`); + // 2.2.1: no window border. With a 1px border the canvas child is clipped 1px inside the + // window on every side, while rects (clip rect intersect=false) paint over the border. + // Border 0 makes the exported canvas exactly W x H, like the editor. + L.push(` reaper.ImGui_PushStyleVar(ctx, reaper.ImGui_StyleVar_WindowBorderSize(), 0)`); if(_reaBgExport){ L.push(` reaper.ImGui_PushStyleColor(ctx, reaper.ImGui_Col_WindowBg(), BG)`); } @@ -26375,7 +26753,7 @@ L.push(` reaper.ImGui_PopStyleColor(ctx)`); }; if(chromePushes.length) L.push(` reaper.ImGui_PopStyleColor(ctx, ${chromePushes.length})`); - L.push(` reaper.ImGui_PopStyleVar(ctx, 2)`); + L.push(` reaper.ImGui_PopStyleVar(ctx, 3)`); L.push(` if visible then`); // 1.6.0 (ADR-007 M3/M5): the menu bar, before the canvas child. It is drawn in the // outer window, so it pushes ##Canvas down as a whole and no widget coordinate moves. @@ -26612,7 +26990,13 @@ const scrollY=!!(s.tableFlags&&s.tableFlags.ScrollY); // 2.1.0-dev.1 (A07): cell padding (S5), stretch (S2/S3), rows keep their height (S4), // row backgrounds and the highlight hook (S6). None of them = the 2.0.0 lines. - const cellPad=tableHasCustomCellPadding(s)?getTableCellPadding(s):null; + // C02: default padding is still a table-owned value. If an enclosing + // table pushed custom padding, explicitly restore this table's own + // pair so nested helpers and cell rebasing agree with Preview. + const ownCellPad=getTableCellPadding(s); + const enclosingTable=getParentChain(s).find(q=>q.widgetType==='Table'); + const enclosingPad=enclosingTable?getTableCellPadding(enclosingTable):null; + const cellPad=tableHasCustomCellPadding(s)||(enclosingPad&&(enclosingPad[0]!==ownCellPad[0]||enclosingPad[1]!==ownCellPad[1]))?ownCellPad:null; const tStretch=exportTableStretch(s), tStretched=tStretch.w||tStretch.h; const nofill=tableRowsKeepHeight(s); const hlCol=getTableHighlightColor(s); diff --git a/tools/export-gate/export_gate.js b/tools/export-gate/export_gate.js index e67a0f0..1f33927 100644 --- a/tools/export-gate/export_gate.js +++ b/tools/export-gate/export_gate.js @@ -1,44 +1,396 @@ #!/usr/bin/env node /* ============================================================================ - * export_gate.js — standing export-gate harness for the REAPER UI Layout Editor + * export_gate.js (v13) — standing export-gate harness for ReaUI Builder * ---------------------------------------------------------------------------- - * Loads a single-file plugin_ui_layout_v3_NNN.html headlessly (jsdom), builds a - * fixed fixture by driving the tool's OWN creation functions, then runs - * genImGui / genSeed. Used to prove that a patch does NOT change the exported - * output of widgets it shouldn't affect. (genLua was removed from the tool; the - * gate used to emit an empty third artefact that compared nothing.) + * Implements ADR-002 (claude/adr/002_gate_coverage.md). Canonical home: + * tools/export-gate/export_gate.js — every other copy is a mirror (G1). + * v3 (brief B02 stage 2.1) adds, after every v2 scene: the alpha scenes for ADR-004, + * the G5 alpha-255 cross-scene check and the theme-library-separation check for + * ADR-003 F7. No v2 scene content changed: v2 goldens stay byte-identical. + * v4 (brief B03 stage 3.1) adds, fixture first for release 1.2.0 (ADR-002 G6): four + * types appended to FROZEN_TYPES (TextLink, CheckboxFlags, PlotLines, PlotHistogram; + * new slots at y >= 1000, no existing entry moved), the scenes wave-a and + * wave-a.explicit-defaults after every v3 scene, and the G5 wave-a cross-scene check. + * No v3 scene content changed: on a build that lacks the four types, all-types is + * byte-identical to v3 (the new entries are skipped before any create or uid draw) + * and only gains four `N/A` notes; every other v3 golden is byte-identical. + * v5 (ADR-005 stage X1.0) adds, fixture first for release 1.3.0 (ADR-002 G6), the scene + * text-metrics after every v4 scene. No v4 scene content changed: every v4 golden is + * byte-identical under v5. + * v6 (brief B05 stage 5.1) adds, fixture first for release 1.4.0 (ADR-002 G6): one type + * appended to FROZEN_TYPES (InvisibleButton; a new slot at y >= 1000, no existing entry + * moved), the scenes wave-b and wave-b.explicit-defaults after every v5 scene, and the + * G5 wave-b cross-scene check. No v5 scene content changed: on a build that lacks + * InvisibleButton, all-types is byte-identical to v5 (the new entry is skipped before + * any create or uid draw) and only gains one `N/A` note; every other v5 golden is + * byte-identical. + * v7 (brief B06 stage 6.1) adds, fixture first for release 1.5.0 (ADR-002 G6, ADR-011): + * the scenes tables-b and tables-b.explicit-defaults after every v6 scene, and the + * G5 tables-b cross-scene check. No v6 scene content changed: every v6 golden is + * byte-identical under v7. tables-b covers the two new Table properties (ADR-011 G2/G4) + * — angledHeaders and scrollRows — on six explicitly named tables built through + * H.create then mutated on the live shape, as wave-a/wave-b do; a bridge helper + * H.resizeTable grows a table's row count the same way the inspector's row stepper + * does (rowCount/rowHeights/columns kept in sync, ensureTableCells/syncTableCellBounds + * re-run), since the harness builds tables outside the inspector UI. + * v8 (brief B07 stage 7.1) adds, fixture first for release 1.6.0 (ADR-002 G6, ADR-007): + * the scenes menus, menus.themed and menus.explicit-defaults after every v7 scene, and + * the G5 menus cross-scene check. No v7 scene content changed: every v7 golden is + * byte-identical under v8. A menu bar is project data, not a shape: the menus scenes + * build a small widget set through H.create, then attach `menuBar` to the saved project + * and round-trip it through Save -> reset -> Load (withMenuBar), so a build that does + * not know the key still builds every scene (it simply exports no menu). The 1.5.0-dev.2 + * baseline drops an unknown `menuBar` key silently on Save, in genSeed() and in + * genImGui(), so on the baseline every menus scene exports identically to one with no + * menu bar at all. + * v9 (brief B07 stage 7.3) adds, fixture first for release 1.6.0 (ADR-002 G6, ADR-007 + * M11): the scenes themes.slate-title, themes.slate-title.explicit-default and + * menus.themed-title after every v8 scene, and the G5 title cross-scene check. No v8 + * scene content changed: every v8 golden is byte-identical under v9. `themedTitleBar` + * is project data, not a shape, same as `menuBar`: withProjectKeys generalises + * withMenuBar's pattern (Save -> add keys -> reset -> Load) to any project-level key, + * so a build that does not know the key still builds every scene (it simply always + * themes the title bar, since the 1.6.0-dev.1 baseline has no title-bar option and + * colours the title unconditionally on a non-default theme). + * v10 (brief B11 stage 11.1) adds one scene, `arcs`, after every v9 scene. It covers F04 + * (1.6.0-dev.10) after the fact (B10 review R1; ADR-002 G6 wanted it first): pie fills over + * 180 degrees, sweeps that cross 0, negative and past-one-turn angles, a full-turn pie, a + * stroke-less ring. Nothing else is added (no G5, no check). No v9 scene content changed: + * every v9 golden is byte-identical under v10. On a pre-F04 build (1.6.0-dev.3) the arcs + * scene shows the F04 lines as CHANGED, which is expected. + * v11 (brief A01) adds, fixture first for the Adaptive UI layout work (ADR-002 G6, ADR-009 + * AD11), a fourth channel and ten scenes. CHANNEL `file`: every scene also stores + * `H.saveText()` (the saved project, pretty-printed JSON) taken from the first build, compared + * with normSeed (ids normalised) exactly like the seed. Before v11 no channel looked at the + * saved file, so a build could write new keys and demo objects into every project and pass + * every scene (A0_sketch_review.md §3). A rebuild whose file differs is NON-DETERMINISTIC + * "(file)". SCENES `adaptive.*` (after `arcs`): per-shape pins `pinH` / `pinV` and the project + * key `windowResize` are written into the SAVED project only (withAdaptive: Save -> edit the + * JSON by shape name -> reset -> Load), never onto live shapes, so a build that does not know + * them shows what its loader does with them. Body A is a 640x440 form (16 named shapes, a Panel + * with a Group inside); `adaptive.base` has no pins, `adaptive.inert` has MOVE+STRETCH pins and + * no `windowResize` key, `adaptive.move` / `.move.explicit-defaults` / `.limits` / + * `.stretch` add the key, `adaptive.nested` (StyleRegion, TabBar, TreeNode, nested Panels, + * Table, CollapsingHeader), `adaptive.primitives` (seven primitives + one widget) and + * `adaptive.menus` (the v8 menu fixture, `maxW:1000`) cover the other containers, and + * `adaptive.invalid` writes every value ADR-009 AD1/AD2/AD4 make the loader drop. CROSS-SCENE + * CHECK `G5 adaptive`: adaptive.move (absent) vs adaptive.move.explicit-defaults, three parts: + * (a) imgui, (b) seed after Save -> reset -> Load, (c) the file after Save -> reset -> Load. + * It prints `N/A` (no exit change) on a build whose loader drops `windowResize` (support + * probe). CHECK `adaptive inert`: adaptive.inert's genImGui() must equal adaptive.base's, in + * separate instances, on every build, the baseline included (seed and file are not compared: + * the pins are in them by design). A G5 adaptive FAIL or an adaptive inert FAIL follows the + * v3 rule: the build under test sets exit 3, the BEFORE build prints it as pre-existing. + * No v10 scene content changed: every v10 golden (.imgui, .seed) is byte-identical under v11. + * v12 (brief A07.1), fixture first for the 2.1.0 tables work (ADR-002 G6, ADR-009 AD4/AD5/AD6/AD8, + * ADR-011 G1/G3/G4), adds three scenes after every v11 scene and one bridge helper. SCENES + * `tables-c.stretch` (640x480, `windowResize {minW:480, minH:320}`; three tables tc_list / tc_hdr / + * tc_plain, cell children inside tc_list, pins written through withAdaptive), `tables-c.style` (a + * fixed window; the new Table properties `cellPadding`, `rowBg`, `highlightColor` + + * `highlightRows`, `rowsFill` and the StyleRegion property `styleFramePadding`, set on the live + * shapes as tables-b does) and `tables-c.explicit-defaults` (the same body with every new property + * written as its default). BRIDGE `H.cellChild(tableName, r, c, type, x, y, ov)` creates a widget + * inside a Table cell at a cell-relative point; `H.cellChildNote()` returns `NOT NESTED ...` when + * the new widget did not land in that cell. `H.resizeTable(t, rows, cols)` also grows columns now. + * CROSS-SCENE CHECK `G5 tables-c`: the tables-c.style body built with the new properties absent vs + * tables-c.explicit-defaults, three parts as G5 adaptive: (a) imgui, (b) seed and (c) file after + * Save -> reset -> Load. On a build that keeps unknown shape keys (2.0.0) part (a) passes for the + * wrong reason and (b) / (c) may FAIL, as G5 tables-b did on its baseline; the harness does not + * hide that. No v11 scene content changed: every v11 golden (.imgui, .seed, .file) is + * byte-identical under v12. + * v13 (2026-11-13, QA): fix the historical tables-b fixture's out-of-order + * TableCell layout update. It now calls H.resizeTable after angledHeaders/scrollRows + * edits and before creating its nested Button, matching the inspector's reflow. + * No other scene, generator, gate assertion, or exported builder code is modified. + * v12 is preserved unchanged for the audit trail. * - * The fixture exercises every nesting the placement/coordinate code touches: - * - a bare-canvas widget - * - a widget inside a Group - * - a widget inside a TabItem - * - a Table (with cells) and a widget dropped inside a cell - * - a CollapsingHeader with a child - * - the four locked-size types (ArrowButton, SeparatorText, BulletText, - * TextLinkOpenURL), whose w/h are a native contract rather than a grid value + * Loads a single-file ReaUI Builder .html headlessly (jsdom), injects a bridge at + * the end of the main '); + if(lc<0) throw new HarnessError('no in '+htmlPath); html = html.slice(0,lc) + BRIDGE + html.slice(lc); const dom = new JSDOM(html,{ runScripts:'outside-only', pretendToBeVisual:true, url:'https://local.test/' }); const { window } = dom; window.HTMLCanvasElement.prototype.getContext = () => makeCtx2d(); window.requestAnimationFrame = () => 0; window.cancelAnimationFrame = () => {}; + if(!window.Path2D) window.Path2D = Path2DStub; + // Seeded PRNG per instance: uid() draws on Math.random, so v1 seeds differed on every + // run and a golden seed could only be compared after normSeed. With a fixed seed the + // goldens are byte-reproducible (cmp works run to run); the before/after comparison + // still normalises ids, because a patch that adds one random draw shifts them all. + window.Math.random = mulberry32(0x5eed0a02); window.alert = window.prompt = window.confirm = () => {}; if(!window.matchMedia) window.matchMedia = () => ({matches:false,addListener(){},removeListener(){},addEventListener(){},removeEventListener(){}}); const errs = []; window.addEventListener('error', e => errs.push('window.error: '+(e.message||e))); for(const el of [...window.document.querySelectorAll('script')]){ try { window.eval(el.textContent); } - catch(e){ console.error('SCRIPT THROW during init ('+path.basename(htmlPath)+'):', e&&e.stack||e); process.exit(1); } + catch(e){ throw new HarnessError('SCRIPT THROW during init ('+path.basename(htmlPath)+'): '+(e&&e.stack||e)); } } - if(!window.__H){ console.error('bridge __H missing — injection failed'); process.exit(1); } - return { H: window.__H, errs }; + if(!window.__H) throw new HarnessError('bridge __H missing — injection failed ('+path.basename(htmlPath)+')'); + return { H: window.__H, errs, window }; } - -function buildFixtureAndExport(htmlPath){ - const { H, errs } = loadTool(htmlPath); - H.reset(); + +// ============================================================================ +// Frozen fixture data. Changing anything here changes goldens: extend, never edit +// (ADR-002 G6: a new type is added here first, captured on the unchanged builder). +// ============================================================================ + +// Every palette-creatable type in 1.0.70 (WIDGET_CONTRACTS minus TabItem/TableCell), +// each with a fixed absolute slot on a 1200x1200 canvas. Slots are fixed per entry, so a +// type missing from one build never moves the others. Names are explicit for the same +// reason: the default name draws on a running counter, and one N/A would rename every +// later widget and turn a one-type difference into a whole-scene diff. +const COL = [20, 260, 500, 740, 980]; +const FROZEN_TYPES = [ + // single-line widgets (default h <= 20), 5 per row, 40 px pitch + ['HelpMarker', COL[0], 20], ['Button', COL[1], 20], ['Checkbox', COL[2], 20], ['Text', COL[3], 20], ['TextColored', COL[4], 20], + ['TextDisabled', COL[0], 60], ['Separator', COL[1], 60], ['SliderDouble', COL[2], 60], ['SliderInt', COL[3], 60], ['InputText', COL[4], 60], + ['InputInt', COL[0], 100], ['InputDouble', COL[1], 100], ['Combo', COL[2], 100], ['ProgressBar', COL[3], 100], ['DragInt', COL[4], 100], + ['DragDouble', COL[0], 140], ['SeparatorText', COL[1], 140], ['ColorEdit3', COL[2], 140], ['ColorEdit4', COL[3], 140], ['ArrowButton', COL[4], 140], + ['InputTextWithHint', COL[0], 180], ['LabelText', COL[1], 180], ['SmallButton', COL[2], 180], ['Selectable', COL[3], 180], ['BulletText', COL[4], 180], + ['TextLinkOpenURL', COL[0], 220], ['SliderAngle', COL[1], 220], ['ColorButton', COL[2], 220], ['RadioButtonEx', COL[3], 220], ['SliderDoubleN', COL[4], 220], + ['DragDoubleN', COL[0], 260], ['InputDoubleN', COL[1], 260], ['DragIntRange2', COL[2], 260], ['DragFloatRange2', COL[3], 260], + // multi-line / tall + ['ListBox', COL[0], 310], ['TextWrapped', COL[1], 310], ['InputTextMultiline', COL[2], 310], + ['VSliderInt', COL[3], 310], ['VSliderDouble', COL[4], 310], + // pickers (height derived from width) + ['ColorPicker3', COL[0], 500], ['ColorPicker4', COL[1], 500], + // containers, empty (children are covered by core / themes / examples) + ['Panel', COL[2], 500], ['Group', COL[3], 500], ['StyleRegion', COL[4], 500], + ['CollapsingHeader', COL[2], 680], ['TreeNode', COL[3], 680], + ['TabBar', COL[0], 830], ['Table', 340, 830], + // v4 — release 1.2.0 types (B03 3.1). Appended, never interleaved: every earlier slot + // and name is unchanged. Placed where nothing is at y >= 1000 on the 1200x1200 canvas: + // TabBar (20,830 280x180) and Table (340,830 320x200) end at x 660, and the primitive + // row starts at y 1080 and ends at x 860. The plots sit at x 740/980 from y 1000: + // a default height up to 80 keeps PlotLines clear of the primitive row (x 780-860 + // from y 1080); PlotHistogram (x 980-1180) only meets TextLink (x 900 + default w, + // y 1160) at a height of 160. CheckboxFlags (x 900-920) meets neither. + ['TextLink', 900, 1160], ['CheckboxFlags', 900, 1110], + ['PlotLines', COL[3], 1000], ['PlotHistogram', COL[4], 1000], + // v6 — release 1.4.0 type (B05 5.1; slot fixed in the coordinator's review). Appended, + // never interleaved: every earlier slot and name is unchanged. Slot (20,1150): below the + // primitive row (y 1080-1140), left of TextLink (x 900, y 1160) and CheckboxFlags + // (x 900, y 1110); a default size up to 860x50 stays clear of both and inside the + // 1200x1200 canvas (B05 B2 suggests 100x40). + ['InvisibleButton', COL[0], 1150], +]; +const ALL_TYPES_CANVAS = { cw:1200, ch:1200 }; +// Draw primitives: [kind, x1, y1, x2, y2] — a drag from (x1,y1) to (x2,y2). +const FROZEN_PRIMITIVES = [ + ['rect', 20, 1080, 100, 1140], ['circle', 140, 1080, 220, 1140], ['poly', 260, 1080, 340, 1140], + ['line', 380, 1080, 460, 1140], ['text', 500, 1080, 620, 1140], ['triangle', 660, 1080, 740, 1140], + ['arc', 780, 1080, 860, 1140], +]; +// Structural children: made by their containers, never from the palette. +const STRUCTURAL_TYPES = new Set(['TabItem','TableCell']); + +// A custom theme with all 15 THEME_CHANNELS authored, every value distinct. +const GATE_CUSTOM_THEME = { + id:'gate-custom', label:'Gate custom', + colors:{ + text:'#f1e2d3', textLabel:'#e3d4c5', childBg:'#1a2b3c', frameBg:'#243546', + frameBgHovered:'#2e3f50', frameBgActive:'#38495a', button:'#6a2c1e', buttonHovered:'#7b3d2f', + buttonActive:'#8c4e40', header:'#1e6a2c', headerHovered:'#2f7b3d', headerActive:'#408c4e', + checkMark:'#c0ffee', sliderGrab:'#b16d2a', sliderGrabActive:'#d28e4b' + } +}; + +// v3 — ADR-004 A2: the 12 channels that may carry alpha, in A2 order. Frozen here, not +// read from the build (a build without alpha has no such list). +const ALPHA_CHANNELS = ['frameBg','frameBgHovered','frameBgActive','button','buttonHovered', + 'buttonActive','header','headerHovered','headerActive','checkMark','sliderGrab','sliderGrabActive']; +// themes.gate-alpha: GATE_CUSTOM_THEME's colours, own id, 12 distinct alphas, none 0/255. +const GATE_ALPHA_VALUES = [0x21,0x32,0x43,0x54,0x65,0x76,0x87,0x98,0xA9,0xBA,0xCB,0xDC]; +const GATE_ALPHA_THEME = { + id:'gate-alpha', label:'Gate alpha', + colors: Object.assign({}, GATE_CUSTOM_THEME.colors), + alpha: Object.fromEntries(ALPHA_CHANNELS.map((c,i)=>[c, GATE_ALPHA_VALUES[i]])) +}; +// themes.gate-alpha-opaque: GATE_CUSTOM_THEME itself (same id) plus twelve 255s. Must +// export exactly like themes.gate-custom (G5). +const GATE_ALPHA_OPAQUE_THEME = { + id:GATE_CUSTOM_THEME.id, label:GATE_CUSTOM_THEME.label, + colors: Object.assign({}, GATE_CUSTOM_THEME.colors), + alpha: Object.fromEntries(ALPHA_CHANNELS.map(c=>[c, 255])) +}; + +// v3 — theme-library-separation (ADR-003 F7). Library colours A and project colours B +// share the id `lib-x`; every value is canonical lower-case and no value repeats across +// A, B and lib-y, so a match can only mean one source. +const LIB_X_A = { + id:'lib-x', label:'Library X', + colors:{ + text:'#e1f0a1', textLabel:'#e1f0a2', childBg:'#10a0a1', frameBg:'#20a0a1', + frameBgHovered:'#20a0a2', frameBgActive:'#20a0a3', button:'#30a0a1', buttonHovered:'#30a0a2', + buttonActive:'#30a0a3', header:'#40a0a1', headerHovered:'#40a0a2', headerActive:'#40a0a3', + checkMark:'#50a0a1', sliderGrab:'#60a0a1', sliderGrabActive:'#60a0a2' + } +}; +const LIB_X_B = { + id:'lib-x', label:'Project X', + colors:{ + text:'#e1f0b1', textLabel:'#e1f0b2', childBg:'#10b0b1', frameBg:'#20b0b1', + frameBgHovered:'#20b0b2', frameBgActive:'#20b0b3', button:'#30b0b1', buttonHovered:'#30b0b2', + buttonActive:'#30b0b3', header:'#40b0b1', headerHovered:'#40b0b2', headerActive:'#40b0b3', + checkMark:'#50b0b1', sliderGrab:'#60b0b1', sliderGrabActive:'#60b0b2' + } +}; +const LIB_Y = { id:'lib-y', label:'Library Y', colors:{ text:'#e1f0c1', childBg:'#10c0c1' } }; +// The 13 theme pushes that map one-to-one to an authored channel (buildThemeColorPushes). +// resolveThemeColors lets authored values win, so each carries the authored colour. +const THEME_PUSH_SLOTS = [ + ['Text','text'], ['FrameBg','frameBg'], ['FrameBgHovered','frameBgHovered'], + ['FrameBgActive','frameBgActive'], ['Button','button'], ['ButtonHovered','buttonHovered'], + ['ButtonActive','buttonActive'], ['Header','header'], ['HeaderHovered','headerHovered'], + ['HeaderActive','headerActive'], ['CheckMark','checkMark'], ['SliderGrab','sliderGrab'], + ['SliderGrabActive','sliderGrabActive'], +]; + +const EXAMPLE_FILES = [ + 'example_01_batch_rename.json', + 'example_02_item_fade_tool.json', + 'example_03_render_loudness.json', + 'example_04_midi_humanizer.json', + 'example_05_marker_palette.json', +]; +const FIXTURE_DIR = path.join(__dirname, 'fixtures', 'examples'); + +// ============================================================================ +// Scenes. build(H, note) runs after H.reset(); note(text) attaches a line to the verdict. +// ============================================================================ + +// core — v1's fixture, verbatim. Do not edit: its output must stay byte-identical +// to the v1 golden of the same build (ADR-002 G2, the rewrite's acceptance test). +function buildCore(H){ H.create('Button', 40, 40); // bare canvas const grp = H.create('Group', 40, 120, { w:200, h:120 }); if(grp) H.create('Checkbox', 70, 160); // inside group @@ -146,14 +794,936 @@ function buildFixtureAndExport(htmlPath){ H.create('Text', H.absX(c)+c.w/2-10, H.absY(c)+c.h/2-6, { w:20, h:12 }); // inside a cell } } - let imgui,seed,stable; - try { - imgui=H.genImGui(); seed=H.genSeed(); - stable = (imgui===H.genImGui()) && (seed===H.genSeed()); - } catch(e){ console.error('GENERATOR THROW ('+path.basename(htmlPath)+'):', e&&e.stack||e); process.exit(1); } - return { imgui, seed, stable, errs, shapeCount:H.shapes().length, cellCount }; } - + +function buildAllTypes(H, note){ + H.set('cw', ALL_TYPES_CANVAS.cw); H.set('ch', ALL_TYPES_CANVAS.ch); + for(const [t, x, y] of FROZEN_TYPES){ + if(!H.hasType(t)){ note('N/A (build lacks '+t+')'); continue; } + const s = H.create(t, x, y, { name:'at_'+t }); + if(!s) note('BLOCKED '+t+' at '+x+','+y+(H.hints().length?' — '+H.hints().join(' / '):'')); + } + for(const [kind, x1, y1, x2, y2] of FROZEN_PRIMITIVES){ + if(!H.primitive(kind, x1, y1, x2, y2)) note('BLOCKED primitive '+kind); + } + const frozen = new Set(FROZEN_TYPES.map(e=>e[0])); + const extra = H.contractKeys().filter(k=>!frozen.has(k) && !STRUCTURAL_TYPES.has(k)); + if(extra.length) note('build has types outside the frozen list: '+extra.join(', ')+' (add them first — G6)'); +} + +// Compact scene for the theme channel: every theme-coloured family appears once. +function buildThemeBody(H){ + H.create('Button', 40, 40); + H.create('Checkbox', 40, 80); + H.create('SliderDouble', 40, 120); + const hdr = H.create('CollapsingHeader', 40, 170, { w:200, h:120 }); + if(hdr) H.create('Button', 60, 230); + H.create('TabBar', 300, 40, { w:240, h:160 }); + H.create('ProgressBar', 300, 240, { w:200, h:20 }); +} +function themeScene(id){ + return function(H, note){ + if(id===GATE_CUSTOM_THEME.id){ + const got = H.adoptProjectTheme(JSON.parse(JSON.stringify(GATE_CUSTOM_THEME))); + if(got!==GATE_CUSTOM_THEME.id) throw new Error('adoptProjectTheme returned '+JSON.stringify(got)); + } + H.set('themeId', id); + buildThemeBody(H); + }; +} + +function buildProject(H){ + H.set('cw', 640); H.set('ch', 360); + H.set('bgMode', 'custom'); H.set('bgColor', '#2d4a6b'); H.set('bgAlpha', 0.6); + H.set('projectTitle', 'Gate "quoted" \\ title'); + H.create('Button', 40, 40); + H.create('TextColored', 40, 80, { w:140, label:'On custom bg' }); + H.create('SliderInt', 40, 120); +} + +function exampleScene(file){ + return function(H){ + const p = path.join(FIXTURE_DIR, file); + if(!fs.existsSync(p)) throw new HarnessError('fixture missing: '+p); + const r = H.loadText(fs.readFileSync(p,'utf8')); + if(!r.ok) throw new Error('applyLoadedProject rejected '+file+(r.reason?': '+r.reason:'')); + }; +} + +// Creation-path guards: creation must not produce a project the loader rejects. +function buildGuards(H, note){ + const pk = H.create('ColorPicker4', 40, 40, { colorEditFlags:['NoInputs'] }); + note('ColorPicker4 + colorEditFlags [NoInputs]: '+(pk + ? 'created (flags '+JSON.stringify(pk.colorEditFlags)+')' + : 'refused'+(H.hints().length?' — '+H.hints().join(' / '):''))); +} + +// v3 — a themes.* scene for a theme definition held here. Same sequence as themeScene's +// gate-custom branch (adopt, set themeId, same body), so two defs that differ only in a +// field the build ignores produce the same export. +function customThemeScene(def){ + return function(H){ + const got = H.adoptProjectTheme(JSON.parse(JSON.stringify(def))); + if(got!==def.id) throw new Error('adoptProjectTheme returned '+JSON.stringify(got)); + H.set('themeId', def.id); + buildThemeBody(H); + }; +} + +// v4 — wave-a (B03 3.1). Layout on the pinned 900x700 canvas, default theme. +// Every widget is created with an explicit name (see the header). Creation goes through +// H.create; a type the build lacks is noted N/A and skipped before any create or uid +// draw; a refused create is noted BLOCKED with the tool's own hint. +function waveMake(H, note, t, x, y, ov){ + if(!H.hasType(t)){ note('N/A (build lacks '+t+')'); return null; } + const s = H.create(t, x, y, ov); + if(!s) note('BLOCKED '+t+' '+(ov&&ov.name||'')+' at '+x+','+y+(H.hints().length?' — '+H.hints().join(' / '):'')); + return s; +} +// A child that did not land in its intended parent would change what the scene covers +// without changing any count, so it is reported. +function waveNested(note, child, parent){ + if(child && parent && child.parentId!==parent.id) + note('NOT NESTED '+child.name+' (parentId '+JSON.stringify(child.parentId)+', expected '+parent.name+')'); +} +// [name, x, treeLines in wave-a (undefined = absent)]. Each TreeNode 240x200 at y 20; +// child TreeNode 180x70 at +20,+40 (below the 24 px header); child Button at +20,+140. +const WAVE_A_TREES = [ + ['wa_tree_none', 20, undefined], + ['wa_tree_full', 280, 'full'], + ['wa_tree_tonodes', 540, 'toNodes'], +]; +// [name, x, highlight in wave-a]. Selectables at y 250. +const WAVE_A_SELECTABLES = [ ['wa_sel_plain', 20, undefined], ['wa_sel_hl', 200, true] ]; +const WAVE_A_PLOT_VALUES = [0, 0.5, 1, 0.25, 0.75]; + +// mode: 'wave' — the wave-a values above; +// 'absent' — no new property set anywhere (G5 wave-a reference); +// 'explicit' — every new property set to its default: treeLines 'none' on all six +// TreeNodes (parents and children), highlight false on both Selectables. +function buildWaveATreeSel(H, note, mode){ + for(const [name, x, lines] of WAVE_A_TREES){ + const tree = waveMake(H, note, 'TreeNode', x, 20, { name, w:240, h:200 }); + if(!tree) continue; + const sub = waveMake(H, note, 'TreeNode', x+20, 60, { name:name+'_sub', w:180, h:70 }); + const btn = waveMake(H, note, 'Button', x+20, 160, { name:name+'_btn', w:120, h:20, label:'Btn' }); + waveNested(note, sub, tree); waveNested(note, btn, tree); + if(mode==='wave' && lines!==undefined) tree.treeLines = lines; + if(mode==='explicit'){ tree.treeLines = 'none'; if(sub) sub.treeLines = 'none'; } + } + for(const [name, x, hl] of WAVE_A_SELECTABLES){ + const s = waveMake(H, note, 'Selectable', x, 250, { name, label:name }); + if(!s) continue; + if(mode==='wave' && hl!==undefined) s.highlight = hl; + if(mode==='explicit') s.highlight = false; + } +} + +function buildWaveA(H, note){ + buildWaveATreeSel(H, note, 'wave'); + // Existing types first: the shipped Int N-variants (componentCount 2..4) plus one + // SliderDouble 3. No change is expected here in 1.2.0. + const cc = [ ['SliderInt', 300, 2], ['DragInt', 350, 3], + ['InputInt', 400, 4], ['SliderDouble', 450, 3] ]; + for(const [t, y, n] of cc){ + const s = waveMake(H, note, t, 20, y, { name:'wa_cc_'+t, w:240, label:t+' x'+n }); + if(s) s.componentCount = n; + } + // New types (1.2.0), after everything else. + const cbf = [ ['wa_cbf_opts0', 300, 'opts', 0], ['wa_cbf_opts3', 340, 'opts', 3], + ['wa_cbf_mode0', 380, 'mode', 0] ]; + for(const [name, y, group, bit] of cbf){ + const s = waveMake(H, note, 'CheckboxFlags', 600, y, { name, label:name }); + if(s){ s.flagGroup = group; s.flagBit = bit; } + } + const pl = waveMake(H, note, 'PlotLines', 320, 300, { name:'wa_plot_lines', w:200, h:60, label:'Lines' }); + if(pl){ pl.plotValues = WAVE_A_PLOT_VALUES.slice(); pl.overlay = 'lvl'; pl.scaleMin = 0; pl.scaleMax = 1; } + waveMake(H, note, 'PlotHistogram', 320, 400, { name:'wa_plot_hist', w:200, h:60, label:'Histogram' }); + waveMake(H, note, 'TextLink', 600, 440, { name:'wa_textlink', label:'Link' }); +} +function buildWaveAExplicit(H, note){ buildWaveATreeSel(H, note, 'explicit'); } + +// v5 — text-metrics (ADR-005 X1.0). Shapes are drawn through H.primitive (the editor's +// release path), then the text properties are set on the live shape. A dark fill gives the +// rect/circle labels the light label colour, a light fill the dark one — both appear. +const TM_LONG = 'The quick brown fox jumps over the lazy dog, then naps in the sun.'; +const TM_CYR = 'Съешь же ещё этих мягких французских булок, да выпей чаю.'; +// [kind, name, x, y, w, h, props] +const TEXT_METRICS_SHAPES = [ + ['rect', 'tm_r_short', 20, 20, 160, 40, { label:'OK', textSize:12, align:'center', fill:'#26323c' }], + ['rect', 'tm_r_left', 200, 20, 160, 90, { label:TM_LONG, textSize:12, align:'left', fill:'#26323c' }], + ['rect', 'tm_r_center', 380, 20, 160, 90, { label:TM_LONG, textSize:12, align:'center', fill:'#26323c' }], + ['rect', 'tm_r_right', 560, 20, 160, 90, { label:TM_LONG, textSize:12, align:'right', fill:'#26323c' }], + ['rect', 'tm_r_newlines', 20, 130, 160, 90, { label:'Line one\nLine two\n\nLine four', textSize:12, align:'left', fill:'#e8ecef' }], + ['rect', 'tm_r_blanks', 200, 130, 160, 60, { label:'Hello world and more blanks', textSize:12, align:'left', fill:'#e8ecef' }], + ['rect', 'tm_r_longword', 380, 130, 120, 60, { label:'Antidisestablishmentarianism', textSize:14, align:'center', fill:'#e8ecef' }], + ['rect', 'tm_r_punct', 560, 130, 140, 60, { label:'alpha,beta,gamma;delta!epsilon?zeta.eta"theta', textSize:12, align:'left', fill:'#e8ecef' }], + ['rect', 'tm_r_cyr', 20, 240, 180, 90, { label:TM_CYR, textSize:12, align:'left', fill:'#26323c' }], + ['rect', 'tm_r_ellipsis', 220, 240, 160, 30, { label:TM_LONG, textSize:12, align:'center', fill:'#26323c' }], + ['rect', 'tm_r_size20', 400, 240, 200, 90, { label:'Big text wraps too', textSize:20, align:'center', fill:'#26323c' }], + ['rect', 'tm_r_size10', 620, 240, 120, 50, { label:'Small text in a small box wraps here', textSize:10, align:'left', fill:'#26323c' }], + ['circle', 'tm_c_circle', 20, 350, 120, 120, { label:TM_LONG, textSize:12, align:'center', fill:'#e8ecef' }], + ['circle', 'tm_c_ellipse', 160, 370, 160, 80, { label:TM_CYR, textSize:10, align:'center', fill:'#26323c' }], + ['text', 'tm_t_single', 340, 350, 200, 20, { label:'Hello', textSize:14, align:'left', vAlign:'top' }], + ['text', 'tm_t_top', 340, 380, 200, 60, { label:TM_LONG, textSize:12, align:'left', vAlign:'top' }], + ['text', 'tm_t_middle', 560, 350, 200, 60, { label:TM_LONG, textSize:12, align:'center', vAlign:'middle' }], + ['text', 'tm_t_bottom', 560, 420, 200, 60, { label:TM_LONG, textSize:12, align:'right', vAlign:'bottom' }], + ['text', 'tm_t_cyr', 20, 490, 160, 60, { label:TM_CYR, textSize:12, align:'left', vAlign:'top' }], + ['text', 'tm_t_newlines', 200, 490, 160, 60, { label:'First line\nSecond line', textSize:14, align:'center', vAlign:'middle' }], + ['text', 'tm_t_overflow', 380, 490, 120, 20, { label:'This sentence is much taller than its box once it wraps', textSize:20, align:'left', vAlign:'top' }], +]; +function buildTextMetrics(H, note){ + for(const [kind, name, x, y, w, h, props] of TEXT_METRICS_SHAPES){ + const s = H.primitive(kind, x, y, x+w, y+h); + if(!s){ note('BLOCKED primitive '+kind+' '+name); continue; } + s.name = name; + Object.assign(s, props); + } +} + +// v6 — wave-b (B05 5.1). Layout on a widened 1100x600 canvas (H.set, as buildProject +// does), default theme. Every widget has an explicit name. Creation goes through +// H.create; a type the build lacks is noted N/A and skipped before any create or uid +// draw; a refused create is noted BLOCKED with the tool's own hint — same helpers as +// wave-a (waveMake, waveNested). +// [name, x, tabButton in wave-b (undefined = absent)]. Each TabBar 280x180 at y 20; its +// two TabItems ("Tab 1"/"Tab 2") are auto-created by H.create (createWidgetAtPoint), +// same as core's tabbar. tabButtonLabel 'Add' is set whenever tabButton is set. +const WAVE_B_TABBARS = [ + ['wb_tabbar_none', 20, undefined], + ['wb_tabbar_leading', 340, 'leading'], + ['wb_tabbar_trailing',660, 'trailing'], +]; +// [name, x, disabled in wave-b]. StyleRegion 200x120 at y 220; each holds one Button +// (interior +20,+40) and one SliderInt (interior +20,+80). The second also gets +// styleText, to cover the push order (B4). +const WAVE_B_STYLEREGIONS = [ + ['wb_sr_off', 20, undefined], + ['wb_sr_on', 260, true], +]; +// [name, x, freezeHeader in wave-b (undefined = absent), scrollY]. Table 320x200 at +// y 380; headersRow true on all three (freezeHeader is only meaningful with it). +const WAVE_B_TABLES = [ + ['wb_table_freeze_scrolly', 20, undefined, true], + ['wb_table_freeze_on_scrolly',380, true, true], + ['wb_table_freeze_on_noscroll',740, true, false], +]; +// mode: 'wave' — the wave-b values above; +// 'absent' — no new property set anywhere (G5 wave-b reference); +// 'explicit' — every new property set to its default: tabButton 'none' on all +// three TabBars, disabled false on both StyleRegions, freezeHeader +// false on all three Tables. +function buildWaveBTabSrTable(H, note, mode){ + for(const [name, x, btn] of WAVE_B_TABBARS){ + const tb = waveMake(H, note, 'TabBar', x, 20, { name, w:280, h:180 }); + if(!tb) continue; + if(mode==='wave' && btn!==undefined){ tb.tabButton = btn; tb.tabButtonLabel = 'Add'; } + if(mode==='explicit') tb.tabButton = 'none'; + } + for(const [name, x, dis] of WAVE_B_STYLEREGIONS){ + const sr = waveMake(H, note, 'StyleRegion', x, 220, { name, w:200, h:120 }); + if(!sr) continue; + const btn = waveMake(H, note, 'Button', x+20, 260, { name:name+'_btn', w:120, h:20, label:'Btn' }); + const sl = waveMake(H, note, 'SliderInt', x+20, 300, { name:name+'_sl', w:120 }); + waveNested(note, btn, sr); waveNested(note, sl, sr); + if(mode==='wave' && dis!==undefined){ sr.disabled = dis; if(name==='wb_sr_on') sr.styleText = '#c0ffee'; } + if(mode==='explicit') sr.disabled = false; + } + for(const [name, x, freeze, scrollY] of WAVE_B_TABLES){ + const t = waveMake(H, note, 'Table', x, 380, { name, w:320, h:200 }); + if(!t) continue; + t.headersRow = true; + t.tableFlags = Object.assign({}, t.tableFlags, { ScrollY: scrollY }); + if(mode==='wave' && freeze!==undefined) t.freezeHeader = freeze; + if(mode==='explicit') t.freezeHeader = false; + } +} +function buildWaveB(H, note){ + H.set('cw', 1100); H.set('ch', 600); + buildWaveBTabSrTable(H, note, 'wave'); + // The new type last (as wave-a): created before the existing types it would take the + // first uid and shift every normalised seed id and auto-name after it. Free spot: + // right of the StyleRegions (x 20-460), above the Tables (y 380). + waveMake(H, note, 'InvisibleButton', 500, 220, { name:'wb_invisible', w:120, h:40 }); +} +function buildWaveBExplicit(H, note){ + H.set('cw', 1100); H.set('ch', 600); + buildWaveBTabSrTable(H, note, 'explicit'); +} + +// v7 — tables-b (B06 6.1, ADR-011 G2/G4). Layout on a widened 1200x800 canvas (H.set), +// default theme. Every table has an explicit name and 3 columns of clearly different +// label widths, so a wrong maxW (ADR-011 fact 3) would show in the REAPER pass. Tables +// sit two per row (600 px pitch), 560x220 boxes at y 20 / 300 / 580 (coordinator review: +// comment corrected; the text-metrics newline labels restored to v6's text). +// [name, x, y, angledHeaders in tables-b (undefined = absent), scrollY, headersRow, +// rowCount, scrollRows in tables-b (undefined = absent), freezeHeader] +const TABLES_B = [ + ['tb_angled_scroll', 20, 20, [0,2], true, true, 6, undefined, undefined], + ['tb_angled_all', 620, 20, [0,1,2], false, true, 4, undefined, undefined], + ['tb_scroll_plain', 20, 300, undefined, true, true, 4, undefined, undefined], + ['tb_scrollrows', 620, 300, undefined, true, true, 4, 20, true], + ['tb_angled_noheader', 20, 580, [1], false, false,4, undefined, undefined], + ['tb_scrollrows_noscroll',620,580, undefined, false,true, 4, 20, undefined], +]; +// Column labels of clearly different widths, reused on every table (only the angled +// tables' labels are ever measured for maxW, but a uniform set keeps the scene simple). +const TABLES_B_COLUMNS = ['Gain', 'Pan', 'Output routing']; + +// v8 — menus (B07 7.1, ADR-007). A menu bar is project data, not a shape: the scenes build +// widgets through H.create, save, add `menuBar` to the saved object, reset and load it back +// (withMenuBar), so a build that does not know the key still builds the scene. +const MENUS_CANVAS = { cw:700, ch:300 }; +const MENUS_FIXTURE = [ + { type:'menu', name:'mb_file', label:'File', items:[ + { type:'item', name:'mb_file_new', label:'New', shortcut:'Ctrl+N' }, + { type:'item', name:'mb_file_open', label:'Open…', shortcut:'Ctrl+O' }, + { type:'item', name:'mb_file_open2', label:'Open…' }, + { type:'separator' }, + { type:'menu', name:'mb_file_recent', label:'Recent', items:[ + { type:'item', name:'mb_recent_a', label:'Project A' }, + { type:'menu', name:'mb_recent_more', label:'More', items:[ + { type:'menu', name:'mb_recent_deep', label:'Deep', items:[ + { type:'item', name:'mb_recent_deep_item', label:'Deepest item' }, + ]}, + ]}, + ]}, + { type:'separator' }, + { type:'item', name:'mb_file_quit', label:'Quit', shortcut:'Ctrl+Q', enabled:false }, + ]}, + { type:'menu', name:'mb_view', label:'View', items:[ + { type:'check', name:'mb_view_grid', label:'Show grid', checked:true }, + { type:'check', name:'mb_view_snap', label:'Snap', shortcut:'S' }, + { type:'check', name:'mb_view_locked', label:'Locked', enabled:false }, + ]}, + { type:'menu', name:'mb_edit', label:'Edit', enabled:false, items:[ + { type:'item', name:'mb_edit_undo', label:'Undo' }, + ]}, + { type:'menu', name:'mb_help', label:'Help', items:[] }, +]; + +// findMenuByName: depth-first search for an entry by name, used to attach +// MENUS_WITH_INVALID's extra entries to the right parent's items array. +function findMenuByName(tree, name){ + for(const e of tree){ + if(e.name===name) return e; + if(e.items){ const r = findMenuByName(e.items, name); if(r) return r; } + } + return null; +} +// MENUS_WITH_INVALID: MENUS_FIXTURE plus entries the 1.6.0 loader must drop or change +// (ADR-007 M2). Each entry's comment says why. +const MENUS_WITH_INVALID = (function(){ + const tree = JSON.parse(JSON.stringify(MENUS_FIXTURE)); + // top level holds menus only. + tree.push({ type:'item', name:'mb_top_item', label:'Top item' }); + const view = findMenuByName(tree, 'mb_view'); + view.items.push({ type:'bogus', name:'mb_bogus', label:'?' }); // unknown type + view.items.push({ type:'item', name:'mb_empty', label:'' }); // empty label + view.items.push({ type:'item', name:'mn_origin', label:'Clash' }); // name taken by a widget + view.items.push({ type:'item', name:'mb_view_grid', label:'Dup name' }); // name taken by an earlier entry + view.items.push({ type:'item', name:'mb_hash', label:'Save##x' }); // kept, label cut at `##` -> `Save` + const deep = findMenuByName(tree, 'mb_recent_deep'); + deep.items.push({ type:'menu', name:'mb_too_deep', label:'Too deep', // depth 5, dropped with its items + items:[ { type:'item', name:'mb_too_deep_item', label:'x' } ] }); + return tree; +})(); + +// menusExplicitDefaults: MENUS_FIXTURE with every default written out explicitly +// (enabled:true, shortcut:'', checked:false) instead of left absent. +function menusExplicitDefaults(tree){ + const clone = JSON.parse(JSON.stringify(tree)); + (function walk(items){ + for(const e of items){ + if(e.type==='menu' || e.type==='item' || e.type==='check'){ + if(e.enabled===undefined) e.enabled = true; + } + if(e.type==='item' || e.type==='check'){ + if(e.shortcut===undefined) e.shortcut = ''; + } + if(e.type==='check'){ + if(e.checked===undefined) e.checked = false; + } + if(e.items) walk(e.items); + } + })(clone); + return clone; +} + +// mode: 'wave' — the tables-b values above (angledHeaders / scrollRows per row); +// 'absent' — no new property set anywhere (G5 tables-b reference); +// 'explicit' — angledHeaders:[] and scrollRows:0 set explicitly on every table +// (the defaults ADR-011 G2/G4 specify). +function buildTablesB(H, note, mode){ + for(const [name, x, y, angled, scrollY, headersRow, rowCount, scrollRows, freeze] of TABLES_B){ + const t = waveMake(H, note, 'Table', x, y, { name, w:560, h:220 }); + if(!t) continue; + t.columns = TABLES_B_COLUMNS.slice(); + t.headersRow = headersRow; + t.tableFlags = Object.assign({}, t.tableFlags, { ScrollY: scrollY }); + if(freeze !== undefined) t.freezeHeader = freeze; + if(mode==='wave'){ + if(angled !== undefined) t.angledHeaders = angled.slice(); + if(scrollRows !== undefined) t.scrollRows = scrollRows; + } else if(mode==='explicit'){ + t.angledHeaders = []; + t.scrollRows = 0; + } + // v13 fixture correction: emulate the inspector's committed Table-property edit. + // The v12 fixture set angledHeaders after its only resize/reflow call, leaving + // TableCell bounds stale until Save -> Load. Refresh AFTER all live mutations, + // and BEFORE positioning the nested Button. This is test setup, not a builder fix. + H.resizeTable(t, rowCount); + // tb_angled_scroll: one Button nested in cell r0c0, captured by the tool's own + // cell placement (as core does with its Text-in-cell, wave*'s waveNested pattern). + if(name==='tb_angled_scroll'){ + const c = H.cellAt(t.id, 0, 0); + if(!c){ note('NO CELL r0c0 on '+name); } + else { + const btn = waveMake(H, note, 'Button', H.absX(c)+4, H.absY(c)+4, { name:name+'_btn', w:60, h:20, label:'Go' }); + waveNested(note, btn, c); + } + } + } +} +function buildTablesB_(H, note){ H.set('cw', 1200); H.set('ch', 520 + 280); buildTablesB(H, note, 'wave'); } +function buildTablesBExplicit(H, note){ H.set('cw', 1200); H.set('ch', 520 + 280); buildTablesB(H, note, 'explicit'); } + +// v8 — menus scene helpers (B07 7.1). withMenuBar round-trips the current project +// through Save -> add `menuBar` -> reset -> Load, so a build that does not know the +// key still builds the scene (menu data lives only in the saved/loaded project, never +// set on a live shape). +function withMenuBar(H, menuBar){ + const p = JSON.parse(H.saveText()); + if(menuBar !== undefined) p.menuBar = JSON.parse(JSON.stringify(menuBar)); + H.reset(); + const r = H.loadText(JSON.stringify(p)); + if(!r.ok) throw new Error('applyLoadedProject rejected the menus project'+(r.reason?': '+r.reason:'')); + return r; +} +// Widgets first (explicit names), at y = 0 so a moved canvas origin would show. +function buildMenusWidgets(H, note){ + H.set('cw', MENUS_CANVAS.cw); H.set('ch', MENUS_CANVAS.ch); + waveMake(H, note, 'Button', 0, 0, { name:'mn_origin', w:120, h:20, label:'Origin' }); + waveMake(H, note, 'Checkbox', 240, 0, { name:'mn_check' }); + waveMake(H, note, 'SliderInt', 0, 40, { name:'mn_slider', w:200 }); +} +function buildMenusScene(menuBar, theme){ + return function(H, note){ + if(theme) H.set('themeId', theme); + buildMenusWidgets(H, note); + const r = withMenuBar(H, menuBar); + if(r.reason) note('loader: '+r.reason.replace(/\s+/g,' ').trim()); + }; +} + +// v9 — add project-level keys to a saved project and load it back (withMenuBar's pattern, +// any keys). A build that does not know a key ignores it. +function withProjectKeys(H, keys){ + const p = JSON.parse(H.saveText()); + Object.assign(p, JSON.parse(JSON.stringify(keys))); + H.reset(); + const r = H.loadText(JSON.stringify(p)); + if(!r.ok) throw new Error('applyLoadedProject rejected the project'+(r.reason?': '+r.reason:'')); + return r; +} + +// v9 — themes.slate-title / themes.slate-title.explicit-default (B07 7.3, ADR-007 M11). +// The compact themes.* body under `slate`, with `themedTitleBar` added to the saved +// project through withProjectKeys — true for the "on" scene, false (the explicit +// default) for the reference scene G5 title compares it against. +function buildSlateTitleScene(themedTitleBar){ + return function(H, note){ + H.set('themeId', 'slate'); + buildThemeBody(H); + const r = withProjectKeys(H, { themedTitleBar }); + if(r.reason) note('loader: '+r.reason.replace(/\s+/g,' ').trim()); + }; +} +// v9 — menus.themed-title (B07 7.3, ADR-007 M11). The menus widgets under `slate`, with +// both `menuBar` and `themedTitleBar:true` added in one withProjectKeys call. +function buildMenusThemedTitleScene(){ + return function(H, note){ + H.set('themeId', 'slate'); + buildMenusWidgets(H, note); + const r = withProjectKeys(H, { menuBar: MENUS_FIXTURE, themedTitleBar:true }); + if(r.reason) note('loader: '+r.reason.replace(/\s+/g,' ').trim()); + }; +} + +// v10 — arcs (B11 11.1; F04 coverage after the fact, B10 review R1). Each arc is drawn through +// H.primitive('arc', ...) (the editor's release path), then name and properties are set on the +// live shape, as text-metrics does. Canvas 800x560, default theme. Frozen table: +// [name, x, y, w, h, props]; 3 rows of 5, column x = 20 + col*155, row y = 20 / 180 / 340, +// boxes 120x120 unless stated. Arcs only, no labels; fill and stroke colours stay at the +// defaults the creation path gives; names are explicit (nothing depends on running counters). +const ARCS_CANVAS = { cw:800, ch:560 }; +const ARCS_SHAPES = [ + // row 1 (y 20) + ['ar_pie_90', 20, 20, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:90 }], // convex, unchanged by F04 + ['ar_pie_180', 175, 20, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:180 }], // convex boundary + ['ar_pie_270', 330, 20, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:270 }], // concave fill (fill + stroke) + ['ar_pie_wrap', 485, 20, 120, 120, { arcMode:'pie', angleStart:300, angleEnd:60 }], // crosses 0: 120 deg clockwise + ['ar_pie_full', 640, 20, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:360 }], // full turn: no centre point + // row 2 (y 180) + ['ar_pie_equal', 20, 180, 120, 120, { arcMode:'pie', angleStart:45, angleEnd:45 }], // empty sweep + ['ar_pie_neg', 175, 180, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:-90 }], // negative end: 270 deg clockwise, concave + ['ar_pie_big', 330, 180, 120, 120, { arcMode:'pie', angleStart:720, angleEnd:810 }], // angles past one turn: 90 deg + ['ar_pie_fill_only', 485, 180, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:270, strokeNone:true }], // concave fill, no stroke + ['ar_pie_stroke_only',640, 180, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:270, fillNone:true }], // stroke only + // row 3 (y 340) + ['ar_pie_alpha', 20, 340, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:270, opacity:128, thickness:6 }], // concave fill with alpha, thick stroke + ['ar_ring_neg', 175, 340, 120, 120, { arcMode:'ring', angleStart:0, angleEnd:-90 }], // open arc, clockwise sweep + ['ar_ring_full', 330, 340, 120, 120, { arcMode:'ring', angleStart:0, angleEnd:360 }], // open arc, full turn + ['ar_ring_nostroke', 485, 340, 120, 120, { arcMode:'ring', angleStart:0, angleEnd:270, strokeNone:true }], // nothing to draw: emits nothing on dev.12 + ['ar_pie_ellipse', 640, 340, 140, 80, { arcMode:'pie', angleStart:30, angleEnd:250 }], // non-square box (radius = min(w, h)/2), concave +]; +function buildArcs(H, note){ + H.set('cw', ARCS_CANVAS.cw); H.set('ch', ARCS_CANVAS.ch); + for(const [name, x, y, w, h, props] of ARCS_SHAPES){ + const s = H.primitive('arc', x, y, x+w, y+h); + if(!s){ note('BLOCKED primitive arc '+name); continue; } + s.name = name; + Object.assign(s, props); + } +} + +// v11 — adaptive scenes (A01, ADR-009 AD11). Fixture first (ADR-002 G6): the harness learns +// `pinH` / `pinV` (per shape) and `windowResize` (per project) before the builder knows them. +// Pins and project keys never touch live shapes: withAdaptive writes them into the SAVED +// project and loads it back, so a build that does not know them shows what its loader does +// with them (1.7.0-dev.3 keeps unknown shape keys and drops unknown project keys). +// +// Body A — a 640x440 form. [name, type, x, y, overrides, parent name | null]. Absolute +// canvas coordinates, passed to H.create (which nests a widget into the container under it); +// a container is created before its children. Every shape has an explicit name. +const ADAPTIVE_BODY_A = [ + ['ad_title', 'Text', 20, 10, { w:200, label:'Adaptive' }, null], + ['ad_close', 'Button', 520, 10, { w:100, h:20, label:'Close' }, null], + ['ad_input', 'InputText', 20, 50, { w:380 }, null], + ['ad_combo', 'Combo', 440, 50, { w:180 }, null], + ['ad_center', 'Button', 270, 90, { w:100, h:24, label:'Center' }, null], + ['ad_slider', 'SliderDouble',440, 90, { w:180 }, null], + ['ad_panel', 'Panel', 20, 130, { w:600, h:200 }, null], + ['ad_p_btn', 'Button', 30, 140, { w:80, h:20, label:'Inner' }, 'ad_panel'], + ['ad_p_list', 'ListBox', 30, 180, { w:280, h:110 }, 'ad_panel'], + ['ad_p_grp', 'Group', 340, 180, { w:170, h:100 }, 'ad_panel'], + ['ad_g_btn', 'Button', 360, 230, { w:100, h:20, label:'Grouped' }, 'ad_p_grp'], + ['ad_p_ok', 'Button', 520, 300, { w:90, h:20, label:'Apply' }, 'ad_panel'], + ['ad_progress', 'ProgressBar', 20, 350, { w:600, h:20 }, null], + ['ad_status', 'Text', 20, 400, { w:240, label:'Status' }, null], + ['ad_cancel', 'Button', 410, 400, { w:100, h:20, label:'Cancel' }, null], + ['ad_ok', 'Button', 520, 400, { w:100, h:20, label:'OK' }, null], +]; +// Pin sets: { : { pinH?, pinV? } }. +const ADAPTIVE_PINS_MOVE = { + ad_close: { pinH:'right' }, + ad_combo: { pinH:'right' }, + ad_center: { pinH:'center' }, + ad_slider: { pinH:'right', pinV:'center' }, + ad_panel: { pinV:'bottom' }, + ad_p_grp: { pinH:'right' }, + ad_g_btn: { pinH:'center' }, + ad_p_ok: { pinH:'right', pinV:'bottom' }, + ad_status: { pinV:'bottom' }, + ad_cancel: { pinH:'right', pinV:'bottom' }, + ad_ok: { pinH:'right', pinV:'bottom' }, +}; +const ADAPTIVE_PINS_STRETCH = { // applied after MOVE; a key here overrides MOVE's + ad_input: { pinH:'stretch' }, + ad_panel: { pinH:'stretch', pinV:'stretch' }, + ad_p_list: { pinH:'stretch', pinV:'stretch' }, + ad_progress: { pinH:'stretch' }, +}; +// Body N pins (the table of the brief, column "pins"). +const ADAPTIVE_PINS_NESTED = { + ad_n_sr: { pinH:'stretch' }, + ad_n_sr_sl: { pinH:'right' }, + ad_n_sr_bt: { pinH:'center' }, + ad_n_tabs: { pinH:'stretch', pinV:'stretch' }, + ad_n_tab_bt: { pinH:'right', pinV:'bottom' }, + ad_n_tree: { pinH:'right' }, + ad_n_tree_bt: { pinH:'center' }, + ad_n_pan: { pinV:'bottom' }, + ad_n_pan_in: { pinH:'stretch' }, + ad_n_pan_bt: { pinH:'right' }, + ad_n_tbl: { pinH:'right', pinV:'bottom' }, + ad_n_hdr: { pinV:'bottom' }, + ad_n_hdr_bt: { pinH:'right' }, +}; +// Body P: [kind, name, x1, y1, x2, y2, props] through H.primitive, then name and props are +// set on the live shape (as buildTextMetrics does). +const ADAPTIVE_PRIMS = [ + ['rect', 'ad_r', 20, 20, 220, 80, { label:'Rect label that wraps at runtime', textSize:14 }], + ['text', 'ad_t', 20, 100, 320, 140, { label:'Text primitive that wraps inside its box', textSize:12, align:'left', vAlign:'top' }], + ['circle', 'ad_c', 520, 20, 600, 100, { label:'C' }], + ['arc', 'ad_a', 280, 180, 360, 260, {}], + ['line', 'ad_l', 20, 300, 220, 340, {}], + ['poly', 'ad_p', 420, 300, 520, 380, {}], + ['triangle', 'ad_tri',260, 320, 340, 400, {}], +]; +const ADAPTIVE_PINS_PRIMS = { + ad_r: { pinH:'stretch', pinV:'center' }, + ad_t: { pinH:'stretch' }, + ad_c: { pinH:'right' }, + ad_a: { pinH:'center', pinV:'center' }, + ad_l: { pinV:'bottom' }, + ad_p: { pinH:'right', pinV:'bottom' }, + ad_tri: { pinH:'center' }, + ad_pr_bt: { pinH:'right' }, +}; +// Body M: buildMenusWidgets + MENUS_FIXTURE (the v8 data, unchanged). +const ADAPTIVE_PINS_MENUS = { + mn_origin: { pinH:'right' }, + mn_check: { pinH:'right' }, + mn_slider: { pinV:'bottom' }, +}; +// adaptive.invalid: values ADR-009 AD1, AD2 and AD4 make the loader drop (maxH:2000 is kept). +// The TabItem and TableCell have no name of their own; buildAdaptiveInvalid finds them. +const ADAPTIVE_PINS_INVALID = { + ad_title: { pinH:'up' }, + ad_close: { pinV:5, pinH:'RIGHT' }, + ad_combo: { pinH:'left' }, + ad_slider: { pinV:'stretch' }, // a native-height control: stretch refused by AD4 + ad_p_grp: { pinH:null }, +}; +const ADAPTIVE_WINDOW_INVALID = { minW:10, minH:'x', maxW:100, maxH:2000 }; + +// withAdaptive(H, pins, keys, note, edit): the pattern of withProjectKeys. +// 1. p = the saved project; +// 2. for every [name, props] of `pins`, Object.assign the props onto the shape named `name` +// in p.shapes (undefined values are not set; a missing name is noted `MISSING `); +// 3. `edit(p)`, when given, may change p further (shapes that have no name of their own); +// 4. Object.assign(p, keys) (undefined values are not set), then reset and Load. A rejected +// load throws, as withProjectKeys does; a loader message is noted as `loader: …`. +// `note` is the scene's note function (MISSING and loader notes go through it). +function withAdaptive(H, pins, keys, note, edit){ + const defined = o => Object.fromEntries(Object.entries(o || {}).filter(([, v]) => v !== undefined)); + const p = JSON.parse(H.saveText()); + for(const [name, props] of Object.entries(pins || {})){ + const s = p.shapes.find(sh => sh.name === name); + if(!s){ note('MISSING '+name); continue; } + Object.assign(s, defined(props)); + } + if(edit) edit(p); + Object.assign(p, JSON.parse(JSON.stringify(defined(keys)))); + H.reset(); + const r = H.loadText(JSON.stringify(p)); + if(!r.ok) throw new Error('applyLoadedProject rejected the adaptive project'+(r.reason?': '+r.reason:'')); + if(r.reason) note('loader: '+r.reason.replace(/\s+/g,' ').trim()); + return r; +} + +// Body A, on a 640 x canvasH canvas (440; 560 for adaptive.invalid). Returns { name: shape }. +function buildAdaptiveBody(H, note, canvasH){ + H.set('cw', 640); H.set('ch', canvasH); + const made = {}; + for(const [name, type, x, y, ov, parent] of ADAPTIVE_BODY_A){ + const s = waveMake(H, note, type, x, y, Object.assign({ name }, ov)); + if(!s) continue; + made[name] = s; + if(parent) waveNested(note, s, made[parent]); + } + return made; +} +// 'move' = MOVE; 'move+stretch' = MOVE then STRETCH (a key in STRETCH overrides MOVE's); +// 'move+explicit' = MOVE plus {pinH:'left', pinV:'top'} on every Body A shape for each key +// MOVE leaves unset; null = no pins. +function adaptivePins(pinSet){ + const out = {}; + const put = src => { for(const [n, pr] of Object.entries(src)) out[n] = Object.assign(out[n] || {}, pr); }; + switch(pinSet){ + case null: break; + case 'move': put(ADAPTIVE_PINS_MOVE); break; + case 'move+stretch': put(ADAPTIVE_PINS_MOVE); put(ADAPTIVE_PINS_STRETCH); break; + case 'move+explicit': + for(const row of ADAPTIVE_BODY_A) out[row[0]] = { pinH:'left', pinV:'top' }; + put(ADAPTIVE_PINS_MOVE); + break; + default: throw new Error('adaptivePins: unknown pin set '+pinSet); + } + return out; +} +// windowResize === null: no `windowResize` key at all; otherwise the key is set to it. +function adaptiveScene(body, pinSet, windowResize){ + return function(H, note){ + if(body !== 'A') throw new Error('adaptiveScene: unknown body '+body); + buildAdaptiveBody(H, note, 440); + withAdaptive(H, adaptivePins(pinSet), windowResize === null ? {} : { windowResize }, note); + }; +} + +// Body N — containers and what they hold, 640x520, `windowResize: {}`. +function buildAdaptiveNested(H, note){ + H.set('cw', 640); H.set('ch', 520); + const mk = (t, name, x, y, ov, parent) => { + const s = waveMake(H, note, t, x, y, Object.assign({ name }, ov)); + if(s && parent) waveNested(note, s, parent); + return s; + }; + const sr = mk('StyleRegion', 'ad_n_sr', 20, 20, { w:600, h:110 }); + mk('SliderDouble', 'ad_n_sr_sl', 40, 60, { w:200 }, sr); + mk('Button', 'ad_n_sr_bt', 300, 90, { w:100, h:20, label:'Mid' }, sr); + const tabs = mk('TabBar', 'ad_n_tabs', 20, 150, { w:380, h:160 }); + const tabBt = mk('Button', 'ad_n_tab_bt', 40, 260, { w:100, h:20, label:'InTab' }); + if(tabBt && tabs){ + // The parent must be the TabBar's active TabItem. + const ti = H.shapes().find(s => s.widgetType==='TabItem' && s.parentId===tabs.id && s.id===tabs.activeTabId); + if(ti) waveNested(note, tabBt, ti); + else note('NOT NESTED ad_n_tab_bt (active TabItem of ad_n_tabs not found)'); + } + const tree = mk('TreeNode', 'ad_n_tree', 420, 150, { w:200, h:160 }); + mk('Button', 'ad_n_tree_bt', 440, 220, { w:120, h:20, label:'InTree' }, tree); + const pan = mk('Panel', 'ad_n_pan', 20, 330, { w:380, h:80 }); + const panIn = mk('Panel', 'ad_n_pan_in', 30, 340, { w:180, h:60 }, pan); + mk('Button', 'ad_n_pan_bt', 40, 350, { w:80, h:20, label:'Deep' }, panIn); + const tbl = mk('Table', 'ad_n_tbl', 420, 330, { w:200, h:80 }); + if(tbl){ + const cells = H.cellsOf(tbl.id); // centre of the first cell, as buildCore does + if(cells.length){ + const c = cells[0]; + mk('Text', 'ad_n_tbl_txt', H.absX(c)+c.w/2-10, H.absY(c)+c.h/2-6, { w:20, h:12 }, c); + } else note('NOT NESTED ad_n_tbl_txt (the table has no cells)'); + } + const hdr = mk('CollapsingHeader', 'ad_n_hdr', 20, 430, { w:600, h:80 }); + mk('Button', 'ad_n_hdr_bt', 40, 470, { w:100, h:20, label:'InHeader' }, hdr); + withAdaptive(H, ADAPTIVE_PINS_NESTED, { windowResize:{} }, note); +} + +// Body P — seven primitives and one widget, 640x440, `windowResize: {}`. +function buildAdaptivePrimitives(H, note){ + H.set('cw', 640); H.set('ch', 440); + for(const [kind, name, x1, y1, x2, y2, props] of ADAPTIVE_PRIMS){ + const s = H.primitive(kind, x1, y1, x2, y2); + if(!s){ note('BLOCKED primitive '+kind+' '+name); continue; } + s.name = name; + Object.assign(s, props); + } + waveMake(H, note, 'Button', 420, 200, { name:'ad_pr_bt', w:100, h:20, label:'Btn' }); + withAdaptive(H, ADAPTIVE_PINS_PRIMS, { windowResize:{} }, note); +} + +// Body M — the v8 menus widgets and MENUS_FIXTURE, `windowResize: { maxW: 1000 }`. +function buildAdaptiveMenus(H, note){ + buildMenusWidgets(H, note); + withAdaptive(H, ADAPTIVE_PINS_MENUS, { menuBar: MENUS_FIXTURE, windowResize:{ maxW:1000 } }, note); +} + +// adaptive.invalid — Body A on a 640x560 canvas plus a TabBar and a Table, then every invalid +// value. The first TabItem and the first TableCell are parent-managed: found in p.shapes by +// widgetType and parentId (a MISSING note if absent). +function buildAdaptiveInvalid(H, note){ + buildAdaptiveBody(H, note, 560); + waveMake(H, note, 'TabBar', 20, 450, { name:'ad_i_tabs', w:300, h:100 }); + waveMake(H, note, 'Table', 340, 450, { name:'ad_i_tbl', w:280, h:100 }); + withAdaptive(H, ADAPTIVE_PINS_INVALID, { windowResize: ADAPTIVE_WINDOW_INVALID }, note, p => { + const firstChild = (parentName, widgetType, props, label) => { + const par = p.shapes.find(s => s.name === parentName); + const kid = par && p.shapes.find(s => s.widgetType === widgetType && s.parentId === par.id); + if(kid) Object.assign(kid, props); else note('MISSING '+label); + }; + firstChild('ad_i_tabs', 'TabItem', { pinH:'right' }, 'first TabItem of ad_i_tabs'); + firstChild('ad_i_tbl', 'TableCell', { pinV:'bottom' }, 'first TableCell of ad_i_tbl'); + }); +} + +// v12 — tables-c scenes (A07.1, ADR-002 G6). Fixture first: the harness learns the 2.1.0 Table +// properties (`cellPadding`, `rowBg`, `highlightColor`, `highlightRows`, `rowsFill`), the +// StyleRegion property `styleFramePadding` and Table stretch pins before the builder knows them. +// Tables are built through H.create and then mutated on the live shape (the wave-b / tables-b +// pattern); pins and `windowResize` go through withAdaptive (the v11 pattern), so a build that +// does not know a property still builds every scene. Canvas 640x480, default theme. +// +// tcCellMake: H.cellChild plus the harness notes (N/A, BLOCKED, NOT NESTED) in waveMake's words. +function tcCellMake(H, note, tableName, r, c, type, x, y, ov){ + if(!H.hasType(type)){ note('N/A (build lacks '+type+')'); return null; } + const s = H.cellChild(tableName, r, c, type, x, y, ov); + const n = H.cellChildNote(); + if(n) note(n); + else if(!s) note('BLOCKED '+type+' '+(ov&&ov.name||'')+' in '+tableName+' r'+r+'c'+c+(H.hints().length?' — '+H.hints().join(' / '):'')); + return s; +} +// Column sizing as the inspector stores it: { sizing:'fixed'|'stretch', value }. +const TC_FIXED = v => ({ sizing:'fixed', value:v }); +const TC_STRETCH = { sizing:'stretch', value:1 }; + +// tables-c.stretch: three tables, [name, x, y, w, h]. Pins: tc_list Left+Right + Top+Bottom +// (pinH + pinV 'stretch'), tc_hdr Left+Right only (pinH 'stretch'), tc_plain Top+Bottom only +// (pinV 'stretch'). tc_list's cell children are named tc_list_rc; the pinned ones are +// tc_list_btn (r0c2, pinH 'right') and tc_list_wrap (r1c2, pinH 'stretch'). +const TABLES_C_STRETCH = { + list: ['tc_list', 20, 20, 600, 200], + hdr: ['tc_hdr', 20, 232, 600, 110], + plain: ['tc_plain', 20, 354, 600, 110], +}; +const TABLES_C_STRETCH_PINS = { + tc_list: { pinH:'stretch', pinV:'stretch' }, + tc_list_btn: { pinH:'right' }, + tc_list_wrap: { pinH:'stretch' }, + tc_hdr: { pinH:'stretch' }, + tc_plain: { pinV:'stretch' }, +}; +function buildTablesCStretch(H, note){ + H.set('cw', 640); H.set('ch', 480); + // tc_list: 4 columns fixed 20 / fixed 30 / stretch / fixed 64, no header, ScrollY, 5 rows fixed at 24. + const [ln, lx, ly, lw, lh] = TABLES_C_STRETCH.list; + const list = waveMake(H, note, 'Table', lx, ly, { name:ln, w:lw, h:lh }); + if(list){ + list.columns = ['A', 'B', 'C', 'D']; + list.columnConfig = [TC_FIXED(20), TC_FIXED(30), Object.assign({}, TC_STRETCH), TC_FIXED(64)]; + list.headersRow = false; + list.tableFlags = Object.assign({}, list.tableFlags, { ScrollY:true }); + list.rowHeights = [24, 24, 24, 24, 24]; + H.resizeTable(list, 5, 4); // grows to 5 x 4 and re-flows the cells + for(let r = 0; r < 5; r++){ + tcCellMake(H, note, ln, r, 0, 'ColorButton', 2, 4, { name:'tc_list_r'+r+'c0', w:16, h:16 }); + tcCellMake(H, note, ln, r, 1, 'Text', 4, 4, { name:'tc_list_r'+r+'c1', w:22, label:String(r+1) }); + tcCellMake(H, note, ln, r, 2, 'Text', 4, 4, { name:'tc_list_r'+r+'c2', w:120, label:'Region '+(r+1) }); + tcCellMake(H, note, ln, r, 3, 'TextDisabled', 4, 4, { name:'tc_list_r'+r+'c3', w:56, label:'00:0'+r }); + } + tcCellMake(H, note, ln, 0, 2, 'Button', 380, 2, { name:'tc_list_btn', w:70, h:20, label:'Go' }); + tcCellMake(H, note, ln, 1, 2, 'TextWrapped', 130, 4, { name:'tc_list_wrap', w:200, h:16, label:'A longer name that wraps' }); + } + // tc_hdr: 3 columns, header row, ScrollY, rows flexible. + const [hn, hx, hy, hw, hh] = TABLES_C_STRETCH.hdr; + const hdr = waveMake(H, note, 'Table', hx, hy, { name:hn, w:hw, h:hh }); + if(hdr){ + hdr.headersRow = true; + hdr.tableFlags = Object.assign({}, hdr.tableFlags, { ScrollY:true }); + H.resizeTable(hdr, 3); + } + // tc_plain: no ScrollY, rows flexible. + const [pn, px, py, pw, ph] = TABLES_C_STRETCH.plain; + const plain = waveMake(H, note, 'Table', px, py, { name:pn, w:pw, h:ph }); + if(plain) H.resizeTable(plain, 3); + withAdaptive(H, TABLES_C_STRETCH_PINS, { windowResize:{ minW:480, minH:320 } }, note); +} + +// tables-c.style: [name, x, y, w, h]. Fixed window, no `windowResize` key. +const TABLES_C_STYLE = [ + ['tc_pad', 20, 20, 300, 110], + ['tc_bg', 330, 20, 290, 110], + ['tc_hl', 20, 140, 300, 130], + ['tc_nofill', 330, 140, 290, 130], +]; +const TC_ROW_BG = ['#ffe0e0', null, '#e0e8ff']; // rowBg on rows 0 and 2 of tc_bg +// mode: 'values' — the 2.1.0 values (tables-c.style); +// 'absent' — no new property set anywhere (G5 tables-c reference); +// 'explicit' — every new property set to its default: cellPadding [4,2], rowBg [], +// highlightRows [], rowsFill true on every table; highlightColor and +// styleFramePadding left out (they have no default / are nullable). +function buildTablesCStyle(H, note, mode){ + H.set('cw', 640); H.set('ch', 480); + for(const [name, x, y, w, h] of TABLES_C_STYLE){ + const t = waveMake(H, note, 'Table', x, y, { name, w, h }); + if(!t) continue; + if(name === 'tc_hl'){ + t.tableFlags = Object.assign({}, t.tableFlags, { ScrollY:true }); + t.scrollRows = 10; + t.rowCount = 5; + } + if(name === 'tc_nofill'){ + t.tableFlags = Object.assign({}, t.tableFlags, { ScrollY:true }); + t.rowHeights = [24, 24, 24]; + } + if(mode === 'values'){ + if(name === 'tc_pad') t.cellPadding = [4, 4]; + if(name === 'tc_bg') t.rowBg = TC_ROW_BG.slice(); + if(name === 'tc_hl'){ t.highlightColor = '#F1F1F1'; t.highlightRows = [1, 3]; } + if(name === 'tc_nofill') t.rowsFill = false; + } else if(mode === 'explicit'){ + t.cellPadding = [4, 2]; + t.rowBg = []; + t.highlightRows = []; + t.rowsFill = true; + } + H.resizeTable(t, name === 'tc_hl' ? 5 : 3); // re-flow the cells after the mutations + if(name === 'tc_pad'){ + tcCellMake(H, note, name, 0, 0, 'Text', 4, 4, { name:'tc_pad_r0c0', w:60, label:'Padded' }); + tcCellMake(H, note, name, 1, 1, 'Text', 4, 4, { name:'tc_pad_r1c1', w:60, label:'Cell' }); + } + } + // tc_sr: a StyleRegion with styleFramePadding [8,5] holding an InputTextWithHint and a Button. + const sr = waveMake(H, note, 'StyleRegion', 20, 290, { name:'tc_sr', w:600, h:90 }); + if(sr){ + if(mode === 'values') sr.styleFramePadding = [8, 5]; + const inp = waveMake(H, note, 'InputTextWithHint', 40, 326, { name:'tc_sr_in', w:300 }); + waveNested(note, inp, sr); + const btn = waveMake(H, note, 'Button', 360, 326, { name:'tc_sr_btn', w:100, h:20, label:'Go' }); + waveNested(note, btn, sr); + } +} +function buildTablesCStyleScene(H, note){ buildTablesCStyle(H, note, 'values'); } +function buildTablesCExplicit(H, note){ buildTablesCStyle(H, note, 'explicit'); } + +const SCENES = [ + { name:'core', build: buildCore }, + { name:'all-types', build: buildAllTypes }, + { name:'themes.slate', build: themeScene('slate') }, + { name:'themes.light', build: themeScene('light') }, + { name:'themes.gate-custom', build: themeScene(GATE_CUSTOM_THEME.id) }, + { name:'project', build: buildProject }, + ...EXAMPLE_FILES.map(f => ({ name:'examples.'+f.replace(/\.json$/,''), build: exampleScene(f) })), + { name:'guards', build: buildGuards }, + // v3 — after every v2 scene (B02 2.1). Names start with `themes.`, so `--scene themes` + // selects them with the others. + { name:'themes.gate-alpha', build: customThemeScene(GATE_ALPHA_THEME) }, + { name:'themes.gate-alpha-opaque', build: customThemeScene(GATE_ALPHA_OPAQUE_THEME) }, + // v4 — after every v3 scene (B03 3.1). `--scene wave-a` selects both. + { name:'wave-a', build: buildWaveA }, + { name:'wave-a.explicit-defaults', build: buildWaveAExplicit }, + // v5 — after every v4 scene (ADR-005 X1.0). + { name:'text-metrics', build: buildTextMetrics }, + // v6 — after every v5 scene (B05 5.1). `--scene wave-b` selects both. + { name:'wave-b', build: buildWaveB }, + { name:'wave-b.explicit-defaults', build: buildWaveBExplicit }, + // v7 — after every v6 scene (B06 6.1). `--scene tables-b` selects both. + { name:'tables-b', build: buildTablesB_ }, + { name:'tables-b.explicit-defaults', build: buildTablesBExplicit }, + // v8 — after every v7 scene (B07 7.1). `--scene menus` selects all three. + { name:'menus', build: buildMenusScene(MENUS_WITH_INVALID) }, + { name:'menus.themed', build: buildMenusScene(MENUS_WITH_INVALID, 'slate') }, + { name:'menus.explicit-defaults', build: buildMenusScene(menusExplicitDefaults(MENUS_FIXTURE)) }, + // v9 — after every v8 scene (B07 7.3, ADR-007 M11). `--scene themes` picks up the two + // themes.* scenes by prefix; `--scene menus` picks up the third. + { name:'themes.slate-title', build: buildSlateTitleScene(true) }, + { name:'themes.slate-title.explicit-default', build: buildSlateTitleScene(false) }, + { name:'menus.themed-title', build: buildMenusThemedTitleScene() }, + // v10 — after every v9 scene (B11) + { name:'arcs', build: buildArcs }, + // v11 — after every v10 scene (A01, ADR-009 AD11). `--scene adaptive` selects all ten. + { name:'adaptive.base', build: adaptiveScene('A', null, null) }, + { name:'adaptive.inert', build: adaptiveScene('A', 'move+stretch', null) }, + { name:'adaptive.move', build: adaptiveScene('A', 'move', {}) }, + { name:'adaptive.move.explicit-defaults', build: adaptiveScene('A', 'move+explicit', {minW:640, minH:440, maxW:0, maxH:0}) }, + { name:'adaptive.limits', build: adaptiveScene('A', 'move', {minW:520, minH:380, maxW:1200, maxH:900}) }, + { name:'adaptive.stretch', build: adaptiveScene('A', 'move+stretch', {}) }, + { name:'adaptive.nested', build: buildAdaptiveNested }, + { name:'adaptive.primitives', build: buildAdaptivePrimitives }, + { name:'adaptive.menus', build: buildAdaptiveMenus }, + { name:'adaptive.invalid', build: buildAdaptiveInvalid }, + // v12 — after every v11 scene (A07.1). `--scene tables-c` selects all three. + { name:'tables-c.stretch', build: buildTablesCStretch }, + { name:'tables-c.style', build: buildTablesCStyleScene }, + { name:'tables-c.explicit-defaults', build: buildTablesCExplicit }, +]; +const G5_SCENE = 'themes.gate-alpha-opaque', G5_REFERENCE = 'themes.gate-custom'; +const G5W_SCENE = 'wave-a.explicit-defaults'; +const G5W2_SCENE = 'wave-b.explicit-defaults'; +const G5T_SCENE = 'tables-b.explicit-defaults'; +const G5M_SCENE = 'menus.explicit-defaults'; +const G5TT_SCENE = 'themes.slate-title.explicit-default'; +const G5AD_REFERENCE = 'adaptive.move', G5AD_SCENE = 'adaptive.move.explicit-defaults'; // v11 — G5 adaptive +const ADAPTIVE_INERT_SCENE = 'adaptive.inert', ADAPTIVE_BASE_SCENE = 'adaptive.base'; // v11 — adaptive inert +const G5TC_SCENE = 'tables-c.explicit-defaults'; // v12 — G5 tables-c +const CHECKS = [ { name:'theme-library-separation', run: runLibrarySeparation } ]; +// Cross-scene checks: listed by --list, not selectable; each runs with its scene. +const CROSS_CHECKS = [ ['G5 alpha-255', G5_SCENE], ['G5 wave-a', G5W_SCENE], ['G5 wave-b', G5W2_SCENE], ['G5 tables-b', G5T_SCENE], ['G5 menus', G5M_SCENE], ['G5 title', G5TT_SCENE], ['G5 adaptive', G5AD_SCENE], ['adaptive inert', ADAPTIVE_INERT_SCENE], ['G5 tables-c', G5TC_SCENE] ]; + +// ============================================================================ +// Running +// ============================================================================ + function normSeed(s){ const map = new Map(); return s.replace(/"(id|[A-Za-z0-9_]*[Ii]d)"\s*:\s*"([^"]*)"/g, (m, key, val) => { @@ -161,46 +1731,886 @@ function normSeed(s){ return '"'+key+'":"'+map.get(val)+'"'; }); } - -const a = process.argv[2], b = process.argv[3]; -if(!a){ console.error('usage: node export_gate.js []'); process.exit(2); } - -if(!b){ - // capture mode - const r = buildFixtureAndExport(a); - const dir = path.join(process.cwd(),'golden'); fs.mkdirSync(dir,{recursive:true}); - const name = path.basename(a).replace(/\.html$/,''); - fs.writeFileSync(path.join(dir,name+'.imgui'), r.imgui); - fs.writeFileSync(path.join(dir,name+'.seed'), r.seed); - console.log('── capture ──'); - console.log('file :', path.basename(a)); - console.log('shapes :', r.shapeCount, '| table cells:', r.cellCount); - console.log('init errors :', r.errs.length?r.errs.join(' | '):'none'); - console.log('determinism :', r.stable?'STABLE':'*** NON-DETERMINISTIC ***'); - console.log('bytes : imgui',Buffer.byteLength(r.imgui),'| seed',Buffer.byteLength(r.seed)); - console.log('written :', 'golden/'+name+'.{imgui,seed}'); - process.exit(r.stable && r.errs.length===0 ? 0 : 1); -} - -// compare mode -const A = buildFixtureAndExport(a), B = buildFixtureAndExport(b); -function diffOne(label, x, y, norm){ - const xn = norm?norm(x):x, yn = norm?norm(y):y; - if(xn===yn){ console.log(' '+label.padEnd(6)+': IDENTICAL'); return true; } - console.log(' '+label.padEnd(6)+': DIFF'); - const xl=xn.split('\n'), yl=yn.split('\n'); let shown=0; - for(let i=0;i { if(!res.notes.includes(t)) res.notes.push(t); }; + const build = () => { + H.reset(); + H.pinProblems().forEach(p => note('reset could not pin '+p)); + scene.build(H, note); + }; + build(); + const i1 = H.genImGui(), s1 = H.genSeed(); + const i1b = H.genImGui(), s1b = H.genSeed(); + const f1 = H.saveText(); // v11: the file channel + if(i1!==i1b || s1!==s1b){ res.stable=false; res.problems.push('NON-DETERMINISTIC '+scene.name+' (same state generated twice differs)'); } + build(); + const i2 = H.genImGui(), s2 = H.genSeed(); + if(i1!==i2 || normSeed(s1)!==normSeed(s2)){ res.stable=false; res.problems.push('NON-DETERMINISTIC '+scene.name+' (rebuild after reset differs — reset() leaks state?)'); } + const f2 = H.saveText(); + if(normSeed(f1)!==normSeed(f2)){ res.stable=false; res.problems.push('NON-DETERMINISTIC '+scene.name+' (rebuild after reset differs (file) — reset() leaks state?)'); } + res.imgui = i1; res.seed = s1; res.file = f1; + // G3 round-trip: Save -> fresh reset -> Load -> genImGui == pre-round-trip export. + const saved = H.saveText(); + H.reset(); + const loaded = H.loadText(saved); + if(!loaded.ok){ + res.rt = { ok:false, reason:'loader rejected the saved project'+(loaded.reason?': '+loaded.reason.replace(/\s+/g,' ').trim():'') }; + } else { + const post = H.genImGui(); + if(post===i2) res.rt = { ok:true }; + else { + const d = multisetDiff(i2.split('\n'), post.split('\n')); + res.rt = { ok:false, reason:'export differs after reload (+'+d.added.length+' −'+d.removed.length+')', diff:d }; + } + } + if(errs.length) res.problems.push('window errors in '+scene.name+': '+errs.join(' | ')); + } catch(e){ + if(e instanceof HarnessError) throw e; + res.error = 'THROW '+scene.name+': '+(e&&e.stack||e); + } finally { + if(tool) closeWindow(tool.window); + } + return res; +} + +function runDefaults(htmlPath){ + const tool = loadTool(htmlPath); + try { + const d = tool.H.defaults(); + return ['cw','ch','themeId','bgMode','projectTitle'].map(k => k+'='+JSON.stringify(d[k])).join(' '); + } finally { closeWindow(tool.window); } +} + +// v3 — ADR-003 F7 probe. Returns { ok, lines:[...], store: } or +// { error } on a throw. `lines` are what gets printed under the verdict and written to +// the capture file; they say exactly what the store held. +function hexLiteral(hex){ return '0x'+hex.slice(1).toUpperCase()+'FF'; } +function countPushes(imgui, colors){ + return THEME_PUSH_SLOTS.filter(([slot,key]) => + imgui.includes('reaper.ImGui_Col_'+slot+'(), '+hexLiteral(colors[key])+')')).length; +} +function sameColors(a, b){ + const ka = Object.keys(a||{}).sort(), kb = Object.keys(b||{}).sort(); + return ka.length===kb.length && ka.every((k,i)=>k===kb[i] && String(a[k]).toLowerCase()===String(b[k]).toLowerCase()); +} +function runLibrarySeparation(htmlPath){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const clone = o => JSON.parse(JSON.stringify(o)); + // The project file, made by the tool's own Save path: a Button under themeDef lib-x (B). + H.reset(); + if(H.adoptProjectTheme(clone(LIB_X_B))!=='lib-x') throw new Error('adoptProjectTheme refused LIB_X_B'); + H.set('themeId', 'lib-x'); + H.create('Button', 40, 40); + const projectText = H.saveText(); + // The probe proper, on an empty session and an empty library. + H.reset(); + H.themeStoreClear(); + if(H.registerTheme(clone(LIB_X_A), true)!=='lib-x') throw new Error('registerCustomTheme refused LIB_X_A'); + const loaded = H.loadText(projectText); + if(!loaded.ok) throw new Error('loader rejected the probe project'+(loaded.reason?': '+loaded.reason:'')); + if(H.registerTheme(clone(LIB_Y), true)!=='lib-y') throw new Error('registerCustomTheme refused LIB_Y'); + const raw = H.themeStoreRead(); + const imgui = H.genImGui(); + const lines = []; + let stored = null, storeProblem = null; + try { + const arr = raw==null ? null : JSON.parse(raw); + if(!Array.isArray(arr)) storeProblem = raw==null ? 'store empty (key absent)' : 'store is not an array'; + else { + lines.push('store ids : '+JSON.stringify(arr.map(t=>t&&t.id))); + stored = arr.find(t=>t&&t.id==='lib-x') || null; + if(!stored) storeProblem = 'store has no lib-x'; + } + } catch(e){ storeProblem = 'store is not JSON: '+e.message; } + let holds = 'n/a'; + if(stored){ + holds = sameColors(stored.colors, LIB_X_A.colors) ? 'A (library)' + : sameColors(stored.colors, LIB_X_B.colors) ? 'B (project copy)' : 'neither A nor B'; + lines.push('store lib-x : colours '+holds+' · label '+JSON.stringify(stored.label)); + lines.push('store lib-x colours: '+JSON.stringify(stored.colors)); + } + if(storeProblem) lines.push('store : '+storeProblem); + const nb = countPushes(imgui, LIB_X_B.colors), na = countPushes(imgui, LIB_X_A.colors); + const themeId = H.get('themeId'); + lines.push('export : colours B '+nb+'/'+THEME_PUSH_SLOTS.length+' pushes, colours A '+na+'/'+THEME_PUSH_SLOTS.length + +' · themeId '+JSON.stringify(themeId)); + const ok = holds==='A (library)' && nb===THEME_PUSH_SLOTS.length; + if(!ok){ + const why = []; + if(holds!=='A (library)') why.push('library lib-x '+(stored ? 'now holds colours '+holds : 'not readable ('+storeProblem+')')); + if(nb!==THEME_PUSH_SLOTS.length) why.push('project exports '+nb+'/'+THEME_PUSH_SLOTS.length+' colour-B pushes'); + lines.push('reason : '+why.join('; ')); + } + return { ok, lines, store: raw }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW theme-library-separation: '+(e&&e.stack||e) }; + } finally { + if(tool) closeWindow(tool.window); + } +} + +// v3 — G5 alpha-255: themes.gate-alpha-opaque must export exactly like themes.gate-custom +// in the same build. Takes the build's results; generates the reference scene if it was +// not selected. null when the opaque scene was not selected. +function runG5(htmlPath, results){ + const opaque = results.find(r=>r.name===G5_SCENE); + if(!opaque) return null; + const ref = results.find(r=>r.name===G5_REFERENCE) + || runScene(htmlPath, SCENES.find(s=>s.name===G5_REFERENCE)); + if(opaque.error || ref.error) return { ok:false, reason:'a scene threw (see its line)' }; + if(opaque.imgui===ref.imgui) return { ok:true }; + const diff = multisetDiff(ref.imgui.split('\n'), opaque.imgui.split('\n')); + return { ok:false, reason:G5_SCENE+' vs '+G5_REFERENCE+' (+'+diff.added.length+' −'+diff.removed.length+')', diff }; +} + +// v4 — G5 wave-a. One fresh instance per variant: build, genImGui (part a), then +// Save -> reset -> Load and genSeed (part b). Both variants make the same creates in the +// same order, so their uid draws line up; the seeds are still compared through normSeed. +function probeWaveATreeSel(htmlPath, mode){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const notes = []; + const note = t => { if(!notes.includes(t)) notes.push(t); }; + H.reset(); + buildWaveATreeSel(H, note, mode); + const imgui = H.genImGui(); + const saved = H.saveText(); + H.reset(); + const loaded = H.loadText(saved); + if(!loaded.ok) throw new Error('loader rejected the '+mode+' project'+(loaded.reason?': '+loaded.reason:'')); + return { imgui, seed: H.genSeed(), notes }; + } finally { + if(tool) closeWindow(tool.window); + } +} +// null when wave-a.explicit-defaults was not selected. +function runG5WaveA(htmlPath, results){ + if(!results.some(r=>r.name===G5W_SCENE)) return null; + try { + const abs = probeWaveATreeSel(htmlPath, 'absent'), exp = probeWaveATreeSel(htmlPath, 'explicit'); + const okA = abs.imgui===exp.imgui; + const okB = normSeed(abs.seed)===normSeed(exp.seed); + return { + ok: okA && okB, + a: okA ? { ok:true } : { ok:false, diff: multisetDiff(abs.imgui.split('\n'), exp.imgui.split('\n')) }, + b: okB ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.seed).split('\n'), normSeed(exp.seed).split('\n')) }, + notes: abs.notes.concat(exp.notes.filter(n=>!abs.notes.includes(n))), + }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW G5 wave-a: '+(e&&e.stack||e) }; + } +} + +// v6 — G5 wave-b. Same pattern as probeWaveATreeSel/runG5WaveA (B03 3.1) applied to the +// wave-b TabBar+StyleRegion+Table part (B05 5.1). +function probeWaveBTabSrTable(htmlPath, mode){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const notes = []; + const note = t => { if(!notes.includes(t)) notes.push(t); }; + H.reset(); + buildWaveBTabSrTable(H, note, mode); + const imgui = H.genImGui(); + const saved = H.saveText(); + H.reset(); + const loaded = H.loadText(saved); + if(!loaded.ok) throw new Error('loader rejected the '+mode+' project'+(loaded.reason?': '+loaded.reason:'')); + return { imgui, seed: H.genSeed(), notes }; + } finally { + if(tool) closeWindow(tool.window); + } +} +// null when wave-b.explicit-defaults was not selected. +function runG5WaveB(htmlPath, results){ + if(!results.some(r=>r.name===G5W2_SCENE)) return null; + try { + const abs = probeWaveBTabSrTable(htmlPath, 'absent'), exp = probeWaveBTabSrTable(htmlPath, 'explicit'); + const okA = abs.imgui===exp.imgui; + const okB = normSeed(abs.seed)===normSeed(exp.seed); + return { + ok: okA && okB, + a: okA ? { ok:true } : { ok:false, diff: multisetDiff(abs.imgui.split('\n'), exp.imgui.split('\n')) }, + b: okB ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.seed).split('\n'), normSeed(exp.seed).split('\n')) }, + notes: abs.notes.concat(exp.notes.filter(n=>!abs.notes.includes(n))), + }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW G5 wave-b: '+(e&&e.stack||e) }; + } +} + +// v7 — G5 tables-b. Same pattern as probeWaveBTabSrTable/runG5WaveB (B05 5.1) applied to +// the tables-b six-table part (B06 6.1, ADR-011 G2/G4). +function probeTablesB(htmlPath, mode){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const notes = []; + const note = t => { if(!notes.includes(t)) notes.push(t); }; + H.reset(); + buildTablesB(H, note, mode); + const imgui = H.genImGui(); + const saved = H.saveText(); + H.reset(); + const loaded = H.loadText(saved); + if(!loaded.ok) throw new Error('loader rejected the '+mode+' project'+(loaded.reason?': '+loaded.reason:'')); + return { imgui, seed: H.genSeed(), notes }; + } finally { + if(tool) closeWindow(tool.window); + } +} +// null when tables-b.explicit-defaults was not selected. +function runG5TablesB(htmlPath, results){ + if(!results.some(r=>r.name===G5T_SCENE)) return null; + try { + const abs = probeTablesB(htmlPath, 'absent'), exp = probeTablesB(htmlPath, 'explicit'); + const okA = abs.imgui===exp.imgui; + const okB = normSeed(abs.seed)===normSeed(exp.seed); + return { + ok: okA && okB, + a: okA ? { ok:true } : { ok:false, diff: multisetDiff(abs.imgui.split('\n'), exp.imgui.split('\n')) }, + b: okB ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.seed).split('\n'), normSeed(exp.seed).split('\n')) }, + notes: abs.notes.concat(exp.notes.filter(n=>!abs.notes.includes(n))), + }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW G5 tables-b: '+(e&&e.stack||e) }; + } +} + +// v9 — G5 title (B07 7.3, ADR-007 M11). Same pattern as probeTablesB/runG5TablesB +// (B06 6.1) applied to the slate themed body with `themedTitleBar` absent vs explicit +// false, both loaded through withProjectKeys. +function probeTitle(htmlPath, keys){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const notes = []; + const note = t => { if(!notes.includes(t)) notes.push(t); }; + H.reset(); + H.set('themeId', 'slate'); + buildThemeBody(H); + const r = withProjectKeys(H, keys); + if(r.reason) note('loader: '+r.reason.replace(/\s+/g,' ').trim()); + const imgui = H.genImGui(); + return { imgui, seed: H.genSeed(), notes }; + } finally { + if(tool) closeWindow(tool.window); + } +} +// null when themes.slate-title.explicit-default was not selected. +function runG5Title(htmlPath, results){ + if(!results.some(r=>r.name===G5TT_SCENE)) return null; + try { + const abs = probeTitle(htmlPath, {}), exp = probeTitle(htmlPath, { themedTitleBar:false }); + const okA = abs.imgui===exp.imgui; + const okB = normSeed(abs.seed)===normSeed(exp.seed); + return { + ok: okA && okB, + a: okA ? { ok:true } : { ok:false, diff: multisetDiff(abs.imgui.split('\n'), exp.imgui.split('\n')) }, + b: okB ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.seed).split('\n'), normSeed(exp.seed).split('\n')) }, + notes: abs.notes.concat(exp.notes.filter(n=>!abs.notes.includes(n))), + }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW G5 title: '+(e&&e.stack||e) }; + } +} + +// v8 — G5 menus (B07 7.1). probeMenus builds the menus widgets on a fresh instance, +// loads the given menuBar (undefined = no key at all) through withMenuBar, and returns +// imgui + seed after the same Save -> reset -> Load cycle probeTablesB uses. Three +// parts: (a)/(b) MENUS_FIXTURE (absent-style, i.e. defaults left implicit) vs +// menusExplicitDefaults(MENUS_FIXTURE) — imgui and post-cycle seed must match: a build +// that keeps unknown properties through load would still agree here since both sides +// go through one Save/Load cycle before comparison; (c) an empty menuBar array vs no +// `menuBar` key at all — both channels must agree that an empty bar exports nothing. +function probeMenus(htmlPath, menuBar){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const notes = []; + const note = t => { if(!notes.includes(t)) notes.push(t); }; + H.reset(); + buildMenusWidgets(H, note); + const r = withMenuBar(H, menuBar); + if(r.reason) note('loader: '+r.reason.replace(/\s+/g,' ').trim()); + return { imgui: H.genImGui(), seed: H.genSeed(), notes }; + } finally { + if(tool) closeWindow(tool.window); + } +} +// null when menus.explicit-defaults was not selected. +function runG5Menus(htmlPath, results){ + if(!results.some(r=>r.name===G5M_SCENE)) return null; + try { + const abs = probeMenus(htmlPath, MENUS_FIXTURE), exp = probeMenus(htmlPath, menusExplicitDefaults(MENUS_FIXTURE)); + const empty = probeMenus(htmlPath, []), none = probeMenus(htmlPath, undefined); + const okA = abs.imgui===exp.imgui; + const okB = normSeed(abs.seed)===normSeed(exp.seed); + const okC = empty.imgui===none.imgui && normSeed(empty.seed)===normSeed(none.seed); + return { + ok: okA && okB && okC, + a: okA ? { ok:true } : { ok:false, diff: multisetDiff(abs.imgui.split('\n'), exp.imgui.split('\n')) }, + b: okB ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.seed).split('\n'), normSeed(exp.seed).split('\n')) }, + c: okC ? { ok:true } : { ok:false, diff: multisetDiff( + empty.imgui.split('\n').concat(normSeed(empty.seed).split('\n')), + none.imgui.split('\n').concat(normSeed(none.seed).split('\n'))) }, + notes: abs.notes.concat(exp.notes, empty.notes, none.notes) + .filter((n,i,arr)=>arr.indexOf(n)===i), + }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW G5 menus: '+(e&&e.stack||e) }; + } +} + +// v11 — G5 adaptive and adaptive inert (A01, ADR-009 AD11). +// probeAdaptiveScene builds a named scene in a fresh instance and returns its genImGui() +// (before any cycle), then the genSeed() and the saved file after one Save -> reset -> Load +// cycle. +function probeAdaptiveScene(htmlPath, sceneName){ + const scene = SCENES.find(s => s.name === sceneName); + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const notes = []; + const note = t => { if(!notes.includes(t)) notes.push(t); }; + H.reset(); + H.pinProblems().forEach(p => note('reset could not pin '+p)); + scene.build(H, note); + const imgui = H.genImGui(); + const saved = H.saveText(); + H.reset(); + const r = H.loadText(saved); + if(!r.ok) throw new Error('applyLoadedProject rejected the saved project'+(r.reason?': '+r.reason:'')); + return { imgui, seed: H.genSeed(), file: H.saveText(), notes }; + } finally { + if(tool) closeWindow(tool.window); + } +} +// Support probe: does a build keep `windowResize` through Save -> Load? (Fresh instance.) +function adaptiveSupported(htmlPath){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + H.reset(); + withAdaptive(H, {}, { windowResize:{} }, () => {}); + return Object.prototype.hasOwnProperty.call(JSON.parse(H.saveText()), 'windowResize'); + } finally { + if(tool) closeWindow(tool.window); + } +} +// null when adaptive.move.explicit-defaults was not selected; { ok:true, na:true } on a build +// without adaptive support. +function runG5Adaptive(htmlPath, results){ + if(!results.some(r=>r.name===G5AD_SCENE)) return null; + try { + if(!adaptiveSupported(htmlPath)) return { ok:true, na:true }; + const abs = probeAdaptiveScene(htmlPath, G5AD_REFERENCE), exp = probeAdaptiveScene(htmlPath, G5AD_SCENE); + const okA = abs.imgui===exp.imgui; + const okB = normSeed(abs.seed)===normSeed(exp.seed); + const okC = normSeed(abs.file)===normSeed(exp.file); + return { + ok: okA && okB && okC, + a: okA ? { ok:true } : { ok:false, diff: multisetDiff(abs.imgui.split('\n'), exp.imgui.split('\n')) }, + b: okB ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.seed).split('\n'), normSeed(exp.seed).split('\n')) }, + c: okC ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.file).split('\n'), normSeed(exp.file).split('\n')) }, + notes: abs.notes.concat(exp.notes).filter((n,i,arr)=>arr.indexOf(n)===i), + }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW G5 adaptive: '+(e&&e.stack||e) }; + } +} +// null when adaptive.inert was not selected. No N/A: it must PASS on every build. +function runAdaptiveInert(htmlPath, results){ + if(!results.some(r=>r.name===ADAPTIVE_INERT_SCENE)) return null; + try { + const inert = probeAdaptiveScene(htmlPath, ADAPTIVE_INERT_SCENE), base = probeAdaptiveScene(htmlPath, ADAPTIVE_BASE_SCENE); + if(inert.imgui===base.imgui) return { ok:true }; + return { ok:false, diff: multisetDiff(base.imgui.split('\n'), inert.imgui.split('\n')) }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW adaptive inert: '+(e&&e.stack||e) }; + } +} + +// v12 — G5 tables-c (A07.1). The tables-c.style body built twice in fresh instances, the new +// Table / StyleRegion properties absent vs at their defaults (= tables-c.explicit-defaults). +// Same three parts as G5 adaptive: (a) imgui before any cycle, (b) seed and (c) saved file after +// one Save -> reset -> Load cycle. No N/A: on a build that keeps unknown shape keys (2.0.0) (b) +// and (c) may FAIL, and that is reported, not hidden. +function probeTablesC(htmlPath, mode){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const notes = []; + const note = t => { if(!notes.includes(t)) notes.push(t); }; + H.reset(); + H.pinProblems().forEach(p => note('reset could not pin '+p)); + buildTablesCStyle(H, note, mode); + const imgui = H.genImGui(); + const saved = H.saveText(); + H.reset(); + const r = H.loadText(saved); + if(!r.ok) throw new Error('applyLoadedProject rejected the '+mode+' project'+(r.reason?': '+r.reason:'')); + return { imgui, seed: H.genSeed(), file: H.saveText(), notes }; + } finally { + if(tool) closeWindow(tool.window); + } +} +// null when tables-c.explicit-defaults was not selected. +function runG5TablesC(htmlPath, results){ + if(!results.some(r=>r.name===G5TC_SCENE)) return null; + try { + const abs = probeTablesC(htmlPath, 'absent'), exp = probeTablesC(htmlPath, 'explicit'); + const okA = abs.imgui===exp.imgui; + const okB = normSeed(abs.seed)===normSeed(exp.seed); + const okC = normSeed(abs.file)===normSeed(exp.file); + return { + ok: okA && okB && okC, + a: okA ? { ok:true } : { ok:false, diff: multisetDiff(abs.imgui.split('\n'), exp.imgui.split('\n')) }, + b: okB ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.seed).split('\n'), normSeed(exp.seed).split('\n')) }, + c: okC ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.file).split('\n'), normSeed(exp.file).split('\n')) }, + notes: abs.notes.concat(exp.notes).filter((n,i,arr)=>arr.indexOf(n)===i), + }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW G5 tables-c: '+(e&&e.stack||e) }; + } +} + +// Multiset line diff (G7): lines only in A (removed) and only in B (added), counted +// with multiplicity, in order of first appearance. Insensitive to position, so one +// inserted line does not cascade. +function multisetDiff(a, b){ + const count = arr => { const m=new Map(); for(const l of arr) m.set(l,(m.get(l)||0)+1); return m; }; + const cb = count(b), ca = count(a); + const removed = [], added = []; + for(const l of a){ if(cb.get(l)>0) cb.set(l, cb.get(l)-1); else removed.push(l); } + for(const l of b){ if(ca.get(l)>0) ca.set(l, ca.get(l)-1); else added.push(l); } + return { removed, added }; +} + +// ============================================================================ +// CLI +// ============================================================================ +function usage(msg){ + if(msg) console.error('export_gate: '+msg); + console.error('usage: node export_gate.js [] [--scene ]... [--full] [--list]'); + process.exit(2); +} + +const argv = process.argv.slice(2); +const files = []; const sceneFilter = []; let FULL = false, LIST = false; +for(let i=0;i=argv.length) usage('--scene needs a name'); sceneFilter.push(argv[++i]); } + else if(a==='--full') FULL = true; + else if(a==='--list') LIST = true; + else if(a.startsWith('--')) usage('unknown option '+a); + else files.push(a); +} +if(LIST){ + SCENES.forEach(s=>console.log(s.name)); CHECKS.forEach(c=>console.log(c.name)); + console.log('# cross-scene checks (not selectable; each runs with its scene)'); + CROSS_CHECKS.forEach(([n, s])=>console.log('# '+n+' <- '+s)); + process.exit(0); +} +if(files.length<1 || files.length>2) usage(); +for(const f of files) if(!fs.existsSync(f)) usage('no such file: '+f); + +const selected = sceneFilter.length + ? SCENES.filter(s => sceneFilter.some(f => s.name===f || s.name.startsWith(f+'.'))) + : SCENES; +for(const f of sceneFilter) + if(!SCENES.some(s => s.name===f || s.name.startsWith(f+'.')) && !CHECKS.some(c => c.name===f)) + usage('unknown scene '+f+' (try --list)'); +// Checks run when no filter is given, or when named exactly. +const selectedChecks = sceneFilter.length ? CHECKS.filter(c => sceneFilter.includes(c.name)) : CHECKS; +if(selected.some(s=>s.name.startsWith('examples.')) && !fs.existsSync(FIXTURE_DIR)) + usage('fixtures folder missing: '+FIXTURE_DIR); + +const CAP = 80; +function printLines(sign, lines, indent){ + const shown = FULL ? lines : lines.slice(0, CAP); + for(const l of shown) console.log(indent+sign+' '+l); + if(shown.length p.ok ? 'IDENTICAL' : 'DIFFERS (+'+p.diff.added.length+' −'+p.diff.removed.length+')'; + console.log(pre+'G5 wave-a '+(g.ok?'PASS':'FAIL')+' (absent vs explicit defaults: (a) imgui '+part(g.a) + +' · (b) seed after save→load '+part(g.b)+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + g.notes.forEach(n => console.log(' '+(gated?'':'before ')+'note: '+n)); + if(!g.ok && !sameAsGated){ + if(!g.a.ok){ console.log(' (a) imgui:'); printDiff(g.a.diff, ' '); } + if(!g.b.ok){ console.log(' (b) seed:'); printDiff(g.b.diff, ' '); } + } else if(!g.ok) console.log(' before: same result as the after build'); + if(gated && !g.ok) raise(3); +} +function sameG5WaveA(x, y){ + if(!x || !y || x.error || y.error) return false; + const k = g => JSON.stringify([g.ok, g.a, g.b]); + return k(x)===k(y); +} +// v6 — G5 wave-b reporting. Same shape as printG5WaveA/sameG5WaveA (B03 3.1). +function printG5WaveB(g, gated, sameAsGated){ + if(!g) return; + const pre = gated ? '' : ' before: '; + if(g.error){ console.log(pre+'G5 wave-b THROW'); console.log(' '+g.error.split('\n').join('\n ')); raise(3); return; } + const part = p => p.ok ? 'IDENTICAL' : 'DIFFERS (+'+p.diff.added.length+' −'+p.diff.removed.length+')'; + console.log(pre+'G5 wave-b '+(g.ok?'PASS':'FAIL')+' (absent vs explicit defaults: (a) imgui '+part(g.a) + +' · (b) seed after save→load '+part(g.b)+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + g.notes.forEach(n => console.log(' '+(gated?'':'before ')+'note: '+n)); + if(!g.ok && !sameAsGated){ + if(!g.a.ok){ console.log(' (a) imgui:'); printDiff(g.a.diff, ' '); } + if(!g.b.ok){ console.log(' (b) seed:'); printDiff(g.b.diff, ' '); } + } else if(!g.ok) console.log(' before: same result as the after build'); + if(gated && !g.ok) raise(3); +} +function sameG5WaveB(x, y){ + if(!x || !y || x.error || y.error) return false; + const k = g => JSON.stringify([g.ok, g.a, g.b]); + return k(x)===k(y); +} +// v7 — G5 tables-b reporting. Same shape as printG5WaveB/sameG5WaveB (B05 5.1). +function printG5TablesB(g, gated, sameAsGated){ + if(!g) return; + const pre = gated ? '' : ' before: '; + if(g.error){ console.log(pre+'G5 tables-b THROW'); console.log(' '+g.error.split('\n').join('\n ')); raise(3); return; } + const part = p => p.ok ? 'IDENTICAL' : 'DIFFERS (+'+p.diff.added.length+' −'+p.diff.removed.length+')'; + console.log(pre+'G5 tables-b '+(g.ok?'PASS':'FAIL')+' (absent vs explicit defaults: (a) imgui '+part(g.a) + +' · (b) seed after save→load '+part(g.b)+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + g.notes.forEach(n => console.log(' '+(gated?'':'before ')+'note: '+n)); + if(!g.ok && !sameAsGated){ + if(!g.a.ok){ console.log(' (a) imgui:'); printDiff(g.a.diff, ' '); } + if(!g.b.ok){ console.log(' (b) seed:'); printDiff(g.b.diff, ' '); } + } else if(!g.ok) console.log(' before: same result as the after build'); + if(gated && !g.ok) raise(3); +} +function sameG5TablesB(x, y){ + if(!x || !y || x.error || y.error) return false; + const k = g => JSON.stringify([g.ok, g.a, g.b]); + return k(x)===k(y); +} +// v9 — G5 title reporting. Same shape as printG5TablesB/sameG5TablesB (B06 6.1). +function printG5Title(g, gated, sameAsGated){ + if(!g) return; + const pre = gated ? '' : ' before: '; + if(g.error){ console.log(pre+'G5 title THROW'); console.log(' '+g.error.split('\n').join('\n ')); raise(3); return; } + const part = p => p.ok ? 'IDENTICAL' : 'DIFFERS (+'+p.diff.added.length+' −'+p.diff.removed.length+')'; + console.log(pre+'G5 title '+(g.ok?'PASS':'FAIL')+' (absent vs explicit false: (a) imgui '+part(g.a) + +' · (b) seed after save→load '+part(g.b)+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + g.notes.forEach(n => console.log(' '+(gated?'':'before ')+'note: '+n)); + if(!g.ok && !sameAsGated){ + if(!g.a.ok){ console.log(' (a) imgui:'); printDiff(g.a.diff, ' '); } + if(!g.b.ok){ console.log(' (b) seed:'); printDiff(g.b.diff, ' '); } + } else if(!g.ok) console.log(' before: same result as the after build'); + if(gated && !g.ok) raise(3); +} +function sameG5Title(x, y){ + if(!x || !y || x.error || y.error) return false; + const k = g => JSON.stringify([g.ok, g.a, g.b]); + return k(x)===k(y); +} +// v8 — G5 menus reporting. Same shape as printG5TablesB/sameG5TablesB (B06 6.1), with a +// third part: (c) an empty menuBar array vs no key at all. +function printG5Menus(g, gated, sameAsGated){ + if(!g) return; + const pre = gated ? '' : ' before: '; + if(g.error){ console.log(pre+'G5 menus THROW'); console.log(' '+g.error.split('\n').join('\n ')); raise(3); return; } + const part = p => p.ok ? 'IDENTICAL' : 'DIFFERS (+'+p.diff.added.length+' −'+p.diff.removed.length+')'; + console.log(pre+'G5 menus '+(g.ok?'PASS':'FAIL')+' (absent vs explicit defaults: (a) imgui '+part(g.a) + +' · (b) seed after save→load '+part(g.b)+' · (c) empty bar vs none '+part(g.c)+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + g.notes.forEach(n => console.log(' '+(gated?'':'before ')+'note: '+n)); + if(!g.ok && !sameAsGated){ + if(!g.a.ok){ console.log(' (a) imgui:'); printDiff(g.a.diff, ' '); } + if(!g.b.ok){ console.log(' (b) seed:'); printDiff(g.b.diff, ' '); } + if(!g.c.ok){ console.log(' (c) empty vs none:'); printDiff(g.c.diff, ' '); } + } else if(!g.ok) console.log(' before: same result as the after build'); + if(gated && !g.ok) raise(3); +} +function sameG5Menus(x, y){ + if(!x || !y || x.error || y.error) return false; + const k = g => JSON.stringify([g.ok, g.a, g.b, g.c]); + return k(x)===k(y); +} +// v11 — G5 adaptive reporting. Same shape as printG5Menus/sameG5Menus (B07 7.1), with part +// (c) the saved file after save→load, and an N/A for a build without adaptive support (no +// failure, no exit change). +function printG5Adaptive(g, gated, sameAsGated){ + if(!g) return; + const pre = gated ? '' : ' before: '; + if(g.error){ console.log(pre+'G5 adaptive THROW'); console.log(' '+g.error.split('\n').join('\n ')); raise(3); return; } + if(g.na){ console.log(pre+'G5 adaptive N/A (build has no adaptive support: windowResize dropped on load)'); return; } + const part = p => p.ok ? 'IDENTICAL' : 'DIFFERS (+'+p.diff.added.length+' −'+p.diff.removed.length+')'; + console.log(pre+'G5 adaptive '+(g.ok?'PASS':'FAIL')+' (absent vs explicit defaults: (a) imgui '+part(g.a) + +' · (b) seed after save→load '+part(g.b)+' · (c) file after save→load '+part(g.c)+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + g.notes.forEach(n => console.log(' '+(gated?'':'before ')+'note: '+n)); + if(!g.ok && !sameAsGated){ + if(!g.a.ok){ console.log(' (a) imgui:'); printDiff(g.a.diff, ' '); } + if(!g.b.ok){ console.log(' (b) seed:'); printDiff(g.b.diff, ' '); } + if(!g.c.ok){ console.log(' (c) file:'); printDiff(g.c.diff, ' '); } + } else if(!g.ok) console.log(' before: same result as the after build'); + if(gated && !g.ok) raise(3); +} +function sameG5Adaptive(x, y){ + if(!x || !y || x.error || y.error || x.na || y.na) return false; + const k = g => JSON.stringify([g.ok, g.a, g.b, g.c]); + return k(x)===k(y); +} +// v11 — adaptive inert reporting: adaptive.inert's imgui must equal adaptive.base's. +function printAdaptiveInert(g, gated){ + if(!g) return; + const pre = gated ? '' : ' before: '; + if(g.error){ console.log(pre+'adaptive inert THROW'); console.log(' '+g.error.split('\n').join('\n ')); raise(3); return; } + console.log(pre+'adaptive inert '+(g.ok?'PASS':'FAIL')+' (imgui of '+ADAPTIVE_INERT_SCENE+' vs '+ADAPTIVE_BASE_SCENE+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + if(!g.ok){ + console.log(' imgui (− '+ADAPTIVE_BASE_SCENE+', + '+ADAPTIVE_INERT_SCENE+'):'); + printDiff(g.diff, ' '); + if(gated) raise(3); + } +} +// v12 — G5 tables-c reporting. Same shape as printG5Adaptive/sameG5Adaptive (A01), no N/A. +function printG5TablesC(g, gated, sameAsGated){ + if(!g) return; + const pre = gated ? '' : ' before: '; + if(g.error){ console.log(pre+'G5 tables-c THROW'); console.log(' '+g.error.split('\n').join('\n ')); raise(3); return; } + const part = p => p.ok ? 'IDENTICAL' : 'DIFFERS (+'+p.diff.added.length+' −'+p.diff.removed.length+')'; + console.log(pre+'G5 tables-c '+(g.ok?'PASS':'FAIL')+' (absent vs explicit defaults: (a) imgui '+part(g.a) + +' · (b) seed after save→load '+part(g.b)+' · (c) file after save→load '+part(g.c)+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + g.notes.forEach(n => console.log(' '+(gated?'':'before ')+'note: '+n)); + if(!g.ok && !sameAsGated){ + if(!g.a.ok){ console.log(' (a) imgui:'); printDiff(g.a.diff, ' '); } + if(!g.b.ok){ console.log(' (b) seed:'); printDiff(g.b.diff, ' '); } + if(!g.c.ok){ console.log(' (c) file:'); printDiff(g.c.diff, ' '); } + } else if(!g.ok) console.log(' before: same result as the after build'); + if(gated && !g.ok) raise(3); +} +function sameG5TablesC(x, y){ + if(!x || !y || x.error || y.error) return false; + const k = g => JSON.stringify([g.ok, g.a, g.b, g.c]); + return k(x)===k(y); +} +function checkText(c){ return c.error ? 'THROW' : (c.ok ? 'PASS' : 'FAIL'); } +function checkFileText(name, c){ + if(c.error) return name+' THROW\n'+c.error+'\n'; + return name+' '+checkText(c)+'\n'+c.lines.join('\n')+'\nraw store:\n'+(c.store==null?'(absent)':c.store)+'\n'; +} + +let exitCode = 0; +const raise = c => { if(c>exitCode) exitCode = c; }; + +try { + if(files.length===1){ + // ── capture ── + const a = files[0]; + const stem = path.basename(a).replace(/\.html?$/i,''); + const dir = path.join(process.cwd(),'golden',stem); + fs.mkdirSync(dir,{recursive:true}); + const defs = runDefaults(a); + fs.writeFileSync(path.join(dir,'defaults.txt'), defs+'\n'); + console.log('── export gate v12 · capture ──'); + console.log('file : '+path.basename(a)); + console.log('goldens : golden/'+stem+'/.{imgui,seed,file}'); + console.log('defaults : '+defs); + const R = runAll(a); + for(const r of R){ + if(r.error){ console.log(r.name.padEnd(36)+' THROW'); console.log(' '+r.error.split('\n').join('\n ')); raise(3); continue; } + fs.writeFileSync(path.join(dir,r.name+'.imgui'), r.imgui); + fs.writeFileSync(path.join(dir,r.name+'.seed'), r.seed); + fs.writeFileSync(path.join(dir,r.name+'.file'), r.file); + console.log(r.name.padEnd(36)+' '+(r.stable?'STABLE':'NON-DETERMINISTIC') + +' · roundtrip '+rtText(r.rt) + +' · bytes imgui '+Buffer.byteLength(r.imgui)+' seed '+Buffer.byteLength(r.seed)+' file '+Buffer.byteLength(r.file)); + r.notes.forEach(n => console.log(' note: '+n)); + r.problems.forEach(p => { console.log(' '+p); raise(3); }); + if(r.rt && !r.rt.ok){ + console.log(' ROUNDTRIP MISMATCH '+r.name+' — '+r.rt.reason); + if(r.rt.diff) printDiff(r.rt.diff, ' '); + raise(3); + } + } + printG5(runG5(a, R), true); + printG5WaveA(runG5WaveA(a, R), true, false); + printG5WaveB(runG5WaveB(a, R), true, false); + printG5TablesB(runG5TablesB(a, R), true, false); + printG5Menus(runG5Menus(a, R), true, false); + printG5Title(runG5Title(a, R), true, false); + printG5Adaptive(runG5Adaptive(a, R), true, false); + printAdaptiveInert(runAdaptiveInert(a, R), true); + printG5TablesC(runG5TablesC(a, R), true, false); + for(const ck of selectedChecks){ + const c = ck.run(a); + fs.writeFileSync(path.join(dir, ck.name+'.txt'), checkFileText(ck.name, c)); + console.log(ck.name.padEnd(36)+' '+checkText(c)); + if(c.error){ console.log(' '+c.error.split('\n').join('\n ')); raise(3); continue; } + c.lines.forEach(l => console.log(' '+l)); + if(!c.ok) raise(3); + } + } else { + // ── compare ── + const [a, b] = files; + console.log('── export gate v12 · compare ──'); + console.log('before: '+path.basename(a)+' | after: '+path.basename(b)); + const da = runDefaults(a), db = runDefaults(b); + if(da===db) console.log('defaults'.padEnd(36)+' IDENTICAL ('+da+')'); + else { + console.log('defaults'.padEnd(36)+' CHANGED'); + console.log(' before: '+da); console.log(' after : '+db); + raise(1); + } + const A = runAll(a), B = runAll(b); + for(let i=0;i same ? 'IDENTICAL' + : (d.added.length||d.removed.length ? 'CHANGED +'+d.added.length+' −'+d.removed.length + : 'CHANGED (order only)'); + console.log(x.name.padEnd(36)+' imgui '+verdict(sameI,ci)+' · seed '+verdict(sameS,cs)+' · file '+verdict(sameF,cf) + +' · roundtrip '+rtText(x.rt)+'/'+rtText(y.rt) + +' · '+(x.stable&&y.stable?'STABLE':'NON-DETERMINISTIC')); + const notesA = x.notes.join('\n'), notesB = y.notes.join('\n'); + if(notesA===notesB) x.notes.forEach(n => console.log(' note: '+n)); + else { x.notes.forEach(n => console.log(' note (before): '+n)); y.notes.forEach(n => console.log(' note (after) : '+n)); } + if(!sameI){ console.log(' imgui:'); printDiff(ci, ' '); raise(1); } + if(!sameS){ console.log(' seed:'); printDiff(cs, ' '); raise(1); } + if(!sameF){ console.log(' file:'); printDiff(cf, ' '); raise(1); } + x.problems.forEach(p => { console.log(' before: '+p); raise(3); }); + y.problems.forEach(p => { console.log(' after : '+p); raise(3); }); + if(x.rt && !x.rt.ok) console.log(' before: ROUNDTRIP MISMATCH '+x.name+' — '+x.rt.reason+' (pre-existing in the before build; not gated)'); + if(y.rt && !y.rt.ok){ + console.log(' ROUNDTRIP MISMATCH '+y.name+' — '+y.rt.reason); + if(y.rt.diff) printDiff(y.rt.diff, ' '); + raise(3); + } + } + // v3 — G5 on the build under test (after); a before-build mismatch is pre-existing. + const g5a = runG5(a, A), g5b = runG5(b, B); + printG5(g5b, true); + if(g5a && !g5a.ok) printG5(g5a, false); + // v4 — G5 wave-a on the build under test; a before-build FAIL is pre-existing. + const gwa = runG5WaveA(a, A), gwb = runG5WaveA(b, B); + printG5WaveA(gwb, true, false); + if(gwa && (gwa.error || !gwa.ok)) printG5WaveA(gwa, false, sameG5WaveA(gwa, gwb)); + // v6 — G5 wave-b on the build under test; a before-build FAIL is pre-existing. + const gwa2 = runG5WaveB(a, A), gwb2 = runG5WaveB(b, B); + printG5WaveB(gwb2, true, false); + if(gwa2 && (gwa2.error || !gwa2.ok)) printG5WaveB(gwa2, false, sameG5WaveB(gwa2, gwb2)); + // v7 — G5 tables-b on the build under test; a before-build FAIL is pre-existing. + const gwa3 = runG5TablesB(a, A), gwb3 = runG5TablesB(b, B); + printG5TablesB(gwb3, true, false); + if(gwa3 && (gwa3.error || !gwa3.ok)) printG5TablesB(gwa3, false, sameG5TablesB(gwa3, gwb3)); + // v8 — G5 menus on the build under test; a before-build FAIL is pre-existing. + const gwa4 = runG5Menus(a, A), gwb4 = runG5Menus(b, B); + printG5Menus(gwb4, true, false); + if(gwa4 && (gwa4.error || !gwa4.ok)) printG5Menus(gwa4, false, sameG5Menus(gwa4, gwb4)); + // v9 — G5 title on the build under test; a before-build FAIL is pre-existing. + const gwa5 = runG5Title(a, A), gwb5 = runG5Title(b, B); + printG5Title(gwb5, true, false); + if(gwa5 && (gwa5.error || !gwa5.ok)) printG5Title(gwa5, false, sameG5Title(gwa5, gwb5)); + // v11 — G5 adaptive and adaptive inert on the build under test; a before-build FAIL is + // pre-existing. A before-build N/A is shown only when the after build supports adaptive. + const gad1 = runG5Adaptive(a, A), gad2 = runG5Adaptive(b, B); + printG5Adaptive(gad2, true, false); + if(gad1 && (gad1.error || !gad1.ok)) printG5Adaptive(gad1, false, sameG5Adaptive(gad1, gad2)); + else if(gad1 && gad1.na && gad2 && !gad2.na) printG5Adaptive(gad1, false, false); + const gin1 = runAdaptiveInert(a, A), gin2 = runAdaptiveInert(b, B); + printAdaptiveInert(gin2, true); + if(gin1 && (gin1.error || !gin1.ok)) printAdaptiveInert(gin1, false); + // v12 — G5 tables-c on the build under test; a before-build FAIL is pre-existing. + const gtc1 = runG5TablesC(a, A), gtc2 = runG5TablesC(b, B); + printG5TablesC(gtc2, true, false); + if(gtc1 && (gtc1.error || !gtc1.ok)) printG5TablesC(gtc1, false, sameG5TablesC(gtc1, gtc2)); + for(const ck of selectedChecks){ + const ca = ck.run(a), cb = ck.run(b); + console.log(ck.name.padEnd(36)+' '+checkText(ca)+'/'+checkText(cb)); + if(cb.error){ console.log(' after : '+cb.error.split('\n').join('\n ')); raise(3); } + else { cb.lines.forEach(l => console.log(' after : '+l)); if(!cb.ok) raise(3); } + if(ca.error){ console.log(' before: '+ca.error.split('\n').join('\n ')); raise(3); } + else if(!ca.ok){ + const same = !cb.error && ca.lines.join('\n')===cb.lines.join('\n'); + if(same) console.log(' before: same result (pre-existing in the before build; not gated)'); + else { ca.lines.forEach(l => console.log(' before: '+l)); console.log(' before: FAIL is pre-existing in the before build; not gated'); } + } + } + console.log('result: '+(exitCode===0 ? 'CLEAN — every scene identical on both channels' + : exitCode===1 ? 'CHANGED — review the multisets: only intended lines may differ' + : 'FAIL — round-trip mismatch, throw, non-determinism, a G5 mismatch (alpha-255 / wave-a / wave-b / tables-b / menus / title / adaptive / tables-c), adaptive inert or a failed check (exit 3)')); + } +} catch(e){ + if(e instanceof HarnessError){ console.error(e.message); process.exit(3); } + throw e; +} +process.exit(exitCode); diff --git a/tools/export-gate/export_gate_README.md b/tools/export-gate/export_gate_README.md index 7d6363f..97c5b65 100644 --- a/tools/export-gate/export_gate_README.md +++ b/tools/export-gate/export_gate_README.md @@ -1,49 +1,25 @@ -# export_gate.js — standing export-gate harness +# Export Gate v13 -Headless regression check for the REAPER UI Layout Editor. Proves that a patch does **not** -change the exported `genImGui` / `genSeed` output of widgets it shouldn't affect. -It loads the single-file HTML under jsdom and builds a fixed fixture (bare widget, widget in a -Group, widget in a Tab, and a widget in a Table cell) by driving the tool's own creation -functions — no edits to the tool are needed. +Headless regression harness for ReaUI Builder (Node.js + jsdom). The test constructs UI scenes through the editor's own creation/export functions; it compares generated ReaImGui Lua, JSON project serialization, deterministic regeneration, and Save → Reset → Load output. -`genLua` does not exist in the tool and never has an export to check here — `genImGui` is the -Lua/ReaImGui code generator. An earlier revision of this gate also captured a `genLua` artefact; -it was removed once `genLua` was removed from the tool, and the gate has emitted only `imgui` -and `seed` ever since. +The original v12 is retained at [historical/export_gate_v12.js](historical/export_gate_v12.js). v13 refreshes Table-cell geometry after setting Table properties in the `tables-b` fixture, before creating its nested Button. This corrects the test setup; it does **not** change ReaUI Builder. -## One-time setup (in this folder) -```bash -npm install jsdom -``` - -## When the gate is required -- **Required** for patches touching export / coordinate / placement logic. -- **Exempt:** CSS-only and selection-only patches. +## Run -## Usage +From the repository root: -Capture a baseline for the current build: ```bash -node export_gate.js plugin_ui_layout_v3_NNN.html -# → writes golden/plugin_ui_layout_v3_NNN.{imgui,seed}, prints sizes + determinism +cd tools/export-gate +npm install --no-save jsdom@26.1.0 +node export_gate.js ../../ReaUI_Builder.html --scene tables-b +node export_gate.js ../../ReaUI_Builder.html ``` -Gate a patch — run BEFORE vs AFTER and diff the two exports: -```bash -node export_gate.js plugin_ui_layout_v3_OLD.html plugin_ui_layout_v3_NEW.html -``` +The full gate includes the five frozen example projects stored in `fixtures/examples/`. Outputs are written to `golden/` in capture mode. + +- Exit 0: all checks pass. +- Exit 1: export/model output changed in a before/after comparison; inspect the diff. +- Exit 2: configuration, file, or fixture error. +- Exit 3: non-determinism, failed round-trip, cross-scene invariance error, or uncaught error. -## Reading the result -- **CLEAN (exit 0)** — exports byte-identical. This is what a selection-only / CSS patch must - produce, and what a placement patch must produce for every widget it did **not** intend to move. -- **CHANGED (exit 1)** — there is a diff. For a placement/coordinate patch this is expected: - read the diff and confirm **only** the widgets you intended to move/resize changed. Any - unrelated widget changing is a regression — stop and investigate. -- Seed `id` fields are random per run and are normalized before diffing, so a seed diff is real - structure/coordinate change, never just ids. - -## Notes -- The fixture is a fixed regression baseline. If a future patch needs a different scenario - (e.g. a specific saved project), extend `buildFixtureAndExport()` — keep it deterministic. -- A `SCRIPT THROW during init` or `GENERATOR THROW` means the build doesn't load/generate - cleanly — that's a syntax/logic break to fix before judging the diff. +Chromium-adapted v13 verification passed in the release QA environment, but that is not a substitute for the Node/jsdom workflow. Consult [the QA addendum](../../docs/Export_Gate_v13_QA_EN.md). diff --git a/tools/export-gate/fixtures/examples/example_01_batch_rename.json b/tools/export-gate/fixtures/examples/example_01_batch_rename.json new file mode 100644 index 0000000..1cf4f9d --- /dev/null +++ b/tools/export-gate/fixtures/examples/example_01_batch_rename.json @@ -0,0 +1,244 @@ +{ + "version": 1, + "layerOrderVersion": 1, + "tableBoxVersion": 2, + "cw": 520, + "ch": 420, + "bgColor": "#ffffff", + "bgAlpha": 1, + "bgMode": "default", + "themeId": "light", + "themeDef": null, + "auditGridMode": false, + "snapEnabled": true, + "gridStep": 10, + "projectTitle": "Batch Rename", + "cnt": { + "rect": 0, + "circle": 0, + "poly": 0, + "line": 0, + "text": 0, + "triangle": 0, + "arc": 0, + "widget": 16 + }, + "shapes": [ + { + "id": "4z2tjcry", + "type": "widget", + "widgetType": "SeparatorText", + "x": 20, + "y": 20, + "w": 480, + "h": 14, + "parentId": null, + "name": "sec_source", + "label": "Source", + "family": "SeparatorText" + }, + { + "id": "pur4w1w6", + "type": "widget", + "widgetType": "Combo", + "x": 20, + "y": 60, + "w": 220, + "h": 20, + "parentId": null, + "name": "target", + "label": "Apply to", + "family": "Combo" + }, + { + "id": "lqg5jdvd", + "type": "widget", + "widgetType": "Checkbox", + "x": 260, + "y": 60, + "w": 20, + "h": 20, + "parentId": null, + "name": "selected_only", + "label": "", + "family": "Checkbox", + "tooltip": "Selected only" + }, + { + "id": "73tprsrv", + "type": "widget", + "widgetType": "InputInt", + "x": 350, + "y": 60, + "w": 60, + "h": 20, + "parentId": null, + "name": "start_index", + "label": "Start", + "family": "Input", + "variant": "Int", + "min": 1, + "max": 999, + "step": 1 + }, + { + "id": "fd1rd0ax", + "type": "widget", + "widgetType": "HelpMarker", + "x": 480, + "y": 60, + "w": 20, + "h": 20, + "parentId": null, + "name": "help_source", + "label": "", + "family": "HelpMarker", + "tooltip": "Tracks, items, regions or markers — the rename runs on the current selection only when the box is ticked." + }, + { + "id": "x6zba090", + "type": "widget", + "widgetType": "SeparatorText", + "x": 20, + "y": 90, + "w": 480, + "h": 14, + "parentId": null, + "name": "sec_pattern", + "label": "Pattern", + "family": "SeparatorText" + }, + { + "id": "qjuf1871", + "type": "widget", + "widgetType": "InputTextWithHint", + "x": 20, + "y": 130, + "w": 280, + "h": 20, + "parentId": null, + "name": "find", + "label": "Find", + "family": "InputTextWithHint", + "hint": "text or /regex/" + }, + { + "id": "g9ehiyyz", + "type": "widget", + "widgetType": "InputTextWithHint", + "x": 20, + "y": 180, + "w": 280, + "h": 20, + "parentId": null, + "name": "replace", + "label": "Replace", + "family": "InputTextWithHint", + "hint": "$1 - track %n" + }, + { + "id": "bxl1gguv", + "type": "widget", + "widgetType": "Checkbox", + "x": 350, + "y": 130, + "w": 20, + "h": 20, + "parentId": null, + "name": "use_regex", + "label": "Regex", + "family": "Checkbox" + }, + { + "id": "f4ktoox3", + "type": "widget", + "widgetType": "Checkbox", + "x": 350, + "y": 180, + "w": 20, + "h": 20, + "parentId": null, + "name": "match_case", + "label": "Match case", + "family": "Checkbox" + }, + { + "id": "c17s4lny", + "type": "widget", + "widgetType": "SeparatorText", + "x": 20, + "y": 220, + "w": 480, + "h": 14, + "parentId": null, + "name": "sec_preview", + "label": "Preview", + "family": "SeparatorText" + }, + { + "id": "p4hc7sgc", + "type": "widget", + "widgetType": "ListBox", + "x": 20, + "y": 260, + "w": 480, + "h": 110, + "parentId": null, + "name": "preview_list", + "label": "Result", + "family": "ListBox" + }, + { + "id": "y4b12f30", + "type": "widget", + "widgetType": "Button", + "x": 20, + "y": 390, + "w": 110, + "h": 20, + "parentId": null, + "name": "btn_preview", + "label": "Preview", + "family": "Button" + }, + { + "id": "id1y8ewr", + "type": "widget", + "widgetType": "Button", + "x": 140, + "y": 390, + "w": 110, + "h": 20, + "parentId": null, + "name": "btn_apply", + "label": "Apply", + "family": "Button" + }, + { + "id": "pto4oj2a", + "type": "widget", + "widgetType": "Button", + "x": 390, + "y": 390, + "w": 110, + "h": 20, + "parentId": null, + "name": "btn_close", + "label": "Close", + "family": "Button" + }, + { + "id": "70aidwfz", + "type": "widget", + "widgetType": "TextDisabled", + "x": 260, + "y": 390, + "w": 120, + "h": 20, + "parentId": null, + "name": "status", + "label": "no preview yet", + "family": "TextDisabled" + } + ] +} \ No newline at end of file diff --git a/tools/export-gate/fixtures/examples/example_02_item_fade_tool.json b/tools/export-gate/fixtures/examples/example_02_item_fade_tool.json new file mode 100644 index 0000000..499ef2e --- /dev/null +++ b/tools/export-gate/fixtures/examples/example_02_item_fade_tool.json @@ -0,0 +1,295 @@ +{ + "version": 1, + "layerOrderVersion": 1, + "tableBoxVersion": 2, + "cw": 560, + "ch": 410, + "bgColor": "#ffffff", + "bgAlpha": 1, + "bgMode": "default", + "themeId": "light", + "themeDef": null, + "auditGridMode": false, + "snapEnabled": true, + "gridStep": 10, + "projectTitle": "Item Fade Tool", + "cnt": { + "rect": 0, + "circle": 0, + "poly": 0, + "line": 0, + "text": 0, + "triangle": 0, + "arc": 0, + "widget": 18 + }, + "shapes": [ + { + "id": "psmcmo9d", + "type": "widget", + "widgetType": "SeparatorText", + "x": 20, + "y": 10, + "w": 520, + "h": 14, + "parentId": null, + "name": "sec_shape", + "label": "Fade shape", + "family": "SeparatorText" + }, + { + "id": "rzvjhqa5", + "type": "widget", + "widgetType": "Group", + "x": 20, + "y": 40, + "w": 340, + "h": 180, + "parentId": null, + "name": "grp_curve", + "label": "Curve", + "family": "Group", + "isContainer": true + }, + { + "id": "ulv0yea1", + "type": "widget", + "widgetType": "Combo", + "x": 20, + "y": 40, + "w": 200, + "h": 20, + "parentId": "rzvjhqa5", + "name": "curve_shape", + "label": "Shape", + "family": "Combo" + }, + { + "id": "z3qwu3qf", + "type": "widget", + "widgetType": "SliderInt", + "x": 20, + "y": 70, + "w": 200, + "h": 20, + "parentId": "rzvjhqa5", + "name": "tension", + "label": "Tension", + "family": "Slider", + "variant": "Int", + "min": -100, + "max": 100, + "format": "%d%%" + }, + { + "id": "wsz784wn", + "type": "widget", + "widgetType": "SliderDouble", + "x": 20, + "y": 120, + "w": 200, + "h": 20, + "parentId": "rzvjhqa5", + "name": "length", + "label": "Length (s)", + "family": "Slider", + "variant": "Double", + "min": 0, + "max": 5, + "format": "%.2f s" + }, + { + "id": "kyeznmsm", + "type": "widget", + "widgetType": "VSliderDouble", + "x": 390, + "y": 60, + "w": 24, + "h": 150, + "parentId": null, + "name": "gain", + "label": "Gain", + "family": "VSlider", + "variant": "Double", + "min": -60, + "max": 12, + "format": "%.1f dB" + }, + { + "id": "lny796k8", + "type": "widget", + "widgetType": "VSliderDouble", + "x": 430, + "y": 60, + "w": 24, + "h": 150, + "parentId": null, + "name": "wet", + "label": "Wet", + "family": "VSlider", + "variant": "Double", + "min": 0, + "max": 100, + "format": "%.0f%%" + }, + { + "id": "28qutuy9", + "type": "widget", + "widgetType": "ArrowButton", + "x": 480, + "y": 60, + "w": 17, + "h": 17, + "parentId": null, + "name": "nudge_up", + "label": "", + "family": "ArrowButton", + "direction": "Up" + }, + { + "id": "gjo7hikm", + "type": "widget", + "widgetType": "ArrowButton", + "x": 480, + "y": 90, + "w": 17, + "h": 17, + "parentId": null, + "name": "nudge_down", + "label": "", + "family": "ArrowButton", + "direction": "Down" + }, + { + "id": "m3ro6f92", + "type": "widget", + "widgetType": "LabelText", + "x": 470, + "y": 130, + "w": 30, + "h": 20, + "parentId": null, + "name": "nudge_readout", + "label": "Nudge", + "family": "LabelText", + "value": "1 dB" + }, + { + "id": "3wbtb7v0", + "type": "widget", + "widgetType": "CollapsingHeader", + "x": 0, + "y": 240, + "w": 520, + "h": 110, + "parentId": null, + "name": "adv", + "label": "Advanced", + "family": "CollapsingHeader", + "isContainer": true + }, + { + "id": "qk7zkypm", + "type": "widget", + "widgetType": "RadioButtonEx", + "x": 20, + "y": 40, + "w": 71, + "h": 20, + "parentId": "3wbtb7v0", + "name": "mode_in", + "label": "Fade in", + "family": "RadioButtonEx", + "radioGroup": "fade_mode", + "radioValue": 0 + }, + { + "id": "u1wjc7r5", + "type": "widget", + "widgetType": "RadioButtonEx", + "x": 120, + "y": 40, + "w": 79, + "h": 20, + "parentId": "3wbtb7v0", + "name": "mode_out", + "label": "Fade out", + "family": "RadioButtonEx", + "radioGroup": "fade_mode", + "radioValue": 1 + }, + { + "id": "r64tp4dv", + "type": "widget", + "widgetType": "RadioButtonEx", + "x": 230, + "y": 40, + "w": 87, + "h": 20, + "parentId": "3wbtb7v0", + "name": "mode_x", + "label": "Crossfade", + "family": "RadioButtonEx", + "radioGroup": "fade_mode", + "radioValue": 2 + }, + { + "id": "9zh8xc6b", + "type": "widget", + "widgetType": "Checkbox", + "x": 360, + "y": 40, + "w": 20, + "h": 20, + "parentId": "3wbtb7v0", + "name": "keep_length", + "label": "Keep length", + "family": "Checkbox" + }, + { + "id": "sl9qkoek", + "type": "widget", + "widgetType": "DragDouble", + "x": 20, + "y": 80, + "w": 200, + "h": 20, + "parentId": "3wbtb7v0", + "name": "offset", + "label": "Offset (ms)", + "family": "Drag", + "variant": "Double", + "min": -500, + "max": 500, + "speed": 1, + "format": "%.0f ms" + }, + { + "id": "2mlglj3v", + "type": "widget", + "widgetType": "ProgressBar", + "x": 20, + "y": 380, + "w": 400, + "h": 18, + "parentId": null, + "name": "progress", + "label": "Applying", + "family": "ProgressBar", + "overlay": "0 / 0 items" + }, + { + "id": "7v1kpvz2", + "type": "widget", + "widgetType": "Button", + "x": 440, + "y": 380, + "w": 100, + "h": 20, + "parentId": null, + "name": "btn_apply", + "label": "Apply", + "family": "Button" + } + ] +} \ No newline at end of file diff --git a/tools/export-gate/fixtures/examples/example_03_render_loudness.json b/tools/export-gate/fixtures/examples/example_03_render_loudness.json new file mode 100644 index 0000000..00681f7 --- /dev/null +++ b/tools/export-gate/fixtures/examples/example_03_render_loudness.json @@ -0,0 +1,496 @@ +{ + "version": 1, + "layerOrderVersion": 1, + "tableBoxVersion": 2, + "cw": 620, + "ch": 410, + "bgColor": "#ffffff", + "bgAlpha": 1, + "bgMode": "default", + "themeId": "light", + "themeDef": null, + "auditGridMode": false, + "snapEnabled": true, + "gridStep": 10, + "projectTitle": "Render Queue", + "cnt": { + "rect": 0, + "circle": 0, + "poly": 0, + "line": 0, + "text": 0, + "triangle": 0, + "arc": 0, + "widget": 31 + }, + "shapes": [ + { + "id": "vmziudix", + "type": "widget", + "widgetType": "SeparatorText", + "x": 20, + "y": 10, + "w": 580, + "h": 14, + "parentId": null, + "name": "sec_queue", + "label": "Render queue", + "family": "SeparatorText" + }, + { + "id": "ljv9dbi3", + "type": "widget", + "widgetType": "TabBar", + "x": 20, + "y": 40, + "w": 580, + "h": 320, + "parentId": null, + "name": "tabs", + "label": "Sections", + "family": "TabBar", + "isContainer": true, + "activeTabId": "ja23pnxk" + }, + { + "id": "ja23pnxk", + "type": "widget", + "widgetType": "TabItem", + "x": 0, + "y": 24, + "w": 580, + "h": 296, + "parentId": "ljv9dbi3", + "name": "tab_analyze", + "label": "Analyze", + "isContainer": true + }, + { + "id": "ew4prttg", + "type": "widget", + "widgetType": "TabItem", + "x": 0, + "y": 24, + "w": 580, + "h": 296, + "parentId": "ljv9dbi3", + "name": "tab_normalize", + "label": "Normalize", + "isContainer": true + }, + { + "id": "8j96w955", + "type": "widget", + "widgetType": "Table", + "x": 20, + "y": 40, + "w": 540, + "h": 106, + "parentId": "ja23pnxk", + "name": "lufs_table", + "label": "Measurements", + "family": "Table", + "isContainer": true, + "columnCount": 4, + "rowCount": 4, + "columns": [ + "Track", + "LUFS-I", + "LRA", + "True peak" + ], + "headersRow": true, + "tableFlags": { + "Borders": true, + "RowBg": true, + "Resizable": false, + "ScrollY": false + }, + "sizing": "SizingStretchSame" + }, + { + "id": "vqwr5xno", + "type": "widget", + "widgetType": "TableCell", + "x": 0, + "y": 18, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r0c0", + "label": "", + "tableRow": 0, + "tableCol": 0, + "isContainer": true + }, + { + "id": "0stjaox6", + "type": "widget", + "widgetType": "TableCell", + "x": 135, + "y": 18, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r0c1", + "label": "", + "tableRow": 0, + "tableCol": 1, + "isContainer": true + }, + { + "id": "42vbvnm4", + "type": "widget", + "widgetType": "TableCell", + "x": 270, + "y": 18, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r0c2", + "label": "", + "tableRow": 0, + "tableCol": 2, + "isContainer": true + }, + { + "id": "f8vtlz9z", + "type": "widget", + "widgetType": "TableCell", + "x": 0, + "y": 40, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r1c0", + "label": "", + "tableRow": 1, + "tableCol": 0, + "isContainer": true + }, + { + "id": "aqs3tdmh", + "type": "widget", + "widgetType": "TableCell", + "x": 135, + "y": 40, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r1c1", + "label": "", + "tableRow": 1, + "tableCol": 1, + "isContainer": true + }, + { + "id": "8e4ouqsv", + "type": "widget", + "widgetType": "TableCell", + "x": 270, + "y": 40, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r1c2", + "label": "", + "tableRow": 1, + "tableCol": 2, + "isContainer": true + }, + { + "id": "em84m0y8", + "type": "widget", + "widgetType": "TableCell", + "x": 0, + "y": 62, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r2c0", + "label": "", + "tableRow": 2, + "tableCol": 0, + "isContainer": true + }, + { + "id": "xgvaxibr", + "type": "widget", + "widgetType": "TableCell", + "x": 135, + "y": 62, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r2c1", + "label": "", + "tableRow": 2, + "tableCol": 1, + "isContainer": true + }, + { + "id": "kzc148qg", + "type": "widget", + "widgetType": "TableCell", + "x": 270, + "y": 62, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r2c2", + "label": "", + "tableRow": 2, + "tableCol": 2, + "isContainer": true + }, + { + "id": "3m10xxel", + "type": "widget", + "widgetType": "TableCell", + "x": 405, + "y": 18, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r0c3", + "label": "", + "tableRow": 0, + "tableCol": 3, + "isContainer": true + }, + { + "id": "rmmxcg8e", + "type": "widget", + "widgetType": "TableCell", + "x": 405, + "y": 40, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r1c3", + "label": "", + "tableRow": 1, + "tableCol": 3, + "isContainer": true + }, + { + "id": "grqn1c65", + "type": "widget", + "widgetType": "TableCell", + "x": 405, + "y": 62, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r2c3", + "label": "", + "tableRow": 2, + "tableCol": 3, + "isContainer": true + }, + { + "id": "1wyt5r7o", + "type": "widget", + "widgetType": "TableCell", + "x": 0, + "y": 84, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r3c0", + "label": "", + "tableRow": 3, + "tableCol": 0, + "isContainer": true + }, + { + "id": "3xd2wscq", + "type": "widget", + "widgetType": "TableCell", + "x": 135, + "y": 84, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r3c1", + "label": "", + "tableRow": 3, + "tableCol": 1, + "isContainer": true + }, + { + "id": "4mwotem4", + "type": "widget", + "widgetType": "TableCell", + "x": 270, + "y": 84, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r3c2", + "label": "", + "tableRow": 3, + "tableCol": 2, + "isContainer": true + }, + { + "id": "p3qhx9nt", + "type": "widget", + "widgetType": "TableCell", + "x": 405, + "y": 84, + "w": 135, + "h": 22, + "parentId": "8j96w955", + "name": "r3c3", + "label": "", + "tableRow": 3, + "tableCol": 3, + "isContainer": true + }, + { + "id": "sbku7v95", + "type": "widget", + "widgetType": "Button", + "x": 20, + "y": 170, + "w": 110, + "h": 20, + "parentId": "ja23pnxk", + "name": "btn_analyze", + "label": "Analyze", + "family": "Button" + }, + { + "id": "n3m9rwtf", + "type": "widget", + "widgetType": "Button", + "x": 140, + "y": 170, + "w": 110, + "h": 20, + "parentId": "ja23pnxk", + "name": "btn_clear", + "label": "Clear", + "family": "Button" + }, + { + "id": "ffvl54qd", + "type": "widget", + "widgetType": "Checkbox", + "x": 280, + "y": 170, + "w": 20, + "h": 20, + "parentId": "ja23pnxk", + "name": "sel_only", + "label": "Selected tracks only", + "family": "Checkbox" + }, + { + "id": "lz00ht42", + "type": "widget", + "widgetType": "Combo", + "x": 20, + "y": 216, + "w": 200, + "h": 20, + "parentId": "ew4prttg", + "name": "loud_target", + "label": "Target", + "family": "Combo" + }, + { + "id": "s079rdc5", + "type": "widget", + "widgetType": "InputDouble", + "x": 250, + "y": 216, + "w": 100, + "h": 20, + "parentId": "ew4prttg", + "name": "lufs_value", + "label": "LUFS", + "family": "Input", + "variant": "Double", + "min": -40, + "max": 0, + "step": 0.1, + "format": "%.1f" + }, + { + "id": "ya1pz35k", + "type": "widget", + "widgetType": "Checkbox", + "x": 410, + "y": 216, + "w": 20, + "h": 20, + "parentId": "ew4prttg", + "name": "tp_limit", + "label": "True-peak limit", + "family": "Checkbox" + }, + { + "id": "intjygxr", + "type": "widget", + "widgetType": "SliderDouble", + "x": 20, + "y": 266, + "w": 260, + "h": 20, + "parentId": "ew4prttg", + "name": "ceiling", + "label": "Ceiling (dBTP)", + "family": "Slider", + "variant": "Double", + "min": -6, + "max": 0, + "format": "%.1f" + }, + { + "id": "ynh4kksf", + "type": "widget", + "widgetType": "DragInt", + "x": 310, + "y": 266, + "w": 150, + "h": 20, + "parentId": "ew4prttg", + "name": "pad", + "label": "Pad (ms)", + "family": "Drag", + "variant": "Int", + "min": 0, + "max": 2000, + "speed": 5 + }, + { + "id": "1zc5z2jq", + "type": "widget", + "widgetType": "ProgressBar", + "x": 20, + "y": 380, + "w": 460, + "h": 20, + "parentId": null, + "name": "progress", + "label": "Progress", + "family": "ProgressBar", + "overlay": "idle" + }, + { + "id": "aainbra3", + "type": "widget", + "widgetType": "Button", + "x": 500, + "y": 380, + "w": 100, + "h": 20, + "parentId": null, + "name": "btn_render", + "label": "Render", + "family": "Button" + } + ] +} \ No newline at end of file diff --git a/tools/export-gate/fixtures/examples/example_04_midi_humanizer.json b/tools/export-gate/fixtures/examples/example_04_midi_humanizer.json new file mode 100644 index 0000000..2773710 --- /dev/null +++ b/tools/export-gate/fixtures/examples/example_04_midi_humanizer.json @@ -0,0 +1,280 @@ +{ + "version": 1, + "layerOrderVersion": 1, + "tableBoxVersion": 2, + "cw": 520, + "ch": 415, + "bgColor": "#ffffff", + "bgAlpha": 1, + "bgMode": "default", + "themeId": "light", + "themeDef": null, + "auditGridMode": false, + "snapEnabled": true, + "gridStep": 10, + "projectTitle": "MIDI Humanizer", + "cnt": { + "rect": 0, + "circle": 0, + "poly": 0, + "line": 0, + "text": 0, + "triangle": 0, + "arc": 0, + "widget": 18 + }, + "shapes": [ + { + "id": "fvm63x7j", + "type": "widget", + "widgetType": "SeparatorText", + "x": 20, + "y": 10, + "w": 480, + "h": 14, + "parentId": null, + "name": "sec_hum", + "label": "Humanize", + "family": "SeparatorText" + }, + { + "id": "3ddqv2vb", + "type": "widget", + "widgetType": "DragIntRange2", + "x": 20, + "y": 50, + "w": 240, + "h": 20, + "parentId": null, + "name": "vel_range", + "label": "Velocity", + "family": "DragRange", + "variant": "Int", + "min": 1, + "max": 127, + "speed": 1 + }, + { + "id": "s2tsvq6t", + "type": "widget", + "widgetType": "DragFloatRange2", + "x": 20, + "y": 100, + "w": 240, + "h": 20, + "parentId": null, + "name": "time_range", + "label": "Timing (ms)", + "family": "DragRange", + "variant": "Double", + "min": -50, + "max": 50, + "speed": 0.5, + "format": "%.1f" + }, + { + "id": "ge29n29o", + "type": "widget", + "widgetType": "SliderDoubleN", + "x": 20, + "y": 140, + "w": 240, + "h": 20, + "parentId": null, + "name": "swing", + "label": "Swing / Depth", + "family": "SliderN", + "arraySize": 2, + "min": 0, + "max": 1, + "format": "%.2f" + }, + { + "id": "sd2s8emk", + "type": "widget", + "widgetType": "DragDoubleN", + "x": 20, + "y": 180, + "w": 240, + "h": 20, + "parentId": null, + "name": "lfo", + "label": "LFO rate / amount / phase", + "family": "DragN", + "arraySize": 3, + "speed": 0.01, + "format": "%.2f" + }, + { + "id": "a251591b", + "type": "widget", + "widgetType": "Checkbox", + "x": 310, + "y": 50, + "w": 20, + "h": 20, + "parentId": null, + "name": "lock_first", + "label": "Lock first note", + "family": "Checkbox" + }, + { + "id": "qo0h4a2a", + "type": "widget", + "widgetType": "Checkbox", + "x": 310, + "y": 100, + "w": 20, + "h": 20, + "parentId": null, + "name": "per_channel", + "label": "Per channel", + "family": "Checkbox" + }, + { + "id": "h2zeuau8", + "type": "widget", + "widgetType": "Combo", + "x": 310, + "y": 150, + "w": 180, + "h": 20, + "parentId": null, + "name": "scale", + "label": "Scale", + "family": "Combo" + }, + { + "id": "3uui4qvq", + "type": "widget", + "widgetType": "TreeNode", + "x": 20, + "y": 230, + "w": 480, + "h": 130, + "parentId": null, + "name": "presets", + "label": "Presets", + "family": "TreeNode", + "isContainer": true + }, + { + "id": "u3nf5602", + "type": "widget", + "widgetType": "Selectable", + "x": 20, + "y": 40, + "w": 200, + "h": 20, + "parentId": "3uui4qvq", + "name": "p_loose", + "label": "Loose drummer", + "family": "Selectable" + }, + { + "id": "h9zyxqvt", + "type": "widget", + "widgetType": "Selectable", + "x": 20, + "y": 60, + "w": 200, + "h": 20, + "parentId": "3uui4qvq", + "name": "p_tight", + "label": "Tight session", + "family": "Selectable" + }, + { + "id": "9tshj1k4", + "type": "widget", + "widgetType": "Selectable", + "x": 20, + "y": 90, + "w": 200, + "h": 20, + "parentId": "3uui4qvq", + "name": "p_tape", + "label": "Drunk tape", + "family": "Selectable" + }, + { + "id": "6e38jk2y", + "type": "widget", + "widgetType": "BulletText", + "x": 240, + "y": 40, + "w": 210, + "h": 14, + "parentId": "3uui4qvq", + "name": "hint_apply", + "label": "Double-click to apply", + "family": "BulletText" + }, + { + "id": "wou3ijx4", + "type": "widget", + "widgetType": "SmallButton", + "x": 240, + "y": 60, + "w": 50, + "h": 20, + "parentId": "3uui4qvq", + "name": "p_save", + "label": "Save", + "family": "SmallButton" + }, + { + "id": "gk7gfije", + "type": "widget", + "widgetType": "SmallButton", + "x": 320, + "y": 60, + "w": 50, + "h": 20, + "parentId": "3uui4qvq", + "name": "p_delete", + "label": "Delete", + "family": "SmallButton" + }, + { + "id": "g9us5afj", + "type": "widget", + "widgetType": "Button", + "x": 20, + "y": 380, + "w": 120, + "h": 20, + "parentId": null, + "name": "btn_apply", + "label": "Apply", + "family": "Button" + }, + { + "id": "modxv7qc", + "type": "widget", + "widgetType": "Button", + "x": 150, + "y": 380, + "w": 120, + "h": 20, + "parentId": null, + "name": "btn_undo", + "label": "Undo", + "family": "Button" + }, + { + "id": "s4mpm1nk", + "type": "widget", + "widgetType": "TextLinkOpenURL", + "x": 370, + "y": 380, + "w": 130, + "h": 14, + "parentId": null, + "name": "docs", + "label": "Humanize docs", + "family": "TextLinkOpenURL", + "url": "https://www.reaper.fm/sdk/reascript/reascripthelp.html" + } + ] +} \ No newline at end of file diff --git a/tools/export-gate/fixtures/examples/example_05_marker_palette.json b/tools/export-gate/fixtures/examples/example_05_marker_palette.json new file mode 100644 index 0000000..3b348fd --- /dev/null +++ b/tools/export-gate/fixtures/examples/example_05_marker_palette.json @@ -0,0 +1,447 @@ +{ + "version": 1, + "layerOrderVersion": 1, + "tableBoxVersion": 2, + "cw": 560, + "ch": 450, + "bgColor": "#20242b", + "bgAlpha": 1, + "bgMode": "default", + "themeId": "default", + "themeDef": null, + "auditGridMode": false, + "snapEnabled": true, + "gridStep": 10, + "projectTitle": "Marker Palette", + "cnt": { + "rect": 0, + "circle": 0, + "poly": 0, + "line": 0, + "text": 0, + "triangle": 0, + "arc": 0, + "widget": 28 + }, + "shapes": [ + { + "id": "lxpkbxfm", + "type": "widget", + "widgetType": "SeparatorText", + "x": 20, + "y": 10, + "w": 480, + "h": 14, + "parentId": null, + "name": "sec_colors", + "label": "Marker colours", + "family": "SeparatorText" + }, + { + "id": "f7k3txvb", + "type": "widget", + "widgetType": "HelpMarker", + "x": 520, + "y": 10, + "w": 20, + "h": 20, + "parentId": null, + "name": "help_colors", + "label": "", + "family": "HelpMarker", + "tooltip": "Colours are written to the selected markers and regions when you press Apply." + }, + { + "id": "ph77r0an", + "type": "widget", + "widgetType": "StyleRegion", + "x": 20, + "y": 40, + "w": 300, + "h": 200, + "parentId": null, + "name": "style_palette", + "label": "Palette", + "family": "StyleRegion", + "isContainer": true, + "styleText": "#e6e9ef", + "styleFrameBg": "#2b313a", + "styleButton": "#3b6ea5", + "styleRounding": 4 + }, + { + "id": "gadj204c", + "type": "widget", + "widgetType": "ColorEdit4", + "x": 20, + "y": 50, + "w": 200, + "h": 20, + "parentId": "ph77r0an", + "name": "col_fill", + "label": "Fill", + "family": "ColorEdit", + "variant": "RGBA", + "colorAlpha": 255 + }, + { + "id": "qjx7e71p", + "type": "widget", + "widgetType": "ColorEdit3", + "x": 20, + "y": 90, + "w": 200, + "h": 20, + "parentId": "ph77r0an", + "name": "col_text", + "label": "Text", + "family": "ColorEdit", + "variant": "RGB" + }, + { + "id": "eubn5yxi", + "type": "widget", + "widgetType": "ColorButton", + "x": 20, + "y": 130, + "w": 40, + "h": 20, + "parentId": "ph77r0an", + "name": "swatch_a", + "label": "", + "family": "ColorButton" + }, + { + "id": "xyi6ljty", + "type": "widget", + "widgetType": "ColorButton", + "x": 70, + "y": 130, + "w": 40, + "h": 20, + "parentId": "ph77r0an", + "name": "swatch_b", + "label": "", + "family": "ColorButton" + }, + { + "id": "cop3ip3x", + "type": "widget", + "widgetType": "ColorButton", + "x": 120, + "y": 130, + "w": 40, + "h": 20, + "parentId": "ph77r0an", + "name": "swatch_c", + "label": "", + "family": "ColorButton" + }, + { + "id": "lq6x6w9q", + "type": "widget", + "widgetType": "SmallButton", + "x": 170, + "y": 130, + "w": 50, + "h": 20, + "parentId": "ph77r0an", + "name": "store_swatch", + "label": "Store", + "family": "SmallButton" + }, + { + "id": "5q26savl", + "type": "widget", + "widgetType": "ColorPicker3", + "x": 350, + "y": 70, + "w": 180, + "h": 226, + "parentId": null, + "name": "picker", + "label": "Picker", + "family": "ColorPicker", + "variant": "RGB", + "colorEditFlags": [ + "NoSidePreview" + ], + "cpSideMigrated": true + }, + { + "id": "coebie3z", + "type": "widget", + "widgetType": "Table", + "x": 20, + "y": 284, + "w": 300, + "h": 116, + "parentId": null, + "name": "marker_table", + "label": "Markers", + "family": "Table", + "isContainer": true, + "columnCount": 3, + "rowCount": 4, + "columns": [ + "#", + "Name", + "Colour" + ], + "headersRow": true, + "tableFlags": { + "Borders": true, + "RowBg": true, + "Resizable": false, + "ScrollY": false + }, + "sizing": "SizingStretchSame" + }, + { + "id": "ltr1xrel", + "type": "widget", + "widgetType": "TableCell", + "x": 0, + "y": 18, + "w": 100, + "h": 25, + "parentId": "coebie3z", + "name": "r0c0", + "label": "", + "tableRow": 0, + "tableCol": 0, + "isContainer": true + }, + { + "id": "5zhfd2oq", + "type": "widget", + "widgetType": "TableCell", + "x": 100, + "y": 18, + "w": 100, + "h": 25, + "parentId": "coebie3z", + "name": "r0c1", + "label": "", + "tableRow": 0, + "tableCol": 1, + "isContainer": true + }, + { + "id": "kyan7d5r", + "type": "widget", + "widgetType": "TableCell", + "x": 200, + "y": 18, + "w": 100, + "h": 25, + "parentId": "coebie3z", + "name": "r0c2", + "label": "", + "tableRow": 0, + "tableCol": 2, + "isContainer": true + }, + { + "id": "inwz05un", + "type": "widget", + "widgetType": "TableCell", + "x": 0, + "y": 43, + "w": 100, + "h": 25, + "parentId": "coebie3z", + "name": "r1c0", + "label": "", + "tableRow": 1, + "tableCol": 0, + "isContainer": true + }, + { + "id": "m5nyoj0j", + "type": "widget", + "widgetType": "TableCell", + "x": 100, + "y": 43, + "w": 100, + "h": 25, + "parentId": "coebie3z", + "name": "r1c1", + "label": "", + "tableRow": 1, + "tableCol": 1, + "isContainer": true + }, + { + "id": "u4o0nfhh", + "type": "widget", + "widgetType": "TableCell", + "x": 200, + "y": 43, + "w": 100, + "h": 25, + "parentId": "coebie3z", + "name": "r1c2", + "label": "", + "tableRow": 1, + "tableCol": 2, + "isContainer": true + }, + { + "id": "4scoexj3", + "type": "widget", + "widgetType": "TableCell", + "x": 0, + "y": 68, + "w": 100, + "h": 25, + "parentId": "coebie3z", + "name": "r2c0", + "label": "", + "tableRow": 2, + "tableCol": 0, + "isContainer": true + }, + { + "id": "gekh5gus", + "type": "widget", + "widgetType": "TableCell", + "x": 100, + "y": 68, + "w": 100, + "h": 25, + "parentId": "coebie3z", + "name": "r2c1", + "label": "", + "tableRow": 2, + "tableCol": 1, + "isContainer": true + }, + { + "id": "zzb4x802", + "type": "widget", + "widgetType": "TableCell", + "x": 200, + "y": 68, + "w": 100, + "h": 25, + "parentId": "coebie3z", + "name": "r2c2", + "label": "", + "tableRow": 2, + "tableCol": 2, + "isContainer": true + }, + { + "id": "p2xnouls", + "type": "widget", + "widgetType": "TableCell", + "x": 0, + "y": 93, + "w": 100, + "h": 23, + "parentId": "coebie3z", + "name": "r3c0", + "label": "", + "tableRow": 3, + "tableCol": 0, + "isContainer": true + }, + { + "id": "2x4mxtlg", + "type": "widget", + "widgetType": "TableCell", + "x": 100, + "y": 93, + "w": 100, + "h": 23, + "parentId": "coebie3z", + "name": "r3c1", + "label": "", + "tableRow": 3, + "tableCol": 1, + "isContainer": true + }, + { + "id": "0wv7kgg1", + "type": "widget", + "widgetType": "TableCell", + "x": 200, + "y": 93, + "w": 100, + "h": 23, + "parentId": "coebie3z", + "name": "r3c2", + "label": "", + "tableRow": 3, + "tableCol": 2, + "isContainer": true + }, + { + "id": "br2f9dja", + "type": "widget", + "widgetType": "TextWrapped", + "x": 350, + "y": 320, + "w": 190, + "h": 36, + "parentId": null, + "name": "note", + "label": "Colours apply to every selected marker and region. Regions keep their own alpha.", + "family": "TextWrapped" + }, + { + "id": "nnnup46s", + "type": "widget", + "widgetType": "TextLinkOpenURL", + "x": 350, + "y": 360, + "w": 190, + "h": 14, + "parentId": null, + "name": "link_ref", + "label": "Colour reference", + "family": "TextLinkOpenURL", + "url": "https://www.reaper.fm/sdk/reascript/reascripthelp.html" + }, + { + "id": "kpiq12o1", + "type": "widget", + "widgetType": "Button", + "x": 20, + "y": 420, + "w": 160, + "h": 20, + "parentId": null, + "name": "btn_apply", + "label": "Apply to selection", + "family": "Button" + }, + { + "id": "a0l7zbcn", + "type": "widget", + "widgetType": "Button", + "x": 190, + "y": 420, + "w": 100, + "h": 20, + "parentId": null, + "name": "btn_reset", + "label": "Reset", + "family": "Button" + }, + { + "id": "bdsgpf8p", + "type": "widget", + "widgetType": "TextDisabled", + "x": 350, + "y": 420, + "w": 190, + "h": 20, + "parentId": null, + "name": "status", + "label": "3 markers selected", + "family": "TextDisabled" + } + ] +} \ No newline at end of file diff --git a/tools/export-gate/historical/export_gate_v12.js b/tools/export-gate/historical/export_gate_v12.js new file mode 100644 index 0000000..100f40a --- /dev/null +++ b/tools/export-gate/historical/export_gate_v12.js @@ -0,0 +1,2607 @@ +#!/usr/bin/env node +/* ============================================================================ + * export_gate.js (v7) — standing export-gate harness for ReaUI Builder + * ---------------------------------------------------------------------------- + * Implements ADR-002 (claude/adr/002_gate_coverage.md). Canonical home: + * tools/export-gate/export_gate.js — every other copy is a mirror (G1). + * v3 (brief B02 stage 2.1) adds, after every v2 scene: the alpha scenes for ADR-004, + * the G5 alpha-255 cross-scene check and the theme-library-separation check for + * ADR-003 F7. No v2 scene content changed: v2 goldens stay byte-identical. + * v4 (brief B03 stage 3.1) adds, fixture first for release 1.2.0 (ADR-002 G6): four + * types appended to FROZEN_TYPES (TextLink, CheckboxFlags, PlotLines, PlotHistogram; + * new slots at y >= 1000, no existing entry moved), the scenes wave-a and + * wave-a.explicit-defaults after every v3 scene, and the G5 wave-a cross-scene check. + * No v3 scene content changed: on a build that lacks the four types, all-types is + * byte-identical to v3 (the new entries are skipped before any create or uid draw) + * and only gains four `N/A` notes; every other v3 golden is byte-identical. + * v5 (ADR-005 stage X1.0) adds, fixture first for release 1.3.0 (ADR-002 G6), the scene + * text-metrics after every v4 scene. No v4 scene content changed: every v4 golden is + * byte-identical under v5. + * v6 (brief B05 stage 5.1) adds, fixture first for release 1.4.0 (ADR-002 G6): one type + * appended to FROZEN_TYPES (InvisibleButton; a new slot at y >= 1000, no existing entry + * moved), the scenes wave-b and wave-b.explicit-defaults after every v5 scene, and the + * G5 wave-b cross-scene check. No v5 scene content changed: on a build that lacks + * InvisibleButton, all-types is byte-identical to v5 (the new entry is skipped before + * any create or uid draw) and only gains one `N/A` note; every other v5 golden is + * byte-identical. + * v7 (brief B06 stage 6.1) adds, fixture first for release 1.5.0 (ADR-002 G6, ADR-011): + * the scenes tables-b and tables-b.explicit-defaults after every v6 scene, and the + * G5 tables-b cross-scene check. No v6 scene content changed: every v6 golden is + * byte-identical under v7. tables-b covers the two new Table properties (ADR-011 G2/G4) + * — angledHeaders and scrollRows — on six explicitly named tables built through + * H.create then mutated on the live shape, as wave-a/wave-b do; a bridge helper + * H.resizeTable grows a table's row count the same way the inspector's row stepper + * does (rowCount/rowHeights/columns kept in sync, ensureTableCells/syncTableCellBounds + * re-run), since the harness builds tables outside the inspector UI. + * v8 (brief B07 stage 7.1) adds, fixture first for release 1.6.0 (ADR-002 G6, ADR-007): + * the scenes menus, menus.themed and menus.explicit-defaults after every v7 scene, and + * the G5 menus cross-scene check. No v7 scene content changed: every v7 golden is + * byte-identical under v8. A menu bar is project data, not a shape: the menus scenes + * build a small widget set through H.create, then attach `menuBar` to the saved project + * and round-trip it through Save -> reset -> Load (withMenuBar), so a build that does + * not know the key still builds every scene (it simply exports no menu). The 1.5.0-dev.2 + * baseline drops an unknown `menuBar` key silently on Save, in genSeed() and in + * genImGui(), so on the baseline every menus scene exports identically to one with no + * menu bar at all. + * v9 (brief B07 stage 7.3) adds, fixture first for release 1.6.0 (ADR-002 G6, ADR-007 + * M11): the scenes themes.slate-title, themes.slate-title.explicit-default and + * menus.themed-title after every v8 scene, and the G5 title cross-scene check. No v8 + * scene content changed: every v8 golden is byte-identical under v9. `themedTitleBar` + * is project data, not a shape, same as `menuBar`: withProjectKeys generalises + * withMenuBar's pattern (Save -> add keys -> reset -> Load) to any project-level key, + * so a build that does not know the key still builds every scene (it simply always + * themes the title bar, since the 1.6.0-dev.1 baseline has no title-bar option and + * colours the title unconditionally on a non-default theme). + * v10 (brief B11 stage 11.1) adds one scene, `arcs`, after every v9 scene. It covers F04 + * (1.6.0-dev.10) after the fact (B10 review R1; ADR-002 G6 wanted it first): pie fills over + * 180 degrees, sweeps that cross 0, negative and past-one-turn angles, a full-turn pie, a + * stroke-less ring. Nothing else is added (no G5, no check). No v9 scene content changed: + * every v9 golden is byte-identical under v10. On a pre-F04 build (1.6.0-dev.3) the arcs + * scene shows the F04 lines as CHANGED, which is expected. + * v11 (brief A01) adds, fixture first for the Adaptive UI layout work (ADR-002 G6, ADR-009 + * AD11), a fourth channel and ten scenes. CHANNEL `file`: every scene also stores + * `H.saveText()` (the saved project, pretty-printed JSON) taken from the first build, compared + * with normSeed (ids normalised) exactly like the seed. Before v11 no channel looked at the + * saved file, so a build could write new keys and demo objects into every project and pass + * every scene (A0_sketch_review.md §3). A rebuild whose file differs is NON-DETERMINISTIC + * "(file)". SCENES `adaptive.*` (after `arcs`): per-shape pins `pinH` / `pinV` and the project + * key `windowResize` are written into the SAVED project only (withAdaptive: Save -> edit the + * JSON by shape name -> reset -> Load), never onto live shapes, so a build that does not know + * them shows what its loader does with them. Body A is a 640x440 form (16 named shapes, a Panel + * with a Group inside); `adaptive.base` has no pins, `adaptive.inert` has MOVE+STRETCH pins and + * no `windowResize` key, `adaptive.move` / `.move.explicit-defaults` / `.limits` / + * `.stretch` add the key, `adaptive.nested` (StyleRegion, TabBar, TreeNode, nested Panels, + * Table, CollapsingHeader), `adaptive.primitives` (seven primitives + one widget) and + * `adaptive.menus` (the v8 menu fixture, `maxW:1000`) cover the other containers, and + * `adaptive.invalid` writes every value ADR-009 AD1/AD2/AD4 make the loader drop. CROSS-SCENE + * CHECK `G5 adaptive`: adaptive.move (absent) vs adaptive.move.explicit-defaults, three parts: + * (a) imgui, (b) seed after Save -> reset -> Load, (c) the file after Save -> reset -> Load. + * It prints `N/A` (no exit change) on a build whose loader drops `windowResize` (support + * probe). CHECK `adaptive inert`: adaptive.inert's genImGui() must equal adaptive.base's, in + * separate instances, on every build, the baseline included (seed and file are not compared: + * the pins are in them by design). A G5 adaptive FAIL or an adaptive inert FAIL follows the + * v3 rule: the build under test sets exit 3, the BEFORE build prints it as pre-existing. + * No v10 scene content changed: every v10 golden (.imgui, .seed) is byte-identical under v11. + * v12 (brief A07.1), fixture first for the 2.1.0 tables work (ADR-002 G6, ADR-009 AD4/AD5/AD6/AD8, + * ADR-011 G1/G3/G4), adds three scenes after every v11 scene and one bridge helper. SCENES + * `tables-c.stretch` (640x480, `windowResize {minW:480, minH:320}`; three tables tc_list / tc_hdr / + * tc_plain, cell children inside tc_list, pins written through withAdaptive), `tables-c.style` (a + * fixed window; the new Table properties `cellPadding`, `rowBg`, `highlightColor` + + * `highlightRows`, `rowsFill` and the StyleRegion property `styleFramePadding`, set on the live + * shapes as tables-b does) and `tables-c.explicit-defaults` (the same body with every new property + * written as its default). BRIDGE `H.cellChild(tableName, r, c, type, x, y, ov)` creates a widget + * inside a Table cell at a cell-relative point; `H.cellChildNote()` returns `NOT NESTED ...` when + * the new widget did not land in that cell. `H.resizeTable(t, rows, cols)` also grows columns now. + * CROSS-SCENE CHECK `G5 tables-c`: the tables-c.style body built with the new properties absent vs + * tables-c.explicit-defaults, three parts as G5 adaptive: (a) imgui, (b) seed and (c) file after + * Save -> reset -> Load. On a build that keeps unknown shape keys (2.0.0) part (a) passes for the + * wrong reason and (b) / (c) may FAIL, as G5 tables-b did on its baseline; the harness does not + * hide that. No v11 scene content changed: every v11 golden (.imgui, .seed, .file) is + * byte-identical under v12. + * + * Loads a single-file ReaUI Builder .html headlessly (jsdom), injects a bridge at + * the end of the main '); + if(lc<0) throw new HarnessError('no in '+htmlPath); + html = html.slice(0,lc) + BRIDGE + html.slice(lc); + const dom = new JSDOM(html,{ runScripts:'outside-only', pretendToBeVisual:true, url:'https://local.test/' }); + const { window } = dom; + window.HTMLCanvasElement.prototype.getContext = () => makeCtx2d(); + window.requestAnimationFrame = () => 0; window.cancelAnimationFrame = () => {}; + if(!window.Path2D) window.Path2D = Path2DStub; + // Seeded PRNG per instance: uid() draws on Math.random, so v1 seeds differed on every + // run and a golden seed could only be compared after normSeed. With a fixed seed the + // goldens are byte-reproducible (cmp works run to run); the before/after comparison + // still normalises ids, because a patch that adds one random draw shifts them all. + window.Math.random = mulberry32(0x5eed0a02); + window.alert = window.prompt = window.confirm = () => {}; + if(!window.matchMedia) window.matchMedia = () => ({matches:false,addListener(){},removeListener(){},addEventListener(){},removeEventListener(){}}); + const errs = []; + window.addEventListener('error', e => errs.push('window.error: '+(e.message||e))); + for(const el of [...window.document.querySelectorAll('script')]){ + try { window.eval(el.textContent); } + catch(e){ throw new HarnessError('SCRIPT THROW during init ('+path.basename(htmlPath)+'): '+(e&&e.stack||e)); } + } + if(!window.__H) throw new HarnessError('bridge __H missing — injection failed ('+path.basename(htmlPath)+')'); + return { H: window.__H, errs, window }; +} + +// ============================================================================ +// Frozen fixture data. Changing anything here changes goldens: extend, never edit +// (ADR-002 G6: a new type is added here first, captured on the unchanged builder). +// ============================================================================ + +// Every palette-creatable type in 1.0.70 (WIDGET_CONTRACTS minus TabItem/TableCell), +// each with a fixed absolute slot on a 1200x1200 canvas. Slots are fixed per entry, so a +// type missing from one build never moves the others. Names are explicit for the same +// reason: the default name draws on a running counter, and one N/A would rename every +// later widget and turn a one-type difference into a whole-scene diff. +const COL = [20, 260, 500, 740, 980]; +const FROZEN_TYPES = [ + // single-line widgets (default h <= 20), 5 per row, 40 px pitch + ['HelpMarker', COL[0], 20], ['Button', COL[1], 20], ['Checkbox', COL[2], 20], ['Text', COL[3], 20], ['TextColored', COL[4], 20], + ['TextDisabled', COL[0], 60], ['Separator', COL[1], 60], ['SliderDouble', COL[2], 60], ['SliderInt', COL[3], 60], ['InputText', COL[4], 60], + ['InputInt', COL[0], 100], ['InputDouble', COL[1], 100], ['Combo', COL[2], 100], ['ProgressBar', COL[3], 100], ['DragInt', COL[4], 100], + ['DragDouble', COL[0], 140], ['SeparatorText', COL[1], 140], ['ColorEdit3', COL[2], 140], ['ColorEdit4', COL[3], 140], ['ArrowButton', COL[4], 140], + ['InputTextWithHint', COL[0], 180], ['LabelText', COL[1], 180], ['SmallButton', COL[2], 180], ['Selectable', COL[3], 180], ['BulletText', COL[4], 180], + ['TextLinkOpenURL', COL[0], 220], ['SliderAngle', COL[1], 220], ['ColorButton', COL[2], 220], ['RadioButtonEx', COL[3], 220], ['SliderDoubleN', COL[4], 220], + ['DragDoubleN', COL[0], 260], ['InputDoubleN', COL[1], 260], ['DragIntRange2', COL[2], 260], ['DragFloatRange2', COL[3], 260], + // multi-line / tall + ['ListBox', COL[0], 310], ['TextWrapped', COL[1], 310], ['InputTextMultiline', COL[2], 310], + ['VSliderInt', COL[3], 310], ['VSliderDouble', COL[4], 310], + // pickers (height derived from width) + ['ColorPicker3', COL[0], 500], ['ColorPicker4', COL[1], 500], + // containers, empty (children are covered by core / themes / examples) + ['Panel', COL[2], 500], ['Group', COL[3], 500], ['StyleRegion', COL[4], 500], + ['CollapsingHeader', COL[2], 680], ['TreeNode', COL[3], 680], + ['TabBar', COL[0], 830], ['Table', 340, 830], + // v4 — release 1.2.0 types (B03 3.1). Appended, never interleaved: every earlier slot + // and name is unchanged. Placed where nothing is at y >= 1000 on the 1200x1200 canvas: + // TabBar (20,830 280x180) and Table (340,830 320x200) end at x 660, and the primitive + // row starts at y 1080 and ends at x 860. The plots sit at x 740/980 from y 1000: + // a default height up to 80 keeps PlotLines clear of the primitive row (x 780-860 + // from y 1080); PlotHistogram (x 980-1180) only meets TextLink (x 900 + default w, + // y 1160) at a height of 160. CheckboxFlags (x 900-920) meets neither. + ['TextLink', 900, 1160], ['CheckboxFlags', 900, 1110], + ['PlotLines', COL[3], 1000], ['PlotHistogram', COL[4], 1000], + // v6 — release 1.4.0 type (B05 5.1; slot fixed in the coordinator's review). Appended, + // never interleaved: every earlier slot and name is unchanged. Slot (20,1150): below the + // primitive row (y 1080-1140), left of TextLink (x 900, y 1160) and CheckboxFlags + // (x 900, y 1110); a default size up to 860x50 stays clear of both and inside the + // 1200x1200 canvas (B05 B2 suggests 100x40). + ['InvisibleButton', COL[0], 1150], +]; +const ALL_TYPES_CANVAS = { cw:1200, ch:1200 }; +// Draw primitives: [kind, x1, y1, x2, y2] — a drag from (x1,y1) to (x2,y2). +const FROZEN_PRIMITIVES = [ + ['rect', 20, 1080, 100, 1140], ['circle', 140, 1080, 220, 1140], ['poly', 260, 1080, 340, 1140], + ['line', 380, 1080, 460, 1140], ['text', 500, 1080, 620, 1140], ['triangle', 660, 1080, 740, 1140], + ['arc', 780, 1080, 860, 1140], +]; +// Structural children: made by their containers, never from the palette. +const STRUCTURAL_TYPES = new Set(['TabItem','TableCell']); + +// A custom theme with all 15 THEME_CHANNELS authored, every value distinct. +const GATE_CUSTOM_THEME = { + id:'gate-custom', label:'Gate custom', + colors:{ + text:'#f1e2d3', textLabel:'#e3d4c5', childBg:'#1a2b3c', frameBg:'#243546', + frameBgHovered:'#2e3f50', frameBgActive:'#38495a', button:'#6a2c1e', buttonHovered:'#7b3d2f', + buttonActive:'#8c4e40', header:'#1e6a2c', headerHovered:'#2f7b3d', headerActive:'#408c4e', + checkMark:'#c0ffee', sliderGrab:'#b16d2a', sliderGrabActive:'#d28e4b' + } +}; + +// v3 — ADR-004 A2: the 12 channels that may carry alpha, in A2 order. Frozen here, not +// read from the build (a build without alpha has no such list). +const ALPHA_CHANNELS = ['frameBg','frameBgHovered','frameBgActive','button','buttonHovered', + 'buttonActive','header','headerHovered','headerActive','checkMark','sliderGrab','sliderGrabActive']; +// themes.gate-alpha: GATE_CUSTOM_THEME's colours, own id, 12 distinct alphas, none 0/255. +const GATE_ALPHA_VALUES = [0x21,0x32,0x43,0x54,0x65,0x76,0x87,0x98,0xA9,0xBA,0xCB,0xDC]; +const GATE_ALPHA_THEME = { + id:'gate-alpha', label:'Gate alpha', + colors: Object.assign({}, GATE_CUSTOM_THEME.colors), + alpha: Object.fromEntries(ALPHA_CHANNELS.map((c,i)=>[c, GATE_ALPHA_VALUES[i]])) +}; +// themes.gate-alpha-opaque: GATE_CUSTOM_THEME itself (same id) plus twelve 255s. Must +// export exactly like themes.gate-custom (G5). +const GATE_ALPHA_OPAQUE_THEME = { + id:GATE_CUSTOM_THEME.id, label:GATE_CUSTOM_THEME.label, + colors: Object.assign({}, GATE_CUSTOM_THEME.colors), + alpha: Object.fromEntries(ALPHA_CHANNELS.map(c=>[c, 255])) +}; + +// v3 — theme-library-separation (ADR-003 F7). Library colours A and project colours B +// share the id `lib-x`; every value is canonical lower-case and no value repeats across +// A, B and lib-y, so a match can only mean one source. +const LIB_X_A = { + id:'lib-x', label:'Library X', + colors:{ + text:'#e1f0a1', textLabel:'#e1f0a2', childBg:'#10a0a1', frameBg:'#20a0a1', + frameBgHovered:'#20a0a2', frameBgActive:'#20a0a3', button:'#30a0a1', buttonHovered:'#30a0a2', + buttonActive:'#30a0a3', header:'#40a0a1', headerHovered:'#40a0a2', headerActive:'#40a0a3', + checkMark:'#50a0a1', sliderGrab:'#60a0a1', sliderGrabActive:'#60a0a2' + } +}; +const LIB_X_B = { + id:'lib-x', label:'Project X', + colors:{ + text:'#e1f0b1', textLabel:'#e1f0b2', childBg:'#10b0b1', frameBg:'#20b0b1', + frameBgHovered:'#20b0b2', frameBgActive:'#20b0b3', button:'#30b0b1', buttonHovered:'#30b0b2', + buttonActive:'#30b0b3', header:'#40b0b1', headerHovered:'#40b0b2', headerActive:'#40b0b3', + checkMark:'#50b0b1', sliderGrab:'#60b0b1', sliderGrabActive:'#60b0b2' + } +}; +const LIB_Y = { id:'lib-y', label:'Library Y', colors:{ text:'#e1f0c1', childBg:'#10c0c1' } }; +// The 13 theme pushes that map one-to-one to an authored channel (buildThemeColorPushes). +// resolveThemeColors lets authored values win, so each carries the authored colour. +const THEME_PUSH_SLOTS = [ + ['Text','text'], ['FrameBg','frameBg'], ['FrameBgHovered','frameBgHovered'], + ['FrameBgActive','frameBgActive'], ['Button','button'], ['ButtonHovered','buttonHovered'], + ['ButtonActive','buttonActive'], ['Header','header'], ['HeaderHovered','headerHovered'], + ['HeaderActive','headerActive'], ['CheckMark','checkMark'], ['SliderGrab','sliderGrab'], + ['SliderGrabActive','sliderGrabActive'], +]; + +const EXAMPLE_FILES = [ + 'example_01_batch_rename.json', + 'example_02_item_fade_tool.json', + 'example_03_render_loudness.json', + 'example_04_midi_humanizer.json', + 'example_05_marker_palette.json', +]; +const FIXTURE_DIR = path.join(__dirname, 'fixtures', 'examples'); + +// ============================================================================ +// Scenes. build(H, note) runs after H.reset(); note(text) attaches a line to the verdict. +// ============================================================================ + +// core — v1's fixture, verbatim. Do not edit: its output must stay byte-identical +// to the v1 golden of the same build (ADR-002 G2, the rewrite's acceptance test). +function buildCore(H){ + H.create('Button', 40, 40); // bare canvas + const grp = H.create('Group', 40, 120, { w:200, h:120 }); + if(grp) H.create('Checkbox', 70, 160); // inside group + const tabbar = H.create('TabBar', 300, 40, { w:240, h:160 }); + if(tabbar) H.create('SliderInt', 330, 90); // inside active tab + const table = H.create('Table', 40, 280, { w:320, h:110 }); + // Locked-size types: their w/h come from a native ReaImGui contract, not the + // grid, and an audit found all four drifting between creation and load (F01). + // The gate reported CLEAN on that patch because none of them were here. + H.create('ArrowButton', 600, 40); + H.create('SeparatorText', 600, 90); + H.create('BulletText', 600, 140); + H.create('TextLinkOpenURL', 600, 190); + // CollapsingHeader with a child: the one container whose emission shape is not + // otherwise covered, and the type whose generated state caused F03. + const hdr = H.create('CollapsingHeader', 40, 440, { w:200, h:120 }); + if(hdr) H.create('Button', 60, 500); + // A labelled primitive: size, colour and clipping of a shape label are a code path + // of their own, and the fixture could not see it - running the gate on the patch that + // rewrote that path reported CLEAN. Long label, non-default text size, and a stroke + // colour distinct from any label colour, so a regression in any of the three shows up + // as a diff rather than as silence. + // c62-c65 coverage (1.0.68). The gate was blind to all of these, which is how a + // 2.5-4 px text-landing offset (c64) and invisible tint marks (c65) shipped CLEAN. + // Native-text landing: TextColored / TextDisabled / HelpMarker. + H.create('TextColored', 600, 240, { w:140, label:'TextColored' }); + H.create('TextDisabled', 600, 280, { w:140, label:'TextDisabled' }); + H.create('HelpMarker', 600, 320); + // ProgressBar overlay text (exported verbatim; empty exports ""). + const pb = H.create('ProgressBar', 600, 360, { w:200, h:20 }); + if(pb) pb.overlay = 'Loading'; + // Tint ramp (c65) + cascade to children: marks must differ from the surface. + const tg = H.create('Group', 300, 440, { w:240, h:150 }); + if(tg){ tg.widgetTint = '#b03a2e'; H.create('Checkbox', 320, 480); H.create('SliderDouble', 320, 530, { w:160 }); } + const ttb = H.create('TabBar', 600, 420, { w:260, h:140 }); + if(ttb){ ttb.widgetTint = '#6c3483'; H.create('Button', 620, 480, { w:120, h:20 }); } + // Label-less container (c62): a stored label must not reach the ImGui ID. + H.create('Panel', 600, 600, { w:200, h:80, label:'IGNORED_LABEL' }); + H.shapes().push({ id:'fixture-rect-label', name:'Rect_label', type:'rect', + x:400, y:300, w:170, h:90, fill:'#ffffff', stroke:'#ff0000', thickness:2, + label:'This label is far longer than the shape that carries it', textSize:20 }); + let cellCount = 0; + if(table){ + const cells = H.cellsOf(table.id); + cellCount = cells.length; + if(cells.length){ + const c = cells[0]; + H.create('Text', H.absX(c)+c.w/2-10, H.absY(c)+c.h/2-6, { w:20, h:12 }); // inside a cell + } + } +} + +function buildAllTypes(H, note){ + H.set('cw', ALL_TYPES_CANVAS.cw); H.set('ch', ALL_TYPES_CANVAS.ch); + for(const [t, x, y] of FROZEN_TYPES){ + if(!H.hasType(t)){ note('N/A (build lacks '+t+')'); continue; } + const s = H.create(t, x, y, { name:'at_'+t }); + if(!s) note('BLOCKED '+t+' at '+x+','+y+(H.hints().length?' — '+H.hints().join(' / '):'')); + } + for(const [kind, x1, y1, x2, y2] of FROZEN_PRIMITIVES){ + if(!H.primitive(kind, x1, y1, x2, y2)) note('BLOCKED primitive '+kind); + } + const frozen = new Set(FROZEN_TYPES.map(e=>e[0])); + const extra = H.contractKeys().filter(k=>!frozen.has(k) && !STRUCTURAL_TYPES.has(k)); + if(extra.length) note('build has types outside the frozen list: '+extra.join(', ')+' (add them first — G6)'); +} + +// Compact scene for the theme channel: every theme-coloured family appears once. +function buildThemeBody(H){ + H.create('Button', 40, 40); + H.create('Checkbox', 40, 80); + H.create('SliderDouble', 40, 120); + const hdr = H.create('CollapsingHeader', 40, 170, { w:200, h:120 }); + if(hdr) H.create('Button', 60, 230); + H.create('TabBar', 300, 40, { w:240, h:160 }); + H.create('ProgressBar', 300, 240, { w:200, h:20 }); +} +function themeScene(id){ + return function(H, note){ + if(id===GATE_CUSTOM_THEME.id){ + const got = H.adoptProjectTheme(JSON.parse(JSON.stringify(GATE_CUSTOM_THEME))); + if(got!==GATE_CUSTOM_THEME.id) throw new Error('adoptProjectTheme returned '+JSON.stringify(got)); + } + H.set('themeId', id); + buildThemeBody(H); + }; +} + +function buildProject(H){ + H.set('cw', 640); H.set('ch', 360); + H.set('bgMode', 'custom'); H.set('bgColor', '#2d4a6b'); H.set('bgAlpha', 0.6); + H.set('projectTitle', 'Gate "quoted" \\ title'); + H.create('Button', 40, 40); + H.create('TextColored', 40, 80, { w:140, label:'On custom bg' }); + H.create('SliderInt', 40, 120); +} + +function exampleScene(file){ + return function(H){ + const p = path.join(FIXTURE_DIR, file); + if(!fs.existsSync(p)) throw new HarnessError('fixture missing: '+p); + const r = H.loadText(fs.readFileSync(p,'utf8')); + if(!r.ok) throw new Error('applyLoadedProject rejected '+file+(r.reason?': '+r.reason:'')); + }; +} + +// Creation-path guards: creation must not produce a project the loader rejects. +function buildGuards(H, note){ + const pk = H.create('ColorPicker4', 40, 40, { colorEditFlags:['NoInputs'] }); + note('ColorPicker4 + colorEditFlags [NoInputs]: '+(pk + ? 'created (flags '+JSON.stringify(pk.colorEditFlags)+')' + : 'refused'+(H.hints().length?' — '+H.hints().join(' / '):''))); +} + +// v3 — a themes.* scene for a theme definition held here. Same sequence as themeScene's +// gate-custom branch (adopt, set themeId, same body), so two defs that differ only in a +// field the build ignores produce the same export. +function customThemeScene(def){ + return function(H){ + const got = H.adoptProjectTheme(JSON.parse(JSON.stringify(def))); + if(got!==def.id) throw new Error('adoptProjectTheme returned '+JSON.stringify(got)); + H.set('themeId', def.id); + buildThemeBody(H); + }; +} + +// v4 — wave-a (B03 3.1). Layout on the pinned 900x700 canvas, default theme. +// Every widget is created with an explicit name (see the header). Creation goes through +// H.create; a type the build lacks is noted N/A and skipped before any create or uid +// draw; a refused create is noted BLOCKED with the tool's own hint. +function waveMake(H, note, t, x, y, ov){ + if(!H.hasType(t)){ note('N/A (build lacks '+t+')'); return null; } + const s = H.create(t, x, y, ov); + if(!s) note('BLOCKED '+t+' '+(ov&&ov.name||'')+' at '+x+','+y+(H.hints().length?' — '+H.hints().join(' / '):'')); + return s; +} +// A child that did not land in its intended parent would change what the scene covers +// without changing any count, so it is reported. +function waveNested(note, child, parent){ + if(child && parent && child.parentId!==parent.id) + note('NOT NESTED '+child.name+' (parentId '+JSON.stringify(child.parentId)+', expected '+parent.name+')'); +} +// [name, x, treeLines in wave-a (undefined = absent)]. Each TreeNode 240x200 at y 20; +// child TreeNode 180x70 at +20,+40 (below the 24 px header); child Button at +20,+140. +const WAVE_A_TREES = [ + ['wa_tree_none', 20, undefined], + ['wa_tree_full', 280, 'full'], + ['wa_tree_tonodes', 540, 'toNodes'], +]; +// [name, x, highlight in wave-a]. Selectables at y 250. +const WAVE_A_SELECTABLES = [ ['wa_sel_plain', 20, undefined], ['wa_sel_hl', 200, true] ]; +const WAVE_A_PLOT_VALUES = [0, 0.5, 1, 0.25, 0.75]; + +// mode: 'wave' — the wave-a values above; +// 'absent' — no new property set anywhere (G5 wave-a reference); +// 'explicit' — every new property set to its default: treeLines 'none' on all six +// TreeNodes (parents and children), highlight false on both Selectables. +function buildWaveATreeSel(H, note, mode){ + for(const [name, x, lines] of WAVE_A_TREES){ + const tree = waveMake(H, note, 'TreeNode', x, 20, { name, w:240, h:200 }); + if(!tree) continue; + const sub = waveMake(H, note, 'TreeNode', x+20, 60, { name:name+'_sub', w:180, h:70 }); + const btn = waveMake(H, note, 'Button', x+20, 160, { name:name+'_btn', w:120, h:20, label:'Btn' }); + waveNested(note, sub, tree); waveNested(note, btn, tree); + if(mode==='wave' && lines!==undefined) tree.treeLines = lines; + if(mode==='explicit'){ tree.treeLines = 'none'; if(sub) sub.treeLines = 'none'; } + } + for(const [name, x, hl] of WAVE_A_SELECTABLES){ + const s = waveMake(H, note, 'Selectable', x, 250, { name, label:name }); + if(!s) continue; + if(mode==='wave' && hl!==undefined) s.highlight = hl; + if(mode==='explicit') s.highlight = false; + } +} + +function buildWaveA(H, note){ + buildWaveATreeSel(H, note, 'wave'); + // Existing types first: the shipped Int N-variants (componentCount 2..4) plus one + // SliderDouble 3. No change is expected here in 1.2.0. + const cc = [ ['SliderInt', 300, 2], ['DragInt', 350, 3], + ['InputInt', 400, 4], ['SliderDouble', 450, 3] ]; + for(const [t, y, n] of cc){ + const s = waveMake(H, note, t, 20, y, { name:'wa_cc_'+t, w:240, label:t+' x'+n }); + if(s) s.componentCount = n; + } + // New types (1.2.0), after everything else. + const cbf = [ ['wa_cbf_opts0', 300, 'opts', 0], ['wa_cbf_opts3', 340, 'opts', 3], + ['wa_cbf_mode0', 380, 'mode', 0] ]; + for(const [name, y, group, bit] of cbf){ + const s = waveMake(H, note, 'CheckboxFlags', 600, y, { name, label:name }); + if(s){ s.flagGroup = group; s.flagBit = bit; } + } + const pl = waveMake(H, note, 'PlotLines', 320, 300, { name:'wa_plot_lines', w:200, h:60, label:'Lines' }); + if(pl){ pl.plotValues = WAVE_A_PLOT_VALUES.slice(); pl.overlay = 'lvl'; pl.scaleMin = 0; pl.scaleMax = 1; } + waveMake(H, note, 'PlotHistogram', 320, 400, { name:'wa_plot_hist', w:200, h:60, label:'Histogram' }); + waveMake(H, note, 'TextLink', 600, 440, { name:'wa_textlink', label:'Link' }); +} +function buildWaveAExplicit(H, note){ buildWaveATreeSel(H, note, 'explicit'); } + +// v5 — text-metrics (ADR-005 X1.0). Shapes are drawn through H.primitive (the editor's +// release path), then the text properties are set on the live shape. A dark fill gives the +// rect/circle labels the light label colour, a light fill the dark one — both appear. +const TM_LONG = 'The quick brown fox jumps over the lazy dog, then naps in the sun.'; +const TM_CYR = 'Съешь же ещё этих мягких французских булок, да выпей чаю.'; +// [kind, name, x, y, w, h, props] +const TEXT_METRICS_SHAPES = [ + ['rect', 'tm_r_short', 20, 20, 160, 40, { label:'OK', textSize:12, align:'center', fill:'#26323c' }], + ['rect', 'tm_r_left', 200, 20, 160, 90, { label:TM_LONG, textSize:12, align:'left', fill:'#26323c' }], + ['rect', 'tm_r_center', 380, 20, 160, 90, { label:TM_LONG, textSize:12, align:'center', fill:'#26323c' }], + ['rect', 'tm_r_right', 560, 20, 160, 90, { label:TM_LONG, textSize:12, align:'right', fill:'#26323c' }], + ['rect', 'tm_r_newlines', 20, 130, 160, 90, { label:'Line one\nLine two\n\nLine four', textSize:12, align:'left', fill:'#e8ecef' }], + ['rect', 'tm_r_blanks', 200, 130, 160, 60, { label:'Hello world and more blanks', textSize:12, align:'left', fill:'#e8ecef' }], + ['rect', 'tm_r_longword', 380, 130, 120, 60, { label:'Antidisestablishmentarianism', textSize:14, align:'center', fill:'#e8ecef' }], + ['rect', 'tm_r_punct', 560, 130, 140, 60, { label:'alpha,beta,gamma;delta!epsilon?zeta.eta"theta', textSize:12, align:'left', fill:'#e8ecef' }], + ['rect', 'tm_r_cyr', 20, 240, 180, 90, { label:TM_CYR, textSize:12, align:'left', fill:'#26323c' }], + ['rect', 'tm_r_ellipsis', 220, 240, 160, 30, { label:TM_LONG, textSize:12, align:'center', fill:'#26323c' }], + ['rect', 'tm_r_size20', 400, 240, 200, 90, { label:'Big text wraps too', textSize:20, align:'center', fill:'#26323c' }], + ['rect', 'tm_r_size10', 620, 240, 120, 50, { label:'Small text in a small box wraps here', textSize:10, align:'left', fill:'#26323c' }], + ['circle', 'tm_c_circle', 20, 350, 120, 120, { label:TM_LONG, textSize:12, align:'center', fill:'#e8ecef' }], + ['circle', 'tm_c_ellipse', 160, 370, 160, 80, { label:TM_CYR, textSize:10, align:'center', fill:'#26323c' }], + ['text', 'tm_t_single', 340, 350, 200, 20, { label:'Hello', textSize:14, align:'left', vAlign:'top' }], + ['text', 'tm_t_top', 340, 380, 200, 60, { label:TM_LONG, textSize:12, align:'left', vAlign:'top' }], + ['text', 'tm_t_middle', 560, 350, 200, 60, { label:TM_LONG, textSize:12, align:'center', vAlign:'middle' }], + ['text', 'tm_t_bottom', 560, 420, 200, 60, { label:TM_LONG, textSize:12, align:'right', vAlign:'bottom' }], + ['text', 'tm_t_cyr', 20, 490, 160, 60, { label:TM_CYR, textSize:12, align:'left', vAlign:'top' }], + ['text', 'tm_t_newlines', 200, 490, 160, 60, { label:'First line\nSecond line', textSize:14, align:'center', vAlign:'middle' }], + ['text', 'tm_t_overflow', 380, 490, 120, 20, { label:'This sentence is much taller than its box once it wraps', textSize:20, align:'left', vAlign:'top' }], +]; +function buildTextMetrics(H, note){ + for(const [kind, name, x, y, w, h, props] of TEXT_METRICS_SHAPES){ + const s = H.primitive(kind, x, y, x+w, y+h); + if(!s){ note('BLOCKED primitive '+kind+' '+name); continue; } + s.name = name; + Object.assign(s, props); + } +} + +// v6 — wave-b (B05 5.1). Layout on a widened 1100x600 canvas (H.set, as buildProject +// does), default theme. Every widget has an explicit name. Creation goes through +// H.create; a type the build lacks is noted N/A and skipped before any create or uid +// draw; a refused create is noted BLOCKED with the tool's own hint — same helpers as +// wave-a (waveMake, waveNested). +// [name, x, tabButton in wave-b (undefined = absent)]. Each TabBar 280x180 at y 20; its +// two TabItems ("Tab 1"/"Tab 2") are auto-created by H.create (createWidgetAtPoint), +// same as core's tabbar. tabButtonLabel 'Add' is set whenever tabButton is set. +const WAVE_B_TABBARS = [ + ['wb_tabbar_none', 20, undefined], + ['wb_tabbar_leading', 340, 'leading'], + ['wb_tabbar_trailing',660, 'trailing'], +]; +// [name, x, disabled in wave-b]. StyleRegion 200x120 at y 220; each holds one Button +// (interior +20,+40) and one SliderInt (interior +20,+80). The second also gets +// styleText, to cover the push order (B4). +const WAVE_B_STYLEREGIONS = [ + ['wb_sr_off', 20, undefined], + ['wb_sr_on', 260, true], +]; +// [name, x, freezeHeader in wave-b (undefined = absent), scrollY]. Table 320x200 at +// y 380; headersRow true on all three (freezeHeader is only meaningful with it). +const WAVE_B_TABLES = [ + ['wb_table_freeze_scrolly', 20, undefined, true], + ['wb_table_freeze_on_scrolly',380, true, true], + ['wb_table_freeze_on_noscroll',740, true, false], +]; +// mode: 'wave' — the wave-b values above; +// 'absent' — no new property set anywhere (G5 wave-b reference); +// 'explicit' — every new property set to its default: tabButton 'none' on all +// three TabBars, disabled false on both StyleRegions, freezeHeader +// false on all three Tables. +function buildWaveBTabSrTable(H, note, mode){ + for(const [name, x, btn] of WAVE_B_TABBARS){ + const tb = waveMake(H, note, 'TabBar', x, 20, { name, w:280, h:180 }); + if(!tb) continue; + if(mode==='wave' && btn!==undefined){ tb.tabButton = btn; tb.tabButtonLabel = 'Add'; } + if(mode==='explicit') tb.tabButton = 'none'; + } + for(const [name, x, dis] of WAVE_B_STYLEREGIONS){ + const sr = waveMake(H, note, 'StyleRegion', x, 220, { name, w:200, h:120 }); + if(!sr) continue; + const btn = waveMake(H, note, 'Button', x+20, 260, { name:name+'_btn', w:120, h:20, label:'Btn' }); + const sl = waveMake(H, note, 'SliderInt', x+20, 300, { name:name+'_sl', w:120 }); + waveNested(note, btn, sr); waveNested(note, sl, sr); + if(mode==='wave' && dis!==undefined){ sr.disabled = dis; if(name==='wb_sr_on') sr.styleText = '#c0ffee'; } + if(mode==='explicit') sr.disabled = false; + } + for(const [name, x, freeze, scrollY] of WAVE_B_TABLES){ + const t = waveMake(H, note, 'Table', x, 380, { name, w:320, h:200 }); + if(!t) continue; + t.headersRow = true; + t.tableFlags = Object.assign({}, t.tableFlags, { ScrollY: scrollY }); + if(mode==='wave' && freeze!==undefined) t.freezeHeader = freeze; + if(mode==='explicit') t.freezeHeader = false; + } +} +function buildWaveB(H, note){ + H.set('cw', 1100); H.set('ch', 600); + buildWaveBTabSrTable(H, note, 'wave'); + // The new type last (as wave-a): created before the existing types it would take the + // first uid and shift every normalised seed id and auto-name after it. Free spot: + // right of the StyleRegions (x 20-460), above the Tables (y 380). + waveMake(H, note, 'InvisibleButton', 500, 220, { name:'wb_invisible', w:120, h:40 }); +} +function buildWaveBExplicit(H, note){ + H.set('cw', 1100); H.set('ch', 600); + buildWaveBTabSrTable(H, note, 'explicit'); +} + +// v7 — tables-b (B06 6.1, ADR-011 G2/G4). Layout on a widened 1200x800 canvas (H.set), +// default theme. Every table has an explicit name and 3 columns of clearly different +// label widths, so a wrong maxW (ADR-011 fact 3) would show in the REAPER pass. Tables +// sit two per row (600 px pitch), 560x220 boxes at y 20 / 300 / 580 (coordinator review: +// comment corrected; the text-metrics newline labels restored to v6's text). +// [name, x, y, angledHeaders in tables-b (undefined = absent), scrollY, headersRow, +// rowCount, scrollRows in tables-b (undefined = absent), freezeHeader] +const TABLES_B = [ + ['tb_angled_scroll', 20, 20, [0,2], true, true, 6, undefined, undefined], + ['tb_angled_all', 620, 20, [0,1,2], false, true, 4, undefined, undefined], + ['tb_scroll_plain', 20, 300, undefined, true, true, 4, undefined, undefined], + ['tb_scrollrows', 620, 300, undefined, true, true, 4, 20, true], + ['tb_angled_noheader', 20, 580, [1], false, false,4, undefined, undefined], + ['tb_scrollrows_noscroll',620,580, undefined, false,true, 4, 20, undefined], +]; +// Column labels of clearly different widths, reused on every table (only the angled +// tables' labels are ever measured for maxW, but a uniform set keeps the scene simple). +const TABLES_B_COLUMNS = ['Gain', 'Pan', 'Output routing']; + +// v8 — menus (B07 7.1, ADR-007). A menu bar is project data, not a shape: the scenes build +// widgets through H.create, save, add `menuBar` to the saved object, reset and load it back +// (withMenuBar), so a build that does not know the key still builds the scene. +const MENUS_CANVAS = { cw:700, ch:300 }; +const MENUS_FIXTURE = [ + { type:'menu', name:'mb_file', label:'File', items:[ + { type:'item', name:'mb_file_new', label:'New', shortcut:'Ctrl+N' }, + { type:'item', name:'mb_file_open', label:'Open…', shortcut:'Ctrl+O' }, + { type:'item', name:'mb_file_open2', label:'Open…' }, + { type:'separator' }, + { type:'menu', name:'mb_file_recent', label:'Recent', items:[ + { type:'item', name:'mb_recent_a', label:'Project A' }, + { type:'menu', name:'mb_recent_more', label:'More', items:[ + { type:'menu', name:'mb_recent_deep', label:'Deep', items:[ + { type:'item', name:'mb_recent_deep_item', label:'Deepest item' }, + ]}, + ]}, + ]}, + { type:'separator' }, + { type:'item', name:'mb_file_quit', label:'Quit', shortcut:'Ctrl+Q', enabled:false }, + ]}, + { type:'menu', name:'mb_view', label:'View', items:[ + { type:'check', name:'mb_view_grid', label:'Show grid', checked:true }, + { type:'check', name:'mb_view_snap', label:'Snap', shortcut:'S' }, + { type:'check', name:'mb_view_locked', label:'Locked', enabled:false }, + ]}, + { type:'menu', name:'mb_edit', label:'Edit', enabled:false, items:[ + { type:'item', name:'mb_edit_undo', label:'Undo' }, + ]}, + { type:'menu', name:'mb_help', label:'Help', items:[] }, +]; + +// findMenuByName: depth-first search for an entry by name, used to attach +// MENUS_WITH_INVALID's extra entries to the right parent's items array. +function findMenuByName(tree, name){ + for(const e of tree){ + if(e.name===name) return e; + if(e.items){ const r = findMenuByName(e.items, name); if(r) return r; } + } + return null; +} +// MENUS_WITH_INVALID: MENUS_FIXTURE plus entries the 1.6.0 loader must drop or change +// (ADR-007 M2). Each entry's comment says why. +const MENUS_WITH_INVALID = (function(){ + const tree = JSON.parse(JSON.stringify(MENUS_FIXTURE)); + // top level holds menus only. + tree.push({ type:'item', name:'mb_top_item', label:'Top item' }); + const view = findMenuByName(tree, 'mb_view'); + view.items.push({ type:'bogus', name:'mb_bogus', label:'?' }); // unknown type + view.items.push({ type:'item', name:'mb_empty', label:'' }); // empty label + view.items.push({ type:'item', name:'mn_origin', label:'Clash' }); // name taken by a widget + view.items.push({ type:'item', name:'mb_view_grid', label:'Dup name' }); // name taken by an earlier entry + view.items.push({ type:'item', name:'mb_hash', label:'Save##x' }); // kept, label cut at `##` -> `Save` + const deep = findMenuByName(tree, 'mb_recent_deep'); + deep.items.push({ type:'menu', name:'mb_too_deep', label:'Too deep', // depth 5, dropped with its items + items:[ { type:'item', name:'mb_too_deep_item', label:'x' } ] }); + return tree; +})(); + +// menusExplicitDefaults: MENUS_FIXTURE with every default written out explicitly +// (enabled:true, shortcut:'', checked:false) instead of left absent. +function menusExplicitDefaults(tree){ + const clone = JSON.parse(JSON.stringify(tree)); + (function walk(items){ + for(const e of items){ + if(e.type==='menu' || e.type==='item' || e.type==='check'){ + if(e.enabled===undefined) e.enabled = true; + } + if(e.type==='item' || e.type==='check'){ + if(e.shortcut===undefined) e.shortcut = ''; + } + if(e.type==='check'){ + if(e.checked===undefined) e.checked = false; + } + if(e.items) walk(e.items); + } + })(clone); + return clone; +} + +// mode: 'wave' — the tables-b values above (angledHeaders / scrollRows per row); +// 'absent' — no new property set anywhere (G5 tables-b reference); +// 'explicit' — angledHeaders:[] and scrollRows:0 set explicitly on every table +// (the defaults ADR-011 G2/G4 specify). +function buildTablesB(H, note, mode){ + for(const [name, x, y, angled, scrollY, headersRow, rowCount, scrollRows, freeze] of TABLES_B){ + const t = waveMake(H, note, 'Table', x, y, { name, w:560, h:220 }); + if(!t) continue; + t.columns = TABLES_B_COLUMNS.slice(); + t.headersRow = headersRow; + t.tableFlags = Object.assign({}, t.tableFlags, { ScrollY: scrollY }); + if(rowCount && rowCount !== t.rowCount) H.resizeTable(t, rowCount); + if(freeze !== undefined) t.freezeHeader = freeze; + if(mode==='wave'){ + if(angled !== undefined) t.angledHeaders = angled.slice(); + if(scrollRows !== undefined) t.scrollRows = scrollRows; + } else if(mode==='explicit'){ + t.angledHeaders = []; + t.scrollRows = 0; + } + // tb_angled_scroll: one Button nested in cell r0c0, captured by the tool's own + // cell placement (as core does with its Text-in-cell, wave*'s waveNested pattern). + if(name==='tb_angled_scroll'){ + const c = H.cellAt(t.id, 0, 0); + if(!c){ note('NO CELL r0c0 on '+name); } + else { + const btn = waveMake(H, note, 'Button', H.absX(c)+4, H.absY(c)+4, { name:name+'_btn', w:60, h:20, label:'Go' }); + waveNested(note, btn, c); + } + } + } +} +function buildTablesB_(H, note){ H.set('cw', 1200); H.set('ch', 520 + 280); buildTablesB(H, note, 'wave'); } +function buildTablesBExplicit(H, note){ H.set('cw', 1200); H.set('ch', 520 + 280); buildTablesB(H, note, 'explicit'); } + +// v8 — menus scene helpers (B07 7.1). withMenuBar round-trips the current project +// through Save -> add `menuBar` -> reset -> Load, so a build that does not know the +// key still builds the scene (menu data lives only in the saved/loaded project, never +// set on a live shape). +function withMenuBar(H, menuBar){ + const p = JSON.parse(H.saveText()); + if(menuBar !== undefined) p.menuBar = JSON.parse(JSON.stringify(menuBar)); + H.reset(); + const r = H.loadText(JSON.stringify(p)); + if(!r.ok) throw new Error('applyLoadedProject rejected the menus project'+(r.reason?': '+r.reason:'')); + return r; +} +// Widgets first (explicit names), at y = 0 so a moved canvas origin would show. +function buildMenusWidgets(H, note){ + H.set('cw', MENUS_CANVAS.cw); H.set('ch', MENUS_CANVAS.ch); + waveMake(H, note, 'Button', 0, 0, { name:'mn_origin', w:120, h:20, label:'Origin' }); + waveMake(H, note, 'Checkbox', 240, 0, { name:'mn_check' }); + waveMake(H, note, 'SliderInt', 0, 40, { name:'mn_slider', w:200 }); +} +function buildMenusScene(menuBar, theme){ + return function(H, note){ + if(theme) H.set('themeId', theme); + buildMenusWidgets(H, note); + const r = withMenuBar(H, menuBar); + if(r.reason) note('loader: '+r.reason.replace(/\s+/g,' ').trim()); + }; +} + +// v9 — add project-level keys to a saved project and load it back (withMenuBar's pattern, +// any keys). A build that does not know a key ignores it. +function withProjectKeys(H, keys){ + const p = JSON.parse(H.saveText()); + Object.assign(p, JSON.parse(JSON.stringify(keys))); + H.reset(); + const r = H.loadText(JSON.stringify(p)); + if(!r.ok) throw new Error('applyLoadedProject rejected the project'+(r.reason?': '+r.reason:'')); + return r; +} + +// v9 — themes.slate-title / themes.slate-title.explicit-default (B07 7.3, ADR-007 M11). +// The compact themes.* body under `slate`, with `themedTitleBar` added to the saved +// project through withProjectKeys — true for the "on" scene, false (the explicit +// default) for the reference scene G5 title compares it against. +function buildSlateTitleScene(themedTitleBar){ + return function(H, note){ + H.set('themeId', 'slate'); + buildThemeBody(H); + const r = withProjectKeys(H, { themedTitleBar }); + if(r.reason) note('loader: '+r.reason.replace(/\s+/g,' ').trim()); + }; +} +// v9 — menus.themed-title (B07 7.3, ADR-007 M11). The menus widgets under `slate`, with +// both `menuBar` and `themedTitleBar:true` added in one withProjectKeys call. +function buildMenusThemedTitleScene(){ + return function(H, note){ + H.set('themeId', 'slate'); + buildMenusWidgets(H, note); + const r = withProjectKeys(H, { menuBar: MENUS_FIXTURE, themedTitleBar:true }); + if(r.reason) note('loader: '+r.reason.replace(/\s+/g,' ').trim()); + }; +} + +// v10 — arcs (B11 11.1; F04 coverage after the fact, B10 review R1). Each arc is drawn through +// H.primitive('arc', ...) (the editor's release path), then name and properties are set on the +// live shape, as text-metrics does. Canvas 800x560, default theme. Frozen table: +// [name, x, y, w, h, props]; 3 rows of 5, column x = 20 + col*155, row y = 20 / 180 / 340, +// boxes 120x120 unless stated. Arcs only, no labels; fill and stroke colours stay at the +// defaults the creation path gives; names are explicit (nothing depends on running counters). +const ARCS_CANVAS = { cw:800, ch:560 }; +const ARCS_SHAPES = [ + // row 1 (y 20) + ['ar_pie_90', 20, 20, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:90 }], // convex, unchanged by F04 + ['ar_pie_180', 175, 20, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:180 }], // convex boundary + ['ar_pie_270', 330, 20, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:270 }], // concave fill (fill + stroke) + ['ar_pie_wrap', 485, 20, 120, 120, { arcMode:'pie', angleStart:300, angleEnd:60 }], // crosses 0: 120 deg clockwise + ['ar_pie_full', 640, 20, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:360 }], // full turn: no centre point + // row 2 (y 180) + ['ar_pie_equal', 20, 180, 120, 120, { arcMode:'pie', angleStart:45, angleEnd:45 }], // empty sweep + ['ar_pie_neg', 175, 180, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:-90 }], // negative end: 270 deg clockwise, concave + ['ar_pie_big', 330, 180, 120, 120, { arcMode:'pie', angleStart:720, angleEnd:810 }], // angles past one turn: 90 deg + ['ar_pie_fill_only', 485, 180, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:270, strokeNone:true }], // concave fill, no stroke + ['ar_pie_stroke_only',640, 180, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:270, fillNone:true }], // stroke only + // row 3 (y 340) + ['ar_pie_alpha', 20, 340, 120, 120, { arcMode:'pie', angleStart:0, angleEnd:270, opacity:128, thickness:6 }], // concave fill with alpha, thick stroke + ['ar_ring_neg', 175, 340, 120, 120, { arcMode:'ring', angleStart:0, angleEnd:-90 }], // open arc, clockwise sweep + ['ar_ring_full', 330, 340, 120, 120, { arcMode:'ring', angleStart:0, angleEnd:360 }], // open arc, full turn + ['ar_ring_nostroke', 485, 340, 120, 120, { arcMode:'ring', angleStart:0, angleEnd:270, strokeNone:true }], // nothing to draw: emits nothing on dev.12 + ['ar_pie_ellipse', 640, 340, 140, 80, { arcMode:'pie', angleStart:30, angleEnd:250 }], // non-square box (radius = min(w, h)/2), concave +]; +function buildArcs(H, note){ + H.set('cw', ARCS_CANVAS.cw); H.set('ch', ARCS_CANVAS.ch); + for(const [name, x, y, w, h, props] of ARCS_SHAPES){ + const s = H.primitive('arc', x, y, x+w, y+h); + if(!s){ note('BLOCKED primitive arc '+name); continue; } + s.name = name; + Object.assign(s, props); + } +} + +// v11 — adaptive scenes (A01, ADR-009 AD11). Fixture first (ADR-002 G6): the harness learns +// `pinH` / `pinV` (per shape) and `windowResize` (per project) before the builder knows them. +// Pins and project keys never touch live shapes: withAdaptive writes them into the SAVED +// project and loads it back, so a build that does not know them shows what its loader does +// with them (1.7.0-dev.3 keeps unknown shape keys and drops unknown project keys). +// +// Body A — a 640x440 form. [name, type, x, y, overrides, parent name | null]. Absolute +// canvas coordinates, passed to H.create (which nests a widget into the container under it); +// a container is created before its children. Every shape has an explicit name. +const ADAPTIVE_BODY_A = [ + ['ad_title', 'Text', 20, 10, { w:200, label:'Adaptive' }, null], + ['ad_close', 'Button', 520, 10, { w:100, h:20, label:'Close' }, null], + ['ad_input', 'InputText', 20, 50, { w:380 }, null], + ['ad_combo', 'Combo', 440, 50, { w:180 }, null], + ['ad_center', 'Button', 270, 90, { w:100, h:24, label:'Center' }, null], + ['ad_slider', 'SliderDouble',440, 90, { w:180 }, null], + ['ad_panel', 'Panel', 20, 130, { w:600, h:200 }, null], + ['ad_p_btn', 'Button', 30, 140, { w:80, h:20, label:'Inner' }, 'ad_panel'], + ['ad_p_list', 'ListBox', 30, 180, { w:280, h:110 }, 'ad_panel'], + ['ad_p_grp', 'Group', 340, 180, { w:170, h:100 }, 'ad_panel'], + ['ad_g_btn', 'Button', 360, 230, { w:100, h:20, label:'Grouped' }, 'ad_p_grp'], + ['ad_p_ok', 'Button', 520, 300, { w:90, h:20, label:'Apply' }, 'ad_panel'], + ['ad_progress', 'ProgressBar', 20, 350, { w:600, h:20 }, null], + ['ad_status', 'Text', 20, 400, { w:240, label:'Status' }, null], + ['ad_cancel', 'Button', 410, 400, { w:100, h:20, label:'Cancel' }, null], + ['ad_ok', 'Button', 520, 400, { w:100, h:20, label:'OK' }, null], +]; +// Pin sets: { : { pinH?, pinV? } }. +const ADAPTIVE_PINS_MOVE = { + ad_close: { pinH:'right' }, + ad_combo: { pinH:'right' }, + ad_center: { pinH:'center' }, + ad_slider: { pinH:'right', pinV:'center' }, + ad_panel: { pinV:'bottom' }, + ad_p_grp: { pinH:'right' }, + ad_g_btn: { pinH:'center' }, + ad_p_ok: { pinH:'right', pinV:'bottom' }, + ad_status: { pinV:'bottom' }, + ad_cancel: { pinH:'right', pinV:'bottom' }, + ad_ok: { pinH:'right', pinV:'bottom' }, +}; +const ADAPTIVE_PINS_STRETCH = { // applied after MOVE; a key here overrides MOVE's + ad_input: { pinH:'stretch' }, + ad_panel: { pinH:'stretch', pinV:'stretch' }, + ad_p_list: { pinH:'stretch', pinV:'stretch' }, + ad_progress: { pinH:'stretch' }, +}; +// Body N pins (the table of the brief, column "pins"). +const ADAPTIVE_PINS_NESTED = { + ad_n_sr: { pinH:'stretch' }, + ad_n_sr_sl: { pinH:'right' }, + ad_n_sr_bt: { pinH:'center' }, + ad_n_tabs: { pinH:'stretch', pinV:'stretch' }, + ad_n_tab_bt: { pinH:'right', pinV:'bottom' }, + ad_n_tree: { pinH:'right' }, + ad_n_tree_bt: { pinH:'center' }, + ad_n_pan: { pinV:'bottom' }, + ad_n_pan_in: { pinH:'stretch' }, + ad_n_pan_bt: { pinH:'right' }, + ad_n_tbl: { pinH:'right', pinV:'bottom' }, + ad_n_hdr: { pinV:'bottom' }, + ad_n_hdr_bt: { pinH:'right' }, +}; +// Body P: [kind, name, x1, y1, x2, y2, props] through H.primitive, then name and props are +// set on the live shape (as buildTextMetrics does). +const ADAPTIVE_PRIMS = [ + ['rect', 'ad_r', 20, 20, 220, 80, { label:'Rect label that wraps at runtime', textSize:14 }], + ['text', 'ad_t', 20, 100, 320, 140, { label:'Text primitive that wraps inside its box', textSize:12, align:'left', vAlign:'top' }], + ['circle', 'ad_c', 520, 20, 600, 100, { label:'C' }], + ['arc', 'ad_a', 280, 180, 360, 260, {}], + ['line', 'ad_l', 20, 300, 220, 340, {}], + ['poly', 'ad_p', 420, 300, 520, 380, {}], + ['triangle', 'ad_tri',260, 320, 340, 400, {}], +]; +const ADAPTIVE_PINS_PRIMS = { + ad_r: { pinH:'stretch', pinV:'center' }, + ad_t: { pinH:'stretch' }, + ad_c: { pinH:'right' }, + ad_a: { pinH:'center', pinV:'center' }, + ad_l: { pinV:'bottom' }, + ad_p: { pinH:'right', pinV:'bottom' }, + ad_tri: { pinH:'center' }, + ad_pr_bt: { pinH:'right' }, +}; +// Body M: buildMenusWidgets + MENUS_FIXTURE (the v8 data, unchanged). +const ADAPTIVE_PINS_MENUS = { + mn_origin: { pinH:'right' }, + mn_check: { pinH:'right' }, + mn_slider: { pinV:'bottom' }, +}; +// adaptive.invalid: values ADR-009 AD1, AD2 and AD4 make the loader drop (maxH:2000 is kept). +// The TabItem and TableCell have no name of their own; buildAdaptiveInvalid finds them. +const ADAPTIVE_PINS_INVALID = { + ad_title: { pinH:'up' }, + ad_close: { pinV:5, pinH:'RIGHT' }, + ad_combo: { pinH:'left' }, + ad_slider: { pinV:'stretch' }, // a native-height control: stretch refused by AD4 + ad_p_grp: { pinH:null }, +}; +const ADAPTIVE_WINDOW_INVALID = { minW:10, minH:'x', maxW:100, maxH:2000 }; + +// withAdaptive(H, pins, keys, note, edit): the pattern of withProjectKeys. +// 1. p = the saved project; +// 2. for every [name, props] of `pins`, Object.assign the props onto the shape named `name` +// in p.shapes (undefined values are not set; a missing name is noted `MISSING `); +// 3. `edit(p)`, when given, may change p further (shapes that have no name of their own); +// 4. Object.assign(p, keys) (undefined values are not set), then reset and Load. A rejected +// load throws, as withProjectKeys does; a loader message is noted as `loader: …`. +// `note` is the scene's note function (MISSING and loader notes go through it). +function withAdaptive(H, pins, keys, note, edit){ + const defined = o => Object.fromEntries(Object.entries(o || {}).filter(([, v]) => v !== undefined)); + const p = JSON.parse(H.saveText()); + for(const [name, props] of Object.entries(pins || {})){ + const s = p.shapes.find(sh => sh.name === name); + if(!s){ note('MISSING '+name); continue; } + Object.assign(s, defined(props)); + } + if(edit) edit(p); + Object.assign(p, JSON.parse(JSON.stringify(defined(keys)))); + H.reset(); + const r = H.loadText(JSON.stringify(p)); + if(!r.ok) throw new Error('applyLoadedProject rejected the adaptive project'+(r.reason?': '+r.reason:'')); + if(r.reason) note('loader: '+r.reason.replace(/\s+/g,' ').trim()); + return r; +} + +// Body A, on a 640 x canvasH canvas (440; 560 for adaptive.invalid). Returns { name: shape }. +function buildAdaptiveBody(H, note, canvasH){ + H.set('cw', 640); H.set('ch', canvasH); + const made = {}; + for(const [name, type, x, y, ov, parent] of ADAPTIVE_BODY_A){ + const s = waveMake(H, note, type, x, y, Object.assign({ name }, ov)); + if(!s) continue; + made[name] = s; + if(parent) waveNested(note, s, made[parent]); + } + return made; +} +// 'move' = MOVE; 'move+stretch' = MOVE then STRETCH (a key in STRETCH overrides MOVE's); +// 'move+explicit' = MOVE plus {pinH:'left', pinV:'top'} on every Body A shape for each key +// MOVE leaves unset; null = no pins. +function adaptivePins(pinSet){ + const out = {}; + const put = src => { for(const [n, pr] of Object.entries(src)) out[n] = Object.assign(out[n] || {}, pr); }; + switch(pinSet){ + case null: break; + case 'move': put(ADAPTIVE_PINS_MOVE); break; + case 'move+stretch': put(ADAPTIVE_PINS_MOVE); put(ADAPTIVE_PINS_STRETCH); break; + case 'move+explicit': + for(const row of ADAPTIVE_BODY_A) out[row[0]] = { pinH:'left', pinV:'top' }; + put(ADAPTIVE_PINS_MOVE); + break; + default: throw new Error('adaptivePins: unknown pin set '+pinSet); + } + return out; +} +// windowResize === null: no `windowResize` key at all; otherwise the key is set to it. +function adaptiveScene(body, pinSet, windowResize){ + return function(H, note){ + if(body !== 'A') throw new Error('adaptiveScene: unknown body '+body); + buildAdaptiveBody(H, note, 440); + withAdaptive(H, adaptivePins(pinSet), windowResize === null ? {} : { windowResize }, note); + }; +} + +// Body N — containers and what they hold, 640x520, `windowResize: {}`. +function buildAdaptiveNested(H, note){ + H.set('cw', 640); H.set('ch', 520); + const mk = (t, name, x, y, ov, parent) => { + const s = waveMake(H, note, t, x, y, Object.assign({ name }, ov)); + if(s && parent) waveNested(note, s, parent); + return s; + }; + const sr = mk('StyleRegion', 'ad_n_sr', 20, 20, { w:600, h:110 }); + mk('SliderDouble', 'ad_n_sr_sl', 40, 60, { w:200 }, sr); + mk('Button', 'ad_n_sr_bt', 300, 90, { w:100, h:20, label:'Mid' }, sr); + const tabs = mk('TabBar', 'ad_n_tabs', 20, 150, { w:380, h:160 }); + const tabBt = mk('Button', 'ad_n_tab_bt', 40, 260, { w:100, h:20, label:'InTab' }); + if(tabBt && tabs){ + // The parent must be the TabBar's active TabItem. + const ti = H.shapes().find(s => s.widgetType==='TabItem' && s.parentId===tabs.id && s.id===tabs.activeTabId); + if(ti) waveNested(note, tabBt, ti); + else note('NOT NESTED ad_n_tab_bt (active TabItem of ad_n_tabs not found)'); + } + const tree = mk('TreeNode', 'ad_n_tree', 420, 150, { w:200, h:160 }); + mk('Button', 'ad_n_tree_bt', 440, 220, { w:120, h:20, label:'InTree' }, tree); + const pan = mk('Panel', 'ad_n_pan', 20, 330, { w:380, h:80 }); + const panIn = mk('Panel', 'ad_n_pan_in', 30, 340, { w:180, h:60 }, pan); + mk('Button', 'ad_n_pan_bt', 40, 350, { w:80, h:20, label:'Deep' }, panIn); + const tbl = mk('Table', 'ad_n_tbl', 420, 330, { w:200, h:80 }); + if(tbl){ + const cells = H.cellsOf(tbl.id); // centre of the first cell, as buildCore does + if(cells.length){ + const c = cells[0]; + mk('Text', 'ad_n_tbl_txt', H.absX(c)+c.w/2-10, H.absY(c)+c.h/2-6, { w:20, h:12 }, c); + } else note('NOT NESTED ad_n_tbl_txt (the table has no cells)'); + } + const hdr = mk('CollapsingHeader', 'ad_n_hdr', 20, 430, { w:600, h:80 }); + mk('Button', 'ad_n_hdr_bt', 40, 470, { w:100, h:20, label:'InHeader' }, hdr); + withAdaptive(H, ADAPTIVE_PINS_NESTED, { windowResize:{} }, note); +} + +// Body P — seven primitives and one widget, 640x440, `windowResize: {}`. +function buildAdaptivePrimitives(H, note){ + H.set('cw', 640); H.set('ch', 440); + for(const [kind, name, x1, y1, x2, y2, props] of ADAPTIVE_PRIMS){ + const s = H.primitive(kind, x1, y1, x2, y2); + if(!s){ note('BLOCKED primitive '+kind+' '+name); continue; } + s.name = name; + Object.assign(s, props); + } + waveMake(H, note, 'Button', 420, 200, { name:'ad_pr_bt', w:100, h:20, label:'Btn' }); + withAdaptive(H, ADAPTIVE_PINS_PRIMS, { windowResize:{} }, note); +} + +// Body M — the v8 menus widgets and MENUS_FIXTURE, `windowResize: { maxW: 1000 }`. +function buildAdaptiveMenus(H, note){ + buildMenusWidgets(H, note); + withAdaptive(H, ADAPTIVE_PINS_MENUS, { menuBar: MENUS_FIXTURE, windowResize:{ maxW:1000 } }, note); +} + +// adaptive.invalid — Body A on a 640x560 canvas plus a TabBar and a Table, then every invalid +// value. The first TabItem and the first TableCell are parent-managed: found in p.shapes by +// widgetType and parentId (a MISSING note if absent). +function buildAdaptiveInvalid(H, note){ + buildAdaptiveBody(H, note, 560); + waveMake(H, note, 'TabBar', 20, 450, { name:'ad_i_tabs', w:300, h:100 }); + waveMake(H, note, 'Table', 340, 450, { name:'ad_i_tbl', w:280, h:100 }); + withAdaptive(H, ADAPTIVE_PINS_INVALID, { windowResize: ADAPTIVE_WINDOW_INVALID }, note, p => { + const firstChild = (parentName, widgetType, props, label) => { + const par = p.shapes.find(s => s.name === parentName); + const kid = par && p.shapes.find(s => s.widgetType === widgetType && s.parentId === par.id); + if(kid) Object.assign(kid, props); else note('MISSING '+label); + }; + firstChild('ad_i_tabs', 'TabItem', { pinH:'right' }, 'first TabItem of ad_i_tabs'); + firstChild('ad_i_tbl', 'TableCell', { pinV:'bottom' }, 'first TableCell of ad_i_tbl'); + }); +} + +// v12 — tables-c scenes (A07.1, ADR-002 G6). Fixture first: the harness learns the 2.1.0 Table +// properties (`cellPadding`, `rowBg`, `highlightColor`, `highlightRows`, `rowsFill`), the +// StyleRegion property `styleFramePadding` and Table stretch pins before the builder knows them. +// Tables are built through H.create and then mutated on the live shape (the wave-b / tables-b +// pattern); pins and `windowResize` go through withAdaptive (the v11 pattern), so a build that +// does not know a property still builds every scene. Canvas 640x480, default theme. +// +// tcCellMake: H.cellChild plus the harness notes (N/A, BLOCKED, NOT NESTED) in waveMake's words. +function tcCellMake(H, note, tableName, r, c, type, x, y, ov){ + if(!H.hasType(type)){ note('N/A (build lacks '+type+')'); return null; } + const s = H.cellChild(tableName, r, c, type, x, y, ov); + const n = H.cellChildNote(); + if(n) note(n); + else if(!s) note('BLOCKED '+type+' '+(ov&&ov.name||'')+' in '+tableName+' r'+r+'c'+c+(H.hints().length?' — '+H.hints().join(' / '):'')); + return s; +} +// Column sizing as the inspector stores it: { sizing:'fixed'|'stretch', value }. +const TC_FIXED = v => ({ sizing:'fixed', value:v }); +const TC_STRETCH = { sizing:'stretch', value:1 }; + +// tables-c.stretch: three tables, [name, x, y, w, h]. Pins: tc_list Left+Right + Top+Bottom +// (pinH + pinV 'stretch'), tc_hdr Left+Right only (pinH 'stretch'), tc_plain Top+Bottom only +// (pinV 'stretch'). tc_list's cell children are named tc_list_rc; the pinned ones are +// tc_list_btn (r0c2, pinH 'right') and tc_list_wrap (r1c2, pinH 'stretch'). +const TABLES_C_STRETCH = { + list: ['tc_list', 20, 20, 600, 200], + hdr: ['tc_hdr', 20, 232, 600, 110], + plain: ['tc_plain', 20, 354, 600, 110], +}; +const TABLES_C_STRETCH_PINS = { + tc_list: { pinH:'stretch', pinV:'stretch' }, + tc_list_btn: { pinH:'right' }, + tc_list_wrap: { pinH:'stretch' }, + tc_hdr: { pinH:'stretch' }, + tc_plain: { pinV:'stretch' }, +}; +function buildTablesCStretch(H, note){ + H.set('cw', 640); H.set('ch', 480); + // tc_list: 4 columns fixed 20 / fixed 30 / stretch / fixed 64, no header, ScrollY, 5 rows fixed at 24. + const [ln, lx, ly, lw, lh] = TABLES_C_STRETCH.list; + const list = waveMake(H, note, 'Table', lx, ly, { name:ln, w:lw, h:lh }); + if(list){ + list.columns = ['A', 'B', 'C', 'D']; + list.columnConfig = [TC_FIXED(20), TC_FIXED(30), Object.assign({}, TC_STRETCH), TC_FIXED(64)]; + list.headersRow = false; + list.tableFlags = Object.assign({}, list.tableFlags, { ScrollY:true }); + list.rowHeights = [24, 24, 24, 24, 24]; + H.resizeTable(list, 5, 4); // grows to 5 x 4 and re-flows the cells + for(let r = 0; r < 5; r++){ + tcCellMake(H, note, ln, r, 0, 'ColorButton', 2, 4, { name:'tc_list_r'+r+'c0', w:16, h:16 }); + tcCellMake(H, note, ln, r, 1, 'Text', 4, 4, { name:'tc_list_r'+r+'c1', w:22, label:String(r+1) }); + tcCellMake(H, note, ln, r, 2, 'Text', 4, 4, { name:'tc_list_r'+r+'c2', w:120, label:'Region '+(r+1) }); + tcCellMake(H, note, ln, r, 3, 'TextDisabled', 4, 4, { name:'tc_list_r'+r+'c3', w:56, label:'00:0'+r }); + } + tcCellMake(H, note, ln, 0, 2, 'Button', 380, 2, { name:'tc_list_btn', w:70, h:20, label:'Go' }); + tcCellMake(H, note, ln, 1, 2, 'TextWrapped', 130, 4, { name:'tc_list_wrap', w:200, h:16, label:'A longer name that wraps' }); + } + // tc_hdr: 3 columns, header row, ScrollY, rows flexible. + const [hn, hx, hy, hw, hh] = TABLES_C_STRETCH.hdr; + const hdr = waveMake(H, note, 'Table', hx, hy, { name:hn, w:hw, h:hh }); + if(hdr){ + hdr.headersRow = true; + hdr.tableFlags = Object.assign({}, hdr.tableFlags, { ScrollY:true }); + H.resizeTable(hdr, 3); + } + // tc_plain: no ScrollY, rows flexible. + const [pn, px, py, pw, ph] = TABLES_C_STRETCH.plain; + const plain = waveMake(H, note, 'Table', px, py, { name:pn, w:pw, h:ph }); + if(plain) H.resizeTable(plain, 3); + withAdaptive(H, TABLES_C_STRETCH_PINS, { windowResize:{ minW:480, minH:320 } }, note); +} + +// tables-c.style: [name, x, y, w, h]. Fixed window, no `windowResize` key. +const TABLES_C_STYLE = [ + ['tc_pad', 20, 20, 300, 110], + ['tc_bg', 330, 20, 290, 110], + ['tc_hl', 20, 140, 300, 130], + ['tc_nofill', 330, 140, 290, 130], +]; +const TC_ROW_BG = ['#ffe0e0', null, '#e0e8ff']; // rowBg on rows 0 and 2 of tc_bg +// mode: 'values' — the 2.1.0 values (tables-c.style); +// 'absent' — no new property set anywhere (G5 tables-c reference); +// 'explicit' — every new property set to its default: cellPadding [4,2], rowBg [], +// highlightRows [], rowsFill true on every table; highlightColor and +// styleFramePadding left out (they have no default / are nullable). +function buildTablesCStyle(H, note, mode){ + H.set('cw', 640); H.set('ch', 480); + for(const [name, x, y, w, h] of TABLES_C_STYLE){ + const t = waveMake(H, note, 'Table', x, y, { name, w, h }); + if(!t) continue; + if(name === 'tc_hl'){ + t.tableFlags = Object.assign({}, t.tableFlags, { ScrollY:true }); + t.scrollRows = 10; + t.rowCount = 5; + } + if(name === 'tc_nofill'){ + t.tableFlags = Object.assign({}, t.tableFlags, { ScrollY:true }); + t.rowHeights = [24, 24, 24]; + } + if(mode === 'values'){ + if(name === 'tc_pad') t.cellPadding = [4, 4]; + if(name === 'tc_bg') t.rowBg = TC_ROW_BG.slice(); + if(name === 'tc_hl'){ t.highlightColor = '#F1F1F1'; t.highlightRows = [1, 3]; } + if(name === 'tc_nofill') t.rowsFill = false; + } else if(mode === 'explicit'){ + t.cellPadding = [4, 2]; + t.rowBg = []; + t.highlightRows = []; + t.rowsFill = true; + } + H.resizeTable(t, name === 'tc_hl' ? 5 : 3); // re-flow the cells after the mutations + if(name === 'tc_pad'){ + tcCellMake(H, note, name, 0, 0, 'Text', 4, 4, { name:'tc_pad_r0c0', w:60, label:'Padded' }); + tcCellMake(H, note, name, 1, 1, 'Text', 4, 4, { name:'tc_pad_r1c1', w:60, label:'Cell' }); + } + } + // tc_sr: a StyleRegion with styleFramePadding [8,5] holding an InputTextWithHint and a Button. + const sr = waveMake(H, note, 'StyleRegion', 20, 290, { name:'tc_sr', w:600, h:90 }); + if(sr){ + if(mode === 'values') sr.styleFramePadding = [8, 5]; + const inp = waveMake(H, note, 'InputTextWithHint', 40, 326, { name:'tc_sr_in', w:300 }); + waveNested(note, inp, sr); + const btn = waveMake(H, note, 'Button', 360, 326, { name:'tc_sr_btn', w:100, h:20, label:'Go' }); + waveNested(note, btn, sr); + } +} +function buildTablesCStyleScene(H, note){ buildTablesCStyle(H, note, 'values'); } +function buildTablesCExplicit(H, note){ buildTablesCStyle(H, note, 'explicit'); } + +const SCENES = [ + { name:'core', build: buildCore }, + { name:'all-types', build: buildAllTypes }, + { name:'themes.slate', build: themeScene('slate') }, + { name:'themes.light', build: themeScene('light') }, + { name:'themes.gate-custom', build: themeScene(GATE_CUSTOM_THEME.id) }, + { name:'project', build: buildProject }, + ...EXAMPLE_FILES.map(f => ({ name:'examples.'+f.replace(/\.json$/,''), build: exampleScene(f) })), + { name:'guards', build: buildGuards }, + // v3 — after every v2 scene (B02 2.1). Names start with `themes.`, so `--scene themes` + // selects them with the others. + { name:'themes.gate-alpha', build: customThemeScene(GATE_ALPHA_THEME) }, + { name:'themes.gate-alpha-opaque', build: customThemeScene(GATE_ALPHA_OPAQUE_THEME) }, + // v4 — after every v3 scene (B03 3.1). `--scene wave-a` selects both. + { name:'wave-a', build: buildWaveA }, + { name:'wave-a.explicit-defaults', build: buildWaveAExplicit }, + // v5 — after every v4 scene (ADR-005 X1.0). + { name:'text-metrics', build: buildTextMetrics }, + // v6 — after every v5 scene (B05 5.1). `--scene wave-b` selects both. + { name:'wave-b', build: buildWaveB }, + { name:'wave-b.explicit-defaults', build: buildWaveBExplicit }, + // v7 — after every v6 scene (B06 6.1). `--scene tables-b` selects both. + { name:'tables-b', build: buildTablesB_ }, + { name:'tables-b.explicit-defaults', build: buildTablesBExplicit }, + // v8 — after every v7 scene (B07 7.1). `--scene menus` selects all three. + { name:'menus', build: buildMenusScene(MENUS_WITH_INVALID) }, + { name:'menus.themed', build: buildMenusScene(MENUS_WITH_INVALID, 'slate') }, + { name:'menus.explicit-defaults', build: buildMenusScene(menusExplicitDefaults(MENUS_FIXTURE)) }, + // v9 — after every v8 scene (B07 7.3, ADR-007 M11). `--scene themes` picks up the two + // themes.* scenes by prefix; `--scene menus` picks up the third. + { name:'themes.slate-title', build: buildSlateTitleScene(true) }, + { name:'themes.slate-title.explicit-default', build: buildSlateTitleScene(false) }, + { name:'menus.themed-title', build: buildMenusThemedTitleScene() }, + // v10 — after every v9 scene (B11) + { name:'arcs', build: buildArcs }, + // v11 — after every v10 scene (A01, ADR-009 AD11). `--scene adaptive` selects all ten. + { name:'adaptive.base', build: adaptiveScene('A', null, null) }, + { name:'adaptive.inert', build: adaptiveScene('A', 'move+stretch', null) }, + { name:'adaptive.move', build: adaptiveScene('A', 'move', {}) }, + { name:'adaptive.move.explicit-defaults', build: adaptiveScene('A', 'move+explicit', {minW:640, minH:440, maxW:0, maxH:0}) }, + { name:'adaptive.limits', build: adaptiveScene('A', 'move', {minW:520, minH:380, maxW:1200, maxH:900}) }, + { name:'adaptive.stretch', build: adaptiveScene('A', 'move+stretch', {}) }, + { name:'adaptive.nested', build: buildAdaptiveNested }, + { name:'adaptive.primitives', build: buildAdaptivePrimitives }, + { name:'adaptive.menus', build: buildAdaptiveMenus }, + { name:'adaptive.invalid', build: buildAdaptiveInvalid }, + // v12 — after every v11 scene (A07.1). `--scene tables-c` selects all three. + { name:'tables-c.stretch', build: buildTablesCStretch }, + { name:'tables-c.style', build: buildTablesCStyleScene }, + { name:'tables-c.explicit-defaults', build: buildTablesCExplicit }, +]; +const G5_SCENE = 'themes.gate-alpha-opaque', G5_REFERENCE = 'themes.gate-custom'; +const G5W_SCENE = 'wave-a.explicit-defaults'; +const G5W2_SCENE = 'wave-b.explicit-defaults'; +const G5T_SCENE = 'tables-b.explicit-defaults'; +const G5M_SCENE = 'menus.explicit-defaults'; +const G5TT_SCENE = 'themes.slate-title.explicit-default'; +const G5AD_REFERENCE = 'adaptive.move', G5AD_SCENE = 'adaptive.move.explicit-defaults'; // v11 — G5 adaptive +const ADAPTIVE_INERT_SCENE = 'adaptive.inert', ADAPTIVE_BASE_SCENE = 'adaptive.base'; // v11 — adaptive inert +const G5TC_SCENE = 'tables-c.explicit-defaults'; // v12 — G5 tables-c +const CHECKS = [ { name:'theme-library-separation', run: runLibrarySeparation } ]; +// Cross-scene checks: listed by --list, not selectable; each runs with its scene. +const CROSS_CHECKS = [ ['G5 alpha-255', G5_SCENE], ['G5 wave-a', G5W_SCENE], ['G5 wave-b', G5W2_SCENE], ['G5 tables-b', G5T_SCENE], ['G5 menus', G5M_SCENE], ['G5 title', G5TT_SCENE], ['G5 adaptive', G5AD_SCENE], ['adaptive inert', ADAPTIVE_INERT_SCENE], ['G5 tables-c', G5TC_SCENE] ]; + +// ============================================================================ +// Running +// ============================================================================ + +function normSeed(s){ + const map = new Map(); + return s.replace(/"(id|[A-Za-z0-9_]*[Ii]d)"\s*:\s*"([^"]*)"/g, (m, key, val) => { + if(!map.has(val)) map.set(val, ''); + return '"'+key+'":"'+map.get(val)+'"'; + }); +} + +function closeWindow(w){ try{ w.close(); }catch(_){} } + +// One scene in a fresh jsdom instance: build, export twice; reset, rebuild, export; +// then the round-trip on the rebuilt state. +function runScene(htmlPath, scene){ + const res = { name:scene.name, notes:[], problems:[], imgui:null, seed:null, file:null, + stable:true, rt:null, error:null }; + let tool; + try { + tool = loadTool(htmlPath); + const { H, errs } = tool; + const note = t => { if(!res.notes.includes(t)) res.notes.push(t); }; + const build = () => { + H.reset(); + H.pinProblems().forEach(p => note('reset could not pin '+p)); + scene.build(H, note); + }; + build(); + const i1 = H.genImGui(), s1 = H.genSeed(); + const i1b = H.genImGui(), s1b = H.genSeed(); + const f1 = H.saveText(); // v11: the file channel + if(i1!==i1b || s1!==s1b){ res.stable=false; res.problems.push('NON-DETERMINISTIC '+scene.name+' (same state generated twice differs)'); } + build(); + const i2 = H.genImGui(), s2 = H.genSeed(); + if(i1!==i2 || normSeed(s1)!==normSeed(s2)){ res.stable=false; res.problems.push('NON-DETERMINISTIC '+scene.name+' (rebuild after reset differs — reset() leaks state?)'); } + const f2 = H.saveText(); + if(normSeed(f1)!==normSeed(f2)){ res.stable=false; res.problems.push('NON-DETERMINISTIC '+scene.name+' (rebuild after reset differs (file) — reset() leaks state?)'); } + res.imgui = i1; res.seed = s1; res.file = f1; + // G3 round-trip: Save -> fresh reset -> Load -> genImGui == pre-round-trip export. + const saved = H.saveText(); + H.reset(); + const loaded = H.loadText(saved); + if(!loaded.ok){ + res.rt = { ok:false, reason:'loader rejected the saved project'+(loaded.reason?': '+loaded.reason.replace(/\s+/g,' ').trim():'') }; + } else { + const post = H.genImGui(); + if(post===i2) res.rt = { ok:true }; + else { + const d = multisetDiff(i2.split('\n'), post.split('\n')); + res.rt = { ok:false, reason:'export differs after reload (+'+d.added.length+' −'+d.removed.length+')', diff:d }; + } + } + if(errs.length) res.problems.push('window errors in '+scene.name+': '+errs.join(' | ')); + } catch(e){ + if(e instanceof HarnessError) throw e; + res.error = 'THROW '+scene.name+': '+(e&&e.stack||e); + } finally { + if(tool) closeWindow(tool.window); + } + return res; +} + +function runDefaults(htmlPath){ + const tool = loadTool(htmlPath); + try { + const d = tool.H.defaults(); + return ['cw','ch','themeId','bgMode','projectTitle'].map(k => k+'='+JSON.stringify(d[k])).join(' '); + } finally { closeWindow(tool.window); } +} + +// v3 — ADR-003 F7 probe. Returns { ok, lines:[...], store: } or +// { error } on a throw. `lines` are what gets printed under the verdict and written to +// the capture file; they say exactly what the store held. +function hexLiteral(hex){ return '0x'+hex.slice(1).toUpperCase()+'FF'; } +function countPushes(imgui, colors){ + return THEME_PUSH_SLOTS.filter(([slot,key]) => + imgui.includes('reaper.ImGui_Col_'+slot+'(), '+hexLiteral(colors[key])+')')).length; +} +function sameColors(a, b){ + const ka = Object.keys(a||{}).sort(), kb = Object.keys(b||{}).sort(); + return ka.length===kb.length && ka.every((k,i)=>k===kb[i] && String(a[k]).toLowerCase()===String(b[k]).toLowerCase()); +} +function runLibrarySeparation(htmlPath){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const clone = o => JSON.parse(JSON.stringify(o)); + // The project file, made by the tool's own Save path: a Button under themeDef lib-x (B). + H.reset(); + if(H.adoptProjectTheme(clone(LIB_X_B))!=='lib-x') throw new Error('adoptProjectTheme refused LIB_X_B'); + H.set('themeId', 'lib-x'); + H.create('Button', 40, 40); + const projectText = H.saveText(); + // The probe proper, on an empty session and an empty library. + H.reset(); + H.themeStoreClear(); + if(H.registerTheme(clone(LIB_X_A), true)!=='lib-x') throw new Error('registerCustomTheme refused LIB_X_A'); + const loaded = H.loadText(projectText); + if(!loaded.ok) throw new Error('loader rejected the probe project'+(loaded.reason?': '+loaded.reason:'')); + if(H.registerTheme(clone(LIB_Y), true)!=='lib-y') throw new Error('registerCustomTheme refused LIB_Y'); + const raw = H.themeStoreRead(); + const imgui = H.genImGui(); + const lines = []; + let stored = null, storeProblem = null; + try { + const arr = raw==null ? null : JSON.parse(raw); + if(!Array.isArray(arr)) storeProblem = raw==null ? 'store empty (key absent)' : 'store is not an array'; + else { + lines.push('store ids : '+JSON.stringify(arr.map(t=>t&&t.id))); + stored = arr.find(t=>t&&t.id==='lib-x') || null; + if(!stored) storeProblem = 'store has no lib-x'; + } + } catch(e){ storeProblem = 'store is not JSON: '+e.message; } + let holds = 'n/a'; + if(stored){ + holds = sameColors(stored.colors, LIB_X_A.colors) ? 'A (library)' + : sameColors(stored.colors, LIB_X_B.colors) ? 'B (project copy)' : 'neither A nor B'; + lines.push('store lib-x : colours '+holds+' · label '+JSON.stringify(stored.label)); + lines.push('store lib-x colours: '+JSON.stringify(stored.colors)); + } + if(storeProblem) lines.push('store : '+storeProblem); + const nb = countPushes(imgui, LIB_X_B.colors), na = countPushes(imgui, LIB_X_A.colors); + const themeId = H.get('themeId'); + lines.push('export : colours B '+nb+'/'+THEME_PUSH_SLOTS.length+' pushes, colours A '+na+'/'+THEME_PUSH_SLOTS.length + +' · themeId '+JSON.stringify(themeId)); + const ok = holds==='A (library)' && nb===THEME_PUSH_SLOTS.length; + if(!ok){ + const why = []; + if(holds!=='A (library)') why.push('library lib-x '+(stored ? 'now holds colours '+holds : 'not readable ('+storeProblem+')')); + if(nb!==THEME_PUSH_SLOTS.length) why.push('project exports '+nb+'/'+THEME_PUSH_SLOTS.length+' colour-B pushes'); + lines.push('reason : '+why.join('; ')); + } + return { ok, lines, store: raw }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW theme-library-separation: '+(e&&e.stack||e) }; + } finally { + if(tool) closeWindow(tool.window); + } +} + +// v3 — G5 alpha-255: themes.gate-alpha-opaque must export exactly like themes.gate-custom +// in the same build. Takes the build's results; generates the reference scene if it was +// not selected. null when the opaque scene was not selected. +function runG5(htmlPath, results){ + const opaque = results.find(r=>r.name===G5_SCENE); + if(!opaque) return null; + const ref = results.find(r=>r.name===G5_REFERENCE) + || runScene(htmlPath, SCENES.find(s=>s.name===G5_REFERENCE)); + if(opaque.error || ref.error) return { ok:false, reason:'a scene threw (see its line)' }; + if(opaque.imgui===ref.imgui) return { ok:true }; + const diff = multisetDiff(ref.imgui.split('\n'), opaque.imgui.split('\n')); + return { ok:false, reason:G5_SCENE+' vs '+G5_REFERENCE+' (+'+diff.added.length+' −'+diff.removed.length+')', diff }; +} + +// v4 — G5 wave-a. One fresh instance per variant: build, genImGui (part a), then +// Save -> reset -> Load and genSeed (part b). Both variants make the same creates in the +// same order, so their uid draws line up; the seeds are still compared through normSeed. +function probeWaveATreeSel(htmlPath, mode){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const notes = []; + const note = t => { if(!notes.includes(t)) notes.push(t); }; + H.reset(); + buildWaveATreeSel(H, note, mode); + const imgui = H.genImGui(); + const saved = H.saveText(); + H.reset(); + const loaded = H.loadText(saved); + if(!loaded.ok) throw new Error('loader rejected the '+mode+' project'+(loaded.reason?': '+loaded.reason:'')); + return { imgui, seed: H.genSeed(), notes }; + } finally { + if(tool) closeWindow(tool.window); + } +} +// null when wave-a.explicit-defaults was not selected. +function runG5WaveA(htmlPath, results){ + if(!results.some(r=>r.name===G5W_SCENE)) return null; + try { + const abs = probeWaveATreeSel(htmlPath, 'absent'), exp = probeWaveATreeSel(htmlPath, 'explicit'); + const okA = abs.imgui===exp.imgui; + const okB = normSeed(abs.seed)===normSeed(exp.seed); + return { + ok: okA && okB, + a: okA ? { ok:true } : { ok:false, diff: multisetDiff(abs.imgui.split('\n'), exp.imgui.split('\n')) }, + b: okB ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.seed).split('\n'), normSeed(exp.seed).split('\n')) }, + notes: abs.notes.concat(exp.notes.filter(n=>!abs.notes.includes(n))), + }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW G5 wave-a: '+(e&&e.stack||e) }; + } +} + +// v6 — G5 wave-b. Same pattern as probeWaveATreeSel/runG5WaveA (B03 3.1) applied to the +// wave-b TabBar+StyleRegion+Table part (B05 5.1). +function probeWaveBTabSrTable(htmlPath, mode){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const notes = []; + const note = t => { if(!notes.includes(t)) notes.push(t); }; + H.reset(); + buildWaveBTabSrTable(H, note, mode); + const imgui = H.genImGui(); + const saved = H.saveText(); + H.reset(); + const loaded = H.loadText(saved); + if(!loaded.ok) throw new Error('loader rejected the '+mode+' project'+(loaded.reason?': '+loaded.reason:'')); + return { imgui, seed: H.genSeed(), notes }; + } finally { + if(tool) closeWindow(tool.window); + } +} +// null when wave-b.explicit-defaults was not selected. +function runG5WaveB(htmlPath, results){ + if(!results.some(r=>r.name===G5W2_SCENE)) return null; + try { + const abs = probeWaveBTabSrTable(htmlPath, 'absent'), exp = probeWaveBTabSrTable(htmlPath, 'explicit'); + const okA = abs.imgui===exp.imgui; + const okB = normSeed(abs.seed)===normSeed(exp.seed); + return { + ok: okA && okB, + a: okA ? { ok:true } : { ok:false, diff: multisetDiff(abs.imgui.split('\n'), exp.imgui.split('\n')) }, + b: okB ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.seed).split('\n'), normSeed(exp.seed).split('\n')) }, + notes: abs.notes.concat(exp.notes.filter(n=>!abs.notes.includes(n))), + }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW G5 wave-b: '+(e&&e.stack||e) }; + } +} + +// v7 — G5 tables-b. Same pattern as probeWaveBTabSrTable/runG5WaveB (B05 5.1) applied to +// the tables-b six-table part (B06 6.1, ADR-011 G2/G4). +function probeTablesB(htmlPath, mode){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const notes = []; + const note = t => { if(!notes.includes(t)) notes.push(t); }; + H.reset(); + buildTablesB(H, note, mode); + const imgui = H.genImGui(); + const saved = H.saveText(); + H.reset(); + const loaded = H.loadText(saved); + if(!loaded.ok) throw new Error('loader rejected the '+mode+' project'+(loaded.reason?': '+loaded.reason:'')); + return { imgui, seed: H.genSeed(), notes }; + } finally { + if(tool) closeWindow(tool.window); + } +} +// null when tables-b.explicit-defaults was not selected. +function runG5TablesB(htmlPath, results){ + if(!results.some(r=>r.name===G5T_SCENE)) return null; + try { + const abs = probeTablesB(htmlPath, 'absent'), exp = probeTablesB(htmlPath, 'explicit'); + const okA = abs.imgui===exp.imgui; + const okB = normSeed(abs.seed)===normSeed(exp.seed); + return { + ok: okA && okB, + a: okA ? { ok:true } : { ok:false, diff: multisetDiff(abs.imgui.split('\n'), exp.imgui.split('\n')) }, + b: okB ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.seed).split('\n'), normSeed(exp.seed).split('\n')) }, + notes: abs.notes.concat(exp.notes.filter(n=>!abs.notes.includes(n))), + }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW G5 tables-b: '+(e&&e.stack||e) }; + } +} + +// v9 — G5 title (B07 7.3, ADR-007 M11). Same pattern as probeTablesB/runG5TablesB +// (B06 6.1) applied to the slate themed body with `themedTitleBar` absent vs explicit +// false, both loaded through withProjectKeys. +function probeTitle(htmlPath, keys){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const notes = []; + const note = t => { if(!notes.includes(t)) notes.push(t); }; + H.reset(); + H.set('themeId', 'slate'); + buildThemeBody(H); + const r = withProjectKeys(H, keys); + if(r.reason) note('loader: '+r.reason.replace(/\s+/g,' ').trim()); + const imgui = H.genImGui(); + return { imgui, seed: H.genSeed(), notes }; + } finally { + if(tool) closeWindow(tool.window); + } +} +// null when themes.slate-title.explicit-default was not selected. +function runG5Title(htmlPath, results){ + if(!results.some(r=>r.name===G5TT_SCENE)) return null; + try { + const abs = probeTitle(htmlPath, {}), exp = probeTitle(htmlPath, { themedTitleBar:false }); + const okA = abs.imgui===exp.imgui; + const okB = normSeed(abs.seed)===normSeed(exp.seed); + return { + ok: okA && okB, + a: okA ? { ok:true } : { ok:false, diff: multisetDiff(abs.imgui.split('\n'), exp.imgui.split('\n')) }, + b: okB ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.seed).split('\n'), normSeed(exp.seed).split('\n')) }, + notes: abs.notes.concat(exp.notes.filter(n=>!abs.notes.includes(n))), + }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW G5 title: '+(e&&e.stack||e) }; + } +} + +// v8 — G5 menus (B07 7.1). probeMenus builds the menus widgets on a fresh instance, +// loads the given menuBar (undefined = no key at all) through withMenuBar, and returns +// imgui + seed after the same Save -> reset -> Load cycle probeTablesB uses. Three +// parts: (a)/(b) MENUS_FIXTURE (absent-style, i.e. defaults left implicit) vs +// menusExplicitDefaults(MENUS_FIXTURE) — imgui and post-cycle seed must match: a build +// that keeps unknown properties through load would still agree here since both sides +// go through one Save/Load cycle before comparison; (c) an empty menuBar array vs no +// `menuBar` key at all — both channels must agree that an empty bar exports nothing. +function probeMenus(htmlPath, menuBar){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const notes = []; + const note = t => { if(!notes.includes(t)) notes.push(t); }; + H.reset(); + buildMenusWidgets(H, note); + const r = withMenuBar(H, menuBar); + if(r.reason) note('loader: '+r.reason.replace(/\s+/g,' ').trim()); + return { imgui: H.genImGui(), seed: H.genSeed(), notes }; + } finally { + if(tool) closeWindow(tool.window); + } +} +// null when menus.explicit-defaults was not selected. +function runG5Menus(htmlPath, results){ + if(!results.some(r=>r.name===G5M_SCENE)) return null; + try { + const abs = probeMenus(htmlPath, MENUS_FIXTURE), exp = probeMenus(htmlPath, menusExplicitDefaults(MENUS_FIXTURE)); + const empty = probeMenus(htmlPath, []), none = probeMenus(htmlPath, undefined); + const okA = abs.imgui===exp.imgui; + const okB = normSeed(abs.seed)===normSeed(exp.seed); + const okC = empty.imgui===none.imgui && normSeed(empty.seed)===normSeed(none.seed); + return { + ok: okA && okB && okC, + a: okA ? { ok:true } : { ok:false, diff: multisetDiff(abs.imgui.split('\n'), exp.imgui.split('\n')) }, + b: okB ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.seed).split('\n'), normSeed(exp.seed).split('\n')) }, + c: okC ? { ok:true } : { ok:false, diff: multisetDiff( + empty.imgui.split('\n').concat(normSeed(empty.seed).split('\n')), + none.imgui.split('\n').concat(normSeed(none.seed).split('\n'))) }, + notes: abs.notes.concat(exp.notes, empty.notes, none.notes) + .filter((n,i,arr)=>arr.indexOf(n)===i), + }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW G5 menus: '+(e&&e.stack||e) }; + } +} + +// v11 — G5 adaptive and adaptive inert (A01, ADR-009 AD11). +// probeAdaptiveScene builds a named scene in a fresh instance and returns its genImGui() +// (before any cycle), then the genSeed() and the saved file after one Save -> reset -> Load +// cycle. +function probeAdaptiveScene(htmlPath, sceneName){ + const scene = SCENES.find(s => s.name === sceneName); + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const notes = []; + const note = t => { if(!notes.includes(t)) notes.push(t); }; + H.reset(); + H.pinProblems().forEach(p => note('reset could not pin '+p)); + scene.build(H, note); + const imgui = H.genImGui(); + const saved = H.saveText(); + H.reset(); + const r = H.loadText(saved); + if(!r.ok) throw new Error('applyLoadedProject rejected the saved project'+(r.reason?': '+r.reason:'')); + return { imgui, seed: H.genSeed(), file: H.saveText(), notes }; + } finally { + if(tool) closeWindow(tool.window); + } +} +// Support probe: does a build keep `windowResize` through Save -> Load? (Fresh instance.) +function adaptiveSupported(htmlPath){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + H.reset(); + withAdaptive(H, {}, { windowResize:{} }, () => {}); + return Object.prototype.hasOwnProperty.call(JSON.parse(H.saveText()), 'windowResize'); + } finally { + if(tool) closeWindow(tool.window); + } +} +// null when adaptive.move.explicit-defaults was not selected; { ok:true, na:true } on a build +// without adaptive support. +function runG5Adaptive(htmlPath, results){ + if(!results.some(r=>r.name===G5AD_SCENE)) return null; + try { + if(!adaptiveSupported(htmlPath)) return { ok:true, na:true }; + const abs = probeAdaptiveScene(htmlPath, G5AD_REFERENCE), exp = probeAdaptiveScene(htmlPath, G5AD_SCENE); + const okA = abs.imgui===exp.imgui; + const okB = normSeed(abs.seed)===normSeed(exp.seed); + const okC = normSeed(abs.file)===normSeed(exp.file); + return { + ok: okA && okB && okC, + a: okA ? { ok:true } : { ok:false, diff: multisetDiff(abs.imgui.split('\n'), exp.imgui.split('\n')) }, + b: okB ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.seed).split('\n'), normSeed(exp.seed).split('\n')) }, + c: okC ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.file).split('\n'), normSeed(exp.file).split('\n')) }, + notes: abs.notes.concat(exp.notes).filter((n,i,arr)=>arr.indexOf(n)===i), + }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW G5 adaptive: '+(e&&e.stack||e) }; + } +} +// null when adaptive.inert was not selected. No N/A: it must PASS on every build. +function runAdaptiveInert(htmlPath, results){ + if(!results.some(r=>r.name===ADAPTIVE_INERT_SCENE)) return null; + try { + const inert = probeAdaptiveScene(htmlPath, ADAPTIVE_INERT_SCENE), base = probeAdaptiveScene(htmlPath, ADAPTIVE_BASE_SCENE); + if(inert.imgui===base.imgui) return { ok:true }; + return { ok:false, diff: multisetDiff(base.imgui.split('\n'), inert.imgui.split('\n')) }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW adaptive inert: '+(e&&e.stack||e) }; + } +} + +// v12 — G5 tables-c (A07.1). The tables-c.style body built twice in fresh instances, the new +// Table / StyleRegion properties absent vs at their defaults (= tables-c.explicit-defaults). +// Same three parts as G5 adaptive: (a) imgui before any cycle, (b) seed and (c) saved file after +// one Save -> reset -> Load cycle. No N/A: on a build that keeps unknown shape keys (2.0.0) (b) +// and (c) may FAIL, and that is reported, not hidden. +function probeTablesC(htmlPath, mode){ + let tool; + try { + tool = loadTool(htmlPath); + const { H } = tool; + const notes = []; + const note = t => { if(!notes.includes(t)) notes.push(t); }; + H.reset(); + H.pinProblems().forEach(p => note('reset could not pin '+p)); + buildTablesCStyle(H, note, mode); + const imgui = H.genImGui(); + const saved = H.saveText(); + H.reset(); + const r = H.loadText(saved); + if(!r.ok) throw new Error('applyLoadedProject rejected the '+mode+' project'+(r.reason?': '+r.reason:'')); + return { imgui, seed: H.genSeed(), file: H.saveText(), notes }; + } finally { + if(tool) closeWindow(tool.window); + } +} +// null when tables-c.explicit-defaults was not selected. +function runG5TablesC(htmlPath, results){ + if(!results.some(r=>r.name===G5TC_SCENE)) return null; + try { + const abs = probeTablesC(htmlPath, 'absent'), exp = probeTablesC(htmlPath, 'explicit'); + const okA = abs.imgui===exp.imgui; + const okB = normSeed(abs.seed)===normSeed(exp.seed); + const okC = normSeed(abs.file)===normSeed(exp.file); + return { + ok: okA && okB && okC, + a: okA ? { ok:true } : { ok:false, diff: multisetDiff(abs.imgui.split('\n'), exp.imgui.split('\n')) }, + b: okB ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.seed).split('\n'), normSeed(exp.seed).split('\n')) }, + c: okC ? { ok:true } : { ok:false, diff: multisetDiff(normSeed(abs.file).split('\n'), normSeed(exp.file).split('\n')) }, + notes: abs.notes.concat(exp.notes).filter((n,i,arr)=>arr.indexOf(n)===i), + }; + } catch(e){ + if(e instanceof HarnessError) throw e; + return { error: 'THROW G5 tables-c: '+(e&&e.stack||e) }; + } +} + +// Multiset line diff (G7): lines only in A (removed) and only in B (added), counted +// with multiplicity, in order of first appearance. Insensitive to position, so one +// inserted line does not cascade. +function multisetDiff(a, b){ + const count = arr => { const m=new Map(); for(const l of arr) m.set(l,(m.get(l)||0)+1); return m; }; + const cb = count(b), ca = count(a); + const removed = [], added = []; + for(const l of a){ if(cb.get(l)>0) cb.set(l, cb.get(l)-1); else removed.push(l); } + for(const l of b){ if(ca.get(l)>0) ca.set(l, ca.get(l)-1); else added.push(l); } + return { removed, added }; +} + +// ============================================================================ +// CLI +// ============================================================================ +function usage(msg){ + if(msg) console.error('export_gate: '+msg); + console.error('usage: node export_gate.js [] [--scene ]... [--full] [--list]'); + process.exit(2); +} + +const argv = process.argv.slice(2); +const files = []; const sceneFilter = []; let FULL = false, LIST = false; +for(let i=0;i=argv.length) usage('--scene needs a name'); sceneFilter.push(argv[++i]); } + else if(a==='--full') FULL = true; + else if(a==='--list') LIST = true; + else if(a.startsWith('--')) usage('unknown option '+a); + else files.push(a); +} +if(LIST){ + SCENES.forEach(s=>console.log(s.name)); CHECKS.forEach(c=>console.log(c.name)); + console.log('# cross-scene checks (not selectable; each runs with its scene)'); + CROSS_CHECKS.forEach(([n, s])=>console.log('# '+n+' <- '+s)); + process.exit(0); +} +if(files.length<1 || files.length>2) usage(); +for(const f of files) if(!fs.existsSync(f)) usage('no such file: '+f); + +const selected = sceneFilter.length + ? SCENES.filter(s => sceneFilter.some(f => s.name===f || s.name.startsWith(f+'.'))) + : SCENES; +for(const f of sceneFilter) + if(!SCENES.some(s => s.name===f || s.name.startsWith(f+'.')) && !CHECKS.some(c => c.name===f)) + usage('unknown scene '+f+' (try --list)'); +// Checks run when no filter is given, or when named exactly. +const selectedChecks = sceneFilter.length ? CHECKS.filter(c => sceneFilter.includes(c.name)) : CHECKS; +if(selected.some(s=>s.name.startsWith('examples.')) && !fs.existsSync(FIXTURE_DIR)) + usage('fixtures folder missing: '+FIXTURE_DIR); + +const CAP = 80; +function printLines(sign, lines, indent){ + const shown = FULL ? lines : lines.slice(0, CAP); + for(const l of shown) console.log(indent+sign+' '+l); + if(shown.length p.ok ? 'IDENTICAL' : 'DIFFERS (+'+p.diff.added.length+' −'+p.diff.removed.length+')'; + console.log(pre+'G5 wave-a '+(g.ok?'PASS':'FAIL')+' (absent vs explicit defaults: (a) imgui '+part(g.a) + +' · (b) seed after save→load '+part(g.b)+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + g.notes.forEach(n => console.log(' '+(gated?'':'before ')+'note: '+n)); + if(!g.ok && !sameAsGated){ + if(!g.a.ok){ console.log(' (a) imgui:'); printDiff(g.a.diff, ' '); } + if(!g.b.ok){ console.log(' (b) seed:'); printDiff(g.b.diff, ' '); } + } else if(!g.ok) console.log(' before: same result as the after build'); + if(gated && !g.ok) raise(3); +} +function sameG5WaveA(x, y){ + if(!x || !y || x.error || y.error) return false; + const k = g => JSON.stringify([g.ok, g.a, g.b]); + return k(x)===k(y); +} +// v6 — G5 wave-b reporting. Same shape as printG5WaveA/sameG5WaveA (B03 3.1). +function printG5WaveB(g, gated, sameAsGated){ + if(!g) return; + const pre = gated ? '' : ' before: '; + if(g.error){ console.log(pre+'G5 wave-b THROW'); console.log(' '+g.error.split('\n').join('\n ')); raise(3); return; } + const part = p => p.ok ? 'IDENTICAL' : 'DIFFERS (+'+p.diff.added.length+' −'+p.diff.removed.length+')'; + console.log(pre+'G5 wave-b '+(g.ok?'PASS':'FAIL')+' (absent vs explicit defaults: (a) imgui '+part(g.a) + +' · (b) seed after save→load '+part(g.b)+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + g.notes.forEach(n => console.log(' '+(gated?'':'before ')+'note: '+n)); + if(!g.ok && !sameAsGated){ + if(!g.a.ok){ console.log(' (a) imgui:'); printDiff(g.a.diff, ' '); } + if(!g.b.ok){ console.log(' (b) seed:'); printDiff(g.b.diff, ' '); } + } else if(!g.ok) console.log(' before: same result as the after build'); + if(gated && !g.ok) raise(3); +} +function sameG5WaveB(x, y){ + if(!x || !y || x.error || y.error) return false; + const k = g => JSON.stringify([g.ok, g.a, g.b]); + return k(x)===k(y); +} +// v7 — G5 tables-b reporting. Same shape as printG5WaveB/sameG5WaveB (B05 5.1). +function printG5TablesB(g, gated, sameAsGated){ + if(!g) return; + const pre = gated ? '' : ' before: '; + if(g.error){ console.log(pre+'G5 tables-b THROW'); console.log(' '+g.error.split('\n').join('\n ')); raise(3); return; } + const part = p => p.ok ? 'IDENTICAL' : 'DIFFERS (+'+p.diff.added.length+' −'+p.diff.removed.length+')'; + console.log(pre+'G5 tables-b '+(g.ok?'PASS':'FAIL')+' (absent vs explicit defaults: (a) imgui '+part(g.a) + +' · (b) seed after save→load '+part(g.b)+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + g.notes.forEach(n => console.log(' '+(gated?'':'before ')+'note: '+n)); + if(!g.ok && !sameAsGated){ + if(!g.a.ok){ console.log(' (a) imgui:'); printDiff(g.a.diff, ' '); } + if(!g.b.ok){ console.log(' (b) seed:'); printDiff(g.b.diff, ' '); } + } else if(!g.ok) console.log(' before: same result as the after build'); + if(gated && !g.ok) raise(3); +} +function sameG5TablesB(x, y){ + if(!x || !y || x.error || y.error) return false; + const k = g => JSON.stringify([g.ok, g.a, g.b]); + return k(x)===k(y); +} +// v9 — G5 title reporting. Same shape as printG5TablesB/sameG5TablesB (B06 6.1). +function printG5Title(g, gated, sameAsGated){ + if(!g) return; + const pre = gated ? '' : ' before: '; + if(g.error){ console.log(pre+'G5 title THROW'); console.log(' '+g.error.split('\n').join('\n ')); raise(3); return; } + const part = p => p.ok ? 'IDENTICAL' : 'DIFFERS (+'+p.diff.added.length+' −'+p.diff.removed.length+')'; + console.log(pre+'G5 title '+(g.ok?'PASS':'FAIL')+' (absent vs explicit false: (a) imgui '+part(g.a) + +' · (b) seed after save→load '+part(g.b)+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + g.notes.forEach(n => console.log(' '+(gated?'':'before ')+'note: '+n)); + if(!g.ok && !sameAsGated){ + if(!g.a.ok){ console.log(' (a) imgui:'); printDiff(g.a.diff, ' '); } + if(!g.b.ok){ console.log(' (b) seed:'); printDiff(g.b.diff, ' '); } + } else if(!g.ok) console.log(' before: same result as the after build'); + if(gated && !g.ok) raise(3); +} +function sameG5Title(x, y){ + if(!x || !y || x.error || y.error) return false; + const k = g => JSON.stringify([g.ok, g.a, g.b]); + return k(x)===k(y); +} +// v8 — G5 menus reporting. Same shape as printG5TablesB/sameG5TablesB (B06 6.1), with a +// third part: (c) an empty menuBar array vs no key at all. +function printG5Menus(g, gated, sameAsGated){ + if(!g) return; + const pre = gated ? '' : ' before: '; + if(g.error){ console.log(pre+'G5 menus THROW'); console.log(' '+g.error.split('\n').join('\n ')); raise(3); return; } + const part = p => p.ok ? 'IDENTICAL' : 'DIFFERS (+'+p.diff.added.length+' −'+p.diff.removed.length+')'; + console.log(pre+'G5 menus '+(g.ok?'PASS':'FAIL')+' (absent vs explicit defaults: (a) imgui '+part(g.a) + +' · (b) seed after save→load '+part(g.b)+' · (c) empty bar vs none '+part(g.c)+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + g.notes.forEach(n => console.log(' '+(gated?'':'before ')+'note: '+n)); + if(!g.ok && !sameAsGated){ + if(!g.a.ok){ console.log(' (a) imgui:'); printDiff(g.a.diff, ' '); } + if(!g.b.ok){ console.log(' (b) seed:'); printDiff(g.b.diff, ' '); } + if(!g.c.ok){ console.log(' (c) empty vs none:'); printDiff(g.c.diff, ' '); } + } else if(!g.ok) console.log(' before: same result as the after build'); + if(gated && !g.ok) raise(3); +} +function sameG5Menus(x, y){ + if(!x || !y || x.error || y.error) return false; + const k = g => JSON.stringify([g.ok, g.a, g.b, g.c]); + return k(x)===k(y); +} +// v11 — G5 adaptive reporting. Same shape as printG5Menus/sameG5Menus (B07 7.1), with part +// (c) the saved file after save→load, and an N/A for a build without adaptive support (no +// failure, no exit change). +function printG5Adaptive(g, gated, sameAsGated){ + if(!g) return; + const pre = gated ? '' : ' before: '; + if(g.error){ console.log(pre+'G5 adaptive THROW'); console.log(' '+g.error.split('\n').join('\n ')); raise(3); return; } + if(g.na){ console.log(pre+'G5 adaptive N/A (build has no adaptive support: windowResize dropped on load)'); return; } + const part = p => p.ok ? 'IDENTICAL' : 'DIFFERS (+'+p.diff.added.length+' −'+p.diff.removed.length+')'; + console.log(pre+'G5 adaptive '+(g.ok?'PASS':'FAIL')+' (absent vs explicit defaults: (a) imgui '+part(g.a) + +' · (b) seed after save→load '+part(g.b)+' · (c) file after save→load '+part(g.c)+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + g.notes.forEach(n => console.log(' '+(gated?'':'before ')+'note: '+n)); + if(!g.ok && !sameAsGated){ + if(!g.a.ok){ console.log(' (a) imgui:'); printDiff(g.a.diff, ' '); } + if(!g.b.ok){ console.log(' (b) seed:'); printDiff(g.b.diff, ' '); } + if(!g.c.ok){ console.log(' (c) file:'); printDiff(g.c.diff, ' '); } + } else if(!g.ok) console.log(' before: same result as the after build'); + if(gated && !g.ok) raise(3); +} +function sameG5Adaptive(x, y){ + if(!x || !y || x.error || y.error || x.na || y.na) return false; + const k = g => JSON.stringify([g.ok, g.a, g.b, g.c]); + return k(x)===k(y); +} +// v11 — adaptive inert reporting: adaptive.inert's imgui must equal adaptive.base's. +function printAdaptiveInert(g, gated){ + if(!g) return; + const pre = gated ? '' : ' before: '; + if(g.error){ console.log(pre+'adaptive inert THROW'); console.log(' '+g.error.split('\n').join('\n ')); raise(3); return; } + console.log(pre+'adaptive inert '+(g.ok?'PASS':'FAIL')+' (imgui of '+ADAPTIVE_INERT_SCENE+' vs '+ADAPTIVE_BASE_SCENE+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + if(!g.ok){ + console.log(' imgui (− '+ADAPTIVE_BASE_SCENE+', + '+ADAPTIVE_INERT_SCENE+'):'); + printDiff(g.diff, ' '); + if(gated) raise(3); + } +} +// v12 — G5 tables-c reporting. Same shape as printG5Adaptive/sameG5Adaptive (A01), no N/A. +function printG5TablesC(g, gated, sameAsGated){ + if(!g) return; + const pre = gated ? '' : ' before: '; + if(g.error){ console.log(pre+'G5 tables-c THROW'); console.log(' '+g.error.split('\n').join('\n ')); raise(3); return; } + const part = p => p.ok ? 'IDENTICAL' : 'DIFFERS (+'+p.diff.added.length+' −'+p.diff.removed.length+')'; + console.log(pre+'G5 tables-c '+(g.ok?'PASS':'FAIL')+' (absent vs explicit defaults: (a) imgui '+part(g.a) + +' · (b) seed after save→load '+part(g.b)+' · (c) file after save→load '+part(g.c)+')' + +(!gated && !g.ok ? ' (pre-existing in the before build; not gated)' : '')); + g.notes.forEach(n => console.log(' '+(gated?'':'before ')+'note: '+n)); + if(!g.ok && !sameAsGated){ + if(!g.a.ok){ console.log(' (a) imgui:'); printDiff(g.a.diff, ' '); } + if(!g.b.ok){ console.log(' (b) seed:'); printDiff(g.b.diff, ' '); } + if(!g.c.ok){ console.log(' (c) file:'); printDiff(g.c.diff, ' '); } + } else if(!g.ok) console.log(' before: same result as the after build'); + if(gated && !g.ok) raise(3); +} +function sameG5TablesC(x, y){ + if(!x || !y || x.error || y.error) return false; + const k = g => JSON.stringify([g.ok, g.a, g.b, g.c]); + return k(x)===k(y); +} +function checkText(c){ return c.error ? 'THROW' : (c.ok ? 'PASS' : 'FAIL'); } +function checkFileText(name, c){ + if(c.error) return name+' THROW\n'+c.error+'\n'; + return name+' '+checkText(c)+'\n'+c.lines.join('\n')+'\nraw store:\n'+(c.store==null?'(absent)':c.store)+'\n'; +} + +let exitCode = 0; +const raise = c => { if(c>exitCode) exitCode = c; }; + +try { + if(files.length===1){ + // ── capture ── + const a = files[0]; + const stem = path.basename(a).replace(/\.html?$/i,''); + const dir = path.join(process.cwd(),'golden',stem); + fs.mkdirSync(dir,{recursive:true}); + const defs = runDefaults(a); + fs.writeFileSync(path.join(dir,'defaults.txt'), defs+'\n'); + console.log('── export gate v12 · capture ──'); + console.log('file : '+path.basename(a)); + console.log('goldens : golden/'+stem+'/.{imgui,seed,file}'); + console.log('defaults : '+defs); + const R = runAll(a); + for(const r of R){ + if(r.error){ console.log(r.name.padEnd(36)+' THROW'); console.log(' '+r.error.split('\n').join('\n ')); raise(3); continue; } + fs.writeFileSync(path.join(dir,r.name+'.imgui'), r.imgui); + fs.writeFileSync(path.join(dir,r.name+'.seed'), r.seed); + fs.writeFileSync(path.join(dir,r.name+'.file'), r.file); + console.log(r.name.padEnd(36)+' '+(r.stable?'STABLE':'NON-DETERMINISTIC') + +' · roundtrip '+rtText(r.rt) + +' · bytes imgui '+Buffer.byteLength(r.imgui)+' seed '+Buffer.byteLength(r.seed)+' file '+Buffer.byteLength(r.file)); + r.notes.forEach(n => console.log(' note: '+n)); + r.problems.forEach(p => { console.log(' '+p); raise(3); }); + if(r.rt && !r.rt.ok){ + console.log(' ROUNDTRIP MISMATCH '+r.name+' — '+r.rt.reason); + if(r.rt.diff) printDiff(r.rt.diff, ' '); + raise(3); + } + } + printG5(runG5(a, R), true); + printG5WaveA(runG5WaveA(a, R), true, false); + printG5WaveB(runG5WaveB(a, R), true, false); + printG5TablesB(runG5TablesB(a, R), true, false); + printG5Menus(runG5Menus(a, R), true, false); + printG5Title(runG5Title(a, R), true, false); + printG5Adaptive(runG5Adaptive(a, R), true, false); + printAdaptiveInert(runAdaptiveInert(a, R), true); + printG5TablesC(runG5TablesC(a, R), true, false); + for(const ck of selectedChecks){ + const c = ck.run(a); + fs.writeFileSync(path.join(dir, ck.name+'.txt'), checkFileText(ck.name, c)); + console.log(ck.name.padEnd(36)+' '+checkText(c)); + if(c.error){ console.log(' '+c.error.split('\n').join('\n ')); raise(3); continue; } + c.lines.forEach(l => console.log(' '+l)); + if(!c.ok) raise(3); + } + } else { + // ── compare ── + const [a, b] = files; + console.log('── export gate v12 · compare ──'); + console.log('before: '+path.basename(a)+' | after: '+path.basename(b)); + const da = runDefaults(a), db = runDefaults(b); + if(da===db) console.log('defaults'.padEnd(36)+' IDENTICAL ('+da+')'); + else { + console.log('defaults'.padEnd(36)+' CHANGED'); + console.log(' before: '+da); console.log(' after : '+db); + raise(1); + } + const A = runAll(a), B = runAll(b); + for(let i=0;i same ? 'IDENTICAL' + : (d.added.length||d.removed.length ? 'CHANGED +'+d.added.length+' −'+d.removed.length + : 'CHANGED (order only)'); + console.log(x.name.padEnd(36)+' imgui '+verdict(sameI,ci)+' · seed '+verdict(sameS,cs)+' · file '+verdict(sameF,cf) + +' · roundtrip '+rtText(x.rt)+'/'+rtText(y.rt) + +' · '+(x.stable&&y.stable?'STABLE':'NON-DETERMINISTIC')); + const notesA = x.notes.join('\n'), notesB = y.notes.join('\n'); + if(notesA===notesB) x.notes.forEach(n => console.log(' note: '+n)); + else { x.notes.forEach(n => console.log(' note (before): '+n)); y.notes.forEach(n => console.log(' note (after) : '+n)); } + if(!sameI){ console.log(' imgui:'); printDiff(ci, ' '); raise(1); } + if(!sameS){ console.log(' seed:'); printDiff(cs, ' '); raise(1); } + if(!sameF){ console.log(' file:'); printDiff(cf, ' '); raise(1); } + x.problems.forEach(p => { console.log(' before: '+p); raise(3); }); + y.problems.forEach(p => { console.log(' after : '+p); raise(3); }); + if(x.rt && !x.rt.ok) console.log(' before: ROUNDTRIP MISMATCH '+x.name+' — '+x.rt.reason+' (pre-existing in the before build; not gated)'); + if(y.rt && !y.rt.ok){ + console.log(' ROUNDTRIP MISMATCH '+y.name+' — '+y.rt.reason); + if(y.rt.diff) printDiff(y.rt.diff, ' '); + raise(3); + } + } + // v3 — G5 on the build under test (after); a before-build mismatch is pre-existing. + const g5a = runG5(a, A), g5b = runG5(b, B); + printG5(g5b, true); + if(g5a && !g5a.ok) printG5(g5a, false); + // v4 — G5 wave-a on the build under test; a before-build FAIL is pre-existing. + const gwa = runG5WaveA(a, A), gwb = runG5WaveA(b, B); + printG5WaveA(gwb, true, false); + if(gwa && (gwa.error || !gwa.ok)) printG5WaveA(gwa, false, sameG5WaveA(gwa, gwb)); + // v6 — G5 wave-b on the build under test; a before-build FAIL is pre-existing. + const gwa2 = runG5WaveB(a, A), gwb2 = runG5WaveB(b, B); + printG5WaveB(gwb2, true, false); + if(gwa2 && (gwa2.error || !gwa2.ok)) printG5WaveB(gwa2, false, sameG5WaveB(gwa2, gwb2)); + // v7 — G5 tables-b on the build under test; a before-build FAIL is pre-existing. + const gwa3 = runG5TablesB(a, A), gwb3 = runG5TablesB(b, B); + printG5TablesB(gwb3, true, false); + if(gwa3 && (gwa3.error || !gwa3.ok)) printG5TablesB(gwa3, false, sameG5TablesB(gwa3, gwb3)); + // v8 — G5 menus on the build under test; a before-build FAIL is pre-existing. + const gwa4 = runG5Menus(a, A), gwb4 = runG5Menus(b, B); + printG5Menus(gwb4, true, false); + if(gwa4 && (gwa4.error || !gwa4.ok)) printG5Menus(gwa4, false, sameG5Menus(gwa4, gwb4)); + // v9 — G5 title on the build under test; a before-build FAIL is pre-existing. + const gwa5 = runG5Title(a, A), gwb5 = runG5Title(b, B); + printG5Title(gwb5, true, false); + if(gwa5 && (gwa5.error || !gwa5.ok)) printG5Title(gwa5, false, sameG5Title(gwa5, gwb5)); + // v11 — G5 adaptive and adaptive inert on the build under test; a before-build FAIL is + // pre-existing. A before-build N/A is shown only when the after build supports adaptive. + const gad1 = runG5Adaptive(a, A), gad2 = runG5Adaptive(b, B); + printG5Adaptive(gad2, true, false); + if(gad1 && (gad1.error || !gad1.ok)) printG5Adaptive(gad1, false, sameG5Adaptive(gad1, gad2)); + else if(gad1 && gad1.na && gad2 && !gad2.na) printG5Adaptive(gad1, false, false); + const gin1 = runAdaptiveInert(a, A), gin2 = runAdaptiveInert(b, B); + printAdaptiveInert(gin2, true); + if(gin1 && (gin1.error || !gin1.ok)) printAdaptiveInert(gin1, false); + // v12 — G5 tables-c on the build under test; a before-build FAIL is pre-existing. + const gtc1 = runG5TablesC(a, A), gtc2 = runG5TablesC(b, B); + printG5TablesC(gtc2, true, false); + if(gtc1 && (gtc1.error || !gtc1.ok)) printG5TablesC(gtc1, false, sameG5TablesC(gtc1, gtc2)); + for(const ck of selectedChecks){ + const ca = ck.run(a), cb = ck.run(b); + console.log(ck.name.padEnd(36)+' '+checkText(ca)+'/'+checkText(cb)); + if(cb.error){ console.log(' after : '+cb.error.split('\n').join('\n ')); raise(3); } + else { cb.lines.forEach(l => console.log(' after : '+l)); if(!cb.ok) raise(3); } + if(ca.error){ console.log(' before: '+ca.error.split('\n').join('\n ')); raise(3); } + else if(!ca.ok){ + const same = !cb.error && ca.lines.join('\n')===cb.lines.join('\n'); + if(same) console.log(' before: same result (pre-existing in the before build; not gated)'); + else { ca.lines.forEach(l => console.log(' before: '+l)); console.log(' before: FAIL is pre-existing in the before build; not gated'); } + } + } + console.log('result: '+(exitCode===0 ? 'CLEAN — every scene identical on both channels' + : exitCode===1 ? 'CHANGED — review the multisets: only intended lines may differ' + : 'FAIL — round-trip mismatch, throw, non-determinism, a G5 mismatch (alpha-255 / wave-a / wave-b / tables-b / menus / title / adaptive / tables-c), adaptive inert or a failed check (exit 3)')); + } +} catch(e){ + if(e instanceof HarnessError){ console.error(e.message); process.exit(3); } + throw e; +} +process.exit(exitCode);