cc-1c-skills
Маркетплейс навыков для разработки на платформе 1С:Предприятие
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/Nikolay-Shirokov/cc-1c-skills with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/Nikolay-Shirokov/cc-1c-skills'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/nikolay-shirokov--cc-1c-skills)HTML
<a href="/listings/nikolay-shirokov--cc-1c-skills"><img src="/api/listings/nikolay-shirokov--cc-1c-skills/badge.svg" alt="findsafeskills safety rating" /></a>Install
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 24 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- {
- "$schema": "https://json.schemastore.org/claude-code-marketplace-manifest.json",
- "name": "cc-1c-skills",
- "description": "Маркетплейс навыков для разработки на платформе 1С:Предприятие",
- "owner": {
- "name": "Nikolay Shirokov"
- },
- "plugins": [
- {
- "name": "1c-skills",
- "source": "./",
- "description": "[PowerShell] Навыки для разработки на 1С:Предприятие 8.3 — абстракции над XML-форматами и CLI конфигуратора, плюс глаза и руки для тестирования через веб-клиент."
- },
- {
- "name": "1c-skills-py",
- "source": {
- "source": "github",
- "repo": "Nikolay-Shirokov/cc-1c-skills",
- "ref": "port-claude-code-py"
- },
- "description": "[Python] То же — для Linux/Mac или когда PowerShell недоступен."
- }
- ]
- }
README.md · README · 288 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- # 1C Skills for Claude Code
- > **Проект живой, активно развивается** — добавляются новые возможности, отлавливаются и исправляются баги, производится оптимизация. Следите за обновлениями.
- Набор навыков для AI-агентов (в первую очередь для [Claude Code](https://docs.anthropic.com/en/docs/claude-code/skills)), помогающий охватить полный цикл разработки на платформе 1С:Предприятие 8.3 — от создания конфигураций, расширений, внешних обработок и отчётов до загрузки изменений в информационную базу, обновления, запуска, публикации на веб-сервере (портативная версия Apache), тестирования через веб-клиент и записи видеоинструкций.
- Навыки дают модели готовые абстракции над XML-форматами и CLI конфигуратора — чтобы работать с сутью задачи, а не с деталями реализации. А веб-тестирование даёт ей глаза и руки для взаимодействия с интерфейсом 1С.
- ## Версии навыков для разных платформ
- > **PS** — версия со скриптами на PowerShell (стандартная, для Windows). **Py** — версия со скриптами на Python (если PowerShell не подходит). Можно начать с **PS** — это основной вариант.
- **Claude Code** [PS](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/main) · [Py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-claude-code-py) — **Cursor** [PS](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-cursor) · [Py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-cursor-py) — **Codex** [PS](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-codex) · [Py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-codex-py) — [Другие платформы →](#поддерживаемые-платформы)
- ## Быстрый старт
- Скопируйте каталог `.claude/skills/` из этого репозитория в корень вашего проекта. Навыки станут доступны при запуске Claude Code из этого каталога.
- ```
- МойПроект/
- ├── .claude/skills/ ← скопировать сюда
- └── ...
- ```
- Или установите как плагин Claude Code:
- ```
- /plugin marketplace add https://github.com/Nikolay-Shirokov/cc-1c-skills
- /plugin install 1c-skills@cc-1c-skills # PowerShell (Windows)
- /plugin install 1c-skills-py@cc-1c-skills # Python (Linux/Mac или если PS недоступен)
- ```
- Или установите как плагин OpenAI Codex:
- ```
- codex plugin marketplace add Nikolay-Shirokov/cc-1c-skills
- codex /plugins # выберите 1c-skills (PowerShell) или 1c-skills-py (Python) и нажмите Install
- ```
- Или используйте скрипт установки:
- ```bash
- git clone https://github.com/Nikolay-Shirokov/cc-1c-skills.git tools/cc-1c-skills
- # Копия (рекомендуется): независимая копия, обновление — повторный запуск
- python tools/cc-1c-skills/scripts/switch.py claude-code --project-dir .
- # Ссылки (экспериментально): обновления подхватываются через git pull
- python tools/cc-1c-skills/scripts/switch.py claude-code --project-dir . --link
- # Интерактивный режим: пошаговый выбор платформы, способа установки и рантайма
- python tools/cc-1c-skills/scripts/switch.py
- ```
- Не обязательно запоминать команды и параметры — просто опишите задачу своими словами, Claude сам подберёт нужные навыки. Слеш-команды (например `/epf-init МояОбработка`) тоже работают — для точного контроля.
- ## Группы навыков
- | Группа | Навыки | Описание | Гайд |
- |--------|--------|----------|------|
- | Внешние обработки (EPF) | 7 навыков `/epf-*` | Создание, сборка, разборка, валидация обработок из XML-исходников | [Подробнее](docs/epf-guide.md) |
- | Внешние отчёты (ERF) | 4 навыка `/erf-*` | Создание, сборка, разборка, валидация внешних отчётов | [Подробнее](docs/epf-guide.md#внешние-отчёты-erf) |
- | Универсальные операции | `/template-add`, `/template-remove`, `/help-add`, `/form-remove` | Добавление/удаление макетов, форм, справки для любых объектов | [Подробнее](docs/epf-guide.md#универсальные-навыки) |
- | Табличный документ (MXL) | 4 навыка `/mxl-*` | Анализ, создание, компиляция макетов печатных форм | [Подробнее](docs/mxl-guide.md) |
- | Управляемые формы (Form) | 5 навыков `/form-*` | Создание, анализ, генерация, модификация, валидация управляемых форм | [Подробнее](docs/form-guide.md) |
- | Роли (Role) | 3 навыка `/role-*` | Анализ прав роли, создание из JSON DSL, валидация | [Подробнее](docs/role-guide.md) |
- | Схема компоновки (СКД) | 4 навыка `/skd-*` | Анализ, генерация из JSON DSL, точечное редактирование, валидация схем компоновки данных | [Подробнее](docs/skd-guide.md) |
- | Метаданные конфигурации | 5 навыков `/meta-*` | Создание, анализ, редактирование, удаление, валидация объектов метаданных (23 типа) | [Подробнее](docs/meta-guide.md) |
- | Корневая конфигурация | 4 навыка `/cf-*` | Создание, анализ, редактирование, валидация корневых файлов конфигурации | [Подробнее](docs/cf-guide.md) |
- | Расширения (CFE) | 5 навыков `/cfe-*` | Создание, заимствование, перехват методов, валидация, анализ расширений | [Подробнее](docs/cfe-guide.md) |
- | Подсистемы (Subsystem) | 4 навыка `/subsystem-*` | Анализ, создание, редактирование, валидация подсистем конфигурации | [Подробнее](docs/subsystem-guide.md) |
- | Командный интерфейс (CI) | 2 навыка `/interface-*` | Редактирование и валидация CommandInterface.xml подсистем | [Подробнее](docs/subsystem-guide.md) |
- | Пакеты XDTO | 5 навыков `/xdto-*` | Анализ, создание из XML-схемы, выгрузка в схему, точечное редактирование, валидация пакетов XDTO | [Подробнее](docs/xdto-guide.md) |
- | Базы данных (DB) | 13 навыков `/db-*` | Создание баз, загрузка/выгрузка конфигураций, обновление БД, загрузка из Git, хранилище конфигурации, управление расширениями в базе | [Подробнее](docs/db-guide.md) |
- | Веб-публикация (Web) | 4 навыка `/web-*` | Публикация баз через Apache, статус, остановка, удаление публикаций | [Подробнее](docs/web-guide.md) |
- | Тестирование (Web) | `/web-test` | Взаимодействие с веб-клиентом 1С — навигация, формы, таблицы, отчёты, тестирование | [Подробнее](docs/web-test-guide.md) |
- | Запись видео (Web) | `/web-test` | Запись видеоинструкций с субтитрами, подсветкой и TTS-озвучкой | [Подробнее](docs/web-test-recording-guide.md) |
- | Регресс прикладного решения (Web) | `/web-test` | Автоматический регресс конфигурации: тесты, проверки, отчёты, прогон после правок | [Подробнее](docs/web-test-regression-guide.md) |
- | Утилиты | `/img-grid`, `/v8-xsd-fetch` | Сетка на изображении для определения пропорций колонок; загрузка XSD-схем платформы для проверки выгрузок | [Подробнее](docs/v8-project-guide.md#xsdpath--xsd-схемы-платформы) |
- ## Требования
- - **Windows** с PowerShell 5.1+ (входит в Windows) — рантайм по умолчанию
- - **1С:Предприятие 8.3** — для сборки/разборки EPF/ERF (навыки генерации XML работают без платформы)
- - **Node.js 18+** — для `/web-test` (тестирование через браузер)
- <a id="поддерживаемые-платформы"></a>
- ### Другие AI-платформы
- Навыки построены на открытом стандарте [Agent Skills](https://agentskills.io/specification) и совместимы с любой платформой, поддерживающей этот формат. Самый быстрый путь — скачать готовую сборку под нужную платформу из ветки ниже (**Code → Download ZIP**) и распаковать в корень своего проекта.
- #### Поддерживаемые платформы
- | Платформа | Целевой каталог | PowerShell | Python |
- |-----------|----------------|------------|--------|
- | Claude Code | `.claude/skills/` | [main](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/main) | [port-claude-code-py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-claude-code-py) |
- | Cursor | `.cursor/skills/` | [port-cursor](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-cursor) | [port-cursor-py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-cursor-py) |
- | OpenAI Codex | `.codex/skills/` | [port-codex](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-codex) | [port-codex-py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-codex-py) |
- | GitHub Copilot | `.github/skills/` | [port-copilot](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-copilot) | [port-copilot-py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-copilot-py) |
- | Augment | `.augment/skills/` | [port-augment](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-augment) | [port-augment-py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-augment-py) |
- | Cline | `.cline/skills/` | [port-cline](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-cline) | [port-cline-py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-cline-py) |
- | Kilo Code | `.kilocode/skills/` | [port-kilo](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-kilo) | [port-kilo-py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-kilo-py) |
- | Kiro | `.kiro/skills/` | [port-kiro](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-kiro) | [port-kiro-py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-kiro-py) |
- | Gemini CLI | `.gemini/skills/` | [port-gemini](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-gemini) | [port-gemini-py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-gemini-py) |
- | OpenCode | `.opencode/skills/` | [port-opencode](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-opencode) | [port-opencode-py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-opencode-py) |
- | Roo Code | `.roo/skills/` | [port-roo](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-roo) | [port-roo-py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-roo-py) |
- | Windsurf | `.windsurf/skills/` | [port-windsurf](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-windsurf) | [port-windsurf-py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-windsurf-py) |
- | Yandex Code Assistant | `.codeassistant/skills/` | [port-codeassistant](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-codeassistant) | [port-codeassistant-py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-codeassistant-py) |
- | Agent Skills | `.agents/skills/` | [port-agents](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-agents) | [port-agents-py](https://github.com/Nikolay-Shirokov/cc-1c-skills/tree/port-agents-py) |
- Готовые ветки `port-*` пересобираются автоматически на каждое изменение в навыках. Если нужна свежая сборка прямо сейчас — соберите [локально через `switch.py`](#альтернативный-способ--собрать-локально-через-switchpy).
- Некоторые платформы (Augment, Cline, VS Code/Copilot) также сканируют `.claude/skills/` как fallback — для них достаточно `main`.
- <a id="альтернативный-способ--собрать-локально-через-switchpy"></a>
- #### Альтернативный способ — собрать локально через `switch.py`
- Если нужна свежая сборка под свою платформу (или платформа ещё не в матрице port-веток):
- ```bash
- python scripts/switch.py # интерактивный режим
- python scripts/switch.py cursor # скопировать навыки для Cursor
- python scripts/switch.py cursor --runtime python # Cursor + Python-рантайм
- python scripts/switch.py claude-code --project-dir /my/proj # установить копию в проект
- python scripts/switch.py claude-code --project-dir /my/proj --link # ссылки вместо копий
- python scripts/switch.py --undo cursor # удалить копию / ссылки
- ```
- Если репозиторий склонирован внутрь проекта (например, в `tools/cc-1c-skills`), используйте `--project-dir` для установки навыков в целевой проект.
- **Сторонние навыки не трогаются.** В каталог навыков платформы `switch.py` кладёт манифест `.cc-1c-skills.json` со списком установленного. При обновлении и `--undo` удаляются только навыки набора: те, что есть в манифесте или в текущей версии. Чужие навыки в том же каталоге остаются на месте. Каталог с чужим навыком, имя которого совпадает с навыком набора, будет перезаписан.
- **Ссылки vs копии.** Флаг `--link` (экспериментальный) создаёт directory junction (Windows) или symlink (Linux/Mac) вместо копирования файлов. Обновления в источнике автоматически подхватываются во всех подключённых проектах — достаточно `git pull`. Ссылки доступны только для платформы Claude Code (для остальных платформ требуется перезапись путей в SKILL.md). Удаление ссылок: `--undo` — безопасно удаляет только ссылки, не трогая источник.
- > ⚠ **Известные ограничения `--link`:** Node.js резолвит `__dirname` через junction к реальному пути источника, а не к каталогу проекта. Это может приводить к тому, что навыки с Node.js-скриптами (например, `/web-test`) будут записывать файлы в каталог репозитория навыков вместо каталога проекта. При возникновении проблем переключитесь на копирование (без `--link`).
- Автоактивация — основной режим: просто опишите задачу своими словами, ассистент сам подберёт нужный навык по `description` в SKILL.md. Слеш-команды (например `/epf-init`) — для точного контроля, когда нужно вызвать конкретный навык.
- ### Переключение рантайма (PowerShell ↔ Python)
- На Windows рекомендуется PS1-рантайм (по умолчанию). Python-порты — для **Linux/Mac** или если PowerShell недоступен. PS1-скрипты — мастер-версия; Python-порты производные (см. [Python Porting Guide](docs/python-porting-guide.md)).
- ```bash
- python scripts/switch.py --runtime python # переключить на Python
- python scripts/switch.py --runtime powershell # вернуть на PowerShell
- ```
- Дополнительные зависимости Python-рантайма (Python 3.9+), одной командой — `pip install -r requirements.txt`:
- - `lxml>=4.9.0` — для навыков, работающих с DOM (edit/validate/info)
- - `Pillow>=10.0.0` — для `/img-grid` (чтение изображений и наложение сетки)
- - `psutil>=5.9.0` — для web-навыков (управление Apache)
- Параметры скриптов идентичны для обоих рантаймов — переключение меняет только интерпретатор в вызовах. Подробнее: [Python Porting Guide](docs/python-porting-guide.md).
- ## Спецификации
- Полный индекс с оглавлением по всем 44 типам объектов: **[Сводный индекс спецификаций](docs/1c-specs-index.md)**
- - [XML-формат выгрузки обработок](docs/1c-epf-spec.md) — структура XML-файлов, namespace, элементы форм
- - [XML-формат внешних отчётов](docs/1c-erf-spec.md) — отличия ERF от EPF, Properties, MainDataCompositionSchema
- - [Управляемая форма](docs/1c-form-spec.md) — Form.xml, элементы, команды, реквизиты
- - [Встроенная справка](docs/1c-help-spec.md) — Help.xml, HTML-страницы, кнопка справки на форме
- - [Пакетный режим конфигуратора 1С](docs/build-spec.md) — команды `1cv8.exe`, DESIGNER, ENTERPRISE, CREATEINFOBASE
- - [Табличный документ (MXL)](docs/1c-spreadsheet-spec.md) — XML-формат SpreadsheetDocument, совместимость версий
- - [MXL DSL](docs/mxl-dsl-spec.md) — JSON-формат описания макета для `/mxl-compile` и `/mxl-decompile`: структура, оформление, полный перечень свойств стиля
- - [Form DSL](docs/form-dsl-spec.md) — JSON-формат описания формы для `/form-compile`
- - [Роли (Rights.xml)](docs/1c-role-spec.md) — XML-формат прав роли, типы объектов, RLS
- - [Role DSL](docs/role-dsl-spec.md) — JSON-формат описания ролей для `/role-compile`
- - [Схема компоновки данных (DCS)](docs/1c-dcs-spec.md) — XML-формат DataCompositionSchema, 930 схем проанализировано
- - [SKD DSL](docs/skd-dsl-spec.md) — JSON-формат описания СКД для `/skd-compile`
- - [Объекты конфигурации](docs/1c-config-objects-spec.md) — XML-формат объектов метаданных конфигурации (23 типа)
- - [Подсистемы и командный интерфейс](docs/1c-subsystem-spec.md) — XML-формат подсистем, CommandInterface.xml, секции видимости/размещения/порядка
- - [Корневая конфигурация](docs/1c-configuration-spec.md) — XML-формат Configuration.xml, ConfigDumpInfo.xml, Languages/, 44 типа ChildObjects
- - [Расширения конфигурации (CFE)](docs/1c-extension-spec.md) — XML-формат выгрузки расширений конфигурации
- - [Веб-публикация 1С](docs/web-spec.md) — VRD, httpd.conf, wsap24.dll, portable Apache
- ## Структура репозитория
- ```
- .claude/skills/ # Навыки Claude Code
- ├── epf-init/ # Создание обработки
- ├── epf-build/ # Сборка EPF
- ├── epf-dump/ # Разборка EPF
- ├── epf-bsp-init/ # Регистрация БСП
- ├── epf-bsp-add-command/ # Команда БСП
- ├── epf-validate/ # Валидация обработки
- ├── erf-init/ # Создание внешнего отчёта
- ├── erf-build/ # Сборка ERF
- ├── erf-dump/ # Разборка ERF
- ├── erf-validate/ # Валидация отчёта
- ├── template-add/ # Добавление макета (универсальный)
- ├── template-remove/ # Удаление макета (универсальный)
- ├── form-add/ # Добавление формы (универсальный)
- ├── form-remove/ # Удаление формы (универсальный)
- ├── help-add/ # Добавление справки (универсальный)
- ├── mxl-info/ # Анализ макета
- ├── mxl-validate/ # Валидация макета
- ├── mxl-compile/ # Компиляция макета из JSON
- ├── mxl-decompile/ # Декомпиляция макета в JSON
- ├── form-info/ # Анализ структуры управляемой формы
- ├── form-compile/ # Компиляция формы из JSON
- ├── form-validate/ # Валидация формы
- ├── form-edit/ # Правка формы: добавление, перенос, изменение, удаление
- ├── role-info/ # Анализ прав роли
- ├── role-compile/ # Создание роли из JSON DSL
- ├── role-edit/ # Точечная правка прав существующей роли
- ├── role-validate/ # Валидация роли
- ├── skd-info/ # Анализ схемы компоновки данных
- ├── skd-compile/ # Компиляция СКД из JSON DSL
- ├── skd-edit/ # Точечное редактирование СКД (25 операций)
- ├── skd-validate/ # Валидация СКД
- ├── meta-info/ # Структура объекта метаданных
- ├── meta-compile/ # Создание объекта метаданных
- ├── meta-edit/ # Редактирование объекта метаданных
- ├── meta-remove/ # Удаление объекта метаданных
- ├── meta-validate/ # Валидация объекта метаданных
- ├── cf-info/ # Анализ структуры конфигурации
- ├── cf-init/ # Создание пустой конфигурации
- ├── cf-edit/ # Редактирование конфигурации
- ├── cf-validate/ # Валидация конфигурации
- ├── cfe-init/ # Создание расширения
- ├── cfe-borrow/ # Заимствование объектов
- ├── cfe-patch-method/ # Перехват методов
- ├── cfe-validate/ # Валидация расширения
- ├── cfe-diff/ # Анализ и сравнение
- ├── subsystem-info/ # Анализ структуры подсистемы
- ├── subsystem-compile/ # Создание подсистемы из JSON
- ├── subsystem-edit/ # Редактирование подсистемы
- ├── subsystem-validate/ # Валидация подсистемы
- ├── interface-edit/ # Редактирование CommandInterface.xml
- ├── interface-validate/ # Валидация CommandInterface.xml
- ├── db-list/ # Управление реестром баз данных
- ├── db-create/ # Создание информационной базы
- ├── db-dump-cf/ # Выгрузка конфигурации в CF
- ├── db-load-cf/ # Загрузка конфигурации из CF
- ├── db-dump-xml/ # Выгрузка конфигурации в XML
- ├── db-load-xml/ # Загрузка конфигурации из XML
- ├── db-dump-dt/ # Выгрузка информационной базы в DT
- ├── db-load-dt/ # Загрузка информационной базы из DT
- ├── db-update/ # Обновление конфигурации БД
- ├── db-run/ # Запуск 1С:Предприятие
- ├── db-load-git/ # Загрузка изменений из Git
- ├── db-repo/ # Хранилище конфигурации
- ├── db-cfe-admin/ # Расширения в базе: состав, проверки, свойства, удаление
- ├── web-publish/ # Публикация базы через Apache
- ├── web-info/ # Статус Apache и публикаций
- ├── web-stop/ # Остановка Apache
- ├── web-unpublish/ # Удаление публикации
- ├── web-test/ # Тестирование через веб-клиент 1С
- ├── img-grid/ # Сетка для анализа изображений
- └── v8-xsd-fetch/ # Загрузка XSD-схем платформы (.v8-xsd)
- scripts/
- └── switch.py # Переключение платформы и рантайма (13 платформ)
- docs/
- ├── epf-guide.md # Гайд: внешние обработки и отчёты
- ├── mxl-guide.md # Гайд: табличный документ
- ├── form-guide.md # Гайд: управляемые формы
- ├── role-guide.md # Гайд: роли
- ├── skd-guide.md # Гайд: схема компоновки данных
- ├── meta-guide.md # Гайд: объекты метаданных конфигурации
- ├── cf-guide.md # Гайд: корневые файлы конфигурации
- ├── cfe-guide.md # Гайд: расширения конфигурации (CFE)
- ├── subsystem-guide.md # Гайд: подсистемы и командный интерфейс
- ├── v8-project-guide.md # Гайд: конфигурация проекта (.v8-project.json)
- ├── db-guide.md # Гайд: базы данных 1С
- ├── web-guide.md # Гайд: веб-публикация через Apache
- ├── web-test-guide.md # Гайд: тестирование через веб-клиент
- ├── web-test-recording-guide.md # Гайд: запись видеоинструкций
- ├── web-test-regression-guide.md # Гайд: регресс прикладного решения
- ├── 1c-epf-spec.md # Спецификация XML-формата (EPF)
- ├── 1c-erf-spec.md # Спецификация XML-формата (ERF)
- ├── 1c-form-spec.md # Спецификация управляемых форм
- ├── 1c-help-spec.md # Спецификация встроенной справки
- ├── 1c-config-objects-spec.md # Спецификация объектов конфигурации
- ├── build-spec.md # Пакетный режим конфигуратора 1С
- ├── 1c-spreadsheet-spec.md # Спецификация табличного документа
- ├── mxl-dsl-spec.md # Спецификация MXL DSL
- ├── form-dsl-spec.md # Спецификация Form DSL
- ├── meta-dsl-spec.md # Спецификация Meta DSL
- ├── 1c-role-spec.md # Спецификация ролей (Rights.xml)
- ├── 1c-dcs-spec.md # Спецификация СКД (DataCompositionSchema)
- ├── skd-dsl-spec.md # Спецификация SKD DSL
- ├── role-dsl-spec.md # Спецификация Role DSL
- ├── 1c-extension-spec.md # Спецификация расширений конфигурации (CFE)
- ├── 1c-subsystem-spec.md # Спецификация подсистем и командного интерфейса
- ├── web-spec.md # Спецификация веб-публикации (VRD, httpd.conf, Apache)
- └── python-porting-guide.md # Руководство по Python-портам навыков
- ```
.claude/skills/cfe-borrow/scripts/cfe-borrow.ps1 · Bundled script · 5,270 lines
- # cfe-borrow v1.63 — Borrow objects from configuration into extension (CFE)
- # Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
- [CmdletBinding(PositionalBinding=$false)]
- param(
- [Parameter(Mandatory)][string]$ExtensionPath,
- [Parameter(Mandatory)][string]$ConfigPath,
- [string]$Object,
- [string]$BorrowMainAttribute,
- [string]$Module,
- [switch]$Check,
- [switch]$Actualize
- )
- $ErrorActionPreference = "Stop"
- [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
- function Info([string]$msg) { Write-Host "[INFO] $msg" }
- function Warn([string]$msg) { Write-Host "[WARN] $msg" }
- # Form data-binding tags (value = attribute path). A binding survives only if its root
- # attribute is borrowed into the form's <Attributes>; otherwise it must be stripped or the
- # platform rejects the form with "Неверный путь к данным" on load.
- # RowPictureDataPath тоже путь к данным («Объект.Товары.РасхождениеЗаказ», «Список.DefaultPicture»),
- # а не индекс картинки: эталон Конфигуратора сохраняет его с заимствованным основным реквизитом
- # и выбрасывает без него — то же правило, что у остальных путей.
- $script:formBindingDataTags = @('DataPath','TitleDataPath','FooterDataPath','HeaderDataPath','MultipleValueDataPath','MultipleValuePresentDataPath','RowPictureDataPath')
- # Picture-path binding tags (value = picture index path, never a data attribute) — always stripped in the skeleton.
- $script:formBindingPictureTags = @('MultipleValuePictureDataPath')
- # Пути ссылок параметров выбора, которые пришлось вырезать (для предупреждения в конце)
- $script:droppedLinks = @()
- # id основного реквизита в заимствованной форме — как у Конфигуратора
- $script:mainAttrId = "1000001"
- # Виды дочерних объектов, которые заимствуются в оболочку поимённо (табличные части — отдельно)
- $script:childObjectKinds = @('Attribute','Dimension','Resource','AddressingAttribute','AccountingFlag','ExtDimensionAccountingFlag')
- # Виды подобъектов в -Object (Тип.Имя.<Вид>.<Имя>). Признак учёта субконто идёт только вместе с
- # ТЧ видов субконто (свойства ExtDimensionTypes у оболочки) — по одному не заимствуется.
- $script:subObjectKinds = @('Attribute','TabularSection','Dimension','Resource','AddressingAttribute','AccountingFlag')
- # Своя колонка в заимствованной ТЧ: у этих видов — отказ UpdateDBCfg на любой платформе, у БП и
- # Задачи — ниже 8.3.25 (граница по версии платформы, не по режиму)
- $script:tsOwnColumnsBlocked = @('ChartOfCharacteristicTypes','ChartOfAccounts','ChartOfCalculationTypes')
- $script:tsOwnColumnsFromPlatform = @{ 'BusinessProcess' = '8.3.25'; 'Task' = '8.3.25' }
- # Прямые дети <Form>, которые в заимствованную форму не переносятся.
- # Структурные секции: AutoCommandBar и ChildItems забираются отдельно, остальные выбрасываются целиком.
- $script:formStructuralSections = @('Events','Attributes','Commands','Parameters','CommandInterface')
- # Свойства формы, значение которых — имя реквизита формы (реквизиты не заимствуются, ссылка повиснет).
- $script:formAttributeRefProps = @('ReportResult','DetailsData','VariantAppearance','GroupList')
- # Strip data-binding tags whose root attribute isn't borrowed.
- # $mainAttrName задан (BorrowMainAttribute): оставить привязки от его имени, остальные снять.
- # Пусто (скелет без основного реквизита): снять все. Картиночные пути снимаются всегда.
- function Strip-FormBindings {
- param([string]$xml, [string]$mainAttrName)
- foreach ($tag in $script:formBindingDataTags) {
- if ($mainAttrName) {
- # Оставить и «Список.Поле», и путь ровно на сам реквизит («Список» у таблицы формы)
- $root = [regex]::Escape($mainAttrName)
- $xml = [regex]::Replace($xml, "\s*<$tag>(?!$root(\.|<))[^<]*</$tag>", '')
- } else {
- $xml = [regex]::Replace($xml, "\s*<$tag>[^<]*</$tag>", '')
- }
- }
- foreach ($tag in $script:formBindingPictureTags) {
- $xml = [regex]::Replace($xml, "\s*<$tag>[^<]*</$tag>", '')
- }
- return $xml
- }
- # Сдвиг блока на уровень вглубь для <BaseForm>; $firstIndent — отступ первой строки.
- # Таб добавляется только в пробельные промежутки между тегами: строки продолжения многострочного
- # текста (<v8:content>, текст запроса) — часть значения. Со сдвигом снимок расходился с формой,
- # и Конфигуратор показывал такой текст изменённым в расширении. Пробельный промежуток между
- # открывающим и закрывающим тегом одного элемента — тоже значение, его не сдвигаем.
- function Get-BaseFormIndented {
- param([string]$xml, [string]$firstIndent)
- $parts = [regex]::Split($xml, '(<(?:[^>"'']|"[^"]*"|''[^'']*'')*>)')
- for ($i = 0; $i -lt $parts.Count; $i += 2) {
- $seg = $parts[$i]
- if (-not $seg.Contains("`n") -or $seg.Trim()) { continue }
- $prevTag = if ($i -gt 0) { $parts[$i - 1] } else { '' }
- $nextTag = if ($i + 1 -lt $parts.Count) { $parts[$i + 1] } else { '' }
- $m = [regex]::Match($prevTag, '^<([\w:.-]+)[^>]*(?<!/)>$')
- if ($m.Success -and $nextTag -ceq "</$($m.Groups[1].Value)>") { continue }
- $parts[$i] = $seg.Replace("`n", "`n`t")
- }
- return $firstIndent + ($parts -join '')
- }
- # Связи формы — параметров выбора (<ChoiceParameterLinks>/<xr:Link>) и по типу (<TypeLink>) —
- # хранят путь в <xr:DataPath>, обычным стриппингом он не снимается. Путь — внутренняя ссылка
- # платформы: в выгрузке она пишет имя, а если имя в контексте формы не разрешается — код.
- # Текстовое имя в расширении разрешается, только если его корень объявлен в <Attributes> самой
- # заимствованной формы; иначе платформа отвергает загрузку — «Неверный путь к полю - X».
- # Конфигуратор поэтому пишет текст там, где он разрешается, и код — где нет.
- # Грамматика кода (оракул «код в форму конфигурации → загрузка → выгрузка → имя», 8.3.27; эталоны
- # Конфигуратора УТ и Issue66Example4-7, JR2433, JR2976, JR49904):
- # первый сегмент <id> — реквизит ИСХОДНОЙ формы (в расширении реквизиты
- # перенумерованы в 1000000+, ссылка остаётся в нумерации базы);
- # <id>:<CurrentData> — элемент-таблица исходной формы, её текущая строка;
- # дальше 0:<uuid> — реквизит/ТЧ/измерение/ресурс метаданных источника;
- # <id> — колонка реквизита формы;
- # <id>:<AddColumn> — колонка AdditionalColumns;
- # -<k> — стандартный реквизит, код по виду объекта ($script:stdFieldCodes).
- # В расширении платформа код обратно в имя не переводит, а висячий код грузит молча — ошибка
- # кодирования не упадёт, а тихо не сработает. Поэтому кодируется только измеренное; прочее
- # вырезается с предупреждением: связь — удобство подбора, без неё форма работает, с неверной
- # текстовой — не грузится вовсе.
- $script:linkCurrentData = '02023637-7868-4a5f-8576-835a76e0c9ba'
- $script:linkAddColumn = '5bdad865-f2c5-434b-8041-ba4aad3b6687'
- # Коды стандартных реквизитов — свой порядок у каждого вида (оракул 8.3.27; в XML объекта
- # полного списка нет). Незамеренное (-1, скрытые поля, колонки ExtDimensionTypes) — не кодируем.
- $script:stdFieldCodes = @{
- 'Catalog' = @{ Code=-2; Description=-3; Parent=-4; Owner=-5; IsFolder=-6; DeletionMark=-7; Ref=-8; DataVersion=-9; Predefined=-10; PredefinedDataName=-13 }
- 'Document' = @{ Number=-2; Date=-3; DeletionMark=-4; Ref=-5; DataVersion=-6; Posted=-7; RegisterRecords=-8 }
- 'ChartOfCharacteristicTypes' = @{ Ref=-2; DataVersion=-3; DeletionMark=-4; Predefined=-5; Parent=-6; IsFolder=-7; Code=-8; Description=-9; ValueType=-11; PredefinedDataName=-14 }
- 'ChartOfAccounts' = @{ Ref=-2; DataVersion=-3; DeletionMark=-4; Predefined=-5; Parent=-6; Code=-7; Description=-8; Type=-10; OffBalance=-11; ExtDimensionTypes=-12; Order=-17; PredefinedDataName=-28 }
- 'ChartOfCalculationTypes' = @{ Code=-2; Description=-3; ActionPeriodIsBasic=-4; DeletionMark=-5; Ref=-6; DataVersion=-7; Predefined=-8; PredefinedDataName=-11; DisplacingCalculationTypes=-20; LeadingCalculationTypes=-30 }
- 'ExchangePlan' = @{ Code=-2; Description=-3; DeletionMark=-4; Ref=-6; DataVersion=-7; SentNo=-9; ReceivedNo=-10; ThisNode=-13; ExchangeDate=-14 }
- 'BusinessProcess' = @{ Number=-2; Date=-3; DeletionMark=-4; Ref=-5; DataVersion=-6; Completed=-7; HeadTask=-8; Started=-9 }
- 'Task' = @{ Number=-2; Date=-3; DeletionMark=-4; Ref=-5; DataVersion=-6; BusinessProcess=-7; RoutePoint=-8; Description=-9; Executed=-10 }
- 'InformationRegisterRecord' = @{ Period=-2; Recorder=-3; LineNumber=-4; Active=-5 }
- 'AccumulationRegisterRow' = @{ Period=-2; Recorder=-3; LineNumber=-4; Active=-5; RecordType=-9; SecondPeriod=-10; MinutePeriod=-11; HourPeriod=-12; DayPeriod=-13; WeekPeriod=-14; TenDaysPeriod=-15 }
- 'TabularSectionRow' = @{ LineNumber=-2 }
- }
- # Тип основного реквизита → вид для таблицы стандартных кодов (запись РС — сам реквизит,
- # набор записей РН — строка таблицы на нём)
- $script:mainAttrKinds = @{
- 'CatalogObject'='Catalog'; 'DocumentObject'='Document'; 'ChartOfCharacteristicTypesObject'='ChartOfCharacteristicTypes'
- 'ChartOfAccountsObject'='ChartOfAccounts'; 'ChartOfCalculationTypesObject'='ChartOfCalculationTypes'
- 'ExchangePlanObject'='ExchangePlan'; 'BusinessProcessObject'='BusinessProcess'; 'TaskObject'='Task'
- 'InformationRegisterRecordManager'='InformationRegisterRecord'; 'AccumulationRegisterRecordSet'='AccumulationRegisterRow'
- 'ConstantsSet'='ConstantsSet'
- }
- # Путь связи → текст (разрешается в расширении), код или $null (вырезать).
- # $ctx: MainName, MainId, MainBorrowed, MainKind, BorrowedNames (реквизиты объекта в расширении;
- # $null — все), AttrUuids (имя/«ТЧ.Реквизит» → uuid),
- # FormAttrIds, FormAttrCols («Реквизит.Колонка» → id), AddCols («<путь таблицы>.Колонка» → id),
- # Tables (имя элемента-таблицы → @{ Id; Path }).
- function Resolve-LinkDataPath {
- param([string]$path, $ctx)
- # Уже код (форма-источник сама из расширения, или висячая ссылка в типовой) — как есть
- if ($path -match '^-?\d') { return $path }
- $main = $ctx.MainName
- # Текущая строка элемента-таблицы
- $cd = [regex]::Match($path, '^Items\.([^.]+)\.CurrentData\.([^.]+)$')
- if ($cd.Success) {
- $tbl = $ctx.Tables[$cd.Groups[1].Value]
- $field = $cd.Groups[2].Value
- if (-not $tbl) { return $null }
- $tp = $tbl.Path
- $prefix = "$($tbl.Id):$($script:linkCurrentData)"
- if ($main -and ($tp -ceq $main -or $tp.StartsWith("$main.", [StringComparison]::Ordinal))) {
- # Таблица на основном реквизите: с заимствованным — текст разрешается (эталоны 7_1, УТ)
- if ($ctx.MainBorrowed) { return $path }
- if ($tp -ceq $main) {
- # Строки самого основного реквизита — набор записей регистра накопления
- if ($ctx.MainKind -ne 'AccumulationRegisterRow') { return $null }
- if ($ctx.AttrUuids.ContainsKey($field)) { return "$prefix/0:$($ctx.AttrUuids[$field])" }
- $code = $script:stdFieldCodes['AccumulationRegisterRow'][$field]
- if ($code) { return "$prefix/$code" }
- return $null
- }
- $ts = $tp.Substring($main.Length + 1)
- if ($ts.Contains('.')) { return $null }
- if ($ctx.AttrUuids.ContainsKey("$ts.$field")) { return "$prefix/0:$($ctx.AttrUuids["$ts.$field"])" }
- if ($ctx.AddCols.ContainsKey("$tp.$field")) { return "$prefix/$($ctx.AddCols["$tp.$field"]):$($script:linkAddColumn)" }
- $code = $script:stdFieldCodes['TabularSectionRow'][$field]
- if ($code) { return "$prefix/$code" }
- return $null
- }
- # Таблица на реквизите формы: реквизиты формы не заимствуются никогда — только код
- # (текст платформа отвергает и с заимствованным основным реквизитом, оракул 8.3.27)
- if ($ctx.FormAttrIds.ContainsKey($tp) -and $ctx.FormAttrCols.ContainsKey("$tp.$field")) {
- return "$prefix/$($ctx.FormAttrCols["$tp.$field"])"
- }
- return $null
- }
- # Путь от основного реквизита формы
- if ($main -and $path.StartsWith("$main.", [StringComparison]::Ordinal)) {
- $rest = $path.Substring($main.Length + 1)
- if ($ctx.MainBorrowed) {
- # Заимствованный реквизит объекта разрешается текстом и остаётся читаемым. Стандартное
- # поле («Объект.Owner», «Объект.Date») и реквизит, который в расширение не попал (в режиме
- # Form заимствуется только используемое формой) — нет: платформа отвергает «Неверный путь
- # к полю». Конфигуратор в обоих случаях ставит ссылку на сам основной реквизит (эталоны
- # Issue66Example7_1 и УТ Претензии.ФормаЭлементаСамообслуживание).
- $borrowed = $null -eq $ctx.BorrowedNames -or $ctx.BorrowedNames.ContainsKey($rest.Split('.')[0])
- if ($borrowed -and $ctx.AttrUuids.ContainsKey($rest)) { return $path }
- return $ctx.MainId
- }
- # Код пути на константу набора не измерен — такую связь вырезаем, а не кодируем наугад
- if ($ctx.MainKind -eq 'ConstantsSet') { return $null }
- $segs = $rest.Split('.')
- if ($segs.Count -eq 1) {
- if ($ctx.AttrUuids.ContainsKey($rest)) { return "$($ctx.MainId)/0:$($ctx.AttrUuids[$rest])" }
- $codes = if ($ctx.MainKind) { $script:stdFieldCodes[$ctx.MainKind] } else { $null }
- if ($codes -and $codes.ContainsKey($rest)) { return "$($ctx.MainId)/$($codes[$rest])" }
- return $null
- }
- if ($segs.Count -eq 2 -and $ctx.AttrUuids.ContainsKey($segs[0]) -and $ctx.AttrUuids.ContainsKey($rest)) {
- return "$($ctx.MainId)/0:$($ctx.AttrUuids[$segs[0]])/0:$($ctx.AttrUuids[$rest])"
- }
- return $null
- }
- # Путь от реквизита формы — только по id исходной формы, в обоих режимах
- $segs = $path.Split('.')
- if ($ctx.FormAttrIds.ContainsKey($segs[0])) {
- $attrId = $ctx.FormAttrIds[$segs[0]]
- if ($segs.Count -eq 1) { return $attrId }
- if ($segs.Count -eq 2 -and $ctx.FormAttrCols.ContainsKey($path)) { return "$attrId/$($ctx.FormAttrCols[$path])" }
- return $null
- }
- # Прочее: с заимствованным основным реквизитом текст может разрешиться, без него — нет
- if ($ctx.MainBorrowed) { return $path }
- return $null
- }
- # Путь в <xr:DataPath> блока связи → разрешённый; неразрешимый блок вырезается целиком
- function Rewrite-LinkBlocks {
- param([string]$xml, [string]$blockPattern, $ctx)
- return [regex]::Replace($xml, $blockPattern, {
- param($m)
- $link = $m.Value
- $dp = [regex]::Match($link, '<xr:DataPath[^>]*>([^<]+)</xr:DataPath>')
- if (-not $dp.Success) { return $link }
- $path = $dp.Groups[1].Value
- $resolved = Resolve-LinkDataPath $path $ctx
- if ($null -eq $resolved) {
- $script:droppedLinks += $path
- return ''
- }
- if ($resolved -ceq $path) { return $link }
- return $link.Substring(0, $dp.Groups[1].Index) + $resolved + $link.Substring($dp.Groups[1].Index + $dp.Groups[1].Length)
- })
- }
- function Rewrite-ChoiceParameterLinks {
- param([string]$xml, $ctx)
- if ($xml -notmatch '<ChoiceParameterLinks>') { return $xml }
- $xml = Rewrite-LinkBlocks $xml '(?s)\s*<xr:Link>.*?</xr:Link>' $ctx
- # Опустевший контейнер платформе не нужен
- $xml = [regex]::Replace($xml, '(?s)\s*<ChoiceParameterLinks>\s*</ChoiceParameterLinks>', '')
- return $xml
- }
- # Связь по типу — тот же путь и то же правило (эталоны УТ ВводОстатков.ФормаРасчетыМеждуОрганизациями:
- # без основного реквизита — код, с ним — текст)
- function Rewrite-TypeLinks {
- param([string]$xml, $ctx)
- if ($xml -notmatch '<TypeLink>') { return $xml }
- return Rewrite-LinkBlocks $xml '(?s)\s*<TypeLink>.*?</TypeLink>' $ctx
- }
- # Имена ПРЯМЫХ детей собственного <ChildObjects> объекта — для дедупа при повторном
- # заимствовании. Текстом это не снять: regex «первый <ChildObjects> до первого </ChildObjects>»
- # у объекта с табличными частями обрывается на закрытии первой ТЧ, забирает имена её колонок и
- # теряет то, что идёт после неё.
- function Get-OwnChildObjectNames {
- param([string]$objFile)
- $names = @{}
- if (-not (Test-Path -LiteralPath $objFile)) { return $names }
- $doc = New-Object System.Xml.XmlDocument
- $doc.PreserveWhitespace = $false
- try { $doc.Load($objFile) } catch { return $names }
- $objEl = $null
- foreach ($c in $doc.DocumentElement.ChildNodes) {
- if ($c.NodeType -eq 'Element') { $objEl = $c; break }
- }
- if (-not $objEl) { return $names }
- $childObjs = $objEl.SelectSingleNode("*[local-name()='ChildObjects']")
- if (-not $childObjs) { return $names }
- foreach ($child in $childObjs.ChildNodes) {
- if ($child.NodeType -ne 'Element') { continue }
- $nameNode = $child.SelectSingleNode("*[local-name()='Properties']/*[local-name()='Name']")
- if ($nameNode) { $names[$nameNode.InnerText.Trim()] = $true }
- }
- return $names
- }
- # Порядок групп в <ChildObjects> объекта по виду. Это xs:sequence <Вид>ChildObjects из MDClasses XSD,
- # сверенный выгрузкой платформы: выгрузка сама ставит группы в этот порядок, так что вставка не на место
- # даёт дифф при следующей выгрузке. Единого порядка нет — у документа Form стоит до TabularSection.
- function Get-ObjectChildOrder {
- return @{
- "Catalog" = @("Attribute", "TabularSection", "Form", "Template", "Command")
- "Document" = @("Attribute", "Form", "TabularSection", "Template", "Command")
- "ExchangePlan" = @("Attribute", "TabularSection", "Form", "Template", "Command")
- "ChartOfCharacteristicTypes" = @("Attribute", "TabularSection", "Form", "Template", "Command")
- "ChartOfAccounts" = @("Attribute", "TabularSection", "AccountingFlag", "ExtDimensionAccountingFlag", "Form", "Template", "Command")
- "ChartOfCalculationTypes" = @("Attribute", "TabularSection", "Form", "Template", "Command")
- "BusinessProcess" = @("Attribute", "TabularSection", "Form", "Template", "Command")
- "Task" = @("Attribute", "TabularSection", "Form", "Template", "AddressingAttribute", "Command")
- "DataProcessor" = @("Attribute", "TabularSection", "Form", "Template", "Command")
- "Report" = @("Attribute", "TabularSection", "Form", "Template", "Command")
- "ExternalDataProcessor" = @("Attribute", "TabularSection", "Form", "Template")
- "ExternalReport" = @("Attribute", "TabularSection", "Form", "Template")
- "Enum" = @("EnumValue", "Form", "Template", "Command")
- "InformationRegister" = @("Resource", "Attribute", "Dimension", "Form", "Template", "Command")
- "AccumulationRegister" = @("Resource", "Attribute", "Dimension", "Form", "Template", "Command")
- "AccountingRegister" = @("Dimension", "Resource", "Attribute", "Form", "Template", "Command")
- "CalculationRegister" = @("Resource", "Attribute", "Dimension", "Recalculation", "Form", "Template", "Command")
- "DocumentJournal" = @("Column", "Form", "Template", "Command")
- "Table" = @("Field", "Form", "Command", "Template")
- "ExternalDataSource" = @("Table", "Cube", "Function")
- "Cube" = @("DimensionTable", "Dimension", "Resource", "Form", "Command", "Template")
- "DimensionTable" = @("Field", "Form", "Command", "Template")
- "FilterCriterion" = @("Form", "Command")
- "SettingsStorage" = @("Form", "Template")
- "TabularSection" = @("Attribute")
- }
- }
- # Элемент <ChildObjects>, ПЕРЕД которым встаёт новый <tag>; $null — дописать в конец.
- # Сразу за последним элементом своего тега, иначе перед первым элементом группы, идущей
- # по канону вида позже. Вид или тег вне канона — $null, как раньше.
- function Find-ChildAnchor($container, [string]$tag, [string]$objType) {
- $children = New-Object System.Collections.Generic.List[object]
- foreach ($c in $container.ChildNodes) { if ($c.NodeType -eq 'Element') { $children.Add($c) } }
- $lastIdx = -1
- for ($i = 0; $i -lt $children.Count; $i++) {
- if ($children[$i].LocalName -ceq $tag) { $lastIdx = $i }
- }
- if ($lastIdx -ge 0) {
- if ($lastIdx + 1 -lt $children.Count) { return $children[$lastIdx + 1] }
- return $null
- }
- $order = (Get-ObjectChildOrder)[$objType]
- if (-not $order) { return $null }
- $tagIdx = [array]::IndexOf([string[]]$order, $tag)
- if ($tagIdx -lt 0) { return $null }
- $later = @($order | Select-Object -Skip ($tagIdx + 1))
- foreach ($c in $children) {
- if ($later -ccontains $c.LocalName) { return $c }
- }
- return $null
- }
- # Вставка ОДНОГО узла <tag> ($fragment — с отступом прямого ребёнка) в СОБСТВЕННЫЙ <ChildObjects>
- # объекта на место по канону вида — как Find-ChildAnchor, только по тексту: за последним своим тегом,
- # иначе перед первой группой, идущей по канону позже, иначе перед закрывающим тегом. Свой контейнер
- # открывается первым (свойства объекта <ChildObjects> не содержат) и закрывается последним: вложенные
- # <ChildObjects> табличных частей лежат внутри него, поиск «первого </ChildObjects>» уводил вставку в ТЧ.
- # Прямые дети — по глубине вложенности, не по отступу. Строку с одним тегом дополняем целой строкой,
- # перевод строки — из самого файла. $null — своего <ChildObjects> у объекта нет.
- function Insert-IntoOwnChildObjectsByCanon {
- param([string]$text, [string]$fragment, [string]$tag, [string]$objType)
- $eol = if ($text.Contains("`r`n")) { "`r`n" } else { "`n" }
- $frag = ($fragment.TrimEnd().TrimStart([char[]]"`r`n") -replace "`r`n", "`n") -replace "`n", $eol
- $mOpen = [regex]::Match($text, '<ChildObjects\b[^>]*?(/?)>')
- if (-not $mOpen.Success) { return $null }
- # Начало строки и отступ до позиции p; Indent = $null — перед p на строке есть что-то кроме пробелов
- $lineAt = {
- param([int]$p)
- $ls = if ($p -gt 0) { $text.LastIndexOf("`n", $p - 1) + 1 } else { 0 }
- $pre = $text.Substring($ls, $p - $ls)
- @{ Start = $ls; Indent = $(if ($pre.Trim().Length -eq 0) { $pre } else { $null }) }
- }
- if ($mOpen.Groups[1].Value) {
- # Контейнер самозакрытый — детей у него нет, раскрыть с единственным узлом
- $ind = (& $lineAt $mOpen.Index).Indent
- if ($null -eq $ind) { $ind = "" }
- return $text.Substring(0, $mOpen.Index) + "<ChildObjects>" + $eol + $frag + $eol + $ind + "</ChildObjects>" + $text.Substring($mOpen.Index + $mOpen.Length)
- }
- $closes = [regex]::Matches($text, '</ChildObjects\s*>')
- if ($closes.Count -eq 0) { return $null }
- $mClose = $closes[$closes.Count - 1]
- $bodyStart = $mOpen.Index + $mOpen.Length
- if ($mClose.Index -lt $bodyStart) { return $null }
- $starts = New-Object System.Collections.Generic.List[object]
- $depth = 0
- foreach ($m in [regex]::Matches($text.Substring($bodyStart, $mClose.Index - $bodyStart), '<(/?)([\w:.-]+)[^>]*?(/?)>')) {
- if ($m.Groups[1].Value) { $depth--; continue }
- if ($depth -eq 0) {
- $nm = $m.Groups[2].Value
- $starts.Add(@{ Pos = $bodyStart + $m.Index; Tag = $nm.Substring($nm.LastIndexOf(':') + 1) })
- }
- if (-not $m.Groups[3].Value) { $depth++ }
- }
- $pos = $mClose.Index
- $lastIdx = -1
- for ($i = 0; $i -lt $starts.Count; $i++) { if ($starts[$i].Tag -ceq $tag) { $lastIdx = $i } }
- $order = (Get-ObjectChildOrder)[$objType]
- if ($lastIdx -ge 0) {
- if ($lastIdx + 1 -lt $starts.Count) { $pos = $starts[$lastIdx + 1].Pos }
- } elseif ($order -and ($order -ccontains $tag)) {
- $later = @($order | Select-Object -Skip ([array]::IndexOf([string[]]$order, $tag) + 1))
- foreach ($s in $starts) { if ($later -ccontains $s.Tag) { $pos = $s.Pos; break } }
- }
- $line = & $lineAt $pos
- if ($null -ne $line.Indent) {
- return $text.Substring(0, $line.Start) + $frag + $eol + $text.Substring($line.Start)
- }
- return $text.Substring(0, $pos) + $frag.TrimStart() + $text.Substring($pos)
- }
- # Insert-IntoOwnChildObjectsByCanon, но своего <ChildObjects> нет — создать его последним ребёнком
- # элемента объекта; вставить всё равно некуда — отказ, а не молчаливое «добавлено».
- function Insert-OwnChildOrDie {
- param([string]$text, [string]$fragment, [string]$tag, [string]$objType, [string]$objFile)
- if (-not [regex]::IsMatch($text, '<ChildObjects\b')) {
- $ends = [regex]::Matches($text, '</' + [regex]::Escape($objType) + '\s*>')
- if ($ends.Count -gt 0) {
- $mEnd = $ends[$ends.Count - 1]
- $ls = if ($mEnd.Index -gt 0) { $text.LastIndexOf("`n", $mEnd.Index - 1) + 1 } else { 0 }
- $pre = $text.Substring($ls, $mEnd.Index - $ls)
- if ($pre.Trim().Length -eq 0) {
- $eol = if ($text.Contains("`r`n")) { "`r`n" } else { "`n" }
- $text = $text.Substring(0, $ls) + $pre + "`t<ChildObjects/>" + $eol + $text.Substring($ls)
- } else {
- $text = $text.Substring(0, $mEnd.Index) + "<ChildObjects/>" + $text.Substring($mEnd.Index)
- }
- }
- }
- $result = Insert-IntoOwnChildObjectsByCanon $text $fragment $tag $objType
- if ($null -eq $result) {
- Write-Error "Cannot insert <${tag}>: no own <ChildObjects> in $objFile"
- exit 1
- }
- return $result
- }
- # --- 1. Resolve paths ---
- if (-not [System.IO.Path]::IsPathRooted($ExtensionPath)) {
- $ExtensionPath = Join-Path (Get-Location).ProviderPath $ExtensionPath
- }
- if (Test-Path $ExtensionPath -PathType Container) {
- $candidate = Join-Path $ExtensionPath "Configuration.xml"
- if (Test-Path $candidate) { $ExtensionPath = $candidate }
- else { Write-Error "No Configuration.xml in extension directory: $ExtensionPath"; exit 1 }
- }
- if (-not (Test-Path $ExtensionPath)) { Write-Error "Extension file not found: $ExtensionPath"; exit 1 }
- $extResolvedPath = (Resolve-Path $ExtensionPath).ProviderPath
- $extDir = Split-Path $extResolvedPath -Parent
- if (-not [System.IO.Path]::IsPathRooted($ConfigPath)) {
- $ConfigPath = Join-Path (Get-Location).ProviderPath $ConfigPath
- }
- if (Test-Path $ConfigPath -PathType Container) {
- $candidate = Join-Path $ConfigPath "Configuration.xml"
- if (Test-Path $candidate) { $ConfigPath = $candidate }
- else { Write-Error "No Configuration.xml in config directory: $ConfigPath"; exit 1 }
- }
- if (-not (Test-Path $ConfigPath)) { Write-Error "Config file not found: $ConfigPath"; exit 1 }
- $cfgResolvedPath = (Resolve-Path $ConfigPath).ProviderPath
- $cfgDir = Split-Path $cfgResolvedPath -Parent
- # --- 2. Load extension Configuration.xml ---
- $script:xmlDoc = New-Object System.Xml.XmlDocument
- $script:xmlDoc.PreserveWhitespace = $true
- $script:xmlDoc.Load($extResolvedPath)
- $script:mdNs = "http://v8.1c.ru/8.3/MDClasses"
- $script:xrNs = "http://v8.1c.ru/8.3/xcf/readable"
- $script:xsiNs = "http://www.w3.org/2001/XMLSchema-instance"
- $script:v8Ns = "http://v8.1c.ru/8.1/data/core"
- $root = $script:xmlDoc.DocumentElement
- $script:cfgEl = $null
- foreach ($child in $root.ChildNodes) {
- if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Configuration") {
- $script:cfgEl = $child; break
- }
- }
- if (-not $script:cfgEl) { Write-Error "No <Configuration> element found in extension"; exit 1 }
- $script:propsEl = $null
- $script:childObjsEl = $null
- foreach ($child in $script:cfgEl.ChildNodes) {
- if ($child.NodeType -ne 'Element') { continue }
- if ($child.LocalName -eq "Properties") { $script:propsEl = $child }
- if ($child.LocalName -eq "ChildObjects") { $script:childObjsEl = $child }
- }
- if (-not $script:propsEl) { Write-Error "No <Properties> element found in extension"; exit 1 }
- if (-not $script:childObjsEl) { Write-Error "No <ChildObjects> element found in extension"; exit 1 }
- # --- 3. Extract NamePrefix ---
- $script:namePrefix = ""
- foreach ($child in $script:propsEl.ChildNodes) {
- if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "NamePrefix") {
- $script:namePrefix = $child.InnerText.Trim(); break
- }
- }
- Info "Extension NamePrefix: $($script:namePrefix)"
- # --- 4. Type mappings ---
- $childTypeDirMap = @{
- "Catalog"="Catalogs"; "Document"="Documents"; "Enum"="Enums"
- "CommonModule"="CommonModules"; "CommonPicture"="CommonPictures"
- "CommonCommand"="CommonCommands"; "CommonTemplate"="CommonTemplates"
- "ExchangePlan"="ExchangePlans"; "Report"="Reports"; "DataProcessor"="DataProcessors"
- "InformationRegister"="InformationRegisters"; "AccumulationRegister"="AccumulationRegisters"
- "ChartOfCharacteristicTypes"="ChartsOfCharacteristicTypes"
- "ChartOfAccounts"="ChartsOfAccounts"; "AccountingRegister"="AccountingRegisters"
- "ChartOfCalculationTypes"="ChartsOfCalculationTypes"; "CalculationRegister"="CalculationRegisters"
- "BusinessProcess"="BusinessProcesses"; "Task"="Tasks"
- "Subsystem"="Subsystems"; "Role"="Roles"; "Constant"="Constants"
- "FunctionalOption"="FunctionalOptions"; "DefinedType"="DefinedTypes"
- "FunctionalOptionsParameter"="FunctionalOptionsParameters"
- "CommonForm"="CommonForms"; "DocumentJournal"="DocumentJournals"
- "SessionParameter"="SessionParameters"; "StyleItem"="StyleItems"
- "EventSubscription"="EventSubscriptions"; "ScheduledJob"="ScheduledJobs"
- "SettingsStorage"="SettingsStorages"; "FilterCriterion"="FilterCriteria"
- "CommandGroup"="CommandGroups"; "DocumentNumerator"="DocumentNumerators"
- "Sequence"="Sequences"; "ExternalDataSource"="ExternalDataSources"; "IntegrationService"="IntegrationServices"
- "XDTOPackage"="XDTOPackages"; "WebService"="WebServices"
- "HTTPService"="HTTPServices"; "WSReference"="WSReferences"
- "CommonAttribute"="CommonAttributes"; "Style"="Styles"; "Bot"="Bots"; "PaletteColor"="PaletteColors"; "Language"="Languages"
- }
- # --- 4a. Модули заимствованных объектов ---
- # Порядок внутри значения — порядок выгрузки Конфигуратора: сначала «объектный» модуль
- # (ObjectModule / RecordSetModule / ValueManagerModule), затем ManagerModule.
- $script:moduleKindsByType = @{
- "CommonModule"=@("Module"); "HTTPService"=@("Module"); "WebService"=@("Module")
- "Catalog"=@("ObjectModule","ManagerModule"); "Document"=@("ObjectModule","ManagerModule")
- "Report"=@("ObjectModule","ManagerModule"); "DataProcessor"=@("ObjectModule","ManagerModule")
- "ExchangePlan"=@("ObjectModule","ManagerModule")
- "ChartOfCharacteristicTypes"=@("ObjectModule","ManagerModule")
- "ChartOfAccounts"=@("ObjectModule","ManagerModule")
- "ChartOfCalculationTypes"=@("ObjectModule","ManagerModule")
- "BusinessProcess"=@("ObjectModule","ManagerModule"); "Task"=@("ObjectModule","ManagerModule")
- "InformationRegister"=@("RecordSetModule","ManagerModule")
- "AccumulationRegister"=@("RecordSetModule","ManagerModule")
- "AccountingRegister"=@("RecordSetModule","ManagerModule")
- "CalculationRegister"=@("RecordSetModule","ManagerModule")
- "Sequence"=@("RecordSetModule","ManagerModule")
- "Constant"=@("ValueManagerModule","ManagerModule")
- "Enum"=@("ManagerModule"); "DocumentJournal"=@("ManagerModule")
- "FilterCriterion"=@("ManagerModule")
- }
- # Типы с ЕДИНСТВЕННЫМ модулем: ради него объект и заимствуют, поэтому файл создаётся молча.
- # Отказ — `-Module None`.
- $script:autoModuleTypes = @("CommonModule", "HTTPService", "WebService")
- $script:moduleKindNames = @("Module", "ObjectModule", "ManagerModule", "RecordSetModule", "ValueManagerModule")
- # --- 4b. Russian synonym → English type ---
- $synonymMap = @{
- "Справочник"="Catalog"; "Документ"="Document"; "Перечисление"="Enum"
- "ОбщийМодуль"="CommonModule"; "ОбщаяКартинка"="CommonPicture"
- "ОбщаяКоманда"="CommonCommand"; "ОбщийМакет"="CommonTemplate"
- "ПланОбмена"="ExchangePlan"; "Отчет"="Report"; "Отчёт"="Report"
- "Обработка"="DataProcessor"; "РегистрСведений"="InformationRegister"
- "РегистрНакопления"="AccumulationRegister"
- "ПланВидовХарактеристик"="ChartOfCharacteristicTypes"
- "ПланСчетов"="ChartOfAccounts"; "РегистрБухгалтерии"="AccountingRegister"
- "ПланВидовРасчета"="ChartOfCalculationTypes"; "РегистрРасчета"="CalculationRegister"
- "БизнесПроцесс"="BusinessProcess"; "Задача"="Task"
- "Подсистема"="Subsystem"; "Роль"="Role"; "Константа"="Constant"
- "ФункциональнаяОпция"="FunctionalOption"; "ОпределяемыйТип"="DefinedType"
- "ОбщаяФорма"="CommonForm"; "ЖурналДокументов"="DocumentJournal"
- "ПараметрСеанса"="SessionParameter"; "ГруппаКоманд"="CommandGroup"
- "ПодпискаНаСобытие"="EventSubscription"; "РегламентноеЗадание"="ScheduledJob"
- "ОбщийРеквизит"="CommonAttribute"; "ПакетXDTO"="XDTOPackage"
- "HTTPСервис"="HTTPService"; "СервисИнтеграции"="IntegrationService"
- }
- # --- 5. Canonical type order (46 types) ---
- $script:typeOrder = @(
- "Language","Subsystem","StyleItem","Style",
- "CommonPicture","SessionParameter","Role","CommonTemplate",
- "FilterCriterion","CommonModule","CommonAttribute","ExchangePlan",
- "XDTOPackage","WebService","HTTPService","WSReference",
- "EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
- "FunctionalOptionsParameter","DefinedType","Bot","PaletteColor","CommonCommand","CommandGroup",
- "Constant","CommonForm","Catalog","Document",
- "DocumentNumerator","Sequence","DocumentJournal","Enum",
- "Report","DataProcessor","InformationRegister","AccumulationRegister",
- "ChartOfCharacteristicTypes","ChartOfAccounts","AccountingRegister",
- "ChartOfCalculationTypes","CalculationRegister",
- "BusinessProcess","Task","ExternalDataSource","IntegrationService"
- )
- # --- 6. GeneratedType patterns per type ---
- $script:generatedTypes = @{
- "Catalog" = @(
- @{ prefix = "CatalogObject"; category = "Object" }
- @{ prefix = "CatalogRef"; category = "Ref" }
- @{ prefix = "CatalogSelection"; category = "Selection" }
- @{ prefix = "CatalogList"; category = "List" }
- @{ prefix = "CatalogManager"; category = "Manager" }
- )
- "Document" = @(
- @{ prefix = "DocumentObject"; category = "Object" }
- @{ prefix = "DocumentRef"; category = "Ref" }
- @{ prefix = "DocumentSelection"; category = "Selection" }
- @{ prefix = "DocumentList"; category = "List" }
- @{ prefix = "DocumentManager"; category = "Manager" }
- )
- "Enum" = @(
- @{ prefix = "EnumRef"; category = "Ref" }
- @{ prefix = "EnumManager"; category = "Manager" }
- @{ prefix = "EnumList"; category = "List" }
- )
- "Constant" = @(
- @{ prefix = "ConstantManager"; category = "Manager" }
- @{ prefix = "ConstantValueManager"; category = "ValueManager" }
- @{ prefix = "ConstantValueKey"; category = "ValueKey" }
- )
- "InformationRegister" = @(
- @{ prefix = "InformationRegisterRecord"; category = "Record" }
- @{ prefix = "InformationRegisterManager"; category = "Manager" }
- @{ prefix = "InformationRegisterSelection"; category = "Selection" }
- @{ prefix = "InformationRegisterList"; category = "List" }
- @{ prefix = "InformationRegisterRecordSet"; category = "RecordSet" }
- @{ prefix = "InformationRegisterRecordKey"; category = "RecordKey" }
- @{ prefix = "InformationRegisterRecordManager"; category = "RecordManager" }
- )
- "AccumulationRegister" = @(
- @{ prefix = "AccumulationRegisterRecord"; category = "Record" }
- @{ prefix = "AccumulationRegisterManager"; category = "Manager" }
- @{ prefix = "AccumulationRegisterSelection"; category = "Selection" }
- @{ prefix = "AccumulationRegisterList"; category = "List" }
- @{ prefix = "AccumulationRegisterRecordSet"; category = "RecordSet" }
- @{ prefix = "AccumulationRegisterRecordKey"; category = "RecordKey" }
- )
- "AccountingRegister" = @(
- @{ prefix = "AccountingRegisterRecord"; category = "Record" }
- @{ prefix = "AccountingRegisterExtDimensions"; category = "ExtDimensions" }
- @{ prefix = "AccountingRegisterManager"; category = "Manager" }
- @{ prefix = "AccountingRegisterSelection"; category = "Selection" }
- @{ prefix = "AccountingRegisterList"; category = "List" }
- @{ prefix = "AccountingRegisterRecordSet"; category = "RecordSet" }
- @{ prefix = "AccountingRegisterRecordKey"; category = "RecordKey" }
- )
- "CalculationRegister" = @(
- @{ prefix = "CalculationRegisterRecord"; category = "Record" }
- @{ prefix = "CalculationRegisterManager"; category = "Manager" }
- @{ prefix = "CalculationRegisterSelection"; category = "Selection" }
- @{ prefix = "CalculationRegisterList"; category = "List" }
- @{ prefix = "CalculationRegisterRecordSet"; category = "RecordSet" }
- @{ prefix = "CalculationRegisterRecordKey"; category = "RecordKey" }
- @{ prefix = "RecalculationsManager"; category = "Recalcs" }
- )
- "ChartOfAccounts" = @(
- @{ prefix = "ChartOfAccountsObject"; category = "Object" }
- @{ prefix = "ChartOfAccountsRef"; category = "Ref" }
- @{ prefix = "ChartOfAccountsSelection"; category = "Selection" }
- @{ prefix = "ChartOfAccountsList"; category = "List" }
- @{ prefix = "ChartOfAccountsManager"; category = "Manager" }
- @{ prefix = "ChartOfAccountsExtDimensionTypes"; category = "ExtDimensionTypes" }
- @{ prefix = "ChartOfAccountsExtDimensionTypesRow"; category = "ExtDimensionTypesRow" }
- )
- "ChartOfCharacteristicTypes" = @(
- @{ prefix = "ChartOfCharacteristicTypesObject"; category = "Object" }
- @{ prefix = "ChartOfCharacteristicTypesRef"; category = "Ref" }
- @{ prefix = "ChartOfCharacteristicTypesSelection"; category = "Selection" }
- @{ prefix = "ChartOfCharacteristicTypesList"; category = "List" }
- @{ prefix = "Characteristic"; category = "Characteristic" }
- @{ prefix = "ChartOfCharacteristicTypesManager"; category = "Manager" }
- )
- "ChartOfCalculationTypes" = @(
- @{ prefix = "ChartOfCalculationTypesObject"; category = "Object" }
- @{ prefix = "ChartOfCalculationTypesRef"; category = "Ref" }
- @{ prefix = "ChartOfCalculationTypesSelection"; category = "Selection" }
- @{ prefix = "ChartOfCalculationTypesList"; category = "List" }
- @{ prefix = "ChartOfCalculationTypesManager"; category = "Manager" }
- @{ prefix = "DisplacingCalculationTypes"; category = "DisplacingCalculationTypes" }
- @{ prefix = "DisplacingCalculationTypesRow"; category = "DisplacingCalculationTypesRow" }
- @{ prefix = "BaseCalculationTypes"; category = "BaseCalculationTypes" }
- @{ prefix = "BaseCalculationTypesRow"; category = "BaseCalculationTypesRow" }
- @{ prefix = "LeadingCalculationTypes"; category = "LeadingCalculationTypes" }
- @{ prefix = "LeadingCalculationTypesRow"; category = "LeadingCalculationTypesRow" }
- )
- "BusinessProcess" = @(
- @{ prefix = "BusinessProcessObject"; category = "Object" }
- @{ prefix = "BusinessProcessRef"; category = "Ref" }
- @{ prefix = "BusinessProcessSelection"; category = "Selection" }
- @{ prefix = "BusinessProcessList"; category = "List" }
- @{ prefix = "BusinessProcessManager"; category = "Manager" }
- @{ prefix = "BusinessProcessRoutePointRef"; category = "RoutePointRef" }
- )
- "Task" = @(
- @{ prefix = "TaskObject"; category = "Object" }
- @{ prefix = "TaskRef"; category = "Ref" }
- @{ prefix = "TaskSelection"; category = "Selection" }
- @{ prefix = "TaskList"; category = "List" }
- @{ prefix = "TaskManager"; category = "Manager" }
- )
- "ExchangePlan" = @(
- @{ prefix = "ExchangePlanObject"; category = "Object" }
- @{ prefix = "ExchangePlanRef"; category = "Ref" }
- @{ prefix = "ExchangePlanSelection"; category = "Selection" }
- @{ prefix = "ExchangePlanList"; category = "List" }
- @{ prefix = "ExchangePlanManager"; category = "Manager" }
- )
- "DocumentJournal" = @(
- @{ prefix = "DocumentJournalSelection"; category = "Selection" }
- @{ prefix = "DocumentJournalList"; category = "List" }
- @{ prefix = "DocumentJournalManager"; category = "Manager" }
- )
- "Report" = @(
- @{ prefix = "ReportObject"; category = "Object" }
- @{ prefix = "ReportManager"; category = "Manager" }
- )
- "DataProcessor" = @(
- @{ prefix = "DataProcessorObject"; category = "Object" }
- @{ prefix = "DataProcessorManager"; category = "Manager" }
- )
- "DefinedType" = @(
- @{ prefix = "DefinedType"; category = "DefinedType" }
- )
- "ExternalDataSource" = @(
- @{ prefix = "ExternalDataSourceManager"; category = "Manager" }
- @{ prefix = "ExternalDataSourceTablesManager"; category = "TablesManager" }
- @{ prefix = "ExternalDataSourceCubesManager"; category = "CubesManager" }
- )
- "Sequence" = @(
- @{ prefix = "SequenceRecord"; category = "Record" }
- @{ prefix = "SequenceManager"; category = "Manager" }
- @{ prefix = "SequenceRecordSet"; category = "RecordSet" }
- )
- "FilterCriterion" = @(
- @{ prefix = "FilterCriterionManager"; category = "Manager" }
- @{ prefix = "FilterCriterionList"; category = "List" }
- )
- "SettingsStorage" = @(
- @{ prefix = "SettingsStorageManager"; category = "Manager" }
- )
- "IntegrationService" = @(
- @{ prefix = "IntegrationServiceManager"; category = "Manager" }
- )
- "WSReference" = @(
- @{ prefix = "WSReferenceManager"; category = "Manager" }
- )
- }
- # Types that need ChildObjects element — fallback when the source object cannot be probed.
- # The platform emits <ChildObjects> for every container type even when empty, and rejects
- # the file without it ("ожидаемое ChildObjects"); primary signal is the source object itself.
- $typesWithChildObjects = @(
- "Catalog","Document","ExchangePlan","ChartOfAccounts",
- "ChartOfCharacteristicTypes","ChartOfCalculationTypes",
- "BusinessProcess","Task","Enum",
- "InformationRegister","AccumulationRegister","AccountingRegister","CalculationRegister",
- "DataProcessor","Report","DocumentJournal","FilterCriterion","SettingsStorage",
- "Sequence","HTTPService","WebService","IntegrationService","Subsystem"
- )
- # CommonModule properties to copy from source
- $commonModuleProps = @("Global","ClientManagedApplication","Server","ExternalConnection","ClientOrdinaryApplication","ServerCall")
- # Свойства объекта, от которых зависит существование стандартного поля: без них платформа
- # отвергает загрузку — «Неверный путь к данным». Конфигуратор переносит ровно их (эталоны
- # Issue66Example7_1 и Issue66Example2). Проверено сплошным прогоном по типам: у регистра сведений
- # без InformationRegisterPeriodicity не разрешается «Запись.Period».
- # Тем же путём переносится код языка: платформа принимает заимствованный язык и без него, но
- # конфигуратор пишет LanguageCode у любого заимствованного языка, основного и неосновного (замер 8.3.24).
- $script:typeGateProps = @{
- "InformationRegister" = @("InformationRegisterPeriodicity","WriteMode")
- "Language" = @("LanguageCode")
- }
- # Владельцы справочника — список <xr:Item>, а не скаляр: переносится фрагментом, как __TypeXml
- $script:typesWithOwners = @("Catalog","ChartOfCharacteristicTypes")
- # Standard system fields to skip when collecting DataPath references
- $script:standardFields = @("Code","Description","Ref","Parent","DeletionMark","Predefined","IsFolder","LineNumber","RowsCount","PredefinedDataName")
- # --- 7. XML manipulation helpers (from cf-edit) ---
- function Get-ChildIndent($container) {
- foreach ($child in $container.ChildNodes) {
- if ($child.NodeType -eq 'Whitespace' -or $child.NodeType -eq 'SignificantWhitespace') {
- if ($child.Value -match '^\r?\n(\t+)$') { return $Matches[1] }
- if ($child.Value -match '^\r?\n(\t+)') { return $Matches[1] }
- }
- }
- $depth = 0; $current = $container
- while ($current -and $current -ne $script:xmlDoc.DocumentElement) { $depth++; $current = $current.ParentNode }
- return "`t" * ($depth + 1)
- }
- function Insert-BeforeElement($container, $newNode, $refNode, $childIndent) {
- $ws = $script:xmlDoc.CreateWhitespace("`r`n$childIndent")
- if ($refNode) {
- $container.InsertBefore($ws, $refNode) | Out-Null
- $container.InsertBefore($newNode, $ws) | Out-Null
- } else {
- $trailing = $container.LastChild
- if ($trailing -and ($trailing.NodeType -eq 'Whitespace' -or $trailing.NodeType -eq 'SignificantWhitespace')) {
- $container.InsertBefore($ws, $trailing) | Out-Null
- $container.InsertBefore($newNode, $trailing) | Out-Null
- } else {
- $container.AppendChild($ws) | Out-Null
- $container.AppendChild($newNode) | Out-Null
- $parentIndent = if ($childIndent.Length -gt 1) { $childIndent.Substring(0, $childIndent.Length - 1) } else { "" }
- $closeWs = $script:xmlDoc.CreateWhitespace("`r`n$parentIndent")
- $container.AppendChild($closeWs) | Out-Null
- }
- }
- }
- function Expand-SelfClosingElement($container, $parentIndent) {
- if (-not $container.HasChildNodes -or $container.IsEmpty) {
- $closeWs = $script:xmlDoc.CreateWhitespace("`r`n$parentIndent")
- $container.AppendChild($closeWs) | Out-Null
- }
- }
- # --- 7b. Detect format version ---
- function Detect-FormatVersion([string]$dir) {
- $d = $dir
- while ($d) {
- # Автономная внешняя обработка/отчёт: своего Configuration.xml у неё нет, версию несёт
- # корень самой обработки. Без этого форма и макет внутри обработки 2.21 писались бы 2.17.
- $extPath = "$d.xml"
- if (Test-Path $extPath) {
- $extText = [System.IO.File]::ReadAllText($extPath, [System.Text.Encoding]::UTF8)
- $extHead = $extText.Substring(0, [Math]::Min(2000, $extText.Length))
- if ($extHead -match '<(ExternalDataProcessor|ExternalReport)[ >]' -and $extHead -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
- }
- $cfgPath = Join-Path $d "Configuration.xml"
- if (Test-Path $cfgPath) {
- $cfgText = [System.IO.File]::ReadAllText($cfgPath, [System.Text.Encoding]::UTF8)
- # Длину среза берём по СТРОКЕ, а не по размеру файла: размер в БАЙТАХ, Substring считает
- # СИМВОЛЫ, и на кириллице байт больше — короткий Configuration.xml ронял навык исключением.
- $head = $cfgText.Substring(0, [Math]::Min(2000, $cfgText.Length))
- if ($head -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
- }
- $parent = Split-Path $d -Parent
- if ($parent -eq $d) { break }
- $d = $parent
- }
- return "2.17"
- }
- $script:formatVersion = Detect-FormatVersion $extDir
- # --- 8. Namespaces declaration for object XML ---
- $script:xmlnsDecl = 'xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
- # Версия формата как число для сравнений: "2.20" → 220, "2.9" → 209.
- # Строковое сравнение здесь неверно ("2.9" > "2.17" лексикографически) — известная ловушка.
- function Get-FormatRank([string]$ver) {
- if ($ver -match '^(\d+)\.(\d+)$') { return [int]$Matches[1] * 100 + [int]$Matches[2] }
- return 0
- }
- # 2.21 (8.5) добавила в шапку пространство палитры — ради <Color> у значений перечисления.
- # Вставляем НА МЕСТО (после lf, перед style): платформа держит объявления по алфавиту,
- # дописать в конец нельзя.
- if ((Get-FormatRank $script:formatVersion) -ge 221) {
- $script:xmlnsDecl = $script:xmlnsDecl -replace ' xmlns:style=', ' xmlns:pal="http://v8.1c.ru/8.1/data/ui/colors/palette" xmlns:style='
- }
- # --- 9. Parse -Object into items ---
- if ($Check -and $Actualize) {
- Write-Error "-Check and -Actualize cannot be combined"
- exit 1
- }
- if (($Check -or $Actualize) -and ($Module -or $BorrowMainAttribute)) {
- Write-Error "-Check and -Actualize cannot be combined with -Module or -BorrowMainAttribute"
- exit 1
- }
- $items = @()
- if ($Object) {
- foreach ($part in $Object.Split(";;")) {
- $trimmed = $part.Trim()
- if ($trimmed) { $items += $trimmed }
- }
- }
- if ($items.Count -eq 0 -and -not ($Check -or $Actualize)) {
- Write-Error "No objects specified in -Object"
- exit 1
- }
- # --- 9b. Validate -BorrowMainAttribute ---
- if ($BorrowMainAttribute) {
- if ($BorrowMainAttribute -notin @("Form","All")) {
- Write-Error "-BorrowMainAttribute accepts 'Form' or 'All' (default: Form)"
- exit 1
- }
- # Validate: only with a form — .Form. pattern or a common form
- $hasForm = $false
- foreach ($item in $items) { if ($item -match '\.Form\.' -or $item -match '^(CommonForm|ОбщаяФорма)\.') { $hasForm = $true; break } }
- if (-not $hasForm) {
- Write-Error "-BorrowMainAttribute requires a form in -Object (e.g. 'Catalog.X.Form.Y')"
- exit 1
- }
- }
- # --- 9c. Validate -Module ---
- $script:requestedModules = @()
- $script:noModule = $false
- if ($Module) {
- foreach ($raw in ($Module -split '[,;]')) {
- $kind = $raw.Trim()
- if (-not $kind) { continue }
- # Сравнение РЕГИСТРОНЕЗАВИСИМОЕ явно (-ieq): в py-порте это отдельная ветка, и молчаливое
- # расхождение портов на «none» ловится только глазами.
- if ($kind -ieq "None") { $script:noModule = $true; continue }
- $canon = @($script:moduleKindNames | Where-Object { $_ -ieq $kind })
- if ($canon.Count -eq 0) {
- Write-Error "Неизвестный вид модуля '$kind'. Допустимо: $($script:moduleKindNames -join ', '), None"
- exit 1
- }
- $script:requestedModules += $canon[0]
- }
- if ($script:noModule -and $script:requestedModules.Count -gt 0) {
- Write-Error "-Module None нельзя сочетать с видами модулей"
- exit 1
- }
- }
- # Какие модули создать для объекта. Тип с единственным модулем получает его всегда — уточнять
- # там нечего; -Module разбирает только неоднозначные типы. Иначе батч смешанных типов
- # (`CommonModule.X ;; Catalog.Y`) не выражался бы одним вызовом.
- function Resolve-ModuleKinds {
- param([string]$typeName)
- if ($script:noModule) { return @() }
- $allowed = @($script:moduleKindsByType[$typeName])
- if ($allowed.Count -eq 0) { return @() }
- if ($script:autoModuleTypes -contains $typeName) { return @($allowed[0]) }
- if ($script:requestedModules.Count -eq 0) { return @() }
- # Порядок берём из таблицы типа, а не из порядка ключей в -Module.
- $selected = @($allowed | Where-Object { $script:requestedModules -contains $_ })
- if ($selected.Count -eq 0) {
- Warn " Тип $typeName не имеет запрошенных модулей — пропущено. Допустимо: $($allowed -join ', ')"
- }
- return $selected
- }
- # --- 10. Helper: read source object XML ---
- # Имена реквизитов исходного объекта → uuid: реквизиты, ТЧ, измерения и ресурсы регистра, реквизиты
- # ТЧ — ключом «ТЧ.Реквизит». Нужны для кода пути в связях формы (см. Resolve-LinkDataPath).
- function Get-SourceAttributeUuids {
- param([string]$typeName, [string]$objName)
- $result = @{}
- $dirName = $childTypeDirMap[$typeName]
- if (-not $dirName) { return $result }
- $srcFile = Join-Path (Join-Path $cfgDir $dirName) "${objName}.xml"
- if (-not (Test-Path $srcFile)) { return $result }
- $doc = New-Object System.Xml.XmlDocument
- $doc.PreserveWhitespace = $false
- $doc.Load($srcFile)
- $objEl = $null
- foreach ($c in $doc.DocumentElement.ChildNodes) {
- if ($c.NodeType -eq 'Element') { $objEl = $c; break }
- }
- if (-not $objEl) { return $result }
- $childObjects = $objEl.SelectSingleNode("*[local-name()='ChildObjects']")
- if (-not $childObjects) { return $result }
- foreach ($child in $childObjects.ChildNodes) {
- if ($child.NodeType -ne 'Element') { continue }
- if ($child.LocalName -notin @('Attribute','TabularSection','Dimension','Resource')) { continue }
- $uuid = $child.GetAttribute("uuid")
- $nameNode = $child.SelectSingleNode("*[local-name()='Properties']/*[local-name()='Name']")
- if (-not ($uuid -and $nameNode)) { continue }
- $name = $nameNode.InnerText.Trim()
- $result[$name] = $uuid
- if ($child.LocalName -ne 'TabularSection') { continue }
- foreach ($tsAttr in @($child.SelectNodes("*[local-name()='ChildObjects']/*[local-name()='Attribute']"))) {
- $tsUuid = $tsAttr.GetAttribute("uuid")
- $tsName = $tsAttr.SelectSingleNode("*[local-name()='Properties']/*[local-name()='Name']")
- if ($tsUuid -and $tsName) { $result["$name.$($tsName.InnerText.Trim())"] = $tsUuid }
- }
- }
- return $result
- }
- function Read-SourceObject {
- param([string]$typeName, [string]$objName)
- $dirName = $childTypeDirMap[$typeName]
- if (-not $dirName) {
- Write-Error "Unknown type '$typeName'"
- exit 1
- }
- $srcFile = Join-Path (Join-Path $cfgDir $dirName) "${objName}.xml"
- if (-not (Test-Path $srcFile)) {
- Write-Error "Source object not found: $srcFile"
- exit 1
- }
- $srcDoc = New-Object System.Xml.XmlDocument
- $srcDoc.PreserveWhitespace = $false
- $srcDoc.Load($srcFile)
- $srcNs = New-Object System.Xml.XmlNamespaceManager($srcDoc.NameTable)
- $srcNs.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
- $srcNs.AddNamespace("xr", "http://v8.1c.ru/8.3/xcf/readable")
- # Find the type element (e.g. <Catalog uuid="...">)
- $srcRoot = $srcDoc.DocumentElement
- $srcEl = $null
- foreach ($c in $srcRoot.ChildNodes) {
- if ($c.NodeType -eq 'Element') { $srcEl = $c; break }
- }
- if (-not $srcEl) {
- Write-Error "No metadata element found in ${dirName}/${objName}.xml"
- exit 1
- }
- # Extract uuid
- $srcUuid = $srcEl.GetAttribute("uuid")
- if (-not $srcUuid) {
- Write-Error "No uuid attribute on source element in ${dirName}/${objName}.xml"
- exit 1
- }
- # Extract properties for CommonModule
- $srcProps = @{}
- $propsNode = $srcEl.SelectSingleNode("md:Properties", $srcNs)
- if ($propsNode) {
- foreach ($propName in $commonModuleProps) {
- $propNode = $propsNode.SelectSingleNode("md:${propName}", $srcNs)
- if ($propNode) {
- $srcProps[$propName] = $propNode.InnerText.Trim()
- }
- }
- # DefinedType: carry the <Type> definition. A type alias is meaningless as a bare shell —
- # the platform needs its underlying type (e.g. to know a column is a summable Number for totals).
- if ($typeName -eq "DefinedType") {
- $typeNode = $propsNode.SelectSingleNode("md:Type", $srcNs)
- if ($typeNode) {
- $srcProps["__TypeXml"] = [regex]::Replace($typeNode.OuterXml, '\s+xmlns(?::\w+)?="[^"]*"', '')
- }
- }
- # Владельцы: стандартное поле «Owner» появляется у справочника, только если задан Owners
- if ($script:typesWithOwners -ccontains $typeName) {
- $ownersNode = $propsNode.SelectSingleNode("md:Owners", $srcNs)
- if ($ownersNode -and $ownersNode.HasChildNodes) {
- $srcProps["__OwnersXml"] = [regex]::Replace($ownersNode.OuterXml, '\s+xmlns(?::\w+)?="[^"]*"', '')
- }
- }
- # Скалярные свойства, включающие стандартные поля своего типа
- foreach ($gp in @($script:typeGateProps[$typeName])) {
- if (-not $gp) { continue }
- $gpNode = $propsNode.SelectSingleNode("md:${gp}", $srcNs)
- if ($gpNode) { $srcProps[$gp] = $gpNode.InnerText.Trim() }
- }
- }
- # Whether the platform emits <ChildObjects> for this type — the source object is the ground truth
- $srcProps["__HasChildObjects"] = ($srcEl.SelectSingleNode("md:ChildObjects", $srcNs) -ne $null)
- return @{
- Uuid = $srcUuid
- Properties = $srcProps
- Element = $srcEl
- NsManager = $srcNs
- }
- }
- # --- 10b. Helper: read source form UUID ---
- function Read-SourceFormUuid {
- param([string]$typeName, [string]$objName, [string]$formName)
- $dirName = $childTypeDirMap[$typeName]
- # Общая форма — сама объект конфигурации: её описание лежит рядом с другими, а не в Forms владельца
- $srcFile = if ($typeName -eq 'CommonForm') { Join-Path (Join-Path $cfgDir $dirName) "${objName}.xml" }
- else { Join-Path (Join-Path (Join-Path (Join-Path $cfgDir $dirName) $objName) "Forms") "${formName}.xml" }
- if (-not (Test-Path $srcFile)) {
- Write-Error "Source form not found: $srcFile"
- exit 1
- }
- $srcDoc = New-Object System.Xml.XmlDocument
- $srcDoc.PreserveWhitespace = $false
- $srcDoc.Load($srcFile)
- $srcEl = $null
- foreach ($c in $srcDoc.DocumentElement.ChildNodes) {
- if ($c.NodeType -eq 'Element') { $srcEl = $c; break }
- }
- if (-not $srcEl) {
- Write-Error "No metadata element found in source form: $srcFile"
- exit 1
- }
- $srcUuid = $srcEl.GetAttribute("uuid")
- if (-not $srcUuid) {
- Write-Error "No uuid attribute on source form element: $srcFile"
- exit 1
- }
- return $srcUuid
- }
- # --- 10c. Helper: borrow a form ---
- function Borrow-Form {
- param([string]$typeName, [string]$objName, [string]$formName, [switch]$BorrowMainAttr, [switch]$RenderOnly, [switch]$Rebuild)
- $dirName = $childTypeDirMap[$typeName]
- $enc = New-Object System.Text.UTF8Encoding($true)
- # Общая форма — сама объект конфигурации: описание CommonForms/<Имя>.xml с корнем <CommonForm>,
- # тело CommonForms/<Имя>/Ext/Form.xml, регистрация в Configuration.xml. Форма объекта — в Forms
- # владельца. Остальное (скелет, BaseForm, связи, оформление, картинки) одинаково (эталон УТ link).
- $isCommonForm = $typeName -eq 'CommonForm'
- # Уже заимствованная общая форма (в т.ч. оболочкой от прежних версий навыка) в Configuration.xml
- # уже есть — повторно не регистрируем
- $commonFormRegistered = $isCommonForm -and (Test-ObjectBorrowed $typeName $objName)
- if ($isCommonForm) {
- $srcFormDir = Join-Path (Join-Path $cfgDir $dirName) $objName
- $formMetaFile = Join-Path (Join-Path $extDir $dirName) "${objName}.xml"
- $extFormDir = Join-Path (Join-Path $extDir $dirName) $objName
- $formMetaTag = 'CommonForm'
- } else {
- $srcFormDir = Join-Path (Join-Path (Join-Path (Join-Path $cfgDir $dirName) $objName) "Forms") $formName
- $formMetaFile = Join-Path (Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Forms") "${formName}.xml"
- $extFormDir = Join-Path (Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Forms") $formName
- $formMetaTag = 'Form'
- }
- # 1. Read source form UUID
- # -RenderOnly: только текст Form.xml по текущему источнику — для сравнения с заимствованной
- # формой; ничего не пишет и попутно ничего не заимствует
- $formUuid = Read-SourceFormUuid $typeName $objName $formName
- if (-not $RenderOnly) { Info " Source form UUID: $formUuid" }
- # 2. Read source Form.xml content
- $srcFormXmlPath = Join-Path $srcFormDir "Ext/Form.xml"
- if (-not (Test-Path $srcFormXmlPath)) {
- Write-Error "Source Form.xml not found: $srcFormXmlPath"
- exit 1
- }
- $srcFormContent = [System.IO.File]::ReadAllText($srcFormXmlPath, $enc)
- # 3. Generate form metadata XML (ФормаЭлемента.xml).
- # If the wrapper was already borrowed, reuse its uuid so re-borrow is idempotent
- # (regenerating it would churn the form's identity on every rerun).
- $newFormUuid = ""
- if (Test-Path $formMetaFile) {
- try {
- $existingDoc = New-Object System.Xml.XmlDocument
- $existingDoc.Load($formMetaFile)
- $existingFormNode = $existingDoc.DocumentElement.SelectSingleNode("*[local-name()='$formMetaTag']")
- if ($existingFormNode) {
- $existingUuid = $existingFormNode.GetAttribute("uuid")
- if ($existingUuid) { $newFormUuid = $existingUuid }
- }
- } catch { }
- }
- if (-not $newFormUuid) { $newFormUuid = [guid]::NewGuid().ToString() }
- $formMetaSb = New-Object System.Text.StringBuilder
- $formMetaSb.AppendLine("<?xml version=`"1.0`" encoding=`"UTF-8`"?>") | Out-Null
- $formMetaSb.AppendLine("<MetaDataObject $($script:xmlnsDecl) version=`"$($script:formatVersion)`">") | Out-Null
- $formMetaSb.AppendLine("`t<$formMetaTag uuid=`"${newFormUuid}`">") | Out-Null
- $formMetaSb.AppendLine("`t`t<InternalInfo/>") | Out-Null
- $formMetaSb.AppendLine("`t`t<Properties>") | Out-Null
- $formMetaSb.AppendLine("`t`t`t<ObjectBelonging>Adopted</ObjectBelonging>") | Out-Null
- $formMetaSb.AppendLine("`t`t`t<Name>${formName}</Name>") | Out-Null
- $formMetaSb.AppendLine("`t`t`t<Comment/>") | Out-Null
- $formMetaSb.AppendLine("`t`t`t<ExtendedConfigurationObject>${formUuid}</ExtendedConfigurationObject>") | Out-Null
- $formMetaSb.AppendLine("`t`t`t<FormType>Managed</FormType>") | Out-Null
- $formMetaSb.AppendLine("`t`t</Properties>") | Out-Null
- $formMetaSb.AppendLine("`t</$formMetaTag>") | Out-Null
- $formMetaSb.Append("</MetaDataObject>") | Out-Null
- # 4. Create directories
- $formMetaDir = Split-Path $formMetaFile -Parent
- if (-not $RenderOnly -and -not (Test-Path $formMetaDir)) {
- New-Item -ItemType Directory -Path $formMetaDir -Force | Out-Null
- }
- # Write form metadata
- # -Rebuild: форма уже заимствована — пересобирается только Form.xml, метаданные и регистрация как есть
- if (-not $RenderOnly -and -not $Rebuild) {
- [System.IO.File]::WriteAllText($formMetaFile, $formMetaSb.ToString(), $enc)
- Info " Created: $formMetaFile"
- }
- # 5. Generate Form.xml with BaseForm (visual elements only)
- # Parse source Form.xml as XmlDocument
- $srcFormDoc = New-Object System.Xml.XmlDocument
- $srcFormDoc.PreserveWhitespace = $true
- $srcFormDoc.Load($srcFormXmlPath)
- $srcFormEl = $srcFormDoc.DocumentElement
- # Borrowed form must use the extension's format version (not the source form's), so the whole
- # extension stays uniform — otherwise the platform rejects the import on a version mismatch
- # (e.g. a 2.13 form inside a 2.17 extension). The platform itself upgrades the form to the root version.
- $formVersion = $script:formatVersion
- # Find direct children: form properties, AutoCommandBar, ChildItems.
- # Секции формы отбираются по имени, а не по позиции: свойства лежат и до, и после <CommandSet>
- # (корпусная проверка: у всех 794 форм документов ERP с CommandSet он стоит раньше AutoCommandBar,
- # а AutoTime/UsePostingMode/RepostOnWrite — после него). Позиционная отсечка теряла весь хвост,
- # и платформа молча подставляла дефолты вместо потерянных свойств.
- $srcAutoCmd = $null
- $srcChildItems = $null
- $formProps = @()
- foreach ($fc in $srcFormEl.ChildNodes) {
- if ($fc.NodeType -ne 'Element') { continue }
- if ($fc.LocalName -eq 'AutoCommandBar' -and -not $srcAutoCmd) {
- $srcAutoCmd = $fc; continue
- }
- if ($fc.LocalName -eq 'ChildItems' -and -not $srcChildItems) {
- $srcChildItems = $fc; continue
- }
- # Структурные секции: в расширении их содержимое недействительно (обработчики, команды и
- # параметры базовой формы, ссылки командного интерфейса на команды базовой конфигурации).
- if ($script:formStructuralSections -ccontains $fc.LocalName) { continue }
- # Свойства, значение которых — имя реквизита формы. Реквизиты в заимствованную форму не
- # переносятся, поэтому Конфигуратор такие свойства выбрасывает (проверено на форме отчёта:
- # ReportResult и DetailsData выброшены, CustomSettingsFolder — имя элемента — сохранён).
- if ($script:formAttributeRefProps -ccontains $fc.LocalName) { continue }
- $formProps += $fc.OuterXml
- }
- # Get OuterXml and strip redundant namespace redeclarations (they're on root <Form>)
- $nsStripPattern = '\s+xmlns(?::\w+)?="[^"]*"'
- # Основной реквизит исходной формы: его имя — корень путей к данным, которые нужно сохранить
- # («Объект.» у формы объекта, «Список.» у формы списка, «Запись.» у формы записи регистра)
- # Имя основного реквизита источника нужно в обоих режимах: по нему опознаётся корень путей
- # в ссылках параметров выбора. А $mainAttrName управляет вырезанием привязок и потому остаётся
- # пустым в скелетном режиме — там привязки снимаются все.
- $srcMainInfo = Get-MainAttributeInfo $srcFormEl $nsStripPattern
- $srcMainAttrName = if ($srcMainInfo) { $srcMainInfo.Name } else { "" }
- $formAttrIds = Get-FormAttributeIds $srcFormEl
- # Условное оформление формы Конфигуратор копирует как есть в обе части, внутрь <Attributes>
- # после реквизитов — и без основного реквизита тоже; ссылки на незаимствованные реквизиты формы
- # платформа принимает (эталоны УТ StdPic, StdPic_WithMain, CAStyle, УНФ Номенклатура)
- $srcCondAppearance = $srcFormEl.SelectSingleNode("*[local-name()='Attributes']/*[local-name()='ConditionalAppearance']")
- $srcCondAppearanceXml = if ($srcCondAppearance) { [regex]::Replace($srcCondAppearance.OuterXml, $nsStripPattern, '') } else { "" }
- $mainAttrInfo = if ($BorrowMainAttr) { $srcMainInfo } else { $null }
- $mainAttrName = if ($mainAttrInfo) { $mainAttrInfo.Name } else { "" }
- if ($BorrowMainAttr -and -not $mainAttrInfo -and -not $RenderOnly) {
- Warn " У формы нет основного реквизита — -BorrowMainAttribute проигнорирован"
- }
- # Имена реквизитов объекта нужны в обоих режимах: без заимствования — для кода пути в связях
- # формы, с заимствованием — чтобы отличить реквизит (разрешается текстом) от стандартного поля
- # У общей формы реквизиты берутся у владельца, выведенного из типа основного реквизита;
- # у набора констант — ничего: код пути на константу не измерен, связь без основного реквизита
- # вырезается с предупреждением, с ним — остаётся текстом
- if ($isCommonForm) {
- $cfOwner = Resolve-CommonFormOwner $srcFormEl
- $srcAttrUuids = @{}
- if ($cfOwner -and $cfOwner.Kind -eq 'Object') {
- $srcAttrUuids = Get-SourceAttributeUuids $cfOwner.TypeName $cfOwner.ObjName
- } elseif ($cfOwner -and $cfOwner.Kind -eq 'Constants') {
- # Константы, на которые есть пути: с основным реквизитом путь на заимствованную — текстом
- foreach ($cName in @((Collect-FormDataPaths $srcFormXmlPath $cfOwner.MainName).FirstLevel.Keys)) {
- $cFile = Join-Path (Join-Path $cfgDir "Constants") "${cName}.xml"
- if (-not (Test-Path $cFile)) { continue }
- $cm = [regex]::Match([System.IO.File]::ReadAllText($cFile), '<Constant uuid="([^"]+)"')
- if ($cm.Success) { $srcAttrUuids[$cName] = $cm.Groups[1].Value }
- }
- }
- } else {
- $maObj = Resolve-MainAttributeObject $srcFormEl $typeName $objName
- $srcAttrUuids = Get-SourceAttributeUuids $maObj.TypeName $maObj.ObjName
- }
- # Реквизиты объекта, которые попадут в расширение: в режиме Form — только используемые формой
- # (тот же сбор, что в Borrow-MainAttribute), в режиме All — все ($null)
- $borrowedNames = $null
- if ($mainAttrInfo -and $BorrowMainAttribute -eq 'Form') {
- $borrowedNames = (Collect-FormDataPaths $srcFormXmlPath $srcMainAttrName).FirstLevel
- }
- $linkCtx = Get-LinkContext $srcFormEl $srcMainAttrName ([bool]$mainAttrInfo) $borrowedNames $srcAttrUuids $formAttrIds
- # AutoCommandBar: keep ChildItems (buttons with CommandName→0). Autofill — как в источнике: Конфигуратор
- # копирует значение, а true (умолчание) не пишет (замер М7б, эталон заимствования Конфигуратором)
- $autoCmdXml = ""
- if ($srcAutoCmd) {
- $autoCmdXml = $srcAutoCmd.OuterXml
- $autoCmdXml = [regex]::Replace($autoCmdXml, $nsStripPattern, '')
- $autoCmdXml = [regex]::Replace($autoCmdXml, '<CommandName>[^<]*</CommandName>', '<CommandName>0</CommandName>')
- $autoCmdXml = [regex]::Replace($autoCmdXml, '^(<AutoCommandBar\b[^>]*>)\s*<Autofill>true</Autofill>', '$1')
- # Вложенный CommandSet выбрасывается целиком, а не опустошается: Конфигуратор в заимствованной
- # форме оставляет только корневой (тот идёт свойством формы, здесь его нет).
- $autoCmdXml = [regex]::Replace($autoCmdXml, '(?s)\s*<CommandSet>.*?</CommandSet>', '')
- $autoCmdXml = [regex]::Replace($autoCmdXml, '\s*<CommandSet/>', '')
- # Strip data-binding tags whose root attribute isn't borrowed
- $autoCmdXml = Strip-FormBindings $autoCmdXml $mainAttrName
- $autoCmdXml = Rewrite-ChoiceParameterLinks $autoCmdXml $linkCtx
- $autoCmdXml = [regex]::Replace($autoCmdXml, '^<AutoCommandBar\b([^>]*[^/])>\s*</AutoCommandBar>$', '<AutoCommandBar$1/>')
- }
- # Картинка декорации в заимствованную форму не переносится: Конфигуратор выбрасывает <Picture>
- # у PictureDecoration из обеих частей формы при любом виде картинки (своя, общая, стандартная)
- # и не тянет за ней ни файл, ни общую картинку. Замер 8.3.27: 10 декораций в 5 формах УТ.
- # Картинки кнопок, таблиц и полей картинки остаются — вместе с файлами, см. копирование ниже.
- if ($srcChildItems) {
- foreach ($decoPic in @($srcChildItems.SelectNodes(".//*[local-name()='PictureDecoration']/*[local-name()='Picture']"))) {
- $prevWs = $decoPic.PreviousSibling
- if ($prevWs -and ($prevWs.NodeType -eq 'Whitespace' -or $prevWs.NodeType -eq 'SignificantWhitespace')) {
- $decoPic.ParentNode.RemoveChild($prevWs) | Out-Null
- }
- $decoPic.ParentNode.RemoveChild($decoPic) | Out-Null
- }
- }
- # ChildItems: copy full tree, clean up base-config references
- $childItemsXml = ""
- if ($srcChildItems) {
- $childItemsXml = $srcChildItems.OuterXml
- $childItemsXml = [regex]::Replace($childItemsXml, $nsStripPattern, '')
- # Replace all CommandName values with 0
- $childItemsXml = [regex]::Replace($childItemsXml, '<CommandName>[^<]*</CommandName>', '<CommandName>0</CommandName>')
- # Strip data-binding tags whose root attribute isn't borrowed
- # (DataPath/TitleDataPath/FooterDataPath/HeaderDataPath/MultipleValue*/RowPicture*)
- $childItemsXml = Strip-FormBindings $childItemsXml $mainAttrName
- $childItemsXml = Rewrite-ChoiceParameterLinks $childItemsXml $linkCtx
- # Вложенные CommandSet (у таблиц, полей табличного документа и т.п.) — целиком, см. выше.
- # Исключение — набор таблицы самого основного реквизита, когда он заимствован: его команды
- # (Find/CancelSearch динамического списка) снова разрешимы, и Конфигуратор набор оставляет
- # (эталоны УТ CommonMain/ФайлыВТоме, StdPic_WithMain/ЖурналСкладскихАктов; без основного
- # реквизита и у прочих элементов — выброшен во всех эталонах).
- $keptCmdSets = [ordered]@{}
- if ($mainAttrName) {
- $mainTablePat = '(?s)(<Table name="[^"]+" id="\d+">(?:(?!<ChildItems>|</Table>|<CommandSet>).)*?<DataPath>' +
- [regex]::Escape($mainAttrName) + '</DataPath>(?:(?!<ChildItems>|</Table>|<CommandSet>).)*?)(<CommandSet>.*?</CommandSet>)'
- $childItemsXml = [regex]::Replace($childItemsXml, $mainTablePat, {
- param($m)
- $key = "@@KEPTCMDSET$($keptCmdSets.Count)@@"
- $keptCmdSets[$key] = $m.Groups[2].Value
- $m.Groups[1].Value + $key
- })
- }
- $childItemsXml = [regex]::Replace($childItemsXml, '(?s)\s*<CommandSet>.*?</CommandSet>', '')
- $childItemsXml = [regex]::Replace($childItemsXml, '\s*<CommandSet/>', '')
- foreach ($key in $keptCmdSets.Keys) { $childItemsXml = $childItemsXml.Replace($key, $keptCmdSets[$key]) }
- $childItemsXml = Rewrite-TypeLinks $childItemsXml $linkCtx
- # Strip element-level Events (base form handlers not in extension)
- $childItemsXml = [regex]::Replace($childItemsXml, '(?s)\s*<Events>.*?</Events>', '')
- # Collect CommonPicture references from ChildItems and AutoCommandBar
- $referencedPictures = @{}
- $picRefs = [regex]::Matches($childItemsXml, '<xr:Ref>CommonPicture\.(\w+)</xr:Ref>')
- foreach ($m in $picRefs) { $referencedPictures[$m.Groups[1].Value] = $true }
- if ($autoCmdXml) {
- $picRefs2 = [regex]::Matches($autoCmdXml, '<xr:Ref>CommonPicture\.(\w+)</xr:Ref>')
- foreach ($m in $picRefs2) { $referencedPictures[$m.Groups[1].Value] = $true }
- }
- # Auto-borrow referenced CommonPictures (if not already borrowed)
- $autoBorrowedPics = @()
- $renderPics = @{}
- foreach ($picName in $referencedPictures.Keys) {
- if (-not (Test-ObjectBorrowed "CommonPicture" $picName)) {
- $picSrcFile = Join-Path (Join-Path $cfgDir "CommonPictures") "${picName}.xml"
- if ($RenderOnly) { if (Test-Path $picSrcFile) { $renderPics[$picName] = $true }; continue }
- if (Test-Path $picSrcFile) {
- $src = Read-SourceObject "CommonPicture" $picName
- $borrowedXml = Build-BorrowedObjectXml "CommonPicture" $picName $src.Uuid $src.Properties
- $targetDir = Join-Path $extDir "CommonPictures"
- if (-not (Test-Path $targetDir)) {
- New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
- }
- $targetFile = Join-Path $targetDir "${picName}.xml"
- $encBom = New-Object System.Text.UTF8Encoding($true)
- [System.IO.File]::WriteAllText($targetFile, $borrowedXml, $encBom)
- Add-ToChildObjects "CommonPicture" $picName
- $autoBorrowedPics += $picName
- $script:borrowedFiles += $targetFile
- Info " Auto-borrowed: CommonPicture.${picName}"
- } else {
- Warn " CommonPicture.${picName} not found in source config — will strip from form"
- }
- }
- }
- # Collect all borrowed CommonPictures (including previously borrowed)
- $borrowedPicSet = @{}
- $nsMgr2 = New-Object System.Xml.XmlNamespaceManager($script:xmlDoc.NameTable)
- $nsMgr2.AddNamespace("md", $script:mdNs)
- $picNodes = $script:xmlDoc.SelectNodes("//md:ChildObjects/md:CommonPicture", $nsMgr2)
- foreach ($pn in $picNodes) { $borrowedPicSet[$pn.InnerText] = $true }
- foreach ($rp in $renderPics.Keys) { $borrowedPicSet[$rp] = $true }
- # Strip <Picture> blocks referencing non-borrowed CommonPictures
- $picBlockPattern = '(?s)\s*<Picture>\s*<xr:Ref>CommonPicture\.(\w+)</xr:Ref>.*?</Picture>'
- $picMatches = [regex]::Matches($childItemsXml, $picBlockPattern)
- # Process in reverse order to preserve positions
- for ($mi = $picMatches.Count - 1; $mi -ge 0; $mi--) {
- $pm = $picMatches[$mi]
- $cpName = $pm.Groups[1].Value
- if (-not $borrowedPicSet.ContainsKey($cpName)) {
- $childItemsXml = $childItemsXml.Remove($pm.Index, $pm.Length)
- }
- }
- # Стандартные картинки (StdPicture.*) не вырезаются: Конфигуратор оставляет их у кнопок, подменю
- # и страниц в обеих частях формы (эталоны 8.3.27, 26 элементов в 3 формах).
- # Same Picture strip for AutoCommandBar
- if ($autoCmdXml) {
- $acPicMatches = [regex]::Matches($autoCmdXml, $picBlockPattern)
- for ($mi = $acPicMatches.Count - 1; $mi -ge 0; $mi--) {
- $pm = $acPicMatches[$mi]
- $cpName = $pm.Groups[1].Value
- if (-not $borrowedPicSet.ContainsKey($cpName)) {
- $autoCmdXml = $autoCmdXml.Remove($pm.Index, $pm.Length)
- }
- }
- }
- # Auto-borrow Enums + EnumValues referenced via DesignTimeRef in ChoiceParameters
- # Collect Enum -> [EnumValue names] map
- $dtRefs = [regex]::Matches($childItemsXml, 'xr:DesignTimeRef">Enum\.(\w+)\.EnumValue\.(\w+)')
- $referencedEnumValues = @{}
- foreach ($m in $dtRefs) {
- $eName = $m.Groups[1].Value
- $evName = $m.Groups[2].Value
- if (-not $referencedEnumValues.ContainsKey($eName)) { $referencedEnumValues[$eName] = @{} }
- $referencedEnumValues[$eName][$evName] = $true
- }
- foreach ($enumName in $referencedEnumValues.Keys) {
- if (-not $RenderOnly -and -not (Test-ObjectBorrowed "Enum" $enumName)) {
- $enumSrcFile = Join-Path (Join-Path $cfgDir "Enums") "${enumName}.xml"
- if (Test-Path $enumSrcFile) {
- # Read source Enum to get UUID and EnumValue UUIDs
- $srcParser = New-Object System.Xml.XmlDocument
- $srcParser.PreserveWhitespace = $true
- $srcParser.Load($enumSrcFile)
- $srcEnumEl = $null
- foreach ($cn in $srcParser.DocumentElement.ChildNodes) {
- if ($cn.NodeType -eq 'Element') { $srcEnumEl = $cn; break }
- }
- $srcEnumUuid = $srcEnumEl.GetAttribute("uuid")
- # Find source EnumValues by name
- $enumValueXmls = @()
- $neededValues = $referencedEnumValues[$enumName]
- $srcNsMgr = New-Object System.Xml.XmlNamespaceManager($srcParser.NameTable)
- $srcNsMgr.AddNamespace("md", $script:mdNs)
- $srcEvNodes = $srcEnumEl.SelectNodes("md:ChildObjects/md:EnumValue", $srcNsMgr)
- foreach ($evNode in $srcEvNodes) {
- $evUuid = $evNode.GetAttribute("uuid")
- $evNameNode = $evNode.SelectSingleNode("md:Properties/md:Name", $srcNsMgr)
- if ($evNameNode -and $neededValues.ContainsKey($evNameNode.InnerText)) {
- $newEvUuid = [guid]::NewGuid().ToString()
- $enumValueXmls += @"
- <EnumValue uuid="${newEvUuid}">
- <InternalInfo/>
- <Properties>
- <ObjectBelonging>Adopted</ObjectBelonging>
- <Name>$($evNameNode.InnerText)</Name>
- <Comment/>
- <ExtendedConfigurationObject>${evUuid}</ExtendedConfigurationObject>
- </Properties>
- </EnumValue>
- "@
- }
- }
- # Build borrowed Enum with EnumValues in ChildObjects
- $src = Read-SourceObject "Enum" $enumName
- $borrowedXml = Build-BorrowedObjectXml "Enum" $enumName $src.Uuid $src.Properties
- if ($enumValueXmls.Count -gt 0) {
- $evBlock = ($enumValueXmls -join "`r`n")
- $borrowedXml = $borrowedXml -replace '<ChildObjects/>', "<ChildObjects>`r`n${evBlock}`r`n`t`t</ChildObjects>"
- }
- $targetDir = Join-Path $extDir "Enums"
- if (-not (Test-Path $targetDir)) {
- New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
- }
- $targetFile = Join-Path $targetDir "${enumName}.xml"
- $encBom = New-Object System.Text.UTF8Encoding($true)
- [System.IO.File]::WriteAllText($targetFile, $borrowedXml, $encBom)
- Add-ToChildObjects "Enum" $enumName
- $script:borrowedFiles += $targetFile
- Info " Auto-borrowed: Enum.${enumName} (with $($enumValueXmls.Count) EnumValue(s))"
- } else {
- Warn " Enum.${enumName} not found in source config"
- }
- }
- }
- }
- # Вне блока ChildItems: стили нужны и оформлению формы без элементов
- # Auto-borrow StyleItems referenced in ChildItems and in the form's conditional appearance
- # (стиль только из оформления Конфигуратор тоже заимствует — эталон УТ CAStyle)
- # Pattern 1: <Font ref="style:XXX" kind="StyleItem"/>, <TitleFont ref="style:XXX" ... kind="StyleItem"/>
- # Pattern 2: <BackColor>style:XXX</BackColor>, <TextColor>style:XXX</TextColor>, etc.
- # Порядок первого упоминания — как в Python-порте (от него зависит порядок в ChildObjects)
- $styleScanXml = $childItemsXml + $srcCondAppearanceXml
- $referencedStyles = [ordered]@{}
- $styleRefs1 = [regex]::Matches($styleScanXml, 'ref="style:(\w+)"[^>]*kind="StyleItem"')
- foreach ($m in $styleRefs1) { $referencedStyles[$m.Groups[1].Value] = $true }
- # Закрывающий тег может быть с префиксом: в оформлении значение — <dcscor:value>style:X</dcscor:value>
- $styleRefs2 = [regex]::Matches($styleScanXml, '>style:(\w+)</[\w:]+>')
- foreach ($m in $styleRefs2) { $referencedStyles[$m.Groups[1].Value] = $true }
- foreach ($styleName in $referencedStyles.Keys) {
- if (-not $RenderOnly -and -not (Test-ObjectBorrowed "StyleItem" $styleName)) {
- $styleSrcFile = Join-Path (Join-Path $cfgDir "StyleItems") "${styleName}.xml"
- if (Test-Path $styleSrcFile) {
- $src = Read-SourceObject "StyleItem" $styleName
- $borrowedXml = Build-BorrowedObjectXml "StyleItem" $styleName $src.Uuid $src.Properties
- $targetDir = Join-Path $extDir "StyleItems"
- if (-not (Test-Path $targetDir)) {
- New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
- }
- $targetFile = Join-Path $targetDir "${styleName}.xml"
- $encBom = New-Object System.Text.UTF8Encoding($true)
- [System.IO.File]::WriteAllText($targetFile, $borrowedXml, $encBom)
- Add-ToChildObjects "StyleItem" $styleName
- $script:borrowedFiles += $targetFile
- Info " Auto-borrowed: StyleItem.${styleName}"
- }
- # Файла нет — встроенный стиль платформы (ImportantColor, AccentColor…): заимствовать
- # нечего, пропускаем молча. Пользовательский стиль, на который ссылается форма, в
- # валидном источнике существует всегда — предупреждение было только шумом.
- }
- }
- # Открывающий тег <Form ...> берём из исходной формы — ради её объявлений пространств имён,
- # но version подставляем СВОЮ: форма обязана нести версию расширения, иначе платформа
- # отвергает импорт (форма 2.13 внутри расширения 2.17). Раньше тег копировался целиком,
- # и версия источника молча побеждала.
- $xmlDecl = '<?xml version="1.0" encoding="UTF-8"?>'
- $formTag = "<Form version=`"${formVersion}`">"
- if ($srcFormContent -match '(?s)^(<\?xml[^?]*\?>)') { $xmlDecl = $Matches[1] }
- if ($srcFormContent -match '(<Form[^>]*>)') {
- $srcTag = $Matches[1]
- $srcNs = $srcTag -replace '^<Form\s*', '' -replace '\s*/?>$', '' -replace '\s*version="[^"]*"', ''
- # 2.21 (8.5): пространство палитры. Место строгое — после lf, перед style.
- if ((Get-FormatRank $formVersion) -ge 221 -and $srcNs -notmatch 'xmlns:pal=') {
- $srcNs = $srcNs -replace ' xmlns:style=', ' xmlns:pal="http://v8.1c.ru/8.1/data/ui/colors/palette" xmlns:style='
- }
- $formTag = if ($srcNs) { "<Form $srcNs version=`"${formVersion}`">" } else { "<Form version=`"${formVersion}`">" }
- }
- # Build output Form.xml
- $formXmlSb = New-Object System.Text.StringBuilder
- $formXmlSb.Append($xmlDecl) | Out-Null
- $formXmlSb.Append("`r`n") | Out-Null
- $formXmlSb.Append($formTag) | Out-Null
- $formXmlSb.Append("`r`n") | Out-Null
- # Part 1: form properties + AutoCommandBar + ChildItems
- foreach ($propXml in $formProps) {
- $propXml = [regex]::Replace($propXml, $nsStripPattern, '')
- $formXmlSb.Append("`t$propXml`r`n") | Out-Null
- }
- if ($autoCmdXml) {
- $formXmlSb.Append("`t$autoCmdXml") | Out-Null
- $formXmlSb.Append("`r`n") | Out-Null
- }
- if ($childItemsXml) {
- $formXmlSb.Append("`t$childItemsXml") | Out-Null
- $formXmlSb.Append("`r`n") | Out-Null
- }
- # Attributes: основной реквизит (с -BorrowMainAttribute) и условное оформление формы — после него
- $withMainAttr = $BorrowMainAttr -and $mainAttrInfo
- if ($withMainAttr -or $srcCondAppearanceXml) {
- $formXmlSb.Append("`t<Attributes>`r`n") | Out-Null
- if ($withMainAttr) { $formXmlSb.Append("`t`t$($mainAttrInfo.Xml)`r`n") | Out-Null }
- if ($srcCondAppearanceXml) { $formXmlSb.Append("`t`t$srcCondAppearanceXml`r`n") | Out-Null }
- $formXmlSb.Append("`t</Attributes>") | Out-Null
- } else {
- $formXmlSb.Append("`t<Attributes/>") | Out-Null
- }
- $formXmlSb.Append("`r`n") | Out-Null
- # BaseForm: same content, indented one more level (многострочный текст не сдвигается)
- $formXmlSb.Append("`t<BaseForm version=`"${formVersion}`">") | Out-Null
- $formXmlSb.Append("`r`n") | Out-Null
- foreach ($propXml in $formProps) {
- $propXml = [regex]::Replace($propXml, $nsStripPattern, '')
- $formXmlSb.Append((Get-BaseFormIndented $propXml "`t`t") + "`r`n") | Out-Null
- }
- if ($autoCmdXml) {
- $formXmlSb.Append((Get-BaseFormIndented $autoCmdXml "`t`t") + "`r`n") | Out-Null
- }
- if ($childItemsXml) {
- $formXmlSb.Append((Get-BaseFormIndented $childItemsXml "`t`t") + "`r`n") | Out-Null
- }
- # BaseForm Attributes: same as main section
- if ($withMainAttr -or $srcCondAppearanceXml) {
- $formXmlSb.Append("`t`t<Attributes>`r`n") | Out-Null
- # В BaseForm та же секция на уровень глубже — сдвиг тот же, что у ChildItems
- if ($withMainAttr) { $formXmlSb.Append((Get-BaseFormIndented $mainAttrInfo.Xml "`t`t`t") + "`r`n") | Out-Null }
- if ($srcCondAppearanceXml) { $formXmlSb.Append((Get-BaseFormIndented $srcCondAppearanceXml "`t`t`t") + "`r`n") | Out-Null }
- $formXmlSb.Append("`t`t</Attributes>") | Out-Null
- } else {
- $formXmlSb.Append("`t`t<Attributes/>") | Out-Null
- }
- $formXmlSb.Append("`r`n") | Out-Null
- $formXmlSb.Append("`t</BaseForm>") | Out-Null
- $formXmlSb.Append("`r`n") | Out-Null
- $formXmlSb.Append("</Form>") | Out-Null
- # Динамический список: оболочка его основной таблицы и тильда у путей полей — в конце запуска
- # (шаги 14a и 14c), по итоговому составу расширения — реквизиты основной таблицы заимствует
- # Borrow-MainAttribute уже после формы, а в пакете — и соседние формы.
- $formXmlText = $formXmlSb.ToString()
- $pendingDynList = ($withMainAttr -and ($mainAttrInfo.Xml -match ':DynamicList<' -or $mainAttrInfo.Xml -match 'xsi:type="DynamicList"'))
- # Write Form.xml
- $formXmlDir = Join-Path $extFormDir "Ext"
- if (-not $RenderOnly -and -not (Test-Path $formXmlDir)) {
- New-Item -ItemType Directory -Path $formXmlDir -Force | Out-Null
- }
- $formXmlFile = Join-Path $formXmlDir "Form.xml"
- # Пустой элемент: XmlWriter отдаёт `<a />`, Конфигуратор пишет `<a/>`. Внутри
- # CDATA/комментария ` />` может быть содержимым (там `>` не экранируется),
- # поэтому они идут первыми ветками альтернации и возвращаются как есть.
- # Здесь источник не XmlWriter, а OuterXml исходного документа — спацовывает так же.
- $formXmlText = [regex]::Replace($formXmlText, '(?s)<!\[CDATA\[.*?\]\]>|<!--.*?-->|(?<=\S) />', { param($m) if ($m.Value -eq ' />') { '/>' } else { $m.Value } })
- # Файл создаём мы — канон выгрузки: CRLF в разделителях строк.
- $formXmlText = ($formXmlText -replace "`r`n", "`n") -replace "`n", "`r`n"
- if ($RenderOnly) {
- $script:droppedLinks = @()
- return $formXmlText
- }
- [System.IO.File]::WriteAllText($formXmlFile, $formXmlText, $enc)
- if ($pendingDynList) {
- $dlMt = [regex]::Match($mainAttrInfo.Xml, '<MainTable>([^<]*)</MainTable>')
- $dlQt = [regex]::Match($mainAttrInfo.Xml, '(?s)<QueryText>(.*?)</QueryText>')
- $script:dynListForms += @{
- File = $formXmlFile; MainName = $mainAttrInfo.Name
- Manual = ($mainAttrInfo.Xml -match '<ManualQuery>true</ManualQuery>')
- MainTable = $(if ($dlMt.Success) { $dlMt.Groups[1].Value.Trim() } else { '' })
- Query = $(if ($dlQt.Success) { [System.Net.WebUtility]::HtmlDecode($dlQt.Groups[1].Value) } else { '' })
- }
- }
- Info " Created: $formXmlFile"
- if ($script:droppedLinks.Count -gt 0) {
- $uniq = @($script:droppedLinks | Sort-Object -Unique)
- Warn " Вырезано связей формы: $($uniq.Count) — путь не разрешается в расширении: $($uniq -join ', ')"
- $script:droppedLinks = @()
- }
- # 6. Create empty Module.bsl — but NEVER overwrite an existing one (re-borrow must
- # not clobber user code added to the form module).
- $moduleDir = Join-Path $formXmlDir "Form"
- if (-not (Test-Path $moduleDir)) {
- New-Item -ItemType Directory -Path $moduleDir -Force | Out-Null
- }
- $moduleBslFile = Join-Path $moduleDir "Module.bsl"
- if (Test-Path $moduleBslFile) {
- Info " Preserved existing Module.bsl"
- } else {
- [System.IO.File]::WriteAllText($moduleBslFile, "", $enc)
- Info " Created: $moduleBslFile"
- }
- # 6b. Встроенные картинки элементов. Form.xml ссылается на них как <xr:Abs>Файл</xr:Abs>, а сам файл
- # лежит в Ext/Form/Items/<Элемент>/<Файл>; без него платформа отвергает расширение («Файл не найден»).
- # Конфигуратор копирует их байт в байт. Берём ровно то, на что ссылается скелет (картинки декораций
- # выброшены выше). Уже лежащий файл не перезаписываем: его могли заменить в расширении.
- $picFiles = @()
- $srcItemsDir = Join-Path (Join-Path (Split-Path $srcFormXmlPath -Parent) "Form") "Items"
- $picRels = New-Object System.Collections.Generic.List[string]
- foreach ($sect in @($srcAutoCmd, $srcChildItems)) {
- if (-not $sect) { continue }
- foreach ($absNode in @($sect.SelectNodes(".//*[local-name()='Abs' and namespace-uri()='http://v8.1c.ru/8.3/xcf/readable']"))) {
- $picOwner = $absNode.ParentNode.ParentNode
- $picElName = $picOwner.GetAttribute("name")
- $picFileName = $absNode.InnerText.Trim()
- if (-not $picElName -or -not $picFileName) { continue }
- # Платформа пишет сюда голое имя файла. Иное (путь, «..») — не наша выгрузка: мимо Items не ходим.
- if ($picElName -match '[\\/]' -or $picFileName -match '[\\/]' -or
- $picElName -match '^\.\.?$' -or $picFileName -match '^\.\.?$') {
- Warn " Картинка элемента пропущена — не имя файла: $picElName / $picFileName"
- continue
- }
- $rel = "$picElName/$picFileName"
- if (-not $picRels.Contains($rel)) { $picRels.Add($rel) }
- }
- }
- $picRelArr = $picRels.ToArray()
- [Array]::Sort($picRelArr, [System.StringComparer]::Ordinal)
- foreach ($rel in $picRelArr) {
- $picParts = $rel.Split('/')
- $srcPic = Join-Path (Join-Path $srcItemsDir $picParts[0]) $picParts[1]
- $dstPicDir = Join-Path (Join-Path $moduleDir "Items") $picParts[0]
- $dstPic = Join-Path $dstPicDir $picParts[1]
- if (Test-Path -LiteralPath $dstPic) {
- Info " Preserved existing: $dstPic"
- continue
- }
- if (-not (Test-Path -LiteralPath $srcPic -PathType Leaf)) {
- Warn " Картинка элемента не найдена в источнике: $srcPic"
- continue
- }
- if (-not (Test-Path -LiteralPath $dstPicDir)) { New-Item -ItemType Directory -Path $dstPicDir -Force | Out-Null }
- Copy-Item -LiteralPath $srcPic -Destination $dstPic
- $picFiles += $dstPic
- Info " Copied: $dstPic"
- }
- # 7. Register form: общая форма — в Configuration.xml, форма объекта — в ChildObjects владельца
- if ($isCommonForm) {
- if (-not $commonFormRegistered) { Add-ToChildObjects $typeName $objName }
- } else {
- if (-not $Rebuild) { Register-FormInObject $typeName $objName $formName }
- }
- return @($formMetaFile, $formXmlFile, $moduleBslFile) + $picFiles
- }
- # --- 10d. Helper: register form in parent object's ChildObjects ---
- function Register-FormInObject {
- param([string]$typeName, [string]$objName, [string]$formName)
- $dirName = $childTypeDirMap[$typeName]
- $objFile = Join-Path (Join-Path $extDir $dirName) "${objName}.xml"
- if (-not (Test-Path $objFile)) {
- Warn "Parent object file not found: $objFile — form not registered in ChildObjects"
- return
- }
- $objDoc = New-Object System.Xml.XmlDocument
- $objDoc.PreserveWhitespace = $true
- $objDoc.Load($objFile)
- $objNs = New-Object System.Xml.XmlNamespaceManager($objDoc.NameTable)
- $objNs.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
- # Find the type element
- $objEl = $null
- foreach ($c in $objDoc.DocumentElement.ChildNodes) {
- if ($c.NodeType -eq 'Element') { $objEl = $c; break }
- }
- if (-not $objEl) {
- Warn "No type element in $objFile — form not registered"
- return
- }
- # Find or create ChildObjects
- $childObjs = $objEl.SelectSingleNode("md:ChildObjects", $objNs)
- if (-not $childObjs) {
- # Create ChildObjects element
- $childObjs = $objDoc.CreateElement("ChildObjects", "http://v8.1c.ru/8.3/MDClasses")
- $objEl.AppendChild($objDoc.CreateWhitespace("`r`n`t`t")) | Out-Null
- $objEl.AppendChild($childObjs) | Out-Null
- $objEl.AppendChild($objDoc.CreateWhitespace("`r`n`t")) | Out-Null
- }
- # Check dedup
- foreach ($c in $childObjs.ChildNodes) {
- if ($c.NodeType -eq 'Element' -and $c.LocalName -eq "Form" -and $c.InnerText -eq $formName) {
- Warn "Form '$formName' already in ChildObjects of ${typeName}.${objName}"
- return
- }
- }
- # Expand self-closing if needed
- if (-not $childObjs.HasChildNodes -or $childObjs.IsEmpty) {
- $closeWs = $objDoc.CreateWhitespace("`r`n`t`t")
- $childObjs.AppendChild($closeWs) | Out-Null
- }
- # Add <Form>formName</Form>
- $formEl = $objDoc.CreateElement("Form", "http://v8.1c.ru/8.3/MDClasses")
- $formEl.InnerText = $formName
- $trailing = $childObjs.LastChild
- $ws = $objDoc.CreateWhitespace("`r`n`t`t`t")
- # Место — по канону вида (у документа форма до ТЧ, у справочника после)
- $anchor = Find-ChildAnchor $childObjs "Form" $objEl.LocalName
- if ($anchor) {
- $childObjs.InsertBefore($formEl, $anchor) | Out-Null
- $childObjs.InsertBefore($ws, $anchor) | Out-Null
- } elseif ($trailing -and ($trailing.NodeType -eq 'Whitespace' -or $trailing.NodeType -eq 'SignificantWhitespace')) {
- $childObjs.InsertBefore($ws, $trailing) | Out-Null
- $childObjs.InsertBefore($formEl, $trailing) | Out-Null
- } else {
- $childObjs.AppendChild($ws) | Out-Null
- $childObjs.AppendChild($formEl) | Out-Null
- }
- # Save object XML
- # Стиль исходника снимаем ДО записи: правка чужого файла наследует его BOM/EOL/заголовок
- # (#44/#46/#47), новый файл получает канон выгрузки. Зеркало _detect_xml_style в py-порту.
- $style2 = Detect-XmlStyle $objFile
- $settings2 = New-Object System.Xml.XmlWriterSettings
- $settings2.Encoding = New-Object System.Text.UTF8Encoding($true)
- $settings2.Indent = $false
- $settings2.NewLineHandling = [System.Xml.NewLineHandling]::None
- $memStream2 = New-Object System.IO.MemoryStream
- $writer2 = [System.Xml.XmlWriter]::Create($memStream2, $settings2)
- $objDoc.Save($writer2)
- $writer2.Flush(); $writer2.Close()
- $text2 = [System.Text.Encoding]::UTF8.GetString($memStream2.ToArray())
- $memStream2.Close()
- $text2 = Finalize-XmlText $text2 $style2
- $writeBom2 = ($null -eq $style2) -or $style2.bom
- [System.IO.File]::WriteAllText($objFile, $text2, (New-Object System.Text.UTF8Encoding($writeBom2)))
- Info " Registered form in: $objFile"
- }
- # --- 10e. Helper: check if object is already borrowed in extension ---
- function Test-ObjectBorrowed {
- param([string]$typeName, [string]$objName)
- $dirName = $childTypeDirMap[$typeName]
- $objFile = Join-Path (Join-Path $extDir $dirName) "${objName}.xml"
- return (Test-Path $objFile)
- }
- # --- 10f. Helper: пометка расширенного свойства (<xr:PropertyState>) ---
- # Свойство появилось в формате 2.19 (8.3.26): на 2.18 и ниже платформа молча выбрасывает элемент
- # при загрузке. С 2.19 Конфигуратор ставит его сам при выгрузке — эмитим, чтобы исходники навыка
- # совпадали с эталоном. Имя свойства = базовое имя файла модуля (Module / ObjectModule / …),
- # у заимствованной формы — Form. Ставит тот, кто создал файл модуля (или форму).
- function Build-PropertyStateXml {
- param([string]$propertyName, [string]$indent)
- $sb = New-Object System.Text.StringBuilder
- $sb.AppendLine("${indent}<xr:PropertyState>") | Out-Null
- $sb.AppendLine("${indent}`t<xr:Property>${propertyName}</xr:Property>") | Out-Null
- $sb.AppendLine("${indent}`t<xr:State>Extended</xr:State>") | Out-Null
- $sb.Append("${indent}</xr:PropertyState>") | Out-Null
- return $sb.ToString()
- }
- function Set-PropertyStateFlag {
- param([string]$objFile, [string]$propertyName, [string]$formatVersion)
- if ((Get-FormatRank $formatVersion) -lt 219) { return }
- if (-not (Test-Path $objFile)) { return }
- $enc = New-Object System.Text.UTF8Encoding($true)
- $text = [System.IO.File]::ReadAllText($objFile, $enc)
- $nl = if ($text -match "`r`n") { "`r`n" } else { "`n" }
- # ПЕРВЫЙ <InternalInfo> в файле — собственный у объекта: у реквизитов и подобъектов свои,
- # но они лежат ниже, внутри <ChildObjects>.
- $empty = [regex]::Match($text, '([ \t]*)<InternalInfo\s*/>')
- $open = [regex]::Match($text, '(?s)([ \t]*)<InternalInfo>(.*?)</InternalInfo>')
- if ($empty.Success -and (-not $open.Success -or $empty.Index -lt $open.Index)) {
- $ind = $empty.Groups[1].Value
- $block = Build-PropertyStateXml $propertyName ($ind + "`t")
- $replacement = "${ind}<InternalInfo>${nl}${block}${nl}${ind}</InternalInfo>"
- $text = $text.Remove($empty.Index, $empty.Length).Insert($empty.Index, $replacement)
- } elseif ($open.Success) {
- if ($open.Groups[2].Value -match "<xr:Property>$([regex]::Escape($propertyName))</xr:Property>") { return }
- $ind = $open.Groups[1].Value
- $block = Build-PropertyStateXml $propertyName ($ind + "`t")
- # Дописываем в КОНЕЦ InternalInfo: у Конфигуратора PropertyState идёт после GeneratedType.
- $closeAt = $open.Index + $open.Length - "</InternalInfo>".Length - $ind.Length
- $text = $text.Insert($closeAt, "${block}${nl}")
- } else {
- return
- }
- [System.IO.File]::WriteAllText($objFile, $text, $enc)
- }
- # --- 10g. Helper: пустой модуль заимствованного объекта ---
- function New-BorrowedModuleFile {
- param([string]$typeName, [string]$objName, [string]$moduleKind)
- $dirName = $childTypeDirMap[$typeName]
- $objDir = Join-Path (Join-Path $extDir $dirName) $objName
- $moduleDir = Join-Path $objDir "Ext"
- if (-not (Test-Path $moduleDir)) { New-Item -ItemType Directory -Path $moduleDir -Force | Out-Null }
- # NEVER overwrite an existing one: повторное заимствование не должно затирать дописанный код
- # (то же правило, что у модуля формы).
- $moduleFile = Join-Path $moduleDir "${moduleKind}.bsl"
- if (Test-Path $moduleFile) {
- Info " Preserved existing ${moduleKind}.bsl"
- } else {
- $enc = New-Object System.Text.UTF8Encoding($true)
- [System.IO.File]::WriteAllText($moduleFile, "", $enc)
- Info " Created: $moduleFile"
- }
- # Флаг ставим и для уже существовавшего файла: состояние объекта должно отражать факт модуля.
- Set-PropertyStateFlag (Join-Path (Join-Path $extDir $dirName) "${objName}.xml") $moduleKind $script:formatVersion
- return $moduleFile
- }
- # --- 11. Helper: generate InternalInfo XML ---
- function Build-InternalInfoXml {
- param([string]$typeName, [string]$objName, [string]$indent)
- $types = $script:generatedTypes[$typeName]
- if (-not $types -or $types.Count -eq 0) {
- return "${indent}<InternalInfo/>"
- }
- $sb = New-Object System.Text.StringBuilder
- $sb.AppendLine("${indent}<InternalInfo>") | Out-Null
- # ExchangePlan: ThisNode UUID before GeneratedTypes
- if ($typeName -eq "ExchangePlan") {
- $thisNodeUuid = [guid]::NewGuid().ToString()
- $sb.AppendLine("${indent}`t<xr:ThisNode>${thisNodeUuid}</xr:ThisNode>") | Out-Null
- }
- foreach ($gt in $types) {
- $fullName = "$($gt.prefix).${objName}"
- $typeId = [guid]::NewGuid().ToString()
- $valueId = [guid]::NewGuid().ToString()
- $sb.AppendLine("${indent}`t<xr:GeneratedType name=`"${fullName}`" category=`"$($gt.category)`">") | Out-Null
- $sb.AppendLine("${indent}`t`t<xr:TypeId>${typeId}</xr:TypeId>") | Out-Null
- $sb.AppendLine("${indent}`t`t<xr:ValueId>${valueId}</xr:ValueId>") | Out-Null
- $sb.AppendLine("${indent}`t</xr:GeneratedType>") | Out-Null
- }
- $sb.Append("${indent}</InternalInfo>") | Out-Null
- return $sb.ToString()
- }
- # --- 11b. Collect DataPath references from source Form.xml ---
- # --- 11b1. Основной реквизит исходной формы ---
- # Переносится ЦЕЛИКОМ, а не собирается из констант: имя, тип и состав детей зависят от вида формы.
- # У формы объекта это «Объект»/<Тип>Object + SavedData/UseAlways/Columns, у формы списка —
- # «Список»/DynamicList + Settings, у формы записи регистра — «Запись»/RecordManager + SavedData.
- # Синтез фиксированного набора давал для необъектных форм «Исключение XDTO» при загрузке.
- # Конфигуратор меняет у скопированного реквизита только id (эталоны Issue64UtB, Issue66Example2).
- # Имена реквизитов ИСХОДНОЙ формы → их id. Ссылки параметров выбора адресуют реквизит формы
- # именно по id базовой формы (см. Rewrite-ChoiceParameterLinks).
- function Get-FormAttributeIds {
- param($formEl)
- $result = @{}
- $attrs = $formEl.SelectSingleNode("*[local-name()='Attributes']")
- if (-not $attrs) { return $result }
- foreach ($a in $attrs.ChildNodes) {
- if ($a.NodeType -ne 'Element' -or $a.LocalName -ne 'Attribute') { continue }
- $nm = $a.GetAttribute("name"); $id = $a.GetAttribute("id")
- if ($nm -and $id) { $result[$nm] = $id }
- }
- return $result
- }
- # Контекст разрешения путей в связях формы (см. Resolve-LinkDataPath) — всё по ИСХОДНОЙ форме:
- # колонки реквизитов формы, колонки AdditionalColumns, элементы-таблицы и вид основного реквизита.
- function Get-LinkContext {
- param($formEl, [string]$mainName, [bool]$mainBorrowed, $borrowedNames, $attrUuids, $formAttrIds)
- $cols = @{}; $addCols = @{}; $tables = @{}; $kind = $null
- $attrs = $formEl.SelectSingleNode("*[local-name()='Attributes']")
- if ($attrs) {
- foreach ($a in $attrs.ChildNodes) {
- if ($a.NodeType -ne 'Element' -or $a.LocalName -ne 'Attribute') { continue }
- $nm = $a.GetAttribute("name")
- $columns = $a.SelectSingleNode("*[local-name()='Columns']")
- if ($columns) {
- foreach ($c in $columns.ChildNodes) {
- if ($c.NodeType -ne 'Element') { continue }
- if ($c.LocalName -eq 'Column') {
- $cols["$nm.$($c.GetAttribute('name'))"] = $c.GetAttribute('id')
- } elseif ($c.LocalName -eq 'AdditionalColumns') {
- $tblPath = $c.GetAttribute('table')
- foreach ($ac in @($c.SelectNodes("*[local-name()='Column']"))) {
- $addCols["$tblPath.$($ac.GetAttribute('name'))"] = $ac.GetAttribute('id')
- }
- }
- }
- }
- if ($mainName -and $nm -ceq $mainName) {
- $typeNode = $a.SelectSingleNode("*[local-name()='Type']/*[local-name()='Type']")
- if ($typeNode) {
- # Тип без имени объекта (cfg:ConstantsSet) — тоже вид
- $tm = [regex]::Match($typeNode.InnerText.Trim(), '^(?:\w+:)?(\w+)(?:\.|$)')
- if ($tm.Success -and $script:mainAttrKinds.ContainsKey($tm.Groups[1].Value)) { $kind = $script:mainAttrKinds[$tm.Groups[1].Value] }
- }
- }
- }
- }
- $items = $formEl.SelectSingleNode("*[local-name()='ChildItems']")
- if ($items) {
- foreach ($t in @($items.SelectNodes(".//*[local-name()='Table']"))) {
- $dp = $t.SelectSingleNode("*[local-name()='DataPath']")
- if ($dp) { $tables[$t.GetAttribute('name')] = @{ Id = $t.GetAttribute('id'); Path = $dp.InnerText.Trim() } }
- }
- }
- $mainId = if ($mainName -and $formAttrIds.ContainsKey($mainName)) { $formAttrIds[$mainName] } else { "1" }
- return @{
- MainName = $mainName; MainId = $mainId; MainBorrowed = $mainBorrowed; MainKind = $kind; BorrowedNames = $borrowedNames
- AttrUuids = $attrUuids; FormAttrIds = $formAttrIds; FormAttrCols = $cols; AddCols = $addCols; Tables = $tables
- }
- }
- # Ключ сравнения имён в тексте запроса: язык запросов регистронезависим, Ё и Е — одна буква.
- function Get-QueryKey([string]$s) {
- return $s.ToUpperInvariant().Replace([string][char]0x0401, [string][char]0x0415)
- }
- # Виды таблиц языка запросов (рус. и англ.) → вид метаданных. Ключи — через Get-QueryKey.
- $script:queryTableKinds = @{}
- foreach ($qk in @(
- @("Справочник","Catalog"), @("Документ","Document"), @("Перечисление","Enum"),
- @("ПланВидовХарактеристик","ChartOfCharacteristicTypes"), @("ПланСчетов","ChartOfAccounts"),
- @("ПланВидовРасчета","ChartOfCalculationTypes"), @("ПланОбмена","ExchangePlan"),
- @("БизнесПроцесс","BusinessProcess"), @("Задача","Task"),
- @("РегистрСведений","InformationRegister"), @("РегистрНакопления","AccumulationRegister"),
- @("РегистрБухгалтерии","AccountingRegister"), @("РегистрРасчета","CalculationRegister"),
- @("ЖурналДокументов","DocumentJournal"), @("Константа","Constant"),
- @("Последовательность","Sequence"), @("КритерийОтбора","FilterCriterion"),
- @("ВнешнийИсточникДанных","ExternalDataSource"))) {
- $script:queryTableKinds[(Get-QueryKey $qk[0])] = $qk[1]
- $script:queryTableKinds[(Get-QueryKey $qk[1])] = $qk[1]
- }
- # Ключевые слова языка запросов, которые могут стоять сразу за таблицей вместо псевдонима.
- $script:queryAliasStopWords = @{}
- foreach ($kw in @("ГДЕ","WHERE","ЛЕВОЕ","LEFT","ПРАВОЕ","RIGHT","ПОЛНОЕ","FULL","ВНУТРЕННЕЕ","INNER",
- "ВНЕШНЕЕ","OUTER","СОЕДИНЕНИЕ","JOIN","ПО","ON","СГРУППИРОВАТЬ","GROUP","УПОРЯДОЧИТЬ","ORDER",
- "ИМЕЮЩИЕ","HAVING","ОБЪЕДИНИТЬ","UNION","ДЛЯ","FOR","ИТОГИ","TOTALS","ИНДЕКСИРОВАТЬ","INDEX",
- "ИЗ","FROM","ВЫБРАТЬ","SELECT","И","AND","ИЛИ","OR","НЕ","NOT","КОГДА","WHEN","ТОГДА","THEN",
- "ИНАЧЕ","ELSE","КОНЕЦ","END","ПОМЕСТИТЬ","INTO","ССЫЛКА","REFS","В","IN","МЕЖДУ","BETWEEN",
- "ПОДОБНО","LIKE","ЕСТЬ","IS","ИЕРАРХИИ","HIERARCHY","ВОЗР","ASC","УБЫВ","DESC","АВТОУПОРЯДОЧИВАНИЕ",
- "AUTOORDER","ИЗМЕНЕНИЯ","UPDATE","ВСЕ","ALL")) { $script:queryAliasStopWords[(Get-QueryKey $kw)] = $true }
- # Стандартные поля по видам объектов (рус. и англ.) — есть у таблицы без заимствования реквизитов.
- # У каждого вида свои: Номер/Дата — стандартные у документа, а у справочника это обычные реквизиты,
- # которых в оболочке нет. Неизвестный вид — только общие поля. Поля, которые включаются свойством
- # объекта (Родитель, Владелец, Период регистра сведений…), — в $script:queryGatedStd. Ключи — Get-QueryKey.
- $script:queryStdByKind = @{}
- $qsCommon = @("Ссылка","Ref","ПометкаУдаления","DeletionMark","Предопределенный","Predefined",
- "ИмяПредопределенныхДанных","PredefinedDataName","ВерсияДанных","DataVersion","Представление",
- "Presentation","DefaultPicture")
- $qsByKind = @{
- "Catalog" = @("Код","Code","Наименование","Description")
- "Document" = @("Номер","Number","Дата","Date","Проведен","Posted","МоментВремени","PointInTime")
- "ChartOfCharacteristicTypes" = @("Код","Code","Наименование","Description","ТипЗначения","ValueType")
- "ChartOfAccounts" = @("Код","Code","Наименование","Description","Родитель","Parent","Порядок","Order","Вид","Type","Забалансовый","OffBalance")
- "ChartOfCalculationTypes" = @("Код","Code","Наименование","Description")
- "ExchangePlan" = @("Код","Code","Наименование","Description","НомерОтправленного","SentNo","НомерПринятого","ReceivedNo","ЭтотУзел","ThisNode")
- "BusinessProcess" = @("Номер","Number","Дата","Date","Завершен","Completed","Стартован","Started","ВедущаяЗадача","HeadTask")
- "Task" = @("Номер","Number","Дата","Date","Наименование","Description","Выполнена","Executed","БизнесПроцесс","BusinessProcess","ТочкаМаршрута","RoutePoint")
- "Enum" = @("Порядок","Order")
- "DocumentJournal" = @("Номер","Number","Дата","Date","Проведен","Posted","Тип","Type")
- "InformationRegister" = @()
- "AccumulationRegister" = @("Период","Period","Регистратор","Recorder","НомерСтроки","LineNumber","Активность","Active","ВидДвижения","RecordType")
- "AccountingRegister" = @("Период","Period","Регистратор","Recorder","НомерСтроки","LineNumber","Активность","Active")
- "CalculationRegister" = @("Регистратор","Recorder","НомерСтроки","LineNumber","Активность","Active")
- }
- $script:queryStdCommon = @{}
- foreach ($sf in $qsCommon) { $script:queryStdCommon[(Get-QueryKey $sf)] = $true }
- foreach ($qsk in $qsByKind.Keys) {
- $set = @{}
- foreach ($sf in $qsCommon + $qsByKind[$qsk]) { $set[(Get-QueryKey $sf)] = $true }
- $script:queryStdByKind[$qsk] = $set
- }
- # Стандартные поля, которые есть, только если это включено свойством объекта: у заимствованного
- # объекта в расширении их нет, пока свойства нет в его копии (замер 8.3.24: Родитель у иерархического
- # справочника на оболочке без <Hierarchical> — «Неверный путь к данным»; Код, Наименование — есть).
- $script:queryGatedStd = @{}
- foreach ($g in @(
- @("Catalog", "Hierarchical", @("Родитель","Parent","ЭтоГруппа","IsFolder")),
- @("ChartOfCharacteristicTypes", "Hierarchical", @("Родитель","Parent","ЭтоГруппа","IsFolder")),
- @("Catalog", "Owners", @("Владелец","Owner")),
- @("InformationRegister", "Periodic", @("Период","Period")),
- @("InformationRegister", "Recorder", @("Регистратор","Recorder","НомерСтроки","LineNumber","Активность","Active")))) {
- foreach ($f in $g[2]) { $script:queryGatedStd["$($g[0])|$(Get-QueryKey $f)"] = $g[1] }
- }
- function Test-QueryStdField($info, [string]$fieldKey) {
- $gate = $script:queryGatedStd["$($info.Kind)|$fieldKey"]
- if ($gate) { return [bool]$info.Gates[$gate] }
- if ($script:queryStdByKind.ContainsKey($info.Kind)) { return $script:queryStdByKind[$info.Kind].ContainsKey($fieldKey) }
- return $script:queryStdCommon.ContainsKey($fieldKey)
- }
- # Псевдоним таблицы, ссылка на которую кончается в позиции $pos: «КАК имя» / «AS имя», имя без
- # КАК (если это не ключевое слово); параметры виртуальной таблицы в скобках пропускаются.
- # $null — псевдонима нет, тогда псевдоним — последний сегмент имени таблицы. Иначе — имя и позиция:
- # имя без КАК — тоже определение псевдонима, а не поле.
- $script:reTableAlias = New-Object System.Text.RegularExpressions.Regex '\G(?:(КАК|AS)\s+)?([^\W\d]\w*)', ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
- function Get-QueryTableAlias([string]$q, [int]$pos) {
- $i = $pos
- while ($i -lt $q.Length -and [char]::IsWhiteSpace($q[$i])) { $i++ }
- if ($i -lt $q.Length -and $q[$i] -eq '(') {
- $depth = 0
- while ($i -lt $q.Length) {
- if ($q[$i] -eq '(') { $depth++ } elseif ($q[$i] -eq ')') { $depth--; if ($depth -eq 0) { $i++; break } }
- $i++
- }
- while ($i -lt $q.Length -and [char]::IsWhiteSpace($q[$i])) { $i++ }
- }
- $m = $script:reTableAlias.Match($q, $i)
- if (-not $m.Success) { return $null }
- if (-not $m.Groups[1].Success -and $script:queryAliasStopWords.ContainsKey((Get-QueryKey $m.Groups[2].Value))) { return $null }
- return @{ Name = $m.Groups[2].Value; Index = $m.Groups[2].Index }
- }
- # Зарезервированные слова языка запросов — полем быть не могут: стоп-слова псевдонима плюс
- # литералы и модификаторы. Имена типов (СТРОКА, ДАТА…) и периодов (МЕСЯЦ, ГОД…) сюда не входят:
- # это бывают и имена полей. Тип пропускается по позиции — после КАК, как всякое определение
- # псевдонима; период — аргументом после запятой внутри скобок (НАЧАЛОПЕРИОДА(Д.Дата, МЕСЯЦ)).
- $script:queryReservedWords = @{}
- foreach ($kw in $script:queryAliasStopWords.Keys) { $script:queryReservedWords[$kw] = $true }
- foreach ($kw in @("КАК","AS","РАЗРЕШЕННЫЕ","ALLOWED","РАЗЛИЧНЫЕ","DISTINCT","ПЕРВЫЕ","TOP","NULL","ИСТИНА",
- "TRUE","ЛОЖЬ","FALSE","НЕОПРЕДЕЛЕНО","UNDEFINED","ВЫБОР","CASE","СПЕЦСИМВОЛ","ESCAPE","BY",
- "ИЕРАРХИЯ","ОБЩИЕ","OVERALL","ПЕРИОДАМИ","PERIODS","УНИЧТОЖИТЬ","DROP","ГРУППИРУЮЩИМ","НАБОРАМ",
- "GROUPING","SETS")) {
- $script:queryReservedWords[(Get-QueryKey $kw)] = $true
- }
- $script:queryPeriodNames = @{}
- foreach ($kw in @("СЕКУНДА","SECOND","МИНУТА","MINUTE","ЧАС","HOUR","ДЕНЬ","DAY","НЕДЕЛЯ","WEEK",
- "МЕСЯЦ","MONTH","КВАРТАЛ","QUARTER","ГОД","YEAR","ДЕКАДА","TENDAYS","ПОЛУГОДИЕ","HALFYEAR","АВТО","AUTO")) {
- $script:queryPeriodNames[(Get-QueryKey $kw)] = $true
- }
- $script:reFuncParen = New-Object System.Text.RegularExpressions.Regex '\G\s*\('
- # Слова, после которых в запросе стоит таблица-источник
- $script:querySourceKeywords = @{}
- foreach ($kw in @("ИЗ","FROM","СОЕДИНЕНИЕ","JOIN")) { $script:querySourceKeywords[(Get-QueryKey $kw)] = $true }
- # Ссылочный тип → вид метаданных: CatalogRef → Catalog и т.п. (у DefinedType и прочих — $null).
- function Get-RefKindFromType([string]$typeText) {
- $t = $typeText.Trim()
- $ci = $t.IndexOf(':'); if ($ci -ge 0) { $t = $t.Substring($ci + 1) }
- if ($t -match '^(\w+)Ref\.(\w+)$') { return @{ Kind = $Matches[1]; Name = $Matches[2] } }
- return $null
- }
- # Что объект предоставляет запросу в контексте расширения — по итоговому составу расширения.
- # $null — объекта в расширении нет. Fields: имена заимствованных подобъектов (реквизиты, измерения,
- # ресурсы, ТЧ, признаки учёта…); TSCols: колонки заимствованных ТЧ; EnumValues: значения
- # перечисления; Types: поле → ссылочный тип (одиночный) для разыменования. Ключи — Get-QueryKey.
- $script:extTableInfoCache = @{}
- $script:queryFieldKinds = @('Attribute','Dimension','Resource','TabularSection','AddressingAttribute','AccountingFlag','ExtDimensionAccountingFlag','Column','EnumValue')
- function Get-ExtTableInfo([string]$kind, [string]$nameKey) {
- $cacheKey = "$kind|$nameKey"
- if ($script:extTableInfoCache.ContainsKey($cacheKey)) { return $script:extTableInfoCache[$cacheKey] }
- $info = $null
- $dir = $childTypeDirMap[$kind]
- $actual = $null
- if ($dir) {
- # Имя — каноническое, из состава расширения: в запросе регистр и Ё/Е произвольны
- foreach ($c in $script:childObjsEl.ChildNodes) {
- if ($c.NodeType -ne 'Element' -or $c.LocalName -ne $kind) { continue }
- if ((Get-QueryKey $c.InnerText.Trim()) -ceq $nameKey) { $actual = $c.InnerText.Trim(); break }
- }
- }
- if ($actual) {
- $f = Join-Path (Join-Path $extDir $dir) "$actual.xml"
- if (Test-Path -LiteralPath $f) {
- $doc = New-Object System.Xml.XmlDocument
- $doc.Load($f)
- $el = $null
- foreach ($c in $doc.DocumentElement.ChildNodes) { if ($c.NodeType -eq 'Element') { $el = $c; break } }
- $info = @{ Kind = $kind; Fields = @{}; TSCols = @{}; EnumValues = @{}; Types = @{}; Gates = @{} }
- if ($el) {
- $pr = $el.SelectSingleNode("*[local-name()='Properties']")
- if ($pr) {
- $hv = $pr.SelectSingleNode("*[local-name()='Hierarchical']")
- $info.Gates['Hierarchical'] = [bool]($hv -and $hv.InnerText.Trim() -ceq 'true')
- $info.Gates['Owners'] = [bool]($pr.SelectSingleNode("*[local-name()='Owners']/*"))
- $pv = $pr.SelectSingleNode("*[local-name()='InformationRegisterPeriodicity']")
- $info.Gates['Periodic'] = [bool]($pv -and $pv.InnerText.Trim() -and $pv.InnerText.Trim() -cne 'Nonperiodical')
- $wv = $pr.SelectSingleNode("*[local-name()='WriteMode']")
- $info.Gates['Recorder'] = [bool]($wv -and $wv.InnerText.Trim() -ceq 'RecorderSubordinate')
- }
- foreach ($sub in $el.SelectNodes("*[local-name()='ChildObjects']/*")) {
- # Поля таблицы — только данные: команды, формы, макеты и т.п. полями не бывают
- if ($script:queryFieldKinds -notcontains $sub.LocalName) { continue }
- $nm = $sub.SelectSingleNode("*[local-name()='Properties']/*[local-name()='Name']")
- if (-not $nm) { continue }
- $k = Get-QueryKey $nm.InnerText.Trim()
- if ($sub.LocalName -eq 'EnumValue') { $info.EnumValues[$k] = $true; continue }
- $info.Fields[$k] = $true
- $types = @($sub.SelectNodes("*[local-name()='Properties']/*[local-name()='Type']/*[local-name()='Type']"))
- if ($types.Count -eq 1) {
- $rk = Get-RefKindFromType $types[0].InnerText
- if ($rk) { $info.Types[$k] = $rk }
- }
- if ($sub.LocalName -eq 'TabularSection') {
- $cols = @{}
- foreach ($cn in $sub.SelectNodes("*[local-name()='ChildObjects']/*/*[local-name()='Properties']/*[local-name()='Name']")) {
- $cols[(Get-QueryKey $cn.InnerText.Trim())] = $true
- }
- $info.TSCols[$k] = $cols
- }
- }
- }
- }
- }
- $script:extTableInfoCache[$cacheKey] = $info
- return $info
- }
- # Что в ручном запросе динамического списка не разрешится в контексте расширения — список причин;
- # пустой — запрос разрешим, тильда не нужна. Проверяется по ИТОГОВОМУ составу расширения, а не по
- # прогнозу заимствования: каждая таблица запроса (её объект) должна быть в расширении, её ТЧ,
- # значения перечисления — тоже; каждое поле — заимствованным подобъектом или стандартным полем,
- # разыменование — по одиночному ссылочному типу до объекта, который тоже есть в расширении.
- # Предопределённые, виртуальные таблицы, «*», обращения через скобку и неизвестные слова — не
- # разрешаются. Правило консервативное: лишняя тильда — лишь шум, пропущенная — отказ загрузки.
- # Сверено с платформой 8.3.24 (оракул — загрузка без тильды).
- function Get-DynListQueryUnresolved([string]$queryText) {
- $reasons = New-Object System.Collections.Generic.List[string]
- # Строковые литералы и комментарии — не код запроса; пробелы вокруг точки — часть пути
- $q = [regex]::Replace($queryText, '"(?:[^"]|"")*"|//[^\r\n]*', ' ')
- $q = [regex]::Replace($q, '(?<=[\w)])\s*\.\s*(?=[^\W\d]|\*)', '.')
- $emptyRefKeys = @((Get-QueryKey "ПустаяСсылка"), (Get-QueryKey "EmptyRef"))
- $tsStdKeys = @((Get-QueryKey "Ссылка"), (Get-QueryKey "Ref"), (Get-QueryKey "НомерСтроки"), (Get-QueryKey "LineNumber"))
- $sameObjStd = @((Get-QueryKey "Ссылка"), (Get-QueryKey "Ref"), (Get-QueryKey "Родитель"), (Get-QueryKey "Parent"))
- $refKeys = @((Get-QueryKey "Ссылка"), (Get-QueryKey "Ref"))
- # «*» (кроме КОЛИЧЕСТВО(*)) и обращение через скобку — состав полей не виден
- if ([regex]::IsMatch($q, '(?i)\.\*|(?:(?<![\w.])(?:ВЫБРАТЬ|SELECT|РАЗЛИЧНЫЕ|DISTINCT|РАЗРЕШЕННЫЕ|ALLOWED)|,|\{|(?<![\w.])(?:ПЕРВЫЕ|TOP)\s+\d+)\s*\*')) { $reasons.Add("*") }
- # Области запроса не разбираются: части ОБЪЕДИНИТЬ и вложенные запросы — со своими таблицами
- if ([regex]::IsMatch($q, '(?i)(?<![\w.])(?:ОБЪЕДИНИТЬ|UNION)(?![\w.])')) { $reasons.Add("ОБЪЕДИНИТЬ") }
- if ([regex]::Matches($q, '(?i)(?<![\w.])(?:ВЫБРАТЬ|SELECT)(?![\w.])').Count -gt 1) { $reasons.Add("вложенный запрос") }
- if ([regex]::IsMatch($q, '\)\.[^\W\d]')) { $reasons.Add(").Поле") }
- $pathMatches = @([regex]::Matches($q, '(?<![\w.&])[^\W\d]\w*(?:\.[^\W\d]\w*)+'))
- $aliasPos = New-Object 'System.Collections.Generic.HashSet[int]'
- # Таблицы и их псевдонимы: псевдоним → @{ Info; TS ('' — сам объект) }
- $aliasMap = @{}
- foreach ($pm in $pathMatches) {
- $segs = $pm.Value.Split('.')
- $k0 = Get-QueryKey $segs[0]
- if (-not $script:queryTableKinds.ContainsKey($k0)) { continue }
- $kind = $script:queryTableKinds[$k0]
- $info = Get-ExtTableInfo $kind (Get-QueryKey $segs[1])
- if ($null -eq $info) { $reasons.Add("$($segs[0]).$($segs[1])"); continue }
- $tsKey = ''
- if ($segs.Count -ge 3) {
- $k2 = Get-QueryKey $segs[2]
- if ($segs.Count -eq 3 -and ($emptyRefKeys -ccontains $k2 -or $info.EnumValues.ContainsKey($k2))) { continue }
- if ($segs.Count -eq 3 -and $info.TSCols.ContainsKey($k2)) { $tsKey = $k2 }
- else { $reasons.Add($pm.Value); continue }
- }
- # Псевдоним — только у таблицы-источника (после ИЗ/СОЕДИНЕНИЕ или запятой в их списке). У
- # ссылок в ЗНАЧЕНИЕ(), ТИП(), ВЫРАЗИТЬ(... КАК …), ССЫЛКА … псевдонима нет: фантомный псевдоним
- # закрыл бы от проверки одноимённое поле.
- $bi = $pm.Index - 1
- while ($bi -ge 0 -and [char]::IsWhiteSpace($q[$bi])) { $bi-- }
- $isSource = $false
- if ($bi -ge 0 -and $q[$bi] -eq ',') { $isSource = $true }
- elseif ($bi -ge 0) {
- $we = $bi + 1
- while ($bi -ge 0 -and [char]::IsLetterOrDigit($q[$bi])) { $bi-- }
- $isSource = $script:querySourceKeywords.ContainsKey((Get-QueryKey $q.Substring($bi + 1, $we - $bi - 1)))
- }
- if (-not $isSource) { continue }
- $al = Get-QueryTableAlias $q ($pm.Index + $pm.Length)
- $alias = $segs[-1]
- if ($al) { $alias = $al.Name; [void]$aliasPos.Add($al.Index) }
- $aliasMap[(Get-QueryKey $alias)] = @{ Info = $info; TS = $tsKey }
- }
- # Поле Источник.Поле[.Подполе…]: каждое звено — заимствованный подобъект или стандартное поле
- foreach ($pm in $pathMatches) {
- $segs = $pm.Value.Split('.')
- $k0 = Get-QueryKey $segs[0]
- if ($script:queryTableKinds.ContainsKey($k0)) { continue }
- if (-not $aliasMap.ContainsKey($k0)) { $reasons.Add($pm.Value); continue }
- $curInfo = $aliasMap[$k0].Info; $curTS = $aliasMap[$k0].TS
- $ok = $true
- for ($i = 1; $i -lt $segs.Count; $i++) {
- $fk = Get-QueryKey $segs[$i]
- $last = ($i -eq $segs.Count - 1)
- if ($curTS) {
- # Поле строки ТЧ: колонка (без разыменования) или Ссылка/НомерСтроки
- if ($last -and ($curInfo.TSCols[$curTS].ContainsKey($fk) -or $tsStdKeys -ccontains $fk)) { break }
- if (-not $last -and $refKeys -ccontains $fk) { $curTS = ''; continue }
- $ok = $false; break
- }
- if ($last) {
- if (-not ($curInfo.Fields.ContainsKey($fk) -or (Test-QueryStdField $curInfo $fk))) { $ok = $false }
- break
- }
- # Разыменование: Ссылка/Родитель — тот же объект; реквизит — по его ссылочному типу
- if ($sameObjStd -ccontains $fk -and (Test-QueryStdField $curInfo $fk)) { continue }
- if ($curInfo.Types.ContainsKey($fk)) {
- $t = $curInfo.Types[$fk]
- $curInfo = Get-ExtTableInfo $t.Kind (Get-QueryKey $t.Name)
- if ($null -eq $curInfo) { $ok = $false; break }
- continue
- }
- $ok = $false; break
- }
- if (-not $ok) { $reasons.Add($pm.Value) }
- }
- # Слова без точки. Пропускаются: определение псевдонима (после КАК/AS — в т.ч. имя типа в
- # ВЫРАЗИТЬ), имя функции (перед «(»), зарезервированное слово, период аргументом после запятой
- # внутри скобок. Остальное — поле одной из таблиц запроса: Месяц, Документ, Сумма — и имена полей.
- $aliasDefs = New-Object 'System.Collections.Generic.HashSet[int]'
- foreach ($m in [regex]::Matches($q, '(?i)(?<![\w.])(?:КАК|AS)\s+([^\W\d]\w*)')) { [void]$aliasDefs.Add($m.Groups[1].Index) }
- $commaArgs = New-Object 'System.Collections.Generic.HashSet[int]'
- foreach ($m in [regex]::Matches($q, ',\s*([^\W\d]\w*)')) { [void]$commaArgs.Add($m.Groups[1].Index) }
- $depthAt = New-Object 'int[]' ($q.Length + 1)
- $depth = 0
- for ($ci = 0; $ci -lt $q.Length; $ci++) {
- $depthAt[$ci] = $depth
- if ($q[$ci] -eq '(') { $depth++ } elseif ($q[$ci] -eq ')') { $depth-- }
- }
- foreach ($wm in [regex]::Matches($q, '(?<![\w.&])[^\W\d]\w*(?![\w.])')) {
- if ($aliasDefs.Contains($wm.Index) -or $aliasPos.Contains($wm.Index)) { continue }
- $wk = Get-QueryKey $wm.Value
- if ($script:queryReservedWords.ContainsKey($wk)) { continue }
- if ($script:queryPeriodNames.ContainsKey($wk) -and $commaArgs.Contains($wm.Index) -and $depthAt[$wm.Index] -gt 0) { continue }
- if ($script:reFuncParen.Match($q, $wm.Index + $wm.Length).Success) { continue }
- $found = $false
- foreach ($src in $aliasMap.Values) {
- if ($src.TS) {
- if ($src.Info.TSCols[$src.TS].ContainsKey($wk) -or $tsStdKeys -ccontains $wk) { $found = $true; break }
- } elseif ($src.Info.Fields.ContainsKey($wk) -or (Test-QueryStdField $src.Info $wk)) { $found = $true; break }
- }
- if (-not $found) { $reasons.Add($wm.Value) }
- }
- # Дедуп с учётом регистра — как в py-порте (хеш-таблица PowerShell регистронезависима)
- $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::Ordinal)
- return @($reasons | Where-Object { $seen.Add($_) })
- }
- function Get-MainAttributeInfo {
- param($formEl, [string]$nsStripPattern)
- $mainAttr = $formEl.SelectSingleNode("*[local-name()='Attributes']/*[local-name()='Attribute'][*[local-name()='MainAttribute']='true']")
- if (-not $mainAttr) { return $null }
- $xml = [regex]::Replace($mainAttr.OuterXml, $nsStripPattern, '')
- # id заменяется только в открывающем теге самого реквизита — у вложенных элементов свои
- $xml = [regex]::Replace($xml, '^(<Attribute\s[^>]*?)id="[^"]*"', "`${1}id=`"$script:mainAttrId`"")
- return @{ Name = $mainAttr.GetAttribute("name"); Xml = $xml }
- }
- function Collect-FormDataPaths {
- param([string]$formXmlPath, [string]$mainAttrName)
- # Корень путей — имя основного реквизита формы: «Объект» у формы объекта, «Список» у формы
- # списка, «Запись» у формы записи регистра. Зашитый «Объект» не находил ничего у необъектных
- # форм, и в оболочку не заимствовалось ни одного дочернего объекта.
- $root = [regex]::Escape($mainAttrName)
- $enc = New-Object System.Text.UTF8Encoding($true)
- $content = [System.IO.File]::ReadAllText($formXmlPath, $enc)
- $firstLevel = @{}
- $deepPaths = @()
- # Scan every data-binding tag (DataPath/TitleDataPath/FooterDataPath/HeaderDataPath/MultipleValue*)
- # for Объект.* references — picture-path tags carry picture indices, not data attributes.
- foreach ($tag in $script:formBindingDataTags) {
- $bms = [regex]::Matches($content, "<$tag>[^<]*\b$root\.(\w+(?:\.\w+)*)</$tag>")
- foreach ($m in $bms) {
- $path = $m.Groups[1].Value
- $segments = $path.Split(".")
- $seg0 = $segments[0]
- if ($script:standardFields -contains $seg0) { continue }
- $firstLevel[$seg0] = $true
- if ($segments.Count -ge 2) {
- if ($script:standardFields -contains $segments[1]) { continue }
- $deepPaths += ,$segments
- }
- }
- }
- # Also scan <Field>Объект.X</Field> — object attributes referenced by filter/conditional-appearance
- # fields (and dynamic lists), not via a *DataPath binding (e.g. УдалитьЮрФизЛицо). Designer borrows these too.
- $fieldMatches = [regex]::Matches($content, "<Field>[^<]*\b$root\.(\w+(?:\.\w+)*)</Field>")
- foreach ($m in $fieldMatches) {
- $path = $m.Groups[1].Value
- $segments = $path.Split(".")
- $seg0 = $segments[0]
- if ($script:standardFields -contains $seg0) { continue }
- $firstLevel[$seg0] = $true
- if ($segments.Count -ge 2) {
- if ($script:standardFields -contains $segments[1]) { continue }
- $deepPaths += ,$segments
- }
- }
- # Also scan <AdditionalColumns table="Объект.X"> — доп. колонки табличной части, объявленные в
- # самой форме (напр. Объект.Товары.Артикул). Такая ТЧ может больше нигде на форме не встречаться,
- # и без её заимствования платформа отвергает форму: «Неверный путь к данным».
- $acMatches = [regex]::Matches($content, "<AdditionalColumns table=`"$root\.(\w+)`"")
- foreach ($m in $acMatches) {
- $seg0 = $m.Groups[1].Value
- if ($script:standardFields -contains $seg0) { continue }
- $firstLevel[$seg0] = $true
- }
- # Текст запроса динамического списка — такое же место ссылки на реквизиты объекта, как DataPath.
- # Конфигуратор заимствует всё, что упомянуто в запросе: на эталоне Issue66Example2 это 21 из 27
- # дочерних объектов, совпадение с ним точное в обе стороны. У списка без ручного запроса
- # (<QueryText> нет) заимствуется только видимое на форме — эталон Issue66Example3.
- # Разбирать язык запросов не нужно: имена-кандидаты отфильтрует Resolve-SourceAttributes по
- # реальному составу объекта, поэтому лишние слова из запроса безвредны.
- foreach ($qm in [regex]::Matches($content, '(?s)<QueryText>(.*?)</QueryText>')) {
- foreach ($w in [regex]::Matches($qm.Groups[1].Value, '[\w]+')) {
- $word = $w.Value
- if ($script:standardFields -contains $word) { continue }
- $firstLevel[$word] = $true
- }
- }
- # Deduplicate deep paths (each is the full segment list after the root)
- $seen = @{}
- $uniqueDeep = @()
- foreach ($dp in $deepPaths) {
- $key = $dp -join "."
- if (-not $seen.ContainsKey($key)) {
- $seen[$key] = $true
- $uniqueDeep += ,$dp
- }
- }
- return @{ FirstLevel = $firstLevel; DeepPaths = $uniqueDeep }
- }
- # --- 11c. Resolve source attributes and tabular sections ---
- function Resolve-SourceAttributes {
- param([string]$typeName, [string]$objName, $firstLevelNames)
- # $firstLevelNames: hashtable of names, or $null for "all"
- # Имена сверяются ключом запроса (регистр, Ё/Е): слова приходят и из текста запроса списка,
- # а правило тильды (Get-DynListQueryUnresolved) считает их найденными по тому же ключу.
- $flKeys = $null
- if ($null -ne $firstLevelNames) {
- $flKeys = @{}
- foreach ($flk in $firstLevelNames.Keys) { $flKeys[(Get-QueryKey $flk)] = $true }
- }
- $dirName = $childTypeDirMap[$typeName]
- $srcFile = Join-Path (Join-Path $cfgDir $dirName) "${objName}.xml"
- if (-not (Test-Path $srcFile)) {
- Write-Error "Source object not found: $srcFile"
- exit 1
- }
- $srcDoc = New-Object System.Xml.XmlDocument
- $srcDoc.PreserveWhitespace = $false
- $srcDoc.Load($srcFile)
- $srcNs = New-Object System.Xml.XmlNamespaceManager($srcDoc.NameTable)
- $srcNs.AddNamespace("md", $script:mdNs)
- $srcNs.AddNamespace("xr", $script:xrNs)
- $srcNs.AddNamespace("v8", $script:v8Ns)
- $srcEl = $null
- foreach ($c in $srcDoc.DocumentElement.ChildNodes) {
- if ($c.NodeType -eq 'Element') { $srcEl = $c; break }
- }
- if (-not $srcEl) { Write-Error "No metadata element in source: $srcFile"; exit 1 }
- $childObjs = $srcEl.SelectSingleNode("md:ChildObjects", $srcNs)
- if (-not $childObjs) { return @{ Attributes = @(); TabularSections = @(); ExtraProps = @{} } }
- $attrs = @()
- $tabSections = @()
- # Стандартная ТЧ видов субконто плана счетов: нужна форме (или режим All) — переносятся свойства
- # ExtDimensionTypes/MaxExtDimensionCount и признаки учёта субконто
- $wantExtDim = $typeName -eq 'ChartOfAccounts' -and ($null -eq $flKeys -or $flKeys.ContainsKey((Get-QueryKey 'ExtDimensionTypes')) -or
- $flKeys.ContainsKey((Get-QueryKey 'ВидыСубконто')))
- foreach ($child in $childObjs.ChildNodes) {
- if ($child.NodeType -ne 'Element') { continue }
- # Реквизит объекта, измерение и ресурс регистра — один и тот же вид дочернего объекта с
- # точки зрения заимствования, различается только имя элемента. Конфигуратор переносит их
- # своим видом (эталон Issue66Example2: у регистра <Dimension> x3 и <Resource>), поэтому вид
- # запоминается и выпускается как есть — иначе измерение уехало бы в файл как <Attribute>.
- if ($script:childObjectKinds -ccontains $child.LocalName) {
- $nameNode = $child.SelectSingleNode("md:Properties/md:Name", $srcNs)
- if (-not $nameNode) { continue }
- $attrName = $nameNode.InnerText
- # Признак учёта субконто — колонка стандартной ТЧ видов субконто (Объект.ВидыСубконто.<Признак>):
- # идёт вместе с ней, а не по первому сегменту пути
- if ($child.LocalName -eq 'ExtDimensionAccountingFlag') {
- if (-not $wantExtDim) { continue }
- } elseif ($null -ne $flKeys -and -not $flKeys.ContainsKey((Get-QueryKey $attrName))) { continue }
- $uuid = $child.GetAttribute("uuid")
- $typeNode = $child.SelectSingleNode("md:Properties/md:Type", $srcNs)
- $typeXml = if ($typeNode) { $typeNode.OuterXml } else { "" }
- # Strip namespace declarations from Type
- $typeXml = [regex]::Replace($typeXml, '\s+xmlns(?::\w+)?="[^"]*"', '')
- $attrs += @{ Name = $attrName; Uuid = $uuid; TypeXml = $typeXml; Kind = $child.LocalName }
- }
- elseif ($child.LocalName -eq 'TabularSection') {
- $nameNode = $child.SelectSingleNode("md:Properties/md:Name", $srcNs)
- if (-not $nameNode) { continue }
- $tsName = $nameNode.InnerText
- if ($null -ne $flKeys -and -not $flKeys.ContainsKey((Get-QueryKey $tsName))) { continue }
- $tsUuid = $child.GetAttribute("uuid")
- # Extract GeneratedTypes from InternalInfo
- $tsGenTypes = @()
- $iiNode = $child.SelectSingleNode("md:InternalInfo", $srcNs)
- if ($iiNode) {
- $gtNodes = $iiNode.SelectNodes("xr:GeneratedType", $srcNs)
- foreach ($gt in $gtNodes) {
- $tsGenTypes += @{
- Name = $gt.GetAttribute("name")
- Category = $gt.GetAttribute("category")
- TypeId = $gt.SelectSingleNode("xr:TypeId", $srcNs).InnerText
- ValueId = $gt.SelectSingleNode("xr:ValueId", $srcNs).InnerText
- }
- }
- }
- # Extract ALL child attributes of TabularSection
- $tsAttrs = @()
- $tsChildObjs = $child.SelectSingleNode("md:ChildObjects", $srcNs)
- if ($tsChildObjs) {
- foreach ($tsChild in $tsChildObjs.ChildNodes) {
- if ($tsChild.NodeType -ne 'Element' -or $tsChild.LocalName -ne 'Attribute') { continue }
- $tsAttrName = $tsChild.SelectSingleNode("md:Properties/md:Name", $srcNs)
- if (-not $tsAttrName) { continue }
- $tsAttrUuid = $tsChild.GetAttribute("uuid")
- $tsTypeNode = $tsChild.SelectSingleNode("md:Properties/md:Type", $srcNs)
- $tsTypeXml = if ($tsTypeNode) { $tsTypeNode.OuterXml } else { "" }
- $tsTypeXml = [regex]::Replace($tsTypeXml, '\s+xmlns(?::\w+)?="[^"]*"', '')
- $tsAttrs += @{ Name = $tsAttrName.InnerText; Uuid = $tsAttrUuid; TypeXml = $tsTypeXml }
- }
- }
- $tabSections += @{ Name = $tsName; Uuid = $tsUuid; GeneratedTypes = $tsGenTypes; Attributes = $tsAttrs }
- }
- }
- # Extract extra Properties for main object enrichment (Hierarchical, CodeLength, etc.)
- # Ordered so PS emits the same property order as the Python port (dict preserves insertion order).
- $extraProps = [ordered]@{}
- $propsNode = $srcEl.SelectSingleNode("md:Properties", $srcNs)
- if ($propsNode) {
- # NumberPeriodicity сюда НЕ входит: платформа считает его модификацией настроек нумерации и
- # тогда требует объявить ещё и <Numerator/>, иначе /UpdateDBCfg падает — «отключать
- # контролируемость свойства "Нумератор" недопустимо». Конфигуратор его не переносит
- # (эталон заимствования документа: NumberType/NumberLength/NumberAllowedLength и всё).
- # Загрузку это не ломает, ошибка вылезает только на обновлении конфигурации БД.
- # FoldersOnTop сюда НЕ входит: платформа его у заимствованной оболочки не хранит — при
- # загрузке молча выбрасывает (проверено раундтрипом: записали, выгрузили обратно, свойства
- # нет). Конфигуратор его тоже не переносит. Остальные из списка сохраняются.
- $propsToExtract = @("Hierarchical","CodeLength","DescriptionLength","CodeType","CodeAllowedLength",
- "NumberType","NumberLength","NumberAllowedLength")
- foreach ($pName in $propsToExtract) {
- $pNode = $propsNode.SelectSingleNode("md:${pName}", $srcNs)
- if ($pNode) { $extraProps[$pName] = $pNode.InnerText }
- }
- # Стандартная ТЧ видов субконто плана счетов видна форме расширения, только если в оболочке есть
- # ExtDimensionTypes и MaxExtDimensionCount, а ПВХ видов субконто заимствован (замер 8.3.24, 8.3.27).
- # ПВХ нет в источнике — свойства не переносим: ссылка на незаимствованный объект не загрузится.
- $edtNode = $propsNode.SelectSingleNode("md:ExtDimensionTypes", $srcNs)
- $maxNode = $propsNode.SelectSingleNode("md:MaxExtDimensionCount", $srcNs)
- if ($wantExtDim -and $edtNode -and $maxNode -and $edtNode.InnerText.Trim()) {
- $edm = [regex]::Match($edtNode.InnerText.Trim(), '^(\w+)\.(.+)$')
- $edFound = $edm.Success -and $childTypeDirMap.ContainsKey($edm.Groups[1].Value) -and
- (Test-Path (Join-Path (Join-Path $cfgDir $childTypeDirMap[$edm.Groups[1].Value]) "$($edm.Groups[2].Value).xml"))
- if ($edFound) {
- $extraProps["ExtDimensionTypes"] = $edtNode.InnerText.Trim()
- $extraProps["MaxExtDimensionCount"] = $maxNode.InnerText.Trim()
- } else {
- Warn " ${typeName}.${objName}: виды субконто $($edtNode.InnerText.Trim()) не найдены в конфигурации-источнике — ТЧ видов субконто форме расширения не будет видна"
- }
- }
- }
- return @{ Attributes = $attrs; TabularSections = $tabSections; ExtraProps = $extraProps }
- }
- # --- 11d. Build adopted attribute XML ---
- function Build-AdoptedAttributeXml {
- param([string]$name, [string]$sourceUuid, [string]$typeXml, [string]$indent, [string]$kind = "Attribute")
- $newUuid = [guid]::NewGuid().ToString()
- $sb = New-Object System.Text.StringBuilder
- $sb.AppendLine("${indent}<${kind} uuid=`"${newUuid}`">") | Out-Null
- $sb.AppendLine("${indent}`t<InternalInfo/>") | Out-Null
- $sb.AppendLine("${indent}`t<Properties>") | Out-Null
- $sb.AppendLine("${indent}`t`t<ObjectBelonging>Adopted</ObjectBelonging>") | Out-Null
- $sb.AppendLine("${indent}`t`t<Name>${name}</Name>") | Out-Null
- $sb.AppendLine("${indent}`t`t<Comment/>") | Out-Null
- $sb.AppendLine("${indent}`t`t<ExtendedConfigurationObject>${sourceUuid}</ExtendedConfigurationObject>") | Out-Null
- $sb.AppendLine("${indent}`t`t${typeXml}") | Out-Null
- $sb.AppendLine("${indent}`t</Properties>") | Out-Null
- $sb.Append("${indent}</${kind}>") | Out-Null
- return $sb.ToString()
- }
- # --- 11e. Build adopted tabular section XML ---
- function Build-AdoptedTabularSectionXml {
- param([string]$tsName, [string]$sourceUuid, $generatedTypes, $childAttrs, [string]$indent)
- $newUuid = [guid]::NewGuid().ToString()
- $sb = New-Object System.Text.StringBuilder
- $sb.AppendLine("${indent}<TabularSection uuid=`"${newUuid}`">") | Out-Null
- # InternalInfo with GeneratedTypes (new UUIDs, referencing source names)
- if ($generatedTypes -and $generatedTypes.Count -gt 0) {
- $sb.AppendLine("${indent}`t<InternalInfo>") | Out-Null
- foreach ($gt in $generatedTypes) {
- $newTid = [guid]::NewGuid().ToString()
- $newVid = [guid]::NewGuid().ToString()
- $sb.AppendLine("${indent}`t`t<xr:GeneratedType name=`"$($gt.Name)`" category=`"$($gt.Category)`">") | Out-Null
- $sb.AppendLine("${indent}`t`t`t<xr:TypeId>${newTid}</xr:TypeId>") | Out-Null
- $sb.AppendLine("${indent}`t`t`t<xr:ValueId>${newVid}</xr:ValueId>") | Out-Null
- $sb.AppendLine("${indent}`t`t</xr:GeneratedType>") | Out-Null
- }
- $sb.AppendLine("${indent}`t</InternalInfo>") | Out-Null
- } else {
- $sb.AppendLine("${indent}`t<InternalInfo/>") | Out-Null
- }
- $sb.AppendLine("${indent}`t<Properties>") | Out-Null
- $sb.AppendLine("${indent}`t`t<ObjectBelonging>Adopted</ObjectBelonging>") | Out-Null
- $sb.AppendLine("${indent}`t`t<Name>${tsName}</Name>") | Out-Null
- $sb.AppendLine("${indent}`t`t<Comment/>") | Out-Null
- $sb.AppendLine("${indent}`t`t<ExtendedConfigurationObject>${sourceUuid}</ExtendedConfigurationObject>") | Out-Null
- $sb.AppendLine("${indent}`t</Properties>") | Out-Null
- # ChildObjects with all attributes
- if ($childAttrs -and $childAttrs.Count -gt 0) {
- $sb.AppendLine("${indent}`t<ChildObjects>") | Out-Null
- foreach ($ca in $childAttrs) {
- $caXml = Build-AdoptedAttributeXml $ca.Name $ca.Uuid $ca.TypeXml "${indent}`t`t"
- $sb.AppendLine($caXml) | Out-Null
- }
- $sb.AppendLine("${indent}`t</ChildObjects>") | Out-Null
- } else {
- $sb.AppendLine("${indent}`t<ChildObjects/>") | Out-Null
- }
- $sb.Append("${indent}</TabularSection>") | Out-Null
- return $sb.ToString()
- }
- # --- 11f. Collect reference types from attribute Type XML strings ---
- function Collect-ReferenceTypes {
- param([string[]]$typeXmls)
- # Порядок первого упоминания: от него зависит порядок заимствования в ChildObjects
- $result = [ordered]@{}
- foreach ($typeXml in $typeXmls) {
- # cfg:CatalogRef.XXX, cfg:EnumRef.XXX, cfg:DocumentRef.XXX, etc.
- $refMatches = [regex]::Matches($typeXml, 'cfg:(\w+)Ref\.(\w+)')
- foreach ($m in $refMatches) {
- $refPrefix = $m.Groups[1].Value # e.g. "Catalog", "Enum", "Document"
- $objName = $m.Groups[2].Value
- $key = "${refPrefix}.${objName}"
- if (-not $result.Contains($key)) {
- $result[$key] = @{ TypeName = $refPrefix; ObjName = $objName }
- }
- }
- # cfg:DefinedType.XXX (via v8:TypeSet or v8:Type)
- $dtMatches = [regex]::Matches($typeXml, 'cfg:DefinedType\.(\w+)')
- foreach ($m in $dtMatches) {
- $dtName = $m.Groups[1].Value
- $key = "DefinedType.${dtName}"
- if (-not $result.Contains($key)) {
- $result[$key] = @{ TypeName = "DefinedType"; ObjName = $dtName }
- }
- }
- }
- return @($result.Values)
- }
- # --- 11g. Merge adopted attributes into existing extension object XML ---
- function Merge-AttributesIntoObject {
- param([string]$typeName, [string]$objName, $attrsToAdd)
- $dirName = $childTypeDirMap[$typeName]
- $objFile = Join-Path (Join-Path $extDir $dirName) "${objName}.xml"
- if (-not (Test-Path $objFile)) {
- Warn "Cannot merge attributes: $objFile not found"
- return
- }
- $objDoc = New-Object System.Xml.XmlDocument
- $objDoc.PreserveWhitespace = $true
- $objDoc.Load($objFile)
- $objNs = New-Object System.Xml.XmlNamespaceManager($objDoc.NameTable)
- $objNs.AddNamespace("md", $script:mdNs)
- $objEl = $null
- foreach ($c in $objDoc.DocumentElement.ChildNodes) {
- if ($c.NodeType -eq 'Element') { $objEl = $c; break }
- }
- if (-not $objEl) { Warn "No type element in $objFile"; return }
- # Нет своего <ChildObjects> — его создаст Insert-OwnChildOrDie
- $childObjs = $objEl.SelectSingleNode("md:ChildObjects", $objNs)
- # Имена всех прямых детей своего ChildObjects — дедуп для любого вида (реквизит, измерение, признак)
- $existingNames = @{}
- if ($childObjs) {
- foreach ($c in $childObjs.ChildNodes) {
- if ($c.NodeType -ne 'Element') { continue }
- $nameNode = $c.SelectSingleNode("md:Properties/md:Name", $objNs)
- if ($nameNode) { $existingNames[$nameNode.InnerText.Trim()] = $true }
- }
- }
- $added = 0
- foreach ($attr in $attrsToAdd) {
- if ($existingNames.ContainsKey($attr.Name)) { continue }
- $added++
- }
- if ($added -gt 0) {
- # Build all adopted attributes as text and do string-level insertion
- $attrParts = New-Object System.Collections.Generic.List[object]
- foreach ($attr in $attrsToAdd) {
- if ($existingNames.ContainsKey($attr.Name)) { continue }
- $kind = if ($attr.Kind) { $attr.Kind } else { "Attribute" }
- $attrParts.Add(@{ Tag = $kind; Xml = (Build-AdoptedAttributeXml $attr.Name $attr.Uuid $attr.TypeXml "`t`t`t" $kind) })
- }
- # Save via text manipulation to avoid namespace issues with InnerXml
- # Стиль исходника снимаем ДО записи: правка чужого файла наследует его BOM/EOL/заголовок
- # (#44/#46/#47), новый файл получает канон выгрузки. Зеркало _detect_xml_style в py-порту.
- $style3 = Detect-XmlStyle $objFile
- $settings3 = New-Object System.Xml.XmlWriterSettings
- $settings3.Encoding = New-Object System.Text.UTF8Encoding($true)
- $settings3.Indent = $false
- $settings3.NewLineHandling = [System.Xml.NewLineHandling]::None
- $memStream3 = New-Object System.IO.MemoryStream
- $writer3 = [System.Xml.XmlWriter]::Create($memStream3, $settings3)
- $objDoc.Save($writer3)
- $writer3.Flush(); $writer3.Close()
- $text3 = [System.Text.Encoding]::UTF8.GetString($memStream3.ToArray())
- $memStream3.Close()
- # Самозакрытый элемент раскрывается текстом, а не пробельным узлом в DOM: тот давал
- # лишнюю строку с табуляцией перед первым <Attribute> (у Конфигуратора пустых строк нет).
- # Стоит ДО Finalize-XmlText, чтобы схлопывание пустых тегов накрыло и вставленные реквизиты.
- foreach ($part in $attrParts) {
- $text3 = Insert-OwnChildOrDie $text3 $part.Xml $part.Tag $typeName $objFile
- }
- $text3 = Finalize-XmlText $text3 $style3
- $writeBom3 = ($null -eq $style3) -or $style3.bom
- [System.IO.File]::WriteAllText($objFile, $text3, (New-Object System.Text.UTF8Encoding($writeBom3)))
- Info " Merged $added attribute(s) into: $objFile"
- }
- }
- # Блок <TabularSection> с именем $tsName среди прямых детей СОБСТВЕННОГО <ChildObjects> объекта:
- # @{ Start; End } в тексте, $null — нет. Прямые дети — по глубине, как в Insert-IntoOwnChildObjectsByCanon;
- # имя ТЧ — первый <Name> блока (в InternalInfo имён нет), без учёта регистра, как имена 1С. Реквизит с тем же
- # именем — не ТЧ.
- function Find-OwnTabularSectionSpan([string]$text, [string]$tsName) {
- $mOpen = [regex]::Match($text, '<ChildObjects\b[^>]*?(/?)>')
- if (-not $mOpen.Success -or $mOpen.Groups[1].Value) { return $null }
- $closes = [regex]::Matches($text, '</ChildObjects\s*>')
- if ($closes.Count -eq 0) { return $null }
- $bodyStart = $mOpen.Index + $mOpen.Length
- $bodyEnd = $closes[$closes.Count - 1].Index
- if ($bodyEnd -lt $bodyStart) { return $null }
- $depth = 0
- $tsStart = -1
- foreach ($m in [regex]::Matches($text.Substring($bodyStart, $bodyEnd - $bodyStart), '<(/?)([\w:.-]+)[^>]*?(/?)>')) {
- if ($m.Groups[1].Value) {
- $depth--
- if ($depth -eq 0 -and $tsStart -ge 0) {
- $end = $bodyStart + $m.Index + $m.Length
- $nm = [regex]::Match($text.Substring($tsStart, $end - $tsStart), '<Name>([^<]*)</Name>')
- if ($nm.Success -and $nm.Groups[1].Value -eq $tsName) { return @{ Start = $tsStart; End = $end } }
- $tsStart = -1
- }
- continue
- }
- if ($depth -eq 0) { $tsStart = if ($m.Groups[2].Value -ceq 'TabularSection') { $bodyStart + $m.Index } else { -1 } }
- if (-not $m.Groups[3].Value) { $depth++ }
- }
- return $null
- }
- # Колонки источника — в уже заимствованную ТЧ объекта расширения (недостающие по имени; свои колонки
- # и порядок остальных не трогаем). Возвращает число добавленных; ТЧ нет — -1.
- function Merge-ColumnsIntoTabularSection {
- param([string]$typeName, [string]$objName, [string]$tsName, $cols)
- $objFile = Join-Path (Join-Path $extDir $childTypeDirMap[$typeName]) "${objName}.xml"
- $style = Detect-XmlStyle $objFile
- $text = [System.IO.File]::ReadAllText($objFile, (New-Object System.Text.UTF8Encoding($true)))
- $span = Find-OwnTabularSectionSpan $text $tsName
- if (-not $span) { return -1 }
- $block = $text.Substring($span.Start, $span.End - $span.Start)
- # Имена колонок — все <Name> блока, кроме первого (имя самой ТЧ)
- $existing = @{}
- $first = $true
- foreach ($nm in [regex]::Matches($block, '<Name>([^<]*)</Name>')) {
- if ($first) { $first = $false; continue }
- $existing[$nm.Groups[1].Value] = $true
- }
- $ls = if ($span.Start -gt 0) { $text.LastIndexOf("`n", $span.Start - 1) + 1 } else { 0 }
- $colIndent = $text.Substring($ls, $span.Start - $ls) + "`t`t"
- $added = 0
- foreach ($c in $cols) {
- if ($existing.ContainsKey($c.Name)) { continue }
- $newBlock = Insert-IntoOwnChildObjectsByCanon $block (Build-AdoptedAttributeXml $c.Name $c.Uuid $c.TypeXml $colIndent) "Attribute" "TabularSection"
- if ($null -eq $newBlock) { Warn " Tabular section ${tsName} has no <ChildObjects> — attribute $($c.Name) not added"; break }
- $block = $newBlock
- $existing[$c.Name] = $true
- $added++
- }
- if ($added -gt 0) {
- $text = $text.Substring(0, $span.Start) + $block + $text.Substring($span.End)
- [System.IO.File]::WriteAllText($objFile, $text, (Get-StyleEncoding $style))
- Info " Merged $added attribute(s) into tabular section ${tsName}: $objFile"
- }
- return $added
- }
- # --- 11h. Borrow-MainAttribute orchestrator ---
- # Ссылочные типы → объекты-оболочки в расширении (кто уже заимствован — пропускается)
- # Объект-оболочка в расширении: кто уже заимствован — пропускается, без источника — предупреждение.
- function Borrow-ObjectShell([string]$typeName, [string]$objName) {
- if (-not $childTypeDirMap.ContainsKey($typeName)) {
- Warn " Unknown object type: ${typeName}.${objName}"
- return
- }
- if (Test-ObjectBorrowed $typeName $objName) {
- Info " Already borrowed: ${typeName}.${objName}"
- return
- }
- $srcFile = Join-Path (Join-Path $cfgDir $childTypeDirMap[$typeName]) "${objName}.xml"
- if (-not (Test-Path $srcFile)) {
- Warn " Source not found: ${typeName}.${objName}"
- return
- }
- $src = Read-SourceObject $typeName $objName
- $borrowedXml = Build-BorrowedObjectXml $typeName $objName $src.Uuid $src.Properties
- $targetDir = Join-Path $extDir $childTypeDirMap[$typeName]
- if (-not (Test-Path $targetDir)) {
- New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
- }
- $targetFile = Join-Path $targetDir "${objName}.xml"
- [System.IO.File]::WriteAllText($targetFile, $borrowedXml, (New-Object System.Text.UTF8Encoding($true)))
- Add-ToChildObjects $typeName $objName
- $script:borrowedFiles += $targetFile
- Info " Auto-borrowed: ${typeName}.${objName}"
- # Оболочка определяемого типа несёт его состав: объекты из состава — оболочками (эталон
- # Конфигуратора). Без них ниже 8.3.25 загрузка падает: «Неизвестное имя типа».
- if ($typeName -eq "DefinedType" -and $src.Properties.ContainsKey("__TypeXml")) {
- foreach ($rt in (Collect-ReferenceTypes @($src.Properties["__TypeXml"]))) {
- Borrow-ObjectShell $rt.TypeName $rt.ObjName
- }
- }
- }
- # Единственный объект, на который ведёт ссылочный тип: <Вид>Ref.<Имя> или определяемый тип из одной
- # такой ссылки (состав — из источника). Составной, примитивный, неизвестный вид — $null: дальше
- # такого типа путь формы не продолжается. Определяемый тип раскрывается один раз: в его составе
- # определяемых типов не бывает.
- function Resolve-SingleRefTarget([string]$typeXml, [bool]$allowDefined = $true) {
- $types = @([regex]::Matches($typeXml, '<v8:(?:Type|TypeSet)>([^<]+)</v8:(?:Type|TypeSet)>') | ForEach-Object { $_.Groups[1].Value })
- if ($types.Count -ne 1) { return $null }
- $dt = [regex]::Match($types[0], '^(?:\w+:)?DefinedType\.(\w+)$')
- if ($dt.Success -and -not $allowDefined) { return $null }
- if ($dt.Success) {
- $dtFile = Join-Path (Join-Path $cfgDir $childTypeDirMap["DefinedType"]) "$($dt.Groups[1].Value).xml"
- if (-not (Test-Path $dtFile)) { return $null }
- $dtSrc = Read-SourceObject "DefinedType" $dt.Groups[1].Value
- if (-not $dtSrc.Properties.ContainsKey("__TypeXml")) { return $null }
- return Resolve-SingleRefTarget $dtSrc.Properties["__TypeXml"] $false
- }
- $ref = [regex]::Match($types[0], '^(?:\w+:)?(\w+)Ref\.(\w+)$')
- if (-not $ref.Success -or -not $childTypeDirMap.ContainsKey($ref.Groups[1].Value)) { return $null }
- return @{ TypeName = $ref.Groups[1].Value; ObjName = $ref.Groups[2].Value }
- }
- function Borrow-ReferenceTypeShells {
- param([string[]]$typeXmls)
- $refTypes = @(Collect-ReferenceTypes $typeXmls)
- Info " Reference types to borrow: $($refTypes.Count)"
- foreach ($rt in $refTypes) {
- Borrow-ObjectShell $rt.TypeName $rt.ObjName
- }
- }
- # Владелец общей формы — из ТИПА её основного реквизита (эталон УТ CommonMain):
- # <Вид>Object.Имя / <Вид>RecordManager.Имя → объект; DynamicList → объект из <MainTable>;
- # ConstantsSet → константы по путям формы. Примитив, тип без имени (ReportObject — любой отчёт),
- # список без MainTable → владельца нет: в расширение идёт только сам реквизит формы.
- $script:commonFormOwnerKinds = [ordered]@{
- 'CatalogObject'='Catalog'; 'DocumentObject'='Document'; 'DataProcessorObject'='DataProcessor'; 'ReportObject'='Report'
- 'ChartOfCharacteristicTypesObject'='ChartOfCharacteristicTypes'; 'ChartOfAccountsObject'='ChartOfAccounts'
- 'ChartOfCalculationTypesObject'='ChartOfCalculationTypes'; 'ExchangePlanObject'='ExchangePlan'
- 'BusinessProcessObject'='BusinessProcess'; 'TaskObject'='Task'
- 'InformationRegisterRecordManager'='InformationRegister'; 'InformationRegisterRecordSet'='InformationRegister'
- 'AccumulationRegisterRecordSet'='AccumulationRegister'
- }
- function Resolve-CommonFormOwner {
- param($formEl)
- $mainAttr = $formEl.SelectSingleNode("*[local-name()='Attributes']/*[local-name()='Attribute'][*[local-name()='MainAttribute']='true']")
- if (-not $mainAttr) { return $null }
- $typeNode = $mainAttr.SelectSingleNode("*[local-name()='Type']/*[local-name()='Type']")
- $typeText = if ($typeNode) { $typeNode.InnerText.Trim() } else { "" }
- if ($typeText -ceq 'cfg:ConstantsSet') { return @{ Kind = 'Constants'; MainName = $mainAttr.GetAttribute("name") } }
- $m = [regex]::Match($typeText, '^cfg:(\w+)\.(\w+)$')
- if ($m.Success -and $script:commonFormOwnerKinds.Contains($m.Groups[1].Value)) {
- return @{ Kind = 'Object'; TypeName = $script:commonFormOwnerKinds[$m.Groups[1].Value]; ObjName = $m.Groups[2].Value; ByType = $true }
- }
- if ($typeText -ceq 'cfg:DynamicList') {
- $mt = $mainAttr.SelectSingleNode(".//*[local-name()='MainTable']")
- if ($mt) {
- $mtm = [regex]::Match($mt.InnerText.Trim(), '^(\w+)\.(\w+)$')
- if ($mtm.Success -and $childTypeDirMap.ContainsKey($mtm.Groups[1].Value)) {
- return @{ Kind = 'Object'; TypeName = $mtm.Groups[1].Value; ObjName = $mtm.Groups[2].Value }
- }
- }
- }
- return $null
- }
- # Объект, по которому разрешаются пути формы объекта: тип основного реквизита <Вид>Object.Имя и т.п.,
- # а не владелец формы — форма обработки с основным реквизитом DocumentObject.X видит реквизиты X (замер
- # 8.3.24, #120). Список (DynamicList) и прочие типы — владелец формы, как раньше.
- function Resolve-MainAttributeObject {
- param($formEl, [string]$typeName, [string]$objName)
- $o = Resolve-CommonFormOwner $formEl
- if ($o -and $o.Kind -eq 'Object' -and $o.ByType) { return @{ TypeName = $o.TypeName; ObjName = $o.ObjName } }
- return @{ TypeName = $typeName; ObjName = $objName }
- }
- # Набор констант как основной реквизит общей формы: заимствуются константы, пути на которые есть
- # в форме (<Реквизит>.<Константа>), — с типом как в источнике; их ссылочные типы — оболочками
- # (эталон УТ CommonMain: НастройкаПереводаТекста → две константы + перечисление из типа).
- function Borrow-FormConstants {
- param([string]$srcFormXmlPath, [string]$mainName)
- Info "Borrowing constants for main attribute ${mainName} (ConstantsSet)..."
- $names = (Collect-FormDataPaths $srcFormXmlPath $mainName).FirstLevel
- $encBom = New-Object System.Text.UTF8Encoding($true)
- $typeXmls = @()
- foreach ($cName in @($names.Keys)) {
- $cSrcFile = Join-Path (Join-Path $cfgDir "Constants") "${cName}.xml"
- if (-not (Test-Path $cSrcFile)) { continue }
- $cDoc = New-Object System.Xml.XmlDocument
- # С пробелами: вложенные отступы типа в источнике — ровно та же глубина, что в расширении
- $cDoc.PreserveWhitespace = $true
- $cDoc.Load($cSrcFile)
- $cTypeNode = $cDoc.SelectSingleNode("//*[local-name()='Constant']/*[local-name()='Properties']/*[local-name()='Type']")
- $cTypeXml = if ($cTypeNode) { ([regex]::Replace($cTypeNode.OuterXml, '\s+xmlns(?::\w+)?="[^"]*"', '') -replace "`r?`n", "`r`n") } else { "" }
- if ($cTypeXml) { $typeXmls += $cTypeXml }
- # Тип — последним свойством, после ExtendedConfigurationObject (как у Конфигуратора)
- $addType = {
- param([string]$xml)
- ([regex]'(?<ind>[ \t]*)<ExtendedConfigurationObject>[^<]*</ExtendedConfigurationObject>').Replace($xml, {
- param($mm) $mm.Value + "`r`n" + $mm.Groups['ind'].Value + $cTypeXml
- }, 1)
- }
- if (Test-ObjectBorrowed "Constant" $cName) {
- # Заимствованная раньше оболочкой (-Object Constant.X) — без типа: дописываем, как при
- # слиянии реквизитов в уже заимствованный объект
- $extCFile = Join-Path (Join-Path $extDir "Constants") "${cName}.xml"
- $extCText = [System.IO.File]::ReadAllText($extCFile, $encBom)
- if ($cTypeXml -and $extCText -cnotmatch '<Type>') {
- [System.IO.File]::WriteAllText($extCFile, (& $addType $extCText), $encBom)
- Info " Added type: Constant.${cName}"
- } else {
- Info " Already borrowed: Constant.${cName}"
- }
- continue
- }
- $src = Read-SourceObject "Constant" $cName
- $borrowedXml = Build-BorrowedObjectXml "Constant" $cName $src.Uuid $src.Properties
- if ($cTypeXml) { $borrowedXml = & $addType $borrowedXml }
- $targetDir = Join-Path $extDir "Constants"
- if (-not (Test-Path $targetDir)) { New-Item -ItemType Directory -Path $targetDir -Force | Out-Null }
- $targetFile = Join-Path $targetDir "${cName}.xml"
- [System.IO.File]::WriteAllText($targetFile, $borrowedXml, $encBom)
- Add-ToChildObjects "Constant" $cName
- $script:borrowedFiles += $targetFile
- Info " Borrowed: Constant.${cName}"
- }
- Borrow-ReferenceTypeShells $typeXmls
- }
- function Borrow-MainAttribute {
- param([string]$typeName, [string]$objName, [string]$formName, [string]$mode, [string]$srcFormXmlPath = "")
- $dirName = $childTypeDirMap[$typeName]
- Info "Borrowing main attribute for ${typeName}.${objName} (mode: $mode)..."
- # Путь к исходной форме: у общей формы его передают явно (владелец выведен из типа реквизита)
- if (-not $srcFormXmlPath) {
- $srcFormXmlPath = Join-Path (Join-Path (Join-Path (Join-Path (Join-Path $cfgDir $dirName) $objName) "Forms") $formName) "Ext/Form.xml"
- }
- # Step 1: Collect DataPaths (Form mode) or take all (All mode)
- $firstLevelNames = $null
- $deepPaths = @()
- if ($mode -eq "Form") {
- if (-not (Test-Path $srcFormXmlPath)) {
- Write-Error "Source Form.xml not found: $srcFormXmlPath"
- exit 1
- }
- # Имя основного реквизита исходной формы — корень путей, которые надо собрать
- $dpDoc = New-Object System.Xml.XmlDocument
- $dpDoc.PreserveWhitespace = $true
- $dpDoc.Load($srcFormXmlPath)
- $dpInfo = Get-MainAttributeInfo $dpDoc.DocumentElement '\s+xmlns(?::\w+)?="[^"]*"'
- if (-not $dpInfo) {
- Warn " У формы нет основного реквизита — заимствовать нечего"
- return
- }
- $dp = Collect-FormDataPaths $srcFormXmlPath $dpInfo.Name
- $firstLevelNames = $dp.FirstLevel
- $deepPaths = $dp.DeepPaths
- Info " Collected $($firstLevelNames.Count) first-level DataPath references, $($deepPaths.Count) deep paths"
- } else {
- Info " Mode All: borrowing all attributes and tabular sections"
- # Первый уровень — все реквизиты, но глубокие пути формы те же: объекты по ссылкам из них
- # нужны с показанными реквизитами в любом режиме
- if (Test-Path $srcFormXmlPath) {
- $dpDoc = New-Object System.Xml.XmlDocument
- $dpDoc.PreserveWhitespace = $true
- $dpDoc.Load($srcFormXmlPath)
- $dpInfo = Get-MainAttributeInfo $dpDoc.DocumentElement '\s+xmlns(?::\w+)?="[^"]*"'
- if ($dpInfo) { $deepPaths = (Collect-FormDataPaths $srcFormXmlPath $dpInfo.Name).DeepPaths }
- }
- }
- # Step 2: Resolve source attributes
- $resolved = Resolve-SourceAttributes $typeName $objName $firstLevelNames
- $srcAttrs = $resolved.Attributes
- $srcTS = $resolved.TabularSections
- $extraProps = $resolved.ExtraProps
- Info " Resolved: $($srcAttrs.Count) attributes, $($srcTS.Count) tabular section(s)"
- # Identify which FirstLevel names are TabularSections (for deep path filtering)
- $tsNames = @{}
- foreach ($ts in $srcTS) { $tsNames[$ts.Name] = $true }
- # Step 3: Build the adopted content and insert into main object XML
- $objFile = Join-Path (Join-Path $extDir $dirName) "${objName}.xml"
- # Read existing object XML (needed for dedup + enrichment)
- $objStyle = Detect-XmlStyle $objFile
- $objContent = [System.IO.File]::ReadAllText($objFile, (New-Object System.Text.UTF8Encoding($true)))
- # Dedup: skip attributes/TS already present in object's ChildObjects (idempotent re-borrow)
- $existingChildNames = Get-OwnChildObjectNames $objFile
- $insertAttrs = @($srcAttrs | Where-Object { -not $existingChildNames.ContainsKey($_.Name) })
- $insertTS = @($srcTS | Where-Object { -not $existingChildNames.ContainsKey($_.Name) })
- # Узлы заимствуемого содержимого: тег + XML. Место каждому — по канону вида при вставке
- $contentParts = New-Object System.Collections.Generic.List[object]
- foreach ($attr in $insertAttrs) {
- $attrKind = if ($attr.Kind) { $attr.Kind } else { "Attribute" }
- $contentParts.Add(@{ Tag = $attrKind; Xml = (Build-AdoptedAttributeXml $attr.Name $attr.Uuid $attr.TypeXml "`t`t`t" $attrKind) })
- }
- foreach ($ts in $insertTS) {
- $contentParts.Add(@{ Tag = "TabularSection"; Xml = (Build-AdoptedTabularSectionXml $ts.Name $ts.Uuid $ts.GeneratedTypes $ts.Attributes "`t`t`t") })
- }
- # Inject extra properties into the object's OWN Properties only — idempotent and anchored to the
- # first ExtendedConfigurationObject (the object's). On re-borrow, adopted attributes each have their
- # own ExtendedConfigurationObject; a global replace would push object props inside every <Attribute>.
- if ($extraProps.Count -gt 0) {
- $objPropsBlock = ""
- if ($objContent -match '(?s)<Properties>(.*?)</Properties>') { $objPropsBlock = $Matches[1] }
- $propsSb = New-Object System.Text.StringBuilder
- foreach ($pName in $extraProps.Keys) {
- if ($objPropsBlock -match "<$pName>") { continue }
- $propsSb.Append("`r`n`t`t`t<${pName}>$($extraProps[$pName])</${pName}>") | Out-Null
- }
- if ($propsSb.Length -gt 0) {
- $objContent = ([regex]'</ExtendedConfigurationObject>').Replace($objContent, "</ExtendedConfigurationObject>$($propsSb.ToString())", 1)
- }
- }
- # Добавить заимствованное содержимое в ChildObjects объекта (там уже может лежать <Form>)
- foreach ($part in $contentParts) {
- $objContent = Insert-OwnChildOrDie $objContent $part.Xml $part.Tag $typeName $objFile
- }
- [System.IO.File]::WriteAllText($objFile, $objContent, (Get-StyleEncoding $objStyle))
- Info " Enriched object: $objFile"
- # ТЧ уже в расширении (заимствована без формы, своими колонками) — колонки, которые нужны форме,
- # доливаются в неё: пропуск по имени оставил бы форму с «Неверный путь к данным Объект.<ТЧ>.<Колонка>»
- foreach ($ts in $srcTS) {
- if (-not $existingChildNames.ContainsKey($ts.Name)) { continue }
- if ((Merge-ColumnsIntoTabularSection $typeName $objName $ts.Name $ts.Attributes) -lt 0) {
- Warn " $($ts.Name): name is taken in ${typeName}.${objName}, but not by a tabular section — its attributes not borrowed"
- }
- }
- # Step 4: Collect all reference types and borrow as shells
- $allTypeXmls = @()
- foreach ($a in $srcAttrs) { $allTypeXmls += $a.TypeXml }
- foreach ($ts in $srcTS) {
- foreach ($tsa in $ts.Attributes) { $allTypeXmls += $tsa.TypeXml }
- }
- # Типы из <Columns> основного реквизита формы: колонку мы переносим (Borrow-Form), значит и её
- # тип должен быть заимствован — иначе колонка ссылается на DefinedType/справочник, которого в
- # расширении нет. Конфигуратор поступает так же (эталон: DefinedTypes/Артикул при заимствовании
- # формы заказа поставщику).
- $srcFormForCols = $srcFormXmlPath
- if (Test-Path $srcFormForCols) {
- $colsDoc = New-Object System.Xml.XmlDocument
- $colsDoc.PreserveWhitespace = $true
- $colsDoc.Load($srcFormForCols)
- $colsInfo = Get-MainAttributeInfo $colsDoc.DocumentElement '\s+xmlns(?::\w+)?="[^"]*"'
- if ($colsInfo) {
- foreach ($m in [regex]::Matches($colsInfo.Xml, '(?s)<Columns>.*?</Columns>')) { $allTypeXmls += $m.Value }
- }
- }
- Borrow-ReferenceTypeShells $allTypeXmls
- # ПВХ видов субконто, на который ссылается перенесённое свойство ExtDimensionTypes, — оболочкой:
- # иначе «Неизвестный объект метаданных» при загрузке
- if ($extraProps.Contains('ExtDimensionTypes')) {
- $edm = [regex]::Match($extraProps['ExtDimensionTypes'], '^(\w+)\.(.+)$')
- if ($edm.Success) { Borrow-ObjectShell $edm.Groups[1].Value $edm.Groups[2].Value }
- }
- # Step 5: Deep paths — Объект.<Реквизит>.<…> and Объект.<ТЧ>.<Колонка>.<…>. Each reference step borrows
- # its target object with the next segment's attribute (Designer etalon), down the whole chain
- if ($deepPaths.Count -gt 0) {
- Info " Processing $($deepPaths.Count) deep path(s)..."
- foreach ($segs in $deepPaths) {
- if ($tsNames.ContainsKey($segs[0])) {
- $tsInfo = $srcTS | Where-Object { $_.Name -eq $segs[0] } | Select-Object -First 1
- $startAttr = $tsInfo.Attributes | Where-Object { $_.Name -eq $segs[1] } | Select-Object -First 1
- $next = 2
- } else {
- $startAttr = $srcAttrs | Where-Object { $_.Name -eq $segs[0] } | Select-Object -First 1
- $next = 1
- }
- if (-not $startAttr) { continue }
- $typeXml = $startAttr.TypeXml
- for ($i = $next; $i -lt $segs.Count; $i++) {
- if ($script:standardFields -contains $segs[$i]) { break }
- $target = Resolve-SingleRefTarget $typeXml
- if (-not $target) { break }
- $merged = @(Borrow-DeepTargetAttrs $target.TypeName $target.ObjName @($segs[$i]))
- if ($merged.Count -eq 0) { break }
- $typeXml = $merged[0].TypeXml
- }
- }
- }
- Info " Main attribute borrowing complete"
- }
- # --- 11i. Helper: borrow a deep-path target object together with the referenced sub-attributes ---
- # Mirrors Designer: the referenced object is adopted WITH the sub-attributes the form shows, otherwise
- # the platform rejects the deep DataPath ("Неверный путь к данным"). Returns the merged source attributes
- # (Name/TypeXml) — the chain walk continues along their types.
- function Borrow-DeepTargetAttrs {
- param([string]$targetTypeName, [string]$targetObjName, $subAttrNames)
- Borrow-ObjectShell $targetTypeName $targetObjName
- if (-not (Test-ObjectBorrowed $targetTypeName $targetObjName)) { return @() }
- $subNames = @{}
- foreach ($sn in $subAttrNames) { $subNames[$sn] = $true }
- $subResolved = Resolve-SourceAttributes $targetTypeName $targetObjName $subNames
- if ($subResolved.Attributes.Count -eq 0) { return @() }
- Merge-AttributesIntoObject $targetTypeName $targetObjName $subResolved.Attributes
- # Ссылочные типы смёрженных реквизитов — оболочками
- Borrow-ReferenceTypeShells @($subResolved.Attributes | ForEach-Object { $_.TypeXml })
- return $subResolved.Attributes
- }
- # --- 12. Helper: build borrowed object XML ---
- function Build-BorrowedObjectXml {
- param(
- [string]$typeName,
- [string]$objName,
- [string]$sourceUuid,
- [hashtable]$sourceProps
- )
- $newUuid = [guid]::NewGuid().ToString()
- $internalInfoXml = Build-InternalInfoXml $typeName $objName "`t`t"
- $sb = New-Object System.Text.StringBuilder
- $sb.AppendLine("<?xml version=`"1.0`" encoding=`"UTF-8`"?>") | Out-Null
- $sb.AppendLine("<MetaDataObject $($script:xmlnsDecl) version=`"$($script:formatVersion)`">") | Out-Null
- $sb.AppendLine("`t<${typeName} uuid=`"${newUuid}`">") | Out-Null
- # InternalInfo
- $sb.AppendLine($internalInfoXml) | Out-Null
- # Properties
- $sb.AppendLine("`t`t<Properties>") | Out-Null
- $sb.AppendLine("`t`t`t<ObjectBelonging>Adopted</ObjectBelonging>") | Out-Null
- $sb.AppendLine("`t`t`t<Name>${objName}</Name>") | Out-Null
- $sb.AppendLine("`t`t`t<Comment/>") | Out-Null
- $sb.AppendLine("`t`t`t<ExtendedConfigurationObject>${sourceUuid}</ExtendedConfigurationObject>") | Out-Null
- # CommonModule: extra properties from source
- if ($typeName -eq "CommonModule") {
- foreach ($propName in $commonModuleProps) {
- $propVal = "false"
- if ($sourceProps.ContainsKey($propName)) {
- $propVal = $sourceProps[$propName]
- }
- $sb.AppendLine("`t`t`t<${propName}>${propVal}</${propName}>") | Out-Null
- }
- }
- # DefinedType: emit the carried <Type> definition (needed for the alias to resolve, e.g. totals)
- if ($typeName -eq "DefinedType" -and $sourceProps.ContainsKey("__TypeXml")) {
- $sb.AppendLine("`t`t`t$($sourceProps['__TypeXml'])") | Out-Null
- }
- # Свойства, от которых зависят стандартные поля (см. $script:typeGateProps / $script:typesWithOwners)
- foreach ($gp in @($script:typeGateProps[$typeName])) {
- if ($gp -and $sourceProps.ContainsKey($gp)) {
- $sb.AppendLine("`t`t`t<${gp}>$($sourceProps[$gp])</${gp}>") | Out-Null
- }
- }
- if ($sourceProps.ContainsKey("__OwnersXml")) {
- $sb.AppendLine("`t`t`t$($sourceProps['__OwnersXml'])") | Out-Null
- }
- $sb.AppendLine("`t`t</Properties>") | Out-Null
- # ChildObjects (for types that need it)
- if ($sourceProps["__HasChildObjects"] -or ($typesWithChildObjects -contains $typeName)) {
- $sb.AppendLine("`t`t<ChildObjects/>") | Out-Null
- }
- $sb.AppendLine("`t</${typeName}>") | Out-Null
- $sb.Append("</MetaDataObject>") | Out-Null
- return $sb.ToString()
- }
- # --- 13. Helper: add object to extension ChildObjects ---
- # Стиль существующего файла для round-trip-сохранения: BOM / EOL / регистр encoding /
- # финальный перенос. $null → файл новый (сохранить текущее поведение).
- # Реестр семьи: tests/skills/check-inline-drift.mjs.
- # Кодировка записи с BOM, как был у файла ($style — Detect-XmlStyle до записи; файла не было — с BOM)
- function Get-StyleEncoding($style) {
- return (New-Object System.Text.UTF8Encoding(($null -eq $style) -or $style.bom))
- }
- function Detect-XmlStyle([string]$path) {
- if (-not (Test-Path -LiteralPath $path)) { return $null }
- $raw = [System.IO.File]::ReadAllBytes($path)
- $bom = ($raw.Length -ge 3 -and $raw[0] -eq 0xEF -and $raw[1] -eq 0xBB -and $raw[2] -eq 0xBF)
- $body = if ($bom) { [System.Text.Encoding]::UTF8.GetString($raw, 3, $raw.Length - 3) } else { [System.Text.Encoding]::UTF8.GetString($raw) }
- $head = if ($body.Length -gt 200) { $body.Substring(0, 200) } else { $body }
- $m = [regex]::Match($head, 'encoding="([^"]+)"')
- return @{
- bom = $bom
- crlf = $body.Contains("`r`n")
- enc = $(if ($m.Success) { $m.Groups[1].Value } else { "utf-8" })
- finalNl = $body.EndsWith("`n")
- }
- }
- # Привести текст XmlWriter к стилю оригинала; для НОВОГО файла ($null) — к канону выгрузки
- # Конфигуратора: encoding="UTF-8", CRLF, без перевода строки в конце.
- # Реестр семьи: tests/skills/check-inline-drift.mjs.
- function Finalize-XmlText([string]$text, $style) {
- if ($text.Length -gt 0 -and $text[0] -eq [char]0xFEFF) { $text = $text.Substring(1) }
- $encDecl = $(if ($style) { $style.enc } else { "UTF-8" })
- $text = $text.Replace('encoding="utf-8"', 'encoding="' + $encDecl + '"')
- # Пустой элемент: XmlWriter отдаёт `<a />`, Конфигуратор пишет `<a/>`. Внутри
- # CDATA/комментария ` />` может быть содержимым (там `>` не экранируется),
- # поэтому они идут первыми ветками альтернации и возвращаются как есть.
- $text = [regex]::Replace($text, '(?s)<!\[CDATA\[.*?\]\]>|<!--.*?-->|(?<=\S) />', { param($m) if ($m.Value -eq ' />') { '/>' } else { $m.Value } })
- $text = ($text -replace "`r`n", "`n").TrimEnd("`n")
- if ($style -and $style.finalNl) { $text += "`n" }
- if (-not $style -or $style.crlf) { $text = $text -replace "`n", "`r`n" }
- return $text
- }
- function Find-V8Project([string]$startDir) {
- $d = $startDir
- for ($i = 0; $i -lt 20 -and $d; $i++) {
- $pj = Join-Path $d ".v8-project.json"
- if (Test-Path $pj) { return $pj }
- $parent = [System.IO.Path]::GetDirectoryName($d)
- if ($parent -eq $d) { break }
- $d = $parent
- }
- return $null
- }
- # Куда навык ставит новую запись в <ChildObjects> — настройка newObjectPosition.
- # databases[].newObjectPosition базы, чей configSrc охватывает каталог родительского XML,
- # иначе корневое поле, иначе end. Значения: end — после последнего объекта того же вида
- # (так дописывает Конфигуратор); byName — по имени среди объектов того же вида.
- # Файл ищем от рабочего каталога вверх, каталог конфигурации — запасной путь: так же
- # его ищут support-guard и группа db-*, а скрипт навыка зовут по абсолютному пути, и cwd
- # остаётся рабочим каталогом проекта.
- # configSrc считается от каталога .v8-project.json, как задокументировано в
- # docs/v8-project-guide.md. Реестр семьи: tests/skills/check-inline-drift.mjs.
- function Get-NewObjectPosition([string]$cfgDir) {
- try {
- if (-not $cfgDir) { $cfgDir = "." }
- $pj = Find-V8Project (Get-Location).ProviderPath
- if (-not $pj) { $pj = Find-V8Project ([System.IO.Path]::GetFullPath($cfgDir)) }
- if (-not $pj) { return "end" }
- # UTF-8 явно: PS 5.1 читает файл без BOM как ANSI, и configSrc с кириллицей не совпал бы
- $proj = Get-Content -Raw -Encoding UTF8 $pj | ConvertFrom-Json
- $projDir = [System.IO.Path]::GetDirectoryName($pj)
- $cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
- if ($proj.databases) {
- foreach ($db in $proj.databases) {
- if ($db.configSrc -and $db.newObjectPosition) {
- $src = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($projDir, $db.configSrc)).TrimEnd('\', '/')
- if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
- if ("$($db.newObjectPosition)" -eq "byName") { return "byName" }
- return "end"
- }
- }
- }
- }
- if ("$($proj.newObjectPosition)" -eq "byName") { return "byName" }
- return "end"
- } catch { return "end" }
- }
- # Виды, у которых порядок в дереве несёт смысл: автоматически их не упорядочиваем.
- # CommonAttribute — исключение самого стандарта (#std467): у общих реквизитов-разделителей
- # порядок в дереве задаёт порядок установки параметров сеанса. Subsystem и CommandGroup:
- # пока они не перечислены в <SubsystemsOrder> / <GroupsOrder> файла Ext/CommandInterface.xml,
- # порядок дерева задаёт порядок в интерфейсе, а платформа эти списки сама не заводит
- # (в выгрузке ACC вне GroupsOrder 15 живых групп из 39). Language исключён из осторожности,
- # без замера: языков обычно один-два, и в типовых их порядок не алфавитный.
- # Явно названный вид сортируется в любом случае.
- # Реестр семьи: tests/skills/check-inline-drift.mjs.
- function Test-OrderSensitiveType([string]$typeName) {
- return @("CommonAttribute", "Subsystem", "CommandGroup", "Language") -ccontains $typeName
- }
- # Порядок имён объектов метаданных, как в дереве Конфигуратора.
- # Ключ — пары «ранг+символ»: регистр не учитывается, подчёркивание раньше цифр, цифры раньше
- # букв, буквы по кодам (латиница раньше кириллицы), ё на месте е. Культурные таблицы не
- # используются — они разные на разных ОС и в разных рантаймах, а так оба порта сравнивают
- # одинаково везде. Равные ключи разводит ordinal-сравнение исходных строк.
- # Возвращает -1 | 0 | 1. Реестр семьи: tests/skills/check-inline-drift.mjs.
- function Compare-MetadataNames([string]$a, [string]$b) {
- $keys = @("", "")
- $names = @($a, $b)
- for ($i = 0; $i -lt 2; $i++) {
- $sb = New-Object System.Text.StringBuilder
- foreach ($ch in $names[$i].ToLowerInvariant().ToCharArray()) {
- if ($ch -eq [char]0x0451) { $ch = [char]0x0435 }
- if ([char]::IsDigit($ch)) { [void]$sb.Append('1') }
- elseif ([char]::IsLetter($ch)) { [void]$sb.Append('2') }
- else { [void]$sb.Append('0') }
- [void]$sb.Append($ch)
- }
- $keys[$i] = $sb.ToString()
- }
- $r = [string]::CompareOrdinal($keys[0], $keys[1])
- if ($r -eq 0) { $r = [string]::CompareOrdinal($a, $b) }
- if ($r -lt 0) { return -1 }
- if ($r -gt 0) { return 1 }
- return 0
- }
- function Add-ToChildObjects {
- param([string]$typeName, [string]$objName)
- $cfgIndent = Get-ChildIndent $script:cfgEl
- # Expand self-closing ChildObjects if needed
- if (-not $script:childObjsEl.HasChildNodes -or $script:childObjsEl.IsEmpty) {
- Expand-SelfClosingElement $script:childObjsEl $cfgIndent
- }
- $childIndent = Get-ChildIndent $script:childObjsEl
- $typeIdx = $script:typeOrder.IndexOf($typeName)
- if ($typeIdx -lt 0) {
- Write-Error "Unknown type '$typeName' for ChildObjects ordering"
- exit 1
- }
- # Dedup check
- foreach ($child in $script:childObjsEl.ChildNodes) {
- if ($child.NodeType -eq 'Element' -and $child.LocalName -eq $typeName -and $child.InnerText -eq $objName) {
- Warn "Already in ChildObjects: ${typeName}.${objName}"
- return
- }
- }
- # Место вставки. Вид — по $script:typeOrder; внутри вида — по newObjectPosition: end
- # (по умолчанию) кладёт после последнего объекта того же вида, byName — по имени. Так же
- # заимствует Конфигуратор: в боевых выгрузках расширений ChildObjects не отсортирован.
- # Subsystem по имени не упорядочиваем никогда: порядок подсистем в дереве задаёт порядок
- # разделов в панели.
- $byName = (-not (Test-OrderSensitiveType $typeName) -and (Get-NewObjectPosition $extDir) -eq "byName")
- $insertBefore = $null
- $lastSameType = $null
- foreach ($child in $script:childObjsEl.ChildNodes) {
- if ($child.NodeType -ne 'Element') { continue }
- $childTypeIdx = $script:typeOrder.IndexOf($child.LocalName)
- if ($childTypeIdx -lt 0) { continue }
- if ($child.LocalName -eq $typeName) {
- if ($byName -and -not $insertBefore -and (Compare-MetadataNames $child.InnerText $objName) -gt 0) {
- $insertBefore = $child
- }
- $lastSameType = $child
- } elseif ($childTypeIdx -gt $typeIdx -and -not $insertBefore) {
- # First element of a later type -- insert before it
- $insertBefore = $child
- }
- }
- # Create element
- $newEl = $script:xmlDoc.CreateElement($typeName, $script:mdNs)
- $newEl.InnerText = $objName
- if ($insertBefore) {
- Insert-BeforeElement $script:childObjsEl $newEl $insertBefore $childIndent
- } else {
- Insert-BeforeElement $script:childObjsEl $newEl $null $childIndent
- }
- Info "Added to ChildObjects: ${typeName}.${objName}"
- }
- # --- 14. Process each item ---
- $script:borrowedFiles = @()
- # Формы с динамическим списком — основная таблица и тильда решаются в конце запуска (шаги 14a, 14c)
- $script:dynListForms = @()
- $borrowedCount = 0
- # Элемент -Object: тип (синоним → английское имя), объект, форма и путь к её Form.xml в источнике.
- # Error — текст отказа для неверного элемента.
- function Split-BorrowItem([string]$item) {
- $fmtHint = "expected 'Type.Name', 'Type.Name.Form.FormName', 'Type.Name.<Kind>.<SubName>' or 'Type.Name.TabularSection.<TS>.Attribute.<Attribute>'"
- $dotIdx = $item.IndexOf(".")
- if ($dotIdx -lt 1) { return @{ Error = "Invalid format '${item}', $fmtHint" } }
- $typeName = $item.Substring(0, $dotIdx)
- $remainder = $item.Substring($dotIdx + 1)
- # Resolve Russian synonym to English type name
- if ($synonymMap.ContainsKey($typeName)) { $typeName = $synonymMap[$typeName] }
- if (-not $childTypeDirMap.ContainsKey($typeName)) { return @{ Error = "Unknown type '${typeName}'" } }
- # Имена метаданных без точек — разбор по сегментам: Имя | Имя.Form.Ф | Имя.<Вид>.<П> | Имя.TabularSection.<ТЧ>.Attribute.<К>
- $segs = $remainder.Split('.')
- if ($segs -contains '') { return @{ Error = "Invalid format '${item}', $fmtHint" } }
- $objName = $segs[0]
- $formName = $null; $subKind = $null; $subName = $null; $colName = $null
- if ($segs.Count -eq 1) {
- } elseif ($segs.Count -eq 3 -and $segs[1] -ceq 'Form') {
- $formName = $segs[2]
- } elseif ($segs.Count -eq 3 -and $script:subObjectKinds -ccontains $segs[1]) {
- $subKind = $segs[1]; $subName = $segs[2]
- } elseif ($segs.Count -eq 5 -and $segs[1] -ceq 'TabularSection' -and $segs[3] -ceq 'Attribute') {
- $subKind = 'TabularSection'; $subName = $segs[2]; $colName = $segs[4]
- } elseif ($segs.Count -eq 3) {
- return @{ Error = "Unsupported child object kind '$($segs[1])' in '${item}': expected Form, $($script:subObjectKinds -join ', ')" }
- } else {
- return @{ Error = "Invalid format '${item}', $fmtHint" }
- }
- # Вид подобъекта — из канона ChildObjects своего типа: измерения у документа нет
- if ($subKind) {
- $order = (Get-ObjectChildOrder)[$typeName]
- if (-not $order -or $order -cnotcontains $subKind) { return @{ Error = "${typeName} has no child objects of kind ${subKind} ('${item}')" } }
- }
- # Общая форма — сама форма: «CommonForm.X» заимствуется вместе с содержимым, владельца у неё нет
- $isCommonForm = $typeName -eq 'CommonForm'
- if ($isCommonForm) {
- if ($segs.Count -ne 1) { return @{ Error = "Invalid format '${item}': общая форма задаётся как 'CommonForm.Имя'" } }
- $formName = $objName
- }
- $dirName = $childTypeDirMap[$typeName]
- $srcFormXml = $null
- if ($isCommonForm) { $srcFormXml = Join-Path (Join-Path (Join-Path $cfgDir $dirName) $objName) "Ext/Form.xml" }
- elseif ($formName) { $srcFormXml = Join-Path (Join-Path (Join-Path (Join-Path (Join-Path $cfgDir $dirName) $objName) "Forms") $formName) "Ext/Form.xml" }
- return @{ TypeName = $typeName; ObjName = $objName; FormName = $formName; IsCommonForm = $isCommonForm; DirName = $dirName; SrcFormXml = $srcFormXml
- SubKind = $subKind; SubName = $subName; ColName = $colName }
- }
- # Подобъект в источнике: реквизит/измерение/… своего вида, ТЧ и колонка. Имя сверяется ключом
- # запроса, как у Resolve-SourceAttributes; в расширение идёт имя из источника. Нет — Error.
- function Resolve-SubObjectSource($pi) {
- $res = Resolve-SourceAttributes $pi.TypeName $pi.ObjName @{ $pi.SubName = $true }
- $key = Get-QueryKey $pi.SubName
- $where = "$($pi.TypeName).$($pi.ObjName)"
- if ($pi.SubKind -ceq 'TabularSection') {
- $ts = $res.TabularSections | Where-Object { (Get-QueryKey $_.Name) -ceq $key } | Select-Object -First 1
- if (-not $ts) { return @{ Error = "TabularSection '$($pi.SubName)' not found in ${where}" } }
- $col = $null
- if ($pi.ColName) {
- $colKey = Get-QueryKey $pi.ColName
- $col = $ts.Attributes | Where-Object { (Get-QueryKey $_.Name) -ceq $colKey } | Select-Object -First 1
- if (-not $col) { return @{ Error = "Attribute '$($pi.ColName)' not found in tabular section ${where}.$($ts.Name)" } }
- }
- return @{ TS = $ts; Col = $col }
- }
- $attr = $res.Attributes | Where-Object { $_.Kind -ceq $pi.SubKind -and (Get-QueryKey $_.Name) -ceq $key } | Select-Object -First 1
- if (-not $attr) { return @{ Error = "$($pi.SubKind) '$($pi.SubName)' not found in ${where}" } }
- return @{ Attr = $attr }
- }
- # Объект-родитель формы или подобъекта: не заимствован — заимствовать заготовкой
- function Ensure-ParentBorrowed([string]$typeName, [string]$objName) {
- if (Test-ObjectBorrowed $typeName $objName) { return }
- Info " Parent object ${typeName}.${objName} not yet borrowed — borrowing first..."
- $src = Read-SourceObject $typeName $objName
- Info " Source UUID: $($src.Uuid)"
- $borrowedXml = Build-BorrowedObjectXml $typeName $objName $src.Uuid $src.Properties
- $targetDir = Join-Path $extDir $childTypeDirMap[$typeName]
- if (-not (Test-Path $targetDir)) {
- New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
- }
- $targetFile = Join-Path $targetDir "${objName}.xml"
- $enc = New-Object System.Text.UTF8Encoding($true)
- [System.IO.File]::WriteAllText($targetFile, $borrowedXml, $enc)
- Info " Created: $targetFile"
- Add-ToChildObjects $typeName $objName
- $script:borrowedFiles += $targetFile
- }
- # Подобъект без формы — как «Добавить в расширение» Конфигуратора: ТЧ пустая (свои колонки — потом,
- # meta-edit), реквизит/измерение/колонка — по одному, ссылочные типы — оболочками. Свойства объекта
- # (Hierarchical, CodeLength…) не переносятся — Конфигуратор их тут тоже не пишет.
- function Borrow-SubObject($pi, $src) {
- $typeName = $pi.TypeName; $objName = $pi.ObjName
- Ensure-ParentBorrowed $typeName $objName
- $objFile = Join-Path (Join-Path $extDir $pi.DirName) "${objName}.xml"
- if ($pi.SubKind -cne 'TabularSection') {
- $attr = $src.Attr
- if ((Get-OwnChildObjectNames $objFile).ContainsKey($attr.Name)) {
- Info " Already borrowed: $($pi.SubKind) $($attr.Name)"
- } else {
- Merge-AttributesIntoObject $typeName $objName @($attr)
- }
- Borrow-ReferenceTypeShells @($attr.TypeXml)
- return
- }
- $ts = $src.TS
- $style = Detect-XmlStyle $objFile
- $text = [System.IO.File]::ReadAllText($objFile, (New-Object System.Text.UTF8Encoding($true)))
- if (Find-OwnTabularSectionSpan $text $ts.Name) {
- Info " Already borrowed: TabularSection $($ts.Name)"
- } else {
- $text = Insert-OwnChildOrDie $text (Build-AdoptedTabularSectionXml $ts.Name $ts.Uuid $ts.GeneratedTypes @() "`t`t`t") "TabularSection" $typeName $objFile
- [System.IO.File]::WriteAllText($objFile, $text, (Get-StyleEncoding $style))
- Info " Borrowed TabularSection $($ts.Name) (no attributes): $objFile"
- }
- # Собственный реквизит в заимствованную ТЧ этих видов платформа не примет — отказ на обновлении БД.
- # Предупреждаем, когда ТЧ заимствуется под собственные реквизиты — элемент без реквизита источника
- if (-not $src.Col) {
- if ($script:tsOwnColumnsBlocked -ccontains $typeName) {
- Warn " ${typeName}: own attributes cannot be added to a borrowed tabular section of this kind — the platform rejects them on database update"
- } elseif ($script:tsOwnColumnsFromPlatform.ContainsKey($typeName)) {
- Warn " ${typeName}: own attributes in a borrowed tabular section are accepted only from platform $($script:tsOwnColumnsFromPlatform[$typeName])"
- }
- }
- if ($src.Col) {
- Merge-ColumnsIntoTabularSection $typeName $objName $ts.Name @($src.Col) | Out-Null
- Borrow-ReferenceTypeShells @($src.Col.TypeXml)
- }
- }
- # --- 13b. Актуализация заимствованного (повтор, -Check, -Actualize) ---
- # Заимствованное сверяется с источником: связь (ExtendedConfigurationObject) и объявленные свойства.
- # Платформа связывает заимствованное ПО ИМЕНИ, ECO — сверка подлинности; контролируется то, что
- # объявлено в Properties, режим — <xr:PropertyState> в InternalInfo: нет — проверять и запрещать,
- # Notify — проверять, не запрещать, Extended — переопределять, MultiState — у составного типа свой
- # режим на часть типов (xr:CheckValue / xr:ExtendValue / xr:NotifyValue). Свойства, которого нет в
- # расширении, нет и контроля — его не добавляем. Правки — текстом на месте: XmlDocument переписал бы
- # пустые элементы и пробелы файла.
- # Режим: Check — только отчёт; Apply (повтор -Object, -Actualize) — правки. Все правки идут по тому же
- # UUID (связь, свойства, имя вслед за источником), поэтому данные целы; перепривязку к объекту с другим
- # UUID — единственное, что грозит потерей данных, — не делаем, только сообщаем.
- $script:actMode = 'Apply'
- $script:actRows = New-Object System.Collections.Generic.List[object]
- $script:srcHeadCache = @{}
- $script:srcUuidIndex = @{}
- function New-ActRow([string]$path) {
- $row = @{ Path = $path; Status = $null; Notes = (New-Object System.Collections.Generic.List[object]) }
- $script:actRows.Add($row)
- return $row
- }
- # Заметка строки отчёта: Applied — правка сделана (в -Check — нет)
- # Info — заметка для сведения: на статус строки и код возврата не влияет
- function Add-ActNote($row, [string]$text, [bool]$applied, [bool]$info = $false) {
- $row.Notes.Add(@{ Text = $text; Applied = $applied; Info = $info })
- }
- function Test-EditAllowed {
- return ($script:actMode -ne 'Check')
- }
- # Элемент XML текстом: позиции тега, содержимого и конца. $pos — на «<» открывающего тега.
- $script:reXmlOpen = [regex]'\G<([\w:.-]+)((?:\s+[\w:.-]+\s*=\s*"[^"]*")*)\s*(/?)>'
- function Get-XmlElementAt([string]$text, [int]$pos) {
- $m = $script:reXmlOpen.Match($text, $pos)
- if (-not $m.Success) { return $null }
- $name = $m.Groups[1].Value
- $local = if ($name.Contains(':')) { $name.Substring($name.IndexOf(':') + 1) } else { $name }
- $openEnd = $pos + $m.Length
- if ($m.Groups[3].Value -eq '/') {
- return @{ Name = $name; Local = $local; Attrs = $m.Groups[2].Value; Start = $pos; OpenEnd = $openEnd; CloseStart = $openEnd; End = $openEnd; Empty = $true }
- }
- $re = [regex]('<(/?)' + [regex]::Escape($name) + '(?=[\s/>])')
- $depth = 1; $i = $openEnd
- while ($true) {
- $t = $re.Match($text, $i)
- if (-not $t.Success) { return $null }
- $gt = $text.IndexOf('>', $t.Index)
- if ($gt -lt 0) { return $null }
- if ($t.Groups[1].Value -eq '/') {
- $depth--
- if ($depth -eq 0) {
- return @{ Name = $name; Local = $local; Attrs = $m.Groups[2].Value; Start = $pos; OpenEnd = $openEnd; CloseStart = $t.Index; End = $gt + 1; Empty = $false }
- }
- } elseif ($text[$gt - 1] -ne '/') {
- $depth++
- }
- $i = $gt + 1
- }
- }
- function Get-XmlChildren([string]$text, $el) {
- $res = New-Object System.Collections.Generic.List[object]
- if (-not $el -or $el.Empty) { return ,$res }
- $i = $el.OpenEnd
- while ($i -lt $el.CloseStart) {
- $lt = $text.IndexOf('<', $i)
- if ($lt -lt 0 -or $lt -ge $el.CloseStart) { break }
- $c = Get-XmlElementAt $text $lt
- if (-not $c) { break }
- $res.Add($c)
- $i = $c.End
- }
- return ,$res
- }
- function Get-XmlChild([string]$text, $el, [string]$local) {
- foreach ($c in (Get-XmlChildren $text $el)) { if ($c.Local -ceq $local) { return $c } }
- return $null
- }
- function Get-XmlInner([string]$text, $el) {
- if ($el.Empty) { return '' }
- return $text.Substring($el.OpenEnd, $el.CloseStart - $el.OpenEnd)
- }
- function Get-XmlOuter([string]$text, $el) { return $text.Substring($el.Start, $el.End - $el.Start) }
- function Get-XmlAttr($el, [string]$name) {
- $m = [regex]::Match($el.Attrs, '(?:^|\s)' + [regex]::Escape($name) + '\s*=\s*"([^"]*)"')
- if ($m.Success) { return $m.Groups[1].Value }
- return $null
- }
- # Корневой элемент описания объекта (<Catalog uuid=…>) — первый ребёнок <MetaDataObject>
- function Get-MdRoot([string]$text) {
- $mdo = [regex]::Match($text, '<MetaDataObject[\s>]')
- if (-not $mdo.Success) { return $null }
- $doc = Get-XmlElementAt $text $mdo.Index
- if (-not $doc) { return $null }
- $kids = Get-XmlChildren $text $doc
- if ($kids.Count -eq 0) { return $null }
- return $kids[0]
- }
- function Get-NormXml([string]$s) { return ([regex]::Replace($s, '>\s+<', '><')).Trim() }
- function Get-LineIndent([string]$text, [int]$pos) {
- $ls = if ($pos -gt 0) { $text.LastIndexOf("`n", $pos - 1) } else { -1 }
- $ls = $ls + 1
- $pre = $text.Substring($ls, $pos - $ls)
- if ($pre -match '^[ \t]*$') { return $pre }
- return ''
- }
- # Фрагмент из другого файла — отступы строк с исходного уровня на целевой, переводы строк — как в цели
- function Set-FragmentIndent([string]$frag, [string]$from, [string]$to, [string]$eol) {
- $lines = $frag -split "\r?\n"
- for ($i = 1; $i -lt $lines.Count; $i++) {
- if ($lines[$i].StartsWith($from)) { $lines[$i] = $to + $lines[$i].Substring($from.Length) }
- }
- return ($lines -join $eol)
- }
- function Get-TextEol([string]$text) { if ($text.Contains("`r`n")) { return "`r`n" } else { return "`n" } }
- function Apply-TextEdits([string]$text, $edits) {
- $sorted = @($edits | Sort-Object -Property @{ Expression = { $_.Start }; Descending = $true }, @{ Expression = { $_.End }; Descending = $true })
- foreach ($e in $sorted) { $text = $text.Substring(0, $e.Start) + $e.Text + $text.Substring($e.End) }
- return $text
- }
- # Правка в файл расширения, если режим её разрешает; заметка в отчёт — в любом случае
- function Add-ActEdit($ctx, $row, [int]$start, [int]$end, [string]$newText, [string]$note) {
- $ok = Test-EditAllowed
- if ($ok) { $ctx.Edits.Add(@{ Start = $start; End = $end; Text = $newText }) }
- Add-ActNote $row $note $ok
- }
- # Режимы свойств элемента: имя свойства → состояние из <xr:PropertyState>
- function Get-PropertyStates([string]$text, $el) {
- $states = @{}
- $ii = Get-XmlChild $text $el 'InternalInfo'
- if (-not $ii) { return $states }
- foreach ($ps in (Get-XmlChildren $text $ii)) {
- if ($ps.Local -cne 'PropertyState') { continue }
- $p = Get-XmlChild $text $ps 'Property'; $s = Get-XmlChild $text $ps 'State'
- if ($p -and $s) { $states[(Get-XmlInner $text $p).Trim()] = (Get-XmlInner $text $s).Trim() }
- }
- return $states
- }
- # Элемент <xr:PropertyState> свойства (для удаления недопустимого режима) или $null
- function Get-PropertyStateEl([string]$text, $el, [string]$prop) {
- $ii = Get-XmlChild $text $el 'InternalInfo'
- if (-not $ii) { return $null }
- foreach ($ps in (Get-XmlChildren $text $ii)) {
- if ($ps.Local -cne 'PropertyState') { continue }
- $p = Get-XmlChild $text $ps 'Property'
- if ($p -and (Get-XmlInner $text $p).Trim() -ceq $prop) { return $ps }
- }
- return $null
- }
- # Описание типов: состав (Type / TypeSet / TypeId) и квалификаторы по виду
- function Get-TypeModel([string]$text, $typeEl) {
- $types = New-Object System.Collections.Generic.List[string]
- $quals = @{}
- foreach ($c in (Get-XmlChildren $text $typeEl)) {
- if ($c.Local -ceq 'Type' -or $c.Local -ceq 'TypeSet' -or $c.Local -ceq 'TypeId') {
- $types.Add($c.Local + '|' + (Get-XmlInner $text $c).Trim())
- } elseif ($c.Local.EndsWith('Qualifiers')) {
- $quals[$c.Local] = $c
- }
- }
- return @{ Types = $types; Quals = $quals }
- }
- # Квалификатор, который нужен типу из состава
- $script:qualKindByType = @{ 'Type|xs:string' = 'StringQualifiers'; 'Type|xs:decimal' = 'NumberQualifiers'; 'Type|xs:dateTime' = 'DateQualifiers'; 'Type|xs:base64Binary' = 'BinaryDataQualifiers' }
- $script:qualOrder = @('NumberQualifiers', 'StringQualifiers', 'DateQualifiers', 'BinaryDataQualifiers')
- function Get-QualValue([string]$text, $q, [string]$local) {
- $c = Get-XmlChild $text $q $local
- if ($c) { return (Get-XmlInner $text $c).Trim() }
- return ''
- }
- # Короткое описание состава типа для отчёта: String(10), Number(10,2), CatalogRef.X
- function Format-TypeSummary([string]$text, $model, $kinds) {
- $parts = @()
- foreach ($t in $model.Types) {
- if ($kinds -and $kinds -cnotcontains $t) { continue }
- $v = $t.Substring($t.IndexOf('|') + 1)
- switch ($t) {
- 'Type|xs:string' { $q = $model.Quals['StringQualifiers']; $v = if ($q) { "String($(Get-QualValue $text $q 'Length'))" } else { 'String' } }
- 'Type|xs:decimal' { $q = $model.Quals['NumberQualifiers']; $v = if ($q) { "Number($(Get-QualValue $text $q 'Digits'),$(Get-QualValue $text $q 'FractionDigits'))" } else { 'Number' } }
- 'Type|xs:boolean' { $v = 'Boolean' }
- 'Type|xs:dateTime' { $v = 'Date' }
- default { $v = $v -replace '^\w+:', '' }
- }
- $parts += $v
- }
- return ($parts -join ', ')
- }
- # Сравнение состава типа с источником: те же типы и те же квалификаторы нужных видов
- function Test-TypeModelEqual([string]$aText, $a, [string]$bText, $b) {
- if ($a.Types.Count -ne $b.Types.Count) { return $false }
- foreach ($t in $a.Types) { if ($b.Types -cnotcontains $t) { return $false } }
- $keys = @($a.Quals.Keys) + @($b.Quals.Keys) | Select-Object -Unique
- foreach ($k in $keys) {
- $qa = $a.Quals[$k]; $qb = $b.Quals[$k]
- if (-not $qa -or -not $qb) { return $false }
- if ((Get-NormXml (Get-XmlOuter $aText $qa)) -cne (Get-NormXml (Get-XmlOuter $bText $qb))) { return $false }
- }
- return $true
- }
- # Карта переименований заимствованных объектов: «Вид.ИмяВРасширении» → имя в источнике (ECO найден
- # под другим именем). Ссылки расширения на такие объекты сверяются с источником через неё — иначе
- # CatalogRef.Старое в типе выглядело бы пропавшим из источника, а фрагмент из источника, вписанный
- # до переименования, сослался бы на имя, которого в расширении ещё нет.
- $script:extRenames = $null
- function Get-ExtRenames {
- if ($null -ne $script:extRenames) { return $script:extRenames }
- $script:extRenames = @{}
- foreach ($it in (Get-AllAdoptedItems)) {
- $t = $it.Substring(0, $it.IndexOf('.')); $n = $it.Substring($it.IndexOf('.') + 1)
- $text = [System.IO.File]::ReadAllText((Join-Path (Join-Path $extDir $childTypeDirMap[$t]) "$n.xml"))
- $root = Get-MdRoot $text
- if (-not $root) { continue }
- $link = Get-ElementLink $text $root
- if (-not $link) { continue }
- $id = Resolve-FileIdentity (Join-Path $cfgDir $childTypeDirMap[$t]) $n $link
- if ($id.Kind -eq 'Renamed') { $script:extRenames["$t.$n"] = $id.Src.Name }
- }
- return $script:extRenames
- }
- # Префиксы ссылок на объект вида: сам вид (MDObjectRef), его порождённые типы (CatalogRef, …) и типы
- # табличных частей (CatalogTabularSection.Имя.ТЧ, CatalogTabularSectionRow.Имя.ТЧ)
- function Get-TypeRefPrefixes([string]$typeName) {
- return @($typeName, "${typeName}TabularSection", "${typeName}TabularSectionRow") + @($script:generatedTypes[$typeName] | ForEach-Object { $_.prefix })
- }
- # Ссылки на переименованные объекты: $toSource — имена расширения → имена источника, иначе обратно
- # Один проход на вид: по очереди обмен именами (A ↔ B) вернул бы первую замену второй, и тип молча
- # указал бы на другой объект
- function Convert-RenamedRefs([string]$s, [bool]$toSource) {
- $map = Get-ExtRenames
- $byType = @{}
- foreach ($k in @($map.Keys)) {
- $t = $k.Substring(0, $k.IndexOf('.')); $old = $k.Substring($k.IndexOf('.') + 1); $new = $map[$k]
- if (-not $byType.ContainsKey($t)) { $byType[$t] = @{} }
- if ($toSource) { $byType[$t][$old] = $new } else { $byType[$t][$new] = $old }
- }
- foreach ($t in @($byType.Keys)) {
- $tm = $byType[$t]
- $alt = (Get-TypeRefPrefixes $t | Sort-Object -Property Length -Descending | ForEach-Object { [regex]::Escape($_) }) -join '|'
- $re = [regex]('(?<![\w.])((?:' + $alt + ')\.)(' + (New-RenameRegexAlt $tm) + ')(?![\wА-Яа-яЁё])')
- $s = $re.Replace($s, { param($m) $m.Groups[1].Value + $tm[$m.Groups[2].Value] })
- }
- return $s
- }
- # Часть составного типа (xr:CheckValue / xr:NotifyValue) против источника: типы, которых в источнике
- # нет, удаляются (заявленного в источнике больше нет — расширение с ним не применится), квалификаторы — из источника. ExtendValue — переопределение, не трогаем.
- # Новые типы источника не добавляем: платформа сверяет заявленное как подмножество (замер М5).
- function Sync-TypePart($ctx, $row, $part, [string]$srcText, $srcModel, [string]$label) {
- $text = $ctx.Text
- $pm = Get-TypeModel $text $part
- $keep = @($pm.Types | Where-Object { $srcModel.Types -ccontains (Convert-RenamedRefs $_ $true) })
- $gone = @($pm.Types | Where-Object { $srcModel.Types -cnotcontains (Convert-RenamedRefs $_ $true) })
- $needKinds = @($keep | ForEach-Object { $script:qualKindByType[$_] } | Where-Object { $_ })
- $qualsDiffer = $false
- foreach ($k in $script:qualOrder) {
- $has = $pm.Quals.ContainsKey($k); $need = ($needKinds -ccontains $k) -and $srcModel.Quals.ContainsKey($k)
- if ($has -ne $need) { $qualsDiffer = $true; break }
- if ($has -and (Get-NormXml (Get-XmlOuter $text $pm.Quals[$k])) -cne (Get-NormXml (Get-XmlOuter $srcText $srcModel.Quals[$k]))) { $qualsDiffer = $true; break }
- }
- if ($gone.Count -eq 0 -and -not $qualsDiffer) { return }
- $eol = $ctx.Eol
- $partIndent = Get-LineIndent $text $part.Start
- $kids = Get-XmlChildren $text $part
- $childIndent = if ($kids.Count -gt 0) { Get-LineIndent $text $kids[0].Start } else { $partIndent + "`t" }
- $before = Format-TypeSummary $text $pm $null
- if ($keep.Count -eq 0) {
- # Часть опустела — убираем элемент целиком вместе с его строкой
- $ls = $part.Start - $partIndent.Length
- $cut = $ls; if ($cut -ge $eol.Length -and $text.Substring($cut - $eol.Length, $eol.Length) -eq $eol) { $cut -= $eol.Length }
- Add-ActEdit $ctx $row $cut $part.End '' "${label}: $before -> (removed: not in the source)"
- return
- }
- $sb = New-Object System.Text.StringBuilder
- $sb.Append($text.Substring($part.Start, $part.OpenEnd - $part.Start)) | Out-Null
- foreach ($c in $kids) {
- if (($c.Local -ceq 'Type' -or $c.Local -ceq 'TypeSet' -or $c.Local -ceq 'TypeId') -and $keep -ccontains ($c.Local + '|' + (Get-XmlInner $text $c).Trim())) {
- $sb.Append($eol + $childIndent + (Get-XmlOuter $text $c)) | Out-Null
- }
- }
- foreach ($k in $script:qualOrder) {
- if (($needKinds -ccontains $k) -and $srcModel.Quals.ContainsKey($k)) {
- $sq = $srcModel.Quals[$k]
- $frag = Set-FragmentIndent (Get-XmlOuter $srcText $sq) (Get-LineIndent $srcText $sq.Start) $childIndent $eol
- $sb.Append($eol + $childIndent + $frag) | Out-Null
- }
- }
- $sb.Append($eol + $partIndent + "</$($part.Name)>") | Out-Null
- $afterModel = @{ Types = $keep; Quals = $srcModel.Quals }
- $after = Format-TypeSummary $srcText $afterModel $null
- $note = "${label}: $before -> $after"
- if ($gone.Count -gt 0) { $note += " (removed: not in the source)" }
- Add-ActEdit $ctx $row $part.Start $part.End $sb.ToString() $note
- }
- # Группы объявленных свойств. Контролируемые (замеры М2/М4/М5, ПР #99) приводятся к источнику по режимам.
- # Дополнения — список расширения сливается со списком источника (замер М10: движения документа, состав
- # подсистемы): там своё расширения, к источнику не приводим. Прочие — не трогаем, только сообщаем о
- # расхождении: свойство может оказаться дополнением, и замена стёрла бы чужое.
- $script:controlledProps = @('Type', 'Owners', 'Global', 'ClientManagedApplication', 'Server', 'ExternalConnection',
- 'ClientOrdinaryApplication', 'ServerCall', 'Hierarchical', 'CodeLength', 'DescriptionLength', 'CodeType',
- 'CodeAllowedLength', 'NumberType', 'NumberLength', 'NumberAllowedLength', 'InformationRegisterPeriodicity',
- 'WriteMode', 'LanguageCode', 'RegisteredDocuments', 'ExtDimensionTypes', 'MaxExtDimensionCount')
- $script:additiveProps = @('RegisterRecords', 'Content')
- # Свойства, для которых Конфигуратор переопределения не предлагает (замер М4). Платформа Extended у них
- # принимает, но при выгрузке теряет, и своя же выгрузка не грузится (замеры М15, М16: Hierarchical,
- # InformationRegisterPeriodicity) — сверяем как контролируемые, режим убираем
- $script:noOverrideProps = @('Hierarchical', 'InformationRegisterPeriodicity', 'WriteMode', 'Global',
- 'ClientManagedApplication', 'Server', 'ExternalConnection', 'ClientOrdinaryApplication', 'ServerCall', 'CodeAllowedLength', 'LanguageCode')
- # Свойства заимствованного элемента против источника — по режимам
- function Sync-AdoptedProperties($ctx, $row, $extEl, [string]$srcText, $srcEl) {
- $text = $ctx.Text
- $props = Get-XmlChild $text $extEl 'Properties'
- $srcProps = Get-XmlChild $srcText $srcEl 'Properties'
- if (-not $props -or -not $srcProps) { return }
- $states = Get-PropertyStates $text $extEl
- $srcKids = @{}
- foreach ($sc in (Get-XmlChildren $srcText $srcProps)) { if (-not $srcKids.ContainsKey($sc.Local)) { $srcKids[$sc.Local] = $sc } }
- foreach ($c in (Get-XmlChildren $text $props)) {
- if (@('ObjectBelonging', 'Name', 'Comment', 'ExtendedConfigurationObject') -ccontains $c.Local) { continue }
- $state = $states[$c.Local]
- if ($state -ceq 'Extended' -and $script:noOverrideProps -ccontains $c.Local) {
- $psEl = Get-PropertyStateEl $text $extEl $c.Local
- if ($psEl) {
- $ls = $text.LastIndexOf("`n", $psEl.Start) + 1
- $le = $psEl.End; if ($le -lt $text.Length -and $text[$le] -eq "`r") { $le++ }; if ($le -lt $text.Length -and $text[$le] -eq "`n") { $le++ }
- Add-ActEdit $ctx $row $ls $le '' "$($c.Local): override mode removed — not supported for this property (the platform drops it on dump, and the next load fails); compared as controlled"
- }
- $state = $null
- }
- # Переопределение типа платформа принимает только частями (MultiState, xr:ExtendValue); одиночный
- # Extended у Type она не применяет и сверяет тип как контролируемый (замер М13, 8.3.27)
- if ($state -ceq 'Extended' -and $c.Local -cne 'Type') { continue }
- if ($script:additiveProps -ccontains $c.Local) { continue }
- $sc = $srcKids[$c.Local]
- if (-not $sc) { continue }
- if ($script:controlledProps -cnotcontains $c.Local) {
- if ((Get-NormXml (Convert-RenamedRefs (Get-XmlOuter $text $c) $true)) -cne (Get-NormXml (Get-XmlOuter $srcText $sc))) {
- Add-ActNote $row "$($c.Local): differs from the source, not refreshed (not a known controlled property)" $false $true
- }
- continue
- }
- $modeTag = if ($state -ceq 'Notify') { ' (mode: Notify)' } else { '' }
- if ($c.Local -ceq 'Owners') {
- $srcItems = @((Get-XmlChildren $srcText $sc) | ForEach-Object { (Get-XmlInner $srcText $_).Trim() })
- $items = Get-XmlChildren $text $c
- $gone = @($items | Where-Object { $srcItems -cnotcontains (Convert-RenamedRefs (Get-XmlInner $text $_).Trim() $true) })
- if ($gone.Count -eq 0) { continue }
- $ind = Get-LineIndent $text $c.Start
- $kept = @($items | Where-Object { $srcItems -ccontains (Convert-RenamedRefs (Get-XmlInner $text $_).Trim() $true) })
- if ($kept.Count -eq 0) { $new = "<$($c.Name)/>" }
- else {
- $ci = Get-LineIndent $text $kept[0].Start
- $new = "<$($c.Name)>" + (($kept | ForEach-Object { $ctx.Eol + $ci + (Get-XmlOuter $text $_) }) -join '') + $ctx.Eol + $ind + "</$($c.Name)>"
- }
- $goneNames = ($gone | ForEach-Object { (Get-XmlInner $text $_).Trim() }) -join ', '
- Add-ActEdit $ctx $row $c.Start $c.End $new "Owners: removed $goneNames (not in the source)"
- continue
- }
- if ($c.Local -ceq 'Type') {
- $srcModel = Get-TypeModel $srcText $sc
- if ($state -ceq 'MultiState' -or $c.Attrs -match 'ExtendedProperty') {
- foreach ($part in (Get-XmlChildren $text $c)) {
- if ($part.Local -ceq 'CheckValue') { Sync-TypePart $ctx $row $part $srcText $srcModel 'Type (check part)' }
- elseif ($part.Local -ceq 'NotifyValue') { Sync-TypePart $ctx $row $part $srcText $srcModel 'Type (notify part)' }
- }
- continue
- }
- $model = Get-TypeModel $text $c
- $cmpModel = @{ Types = @($model.Types | ForEach-Object { Convert-RenamedRefs $_ $true }); Quals = $model.Quals }
- if (Test-TypeModelEqual $text $cmpModel $srcText $srcModel) { continue }
- $new = Convert-RenamedRefs (Set-FragmentIndent (Get-XmlOuter $srcText $sc) (Get-LineIndent $srcText $sc.Start) (Get-LineIndent $text $c.Start) $ctx.Eol) $false
- Add-ActEdit $ctx $row $c.Start $c.End $new "Type$($modeTag): $(Format-TypeSummary $text $model $null) -> $(Format-TypeSummary $srcText $srcModel $null)"
- # Новые ссылочные типы — оболочками, как при первом заимствовании (ниже 8.3.25 иначе «Неизвестное имя типа»)
- if (Test-EditAllowed) { $ctx.Shells.Add(@{ Row = $row; Xml = $new }) }
- continue
- }
- $extNorm = Get-NormXml (Convert-RenamedRefs (Get-XmlOuter $text $c) $true); $srcNorm = Get-NormXml (Get-XmlOuter $srcText $sc)
- if ($extNorm -ceq $srcNorm) { continue }
- $new = Convert-RenamedRefs (Set-FragmentIndent (Get-XmlOuter $srcText $sc) (Get-LineIndent $srcText $sc.Start) (Get-LineIndent $text $c.Start) $ctx.Eol) $false
- $was = (Get-XmlInner $text $c).Trim(); $now = (Get-XmlInner $srcText $sc).Trim()
- if ($was.Contains('<') -or $now.Contains('<')) { $was = '…'; $now = '(source value)' }
- Add-ActEdit $ctx $row $c.Start $c.End $new "$($c.Local)$($modeTag): $was -> $now"
- # Виды субконто — ссылка на ПВХ: он обязан быть в расширении (иначе «ВидыСубконто не совпадает»,
- # замер 8.3.27), как при первом заимствовании
- if ($c.Local -ceq 'ExtDimensionTypes' -and (Test-EditAllowed) -and $now -match '^(\w+)\.([^.]+)$') {
- $ctx.Shells.Add(@{ Row = $row; Ref = @{ TypeName = $Matches[1]; ObjName = $Matches[2] } })
- }
- }
- }
- # Связь заимствованного элемента: дописать отсутствующий ECO (данные своих реквизитов при этом целы — М3)
- function Add-MissingLink($ctx, $row, $extEl, [string]$uuid) {
- $text = $ctx.Text
- $props = Get-XmlChild $text $extEl 'Properties'
- if (-not $props) { return }
- $anchor = Get-XmlChild $text $props 'Comment'
- if (-not $anchor) { $anchor = Get-XmlChild $text $props 'Name' }
- if (-not $anchor) { return }
- # Нулевой UUID (cfe-init без -ConfigPath) ни с чем не совпадает — заменяем значение на месте
- $zero = Get-XmlChild $text $props 'ExtendedConfigurationObject'
- if ($zero) {
- Add-ActEdit $ctx $row $zero.Start $zero.End "<ExtendedConfigurationObject>$uuid</ExtendedConfigurationObject>" "ExtendedConfigurationObject: zero link replaced ($uuid)"
- return
- }
- $ind = Get-LineIndent $text $anchor.Start
- Add-ActEdit $ctx $row $anchor.End $anchor.End ($ctx.Eol + $ind + "<ExtendedConfigurationObject>$uuid</ExtendedConfigurationObject>") "ExtendedConfigurationObject: link restored ($uuid)"
- }
- function Get-MdElementName([string]$text, $el) {
- $props = Get-XmlChild $text $el 'Properties'
- if (-not $props) { return $null }
- $n = Get-XmlChild $text $props 'Name'
- if ($n) { return (Get-XmlInner $text $n).Trim() }
- return $null
- }
- function Get-ElementLink([string]$text, $el) {
- $props = Get-XmlChild $text $el 'Properties'
- if (-not $props) { return $null }
- $e = Get-XmlChild $text $props 'ExtendedConfigurationObject'
- if ($e) {
- # Нулевой UUID — связи нет (след cfe-init без -ConfigPath), а не пересозданный объект
- $v = (Get-XmlInner $text $e).Trim()
- if ($v -ceq '00000000-0000-0000-0000-000000000000') { return $null }
- return $v
- }
- return $null
- }
- function Test-ElementAdopted([string]$text, $el) {
- $props = Get-XmlChild $text $el 'Properties'
- if (-not $props) { return $false }
- $ob = Get-XmlChild $text $props 'ObjectBelonging'
- return ($ob -and (Get-XmlInner $text $ob).Trim() -ceq 'Adopted')
- }
- # Начало файла источника: uuid и имя объекта (первый <Name> — имя самого объекта)
- function Read-SourceHead([string]$file) {
- if ($script:srcHeadCache.ContainsKey($file)) { return $script:srcHeadCache[$file] }
- # Читаем порциями до первого </Name>: файл объекта бывает в мегабайты, а нужна только шапка
- $sr = New-Object System.IO.StreamReader($file, [System.Text.Encoding]::UTF8)
- $sb = New-Object System.Text.StringBuilder
- $buf = New-Object char[] 16384
- try {
- while (($k = $sr.Read($buf, 0, $buf.Length)) -gt 0) {
- $from = [Math]::Max(0, $sb.Length - 6)
- $sb.Append($buf, 0, $k) | Out-Null
- if ($sb.ToString($from, $sb.Length - $from).Contains('</Name>')) { break }
- }
- } finally { $sr.Close() }
- $text = $sb.ToString()
- $u = [regex]::Match($text, '<MetaDataObject[^>]*>\s*<\w+\s+uuid="([^"]+)"')
- $n = [regex]::Match($text, '<Name>([^<]*)</Name>')
- $h = @{ Uuid = $(if ($u.Success) { $u.Groups[1].Value.ToLowerInvariant() } else { '' }); Name = $(if ($n.Success) { $n.Groups[1].Value } else { '' }); File = $file }
- $script:srcHeadCache[$file] = $h
- return $h
- }
- # Связи заимствованных объектов вида в расширении: UUID источника → имена (больше одного — дубль). Строится
- # один раз за запуск по состоянию до правок
- $script:extLinkIndex = @{}
- function Get-ExtLinkIndex([string]$typeName) {
- if ($script:extLinkIndex.ContainsKey($typeName)) { return $script:extLinkIndex[$typeName] }
- $idx = @{}
- $dir = Join-Path $extDir $childTypeDirMap[$typeName]
- if (Test-Path -LiteralPath $dir) {
- foreach ($f in (Get-ChildItem -LiteralPath $dir -Filter '*.xml' -File)) {
- if ($f.Extension -ne '.xml') { continue }
- $t = [System.IO.File]::ReadAllText($f.FullName)
- $root = Get-MdRoot $t
- if (-not $root -or -not (Test-ElementAdopted $t $root)) { continue }
- $l = Get-ElementLink $t $root
- if (-not $l) { continue }
- $l = $l.ToLowerInvariant()
- if (-not $idx.ContainsKey($l)) { $idx[$l] = @() }
- $idx[$l] += (Get-MdElementName $t $root)
- }
- }
- $script:extLinkIndex[$typeName] = $idx
- return $idx
- }
- # Элемент пакета назван именем источника, а в расширении он заимствован под прежним (источник его
- # переименовал): тот же UUID связи. Возвращает элемент под именем расширения — актуализация переименует
- # его вслед за источником, а не заимствует второй с той же связью (платформа такой не грузит, замер М15)
- function Resolve-ItemByLink([string]$item) {
- $pi = Split-BorrowItem $item
- if ($pi.Error -or $pi.IsCommonForm) { return $item }
- $srcDir = Join-Path $cfgDir $pi.DirName
- if (-not (Test-ObjectBorrowed $pi.TypeName $pi.ObjName)) {
- $sf = Join-Path $srcDir "$($pi.ObjName).xml"
- if (-not (Test-Path -LiteralPath $sf)) { return $item }
- $h = Read-SourceHead $sf
- $names = @((Get-ExtLinkIndex $pi.TypeName)[$h.Uuid] | Where-Object { $_ })
- if ($names.Count -gt 1) {
- # Дубль уже есть — ещё одна копия с той же связью только усугубит
- Write-Error "$($pi.TypeName).$($pi.ObjName): the extension already has several borrowed objects bound to this source object ($(($names | ForEach-Object { "$($pi.TypeName).$_" }) -join ', ')) — the platform does not load such an extension; ask the user which one is extra and remove it by hand. Extension not changed"
- exit 1
- }
- if ($names.Count -ne 1) { return $item }
- Info "$($pi.TypeName).$($pi.ObjName) is borrowed as $($pi.TypeName).$($names[0]) (renamed in the source)"
- $item = $item -replace ('^([^.]+)\.' + [regex]::Escape($pi.ObjName) + '(?=\.|$)'), ('$1.' + $names[0].Replace('$', '$$'))
- $pi = Split-BorrowItem $item
- }
- if ($pi.SubKind -and -not (Test-SubBorrowed $pi)) {
- $ext = [System.IO.File]::ReadAllText((Join-Path (Join-Path $extDir $pi.DirName) "$($pi.ObjName).xml"))
- # Объект источника — по связи объекта расширения (его тоже могли переименовать), иначе по имени
- $sf = Join-Path $srcDir "$($pi.ObjName).xml"
- $ol = Get-ElementLink $ext (Get-MdRoot $ext)
- if ($ol) { $hs = (Get-SourceUuidIndex $srcDir)[$ol.ToLowerInvariant()]; if ($hs) { $sf = $hs.File } }
- if (-not (Test-Path -LiteralPath $sf)) { return $item }
- $st = [System.IO.File]::ReadAllText($sf)
- $sEl = $null
- foreach ($sc in (Get-XmlChildren $st (Get-XmlChild $st (Get-MdRoot $st) 'ChildObjects'))) {
- if ($sc.Local -ceq $pi.SubKind -and (Get-MdElementName $st $sc) -ceq $pi.SubName) { $sEl = $sc; break }
- }
- if (-not $sEl) { return $item }
- $su = (Get-XmlAttr $sEl 'uuid')
- if (-not $su) { return $item }
- foreach ($ec in (Get-XmlChildren $ext (Get-XmlChild $ext (Get-MdRoot $ext) 'ChildObjects'))) {
- if ($ec.Local -cne $pi.SubKind -or -not (Get-XmlChild $ext $ec 'Properties') -or -not (Test-ElementAdopted $ext $ec)) { continue }
- $el = Get-ElementLink $ext $ec
- if ($el -and $el.ToLowerInvariant() -eq $su.ToLowerInvariant()) {
- $en = Get-MdElementName $ext $ec
- Info "$($pi.TypeName).$($pi.ObjName).$($pi.SubKind).$($pi.SubName) is borrowed as $($pi.SubKind) $en (renamed in the source)"
- $item = "$($pi.TypeName).$($pi.ObjName).$($pi.SubKind).$en"
- if ($pi.ColName) { $item += ".Attribute.$($pi.ColName)" }
- break
- }
- }
- }
- # Форма: заимствована под прежним именем (переименована в источнике) — та же связь
- if ($pi.FormName -and (Test-ObjectBorrowed $pi.TypeName $pi.ObjName) -and -not (Test-FormBorrowed $pi)) {
- $ext = [System.IO.File]::ReadAllText((Join-Path (Join-Path $extDir $pi.DirName) "$($pi.ObjName).xml"))
- $srcObj = $pi.ObjName
- $ol = Get-ElementLink $ext (Get-MdRoot $ext)
- if ($ol) { $hs = (Get-SourceUuidIndex $srcDir)[$ol.ToLowerInvariant()]; if ($hs) { $srcObj = $hs.Name } }
- $sff = Join-Path (Join-Path (Join-Path $srcDir $srcObj) "Forms") "$($pi.FormName).xml"
- $extForms = Join-Path (Join-Path (Join-Path $extDir $pi.DirName) $pi.ObjName) "Forms"
- if ((Test-Path -LiteralPath $sff) -and (Test-Path -LiteralPath $extForms)) {
- $fu = (Read-SourceHead $sff).Uuid
- foreach ($ef in (Get-ChildItem -LiteralPath $extForms -Filter '*.xml' -File)) {
- if ($ef.Extension -ne '.xml') { continue }
- $et = [System.IO.File]::ReadAllText($ef.FullName)
- $el = Get-ElementLink $et (Get-MdRoot $et)
- if ($fu -and $el -and $el.ToLowerInvariant() -eq $fu) {
- $en = Get-MdElementName $et (Get-MdRoot $et)
- Info "$($pi.TypeName).$($pi.ObjName).Form.$($pi.FormName) is borrowed as form $en (renamed in the source)"
- $item = "$($pi.TypeName).$($pi.ObjName).Form.$en"
- break
- }
- }
- }
- }
- return $item
- }
- function Get-SourceUuidIndex([string]$dir) {
- if ($script:srcUuidIndex.ContainsKey($dir)) { return $script:srcUuidIndex[$dir] }
- $idx = @{}
- if (Test-Path -LiteralPath $dir) {
- foreach ($f in (Get-ChildItem -LiteralPath $dir -Filter '*.xml' -File)) {
- if ($f.Extension -ne '.xml') { continue }
- $h = Read-SourceHead $f.FullName
- if ($h.Uuid -and -not $idx.ContainsKey($h.Uuid)) { $idx[$h.Uuid] = $h }
- }
- }
- $script:srcUuidIndex[$dir] = $idx
- return $idx
- }
- # Чей это объект в источнике: по ECO и по имени. Kind: Match | NoLink (ECO нет, имя есть) |
- # Renamed (ECO под другим именем) | Replaced (по ECO нет, тёзка с другим UUID) | Missing
- function Resolve-FileIdentity([string]$srcDir, [string]$name, [string]$link) {
- $byName = $null
- $f = Join-Path $srcDir "$name.xml"
- if (Test-Path -LiteralPath $f -PathType Leaf) {
- $h = Read-SourceHead $f
- if ($h.Name -ceq $name) { $byName = $h }
- }
- $link = if ($link) { $link.ToLowerInvariant() } else { '' }
- if (-not $link) {
- if ($byName) { return @{ Kind = 'NoLink'; Src = $byName } }
- return @{ Kind = 'Missing' }
- }
- if ($byName -and $byName.Uuid -eq $link) { return @{ Kind = 'Match'; Src = $byName } }
- $idx = Get-SourceUuidIndex $srcDir
- if ($idx.ContainsKey($link)) { return @{ Kind = 'Renamed'; Src = $idx[$link] } }
- if ($byName) { return @{ Kind = 'Replaced'; Src = $byName } }
- return @{ Kind = 'Missing' }
- }
- # То же для подобъекта — среди детей того же вида в элементе источника
- function Resolve-ChildIdentity([string]$srcText, $srcParent, [string]$kind, [string]$name, [string]$link) {
- $co = Get-XmlChild $srcText $srcParent 'ChildObjects'
- $byName = $null; $byLink = $null
- $link = if ($link) { $link.ToLowerInvariant() } else { '' }
- foreach ($c in (Get-XmlChildren $srcText $co)) {
- if ($c.Local -cne $kind) { continue }
- $u = (Get-XmlAttr $c 'uuid'); $u = if ($u) { $u.ToLowerInvariant() } else { '' }
- $n = Get-MdElementName $srcText $c
- if ($link -and $u -eq $link) { $byLink = @{ El = $c; Name = $n; Uuid = $u } }
- if ($n -ceq $name) { $byName = @{ El = $c; Name = $n; Uuid = $u } }
- }
- if (-not $link) { if ($byName) { return @{ Kind = 'NoLink'; Src = $byName } }; return @{ Kind = 'Missing' } }
- if ($byLink) {
- if ($byLink.Name -ceq $name) { return @{ Kind = 'Match'; Src = $byLink } }
- return @{ Kind = 'Renamed'; Src = $byLink }
- }
- if ($byName) { return @{ Kind = 'Replaced'; Src = $byName } }
- return @{ Kind = 'Missing' }
- }
- function Set-IdentityStatus($row, $id, [string]$oldName) {
- switch ($id.Kind) {
- 'Replaced' {
- $row.Status = 'REPLACED'
- Add-ActNote $row "the source has an object with this name but another UUID ($($id.Src.Uuid)): it is a different object, the extension is not applied to it — not changed" $false
- }
- 'Missing' {
- $row.Status = 'NOT FOUND'
- Add-ActNote $row "not found in the source by link or by name — not changed" $false
- }
- }
- }
- # Переименования одного уровня применяются ОДНИМ проходом по карте «старое → новое»: по очереди обмен
- # именами (A ↔ B) вернул бы первое переименование вторым, и поле формы молча показало бы другой реквизит.
- # Возвращают число замен по каждому старому имени.
- function New-RenameRegexAlt($map) {
- return (@($map.Keys) | Sort-Object -Property Length -Descending | ForEach-Object { [regex]::Escape($_) }) -join '|'
- }
- # Сегменты путей к данным формы: <Основной>[.<ТЧ>].<Старое> → .<Новое> (DataPath*, Field, в форме и BaseForm)
- function Rename-FormDataPaths([string]$formXml, [string]$prefixPath, $map) {
- $counts = @{}
- if (-not (Test-Path -LiteralPath $formXml)) { return $counts }
- $style = Detect-XmlStyle $formXml
- $text = [System.IO.File]::ReadAllText($formXml)
- $main = [regex]::Match($text, '<Attribute name="([^"]+)"[^>]*>(?:(?!</Attribute>).)*?<MainAttribute>true</MainAttribute>', 'Singleline')
- if (-not $main.Success) { return $counts }
- $pre = [regex]::Escape($main.Groups[1].Value + $prefixPath + '.')
- $re = [regex]('(<(?:\w*DataPath|Field)>~?' + $pre + ')(' + (New-RenameRegexAlt $map) + ')(?=[.<])')
- $n = $re.Replace($text, { param($m) $o = $m.Groups[2].Value; $counts[$o] = 1 + [int]$counts[$o]; $m.Groups[1].Value + $map[$o] })
- if ($counts.Count -gt 0) { [System.IO.File]::WriteAllText($formXml, $n, (Get-StyleEncoding $style)) }
- return $counts
- }
- # Ссылки на переименованный подобъект в XML расширения — MDObjectRef вида Enum.X.EnumValue.Старое,
- # Catalog.X.Attribute.Старое (параметры выбора форм, права ролей, поля блокировки). Configuration.xml
- # пишется в конце из $script:xmlDoc — подобъектов в нём нет.
- function Rename-SubObjectRefs([string]$refPath, $map) {
- $counts = @{}
- $re = [regex]('(?<![\w.])(' + [regex]::Escape("$refPath.") + ')(' + (New-RenameRegexAlt $map) + ')(?![\wА-Яа-яЁё])')
- $cfgLong = (Get-Item -LiteralPath $extResolvedPath).FullName
- foreach ($f in (Get-ChildItem -LiteralPath $extDir -Recurse -File -Filter '*.xml')) {
- if ($f.FullName -eq $cfgLong) { continue }
- $t = [System.IO.File]::ReadAllText($f.FullName)
- if (-not $re.IsMatch($t)) { continue }
- $n = $re.Replace($t, { param($m) $o = $m.Groups[2].Value; $counts[$o] = 1 + [int]$counts[$o]; $m.Groups[1].Value + $map[$o] })
- [System.IO.File]::WriteAllText($f.FullName, $n, (Get-StyleEncoding (Detect-XmlStyle $f.FullName)))
- }
- return $counts
- }
- # Оставшиеся упоминания старых имён в коде расширения — для ручной правки: модули целиком, в XML —
- # только тексты запросов (<QueryText> динамического списка, <query> схемы компоновки); заголовки и
- # имена элементов формы к ссылкам не относятся. Один проход по файлам на все имена.
- function Find-NameMentions([string[]]$names) {
- $res = @{}
- foreach ($n in $names) { $res[$n] = @() }
- if ($names.Count -eq 0) { return $res }
- $alt = ($names | Sort-Object -Property Length -Descending | ForEach-Object { [regex]::Escape($_) }) -join '|'
- $re = New-Object System.Text.RegularExpressions.Regex(('(?<![\wА-Яа-яЁё])(?:' + $alt + ')(?![\wА-Яа-яЁё])'), 'IgnoreCase')
- # Get-ChildItem отдаёт длинные пути, а $extDir из Resolve-Path может быть коротким (NSHIRO~1)
- $base = (Get-Item -LiteralPath $extDir).FullName
- foreach ($f in (Get-ChildItem -LiteralPath $extDir -Recurse -File -Include '*.bsl', '*.xml')) {
- $rel = $f.FullName.Substring($base.Length).TrimStart('\', '/') -replace '\\', '/'
- $text = [System.IO.File]::ReadAllText($f.FullName)
- $hits = New-Object System.Collections.Generic.List[object]
- if ($f.Extension -ieq '.bsl') {
- foreach ($m in $re.Matches($text)) { $hits.Add(@($m.Value, $m.Index)) }
- } else {
- foreach ($q in [regex]::Matches($text, '(?s)<(QueryText|query)>(.*?)</\1>')) {
- foreach ($m in $re.Matches($q.Groups[2].Value)) { $hits.Add(@($m.Value, ($q.Groups[2].Index + $m.Index))) }
- }
- }
- foreach ($h in $hits) {
- $key = $names | Where-Object { $_ -ieq $h[0] } | Select-Object -First 1
- $loc = "${rel}:$($text.Substring(0, $h[1]).Split("`n").Count)"
- if ($res[$key] -notcontains $loc) { $res[$key] += $loc }
- }
- }
- return $res
- }
- # Упоминания ищутся в конце запуска — по итоговым файлам и путям, после всех переименований.
- # Смена только регистра — не повод: имена в коде 1С регистронезависимы.
- $script:pendingMentions = New-Object System.Collections.Generic.List[object]
- # $takenBy — кем старое имя теперь занято в источнике (тёзка, обмен именами): код со старым именем
- # скомпилируется и молча будет работать с другим объектом — упоминания становятся предупреждением
- function Add-MentionsNote($row, [string]$old, [string]$new, [string]$takenBy = '') {
- if ($old -ieq $new) { return }
- $script:pendingMentions.Add(@{ Row = $row; Name = $old; TakenBy = $takenBy })
- }
- function Resolve-PendingMentions {
- if ($script:pendingMentions.Count -eq 0) { return }
- $found = Find-NameMentions @($script:pendingMentions | ForEach-Object { $_.Name } | Select-Object -Unique)
- foreach ($pm in $script:pendingMentions) {
- $m = @($found[$pm.Name])
- if ($m.Count -eq 0) { continue }
- $shown = ($m | Select-Object -First 10) -join ', '
- if ($m.Count -gt 10) { $shown += ", … ($($m.Count) total)" }
- if ($pm.TakenBy) {
- Add-ActNote $pm.Row "'$($pm.Name)' is still mentioned in the code, and in the source this name now belongs to another object ($($pm.TakenBy)) — the code would silently use it; fix by hand: $shown" $false
- } else {
- Add-ActNote $pm.Row "'$($pm.Name)' is still mentioned in the code — fix by hand: $shown" $false
- }
- }
- $script:pendingMentions.Clear()
- }
- # Переименование файла или каталога через временное имя: Move-Item в PS 5.1 не меняет регистр имени
- function Move-PathViaTemp([string]$from, [string]$to) {
- $tmp = Join-Path (Split-Path $from -Parent) ("__rename_" + [guid]::NewGuid().ToString('N'))
- Move-Item -LiteralPath $from -Destination $tmp
- Move-Item -LiteralPath $tmp -Destination $to
- }
- # Переименование заимствованного объекта следом за источником (как «Переименовать, сохранив
- # соответствие» Конфигуратора): файл и каталог, Name, ChildObjects расширения, имена GeneratedType,
- # ссылки в XML расширения (cfg:CatalogRef.Old, Catalog.Old, …). Код и тексты запросов — не трогаем.
- function Rename-BorrowedObject([string]$typeName, [string]$old, [string]$new, $row) {
- $dir = Join-Path $extDir $childTypeDirMap[$typeName]
- $newFile = Join-Path $dir "$new.xml"
- if ((Test-Path -LiteralPath $newFile) -and ($old -ine $new)) {
- # Обмен именами в источнике (A ↔ B): имя занято заимствованным объектом, который сам переименован
- # в источнике, — уводим его на временное имя, своё новое имя он получит в свою очередь
- $renamesMap = Get-ExtRenames
- $blockerTo = $renamesMap["$typeName.$new"]
- if (-not $blockerTo) {
- Add-ActNote $row "cannot rename: $typeName.$new already exists in the extension" $false
- return $false
- }
- $tmp = "__swap_" + [guid]::NewGuid().ToString('N').Substring(0, 8)
- Move-BorrowedObjectName $typeName $new $tmp
- $renamesMap.Remove("$typeName.$new")
- $renamesMap["$typeName.$tmp"] = $blockerTo
- $script:objRenamed["$typeName.$new"] = $tmp
- $script:swapPending.Add(@{ TypeName = $typeName; Tmp = $tmp; Shown = $new })
- }
- Move-BorrowedObjectName $typeName $old $new
- if ($null -ne $script:extRenames) { $script:extRenames.Remove("$typeName.$old") }
- $script:objRenamed["$typeName.$old"] = $new
- return $true
- }
- # Файлы, имена, ссылки в XML расширения и ChildObjects — от старого имени объекта к новому
- $script:swapPending = New-Object System.Collections.Generic.List[object]
- function Move-BorrowedObjectName([string]$typeName, [string]$old, [string]$new) {
- $dir = Join-Path $extDir $childTypeDirMap[$typeName]
- $oldFile = Join-Path $dir "$old.xml"; $newFile = Join-Path $dir "$new.xml"
- Move-PathViaTemp $oldFile $newFile
- $oldDir = Join-Path $dir $old
- if (Test-Path -LiteralPath $oldDir -PathType Container) { Move-PathViaTemp $oldDir (Join-Path $dir $new) }
- $prefixes = Get-TypeRefPrefixes $typeName
- $alt = ($prefixes | Sort-Object -Property Length -Descending | ForEach-Object { [regex]::Escape($_) }) -join '|'
- $re = [regex]('(?<![\w.])((?:' + $alt + ')\.)' + [regex]::Escape($old) + '(?![\wА-Яа-яЁё])')
- $cfgLong = (Get-Item -LiteralPath $extResolvedPath).FullName
- foreach ($f in (Get-ChildItem -LiteralPath $extDir -Recurse -File -Filter '*.xml')) {
- # Configuration.xml пишется в конце из $script:xmlDoc
- if ($f.FullName -eq $cfgLong) { continue }
- $t = [System.IO.File]::ReadAllText($f.FullName)
- $n = $re.Replace($t, '${1}' + $new.Replace('$', '$$'))
- if ($n -cne $t) {
- $style = Detect-XmlStyle $f.FullName
- [System.IO.File]::WriteAllText($f.FullName, $n, (Get-StyleEncoding $style))
- }
- }
- # Имя самого объекта — первый <Name> в его Properties
- $t = [System.IO.File]::ReadAllText($newFile)
- $n = ([regex]('(<Properties>\s*(?:<ObjectBelonging>[^<]*</ObjectBelonging>\s*)?<Name>)' + [regex]::Escape($old) + '(</Name>)')).Replace($t, '${1}' + $new.Replace('$', '$$') + '${2}', 1)
- [System.IO.File]::WriteAllText($newFile, $n, (Get-StyleEncoding (Detect-XmlStyle $newFile)))
- # ChildObjects расширения — Configuration.xml пишется в конце из $script:xmlDoc
- foreach ($child in @($script:childObjsEl.ChildNodes)) {
- if ($child.NodeType -eq 'Element' -and $child.LocalName -eq $typeName -and $child.InnerText -ceq $old) {
- $prev = $child.PreviousSibling
- if ($prev -and ($prev.NodeType -eq 'Whitespace' -or $prev.NodeType -eq 'SignificantWhitespace')) { $script:childObjsEl.RemoveChild($prev) | Out-Null }
- $script:childObjsEl.RemoveChild($child) | Out-Null
- }
- }
- Add-ToChildObjects $typeName $new
- }
- # Заимствованная форма против формы источника. Своей пересборки на этом этапе нет: в рантайме
- # платформа сама сливает BaseForm / форму расширения / текущую форму источника (замер М1), поэтому
- # Form.xml не переписываем, а сообщаем, что поменялось, и где правка расширения столкнётся с источником.
- # Сравнивается заготовка: текущая форма источника проходит тот же путь, что при заимствовании
- # (Borrow-Form -RenderOnly), и её BaseForm сверяется с BaseForm расширения. Связи параметров выбора
- # зависят от состава заимствованных реквизитов — их не сравниваем.
- $script:formIgnoredTags = @('ChildItems', 'Events', 'ChoiceParameterLinks', 'TypeLink')
- function Get-FormElementFlat([string]$text, $el) {
- $sb = New-Object System.Text.StringBuilder
- $sb.Append($el.Local + ' ' + ([regex]::Replace($el.Attrs, '\s+', ' ')).Trim()) | Out-Null
- foreach ($c in (Get-XmlChildren $text $el)) {
- if ($script:formIgnoredTags -ccontains $c.Local) { continue }
- if (Get-XmlAttr $c 'name') { continue }
- $sb.Append('|' + (Get-NormXml (Get-XmlOuter $text $c))) | Out-Null
- }
- # Тильда у путей динамического списка ставится после заимствования (шаг 14c)
- return ($sb.ToString() -replace '(<(?:\w*DataPath|Field)>)~', '$1')
- }
- function Add-FormElementsFlat([string]$text, $el, $map) {
- foreach ($c in (Get-XmlChildren $text $el)) {
- if (@('Events', 'Attributes', 'Commands', 'Parameters', 'CommandInterface', 'BaseForm') -ccontains $c.Local) { continue }
- $n = Get-XmlAttr $c 'name'
- if ($n) { $map[$n] = Get-FormElementFlat $text $c }
- Add-FormElementsFlat $text $c $map
- }
- }
- function Get-FormFlatMap([string]$text, $formEl) {
- $map = New-Object System.Collections.Hashtable ([System.StringComparer]::Ordinal)
- $own = New-Object System.Text.StringBuilder
- foreach ($c in (Get-XmlChildren $text $formEl)) {
- if (@('AutoCommandBar', 'ChildItems') -ccontains $c.Local) { Add-FormElementsFlat $text $c $map; continue }
- if (@('Events', 'Attributes', 'Commands', 'Parameters', 'CommandInterface', 'BaseForm') -ccontains $c.Local) { continue }
- if ($script:formAttributeRefProps -ccontains $c.Local) { continue }
- $own.Append('|' + (Get-NormXml (Get-XmlOuter $text $c))) | Out-Null
- }
- $map['(form properties)'] = $own.ToString()
- return $map
- }
- function Compare-BorrowedForm($row, [string]$extFormXml, [string]$typeName, [string]$srcObjName, [string]$srcFormName, [string]$srcFormXml) {
- if (-not (Test-Path -LiteralPath $extFormXml) -or -not (Test-Path -LiteralPath $srcFormXml)) { return }
- $eText = [System.IO.File]::ReadAllText($extFormXml)
- $eForm = Get-XmlElementAt $eText ([regex]::Match($eText, '<Form[\s>]').Index)
- if (-not $eForm) { return }
- $base = Get-XmlChild $eText $eForm 'BaseForm'
- if (-not $base) { return }
- $hasMain = (Get-XmlOuter $eText $base) -match '<MainAttribute>true</MainAttribute>'
- $sText = Borrow-Form $typeName $srcObjName $srcFormName -BorrowMainAttr:$hasMain -RenderOnly
- $sForm = Get-XmlElementAt $sText ([regex]::Match($sText, '<Form[\s>]').Index)
- $sBase = if ($sForm) { Get-XmlChild $sText $sForm 'BaseForm' } else { $null }
- if (-not $sBase) { return }
- $old = Get-FormFlatMap $eText $base
- $new = Get-FormFlatMap $sText $sBase
- $mine = Get-FormFlatMap $eText $eForm
- $added = @($new.Keys | Where-Object { -not $old.ContainsKey($_) } | Sort-Object)
- $removed = @($old.Keys | Where-Object { -not $new.ContainsKey($_) } | Sort-Object)
- $changed = @($old.Keys | Where-Object { $new.ContainsKey($_) -and $old[$_] -cne $new[$_] } | Sort-Object)
- if ($added.Count + $removed.Count + $changed.Count -eq 0) { return }
- $row.Status = 'FORM CHANGED IN SOURCE'
- $fmt = { param($a) $s = ($a | Select-Object -First 5) -join ', '; if ($a.Count -gt 5) { $s += ", … ($($a.Count))" }; $s }
- if ($added.Count) { Add-ActNote $row "added in the source: $(& $fmt $added)" $false }
- if ($removed.Count) { Add-ActNote $row "removed in the source: $(& $fmt $removed)" $false }
- if ($changed.Count) { Add-ActNote $row "changed in the source: $(& $fmt $changed)" $false }
- foreach ($k in ($changed + $removed)) {
- if (-not $mine.ContainsKey($k) -or $mine[$k] -ceq $old[$k]) { continue }
- if ($new.ContainsKey($k)) { Add-ActNote $row "conflict: $k is edited by the extension and changed in the source — at runtime the extension value wins, the source change is lost" $false }
- else { Add-ActNote $row "conflict: $k is edited by the extension and removed in the source — at runtime the extension edit is lost" $false }
- }
- Add-ActNote $row "Form.xml is kept as is: the platform merges the source changes at runtime" $false
- }
- # Заимствованная форма объекта: связь с формой источника и сравнение содержимого
- function Actualize-BorrowedForm($objCtx, [string]$typeName, [string]$objName, [string]$formName, [string]$srcObjName) {
- $dirName = $childTypeDirMap[$typeName]
- $row = New-ActRow "$typeName.$objName.Form.$formName"
- $metaFile = Join-Path (Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Forms") "$formName.xml"
- if (-not (Test-Path -LiteralPath $metaFile)) {
- $row.Status = 'NOT FOUND'
- Add-ActNote $row "the form is listed in the object, but its file $dirName/$objName/Forms/$formName.xml is missing in the extension — not changed" $false
- return
- }
- $mText = [System.IO.File]::ReadAllText($metaFile)
- $mRoot = Get-MdRoot $mText
- if (-not $mRoot -or -not (Test-ElementAdopted $mText $mRoot)) { $script:actRows.Remove($row) | Out-Null; return }
- $srcFormsDir = Join-Path (Join-Path (Join-Path $cfgDir $dirName) $srcObjName) "Forms"
- $id = Resolve-FileIdentity $srcFormsDir $formName (Get-ElementLink $mText $mRoot)
- Set-IdentityStatus $row $id $formName
- if ($id.Kind -eq 'Replaced' -or $id.Kind -eq 'Missing') { return }
- $srcFormName = $id.Src.Name
- if ($id.Kind -eq 'NoLink') {
- $mCtx = @{ Text = $mText; Edits = (New-Object System.Collections.Generic.List[object]); Eol = (Get-TextEol $mText) }
- Add-MissingLink $mCtx $row $mRoot $id.Src.Uuid
- if ($mCtx.Edits.Count -gt 0) {
- $style = Detect-XmlStyle $metaFile
- [System.IO.File]::WriteAllText($metaFile, (Apply-TextEdits $mText $mCtx.Edits), (Get-StyleEncoding $style))
- }
- }
- $extFormXml = Join-Path (Join-Path (Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Forms") $formName) "Ext/Form.xml"
- $srcFormXml = Join-Path (Join-Path $srcFormsDir $srcFormName) "Ext/Form.xml"
- if ($id.Kind -eq 'Renamed') {
- $row.Status = 'RENAMED'
- $fDir = Split-Path $metaFile -Parent
- if ((Test-EditAllowed) -and ($formName -ine $srcFormName) -and (Test-Path -LiteralPath (Join-Path $fDir "$srcFormName.xml"))) {
- Add-ActNote $row "cannot rename: form $srcFormName already exists in the extension" $false
- } elseif (Test-EditAllowed) {
- $t = [System.IO.File]::ReadAllText($metaFile)
- $t = [regex]::Replace($t, '(<Name>)' + [regex]::Escape($formName) + '(</Name>)', '${1}' + $srcFormName.Replace('$', '$$') + '${2}', 1)
- [System.IO.File]::WriteAllText($metaFile, $t, (Get-StyleEncoding (Detect-XmlStyle $metaFile)))
- Move-PathViaTemp $metaFile (Join-Path $fDir "$srcFormName.xml")
- if (Test-Path -LiteralPath (Join-Path $fDir $formName)) { Move-PathViaTemp (Join-Path $fDir $formName) (Join-Path $fDir $srcFormName) }
- $extFormXml = Join-Path (Join-Path $fDir $srcFormName) "Ext/Form.xml"
- # Регистрация формы в ChildObjects владельца — правкой его текста
- $reg = [regex]::Match($objCtx.Text, '<Form>' + [regex]::Escape($formName) + '</Form>')
- if ($reg.Success) { $objCtx.Edits.Add(@{ Start = $reg.Index; End = $reg.Index + $reg.Length; Text = "<Form>$srcFormName</Form>" }) }
- Add-ActNote $row "renamed: $formName -> $srcFormName" $true
- Add-MentionsNote $row $formName $srcFormName
- # Ссылки Catalog.X.Form.Old в XML расширения — после записи файла владельца (его текст ещё правится)
- $objCtx.FormRenames[$formName] = $srcFormName
- $script:formRenamed["$typeName.$objName.$formName"] = $srcFormName
- } else {
- Add-ActNote $row "renamed in the source: $formName -> $srcFormName" $false
- }
- }
- Compare-BorrowedForm $row $extFormXml $typeName $srcObjName $srcFormName $srcFormXml
- }
- # Заимствованные подобъекты одного уровня (реквизиты, ТЧ, измерения…) против источника.
- # $only — @{ Kind; Name } (один подобъект) или $null (все); $colOnly — одна колонка ТЧ из $only.
- # $refPrefix — путь элемента в ссылках MDObjectRef (Catalog.X / Catalog.X.TabularSection.ТЧ) по именам, какие
- # будут в расширении: по нему переименованный подобъект ищется в XML расширения.
- function Sync-AdoptedChildren($ctx, $extParent, [string]$srcText, $srcParent, [string]$pathPrefix, [string]$formPrefix, $only, $colOnly, $renames, [string]$refPrefix) {
- $text = $ctx.Text
- $co = Get-XmlChild $text $extParent 'ChildObjects'
- # Связи заимствованных подобъектов этого уровня: одна связь у двух — дубль (замер М15)
- $linkCount = @{}
- foreach ($c in (Get-XmlChildren $text $co)) {
- if (-not (Get-XmlChild $text $c 'Properties') -or -not (Test-ElementAdopted $text $c)) { continue }
- $l = Get-ElementLink $text $c
- if ($l) { $k = "$($c.Local)|$($l.ToLowerInvariant())"; $linkCount[$k] = 1 + [int]$linkCount[$k] }
- }
- foreach ($c in (Get-XmlChildren $text $co)) {
- # Значения перечисления заимствуются вместе с формой (параметры выбора) — сверяются так же
- if (-not ($script:childObjectKinds -ccontains $c.Local -or $c.Local -ceq 'TabularSection' -or $c.Local -ceq 'EnumValue')) { continue }
- if (-not (Test-ElementAdopted $text $c)) {
- # Собственный подобъект, одноимённый (без учёта регистра) с подобъектом источника того же вида:
- # платформа не обновит базу («Уже существует объект с именем …», замер М14). Переименовать своё —
- # решение человека: у него данные
- if (-not $only) {
- $own = Get-MdElementName $text $c
- foreach ($sc in (Get-XmlChildren $srcText (Get-XmlChild $srcText $srcParent 'ChildObjects'))) {
- if ($sc.Local -cne $c.Local) { continue }
- $sn = Get-MdElementName $srcText $sc
- if ($sn -ine $own) { continue }
- $cr = New-ActRow "$pathPrefix.$($c.Local).$own"
- $cr.Status = 'NAME CONFLICT'
- Add-ActNote $cr "own $($c.Local): the source now has a $($c.Local) with this name ($sn) — the platform does not update the database («Уже существует объект с именем …»); rename the own $($c.Local) by hand" $false
- break
- }
- }
- continue
- }
- $name = Get-MdElementName $text $c
- if ($only -and -not ($c.Local -ceq $only.Kind -and $name -ceq $only.Name)) { continue }
- $isTs = $c.Local -ceq 'TabularSection'
- # ТЧ ради одной колонки в отчёт сама не идёт — только если её нет в источнике
- $inScope = -not ($isTs -and $colOnly)
- $cLink = Get-ElementLink $text $c
- if ($cLink -and $linkCount["$($c.Local)|$($cLink.ToLowerInvariant())"] -gt 1) {
- $row = New-ActRow "$pathPrefix.$($c.Local).$name"
- $row.Status = 'DUPLICATE LINK'
- Add-ActNote $row "another borrowed $($c.Local) of this object is bound to the same source $($c.Local) — the platform does not load the extension; remove the extra one by hand (both may hold data)" $false
- continue
- }
- $id = Resolve-ChildIdentity $srcText $srcParent $c.Local $name $cLink
- $row = $null
- if ($inScope -or $id.Kind -eq 'Replaced' -or $id.Kind -eq 'Missing') {
- $row = New-ActRow "$pathPrefix.$($c.Local).$name"
- Set-IdentityStatus $row $id $name
- }
- if ($id.Kind -eq 'Replaced' -or $id.Kind -eq 'Missing') { continue }
- if ($inScope) {
- if ($id.Kind -eq 'NoLink') { Add-MissingLink $ctx $row $c $id.Src.Uuid }
- if ($id.Kind -eq 'Renamed') {
- $row.Status = 'RENAMED'
- $props = Get-XmlChild $text $c 'Properties'
- $nEl = Get-XmlChild $text $props 'Name'
- $newName = $id.Src.Name
- $ok = Test-EditAllowed
- if ($ok) {
- $ctx.Edits.Add(@{ Start = $nEl.Start; End = $nEl.End; Text = "<Name>$newName</Name>" })
- # Старое имя в источнике занято другим подобъектом того же вида (тёзка, обмен именами)?
- $taken = ''
- foreach ($sc in (Get-XmlChildren $srcText (Get-XmlChild $srcText $srcParent 'ChildObjects'))) {
- if ($sc.Local -ceq $c.Local -and (Get-MdElementName $srcText $sc) -ceq $name) { $taken = "another $($c.Local) $name of this object"; break }
- }
- $renames.Add(@{ Prefix = $formPrefix; Old = $name; New = $newName; Row = $row; RefPath = "$refPrefix.$($c.Local)"; TakenBy = $taken })
- $script:subRenamed["$pathPrefix.$($c.Local).$name"] = $newName
- }
- Add-ActNote $row $(if ($ok) { "renamed: $name -> $newName" } else { "renamed in the source: $name -> $newName" }) $ok
- }
- Sync-AdoptedProperties $ctx $row $c $srcText $id.Src.El
- }
- if ($isTs) {
- $nested = if ($colOnly) { @{ Kind = 'Attribute'; Name = $colOnly } } else { $null }
- # Пути колонок в формах — по имени ТЧ, какое будет в расширении: новое, если ТЧ переименована здесь же
- $tsPathName = if ($inScope -and $id.Kind -eq 'Renamed' -and (Test-EditAllowed)) { $id.Src.Name } else { $name }
- Sync-AdoptedChildren $ctx $c $srcText $id.Src.El "$pathPrefix.TabularSection.$name" "$formPrefix.$tsPathName" $nested $null $renames "$refPrefix.TabularSection.$tsPathName"
- }
- }
- }
- # UUID заимствованных подобъектов объекта (реквизиты, ТЧ и их колонки, значения перечисления…)
- function Get-AdoptedChildLinks([string]$text, $el) {
- $res = @()
- foreach ($c in (Get-XmlChildren $text (Get-XmlChild $text $el 'ChildObjects'))) {
- if (-not (Get-XmlChild $text $c 'Properties')) { continue }
- if (Test-ElementAdopted $text $c) {
- $l = Get-ElementLink $text $c
- if ($l) { $res += $l.ToLowerInvariant() }
- }
- $res += @(Get-AdoptedChildLinks $text $c)
- }
- return $res
- }
- # Связи у объекта нет — по имени нельзя отличить переименование с тёзкой от того же объекта. Подсказка —
- # заимствованные подобъекты: их ECO указывают, в каком объекте источника они теперь (замер М14: по имени
- # расширение привязалось к тёзке, а данные своих реквизитов остались у переименованного объекта).
- function Resolve-IdentityByChildren($id, [string]$srcDir, [string]$text, $root, $row) {
- $links = @(Get-AdoptedChildLinks $text $root | Select-Object -Unique)
- if ($links.Count -eq 0) {
- if ($id.Kind -eq 'NoLink') { Add-ActNote $row "the link is restored by name: if the source object was renamed and a new one was created under this name, the extension now refers to the new one — check" $false $true }
- return $id
- }
- # Частый случай — подобъекты там же, в файле с этим именем: он один и читается без индекса каталога
- if ($id.Kind -eq 'NoLink') {
- $ft = [System.IO.File]::ReadAllText($id.Src.File).ToLowerInvariant()
- foreach ($u in $links) { if ($ft.Contains("uuid=`"$u`"")) { return $id } }
- }
- $idx = Get-SourceChildUuidIndex $srcDir
- $files = @($links | ForEach-Object { $idx[$_] } | Where-Object { $_ } | Select-Object -Unique)
- # Каталог один — сравниваем по имени файла (пути бывают в короткой и длинной форме)
- $own = if ($id.Src) { [System.IO.Path]::GetFileName($id.Src.File) } else { '' }
- if ($id.Kind -eq 'NoLink' -and (@($files | ForEach-Object { [System.IO.Path]::GetFileName($_) }) -contains $own)) { return $id }
- foreach ($f in $files) {
- if ($own -and [System.IO.Path]::GetFileName($f) -eq $own) { continue }
- $h = Read-SourceHead $f
- Add-ActNote $row "no link in the extension; the borrowed sub-objects are found in $($h.Name) of the source — the object was renamed there" $false $true
- return @{ Kind = 'Renamed'; Src = $h }
- }
- return $id
- }
- # UUID подобъектов источника → файл объекта; по каталогу вида один раз за запуск (объектов без связи
- # бывает много — выгрузка без ECO целиком, ПР #138)
- $script:srcChildUuidIndex = @{}
- function Get-SourceChildUuidIndex([string]$dir) {
- if ($script:srcChildUuidIndex.ContainsKey($dir)) { return $script:srcChildUuidIndex[$dir] }
- $idx = @{}
- if (Test-Path -LiteralPath $dir) {
- foreach ($f in (Get-ChildItem -LiteralPath $dir -Filter '*.xml' -File)) {
- if ($f.Extension -ne '.xml') { continue }
- foreach ($m in [regex]::Matches([System.IO.File]::ReadAllText($f.FullName), '\buuid="([^"]+)"')) {
- $u = $m.Groups[1].Value.ToLowerInvariant()
- if (-not $idx.ContainsKey($u)) { $idx[$u] = $f.FullName }
- }
- }
- }
- $script:srcChildUuidIndex[$dir] = $idx
- return $idx
- }
- # Один заимствованный объект (с подобъектами и формами — по области): возвращает итоговое имя
- function Actualize-BorrowedObject([string]$typeName, [string]$objName, $scope) {
- $dirName = $childTypeDirMap[$typeName]
- $objFile = Join-Path (Join-Path $extDir $dirName) "$objName.xml"
- $text = [System.IO.File]::ReadAllText($objFile)
- $root = Get-MdRoot $text
- if (-not $root -or -not (Test-ElementAdopted $text $root)) {
- Info "${typeName}.${objName}: own object of the extension — nothing to actualize"
- return $objName
- }
- $ctx = @{ Text = $text; Edits = (New-Object System.Collections.Generic.List[object]); Eol = (Get-TextEol $text); Shells = (New-Object System.Collections.Generic.List[object]); FormRenames = @{} }
- # На временном имени (обмен именами) объект показывается под прежним
- $shown = $objName
- foreach ($sw in $script:swapPending) { if ($sw.TypeName -eq $typeName -and $sw.Tmp -ceq $objName) { $shown = $sw.Shown } }
- $row = New-ActRow "$typeName.$shown"
- $objLink = Get-ElementLink $text $root
- # Два заимствованных объекта связаны с одним объектом источника: платформа не грузит расширение
- # («Не найден объект …», замер М15). Какой лишний — решает человек: у обоих могут быть данные
- if ($objLink) {
- # Индекс — по состоянию до правок; за запуск имена меняются (обмен через временное имя), поэтому
- # двойник подтверждается текущей связью в его файле
- $twins = @((Get-ExtLinkIndex $typeName)[$objLink.ToLowerInvariant()] | Where-Object {
- # Имена в 1С без учёта регистра: «goods» в ChildObjects и «Goods» в файле — один объект
- if ($_ -ieq $objName -or -not (Test-ObjectBorrowed $typeName $_)) { return $false }
- $tt = [System.IO.File]::ReadAllText((Join-Path (Join-Path $extDir $dirName) "$_.xml"))
- $tl = Get-ElementLink $tt (Get-MdRoot $tt)
- return [bool]($tl -and $tl.ToLowerInvariant() -eq $objLink.ToLowerInvariant())
- })
- if ($twins.Count -gt 0) {
- $row.Status = 'DUPLICATE LINK'
- Add-ActNote $row "bound to the same source object as $(($twins | ForEach-Object { "$typeName.$_" }) -join ', ') — the platform does not load the extension; remove the extra one by hand (both may hold data)" $false
- $script:actBlocked["$typeName.$objName"] = $true
- return $objName
- }
- }
- $id = Resolve-FileIdentity (Join-Path $cfgDir $dirName) $objName $objLink
- if (-not $objLink) { $id = Resolve-IdentityByChildren $id (Join-Path $cfgDir $dirName) $text $root $row }
- Set-IdentityStatus $row $id $objName
- if ($id.Kind -eq 'Replaced' -or $id.Kind -eq 'Missing') { $script:actBlocked["$typeName.$objName"] = $true; return $objName }
- $srcText = [System.IO.File]::ReadAllText($id.Src.File)
- $srcRoot = Get-MdRoot $srcText
- $srcName = $id.Src.Name
- if (-not $objLink -and $id.Src) { Add-MissingLink $ctx $row $root $id.Src.Uuid }
- if ($scope.Kind -eq 'Object') {
- Sync-AdoptedProperties $ctx $row $root $srcText $srcRoot
- }
- $renames = New-Object System.Collections.Generic.List[object]
- if ($scope.Kind -eq 'Object') {
- Sync-AdoptedChildren $ctx $root $srcText $srcRoot "$typeName.$shown" '' $null $null $renames "$typeName.$objName"
- } elseif ($scope.Kind -eq 'Sub') {
- Sync-AdoptedChildren $ctx $root $srcText $srcRoot "$typeName.$shown" '' @{ Kind = $scope.SubKind; Name = $scope.SubName } $scope.ColName $renames "$typeName.$objName"
- }
- if ($typeName -eq 'CommonForm' -and $scope.Kind -eq 'Object') {
- Compare-BorrowedForm $row (Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Ext/Form.xml") $typeName $srcName $srcName (Join-Path (Join-Path (Join-Path $cfgDir $dirName) $srcName) "Ext/Form.xml")
- } elseif ($scope.Kind -ne 'Sub') {
- foreach ($fm in [regex]::Matches($text, '<Form>([^<]+)</Form>')) {
- $fn = $fm.Groups[1].Value
- if ($scope.Kind -eq 'Form' -and $fn -cne $scope.FormName) { continue }
- Actualize-BorrowedForm $ctx $typeName $objName $fn $srcName
- }
- }
- # Строка самого объекта при повторе по подобъекту или форме — только если с объектом что-то произошло
- $row.Optional = ($scope.Kind -ne 'Object')
- if ($ctx.Edits.Count -gt 0) {
- $style = Detect-XmlStyle $objFile
- [System.IO.File]::WriteAllText($objFile, (Apply-TextEdits $text $ctx.Edits), (Get-StyleEncoding $style))
- }
- # Переименованные формы — ссылки на них (основная форма объекта, команды, подсистемы…), одним проходом
- if ($ctx.FormRenames.Count -gt 0) { Rename-SubObjectRefs "$typeName.$objName.Form" $ctx.FormRenames | Out-Null }
- foreach ($sh in $ctx.Shells) {
- $refs = if ($sh.Ref) { @($sh.Ref) } else { @(Collect-ReferenceTypes @($sh.Xml)) }
- foreach ($rt in $refs) {
- if (Test-ObjectBorrowed $rt.TypeName $rt.ObjName) { continue }
- Borrow-ObjectShell $rt.TypeName $rt.ObjName
- if (Test-ObjectBorrowed $rt.TypeName $rt.ObjName) { Add-ActNote $sh.Row "borrowed as a shell: $($rt.TypeName).$($rt.ObjName)" $true }
- }
- }
- # Переименованные подобъекты — пути к данным в формах этого объекта
- # Группы по уровню (путь формы, путь ссылки) — в порядке появления: ТЧ переименовывается раньше
- # своих колонок, их пути уже идут по новому имени ТЧ
- $formsDir = Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Forms"
- $pathGroups = [ordered]@{}; $refGroups = [ordered]@{}
- foreach ($rn in $renames) {
- if (-not $pathGroups.Contains($rn.Prefix)) { $pathGroups[$rn.Prefix] = New-Object System.Collections.Hashtable ([System.StringComparer]::Ordinal) }
- if (-not $refGroups.Contains($rn.RefPath)) { $refGroups[$rn.RefPath] = New-Object System.Collections.Hashtable ([System.StringComparer]::Ordinal) }
- $pathGroups[$rn.Prefix][$rn.Old] = $rn.New
- $refGroups[$rn.RefPath][$rn.Old] = $rn.New
- }
- $pathCounts = @{}; $refCounts = @{}
- foreach ($pfx in $pathGroups.Keys) {
- if (-not (Test-Path -LiteralPath $formsDir)) { break }
- foreach ($fx in (Get-ChildItem -LiteralPath $formsDir -Recurse -File -Filter 'Form.xml')) {
- $c = Rename-FormDataPaths $fx.FullName $pfx $pathGroups[$pfx]
- foreach ($k in $c.Keys) { $pathCounts["$pfx|$k"] = $c[$k] + [int]$pathCounts["$pfx|$k"] }
- }
- }
- foreach ($rp in $refGroups.Keys) {
- $c = Rename-SubObjectRefs $rp $refGroups[$rp]
- foreach ($k in $c.Keys) { $refCounts["$rp|$k"] = $c[$k] }
- }
- foreach ($rn in $renames) {
- $cnt = [int]$pathCounts["$($rn.Prefix)|$($rn.Old)"]
- if ($cnt -gt 0) { Add-ActNote $rn.Row "form data paths updated: $cnt" $true }
- $refCnt = [int]$refCounts["$($rn.RefPath)|$($rn.Old)"]
- if ($refCnt -gt 0) { Add-ActNote $rn.Row "references in the extension XML updated: $refCnt" $true }
- Add-MentionsNote $rn.Row $rn.Old $rn.New $rn.TakenBy
- }
- if ($id.Kind -eq 'Renamed') {
- $row.Status = 'RENAMED'
- if (Test-EditAllowed) {
- if (Rename-BorrowedObject $typeName $objName $srcName $row) {
- Add-ActNote $row "renamed: $shown -> $srcName (files, ChildObjects, type references in the extension XML)" $true
- $oldSrc = Join-Path (Join-Path $cfgDir $dirName) "$shown.xml"
- $taken = if ((Test-Path -LiteralPath $oldSrc) -and (Read-SourceHead $oldSrc).Name -ceq $shown) { "$typeName.$shown" } else { '' }
- Add-MentionsNote $row $shown $srcName $taken
- return $srcName
- }
- } else {
- Add-ActNote $row "renamed in the source: $objName -> $srcName" $false
- }
- }
- return $objName
- }
- # Отчёт актуализации: строка на элемент, отложенные правки — с пометкой
- $script:actUnresolved = @()
- $script:objRenamed = @{}
- $script:subRenamed = @{}
- # Объекты, оставленные без изменений до решения человека (подмена, нет в источнике, дубль связи)
- $script:actBlocked = @{}
- $script:formRenamed = @{}
- function Write-ActReport {
- Resolve-PendingMentions
- if ($script:actRows.Count -eq 0) { return 0 }
- Write-Host ""
- Write-Host $(if ($script:actMode -eq 'Check') { "=== Actualization check ===" } else { "=== Actualization ===" })
- $notUpToDate = 0
- foreach ($r in $script:actRows) {
- if ($r.Optional -and $r.Notes.Count -eq 0 -and -not $r.Status) { continue }
- $changes = @($r.Notes | Where-Object { $_.Applied })
- $counted = @($r.Notes | Where-Object { -not $_.Info })
- $st = $r.Status
- if (-not $st) {
- if ($counted.Count -eq 0) { $st = 'UP-TO-DATE' }
- elseif ($script:actMode -eq 'Check') { $st = 'OUTDATED' }
- elseif ($changes.Count -gt 0) { $st = 'ACTUALIZED' }
- else { $st = 'OUTDATED' }
- }
- if ($st -ne 'UP-TO-DATE') { $notUpToDate++ }
- if ($st -eq 'REPLACED' -or $st -eq 'NOT FOUND' -or $st -eq 'NAME CONFLICT' -or $st -eq 'DUPLICATE LINK') { $script:actUnresolved += "$($r.Path) ($($st.ToLower()))" }
- Write-Host "[$st] $($r.Path)"
- foreach ($n in $r.Notes) { Write-Host " - $($n.Text)" }
- }
- return $notUpToDate
- }
- # Все заимствованные объекты расширения (область -Check / -Actualize без -Object)
- function Get-AllAdoptedItems {
- $res = @()
- foreach ($child in $script:childObjsEl.ChildNodes) {
- if ($child.NodeType -ne 'Element') { continue }
- $t = $child.LocalName; $n = $child.InnerText.Trim()
- if (-not $childTypeDirMap.ContainsKey($t) -or $t -eq 'Language') { continue }
- $f = Join-Path (Join-Path $extDir $childTypeDirMap[$t]) "$n.xml"
- if (-not (Test-Path -LiteralPath $f)) { continue }
- $head = [System.IO.File]::ReadAllText($f)
- if ($head -match '<ObjectBelonging>Adopted</ObjectBelonging>') { $res += "$t.$n" }
- }
- return $res
- }
- # Подобъект из -Object уже заимствован? (тогда его актуализируем, а не заимствуем)
- function Test-SubBorrowed($pi) {
- if (-not (Test-ObjectBorrowed $pi.TypeName $pi.ObjName)) { return $false }
- $objFile = Join-Path (Join-Path $extDir $pi.DirName) "$($pi.ObjName).xml"
- $text = [System.IO.File]::ReadAllText($objFile)
- $root = Get-MdRoot $text
- $co = Get-XmlChild $text $root 'ChildObjects'
- foreach ($c in (Get-XmlChildren $text $co)) {
- if ($c.Local -cne $pi.SubKind -or (Get-MdElementName $text $c) -cne $pi.SubName) { continue }
- if (-not $pi.ColName) { return $true }
- foreach ($cc in (Get-XmlChildren $text (Get-XmlChild $text $c 'ChildObjects'))) {
- if ($cc.Local -ceq 'Attribute' -and (Get-MdElementName $text $cc) -ceq $pi.ColName) { return $true }
- }
- return $false
- }
- return $false
- }
- # В заимствованной форме нет правок расширения: основная часть совпадает с BaseForm (так её и создаёт
- # заимствование). Тогда пересобрать её — например, с основным реквизитом — нечего терять.
- function Test-FormUnedited([string]$formXml) {
- if (-not (Test-Path -LiteralPath $formXml)) { return $false }
- $text = [System.IO.File]::ReadAllText($formXml)
- $form = Get-XmlElementAt $text ([regex]::Match($text, '<Form[\s>]').Index)
- if (-not $form) { return $false }
- $base = Get-XmlChild $text $form 'BaseForm'
- if (-not $base) { return $false }
- $main = New-Object System.Text.StringBuilder
- foreach ($c in (Get-XmlChildren $text $form)) { if ($c.Local -cne 'BaseForm') { $main.Append((Get-NormXml (Get-XmlOuter $text $c))) | Out-Null } }
- $orig = New-Object System.Text.StringBuilder
- foreach ($c in (Get-XmlChildren $text $base)) { $orig.Append((Get-NormXml (Get-XmlOuter $text $c))) | Out-Null }
- return ($main.ToString() -ceq $orig.ToString())
- }
- function Test-FormBorrowed($pi) {
- if ($pi.IsCommonForm) { return (Test-ObjectBorrowed $pi.TypeName $pi.ObjName) }
- $f = Join-Path (Join-Path (Join-Path (Join-Path $extDir $pi.DirName) $pi.ObjName) "Forms") "$($pi.FormName).xml"
- return (Test-Path -LiteralPath $f)
- }
- # С -BorrowMainAttribute реквизиты берутся у объекта из типа основного реквизита формы. Если это не
- # владелец формы и его нет в конфигурации-источнике, форма в расширении не загрузится — отказываем
- # до записи, расширение не трогаем.
- if ($BorrowMainAttribute) {
- foreach ($item in $items) {
- $pi = Split-BorrowItem $item
- # Неверный элемент и нет самой формы — об этом скажет основной цикл
- if ($pi.Error -or -not $pi.SrcFormXml -or -not (Test-Path $pi.SrcFormXml)) { continue }
- $pDoc = New-Object System.Xml.XmlDocument
- $pDoc.Load($pi.SrcFormXml)
- if ($pi.IsCommonForm) {
- $pOwner = Resolve-CommonFormOwner $pDoc.DocumentElement
- if (-not $pOwner -or $pOwner.Kind -ne 'Object') { continue }
- } else {
- $pOwner = Resolve-MainAttributeObject $pDoc.DocumentElement $pi.TypeName $pi.ObjName
- if ($pOwner.TypeName -eq $pi.TypeName -and $pOwner.ObjName -eq $pi.ObjName) { continue }
- }
- $pFound = $childTypeDirMap.ContainsKey($pOwner.TypeName) -and
- (Test-Path (Join-Path (Join-Path $cfgDir $childTypeDirMap[$pOwner.TypeName]) "$($pOwner.ObjName).xml"))
- if (-not $pFound) {
- Write-Error "Основной реквизит формы ${item} ссылается на $($pOwner.TypeName).$($pOwner.ObjName), а его нет в конфигурации-источнике — форма в расширении не загрузится. Расширение не изменено"
- exit 1
- }
- }
- }
- # Элементы разобраны и подобъекты найдены в источнике ДО записи: ошибка в любом элементе пакета —
- # расширение не тронуто
- $script:subObjectSources = @{}
- # Элементы, названные именем источника, но заимствованные под прежним, — к имени расширения
- $items = @($items | ForEach-Object { Resolve-ItemByLink $_ })
- foreach ($item in $items) {
- $pi = Split-BorrowItem $item
- if ($pi.Error) {
- Write-Error $pi.Error
- exit 1
- }
- if (-not $pi.SubKind) { continue }
- # Уже заимствованный подобъект актуализируется — его может не быть в источнике под этим именем
- if (Test-SubBorrowed $pi) { continue }
- $subSrc = Resolve-SubObjectSource $pi
- if ($subSrc.Error) {
- Write-Error "$($subSrc.Error). Extension not changed"
- exit 1
- }
- $script:subObjectSources[$item] = $subSrc
- }
- # Повтор по заимствованному и -Actualize — актуализация (с -Actualize без -Object — всё расширение); -Check — отчёт
- $script:actMode = if ($Check) { 'Check' } else { 'Apply' }
- if ($items.Count -eq 0) { $items = @(Get-AllAdoptedItems) }
- if ($Check) {
- foreach ($item in $items) {
- $pi = Split-BorrowItem $item
- if ($pi.SubKind) { $borrowed = Test-SubBorrowed $pi }
- elseif ($pi.FormName) { $borrowed = Test-FormBorrowed $pi }
- else { $borrowed = Test-ObjectBorrowed $pi.TypeName $pi.ObjName }
- if (-not $borrowed) {
- $nb = New-ActRow $item
- $nb.Status = 'NOT BORROWED'
- continue
- }
- if ($pi.SubKind) { Actualize-BorrowedObject $pi.TypeName $pi.ObjName @{ Kind = 'Sub'; SubKind = $pi.SubKind; SubName = $pi.SubName; ColName = $pi.ColName } | Out-Null }
- elseif ($pi.FormName -and -not $pi.IsCommonForm) { Actualize-BorrowedObject $pi.TypeName $pi.ObjName @{ Kind = 'Form'; FormName = $pi.FormName } | Out-Null }
- else { Actualize-BorrowedObject $pi.TypeName $pi.ObjName @{ Kind = 'Object' } | Out-Null }
- }
- $bad = Write-ActReport
- exit $(if ($bad -gt 0) { 1 } else { 0 })
- }
- foreach ($item in $items) {
- $pi = Split-BorrowItem $item
- if ($pi.Error) {
- Write-Error $pi.Error
- exit 1
- }
- # Объект переименован раньше в этом запуске (вслед за источником) — элемент пакета идёт под новым именем
- $origObjName = $pi.ObjName
- $renamedTo = $script:objRenamed["$($pi.TypeName).$($pi.ObjName)"]
- if ($renamedTo) {
- $item = $item -replace ('^([^.]+)\.' + [regex]::Escape($pi.ObjName) + '(?=\.|$)'), ('$1.' + $renamedTo.Replace('$', '$$'))
- $pi = Split-BorrowItem $item
- }
- # То же для подобъекта (и колонки ТЧ), переименованного раньше в этом запуске. Ключ — под тем именем
- # объекта, какое было при переименовании подобъекта: прежним, если объект переименован следом
- if ($pi.SubKind) {
- $subKey = "$($pi.TypeName).$($pi.ObjName).$($pi.SubKind).$($pi.SubName)"
- $oldKey = "$($pi.TypeName).$origObjName.$($pi.SubKind).$($pi.SubName)"
- $subNew = if ($script:subRenamed[$subKey]) { $script:subRenamed[$subKey] } else { $script:subRenamed[$oldKey] }
- $colNew = $null
- if ($pi.ColName) { $colNew = if ($script:subRenamed["$subKey.Attribute.$($pi.ColName)"]) { $script:subRenamed["$subKey.Attribute.$($pi.ColName)"] } else { $script:subRenamed["$oldKey.Attribute.$($pi.ColName)"] } }
- if ($subNew -or $colNew) {
- $item = "$($pi.TypeName).$($pi.ObjName).$($pi.SubKind).$(if ($subNew) { $subNew } else { $pi.SubName })"
- if ($pi.ColName) { $item += ".Attribute.$(if ($colNew) { $colNew } else { $pi.ColName })" }
- $pi = Split-BorrowItem $item
- }
- }
- # И для формы, переименованной раньше в этом запуске (ключ — под именем объекта на момент переименования)
- if ($pi.FormName -and -not $pi.IsCommonForm) {
- $fNew = $script:formRenamed["$($pi.TypeName).$($pi.ObjName).$($pi.FormName)"]
- if (-not $fNew) { $fNew = $script:formRenamed["$($pi.TypeName).$origObjName.$($pi.FormName)"] }
- if ($fNew) {
- $item = "$($pi.TypeName).$($pi.ObjName).Form.$fNew"
- $pi = Split-BorrowItem $item
- }
- }
- $typeName = $pi.TypeName; $objName = $pi.ObjName; $formName = $pi.FormName; $isCommonForm = $pi.IsCommonForm
- $dirName = $childTypeDirMap[$typeName]
- if ($pi.SubKind) {
- if (Test-SubBorrowed $pi) {
- Info "Actualizing ${item}..."
- $objName = Actualize-BorrowedObject $typeName $objName @{ Kind = 'Sub'; SubKind = $pi.SubKind; SubName = $pi.SubName; ColName = $pi.ColName }
- # ТЧ целиком просят под собственные реквизиты — то же предупреждение, что при первом заимствовании
- if ($pi.SubKind -ceq 'TabularSection' -and -not $pi.ColName) {
- if ($script:tsOwnColumnsBlocked -ccontains $typeName) {
- Warn " ${typeName}: own attributes cannot be added to a borrowed tabular section of this kind — the platform rejects them on database update"
- } elseif ($script:tsOwnColumnsFromPlatform.ContainsKey($typeName)) {
- Warn " ${typeName}: own attributes in a borrowed tabular section are accepted only from platform $($script:tsOwnColumnsFromPlatform[$typeName])"
- }
- }
- } else {
- Info "Borrowing ${item}..."
- Borrow-SubObject $pi $script:subObjectSources[$item]
- $borrowedCount++
- }
- } elseif ($formName) {
- # --- Form borrowing ---
- $formExists = Test-FormBorrowed $pi
- $verb = if ($formExists) { "Actualizing" } else { "Borrowing" }
- if ($isCommonForm) { Info "$verb common form ${typeName}.${objName}..." }
- else { Info "$verb form ${typeName}.${objName}.Form.${formName}..." }
- # Auto-borrow parent object if not yet borrowed
- if (-not $isCommonForm) { Ensure-ParentBorrowed $typeName $objName }
- $hasBMA = [bool]$BorrowMainAttribute
- $rebuildForm = $false
- if ($formExists) {
- # Уже заимствованную форму не переписываем: в Form.xml правки расширения
- if ($isCommonForm) { $newName = Actualize-BorrowedObject $typeName $objName @{ Kind = 'Object' } }
- else { $newName = Actualize-BorrowedObject $typeName $objName @{ Kind = 'Form'; FormName = $formName } }
- # Форма (и объект) могли переименоваться вслед за источником — дальше идём под новыми именами
- $newForm = if ($isCommonForm) { $null } else { $script:formRenamed["$typeName.$objName.$formName"] }
- if ($newName -cne $objName -or $newForm) {
- if ($newForm) { $formName = $newForm }
- $item = if ($isCommonForm) { "$typeName.$newName" } else { "$typeName.$newName.Form.$formName" }
- $pi = Split-BorrowItem $item
- $objName = $newName
- }
- if ($hasBMA) {
- $exFormXml = if ($isCommonForm) { Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Ext/Form.xml" }
- else { Join-Path (Join-Path (Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Forms") $formName) "Ext/Form.xml" }
- if ((Test-Path -LiteralPath $exFormXml) -and -not ([System.IO.File]::ReadAllText($exFormXml) -match '<MainAttribute>true</MainAttribute>')) {
- # Форма без основного реквизита: правок расширения нет — пересобираем с ним, есть — не трогаем
- if (Test-FormUnedited $exFormXml) {
- Info " The form has no edits of the extension — rebuilt with its main attribute"
- $rebuildForm = $true
- } else {
- Warn " The form is already borrowed without its main attribute and has edits of the extension; Form.xml is kept, so the attributes below are borrowed into the object but the form does not show them"
- }
- }
- }
- }
- if (-not $formExists -or $rebuildForm) {
- $formFiles = Borrow-Form $typeName $objName $formName -BorrowMainAttr:$hasBMA -Rebuild:$rebuildForm
- $script:borrowedFiles += $formFiles
- # Замер на 8.3.26: платформа помечает форму расширенной сразу при заимствовании,
- # даже если элементы не менялись. Флаг живёт в метаданных формы, не у владельца.
- Set-PropertyStateFlag $formFiles[0] "Form" $script:formatVersion
- if (-not $rebuildForm) { $borrowedCount++ }
- }
- # Borrow main attribute if requested
- if ($hasBMA -and $isCommonForm) {
- # У общей формы владельца нет — он выводится из типа основного реквизита
- $cfSrcFormXmlPath = $pi.SrcFormXml
- $cfDoc = New-Object System.Xml.XmlDocument
- $cfDoc.PreserveWhitespace = $true
- $cfDoc.Load($cfSrcFormXmlPath)
- $cfOwner = Resolve-CommonFormOwner $cfDoc.DocumentElement
- if (-not $cfOwner) {
- Info " Основной реквизит общей формы не ссылается на объект — заимствуется только сам реквизит"
- } elseif ($cfOwner.Kind -eq 'Constants') {
- Borrow-FormConstants $cfSrcFormXmlPath $cfOwner.MainName
- } else {
- Borrow-ObjectShell $cfOwner.TypeName $cfOwner.ObjName
- if (Test-ObjectBorrowed $cfOwner.TypeName $cfOwner.ObjName) {
- Borrow-MainAttribute $cfOwner.TypeName $cfOwner.ObjName $null $BorrowMainAttribute $cfSrcFormXmlPath
- }
- }
- } elseif ($hasBMA) {
- # Реквизиты заимствуются у объекта из типа основного реквизита: у формы обработки с
- # DocumentObject.X это X, и его нужно заимствовать — иначе форма не загрузится
- $srcFormXmlPath = $pi.SrcFormXml
- $maObj = @{ TypeName = $typeName; ObjName = $objName }
- if (Test-Path $srcFormXmlPath) {
- $maDoc = New-Object System.Xml.XmlDocument
- $maDoc.PreserveWhitespace = $true
- $maDoc.Load($srcFormXmlPath)
- $maObj = Resolve-MainAttributeObject $maDoc.DocumentElement $typeName $objName
- }
- if ($maObj.TypeName -eq $typeName -and $maObj.ObjName -eq $objName) {
- Borrow-MainAttribute $typeName $objName $formName $BorrowMainAttribute
- } else {
- Info " Основной реквизит формы — $($maObj.TypeName).$($maObj.ObjName): реквизиты заимствуются у него"
- Borrow-ObjectShell $maObj.TypeName $maObj.ObjName
- if (Test-ObjectBorrowed $maObj.TypeName $maObj.ObjName) {
- Borrow-MainAttribute $maObj.TypeName $maObj.ObjName $null $BorrowMainAttribute $srcFormXmlPath
- }
- }
- }
- } else {
- # --- Object borrowing (existing logic) ---
- $targetDir = Join-Path $extDir $dirName
- $targetFile = Join-Path $targetDir "${objName}.xml"
- # Уже заимствованный объект НЕ переписываем: в его XML лежат собственные реквизиты
- # расширения, заимствованные подобъекты и состояния, которые из источника не выводятся.
- # Повторный вызов — законный способ доделать модуль (-Module), а не переиздать заготовку.
- $src = $null
- $isNew = -not (Test-ObjectBorrowed $typeName $objName)
- if (-not $isNew) {
- Info "Actualizing ${typeName}.${objName}..."
- $objName = Actualize-BorrowedObject $typeName $objName @{ Kind = 'Object' }
- $targetFile = Join-Path $targetDir "${objName}.xml"
- } else {
- Info "Borrowing ${typeName}.${objName}..."
- $src = Read-SourceObject $typeName $objName
- Info " Source UUID: $($src.Uuid)"
- $borrowedXml = Build-BorrowedObjectXml $typeName $objName $src.Uuid $src.Properties
- if (-not (Test-Path $targetDir)) {
- New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
- }
- $enc = New-Object System.Text.UTF8Encoding($true)
- [System.IO.File]::WriteAllText($targetFile, $borrowedXml, $enc)
- Info " Created: $targetFile"
- }
- if ($isNew) {
- Add-ToChildObjects $typeName $objName
- # Определяемый тип — с оболочками объектов своего состава, как у Конфигуратора
- if ($src -and $typeName -eq "DefinedType" -and $src.Properties.ContainsKey("__TypeXml")) {
- foreach ($rt in (Collect-ReferenceTypes @($src.Properties["__TypeXml"]))) {
- Borrow-ObjectShell $rt.TypeName $rt.ObjName
- }
- }
- $script:borrowedFiles += $targetFile
- $borrowedCount++
- }
- # У заимствованного раньше модуль создаётся при явном вызове по объекту (-Object): у типа с единственным
- # модулем — всегда, у прочих — по -Module. Массовый -Actualize модулей не добавляет (оболочки остаются без них)
- if (($isNew -or $Module -or $Object) -and -not $script:actBlocked["$typeName.$objName"]) {
- foreach ($kind in (Resolve-ModuleKinds $typeName)) {
- $script:borrowedFiles += (New-BorrowedModuleFile $typeName $objName $kind)
- }
- }
- }
- }
- # --- 14. (хвост) Обмен именами: объект, уведённый на временное имя, получает своё новое имя, даже если
- # сам не был в области запуска — временное имя в расширении не остаётся
- foreach ($sw in $script:swapPending.ToArray()) {
- if ($script:objRenamed.ContainsKey("$($sw.TypeName).$($sw.Tmp)")) { continue }
- Actualize-BorrowedObject $sw.TypeName $sw.Tmp @{ Kind = 'Object' } | Out-Null
- }
- # --- 14a. Основные таблицы динамических списков заимствованных форм — оболочками ---
- # Объект основной таблицы списка обязан быть в расширении («Неверно указана главная таблица
- # динамического списка»), даже если форма принадлежит другому объекту. Для виртуальной таблицы или
- # ТЧ (InformationRegister.Цены.SliceLast) — объект по первым двум сегментам. До шага 14b: оболочке
- # справочника нужны и его владельцы.
- foreach ($dl in $script:dynListForms) {
- if ($dl.MainTable -match '^(\w+)\.(\w+)(?:\.\w+)*$' -and $childTypeDirMap.ContainsKey($Matches[1])) {
- $mtKind = $Matches[1]; $mtName = $Matches[2]
- if (-not (Test-ObjectBorrowed $mtKind $mtName)) {
- Info "Основная таблица динамического списка ${mtKind}.${mtName} — в расширение оболочкой"
- Borrow-ObjectShell $mtKind $mtName
- }
- }
- }
- # --- 14b. Владельцы заимствованных справочников ---
- # Ссылка в <Owners> должна вести на объект, который в расширении есть: иначе платформа падает при
- # загрузке (проверено — access violation, не сообщение об ошибке). Конфигуратор владельца
- # заимствует (эталон Issue66Example7_1: вместе со справочником перенесён и его ПВХ-владелец).
- # Проход общий и повторяется, пока находятся новые: у владельца может быть свой владелец.
- $ownerPass = 0
- while ($true) {
- $ownerPass++
- if ($ownerPass -gt 10) { break }
- $newOwners = @()
- foreach ($shell in (Get-ChildItem -Path $extDir -Filter "*.xml" -Recurse -File)) {
- $shellText = [System.IO.File]::ReadAllText($shell.FullName)
- if ($shellText -notmatch '<Owners>') { continue }
- foreach ($om in [regex]::Matches($shellText, '<xr:Item[^>]*>(\w+)\.(\w+)</xr:Item>')) {
- $oType = $om.Groups[1].Value; $oName = $om.Groups[2].Value
- if (-not $childTypeDirMap.ContainsKey($oType)) { continue }
- if (Test-ObjectBorrowed $oType $oName) { continue }
- if ($newOwners | Where-Object { $_.T -eq $oType -and $_.N -eq $oName }) { continue }
- $newOwners += @{ T = $oType; N = $oName }
- }
- }
- if ($newOwners.Count -eq 0) { break }
- foreach ($ow in $newOwners) {
- $owSrcFile = Join-Path (Join-Path $cfgDir $childTypeDirMap[$ow.T]) "$($ow.N).xml"
- if (-not (Test-Path $owSrcFile)) {
- Warn " Владелец $($ow.T).$($ow.N) не найден в источнике — ссылка останется висячей"
- continue
- }
- $owSrc = Read-SourceObject $ow.T $ow.N
- $owXml = Build-BorrowedObjectXml $ow.T $ow.N $owSrc.Uuid $owSrc.Properties
- $owDir = Join-Path $extDir $childTypeDirMap[$ow.T]
- if (-not (Test-Path $owDir)) { New-Item -ItemType Directory -Path $owDir -Force | Out-Null }
- $owFile = Join-Path $owDir "$($ow.N).xml"
- $owEnc = New-Object System.Text.UTF8Encoding($true)
- [System.IO.File]::WriteAllText($owFile, $owXml, $owEnc)
- Add-ToChildObjects $ow.T $ow.N
- $script:borrowedFiles += $owFile
- Info " Auto-borrowed owner: $($ow.T).$($ow.N)"
- }
- }
- # --- 14c. Тильда у путей полей динамических списков заимствованных форм ---
- # Запрос списка компилируется в контексте расширения, и что-то из него, чего там нет, делает
- # невалидными все поля списка («Неверный путь к данным»). Конфигуратор такие пути пишет с тильдой —
- # платформа разрешает их после наложения на основную конфигурацию. Тильду ставим, только если
- # список не разрешится в расширении (Get-DynListQueryUnresolved): лишняя тильда безвредна, но первая
- # выгрузка из базы её снимет — шум в истории файлов. У списка без ручного запроса поля — пути формы
- # по основной таблице: проверяем их как запрос «ВЫБРАТЬ Т.Поле… ИЗ <таблица> КАК Т». Решаем здесь,
- # по итоговому составу расширения (после 14a и 14b): реквизиты заимствуются уже после формы, в пакете —
- # и соседними формами. Помечаются привязки, которые платформа проверяет при загрузке: *DataPath
- # элементов (DataPath, FooterDataPath, RowPictureDataPath…) и <Field> в UseAlways; в форме и в
- # BaseForm. Сам список (DataPath без поля) — как есть; пути отбора и оформления (dcsset:/dcscor:)
- # не проверяются.
- foreach ($dl in $script:dynListForms) {
- $dlText = [System.IO.File]::ReadAllText($dl.File, [System.Text.Encoding]::UTF8)
- if ($dl.Manual) {
- $dlQuery = $dl.Query
- } else {
- if (-not $dl.MainTable) { continue }
- $dlPathPat = '<(?:\w*DataPath|Field)>~?' + [regex]::Escape($dl.MainName) + '\.([^<]+)<'
- $dlFields = @([regex]::Matches($dlText, $dlPathPat) | ForEach-Object { "Т." + $_.Groups[1].Value } | Select-Object -Unique)
- if ($dlFields.Count -eq 0) { continue }
- $dlQuery = "ВЫБРАТЬ " + ($dlFields -join ", ") + " ИЗ $($dl.MainTable) КАК Т"
- }
- $dlUnresolved = @(Get-DynListQueryUnresolved $dlQuery)
- if ($dlUnresolved.Count -eq 0) { continue }
- $dlFieldPat = '(<(?:\w*DataPath|Field)>)(?=' + [regex]::Escape($dl.MainName) + '\.)'
- $script:dlCount = 0
- $dlText = [regex]::Replace($dlText, $dlFieldPat, { param($m) $script:dlCount++; $m.Groups[1].Value + '~' })
- if ($script:dlCount -gt 0) {
- [System.IO.File]::WriteAllText($dl.File, $dlText, (New-Object System.Text.UTF8Encoding($true)))
- $dlShown = ($dlUnresolved | Select-Object -First 5) -join ', '
- if ($dlUnresolved.Count -gt 5) { $dlShown += ", …" }
- $dlRel = $dl.File.Substring($extDir.Length).TrimStart('\', '/') -replace '\\', '/'
- Info "Поля динамического списка ($dlRel): пути с тильдой ($($script:dlCount)) — список использует то, чего нет в расширении ($dlShown); разрешатся после наложения"
- }
- }
- # --- 15. Save modified Configuration.xml ---
- # Стиль исходника снимаем ДО записи: правка чужого файла наследует его BOM/EOL/заголовок
- # (#44/#46/#47), новый файл получает канон выгрузки. Зеркало _detect_xml_style в py-порту.
- $style = Detect-XmlStyle $extResolvedPath
- $settings = New-Object System.Xml.XmlWriterSettings
- $settings.Encoding = New-Object System.Text.UTF8Encoding($true)
- $settings.Indent = $false
- $settings.NewLineHandling = [System.Xml.NewLineHandling]::None
- $memStream = New-Object System.IO.MemoryStream
- $writer = [System.Xml.XmlWriter]::Create($memStream, $settings)
- $script:xmlDoc.Save($writer)
- $writer.Flush(); $writer.Close()
- $text = [System.Text.Encoding]::UTF8.GetString($memStream.ToArray())
- $memStream.Close()
- $text = Finalize-XmlText $text $style
- $writeBom = ($null -eq $style) -or $style.bom
- [System.IO.File]::WriteAllText($extResolvedPath, $text, (New-Object System.Text.UTF8Encoding($writeBom)))
- Info "Saved: $extResolvedPath"
- # --- 16. Summary ---
- Write-Host ""
- Write-Host "=== cfe-borrow summary ==="
- Write-Host " Extension: $extDir"
- Write-Host " Config: $cfgDir"
- Write-Host " Borrowed: $borrowedCount object(s)"
- foreach ($f in $script:borrowedFiles) {
- Write-Host " - $f"
- }
- Write-ActReport | Out-Null
- # Заимствованное, которое не удалось сопоставить с источником (пересоздано, пропало), осталось как было —
- # остальное применено, поэтому код 0, а не отказ; решение по ним — за человеком
- if ($script:actUnresolved.Count -gt 0) {
- $shown = ($script:actUnresolved | Select-Object -First 5) -join ', '
- if ($script:actUnresolved.Count -gt 5) { $shown += ", …" }
- Warn "$($script:actUnresolved.Count) element(s) left unresolved ($shown): all other changes are applied; these need a decision"
- }
- exit 0
.claude/skills/form-decompile/scripts/form-decompile.ps1 · Bundled script · 2,993 lines
- # form-decompile v0.160 — Decompile 1C managed Form.xml to JSON DSL (draft)
- # Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
- # ВНИМАНИЕ: раундтрип не гарантируется. Навык исключён из авто-использования моделью.
- [CmdletBinding(PositionalBinding=$false)]
- param(
- [Parameter(Mandatory)]
- [Alias('Path')]
- [string]$FormPath,
- [string]$OutputPath
- )
- $ErrorActionPreference = "Stop"
- [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
- # --- 0. Resolve and validate input ---
- if (-not (Test-Path $FormPath)) {
- Write-Error "Form not found: $FormPath"
- exit 1
- }
- $FormPath = (Resolve-Path $FormPath).ProviderPath
- $xmlDoc = New-Object System.Xml.XmlDocument
- $xmlDoc.PreserveWhitespace = $false
- $xmlDoc.Load($FormPath)
- $root = $xmlDoc.DocumentElement
- # Второй документ с сохранением whitespace — только для восстановления ТОЧНОГО числа пробелов
- # в whitespace-only <v8:content> (декорации-распорки без width: число пробелов = ширина). Основной
- # парс (PreserveWhitespace=false) не трогаем; элементная структура обоих документов идентична →
- # навигация по индекс-пути элементов (Resolve-WS). Загрузка лениво-безопасная.
- $script:xmlDocWS = $null
- try { $script:xmlDocWS = New-Object System.Xml.XmlDocument; $script:xmlDocWS.PreserveWhitespace = $true; $script:xmlDocWS.Load($FormPath) } catch { $script:xmlDocWS = $null }
- # Ring 2: not a managed Form
- if ($root.LocalName -ne 'Form') {
- [Console]::Error.WriteLine("form-decompile: корневой элемент <$($root.LocalName)> не <Form> — это не управляемая форма.")
- exit 2
- }
- # --- 1. Namespaces ---
- $NS_LF = "http://v8.1c.ru/8.3/xcf/logform"
- $NS_V8 = "http://v8.1c.ru/8.1/data/core"
- $NS_XR = "http://v8.1c.ru/8.3/xcf/readable"
- $NS_XSI = "http://www.w3.org/2001/XMLSchema-instance"
- $NS_DCSSET = "http://v8.1c.ru/8.1/data-composition-system/settings"
- $NS_DCSSCH = "http://v8.1c.ru/8.1/data-composition-system/schema"
- $NS_DCSCOR = "http://v8.1c.ru/8.1/data-composition-system/core"
- $NS_V8UI = "http://v8.1c.ru/8.1/data/ui"
- $NS_APP = "http://v8.1c.ru/8.2/managed-application/core"
- $ns = New-Object System.Xml.XmlNamespaceManager($xmlDoc.NameTable)
- $ns.AddNamespace("lf", $NS_LF)
- $ns.AddNamespace("v8", $NS_V8)
- $ns.AddNamespace("xr", $NS_XR)
- $ns.AddNamespace("xsi", $NS_XSI)
- $ns.AddNamespace("dcsset", $NS_DCSSET)
- $ns.AddNamespace("dcssch", $NS_DCSSCH)
- $ns.AddNamespace("dcscor", $NS_DCSCOR)
- $ns.AddNamespace("v8ui", $NS_V8UI)
- $ns.AddNamespace("app", $NS_APP)
- # Список с явным ключом набора (FieldValue/RowKey/RowNumber) без основной таблицы: ссылки в строке нет,
- # умный дефолт RowPictureDataPath = <Список>.DefaultPicture компилятор ему не ставит.
- function Test-DynListExplicitKey([string]$listName) {
- foreach ($a in $root.SelectNodes("lf:Attributes/lf:Attribute", $ns)) {
- if ($a.GetAttribute('name') -ne $listName) { continue }
- $kt = $a.SelectSingleNode("lf:Settings/lf:KeyType", $ns)
- $v = if ($null -ne $kt) { $kt.InnerText.Trim() } else { '' }
- return ($v -ne '' -and $v -ne 'Auto' -and $null -eq $a.SelectSingleNode("lf:Settings/lf:MainTable", $ns))
- }
- return $false
- }
- # Каноничные GUID пустых контейнеров ListSettings (умолчание платформы, ~90% форм).
- # Если ListSettings = пустой скелет с этими GUID → декомпилятор опускает настройки вовсе,
- # компилятор регенерит тот же скелет → чистый раундтрип.
- $CANON_FILTER_ID = 'dfcece9d-5077-440b-b6b3-45a5cb4538eb'
- $CANON_ORDER_ID = '88619765-ccb3-46c6-ac52-38e9c992ebd4'
- $CANON_CA_ID = 'b75fecce-942b-4aed-abc9-e6a02e460fb3'
- $CANON_ITEMS_ID = '911b6018-f537-43e8-a417-da56b22f9aec'
- # --- Вынос запроса динсписка в .sql рядом с output (зеркало skd-decompile) ---
- $script:outputDir = $null
- $script:outputBasename = $null
- if ($OutputPath) {
- $od = Split-Path -Parent $OutputPath
- if (-not $od) { $od = (Get-Location).ProviderPath }
- $script:outputDir = $od
- $script:outputBasename = [System.IO.Path]::GetFileNameWithoutExtension($OutputPath)
- }
- $script:queryFilesAccumulator = @()
- $script:queryFileNamesUsed = @{}
- # Запрос ≥3 строк + есть outputDir → вынести в `<basename>-<listName>.sql`, вернуть "@file".
- function Maybe-ExternalizeQuery {
- param([string]$queryText, [string]$listName)
- if (-not $queryText) { return $queryText }
- if (-not $script:outputDir) { return $queryText }
- $lineCount = ([regex]::Matches($queryText, "`n")).Count + 1
- if ($lineCount -lt 3) { return $queryText }
- $safe = ($listName -replace '[^\w\-]', '_'); if (-not $safe) { $safe = 'query' }
- $prefix = if ($script:outputBasename) { "$($script:outputBasename)-" } else { '' }
- $fileName = "$prefix$safe.sql"
- $suffix = 1
- while ($script:queryFileNamesUsed.ContainsKey($fileName)) { $suffix++; $fileName = "$prefix$safe`_$suffix.sql" }
- $script:queryFileNamesUsed[$fileName] = $true
- $script:queryFilesAccumulator += [ordered]@{ fileName = $fileName; text = $queryText }
- return "@$fileName"
- }
- function Save-QueryFiles {
- if ($script:queryFilesAccumulator.Count -eq 0) { return }
- if (-not $script:outputDir) { return }
- $enc = New-Object System.Text.UTF8Encoding($false)
- foreach ($qf in $script:queryFilesAccumulator) {
- [System.IO.File]::WriteAllText((Join-Path $script:outputDir $qf.fileName), $qf.text, $enc)
- }
- [Console]::Error.WriteLine("Saved $($script:queryFilesAccumulator.Count) external query file(s)")
- }
- # Есть ли в ListSettings содержательные настройки (реальные items фильтра/порядка/
- # условного оформления/параметров)? Пустой скелет (только viewMode+GUID) → false:
- # декомпилятор опускает настройки, компилятор регенерит каноничный скелет, harness
- # нормализует GUID → чистый раундтрип. true → контент захватывается (см. ниже).
- function Test-ListSettingsHasContent {
- param($lsNode)
- if (-not $lsNode) { return $false }
- foreach ($cont in @('filter','order','conditionalAppearance','dataParameters')) {
- $cn = $lsNode.SelectSingleNode("dcsset:$cont", $ns)
- if ($cn -and $cn.SelectSingleNode("dcsset:item", $ns)) { return $true }
- }
- return $false
- }
- # Форма ListSettings: ordered-карта present top-level элементов (filter/order/conditionalAppearance →
- # блок-мета 'v'/'u'/'vu'/''; itemsViewMode/itemsUserSettingID → $true). Возвращает $null, если форма ==
- # полному каноничному скелету (компилятор регенерит сам) ИЛИ содержит неподдержанные top-level элементы
- # (item/dataParameters/viewMode/userSettingID/… → fallback на канон). Иначе — дескриптор для компилятора.
- function Get-ListSettingsShape {
- param($lsNode, [bool]$hasGrouping = $false)
- if (-not $lsNode) { return $null }
- $shape = [ordered]@{}
- foreach ($child in $lsNode.ChildNodes) {
- if ($child.NodeType -ne [System.Xml.XmlNodeType]::Element) { continue }
- $tag = $child.LocalName
- if ($tag -in @('filter','order','conditionalAppearance')) {
- $hasVM = $null -ne $child.SelectSingleNode("dcsset:viewMode", $ns)
- $hasUS = $null -ne $child.SelectSingleNode("dcsset:userSettingID", $ns)
- $code = "$(if ($hasVM) {'v'})$(if ($hasUS) {'u'})"
- # Контейнер может нести собственный <dcsset:userSettingPresentation> (кастомная подпись
- # настройки) — сохраняем форму по xsi:type (Get-PresByType: ru-only LocalString ≠ xs:string).
- $uspNode = $child.SelectSingleNode("dcsset:userSettingPresentation", $ns)
- if ($uspNode) {
- $usp = Get-PresByType $uspNode
- $shape[$tag] = [ordered]@{ meta = $code; presentation = $usp }
- } else { $shape[$tag] = $code }
- } elseif ($tag -eq 'itemsViewMode') { $shape['itemsViewMode'] = $true }
- elseif ($tag -eq 'itemsUserSettingID') { $shape['itemsUserSettingID'] = $true }
- elseif ($tag -eq 'itemsUserSettingPresentation') { $shape['itemsUserSettingPresentation'] = Get-PresByType $child } # items-уровневая подпись (форма по xsi:type)
- elseif ($tag -eq 'dataParameters') { $shape['dataParameters'] = $true } # значения параметров запроса (контент в settings.dataParameters)
- elseif ($tag -eq 'item') { if ($hasGrouping) { $shape['structure'] = $true } else { return $null } }
- else { return $null } # неизвестный top-level → канон-fallback
- }
- # Полный каноничный скелет → опускаем (компилятор регенерит)
- if ($shape.Count -eq 5 -and $shape['filter'] -eq 'vu' -and $shape['order'] -eq 'vu' -and `
- $shape['conditionalAppearance'] -eq 'vu' -and $shape['itemsViewMode'] -eq $true -and $shape['itemsUserSettingID'] -eq $true) { return $null }
- return $shape
- }
- # Группировка строк динамического списка: цепочка <dcsset:item StructureItemGroup> (каждый уровень =
- # один groupItems-field; вложенность через дочерний <dcsset:item>). Возвращает ПЛОСКИЙ массив уровней
- # (string для дефолтного поля; объект {field,groupType?,periodAdditionType?,periodAdditionBegin?,periodAdditionEnd?}
- # для нестандартного) ИЛИ $null, если структура не «чистая линейная цепочка одно-польных уровней»
- # (ветвление/мультиполе/доп.содержимое) → честный fallback на канон (LOST), а не тихая порча.
- function Build-GroupLevel {
- param($fn)
- $field = Get-Child $fn 'field'
- $gt = Get-Child $fn 'groupType'
- $pat = Get-Child $fn 'periodAdditionType'
- $pabN = $fn.SelectSingleNode("dcsset:periodAdditionBegin", $ns)
- $paeN = $fn.SelectSingleNode("dcsset:periodAdditionEnd", $ns)
- $pab = $null; $pae = $null
- if ($pabN) { $pt = $pabN.GetAttribute("type", $NS_XSI); $pv = $pabN.InnerText; if (($pt -match 'Field$') -or ($pv -and $pv -ne '0001-01-01T00:00:00')) { $pab = $pv } }
- if ($paeN) { $pt = $paeN.GetAttribute("type", $NS_XSI); $pv = $paeN.InnerText; if (($pt -match 'Field$') -or ($pv -and $pv -ne '0001-01-01T00:00:00')) { $pae = $pv } }
- $isDefault = ((-not $gt) -or $gt -eq 'Items') -and ((-not $pat) -or $pat -eq 'None') -and (-not $pab) -and (-not $pae)
- if ($isDefault) { return $field }
- $o = [ordered]@{ field = $field }
- if ($gt -and $gt -ne 'Items') { $o['groupType'] = $gt }
- if ($pat -and $pat -ne 'None') { $o['periodAdditionType'] = $pat }
- if ($pab) { $o['periodAdditionBegin'] = $pab }
- if ($pae) { $o['periodAdditionEnd'] = $pae }
- return $o
- }
- function Build-ListGrouping {
- param($itemNode)
- $levels = New-Object System.Collections.ArrayList
- $cur = $itemNode
- while ($cur) {
- if (($cur.GetAttribute("type", $NS_XSI)) -notmatch 'StructureItemGroup$') { return $null }
- $gi = $null; $nested = @()
- foreach ($ch in $cur.ChildNodes) {
- if ($ch.NodeType -ne [System.Xml.XmlNodeType]::Element) { continue }
- switch ($ch.LocalName) {
- 'groupItems' { if ($gi) { return $null }; $gi = $ch }
- 'item' { $nested += $ch }
- default { return $null } # use/name/filter/order/… — здесь не поддержано
- }
- }
- if (-not $gi) { return $null }
- $fieldItems = @($gi.SelectNodes("dcsset:item", $ns))
- if ($fieldItems.Count -ne 1) { return $null }
- $fn = $fieldItems[0]
- if (($fn.GetAttribute("type", $NS_XSI)) -notmatch 'GroupItemField$') { return $null }
- [void]$levels.Add((Build-GroupLevel $fn))
- if ($nested.Count -eq 0) { break }
- if ($nested.Count -gt 1) { return $null } # ветвление — не линейно
- $cur = $nested[0]
- }
- if ($levels.Count -eq 0) { return $null }
- return ,@($levels)
- }
- # --- 1b. Ring-3 scan: конструкции вне зоны поддержки (draft list) ---
- function Fail-Ring3 {
- param([string]$kind, [string]$loc)
- [Console]::Error.WriteLine("form-decompile: декомпиляция пока не поддерживает $kind (path: $loc)")
- [Console]::Error.WriteLine("Для точечной работы с этой формой используй /form-edit.")
- exit 3
- }
- # ConditionalAppearance со scope (привязка к области) пока не воспроизводим — fail-ring3 только в этом случае.
- foreach ($el in $xmlDoc.SelectNodes("//*[local-name()='ConditionalAppearance']/*[local-name()='item']/*[local-name()='scope'][node()]")) { Fail-Ring3 -kind "ConditionalAppearance со scope" -loc "form/ConditionalAppearance/item/scope" }
- # Реквизит с design-time конфигурацией (<Settings> chart-типа: Диаграмма/ДиаграммаГанта/… —
- # d4p1:GanttChart и т.п.). Поддержаны только TypeDescription (valueType) и DynamicList; прочие
- # (встроенная конфигурация диаграммы) пока НЕ воспроизводим → честный скип, чтобы не потерять молча.
- foreach ($s in $xmlDoc.SelectNodes("//*[local-name()='Attribute']/*[local-name()='Settings']")) {
- $st = $s.GetAttribute("type", $NS_XSI)
- if ($st -and $st -notmatch 'TypeDescription$' -and $st -notmatch 'DynamicList$' -and $st -notmatch 'Planner$' -and $st -notmatch 'd4p1:(Gantt)?Chart$') {
- Fail-Ring3 -kind "Attribute>Settings типа '$st' (design-time конфигурация, напр. диаграмма)" -loc "Attribute/Settings"
- }
- # Chart/GanttChart с точками/осями: типизированные значения (xsi:type), xsi:nil и ML с
- # префиксом d4p1: (а не v8:) генерик-движок не сохраняет → честный скип. Частые
- # дашборд-диаграммы/гант (серии/легенда/оформление/шкала) поддержаны.
- elseif ($st -match 'd4p1:(Gantt)?Chart$' -and ($s.OuterXml -match '<d4p1:\w+ xsi:type=' -or $s.OuterXml -match '<d4p1:\w+ xsi:nil=' -or $s.OuterXml -match '<d4p1:item[ >]')) {
- Fail-Ring3 -kind "Attribute>Settings $st с точками/осями (типизированные значения/d4p1-ML)" -loc "Attribute/Settings"
- }
- }
- # --- 1c. Compact JSON serializer (созвучно skd-decompile: 2-проб. indent, inline в пределах lineLimit) ---
- function Convert-StringToJsonLiteral {
- param([string]$s)
- if ($null -eq $s) { return 'null' }
- $sb = New-Object System.Text.StringBuilder
- [void]$sb.Append('"')
- foreach ($ch in $s.ToCharArray()) {
- $code = [int]$ch
- if ($code -eq 0x22) { [void]$sb.Append('\"') }
- elseif ($code -eq 0x5C) { [void]$sb.Append('\\') }
- elseif ($code -eq 0x08) { [void]$sb.Append('\b') }
- elseif ($code -eq 0x09) { [void]$sb.Append('\t') }
- elseif ($code -eq 0x0A) { [void]$sb.Append('\n') }
- elseif ($code -eq 0x0C) { [void]$sb.Append('\f') }
- elseif ($code -eq 0x0D) { [void]$sb.Append('\r') }
- elseif ($code -lt 0x20) { [void]$sb.AppendFormat('\u{0:x4}', $code) }
- else { [void]$sb.Append($ch) }
- }
- [void]$sb.Append('"')
- return $sb.ToString()
- }
- function Try-InlineJson {
- param($obj)
- if ($null -eq $obj) { return 'null' }
- if ($obj -is [bool]) { if ($obj) { return 'true' } else { return 'false' } }
- if ($obj -is [string]) { return (Convert-StringToJsonLiteral $obj) }
- if ($obj -is [int] -or $obj -is [long]) { return "$obj" }
- if ($obj -is [double] -or $obj -is [single] -or $obj -is [decimal]) {
- return ([System.Convert]::ToString($obj, [System.Globalization.CultureInfo]::InvariantCulture))
- }
- if ($obj -is [System.Collections.IDictionary]) {
- if ($obj.Count -eq 0) { return '{}' }
- $parts = @()
- foreach ($k in $obj.Keys) {
- $v = Try-InlineJson $obj[$k]
- if ($null -eq $v) { return $null }
- $parts += "$(Convert-StringToJsonLiteral "$k"): $v"
- }
- return '{ ' + ($parts -join ', ') + ' }'
- }
- if ($obj -is [array] -or $obj -is [System.Collections.IList]) {
- $items = @($obj)
- if ($items.Count -eq 0) { return '[]' }
- $parts = @()
- foreach ($it in $items) {
- $v = Try-InlineJson $it
- if ($null -eq $v) { return $null }
- $parts += $v
- }
- return '[' + ($parts -join ', ') + ']'
- }
- return $null
- }
- function ConvertTo-CompactJson {
- param($obj, [int]$depth = 0, [string]$indentUnit = ' ', [int]$lineLimit = 120)
- $indent = $indentUnit * $depth
- $childIndent = $indentUnit * ($depth + 1)
- if ($null -eq $obj) { return 'null' }
- if ($obj -is [bool]) { if ($obj) { return 'true' } else { return 'false' } }
- if ($obj -is [string]) { return (Convert-StringToJsonLiteral $obj) }
- if ($obj -is [int] -or $obj -is [long]) { return "$obj" }
- if ($obj -is [double] -or $obj -is [single] -or $obj -is [decimal]) {
- return ([System.Convert]::ToString($obj, [System.Globalization.CultureInfo]::InvariantCulture))
- }
- $isContainer = ($obj -is [System.Collections.IDictionary]) -or ($obj -is [array]) -or ($obj -is [System.Collections.IList])
- if ($isContainer) {
- $inlineAttempt = Try-InlineJson $obj
- if ($null -ne $inlineAttempt -and ($indent.Length + $inlineAttempt.Length) -le $lineLimit) { return $inlineAttempt }
- }
- if ($obj -is [System.Collections.IDictionary]) {
- $keys = @($obj.Keys)
- if ($keys.Count -eq 0) { return '{}' }
- $parts = @()
- foreach ($k in $keys) {
- $val = ConvertTo-CompactJson -obj $obj[$k] -depth ($depth + 1) -indentUnit $indentUnit -lineLimit $lineLimit
- $parts += "$childIndent$(Convert-StringToJsonLiteral "$k"): $val"
- }
- return "{`n" + ($parts -join ",`n") + "`n$indent}"
- }
- if ($obj -is [array] -or $obj -is [System.Collections.IList]) {
- $items = @($obj)
- if ($items.Count -eq 0) { return '[]' }
- $parts = @($items | ForEach-Object { "$childIndent$(ConvertTo-CompactJson -obj $_ -depth ($depth + 1) -indentUnit $indentUnit -lineLimit $lineLimit)" })
- return "[`n" + ($parts -join ",`n") + "`n$indent]"
- }
- return (Convert-StringToJsonLiteral "$obj")
- }
- # --- 2. Helpers ---
- # Companion-элементы (авто-генерируемые компилятором) — пропускаем при обходе детей.
- # Дополнения (Search*/ViewStatus) БОЛЬШЕ не companion — декомпилируются как тип-элементы
- # (кастомные в AutoCommandBar/ChildItems → commandBar.children; стандартные на уровне таблицы → карта additions).
- $COMPANION_TAGS = @('ContextMenu','ExtendedTooltip','AutoCommandBar')
- # Извлечь мультиязычный Title/Presentation → string (ru) или ordered hash {ru,en,...}
- function Get-LangText {
- param($node)
- if ($null -eq $node) { return $null }
- $items = @($node.SelectNodes("v8:item", $ns))
- if ($items.Count -eq 0) { return $null }
- $map = [ordered]@{}
- foreach ($it in $items) {
- $lang = $it.SelectSingleNode("v8:lang", $ns)
- $content = $it.SelectSingleNode("v8:content", $ns)
- if ($lang) { $map[$lang.InnerText] = if ($content) { $content.InnerText } else { "" } }
- }
- if ($map.Count -eq 1 -and $map.Contains('ru')) { return $map['ru'] }
- return $map
- }
- # Get-LangText с восстановлением значимого пробела: PreserveWhitespace=false стрипает
- # <v8:content> </v8:content> → "" (неотличимо от суппресса). Платформа НЕ эмитит пустой
- # Title/ToolTip, значит исходно был пробел → возвращаем " " (как Get-MLFormattedValue).
- # Покрывает и одиночную строку (ru-only), и мультиязычную мапу (напр. декорация-разделитель
- # «Пробел» с ru+en пробелами): восстанавливаем " " в каждом языке, где content-узел есть, но пуст.
- # Точное число пробелов whitespace-only <v8:content> из PreserveWhitespace-документа (основной
- # парс стрипает его в ""). Навигация по индекс-пути элементов (структура обоих документов идентична).
- function Resolve-WS {
- param($contentNode)
- if (-not $contentNode -or -not $script:xmlDocWS) { return $null }
- $idxs = New-Object System.Collections.ArrayList
- $cur = $contentNode
- while ($cur.ParentNode -and $cur.ParentNode.NodeType -eq [System.Xml.XmlNodeType]::Element) {
- $i = 0; $sib = $cur.PreviousSibling
- while ($sib) { if ($sib.NodeType -eq [System.Xml.XmlNodeType]::Element) { $i++ }; $sib = $sib.PreviousSibling }
- [void]$idxs.Insert(0, $i)
- $cur = $cur.ParentNode
- }
- $wcur = $script:xmlDocWS.DocumentElement
- foreach ($ix in $idxs) {
- $els = @(); foreach ($ch in $wcur.ChildNodes) { if ($ch.NodeType -eq [System.Xml.XmlNodeType]::Element) { $els += $ch } }
- if ($ix -ge $els.Count) { return $null }
- $wcur = $els[$ix]
- }
- return $wcur.InnerText
- }
- # Точное восстановление пробела (число): whitespace-only content → реальная строка пробелов из WS-дока.
- function Restore-WSContent {
- param($contentNode)
- $ws = Resolve-WS $contentNode
- if ($ws -and $ws.Trim() -eq '') { return $ws } # только если действительно whitespace
- return ' '
- }
- function Get-LangTextWS {
- param($node)
- $t = Get-LangText $node
- if ($null -eq $t) { return $null }
- if ($t -is [string]) {
- $cn = $node.SelectSingleNode("v8:item/v8:content", $ns)
- if ($t -eq '' -and $cn) { return (Restore-WSContent $cn) }
- return $t
- }
- foreach ($it in @($node.SelectNodes("v8:item", $ns))) {
- $lang = $it.SelectSingleNode("v8:lang", $ns)
- $content = $it.SelectSingleNode("v8:content", $ns)
- if ($lang -and $content -and $t.Contains($lang.InnerText) -and $t[$lang.InnerText] -eq '') {
- $t[$lang.InnerText] = (Restore-WSContent $content)
- }
- }
- return $t
- }
- # Авто-вывод заголовка из имени — ТОЧНОЕ зеркало Title-FromName из form-compile.
- # Нужен, чтобы опускать ru-only заголовки, которые компилятор воспроизведёт сам.
- function Title-FromName {
- param([string]$name)
- if (-not $name) { return '' }
- $s = [regex]::Replace($name, '([А-ЯA-Z])([А-ЯA-Z][а-яa-z])', '$1 $2')
- $s = [regex]::Replace($s, '([а-яa-z0-9])([А-ЯA-Z])', '$1 $2')
- $parts = $s -split ' '
- if ($parts.Count -eq 0) { return $s }
- $out = New-Object System.Collections.ArrayList
- [void]$out.Add($parts[0])
- for ($i = 1; $i -lt $parts.Count; $i++) {
- $p = $parts[$i]
- if ($p.Length -gt 1 -and $p -ceq $p.ToUpper()) {
- [void]$out.Add($p)
- } else {
- [void]$out.Add($p.ToLower())
- }
- }
- return ($out -join ' ')
- }
- # Детектор «настоящей» inline-разметки форматированного текста (идентичен form-compile!).
- $script:fmtMarkupRe = '</>|<\s*(?:link|b|i|u|s|color|colorStyle|bgColor|bgColorStyle|font|fontSize|fontStyle|img)(?:\s|>)'
- function Test-HasRealMarkup {
- param($text)
- if ($null -eq $text) { return $false }
- $vals = if ($text -is [System.Collections.IDictionary]) { @($text.Values) }
- elseif ($text -is [System.Management.Automation.PSCustomObject]) { @($text.PSObject.Properties.Value) }
- else { @("$text") }
- foreach ($v in $vals) { if ("$v" -match $script:fmtMarkupRe) { return $true } }
- return $false
- }
- # Title-узел → DSL-значение ML-поля (гибрид): строка/мапа когда авто-детект formatted
- # совпал с атрибутом; иначе явный {text, formatted}.
- function Get-MLFormattedValue {
- param($titleNode)
- if (-not $titleNode) { return $null }
- # Get-LangTextWS восстанавливает значимый пробел в <v8:content> </v8:content> (одиночный и
- # мультиязычный случай) — иначе декорация-разделитель «Пробел» спуталась бы с суппресс-маркером "".
- $text = Get-LangTextWS $titleNode
- if ($null -eq $text) { return $null }
- $fmtAttr = ($titleNode.GetAttribute('formatted') -eq 'true')
- if ($fmtAttr -eq (Test-HasRealMarkup $text)) { return $text }
- $o = [ordered]@{}; $o['text'] = $text; $o['formatted'] = $fmtAttr; return $o
- }
- # Прочитать дочерний скаляр (по local-name, без namespace)
- function Get-Child {
- param($node, [string]$name)
- $c = $node.SelectSingleNode("*[local-name()='$name']")
- if ($c) { return $c.InnerText } else { return $null }
- }
- function Has-Child { param($node, [string]$name) return $null -ne $node.SelectSingleNode("*[local-name()='$name']") }
- function To-Bool { param([string]$v) return ($v -eq 'true') }
- # Значение с учётом xsi:type → нативный JSON-тип (число/булево/строка).
- # Нужно, чтобы авто-детект типа в компиляторе восстановил тот же xsi:type.
- function Convert-TypedValue {
- param([string]$raw, [string]$xsiType)
- switch -regex ($xsiType) {
- 'decimal$' {
- if ($raw -match '^-?\d+$') { return [int]$raw }
- return [double]::Parse($raw, [System.Globalization.CultureInfo]::InvariantCulture)
- }
- 'boolean$' { return ($raw -eq 'true') }
- default { return $raw }
- }
- }
- # =====================================================================
- # Захват настроек компоновщика динамического списка (ListSettings):
- # filter / order / conditionalAppearance. Логика портирована из навыка
- # skd-decompile (Build-FilterItem/Build-Order/Build-ConditionalAppearance
- # и сериализаторы оформления). Механизм New-Sentinel/Add-Warning из skd
- # заменён на запись в stderr + пропуск элемента (form-decompile — draft,
- # скрипт не падает на непокрытых конструкциях).
- # =====================================================================
- # Прочитать дочерний скаляр по xpath (с $ns). Аналог skd Get-Text.
- function Get-Text {
- param($node, [string]$xpath)
- if (-not $node) { return $null }
- if ([string]::IsNullOrEmpty($xpath)) { return $node.InnerText }
- $n = $node.SelectSingleNode($xpath, $ns)
- if ($n) { return $n.InnerText } else { return $null }
- }
- # Мультиязычный текст (LocalStringType) → string (ru) или ordered hash.
- # Алиас на уже существующий Get-LangText (тот же контракт).
- function Get-MLText { param($node) return (Get-LangText $node) }
- # Презентация: либо мультиязычный LocalStringType, либо плоский xs:string.
- # Get-MLText даёт $null для xs:string (нет v8:item) → откат к InnerText.
- function Get-PresText {
- param($node)
- if (-not $node) { return $null }
- $ml = Get-MLText $node
- if ($null -ne $ml) { return $ml }
- if ($node.InnerText) { return $node.InnerText }
- return $null
- }
- # Presentation, сохраняющий ФОРМУ по xsi:type (не схлопывает ru-only LocalStringType в строку):
- # <… xsi:type="v8:LocalStringType"> → объект {lang:text} (даже один ru), иначе xs:string → плоская строка.
- # Нужно, чтобы компилятор воспроизвёл точный xsi:type (LocalStringType vs xs:string). Пустой LocalStringType → $null.
- function Get-PresByType {
- param($node)
- if (-not $node) { return $null }
- $xt = $node.GetAttribute("type", $NS_XSI)
- if ($xt -match 'LocalStringType$') {
- $d = [ordered]@{}
- foreach ($it in $node.SelectNodes("v8:item", $ns)) {
- $lang = Get-Text $it "v8:lang"; $content = Get-Text $it "v8:content"
- if ($lang) { $d[$lang] = $content }
- }
- if ($d.Count -gt 0) { return $d }
- return $null
- }
- if ($node.InnerText) { return $node.InnerText }
- return $null
- }
- # Снять namespace-префикс с xsi:type ("dcsset:Foo" → "Foo")
- function Get-LocalXsiType {
- param($node)
- if (-not $node) { return $null }
- $t = $node.GetAttribute("type", $NS_XSI)
- if ($t -match ':(.+)$') { return $matches[1] }
- return $t
- }
- # Шрифт оформления → объект {@type:Font, ...} (bit-perfect для compile).
- function Get-FontValue {
- param($valNode)
- $f = [ordered]@{ '@type' = 'Font' }
- foreach ($attrName in @('ref','faceName','height','bold','italic','underline','strikeout','kind','scale')) {
- $a = $valNode.Attributes[$attrName]
- if ($null -ne $a) { $f[$attrName] = $a.Value }
- }
- return $f
- }
- # Линия (граница) оформления → объект {@type:Line, width, gap, style}.
- function Get-LineValue {
- param($valNode)
- $obj = [ordered]@{ '@type' = 'Line' }
- $w = $valNode.GetAttribute("width")
- $g = $valNode.GetAttribute("gap")
- if ($w -ne '') { $obj['width'] = if ($w -match '^-?\d+$') { [int]$w } else { $w } }
- if ($g -ne '') { $obj['gap'] = ($g -eq 'true') }
- $styleNode = $valNode.SelectSingleNode("v8ui:style", $ns)
- if ($styleNode) { $obj['style'] = $styleNode.InnerText }
- return $obj
- }
- # Прочитать <dcscor:value> в JSON-значение: Font/Line/Field/multilang/raw text.
- function Read-AppearanceValueNode {
- param($valNode)
- if (-not $valNode) { return $null }
- $vt = Get-LocalXsiType $valNode
- if ($vt -eq 'LocalStringType') {
- # НЕ схлопываем одноязычный в строку: значение параметра оформления различает
- # xs:string (плоская строка) и LocalStringType (локализуемый текст) — обе формы
- # одноязычно дают одну строку. Всегда объект-карта языков → компилятор эмитит LocalStringType.
- $map = [ordered]@{}
- foreach ($it in @($valNode.SelectNodes("v8:item", $ns))) {
- $lang = $it.SelectSingleNode("v8:lang", $ns); $content = $it.SelectSingleNode("v8:content", $ns)
- if ($lang) { $map[$lang.InnerText] = if ($content) { $content.InnerText } else { "" } }
- }
- return $map
- }
- if ($vt -eq 'Font') { return (Get-FontValue $valNode) }
- if ($vt -eq 'Line') { return (Get-LineValue $valNode) }
- # dcscor:Field — значение = ссылка на поле компоновки → объект {field:путь}
- if ($vt -eq 'Field') { return [ordered]@{ field = $valNode.InnerText } }
- return $valNode.InnerText
- }
- # Обратная карта comparisonType → короткий оператор фильтра (зеркало skd).
- $script:filterOpMap = @{
- 'Equal'='='; 'NotEqual'='<>'; 'Greater'='>'; 'GreaterOrEqual'='>=';
- 'Less'='<'; 'LessOrEqual'='<='; 'InList'='in'; 'NotInList'='notIn';
- 'InHierarchy'='inHierarchy'; 'InListByHierarchy'='inListByHierarchy';
- 'Contains'='contains'; 'NotContains'='notContains';
- 'BeginsWith'='beginsWith'; 'NotBeginsWith'='notBeginsWith';
- 'Like'='like'; 'NotLike'='notLike';
- 'Filled'='filled'; 'NotFilled'='notFilled'
- }
- # Render filter value node → shorthand-acceptable scalar string
- function Get-FilterValue {
- param($valNode)
- if (-not $valNode) { return '_' }
- $nil = $valNode.GetAttribute("nil", $NS_XSI)
- if ($nil -eq 'true') { return '_' }
- $vType = Get-LocalXsiType $valNode
- if ($vType -eq 'DesignTimeValue') { return $valNode.InnerText }
- if ($vType -eq 'LocalStringType') { return (Get-MLText $valNode) }
- $txt = $valNode.InnerText
- if (-not $txt) { return '_' }
- return $txt
- }
- # Get-FilterValue + xsi:type значения (для valueType, например dcscor:Field).
- function Get-FilterValueWithType {
- param($valNode)
- if (-not $valNode) { return @{ value = '_'; type = $null } }
- $rawType = $valNode.GetAttribute("type", $NS_XSI)
- $nil = $valNode.GetAttribute("nil", $NS_XSI)
- if ($nil -eq 'true') { return @{ value = '_'; type = $null } }
- $vType = Get-LocalXsiType $valNode
- if ($vType -eq 'LocalStringType') {
- return @{ value = (Get-MLText $valNode); type = $rawType }
- }
- # Стандартная дата начала/окончания. Формы (от самой компактной):
- # SBD Custom+date → голая ISO-дата без valueType (компилятор выводит SBD Custom — дефолт
- # даты в фильтре, корпус 268 vs 2 xs:dateTime); именованный вариант → строка + valueType;
- # SED Custom / нетипичное → объект {variant, date} + valueType. Иначе InnerText склеивал.
- if ($vType -eq 'StandardBeginningDate' -or $vType -eq 'StandardEndDate') {
- $variantN = $valNode.SelectSingleNode("v8:variant", $ns)
- $dateN = $valNode.SelectSingleNode("v8:date", $ns)
- $variantStr = if ($variantN) { $variantN.InnerText } else { '' }
- if ($dateN) {
- if ($vType -eq 'StandardBeginningDate' -and $variantStr -eq 'Custom') {
- return @{ value = $dateN.InnerText; type = $null } # голая дата = SBD Custom шорткат
- }
- return @{ value = [ordered]@{ variant = $variantStr; date = $dateN.InnerText }; type = $rawType }
- }
- return @{ value = $variantStr; type = $rawType } # именованный вариант
- }
- $txt = $valNode.InnerText
- if (-not $txt) { return @{ value = '_'; type = $rawType } }
- if ($vType -eq 'boolean') { return @{ value = ($txt -eq 'true'); type = $rawType } }
- if ($vType -eq 'decimal') {
- if ($txt -match '^-?\d+$') { return @{ value = [int]$txt; type = $rawType } }
- return @{ value = [double]$txt; type = $rawType }
- }
- return @{ value = $txt; type = $rawType }
- }
- # Convert filter item node → shorthand string или object form (рекурсивно для групп).
- function Build-FilterItem {
- param($itemNode, [string]$loc)
- $xtype = Get-LocalXsiType $itemNode
- if ($xtype -eq 'FilterItemGroup') {
- $gt = Get-Text $itemNode "dcsset:groupType"
- $groupName = switch ($gt) { 'OrGroup' { 'Or' } 'NotGroup' { 'Not' } default { 'And' } }
- $items = @()
- foreach ($c in $itemNode.SelectNodes("dcsset:item", $ns)) {
- $bi = (Build-FilterItem -itemNode $c -loc "$loc/item")
- if ($null -ne $bi) { $items += $bi }
- }
- $gObj = [ordered]@{ group = $groupName; items = $items }
- if ((Get-Text $itemNode "dcsset:use") -eq 'false') { $gObj['use'] = $false } # группа отключена (@off)
- $gPresNode = $itemNode.SelectSingleNode("dcsset:presentation", $ns)
- if ($gPresNode) {
- # Сохраняем форму по xsi:type (LocalStringType ru-only ≠ xs:string)
- $gPres = Get-PresByType $gPresNode
- if ($null -ne $gPres -and $gPres -ne '') { $gObj['presentation'] = $gPres }
- }
- $gVMNode = $itemNode.SelectSingleNode("dcsset:viewMode", $ns)
- if ($gVMNode) { $gObj['viewMode'] = $gVMNode.InnerText }
- $gUSID = Get-Text $itemNode "dcsset:userSettingID"
- if ($gUSID) { $gObj['userSettingID'] = 'auto' }
- $gUSPN = $itemNode.SelectSingleNode("dcsset:userSettingPresentation", $ns)
- if ($gUSPN) {
- $gUSP = Get-PresText $gUSPN
- if ($gUSP) { $gObj['userSettingPresentation'] = $gUSP }
- }
- return $gObj
- }
- if ($xtype -ne 'FilterItemComparison') {
- [Console]::Error.WriteLine("form-decompile: пропущен фильтр неизвестного типа '$xtype' (path: $loc)")
- return $null
- }
- $leftNode = $itemNode.SelectSingleNode("dcsset:left", $ns)
- $field = if ($leftNode) { $leftNode.InnerText } else { $null }
- $ct = Get-Text $itemNode "dcsset:comparisonType"
- $op = $script:filterOpMap[$ct]
- if (-not $op) { $op = $ct }
- $rightNodes = @($itemNode.SelectNodes("dcsset:right", $ns))
- $value = $null
- $valueIsArrayFlag = $false
- $valueTypeAttr = $null
- if ($rightNodes.Count -eq 1) {
- $rn = $rightNodes[0]
- if ((Get-LocalXsiType $rn) -eq 'ValueListType') {
- $value = @()
- $valueIsArrayFlag = $true
- } else {
- $vt = Get-FilterValueWithType $rn
- $value = $vt.value
- $autoDetectsDTV = ($vt.type -eq 'dcscor:DesignTimeValue') -and `
- ("$($vt.value)" -match '^(Перечисление|Справочник|ПланСчетов|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|РегистрСведений|ПланОбмена|Catalog|Enum|Document|ChartOfAccounts|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|InformationRegister|ExchangePlan)\.')
- if ($vt.type -and $vt.type -notmatch '^xs:' -and -not $autoDetectsDTV) {
- $valueTypeAttr = $vt.type
- } elseif ($vt.type -eq 'xs:string' -and ($value -is [string]) -and ($value -match '^(-?\d+(\.\d+)?|\d{4}-\d{2}-\d{2}T)')) {
- # Значение-строка "1"/"2020-..." с xsi:type="xs:string": компилятор авто-детектит число/дату
- # (теряет xs:string). Когда авто-вывод дал бы ДРУГОЙ тип — фиксируем явный valueType.
- $valueTypeAttr = 'xs:string'
- }
- }
- } elseif ($rightNodes.Count -gt 1) {
- $arr = @()
- $rawTypes = @()
- foreach ($rn in $rightNodes) {
- $arr += (Get-FilterValue $rn)
- $rawTypes += $rn.GetAttribute("type", $NS_XSI)
- }
- $value = $arr
- $valueIsArrayFlag = $true
- $uniqTypes = @($rawTypes | Sort-Object -Unique)
- if ($uniqTypes.Count -eq 1 -and $uniqTypes[0]) {
- $autoDetectsDTV = ($uniqTypes[0] -eq 'dcscor:DesignTimeValue') -and `
- ($arr.Count -gt 0) -and `
- (@($arr | Where-Object { "$_" -notmatch '^(Перечисление|Справочник|ПланСчетов|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|РегистрСведений|ПланОбмена|Catalog|Enum|Document|ChartOfAccounts|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|InformationRegister|ExchangePlan)\.' }).Count -eq 0)
- if (-not $autoDetectsDTV) {
- $valueTypeAttr = $uniqTypes[0]
- }
- }
- }
- $use = Get-Text $itemNode "dcsset:use"
- $userId = Get-Text $itemNode "dcsset:userSettingID"
- $vmNode = $itemNode.SelectSingleNode("dcsset:viewMode", $ns)
- $viewMode = if ($vmNode) { $vmNode.InnerText } else { $null }
- $userPresNode = $itemNode.SelectSingleNode("dcsset:userSettingPresentation", $ns)
- $fiPresNode = $itemNode.SelectSingleNode("dcsset:presentation", $ns)
- $fiPres = $null
- if ($fiPresNode) {
- # Сохраняем форму по xsi:type (LocalStringType ru-only ≠ xs:string)
- $fiPres = Get-PresByType $fiPresNode
- }
- $flags = @()
- if ($use -eq 'false') { $flags += '@off' }
- if ($userId) { $flags += '@user' }
- if ($viewMode -eq 'QuickAccess') { $flags += '@quickAccess' }
- elseif ($viewMode -eq 'Inaccessible') { $flags += '@inaccessible' }
- elseif ($viewMode -eq 'Normal') { $flags += '@normal' }
- $noValueOps = @('filled','notFilled')
- # Пустой xs:string right (<dcsset:right xsi:type="xs:string"/>) ≠ отсутствие <right>:
- # Get-FilterValueWithType маппит наличие пустого/nil right в value='_' (отсутствие → $null).
- # Shorthand `_` неоднозначен (схлопывает оба, компилятор → нет right). Пробельные значения рвут
- # shorthand-парсинг (split по пробелам). → форсим объектную форму (value='_' → self-closing;
- # пробелы — как есть в <right>).
- $valNeedsObj = $false
- if ($rightNodes.Count -eq 1 -and -not $valueIsArrayFlag -and $op -notin $noValueOps) {
- if ("$value" -eq '_') {
- # Truly-empty <right xsi:type="xs:string"/> ИЛИ whitespace-only <right> </right>
- # (PreserveWhitespace=false стрипнул пробелы в '' → Get-FilterValueWithType вернул '_').
- # Восстанавливаем реальные пробелы из WS-дока (как у whitespace-заголовков).
- $ws = Resolve-WS $rightNodes[0]
- if ($ws -and $ws.Length -gt 0 -and $ws.Trim() -eq '') { $value = $ws }
- $valNeedsObj = $true
- }
- elseif ($null -ne $value -and "$value" -match '\s') { $valNeedsObj = $true }
- }
- if ($userPresNode -or $valueIsArrayFlag -or $valueTypeAttr -or $fiPres -or $valNeedsObj) {
- $obj = [ordered]@{ field = $field; op = $op }
- if ($op -notin $noValueOps -and $null -ne $value) {
- if ($valueIsArrayFlag) {
- $arrAsList = New-Object System.Collections.ArrayList
- foreach ($vv in @($value)) { [void]$arrAsList.Add($vv) }
- $obj['value'] = $arrAsList
- } else {
- $obj['value'] = $value
- }
- }
- if ($valueTypeAttr) { $obj['valueType'] = $valueTypeAttr }
- if ($use -eq 'false') { $obj['use'] = $false }
- if ($userId) { $obj['userSettingID'] = 'auto' }
- if ($fiPres) { $obj['presentation'] = $fiPres }
- if ($viewMode) { $obj['viewMode'] = $viewMode }
- if ($userPresNode) { $obj['userSettingPresentation'] = Get-PresText $userPresNode }
- return $obj
- }
- $s = $field
- if ($op -in $noValueOps) {
- $s += " $op"
- } else {
- $vDisplay = '_'
- if ($null -ne $value) {
- if ($value -is [bool]) { $vDisplay = if ($value) { 'true' } else { 'false' } }
- elseif ("$value" -ne '') { $vDisplay = "$value" }
- }
- $s += " $op $vDisplay"
- }
- if ($flags) { $s += ' ' + ($flags -join ' ') }
- return $s
- }
- # Рекурсивный хелпер одного элемента selection (для conditionalAppearance).
- function Build-SelectionItem {
- param($item, [string]$loc)
- $xt = Get-LocalXsiType $item
- if (-not $xt) {
- $fName = Get-Text $item "dcsset:field"
- if ($fName) { return $fName }
- $fieldEl = $item.SelectSingleNode("dcsset:field", $ns)
- if ($fieldEl) { return 'Auto' }
- }
- switch ($xt) {
- 'SelectedItemAuto' {
- $useV = Get-Text $item "dcsset:use"
- if ($useV -eq 'false') {
- return [ordered]@{ auto = $true; use = $false }
- }
- return 'Auto'
- }
- 'SelectedItemField' {
- $fName = Get-Text $item "dcsset:field"
- $titleNode = $item.SelectSingleNode("dcsset:lwsTitle", $ns)
- $title = Get-MLText $titleNode
- $vmN = $item.SelectSingleNode("dcsset:viewMode", $ns)
- $useV = Get-Text $item "dcsset:use"
- $useFalse = ($useV -eq 'false')
- if ($title -or $vmN -or $useFalse) {
- $obj = [ordered]@{ field = $fName }
- if ($useFalse) { $obj['use'] = $false }
- if ($title) { $obj['title'] = $title }
- if ($vmN) { $obj['viewMode'] = $vmN.InnerText }
- return $obj
- }
- return $fName
- }
- 'SelectedItemFolder' {
- $titleNode = $item.SelectSingleNode("dcsset:lwsTitle", $ns)
- $folderTitle = Get-MLText $titleNode
- $inner = @()
- foreach ($sub in $item.SelectNodes("dcsset:item", $ns)) {
- $bi = (Build-SelectionItem -item $sub -loc "$loc/folder")
- if ($null -ne $bi) { $inner += $bi }
- }
- $entry = [ordered]@{ folder = $folderTitle; items = $inner }
- $folderField = Get-Text $item "dcsset:field"
- if ($folderField) { $entry['field'] = $folderField }
- $plN = $item.SelectSingleNode("dcsset:placement", $ns)
- if ($plN -and $plN.InnerText -and $plN.InnerText -ne 'Auto') {
- $entry['placement'] = $plN.InnerText
- }
- return $entry
- }
- default {
- [Console]::Error.WriteLine("form-decompile: пропущен элемент selection неизвестного типа '$xt' (path: $loc)")
- return $null
- }
- }
- }
- # Build selection items array (для conditionalAppearance).
- function Build-Selection {
- param($selNode, [string]$loc)
- if (-not $selNode) { return @() }
- $out = @()
- foreach ($it in $selNode.SelectNodes("dcsset:item", $ns)) {
- $bi = (Build-SelectionItem -item $it -loc $loc)
- if ($null -ne $bi) { $out += $bi }
- }
- return ,$out
- }
- # Build order items array.
- function Build-Order {
- param($ordNode, [string]$loc)
- if (-not $ordNode) { return @() }
- $out = @()
- foreach ($it in $ordNode.SelectNodes("dcsset:item", $ns)) {
- $xt = Get-LocalXsiType $it
- switch ($xt) {
- 'OrderItemAuto' { $out += 'Auto' }
- 'OrderItemField' {
- $fn = Get-Text $it "dcsset:field"
- $ot = Get-Text $it "dcsset:orderType"
- $vmN = $it.SelectSingleNode("dcsset:viewMode", $ns)
- $useV = Get-Text $it "dcsset:use"
- $useFalse = ($useV -eq 'false')
- if ($vmN -or $useFalse) {
- $obj = [ordered]@{ field = $fn }
- if ($useFalse) { $obj['use'] = $false }
- if ($ot -eq 'Desc') { $obj['direction'] = 'desc' }
- if ($vmN) { $obj['viewMode'] = $vmN.InnerText }
- $out += $obj
- } else {
- if ($ot -eq 'Desc') { $out += "$fn desc" } else { $out += $fn }
- }
- }
- default {
- [Console]::Error.WriteLine("form-decompile: пропущен элемент сортировки неизвестного типа '$xt' (path: $loc)")
- }
- }
- }
- return ,$out
- }
- # Build appearance dict из <dcsset:appearance> (Line/Font/multilang/nested items).
- function Get-SettingsAppearance {
- param($appNode)
- if (-not $appNode) { return $null }
- $dict = [ordered]@{}
- foreach ($it in $appNode.SelectNodes("dcscor:item", $ns)) {
- $pName = Get-Text $it "dcscor:parameter"
- $val = $it.SelectSingleNode("dcscor:value", $ns)
- if (-not $pName -or -not $val) { continue }
- $rawVal = Read-AppearanceValueNode $val
- $useV = Get-Text $it "dcscor:use"
- $nestedItems = [ordered]@{}
- foreach ($sub in $it.SelectNodes("dcscor:item", $ns)) {
- $subName = Get-Text $sub "dcscor:parameter"
- $subVal = $sub.SelectSingleNode("dcscor:value", $ns)
- if (-not $subName) { continue }
- $subRaw = Read-AppearanceValueNode $subVal
- $subUse = Get-Text $sub "dcscor:use"
- $subEntry = [ordered]@{ value = $subRaw }
- if ($subUse -eq 'false') { $subEntry['use'] = $false }
- $nestedItems[$subName] = $subEntry
- }
- $valIsLine = ($rawVal -is [System.Collections.IDictionary]) -and $rawVal.Contains('@type') -and ($rawVal['@type'] -eq 'Line')
- if ($valIsLine) {
- if ($useV -eq 'false') { $rawVal['use'] = $false }
- if ($nestedItems.Count -gt 0) { $rawVal['items'] = $nestedItems }
- $dict[$pName] = $rawVal
- } elseif (($useV -eq 'false') -or ($nestedItems.Count -gt 0)) {
- $wrap = [ordered]@{ value = $rawVal }
- if ($useV -eq 'false') { $wrap['use'] = $false }
- if ($nestedItems.Count -gt 0) { $wrap['items'] = $nestedItems }
- $dict[$pName] = $wrap
- } else {
- $dict[$pName] = $rawVal
- }
- }
- return $dict
- }
- # Build conditionalAppearance array.
- function Build-ConditionalAppearance {
- param($caNode, [string]$loc)
- if (-not $caNode) { return @() }
- $out = @()
- $i = 0
- foreach ($it in $caNode.SelectNodes("dcsset:item", $ns)) {
- $entry = [ordered]@{}
- $scopeNode = $it.SelectSingleNode("dcsset:scope", $ns)
- if ($scopeNode -and $scopeNode.HasChildNodes) {
- [Console]::Error.WriteLine("form-decompile: conditionalAppearance item имеет scope — не воспроизводится в DSL (path: $loc/$i/scope)")
- }
- $selNode = $it.SelectSingleNode("dcsset:selection", $ns)
- if ($selNode -and $selNode.SelectNodes("dcsset:item", $ns).Count -gt 0) {
- $entry['selection'] = Build-Selection -selNode $selNode -loc "$loc/$i/selection"
- }
- $filterNode = $it.SelectSingleNode("dcsset:filter", $ns)
- if ($filterNode -and $filterNode.SelectNodes("dcsset:item", $ns).Count -gt 0) {
- $f = @()
- foreach ($fc in $filterNode.SelectNodes("dcsset:item", $ns)) {
- $bi = (Build-FilterItem -itemNode $fc -loc "$loc/$i/filter")
- if ($null -ne $bi) { $f += $bi }
- }
- $entry['filter'] = $f
- }
- $appNode = $it.SelectSingleNode("dcsset:appearance", $ns)
- $ap = Get-SettingsAppearance $appNode
- if ($ap -and $ap.Count -gt 0) { $entry['appearance'] = $ap }
- $presNode = $it.SelectSingleNode("dcsset:presentation", $ns)
- if ($presNode) {
- # Сохраняем форму по xsi:type: LocalStringType (даже ru-only) → объект → компилятор эмитит LocalStringType.
- $pres = Get-PresByType $presNode
- if ($null -ne $pres -and $pres -ne '') { $entry['presentation'] = $pres }
- }
- $vmN = $it.SelectSingleNode("dcsset:viewMode", $ns)
- if ($vmN) { $entry['viewMode'] = $vmN.InnerText }
- $usid = Get-Text $it "dcsset:userSettingID"
- if ($usid) { $entry['userSettingID'] = 'auto' }
- $uspN = $it.SelectSingleNode("dcsset:userSettingPresentation", $ns)
- if ($uspN) {
- $usp = Get-PresText $uspN
- if ($usp) { $entry['userSettingPresentation'] = $usp }
- }
- $useV = Get-Text $it "dcsset:use"
- if ($useV -eq 'false') { $entry['use'] = $false }
- $useInDontUse = @()
- foreach ($ch in $it.ChildNodes) {
- if ($ch.NodeType -ne 'Element' -or $ch.NamespaceURI -ne $NS_DCSSET) { continue }
- if ($ch.LocalName -match '^useIn(.+)$' -and $ch.InnerText -eq 'DontUse') {
- $shortName = ($matches[1]).Substring(0, 1).ToLower() + ($matches[1]).Substring(1)
- $useInDontUse += $shortName
- }
- }
- if ($useInDontUse.Count -gt 0) { $entry['useInDontUse'] = $useInDontUse }
- $out += $entry
- $i++
- }
- return ,$out
- }
- # Общие layout-свойства → в $obj (симметрично Emit-Layout компилятора).
- # Вызывается один раз для любого элемента. Height тут — высота элемента (<Height>),
- # в т.ч. у Table; высоту в строках (<HeightInTableRows>) Table ловит отдельно в heightInTableRows.
- function Add-Layout {
- param($obj, $node)
- # Общие свойства элемента (любой тип): default/drag/skip
- if ((Get-Child $node 'DefaultItem') -eq 'true') { $obj['defaultItem'] = $true }
- $soi = Get-Child $node 'SkipOnInput'; if ($null -ne $soi) { $obj['skipOnInput'] = ($soi -eq 'true') }
- # EnableStartDrag/EnableDrag — фактическое значение (платформа эмитит и явный false, напр. SpreadSheet)
- $esd = Get-Child $node 'EnableStartDrag'; if ($null -ne $esd) { $obj['enableStartDrag'] = ($esd -eq 'true') }
- $edr = Get-Child $node 'EnableDrag'; if ($null -ne $edr) { $obj['enableDrag'] = ($edr -eq 'true') }
- $fdm = Get-Child $node 'FileDragMode'; if ($fdm) { $obj['fileDragMode'] = $fdm }
- # AutoMaxWidth: компилятор додумывает false для multiLine-input без явного ключа (multiLineDefault).
- # Захват факт. значения; multiLine-input без тега → autoMaxWidth:true (суппресс эвристики).
- $amwNode = Get-Child $node 'AutoMaxWidth'
- if ($amwNode -eq 'false') { $obj['autoMaxWidth'] = $false }
- elseif ($amwNode -eq 'true') { $obj['autoMaxWidth'] = $true }
- elseif ((Get-Child $node 'MultiLine') -eq 'true') { $obj['autoMaxWidth'] = $true }
- $mw = Get-Child $node 'MaxWidth'; if ($mw) { $obj['maxWidth'] = [int]$mw }
- if ((Get-Child $node 'AutoMaxHeight') -eq 'false') { $obj['autoMaxHeight'] = $false }
- $mh = Get-Child $node 'MaxHeight'; if ($mh) { $obj['maxHeight'] = [int]$mh }
- $w = Get-Child $node 'Width'; if ($w) { $obj['width'] = [int]$w }
- $h = Get-Child $node 'Height'; if ($h) { $obj['height'] = [int]$h }
- # Stretch: захват фактического значения (true И false — платформа эмитит явное)
- $hs = Get-Child $node 'HorizontalStretch'; if ($null -ne $hs) { $obj['horizontalStretch'] = ($hs -eq 'true') }
- $vs = Get-Child $node 'VerticalStretch'; if ($null -ne $vs) { $obj['verticalStretch'] = ($vs -eq 'true') }
- $gha = Get-Child $node 'GroupHorizontalAlign'; if ($gha) { $obj['groupHorizontalAlign'] = $gha }
- $gva = Get-Child $node 'GroupVerticalAlign'; if ($gva) { $obj['groupVerticalAlign'] = $gva }
- $ha = Get-Child $node 'HorizontalAlign'; if ($ha) { $obj['horizontalAlign'] = $ha }
- # Cell-свойства поля в таблице (общие для Input/Label/Picture/CheckBox): захват «как есть»
- foreach ($p in @('ShowInHeader','ShowInFooter','AutoCellHeight')) {
- $v = Get-Child $node $p; if ($null -ne $v) { $obj[($p.Substring(0,1).ToLower()+$p.Substring(1))] = ($v -eq 'true') }
- }
- $fha = Get-Child $node 'FooterHorizontalAlign'; if ($fha) { $obj['footerHorizontalAlign'] = $fha }
- $hha = Get-Child $node 'HeaderHorizontalAlign'; if ($hha) { $obj['headerHorizontalAlign'] = $hha }
- # ColumnGroup: динамический заголовок из данных + формат заголовка (ML-текст)
- $hdp = Get-Child $node 'HeaderDataPath'; if ($hdp) { $obj['headerDataPath'] = $hdp }
- $hfNode = $node.SelectSingleNode("lf:HeaderFormat", $ns); if ($hfNode) { $hf = Get-LangText $hfNode; if ($null -ne $hf) { $obj['headerFormat'] = $hf } }
- }
- # TitleLocation у check/radio (зеркало Emit-TitleLocation):
- # тега нет → "" (дефолт платформы); значение = умный дефолт → опускаем; иначе пишем.
- function Add-TitleLocation {
- param($obj, $node, [string]$smartDefault)
- $tl = Get-Child $node 'TitleLocation'
- if ($null -eq $tl) { $obj['titleLocation'] = '' }
- elseif ($tl -ne $smartDefault) { $obj['titleLocation'] = $tl.ToLower() }
- }
- # Разобрать <Events> формы или элемента → упорядоченная мапа { ИмяСобытия: ИмяОбработчика }
- # в порядке документа. Имена обработчиков всегда явные. Привязка с видом вызова (расширение) —
- # { handler, callType }; несколько привязок одного события (Before и After) — массив таких объектов.
- function Get-Events {
- param($node, [string]$elName)
- $ev = $node.SelectSingleNode("lf:Events", $ns)
- if (-not $ev) { return $null }
- $events = [ordered]@{}
- foreach ($e in @($ev.SelectNodes("lf:Event", $ns))) {
- $n = $e.GetAttribute("name"); $ct = $e.GetAttribute("callType")
- $v = if ($ct) { [ordered]@{ handler = $e.InnerText; callType = $ct } } else { $e.InnerText }
- if ($events.Contains($n)) { $events[$n] = @(@($events[$n]) + , $v) } else { $events[$n] = $v }
- }
- if ($events.Count -eq 0) { return $null }
- return $events
- }
- # Инверсия Emit-XrFlag: role-adjustable boolean (UserVisible/View/Edit/Use).
- # <TAG><xr:Common/>[<xr:Value name="Role.X"/>…]</TAG> → скаляр bool (без ролей) или объект { common, roles:{Имя:bool} }.
- # Имя роли отдаём без префикса "Role.". Возвращает $null, если тег отсутствует.
- function Decompile-XrFlag {
- param($node, [string]$tag)
- $el = $node.SelectSingleNode("*[local-name()='$tag']")
- if (-not $el) { return $null }
- $commonNode = $el.SelectSingleNode("*[local-name()='Common']")
- $common = ($commonNode -and $commonNode.InnerText -eq 'true')
- $valNodes = @($el.SelectNodes("*[local-name()='Value']"))
- if ($valNodes.Count -eq 0) { return $common }
- $roles = [ordered]@{}
- foreach ($v in $valNodes) {
- $rn = $v.GetAttribute("name")
- if ($rn -match '^Role\.') { $rn = $rn.Substring(5) }
- $roles[$rn] = ($v.InnerText -eq 'true')
- }
- $o = [ordered]@{}
- $o['common'] = $common
- $o['roles'] = $roles
- return $o
- }
- # Командный интерфейс формы (<CommandInterface>): панели CommandBar + NavigationPanel,
- # каждая — список переопределений команд (платформа эмитит ТОЛЬКО отклонения от авто-расстановки).
- # Элемент: command (verbatim, "0"=пустой) + type (Auto опускаем) + attribute/group(CommandGroup)/index +
- # defaultVisible(bool) + visible(xr-flag bool/{common,roles} — тот же механизм, что userVisible).
- # Голый элемент (только команда, Type=Auto) → строковый shorthand.
- function Decompile-CommandInterface {
- $ciNode = $root.SelectSingleNode("lf:CommandInterface", $ns)
- if (-not $ciNode) { return $null }
- $ci = [ordered]@{}
- foreach ($panel in @(@('CommandBar','commandBar'), @('NavigationPanel','navigationPanel'))) {
- $pn = $ciNode.SelectSingleNode("lf:$($panel[0])", $ns)
- if (-not $pn) { continue }
- $items = New-Object System.Collections.ArrayList
- foreach ($it in @($pn.SelectNodes("lf:Item", $ns))) {
- $o = [ordered]@{}
- $cmd = Get-Child $it 'Command'
- $o['command'] = "$cmd"
- $ty = Get-Child $it 'Type'; if ($ty -and $ty -ne 'Auto') { $o['type'] = $ty }
- $at = Get-Child $it 'Attribute'; if ($at) { $o['attribute'] = $at }
- $cg = Get-Child $it 'CommandGroup'; if ($cg) { $o['group'] = $cg }
- $idx = Get-Child $it 'Index'; if ($null -ne $idx) { $o['index'] = [int]$idx }
- $dv = Get-Child $it 'DefaultVisible'; if ($null -ne $dv) { $o['defaultVisible'] = ($dv -eq 'true') }
- $vis = Decompile-XrFlag $it 'Visible'; if ($null -ne $vis) { $o['visible'] = $vis }
- # Голый элемент (только command) → строка-shorthand; иначе объект
- if ($o.Count -eq 1) { [void]$items.Add("$cmd") } else { [void]$items.Add($o) }
- }
- if ($items.Count -gt 0) { $ci[$panel[1]] = @($items) }
- }
- if ($ci.Count -gt 0) { return $ci }
- return $null
- }
- # <FunctionalOptions><Item>FunctionalOption.X</Item>…> → массив строк (префикс FunctionalOption. снят; GUID — как есть).
- function Decompile-FunctionalOptions {
- param($node)
- $foNode = $node.SelectSingleNode("lf:FunctionalOptions", $ns)
- if (-not $foNode) { return $null }
- $opts = New-Object System.Collections.ArrayList
- foreach ($it in @($foNode.SelectNodes("lf:Item", $ns))) {
- $t = $it.InnerText.Trim() -replace '^FunctionalOption\.', ''
- [void]$opts.Add($t)
- }
- if ($opts.Count -gt 0) { return ,@($opts) }
- return $null
- }
- # Колонка реквизита (прямая или внутри AdditionalColumns): name/type/title/functionalOptions.
- function Decompile-AttrColumn {
- param($c)
- $co = [ordered]@{}; $co['name'] = $c.GetAttribute("name")
- $cty = Decompile-Type ($c.SelectSingleNode("lf:Type", $ns)); if ($cty) { $co['type'] = $cty }
- $ctNode = $c.SelectSingleNode("lf:Title", $ns); if ($ctNode) { $t = Get-LangTextWS $ctNode; if ($null -ne $t) { $co['title'] = $t } }
- $cfc = Get-Child $c 'FillCheck'; if ($cfc) { $co['fillCheck'] = $cfc } # проверка заполнения колонки (как у реквизита)
- $cfo = Decompile-FunctionalOptions $c; if ($cfo) { $co['functionalOptions'] = $cfo }
- # Ролевой доступ колонки (View/Edit) — xr-флаг, как у самого реквизита (bool | {common,roles})
- $cv = Decompile-XrFlag $c 'View'; if ($null -ne $cv) { $co['view'] = $cv }
- $ce = Decompile-XrFlag $c 'Edit'; if ($null -ne $ce) { $co['edit'] = $ce }
- return $co
- }
- # Общие свойства элемента (visible/enabled/readonly/title/events) → в hash
- # Картинка-ссылка с прозрачностью (HeaderPicture/FooterPicture/ValuesPicture/Page Picture).
- # Платформа ВСЕГДА эмитит <xr:LoadTransparent> (и true, и false) → дефолт DSL = false.
- # Источник: <xr:Ref> (именованная/стилевая) ИЛИ <xr:Abs> (встроенная → префикс "abs:").
- # Скаляр (src) при loadTransparent=false и без TransparentPixel; иначе объект
- # {src, loadTransparent?, transparentPixel?}.
- function Get-PictureRef {
- param($node, [string]$picTag)
- $ref = $node.SelectSingleNode("lf:$picTag/xr:Ref", $ns)
- $abs = $node.SelectSingleNode("lf:$picTag/xr:Abs", $ns)
- if (-not $ref -and -not $abs) { return $null }
- $src = if ($ref) { $ref.InnerText } else { "abs:$($abs.InnerText)" }
- $lt = $node.SelectSingleNode("lf:$picTag/xr:LoadTransparent", $ns)
- $ltTrue = ($lt -and $lt.InnerText -eq 'true')
- $tpx = $node.SelectSingleNode("lf:$picTag/xr:TransparentPixel", $ns)
- if (-not $ltTrue -and -not $tpx) { return $src }
- $o = [ordered]@{ src = $src }
- if ($ltTrue) { $o['loadTransparent'] = $true }
- if ($tpx) { $o['transparentPixel'] = [ordered]@{ x = [int]$tpx.GetAttribute('x'); y = [int]$tpx.GetAttribute('y') } }
- return $o
- }
- # <Picture> кнопки/попапа/команды. Дефолт LoadTransparent=true (обратная конвенция к header/values):
- # фиксируем только отклонение false. Источник <xr:Ref> или <xr:Abs> (→ "abs:"). При наличии
- # <xr:TransparentPixel> → объектная форма {src, loadTransparent?, transparentPixel}, иначе скаляр picture
- # + отдельный loadTransparent:false.
- function Set-CommandPicture {
- param($obj, $node)
- $ref = $node.SelectSingleNode("lf:Picture/xr:Ref", $ns)
- $abs = $node.SelectSingleNode("lf:Picture/xr:Abs", $ns)
- if (-not $ref -and -not $abs) { return }
- $src = if ($ref) { $ref.InnerText } else { "abs:$($abs.InnerText)" }
- $lt = $node.SelectSingleNode("lf:Picture/xr:LoadTransparent", $ns)
- $ltFalse = ($lt -and $lt.InnerText -eq 'false')
- $tpx = $node.SelectSingleNode("lf:Picture/xr:TransparentPixel", $ns)
- if ($tpx) {
- $o = [ordered]@{ src = $src }
- if ($ltFalse) { $o['loadTransparent'] = $false }
- $o['transparentPixel'] = [ordered]@{ x = [int]$tpx.GetAttribute('x'); y = [int]$tpx.GetAttribute('y') }
- $obj['picture'] = $o
- } else {
- $obj['picture'] = $src
- if ($ltFalse) { $obj['loadTransparent'] = $false }
- }
- }
- # Шрифт <Font ...> → строка-ref (если только ref+kind=StyleItem) или объект-атрибуты.
- function Build-FontValue {
- param($f)
- $present = @()
- foreach ($a in @('ref','faceName','height','bold','italic','underline','strikeout','kind','scale')) {
- if ($f.HasAttribute($a)) { $present += $a }
- }
- # Чистый style-ref (ref + kind=StyleItem) → строка-шорткат
- if ($present.Count -eq 2 -and ($present -contains 'ref') -and $f.GetAttribute('kind') -eq 'StyleItem') {
- return $f.GetAttribute('ref')
- }
- $o = [ordered]@{}
- foreach ($k in $present) {
- $v = $f.GetAttribute($k)
- if ($k -in @('height','scale') -and $v -match '^-?\d+$') { $o[$k] = [int]$v }
- elseif ($k -in @('bold','italic','underline','strikeout')) { $o[$k] = ($v -eq 'true') }
- else { $o[$k] = $v }
- }
- return $o
- }
- # Граница <Border> → строка-ref (из стиля) или объект {width, style}.
- function Build-BorderValue {
- param($b)
- if ($b.HasAttribute('ref')) { return $b.GetAttribute('ref') }
- $o = [ordered]@{}
- if ($b.HasAttribute('width')) { $w = $b.GetAttribute('width'); $o['width'] = if ($w -match '^-?\d+$') { [int]$w } else { $w } }
- $st = $b.SelectSingleNode("v8ui:style", $ns)
- if ($st) { $o['style'] = $st.InnerText }
- return $o
- }
- # Оформление элемента (цвета/шрифты/граница) → canonical DSL-ключи. Цвет — verbatim-строка.
- function Add-Appearance {
- param($obj, $node)
- $colorMap = @{
- 'TitleTextColor'='titleTextColor'; 'TitleBackColor'='titleBackColor'
- 'FooterTextColor'='footerTextColor'; 'FooterBackColor'='footerBackColor'
- 'TextColor'='textColor'; 'BackColor'='backColor'; 'BorderColor'='borderColor'
- }
- foreach ($tag in $colorMap.Keys) {
- $c = $node.SelectSingleNode("lf:$tag", $ns)
- if ($c) { $obj[$colorMap[$tag]] = $c.InnerText }
- }
- foreach ($pair in @(@('Font','font'), @('TitleFont','titleFont'), @('FooterFont','footerFont'))) {
- $f = $node.SelectSingleNode("lf:$($pair[0])", $ns)
- if ($f) { $obj[$pair[1]] = (Build-FontValue $f) }
- }
- $b = $node.SelectSingleNode("lf:Border", $ns)
- if ($b) { $obj['border'] = (Build-BorderValue $b) }
- }
- function Add-CommonProps {
- param($obj, $node, [string]$elName)
- Add-Appearance $obj $node
- if ((Get-Child $node 'Visible') -eq 'false') { $obj['hidden'] = $true }
- if ((Get-Child $node 'Enabled') -eq 'false') { $obj['disabled'] = $true }
- if ((Get-Child $node 'ReadOnly') -eq 'true') { $obj['readOnly'] = $true }
- $uv = Decompile-XrFlag $node 'UserVisible'; if ($null -ne $uv) { $obj['userVisible'] = $uv }
- $titleNode = $node.SelectSingleNode("lf:Title", $ns)
- if ($titleNode) {
- $t = Get-LangTextWS $titleNode # восстановление значимого пробела (whitespace-заголовок)
- if ($null -ne $t) { $obj['title'] = $t }
- # formatted у LabelDecoration выводится компилятором из hyperlink — отдельный ключ не нужен (#16 хвост)
- }
- $ttNode = $node.SelectSingleNode("lf:ToolTip", $ns)
- if ($ttNode) { $tt = Get-LangTextWS $ttNode; if ($null -ne $tt) { $obj['tooltip'] = $tt } }
- $ttr = Get-Child $node 'ToolTipRepresentation'; if ($ttr) { $obj['tooltipRepresentation'] = $ttr }
- # Картинки заголовка/подвала колонки (любой field-тип, эмитятся платформой как column header/footer icon)
- $hp = Get-PictureRef $node 'HeaderPicture'; if ($null -ne $hp) { $obj['headerPicture'] = $hp }
- $fp = Get-PictureRef $node 'FooterPicture'; if ($null -ne $fp) { $obj['footerPicture'] = $fp }
- $ev = Get-Events $node $elName
- if ($ev) { $obj['events'] = $ev }
- # CommandSet — общий для полей (input/label/check/spreadsheet/html/formatted/picture):
- # список отключённых команд редактора. Только <ExcludedCommand>, пустого не бывает.
- $csNode = $node.SelectSingleNode("lf:CommandSet", $ns)
- if ($csNode) {
- $exc = New-Object System.Collections.ArrayList
- foreach ($ec in @($csNode.SelectNodes("lf:ExcludedCommand", $ns))) { [void]$exc.Add($ec.InnerText) }
- if ($exc.Count -gt 0) { $obj['excludedCommands'] = @($exc) }
- }
- }
- # --- 3. Type decompile (inverse of Emit-Type) ---
- function Decompile-Type {
- param($typeNode)
- if (-not $typeNode) { return $null }
- $parts = New-Object System.Collections.ArrayList
- foreach ($vt in @($typeNode.SelectNodes("v8:Type", $ns))) {
- $raw = $vt.InnerText.Trim()
- $short = $raw
- # break обязателен: иначе общий case ^(v8|v8ui|cfg): перетирает специфичные (напр. v8:ValueListType → ValueList).
- switch -regex ($raw) {
- '^xs:string$' {
- $len = $typeNode.SelectSingleNode("v8:StringQualifiers/v8:Length", $ns)
- $al = $typeNode.SelectSingleNode("v8:StringQualifiers/v8:AllowedLength", $ns)
- $fixed = ($al -and $al.InnerText -eq 'Fixed') # Variable = дефолт (опускаем); Fixed — явно
- $ll = if ($len) { $len.InnerText } else { '0' }
- if ($fixed -and [int]$ll -gt 0) { $short = "string($ll,fixed)" } # Fixed при длине 0 платформа не хранит
- elseif ([int]$ll -gt 0) { $short = "string($ll)" }
- else { $short = "string" } # голая строка у form-compile — неограниченная
- break
- }
- '^xs:decimal$' {
- $d = $typeNode.SelectSingleNode("v8:NumberQualifiers/v8:Digits", $ns)
- $f = $typeNode.SelectSingleNode("v8:NumberQualifiers/v8:FractionDigits", $ns)
- $sgn = $typeNode.SelectSingleNode("v8:NumberQualifiers/v8:AllowedSign", $ns)
- $dd = if ($d) { $d.InnerText } else { '0' }
- $ff = if ($f) { $f.InnerText } else { '0' }
- if ($sgn -and $sgn.InnerText -eq 'Nonnegative') { $short = "decimal($dd,$ff,nonneg)" }
- elseif ($dd -eq '10' -and $ff -eq '0') { $short = "decimal" } # голое число у form-compile — 10,0
- else { $short = "decimal($dd,$ff)" }
- break
- }
- '^xs:boolean$' { $short = "boolean"; break }
- '^xs:dateTime$' {
- $df = $typeNode.SelectSingleNode("v8:DateQualifiers/v8:DateFractions", $ns)
- $dfv = if ($df) { $df.InnerText } else { 'DateTime' }
- switch ($dfv) { 'Date' { $short = 'date' } 'Time' { $short = 'time' } default { $short = 'dateTime' } }
- break
- }
- '^cfg:(.+)$' { $short = $matches[1]; break }
- '^(v8|v8ui):' {
- # Платформенный тип: friendly-шорткат если есть, иначе оставляем с префиксом
- # (компилятор эмитит verbatim) — чтобы не терять v8:UUID и прочий хвост.
- $rev = @{
- 'v8:ValueTable'='ValueTable'; 'v8:ValueTree'='ValueTree'; 'v8:ValueListType'='ValueList'
- 'v8:TypeDescription'='TypeDescription'; 'v8:Universal'='Universal'
- 'v8:FixedArray'='FixedArray'; 'v8:FixedStructure'='FixedStructure'
- 'v8ui:FormattedString'='FormattedString'; 'v8ui:Picture'='Picture'; 'v8ui:Color'='Color'; 'v8ui:Font'='Font'
- }
- if ($rev.ContainsKey($raw)) { $short = $rev[$raw] } else { $short = $raw }
- break
- }
- default { $short = $raw }
- }
- [void]$parts.Add($short)
- }
- # TypeSet (набор типов): определяемый тип / характеристика / «любая ссылка вида».
- # Префикс cfg:/v8: снимаем — обратный роутинг в компиляторе по форме токена.
- foreach ($ts in @($typeNode.SelectNodes("v8:TypeSet", $ns))) {
- $raw = $ts.InnerText.Trim()
- $short = $raw -replace '^(v8ui|v8|cfg):', ''
- [void]$parts.Add($short)
- }
- # TypeId — тип, заданный глобальным стабильным GUID (<v8:TypeId>, не <v8:Type>). Платформа так
- # сериализует типы, чьё имя в этом контексте недоступно (определяемые/характеристики). GUID глобально
- # стабилен → эмитим verbatim как маркер 'typeid:GUID' (компилятор разворачивает обратно; как роль-по-GUID).
- foreach ($ti in @($typeNode.SelectNodes("v8:TypeId", $ns))) {
- [void]$parts.Add("typeid:" + $ti.InnerText.Trim())
- }
- if ($parts.Count -eq 0) { return $null }
- if ($parts.Count -eq 1) { return $parts[0] }
- return ($parts -join ' | ')
- }
- # Ограничения использования (useRestriction/attributeUseRestriction) → объект {field?,condition?,group?,order?}.
- function Build-RestrictObj {
- param($node)
- $r = [ordered]@{}
- foreach ($k in 'field','condition','group','order') { if ((Get-Child $node $k) -eq 'true') { $r[$k] = $true } }
- return $r
- }
- # Вычисляемое поле DataSet динамического списка (<CalculatedField>) → объектная модель.
- # Зеркало эмиссии form-compile (Emit-CalcFields). Грамматика — как skd calculatedFields,
- # + форм-extras presentationExpression/orderExpression (в namespace dcscommon).
- function Build-CalcField {
- param($cfNode)
- $o = [ordered]@{}
- $o['dataPath'] = Get-Child $cfNode 'dataPath'
- $o['expression'] = Get-Child $cfNode 'expression'
- $tn = $cfNode.SelectSingleNode("dcssch:title", $ns)
- if ($tn) { $t = Get-LangText $tn; if ($null -ne $t) { $o['title'] = $t } }
- $vt = $cfNode.SelectSingleNode("dcssch:valueType", $ns)
- if ($vt) { $v = Decompile-Type $vt; if ($v) { $o['valueType'] = $v } }
- $ur = $cfNode.SelectSingleNode("dcssch:useRestriction", $ns)
- if ($ur) {
- $r = [ordered]@{}
- foreach ($k in 'field','condition','group','order') { if ((Get-Child $ur $k) -eq 'true') { $r[$k] = $true } }
- if ($r.Count -gt 0) { $o['useRestriction'] = $r }
- }
- $pe = Get-Child $cfNode 'presentationExpression'
- if ($null -ne $pe -and $pe -ne '') { $o['presentationExpression'] = $pe }
- $oeNodes = @($cfNode.SelectNodes("dcssch:orderExpression", $ns))
- if ($oeNodes.Count -gt 0) {
- $oes = New-Object System.Collections.ArrayList
- foreach ($oen in $oeNodes) {
- $eo = [ordered]@{}
- $exprN = $oen.SelectSingleNode("*[local-name()='expression']")
- $otN = $oen.SelectSingleNode("*[local-name()='orderType']")
- $aoN = $oen.SelectSingleNode("*[local-name()='autoOrder']")
- $eo['expression'] = if ($exprN) { $exprN.InnerText } else { '' }
- if ($otN -and $otN.InnerText -ne 'Asc') { $eo['orderType'] = $otN.InnerText }
- if ($aoN -and $aoN.InnerText -eq 'true') { $eo['autoOrder'] = $true }
- [void]$oes.Add($eo)
- }
- $o['orderExpression'] = @($oes)
- }
- return $o
- }
- # Schema-параметры динамического списка (<Parameter> под <Settings>) — зеркало эмиссии
- # form-compile (Emit-DLParameters). Инверсия контекстных дефолтов: useRestriction=true и
- # title==Title-FromName опускаем (компилятор восстановит). Сущность = DataCompositionSchemaParameter.
- function Build-DLInputParameters {
- param($ipNode)
- $items = New-Object System.Collections.ArrayList
- foreach ($it in @($ipNode.SelectNodes("dcscor:item", $ns))) {
- $io = [ordered]@{}
- $io['parameter'] = Get-Child $it 'parameter'
- $useN = $it.SelectSingleNode("dcscor:use", $ns)
- if ($useN -and $useN.InnerText -eq 'false') { $io['use'] = $false }
- $valN = $it.SelectSingleNode("dcscor:value", $ns)
- if ($valN) {
- $vt = $valN.GetAttribute("type", $NS_XSI)
- if ($vt -match 'ChoiceParameters$') {
- $cps = New-Object System.Collections.ArrayList
- foreach ($cpi in @($valN.SelectNodes("dcscor:item", $ns))) {
- $cpo = [ordered]@{}
- $cpo['name'] = Get-Child $cpi 'choiceParameter'
- $vals = New-Object System.Collections.ArrayList
- foreach ($cv in @($cpi.SelectNodes("dcscor:value", $ns))) {
- [void]$vals.Add((Convert-TypedValue -raw $cv.InnerText -xsiType ($cv.GetAttribute("type", $NS_XSI))))
- }
- $cpo['values'] = @($vals)
- [void]$cps.Add($cpo)
- }
- $io['choiceParameters'] = @($cps)
- } elseif ($vt -match 'ChoiceParameterLinks$') {
- $cpls = New-Object System.Collections.ArrayList
- foreach ($cpi in @($valN.SelectNodes("dcscor:item", $ns))) {
- $cpo = [ordered]@{}
- $cpo['name'] = Get-Child $cpi 'choiceParameter'
- $cpo['value'] = Get-Child $cpi 'value'
- $md = Get-Child $cpi 'mode'; if ($md -and $md -ne 'Auto') { $cpo['mode'] = $md }
- [void]$cpls.Add($cpo)
- }
- $io['choiceParameterLinks'] = @($cpls)
- } elseif ($vt -match 'TypeLink$') {
- # Связь по типу (dcscor:TypeLink): field + linkItem — структурное значение,
- # НЕ склеивать InnerText в строку ("СчетДт"+"1"="СчетДт1").
- $tlo = [ordered]@{}
- $tlf = Get-Child $valN 'field'; if ($null -ne $tlf) { $tlo['field'] = $tlf }
- $tli = Get-Child $valN 'linkItem'; if ($null -ne $tli) { $tlo['linkItem'] = if ($tli -match '^-?\d+$') { [int]$tli } else { $tli } }
- $io['typeLink'] = $tlo
- } else {
- if ($valN.GetAttribute("nil", $NS_XSI) -ne 'true') { $io['value'] = Convert-TypedValue -raw $valN.InnerText -xsiType $vt }
- }
- }
- [void]$items.Add($io)
- }
- return @($items)
- }
- # dcsset:dataParameters → массив (shorthand "Имя @off" для value-less / объект для типизированного
- # значения). Грамматика зеркалит skd-compile Emit-DataParameters (form-контекст: значение опционально,
- # в отличие от skd-settings). Без «auto»-компактизации (нужна машинерия сравнения с top-level).
- function Build-FormDataParameters {
- param($dpNode)
- $entries = @()
- foreach ($it in @($dpNode.SelectNodes("dcscor:item", $ns))) {
- $pn = Get-Text $it "dcscor:parameter"
- $use = Get-Text $it "dcscor:use"
- $valNodes = @($it.SelectNodes("dcscor:value", $ns))
- $valNode = if ($valNodes.Count -ge 1) { $valNodes[0] } else { $null }
- $usidN = $it.SelectSingleNode("dcsset:userSettingID", $ns)
- $vmN = $it.SelectSingleNode("dcsset:viewMode", $ns)
- $uspN = $it.SelectSingleNode("dcsset:userSettingPresentation", $ns)
- if ($valNode -or $usidN -or $vmN -or $uspN) {
- $obj = [ordered]@{ parameter = $pn }
- if ($valNodes.Count -gt 1) {
- # Список значений параметра (valueListAllowed) — захватываем ВСЕ <dcscor:value> массивом
- $obj['value'] = @($valNodes | ForEach-Object { $_.InnerText })
- $vt0 = $valNodes[0].GetAttribute("type", $NS_XSI); if ($vt0) { $obj['valueType'] = $vt0 }
- } elseif ($valNode) {
- if ($valNode.GetAttribute("nil", $NS_XSI) -eq 'true') { $obj['nilValue'] = $true }
- else {
- $vType = $valNode.GetAttribute("type", $NS_XSI); $vVal = $valNode.InnerText
- if ($vType -match 'decimal$' -and $vVal -match '^-?\d+$') { $obj['value'] = [int]$vVal }
- elseif ($vType -match 'boolean$') { $obj['value'] = ($vVal -eq 'true') }
- else { $obj['value'] = $vVal }
- if ($vType) { $obj['valueType'] = $vType }
- }
- }
- if ($use -eq 'false') { $obj['use'] = $false }
- if ($usidN) { $obj['userSettingID'] = 'auto' }
- if ($vmN) { $obj['viewMode'] = $vmN.InnerText }
- if ($uspN) { $usp = Get-PresText $uspN; if ($null -ne $usp) { $obj['userSettingPresentation'] = $usp } }
- $entries += $obj
- } else {
- $s = $pn; if ($use -eq 'false') { $s += ' @off' }
- $entries += $s
- }
- }
- return ,$entries
- }
- function Build-DLParameter {
- param($pNode)
- $name = Get-Child $pNode 'name'
- $o = [ordered]@{}
- $o['name'] = $name
- # title — опускаем, если совпадает с авто-выводом из имени (ru-only)
- $titleNode = $pNode.SelectSingleNode("dcssch:title", $ns)
- if ($titleNode) {
- $t = Get-LangTextWS $titleNode # восстановление значимого пробела: заголовком-пробелом гасят подпись
- if ($null -ne $t) {
- # Сравнение байт в байт: эталон — компилятор, он пишет заголовок как есть. -eq
- # регистронезависим, и заголовок, отличающийся от авто-вывода только регистром
- # («Организации ВетИС» при авто «Организации ВЕТИС»), терялся молча. Даже -ceq мало:
- # он культурный, мягкий перенос и NFD-разложение для него — ноль. Нужен Ordinal,
- # он же и есть зеркало питоновского ==.
- $auto = Title-FromName -name $name
- if (-not (($t -is [string]) -and [string]::Equals($t, $auto, [StringComparison]::Ordinal))) { $o['title'] = $t }
- }
- }
- # valueType
- $vtNode = $pNode.SelectSingleNode("dcssch:valueType", $ns)
- $typeVal = $null
- if ($vtNode) { $typeVal = Decompile-Type $vtNode; if ($typeVal) { $o['type'] = $typeVal } }
- # value — опускаем nil (дефолт), КРОМЕ valueListAllowed+nil: платформа пишет <value xsi:nil/>
- # не всегда (корпус 27 с / 47 без), а компилятор при valueListAllowed по умолчанию его НЕ эмитит →
- # явный маркер value:null, чтобы реэмитить nil. (Различается через Has-DLProp в компиляторе.)
- $vNodes = @($pNode.SelectNodes("dcssch:value", $ns))
- if ($vNodes.Count -gt 1) {
- # valueListAllowed: список значений — захватываем ВСЕ <dcssch:value> массивом
- $o['value'] = @($vNodes | ForEach-Object { Convert-TypedValue -raw $_.InnerText -xsiType ($_.GetAttribute("type", $NS_XSI)) })
- } elseif ($vNodes.Count -eq 1) {
- $vNode = $vNodes[0]
- if ($vNode.GetAttribute("nil", $NS_XSI) -ne 'true') {
- $o['value'] = Convert-TypedValue -raw $vNode.InnerText -xsiType ($vNode.GetAttribute("type", $NS_XSI))
- } elseif ((Get-Child $pNode 'valueListAllowed') -eq 'true') {
- $o['value'] = $null
- }
- }
- # useRestriction — опускаем true (дефолт), фиксируем false
- if ((Get-Child $pNode 'useRestriction') -eq 'false') { $o['useRestriction'] = $false }
- # expression
- $expr = Get-Child $pNode 'expression'; if ($null -ne $expr -and $expr -ne '') { $o['expression'] = $expr }
- # availableValues
- $avNodes = @($pNode.SelectNodes("dcssch:availableValue", $ns))
- if ($avNodes.Count -gt 0) {
- $avs = New-Object System.Collections.ArrayList
- foreach ($avn in $avNodes) {
- $avo = [ordered]@{}
- $avv = $avn.SelectSingleNode("dcssch:value", $ns)
- if ($avv -and ($avv.GetAttribute("nil", $NS_XSI) -ne 'true')) { $avo['value'] = Convert-TypedValue -raw $avv.InnerText -xsiType ($avv.GetAttribute("type", $NS_XSI)) }
- else { $avo['value'] = $null }
- $avp = $avn.SelectSingleNode("dcssch:presentation", $ns)
- if ($avp) { $pres = Get-LangText $avp; if ($null -ne $pres) { $avo['presentation'] = $pres } }
- [void]$avs.Add($avo)
- }
- $o['availableValues'] = @($avs)
- }
- # valueListAllowed / availableAsField
- if ((Get-Child $pNode 'valueListAllowed') -eq 'true') { $o['valueListAllowed'] = $true }
- if ((Get-Child $pNode 'availableAsField') -eq 'false') { $o['availableAsField'] = $false }
- # inputParameters
- $ipNode = $pNode.SelectSingleNode("dcssch:inputParameters", $ns)
- if ($ipNode) { $ip = Build-DLInputParameters $ipNode; if (@($ip).Count -gt 0) { $o['inputParameters'] = $ip } }
- # denyIncompleteValues / use
- if ((Get-Child $pNode 'denyIncompleteValues') -eq 'true') { $o['denyIncompleteValues'] = $true }
- $use = Get-Child $pNode 'use'; if ($null -ne $use -and $use -ne '') { $o['use'] = $use }
- # Компактизация: {name} → строка "name"; {name, type} → "name: type"; иначе объект.
- $keys = @($o.Keys)
- if ($keys.Count -eq 1) { return $name }
- if ($keys.Count -eq 2 -and $o.Contains('type') -and ($typeVal -is [string])) { return ("{0}: {1}" -f $name, $typeVal) }
- return $o
- }
- # --- 4. Element dispatch ---
- $ELEMENT_KEY = @{
- 'UsualGroup'='group'; 'ColumnGroup'='columnGroup'; 'ButtonGroup'='buttonGroup'; 'InputField'='input'; 'CheckBoxField'='check';
- 'RadioButtonField'='radio'; 'LabelDecoration'='label'; 'LabelField'='labelField';
- 'PictureDecoration'='picture'; 'PictureField'='picField'; 'CalendarField'='calendar';
- 'Table'='table'; 'Pages'='pages'; 'Page'='page'; 'Button'='button'; 'CommandBar'='cmdBar'; 'Popup'='popup';
- 'SearchStringAddition'='searchString'; 'ViewStatusAddition'='viewStatus'; 'SearchControlAddition'='searchControl';
- 'SpreadSheetDocumentField'='spreadsheet'; 'HTMLDocumentField'='html'; 'TextDocumentField'='textDoc';
- 'FormattedDocumentField'='formattedDoc'; 'ProgressBarField'='progressBar'; 'TrackBarField'='trackBar';
- 'ChartField'='chart'; 'GraphicalSchemaField'='graphicalSchema'; 'PlannerField'='planner';
- 'PeriodField'='periodField'; 'DendrogramField'='dendrogram'; 'GanttChartField'='ganttChart'
- }
- # Простые скаляры элемента (pass-through, зеркало $script:genericScalars компилятора). kind bool/value.
- $GENERIC_SCALARS = @(
- @{ Tag='VerticalAlign'; Key='verticalAlign'; Kind='value' }
- @{ Tag='ThroughAlign'; Key='throughAlign'; Kind='value' }
- @{ Tag='EnableContentChange'; Key='enableContentChange'; Kind='bool' }
- @{ Tag='PictureSize'; Key='pictureSize'; Kind='value' }
- @{ Tag='TitleHeight'; Key='titleHeight'; Kind='value' }
- @{ Tag='ChildItemsWidth'; Key='childItemsWidth'; Kind='value' }
- @{ Tag='ShowLeftMargin'; Key='showLeftMargin'; Kind='bool' }
- @{ Tag='CellHyperlink'; Key='cellHyperlink'; Kind='bool' }
- @{ Tag='ViewMode'; Key='viewMode'; Kind='value' }
- @{ Tag='VerticalScrollBar'; Key='verticalScrollBar'; Kind='value' }
- @{ Tag='RowInputMode'; Key='rowInputMode'; Kind='value' }
- @{ Tag='Mask'; Key='mask'; Kind='value' }
- @{ Tag='CreateButton'; Key='createButton'; Kind='bool' }
- @{ Tag='FixingInTable'; Key='fixingInTable'; Kind='value' }
- @{ Tag='VerticalSpacing'; Key='verticalSpacing'; Kind='value' }
- # Спец-поля (документ/датчик) — типоспец. enum/bool скаляры pass-through (зеркало компилятора)
- @{ Tag='HorizontalScrollBar'; Key='horizontalScrollBar'; Kind='value' }
- @{ Tag='ViewScalingMode'; Key='viewScalingMode'; Kind='value' }
- @{ Tag='Output'; Key='output'; Kind='value' }
- @{ Tag='SelectionShowMode'; Key='selectionShowMode'; Kind='value' }
- @{ Tag='PointerType'; Key='pointerType'; Kind='value' }
- @{ Tag='DrawingSelectionShowMode'; Key='drawingSelectionShowMode'; Kind='value' }
- @{ Tag='WarningOnEditRepresentation'; Key='warningOnEditRepresentation'; Kind='value' }
- @{ Tag='MarkingAppearance'; Key='markingAppearance'; Kind='value' }
- @{ Tag='Protection'; Key='protection'; Kind='bool' }
- @{ Tag='Edit'; Key='edit'; Kind='bool' }
- @{ Tag='ShowGrid'; Key='showGrid'; Kind='bool' }
- @{ Tag='ShowGroups'; Key='showGroups'; Kind='bool' }
- @{ Tag='ShowHeaders'; Key='showHeaders'; Kind='bool' }
- @{ Tag='ShowRowAndColumnNames'; Key='showRowAndColumnNames'; Kind='bool' }
- @{ Tag='ShowCellNames'; Key='showCellNames'; Kind='bool' }
- @{ Tag='ShowPercent'; Key='showPercent'; Kind='bool' }
- # Report-form контекст: интервал группы / представление кнопки в контекстном меню / детальное представление настройки таблицы
- @{ Tag='HorizontalSpacing'; Key='horizontalSpacing'; Kind='value' }
- @{ Tag='RepresentationInContextMenu'; Key='representationInContextMenu'; Kind='value' }
- @{ Tag='SettingsNamedItemDetailedRepresentation'; Key='settingsNamedItemDetailedRepresentation'; Kind='bool' }
- # Хвост: высота элемента списка (radio) / ширина выпадающего списка (input)
- @{ Tag='ItemHeight'; Key='itemHeight'; Kind='value' }
- @{ Tag='DropListWidth'; Key='dropListWidth'; Kind='value' }
- # Хвост CI-форм: динамический заголовок (Page/Group) / расширенное ред. (input) / высота таблицы по строкам
- @{ Tag='TitleDataPath'; Key='titleDataPath'; Kind='value' }
- @{ Tag='ExtendedEdit'; Key='extendedEdit'; Kind='bool' }
- @{ Tag='MaxRowsCount'; Key='maxRowsCount'; Kind='value' }
- @{ Tag='AutoMaxRowsCount'; Key='autoMaxRowsCount'; Kind='bool' }
- @{ Tag='HeightControlVariant'; Key='heightControlVariant'; Kind='value' }
- @{ Tag='EditTextUpdate'; Key='editTextUpdate'; Kind='value' }
- # Корпусный хвост (zеркало компилятора): свёртка группы / форма попапа / авто-добавление /
- # выделение отрицательных / нач. позиция списка / высота списка выбора / три состояния / прокрутка
- @{ Tag='ControlRepresentation'; Key='controlRepresentation'; Kind='value' }
- @{ Tag='ShapeRepresentation'; Key='shapeRepresentation'; Kind='value' }
- @{ Tag='AutoAddIncomplete'; Key='autoAddIncomplete'; Kind='bool' }
- @{ Tag='MarkNegatives'; Key='markNegatives'; Kind='bool' }
- @{ Tag='InitialListView'; Key='initialListView'; Kind='value' }
- @{ Tag='ChoiceListHeight'; Key='choiceListHeight'; Kind='value' }
- @{ Tag='ThreeState'; Key='threeState'; Kind='bool' }
- @{ Tag='ScrollOnCompress'; Key='scrollOnCompress'; Kind='bool' }
- # Сочетание клавиш — общее свойство элемента (команда — отдельный путь)
- @{ Tag='Shortcut'; Key='shortcut'; Kind='value' }
- # Батч простых скаляров (зеркало компилятора; Table HeaderHeight/FooterHeight/CurrentRowUse — отдельно)
- @{ Tag='IncompleteChoiceMode'; Key='incompleteChoiceMode'; Kind='value' }
- @{ Tag='EqualColumnsWidth'; Key='equalColumnsWidth'; Kind='bool' }
- @{ Tag='ChildrenAlign'; Key='childrenAlign'; Kind='value' }
- @{ Tag='ImageScale'; Key='imageScale'; Kind='value' }
- @{ Tag='Zoomable'; Key='zoomable'; Kind='bool' }
- @{ Tag='Shape'; Key='shape'; Kind='value' }
- @{ Tag='PictureLocation'; Key='pictureLocation'; Kind='value' }
- # Равная ширина элементов (check/radio) / высота заголовка пункта (radio)
- @{ Tag='EqualItemsWidth'; Key='equalItemsWidth'; Kind='bool' }
- @{ Tag='ItemTitleHeight'; Key='itemTitleHeight'; Kind='value' }
- # Спец-режим ввода текста (input, моб.: Email/PhoneNumber/...) — листовой enum-скаляр
- @{ Tag='SpecialTextInputMode'; Key='specialTextInputMode'; Kind='value' }
- # Ширина пункта (radio/check) / выбор нескольких значений из выпадающего (input)
- @{ Tag='ItemWidth'; Key='itemWidth'; Kind='value' }
- @{ Tag='ShowCheckBoxesInDropList'; Key='showCheckBoxesInDropList'; Kind='bool' }
- @{ Tag='MultipleValueDataPath'; Key='multipleValueDataPath'; Kind='value' }
- @{ Tag='MultipleValuePresentDataPath'; Key='multipleValuePresentDataPath'; Kind='value' }
- # Режим авто-показа кнопок открытия/очистки (input, enum)
- @{ Tag='AutoShowOpenButtonMode'; Key='autoShowOpenButtonMode'; Kind='value' }
- @{ Tag='AutoShowClearButtonMode'; Key='autoShowClearButtonMode'; Kind='value' }
- # Оформление/картинка множественного выбора (input, редко; цвета — текст-контент)
- @{ Tag='MultipleValuesTextColor'; Key='multipleValuesTextColor'; Kind='value' }
- @{ Tag='MultipleValuesBackColor'; Key='multipleValuesBackColor'; Kind='value' }
- @{ Tag='MultipleValuePictureShape'; Key='multipleValuePictureShape'; Kind='value' }
- @{ Tag='MultipleValuePictureDataPath'; Key='multipleValuePictureDataPath'; Kind='value' }
- # Хвост листовых скаляров (по 1): автокоррекция / уникальность команды / пустое множ.значение / гориз.сжатие
- @{ Tag='AutoCorrectionOnTextInput'; Key='autoCorrectionOnTextInput'; Kind='value' }
- @{ Tag='SpellCheckingOnTextInput'; Key='spellCheckingOnTextInput'; Kind='value' }
- @{ Tag='CommandUniqueness'; Key='commandUniqueness'; Kind='bool' }
- @{ Tag='AllowInputEmptyMultipleValues'; Key='allowInputEmptyMultipleValues'; Kind='bool' }
- @{ Tag='BehaviorOnHorizontalCompression'; Key='behaviorOnHorizontalCompression'; Kind='value' }
- )
- # Захват generic-скаляров. Специфичная обработка (если ключ уже задан) — побеждает.
- function Add-GenericScalars {
- param($obj, $node)
- foreach ($s in $GENERIC_SCALARS) {
- if ($obj.Contains($s.Key)) { continue }
- $v = Get-Child $node $s.Tag
- if ($null -eq $v) { continue }
- if ($s.Kind -eq 'bool') { $obj[$s.Key] = ($v -eq 'true') } else { $obj[$s.Key] = $v }
- }
- }
- function Decompile-Children {
- param($parentNode, [string]$childContainer = 'ChildItems')
- $container = $parentNode.SelectSingleNode("lf:$childContainer", $ns)
- if (-not $container) { return $null }
- $list = New-Object System.Collections.ArrayList
- foreach ($child in $container.ChildNodes) {
- if ($child.NodeType -ne [System.Xml.XmlNodeType]::Element) { continue }
- if ($COMPANION_TAGS -contains $child.LocalName) { continue }
- $el = Decompile-Element $child
- if ($el) { [void]$list.Add($el) }
- }
- if ($list.Count -eq 0) { return $null }
- return ,@($list)
- }
- # Инверсия Emit-CompanionPanel: companion-командная-панель (ContextMenu/AutoCommandBar) с контентом
- # → { autofill?, horizontalAlign?, children?[] } либо $null, если companion пустой (self-closing).
- # Дин-список-таблица: компилятор-эвристика додумывает Autofill=false. Выражаем только ОТКЛОНЕНИЕ:
- # autofill=false (нет детей) → совпадает с дефолтом → молчим;
- # голый <AutoCommandBar/> (autofill=true по умолчанию) → маркер { autofill: true } (панель не скрыта).
- function Decompile-CompanionPanel {
- param($node, [string]$tag, [bool]$isDynListTable = $false)
- $p = $node.SelectSingleNode("lf:$tag", $ns)
- if (-not $p) { return $null }
- $autofillRaw = Get-Child $p 'Autofill'
- $halign = Get-Child $p 'HorizontalAlign'
- $kids = Decompile-Children $p
- $hasKids = $kids -and @($kids).Count -gt 0
- if ($isDynListTable -and $tag -eq 'AutoCommandBar' -and -not $hasKids -and -not $halign) {
- if ($autofillRaw -eq 'false') { return $null } # = дефолт эвристики → молчим
- return [ordered]@{ autofill = $true } # голая панель → отклонение
- }
- if (-not $hasKids -and $null -eq $autofillRaw -and -not $halign) { return $null }
- $o = [ordered]@{}
- if ($halign) { $o['horizontalAlign'] = $halign }
- if ($autofillRaw -eq 'false') { $o['autofill'] = $false }
- elseif ($autofillRaw -eq 'true') { $o['autofill'] = $true }
- if ($hasKids) { $o['children'] = $kids }
- return $o
- }
- # Инверсия Emit-ChoiceList: <ChoiceList><xr:Item>… → [ { value, presentation? } ] либо $null.
- # У RadioButtonField и InputField.
- function Decompile-ChoiceList {
- param($node)
- $cl = $node.SelectSingleNode("lf:ChoiceList", $ns)
- if (-not $cl) { return $null }
- $items = New-Object System.Collections.ArrayList
- foreach ($it in @($cl.SelectNodes("xr:Item", $ns))) {
- $valNode = $it.SelectSingleNode("xr:Value/lf:Value", $ns)
- $presNode = $it.SelectSingleNode("xr:Value/lf:Presentation", $ns)
- $ci = [ordered]@{}
- if ($valNode) {
- if ($valNode.GetAttribute("nil", $NS_XSI) -eq 'true') {
- # nil-значение элемента choiceList — компилятор эмитит <Value xsi:nil="true"/>
- # (иначе Convert-TypedValue вернул бы "" → typed-empty xs:string).
- $ci['valueType'] = 'nil'
- } else {
- $xsiType = $valNode.GetAttribute("type", $NS_XSI)
- $ci['value'] = Convert-TypedValue $valNode.InnerText $xsiType
- # Системное перечисление (ent:*) / иной не-примитивный тип → сохраняем valueType
- # (Normalize-ChoiceValue вывела бы xs:string). DesignTimeRef обычно авто-детектится
- # компилятором по named-ref (Enum.X.Y), НО raw-ссылка по GUID (GUID.GUID) — нет → сохраняем.
- if ($xsiType -and $xsiType -notmatch '^xs:(string|decimal|boolean|dateTime)$' -and `
- ($xsiType -ne 'xr:DesignTimeRef' -or "$($valNode.InnerText)" -match '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-')) {
- $ci['valueType'] = $xsiType
- }
- }
- }
- # Presentation: непустой → текст/мультиязык; пустой <Presentation/> → "" — суппресс-маркер,
- # подавляет авто-вывод компилятора (иначе компилятор додумает presentation из значения).
- if ($presNode) {
- $p = Get-LangTextWS $presNode # восстановление значимого пробела (whitespace-presentation)
- if ($null -ne $p -and $p -ne '') { $ci['presentation'] = $p } else { $ci['presentation'] = '' }
- }
- [void]$items.Add($ci)
- }
- if ($items.Count -gt 0) { return ,@($items) }
- return $null
- }
- # Значение Параметра выбора (<lf:Value>): скаляр через Convert-TypedValue, либо
- # v8:FixedArray → массив скаляров (каждый — FormChoiceListDesTimeValue с внутренним lf:Value).
- function Convert-ChoiceParamValue {
- param($valNode)
- $vt = $valNode.GetAttribute("type", $NS_XSI)
- if ($vt -match 'FixedArray$') {
- $arr = New-Object System.Collections.ArrayList
- foreach ($it in @($valNode.SelectNodes("v8:Value", $ns))) {
- $inner = $it.SelectSingleNode("lf:Value", $ns)
- if ($inner) { [void]$arr.Add((Convert-TypedValue -raw $inner.InnerText -xsiType ($inner.GetAttribute("type", $NS_XSI)))) }
- }
- return ,@($arr)
- }
- return Convert-TypedValue -raw $valNode.InnerText -xsiType $vt
- }
- # Инверсия Emit-ChoiceParameters: <ChoiceParameters><app:item name="X"><app:value><Value…> → [{name, value}].
- function Decompile-ChoiceParameters {
- param($node)
- $cpn = $node.SelectSingleNode("lf:ChoiceParameters", $ns)
- if (-not $cpn) { return $null }
- $items = New-Object System.Collections.ArrayList
- foreach ($it in @($cpn.SelectNodes("app:item", $ns))) {
- $o = [ordered]@{}
- $o['name'] = $it.GetAttribute("name")
- $valNode = $it.SelectSingleNode("app:value/lf:Value", $ns)
- if ($valNode) { $o['value'] = Convert-ChoiceParamValue $valNode }
- [void]$items.Add($o)
- }
- if ($items.Count -gt 0) { return ,@($items) }
- return $null
- }
- # Инверсия Emit-ChoiceParameterLinks: <ChoiceParameterLinks><xr:Link><xr:Name><xr:DataPath><xr:ValueChange> →
- # [{name, dataPath, valueChange?}]. valueChange дефолт Clear → опускаем (компилятор восстановит).
- function Decompile-ChoiceParameterLinks {
- param($node)
- $cln = $node.SelectSingleNode("lf:ChoiceParameterLinks", $ns)
- if (-not $cln) { return $null }
- $items = New-Object System.Collections.ArrayList
- foreach ($lk in @($cln.SelectNodes("xr:Link", $ns))) {
- $o = [ordered]@{}
- $o['name'] = Get-Text $lk "xr:Name"
- $o['dataPath'] = Get-Text $lk "xr:DataPath"
- $vc = Get-Text $lk "xr:ValueChange"
- if ($vc -and $vc -ne 'Clear') { $o['valueChange'] = $vc }
- [void]$items.Add($o)
- }
- if ($items.Count -gt 0) { return ,@($items) }
- return $null
- }
- # Инверсия Emit-TypeLink: <TypeLink><xr:DataPath><xr:LinkItem> → {dataPath, linkItem}.
- function Decompile-TypeLink {
- param($node)
- $tn = $node.SelectSingleNode("lf:TypeLink", $ns)
- if (-not $tn) { return $null }
- $o = [ordered]@{}
- $o['dataPath'] = Get-Text $tn "xr:DataPath"
- $li = Get-Text $tn "xr:LinkItem"
- if ($null -ne $li -and $li -ne '') { $o['linkItem'] = [int]$li }
- return $o
- }
- # Захват <Format>/<EditFormat> (LocalStringType) → format/editFormat (строка или {ru,en}).
- function Add-FormatProps {
- param($obj, $node)
- $fmt = $node.SelectSingleNode("lf:Format", $ns); if ($fmt) { $t = Get-LangText $fmt; if ($null -ne $t -and $t -ne '') { $obj['format'] = $t } }
- $efmt = $node.SelectSingleNode("lf:EditFormat", $ns); if ($efmt) { $t = Get-LangText $efmt; if ($null -ne $t -and $t -ne '') { $obj['editFormat'] = $t } }
- }
- # Ядро дополнения: source + общие свойства (Add-CommonProps) + horizontalLocation.
- # Layout (Add-Layout) добавляется ОТДЕЛЬНО (в Decompile-Element — пост-обработкой, в standalone — явно).
- function Add-AdditionCore {
- param($obj, $node, [string]$elName)
- $src = $node.SelectSingleNode("lf:AdditionSource/lf:Item", $ns); if ($src) { $obj['source'] = $src.InnerText }
- Add-CommonProps $obj $node $elName
- $hl = Get-Child $node 'HorizontalLocation'; if ($hl) { $obj['horizontalLocation'] = $hl.ToLower() }
- }
- # Стандартные дополнения уровня таблицы (прямые дети <Table>): извлечь ТОЛЬКО отклонения в карту
- # { тип: {свойства} }. Имя (=tableName+suffix) и source (=tableName) — дефолтные, опускаем.
- function Decompile-TableAdditions {
- param($tableNode, [string]$tableName)
- $tagToKey = @{ 'SearchStringAddition'='searchString'; 'ViewStatusAddition'='viewStatus'; 'SearchControlAddition'='searchControl' }
- $map = [ordered]@{}
- foreach ($child in $tableNode.ChildNodes) {
- if ($child.NodeType -ne [System.Xml.XmlNodeType]::Element) { continue }
- if (-not $tagToKey.ContainsKey($child.LocalName)) { continue }
- $key = $tagToKey[$child.LocalName]
- $nm = $child.GetAttribute("name")
- $o = [ordered]@{}; $o[$key] = $nm
- Add-AdditionCore $o $child $nm
- Add-Layout $o $child
- $o.Remove($key) # имя авто
- if ($o.Contains('source') -and $o['source'] -eq $tableName) { $o.Remove('source') } # source=таблица дефолт
- if ($o.Count -gt 0) { $map[$key] = $o }
- }
- if ($map.Count -gt 0) { return $map }
- return $null
- }
- # Спец-поля «документ/датчик» — общий скелет поля (имя/path/CommonProps/TitleLocation/editMode).
- # Типоспец. enum/bool скаляры ловит пост-switch Add-GenericScalars; layout/companions — общий хвост.
- function Decompile-SimpleField {
- param($obj, $node, [string]$name, [string]$key)
- $obj[$key] = $name
- $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
- Add-CommonProps $obj $node $name
- $tl = Get-Child $node 'TitleLocation'; if ($tl) { $obj['titleLocation'] = $tl.ToLower() }
- $em = Get-Child $node 'EditMode'; if ($em) { $obj['editMode'] = $em }
- }
- # Числовые скаляры датчиков (ProgressBar/TrackBar) — без xsi:type (≠ типизированных InputField).
- function Add-GaugeScalars {
- param($obj, $node, $tags)
- foreach ($p in $tags) {
- $v = Get-Child $node $p
- if ($null -eq $v) { continue }
- $key = $p.Substring(0,1).ToLower() + $p.Substring(1)
- if ($v -match '^-?\d+$') { $obj[$key] = [int]$v } else { $obj[$key] = $v }
- }
- }
- function Decompile-Element {
- param($node)
- $tag = $node.LocalName
- if (-not $ELEMENT_KEY.ContainsKey($tag)) {
- Fail-Ring3 -kind "элемент <$tag>" -loc "ChildItems/$tag"
- }
- $key = $ELEMENT_KEY[$tag]
- $name = $node.GetAttribute("name")
- $obj = [ordered]@{}
- switch ($tag) {
- 'UsualGroup' {
- # group = направление (<Group>); behavior = <Behavior> (Авто = нет тега → ключ опускаем).
- # group = направление (<Group>). Нет тега → '' (тип-маркер сохраняется, направление
- # не эмитим). Платформа явно пишет Vertical в большинстве случаев, поэтому '' ≠ 'vertical'
- # — иначе компилятор додумает <Group>Vertical</Group> там, где его нет.
- $g = Get-Child $node 'Group'
- $gmap = @{ 'Horizontal'='horizontal'; 'Vertical'='vertical'; 'AlwaysHorizontal'='alwaysHorizontal'; 'AlwaysVertical'='alwaysVertical'; 'HorizontalIfPossible'='horizontalIfPossible' }
- if ($g -and $gmap.ContainsKey($g)) { $obj[$key] = $gmap[$g] } else { $obj[$key] = '' }
- $behavior = Get-Child $node 'Behavior'
- if ($behavior) {
- $bmap = @{ 'Usual'='usual'; 'Collapsible'='collapsible'; 'PopUp'='popup' }
- if ($bmap.ContainsKey($behavior)) { $obj['behavior'] = $bmap[$behavior] } else { $obj['behavior'] = $behavior }
- }
- $obj['name'] = $name
- Add-CommonProps $obj $node $name
- $rep = Get-Child $node 'Representation'
- if ($rep) { $repmap=@{'None'='none';'NormalSeparation'='normal';'WeakSeparation'='weak';'StrongSeparation'='strong'}; if ($repmap.ContainsKey($rep)) { $obj['representation']=$repmap[$rep] } else { $obj['representation']=$rep } }
- # Зеркало компилятора. Обычная группа без showTitle: с заголовком (title/titleDataPath) — показан, без — скрыт; ключ
- # пишется, только когда факт расходится с этим умолчанием. Сворачиваемая/всплывающая — факт. значение.
- $st = Get-Child $node 'ShowTitle'
- if (@('Collapsible','PopUp') -contains $behavior) { if ($null -ne $st) { $obj['showTitle'] = ($st -eq 'true') } }
- elseif ($obj['title'] -or (Get-Child $node 'TitleDataPath')) { if ($st -eq 'false') { $obj['showTitle'] = $false } }
- elseif ($st -ne 'false') { $obj['showTitle'] = $true }
- $cru = Get-Child $node 'CurrentRowUse'; if ($cru) { $obj['currentRowUse'] = $cru } # использование текущей строки группы
- $crt = $node.SelectSingleNode("lf:CollapsedRepresentationTitle", $ns); if ($crt) { $ct = Get-LangText $crt; if ($null -ne $ct -and $ct -ne '') { $obj['collapsedTitle'] = $ct } }
- if ((Get-Child $node 'United') -eq 'false') { $obj['united'] = $false }
- if ((Get-Child $node 'Collapsed') -eq 'true') { $obj['collapsed'] = $true }
- # Формат значения пути к данным заголовка (<Format>; парный к titleDataPath группы)
- Add-FormatProps $obj $node
- $kids = Decompile-Children $node
- if ($kids) { $obj['children'] = $kids }
- }
- 'ColumnGroup' {
- # columnGroup = направление (<Group>). Нет тега → '' (тип-маркер сохраняется, направление
- # не эмитим). Иначе компилятор додумает <Group>Horizontal</Group> там, где его нет.
- $g = Get-Child $node 'Group'
- $gmap = @{ 'Horizontal'='horizontal'; 'Vertical'='vertical'; 'InCell'='inCell' }
- if ($g -and $gmap.ContainsKey($g)) { $obj[$key] = $gmap[$g] } else { $obj[$key] = '' }
- $obj['name'] = $name
- Add-CommonProps $obj $node $name
- $st = Get-Child $node 'ShowTitle'; if ($null -ne $st) { $obj['showTitle'] = ($st -eq 'true') } # факт. значение (явный true тоже)
- $sih = Get-Child $node 'ShowInHeader'; if ($null -ne $sih) { $obj['showInHeader'] = (To-Bool $sih) }
- $kids = Decompile-Children $node
- if ($kids) { $obj['children'] = $kids }
- }
- 'InputField' {
- $obj[$key] = $name
- $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
- Add-CommonProps $obj $node $name
- # MultiLine: факт. значение (платформа эмитит и явный false — 425 в корпусе; ≠ «if true»)
- $mlIn = Get-Child $node 'MultiLine'; if ($null -ne $mlIn) { $obj['multiLine'] = ($mlIn -eq 'true') }
- # PasswordMode: факт. значение (платформа эмитит и false — 349/504 в корпусе; ≠ «if true»)
- $pmIn = Get-Child $node 'PasswordMode'; if ($null -ne $pmIn) { $obj['passwordMode'] = ($pmIn -eq 'true') }
- $mi = Get-Child $node 'AutoMarkIncomplete'; if ($null -ne $mi) { $obj['markIncomplete'] = ($mi -eq 'true') }
- $em = Get-Child $node 'EditMode'; if ($em) { $obj['editMode'] = $em }
- $tl = Get-Child $node 'TitleLocation'; if ($tl) { $obj['titleLocation'] = $tl.ToLower() }
- $ih = $node.SelectSingleNode("lf:InputHint", $ns); if ($ih) { $t = Get-LangTextWS $ih; if ($t) { $obj['inputHint'] = $t } }
- $woe = $node.SelectSingleNode("lf:WarningOnEdit", $ns); if ($woe) { $t = Get-LangTextWS $woe; if ($null -ne $t) { $obj['warningOnEdit'] = $t } }
- $ftxt = $node.SelectSingleNode("lf:FooterText", $ns); if ($ftxt) { $t = Get-LangTextWS $ftxt; if ($null -ne $t) { $obj['footerText'] = $t } }
- foreach ($p in @('ChoiceButton','ClearButton','SpinButton','DropListButton','ChoiceListButton')) {
- $v = Get-Child $node $p; if ($null -ne $v) { $obj[($p.Substring(0,1).ToLower()+$p.Substring(1))] = (To-Bool $v) }
- }
- # InputField-специфичные bool-скаляры (захват «как есть»)
- foreach ($p in @('Wrap','OpenButton','ListChoiceMode','ExtendedEditMultipleValues','ChooseType','QuickChoice','AutoChoiceIncomplete')) {
- $v = Get-Child $node $p; if ($null -ne $v) { $obj[($p.Substring(0,1).ToLower()+$p.Substring(1))] = (To-Bool $v) }
- }
- # InputField-специфичные value-скаляры (захват «как есть»)
- foreach ($p in @('ChoiceForm','ChoiceHistoryOnInput','ChoiceFoldersAndItems','FooterDataPath')) {
- $v = Get-Child $node $p; if ($null -ne $v) { $obj[($p.Substring(0,1).ToLower()+$p.Substring(1))] = $v }
- }
- # MinValue/MaxValue — типизированное (<MinValue xsi:type="xs:decimal">N). Тип кодируем в JSON-тип:
- # xs:decimal/int → число (компилятор → xs:decimal), иначе → строка (компилятор → xs:string).
- foreach ($p in @('MinValue','MaxValue')) {
- $mn = $node.SelectSingleNode("lf:$p", $ns)
- if ($mn) {
- $xt = $mn.GetAttribute("type", $NS_XSI); $txt = $mn.InnerText
- $key = $p.Substring(0,1).ToLower() + $p.Substring(1)
- if ($xt -match 'decimal|int') {
- if ($txt -match '^-?\d+$') { $obj[$key] = [int]$txt } elseif ($txt -match '^-?\d+\.\d+$') { $obj[$key] = [decimal]$txt } else { $obj[$key] = $txt }
- } else { $obj[$key] = $txt }
- }
- }
- # Ограничение доступных типов (поле на составном/характеристика-типе): домен типов + явный набор.
- # availableTypes — тот же формат типа, что у реквизитов (§type), захват через Decompile-Type.
- $tde = Get-Child $node 'TypeDomainEnabled'; if ($null -ne $tde) { $obj['typeDomainEnabled'] = (To-Bool $tde) }
- $atNode = $node.SelectSingleNode("lf:AvailableTypes", $ns); if ($atNode) { $at = Decompile-Type $atNode; if ($at) { $obj['availableTypes'] = $at } }
- $cbr = Get-Child $node 'ChoiceButtonRepresentation'; if ($cbr) { $obj['choiceButtonRepresentation'] = $cbr }
- $cbp = Get-PictureRef $node 'ChoiceButtonPicture'; if ($null -ne $cbp) { $obj['choiceButtonPicture'] = $cbp }
- if ((Get-Child $node 'TextEdit') -eq 'false') { $obj['textEdit'] = $false }
- $cl = Decompile-ChoiceList $node; if ($cl) { $obj['choiceList'] = $cl }
- Add-FormatProps $obj $node
- # Параметры выбора / Связи параметров выбора / Связь по типу
- $cp = Decompile-ChoiceParameters $node; if ($cp) { $obj['choiceParameters'] = $cp }
- $cpl = Decompile-ChoiceParameterLinks $node; if ($cpl) { $obj['choiceParameterLinks'] = $cpl }
- $tlk = Decompile-TypeLink $node; if ($tlk) { $obj['typeLink'] = $tlk }
- }
- 'CheckBoxField' {
- $obj[$key] = $name
- $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
- Add-CommonProps $obj $node $name
- $em = Get-Child $node 'EditMode'; if ($em) { $obj['editMode'] = $em }
- # CheckBoxType: Auto = умный дефолт → опустить; нет тега → ""; иначе значение
- $cbt = Get-Child $node 'CheckBoxType'
- if ($null -eq $cbt) { $obj['checkBoxType'] = '' }
- elseif ($cbt -ne 'Auto') { $obj['checkBoxType'] = $cbt.Substring(0,1).ToLower() + $cbt.Substring(1) }
- Add-TitleLocation $obj $node 'Right'
- $woe = $node.SelectSingleNode("lf:WarningOnEdit", $ns); if ($woe) { $t = Get-LangTextWS $woe; if ($null -ne $t) { $obj['warningOnEdit'] = $t } }
- # FooterDataPath / FooterText — общие cell-свойства колонки (как у input/labelField)
- $fdp = Get-Child $node 'FooterDataPath'; if ($fdp) { $obj['footerDataPath'] = $fdp }
- $ftxt = $node.SelectSingleNode("lf:FooterText", $ns); if ($ftxt) { $t = Get-LangTextWS $ftxt; if ($null -ne $t) { $obj['footerText'] = $t } }
- Add-FormatProps $obj $node
- }
- 'RadioButtonField' {
- $obj[$key] = $name
- $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
- Add-CommonProps $obj $node $name
- Add-TitleLocation $obj $node 'None'
- $em = Get-Child $node 'EditMode'; if ($em) { $obj['editMode'] = $em }
- $rbt = Get-Child $node 'RadioButtonType'; if ($rbt) { $obj['radioButtonType'] = $rbt }
- $cc = Get-Child $node 'ColumnsCount'; if ($cc) { $obj['columnsCount'] = [int]$cc }
- $woe = $node.SelectSingleNode("lf:WarningOnEdit", $ns); if ($woe) { $t = Get-LangTextWS $woe; if ($null -ne $t) { $obj['warningOnEdit'] = $t } }
- $cl = Decompile-ChoiceList $node; if ($cl) { $obj['choiceList'] = $cl }
- }
- 'LabelDecoration' {
- $obj[$key] = $name
- Add-CommonProps $obj $node $name
- if ((Get-Child $node 'Hyperlink') -eq 'true') { $obj['hyperlink'] = $true }
- # title декорации — единая ML-text форма с авто-детектом formatted (как extendedTooltip)
- $tiNode = $node.SelectSingleNode("lf:Title", $ns)
- if ($tiNode) { $tv = Get-MLFormattedValue $tiNode; if ($null -ne $tv) { $obj['title'] = $tv } }
- }
- 'LabelField' {
- $obj[$key] = $name
- $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
- Add-CommonProps $obj $node $name
- $tl = Get-Child $node 'TitleLocation'; if ($tl) { $obj['titleLocation'] = $tl.ToLower() }
- $em = Get-Child $node 'EditMode'; if ($em) { $obj['editMode'] = $em }
- # LabelField: тег <Hiperlink> (опечатка платформы), не <Hyperlink>
- if ((Get-Child $node 'Hiperlink') -eq 'true') { $obj['hyperlink'] = $true }
- # PasswordMode на LabelField — платформа эмитит явный false (редко); захват факт. значения
- $pm = Get-Child $node 'PasswordMode'; if ($null -ne $pm) { $obj['passwordMode'] = ($pm -eq 'true') }
- $woe = $node.SelectSingleNode("lf:WarningOnEdit", $ns); if ($woe) { $t = Get-LangTextWS $woe; if ($null -ne $t) { $obj['warningOnEdit'] = $t } }
- # FooterDataPath / FooterText — общие cell-свойства колонки (как у input), не только input
- $fdp = Get-Child $node 'FooterDataPath'; if ($fdp) { $obj['footerDataPath'] = $fdp }
- $ftxt = $node.SelectSingleNode("lf:FooterText", $ns); if ($ftxt) { $t = Get-LangTextWS $ftxt; if ($null -ne $t) { $obj['footerText'] = $t } }
- Add-FormatProps $obj $node
- }
- 'PictureDecoration' {
- $obj[$key] = $name
- Add-CommonProps $obj $node $name
- # title декорации — единая ML-text форма с formatted (атрибут <Title formatted> у PictureDecoration)
- $tiNode = $node.SelectSingleNode("lf:Title", $ns)
- if ($tiNode) { $tv = Get-MLFormattedValue $tiNode; if ($null -ne $tv) { $obj['title'] = $tv } }
- $npt = $node.SelectSingleNode("lf:NonselectedPictureText", $ns); if ($npt) { $t = Get-LangTextWS $npt; if ($null -ne $t) { $obj['nonselectedPictureText'] = $t } }
- $ref = $node.SelectSingleNode("lf:Picture/xr:Ref", $ns)
- $abs = $node.SelectSingleNode("lf:Picture/xr:Abs", $ns)
- if ($ref) { $obj['src'] = $ref.InnerText } elseif ($abs) { $obj['src'] = "abs:$($abs.InnerText)" } # встроенная картинка → префикс abs:
- $lt = $node.SelectSingleNode("lf:Picture/xr:LoadTransparent", $ns); if ($lt -and $lt.InnerText -eq 'true') { $obj['loadTransparent'] = $true }
- # Прозрачный пиксель картинки (<xr:TransparentPixel x y/>) — координаты фона прозрачности
- $tpx = $node.SelectSingleNode("lf:Picture/xr:TransparentPixel", $ns)
- if ($tpx) { $obj['transparentPixel'] = [ordered]@{ x = [int]$tpx.GetAttribute('x'); y = [int]$tpx.GetAttribute('y') } }
- if ((Get-Child $node 'Hyperlink') -eq 'true') { $obj['hyperlink'] = $true }
- }
- 'PictureField' {
- $obj[$key] = $name
- $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
- Add-CommonProps $obj $node $name
- $em = Get-Child $node 'EditMode'; if ($em) { $obj['editMode'] = $em }
- $tl = Get-Child $node 'TitleLocation'; if ($tl) { $obj['titleLocation'] = $tl.ToLower() }
- if ((Get-Child $node 'Hyperlink') -eq 'true') { $obj['hyperlink'] = $true }
- $vp = Get-PictureRef $node 'ValuesPicture'; if ($null -ne $vp) { $obj['valuesPicture'] = $vp }
- $npt = $node.SelectSingleNode("lf:NonselectedPictureText", $ns); if ($npt) { $t = Get-LangTextWS $npt; if ($null -ne $t) { $obj['nonselectedPictureText'] = $t } }
- # FooterDataPath / FooterText — общие cell-свойства колонки (как у input/labelField)
- $fdp = Get-Child $node 'FooterDataPath'; if ($fdp) { $obj['footerDataPath'] = $fdp }
- $ftxt = $node.SelectSingleNode("lf:FooterText", $ns); if ($ftxt) { $t = Get-LangTextWS $ftxt; if ($null -ne $t) { $obj['footerText'] = $t } }
- }
- 'CalendarField' {
- $obj[$key] = $name
- $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
- Add-CommonProps $obj $node $name
- $tl = Get-Child $node 'TitleLocation'; if ($tl) { $obj['titleLocation'] = $tl.ToLower() }
- $sm = Get-Child $node 'SelectionMode'; if ($sm) { $obj['selectionMode'] = $sm }
- $scd = Get-Child $node 'ShowCurrentDate'; if ($null -ne $scd) { $obj['showCurrentDate'] = ($scd -eq 'true') }
- $wim = Get-Child $node 'WidthInMonths'; if ($null -ne $wim) { $obj['widthInMonths'] = [int]$wim }
- $him = Get-Child $node 'HeightInMonths'; if ($null -ne $him) { $obj['heightInMonths'] = [int]$him }
- $smp = Get-Child $node 'ShowMonthsPanel'; if ($null -ne $smp) { $obj['showMonthsPanel'] = ($smp -eq 'true') }
- }
- 'Table' {
- $obj[$key] = $name
- $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
- Add-CommonProps $obj $node $name
- $tl = Get-Child $node 'TitleLocation'; if ($tl) { $obj['titleLocation'] = $tl.ToLower() }
- $rep = Get-Child $node 'Representation'; if ($rep) { $obj['representation'] = $rep }
- $crs = Get-Child $node 'ChangeRowSet'; if ($null -ne $crs) { $obj['changeRowSet'] = ($crs -eq 'true') }
- $cro = Get-Child $node 'ChangeRowOrder'; if ($null -ne $cro) { $obj['changeRowOrder'] = ($cro -eq 'true') }
- if ((Get-Child $node 'AutoInsertNewRow') -eq 'true') { $obj['autoInsertNewRow'] = $true }
- # enableDrag — теперь общий (Add-Layout, фактическое значение)
- if ($node.SelectSingleNode("lf:RowFilter", $ns)) { $obj['rowFilter'] = $null }
- if ((Get-Child $node 'Header') -eq 'false') { $obj['header'] = $false }
- if ((Get-Child $node 'Footer') -eq 'true') { $obj['footer'] = $true }
- # Высота в строках — отдельный ключ heightInTableRows (≠ height = <Height>, его ловит Add-Layout)
- $htr = Get-Child $node 'HeightInTableRows'; if ($htr) { $obj['heightInTableRows'] = [int]$htr }
- # Высота шапки/подвала таблицы в строках (pass-through; компилятор эмитит в Emit-Table)
- $hh = Get-Child $node 'HeaderHeight'; if ($null -ne $hh) { $obj['headerHeight'] = [int]$hh }
- $fh = Get-Child $node 'FooterHeight'; if ($null -ne $fh) { $obj['footerHeight'] = [int]$fh }
- # Использование текущей строки (Table-уровень; ≠ command-level CurrentRowUse) — pass-through
- $cru = Get-Child $node 'CurrentRowUse'; if ($cru) { $obj['currentRowUse'] = $cru }
- # Запрос обновления дин-списка (всегда PullFromTop в корпусе) — pass-through
- $rr = Get-Child $node 'RefreshRequest'; if ($rr) { $obj['refreshRequest'] = $rr }
- # CommandBarLocation: для дин-список-таблицы компилятор авто-инжектит "None" → инвертируем
- # (нет тега → суппресс-маркер ""; "None" → опускаем = авто-дефолт; иначе → захват).
- $cbl = Get-Child $node 'CommandBarLocation'
- if (Has-Child $node 'UpdateOnDataChange') {
- if ($null -eq $cbl) { $obj['commandBarLocation'] = '' }
- elseif ($cbl -ne 'None') { $obj['commandBarLocation'] = $cbl }
- } elseif ($cbl) { $obj['commandBarLocation'] = $cbl }
- $ssl = Get-Child $node 'SearchStringLocation'; if ($ssl) { $obj['searchStringLocation'] = $ssl }
- $vsl = Get-Child $node 'ViewStatusLocation'; if ($vsl) { $obj['viewStatusLocation'] = $vsl }
- $scl = Get-Child $node 'SearchControlLocation'; if ($scl) { $obj['searchControlLocation'] = $scl }
- # --- Общие свойства таблицы (любой тип таблицы, не только динсписок) ---
- if ((Get-Child $node 'ChoiceMode') -eq 'true') { $obj['choiceMode'] = $true }
- $selm = Get-Child $node 'SelectionMode'; if ($selm) { $obj['selectionMode'] = $selm }
- $rsm = Get-Child $node 'RowSelectionMode'; if ($rsm) { $obj['rowSelectionMode'] = $rsm }
- if ((Get-Child $node 'VerticalLines') -eq 'false') { $obj['verticalLines'] = $false }
- if ((Get-Child $node 'HorizontalLines') -eq 'false') { $obj['horizontalLines'] = $false }
- if ((Get-Child $node 'UseAlternationRowColor') -eq 'true') { $obj['useAlternationRowColor'] = $true }
- # Скаляры таблицы (захват «как есть»). Autofill — СВОЁ свойство таблицы (≠ AutoCommandBar autofill).
- $taf = Get-Child $node 'Autofill'; if ($null -ne $taf) { $obj['autofill'] = ($taf -eq 'true') }
- if ((Get-Child $node 'MultipleChoice') -eq 'true') { $obj['multipleChoice'] = $true }
- $soin = Get-Child $node 'SearchOnInput'; if ($soin) { $obj['searchOnInput'] = $soin }
- $mi = Get-Child $node 'AutoMarkIncomplete'; if ($null -ne $mi) { $obj['markIncomplete'] = ($mi -eq 'true') }
- $itv = Get-Child $node 'InitialTreeView'; if ($itv) { $obj['initialTreeView'] = $itv }
- # RowsPicture — конвенция ValuesPicture (Ref/Abs + LoadTransparent дефолт false + TransparentPixel)
- $rp = Get-PictureRef $node 'RowsPicture'; if ($null -ne $rp) { $obj['rowsPicture'] = $rp }
- $rpdp = Get-Child $node 'RowPictureDataPath'
- # --- Блок дин-список-таблицы (признак: дочерний <UpdateOnDataChange>) ---
- if (Has-Child $node 'UpdateOnDataChange') {
- if ((Get-Child $node 'AutoRefresh') -eq 'true') { $obj['autoRefresh'] = $true }
- $arp = Get-Child $node 'AutoRefreshPeriod'; if ($arp -and $arp -ne '60') { $obj['autoRefreshPeriod'] = [int]$arp }
- $cfi = Get-Child $node 'ChoiceFoldersAndItems'; if ($cfi -and $cfi -ne 'Items') { $obj['choiceFoldersAndItems'] = $cfi }
- if ((Get-Child $node 'RestoreCurrentRow') -eq 'true') { $obj['restoreCurrentRow'] = $true }
- if ((Get-Child $node 'ShowRoot') -eq 'false') { $obj['showRoot'] = $false }
- if ((Get-Child $node 'AllowRootChoice') -eq 'true') { $obj['allowRootChoice'] = $true }
- $uodc = Get-Child $node 'UpdateOnDataChange'; if ($uodc -and $uodc -ne 'Auto') { $obj['updateOnDataChange'] = $uodc }
- if ((Get-Child $node 'AllowGettingCurrentRowURL') -eq 'false') { $obj['allowGettingCurrentRowURL'] = $false }
- # RowPictureDataPath: инверсия умного дефолта <Список>.DefaultPicture. У списка с явным ключом
- # без основной таблицы умолчание — отсутствие (компилятор его не ставит): ""-маркер не нужен,
- # а любое значение — явное.
- if (Test-DynListExplicitKey "$($obj['path'])") {
- if ($null -ne $rpdp) { $obj['rowPictureDataPath'] = $rpdp }
- }
- elseif ($null -eq $rpdp) { $obj['rowPictureDataPath'] = '' }
- elseif ($rpdp -ne "$($obj['path']).DefaultPicture") { $obj['rowPictureDataPath'] = $rpdp }
- $usg = Get-Child $node 'UserSettingsGroup'
- if ($usg) { if ($usg -match '^\d+:[0-9a-fA-F]{8}-') { [Console]::Error.WriteLine("form-decompile: UserSettingsGroup '$usg' ($name) — ссылка по id, не воспроизводима, опущена") } else { $obj['userSettingsGroup'] = $usg } }
- } elseif ($rpdp) { $obj['rowPictureDataPath'] = $rpdp }
- $csNode = $node.SelectSingleNode("lf:CommandSet", $ns)
- if ($csNode) {
- $exc = New-Object System.Collections.ArrayList
- foreach ($ec in @($csNode.SelectNodes("lf:ExcludedCommand", $ns))) { [void]$exc.Add($ec.InnerText) }
- if ($exc.Count -gt 0) { $obj['excludedCommands'] = @($exc) }
- }
- $cols = Decompile-Children $node
- if ($cols) { $obj['columns'] = $cols }
- # Стандартные дополнения уровня таблицы (прямые дети) → карта отклонений additions
- $addMap = Decompile-TableAdditions $node $name
- if ($addMap) { $obj['additions'] = $addMap }
- }
- 'Pages' {
- $obj[$key] = $name
- Add-CommonProps $obj $node $name
- $pr = Get-Child $node 'PagesRepresentation'; if ($pr) { $obj['pagesRepresentation'] = $pr }
- $cru = Get-Child $node 'CurrentRowUse'; if ($cru) { $obj['currentRowUse'] = $cru }
- $kids = Decompile-Children $node
- if ($kids) { $obj['children'] = $kids }
- }
- 'Page' {
- $obj[$key] = $name
- Add-CommonProps $obj $node $name
- $g = Get-Child $node 'Group'
- $gmap = @{ 'Horizontal'='horizontal'; 'Vertical'='vertical'; 'AlwaysHorizontal'='alwaysHorizontal'; 'AlwaysVertical'='alwaysVertical'; 'HorizontalIfPossible'='horizontalIfPossible' }
- if ($g -and $gmap.ContainsKey($g)) { $obj['group'] = $gmap[$g] }
- # Картинка страницы (иконка вкладки) — конвенция ValuesPicture (дефолт LoadTransparent=false)
- $pp = Get-PictureRef $node 'Picture'; if ($null -ne $pp) { $obj['picture'] = $pp }
- $st = Get-Child $node 'ShowTitle'; if ($null -ne $st) { $obj['showTitle'] = ($st -eq 'true') } # факт. значение (явный true тоже)
- # Формат значения пути к данным заголовка (<Format>; парный к titleDataPath страницы)
- Add-FormatProps $obj $node
- $kids = Decompile-Children $node
- if ($kids) { $obj['children'] = $kids }
- }
- 'Button' {
- $obj[$key] = $name
- $cmd = Get-Child $node 'CommandName'
- if ($cmd) {
- if ($cmd -match '^Form\.Command\.(.+)$') { $obj['command'] = $matches[1] }
- elseif ($cmd -match '^Form\.StandardCommand\.(.+)$') { $obj['stdCommand'] = $matches[1] }
- elseif ($cmd -match '^Form\.Item\.(.+)\.StandardCommand\.(.+)$') { $obj['stdCommand'] = "$($matches[1]).$($matches[2])" }
- else { $obj['commandName'] = $cmd }
- }
- $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
- # Parameter команды: xr:MDObjectRef (объект метаданных, строка) или v8:TypeDescription (тип → {type})
- $btnParam = $node.SelectSingleNode("lf:Parameter", $ns)
- if ($btnParam) {
- $pxt = $btnParam.GetAttribute("type", $NS_XSI)
- if ($pxt -match 'TypeDescription$') { $pt = Decompile-Type $btnParam; if ($pt) { $obj['parameter'] = [ordered]@{ type = $pt } } }
- elseif ($btnParam.InnerText) { $obj['parameter'] = $btnParam.InnerText }
- }
- Add-CommonProps $obj $node $name
- $type = Get-Child $node 'Type'
- if ($type) { $tmap=@{'CommandBarButton'='commandBar';'UsualButton'='usual';'Hyperlink'='hyperlink';'CommandBarHyperlink'='hyperlink'}; if ($tmap.ContainsKey($type)) { $obj['type']=$tmap[$type] } else { $obj['type']=$type } }
- if ((Get-Child $node 'DefaultButton') -eq 'true') { $obj['defaultButton'] = $true }
- if ((Get-Child $node 'Check') -eq 'true') { $obj['checked'] = $true }
- Set-CommandPicture $obj $node
- $rep = Get-Child $node 'Representation'; if ($rep) { $obj['representation'] = $rep }
- $lic = Get-Child $node 'LocationInCommandBar'; if ($lic) { $obj['locationInCommandBar'] = $lic }
- }
- 'ButtonGroup' {
- $obj[$key] = $name
- Add-CommonProps $obj $node $name
- $cs = Get-Child $node 'CommandSource'
- if ($cs) { if ($cs -match '^\d+:[0-9a-fA-F]{8}-') { [Console]::Error.WriteLine("form-decompile: CommandSource '$cs' ($name) — ссылка по id, не воспроизводима, опущена") } else { $obj['commandSource'] = $cs } }
- $rep = Get-Child $node 'Representation'; if ($rep) { $obj['representation'] = $rep }
- $kids = Decompile-Children $node
- if ($kids) { $obj['children'] = $kids }
- }
- 'CommandBar' {
- $obj[$key] = $name
- Add-CommonProps $obj $node $name
- $cs = Get-Child $node 'CommandSource'
- if ($cs) { if ($cs -match '^\d+:[0-9a-fA-F]{8}-') { [Console]::Error.WriteLine("form-decompile: CommandSource '$cs' ($name) — ссылка по id, не воспроизводима, опущена") } else { $obj['commandSource'] = $cs } }
- $hl = Get-Child $node 'HorizontalLocation'; if ($hl) { $obj['horizontalLocation'] = $hl.ToLower() }
- if ((Get-Child $node 'Autofill') -eq 'true') { $obj['autofill'] = $true }
- $kids = Decompile-Children $node
- if ($kids) { $obj['children'] = $kids }
- }
- 'Popup' {
- $obj[$key] = $name
- Add-CommonProps $obj $node $name
- Set-CommandPicture $obj $node
- $rep = Get-Child $node 'Representation'; if ($rep) { $obj['representation'] = $rep }
- # Источник команд попапа (Form / FormCommandPanelGlobalCommands / Item.X) — как у ButtonGroup/CommandBar
- $cs = Get-Child $node 'CommandSource'
- if ($cs) { if ($cs -match '^\d+:[0-9a-fA-F]{8}-') { [Console]::Error.WriteLine("form-decompile: CommandSource '$cs' ($name) — ссылка по id, не воспроизводима, опущена") } else { $obj['commandSource'] = $cs } }
- $kids = Decompile-Children $node
- if ($kids) { $obj['children'] = $kids }
- }
- 'SearchStringAddition' { $obj[$key] = $name; Add-AdditionCore $obj $node $name }
- 'ViewStatusAddition' { $obj[$key] = $name; Add-AdditionCore $obj $node $name }
- 'SearchControlAddition' { $obj[$key] = $name; Add-AdditionCore $obj $node $name }
- 'SpreadSheetDocumentField' { Decompile-SimpleField $obj $node $name $key }
- 'HTMLDocumentField' { Decompile-SimpleField $obj $node $name $key }
- 'TextDocumentField' { Decompile-SimpleField $obj $node $name $key }
- 'FormattedDocumentField' { Decompile-SimpleField $obj $node $name $key }
- 'ProgressBarField' { Decompile-SimpleField $obj $node $name $key; Add-GaugeScalars $obj $node @('MinValue','MaxValue') }
- 'TrackBarField' { Decompile-SimpleField $obj $node $name $key; Add-GaugeScalars $obj $node @('MinValue','MaxValue','LargeStep','MarkingStep','Step') }
- 'ChartField' { Decompile-SimpleField $obj $node $name $key }
- 'GraphicalSchemaField' { Decompile-SimpleField $obj $node $name $key }
- 'PlannerField' { Decompile-SimpleField $obj $node $name $key }
- 'PeriodField' { Decompile-SimpleField $obj $node $name $key }
- 'DendrogramField' { Decompile-SimpleField $obj $node $name $key }
- 'GanttChartField' {
- Decompile-SimpleField $obj $node $name $key
- # Вложенная <Table> (полноценная таблица) — переиспользуем общий Decompile-Element.
- # Ключ ganttTable (не 'table' — во избежание коллизии с тип-ключом таблицы в диспетчере).
- $tblNode = $node.SelectSingleNode("lf:Table", $ns)
- if ($tblNode) { $obj['ganttTable'] = Decompile-Element $tblNode }
- }
- }
- # DisplayImportance — атрибут открывающего тега (адаптивная важность отображения), захват «как есть».
- $di = $node.GetAttribute("DisplayImportance"); if ($di) { $obj['displayImportance'] = $di }
- # title: "" — подавление авто-вывода: для типов, где компилятор вывел бы
- # заголовок из имени, а в оригинале <Title> отсутствует.
- if (-not $obj.Contains('title')) {
- $autoTitle = $false
- if ($tag -in @('LabelDecoration','Page','Popup')) { $autoTitle = $true }
- elseif ($tag -eq 'Button') { $autoTitle = -not ($obj.Contains('command') -or $obj.Contains('commandName') -or $obj.Contains('stdCommand')) }
- elseif ($tag -in @('InputField','CheckBoxField','RadioButtonField','LabelField','Table','CalendarField')) { $autoTitle = -not $obj.Contains('path') }
- if ($autoTitle) { $obj['title'] = '' }
- }
- Add-Layout $obj $node
- Add-GenericScalars $obj $node
- # extendedTooltip: companion <ExtendedTooltip> (это LabelDecoration). Текст-форма (только <Title>) →
- # строка/{text,formatted}. Own-content (layout/оформление/флаги/hyperlink/events) → объект { text?, … }.
- $etNode = $node.SelectSingleNode("lf:ExtendedTooltip", $ns)
- if ($etNode) {
- $etTitle = $etNode.SelectSingleNode("lf:Title", $ns)
- $textVal = if ($etTitle) { Get-MLFormattedValue $etTitle } else { $null }
- $etObj = [ordered]@{}
- Add-Layout $etObj $etNode
- Add-GenericScalars $etObj $etNode
- Add-Appearance $etObj $etNode
- # ToolTip самого компаньона (подсказка расширенной подсказки) — реальный текст (ML), не пустой Title
- $etTT = $etNode.SelectSingleNode("lf:ToolTip", $ns)
- if ($etTT) { $ttVal = Get-LangText $etTT; if ($null -ne $ttVal) { $etObj['tooltip'] = $ttVal } }
- if ((Get-Child $etNode 'Visible') -eq 'false') { $etObj['hidden'] = $true }
- if ((Get-Child $etNode 'Enabled') -eq 'false') { $etObj['disabled'] = $true }
- if ((Get-Child $etNode 'Hyperlink') -eq 'true') { $etObj['hyperlink'] = $true }
- # События компаньона (напр. URLProcessing у hyperlink-подсказки) — переиспользуем механизм событий элемента
- $etEv = Get-Events $etNode $name; if ($etEv) { $etObj['events'] = $etEv }
- if ($etObj.Count -gt 0) {
- if ($null -ne $textVal) {
- if ($textVal -is [System.Collections.IDictionary] -and $textVal.Contains('text')) { $etObj['text'] = $textVal['text']; if ($textVal['formatted']) { $etObj['formatted'] = $true } }
- else { $etObj['text'] = $textVal }
- # formatted ЯВНО из атрибута Title — компилятор не re-детектит markup на мультиязычном тексте
- if (-not $etObj.Contains('formatted') -and $etTitle -and $etTitle.GetAttribute('formatted') -eq 'true') { $etObj['formatted'] = $true }
- }
- $obj['extendedTooltip'] = $etObj
- } elseif ($null -ne $textVal) {
- $obj['extendedTooltip'] = $textVal
- }
- }
- # companion-панели с контентом: AutoCommandBar → commandBar, ContextMenu → contextMenu (любой элемент)
- $isDynListTable = ($tag -eq 'Table') -and (Has-Child $node 'UpdateOnDataChange')
- $cb = Decompile-CompanionPanel $node 'AutoCommandBar' $isDynListTable
- if ($null -ne $cb) { $obj['commandBar'] = $cb }
- $cm = Decompile-CompanionPanel $node 'ContextMenu'
- if ($null -ne $cm) { $obj['contextMenu'] = $cm }
- return $obj
- }
- # ─────────────────────────────────────────────────────────────────────────────
- # Planner design-time <Settings xsi:type="pl:Planner"> → объект planner на реквизите.
- # Полный захват каждого поля (раундтрип бит-в-бит); зеркало Emit-PlannerSettings.
- function PLD-Bool { param($v) if ($null -eq $v) { return $null } return ($v -eq 'true') }
- function PLD-Int { param($v) if ($null -eq $v) { return $null } return [int]$v }
- # <pl:value> → текст (тип xr:DesignTimeRef/xs:string выводится компилятором из вида значения); nil → $null.
- function Get-PlannerValue {
- param($node)
- if (-not $node) { return $null }
- if ($node.GetAttribute('nil', $NS_XSI) -eq 'true') { return $null }
- if ($node.InnerText) { return $node.InnerText } else { return $null }
- }
- function Build-PlannerFont {
- param($node)
- if (-not $node) { return $null }
- $o = [ordered]@{}
- foreach ($a in @('ref','faceName','height','bold','italic','underline','strikeout','kind','scale')) {
- $av = $node.GetAttribute($a); if ($av -ne '') { $o[$a] = $av }
- }
- if ($o.Count -eq 0) { return $null }
- return $o
- }
- function Build-PlannerBorder {
- param($node)
- if (-not $node) { return $null }
- $o = [ordered]@{}
- $w = $node.GetAttribute('width'); if ($w -ne '') { $o['width'] = [int]$w }
- $st = $node.SelectSingleNode("*[local-name()='style']"); if ($st) { $o['style'] = $st.InnerText }
- return $o
- }
- function Build-PlannerItem {
- param($itn)
- $o = [ordered]@{}
- $valNode = $itn.SelectSingleNode("*[local-name()='value']")
- if ($valNode -and $valNode.GetAttribute('nil', $NS_XSI) -ne 'true' -and $valNode.InnerText) { $o['value'] = $valNode.InnerText }
- $o['text'] = (Get-Child $itn 'text')
- $tt = Get-Child $itn 'tooltip'; if ($tt) { $o['tooltip'] = $tt }
- $o['begin'] = (Get-Child $itn 'begin')
- $o['end'] = (Get-Child $itn 'end')
- $o['borderColor'] = (Get-Child $itn 'borderColor')
- $o['backColor'] = (Get-Child $itn 'backColor')
- $o['textColor'] = (Get-Child $itn 'textColor')
- $fnt = Build-PlannerFont ($itn.SelectSingleNode("*[local-name()='font']")); if ($fnt) { $o['font'] = $fnt }
- $o['replacementDate'] = (Get-Child $itn 'replacementDate')
- $o['deleted'] = (PLD-Bool (Get-Child $itn 'deleted'))
- $o['id'] = (Get-Child $itn 'id')
- $o['textFormatted'] = (PLD-Bool (Get-Child $itn 'textFormatted'))
- $brd = Build-PlannerBorder ($itn.SelectSingleNode("*[local-name()='border']")); if ($brd) { $o['border'] = $brd }
- $o['editMode'] = (Get-Child $itn 'editMode')
- return $o
- }
- function Build-PlannerDimElement {
- param($eln)
- $o = [ordered]@{}
- $v = Get-PlannerValue ($eln.SelectSingleNode("*[local-name()='value']")); if ($null -ne $v) { $o['value'] = $v }
- $o['text'] = (Get-Child $eln 'text')
- $o['borderColor'] = (Get-Child $eln 'borderColor')
- $o['backColor'] = (Get-Child $eln 'backColor')
- $o['textColor'] = (Get-Child $eln 'textColor')
- $fnt = Build-PlannerFont ($eln.SelectSingleNode("*[local-name()='font']")); if ($fnt) { $o['font'] = $fnt }
- $subs = New-Object System.Collections.ArrayList
- foreach ($s in @($eln.SelectNodes("*[local-name()='item']"))) { [void]$subs.Add((Build-PlannerDimElement $s)) }
- if ($subs.Count -gt 0) { $o['elements'] = @($subs) }
- $sos = Get-Child $eln 'showOnlySubordinatesAreas'; if ($null -ne $sos) { $o['showOnlySubordinatesAreas'] = ($sos -eq 'true') }
- $o['textFormatted'] = (PLD-Bool (Get-Child $eln 'textFormatted'))
- return $o
- }
- function Build-PlannerDimension {
- param($dn)
- $o = [ordered]@{}
- $v = Get-PlannerValue ($dn.SelectSingleNode("*[local-name()='value']")); if ($null -ne $v) { $o['value'] = $v }
- $o['text'] = (Get-Child $dn 'text')
- $o['borderColor'] = (Get-Child $dn 'borderColor')
- $o['backColor'] = (Get-Child $dn 'backColor')
- $o['textColor'] = (Get-Child $dn 'textColor')
- $fnt = Build-PlannerFont ($dn.SelectSingleNode("*[local-name()='font']")); if ($fnt) { $o['font'] = $fnt }
- $els = New-Object System.Collections.ArrayList
- foreach ($e in @($dn.SelectNodes("*[local-name()='item']"))) { [void]$els.Add((Build-PlannerDimElement $e)) }
- if ($els.Count -gt 0) { $o['elements'] = @($els) }
- $o['textFormatted'] = (PLD-Bool (Get-Child $dn 'textFormatted'))
- return $o
- }
- function Build-PlannerLevel {
- param($lvn)
- $o = [ordered]@{}
- $o['measure'] = (Get-Child $lvn 'measure')
- $o['interval'] = (PLD-Int (Get-Child $lvn 'interval'))
- $o['show'] = (PLD-Bool (Get-Child $lvn 'show'))
- $lineNode = $lvn.SelectSingleNode("*[local-name()='line']")
- if ($lineNode) {
- $ln = [ordered]@{}
- $w = $lineNode.GetAttribute('width'); if ($w -ne '') { $ln['width'] = [int]$w }
- $g = $lineNode.GetAttribute('gap'); if ($g -ne '') { $ln['gap'] = ($g -eq 'true') }
- $st = $lineNode.SelectSingleNode("*[local-name()='style']"); if ($st) { $ln['style'] = $st.InnerText }
- $o['line'] = $ln
- }
- $o['scaleColor'] = (Get-Child $lvn 'scaleColor')
- $o['dayFormatRule'] = (Get-Child $lvn 'dayFormatRule')
- $fmtNode = $lvn.SelectSingleNode("*[local-name()='format']")
- if ($fmtNode) { $f = Get-LangText $fmtNode; if ($null -ne $f) { $o['format'] = $f } }
- $labelsNode = $lvn.SelectSingleNode("*[local-name()='labels']")
- if ($labelsNode) { $o['labels'] = [ordered]@{ ticks = (PLD-Int (Get-Child $labelsNode 'ticks')) } }
- $o['backColor'] = (Get-Child $lvn 'backColor')
- $o['textColor'] = (Get-Child $lvn 'textColor')
- $o['showPereodicalLabels'] = (PLD-Bool (Get-Child $lvn 'showPereodicalLabels'))
- return $o
- }
- function Build-PlannerTimeScale {
- param($tsn)
- $o = [ordered]@{}
- $o['placement'] = (Get-Child $tsn 'placement')
- $levels = New-Object System.Collections.ArrayList
- foreach ($lvn in @($tsn.SelectNodes("*[local-name()='level']"))) { [void]$levels.Add((Build-PlannerLevel $lvn)) }
- $o['levels'] = @($levels)
- $o['transparent'] = (PLD-Bool (Get-Child $tsn 'transparent'))
- $o['backColor'] = (Get-Child $tsn 'backColor')
- $o['textColor'] = (Get-Child $tsn 'textColor')
- $o['currentLevel'] = (PLD-Int (Get-Child $tsn 'currentLevel'))
- return $o
- }
- function Build-PlannerSettings {
- param($setNode)
- $pl = [ordered]@{}
- $itemNodes = @($setNode.SelectNodes("*[local-name()='item']"))
- if ($itemNodes.Count -gt 0) {
- $items = New-Object System.Collections.ArrayList
- foreach ($itn in $itemNodes) { [void]$items.Add((Build-PlannerItem $itn)) }
- $pl['items'] = @($items)
- }
- $dimNodes = @($setNode.SelectNodes("*[local-name()='dimension']"))
- if ($dimNodes.Count -gt 0) {
- $dims = New-Object System.Collections.ArrayList
- foreach ($dn in $dimNodes) { [void]$dims.Add((Build-PlannerDimension $dn)) }
- $pl['dimensions'] = @($dims)
- }
- $pl['borderColor'] = (Get-Child $setNode 'borderColor')
- $pl['backColor'] = (Get-Child $setNode 'backColor')
- $pl['textColor'] = (Get-Child $setNode 'textColor')
- $pl['lineColor'] = (Get-Child $setNode 'lineColor')
- $fnt = Build-PlannerFont ($setNode.SelectSingleNode("*[local-name()='font']")); if ($fnt) { $pl['font'] = $fnt }
- $pl['beginOfRepresentationPeriod'] = (Get-Child $setNode 'beginOfRepresentationPeriod')
- $pl['endOfRepresentationPeriod'] = (Get-Child $setNode 'endOfRepresentationPeriod')
- $pl['alignElementsOfTimeScale'] = (PLD-Bool (Get-Child $setNode 'alignElementsOfTimeScale'))
- $pl['displayTimeScaleWrapHeaders'] = (PLD-Bool (Get-Child $setNode 'displayTimeScaleWrapHeaders'))
- $pl['displayWrapHeaders'] = (PLD-Bool (Get-Child $setNode 'displayWrapHeaders'))
- $wfNode = $setNode.SelectSingleNode("*[local-name()='timeScaleWrapHeadersFormat']")
- if ($wfNode) { $wf = Get-LangText $wfNode; if ($null -ne $wf) { $pl['timeScaleWrapHeadersFormat'] = $wf } }
- $pl['periodicVariantUnit'] = (Get-Child $setNode 'periodicVariantUnit')
- $pl['periodicVariantRepetition'] = (PLD-Int (Get-Child $setNode 'periodicVariantRepetition'))
- $pl['timeScaleWrapBeginIndent'] = (PLD-Int (Get-Child $setNode 'timeScaleWrapBeginIndent'))
- $pl['timeScaleWrapEndIndent'] = (PLD-Int (Get-Child $setNode 'timeScaleWrapEndIndent'))
- $tsNode = $setNode.SelectSingleNode("*[local-name()='timeScale']")
- if ($tsNode) { $pl['timeScale'] = (Build-PlannerTimeScale $tsNode) }
- $perNode = $setNode.SelectSingleNode("*[local-name()='period']")
- if ($perNode) { $pl['period'] = [ordered]@{ begin = (Get-Child $perNode 'begin'); end = (Get-Child $perNode 'end') } }
- $pl['displayCurrentDate'] = (PLD-Bool (Get-Child $setNode 'displayCurrentDate'))
- $pl['itemsTimeRepresentation'] = (Get-Child $setNode 'itemsTimeRepresentation')
- $pl['itemsBehaviorWhenSpaceInsufficient'] = (Get-Child $setNode 'itemsBehaviorWhenSpaceInsufficient')
- $pl['autoMinColumnWidth'] = (PLD-Bool (Get-Child $setNode 'autoMinColumnWidth'))
- $pl['autoMinRowHeight'] = (PLD-Bool (Get-Child $setNode 'autoMinRowHeight'))
- $pl['minColumnWidth'] = (PLD-Int (Get-Child $setNode 'minColumnWidth'))
- $pl['minRowHeight'] = (PLD-Int (Get-Child $setNode 'minRowHeight'))
- $pl['fixDimensionsHeader'] = (Get-Child $setNode 'fixDimensionsHeader')
- $pl['fixTimeScaleHeader'] = (Get-Child $setNode 'fixTimeScaleHeader')
- $brd = Build-PlannerBorder ($setNode.SelectSingleNode("*[local-name()='border']")); if ($brd) { $pl['border'] = $brd }
- $pl['newItemsTextType'] = (Get-Child $setNode 'newItemsTextType')
- return $pl
- }
- # ─────────────────────────────────────────────────────────────────────────────
- # Chart design-time <Settings xsi:type="d4p1:Chart"> → объект chart. Генерик-движок:
- # рекурсивный захват поддерева d4p1; структуры (line/border/font/ML/области/серии)
- # детектируются по форме узла. Малые name-set'ы: ML-поля (даже ru-only/пустые → ML),
- # серии (всегда массив), attrs-узлы. Порядок ключей JSON = порядок XML (раундтрип).
- $CHART_ML_FIELDS = @{ 'title'=1;'lbFormat'=1;'lbpFormat'=1;'vsFormat'=1;'dtFormat'=1;'dataSourceDescription'=1;'labelFormat'=1;'text'=1 }
- $CHART_SERIES_FIELDS = @{ 'realSeriesData'=1;'realExSeriesData'=1;'realPointData'=1;'realDataItems'=1 }
- $CHART_ATTR_FIELDS = @{ 'gaugeQualityBands'=1 }
- function Conv-ChartScalar {
- param([string]$v)
- if ($v -eq 'true') { return $true }
- if ($v -eq 'false') { return $false }
- return $v
- }
- function Build-ChartNode {
- param($n, [string]$name)
- # ML-поле → строка/мапа/"" (даже ru-only форсим в ML на эмите по имени)
- if ($CHART_ML_FIELDS.Contains($name)) {
- $ml = Get-LangText $n
- if ($null -eq $ml) { return '' } else { return $ml }
- }
- $kids = @($n.SelectNodes("*"))
- if ($kids.Count -eq 0) {
- # лист: attrs-only (шрифт/gaugeQualityBands) или текст
- $attrs = @($n.Attributes | Where-Object { $_.Name -ne 'xmlns' -and -not $_.Name.StartsWith('xmlns:') -and $_.Name -ne 'xsi:type' -and $_.Name -ne 'xsi:nil' })
- if ($attrs.Count -gt 0) {
- $o = [ordered]@{}; foreach ($a in $attrs) { $o[$a.Name] = (Conv-ChartScalar $a.Value) }; return $o
- }
- return (Conv-ChartScalar $n.InnerText)
- }
- # line/border: дочерний v8ui:style (+ width[/gap])
- $styleChild = $n.SelectSingleNode("*[local-name()='style']")
- if ($styleChild) {
- $o = [ordered]@{}
- $w = $n.GetAttribute('width'); if ($w -ne '') { $o['width'] = [int]$w }
- $g = $n.GetAttribute('gap'); if ($g -ne '') { $o['gap'] = ($g -eq 'true') }
- $o['style'] = $styleChild.InnerText
- return $o
- }
- # вложенный объект d4p1 (область/шкала/titleArea/серия): группируем детей по имени
- $o = [ordered]@{}
- foreach ($c in $kids) {
- $ln = $c.LocalName
- $val = Build-ChartNode $c $ln
- if ($CHART_SERIES_FIELDS.Contains($ln)) {
- if (-not $o.Contains($ln)) { $o[$ln] = New-Object System.Collections.ArrayList }
- [void]$o[$ln].Add($val)
- } elseif ($o.Contains($ln)) {
- if ($o[$ln] -isnot [System.Collections.IList]) { $tmp = New-Object System.Collections.ArrayList; [void]$tmp.Add($o[$ln]); $o[$ln] = $tmp }
- [void]$o[$ln].Add($val)
- } else {
- $o[$ln] = $val
- }
- }
- # нормализуем ArrayList → @() для сериализации
- foreach ($k in @($o.Keys)) { if ($o[$k] -is [System.Collections.ArrayList]) { $o[$k] = @($o[$k]) } }
- return $o
- }
- function Build-ChartSettings {
- param($setNode)
- return (Build-ChartNode $setNode '')
- }
- # --- 5. Form-level assembly ---
- $dsl = [ordered]@{}
- $titleNode = $root.SelectSingleNode("lf:Title", $ns)
- if ($titleNode) { $t = Get-LangText $titleNode; if ($null -ne $t) { $dsl['title'] = $t } }
- # properties (прямые скаляры под <Form>, PascalCase → camelCase)
- $KNOWN_FORM_PROPS = @('AutoTitle','ReportResult','DetailsData','ReportFormType','AutoShowState','ReportResultViewMode','ViewModeApplicationOnSetReportResult','WindowOpeningMode','CommandBarLocation','SaveDataInSettings','AutoSaveDataInSettings','AutoTime','UsePostingMode','RepostOnWrite','AutoURL','AutoFillCheck','Customizable','EnterKeyBehavior','VerticalScroll','Width','Height','Group','UseForFoldersAndItems','SaveWindowSettings','ScalingMode','VerticalSpacing','VariantAppearance','ShowCloseButton','HorizontalAlign','ChildrenAlign','ShowTitle','ConversationsRepresentation','CollapseItemsByImportanceVariant','GroupList','ChildItemsWidth','VerticalAlign','HorizontalSpacing','CustomSettingsFolder','SettingsStorage','Enabled','Scale')
- $props = [ordered]@{}
- foreach ($pn in $KNOWN_FORM_PROPS) {
- $v = Get-Child $root $pn
- if ($null -ne $v) {
- $camel = $pn.Substring(0,1).ToLower() + $pn.Substring(1)
- if ($v -eq 'true') { $props[$camel] = $true }
- elseif ($v -eq 'false') { $props[$camel] = $false }
- elseif ($v -match '^\d+$') { $props[$camel] = [int]$v }
- else { $props[$camel] = $v }
- }
- }
- # Ссылка на члена формы по id ("N:uuid") в groupList/customSettingsFolder НЕ воспроизводима: наш
- # компилятор переназначает id, и ссылка указала бы не туда (либо вовсе dangling — платформа сама их
- # часто не разрешает). Резолв в имя ненадёжен (N не всегда соответствует named-элементу). Игнорируем
- # с предупреждением (имя задаётся вручную через form-edit). Имя-форма захватывается как есть.
- foreach ($refKey in 'groupList','customSettingsFolder') {
- if ($props.Contains($refKey) -and "$($props[$refKey])" -match '^\d+:[0-9a-fA-F]{8}-') {
- [Console]::Error.WriteLine("form-decompile: $refKey = '$($props[$refKey])' — ссылка на члена формы по id, не воспроизводима (id переназначаются), опущена. Задайте по имени через form-edit.")
- $props.Remove($refKey)
- }
- }
- # AutoTitle при наличии title: компилятор инъектит false (~95% форм). Зеркалим:
- # - оригинал имеет AutoTitle=false → опускаем ключ (компилятор реинъектит при наличии title);
- # - оригинал НЕ имеет AutoTitle (редкие 5%, напр. вспом. формы) → суппресс-маркер "" (не инъектить).
- if ($dsl.Contains('title')) {
- if (-not $props.Contains('autoTitle')) { $props['autoTitle'] = '' }
- elseif ($props['autoTitle'] -eq $false) { $props.Remove('autoTitle') }
- }
- if ($props.Count -gt 0) { $dsl['properties'] = $props }
- # MobileDeviceCommandBarContent (form-level) → список имён командных панелей/кнопок
- $mdcb = $root.SelectSingleNode("lf:MobileDeviceCommandBarContent", $ns)
- if ($mdcb) {
- $names = New-Object System.Collections.ArrayList
- foreach ($it in @($mdcb.SelectNodes("xr:Item", $ns))) {
- $v = $it.SelectSingleNode("xr:Value", $ns); if ($v) { [void]$names.Add($v.InnerText) }
- }
- if ($names.Count -gt 0) { $dsl['mobileCommandBarContent'] = @($names) }
- }
- # excludedCommands (form-level <CommandSet>)
- $csForm = $root.SelectSingleNode("lf:CommandSet", $ns)
- if ($csForm) {
- $excForm = New-Object System.Collections.ArrayList
- foreach ($ec in @($csForm.SelectNodes("lf:ExcludedCommand", $ns))) { [void]$excForm.Add($ec.InnerText) }
- if ($excForm.Count -gt 0) { $dsl['excludedCommands'] = @($excForm) }
- }
- # events (form-level)
- $evForm = Get-Events $root $null
- if ($evForm) { $dsl['events'] = $evForm }
- # Зеркало компилятор-эвристики B3 (Compute-MainAcbAutofill): наличие cmdBar-элемента где-либо
- # в дереве → форменный AutoCommandBar autofill=false. Нужно, чтобы предсказать вывод и выразить
- # отклонение (голый корень при наличии cmdBar).
- function Test-AnyCmdBar {
- param($list)
- if (-not $list) { return $false }
- foreach ($e in $list) {
- if ($e -is [System.Collections.IDictionary] -and $e.Contains('cmdBar')) { return $true }
- if ($e -is [System.Collections.IDictionary]) {
- if ($e.Contains('children') -and (Test-AnyCmdBar $e['children'])) { return $true }
- if ($e.Contains('columns') -and (Test-AnyCmdBar $e['columns'])) { return $true }
- }
- }
- return $false
- }
- # elements (+ форменный AutoCommandBar как autoCmdBar-элемент, если у него есть содержимое/отклонение)
- $elemList = New-Object System.Collections.ArrayList
- $elements = Decompile-Children $root
- $formHasCmdBar = Test-AnyCmdBar $elements
- $acb = $root.SelectSingleNode("lf:AutoCommandBar", $ns)
- if ($acb) {
- $haln = Get-Child $acb 'HorizontalAlign'
- $acbAutofill = Get-Child $acb 'Autofill'
- $acbDI = $acb.GetAttribute("DisplayImportance") # адаптивная важность форменной панели (атрибут тега)
- $acbKids = Decompile-Children $acb
- $acbObj = $null
- if ($haln -or ($acbAutofill -eq 'false') -or $acbKids -or $acbDI) {
- $acbObj = [ordered]@{}
- $acbObj['autoCmdBar'] = $acb.GetAttribute("name")
- if ($acbDI) { $acbObj['displayImportance'] = $acbDI }
- if ($haln) { $acbObj['horizontalAlign'] = $haln }
- if ($acbAutofill -eq 'false') { $acbObj['autofill'] = $false }
- if ($acbKids) { $acbObj['children'] = $acbKids }
- } elseif ($formHasCmdBar -and $null -eq $acbAutofill) {
- # Корень голый (autofill=true по умолчанию), но эвристика B3 дала бы false (есть cmdBar) → маркер
- $acbObj = [ordered]@{}
- $acbObj['autoCmdBar'] = $acb.GetAttribute("name")
- $acbObj['autofill'] = $true
- }
- if ($acbObj) { [void]$elemList.Add($acbObj) }
- }
- if ($elements) { foreach ($e in $elements) { [void]$elemList.Add($e) } }
- if ($elemList.Count -gt 0) { $dsl['elements'] = @($elemList) }
- # attributes
- # Объектный тип (зеркало Test-IsObjectLikeType компилятора) — кандидат на авто-main эвристики 11b.3.
- function Test-IsObjectLikeTypeDec([string]$type) {
- if ([string]::IsNullOrEmpty($type)) { return $false }
- if ($type -eq 'DynamicList' -or $type -eq 'ConstantsSet') { return $true }
- return ($type -match '^(CatalogObject|DocumentObject|DataProcessorObject|ReportObject|ExternalDataProcessorObject|ExternalReportObject|BusinessProcessObject|TaskObject|ChartOfAccountsObject|ChartOfCharacteristicTypesObject|ChartOfCalculationTypesObject|ExchangePlanObject|InformationRegisterRecordSet|AccumulationRegisterRecordSet|AccountingRegisterRecordSet|CalculationRegisterRecordSet|InformationRegisterRecordManager)\.')
- }
- $attrsNode = $root.SelectSingleNode("lf:Attributes", $ns)
- if ($attrsNode) {
- $attrs = New-Object System.Collections.ArrayList
- # Подавление авто-main (эвристика компилятора 11b.3): если НЕТ ни одного <MainAttribute> И ровно
- # один реквизит объектного типа — компилятор пометит его main. В оригинале он НЕ main (раз тега нет)
- # → ставим суппресс-маркер main:false. На формах с >1 объектным реквизитом / с явным main — не нужно.
- $allAttrNodes = @($attrsNode.SelectNodes("lf:Attribute", $ns))
- $anyMainAttr = $false; $objLikeNodes = @()
- foreach ($an in $allAttrNodes) {
- if ((Get-Child $an 'MainAttribute') -eq 'true') { $anyMainAttr = $true }
- $atype = Decompile-Type ($an.SelectSingleNode("lf:Type", $ns))
- if (Test-IsObjectLikeTypeDec "$atype") { $objLikeNodes += $an }
- }
- $suppressMainName = if ((-not $anyMainAttr) -and $objLikeNodes.Count -eq 1) { $objLikeNodes[0].GetAttribute("name") } else { $null }
- foreach ($a in $allAttrNodes) {
- $ao = [ordered]@{}
- $ao['name'] = $a.GetAttribute("name")
- $ty = Decompile-Type ($a.SelectSingleNode("lf:Type", $ns)); if ($ty) { $ao['type'] = $ty }
- # valueType: <Settings xsi:type="v8:TypeDescription"> — уточнение типа значений ValueList
- # (та же грамматика типа). Дин-список Settings (xsi:type="DynamicList") обрабатывается отдельно.
- $setNode = $a.SelectSingleNode("lf:Settings", $ns)
- if ($setNode -and $setNode.GetAttribute("type", $NS_XSI) -match 'TypeDescription$') {
- $vt = Decompile-Type $setNode
- $ao['valueType'] = if ($vt) { $vt } else { '' } # пустой Settings → маркер ""
- }
- # Planner design-time <Settings xsi:type="pl:Planner"> → объект planner (полный захват).
- elseif ($setNode -and $setNode.GetAttribute("type", $NS_XSI) -match 'Planner$') {
- $ao['planner'] = Build-PlannerSettings $setNode
- }
- # Chart/GanttChart design-time <Settings xsi:type="d4p1:Chart"/"d4p1:GanttChart"> → chart (генерик).
- elseif ($setNode -and $setNode.GetAttribute("type", $NS_XSI) -match 'd4p1:(Gantt)?Chart$') {
- $ao['chart'] = Build-ChartSettings $setNode
- }
- if ((Get-Child $a 'MainAttribute') -eq 'true') { $ao['main'] = $true }
- elseif ($suppressMainName -and $ao['name'] -eq $suppressMainName) { $ao['main'] = $false }
- $vw = Decompile-XrFlag $a 'View'; if ($null -ne $vw) { $ao['view'] = $vw }
- $ed = Decompile-XrFlag $a 'Edit'; if ($null -ne $ed) { $ao['edit'] = $ed }
- # Title атрибута. Компилятор для не-main атрибута без ключа title додумывает заголовок
- # из имени. Поэтому: нет <Title> → суппресс-маркер ''; ru-only == авто-вывод → опускаем
- # ключ (компилятор воспроизведёт); иначе → явный заголовок.
- $isMain = ($ao['main'] -eq $true) # именно true; main:false (суппресс-маркер) → не-main для Title
- $tNode = $a.SelectSingleNode("lf:Title", $ns)
- if ($tNode) {
- $t = Get-LangTextWS $tNode # восстановление значимого пробела (whitespace-заголовок реквизита)
- if ($null -ne $t) {
- # Ordinal, а не -ne/-ceq: заголовок опускаем только при ТОЧНОМ, побайтовом совпадении
- # с авто-выводом — компилятор восстановит его как есть, значим и регистр, и мягкий
- # перенос, и форма нормализации.
- if ($isMain -or -not ($t -is [string]) -or -not [string]::Equals($t, (Title-FromName $ao['name']), [StringComparison]::Ordinal)) { $ao['title'] = $t }
- }
- } elseif (-not $isMain) {
- $ao['title'] = ''
- }
- # SavedData: компилятор додумывает true для main-реквизита объектного типа (эвристика $mainSaved:
- # Catalog/Document/ChartOf*/ExchangePlan/BusinessProcess/Task Object + RecordManager). Если оригинал
- # тега не имеет — ставим суппресс-маркер savedData:false (как с MainAttribute).
- if ((Get-Child $a 'SavedData') -eq 'true') { $ao['savedData'] = $true }
- elseif ($ao['main'] -eq $true -and "$($ao['type'])" -match '^(CatalogObject|DocumentObject|ChartOfAccountsObject|ChartOfCalculationTypesObject|ChartOfCharacteristicTypesObject|ExchangePlanObject|BusinessProcessObject|TaskObject)\.|RecordManager\.') { $ao['savedData'] = $false }
- # Save: сохранение значения реквизита в пользовательских настройках. Один Field=имя → save:true;
- # иначе снимаем префикс "имя." (голое имя/UUID/прочее — как есть) → строка (1) или массив.
- $saveNode = $a.SelectSingleNode("lf:Save", $ns)
- if ($saveNode) {
- $nm = "$($ao['name'])"
- $flds = @($saveNode.SelectNodes("lf:Field", $ns) | ForEach-Object { $_.InnerText })
- if ($flds.Count -eq 1 -and $flds[0] -eq $nm) {
- $ao['save'] = $true
- } elseif ($flds.Count -gt 0) {
- # Снимаем префикс "имя." ТОЛЬКО когда остаток — простое подполе, которое компилятор
- # реинъектит (зеркало его условия: ≠имя, без точки, не UUID-ссылка ^N/M). Многоуровневый
- # путь "имя.Settings.Filter" и UUID-ссылка "имя.1/0:GUID" компилятор эмитит как есть
- # (префикс не вернёт) → храним ПОЛНЫЙ путь, иначе префикс теряется.
- $stripped = @($flds | ForEach-Object {
- if ($_ -match "^$([regex]::Escape($nm))\.([^.]+)$" -and $matches[1] -notmatch '^\d+/\d+') { $matches[1] } else { $_ }
- })
- if ($stripped.Count -eq 1) { $ao['save'] = $stripped[0] } else { $ao['save'] = $stripped }
- }
- }
- $fc = Get-Child $a 'FillCheck'; if ($fc) { $ao['fillCheck'] = $fc }
- $afo = Decompile-FunctionalOptions $a; if ($afo) { $ao['functionalOptions'] = $afo }
- $colsNode = $a.SelectSingleNode("lf:Columns", $ns)
- if ($colsNode) {
- $cols = New-Object System.Collections.ArrayList
- foreach ($c in @($colsNode.SelectNodes("lf:Column", $ns))) { [void]$cols.Add((Decompile-AttrColumn $c)) }
- if ($cols.Count -gt 0) { $ao['columns'] = @($cols) }
- # AdditionalColumns: доп. колонки табличных частей объекта (группа на табличную часть)
- $addNodes = @($colsNode.SelectNodes("lf:AdditionalColumns", $ns))
- if ($addNodes.Count -gt 0) {
- $addList = New-Object System.Collections.ArrayList
- foreach ($an in $addNodes) {
- $acObj = [ordered]@{}; $acObj['table'] = $an.GetAttribute("table")
- $acCols = New-Object System.Collections.ArrayList
- foreach ($c in @($an.SelectNodes("lf:Column", $ns))) { [void]$acCols.Add((Decompile-AttrColumn $c)) }
- $acObj['columns'] = @($acCols)
- [void]$addList.Add($acObj)
- }
- $ao['additionalColumns'] = @($addList)
- }
- }
- # UseAlways: поля, всегда читаемые. Префикс "ИмяРеквизита." снимаем.
- # ValueTable (есть columns): useAlways:true на совпавшей колонке; остальные → массив атрибута.
- # Дин-список/прочие (нет columns): массив useAlways на атрибуте.
- $uaNode = $a.SelectSingleNode("lf:UseAlways", $ns)
- if ($uaNode) {
- $prefix = "$($ao['name'])."
- $shorts = New-Object System.Collections.ArrayList
- foreach ($fn in @($uaNode.SelectNodes("lf:Field", $ns))) {
- $t = $fn.InnerText.Trim()
- # Снимаем префикс "ИмяРеквизита.". Маркер "~" (query-поле дин-списка) сохраняем,
- # префикс снимаем ПОСЛЕ него: ~Список.Остановлен → ~Остановлен (компилятор развернёт обратно).
- if ($t.StartsWith('~')) {
- $rest = $t.Substring(1)
- if ($rest.StartsWith($prefix)) { $rest = $rest.Substring($prefix.Length) }
- $t = "~$rest"
- } elseif ($t.StartsWith($prefix)) {
- $t = $t.Substring($prefix.Length)
- }
- [void]$shorts.Add($t)
- }
- if ($ao.Contains('columns')) {
- $rest = New-Object System.Collections.ArrayList
- foreach ($s in $shorts) {
- $col = $ao['columns'] | Where-Object { $_['name'] -eq $s } | Select-Object -First 1
- if ($col) { $col['useAlways'] = $true } else { [void]$rest.Add($s) }
- }
- if ($rest.Count -gt 0) { $ao['useAlways'] = @($rest) }
- } elseif ($shorts.Count -gt 0) {
- $ao['useAlways'] = @($shorts)
- }
- }
- # Settings динамического списка (только xsi:type=DynamicList; Planner/TypeDescription — выше)
- $setNode = $a.SelectSingleNode("lf:Settings", $ns)
- if ($setNode -and $setNode.GetAttribute("type", $NS_XSI) -match 'DynamicList$') {
- $so = [ordered]@{}
- # AutoFillAvailableFields — дефолт true, платформа эмитит только отклонение (false). Захват «как есть».
- $afaf = Get-Child $setNode 'AutoFillAvailableFields'; if ($null -ne $afaf) { $so['autoFillAvailableFields'] = ($afaf -eq 'true') }
- $mt = Get-Child $setNode 'MainTable'; if ($mt) { $so['mainTable'] = $mt }
- # GetInvisibleFieldPresentations — дефолт true, платформа эмитит только отклонение (false, корпус 20/20). Факт. значение.
- $gifp = Get-Child $setNode 'GetInvisibleFieldPresentations'; if ($null -ne $gifp) { $so['getInvisibleFieldPresentations'] = ($gifp -eq 'true') }
- # Ключ набора (query-based список): KeyType (RowNumber/FieldValue/RowKey) + KeyField* (0+).
- $kt = Get-Child $setNode 'KeyType'; if ($kt) { $so['keyType'] = $kt }
- $kfNodes = @($setNode.SelectNodes("lf:KeyField", $ns) | ForEach-Object { $_.InnerText })
- if ($kfNodes.Count -gt 0) { $so['keyFields'] = @($kfNodes) }
- # AutoSaveUserSettings — авто-сохранение польз. настроек дин-списка (в корпусе только false;
- # дефолт true → платформа эмитит отклонение). Захват факт. значения.
- $asus = Get-Child $setNode 'AutoSaveUserSettings'; if ($null -ne $asus) { $so['autoSaveUserSettings'] = ($asus -eq 'true') }
- $qtNode = $setNode.SelectSingleNode("lf:QueryText", $ns)
- $hasQ = [bool]($qtNode -and $qtNode.InnerText)
- if ($hasQ) { $so['query'] = Maybe-ExternalizeQuery -queryText $qtNode.InnerText -listName "$($ao['name'])" }
- # ManualQuery: компилятор выводит из наличия query (hasQuery → true). Платформа в редких
- # случаях (корпус 16) хранит QueryText при ManualQuery=false → фиксируем отклонение от эвристики.
- $mqV = Get-Child $setNode 'ManualQuery'
- if ($null -ne $mqV) { $mqActual = ($mqV -eq 'true'); if ($mqActual -ne $hasQ) { $so['manualQuery'] = $mqActual } }
- # DynamicDataRead: дефолт true → эмитим только false
- if ((Get-Child $setNode 'DynamicDataRead') -eq 'false') { $so['dynamicDataRead'] = $false }
- # Явные поля набора (редко, ~4.5%) — захват только при наличии Field
- $fieldNodes = @($setNode.SelectNodes("lf:Field", $ns))
- if ($fieldNodes.Count -gt 0) {
- $fields = New-Object System.Collections.ArrayList
- foreach ($fn in $fieldNodes) {
- $fo = [ordered]@{}
- $fld = Get-Child $fn 'field'
- $dp = Get-Child $fn 'dataPath'
- if ($fld) { $fo['field'] = $fld }
- if ((Has-Child $fn 'dataPath') -and $dp -ne $fld) { $fo['dataPath'] = $dp }
- # Тип поля набора: DataSetFieldField (дефолт, компилятор хардкодит) vs
- # DataSetFieldNestedDataSet (поле-вложенный набор = реквизит табличной части). Маркер nested.
- $fTypeAttr = $fn.GetAttribute("type", $NS_XSI)
- if ($fTypeAttr -match 'NestedDataSet$') { $fo['nested'] = $true }
- elseif ($fTypeAttr -match 'Folder$') { $fo['folder'] = $true }
- $ftn = $fn.SelectSingleNode("dcssch:title", $ns)
- if ($ftn) { $t = Get-LangText $ftn; if ($null -ne $t) { $fo['title'] = $t } }
- # valueType поля набора (тип значения; вычисляемые/кастомные поля). Грамматика типа.
- $fvt = $fn.SelectSingleNode("dcssch:valueType", $ns)
- if ($fvt) { $fvtVal = Decompile-Type $fvt; if ($fvtVal) { $fo['valueType'] = $fvtVal } }
- # presentationExpression (выражение представления поля) + appearance (формат/оформление поля)
- $fpe = Get-Child $fn 'presentationExpression'
- if ($null -ne $fpe -and $fpe -ne '') { $fo['presentationExpression'] = $fpe }
- $fappNode = $fn.SelectSingleNode("dcssch:appearance", $ns)
- if ($fappNode) { $fap = Get-SettingsAppearance $fappNode; if ($fap -and $fap.Count -gt 0) { $fo['appearance'] = $fap } }
- $furNode = $fn.SelectSingleNode("dcssch:useRestriction", $ns)
- if ($furNode) { $fur = Build-RestrictObj $furNode; if ($fur.Count -gt 0) { $fo['useRestriction'] = $fur } }
- $faurNode = $fn.SelectSingleNode("dcssch:attributeUseRestriction", $ns)
- if ($faurNode) { $faur = Build-RestrictObj $faurNode; if ($faur.Count -gt 0) { $fo['attributeUseRestriction'] = $faur } }
- $fipNode = $fn.SelectSingleNode("dcssch:inputParameters", $ns)
- if ($fipNode) { $fip = Build-DLInputParameters $fipNode; if (@($fip).Count -gt 0) { $fo['inputParameters'] = $fip } }
- [void]$fields.Add($fo)
- }
- $so['fields'] = @($fields)
- }
- # Вычисляемые поля DataSet (<CalculatedField>) — после Field*, до Parameter*.
- $calcNodes = @($setNode.SelectNodes("lf:CalculatedField", $ns))
- if ($calcNodes.Count -gt 0) {
- $cfs = New-Object System.Collections.ArrayList
- foreach ($cn in $calcNodes) { [void]$cfs.Add((Build-CalcField $cn)) }
- $so['calculatedFields'] = @($cfs)
- }
- # Schema-параметры дин-списка (прямые <Parameter> под Settings, не в ListSettings)
- $paramNodes = @($setNode.SelectNodes("lf:Parameter", $ns))
- if ($paramNodes.Count -gt 0) {
- $dlPars = New-Object System.Collections.ArrayList
- foreach ($pn in $paramNodes) { [void]$dlPars.Add((Build-DLParameter $pn)) }
- $so['parameters'] = @($dlPars)
- }
- # ListSettings: пустой скелет (только viewMode+GUID) опускаем — компилятор
- # регенерит каноничный скелет. Захватываем только контейнеры с реальными
- # dcsset:item (filter/order/conditionalAppearance) в формат компилятора.
- $lsNode = $setNode.SelectSingleNode("lf:ListSettings", $ns)
- if ($lsNode) {
- $fNode = $lsNode.SelectSingleNode("dcsset:filter", $ns)
- if ($fNode -and $fNode.SelectSingleNode("dcsset:item", $ns)) {
- $flt = @()
- foreach ($fc in $fNode.SelectNodes("dcsset:item", $ns)) {
- $bi = (Build-FilterItem -itemNode $fc -loc "settings/filter")
- if ($null -ne $bi) { $flt += $bi }
- }
- if ($flt.Count -gt 0) { $so['filter'] = @($flt) }
- }
- $oNode = $lsNode.SelectSingleNode("dcsset:order", $ns)
- if ($oNode -and $oNode.SelectSingleNode("dcsset:item", $ns)) {
- $ord = Build-Order -ordNode $oNode -loc "settings/order"
- if (@($ord).Count -gt 0) { $so['order'] = @($ord) }
- }
- $caNode = $lsNode.SelectSingleNode("dcsset:conditionalAppearance", $ns)
- if ($caNode -and $caNode.SelectSingleNode("dcsset:item", $ns)) {
- $ca = Build-ConditionalAppearance -caNode $caNode -loc "settings/conditionalAppearance"
- if (@($ca).Count -gt 0) { $so['conditionalAppearance'] = @($ca) }
- }
- # Параметры данных компоновки (dcsset:dataParameters) — значения параметров запроса в
- # настройках. Грамматика как у СКД (shorthand "Имя @off" / объект). См. Build-FormDataParameters.
- $dpNode = $lsNode.SelectSingleNode("dcsset:dataParameters", $ns)
- if ($dpNode -and $dpNode.SelectSingleNode("dcscor:item", $ns)) {
- $dp = Build-FormDataParameters $dpNode
- if (@($dp).Count -gt 0) { $so['dataParameters'] = @($dp) }
- }
- # Форма скелета ListSettings: дескриптор только для НЕ-каноничных форм (частичные/минимальные).
- # Канон → $null (компилятор регенерит полный скелет, как раньше).
- # Группировка строк списка: прямой <dcsset:item> ListSettings (не в filter/order/CA).
- $grpItemNode = $lsNode.SelectSingleNode("dcsset:item", $ns)
- $grouping = $null
- if ($grpItemNode) { $grouping = Build-ListGrouping $grpItemNode }
- if ($null -ne $grouping) { $so['grouping'] = $grouping }
- $lsShape = Get-ListSettingsShape $lsNode ($null -ne $grouping)
- if ($null -ne $lsShape) { $so['listSettings'] = $lsShape }
- }
- if ($so.Count -gt 0) { $ao['settings'] = $so }
- }
- [void]$attrs.Add($ao)
- }
- if ($attrs.Count -gt 0) { $dsl['attributes'] = @($attrs) }
- }
- # conditionalAppearance формы (<ConditionalAppearance> — последний child <Attributes>;
- # та же DCS-грамматика, что settings.conditionalAppearance → переиспользуем Build-ConditionalAppearance)
- if ($attrsNode) {
- $caNode = $attrsNode.SelectSingleNode("lf:ConditionalAppearance", $ns)
- if ($caNode) {
- $ca = Build-ConditionalAppearance -caNode $caNode -loc "form/conditionalAppearance"
- if (@($ca).Count -gt 0) { $dsl['conditionalAppearance'] = @($ca) }
- }
- }
- # parameters
- $parsNode = $root.SelectSingleNode("lf:Parameters", $ns)
- if ($parsNode) {
- $pars = New-Object System.Collections.ArrayList
- foreach ($p in @($parsNode.SelectNodes("lf:Parameter", $ns))) {
- $po = [ordered]@{}; $po['name'] = $p.GetAttribute("name")
- $ty = Decompile-Type ($p.SelectSingleNode("lf:Type", $ns)); if ($ty) { $po['type'] = $ty }
- if ((Get-Child $p 'KeyParameter') -eq 'true') { $po['key'] = $true }
- [void]$pars.Add($po)
- }
- if ($pars.Count -gt 0) { $dsl['parameters'] = @($pars) }
- }
- # commands
- $cmdsNode = $root.SelectSingleNode("lf:Commands", $ns)
- if ($cmdsNode) {
- $cmds = New-Object System.Collections.ArrayList
- foreach ($c in @($cmdsNode.SelectNodes("lf:Command", $ns))) {
- $co = [ordered]@{}; $co['name'] = $c.GetAttribute("name")
- $act = Get-Child $c 'Action'; if ($act) { $co['action'] = $act }
- if ((Get-Child $c 'ModifiesSavedData') -eq 'true') { $co['modifiesSavedData'] = $true }
- # Заголовок команды: есть <Title> → захват; нет → суппресс-маркер "" (иначе компилятор
- # додумает из имени — авто-вывод неверен для ~0.13% команд без заголовка в оригинале).
- $tNode = $c.SelectSingleNode("lf:Title", $ns)
- if ($tNode) { $t = Get-LangText $tNode; if ($null -ne $t) { $co['title'] = $t } }
- else { $co['title'] = '' }
- $ttNode = $c.SelectSingleNode("lf:ToolTip", $ns); if ($ttNode) { $t = Get-LangText $ttNode; if ($null -ne $t) { $co['tooltip'] = $t } }
- $us = Decompile-XrFlag $c 'Use'; if ($null -ne $us) { $co['use'] = $us }
- $cfo = Decompile-FunctionalOptions $c; if ($cfo) { $co['functionalOptions'] = $cfo }
- $cru = Get-Child $c 'CurrentRowUse'; if ($cru) { $co['currentRowUse'] = $cru }
- # Используемая таблица — ссылка по имени элемента-таблицы (<AssociatedTableElementId xsi:type="xs:string">Имя</…>)
- $ate = Get-Child $c 'AssociatedTableElementId'; if ($ate) { $co['table'] = $ate }
- $sc = Get-Child $c 'Shortcut'; if ($sc) { $co['shortcut'] = $sc }
- Set-CommandPicture $co $c
- $rep = Get-Child $c 'Representation'; if ($rep) { $co['representation'] = $rep }
- [void]$cmds.Add($co)
- }
- if ($cmds.Count -gt 0) { $dsl['commands'] = @($cmds) }
- }
- # commandInterface (форменный <CommandInterface> — последний дочерний Form)
- $ci = Decompile-CommandInterface
- if ($null -ne $ci) { $dsl['commandInterface'] = $ci }
- # --- 6. Output ---
- $json = ConvertTo-CompactJson -obj $dsl
- if ($OutputPath) {
- [System.IO.File]::WriteAllText($OutputPath, $json, (New-Object System.Text.UTF8Encoding($false)))
- Save-QueryFiles
- Write-Host "form-decompile: $OutputPath"
- } else {
- Write-Output $json
- }
.claude/skills/form-edit/scripts/form-edit.ps1 · Bundled script · 9,026 lines
- # form-edit v1.60 — Edit 1C managed form elements
- # Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
- [CmdletBinding(PositionalBinding=$false)]
- param(
- [Parameter(Mandatory)]
- [Alias('Path')]
- [string]$FormPath,
- [Parameter(Mandatory)]
- [string]$JsonPath
- )
- $ErrorActionPreference = "Stop"
- # --- Булевы флаги DSL: прощающий ввод ---
- # Флаг строкой или числом — однозначная ошибка автора JSON: true|да|истина|1 / false|нет|ложь|0 (без
- # регистра; 1/0 — и числом) приводим к bool молча. Иное — ошибка без записи: молчаливое «false» из «yes»
- # хуже отказа. Без общего читателя порты расходились: PS (-eq) принимал "false", py (is) — нет.
- function ConvertTo-DslBool {
- param($Value, [string]$Key, [bool]$Default)
- if ($null -eq $Value) { return $Default }
- if ($Value -is [bool]) { return $Value }
- if ($Value -is [string]) {
- $t = $Value.Trim().ToLowerInvariant()
- if (@('true', 'да', 'истина', '1') -ccontains $t) { return $true }
- if (@('false', 'нет', 'ложь', '0') -ccontains $t) { return $false }
- } elseif ($Value -is [int] -or $Value -is [long] -or $Value -is [double] -or $Value -is [decimal]) {
- if ($Value -eq 1) { return $true }
- if ($Value -eq 0) { return $false }
- }
- $shown = if ($Value -is [string]) { '"' + $Value + '"' } else { "$Value" }
- [Console]::Error.WriteLine("[ERROR] $Key = ${shown}: expected true or false")
- exit 1
- }
- # Первый найденный ключ из $Keys (синонимы, без регистра) → ConvertTo-DslBool; не объект / нет ключа → $Default.
- function Get-DslBool {
- param($Obj, [string[]]$Keys, [bool]$Default)
- if ($null -eq $Obj -or $Obj -is [string] -or $Obj -is [ValueType]) { return $Default }
- foreach ($k in $Keys) {
- if ($Obj -is [System.Collections.IDictionary]) {
- if ($Obj.Contains($k)) { return (ConvertTo-DslBool $Obj[$k] $k $Default) }
- } elseif ($Obj.PSObject.Properties[$k]) {
- return (ConvertTo-DslBool $Obj.PSObject.Properties[$k].Value $k $Default)
- }
- }
- return $Default
- }
- # --- Разбор пользовательского JSON ---
- # Одна строка в stderr вместо дампа исключения ConvertFrom-Json (issue #80): агент по стектрейсу
- # идёт чинить скрипт, а не свой вызов. $source — файл или параметр. $expected заполняем только
- # для полиморфного входа: у файла подсказка была бы наполнителем. -Inline печатает ещё и то,
- # что доехало: у файла такого вопроса нет — путь назван, позицию дал парсер, файл на диске.
- # Возврат через запятую: без неё одноэлементный JSON-массив разворачивался бы в скаляр
- # вторым анруллингом. Не Write-Output -NoEnumerate: pwsh 7.6 заворачивает им в List
- # и одиночный объект (issue #136).
- function ConvertFrom-JsonInput([string]$text, [string]$source, [string]$expected, [switch]$Inline) {
- try {
- # PS 5.1 на пустой строке отдаёт $null, а не ошибку — навык уходил дальше с $null,
- # тогда как py-порт падал. Проверяем сами, чтобы порты вели себя одинаково.
- if ([string]::IsNullOrWhiteSpace($text)) { throw 'input is empty' }
- # pwsh 7+ сам разворачивает массив верхнего уровня ([x] → x, [] → $null). Ключ -NoEnumerate
- # появился там же: в 5.1 и pwsh 6 его нет, поэтому спрашиваем командлет, а не версию.
- $cfj = @{}
- $cfjKeys = (Get-Command ConvertFrom-Json).Parameters
- if ($cfjKeys.ContainsKey('NoEnumerate')) { $cfj.NoEnumerate = $true }
- # pwsh 7.5+ без -DateKind String превращает ISO-строки дат в DateTime, и в XML уходит формат
- # локали; в 5.1 и pwsh до 7.5 ключа нет (5.1 даты и так не трогает).
- if ($cfjKeys.ContainsKey('DateKind')) { $cfj.DateKind = 'String' }
- $parsed = $text | ConvertFrom-Json @cfj
- } catch {
- $what = if ($expected) { "$source expects $expected" } else { "Invalid JSON in $source" }
- if ($Inline) {
- $got = ($text -replace '\s+', ' ').Trim()
- $label = 'got'
- if (-not $got) { $got = '(empty)' }
- elseif ($got.Length -gt 60) { $label = 'got (first 60 chars)'; $got = $got.Substring(0, 60) }
- $what = "${what}, ${label}: ${got}"
- }
- [Console]::Error.WriteLine("[ERROR] ${what} ($($_.Exception.Message))")
- exit 1
- }
- return ,$parsed
- }
- # --- Чтение входного JSON-файла ---
- # Кодировку берём из BOM — это объявление самого файла, а не догадка. Без BOM ждём строгий UTF-8:
- # Get-Content -Encoding UTF8 на файле в cp1251 тихо меняет кириллицу на U+FFFD, JSON после этого
- # разбирается успешно, и в конфигурацию уезжает имя из «замен». Кодовую страницу не подбираем:
- # угаданное имя уйдёт в метаданные так же молча.
- function Read-JsonInputFile([string]$path) {
- # Проверка здесь, а не по навыкам: часть навыков проверяла путь сама, часть — нет, и один и тот
- # же промах давал то внятную строку, то дамп MethodInvocationException. Навыки со своей
- # проверкой срабатывают раньше и сохраняют свой текст.
- if (-not (Test-Path -LiteralPath $path)) {
- [Console]::Error.WriteLine("[ERROR] File not found: $path")
- exit 1
- }
- if (Test-Path -LiteralPath $path -PathType Container) {
- [Console]::Error.WriteLine("[ERROR] Expected a JSON file, got a directory: $path")
- exit 1
- }
- $bytes = [System.IO.File]::ReadAllBytes($path)
- if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) {
- return [System.Text.Encoding]::UTF8.GetString($bytes, 3, $bytes.Length - 3)
- }
- if ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFF -and $bytes[1] -eq 0xFE) {
- return [System.Text.Encoding]::Unicode.GetString($bytes, 2, $bytes.Length - 2)
- }
- if ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFE -and $bytes[1] -eq 0xFF) {
- return [System.Text.Encoding]::BigEndianUnicode.GetString($bytes, 2, $bytes.Length - 2)
- }
- try {
- return (New-Object System.Text.UTF8Encoding($false, $true)).GetString($bytes)
- } catch {
- $detail = if ($_.Exception.InnerException) { $_.Exception.InnerException.Message } else { $_.Exception.Message }
- [Console]::Error.WriteLine("[ERROR] ${path} is not valid UTF-8: ${detail} - save the file as UTF-8, or add a BOM if it is UTF-16")
- exit 1
- }
- }
- [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
- # --- Support guard (Ext/ParentConfigurations.bin) ---
- # See docs/1c-support-state-spec.md. Blocks edits of vendor objects "на замке" /
- # read-only configs unless allowed. Trigger = bin present; reaction from
- # .v8-project.json editingAllowedCheck (deny|warn|off, default deny). Never
- # throws — guard errors degrade to allow.
- function Get-RootUuid([string]$xmlPath) {
- if (-not (Test-Path $xmlPath)) { return $null }
- try {
- [xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
- $el = $mx.DocumentElement.FirstChild
- while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
- if ($el) { $u = $el.GetAttribute("uuid"); if ($u) { return $u } }
- } catch {}
- return $null
- }
- function Test-ExternalObjectRoot([string]$xmlPath) {
- if (-not (Test-Path $xmlPath)) { return $false }
- try {
- [xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
- $el = $mx.DocumentElement.FirstChild
- while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
- if ($el) { return @('ExternalDataProcessor','ExternalReport') -contains $el.LocalName }
- } catch {}
- return $false
- }
- function Find-V8Project([string]$startDir) {
- $d = $startDir
- for ($i = 0; $i -lt 20 -and $d; $i++) {
- $pj = Join-Path $d ".v8-project.json"
- if (Test-Path $pj) { return $pj }
- $parent = [System.IO.Path]::GetDirectoryName($d)
- if ($parent -eq $d) { break }
- $d = $parent
- }
- return $null
- }
- function Get-EditMode([string]$cfgDir) {
- try {
- $pj = Find-V8Project (Get-Location).ProviderPath
- if (-not $pj) { $pj = Find-V8Project ([System.IO.Path]::GetFullPath($cfgDir)) }
- if (-not $pj) { return 'deny' }
- # UTF-8 явно: PS 5.1 читает файл без BOM как ANSI, и configSrc с кириллицей не совпал бы
- $proj = Get-Content -Raw -Encoding UTF8 $pj | ConvertFrom-Json
- # configSrc — от каталога .v8-project.json, а не от рабочего каталога: иначе из подкаталога
- # проекта база не сопоставляется и берётся правило проекта.
- $projDir = [System.IO.Path]::GetDirectoryName($pj)
- $cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
- if ($proj.databases) {
- foreach ($db in $proj.databases) {
- if ($db.configSrc) {
- $src = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($projDir, $db.configSrc)).TrimEnd('\', '/')
- if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
- if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
- }
- }
- }
- }
- if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
- return 'deny'
- } catch { return 'deny' }
- }
- function Assert-EditAllowed([string]$targetPath, [string]$require) {
- try {
- $rp = $targetPath
- try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).ProviderPath } catch {}
- # Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
- if (Test-ExternalObjectRoot $rp) { return }
- $elemUuid = Get-RootUuid $rp
- $cfgDir = $null; $binPath = $null
- $d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
- for ($i = 0; $i -lt 12 -and $d; $i++) {
- if (Test-ExternalObjectRoot "$d.xml") { return }
- if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
- if (-not $cfgDir) {
- $cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
- if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
- }
- if ($elemUuid -and $cfgDir) { break }
- $parent = [System.IO.Path]::GetDirectoryName($d)
- if ($parent -eq $d) { break }
- $d = $parent
- }
- # New object (no element file): fall back to config root uuid.
- if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
- if (-not $binPath -or -not (Test-Path $binPath)) { return }
- $bytes = [System.IO.File]::ReadAllBytes($binPath)
- if ($bytes.Length -le 32) { return }
- $start = 0
- if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
- $text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
- $hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
- if (-not $hm.Success) { return }
- $G = [int]$hm.Groups[1].Value
- $K = [int]$hm.Groups[2].Value
- if ($K -eq 0) { return }
- $best = $null
- if ($elemUuid) {
- $u = [regex]::Escape($elemUuid.ToLower())
- foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
- $f1 = [int]$m.Groups[1].Value
- if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
- }
- }
- $blocked = $false; $code = ""; $reason = ""
- if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
- elseif ($require -eq 'removed') {
- if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
- }
- else {
- if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
- }
- if (-not $blocked) { return }
- $mode = Get-EditMode $cfgDir
- if ($mode -eq 'off') { return }
- # Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
- # latter throws and would be swallowed by this function's own catch.
- if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
- $head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
- $cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
- $offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
- if ($code -eq "capability-off") {
- $state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
- $fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
- } elseif ($code -eq "not-removed") {
- $state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
- $fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
- } else {
- $state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
- $fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
- }
- [Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
- exit 1
- } catch { return }
- }
- # === 1. Load Form.xml ===
- if (-not (Test-Path $FormPath)) {
- Write-Error "File not found: $FormPath"
- exit 1
- }
- if (-not (Test-Path $JsonPath)) {
- Write-Error "File not found: $JsonPath"
- exit 1
- }
- $resolvedFormPath = (Resolve-Path $FormPath).ProviderPath
- Assert-EditAllowed $resolvedFormPath 'editable'
- $xmlDoc = New-Object System.Xml.XmlDocument
- $xmlDoc.PreserveWhitespace = $true
- try {
- $xmlDoc.Load($resolvedFormPath)
- } catch {
- Write-Host "[ERROR] XML parse error: $($_.Exception.Message)"
- exit 1
- }
- $formNs = "http://v8.1c.ru/8.3/xcf/logform"
- $v8Ns = "http://v8.1c.ru/8.1/data/core"
- $nsMgr = New-Object System.Xml.XmlNamespaceManager($xmlDoc.NameTable)
- $nsMgr.AddNamespace("f", $formNs)
- $nsMgr.AddNamespace("v8", $v8Ns)
- $root = $xmlDoc.DocumentElement
- # === 2. Load JSON ===
- $def = ConvertFrom-JsonInput (Read-JsonInputFile $JsonPath) $JsonPath
- # Флаг main строкой или числом ("true", 1) — как булево: иначе порты расходятся (PS `-eq $true` принимает
- # строку и 1, Python `is True` — нет)
- function Normalize-MainFlag($attrs) {
- foreach ($a in @($attrs)) {
- if ($a -isnot [System.Management.Automation.PSCustomObject]) { continue }
- $p = $a.PSObject.Properties['main']
- if ($null -eq $p) { continue }
- $v = $p.Value
- if ($v -is [string]) {
- $s = $v.Trim().ToLower()
- if ($s -eq 'true') { $p.Value = $true } elseif ($s -eq 'false') { $p.Value = $false }
- } elseif (($v -is [int] -or $v -is [long]) -and ($v -eq 0 -or $v -eq 1)) {
- $p.Value = ($v -eq 1)
- }
- }
- }
- Normalize-MainFlag $def.attributes
- # === 3. Form name + header ===
- $formName = [System.IO.Path]::GetFileNameWithoutExtension($FormPath)
- $parentDir = [System.IO.Path]::GetDirectoryName($resolvedFormPath)
- if ($parentDir) {
- $extDir = [System.IO.Path]::GetFileName($parentDir)
- if ($extDir -eq "Ext") {
- $formDir = [System.IO.Path]::GetDirectoryName($parentDir)
- if ($formDir) { $formName = [System.IO.Path]::GetFileName($formDir) }
- }
- }
- Write-Host "=== form-edit: $formName ==="
- Write-Host ""
- # === 4. Scan max IDs per pool ===
- $script:nextElemId = 0
- $script:nextAttrId = 0
- $script:nextCmdId = 0
- # Scan ALL element IDs via XPath (includes companions like ExtendedTooltip, ContextMenu)
- $rootCI = $root.SelectSingleNode("f:ChildItems", $nsMgr)
- if ($rootCI) {
- foreach ($elem in $rootCI.SelectNodes(".//*[@id]")) {
- $id = $elem.GetAttribute("id")
- if ($id -and $id -ne "-1") {
- try { $intId = [int]$id; if ($intId -gt $script:nextElemId) { $script:nextElemId = $intId } } catch {}
- }
- }
- }
- # Командная панель формы: сама (id=-1) и её кнопки — из того же пула, что и элементы
- $acb = $root.SelectSingleNode("f:AutoCommandBar", $nsMgr)
- if ($acb) {
- $acbIds = New-Object System.Collections.ArrayList
- [void]$acbIds.Add($acb.GetAttribute("id"))
- foreach ($elem in $acb.SelectNodes(".//*[@id]")) { [void]$acbIds.Add($elem.GetAttribute("id")) }
- foreach ($id in $acbIds) {
- if ($id -and $id -ne "-1") {
- try { $intId = [int]$id; if ($intId -gt $script:nextElemId) { $script:nextElemId = $intId } } catch {}
- }
- }
- }
- # Scan attribute IDs (including column IDs — same pool)
- foreach ($attr in $root.SelectNodes("f:Attributes/f:Attribute", $nsMgr)) {
- $id = $attr.GetAttribute("id")
- if ($id) {
- try { $intId = [int]$id; if ($intId -gt $script:nextAttrId) { $script:nextAttrId = $intId } } catch {}
- }
- # Column IDs are in the same pool as attribute IDs
- foreach ($col in $attr.SelectNodes("f:Columns/f:Column", $nsMgr)) {
- $colId = $col.GetAttribute("id")
- if ($colId) {
- try { $intColId = [int]$colId; if ($intColId -gt $script:nextAttrId) { $script:nextAttrId = $intColId } } catch {}
- }
- }
- }
- # Scan command IDs
- foreach ($cmd in $root.SelectNodes("f:Commands/f:Command", $nsMgr)) {
- $id = $cmd.GetAttribute("id")
- if ($id) {
- try { $intId = [int]$id; if ($intId -gt $script:nextCmdId) { $script:nextCmdId = $intId } } catch {}
- }
- }
- $script:nextElemId++
- $script:nextAttrId++
- $script:nextCmdId++
- # Префикс имён расширения — <NamePrefix> ближайшего вверх Configuration.xml; "" — не расширение или не задан.
- function Get-ExtensionNamePrefix([string]$dir) {
- $d = $dir
- while ($d) {
- $cfg = Join-Path $d 'Configuration.xml'
- if (Test-Path -LiteralPath $cfg) {
- $m = [regex]::Match([System.IO.File]::ReadAllText($cfg), '<NamePrefix>([^<]*)</NamePrefix>')
- if ($m.Success) { return $m.Groups[1].Value }
- return ''
- }
- $parent = Split-Path $d -Parent
- if (-not $parent -or $parent -eq $d) { break }
- $d = $parent
- }
- return ''
- }
- # --- 4b. Auto-detect extension mode (BaseForm present) ---
- $script:isExtension = $false
- $script:extNamePrefix = ''
- $baseForm = $root.SelectSingleNode("f:BaseForm", $nsMgr)
- if ($baseForm) {
- $script:isExtension = $true
- $script:extNamePrefix = Get-ExtensionNamePrefix ([System.IO.Path]::GetDirectoryName($resolvedFormPath))
- if ($script:nextAttrId -lt 1000000) { $script:nextAttrId = 1000000 }
- if ($script:nextCmdId -lt 1000000) { $script:nextCmdId = 1000000 }
- if ($script:nextElemId -lt 1000000) { $script:nextElemId = 1000000 }
- }
- function New-ElemId { $id = $script:nextElemId; $script:nextElemId++; return $id }
- function New-AttrId { $id = $script:nextAttrId; $script:nextAttrId++; return $id }
- function New-CmdId { $id = $script:nextCmdId; $script:nextCmdId++; return $id }
- # For element emitters, New-Id = New-ElemId
- function New-Id { return New-ElemId }
- # === 5. Fragment helpers (StringBuilder + Emit-* from form-compile) ===
- $script:xml = New-Object System.Text.StringBuilder 4096
- function X {
- param([string]$text)
- $script:xml.AppendLine($text) | Out-Null
- }
- # --- Type emitter ---
- $script:formTypeSynonyms = New-Object System.Collections.Hashtable
- $script:formTypeSynonyms["строка"] = "string"
- $script:formTypeSynonyms["число"] = "decimal"
- $script:formTypeSynonyms["булево"] = "boolean"
- $script:formTypeSynonyms["дата"] = "date"
- $script:formTypeSynonyms["датавремя"]= "dateTime"
- $script:formTypeSynonyms["number"] = "decimal"
- $script:formTypeSynonyms["bool"] = "boolean"
- $script:formTypeSynonyms["справочникссылка"] = "CatalogRef"
- $script:formTypeSynonyms["справочникобъект"] = "CatalogObject"
- $script:formTypeSynonyms["документссылка"] = "DocumentRef"
- $script:formTypeSynonyms["документобъект"] = "DocumentObject"
- $script:formTypeSynonyms["перечислениессылка"] = "EnumRef"
- $script:formTypeSynonyms["плансчетовссылка"] = "ChartOfAccountsRef"
- $script:formTypeSynonyms["планвидовхарактеристикссылка"] = "ChartOfCharacteristicTypesRef"
- $script:formTypeSynonyms["планвидоврасчётассылка"] = "ChartOfCalculationTypesRef"
- $script:formTypeSynonyms["планвидоврасчетассылка"] = "ChartOfCalculationTypesRef"
- $script:formTypeSynonyms["планобменассылка"] = "ExchangePlanRef"
- $script:formTypeSynonyms["бизнеспроцессссылка"] = "BusinessProcessRef"
- $script:formTypeSynonyms["задачассылка"] = "TaskRef"
- $script:formTypeSynonyms["определяемыйтип"] = "DefinedType"
- $script:formTypeSynonyms["характеристика"] = "Characteristic"
- $script:formTypeSynonyms["любаяссылка"] = "AnyRef"
- $script:formTypeSynonyms["любаяссылкаиб"] = "AnyIBRef"
- # Платформенные v8-типы (forgiving: англ. без префикса + рус.) → каноничный с префиксом v8: (эмитим verbatim)
- $script:formTypeSynonyms["standardperiod"] = "v8:StandardPeriod"
- $script:formTypeSynonyms["стандартныйпериод"] = "v8:StandardPeriod"
- $script:formTypeSynonyms["standardbeginningdate"] = "v8:StandardBeginningDate"
- $script:formTypeSynonyms["стандартнаядатаначала"] = "v8:StandardBeginningDate"
- $script:formTypeSynonyms["uuid"] = "v8:UUID"
- $script:formTypeSynonyms["уникальныйидентификатор"] = "v8:UUID"
- $script:formTypeSynonyms["списокзначений"] = "ValueList"
- # Алиас на локальный словарь: тело Resolve-TypeStr ниже — общая реализация,
- # одинаковая во всех навыках (реестр в tests/skills/check-inline-drift.mjs).
- $script:typeSynonyms = $script:formTypeSynonyms
- # --- Event handler name generator ---
- # --- Element helpers ---
- # Уникальность имён внутри JSON-определения (1С: своя коллекция — свой неймспейс).
- function Assert-EditUnique {
- param([string]$name, [hashtable]$seen, [string]$ctx)
- if ($seen.ContainsKey($name)) {
- Write-Host "[ERROR] Duplicate $ctx '$name' in JSON definition — names must be unique in 1C form"
- exit 1
- }
- $seen[$name] = $true
- }
- # --- Element emitters ---
- # --- Element dispatcher ---
- # === 5b. Эмиттер элементов — общий с form-compile (эталон там; копии держит check-inline-drift) ===
- $script:queryBaseDir = if ($JsonPath) { [System.IO.Path]::GetDirectoryName((Resolve-Path $JsonPath).ProviderPath) } else { (Get-Location).ProviderPath }
- $script:fmtMarkupRe = '</>|<\s*(?:link|b|i|u|s|color|colorStyle|bgColor|bgColorStyle|font|fontSize|fontStyle|img)(?:\s|>)'
- $script:CANON_FILTER_ID = 'dfcece9d-5077-440b-b6b3-45a5cb4538eb'
- $script:CANON_ORDER_ID = '88619765-ccb3-46c6-ac52-38e9c992ebd4'
- $script:CANON_CA_ID = 'b75fecce-942b-4aed-abc9-e6a02e460fb3'
- $script:CANON_ITEMS_ID = '911b6018-f537-43e8-a417-da56b22f9aec'
- $script:comparisonTypes = @{
- "=" = "Equal"; "<>" = "NotEqual"
- ">" = "Greater"; ">=" = "GreaterOrEqual"
- "<" = "Less"; "<=" = "LessOrEqual"
- "in" = "InList"; "notIn" = "NotInList"
- "inHierarchy" = "InHierarchy"; "inListByHierarchy" = "InListByHierarchy"
- "contains" = "Contains"; "notContains" = "NotContains"
- "beginsWith" = "BeginsWith"; "notBeginsWith" = "NotBeginsWith"
- "like" = "Like"; "notLike" = "NotLike"
- "подобно" = "Like"; "неподобно" = "NotLike" # рус. синоним (хэш регистронезависим: ПОДОБНО=подобно)
- "filled" = "Filled"; "notFilled" = "NotFilled"
- }
- $script:calcRestrictMap = @{ 'noField'='field'; 'noFilter'='condition'; 'noCondition'='condition'; 'noGroup'='group'; 'noOrder'='order' }
- $script:dcsCommonNs = 'http://v8.1c.ru/8.1/data-composition-system/common'
- $script:knownInvalidTypes = @{
- "FormDataStructure" = "Runtime type. Use object type without cfg: prefix (e.g. CatalogObject.Контрагенты, DocumentObject.Приход)"
- "FormDataCollection" = "Runtime type. Use ValueTable"
- "FormDataTree" = "Runtime type. Use ValueTree"
- "FormDataTreeItem" = "Runtime type, not valid in XML"
- "FormDataCollectionItem"= "Runtime type, not valid in XML"
- "FormGroup" = "UI element type, not a data type"
- "FormField" = "UI element type, not a data type"
- "FormButton" = "UI element type, not a data type"
- "FormDecoration" = "UI element type, not a data type"
- "FormTable" = "UI element type, not a data type"
- }
- # --- Каталог событий формы (генерируется) ---
- # Тег элемента («Form» — сама форма) → событие → @(суффикс имени обработчика, директива компиляции,
- # параметры, с какой платформы событие есть ("" — с 8.3.20), ограничение). Параметры — строка или
- # @("платформа", "параметры", …) — сигнатура с этой платформы. Ограничение: у таблицы — источник
- # (DynamicList), у формы — владельцы, у форм которых событие есть (по основному реквизиту). Последнее —
- # позиция события в <Events>: платформа пишет события в этом порядке, какой бы ни был на входе.
- # Источники: синтакс-помощник 8.3.20–8.5, типовые конфигурации (28.5 тыс. форм), замер загрузкой на 7 платформах.
- # Перегенерировать: python debug/form-handlers/gen_event_catalog.py
- function Get-FormEventCatalog {
- return @{
- "CalendarField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "DragCheck" = @("ПроверкаПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, ВыбраннаяДата", "", "", 1)
- "OnPeriodOutput" = @("ПриВыводеПериода", "НаКлиенте", "Элемент, ОформлениеПериода", "", "", 2)
- "Selection" = @("Выбор", "НаКлиенте", "Элемент, ВыбраннаяДата", "", "", 3)
- "OnActivateDate" = @("ПриАктивизацииДаты", "НаКлиенте", "Элемент", "", "", 4)
- "DragStart" = @("НачалоПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, Выполнение", "", "", 5)
- "Drag" = @("Перетаскивание", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, ВыбраннаяДата", "", "", 6)
- "DragEnd" = @("ОкончаниеПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 7)
- }
- "ChartField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "Selection" = @("Выбор", "НаКлиенте", "Элемент, ЗначениеДиаграммы, СтандартнаяОбработка", "", "", 1)
- "DetailProcessing" = @("ОбработкаРасшифровки", "НаКлиенте", "Элемент, Расшифровка, СтандартнаяОбработка", "", "", 2)
- "OnActivate" = @("ПриАктивизации", "НаКлиенте", "Элемент", "", "", 3)
- }
- "CheckBoxField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- }
- "DendrogramField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "DetailProcessing" = @("ОбработкаРасшифровки", "НаКлиенте", "Элемент, Расшифровка, СтандартнаяОбработка", "", "", 1)
- "Selection" = @("Выбор", "НаКлиенте", "Элемент, ЗначениеДендрограммы, СтандартнаяОбработка", "", "", 2)
- }
- "ExtendedTooltip" = @{
- "Click" = @("Нажатие", "НаКлиенте", "Элемент", "", "", 0)
- "URLProcessing" = @("ОбработкаНавигационнойСсылки", "НаКлиенте", "Элемент, НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка", "", "", 1)
- }
- "Form" = @{
- "AfterWrite" = @("ПослеЗаписи", "НаКлиенте", "ПараметрыЗаписи", "", "Document, Catalog, ChartOfCharacteristicTypes, BusinessProcess, Task, InformationRegisterRecord, InformationRegisterRecordSet, Constants, ExchangePlan, ChartOfAccounts, ChartOfCalculationTypes", 0)
- "BeforeReopenFromOtherServer" = @("ПередПереоткрытиемСДругогоСервера", "НаКлиенте", "Параметры, Отказ", "", "", 1)
- "ValueChoice" = @("ВыборЗначения", "НаКлиенте", "СтандартнаяОбработка", "", "Document, Catalog, ChartOfCharacteristicTypes, BusinessProcess, Task, ExchangePlan, ChartOfAccounts, ChartOfCalculationTypes", 2)
- "OnReopenFromOtherServer" = @("ПриПереоткрытииСДругогоСервера", "НаКлиенте", "Источник, ПараметрыЗаполнения, СтандартнаяОбработка", "", "", 3)
- "OnSaveDataInSettingsAtServer" = @("ПриСохраненииДанныхВНастройкахНаСервере", "НаСервере", "Настройки", "", "", 4)
- "ChoiceProcessing" = @("ОбработкаВыбора", "НаКлиенте", "ВыбранноеЗначение, ИсточникВыбора", "", "", 5)
- "BeforeLoadVariantAtServer" = @("ПередЗагрузкойВариантаНаСервере", "НаСервере", "Настройки", "", "Report", 6)
- "AfterWriteAtServer" = @("ПослеЗаписиНаСервере", "НаСервере", "ТекущийОбъект, ПараметрыЗаписи", "", "Document, Catalog, ChartOfCharacteristicTypes, BusinessProcess, Task, InformationRegisterRecord, InformationRegisterRecordSet, Constants, ExchangePlan, ChartOfAccounts, ChartOfCalculationTypes", 7)
- "OnPasteFromClipboard" = @("ПриВставкеИзБуфераОбмена", "НаКлиенте", "Значение, СтандартнаяОбработка", "8.3.24", "", 8)
- "BeforeStart" = @("ПередСтартом", "НаКлиенте", "Отказ", "", "BusinessProcess", 9)
- "NotificationProcessing" = @("ОбработкаОповещения", "НаКлиенте", "ИмяСобытия, Параметр, Источник", "", "", 10)
- "OnReadAtServer" = @("ПриЧтенииНаСервере", "НаСервере", "ТекущийОбъект", "", "Document, Catalog, ChartOfCharacteristicTypes, BusinessProcess, Task, InformationRegisterRecord, InformationRegisterRecordSet, Constants, ExchangePlan, ChartOfAccounts, ChartOfCalculationTypes", 11)
- "NewWriteProcessing" = @("ОбработкаЗаписиНового", "НаКлиенте", "НовыйОбъект, Источник, СтандартнаяОбработка", "", "", 12)
- "OnOpen" = @("ПриОткрытии", "НаКлиенте", "Отказ", "", "", 13)
- "BeforeLoadUserSettingsAtServer" = @("ПередЗагрузкойПользовательскихНастроекНаСервере", "НаСервере", "Настройки, ИспользуютсяСтандартныеНастройки", "", "Report", 14)
- "URLListGetProcessing" = @("ОбработкаПолученияСпискаНавигационныхСсылок", "НаКлиенте", "СписокНавигационыхСсылок, КлючПоУмолчанию", "", "", 15)
- "OnSaveVariantAtServer" = @("ПриСохраненииВариантаНаСервере", "НаСервере", "Настройки", "", "Report", 16)
- "BeforeClose" = @("ПередЗакрытием", "НаКлиенте", "Отказ, ЗавершениеРаботы, ТекстПредупреждения, СтандартнаяОбработка", "", "", 17)
- "ExternalEvent" = @("ВнешнееСобытие", "НаКлиенте", "Источник, Событие, Данные", "", "", 18)
- "CollaborationSystemUsersAutoComplete" = @("АвтоПодборПользователейСистемыВзаимодействия", "НаКлиенте", "Текст, ДанныеВыбора, НазначениеВыбора, СтандартнаяОбработка", "", "", 19)
- "OnSettingsChange" = @("ПриИзмененииНастроек", "НаКлиенте", "СтандартнаяОбработка", "8.5", "Report", 20)
- "URLGetProcessing" = @("ОбработкаПолученияНавигационнойСсылки", "НаКлиенте", "Ключ, Представление, НавигационнаяСсылка, СтандартнаяОбработка", "", "", 21)
- "OnReopen" = @("ПриПовторномОткрытии", "НаКлиенте", "", "", "", 22)
- "OnLoadDataFromSettingsAtServer" = @("ПриЗагрузкеДанныхИзНастроекНаСервере", "НаСервере", "Настройки", "", "", 23)
- "OnLoadUserSettingsAtServer" = @("ПриЗагрузкеПользовательскихНастроекНаСервере", "НаСервере", "Настройки, ИспользуютсяСтандартныеНастройки", "", "Report", 24)
- "OnLoadVariantAtServer" = @("ПриЗагрузкеВариантаНаСервере", "НаСервере", "Настройки", "", "Report", 25)
- "NavigationProcessing" = @("ОбработкаПерехода", "НаКлиенте", "ОбъектПерехода, СтандартнаяОбработка", "", "", 26)
- "OnSaveUserSettingsAtServer" = @("ПриСохраненииПользовательскихНастроекНаСервере", "НаСервере", "Настройки", "", "Report", 27)
- "BeforeWrite" = @("ПередЗаписью", "НаКлиенте", "Отказ, ПараметрыЗаписи", "", "Document, Catalog, ChartOfCharacteristicTypes, BusinessProcess, Task, InformationRegisterRecord, InformationRegisterRecordSet, Constants, ExchangePlan, ChartOfAccounts, ChartOfCalculationTypes", 28)
- "OnCreateAtServer" = @("ПриСозданииНаСервере", "НаСервере", "Отказ, СтандартнаяОбработка", "", "", 29)
- "CollaborationSystemUsersChoiceFormGetProcessing" = @("ОбработкаПолученияФормыВыбораПользователейСистемыВзаимодействия", "НаКлиенте", "НазначениеВыбора, Параметры, ВыбраннаяФорма, СтандартнаяОбработка", "", "", 30)
- "OnComposeResult" = @("ПриКомпоновкеРезультата", "НаКлиенте", "СтандартнаяОбработка", "8.5", "Report", 31)
- "ActivationProcessing" = @("ОбработкаАктивизации", "НаКлиенте", "АктивныйОбъект, Источник", "", "", 32)
- "AfterComposeResult" = @("ПослеКомпоновкиРезультата", "НаКлиенте", "Результат, СтандартнаяОбработка", "8.5", "Report", 33)
- "OnChangeDisplaySettings" = @("ПриИзмененииПараметровЭкрана", "НаКлиенте", "", "", "", 34)
- "BeforeWriteAtServer" = @("ПередЗаписьюНаСервере", "НаСервере", "Отказ, ТекущийОбъект, ПараметрыЗаписи", "", "Document, Catalog, ChartOfCharacteristicTypes, BusinessProcess, Task, InformationRegisterRecord, InformationRegisterRecordSet, Constants, ExchangePlan, ChartOfAccounts, ChartOfCalculationTypes", 35)
- "OnWriteAtServer" = @("ПриЗаписиНаСервере", "НаСервере", "Отказ, ТекущийОбъект, ПараметрыЗаписи", "", "Document, Catalog, ChartOfCharacteristicTypes, BusinessProcess, Task, InformationRegisterRecord, InformationRegisterRecordSet, Constants, ExchangePlan, ChartOfAccounts, ChartOfCalculationTypes", 36)
- "OnClose" = @("ПриЗакрытии", "НаКлиенте", "ЗавершениеРаботы", "", "", 37)
- "OnMainServerAvailabilityChange" = @("ПриИзмененииДоступностиОсновногоСервера", "НаКлиенте", "СтандартнаяОбработка", "", "", 38)
- "OnUpdateUserSettingSetAtServer" = @("ПриОбновленииСоставаПользовательскихНастроекНаСервере", "НаСервере", "СтандартнаяОбработка", "", "Report, SettingsComposer", 39)
- "URLProcessing" = @("ОбработкаНавигационнойСсылки", "НаКлиенте", "НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка", "", "", 40)
- "FillCheckProcessingAtServer" = @("ОбработкаПроверкиЗаполненияНаСервере", "НаСервере", "Отказ, ПроверяемыеРеквизиты", "", "", 41)
- "BeforeLoadDataFromSettingsAtServer" = @("ПередЗагрузкойДанныхИзНастроекНаСервере", "НаСервере", "Настройки", "", "", 42)
- "BeforeExecute" = @("ПередВыполнением", "НаКлиенте", "Отказ", "", "Task", 43)
- "AddInDetachmentOnError" = @("ОтключениеВнешнейКомпонентыПриОшибке", "НаКлиенте", "Имя, Местоположение", "8.3.23", "", 44)
- }
- "FormattedDocumentField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "BeforePrint" = @("ПередПечатью", "НаКлиенте", "Элемент, ДиалогПечати, Отказ", "", "", 1)
- "AfterWrite" = @("ПослеЗаписи", "НаКлиенте", "Элемент", "", "", 2)
- "BeforeWrite" = @("ПередЗаписью", "НаКлиенте", "Элемент, Копирование, Отказ", "", "", 3)
- }
- "GanttChartField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "Selection" = @("Выбор", "НаКлиенте", "Элемент, Значения, СтандартнаяОбработка, Дата", "", "", 1)
- "DetailProcessing" = @("ОбработкаРасшифровки", "НаКлиенте", "Элемент, Расшифровка, СтандартнаяОбработка, Дата", "", "", 2)
- "BeforeCollapse" = @("ПередСворачиванием", "НаКлиенте", "Элемент, ИдентификаторЗначения, Отказ", "8.3.23", "", 3)
- "OnActivateInterval" = @("ПриАктивизацииИнтервала", "НаКлиенте", "Элемент", "8.3.23", "", 4)
- "OnActivateValue" = @("ПриАктивизацииЗначения", "НаКлиенте", "Элемент", "8.3.23", "", 5)
- "BeforeExpand" = @("ПередРазворачиванием", "НаКлиенте", "Элемент, ИдентификаторЗначения, Отказ", "8.3.23", "", 6)
- "OnIntervalEditEnd" = @("ПриОкончанииРедактированияИнтервала", "НаКлиенте", "Элемент, Интервал, ОтменаРедактирования", "", "", 7)
- }
- "GeographicalSchemaField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "DetailProcessing" = @("ОбработкаРасшифровки", "НаКлиенте", "Элемент, Расшифровка, СтандартнаяОбработка", "", "", 1)
- "BeforePrint" = @("ПередПечатью", "НаКлиенте", "Элемент, ДиалогПечати, Отказ", "", "", 2)
- }
- "GraphicalSchemaField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "Selection" = @("Выбор", "НаКлиенте", "Элемент", "", "", 1)
- "AfterWrite" = @("ПослеЗаписи", "НаКлиенте", "Элемент", "", "", 2)
- "OnActivate" = @("ПриАктивизации", "НаКлиенте", "Элемент", "", "", 3)
- "BeforeWrite" = @("ПередЗаписью", "НаКлиенте", "Элемент, Копирование, Отказ", "", "", 4)
- "BeforePrint" = @("ПередПечатью", "НаКлиенте", "Элемент, ДиалогПечати, Отказ", "", "", 5)
- }
- "HTMLDocumentField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "DocumentComplete" = @("ДокументСформирован", "НаКлиенте", "Элемент", "", "", 1)
- "BeforeWrite" = @("ПередЗаписью", "НаКлиенте", "Элемент, Копирование, Отказ", "", "", 2)
- "BeforePrint" = @("ПередПечатью", "НаКлиенте", "Элемент, ДиалогПечати, Отказ", "", "", 3)
- "AfterWrite" = @("ПослеЗаписи", "НаКлиенте", "Элемент", "", "", 4)
- "OnClick" = @("ПриНажатии", "НаКлиенте", "Элемент, ДанныеСобытия, СтандартнаяОбработка", "", "", 5)
- }
- "InputField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "EditTextChange" = @("ИзменениеТекстаРедактирования", "НаКлиенте", "Элемент, Текст, СтандартнаяОбработка", "", "", 1)
- "AutoComplete" = @("АвтоПодбор", "НаКлиенте", "Элемент, Текст, ДанныеВыбора, ПараметрыПолученияДанных, Ожидание, СтандартнаяОбработка", "", "", 2)
- "StartChoice" = @("НачалоВыбора", "НаКлиенте", @("8.3.20", "Элемент, ДанныеВыбора, СтандартнаяОбработка", "8.3.23", "Элемент, ДанныеВыбора, ВыборДобавлением, СтандартнаяОбработка"), "", "", 3)
- "MultipleValueURLProcessing" = @("ОбработкаНавигационнойСсылкиМножественногоЗначения", "НаКлиенте", "Элемент, Идентификатор, НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка", "8.3.23", "", 4)
- "MultipleValuesDelete" = @("УдалениеМножественныхЗначений", "НаКлиенте", "Элемент, Идентификаторы, СтандартнаяОбработка", "8.3.23", "", 5)
- "Tuning" = @("Регулирование", "НаКлиенте", "Элемент, Направление, СтандартнаяОбработка", "", "", 6)
- "MultipleValuesAdd" = @("ДобавлениеМножественныхЗначений", "НаКлиенте", "Элемент, Значения, СтандартнаяОбработка", "8.3.23", "", 7)
- "Opening" = @("Открытие", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 8)
- "Creating" = @("Создание", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 9)
- "StartListChoice" = @("НачалоВыбораИзСписка", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 10)
- "Clearing" = @("Очистка", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 11)
- "TextEditEnd" = @("ОкончаниеВводаТекста", "НаКлиенте", "Элемент, Текст, ДанныеВыбора, ПараметрыПолученияДанных, СтандартнаяОбработка", "", "", 12)
- "MultipleValueOpening" = @("ОткрытиеМножественногоЗначения", "НаКлиенте", "Элемент, Идентификатор, СтандартнаяОбработка", "8.3.23", "", 13)
- "ChoiceProcessing" = @("ОбработкаВыбора", "НаКлиенте", @("8.3.20", "Элемент, ВыбранноеЗначение, СтандартнаяОбработка", "8.3.23", "Элемент, ВыбранноеЗначение, ДополнительныеДанные, ВыборДобавлением, СтандартнаяОбработка"), "", "", 14)
- "CommandGenerateProcessing" = @("ОбработкаФормированияКоманд", "НаКлиенте", "Элемент, ПараметрыКоманд, Команды", "8.3.23", "", 15)
- }
- "LabelDecoration" = @{
- "Click" = @("Нажатие", "НаКлиенте", "Элемент", "", "", 0)
- "URLProcessing" = @("ОбработкаНавигационнойСсылки", "НаКлиенте", "Элемент, НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка", "", "", 1)
- }
- "LabelField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "URLProcessing" = @("ОбработкаНавигационнойСсылки", "НаКлиенте", "Элемент, НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка", "", "", 1)
- "Click" = @("Нажатие", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 2)
- }
- "PDFDocumentField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "8.3.23", "", 0)
- "URLClick" = @("НажатиеНаНавигационнойСсылке", "НаКлиенте", "Элемент, НавигационнаяСсылка, СтандартнаяОбработка", "8.3.23", "", 1)
- }
- "Pages" = @{
- "OnCurrentPageChange" = @("ПриСменеСтраницы", "НаКлиенте", "Элемент, ТекущаяСтраница", "", "", 0)
- }
- "PeriodField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "Selection" = @("Выбор", "НаКлиенте", "Элемент, ВыбраннаяДата", "", "", 1)
- }
- "PictureDecoration" = @{
- "DragCheck" = @("ПроверкаПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 0)
- "DragStart" = @("НачалоПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, Выполнение", "", "", 1)
- "Drag" = @("Перетаскивание", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 2)
- "Click" = @("Нажатие", "НаКлиенте", "Элемент", "", "", 3)
- "DragEnd" = @("ОкончаниеПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 4)
- }
- "PictureField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "DragCheck" = @("ПроверкаПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 1)
- "DragStart" = @("НачалоПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, Выполнение", "", "", 2)
- "Drag" = @("Перетаскивание", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 3)
- "Click" = @("Нажатие", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 4)
- "DragEnd" = @("ОкончаниеПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 5)
- }
- "PlannerField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "DragCheck" = @("ПроверкаПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, Дата, ЗначенияИзмерений", "", "", 1)
- "BeforeCollapseDimensionItem" = @("ПередСворачиваниемЭлементаИзмерения", "НаКлиенте", "Элемент, ЭлементИзмерения, ЗначенияИзмерений, Отказ", "", "", 2)
- "TimeScaleItemClick" = @("НажатиеНаЭлементеШкалыВремени", "НаКлиенте", "Элемент, ЭлементШкалыВремени, Дата", "", "", 3)
- "BeforeCreate" = @("ПередСозданием", "НаКлиенте", "Элемент, Начало, Конец, ЗначенияИзмерений, Текст, СтандартнаяОбработка", "", "", 4)
- "InsideDragCheck" = @("ПроверкаПеретаскиванияВнутри", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, ВариантИзмененияГраниц, ДействиеПеретаскивания, Отказ", "", "", 5)
- "BeforePrint" = @("ПередПечатью", "НаКлиенте", "Элемент, ДиалогПечати, Отказ", "", "", 6)
- "DimensionItemClick" = @("НажатиеНаЭлементеИзмерения", "НаКлиенте", "Элемент, ЭлементИзмерения, ЗначенияИзмерений, СтандартнаяОбработка", "", "", 7)
- "OnCurrentRepresentationPeriodChange" = @("ПриСменеТекущегоПериодаОтображения", "НаКлиенте", "Элемент, ТекущиеПериодыОтображения, СтандартнаяОбработка", "", "", 8)
- "OnEditEnd" = @("ПриОкончанииРедактирования", "НаКлиенте", "Элемент, НовыйЭлемент, ОтменаРедактирования", "", "", 9)
- "WrappedTimeScaleHeaderClick" = @("НажатиеНаПеренесенномЗаголовкеШкалыВремени", "НаКлиенте", "Элемент, Дата", "", "", 10)
- "DragStart" = @("НачалоПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, Выполнение", "", "", 11)
- "BeforeDelete" = @("ПередУдалением", "НаКлиенте", "Элемент, Отказ", "", "", 12)
- "BeforeExpandDimensionItem" = @("ПередРазворачиваниемЭлементаИзмерения", "НаКлиенте", "Элемент, ЭлементИзмерения, ЗначенияИзмерений, Отказ", "", "", 13)
- "BeforeStartEdit" = @("ПередНачаломРедактирования", "НаКлиенте", "Элемент, НовыйЭлемент, СтандартнаяОбработка", "", "", 14)
- "Drag" = @("Перетаскивание", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, Дата, ЗначенияИзмерений", "", "", 15)
- "CommandGenerateProcessing" = @("ОбработкаФормированияКоманд", "НаКлиенте", @("8.3.20", "Элемент, Параметры, Команды, КомандаПоУмолчанию", "8.3.23", "Элемент, ПараметрыКоманд, Команды, КомандаПоУмолчанию"), "", "", 16)
- "BeforeStartQuickEdit" = @("ПередНачаломБыстрогоРедактирования", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 17)
- "Selection" = @("Выбор", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 18)
- "OnActivate" = @("ПриАктивизации", "НаКлиенте", "Элемент", "", "", 19)
- "URLClick" = @("НажатиеНаНавигационнойСсылке", "НаКлиенте", "Элемент, Источник, НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка", "", "", 20)
- "DragEnd" = @("ОкончаниеПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 21)
- "PlannerActionClick" = @("НажатиеНаДействиеПланировщика", "НаКлиенте", "Элемент, ЭлементПланировщика, ДействиеЭлементаПланировщика", "", "", 22)
- }
- "ProgressBarField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- }
- "RadioButtonField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- }
- "SpreadSheetDocumentField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "URLProcessing" = @("ОбработкаНавигационнойСсылки", "НаКлиенте", "Элемент, НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка", "8.3.24", "", 1)
- "AdditionalDetailProcessing" = @("ОбработкаДополнительнойРасшифровки", "НаКлиенте", @("8.3.20", "Элемент, Расшифровка, СтандартнаяОбработка, ДополнительныеПараметры", "8.5", "Элемент, Расшифровка, СтандартнаяОбработка, ДополнительныеПараметры, ВсеРасшифровкиОбласти, ДляПанелиДействий"), "", "", 2)
- "DragCheck" = @("ПроверкаПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, Область", "", "", 3)
- "OnActivate" = @("ПриАктивизации", "НаКлиенте", "Элемент", "", "", 4)
- "Selection" = @("Выбор", "НаКлиенте", "Элемент, Область, СтандартнаяОбработка", "", "", 5)
- "DetailProcessing" = @("ОбработкаРасшифровки", "НаКлиенте", "Элемент, Расшифровка, СтандартнаяОбработка, ДополнительныеПараметры", "", "", 6)
- "OnChangeAreaContent" = @("ПриИзмененииСодержимогоОбласти", "НаКлиенте", "Элемент, Область, ДополнительныеПараметры", "", "", 7)
- "BeforePrint" = @("ПередПечатью", "НаКлиенте", "Элемент, ДиалогПечати, Отказ", "", "", 8)
- "DragStart" = @("НачалоПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, Выполнение", "", "", 9)
- "Drag" = @("Перетаскивание", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, Область", "", "", 10)
- "AfterWrite" = @("ПослеЗаписи", "НаКлиенте", "Элемент", "", "", 11)
- "BeforeWrite" = @("ПередЗаписью", "НаКлиенте", "Элемент, Копирование, Отказ", "", "", 12)
- "OnGenerateToolTipText" = @("ПриФормированииТекстаПодсказки", "НаКлиенте", "Элемент, Область, ТекстПодсказки, СтандартнаяОбработка", "8.5", "", 13)
- "DragEnd" = @("ОкончаниеПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 14)
- }
- "Table" = @{
- "OnEditEnd" = @("ПриОкончанииРедактирования", "НаКлиенте", "Элемент, НоваяСтрока, ОтменаРедактирования", "", "", 0)
- "DragCheck" = @("ПроверкаПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, Строка, Поле", "", "", 1)
- "ValueChoice" = @("ВыборЗначения", "НаКлиенте", "Элемент, Значение, СтандартнаяОбработка", "", "", 2)
- "Selection" = @("Выбор", "НаКлиенте", "Элемент, ВыбраннаяСтрока, Поле, СтандартнаяОбработка", "", "", 3)
- "OnSelectedRowsSetChange" = @("ПриИзмененииСоставаВыделенныхСтрок", "НаКлиенте", "Элемент", "8.5", "", 4)
- "BeforeAddRow" = @("ПередНачаломДобавления", "НаКлиенте", "Элемент, Отказ, Копирование, Родитель, ЭтоГруппа, Параметр", "", "", 5)
- "OnCurrentParentChange" = @("ПриСменеТекущегоРодителя", "НаКлиенте", "Элемент", "", "", 6)
- "BeforeDeleteRow" = @("ПередУдалением", "НаКлиенте", "Элемент, Отказ", "", "", 7)
- "OnLoadUserSettingsAtServer" = @("ПриЗагрузкеПользовательскихНастроекНаСервере", "НаСервере", "Элемент, Настройки, ИспользуютсяСтандартныеНастройки", "", "DynamicList", 8)
- "URLListGetProcessing" = @("ОбработкаПолученияСпискаНавигационныхСсылок", "НаКлиенте", "Элемент, СписокНавигационыхСсылок, КлючПоУмолчанию", "8.3.23", "DynamicList", 9)
- "BeforeEditEnd" = @("ПередОкончаниемРедактирования", "НаКлиенте", "Элемент, НоваяСтрока, ОтменаРедактирования, Отказ", "", "", 10)
- "OnActivateRow" = @("ПриАктивизацииСтроки", "НаКлиенте", "Элемент", "", "", 11)
- "URLGetProcessing" = @("ОбработкаПолученияНавигационнойСсылки", "НаКлиенте", "Элемент, Ключ, Представление, НавигационнаяСсылка, СтандартнаяОбработка", "8.3.23", "DynamicList", 12)
- "DragStart" = @("НачалоПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, Выполнение", "", "", 13)
- "OnActivateField" = @("ПриАктивизацииПоля", "НаКлиенте", "Элемент", "", "", 14)
- "BeforeExpand" = @("ПередРазворачиванием", "НаКлиенте", "Элемент, Строка, Отказ", "", "", 15)
- "Drag" = @("Перетаскивание", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, Строка, Поле", "", "", 16)
- "ChoiceProcessing" = @("ОбработкаВыбора", "НаКлиенте", "Элемент, ВыбранноеЗначение, СтандартнаяОбработка", "", "", 17)
- "OnGetDataAtServer" = @("ПриПолученииДанныхНаСервере", "НаСервереБезКонтекста", "ИмяЭлемента, Настройки, Строки", "", "DynamicList", 18)
- "OnSaveUserSettingsAtServer" = @("ПриСохраненииПользовательскихНастроекНаСервере", "НаСервере", "Элемент, Настройки", "", "DynamicList", 19)
- "BeforeCollapse" = @("ПередСворачиванием", "НаКлиенте", "Элемент, Строка, Отказ", "", "", 20)
- "BeforeRowChange" = @("ПередНачаломИзменения", "НаКлиенте", "Элемент, Отказ", "", "", 21)
- "OnStartEdit" = @("ПриНачалеРедактирования", "НаКлиенте", "Элемент, НоваяСтрока, Копирование", "", "", 22)
- "BeforeLoadUserSettingsAtServer" = @("ПередЗагрузкойПользовательскихНастроекНаСервере", "НаСервере", "Элемент, Настройки, ИспользуютсяСтандартныеНастройки", "", "DynamicList", 23)
- "OnHover" = @("ПриНаведении", "НаКлиенте", "Элемент, Строка, Поле", "8.5", "", 24)
- "DragEnd" = @("ОкончаниеПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 25)
- "NewWriteProcessing" = @("ОбработкаЗаписиНового", "НаКлиенте", "НовыйОбъект, Источник, СтандартнаяОбработка", "", "", 26)
- "AfterDeleteRow" = @("ПослеУдаления", "НаКлиенте", "Элемент", "", "", 27)
- "OnUpdateUserSettingSetAtServer" = @("ПриОбновленииСоставаПользовательскихНастроекНаСервере", "НаСервере", "СтандартнаяОбработка", "", "DynamicList", 28)
- "OnActivateCell" = @("ПриАктивизацииЯчейки", "НаКлиенте", "Элемент", "", "", 29)
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 30)
- "RefreshRequestProcessing" = @("ОбработкаЗапросаОбновления", "НаКлиенте", "", "", "", 31)
- }
- "TextDocumentField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- "BeforePrint" = @("ПередПечатью", "НаКлиенте", "Элемент, ДиалогПечати, Отказ", "", "", 1)
- "BeforeWrite" = @("ПередЗаписью", "НаКлиенте", "Элемент, Копирование, Отказ", "", "", 2)
- "AfterWrite" = @("ПослеЗаписи", "НаКлиенте", "Элемент", "", "", 3)
- }
- "TrackBarField" = @{
- "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
- }
- "UsualGroup" = @{
- "Click" = @("Нажатие", "НаКлиенте", "Элемент", "8.5", "", 0)
- }
- }
- }
- # Порядок событий формы у владельцев, у которых он отличается от позиций каталога
- function Get-FormEventOrder {
- return @{
- "Document" = @("AfterWrite", "BeforeReopenFromOtherServer", "ValueChoice", "OnReopenFromOtherServer", "OnSaveDataInSettingsAtServer", "ChoiceProcessing", "AfterWriteAtServer", "OnPasteFromClipboard", "NotificationProcessing", "OnReadAtServer", "NewWriteProcessing", "OnOpen", "URLListGetProcessing", "BeforeClose", "ExternalEvent", "CollaborationSystemUsersAutoComplete", "URLGetProcessing", "OnReopen", "OnLoadDataFromSettingsAtServer", "BeforeWrite", "BeforeWriteAtServer", "NavigationProcessing", "OnCreateAtServer", "CollaborationSystemUsersChoiceFormGetProcessing", "ActivationProcessing", "OnChangeDisplaySettings", "OnWriteAtServer", "OnClose", "OnMainServerAvailabilityChange", "URLProcessing", "FillCheckProcessingAtServer", "BeforeLoadDataFromSettingsAtServer", "AddInDetachmentOnError")
- }
- }
- # --- конец каталога событий формы ---
- $script:eventCatalog = Get-FormEventCatalog
- $script:formEventOrder = Get-FormEventOrder
- function Detect-FormatVersion([string]$dir) {
- $d = $dir
- while ($d) {
- # Автономная внешняя обработка/отчёт: своего Configuration.xml у неё нет, версию несёт
- # корень самой обработки. Без этого форма и макет внутри обработки 2.21 писались бы 2.17.
- $extPath = "$d.xml"
- if (Test-Path $extPath) {
- $extText = [System.IO.File]::ReadAllText($extPath, [System.Text.Encoding]::UTF8)
- $extHead = $extText.Substring(0, [Math]::Min(2000, $extText.Length))
- if ($extHead -match '<(ExternalDataProcessor|ExternalReport)[ >]' -and $extHead -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
- }
- $cfgPath = Join-Path $d "Configuration.xml"
- if (Test-Path $cfgPath) {
- $cfgText = [System.IO.File]::ReadAllText($cfgPath, [System.Text.Encoding]::UTF8)
- # Длину среза берём по СТРОКЕ, а не по размеру файла: размер в БАЙТАХ, Substring считает
- # СИМВОЛЫ, и на кириллице байт больше — короткий Configuration.xml ронял навык исключением.
- $head = $cfgText.Substring(0, [Math]::Min(2000, $cfgText.Length))
- if ($head -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
- }
- $parent = Split-Path $d -Parent
- if ($parent -eq $d) { break }
- $d = $parent
- }
- return "2.17"
- }
- # Версия формата формы: событие новой платформы в форме старого формата — предупреждение.
- # Нет атрибута version — как у form-compile: по конфигурации, иначе 2.17.
- $script:formatVersion = $root.GetAttribute('version')
- if (-not $script:formatVersion) { $script:formatVersion = Detect-FormatVersion ([System.IO.Path]::GetDirectoryName($resolvedFormPath)) }
- function Get-EventEntry([string]$xmlTag, [string]$eventName) {
- if (-not $xmlTag -or -not $script:eventCatalog.ContainsKey($xmlTag)) { return $null }
- $evs = $script:eventCatalog[$xmlTag]
- foreach ($k in $evs.Keys) { if ($k -ceq $eventName) { return ,$evs[$k] } }
- return $null
- }
- # Позиция события в <Events>: платформа пишет события в порядке каталога (у формы — в порядке владельца,
- # если он у владельца свой), внутри события — Before, затем After. Событие вне каталога — после известных.
- function Get-EventRank([string]$xmlTag, [string]$name, [string]$callType = '') {
- $ct = 0
- if ($callType -eq 'After') { $ct = 1 } elseif ($callType -eq 'Override') { $ct = 2 }
- $pos = [int]::MaxValue
- $own = $null
- if ($xmlTag -eq 'Form' -and $script:formOwner) { $own = $script:formEventOrder[$script:formOwner] }
- if ($null -ne $own) {
- $i = [Array]::IndexOf([string[]]$own, $name)
- if ($i -ge 0) { $pos = $i }
- } else {
- $e = Get-EventEntry $xmlTag $name
- if ($e) { $pos = [int]$e[5] }
- }
- return [long]$pos * 4 + $ct
- }
- # Расстояние Левенштейна — для подсказки к неизвестному событию.
- function Get-EditDistance([string]$a, [string]$b) {
- $prev = New-Object int[] ($b.Length + 1)
- for ($j = 0; $j -le $b.Length; $j++) { $prev[$j] = $j }
- for ($i = 1; $i -le $a.Length; $i++) {
- $cur = New-Object int[] ($b.Length + 1)
- $cur[0] = $i
- for ($j = 1; $j -le $b.Length; $j++) {
- $cost = if ($a[$i - 1] -ceq $b[$j - 1]) { 0 } else { 1 }
- $cur[$j] = [Math]::Min([Math]::Min($prev[$j] + 1, $cur[$j - 1] + 1), $prev[$j - 1] + $cost)
- }
- $prev = $cur
- }
- return $prev[$b.Length]
- }
- # Подсказка к неизвестному событию: ближайшие по написанию события вида элемента и виды, у которых такое событие есть.
- function Get-EventHint([string]$xmlTag, [string]$name) {
- $parts = @()
- $evs = $script:eventCatalog[$xmlTag]
- if ($evs) {
- $lim = [Math]::Max(2, [int][Math]::Floor($name.Length / 3))
- $near = [string[]]@(foreach ($k in $evs.Keys) {
- $d = Get-EditDistance $name.ToLowerInvariant() "$k".ToLowerInvariant()
- if ($d -le $lim) { '{0:D3}|{1}' -f $d, $k }
- })
- [Array]::Sort($near, [StringComparer]::Ordinal)
- if ($near.Count) { $parts += 'Did you mean: ' + ((@($near | Select-Object -First 3) | ForEach-Object { $_.Split('|')[1] }) -join ', ') + '?' }
- }
- $tags = [string[]]@(foreach ($t in $script:eventCatalog.Keys) { if ("$t" -ne $xmlTag -and $null -ne (Get-EventEntry "$t" $name)) { "$t" } })
- [Array]::Sort($tags, [StringComparer]::Ordinal)
- if ($tags.Count) { $parts += "'$name' is an event of: $($tags -join ', ')." }
- return ($parts -join ' ')
- }
- function Test-EventPairs {
- param($pairs, [string]$xmlTag, [string]$elementName, [string]$source = '')
- $what = if ($xmlTag -eq 'Form') { 'the form' } else { "$xmlTag '$elementName'" }
- $evs = $script:eventCatalog[$xmlTag]
- foreach ($pr in $pairs) {
- $ev = "$($pr.name)"
- $entry = if ($evs) { Get-EventEntry $xmlTag $ev } else { $null }
- if (-not $entry) {
- # сводкой перед записью формы (Report-UnknownEvents): модель исправит все сразу
- [void]$script:unknownEvents.Add([pscustomobject]@{ tag = $xmlTag; name = $elementName; ev = $ev; noEvents = (-not $evs) })
- continue
- }
- $since = "$($entry[3])"
- if ($since -and (Get-FormatRank $script:formatVersion) -lt $script:platformFormatRank[$since]) {
- Write-Host "[WARN] Event '$ev' of $what exists since platform $since — earlier platforms drop it on load"
- }
- $only = "$($entry[4])"
- if ($only -and $xmlTag -eq 'Form') {
- if ($script:formOwner -and @($only -split ',\s*') -notcontains $script:formOwner) {
- Write-Host "[WARN] Event '$ev' of $what exists only for forms of $only (this form: $($script:formOwner)) — the platform drops it on load"
- }
- } elseif ($only -and $source -and $source -ne $only) {
- Write-Host "[WARN] Event '$ev' of $what exists only for a table bound to $only (bound to $source) — the platform drops it on load"
- }
- }
- }
- # Сводка неизвестных событий за запуск — одним блоком перед записью формы. Формы ветки 8.3 — ошибка (форма не
- # пишется), 8.5 — предупреждение. Перечень событий вида — только если подсказать нечего, один раз на вид.
- function Report-UnknownEvents {
- if ($script:unknownEvents.Count -eq 0) { return }
- # одно событие у нескольких элементов вида — одной строкой (одна и та же опечатка — одно исправление)
- $groups = [ordered]@{}
- foreach ($u in $script:unknownEvents) {
- $key = "$($u.tag)|$($u.ev)"
- if (-not $groups.Contains($key)) { $groups[$key] = [pscustomobject]@{ u = $u; names = New-Object System.Collections.ArrayList } }
- if ($u.name -and -not $groups[$key].names.Contains($u.name)) { [void]$groups[$key].names.Add($u.name) }
- }
- $lines = New-Object System.Collections.ArrayList
- $knownTags = New-Object System.Collections.ArrayList
- foreach ($g in $groups.Values) {
- $u = $g.u
- $where = if ($u.tag -eq 'Form') { 'the form' } else { "$($u.tag) " + ((@($g.names) | ForEach-Object { "'$_'" }) -join ', ') }
- $hint = Get-EventHint $u.tag $u.ev
- $line = " '$($u.ev)' for $where"
- if ($u.noEvents) { $line += " — $($u.tag) has no events." + $(if ($hint) { " $hint" } else { '' }) }
- elseif ($hint) { $line += " — $hint" }
- elseif (-not $knownTags.Contains($u.tag)) { [void]$knownTags.Add($u.tag) }
- [void]$lines.Add($line)
- }
- foreach ($t in $knownTags) {
- $known = [string[]]@($script:eventCatalog[$t].Keys); [Array]::Sort($known, [StringComparer]::Ordinal)
- [void]$lines.Add(" Events of ${t}: $($known -join ', ')")
- }
- if ((Get-FormatRank $script:formatVersion) -le $script:eventCatalogClosedRank) {
- [Console]::Error.WriteLine("[ERROR] Unknown events — the platform drops them on load; the form is not written:`n" + ($lines -join "`n"))
- exit 1
- }
- Write-Host ("[WARN] Unknown events — the platform drops them on load (8.5 builds may add events):`n" + ($lines -join "`n"))
- }
- # Владелец формы по типу основного реквизита — как в ограничениях каталога событий ("" — не определить
- # или вид не замерен: события формы по владельцу тогда не сверяются).
- function Get-FormOwnerKind([string]$type) {
- $t = $type -replace '^\w+:(?=\w)', ''
- if ($t -eq 'SettingsComposer') { return 'SettingsComposer' }
- switch (($t -split '\.')[0]) {
- 'DataProcessorObject' { return 'DataProcessor' }
- 'ExternalDataProcessorObject' { return 'DataProcessor' }
- 'ReportObject' { return 'Report' }
- 'ExternalReportObject' { return 'Report' }
- 'DocumentObject' { return 'Document' }
- 'CatalogObject' { return 'Catalog' }
- 'ChartOfCharacteristicTypesObject' { return 'ChartOfCharacteristicTypes' }
- 'ExchangePlanObject' { return 'ExchangePlan' }
- 'ChartOfAccountsObject' { return 'ChartOfAccounts' }
- 'ChartOfCalculationTypesObject' { return 'ChartOfCalculationTypes' }
- 'BusinessProcessObject' { return 'BusinessProcess' }
- 'TaskObject' { return 'Task' }
- 'InformationRegisterRecordManager' { return 'InformationRegisterRecord' }
- 'InformationRegisterRecordSet' { return 'InformationRegisterRecordSet' }
- 'ConstantsSet' { return 'Constants' }
- 'DynamicList' { return 'List' }
- }
- return ''
- }
- # Владелец формы — по основному реквизиту в Form.xml. Считается перед сверкой событий формы:
- # реквизиты правятся раньше событий, и основной реквизит мог появиться или смениться в этом же вызове.
- $script:formOwner = ''
- function Update-FormOwner {
- $script:formOwner = ''
- foreach ($a in $root.SelectNodes("f:Attributes/f:Attribute", $nsMgr)) {
- $ma = $a.SelectSingleNode("f:MainAttribute", $nsMgr)
- if ($null -ne $ma -and $ma.InnerText.Trim() -eq 'true') {
- $tn = $a.SelectSingleNode("f:Type/v8:Type", $nsMgr)
- if ($null -ne $tn) { $script:formOwner = Get-FormOwnerKind $tn.InnerText }
- break
- }
- }
- }
- function Warn-EventsIgnored($el, [string]$xmlTag, [string]$elementName) {
- $names = @()
- $list = @($el.on)
- if ($el.events -is [array]) { $list = @($el.events) + $list }
- elseif ($el.events -is [System.Management.Automation.PSCustomObject]) { $names += @($el.events.PSObject.Properties | ForEach-Object { $_.Name }) }
- elseif ($el.events) { $names += "$($el.events)" }
- foreach ($evt in $list) { if ($null -ne $evt) { $names += if ($evt -is [System.Management.Automation.PSCustomObject]) { "$($evt.event)" } else { "$evt" } } }
- if ($names.Count -gt 0) {
- Write-Host "[WARN] $xmlTag '$elementName' has no events — ignored: $($names -join ', ')"
- }
- }
- function Get-FormatRank([string]$ver) {
- if ($ver -match '^(\d+)\.(\d+)$') { return [int]$Matches[1] * 100 + [int]$Matches[2] }
- return 0
- }
- # Первая версия формата выгрузки платформы, на которой появилось событие каталога.
- $script:platformFormatRank = @{ "8.3.20" = 213; "8.3.23" = 216; "8.3.24" = 217; "8.3.25" = 218; "8.3.26" = 219; "8.3.27" = 220; "8.5" = 221 }
- # Каталог событий полон по формат 2.20 включительно (ветка 8.3 закрыта): неизвестное событие — ошибка; выше — предупреждение
- $script:eventCatalogClosedRank = 220
- $script:unknownEvents = New-Object System.Collections.ArrayList
- # --- Заготовки обработчиков в модуле формы ---
- # Привязки, которые затронул запуск, собираются в $script:handlerBindings; после записи Form.xml
- # Update-FormModule дописывает в модуль процедуры, которых там ещё нет, — в области по стандарту БСП.
- $script:handlerBindings = New-Object System.Collections.ArrayList
- $script:handlerTable = '' # таблица, колонки которой сейчас эмитятся
- # kind: form | element | command; table — таблица, внутри которой элемент (область «…ТаблицыФормы<Имя>»).
- # Одно имя на несколько событий — одна процедура: сигнатуру даёт первая привязка.
- function Register-Handler([string]$handler, [string]$kind, [string]$xmlTag = '', [string]$eventName = '', [string]$table = '') {
- if (-not $handler) { return }
- foreach ($b in $script:handlerBindings) { if ($b.handler -eq $handler) { return } }
- [void]$script:handlerBindings.Add([pscustomobject]@{ handler = $handler; kind = $kind; xmlTag = $xmlTag; eventName = $eventName; table = $table })
- }
- # Пустой модуль формы. Табличных областей нет: имя таблицы при создании формы неизвестно.
- function Get-FormModuleTemplate {
- $out = @()
- foreach ($r in @('ОбработчикиСобытийФормы', 'ОбработчикиСобытийЭлементовШапкиФормы', 'ОбработчикиКомандФормы', 'ОбработчикиОповещений', 'СлужебныеПроцедурыИФункции')) {
- if ($out.Count -gt 0) { $out += '' }
- $out += @("#Область $r", '', '#КонецОбласти')
- }
- return $out
- }
- # Процедуры и функции модуля (имя, первая и последняя строка; первая — с аннотациями над заголовком)
- # и области (имя, строки #Область и #КонецОбласти, вложенность). Строки нумеруются с 1.
- # Заголовок — только в начале строки: продолжение литерала («|…») и комментарий заголовком не станут.
- function Get-ModuleOutline([string[]]$lines) {
- $procs = New-Object System.Collections.ArrayList
- $regions = New-Object System.Collections.ArrayList
- $open = New-Object System.Collections.ArrayList
- $cur = $null
- for ($i = 0; $i -lt $lines.Count; $i++) {
- $l = $lines[$i]
- if ($null -ne $cur) {
- # конец процедуры — в начале строки или после «;» (`Возврат Х;КонецФункции`)
- if ($l -match '(^|;)\s*(КонецПроцедуры|КонецФункции|EndProcedure|EndFunction)(?![\w])') { $cur.end = $i + 1; [void]$procs.Add($cur); $cur = $null }
- continue
- }
- $m = [regex]::Match($l, '^\s*(?:(?:Асинх|Async)\s+)?(?:Процедура|Функция|Procedure|Function)\s+(\w+)\s*\(', 'IgnoreCase')
- if ($m.Success) {
- $s = $i
- while ($s -gt 0 -and $lines[$s - 1] -match '^\s*&') { $s-- }
- $cur = [pscustomobject]@{ name = $m.Groups[1].Value; start = $s + 1; end = $i + 1 }
- continue
- }
- $m = [regex]::Match($l, '^\s*#(?:Область|Region)\s+(\S+)', 'IgnoreCase')
- if ($m.Success) { [void]$open.Add([pscustomobject]@{ name = $m.Groups[1].Value; start = $i + 1; end = 0; depth = $open.Count }); continue }
- if ($l -match '^\s*#(КонецОбласти|EndRegion)(?![\w])' -and $open.Count -gt 0) {
- $r = $open[$open.Count - 1]; $open.RemoveAt($open.Count - 1)
- $r.end = $i + 1; [void]$regions.Add($r)
- }
- }
- return @{ procs = $procs; regions = $regions }
- }
- # Разметка модуля по коду без литералов и комментариев: «;КонецПроцедуры» в строке не закроет процедуру.
- function Get-ModuleCodeOutline([string[]]$lines) {
- return Get-ModuleOutline (Get-BslScan ($lines -join "`n")).Code
- }
- # Параметры обработчика события по версии формата формы: строка — одна сигнатура для всех платформ;
- # массив @("8.3.20", "А, Б", "8.3.23", "А, Б, В") — сигнатура с указанной платформы (по возрастанию).
- # Формат формы не определён — новейшая сигнатура.
- function Get-EventParams($entry) {
- $p = $entry[2]
- if (-not ($p -is [array])) { return "$p" }
- $rank = Get-FormatRank $script:formatVersion
- $res = "$($p[1])"
- for ($i = 0; $i -lt $p.Count; $i += 2) {
- $since = $script:platformFormatRank["$($p[$i])"]
- if ($null -eq $since) { continue }
- if ($rank -eq 0 -or $rank -ge $since) { $res = "$($p[$i + 1])" }
- }
- return $res
- }
- # Текст заготовки: директива и параметры — из каталога событий, у команды — (Команда) на клиенте.
- # $null — событие вне каталога, сигнатура неизвестна.
- function Get-HandlerStub($b) {
- if ($b.kind -eq 'command') { $dir = 'НаКлиенте'; $params = 'Команда' }
- else {
- $entry = Get-EventEntry $b.xmlTag $b.eventName
- if (-not $entry) { return $null }
- $dir = "$($entry[1])"; $params = Get-EventParams $entry
- }
- return @("&$dir", "Процедура $($b.handler)($params)", "`t// Вставить содержимое обработчика.", 'КонецПроцедуры')
- }
- # Порядок областей модуля формы по стандарту (типовые): куда встаёт новая область.
- function Get-RegionRank([string]$name) {
- $n = $name.ToLower()
- if ($n -eq 'описаниепеременных') { return 0 }
- if ($n -eq 'обработчикисобытийформы') { return 1 }
- if ($n -eq 'обработчикисобытийэлементовшапкиформы' -or $n -eq 'обработчикисобытийэлементовформы') { return 2 }
- if ($n.StartsWith('обработчикисобытийэлементовтаблицыформы')) { return 3 }
- if ($n -eq 'обработчикикомандформы') { return 4 }
- if ($n -eq 'обработчикиоповещений') { return 5 }
- if ($n -eq 'служебныепроцедурыифункции') { return 6 }
- return -1
- }
- # Область для привязки. Общая область элементов (без «шапки») — для всех элементов, и табличных тоже:
- # модуль уже так устроен.
- function Get-HandlerRegionName($b, $regions) {
- if ($b.kind -eq 'form') { return 'ОбработчикиСобытийФормы' }
- if ($b.kind -eq 'command') { return 'ОбработчикиКомандФормы' }
- $has = @{}
- foreach ($r in $regions) { $has[$r.name.ToLower()] = $true }
- # своя область таблицы, если она уже есть, — важнее общей
- if ($b.table -and $has["обработчикисобытийэлементовтаблицыформы$($b.table)".ToLower()]) { return "ОбработчикиСобытийЭлементовТаблицыФормы$($b.table)" }
- if ($has['обработчикисобытийэлементовформы'] -and -not $has['обработчикисобытийэлементовшапкиформы']) { return 'ОбработчикиСобытийЭлементовФормы' }
- if ($b.table) { return "ОбработчикиСобытийЭлементовТаблицыФормы$($b.table)" }
- return 'ОбработчикиСобытийЭлементовШапкиФормы'
- }
- # Вставить заготовку в модуль (список строк): в конец своей области, нет области — создать её на месте
- # по порядку областей, нет областей вообще — в конец модуля. Отделяется одной пустой строкой.
- function Add-StubToModule([System.Collections.ArrayList]$lines, [string[]]$stub, $b) {
- $outline = Get-ModuleCodeOutline $lines.ToArray()
- if ($outline.regions.Count -eq 0) {
- while ($lines.Count -gt 0 -and -not $lines[$lines.Count - 1].Trim()) { $lines.RemoveAt($lines.Count - 1) }
- if ($lines.Count -gt 0) { [void]$lines.Add('') }
- $lines.AddRange($stub)
- return
- }
- $name = Get-HandlerRegionName $b $outline.regions
- $target = $null
- foreach ($r in $outline.regions) { if ($r.name -eq $name -and ($null -eq $target -or $r.start -lt $target.start)) { $target = $r } }
- if ($null -ne $target) {
- # перед #КонецОбласти, сняв пустые строки над ним
- $k = $target.end - 1
- while ($k - 1 -gt $target.start - 1 -and -not $lines[$k - 1].Trim()) { $k--; $lines.RemoveAt($k) }
- $lines.InsertRange($k, [string[]](@('') + $stub + @('')))
- return
- }
- $block = [string[]](@("#Область $name", '') + $stub + @('', '#КонецОбласти'))
- $rank = Get-RegionRank $name
- $top = @($outline.regions | Where-Object { $_.depth -eq 0 } | Sort-Object start)
- $after = $null; $before = $null
- foreach ($r in $top) {
- $rr = Get-RegionRank $r.name
- if ($rr -lt 0) { continue }
- if ($rr -le $rank) { $after = $r } elseif ($null -eq $before) { $before = $r }
- }
- if ($null -ne $after) { $lines.InsertRange($after.end, [string[]](@('') + $block)); return }
- if ($null -ne $before) { $lines.InsertRange($before.start - 1, [string[]]($block + @(''))); return }
- while ($lines.Count -gt 0 -and -not $lines[$lines.Count - 1].Trim()) { $lines.RemoveAt($lines.Count - 1) }
- $lines.InsertRange($lines.Count, [string[]](@('') + $block))
- }
- # Дописать в модуль формы процедуры для привязок, которых в нём нет. Модуль — <каталог Form.xml>/Form/Module.bsl;
- # нет модуля — создаётся из шаблона, но только в раскладке выгрузки (Form.xml в каталоге Ext).
- # Кодировка и переводы строк существующего модуля сохраняются; новый — UTF-8 с BOM, CRLF, как у form-add.
- # Возвращает строки отчёта: что добавлено, что уже было, с диапазонами строк по итоговому тексту.
- function Update-FormModule([string]$formXmlPath, [string]$shownFormPath) {
- if ($script:handlerBindings.Count -eq 0) { return @() }
- $xmlDir = [System.IO.Path]::GetDirectoryName($formXmlPath)
- $path = [System.IO.Path]::Combine($xmlDir, 'Form', 'Module.bsl')
- # путь для вывода — в том же виде, что путь к Form.xml в выводе навыка
- $sep = if ($shownFormPath.Contains('\') -and -not $shownFormPath.Contains('/')) { '\' } else { '/' }
- $shown = ($shownFormPath -replace '[^\\/]+$', '') + "Form${sep}Module.bsl"
- $created = $false
- if (Test-Path -LiteralPath $path) {
- $bytes = [System.IO.File]::ReadAllBytes($path)
- $bom = ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF)
- # строго: модуль не в UTF-8 перезапись испортила бы — такой не трогаем
- try { $text = (New-Object System.Text.UTF8Encoding($false, $true)).GetString($bytes) }
- catch { return @("[WARN] Form module is not UTF-8: $shown — handler stubs not created") }
- if ($bom) { $text = $text.Substring(1) }
- $eol = if ($text.Contains("`r`n") -or -not $text.Contains("`n")) { "`r`n" } else { "`n" }
- $norm = $text -replace "`r`n", "`n"
- # сколько переводов строк в конце — столько и запишем: модуль не должен меняться вне вставок
- $tail = $norm.Length - $norm.TrimEnd("`n").Length
- $src = @($norm.TrimEnd("`n") -split "`n")
- if (-not $text.Trim()) { $src = Get-FormModuleTemplate }
- } elseif ([System.IO.Path]::GetFileName($xmlDir) -eq 'Ext') {
- $created = $true; $bom = $true; $eol = "`r`n"; $tail = 0
- $src = Get-FormModuleTemplate
- } else {
- return @("[WARN] Form module not found: $shown — handler stubs not created")
- }
- $lines = New-Object System.Collections.ArrayList
- $lines.AddRange([string[]]$src)
- $status = @{}
- $changed = $false
- foreach ($b in $script:handlerBindings) {
- $outline = Get-ModuleCodeOutline $lines.ToArray()
- if (@($outline.procs | Where-Object { $_.name -eq $b.handler }).Count -gt 0) { $status[$b.handler] = 'exists'; continue }
- $stub = Get-HandlerStub $b
- if ($null -eq $stub) { $status[$b.handler] = "not added: no signature known for event '$($b.eventName)' of $($b.xmlTag)"; continue }
- Add-StubToModule $lines $stub $b
- $status[$b.handler] = 'added'
- $changed = $true
- }
- if ($changed -or $created) {
- $dir = [System.IO.Path]::GetDirectoryName($path)
- if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
- $out = ($lines.ToArray() -join $eol) + ($eol * $tail)
- [System.IO.File]::WriteAllText($path, $out, (New-Object System.Text.UTF8Encoding($bom)))
- }
- $outline = Get-ModuleCodeOutline $lines.ToArray()
- # в порядке строк модуля; не добавленные — в конце
- $rows = @()
- foreach ($b in $script:handlerBindings) {
- $st = $status[$b.handler]
- $p = @($outline.procs | Where-Object { $_.name -eq $b.handler })[0]
- if ($st -eq 'added') { $rows += [pscustomobject]@{ line = $p.start; n = $rows.Count; text = " + $($b.handler) — empty stub added, lines $($p.start)-$($p.end)" } }
- elseif ($st -eq 'exists') { $rows += [pscustomobject]@{ line = $p.start; n = $rows.Count; text = " = $($b.handler) — exists, lines $($p.start)-$($p.end)" } }
- else { $rows += [pscustomobject]@{ line = [int]::MaxValue; n = $rows.Count; text = " ? $($b.handler) — $st" } }
- }
- $report = @(if ($created) { "Handlers ($shown, module created):" } else { "Handlers ($shown):" })
- foreach ($r in @($rows | Sort-Object line, n)) { $report += $r.text }
- return $report
- }
- # Тип реквизита формы, к которому привязана таблица ("" — не определить: пути нет или реквизита нет в форме).
- function Get-TableSource($el) {
- if ($el.PSObject.Properties["_dynList"] -and $el._dynList) { return 'DynamicList' }
- return Get-DataPathSource "$($el.path)"
- }
- function Get-DataPathSource([string]$path) {
- $rootName = ($path -split '\.')[0]
- if (-not $rootName) { return '' }
- foreach ($a in $root.SelectNodes("f:Attributes/f:Attribute", $nsMgr)) {
- if ($a.GetAttribute('name') -eq $rootName) {
- $t = $a.SelectSingleNode("f:Type/v8:Type", $nsMgr)
- if ($null -ne $t) { return ($t.InnerText -replace '^[^:]*:', '') }
- return ''
- }
- }
- return ''
- }
- $script:companionStructKeys = @(
- 'width','autoMaxWidth','maxWidth','height','autoMaxHeight','maxHeight','verticalAlign','titleHeight',
- 'horizontalStretch','verticalStretch','horizontalAlign','groupHorizontalAlign','groupVerticalAlign',
- 'visible','hidden','enabled','disabled','hyperlink','events','tooltip',
- 'textColor','backColor','borderColor','font','border','цветтекста','цветфона','цветрамки','шрифт','рамка'
- )
- $script:additionTypeMap = [ordered]@{
- 'searchString' = @{ Tag = 'SearchStringAddition'; Type = 'SearchStringRepresentation'; Suffix = 'СтрокаПоиска' }
- 'viewStatus' = @{ Tag = 'ViewStatusAddition'; Type = 'ViewStatusRepresentation'; Suffix = 'СостояниеПросмотра' }
- 'searchControl' = @{ Tag = 'SearchControlAddition'; Type = 'SearchControl'; Suffix = 'УправлениеПоиском' }
- }
- $script:additionKeySynonyms = @{
- 'searchString' = @('SearchStringAddition','SearchStringRepresentation','строкаПоиска','отображениеСтрокиПоиска')
- 'viewStatus' = @('ViewStatusAddition','ViewStatusRepresentation','состояниеПросмотра')
- 'searchControl' = @('SearchControlAddition','SearchControl','управлениеПоиском')
- }
- $script:elementTypeStrOnlyKeys = @('commandBar','autoCommandBar','КоманднаяПанель')
- $script:elementTypeSynonyms = @{
- "commandBar" = "cmdBar"
- "autoCommandBar" = "autoCmdBar"
- "КоманднаяПанель" = "cmdBar"
- "InputField" = "input"
- "ПолеВвода" = "input"
- "CheckBoxField" = "check"
- "ПолеФлажка" = "check"
- "RadioButtonField" = "radio"
- "ПолеПереключателя" = "radio"
- "radioButton" = "radio"
- "PictureField" = "picField"
- "ПолеКартинки" = "picField"
- "LabelField" = "labelField"
- "ПолеНадписи" = "labelField"
- "CalendarField" = "calendar"
- "ПолеКалендаря" = "calendar"
- "LabelDecoration" = "label"
- "Надпись" = "label"
- "PictureDecoration" = "picture"
- "Картинка" = "picture"
- "UsualGroup" = "group"
- "Группа" = "group"
- "ОбычнаяГруппа" = "group"
- "ColumnGroup" = "columnGroup"
- "ГруппаКолонок" = "columnGroup"
- "Pages" = "pages"
- "ГруппаСтраниц" = "pages"
- "Page" = "page"
- "Страница" = "page"
- "Table" = "table"
- "Таблица" = "table"
- "Button" = "button"
- "Кнопка" = "button"
- "Popup" = "popup"
- "ВсплывающееМеню" = "popup"
- # Дополнения командной панели таблицы (тип-как-ключ) — forgiving: XML-тег/Type/рус.имя → канон
- "SearchStringAddition" = "searchString"
- "SearchStringRepresentation" = "searchString"
- "строкаПоиска" = "searchString"
- "отображениеСтрокиПоиска" = "searchString"
- "Отображение строки поиска" = "searchString"
- "ViewStatusAddition" = "viewStatus"
- "ViewStatusRepresentation" = "viewStatus"
- "состояниеПросмотра" = "viewStatus"
- "Состояние просмотра" = "viewStatus"
- "SearchControlAddition" = "searchControl"
- "SearchControl" = "searchControl"
- "управлениеПоиском" = "searchControl"
- "Управление поиском" = "searchControl"
- # Спец-поля (документ/датчик) — XML-имя/рус. → канон
- "SpreadSheetDocumentField" = "spreadsheet"
- "ПолеТабличногоДокумента" = "spreadsheet"
- "HTMLDocumentField" = "html"
- "ПолеHTMLДокумента" = "html"
- "TextDocumentField" = "textDoc"
- "ПолеТекстовогоДокумента" = "textDoc"
- "FormattedDocumentField" = "formattedDoc"
- "ПолеФорматированногоДокумента" = "formattedDoc"
- "ProgressBarField" = "progressBar"
- "ПолеИндикатора" = "progressBar"
- "TrackBarField" = "trackBar"
- "ПолеПолосыРегулирования" = "trackBar"
- "ChartField" = "chart"
- "ПолеДиаграммы" = "chart"
- "GanttChartField" = "ganttChart"
- "ПолеДиаграммыГанта" = "ganttChart"
- "GraphicalSchemaField" = "graphicalSchema"
- "ПолеГрафическойСхемы" = "graphicalSchema"
- "PlannerField" = "planner"
- "ПолеПланировщика" = "planner"
- "PeriodField" = "periodField"
- "ПолеПериода" = "periodField"
- "DendrogramField" = "dendrogram"
- "ПолеДендрограммы" = "dendrogram"
- }
- $script:validEnumValues = @{
- "ActionPurpose" = @("Usual","Create","Finish")
- "AppearanceInCard" = @("Auto","Extended")
- "AppearanceMode" = @("Auto","CommandBar","UsualGroup")
- "AutoAddIncomplete" = @("true","false","auto")
- "AutoCapitalizationOnTextInput" = @("Auto","None","Words","Sentences","AllCharacters")
- "AutoChoiceIncomplete" = @("true","false","auto")
- "AutoCorrectionOnTextInput" = @("Auto","Use","DontUse")
- "AutoMarkIncomplete" = @("true","false","auto")
- "AutoSaveDataInSettings" = @("DontUse","Use")
- "AutoShowClearButtonMode" = @("Auto","Always","FilledOnly")
- "AutoShowOpenButtonMode" = @("Auto","Always","FilledOnly")
- "AutoShowState" = @("Auto","DontShow","Show","ShowOnComposition")
- "AutoTime" = @("DontUse","Last","First","CurrentOrLast","CurrentOrFirst")
- "AutoWidthInTable" = @("Auto","ByData","None","ByDataAndTitle")
- "AutofillHint" = @("DontUse","FullName","GivenName","FamilyName","MiddleName","NamePrefix","NameSuffix","Street","City","Region","Country","PostalCode","UserName","Password","NewPassword","OneTimeCode","Email","PhoneNumber","CreditCardNumber")
- "BackPictureEffect" = @("Auto","None","Semitransparency","SemitransparencyAndBlur")
- "BackgroundShowMode" = @("Auto","DontShow","ShowAndIncreaseSize","ShowAndDontIncreaseSize")
- "Behavior" = @("Usual","Collapsible","PopUp","Auto")
- "BehaviorOnHorizontalCompression" = @("Auto","HideItemsByImportance","MoveItemsByImportance")
- "ButtonImportance" = @("Main","Normal","Supplementary")
- "CardBehaviorOnVerticalCompression" = @("Auto","MoveItemsToSwipeablePages","HideItems")
- "CardPictureAndTitleAlign" = @("Auto","LeftHorizontallySidesVertically","CenterHorizontallySidesVertically","CenterHorizontallyCenterVertically")
- "CardRepresentationType" = @("Usual","Group")
- "CellActionsButtonViewMode" = @("Auto","DontShow","ShowOnHover")
- "CellHyperlinkDisplayVariant" = @("Auto","Always","OnRowHover")
- "CellHyperlinkRepresentation" = @("Auto","Show","DontShow")
- "CellHyperlinksRepresentation" = @("Auto","AutoForSingle","ForAll","DontShow")
- "CellMark" = @("None","ShapeUnderTextOval","IconCircle")
- "CheckBoxType" = @("Auto","CheckBox","Tumbler","Switcher")
- "ChildItemsTitleLocation" = @("Auto","Left","LeftIfPossible","Top")
- "ChildItemsWidth" = @("Auto","Equal","LeftWide","LeftWidest","LeftNarrow","LeftNarrowest")
- "ChildrenAlign" = @("Auto","None","ItemsLeftTitlesLeft","ItemsRightTitlesLeft","ItemsLeftTitlesRight","ItemsRightTitlesRight","TitlesLeftDataLeft","TitlesLeftDataRight","TitlesRightDataLeft","TitlesRightDataRight","TitlesLeftDataAuto")
- "ChoiceButton" = @("true","false","auto")
- "ChoiceButtonRepresentation" = @("Auto","ShowInDropList","ShowInDropListAndInInputField","ShowInInputField")
- "InputField.ChoiceFoldersAndItems" = @("Items","Folders","FoldersAndItems","Auto")
- "Table.ChoiceFoldersAndItems" = @("Items","Folders","FoldersAndItems")
- "ChoiceHistoryOnInput" = @("Auto","DontUse")
- "ChoiceListButton" = @("true","false","auto")
- "ClearButton" = @("true","false","auto")
- "CollapseItemsByImportanceVariant" = @("Auto","Use","DontUse")
- "CommandBarLocation" = @("None","Auto","Top","Bottom")
- "ComplexSettingsViewMode" = @("Show","DontShow")
- "ControlRepresentation" = @("TitleHyperlink","Picture","Button","ButtonInParentElement")
- "ConversationsRepresentation" = @("Auto","Show","DontShow")
- "CreateButton" = @("true","false","auto")
- "Command.CurrentRowUse" = @("Use","DontUse","Auto")
- "Pages.CurrentRowUse" = @("Use","DontUse","Auto")
- "Table.CurrentRowUse" = @("Auto","Choice","SelectionPresentation","SelectionPresentationAndChoice")
- "UsualGroup.CurrentRowUse" = @("Use","DontUse","Auto")
- "DisplayImportance" = @("Auto","VeryHigh","High","Usual","Low","VeryLow")
- "DrawingSelectionShowMode" = @("Show","DontShow","Auto")
- "DropListButton" = @("true","false","auto")
- "EditMode" = @("Directly","Enter","EnterOnInput","Auto")
- "EditTextUpdate" = @("Auto","DontUse","OnValueChange","Always")
- "EnterKeyBehavior" = @("ControlNavigation","DefaultButton")
- "EqualColumnsWidth" = @("true","false","auto")
- "EqualItemsWidth" = @("true","false","auto")
- "ExtendedEdit" = @("true","false","auto")
- "FileDragMode" = @("AsFile","AsFileRef")
- "FillCheck" = @("DontCheck","ShowError")
- "FixInCard" = @("true","false","auto")
- "FixingInTable" = @("None","Left","Right")
- "FooterHorizontalAlign" = @("Left","Center","Right","Auto")
- "ColumnGroup.Group" = @("Horizontal","Vertical","InCell")
- "Form.Group" = @("Horizontal","Vertical","HorizontalIfPossible","AlwaysHorizontal","Auto","AutoScreenTypeSensitive")
- "Page.Group" = @("Horizontal","Vertical","HorizontalIfPossible","AlwaysHorizontal","Auto","AutoScreenTypeSensitive")
- "UsualGroup.Group" = @("Horizontal","Vertical","HorizontalIfPossible","AlwaysHorizontal","Auto","AutoScreenTypeSensitive")
- "GroupHorizontalAlign" = @("Left","Center","Right","Auto")
- "GroupVerticalAlign" = @("Top","Center","Bottom","Auto")
- "HeaderHorizontalAlign" = @("Left","Center","Right","Auto")
- "InputField.HeightControlVariant" = @("Auto","UseHeightInFormRows","UseContentHeight")
- "Table.HeightControlVariant" = @("Auto","UseHeightInFormRows","UseHeightInTableRows","UseContentHeight")
- "HierarchyPanelLocation" = @("Auto","None")
- "HorizontalAlign" = @("Left","Center","Right","Auto")
- "HorizontalLinesBWA" = @("true","false","auto")
- "HorizontalLocation" = @("Left","Center","Right","Auto")
- "Table.HorizontalScrollBar" = @("DontUse","UseAlways","AutoUse")
- "HorizontalSpacing" = @("Auto","None","Half","Single","OneAndHalf","Double")
- "AutoCommandBar.HorizontalStretch" = @("true","false","auto")
- "ButtonGroup.HorizontalStretch" = @("true","false","auto")
- "CheckBoxField.HorizontalStretch" = @("true","false","auto")
- "ColumnGroup.HorizontalStretch" = @("true","false","auto")
- "CommandBar.HorizontalStretch" = @("true","false","auto")
- "ContextMenu.HorizontalStretch" = @("true","false","auto")
- "ExtendedTooltip.HorizontalStretch" = @("true","false","auto")
- "InputField.HorizontalStretch" = @("true","false","auto")
- "LabelDecoration.HorizontalStretch" = @("true","false","auto")
- "LabelField.HorizontalStretch" = @("true","false","auto")
- "Page.HorizontalStretch" = @("true","false","auto")
- "Pages.HorizontalStretch" = @("true","false","auto")
- "PictureDecoration.HorizontalStretch" = @("true","false","auto")
- "Popup.HorizontalStretch" = @("true","false","auto")
- "RadioButtonField.HorizontalStretch" = @("true","false","auto")
- "SearchControlAddition.HorizontalStretch" = @("true","false","auto")
- "SearchStringAddition.HorizontalStretch" = @("true","false","auto")
- "UsualGroup.HorizontalStretch" = @("true","false","auto")
- "ViewStatusAddition.HorizontalStretch" = @("true","false","auto")
- "Importance" = @("Main","Normal","Supplementary")
- "IncompleteChoiceMode" = @("OnEnterPressed","OnActivate")
- "InitialListView" = @("Beginning","End","Auto")
- "InitialRowActivation" = @("Auto","Activate","NoActivate")
- "InitialTreeView" = @("NoExpand","ExpandTopLevel","ExpandAllLevels")
- "IntervalsSelectionMode" = @("Auto","Multiple","Single","None")
- "KeyType" = @("Auto","FieldValue","RowKey","RowNumber")
- "LocationInCommandBar" = @("Auto","InAdditionalSubmenu","InCommandBar","InCommandBarAndInAdditionalSubmenu")
- "MarkNegatives" = @("true","false","auto")
- "MarkRequiredComplete" = @("true","false","auto")
- "MarkingAppearance" = @("DontShow","TopLeft","BottomRight","BothSides")
- "MobileDeviceTableType" = @("Auto","List","Cards")
- "MultiLine" = @("true","false","auto")
- "MultipleValuePictureShape" = @("Auto","Rect","Circle","Square")
- "MultipleValuePictureSize" = @("Auto","Small","Medium","Large")
- "MultipleValuesHyperlink" = @("true","false","auto")
- "OnMainServerUnavalableBehavior" = @("Auto","MakeDisable","DontChangeBehavior")
- "OnScreenKeyboardReturnKeyText" = @("Auto","Return","Go","Join","Next","Search","Send","Done","Continue")
- "OnlyInAllActions" = @("true","false","auto")
- "OpenButton" = @("true","false","auto")
- "Orientation" = @("Horizontal","Vertical","HorizontalIfPossible")
- "Output" = @("Auto","Enable","Disable")
- "PagesRepresentation" = @("None","TabsOnTop","TabsOnBottom","TabsOnLeftHorizontal","TabsOnRightHorizontal","Swipe","Auto")
- "PasswordMode" = @("true","false","auto")
- "PictureLocation" = @("Auto","Left","Right","Top","Bottom")
- "PictureSize" = @("RealSize","Stretch","Proportionally","Tile","AutoSize","RealSizeIgnoreScale","AutoSizeIgnoreScale","ByFontSize")
- "PlacementArea" = @("mainCmdsLeft","autoCmds","userCmds","mainCmdsRight")
- "PointerType" = @("Special","Regular")
- "QuickChoice" = @("true","false","auto")
- "RadioButtonType" = @("Auto","RadioButtons","Tumbler")
- "RefreshRequest" = @("None","PullFromTop","PullFromBottom","PullFromTopOrBottom")
- "ReportFormType" = @("Main","Settings","Variant")
- "ReportResultViewMode" = @("Auto","Default","Compact")
- "Button.Representation" = @("Text","Picture","PictureAndText","Auto")
- "ButtonGroup.Representation" = @("Auto","Usual","Compact")
- "Command.Representation" = @("Text","Picture","TextPicture","Auto")
- "Popup.Representation" = @("Text","Picture","PictureAndText","Auto")
- "ProgressBarField.Representation" = @("Smooth","Broken","BrokenTilt")
- "Table.Representation" = @("List","HierarchicalList","Tree")
- "UsualGroup.Representation" = @("Auto","None","StrongSeparation","WeakSeparation","NormalSeparation","GroupBox","Line","Margin")
- "RepresentationInContextMenu" = @("None","AdditionalInContextMenu","OnlyInContextMenu","Auto")
- "RowActionsShowType" = @("Auto","DontShow","ShowOnHover","ShowAlways")
- "RowInputMode" = @("EndOfList","EndOfWindow","AfterCurrentRow","BeforeCurrentRow")
- "RowSelectionMode" = @("Auto","Cell","Row")
- "SaveColors" = @("Auto","ForUser","ByKeyForUser","DontUse")
- "SaveDataInSettings" = @("DontUse","UseList")
- "ScaleVariant" = @("Auto","Normal","Compact","NormalIfPossible")
- "ScalingMode" = @("Auto","Normal","Compact")
- "Page.ScrollOnCompress" = @("true","false","auto")
- "UsualGroup.ScrollOnCompress" = @("true","false","auto")
- "SearchControlLocation" = @("Auto","None","CommandBar")
- "SearchOnInput" = @("Use","DontUse","Auto")
- "SearchStringLocation" = @("Auto","None","CommandBar","Top","Bottom","FormCaption","PullFromTop")
- "SelectedRowsUse" = @("Use","DontUse","Auto")
- "CalendarField.SelectionMode" = @("Single","Multiple","Interval")
- "Table.SelectionMode" = @("SingleRow","MultiRow")
- "SelectionShowMode" = @("WhenActive","Always","DontShow","WhenMultipleCellsSelected","WhenMultipleCellsSelectedWhenActive")
- "Shape" = @("Auto","Usual","Oval")
- "ShapeRepresentation" = @("Auto","Always","WhenActive","None")
- "ShowCheckBoxesInDropList" = @("true","false","auto")
- "ShowCommandBar" = @("true","false","auto")
- "ShowHorizontalLinesFlag" = @("true","false","auto")
- "ColumnGroup.ShowTitle" = @("true","false","auto")
- "Form.ShowTitle" = @("true","false","auto")
- "Page.ShowTitle" = @("true","false","auto")
- "UsualGroup.ShowTitle" = @("true","false","auto")
- "ShowTitleInCard" = @("true","false","auto")
- "ShowVerticalLinesFlag" = @("true","false","auto")
- "SkipOnInput" = @("true","false","auto")
- "SpecialTextInputMode" = @("Auto","None","DigitsAndPunctuation","URL","Email","PhoneNumber","Digits")
- "SpellCheckingOnTextInput" = @("Auto","Use","DontUse")
- "SpinButton" = @("true","false","auto")
- "SpreadsheetDocumentMultipleSelectionPanelViewMode" = @("Auto","DontShow","ShowOnMultipleSelection","ShowAlways")
- "TableLocation" = @("Auto","Left","Right","None")
- "TextSize" = @("Enlarged","Normal","Reduced")
- "ThroughAlign" = @("Use","DontUse","Auto")
- "TimeChoiceMode" = @("Auto","DontChoose","CustomTime","Interval1Minute","Interval5Minutes","Interval10Minutes","Interval15Minutes","Interval15And20Minutes","Interval20Minutes","Interval30Minutes","Interval60Minutes")
- "TitleLocation" = @("None","Auto","Left","Top","Right","Bottom")
- "ToolTipRepresentation" = @("Auto","None","Balloon","Button","ShowAuto","ShowTop","ShowLeft","ShowBottom","ShowRight")
- "TumblerRepresentation" = @("Text","Picture","Auto")
- "Button.Type" = @("CommandBarButton","UsualButton","Hyperlink","CommandBarHyperlink")
- "UpdateOnDataChange" = @("Auto","DontUpdate")
- "UseAlternationRowColorBWA" = @("true","false","auto")
- "UseCopy" = @("true","false","auto")
- "UseForFoldersAndItems" = @("Items","Folders","FoldersAndItems")
- "UsePostingMode" = @("Regular","RealTime","Ask","Auto")
- "ValuesSelectionMode" = @("Auto","Multiple","Single","None")
- "VerticalAlign" = @("Top","Center","Bottom","Auto")
- "VerticalLinesBWA" = @("true","false","auto")
- "VerticalScroll" = @("auto","use","useIfNecessary","useWithoutStretch")
- "Table.VerticalScrollBar" = @("DontUse","UseAlways","AutoUse")
- "VerticalSpacing" = @("Auto","None","Half","Single","OneAndHalf","Double")
- "AutoCommandBar.VerticalStretch" = @("true","false","auto")
- "ButtonGroup.VerticalStretch" = @("true","false","auto")
- "ColumnGroup.VerticalStretch" = @("true","false","auto")
- "CommandBar.VerticalStretch" = @("true","false","auto")
- "ContextMenu.VerticalStretch" = @("true","false","auto")
- "ExtendedTooltip.VerticalStretch" = @("true","false","auto")
- "InputField.VerticalStretch" = @("true","false","auto")
- "LabelDecoration.VerticalStretch" = @("true","false","auto")
- "LabelField.VerticalStretch" = @("true","false","auto")
- "Page.VerticalStretch" = @("true","false","auto")
- "Pages.VerticalStretch" = @("true","false","auto")
- "PictureDecoration.VerticalStretch" = @("true","false","auto")
- "Popup.VerticalStretch" = @("true","false","auto")
- "UsualGroup.VerticalStretch" = @("true","false","auto")
- "ViewMode" = @("All","QuickAccess")
- "ViewModeApplicationOnSetReportResult" = @("Auto","Apply","DontApply")
- "ViewScalingMode" = @("Auto","Normal","Large")
- "ViewStatusLocation" = @("Auto","None","Top","Bottom")
- "WarningOnEditRepresentation" = @("Show","DontShow","Auto")
- "WidthInCard" = @("Auto","Full","Half")
- "WindowOpeningMode" = @("Auto","DontBlock","LockOwner","LockWholeInterface","Independent","LockOwnerWindow")
- }
- $script:enumValueAliases = @{
- "TitlesLeftDataLeft" = "ItemsLeftTitlesLeft"
- "TitlesLeftDataRight" = "ItemsRightTitlesLeft"
- "TitlesRightDataLeft" = "ItemsLeftTitlesRight"
- "TitlesRightDataRight" = "ItemsRightTitlesRight"
- "GroupBox" = "StrongSeparation"
- "Margin" = "NormalSeparation"
- "Square" = "Rect"
- }
- $script:enumDefaultValues = @{
- "Attribute.FillCheck" = "DontCheck"
- "AutoCommandBar.GroupHorizontalAlign" = "Auto"
- "AutoCommandBar.GroupVerticalAlign" = "Auto"
- "AutoCommandBar.HorizontalAlign" = "Left"
- "AutoCommandBar.HorizontalStretch" = "auto"
- "AutoCommandBar.ToolTipRepresentation" = "Auto"
- "AutoCommandBar.VerticalStretch" = "auto"
- "Button.GroupHorizontalAlign" = "Auto"
- "Button.GroupVerticalAlign" = "Auto"
- "Button.LocationInCommandBar" = "Auto"
- "Button.OnMainServerUnavalableBehavior" = "Auto"
- "Button.PictureLocation" = "Auto"
- "Button.PlacementArea" = "userCmds"
- "Button.Representation" = "Auto"
- "Button.RepresentationInContextMenu" = "Auto"
- "Button.Shape" = "Auto"
- "Button.ShapeRepresentation" = "Auto"
- "Button.SkipOnInput" = "auto"
- "Button.ToolTipRepresentation" = "Auto"
- "ButtonGroup.GroupHorizontalAlign" = "Auto"
- "ButtonGroup.GroupVerticalAlign" = "Auto"
- "ButtonGroup.HorizontalStretch" = "auto"
- "ButtonGroup.PlacementArea" = "userCmds"
- "ButtonGroup.Representation" = "Auto"
- "ButtonGroup.ToolTipRepresentation" = "Auto"
- "ButtonGroup.VerticalStretch" = "auto"
- "CalendarField.EditMode" = "Enter"
- "CalendarField.FixingInTable" = "None"
- "CalendarField.FooterHorizontalAlign" = "Auto"
- "CalendarField.GroupHorizontalAlign" = "Auto"
- "CalendarField.GroupVerticalAlign" = "Auto"
- "CalendarField.HeaderHorizontalAlign" = "Left"
- "CalendarField.HorizontalAlign" = "Auto"
- "CalendarField.OnMainServerUnavalableBehavior" = "Auto"
- "CalendarField.SelectionMode" = "Single"
- "CalendarField.SkipOnInput" = "auto"
- "CalendarField.TitleLocation" = "Auto"
- "CalendarField.ToolTipRepresentation" = "Auto"
- "CalendarField.VerticalAlign" = "Auto"
- "CalendarField.WarningOnEditRepresentation" = "Auto"
- "ChartField.EditMode" = "Enter"
- "ChartField.FixingInTable" = "None"
- "ChartField.FooterHorizontalAlign" = "Auto"
- "ChartField.GroupHorizontalAlign" = "Auto"
- "ChartField.GroupVerticalAlign" = "Auto"
- "ChartField.HeaderHorizontalAlign" = "Left"
- "ChartField.HorizontalAlign" = "Auto"
- "ChartField.OnMainServerUnavalableBehavior" = "Auto"
- "ChartField.SkipOnInput" = "auto"
- "ChartField.TitleLocation" = "Auto"
- "ChartField.ToolTipRepresentation" = "Auto"
- "ChartField.VerticalAlign" = "Auto"
- "ChartField.WarningOnEditRepresentation" = "Auto"
- "CheckBoxField.EditMode" = "Enter"
- "CheckBoxField.EqualItemsWidth" = "auto"
- "CheckBoxField.FixingInTable" = "None"
- "CheckBoxField.FooterHorizontalAlign" = "Auto"
- "CheckBoxField.GroupHorizontalAlign" = "Auto"
- "CheckBoxField.GroupVerticalAlign" = "Auto"
- "CheckBoxField.HeaderHorizontalAlign" = "Left"
- "CheckBoxField.HorizontalAlign" = "Auto"
- "CheckBoxField.OnMainServerUnavalableBehavior" = "Auto"
- "CheckBoxField.SkipOnInput" = "auto"
- "CheckBoxField.TitleLocation" = "Auto"
- "CheckBoxField.ToolTipRepresentation" = "Auto"
- "CheckBoxField.VerticalAlign" = "Auto"
- "CheckBoxField.WarningOnEditRepresentation" = "Auto"
- "Column.FillCheck" = "DontCheck"
- "ColumnGroup.FixingInTable" = "None"
- "ColumnGroup.Group" = "Vertical"
- "ColumnGroup.GroupHorizontalAlign" = "Auto"
- "ColumnGroup.GroupVerticalAlign" = "Auto"
- "ColumnGroup.HeaderHorizontalAlign" = "Auto"
- "ColumnGroup.HorizontalStretch" = "auto"
- "ColumnGroup.ToolTipRepresentation" = "Auto"
- "ColumnGroup.VerticalStretch" = "auto"
- "Command.CurrentRowUse" = "Auto"
- "Command.Representation" = "Auto"
- "CommandBar.GroupHorizontalAlign" = "Auto"
- "CommandBar.GroupVerticalAlign" = "Auto"
- "CommandBar.HorizontalLocation" = "Left"
- "CommandBar.HorizontalStretch" = "auto"
- "CommandBar.ToolTipRepresentation" = "Auto"
- "CommandBar.VerticalStretch" = "auto"
- "ContextMenu.GroupHorizontalAlign" = "Auto"
- "ContextMenu.GroupVerticalAlign" = "Auto"
- "ContextMenu.HorizontalStretch" = "auto"
- "ContextMenu.ToolTipRepresentation" = "Auto"
- "ContextMenu.VerticalStretch" = "auto"
- "ExtendedTooltip.GroupHorizontalAlign" = "Auto"
- "ExtendedTooltip.GroupVerticalAlign" = "Auto"
- "ExtendedTooltip.HorizontalAlign" = "Left"
- "ExtendedTooltip.HorizontalStretch" = "auto"
- "ExtendedTooltip.OnMainServerUnavalableBehavior" = "Auto"
- "ExtendedTooltip.SkipOnInput" = "auto"
- "ExtendedTooltip.ToolTipRepresentation" = "Auto"
- "ExtendedTooltip.VerticalAlign" = "Auto"
- "ExtendedTooltip.VerticalStretch" = "auto"
- "Form.AutoSaveDataInSettings" = "DontUse"
- "Form.ChildItemsWidth" = "Auto"
- "Form.ChildrenAlign" = "Auto"
- "Form.CollapseItemsByImportanceVariant" = "Auto"
- "Form.CommandBarLocation" = "Auto"
- "Form.ConversationsRepresentation" = "Auto"
- "Form.EnterKeyBehavior" = "ControlNavigation"
- "Form.Group" = "Vertical"
- "Form.HorizontalAlign" = "Auto"
- "Form.HorizontalSpacing" = "Auto"
- "Form.SaveDataInSettings" = "DontUse"
- "Form.ScalingMode" = "Auto"
- "Form.VerticalAlign" = "Auto"
- "Form.VerticalScroll" = "auto"
- "Form.VerticalSpacing" = "Auto"
- "Form.WindowOpeningMode" = "Independent"
- "FormattedDocumentField.EditMode" = "Enter"
- "FormattedDocumentField.FixingInTable" = "None"
- "FormattedDocumentField.FooterHorizontalAlign" = "Auto"
- "FormattedDocumentField.GroupHorizontalAlign" = "Auto"
- "FormattedDocumentField.GroupVerticalAlign" = "Auto"
- "FormattedDocumentField.HeaderHorizontalAlign" = "Left"
- "FormattedDocumentField.HorizontalAlign" = "Auto"
- "FormattedDocumentField.OnMainServerUnavalableBehavior" = "Auto"
- "FormattedDocumentField.Output" = "Auto"
- "FormattedDocumentField.SkipOnInput" = "auto"
- "FormattedDocumentField.TitleLocation" = "Auto"
- "FormattedDocumentField.ToolTipRepresentation" = "Auto"
- "FormattedDocumentField.VerticalAlign" = "Auto"
- "FormattedDocumentField.WarningOnEditRepresentation" = "Auto"
- "GraphicalSchemaField.EditMode" = "Enter"
- "GraphicalSchemaField.FixingInTable" = "None"
- "GraphicalSchemaField.FooterHorizontalAlign" = "Auto"
- "GraphicalSchemaField.GroupHorizontalAlign" = "Auto"
- "GraphicalSchemaField.GroupVerticalAlign" = "Auto"
- "GraphicalSchemaField.HeaderHorizontalAlign" = "Left"
- "GraphicalSchemaField.HorizontalAlign" = "Auto"
- "GraphicalSchemaField.OnMainServerUnavalableBehavior" = "Auto"
- "GraphicalSchemaField.Output" = "Auto"
- "GraphicalSchemaField.SkipOnInput" = "auto"
- "GraphicalSchemaField.TitleLocation" = "Auto"
- "GraphicalSchemaField.ToolTipRepresentation" = "Auto"
- "GraphicalSchemaField.VerticalAlign" = "Auto"
- "GraphicalSchemaField.WarningOnEditRepresentation" = "Auto"
- "HTMLDocumentField.EditMode" = "Enter"
- "HTMLDocumentField.FixingInTable" = "None"
- "HTMLDocumentField.FooterHorizontalAlign" = "Auto"
- "HTMLDocumentField.GroupHorizontalAlign" = "Auto"
- "HTMLDocumentField.GroupVerticalAlign" = "Auto"
- "HTMLDocumentField.HeaderHorizontalAlign" = "Left"
- "HTMLDocumentField.HorizontalAlign" = "Auto"
- "HTMLDocumentField.OnMainServerUnavalableBehavior" = "Auto"
- "HTMLDocumentField.Output" = "Auto"
- "HTMLDocumentField.SkipOnInput" = "auto"
- "HTMLDocumentField.TitleLocation" = "Auto"
- "HTMLDocumentField.ToolTipRepresentation" = "Auto"
- "HTMLDocumentField.VerticalAlign" = "Auto"
- "HTMLDocumentField.WarningOnEditRepresentation" = "Auto"
- "InputField.AutoCapitalizationOnTextInput" = "Auto"
- "InputField.AutoChoiceIncomplete" = "auto"
- "InputField.AutoCorrectionOnTextInput" = "Auto"
- "InputField.AutoMarkIncomplete" = "auto"
- "InputField.AutoShowClearButtonMode" = "Auto"
- "InputField.AutoShowOpenButtonMode" = "Auto"
- "InputField.AutofillHint" = "DontUse"
- "InputField.ChoiceButton" = "auto"
- "InputField.ChoiceButtonRepresentation" = "Auto"
- "InputField.ChoiceFoldersAndItems" = "Auto"
- "InputField.ChoiceHistoryOnInput" = "Auto"
- "InputField.ChoiceListButton" = "auto"
- "InputField.ClearButton" = "auto"
- "InputField.CreateButton" = "auto"
- "InputField.DropListButton" = "auto"
- "InputField.EditMode" = "Enter"
- "InputField.EditTextUpdate" = "Auto"
- "InputField.ExtendedEdit" = "auto"
- "InputField.FixingInTable" = "None"
- "InputField.FooterHorizontalAlign" = "Auto"
- "InputField.GroupHorizontalAlign" = "Auto"
- "InputField.GroupVerticalAlign" = "Auto"
- "InputField.HeaderHorizontalAlign" = "Left"
- "InputField.HeightControlVariant" = "Auto"
- "InputField.HorizontalAlign" = "Auto"
- "InputField.HorizontalStretch" = "auto"
- "InputField.IncompleteChoiceMode" = "OnEnterPressed"
- "InputField.MarkNegatives" = "auto"
- "InputField.MultiLine" = "auto"
- "InputField.MultipleValuePictureShape" = "Auto"
- "InputField.MultipleValuePictureSize" = "Auto"
- "InputField.MultipleValuesHyperlink" = "auto"
- "InputField.OnMainServerUnavalableBehavior" = "Auto"
- "InputField.OnScreenKeyboardReturnKeyText" = "Auto"
- "InputField.OpenButton" = "auto"
- "InputField.PasswordMode" = "auto"
- "InputField.QuickChoice" = "auto"
- "InputField.ShowCheckBoxesInDropList" = "auto"
- "InputField.SkipOnInput" = "auto"
- "InputField.SpecialTextInputMode" = "Auto"
- "InputField.SpellCheckingOnTextInput" = "Auto"
- "InputField.SpinButton" = "auto"
- "InputField.TitleLocation" = "Auto"
- "InputField.ToolTipRepresentation" = "Auto"
- "InputField.VerticalAlign" = "Auto"
- "InputField.VerticalStretch" = "auto"
- "InputField.WarningOnEditRepresentation" = "Auto"
- "LabelDecoration.GroupHorizontalAlign" = "Auto"
- "LabelDecoration.GroupVerticalAlign" = "Auto"
- "LabelDecoration.HorizontalAlign" = "Left"
- "LabelDecoration.HorizontalStretch" = "auto"
- "LabelDecoration.OnMainServerUnavalableBehavior" = "Auto"
- "LabelDecoration.SkipOnInput" = "auto"
- "LabelDecoration.ToolTipRepresentation" = "Auto"
- "LabelDecoration.VerticalAlign" = "Auto"
- "LabelDecoration.VerticalStretch" = "auto"
- "LabelField.EditMode" = "Enter"
- "LabelField.FixingInTable" = "None"
- "LabelField.FooterHorizontalAlign" = "Auto"
- "LabelField.GroupHorizontalAlign" = "Auto"
- "LabelField.GroupVerticalAlign" = "Auto"
- "LabelField.HeaderHorizontalAlign" = "Left"
- "LabelField.HorizontalAlign" = "Auto"
- "LabelField.HorizontalStretch" = "auto"
- "LabelField.MarkNegatives" = "auto"
- "LabelField.OnMainServerUnavalableBehavior" = "Auto"
- "LabelField.PasswordMode" = "auto"
- "LabelField.SkipOnInput" = "auto"
- "LabelField.TitleLocation" = "Auto"
- "LabelField.ToolTipRepresentation" = "Auto"
- "LabelField.VerticalAlign" = "Auto"
- "LabelField.VerticalStretch" = "auto"
- "LabelField.WarningOnEditRepresentation" = "Auto"
- "Page.ChildItemsWidth" = "Auto"
- "Page.ChildrenAlign" = "Auto"
- "Page.Group" = "Vertical"
- "Page.GroupHorizontalAlign" = "Auto"
- "Page.GroupVerticalAlign" = "Auto"
- "Page.HorizontalAlign" = "Auto"
- "Page.HorizontalSpacing" = "Auto"
- "Page.HorizontalStretch" = "auto"
- "Page.ToolTipRepresentation" = "Auto"
- "Page.VerticalAlign" = "Auto"
- "Page.VerticalSpacing" = "Auto"
- "Page.VerticalStretch" = "auto"
- "Pages.CurrentRowUse" = "Auto"
- "Pages.GroupHorizontalAlign" = "Auto"
- "Pages.GroupVerticalAlign" = "Auto"
- "Pages.HorizontalStretch" = "auto"
- "Pages.PagesRepresentation" = "Auto"
- "Pages.ToolTipRepresentation" = "Auto"
- "Pages.VerticalStretch" = "auto"
- "PeriodField.EditMode" = "Enter"
- "PeriodField.FixingInTable" = "None"
- "PeriodField.FooterHorizontalAlign" = "Auto"
- "PeriodField.GroupHorizontalAlign" = "Auto"
- "PeriodField.GroupVerticalAlign" = "Auto"
- "PeriodField.HeaderHorizontalAlign" = "Left"
- "PeriodField.HorizontalAlign" = "Auto"
- "PeriodField.OnMainServerUnavalableBehavior" = "Auto"
- "PeriodField.SkipOnInput" = "auto"
- "PeriodField.TitleLocation" = "Auto"
- "PeriodField.ToolTipRepresentation" = "Auto"
- "PeriodField.VerticalAlign" = "Auto"
- "PeriodField.WarningOnEditRepresentation" = "Auto"
- "PictureDecoration.FileDragMode" = "AsFileRef"
- "PictureDecoration.GroupHorizontalAlign" = "Auto"
- "PictureDecoration.GroupVerticalAlign" = "Auto"
- "PictureDecoration.HorizontalStretch" = "auto"
- "PictureDecoration.OnMainServerUnavalableBehavior" = "Auto"
- "PictureDecoration.PictureSize" = "RealSize"
- "PictureDecoration.SkipOnInput" = "auto"
- "PictureDecoration.ToolTipRepresentation" = "Auto"
- "PictureDecoration.VerticalStretch" = "auto"
- "PictureField.EditMode" = "Enter"
- "PictureField.FileDragMode" = "AsFileRef"
- "PictureField.FixingInTable" = "None"
- "PictureField.FooterHorizontalAlign" = "Auto"
- "PictureField.GroupHorizontalAlign" = "Auto"
- "PictureField.GroupVerticalAlign" = "Auto"
- "PictureField.HeaderHorizontalAlign" = "Left"
- "PictureField.HorizontalAlign" = "Auto"
- "PictureField.OnMainServerUnavalableBehavior" = "Auto"
- "PictureField.PictureSize" = "RealSize"
- "PictureField.SkipOnInput" = "auto"
- "PictureField.TitleLocation" = "Auto"
- "PictureField.ToolTipRepresentation" = "Auto"
- "PictureField.VerticalAlign" = "Auto"
- "PictureField.WarningOnEditRepresentation" = "Auto"
- "PlannerField.EditMode" = "Enter"
- "PlannerField.FixingInTable" = "None"
- "PlannerField.FooterHorizontalAlign" = "Auto"
- "PlannerField.GroupHorizontalAlign" = "Auto"
- "PlannerField.GroupVerticalAlign" = "Auto"
- "PlannerField.HeaderHorizontalAlign" = "Left"
- "PlannerField.HorizontalAlign" = "Auto"
- "PlannerField.OnMainServerUnavalableBehavior" = "Auto"
- "PlannerField.SkipOnInput" = "auto"
- "PlannerField.TitleLocation" = "Auto"
- "PlannerField.ToolTipRepresentation" = "Auto"
- "PlannerField.VerticalAlign" = "Auto"
- "PlannerField.WarningOnEditRepresentation" = "Auto"
- "Popup.GroupHorizontalAlign" = "Auto"
- "Popup.GroupVerticalAlign" = "Auto"
- "Popup.HorizontalStretch" = "auto"
- "Popup.PlacementArea" = "userCmds"
- "Popup.Representation" = "Auto"
- "Popup.Shape" = "Auto"
- "Popup.ShapeRepresentation" = "Auto"
- "Popup.ToolTipRepresentation" = "Auto"
- "Popup.VerticalStretch" = "auto"
- "ProgressBarField.EditMode" = "Enter"
- "ProgressBarField.FixingInTable" = "None"
- "ProgressBarField.FooterHorizontalAlign" = "Auto"
- "ProgressBarField.GroupHorizontalAlign" = "Auto"
- "ProgressBarField.GroupVerticalAlign" = "Auto"
- "ProgressBarField.HeaderHorizontalAlign" = "Left"
- "ProgressBarField.HorizontalAlign" = "Auto"
- "ProgressBarField.OnMainServerUnavalableBehavior" = "Auto"
- "ProgressBarField.Orientation" = "Horizontal"
- "ProgressBarField.Representation" = "Smooth"
- "ProgressBarField.SkipOnInput" = "auto"
- "ProgressBarField.TitleLocation" = "Auto"
- "ProgressBarField.ToolTipRepresentation" = "Auto"
- "ProgressBarField.VerticalAlign" = "Auto"
- "ProgressBarField.WarningOnEditRepresentation" = "Auto"
- "RadioButtonField.EditMode" = "Enter"
- "RadioButtonField.EqualColumnsWidth" = "auto"
- "RadioButtonField.FixingInTable" = "None"
- "RadioButtonField.FooterHorizontalAlign" = "Auto"
- "RadioButtonField.GroupHorizontalAlign" = "Auto"
- "RadioButtonField.GroupVerticalAlign" = "Auto"
- "RadioButtonField.HeaderHorizontalAlign" = "Left"
- "RadioButtonField.HorizontalAlign" = "Auto"
- "RadioButtonField.OnMainServerUnavalableBehavior" = "Auto"
- "RadioButtonField.SkipOnInput" = "auto"
- "RadioButtonField.TitleLocation" = "Auto"
- "RadioButtonField.ToolTipRepresentation" = "Auto"
- "RadioButtonField.VerticalAlign" = "Auto"
- "RadioButtonField.WarningOnEditRepresentation" = "Auto"
- "SearchControlAddition.GroupHorizontalAlign" = "Auto"
- "SearchControlAddition.GroupVerticalAlign" = "Auto"
- "SearchControlAddition.HorizontalStretch" = "auto"
- "SearchControlAddition.PlacementArea" = "userCmds"
- "SearchControlAddition.ToolTipRepresentation" = "Auto"
- "SearchStringAddition.GroupHorizontalAlign" = "Auto"
- "SearchStringAddition.GroupVerticalAlign" = "Auto"
- "SearchStringAddition.HorizontalStretch" = "auto"
- "SearchStringAddition.PlacementArea" = "userCmds"
- "SearchStringAddition.ToolTipRepresentation" = "Auto"
- "Settings.KeyType" = "Auto"
- "SpreadSheetDocumentField.DrawingSelectionShowMode" = "Auto"
- "SpreadSheetDocumentField.EditMode" = "Enter"
- "SpreadSheetDocumentField.FixingInTable" = "None"
- "SpreadSheetDocumentField.FooterHorizontalAlign" = "Auto"
- "SpreadSheetDocumentField.GroupHorizontalAlign" = "Auto"
- "SpreadSheetDocumentField.GroupVerticalAlign" = "Auto"
- "SpreadSheetDocumentField.HeaderHorizontalAlign" = "Left"
- "SpreadSheetDocumentField.HorizontalAlign" = "Auto"
- "SpreadSheetDocumentField.OnMainServerUnavalableBehavior" = "Auto"
- "SpreadSheetDocumentField.Output" = "Auto"
- "SpreadSheetDocumentField.PointerType" = "Special"
- "SpreadSheetDocumentField.SelectionShowMode" = "Always"
- "SpreadSheetDocumentField.SkipOnInput" = "auto"
- "SpreadSheetDocumentField.TitleLocation" = "Auto"
- "SpreadSheetDocumentField.ToolTipRepresentation" = "Auto"
- "SpreadSheetDocumentField.VerticalAlign" = "Auto"
- "SpreadSheetDocumentField.ViewScalingMode" = "Auto"
- "SpreadSheetDocumentField.WarningOnEditRepresentation" = "Auto"
- "Table.AutoAddIncomplete" = "auto"
- "Table.AutoMarkIncomplete" = "auto"
- "Table.BehaviorOnHorizontalCompression" = "Auto"
- "Table.CommandBarLocation" = "Auto"
- "Table.CurrentRowUse" = "Auto"
- "Table.FileDragMode" = "AsFileRef"
- "Table.GroupHorizontalAlign" = "Auto"
- "Table.GroupVerticalAlign" = "Auto"
- "Table.HeightControlVariant" = "Auto"
- "Table.HorizontalScrollBar" = "AutoUse"
- "Table.InitialListView" = "Auto"
- "Table.InitialTreeView" = "NoExpand"
- "Table.OnMainServerUnavalableBehavior" = "Auto"
- "Table.Output" = "Auto"
- "Table.RefreshRequest" = "None"
- "Table.Representation" = "HierarchicalList"
- "Table.RowInputMode" = "EndOfList"
- "Table.RowSelectionMode" = "Cell"
- "Table.SearchControlLocation" = "Auto"
- "Table.SearchOnInput" = "Auto"
- "Table.SearchStringLocation" = "Auto"
- "Table.SelectionMode" = "MultiRow"
- "Table.SkipOnInput" = "auto"
- "Table.TitleLocation" = "None"
- "Table.ToolTipRepresentation" = "Auto"
- "Table.VerticalScrollBar" = "AutoUse"
- "Table.ViewStatusLocation" = "Auto"
- "TextDocumentField.EditMode" = "Enter"
- "TextDocumentField.FixingInTable" = "None"
- "TextDocumentField.FooterHorizontalAlign" = "Auto"
- "TextDocumentField.GroupHorizontalAlign" = "Auto"
- "TextDocumentField.GroupVerticalAlign" = "Auto"
- "TextDocumentField.HeaderHorizontalAlign" = "Left"
- "TextDocumentField.HorizontalAlign" = "Auto"
- "TextDocumentField.OnMainServerUnavalableBehavior" = "Auto"
- "TextDocumentField.Output" = "Auto"
- "TextDocumentField.SkipOnInput" = "auto"
- "TextDocumentField.TitleLocation" = "Auto"
- "TextDocumentField.ToolTipRepresentation" = "Auto"
- "TextDocumentField.VerticalAlign" = "Auto"
- "TextDocumentField.WarningOnEditRepresentation" = "Auto"
- "TrackBarField.EditMode" = "Enter"
- "TrackBarField.FixingInTable" = "None"
- "TrackBarField.FooterHorizontalAlign" = "Auto"
- "TrackBarField.GroupHorizontalAlign" = "Auto"
- "TrackBarField.GroupVerticalAlign" = "Auto"
- "TrackBarField.HeaderHorizontalAlign" = "Left"
- "TrackBarField.HorizontalAlign" = "Auto"
- "TrackBarField.MarkingAppearance" = "BottomRight"
- "TrackBarField.OnMainServerUnavalableBehavior" = "Auto"
- "TrackBarField.Orientation" = "Horizontal"
- "TrackBarField.SkipOnInput" = "auto"
- "TrackBarField.TitleLocation" = "Auto"
- "TrackBarField.ToolTipRepresentation" = "Auto"
- "TrackBarField.VerticalAlign" = "Auto"
- "TrackBarField.WarningOnEditRepresentation" = "Auto"
- "UsualGroup.Behavior" = "Auto"
- "UsualGroup.ChildItemsWidth" = "Auto"
- "UsualGroup.ChildrenAlign" = "Auto"
- "UsualGroup.ControlRepresentation" = "TitleHyperlink"
- "UsualGroup.CurrentRowUse" = "Auto"
- "UsualGroup.Group" = "HorizontalIfPossible"
- "UsualGroup.GroupHorizontalAlign" = "Auto"
- "UsualGroup.GroupVerticalAlign" = "Auto"
- "UsualGroup.HorizontalAlign" = "Auto"
- "UsualGroup.HorizontalSpacing" = "Auto"
- "UsualGroup.HorizontalStretch" = "auto"
- "UsualGroup.Representation" = "WeakSeparation"
- "UsualGroup.ThroughAlign" = "Auto"
- "UsualGroup.ToolTipRepresentation" = "Auto"
- "UsualGroup.VerticalAlign" = "Auto"
- "UsualGroup.VerticalSpacing" = "Auto"
- "UsualGroup.VerticalStretch" = "auto"
- "ViewStatusAddition.GroupHorizontalAlign" = "Auto"
- "ViewStatusAddition.GroupVerticalAlign" = "Auto"
- "ViewStatusAddition.HorizontalLocation" = "Auto"
- "ViewStatusAddition.HorizontalStretch" = "auto"
- "ViewStatusAddition.PlacementArea" = "userCmds"
- "ViewStatusAddition.ToolTipRepresentation" = "Auto"
- }
- $script:enumScopeTypes = @{
- 'Attribute' = $true
- 'AutoCommandBar' = $true
- 'Button' = $true
- 'ButtonGroup' = $true
- 'CalendarField' = $true
- 'ChartField' = $true
- 'CheckBoxField' = $true
- 'Column' = $true
- 'ColumnGroup' = $true
- 'Command' = $true
- 'CommandBar' = $true
- 'ContextMenu' = $true
- 'ExtendedTooltip' = $true
- 'Form' = $true
- 'FormattedDocumentField' = $true
- 'GanttChartField' = $true
- 'GraphicalSchemaField' = $true
- 'HTMLDocumentField' = $true
- 'InputField' = $true
- 'LabelDecoration' = $true
- 'LabelField' = $true
- 'Page' = $true
- 'Pages' = $true
- 'PeriodField' = $true
- 'PictureDecoration' = $true
- 'PictureField' = $true
- 'PlannerField' = $true
- 'Popup' = $true
- 'ProgressBarField' = $true
- 'RadioButtonField' = $true
- 'SearchControlAddition' = $true
- 'SearchStringAddition' = $true
- 'Settings' = $true
- 'SpreadSheetDocumentField' = $true
- 'Table' = $true
- 'TextDocumentField' = $true
- 'TrackBarField' = $true
- 'UsualGroup' = $true
- 'ViewStatusAddition' = $true
- }
- $script:enumInputSynonyms = @{
- "Command.Representation" = @{ "PictureAndText" = "TextPicture" }
- "Button.Representation" = @{ "TextPicture" = "PictureAndText" }
- "Popup.Representation" = @{ "TextPicture" = "PictureAndText" }
- "Table.SelectionMode" = @{ "Single" = "SingleRow"; "Multiple" = "MultiRow" }
- "CalendarField.SelectionMode" = @{ "SingleRow" = "Single"; "MultiRow" = "Multiple" }
- }
- $script:objType = $null
- $script:childTagOrder = @{
- 'AutoCommandBar' = 'HorizontalAlign Autofill ChildItems'
- 'Button' = 'Type Visible TitleHeight UserVisible Representation DefaultButton SkipOnInput Enabled DefaultItem Width AutoMaxWidth MaxWidth Height AutoMaxHeight HorizontalStretch MaxHeight VerticalStretch GroupHorizontalAlign Check GroupVerticalAlign CommandName Parameter DataPath TextColor BackColor BorderColor Font Picture Title Shape ToolTipRepresentation RepresentationInContextMenu ShapeRepresentation PictureLocation LocationInCommandBar CommandUniqueness ExtendedTooltip'
- 'ButtonGroup' = 'EnableContentChange Visible Title GroupVerticalAlign ToolTip HorizontalStretch GroupHorizontalAlign ToolTipRepresentation CommandSource Representation VerticalStretch ExtendedTooltip ChildItems'
- 'CalendarField' = 'DataPath SkipOnInput Title TitleLocation ToolTip ToolTipRepresentation Width AutoMaxWidth Height HorizontalStretch SelectionMode ShowCurrentDate ShowMonthsPanel WidthInMonths HeightInMonths ContextMenu ExtendedTooltip Events'
- 'ChartField' = 'DataPath Enabled Title TitleFont Visible TitleLocation GroupHorizontalAlign Width AutoMaxWidth MaxHeight MaxWidth Height AutoMaxHeight HorizontalStretch VerticalStretch ContextMenu ExtendedTooltip Events'
- 'CheckBoxField' = 'DataPath Visible Enabled UserVisible DefaultItem ReadOnly SkipOnInput Title TitleTextColor TitleFont TitleLocation TitleHeight ToolTip FooterHorizontalAlign HorizontalAlign ToolTipRepresentation Shortcut GroupHorizontalAlign VerticalAlign GroupVerticalAlign WarningOnEditRepresentation WarningOnEdit EditMode AutoCellHeight CellHyperlink FixingInTable ShowInHeader FooterDataPath HeaderPicture HeaderHorizontalAlign ShowInFooter CheckBoxType EditFormat ItemHeight ItemTitleHeight ItemWidth EqualItemsWidth ThreeState ContextMenu ExtendedTooltip Events'
- 'ColumnGroup' = 'Visible Enabled ReadOnly UserVisible EnableContentChange Title GroupVerticalAlign TitleFont TitleTextColor ToolTip ToolTipRepresentation Width Height HorizontalStretch GroupHorizontalAlign VerticalStretch Group ShowTitle ShowInHeader HeaderDataPath HeaderHorizontalAlign HeaderFormat HeaderPicture FixingInTable ExtendedTooltip ChildItems'
- 'CommandBar' = 'Enabled Visible EnableContentChange Title ToolTip ToolTipRepresentation Width Height HorizontalStretch VerticalStretch GroupHorizontalAlign GroupVerticalAlign HorizontalLocation CommandSource ExtendedTooltip ChildItems'
- 'FormattedDocumentField' = 'DataPath DefaultItem Enabled ReadOnly SkipOnInput Title TitleLocation CommandSet Font ToolTip EditMode Width AutoMaxWidth Height AutoMaxHeight BorderColor HorizontalStretch MaxWidth ContextMenu ExtendedTooltip Events'
- 'GanttChartField' = 'DataPath DefaultItem TitleLocation Width Height HorizontalStretch VerticalStretch ContextMenu ExtendedTooltip Table Events'
- 'GraphicalSchemaField' = 'DataPath DefaultItem ReadOnly Title TitleLocation WarningOnEditRepresentation Width Height Edit ContextMenu ExtendedTooltip Events'
- 'HTMLDocumentField' = 'DataPath DefaultItem Enabled ReadOnly SkipOnInput Title TitleTextColor TitleFont TitleLocation ToolTipRepresentation Visible WarningOnEditRepresentation Width AutoMaxWidth MaxWidth Height AutoMaxHeight MaxHeight HorizontalStretch VerticalStretch Output BorderColor ContextMenu ExtendedTooltip Events'
- 'InputField' = 'DataPath Visible UserVisible DefaultItem Enabled ReadOnly SkipOnInput Title TitleBackColor TitleTextColor TitleFont TitleLocation TitleHeight ToolTip ToolTipRepresentation WarningOnEditRepresentation WarningOnEdit Shortcut HorizontalAlign VerticalAlign GroupHorizontalAlign GroupVerticalAlign EditMode CellHyperlink FixingInTable AutoCellHeight ShowInHeader HeaderHorizontalAlign HeaderPicture ShowInFooter FooterDataPath FooterText FooterTextColor FooterFont FooterHorizontalAlign FooterPicture Width AutoMaxWidth MaxWidth Height AutoMaxHeight MaxHeight HorizontalStretch AllowInputEmptyMultipleValues MultipleValuesFont MultipleValuesTextColor MultipleValuesBackColor VerticalStretch Wrap MarkNegatives PasswordMode MultiLine ExtendedEdit DropListButton ChoiceButton ChoiceButtonRepresentation ClearButton SpinButton OpenButton CreateButton Mask ListChoiceMode ExtendedEditMultipleValues AutoChoiceIncomplete Format MultipleValuePictureShape QuickChoice ChoiceFoldersAndItems EditFormat AutoMarkIncomplete ChooseType AutoShowOpenButtonMode IncompleteChoiceMode ShowCheckBoxesInDropList MultipleValueDataPath MultipleValuePictureDataPath MultipleValuePresentDataPath SpellCheckingOnTextInput TypeDomainEnabled TextEdit AvailableTypes ChoiceForm ChoiceParameterLinks ChoiceParameters EditTextUpdate MinValue ChoiceButtonPicture MaxValue ChoiceList AutoCorrectionOnTextInput AutoShowClearButtonMode ChoiceListButton ChoiceListHeight DropListWidth TextColor BackColor BorderColor Font HeightControlVariant SpecialTextInputMode InputHint ChoiceHistoryOnInput TypeLink ContextMenu ExtendedTooltip Events'
- 'LabelDecoration' = 'UserVisible Visible Enabled Width AutoMaxWidth MaxWidth Height AutoMaxHeight MaxHeight HorizontalStretch VerticalStretch SkipOnInput TextColor Font Shortcut Title ToolTip ToolTipRepresentation GroupHorizontalAlign GroupVerticalAlign Hyperlink HorizontalAlign VerticalAlign BackColor BorderColor Border TitleHeight ContextMenu ExtendedTooltip Events'
- 'LabelField' = 'DataPath Visible Enabled UserVisible DefaultItem ReadOnly SkipOnInput Title TitleTextColor TitleFont TitleLocation TitleHeight ToolTip ToolTipRepresentation HorizontalAlign VerticalAlign GroupHorizontalAlign GroupVerticalAlign WarningOnEditRepresentation WarningOnEdit EditMode FixingInTable CellHyperlink AutoCellHeight FooterText ShowInHeader HeaderHorizontalAlign FooterDataPath HeaderPicture ShowInFooter FooterHorizontalAlign Width AutoMaxWidth MaxWidth Height AutoMaxHeight MaxHeight HorizontalStretch MarkNegatives VerticalStretch Format Border BorderColor Hiperlink PasswordMode TextColor BackColor Font ContextMenu ExtendedTooltip Events'
- 'Page' = 'Visible Enabled ReadOnly EnableContentChange UserVisible Title GroupVerticalAlign Shortcut TitleTextColor TitleFont ToolTip ToolTipRepresentation Width Height HorizontalStretch VerticalStretch ChildrenAlign Picture Format Group ChildItemsWidth HorizontalSpacing VerticalSpacing HorizontalAlign VerticalAlign ShowTitle BackColor TitleDataPath ScrollOnCompress ExtendedTooltip ChildItems'
- 'Pages' = 'Enabled ReadOnly EnableContentChange UserVisible Visible Title TitleFont ToolTip ToolTipRepresentation Width Height HorizontalStretch VerticalStretch GroupHorizontalAlign GroupVerticalAlign PagesRepresentation CurrentRowUse ExtendedTooltip Events ChildItems'
- 'PeriodField' = 'DataPath TitleLocation ContextMenu ExtendedTooltip'
- 'PictureDecoration' = 'Enabled Visible Width AutoMaxWidth MaxWidth Height AutoMaxHeight MaxHeight HorizontalStretch VerticalStretch SkipOnInput TextColor Font Title ToolTip ToolTipRepresentation GroupHorizontalAlign GroupVerticalAlign Hyperlink PictureSize Zoomable ImageScale NonselectedPictureText EnableStartDrag EnableDrag Picture BorderColor Border FileDragMode ContextMenu ExtendedTooltip Events'
- 'PictureField' = 'DataPath TitleBackColor UserVisible Visible Enabled ReadOnly SkipOnInput Title TitleTextColor TitleLocation TitleHeight ToolTip GroupHorizontalAlign GroupVerticalAlign Shortcut ToolTipRepresentation HorizontalAlign WarningOnEditRepresentation EditMode AutoCellHeight FixingInTable CellHyperlink ShowInHeader FooterDataPath HeaderPicture FooterText HeaderHorizontalAlign ShowInFooter FooterHorizontalAlign Width AutoMaxWidth MaxWidth Height AutoMaxHeight MaxHeight HorizontalStretch VerticalStretch PictureSize Zoomable Hyperlink NonselectedPictureText EnableDrag TextColor ValuesPicture BorderColor Border Font FileDragMode ContextMenu ExtendedTooltip Events'
- 'PlannerField' = 'DataPath TitleLocation ContextMenu ExtendedTooltip Events'
- 'Popup' = 'UserVisible Visible EnableContentChange Title Shape TitleTextColor TitleFont ToolTip ToolTipRepresentation VerticalStretch Width HorizontalStretch Picture CommandSource Representation BackColor ShapeRepresentation BorderColor ExtendedTooltip ChildItems'
- 'ProgressBarField' = 'DataPath Title Visible ReadOnly TitleLocation ToolTip ToolTipRepresentation Width AutoMaxHeight AutoMaxWidth HorizontalStretch MaxValue ShowPercent ContextMenu ExtendedTooltip'
- 'RadioButtonField' = 'DataPath DefaultItem Enabled SkipOnInput UserVisible Visible ReadOnly Title TitleTextColor TitleFont TitleLocation FooterHorizontalAlign TitleHeight ToolTip ToolTipRepresentation EditMode GroupHorizontalAlign Shortcut VerticalAlign GroupVerticalAlign WarningOnEditRepresentation WarningOnEdit RadioButtonType ItemHeight ItemTitleHeight ItemWidth ColumnsCount EqualColumnsWidth ChoiceList Font TextColor ContextMenu ExtendedTooltip Events'
- 'SpreadSheetDocumentField' = 'DataPath Enabled ReadOnly SkipOnInput UserVisible Visible DefaultItem Title TitleLocation DrawingSelectionShowMode FooterHorizontalAlign GroupHorizontalAlign ToolTip ToolTipRepresentation CommandSet Width AutoMaxWidth MaxWidth Height AutoMaxHeight MaxHeight HorizontalStretch VerticalStretch ShowGrid ShowHeaders VerticalScrollBar HorizontalScrollBar Protection SelectionShowMode Edit Output PointerType ShowGroups EnableStartDrag EnableDrag BorderColor ShowCellNames ShowRowAndColumnNames ViewScalingMode ContextMenu ExtendedTooltip Events'
- 'Table' = 'Representation Visible UserVisible TitleLocation CommandBarLocation Autofill Enabled TitleHeight ReadOnly SkipOnInput DefaultItem ChangeRowSet ChangeRowOrder Width AutoMaxWidth MaxWidth Height AutoMaxHeight MaxHeight HeightInTableRows HeightControlVariant AutoMaxRowsCount MaxRowsCount ChoiceMode MultipleChoice RowInputMode SelectionMode RowSelectionMode Header FooterHeight HeaderHeight Footer HorizontalScrollBar VerticalScrollBar HorizontalLines VerticalLines UseAlternationRowColor AutoInsertNewRow AutoAddIncomplete AutoMarkIncomplete SearchOnInput InitialListView InitialTreeView HorizontalStretch Output VerticalStretch EnableStartDrag EnableDrag FileDragMode DataPath Font RowPictureDataPath RowsPicture BackColor BorderColor TextColor Title BehaviorOnHorizontalCompression GroupVerticalAlign Shortcut TitleTextColor TitleFont CommandSet ToolTip ToolTipRepresentation SearchStringLocation ViewStatusLocation SearchControlLocation GroupHorizontalAlign CurrentRowUse RefreshRequest AutoRefresh AutoRefreshPeriod Period ChoiceFoldersAndItems RestoreCurrentRow RowFilter TopLevelParent ShowRoot AllowRootChoice UpdateOnDataChange UserSettingsGroup AllowGettingCurrentRowURL ViewMode SettingsNamedItemDetailedRepresentation ContextMenu AutoCommandBar ExtendedTooltip SearchStringAddition ViewStatusAddition SearchControlAddition Events ChildItems'
- 'TextDocumentField' = 'DataPath DefaultItem ReadOnly Title TitleFont TitleLocation EditMode ToolTip Width AutoMaxWidth Font MaxWidth Height AutoMaxHeight ContextMenu ExtendedTooltip Events'
- 'TrackBarField' = 'DataPath Title TitleLocation HorizontalAlign ToolTip ToolTipRepresentation Width AutoMaxWidth HorizontalStretch MaxWidth Height AutoMaxHeight MinValue MarkingAppearance MaxValue LargeStep Step MarkingStep ContextMenu ExtendedTooltip Events'
- 'UsualGroup' = 'UserVisible Visible Enabled ReadOnly EnableContentChange Title TitleTextColor TitleFont ToolTip ToolTipRepresentation Shortcut Width Height HorizontalStretch VerticalStretch GroupHorizontalAlign GroupVerticalAlign Group ChildrenAlign HorizontalSpacing VerticalSpacing HorizontalAlign VerticalAlign Behavior CollapsedRepresentationTitle Collapsed ControlRepresentation Representation CurrentRowUse Format ShowLeftMargin United ChildItemsWidth ShowTitle BackColor ThroughAlign TitleDataPath ExtendedTooltip Events ChildItems'
- }
- $script:childRank = $null
- $script:appearanceSpec = @{
- titleTextColor = @{ tag='TitleTextColor'; kind='color' }
- titleBackColor = @{ tag='TitleBackColor'; kind='color' }
- titleFont = @{ tag='TitleFont'; kind='font' }
- footerTextColor = @{ tag='FooterTextColor'; kind='color' }
- footerBackColor = @{ tag='FooterBackColor'; kind='color' }
- footerFont = @{ tag='FooterFont'; kind='font' }
- textColor = @{ tag='TextColor'; kind='color' }
- backColor = @{ tag='BackColor'; kind='color' }
- borderColor = @{ tag='BorderColor'; kind='color' }
- border = @{ tag='Border'; kind='border'}
- font = @{ tag='Font'; kind='font' }
- }
- $script:appearanceSynonyms = @{
- 'цветтекста'='textColor'; 'цветфона'='backColor'; 'цветрамки'='borderColor'
- 'цветтекстазаголовка'='titleTextColor'; 'цветфоназаголовка'='titleBackColor'; 'шрифтзаголовка'='titleFont'
- 'цветтекстаподвала'='footerTextColor'; 'цветфонаподвала'='footerBackColor'; 'шрифтподвала'='footerFont'
- 'шрифт'='font'; 'рамка'='border'
- }
- $script:propSynonyms = @{
- 'пометка'='checked'
- 'кнопкавыбора'='choiceButton'; 'кнопкаочистки'='clearButton'; 'кнопкарегулирования'='spinButton'
- 'кнопкавыпадающегосписка'='dropListButton'; 'кнопкасписковоговыбора'='choiceListButton'
- 'кнопкаоткрытия'='openButton'; 'кнопкапоумолчанию'='defaultButton'
- 'быстрыйвыбор'='quickChoice'; 'формавыбора'='choiceForm'; 'историявыборапривводе'='choiceHistoryOnInput'
- 'выборгруппиэлементов'='choiceFoldersAndItems'; 'фиксациявтаблице'='fixingInTable'
- 'путькданнымподвала'='footerDataPath'; 'автоотметканезаполненного'='markIncomplete'
- 'многострочныйрежим'='multiLine'; 'режимпароля'='passwordMode'; 'переноспословам'='wrap'
- 'расположениезаголовка'='titleLocation'; 'пропускатьпривводе'='skipOnInput'
- 'заголовок'='title'; 'ширина'='width'; 'высота'='height'; 'подсказкаввода'='inputHint'
- }
- $script:appOrderField = @('titleTextColor','titleBackColor','titleFont','footerTextColor','footerBackColor','footerFont','textColor','backColor','borderColor','border','font')
- $script:appOrderDecoration = @('textColor','font','backColor','borderColor','border')
- $script:appOrderButton = @('textColor','backColor','borderColor','font')
- $script:genericScalars = @(
- @{ Tag='VerticalAlign'; Key='verticalAlign'; Kind='value' }
- @{ Tag='ThroughAlign'; Key='throughAlign'; Kind='value' }
- @{ Tag='EnableContentChange'; Key='enableContentChange'; Kind='bool' }
- @{ Tag='PictureSize'; Key='pictureSize'; Kind='value' }
- @{ Tag='TitleHeight'; Key='titleHeight'; Kind='value' }
- @{ Tag='ChildItemsWidth'; Key='childItemsWidth'; Kind='value' }
- @{ Tag='ShowLeftMargin'; Key='showLeftMargin'; Kind='bool' }
- @{ Tag='CellHyperlink'; Key='cellHyperlink'; Kind='bool' }
- @{ Tag='ViewMode'; Key='viewMode'; Kind='value' }
- @{ Tag='VerticalScrollBar'; Key='verticalScrollBar'; Kind='value' }
- @{ Tag='RowInputMode'; Key='rowInputMode'; Kind='value' }
- @{ Tag='Mask'; Key='mask'; Kind='value' }
- @{ Tag='CreateButton'; Key='createButton'; Kind='bool' }
- @{ Tag='FixingInTable'; Key='fixingInTable'; Kind='value' }
- @{ Tag='VerticalSpacing'; Key='verticalSpacing'; Kind='value' }
- # Спец-поля (документ/датчик) — типоспец. enum/bool скаляры pass-through
- @{ Tag='HorizontalScrollBar'; Key='horizontalScrollBar'; Kind='value' }
- @{ Tag='ViewScalingMode'; Key='viewScalingMode'; Kind='value' }
- @{ Tag='Output'; Key='output'; Kind='value' }
- @{ Tag='SelectionShowMode'; Key='selectionShowMode'; Kind='value' }
- @{ Tag='PointerType'; Key='pointerType'; Kind='value' }
- @{ Tag='DrawingSelectionShowMode'; Key='drawingSelectionShowMode'; Kind='value' }
- @{ Tag='WarningOnEditRepresentation'; Key='warningOnEditRepresentation'; Kind='value' }
- @{ Tag='MarkingAppearance'; Key='markingAppearance'; Kind='value' }
- @{ Tag='Protection'; Key='protection'; Kind='bool' }
- @{ Tag='Edit'; Key='edit'; Kind='bool' }
- @{ Tag='ShowGrid'; Key='showGrid'; Kind='bool' }
- @{ Tag='ShowGroups'; Key='showGroups'; Kind='bool' }
- @{ Tag='ShowHeaders'; Key='showHeaders'; Kind='bool' }
- @{ Tag='ShowRowAndColumnNames'; Key='showRowAndColumnNames'; Kind='bool' }
- @{ Tag='ShowCellNames'; Key='showCellNames'; Kind='bool' }
- @{ Tag='ShowPercent'; Key='showPercent'; Kind='bool' }
- # Report-form контекст: интервал группы / представление кнопки в контекстном меню / детальное представление настройки таблицы
- @{ Tag='HorizontalSpacing'; Key='horizontalSpacing'; Kind='value' }
- @{ Tag='RepresentationInContextMenu'; Key='representationInContextMenu'; Kind='value' }
- @{ Tag='SettingsNamedItemDetailedRepresentation'; Key='settingsNamedItemDetailedRepresentation'; Kind='bool' }
- # Хвост: высота элемента списка (radio) / ширина выпадающего списка (input)
- @{ Tag='ItemHeight'; Key='itemHeight'; Kind='value' }
- @{ Tag='DropListWidth'; Key='dropListWidth'; Kind='value' }
- # Хвост CI-форм: динамический заголовок (Page/Group) / расширенное ред. (input) / высота таблицы по строкам
- @{ Tag='TitleDataPath'; Key='titleDataPath'; Kind='value' }
- @{ Tag='ExtendedEdit'; Key='extendedEdit'; Kind='bool' }
- @{ Tag='MaxRowsCount'; Key='maxRowsCount'; Kind='value' }
- @{ Tag='AutoMaxRowsCount'; Key='autoMaxRowsCount'; Kind='bool' }
- @{ Tag='HeightControlVariant'; Key='heightControlVariant'; Kind='value' }
- @{ Tag='EditTextUpdate'; Key='editTextUpdate'; Kind='value' }
- # Корпусный хвост: представление управления свёрткой группы / форма кнопки-попапа /
- # авто-добавление незаполненной строки / выделение отрицательных / нач. позиция списка /
- # высота списка выбора / три состояния флажка / прокрутка страницы при сжатии
- @{ Tag='ControlRepresentation'; Key='controlRepresentation'; Kind='value' }
- @{ Tag='ShapeRepresentation'; Key='shapeRepresentation'; Kind='value' }
- @{ Tag='AutoAddIncomplete'; Key='autoAddIncomplete'; Kind='bool' }
- @{ Tag='MarkNegatives'; Key='markNegatives'; Kind='bool' }
- @{ Tag='InitialListView'; Key='initialListView'; Kind='value' }
- @{ Tag='ChoiceListHeight'; Key='choiceListHeight'; Kind='value' }
- @{ Tag='ThreeState'; Key='threeState'; Kind='bool' }
- @{ Tag='ScrollOnCompress'; Key='scrollOnCompress'; Kind='bool' }
- # Сочетание клавиш — общее свойство (input/group/radio/page/picField/label/table/check; команда — отд. путь, §7)
- @{ Tag='Shortcut'; Key='shortcut'; Kind='value' }
- # Батч простых скаляров (input/radio/group/picDecoration/button): режим выбора незаполненного,
- # равная ширина колонок, выравнивание детей, масштаб/зум картинки, форма/положение картинки кнопки.
- # (Table HeaderHeight/FooterHeight/CurrentRowUse — НЕ здесь, а в Emit-Table: pass-through,
- # 1С толерантна к порядку детей Table — в корпусе те же теги встречаются в разных позициях.)
- @{ Tag='IncompleteChoiceMode'; Key='incompleteChoiceMode'; Kind='value' }
- @{ Tag='EqualColumnsWidth'; Key='equalColumnsWidth'; Kind='bool' }
- @{ Tag='ChildrenAlign'; Key='childrenAlign'; Kind='value' }
- @{ Tag='ImageScale'; Key='imageScale'; Kind='value' }
- @{ Tag='Zoomable'; Key='zoomable'; Kind='bool' }
- @{ Tag='Shape'; Key='shape'; Kind='value' }
- @{ Tag='PictureLocation'; Key='pictureLocation'; Kind='value' }
- # Равная ширина элементов (check/radio) / высота заголовка пункта (radio)
- @{ Tag='EqualItemsWidth'; Key='equalItemsWidth'; Kind='bool' }
- @{ Tag='ItemTitleHeight'; Key='itemTitleHeight'; Kind='value' }
- # Спец-режим ввода текста (input, моб.: Email/PhoneNumber/...) — листовой enum-скаляр
- @{ Tag='SpecialTextInputMode'; Key='specialTextInputMode'; Kind='value' }
- # Ширина пункта (radio/check) / выбор нескольких значений из выпадающего (input)
- @{ Tag='ItemWidth'; Key='itemWidth'; Kind='value' }
- @{ Tag='ShowCheckBoxesInDropList'; Key='showCheckBoxesInDropList'; Kind='bool' }
- @{ Tag='MultipleValueDataPath'; Key='multipleValueDataPath'; Kind='value' }
- @{ Tag='MultipleValuePresentDataPath'; Key='multipleValuePresentDataPath'; Kind='value' }
- # Режим авто-показа кнопок открытия/очистки (input, enum Auto/Always/FilledOnly/…)
- @{ Tag='AutoShowOpenButtonMode'; Key='autoShowOpenButtonMode'; Kind='value' }
- @{ Tag='AutoShowClearButtonMode'; Key='autoShowClearButtonMode'; Kind='value' }
- # Оформление/картинка множественного выбора (input, редко; цвета — текст-контент, не атрибуты)
- @{ Tag='MultipleValuesTextColor'; Key='multipleValuesTextColor'; Kind='value' }
- @{ Tag='MultipleValuesBackColor'; Key='multipleValuesBackColor'; Kind='value' }
- @{ Tag='MultipleValuePictureShape'; Key='multipleValuePictureShape'; Kind='value' }
- @{ Tag='MultipleValuePictureDataPath'; Key='multipleValuePictureDataPath'; Kind='value' }
- # Хвост листовых скаляров (по 1 в корпусе): автокоррекция ввода (input) / уникальность команды
- # (button) / допуск пустого множ. значения (input) / поведение при гориз. сжатии (table)
- @{ Tag='AutoCorrectionOnTextInput'; Key='autoCorrectionOnTextInput'; Kind='value' }
- @{ Tag='SpellCheckingOnTextInput'; Key='spellCheckingOnTextInput'; Kind='value' }
- @{ Tag='CommandUniqueness'; Key='commandUniqueness'; Kind='bool' }
- @{ Tag='AllowInputEmptyMultipleValues';Key='allowInputEmptyMultipleValues';Kind='bool' }
- @{ Tag='BehaviorOnHorizontalCompression'; Key='behaviorOnHorizontalCompression'; Kind='value' }
- )
- $script:PLANNER_NS = 'http://v8.1c.ru/8.3/data/planner'
- $script:CHART_NS = 'http://v8.1c.ru/8.2/data/chart'
- $script:CHART_ML_FIELDS = @{ 'title'=1;'lbFormat'=1;'lbpFormat'=1;'vsFormat'=1;'dtFormat'=1;'dataSourceDescription'=1;'labelFormat'=1;'text'=1 }
- $script:CHART_ATTR_FIELDS = @{ 'gaugeQualityBands'=1 }
- $script:CHART_FONT_KEYS = @('ref','faceName','height','bold','italic','underline','strikeout','kind','scale')
- $script:refRootSynonyms = @{
- "Перечисление" = "Enum"
- "Справочник" = "Catalog"
- "Документ" = "Document"
- "ПланСчетов" = "ChartOfAccounts"
- "ПланВидовХарактеристик" = "ChartOfCharacteristicTypes"
- "ПланВидовРасчета" = "ChartOfCalculationTypes"
- "ПланВидовРасчёта" = "ChartOfCalculationTypes"
- "ПланОбмена" = "ExchangePlan"
- "БизнесПроцесс" = "BusinessProcess"
- "Задача" = "Task"
- "РегистрСведений" = "InformationRegister"
- "РегистрНакопления" = "AccumulationRegister"
- "РегистрБухгалтерии" = "AccountingRegister"
- "РегистрРасчета" = "CalculationRegister"
- "РегистрРасчёта" = "CalculationRegister"
- "ЖурналДокументов" = "DocumentJournal"
- "КритерийОтбора" = "FilterCriterion"
- }
- $script:enumValueSynonyms = @("EnumValue","ЗначениеПеречисления")
- # Значение ссылки в dcscor:DesignTimeValue (отборы, параметры) — к виду Конфигуратора:
- # "Enum.X.EnumValue.Y" / "Enum.X.Y" → "Перечисление.X.Y", "Catalog.X.EmptyRef" → "Справочник.X.ПустаяСсылка".
- # Вид с сегментом EnumValue платформа не разрешает: сравнение с ним всегда ложно (замер 8.3.24).
- $script:designTimeRefRoots = @{
- "Enum" = "Перечисление"; "Catalog" = "Справочник"; "Document" = "Документ"; "ChartOfAccounts" = "ПланСчетов"
- "ChartOfCharacteristicTypes" = "ПланВидовХарактеристик"; "ChartOfCalculationTypes" = "ПланВидовРасчета"
- "ExchangePlan" = "ПланОбмена"; "BusinessProcess" = "БизнесПроцесс"; "Task" = "Задача"
- }
- function Normalize-DesignTimeValue([string]$v) {
- $parts = @($v -split '\.')
- if ($parts.Count -lt 3) { return $v }
- if ($script:designTimeRefRoots.ContainsKey($parts[0])) { $parts[0] = $script:designTimeRefRoots[$parts[0]] }
- if ($parts[0] -ceq 'Перечисление' -and $parts.Count -ge 4 -and $script:enumValueSynonyms -contains $parts[2]) {
- $parts = @($parts[0], $parts[1]) + $parts[3..($parts.Count - 1)]
- }
- if ($parts[-1] -ceq 'EmptyRef') { $parts[-1] = 'ПустаяСсылка' }
- return ($parts -join '.')
- }
- $script:formRootTagOrder = 'Title Width Height WindowOpeningMode EnterKeyBehavior AutoSaveDataInSettings SaveDataInSettings SaveWindowSettings SettingsStorage AutoTitle AutoURL Group HorizontalAlign ChildItemsWidth VerticalAlign HorizontalSpacing VerticalSpacing AutoFillCheck Customizable Enabled ChildrenAlign CommandBarLocation VerticalScroll ScalingMode ConversationsRepresentation MobileDeviceCommandBarContent CommandSet AutoTime UsePostingMode RepostOnWrite ReportResult DetailsData ReportFormType ShowTitle ShowCloseButton GroupList CollapseItemsByImportanceVariant UseForFoldersAndItems VariantAppearance AutoShowState CustomSettingsFolder ReportResultViewMode ViewModeApplicationOnSetReportResult Scale AutoCommandBar Events ChildItems Attributes Commands Parameters CommandInterface BaseForm'
- function Resolve-TextFromFile {
- param([string]$val, [string]$baseDir)
- if (-not $val.StartsWith("@")) { return $val }
- $filePath = $val.Substring(1)
- if ([System.IO.Path]::IsPathRooted($filePath)) {
- $candidates = @($filePath)
- } else {
- $candidates = @(
- (Join-Path $baseDir $filePath),
- (Join-Path (Get-Location).ProviderPath $filePath)
- )
- }
- foreach ($c in $candidates) {
- if (Test-Path $c) {
- return (Get-Content -Raw -Encoding UTF8 $c).TrimEnd()
- }
- }
- Write-Error "Файл значения не найден: $filePath (искали: $($candidates -join ', '))"
- exit 1
- }
- function Assert-UniqueName {
- param([string]$name, [hashtable]$seen, [string]$kind)
- if ($seen.ContainsKey($name)) {
- Write-Error "Duplicate $kind name '$name' — names must be unique within their collection in a 1C form (set a unique 'name')"
- exit 1
- }
- $seen[$name] = $true
- }
- function Esc-Xml {
- param([string]$s)
- # Эскейп ЗНАЧЕНИЯ АТРИБУТА: & < > и кавычка — внутри "..." литеральная " невалидна.
- return $s.Replace('&','&').Replace('<','<').Replace('>','>').Replace('"','"')
- }
- function Esc-XmlText {
- # Экранирование ТЕКСТА элемента (<v8:content>, <Value>): только & < > .
- # Кавычки/апострофы в тексте экранировать НЕ нужно (1С их не экранирует — пишет литерально);
- # " ломал бы раундтрип. Кавычки спецсимвольны лишь в значениях атрибутов.
- param([string]$s)
- return $s.Replace('&','&').Replace('<','<').Replace('>','>')
- }
- function Emit-MLItems {
- param($val, [string]$indent)
- if ($val -is [System.Collections.IDictionary]) {
- foreach ($k in $val.Keys) {
- X "$indent<v8:item>"; X "$indent`t<v8:lang>$k</v8:lang>"; X "$indent`t<v8:content>$(Esc-XmlText "$($val[$k])")</v8:content>"; X "$indent</v8:item>"
- }
- } elseif ($val -is [System.Management.Automation.PSCustomObject]) {
- foreach ($p in $val.PSObject.Properties) {
- X "$indent<v8:item>"; X "$indent`t<v8:lang>$($p.Name)</v8:lang>"; X "$indent`t<v8:content>$(Esc-XmlText "$($p.Value)")</v8:content>"; X "$indent</v8:item>"
- }
- } else {
- X "$indent<v8:item>"; X "$indent`t<v8:lang>ru</v8:lang>"; X "$indent`t<v8:content>$(Esc-XmlText "$val")</v8:content>"; X "$indent</v8:item>"
- }
- }
- function Emit-MLText {
- param([string]$tag, $text, [string]$indent, [string]$xsiType)
- $attr = if ($xsiType) { " xsi:type=`"$xsiType`"" } else { "" }
- X "$indent<$tag$attr>"
- Emit-MLItems -val $text -indent "$indent`t"
- X "$indent</$tag>"
- }
- function Emit-USPresentation {
- param($val, [string]$tag, [string]$indent)
- if ($null -eq $val) { return }
- if ($val -is [string]) {
- X "$indent<$tag xsi:type=`"xs:string`">$(Esc-XmlText $val)</$tag>"
- } else {
- Emit-MLText -tag $tag -text $val -indent $indent -xsiType "v8:LocalStringType"
- }
- }
- function Test-HasRealMarkup {
- param($text)
- if ($null -eq $text) { return $false }
- $vals = if ($text -is [System.Collections.IDictionary]) { @($text.Values) }
- elseif ($text -is [System.Management.Automation.PSCustomObject]) { @($text.PSObject.Properties.Value) }
- else { @("$text") }
- foreach ($v in $vals) { if ("$v" -match $script:fmtMarkupRe) { return $true } }
- return $false
- }
- function Resolve-MLFormatted {
- param($val)
- $hasText = $false
- if ($val -is [System.Management.Automation.PSCustomObject]) { $hasText = [bool]$val.PSObject.Properties['text'] }
- elseif ($val -is [System.Collections.IDictionary]) { $hasText = $val.Contains('text') }
- if ($hasText) {
- $t = if ($val -is [System.Collections.IDictionary]) { $val['text'] } else { $val.text }
- $f = if ($val -is [System.Collections.IDictionary]) { $val['formatted'] } else { $val.formatted }
- return @{ text = $t; formatted = (ConvertTo-DslBool $f 'formatted' $false) }
- }
- return @{ text = $val; formatted = (Test-HasRealMarkup $val) }
- }
- function New-Guid-String { return [System.Guid]::NewGuid().ToString() }
- function Parse-FilterShorthand {
- param([string]$s)
- $result = @{ field = ""; op = "Equal"; value = $null; use = $true; userSettingID = $null; viewMode = $null; presentation = $null }
- if ($s -match '@user') { $result.userSettingID = "auto"; $s = $s -replace '\s*@user', '' }
- if ($s -match '@off') { $result.use = $false; $s = $s -replace '\s*@off', '' }
- if ($s -match '@quickAccess') { $result.viewMode = "QuickAccess"; $s = $s -replace '\s*@quickAccess', '' }
- if ($s -match '@normal') { $result.viewMode = "Normal"; $s = $s -replace '\s*@normal', '' }
- if ($s -match '@inaccessible') { $result.viewMode = "Inaccessible"; $s = $s -replace '\s*@inaccessible', '' }
- $s = $s.Trim()
- $opPatterns = @('<>', '>=', '<=', '=', '>', '<',
- 'notIn\b', 'in\b', 'inHierarchy\b', 'inListByHierarchy\b',
- 'notContains\b', 'contains\b', 'notBeginsWith\b', 'beginsWith\b',
- 'notLike\b', 'like\b', 'неподобно\b', 'подобно\b',
- 'notFilled\b', 'filled\b')
- $opJoined = $opPatterns -join '|'
- if ($s -match "^(.+?)\s+($opJoined)\s*(.*)?$") {
- $result.field = $Matches[1].Trim()
- $result.op = $Matches[2].Trim()
- $valPart = if ($Matches[3]) { $Matches[3].Trim() } else { "" }
- if ($valPart -and $valPart -ne "_") {
- if ($valPart -eq "true" -or $valPart -eq "false") { $result.value = [bool]($valPart -eq "true"); $result["valueType"] = "xs:boolean" }
- elseif ($valPart -match '^\d{4}-\d{2}-\d{2}T') { $result.value = $valPart } # дата без valueType → Emit-FilterItem выведет StandardBeginningDate Custom (дефолт даты в фильтре)
- elseif ($valPart -match '^\d+(\.\d+)?$') { $result.value = $valPart; $result["valueType"] = "xs:decimal" }
- elseif ($valPart -match '^(Перечисление|Справочник|ПланСчетов|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|ПланОбмена|Enum|Catalog|Document|ChartOfAccounts|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|ExchangePlan)\.[^.]+\.[^.]+') { $result.value = $valPart; $result["valueType"] = "dcscor:DesignTimeValue" }
- else { $result.value = $valPart; $result["valueType"] = "xs:string" }
- }
- } else { $result.field = $s }
- return $result
- }
- function Get-ValueTypeNsAttr {
- param([string]$valueType, [string]$value)
- if ($valueType -eq 'v8:Type' -and "$value" -match '^([A-Za-z]\w*):') {
- $pref = $Matches[1]
- if ($pref -notin @('xs','cfg','v8','v8ui','ent','dcscor','dcsset','dcssch')) {
- return " xmlns:$pref=`"http://v8.1c.ru/8.2/data/types`""
- }
- }
- return ""
- }
- function Emit-FilterItem {
- param($item, [string]$indent)
- if ($item.group) {
- $groupType = switch ("$($item.group)") { "And" { "AndGroup" } "Or" { "OrGroup" } "Not" { "NotGroup" } default { "$($item.group)Group" } }
- X "$indent<dcsset:item xsi:type=`"dcsset:FilterItemGroup`">"
- if ((-not (Get-DslBool $item @('use') $true))) { X "$indent`t<dcsset:use>false</dcsset:use>" } # группа отключена (перед groupType, порядок исходника)
- X "$indent`t<dcsset:groupType>$groupType</dcsset:groupType>"
- if ($item.items) {
- foreach ($sub in $item.items) {
- if ($sub -is [string]) {
- $parsed = Parse-FilterShorthand $sub
- $obj = @{ field = $parsed.field; op = $parsed.op }
- if ((-not (Get-DslBool $parsed @('use') $true))) { $obj.use = $false }
- if ($null -ne $parsed.value) { $obj.value = $parsed.value }
- if ($parsed["valueType"]) { $obj.valueType = $parsed["valueType"] }
- if ($parsed.userSettingID) { $obj.userSettingID = $parsed.userSettingID }
- if ($parsed.viewMode) { $obj.viewMode = $parsed.viewMode }
- $sub = [pscustomobject]$obj
- }
- Emit-FilterItem -item $sub -indent "$indent`t"
- }
- }
- if ($item.presentation) { Emit-USPresentation -val $item.presentation -tag "dcsset:presentation" -indent "$indent`t" }
- if ($item.viewMode) { X "$indent`t<dcsset:viewMode>$(Esc-XmlText "$($item.viewMode)")</dcsset:viewMode>" }
- if ($item.userSettingID) {
- $guid = if ("$($item.userSettingID)" -eq "auto") { New-Guid-String } else { "$($item.userSettingID)" }
- X "$indent`t<dcsset:userSettingID>$(Esc-XmlText $guid)</dcsset:userSettingID>"
- }
- if ($item.userSettingPresentation) { Emit-USPresentation -val $item.userSettingPresentation -tag "dcsset:userSettingPresentation" -indent "$indent`t" }
- X "$indent</dcsset:item>"
- return
- }
- X "$indent<dcsset:item xsi:type=`"dcsset:FilterItemComparison`">"
- if ((-not (Get-DslBool $item @('use') $true))) { X "$indent`t<dcsset:use>false</dcsset:use>" }
- X "$indent`t<dcsset:left xsi:type=`"dcscor:Field`">$(Esc-XmlText "$($item.field)")</dcsset:left>"
- $compType = $script:comparisonTypes["$($item.op)"]
- if (-not $compType) { $compType = "$($item.op)" }
- X "$indent`t<dcsset:comparisonType>$(Esc-XmlText $compType)</dcsset:comparisonType>"
- $valIsArray = ($item.value -is [array]) -or ($item.value -is [System.Collections.IList] -and $item.value -isnot [string])
- if ($valIsArray) {
- if (@($item.value).Count -eq 0) {
- X "$indent`t<dcsset:right xsi:type=`"v8:ValueListType`">"
- X "$indent`t`t<v8:valueType/>"
- X "$indent`t`t<v8:lastId xsi:type=`"xs:decimal`">-1</v8:lastId>"
- X "$indent`t</dcsset:right>"
- } else {
- foreach ($v in $item.value) {
- $vt = if ($item.valueType) { "$($item.valueType)" } else { "" }
- if (-not $vt) {
- if ($v -is [bool]) { $vt = 'xs:boolean' }
- elseif ($v -is [int] -or $v -is [long] -or $v -is [double]) { $vt = 'xs:decimal' }
- elseif ("$v" -match '^\d{4}-\d{2}-\d{2}T') { $vt = 'xs:dateTime' }
- elseif ("$v" -match '^-?\d+(\.\d+)?$') { $vt = 'xs:decimal' }
- elseif ("$v" -match '^(Перечисление|Справочник|ПланСчетов|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|РегистрСведений|ПланОбмена|Catalog|Enum|Document|ChartOfAccounts|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|InformationRegister|ExchangePlan)\.') { $vt = 'dcscor:DesignTimeValue' }
- else { $vt = 'xs:string' }
- }
- $vStr = if ($v -is [bool]) { "$v".ToLower() } elseif ($vt -eq 'dcscor:DesignTimeValue') { Esc-XmlText (Normalize-DesignTimeValue "$v") } else { Esc-XmlText "$v" }
- $nsAttr = Get-ValueTypeNsAttr -valueType $vt -value "$v"
- X "$indent`t<dcsset:right$nsAttr xsi:type=`"$vt`">$vStr</dcsset:right>"
- }
- }
- } elseif ($null -ne $item.value -and (
- "$($item.valueType)" -match 'Standard(Beginning|End)Date$' -or
- (-not $item.valueType -and "$($item.value)" -match '^\d{4}-\d{2}-\d{2}T'))) {
- # Стандартная дата начала/окончания. Формы значения:
- # объект {variant, date?} — полная (Custom несёт <v8:date>);
- # строка-вариант "BeginningOfThisDay" — именованный вариант без даты;
- # голая ISO-дата без valueType — шорткат для Custom+date (дата в фильтре платформой
- # почти всегда хранится как StandardBeginningDate Custom, корпус 268 vs 2 xs:dateTime;
- # явный valueType="xs:dateTime" → плоская дата, ветка ниже).
- $sdType = if ($item.valueType) { "$($item.valueType)" -replace '^v8:','' } else { 'StandardBeginningDate' }
- $sv = $item.value
- if (($sv -is [PSCustomObject]) -or ($sv -is [System.Collections.IDictionary])) {
- $variant = if ($sv -is [PSCustomObject]) { "$($sv.variant)" } else { "$($sv['variant'])" }
- $hasDate = if ($sv -is [PSCustomObject]) { [bool]$sv.PSObject.Properties['date'] } else { $sv.Contains('date') }
- $dateV = if ($hasDate) { if ($sv -is [PSCustomObject]) { "$($sv.date)" } else { "$($sv['date'])" } } else { $null }
- } elseif ("$sv" -match '^\d{4}-\d{2}-\d{2}T') {
- $variant = 'Custom'; $hasDate = $true; $dateV = "$sv"
- } else {
- $variant = "$sv"; $hasDate = $false; $dateV = $null
- }
- X "$indent`t<dcsset:right xsi:type=`"v8:$sdType`">"
- X "$indent`t`t<v8:variant xsi:type=`"v8:${sdType}Variant`">$(Esc-XmlText $variant)</v8:variant>"
- if ($hasDate) { X "$indent`t`t<v8:date>$(Esc-XmlText $dateV)</v8:date>" }
- X "$indent`t</dcsset:right>"
- } elseif ("$($item.value)" -eq '_') {
- # "_" — маркер пустого значения: платформа эмитит пустой self-closing <dcsset:right>
- # (напр. <dcsset:right xsi:type="dcscor:Field"/> — сравнение с незаданным полем).
- $vt = if ($item.valueType) { "$($item.valueType)" } else { 'xs:string' }
- X "$indent`t<dcsset:right xsi:type=`"$vt`"/>"
- } elseif ($null -ne $item.value) {
- $vt = if ($item.valueType) { "$($item.valueType)" } else { "" }
- if (-not $vt) {
- $v = $item.value
- if ($v -is [bool]) { $vt = "xs:boolean" }
- elseif ($v -is [int] -or $v -is [long] -or $v -is [double]) { $vt = "xs:decimal" }
- elseif ("$v" -match '^\d{4}-\d{2}-\d{2}T') { $vt = "xs:dateTime" }
- elseif ("$v" -match '^-?\d+(\.\d+)?$') { $vt = "xs:decimal" }
- elseif ("$v" -match '^(Перечисление|Справочник|ПланСчетов|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|РегистрСведений|ПланОбмена|Catalog|Enum|Document|ChartOfAccounts|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|InformationRegister|ExchangePlan)\.') { $vt = "dcscor:DesignTimeValue" }
- else { $vt = "xs:string" }
- }
- $vStr = if ($item.value -is [bool]) { "$($item.value)".ToLower() } elseif ($vt -eq 'dcscor:DesignTimeValue') { Esc-XmlText (Normalize-DesignTimeValue "$($item.value)") } else { Esc-XmlText "$($item.value)" }
- $nsAttr = Get-ValueTypeNsAttr -valueType $vt -value "$($item.value)"
- X "$indent`t<dcsset:right$nsAttr xsi:type=`"$vt`">$vStr</dcsset:right>"
- }
- if ($item.presentation) { Emit-USPresentation -val $item.presentation -tag "dcsset:presentation" -indent "$indent`t" }
- if ($item.viewMode) { X "$indent`t<dcsset:viewMode>$(Esc-XmlText "$($item.viewMode)")</dcsset:viewMode>" }
- if ($item.userSettingID) {
- $uid = if ("$($item.userSettingID)" -eq "auto") { New-Guid-String } else { "$($item.userSettingID)" }
- X "$indent`t<dcsset:userSettingID>$(Esc-XmlText $uid)</dcsset:userSettingID>"
- }
- if ($item.userSettingPresentation) { Emit-USPresentation -val $item.userSettingPresentation -tag "dcsset:userSettingPresentation" -indent "$indent`t" }
- X "$indent</dcsset:item>"
- }
- function Emit-Filter {
- param($items, [string]$indent, $blockViewMode = $null, $blockUserSettingID = $null, $blockUserSettingPresentation = $null)
- $hasItems = $items -and $items.Count -gt 0
- $hasBlockMeta = ($null -ne $blockViewMode) -or ($null -ne $blockUserSettingID) -or ($null -ne $blockUserSettingPresentation)
- if (-not $hasItems -and -not $hasBlockMeta) { return }
- X "$indent<dcsset:filter>"
- foreach ($item in $items) {
- if ($item -is [string]) {
- $parsed = Parse-FilterShorthand $item
- $obj = @{ field = $parsed.field; op = $parsed.op }
- if ((-not (Get-DslBool $parsed @('use') $true))) { $obj.use = $false }
- if ($null -ne $parsed.value) { $obj.value = $parsed.value }
- if ($parsed["valueType"]) { $obj.valueType = $parsed["valueType"] }
- if ($parsed.userSettingID) { $obj.userSettingID = $parsed.userSettingID }
- if ($parsed.viewMode) { $obj.viewMode = $parsed.viewMode }
- Emit-FilterItem -item ([pscustomobject]$obj) -indent "$indent`t"
- } else { Emit-FilterItem -item $item -indent "$indent`t" }
- }
- if ($null -ne $blockViewMode) { X "$indent`t<dcsset:viewMode>$(Esc-XmlText "$blockViewMode")</dcsset:viewMode>" }
- if ($null -ne $blockUserSettingID) {
- $uid = if ("$blockUserSettingID" -eq 'auto') { New-Guid-String } else { "$blockUserSettingID" }
- X "$indent`t<dcsset:userSettingID>$(Esc-XmlText $uid)</dcsset:userSettingID>"
- }
- if ($null -ne $blockUserSettingPresentation) { Emit-USPresentation -val $blockUserSettingPresentation -tag "dcsset:userSettingPresentation" -indent "$indent`t" }
- X "$indent</dcsset:filter>"
- }
- function Emit-Order {
- param($items, [string]$indent, [switch]$skipAuto, $blockViewMode = $null, $blockUserSettingID = $null, $blockUserSettingPresentation = $null)
- $hasItems = $items -and $items.Count -gt 0
- $hasBlockMeta = ($null -ne $blockViewMode) -or ($null -ne $blockUserSettingID) -or ($null -ne $blockUserSettingPresentation)
- if (-not $hasItems -and -not $hasBlockMeta) { return }
- X "$indent<dcsset:order>"
- foreach ($item in $items) {
- if ($item -is [string]) {
- if ($item -eq "Auto") { if (-not $skipAuto) { X "$indent`t<dcsset:item xsi:type=`"dcsset:OrderItemAuto`"/>" } }
- else {
- $parts = $item -split '\s+'
- $field = $parts[0]
- $dir = "Asc"
- if ($parts.Count -gt 1 -and $parts[1] -match '^(?i)(desc|убыв)') { $dir = "Desc" }
- elseif ($parts.Count -gt 1 -and $parts[1] -match '^(?i)(asc|возр)') { $dir = "Asc" }
- X "$indent`t<dcsset:item xsi:type=`"dcsset:OrderItemField`">"
- X "$indent`t`t<dcsset:field>$(Esc-XmlText $field)</dcsset:field>"
- X "$indent`t`t<dcsset:orderType>$dir</dcsset:orderType>"
- X "$indent`t</dcsset:item>"
- }
- } else {
- if ($item.field -eq "Auto" -or $item.type -eq "auto") { if (-not $skipAuto) { X "$indent`t<dcsset:item xsi:type=`"dcsset:OrderItemAuto`"/>" }; continue }
- $dir = if ($item.direction) { "$($item.direction)" } else { "Asc" }
- if ($dir -match '^(?i)(desc|убыв)') { $dir = "Desc" } elseif ($dir -match '^(?i)(asc|возр)') { $dir = "Asc" }
- X "$indent`t<dcsset:item xsi:type=`"dcsset:OrderItemField`">"
- if ((-not (Get-DslBool $item @('use') $true))) { X "$indent`t`t<dcsset:use>false</dcsset:use>" }
- X "$indent`t`t<dcsset:field>$(Esc-XmlText "$($item.field)")</dcsset:field>"
- X "$indent`t`t<dcsset:orderType>$dir</dcsset:orderType>"
- if ($item.viewMode) { X "$indent`t`t<dcsset:viewMode>$(Esc-XmlText "$($item.viewMode)")</dcsset:viewMode>" }
- X "$indent`t</dcsset:item>"
- }
- }
- if ($null -ne $blockViewMode) { X "$indent`t<dcsset:viewMode>$(Esc-XmlText "$blockViewMode")</dcsset:viewMode>" }
- if ($null -ne $blockUserSettingID) {
- $uid = if ("$blockUserSettingID" -eq 'auto') { New-Guid-String } else { "$blockUserSettingID" }
- X "$indent`t<dcsset:userSettingID>$(Esc-XmlText $uid)</dcsset:userSettingID>"
- }
- if ($null -ne $blockUserSettingPresentation) { Emit-USPresentation -val $blockUserSettingPresentation -tag "dcsset:userSettingPresentation" -indent "$indent`t" }
- X "$indent</dcsset:order>"
- }
- function Emit-AppearanceValue {
- param([string]$key, $val, [string]$indent)
- X "$indent<dcscor:item xsi:type=`"dcsset:SettingsParameterValue`">"
- function _HasKey { param($o, [string]$k)
- if ($o -is [PSCustomObject]) { return [bool]$o.PSObject.Properties[$k] }
- if ($o -is [System.Collections.IDictionary]) { return $o.Contains($k) }
- return $false
- }
- function _Get { param($o, [string]$k)
- if ($o -is [PSCustomObject]) { return $o.$k }
- if ($o -is [System.Collections.IDictionary]) { return $o[$k] }
- return $null
- }
- $isTopLevelLine = (_HasKey $val '@type') -and ("$(_Get $val '@type')" -eq 'Line')
- $useWrapper = $false
- $innerVal = $val
- $nestedItems = $null
- if ($isTopLevelLine) {
- if ((_HasKey $val 'use') -and -not (ConvertTo-DslBool (_Get $val 'use') 'use' $true)) { $useWrapper = $true }
- if (_HasKey $val 'items') { $nestedItems = (_Get $val 'items') }
- } elseif ((_HasKey $val 'value') -and (($val -is [PSCustomObject]) -or ($val -is [System.Collections.IDictionary]))) {
- $innerVal = (_Get $val 'value')
- if ((_HasKey $val 'use') -and -not (ConvertTo-DslBool (_Get $val 'use') 'use' $true)) { $useWrapper = $true }
- if (_HasKey $val 'items') { $nestedItems = (_Get $val 'items') }
- }
- if ($useWrapper) { X "$indent`t<dcscor:use>false</dcscor:use>" }
- X "$indent`t<dcscor:parameter>$(Esc-XmlText $key)</dcscor:parameter>"
- $isFontDict = $false
- if ($innerVal -is [PSCustomObject]) {
- $tProp = $innerVal.PSObject.Properties['@type']
- if ($tProp -and "$($tProp.Value)" -eq 'Font') { $isFontDict = $true }
- } elseif ($innerVal -is [System.Collections.IDictionary]) {
- if ($innerVal.Contains('@type') -and "$($innerVal['@type'])" -eq 'Font') { $isFontDict = $true }
- }
- $isLineDict = $false
- if (_HasKey $innerVal '@type') { $isLineDict = ("$(_Get $innerVal '@type')" -eq 'Line') }
- $isDict = ($innerVal -is [hashtable]) -or ($innerVal -is [System.Collections.IDictionary]) -or ($innerVal -is [PSCustomObject])
- if ($isLineDict) {
- $lw = if (_HasKey $innerVal 'width') { _Get $innerVal 'width' } else { 0 }
- $lg = if (_HasKey $innerVal 'gap') { if ((_Get $innerVal 'gap')) { 'true' } else { 'false' } } else { 'false' }
- $ls = if (_HasKey $innerVal 'style') { "$(_Get $innerVal 'style')" } else { 'None' }
- X "$indent`t<dcscor:value xsi:type=`"v8ui:Line`" width=`"$lw`" gap=`"$lg`">"
- X "$indent`t`t<v8ui:style xsi:type=`"v8ui:SpreadsheetDocumentCellLineType`">$(Esc-XmlText $ls)</v8ui:style>"
- X "$indent`t</dcscor:value>"
- } elseif ($isFontDict) {
- $attrParts = @()
- foreach ($attrName in @('ref','faceName','height','bold','italic','underline','strikeout','kind','scale')) {
- $av = $null
- if ($innerVal -is [PSCustomObject]) { $ap = $innerVal.PSObject.Properties[$attrName]; if ($ap) { $av = $ap.Value } }
- else { if ($innerVal.Contains($attrName)) { $av = $innerVal[$attrName] } }
- if ($null -ne $av) { $attrParts += "$attrName=`"$(Esc-Xml "$av")`"" }
- }
- X "$indent`t<dcscor:value xsi:type=`"v8ui:Font`" $($attrParts -join ' ')/>"
- } elseif ($isDict -and (_HasKey $innerVal 'field')) {
- # Ссылка на поле (dcscor:Field) — значение параметра оформления = поле компоновки
- X "$indent`t<dcscor:value xsi:type=`"dcscor:Field`">$(Esc-XmlText "$(_Get $innerVal 'field')")</dcscor:value>"
- } elseif ($isDict) {
- # Локализуемый текст параметра оформления: платформа объявляет xsi:type на dcscor:value
- Emit-MLText -tag "dcscor:value" -text $innerVal -indent "$indent`t" -xsiType "v8:LocalStringType"
- } else {
- $actualVal = if ($innerVal -is [bool]) { "$innerVal".ToLower() } else { "$innerVal" }
- $keyTypeMap = @{
- 'Размещение' = 'dcscor:DataCompositionTextPlacementType'
- 'ГоризонтальноеПоложение' = 'v8ui:HorizontalAlign'
- 'ВертикальноеПоложение' = 'v8ui:VerticalAlign'
- 'ОриентацияТекста' = 'xs:decimal'
- 'РасположениеИтогов' = 'dcscor:DataCompositionTotalPlacement'
- 'ТипМакета' = 'dcsset:DataCompositionGroupTemplateType'
- }
- $keyType = $keyTypeMap[$key]
- if ($keyType) { X "$indent`t<dcscor:value xsi:type=`"$keyType`">$(Esc-XmlText $actualVal)</dcscor:value>" }
- elseif ($actualVal -match '^(style|web|win):') { X "$indent`t<dcscor:value xsi:type=`"v8ui:Color`">$(Esc-XmlText $actualVal)</dcscor:value>" }
- elseif ($actualVal -eq "true" -or $actualVal -eq "false") { X "$indent`t<dcscor:value xsi:type=`"xs:boolean`">$actualVal</dcscor:value>" }
- elseif ($key -eq "Текст" -or $key -eq "Заголовок" -or $key -eq "Формат") {
- # Текст/Заголовок/Формат: голая строка = плоский xs:string (так платформа хранит
- # нелокализованный литерал). Локализуемый текст → объект {ru,en} (ветка isDict выше).
- # Пустая строка → самозакрывающийся тег (как у платформы).
- if ($actualVal -eq '') { X "$indent`t<dcscor:value xsi:type=`"xs:string`"/>" }
- else { X "$indent`t<dcscor:value xsi:type=`"xs:string`">$(Esc-XmlText $actualVal)</dcscor:value>" }
- }
- elseif ($actualVal -match '^-?\d+(\.\d+)?$') { X "$indent`t<dcscor:value xsi:type=`"xs:decimal`">$actualVal</dcscor:value>" }
- elseif ($key -eq 'ЦветТекста' -or $key -eq 'ЦветФона' -or $key -eq 'ЦветГраницы') { X "$indent`t<dcscor:value xsi:type=`"v8ui:Color`">$(Esc-XmlText $actualVal)</dcscor:value>" }
- else { X "$indent`t<dcscor:value xsi:type=`"xs:string`">$(Esc-XmlText $actualVal)</dcscor:value>" }
- }
- if ($nestedItems) {
- $niProps = if ($nestedItems -is [PSCustomObject]) { $nestedItems.PSObject.Properties } else { $null }
- if ($niProps) { foreach ($np in $niProps) { Emit-AppearanceValue -key $np.Name -val $np.Value -indent "$indent`t" } }
- elseif ($nestedItems -is [System.Collections.IDictionary]) { foreach ($nk in $nestedItems.Keys) { Emit-AppearanceValue -key $nk -val $nestedItems[$nk] -indent "$indent`t" } }
- }
- X "$indent</dcscor:item>"
- }
- function Emit-ConditionalAppearance {
- param($items, [string]$indent, $blockViewMode = $null, $blockUserSettingID = $null, [string]$wrapTag = 'dcsset:conditionalAppearance', $blockUserSettingPresentation = $null)
- $hasItems = $items -and $items.Count -gt 0
- $hasBlockMeta = ($null -ne $blockViewMode) -or ($null -ne $blockUserSettingID) -or ($null -ne $blockUserSettingPresentation)
- if (-not $hasItems -and -not $hasBlockMeta) { return }
- X "$indent<$wrapTag>"
- foreach ($ca in $items) {
- X "$indent`t<dcsset:item>"
- if ((-not (Get-DslBool $ca @('use') $true))) { X "$indent`t`t<dcsset:use>false</dcsset:use>" }
- if ($ca.selection -and $ca.selection.Count -gt 0) {
- X "$indent`t`t<dcsset:selection>"
- foreach ($sel in $ca.selection) {
- X "$indent`t`t`t<dcsset:item>"
- X "$indent`t`t`t`t<dcsset:field>$(Esc-XmlText "$sel")</dcsset:field>"
- X "$indent`t`t`t</dcsset:item>"
- }
- X "$indent`t`t</dcsset:selection>"
- } else { X "$indent`t`t<dcsset:selection/>" }
- if ($ca.filter -and $ca.filter.Count -gt 0) { Emit-Filter -items $ca.filter -indent "$indent`t`t" }
- else { X "$indent`t`t<dcsset:filter/>" }
- if ($ca.appearance) {
- X "$indent`t`t<dcsset:appearance>"
- foreach ($prop in $ca.appearance.PSObject.Properties) { Emit-AppearanceValue -key $prop.Name -val $prop.Value -indent "$indent`t`t`t" }
- X "$indent`t`t</dcsset:appearance>"
- }
- if ($ca.presentation) {
- if ($ca.presentation -is [hashtable] -or $ca.presentation -is [System.Collections.IDictionary] -or $ca.presentation -is [PSCustomObject]) {
- # Мультиязык → LocalStringType (платформа объявляет тип у локализованного presentation)
- X "$indent`t`t<dcsset:presentation xsi:type=`"v8:LocalStringType`">"
- Emit-MLItems -val $ca.presentation -indent "$indent`t`t`t"
- X "$indent`t`t</dcsset:presentation>"
- }
- else { X "$indent`t`t<dcsset:presentation xsi:type=`"xs:string`">$(Esc-XmlText "$($ca.presentation)")</dcsset:presentation>" }
- }
- if ($ca.viewMode) { X "$indent`t`t<dcsset:viewMode>$(Esc-XmlText "$($ca.viewMode)")</dcsset:viewMode>" }
- if ($ca.userSettingID) {
- $uid = if ("$($ca.userSettingID)" -eq "auto") { New-Guid-String } else { "$($ca.userSettingID)" }
- X "$indent`t`t<dcsset:userSettingID>$(Esc-XmlText $uid)</dcsset:userSettingID>"
- }
- if ($ca.userSettingPresentation) { Emit-USPresentation -val $ca.userSettingPresentation -tag "dcsset:userSettingPresentation" -indent "$indent`t`t" }
- if ($ca.useInDontUse -and $ca.useInDontUse.Count -gt 0) {
- $useInOrder = @('group','hierarchicalGroup','overall','fieldsHeader','header','parameters','filter','resourceFieldsHeader','overallHeader','overallResourceFieldsHeader')
- $set = @{}
- foreach ($n in $ca.useInDontUse) { $set["$n"] = $true }
- foreach ($n in $useInOrder) {
- if ($set.ContainsKey($n)) {
- $tag = "useIn" + ($n.Substring(0,1).ToUpper()) + ($n.Substring(1))
- X "$indent`t`t<dcsset:$tag>DontUse</dcsset:$tag>"
- }
- }
- }
- X "$indent`t</dcsset:item>"
- }
- if ($null -ne $blockViewMode) { X "$indent`t<dcsset:viewMode>$(Esc-XmlText "$blockViewMode")</dcsset:viewMode>" }
- if ($null -ne $blockUserSettingID) {
- $uid = if ("$blockUserSettingID" -eq 'auto') { New-Guid-String } else { "$blockUserSettingID" }
- X "$indent`t<dcsset:userSettingID>$(Esc-XmlText $uid)</dcsset:userSettingID>"
- }
- if ($null -ne $blockUserSettingPresentation) { Emit-USPresentation -val $blockUserSettingPresentation -tag "dcsset:userSettingPresentation" -indent "$indent`t" }
- X "$indent</$wrapTag>"
- }
- function Get-ListGroupingValue {
- param($st)
- foreach ($k in 'grouping','structure','группировка') {
- if ($st.PSObject.Properties[$k] -and $st.$k) { return $st.$k }
- }
- return $null
- }
- function Parse-ListGrouping {
- param($grouping)
- # Шорткат "A > B > C" → массив имён; массив строк/объектов → как есть.
- # Unary comma: иначе PS разворачивает одноэлементный массив при return → строка → индексация даёт char.
- if (-not $grouping) { return ,@() }
- if ($grouping -is [string]) { return ,@($grouping -split '\s*>\s*' | Where-Object { "$_" -ne '' }) }
- return ,@($grouping)
- }
- function Emit-GroupItemField {
- param($level, [string]$indent)
- if ($level -is [string]) {
- $field = $level; $gt = 'Items'; $pat = 'None'; $pab = '0001-01-01T00:00:00'; $pae = '0001-01-01T00:00:00'
- } else {
- $field = "$($level.field)"
- $gt = if ($level.groupType) { "$($level.groupType)" } else { 'Items' }
- $pat = if ($level.periodAdditionType) { "$($level.periodAdditionType)" } else { 'None' }
- $pab = if ($level.periodAdditionBegin) { "$($level.periodAdditionBegin)" } else { '0001-01-01T00:00:00' }
- $pae = if ($level.periodAdditionEnd) { "$($level.periodAdditionEnd)" } else { '0001-01-01T00:00:00' }
- }
- X "$indent<dcsset:item xsi:type=`"dcsset:GroupItemField`">"
- X "$indent`t<dcsset:field>$(Esc-XmlText $field)</dcsset:field>"
- X "$indent`t<dcsset:groupType>$(Esc-XmlText $gt)</dcsset:groupType>"
- X "$indent`t<dcsset:periodAdditionType>$(Esc-XmlText $pat)</dcsset:periodAdditionType>"
- # Авто-детект: ISO-дата → xs:dateTime, иначе путь → dcscor:Field.
- $pabT = if ($pab -match '^\d{4}-\d{2}-\d{2}T') { 'xs:dateTime' } else { 'dcscor:Field' }
- $paeT = if ($pae -match '^\d{4}-\d{2}-\d{2}T') { 'xs:dateTime' } else { 'dcscor:Field' }
- X "$indent`t<dcsset:periodAdditionBegin xsi:type=`"$pabT`">$(Esc-XmlText $pab)</dcsset:periodAdditionBegin>"
- X "$indent`t<dcsset:periodAdditionEnd xsi:type=`"$paeT`">$(Esc-XmlText $pae)</dcsset:periodAdditionEnd>"
- X "$indent</dcsset:item>"
- }
- function Emit-ListGroupingLevels {
- param($levels, [int]$i, [string]$indent)
- X "$indent<dcsset:item xsi:type=`"dcsset:StructureItemGroup`">"
- X "$indent`t<dcsset:groupItems>"
- Emit-GroupItemField $levels[$i] "$indent`t`t"
- X "$indent`t</dcsset:groupItems>"
- if ($i -lt $levels.Count - 1) { Emit-ListGroupingLevels $levels ($i + 1) "$indent`t" }
- X "$indent</dcsset:item>"
- }
- function Emit-ListGrouping {
- param($grouping, [string]$indent)
- $levels = Parse-ListGrouping $grouping
- if ($levels.Count -eq 0) { return }
- Emit-ListGroupingLevels $levels 0 $indent
- }
- function Parse-CalcShorthand {
- param([string]$s)
- $restrict = @()
- foreach ($m in [regex]::Matches($s, '#(noField|noFilter|noCondition|noGroup|noOrder)\b')) { $restrict += $m.Groups[1].Value }
- $s = [regex]::Replace($s, '\s*#(noField|noFilter|noCondition|noGroup|noOrder)\b', '')
- $eq = $s.IndexOf('=')
- if ($eq -gt 0) { $lhs = $s.Substring(0, $eq); $rhs = $s.Substring($eq + 1).Trim() } else { $lhs = $s; $rhs = '' }
- $title = ''
- if ($lhs -match '\[([^\]]+)\]') { $title = $Matches[1]; $lhs = $lhs -replace '\s*\[[^\]]+\]', '' }
- $lhs = $lhs.Trim()
- $type = ''; $dataPath = $lhs
- if ($lhs.Contains(':')) { $parts = $lhs -split ':', 2; $dataPath = $parts[0].Trim(); $type = Resolve-TypeStr ($parts[1].Trim()) }
- return @{ dataPath = $dataPath; expression = $rhs; type = $type; title = $title; restrict = $restrict }
- }
- function Emit-CalcFields {
- param($calcFields, [string]$indent)
- if (-not $calcFields) { return }
- foreach ($cf in $calcFields) {
- $pres = $null; $orderExpr = $null; $restrict = @()
- if ($cf -is [string]) {
- $p = Parse-CalcShorthand $cf
- $dataPath = "$($p.dataPath)"; $expression = "$($p.expression)"; $title = $p.title; $typeStr = "$($p.type)"
- foreach ($r in $p.restrict) { if ($script:calcRestrictMap[$r]) { $restrict += $script:calcRestrictMap[$r] } }
- } else {
- $dataPath = if ($cf.dataPath) { "$($cf.dataPath)" } elseif ($cf.field) { "$($cf.field)" } else { "$($cf.name)" }
- $expression = "$($cf.expression)"
- $title = $cf.title
- $typeStr = if ($cf.valueType) { "$($cf.valueType)" } elseif ($cf.type) { "$($cf.type)" } else { '' }
- $ur = if ($cf.useRestriction) { $cf.useRestriction } elseif ($cf.restrict) { $cf.restrict } else { $null }
- if ($ur -is [System.Management.Automation.PSCustomObject] -or $ur -is [hashtable]) {
- foreach ($k in 'field','condition','group','order') { if (ConvertTo-DslBool $ur.$k $k $false) { $restrict += $k } }
- } elseif ($ur -is [string]) {
- foreach ($tok in ($ur -split '\s+')) { $t = $tok.Trim().TrimStart('#'); if ($t) { $restrict += $(if ($script:calcRestrictMap[$t]) { $script:calcRestrictMap[$t] } else { $t }) } }
- } elseif ($ur) {
- foreach ($r in $ur) { $rr = "$r"; $restrict += $(if ($script:calcRestrictMap[$rr]) { $script:calcRestrictMap[$rr] } else { $rr }) }
- }
- $pres = $cf.presentationExpression
- $orderExpr = $cf.orderExpression
- }
- $ci = "$indent`t"
- X "$indent<CalculatedField>"
- X "$ci<dcssch:dataPath>$(Esc-XmlText $dataPath)</dcssch:dataPath>"
- X "$ci<dcssch:expression>$(Esc-XmlText $expression)</dcssch:expression>"
- if ($title) { Emit-MLText -tag 'dcssch:title' -text $title -indent $ci -xsiType 'v8:LocalStringType' }
- if ($restrict.Count -gt 0) {
- X "$ci<dcssch:useRestriction>"
- foreach ($r in @('field','condition','group','order')) { if ($restrict -contains $r) { X "$ci`t<dcssch:$r>true</dcssch:$r>" } }
- X "$ci</dcssch:useRestriction>"
- }
- if ($pres) { X "$ci<dcssch:presentationExpression>$(Esc-XmlText "$pres")</dcssch:presentationExpression>" }
- if ($orderExpr) {
- $oeList = if ($orderExpr -is [System.Collections.IList]) { $orderExpr } else { @($orderExpr) }
- foreach ($oe in $oeList) {
- if ($oe -is [string]) { $exprV = $oe; $oType = 'Asc'; $auto = 'false' }
- else { $exprV = "$($oe.expression)"; $oType = if ($oe.orderType) { "$($oe.orderType)" } else { 'Asc' }; $auto = if ($oe.autoOrder) { 'true' } else { 'false' } }
- X "$ci<dcssch:orderExpression>"
- X "$ci`t<expression xmlns=`"$($script:dcsCommonNs)`">$(Esc-XmlText $exprV)</expression>"
- X "$ci`t<orderType xmlns=`"$($script:dcsCommonNs)`">$oType</orderType>"
- X "$ci`t<autoOrder xmlns=`"$($script:dcsCommonNs)`">$auto</autoOrder>"
- X "$ci</dcssch:orderExpression>"
- }
- }
- if ($typeStr) { Emit-DLValueType -typeStr $typeStr -indent $ci }
- X "$indent</CalculatedField>"
- }
- }
- function Get-RestrictList {
- param($ur)
- $out = @()
- if (-not $ur) { return ,$out }
- if ($ur -is [System.Management.Automation.PSCustomObject] -or $ur -is [hashtable]) {
- foreach ($k in 'field','condition','group','order') { if (ConvertTo-DslBool $ur.$k $k $false) { $out += $k } }
- } elseif ($ur -is [string]) {
- foreach ($tok in ($ur -split '\s+')) { $t = $tok.Trim().TrimStart('#'); if ($t) { $out += $(if ($script:calcRestrictMap[$t]) { $script:calcRestrictMap[$t] } else { $t }) } }
- } else {
- foreach ($r in $ur) { $rr = "$r"; $out += $(if ($script:calcRestrictMap[$rr]) { $script:calcRestrictMap[$rr] } else { $rr }) }
- }
- return ,$out
- }
- function Emit-RestrictBlock {
- param([string]$tag, $ur, [string]$indent)
- $r = Get-RestrictList $ur
- if ($r.Count -eq 0) { return }
- X "$indent<dcssch:$tag>"
- foreach ($k in @('field','condition','group','order')) { if ($r -contains $k) { X "$indent`t<dcssch:$k>true</dcssch:$k>" } }
- X "$indent</dcssch:$tag>"
- }
- function Resolve-TypeStr {
- param([string]$typeStr)
- if (-not $typeStr) { return $typeStr }
- # Прощающий ввод: ведущий префикс приходит копипастой из выгрузки. Без срезания он ломает
- # поиск в словаре — русское имя типа остаётся непереведённым, и платформа отвечает
- # «Неизвестное имя типа». cfg: снимаем всегда — он однозначно означает текущую конфигурацию.
- # Сгенерированный dNpM: (в корпусе на этом URI встречаются d4p1, d5p1, d6p1 — имя префикса
- # платформа выдаёт по порядку объявления) снимаем ТОЛЬКО у ссылочных типов, с точкой:
- # сам по себе префикс многозначен — в формах d5p1:Chart, d5p1:TextDocument,
- # d5p1:GeographicalSchema адресуют чужие пространства имён, и там он часть значения.
- if ($typeStr.StartsWith('cfg:')) {
- $typeStr = $typeStr.Substring(4)
- } elseif ($typeStr.Contains('.') -and $typeStr -match '^d\d+p\d+:') {
- $typeStr = $typeStr.Substring($typeStr.IndexOf(':') + 1)
- }
- # Хвосты, которые дописывает вывод meta-info к множествам типов: суффикс обобщённого метатипа
- # и счётчик состава. Копипаста строки оттуда — обычный путь, поэтому хвост снимаем молча.
- # Срезаем ТОЛЬКО эти известные формы: круглые скобки заняты параметризованными типами
- # (Число(15,2)), слепой срез скобок сломал бы их.
- $typeStr = ($typeStr -replace '\s*\((?:все|all)\)\s*$', '').Trim()
- $typeStr = ($typeStr -replace '\s*[—-]\s*(?:типов|types):\s*\d+\s*$', '').Trim()
- $typeStr = ($typeStr -replace '\s*\((?:типов|types):\s*\d+\)\s*$', '').Trim()
- # Параметризованные типы: Number(15,2), Строка(100)
- if ($typeStr -match '^([^(]+)\((.+)\)$') {
- $baseName = $Matches[1].Trim()
- $params = $Matches[2]
- $resolved = $script:typeSynonyms[$baseName.ToLower()]
- if ($resolved) { return "$resolved($params)" }
- return $typeStr
- }
- # Ссылочные типы: СправочникСсылка.Организации → CatalogRef.Организации
- if ($typeStr.Contains('.')) {
- $dotIdx = $typeStr.IndexOf('.')
- $prefix = $typeStr.Substring(0, $dotIdx)
- $suffix = $typeStr.Substring($dotIdx) # includes the dot
- $resolved = $script:typeSynonyms[$prefix.ToLower()]
- if ($resolved) { return "$resolved$suffix" }
- return $typeStr
- }
- # Простое имя
- $resolved = $script:typeSynonyms[$typeStr.ToLower()]
- if ($resolved) { return $resolved }
- return $typeStr
- }
- function Emit-Type {
- # $tag/$tagAttrs — обёртка (по умолчанию <Type>); для уточнения типа значений ValueList
- # вызывается с tag="Settings", tagAttrs=' xsi:type="v8:TypeDescription"'.
- param($typeStr, [string]$indent, [string]$tag = "Type", [string]$tagAttrs = "")
- if (-not $typeStr) {
- X "$indent<$tag$tagAttrs/>"
- return
- }
- $typeString = "$typeStr"
- # Composite type: "Type1 | Type2" or "Type1 + Type2"
- $parts = $typeString -split '\s*[|+]\s*'
- X "$indent<$tag$tagAttrs>"
- foreach ($part in $parts) {
- $part = $part.Trim()
- Emit-SingleType -typeStr $part -indent "$indent`t"
- }
- X "$indent</$tag>"
- }
- # Разбор примитивного типа DSL: Number / String / Date / DateTime / Time — с синонимами
- # (decimal, numeric, Число, Строка, Дата …), в любом регистре, с пробелами в скобках.
- # Тело общее у всех навыков-компиляторов (семья в check-inline-drift); умолчание для голого типа
- # зависит от места (хранимый реквизит — 10,0 и 10, СКД — без ограничения) и приходит аргументами.
- # Возврат: $null — не примитив (ссылки, Boolean, …); @{ Error } — база примитива узнана, а
- # параметры нет (вызывающий сообщает ошибку своим способом); иначе описание квалификаторов.
- function Parse-PrimitiveType {
- param([string]$typeStr, [int]$defDigits, [int]$defFraction, [int]$defLength)
- if ($typeStr -notmatch '^\s*([^\s(]+)\s*(\(.*)?$') { return $null }
- $rest = if ($Matches.ContainsKey(2)) { $Matches[2] } else { '' }
- $kind = switch -exact ($Matches[1].ToLowerInvariant()) {
- 'number' { 'Number' } 'decimal' { 'Number' } 'numeric' { 'Number' } 'число' { 'Number' }
- 'string' { 'String' } 'строка' { 'String' }
- 'date' { 'Date' } 'дата' { 'Date' } 'datetime' { 'DateTime' } 'датавремя' { 'DateTime' }
- 'time' { 'Time' } 'время' { 'Time' }
- default { $null }
- }
- if (-not $kind) { return $null }
- $bad = @{ Error = ("Invalid type '$typeStr'. Expected Number, Number(D), Number(D,F), Number(D,F,nonneg), " +
- "String, String(N), String(N,fixed), Date, DateTime, Time") }
- $parts = @()
- if ($rest) {
- if ($rest -notmatch '^\((.*)\)\s*$') { return $bad }
- $parts = @($Matches[1] -split ',' | ForEach-Object { $_.Trim().ToLowerInvariant() })
- }
- if ($kind -eq 'Number') {
- $sign = 'Any'
- if ($parts.Count -gt 0 -and ($parts[-1] -eq 'nonneg' -or $parts[-1] -eq 'any')) {
- if ($parts[-1] -eq 'nonneg') { $sign = 'Nonnegative' }
- $parts = @(if ($parts.Count -gt 1) { $parts[0..($parts.Count - 2)] })
- }
- if ($parts.Count -gt 2) { return $bad }
- foreach ($p in $parts) { if ($p -notmatch '^[0-9]{1,9}$') { return $bad } }
- $d = if ($parts.Count -ge 1) { [int]$parts[0] } else { $defDigits }
- $f = if ($parts.Count -ge 2) { [int]$parts[1] } elseif ($parts.Count -eq 1) { 0 } else { $defFraction }
- # Дробная часть у числа без ограничения (0,F) платформа молча обнуляет — это ошибка ввода
- if ($d -gt 38 -or $f -gt $d) { return $bad }
- return @{ Kind = 'Number'; Digits = $d; Fraction = $f; Sign = $sign }
- }
- if ($kind -eq 'String') {
- $allowed = 'Variable'
- if ($parts.Count -eq 2) {
- if ($parts[1] -eq 'fixed' -or $parts[1] -eq 'fix') { $allowed = 'Fixed' }
- elseif ($parts[1] -ne 'variable') { return $bad }
- }
- if ($parts.Count -gt 2 -or ($parts.Count -ge 1 -and $parts[0] -notmatch '^[0-9]{1,9}$')) { return $bad }
- $len = if ($parts.Count -ge 1) { [int]$parts[0] } else { $defLength }
- # Фиксированную длину у неограниченной строки платформа молча снимает — это ошибка ввода
- if ($allowed -eq 'Fixed' -and $len -eq 0) { return $bad }
- return @{ Kind = 'String'; Length = $len; Allowed = $allowed }
- }
- if ($parts.Count -gt 0) { return $bad }
- return @{ Kind = 'Date'; Fractions = $kind }
- }
- function Emit-SingleType {
- param([string]$typeStr, [string]$indent)
- $typeStr = Resolve-TypeStr $typeStr
- # TypeId — тип, заданный глобальным стабильным GUID (<v8:TypeId>, не <v8:Type>). Платформа так
- # сериализует типы, чьё имя в этом контексте недоступно (определяемые/характеристики). GUID
- # глобально стабилен → эмитим verbatim (как роль-по-GUID). Маркер декомпилятора: 'typeid:GUID'.
- if ($typeStr -match '^typeid:([0-9a-fA-F-]{36})$') {
- X "$indent<v8:TypeId>$($Matches[1])</v8:TypeId>"
- return
- }
- # boolean
- if ($typeStr -eq "boolean") {
- X "$indent<v8:Type>xs:boolean</v8:Type>"
- return
- }
- # Примитивы: string / decimal / date / dateTime / time. Голое число реквизита формы — 10,0,
- # голая строка — неограниченная.
- $prim = Parse-PrimitiveType $typeStr 10 0 0
- if ($prim) {
- if ($prim.Error) { throw $prim.Error }
- if ($prim.Kind -eq 'String') {
- X "$indent<v8:Type>xs:string</v8:Type>"
- X "$indent<v8:StringQualifiers>"
- X "$indent`t<v8:Length>$($prim.Length)</v8:Length>"
- X "$indent`t<v8:AllowedLength>$($prim.Allowed)</v8:AllowedLength>"
- X "$indent</v8:StringQualifiers>"
- } elseif ($prim.Kind -eq 'Number') {
- X "$indent<v8:Type>xs:decimal</v8:Type>"
- X "$indent<v8:NumberQualifiers>"
- X "$indent`t<v8:Digits>$($prim.Digits)</v8:Digits>"
- X "$indent`t<v8:FractionDigits>$($prim.Fraction)</v8:FractionDigits>"
- X "$indent`t<v8:AllowedSign>$($prim.Sign)</v8:AllowedSign>"
- X "$indent</v8:NumberQualifiers>"
- } else {
- X "$indent<v8:Type>xs:dateTime</v8:Type>"
- X "$indent<v8:DateQualifiers>"
- X "$indent`t<v8:DateFractions>$($prim.Fractions)</v8:DateFractions>"
- X "$indent</v8:DateQualifiers>"
- }
- return
- }
- # ValueTable, ValueTree, ValueList, etc.
- $v8Types = @{
- "ValueTable" = "v8:ValueTable"
- "ValueTree" = "v8:ValueTree"
- "ValueList" = "v8:ValueListType"
- "TypeDescription" = "v8:TypeDescription"
- "Universal" = "v8:Universal"
- "FixedArray" = "v8:FixedArray"
- "FixedStructure" = "v8:FixedStructure"
- }
- if ($v8Types.ContainsKey($typeStr)) {
- X "$indent<v8:Type>$($v8Types[$typeStr])</v8:Type>"
- return
- }
- # UI types
- $uiTypes = @{
- "FormattedString" = "v8ui:FormattedString"
- "Picture" = "v8ui:Picture"
- "Color" = "v8ui:Color"
- "Font" = "v8ui:Font"
- }
- if ($uiTypes.ContainsKey($typeStr)) {
- X "$indent<v8:Type>$($uiTypes[$typeStr])</v8:Type>"
- return
- }
- # DCS types
- if ($typeStr -match '^DataComposition') {
- $dcsMap = @{
- "DataCompositionSettings" = "dcsset:DataCompositionSettings"
- "DataCompositionSchema" = "dcssch:DataCompositionSchema"
- "DataCompositionComparisonType" = "dcscor:DataCompositionComparisonType"
- }
- if ($dcsMap.ContainsKey($typeStr)) {
- X "$indent<v8:Type>$($dcsMap[$typeStr])</v8:Type>"
- return
- }
- }
- # Голые конфигурационные типы (cfg: без .Имя): дин-список, набор констант, общий объект отчёта.
- # Корпус (acc+erp 8.3.24): DynamicList 5205, ConstantsSet 103, ReportObject 10. (Дотированные формы
- # ConstantsSet.X / ReportObject.X ловит общий cfg:-regex ниже.)
- if ($typeStr -in @("DynamicList","ConstantsSet","ReportObject")) {
- X "$indent<v8:Type>cfg:$typeStr</v8:Type>"
- return
- }
- # TypeSet (набор типов) → <v8:TypeSet>: определяемый тип / характеристика (именованные)
- # + «любая ссылка вида» (голый ref-вид без .Имя). Развязка с обычным типом — по наличию точки.
- if ($typeStr -match '^(DefinedType|Characteristic)\.') {
- X "$indent<v8:TypeSet>cfg:$typeStr</v8:TypeSet>"
- return
- }
- if ($typeStr -match '^(AnyRef|AnyIBRef|CatalogRef|DocumentRef|EnumRef|ExchangePlanRef|TaskRef|BusinessProcessRef|ChartOfAccountsRef|ChartOfCharacteristicTypesRef|ChartOfCalculationTypesRef)$') {
- X "$indent<v8:TypeSet>cfg:$typeStr</v8:TypeSet>"
- return
- }
- # cfg: references (CatalogRef.XXX, DocumentObject.XXX, etc.)
- if ($typeStr -match '^(CatalogRef|CatalogObject|DocumentRef|DocumentObject|EnumRef|ChartOfAccountsRef|ChartOfAccountsObject|ChartOfCharacteristicTypesRef|ChartOfCharacteristicTypesObject|ChartOfCalculationTypesRef|ChartOfCalculationTypesObject|ExchangePlanRef|ExchangePlanObject|BusinessProcessRef|BusinessProcessObject|TaskRef|TaskObject|InformationRegisterRecordSet|InformationRegisterRecordManager|AccumulationRegisterRecordSet|AccountingRegisterRecordSet|ConstantsSet|DataProcessorObject|ReportObject)\.') {
- X "$indent<v8:Type>cfg:$typeStr</v8:Type>"
- return
- }
- # Спец-типы платформы с собственным namespace (объявляется ЛОКАЛЬНО на <v8:Type>).
- # Префикс d5p1 неоднозначен (5 разных URI), поэтому маппинг по полному значению типа.
- # К таким типам привязаны спец-поля: mxl→SpreadSheetDocumentField, fd→FormattedDocumentField,
- # d5p1:TextDocument→TextDocumentField, pdfdoc→PDF, pl→Planner, chart/geo/graphscheme/data-analysis.
- $specialTypeNs = @{
- "mxl:SpreadsheetDocument" = "http://v8.1c.ru/8.2/data/spreadsheet"
- "fd:FormattedDocument" = "http://v8.1c.ru/8.2/data/formatted-document"
- "d5p1:TextDocument" = "http://v8.1c.ru/8.1/data/txtedt"
- "d5p1:Chart" = "http://v8.1c.ru/8.2/data/chart"
- "d5p1:GanttChart" = "http://v8.1c.ru/8.2/data/chart"
- "d5p1:Dendrogram" = "http://v8.1c.ru/8.2/data/chart"
- "d5p1:FlowchartContextType" = "http://v8.1c.ru/8.2/data/graphscheme"
- "d5p1:DataAnalysisTimeIntervalUnitType" = "http://v8.1c.ru/8.2/data/data-analysis"
- "d5p1:GeographicalSchema" = "http://v8.1c.ru/8.2/data/geo"
- "pdfdoc:PDFDocument" = "http://v8.1c.ru/8.3/data/pdf"
- "pl:Planner" = "http://v8.1c.ru/8.3/data/planner"
- }
- if ($specialTypeNs.ContainsKey($typeStr)) {
- $pref = $typeStr.Substring(0, $typeStr.IndexOf(':'))
- X "$indent<v8:Type xmlns:$pref=`"$($specialTypeNs[$typeStr])`">$typeStr</v8:Type>"
- return
- }
- # Fallback with validation
- if ($script:knownInvalidTypes.ContainsKey($typeStr)) {
- throw "Invalid form attribute type '$typeStr': $($script:knownInvalidTypes[$typeStr])"
- }
- # Платформенный тип с префиксом (v8:/v8ui:/xs:/dcs*:) — эмитим verbatim (напр. v8:UUID, v8:StandardPeriod).
- if ($typeStr -match '^(v8|v8ui|xs|ent|style|sys|web|win|dcs\w*):') {
- X "$indent<v8:Type>$typeStr</v8:Type>"
- } elseif ($typeStr.Contains('.')) {
- X "$indent<v8:Type>cfg:$typeStr</v8:Type>"
- } else {
- Write-Warning "Unrecognized bare type '$typeStr' — will be emitted without namespace prefix"
- X "$indent<v8:Type>$typeStr</v8:Type>"
- }
- }
- function Get-HandlerName {
- param([string]$elementName, [string]$eventName, [string]$xmlTag, [string]$callType = '')
- $entry = Get-EventEntry $xmlTag $eventName
- $name = if ($entry -and $entry[0]) { "$elementName$($entry[0])" } else { "$elementName$eventName" }
- # Обработчик с видом вызова (расширение) — как называет Конфигуратор: префикс расширения + имя + вид вызова.
- # Без этого имя совпало бы с процедурой исходной формы.
- if ($callType) { $name = "$($script:extNamePrefix)$name$(@{ Before = 'Перед'; After = 'После'; Override = 'Вместо' }[$callType])" }
- return $name
- }
- function Get-ElementName {
- param($el, [string]$typeKey)
- if ($el.name) { return "$($el.name)" }
- return "$($el.$typeKey)"
- }
- function Resolve-EventName([string]$xmlTag, [string]$name, [string]$ctx) {
- if (-not $name) {
- Write-Error "${ctx}: event name is empty — a list item object needs `"event`": { `"event`": `"OnChange`", `"handler`": `"Name`" }"
- exit 1
- }
- if ($xmlTag -and $script:eventCatalog.ContainsKey($xmlTag)) {
- foreach ($k in $script:eventCatalog[$xmlTag].Keys) { if ($k -eq $name) { return $k } }
- }
- if ($name -cmatch '^[A-Z]') { return $name }
- $hint = if (@('remove', 'delete') -contains $name) { 'to unbind a handler in form-edit, set the event to null: { "OnOpen": null }' } else { 'keys of events are event names (OnOpen), values are handler names' }
- Write-Error "${ctx}: '$name' is not an event name — $hint"
- exit 1
- }
- function Get-EventPairs {
- param($el, [string]$elementName, [string]$xmlTag)
- $pairs = New-Object System.Collections.ArrayList
- $ctx = if ($xmlTag -eq 'Form') { 'Form events' } else { "Element '$elementName' events" }
- $list = $null
- if ($el.events -is [array]) { $list = @($el.events) }
- elseif ($el.events) {
- if (-not ($el.events -is [System.Management.Automation.PSCustomObject])) {
- Write-Error "${ctx}: events — an object { `"OnChange`": `"Handler`" } or a list of events [`"OnChange`"]"
- exit 1
- }
- foreach ($p in $el.events.PSObject.Properties) {
- $evName = Resolve-EventName $xmlTag $p.Name $ctx
- # Значение — имя обработчика; объект { handler, callType } или массив таких объектов
- # (в расширении на одно событие вешают и Before, и After)
- $vals = @($p.Value) # массив — как есть, одно значение (в т.ч. null) — один элемент
- if ($vals.Count -eq 0) { Write-Error "${ctx}: '$evName' — empty list, specify the handler name"; exit 1 }
- foreach ($v in $vals) {
- $h = ""; $ct = ""
- if ($v -is [System.Management.Automation.PSCustomObject]) { $h = "$($v.handler)"; $ct = Normalize-CallType "$($v.callType)" $elementName $evName } else { $h = "$v" }
- if ([string]::IsNullOrEmpty($h)) {
- Write-Error "${ctx}: '$evName' has no handler name — null unbinds a handler only when editing a form (form-edit); for a handler named by convention list the event: `"events`": [`"$evName`"]"
- exit 1
- }
- [void]$pairs.Add([pscustomobject]@{ name = $evName; handler = $h; callType = $ct })
- }
- }
- } elseif ($el.on) { $list = @($el.on) }
- if ($null -ne $list) {
- foreach ($evt in $list) {
- if ($evt -is [System.Management.Automation.PSCustomObject]) {
- $evtName = Resolve-EventName $xmlTag "$($evt.event)" $ctx; $h = "$($evt.handler)"; $ct = Normalize-CallType "$($evt.callType)" $elementName $evtName
- } else {
- $evtName = Resolve-EventName $xmlTag "$evt" $ctx; $h = ""; $ct = ""
- }
- if (-not $h) { $h = if ($el.handlers -and $el.handlers.$evtName) { "$($el.handlers.$evtName)" } else { Get-HandlerName -elementName $elementName -eventName $evtName -xmlTag $xmlTag -callType $ct } }
- [void]$pairs.Add([pscustomobject]@{ name = $evtName; handler = $h; callType = $ct })
- }
- }
- return $pairs
- }
- # Пары событий в порядке, в котором их пишет платформа (Get-EventRank); равные — в порядке ввода.
- # Только для вывода <Events>: заготовки в модуле идут в порядке ввода.
- function Sort-EventPairs($pairs, [string]$xmlTag) {
- $i = 0
- $keyed = @(foreach ($pr in @($pairs)) { [pscustomobject]@{ k = (Get-EventRank $xmlTag $pr.name $pr.callType); i = $i++; p = $pr } })
- return @($keyed | Sort-Object k, i | ForEach-Object { $_.p })
- }
- function Normalize-CallType([string]$raw, [string]$elementName, [string]$eventName) {
- if ([string]::IsNullOrEmpty($raw)) { return '' }
- foreach ($v in @('Before','After','Override')) { if ($raw -eq $v) { return $v } }
- Write-Error "Element '$elementName', event '$eventName': callType '$raw' — expected Before, After or Override"
- exit 1
- }
- function Emit-Events {
- param($el, [string]$elementName, [string]$indent, [string]$xmlTag, [string]$source = '')
- $pairs = Get-EventPairs -el $el -elementName $elementName -xmlTag $xmlTag
- if ($pairs.Count -eq 0) { return }
- Test-EventPairs -pairs $pairs -xmlTag $xmlTag -elementName $elementName -source $source
- $table = if ($xmlTag -eq 'Table') { $elementName } else { $script:handlerTable }
- foreach ($pr in $pairs) { Register-Handler $pr.handler 'element' $xmlTag $pr.name $table }
- X "$indent<Events>"
- foreach ($pr in (Sort-EventPairs $pairs $xmlTag)) {
- $ctAttr = if ($pr.callType) { " callType=`"$($pr.callType)`"" } else { "" }
- X "$indent`t<Event name=`"$($pr.name)`"$ctAttr>$($pr.handler)</Event>"
- }
- X "$indent</Events>"
- }
- function Test-CompanionStructured {
- param($content)
- if (-not (($content -is [System.Collections.IDictionary]) -or ($content -is [System.Management.Automation.PSCustomObject]))) { return $false }
- foreach ($k in $script:companionStructKeys) {
- $present = if ($content -is [System.Collections.IDictionary]) { $content.Contains($k) } else { [bool]$content.PSObject.Properties[$k] }
- if ($present) { return $true }
- }
- return $false
- }
- function Emit-CompanionTitle {
- param($content, [string]$indent)
- $r = Resolve-MLFormatted $content
- $fmt = if ($r.formatted) { 'true' } else { 'false' }
- X "$indent<Title formatted=`"$fmt`">"
- Emit-MLItems -val $r.text -indent "$indent`t"
- X "$indent</Title>"
- }
- function DI-Attr {
- param($el)
- if ($null -ne $el -and $el.displayImportance) { return " DisplayImportance=`"$(Esc-Xml "$($el.displayImportance)")`"" }
- return ""
- }
- function Emit-Companion {
- param([string]$tag, [string]$name, [string]$indent, $content = $null)
- $id = New-Id
- $hasContent = $null -ne $content -and -not ($content -is [string] -and "$content" -eq '')
- if (-not $hasContent) {
- X "$indent<$tag name=`"$name`" id=`"$id`"/>"
- return
- }
- $inner = "$indent`t"
- # DI-Attr берём от СОБСТВЕННОГО объекта компаньона ($content), НЕ от ambient $el родителя
- # (PowerShell dynamic scope — иначе companion наследует DisplayImportance владельца: баг).
- X "$indent<$tag name=`"$name`" id=`"$id`"$(DI-Attr $content)>"
- if (Test-CompanionStructured $content) {
- # структурированная форма (own-content). Порядок как у платформы: own-content (флаги/hyperlink/
- # layout/оформление) ПЕРЕД Title (в корпусе layout-first 582 vs 10).
- $txtPresent = if ($content -is [System.Collections.IDictionary]) { $content.Contains('text') } else { [bool]$content.PSObject.Properties['text'] }
- Emit-CommonFlags -el $content -indent $inner
- if ((Get-DslBool $content @('hyperlink') $false)) { X "$inner<Hyperlink>true</Hyperlink>" }
- Emit-Layout -el $content -indent $inner
- Emit-Appearance -el $content -indent $inner -profile 'decoration'
- if ($txtPresent) { Emit-CompanionTitle -content $content -indent $inner }
- # ToolTip компаньона (подсказка самой расширенной подсказки) — после Title (порядок схемы LabelDecoration)
- if ($content.tooltip) { Emit-MLText -tag "ToolTip" -text $content.tooltip -indent $inner }
- # События компаньона (ExtendedTooltip = LabelDecoration: напр. URLProcessing у hyperlink-подсказки)
- Emit-Events -el $content -elementName $name -indent $inner -xmlTag 'ExtendedTooltip'
- } else {
- Emit-CompanionTitle -content $content -indent $inner
- }
- X "$indent</$tag>"
- }
- function Emit-CompanionPanel {
- param([string]$tag, [string]$name, [string]$indent, $panel)
- $id = New-Id
- $autofill = $null
- $children = $null
- $halign = $null
- if ($panel -is [array]) {
- $children = $panel
- } elseif ($null -ne $panel) {
- if ($null -ne $panel.PSObject.Properties['autofill'] -and $null -ne $panel.autofill) { $autofill = (ConvertTo-DslBool $panel.autofill 'autofill' $false) }
- if ($null -ne $panel.PSObject.Properties['horizontalAlign'] -and "$($panel.horizontalAlign)" -ne '') { $halign = "$($panel.horizontalAlign)" }
- $children = $panel.children
- }
- $hasChildren = $children -and @($children).Count -gt 0
- # Платформа пишет <Autofill> только при false; true = дефолт (тег опускается).
- $emitAfFalse = ($autofill -eq $false)
- if (-not $emitAfFalse -and -not $hasChildren -and -not $halign) {
- X "$indent<$tag name=`"$name`" id=`"$id`"/>"
- return
- }
- X "$indent<$tag name=`"$name`" id=`"$id`"$(DI-Attr $panel)>"
- if ($halign) { X "$indent`t<HorizontalAlign>$halign</HorizontalAlign>" }
- if ($emitAfFalse) { X "$indent`t<Autofill>false</Autofill>" }
- if ($hasChildren) {
- X "$indent`t<ChildItems>"
- foreach ($c in @($children)) { Emit-Element -el $c -indent "$indent`t`t" -inCmdBar $true }
- X "$indent`t</ChildItems>"
- }
- X "$indent</$tag>"
- }
- function Get-HLocation {
- param($el)
- $v = if ($el -and $el.PSObject.Properties['horizontalLocation']) { $el.horizontalLocation } else { $null }
- if (-not $v) { return $null }
- switch -Regex ("$v".ToLower()) {
- '^(auto|авто)$' { return $null } # дефолт — не эмитим
- '^(left|слева|лево)$' { return 'Left' }
- '^(right|справа|право)$' { return 'Right' }
- '^(center|центр|по центру)$' { return 'Center' }
- default { return "$v" }
- }
- }
- function Emit-AdditionBody {
- param($props, [string]$source, [string]$srcType, [string]$addName, [string]$indent)
- $inner = "$indent`t"
- X "$inner<AdditionSource>"
- X "$inner`t<Item>$source</Item>"
- X "$inner`t<Type>$srcType</Type>"
- X "$inner</AdditionSource>"
- if ($props) {
- if ($props.PSObject.Properties['title'] -and $props.title) { Emit-MLText -tag "Title" -text $props.title -indent $inner }
- Emit-CommonFlags -el $props -indent $inner
- if ($props.tooltip) { Emit-MLText -tag "ToolTip" -text $props.tooltip -indent $inner }
- if ($props.tooltipRepresentation) { X "$inner<ToolTipRepresentation>$($props.tooltipRepresentation)</ToolTipRepresentation>" }
- $hl = Get-HLocation $props; if ($hl) { X "$inner<HorizontalLocation>$hl</HorizontalLocation>" }
- Emit-Layout -el $props -indent $inner
- Emit-Appearance -el $props -indent $inner -profile 'field'
- }
- Emit-Companion -tag "ContextMenu" -name "${addName}КонтекстноеМеню" -indent $inner
- Emit-Companion -tag "ExtendedTooltip" -name "${addName}РасширеннаяПодсказка" -indent $inner
- }
- function Emit-Addition {
- param($el, [string]$name, [int]$id, [string]$typeKey, [string]$indent)
- $map = $script:additionTypeMap[$typeKey]
- $source = if ($el.source) { "$($el.source)" } elseif ($script:currentTableName) { $script:currentTableName } else { '' }
- X "$indent<$($map.Tag) name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- Emit-AdditionBody -props $el -source $source -srcType $map.Type -addName $name -indent $indent
- X "$indent</$($map.Tag)>"
- }
- function Emit-TableAddition {
- param([string]$typeKey, [string]$tableName, [string]$indent, $override = $null)
- $map = $script:additionTypeMap[$typeKey]
- $addName = "$tableName$($map.Suffix)"
- $id = New-Id
- X "$indent<$($map.Tag) name=`"$addName`" id=`"$id`">"
- Emit-AdditionBody -props $override -source $tableName -srcType $map.Type -addName $addName -indent $indent
- X "$indent</$($map.Tag)>"
- }
- function Get-AdditionOverride {
- param($additions, [string]$typeKey)
- if ($null -eq $additions) { return $null }
- foreach ($k in @($typeKey) + $script:additionKeySynonyms[$typeKey]) {
- $p = $additions.PSObject.Properties[$k]
- if ($p) { return $p.Value }
- }
- return $null
- }
- function Normalize-ElementTypeSynonyms {
- param($el)
- foreach ($pair in $script:elementTypeSynonyms.GetEnumerator()) {
- if ($null -ne $el.PSObject.Properties[$pair.Key] -and $null -eq $el.PSObject.Properties[$pair.Value]) {
- if ($script:elementTypeStrOnlyKeys -contains $pair.Key -and -not ($el.($pair.Key) -is [string])) { continue }
- $val = $el.($pair.Key)
- $el.PSObject.Properties.Remove($pair.Key) | Out-Null
- $el | Add-Member -NotePropertyName $pair.Value -NotePropertyValue $val -Force
- }
- }
- }
- function Normalize-EnumValue {
- param([string]$propName, [string]$value)
- $valid = $script:validEnumValues["$script:objType.$propName"]
- if (-not $valid) { $valid = $script:validEnumValues[$propName] }
- # 1. Check alias dictionary — silent auto-correct. Словарь общий для всех свойств: у свойства со
- # списком алиас берётся, только если его результат в списке (иначе «None» дало бы Nonperiodical везде)
- if ($script:enumValueAliases.ContainsKey($value)) {
- $aliased = $script:enumValueAliases[$value]
- if (-not $valid -or $valid -ccontains $aliased) { return $aliased }
- }
- # 2. Case-insensitive match against valid values — silent. Список вида объекта — раньше общего.
- if ($valid) {
- foreach ($v in $valid) {
- if ($v -ieq $value) { return $v }
- }
- # 3. Known property, unknown value — error with hint
- Write-Error "Invalid value '$value' for property '$propName'. Valid values: $($valid -join ', ')"
- exit 1
- }
- # 4. Unknown property — pass-through (no validation data)
- return $value
- }
- function Resolve-EnumInputSynonym([string]$type, [string]$tag, [string]$value) {
- $syn = $script:enumInputSynonyms["$type.$tag"]
- if ($syn) { foreach ($k in $syn.Keys) { if ($k -ieq $value) { return $syn[$k] } } }
- return $value
- }
- function Normalize-EnumTags([string]$text, [string]$rootType = '', [bool]$keepDefaults = $false) {
- $crlf = $text.Contains("`r`n")
- $lines = $text.Replace("`r`n", "`n") -split "`n"
- $stack = New-Object System.Collections.ArrayList
- $drop = @{}
- for ($i = 0; $i -lt $lines.Count; $i++) {
- $line = $lines[$i]
- if ($line -cmatch '^\t*</([A-Za-z_][\w.:-]*)>$') {
- if ($stack.Count -gt 0 -and $stack[$stack.Count - 1].Name -ceq $Matches[1]) { $stack.RemoveAt($stack.Count - 1) }
- continue
- }
- if ($line -cmatch '^(\t*)<([A-Za-z_][\w.:-]*)(\s[^>]*)?>$' -and -not $line.EndsWith('/>')) {
- [void]$stack.Add(@{ Name = $Matches[2]; Ind = $Matches[1].Length; Attrs = $Matches[3] })
- continue
- }
- if ($stack.Count -eq 0) { continue }
- $m = [regex]::Match($line, '^(\t*)<([A-Za-z]\w*)>([^<]+)</([A-Za-z]\w*)>$')
- if (-not $m.Success -or $m.Groups[2].Value -cne $m.Groups[4].Value) { continue }
- $top = $stack[$stack.Count - 1]
- if ($m.Groups[1].Value.Length -ne $top.Ind + 1) { continue }
- $ptype = if ($stack.Count -eq 1) { if ($top.Name -ceq 'Form') { 'Form' } else { $rootType } } else { $top.Name }
- if (-not $ptype -or -not $script:enumScopeTypes.ContainsKey($ptype)) { continue }
- # Settings — только настройки динамического списка (у ValueList/Planner/Chart свои), как в form-validate
- if ($ptype -ceq 'Settings' -and "$($top.Attrs)" -cnotmatch 'xsi:type="DynamicList"') { continue }
- $script:objType = $ptype
- $tag = $m.Groups[2].Value
- $v = Normalize-EnumValue $tag (Resolve-EnumInputSynonym $ptype $tag $m.Groups[3].Value)
- if (-not $keepDefaults -and $script:enumDefaultValues.ContainsKey("$ptype.$tag") -and $script:enumDefaultValues["$ptype.$tag"] -ceq $v) { $drop[$i] = $true; continue }
- if ($v -cne $m.Groups[3].Value) { $lines[$i] = "$($m.Groups[1].Value)<$tag>$v</$tag>" }
- }
- # Строки-умолчания пропускаются по номеру: $null в строковом массиве PS 5.1 становится пустой строкой
- $keep = New-Object System.Collections.Generic.List[string]
- for ($i = 0; $i -lt $lines.Count; $i++) { if (-not $drop.ContainsKey($i)) { $keep.Add($lines[$i]) } }
- $out = $keep -join "`n"
- if ($crlf) { $out = $out.Replace("`n", "`r`n") }
- return $out
- }
- function Get-ChildRank([string]$parentTag, [string]$childTag) {
- if ($null -eq $script:childRank) {
- $script:childRank = @{}
- foreach ($t in $script:childTagOrder.Keys) {
- $idx = @{}; $i = 0
- foreach ($c in ($script:childTagOrder[$t] -split ' ')) { $idx[$c] = $i; $i++ }
- $script:childRank[$t] = $idx
- }
- }
- $idx = $script:childRank[$parentTag]
- if ($idx -and $idx.ContainsKey($childTag)) { return $idx[$childTag] }
- return -1
- }
- function Sort-ElementTagOrder([string]$text) {
- $crlf = $text.Contains("`r`n")
- $lines = New-Object System.Collections.Generic.List[string]
- $lines.AddRange([string[]]($text.Replace("`r`n", "`n") -split "`n"))
- Sort-TagBlocks $lines 0 $lines.Count ''
- $out = $lines -join "`n"
- if ($crlf) { $out = $out.Replace("`n", "`r`n") }
- return $out
- }
- function Get-TagBlockEnd($lines, [int]$i, [string]$ind, [string]$name) {
- $line = $lines[$i]
- if ($line.EndsWith('/>') -and -not $line.Contains('</')) { return $i + 1 }
- if ($line.EndsWith("</$name>")) { return $i + 1 }
- if ($line -cmatch ('^\t*<' + [regex]::Escape($name) + '(\s[^>]*)?>$')) {
- $close = "$ind</$name>"
- $j = $i + 1
- while ($j -lt $lines.Count -and $lines[$j] -cne $close) { $j++ }
- return $j + 1
- }
- # многострочный текст — до строки, которая кончается закрывающим тегом
- $j = $i + 1
- while ($j -lt $lines.Count -and -not $lines[$j - 1].EndsWith("</$name>")) { $j++ }
- return $j
- }
- function Sort-TagBlocks($lines, [int]$lo, [int]$hi, [string]$parent) {
- $ind = $null
- for ($i = $lo; $i -lt $hi; $i++) {
- if ($lines[$i] -cmatch '^(\t*)<[A-Za-z_]') { $ind = $Matches[1]; break }
- }
- if ($null -eq $ind) { return }
- $blocks = New-Object System.Collections.ArrayList
- $i = $lo
- while ($i -lt $hi) {
- $m = [regex]::Match($lines[$i], '^(\t*)<([A-Za-z_][\w.:-]*)(?=[\s/>])')
- if ($m.Success -and $m.Groups[1].Value -ceq $ind) {
- $e = Get-TagBlockEnd $lines $i $ind $m.Groups[2].Value
- [void]$blocks.Add(@{ Name = $m.Groups[2].Value; S = $i; E = $e })
- $i = $e
- } else { $i++ }
- }
- foreach ($b in $blocks) {
- if ($b.E - $b.S -gt 2 -and $lines[$b.S] -cmatch ('^\t*<' + [regex]::Escape($b.Name) + '(\s[^>]*)?>$')) {
- Sort-TagBlocks $lines ($b.S + 1) ($b.E - 1) $b.Name
- }
- }
- if ($blocks.Count -lt 2 -or -not $parent) { return }
- $ptag = ($parent -split ':')[-1]
- if (-not $script:childTagOrder.ContainsKey($ptag)) { return }
- $total = 0
- foreach ($b in $blocks) { $total += $b.E - $b.S }
- $a = $blocks[0].S; $z = $blocks[$blocks.Count - 1].E
- if ($total -ne $z - $a) { return } # между детьми есть посторонние строки — не трогаем
- $last = -1
- $keyed = New-Object System.Collections.ArrayList
- for ($k = 0; $k -lt $blocks.Count; $k++) {
- $r = Get-ChildRank $ptag (($blocks[$k].Name -split ':')[-1])
- if ($r -lt 0) { $r = $last }
- $last = $r
- [void]$keyed.Add([pscustomobject]@{ Key = ($r + 1) * 100000 + $k; K = $k })
- }
- $sorted = @($keyed | Sort-Object Key)
- $same = $true
- for ($k = 0; $k -lt $sorted.Count; $k++) { if ($sorted[$k].K -ne $k) { $same = $false; break } }
- if ($same) { return }
- $seq = New-Object System.Collections.Generic.List[string]
- foreach ($s in $sorted) { $b = $blocks[$s.K]; for ($x = $b.S; $x -lt $b.E; $x++) { $seq.Add($lines[$x]) } }
- $lines.RemoveRange($a, $z - $a)
- $lines.InsertRange($a, $seq)
- }
- function Emit-Element {
- param($el, [string]$indent, [bool]$inCmdBar = $false)
- # Companion-панели (объект/массив-значение) → commandBar/contextMenu, до тип-синонимов.
- Normalize-PanelSynonyms $el
- # Синонимы типа (XML-имя, русское имя) → канонический ключ DSL
- Normalize-ElementTypeSynonyms $el
- # Синонимы ключей-свойств (русские имена 1С → канон. англ.). Case/space-insensitive.
- # Канон побеждает: если задан и русский, и англ. ключ — англ. остаётся, русский отбрасываем.
- foreach ($pn in @($el.PSObject.Properties.Name)) {
- $norm = ($pn -replace '\s','').ToLower()
- $canon = $script:propSynonyms[$norm]
- if ($canon -and $pn -ne $canon) {
- if ($null -eq $el.PSObject.Properties[$canon]) {
- $val = $el.($pn)
- $el | Add-Member -NotePropertyName $canon -NotePropertyValue $val -Force
- }
- $el.PSObject.Properties.Remove($pn) | Out-Null
- }
- }
- # Determine element type from key
- $typeKey = $null
- $xmlTag = $null
- # picture/picField — НИЗКИЙ приоритет: 'picture' это и тип (PictureDecoration), и свойство-иконка
- # у popup/button/cmdBar. Тип-ключ владельца (popup/button/…) должен выиграть.
- # pages/page ПЕРЕД group: у Page/Pages ключ 'group' — это направление раскладки детей
- # (<Group>Horizontal</Group>), а не тип UsualGroup. Реальная UsualGroup ключа page/pages не несёт.
- foreach ($key in @("columnGroup","buttonGroup","pages","page","group","input","check","radio","label","labelField","table","button","calendar","cmdBar","popup","searchString","viewStatus","searchControl","picField","picture","spreadsheet","html","textDoc","formattedDoc","progressBar","trackBar","chart","ganttChart","graphicalSchema","planner","periodField","dendrogram")) {
- if ($el.$key -ne $null) {
- $typeKey = $key
- break
- }
- }
- if (-not $typeKey) {
- Write-Warning "Unknown element type, skipping"
- return
- }
- # Validate known keys — warn about typos and unknown properties
- $knownKeys = @{
- # type keys
- "group"=1;"columnGroup"=1;"buttonGroup"=1;"input"=1;"check"=1;"radio"=1;"label"=1;"labelField"=1;"table"=1;"pages"=1;"page"=1
- "button"=1;"picture"=1;"picField"=1;"calendar"=1;"cmdBar"=1;"popup"=1
- # спец-поля (документ/датчик/диаграмма) — тип-ключи + типоспец. скаляры
- "spreadsheet"=1;"html"=1;"textDoc"=1;"formattedDoc"=1;"progressBar"=1;"trackBar"=1
- "chart"=1;"ganttChart"=1;"graphicalSchema"=1;"planner"=1;"periodField"=1;"dendrogram"=1;"ganttTable"=1
- "showPercent"=1;"largeStep"=1;"markingStep"=1;"step"=1
- "horizontalScrollBar"=1;"viewScalingMode"=1;"output"=1;"selectionShowMode"=1;"protection"=1
- "edit"=1;"showGrid"=1;"showGroups"=1;"showHeaders"=1;"showRowAndColumnNames"=1;"showCellNames"=1
- "pointerType"=1;"drawingSelectionShowMode"=1;"warningOnEditRepresentation"=1;"markingAppearance"=1
- # report-form контекст (generic-скаляры элементов)
- "horizontalSpacing"=1;"representationInContextMenu"=1;"settingsNamedItemDetailedRepresentation"=1
- # хвост: высота элемента списка / ширина выпадающего списка / картинка кнопки выбора / прозрачный пиксель
- "itemHeight"=1;"dropListWidth"=1;"choiceButtonPicture"=1;"transparentPixel"=1
- # хвост CI-форм: динамический заголовок / расширенное редактирование / высота таблицы
- "titleDataPath"=1;"extendedEdit"=1;"maxRowsCount"=1;"autoMaxRowsCount"=1;"heightControlVariant"=1
- "warningOnEdit"=1;"nonselectedPictureText"=1;"editTextUpdate"=1;"footerText"=1
- # columnGroup-specific
- "showInHeader"=1
- # radio-specific
- "radioButtonType"=1;"choiceList"=1;"columnsCount"=1;"checkBoxType"=1;"editMode"=1
- # naming & binding
- "name"=1;"path"=1;"title"=1;"tooltip"=1;"tooltipRepresentation"=1;"extendedTooltip"=1
- # companion-панели (свойства): командная панель + контекстное меню
- "commandBar"=1;"contextMenu"=1
- # источник команд группы/панели (ButtonGroup/CommandBar)
- "commandSource"=1
- # visibility & state
- "visible"=1;"hidden"=1;"enabled"=1;"disabled"=1;"readOnly"=1;"userVisible"=1
- # events ("events" — основной формат; on/handlers — legacy, принимаются ради совместимости)
- "events"=1;"on"=1;"handlers"=1
- # layout
- "titleLocation"=1;"representation"=1;"width"=1;"height"=1
- "horizontalStretch"=1;"verticalStretch"=1;"autoMaxWidth"=1;"autoMaxHeight"=1
- "maxWidth"=1;"maxHeight"=1
- "groupHorizontalAlign"=1;"groupVerticalAlign"=1;"horizontalAlign"=1
- # input-specific
- "multiLine"=1;"passwordMode"=1;"choiceButton"=1;"clearButton"=1
- "spinButton"=1;"dropListButton"=1;"markIncomplete"=1;"skipOnInput"=1;"inputHint"=1
- "textEdit"=1
- "wrap"=1;"openButton"=1;"listChoiceMode"=1;"showInFooter"=1
- "extendedEditMultipleValues"=1;"chooseType"=1;"autoCellHeight"=1
- "choiceButtonRepresentation"=1;"footerHorizontalAlign"=1;"headerHorizontalAlign"=1
- "headerDataPath"=1;"headerFormat"=1;"currentRowUse"=1
- "format"=1;"editFormat"=1;"choiceParameters"=1;"choiceParameterLinks"=1;"typeLink"=1
- # label/hyperlink
- "hyperlink"=1;"formatted"=1
- # group-specific
- "collapsedTitle"=1;"showTitle"=1;"united"=1;"collapsed"=1;"behavior"=1
- # hierarchy
- "children"=1;"columns"=1
- # table-specific
- "changeRowSet"=1;"changeRowOrder"=1;"autoInsertNewRow"=1;"rowFilter"=1;"header"=1;"footer"=1
- "commandBarLocation"=1;"searchStringLocation"=1;"viewStatusLocation"=1;"searchControlLocation"=1
- "excludedCommands"=1
- "choiceMode"=1;"initialTreeView"=1;"enableDrag"=1;"enableStartDrag"=1
- "rowPictureDataPath"=1;"tableAutofill"=1;"heightInTableRows"=1
- "multipleChoice"=1;"searchOnInput"=1;"shortcut"=1
- "rowSelectionMode"=1;"verticalLines"=1;"horizontalLines"=1
- # dynamic-list table block
- "defaultItem"=1;"useAlternationRowColor"=1;"fileDragMode"=1;"autoRefresh"=1
- "autoRefreshPeriod"=1;"choiceFoldersAndItems"=1;"restoreCurrentRow"=1;"showRoot"=1
- "allowRootChoice"=1;"updateOnDataChange"=1;"allowGettingCurrentRowURL"=1
- "userSettingsGroup"=1;"rowsPicture"=1
- # calendar-specific
- "selectionMode"=1;"showCurrentDate"=1;"widthInMonths"=1;"heightInMonths"=1;"showMonthsPanel"=1
- # pages-specific
- "pagesRepresentation"=1
- # button-specific
- "type"=1;"command"=1;"commandName"=1;"stdCommand"=1;"parameter"=1;"defaultButton"=1;"locationInCommandBar"=1;"displayImportance"=1
- # picture/decoration
- "src"=1;"valuesPicture"=1;"loadTransparent"=1;"headerPicture"=1;"footerPicture"=1
- # cmdBar-specific
- "autofill"=1
- # AutoCommandBar-маркер (autofill heuristic) на элементе/таблице
- "autoCmdBar"=1
- # дополнения командной панели таблицы (тип-ключи + свойства)
- "searchString"=1;"viewStatus"=1;"searchControl"=1;"source"=1;"horizontalLocation"=1;"additions"=1
- # generic-скаляры (pass-through) + точечные
- "verticalAlign"=1;"throughAlign"=1;"enableContentChange"=1;"pictureSize"=1;"titleHeight"=1
- "childItemsWidth"=1;"showLeftMargin"=1;"cellHyperlink"=1;"viewMode"=1;"verticalScrollBar"=1
- "rowInputMode"=1;"mask"=1;"createButton"=1;"fixingInTable"=1;"verticalSpacing"=1
- # InputField choice-скаляры
- "choiceListButton"=1;"quickChoice"=1;"autoChoiceIncomplete"=1
- "choiceForm"=1;"choiceHistoryOnInput"=1;"footerDataPath"=1;"minValue"=1;"maxValue"=1
- # Button — пометка toggle-кнопки (ключ 'checked', не 'check' — во избежание конфликта с типом)
- "checked"=1
- }
- # Оформление (цвета/шрифты/граница) — авто-регистрация из самих структур, чтобы allowlist
- # не дрейфовал при добавлении новых ключей/синонимов. Канонические + forgiving-синонимы.
- foreach ($k in $script:appearanceSpec.Keys) { $knownKeys[$k] = 1 }
- foreach ($k in $script:appearanceSynonyms.Keys) { $knownKeys[$k] = 1 }
- foreach ($k in $script:propSynonyms.Keys) { $knownKeys[$k] = 1 }
- # Простые скаляры (pass-through) — тоже из своей таблицы: компилятор их выводит, значит, они известны
- foreach ($g in $script:genericScalars) { $knownKeys[$g.Key] = 1 }
- foreach ($p in $el.PSObject.Properties) {
- if ($p.Name -like '_*') { continue } # внутренние маркеры (напр. _dynList)
- if (-not $knownKeys.ContainsKey($p.Name)) {
- Write-Warning "Element '$($el.$typeKey)': unknown key '$($p.Name)' — ignored. Check SKILL.md for valid keys."
- }
- }
- $name = Get-ElementName -el $el -typeKey $typeKey
- Assert-UniqueName -name $name -seen $script:seenElementNames -kind 'element'
- $id = New-Id
- switch ($typeKey) {
- "group" { Emit-Group -el $el -name $name -id $id -indent $indent }
- "columnGroup" { Emit-ColumnGroup -el $el -name $name -id $id -indent $indent }
- "buttonGroup" { Emit-ButtonGroup -el $el -name $name -id $id -indent $indent }
- "input" { Emit-Input -el $el -name $name -id $id -indent $indent }
- "check" { Emit-Check -el $el -name $name -id $id -indent $indent }
- "radio" { Emit-Radio -el $el -name $name -id $id -indent $indent }
- "label" { Emit-Label -el $el -name $name -id $id -indent $indent }
- "labelField" { Emit-LabelField -el $el -name $name -id $id -indent $indent }
- "table" { Emit-Table -el $el -name $name -id $id -indent $indent }
- "pages" { Emit-Pages -el $el -name $name -id $id -indent $indent }
- "page" { Emit-Page -el $el -name $name -id $id -indent $indent }
- "button" { Emit-Button -el $el -name $name -id $id -indent $indent -inCmdBar $inCmdBar }
- "picture" { Emit-PictureDecoration -el $el -name $name -id $id -indent $indent }
- "searchString" { Emit-Addition -el $el -name $name -typeKey "searchString" -id $id -indent $indent }
- "viewStatus" { Emit-Addition -el $el -name $name -typeKey "viewStatus" -id $id -indent $indent }
- "searchControl" { Emit-Addition -el $el -name $name -typeKey "searchControl" -id $id -indent $indent }
- "picField" { Emit-PictureField -el $el -name $name -id $id -indent $indent }
- "calendar" { Emit-Calendar -el $el -name $name -id $id -indent $indent }
- "cmdBar" { Emit-CommandBar -el $el -name $name -id $id -indent $indent }
- "popup" { Emit-Popup -el $el -name $name -id $id -indent $indent }
- "spreadsheet" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "SpreadSheetDocumentField" -typeKey "spreadsheet" }
- "html" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "HTMLDocumentField" -typeKey "html" }
- "textDoc" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "TextDocumentField" -typeKey "textDoc" }
- "formattedDoc" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "FormattedDocumentField" -typeKey "formattedDoc" }
- "progressBar" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "ProgressBarField" -typeKey "progressBar" }
- "trackBar" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "TrackBarField" -typeKey "trackBar" }
- "chart" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "ChartField" -typeKey "chart" }
- "graphicalSchema" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "GraphicalSchemaField" -typeKey "graphicalSchema" }
- "planner" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "PlannerField" -typeKey "planner" }
- "periodField" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "PeriodField" -typeKey "periodField" }
- "dendrogram" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "DendrogramField" -typeKey "dendrogram" }
- "ganttChart" { Emit-GanttChart -el $el -name $name -id $id -indent $indent }
- }
- }
- function Emit-XrFlag {
- param([string]$tag, $val, [string]$indent)
- if ($null -eq $val) { return }
- if ($val -isnot [System.Management.Automation.PSCustomObject] -and $val -isnot [System.Collections.IDictionary]) {
- $flag = ConvertTo-DslBool $val $tag $false
- X "$indent<$tag>"
- X "$indent`t<xr:Common>$(if ($flag){'true'}else{'false'})</xr:Common>"
- X "$indent</$tag>"
- return
- }
- # объектная форма { common, roles }
- $common = if ($null -ne $val.common) { (ConvertTo-DslBool $val.common 'common' $false) } else { $false }
- X "$indent<$tag>"
- X "$indent`t<xr:Common>$(if ($common){'true'}else{'false'})</xr:Common>"
- if ($val.roles) {
- foreach ($r in $val.roles.PSObject.Properties) {
- # Forgiving: принимаем имя без префикса, с "Role." или кириллическим "Роль." → нормализуем в "Role.".
- # Роль по GUID (заимствованная/расширение — name="<guid>" без префикса) эмитим как есть.
- $rname = "$($r.Name)" -replace '^(Role|Роль)\.', ''
- if ($rname -notmatch '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$') { $rname = "Role.$rname" }
- $rval = if (ConvertTo-DslBool $r.Value "$($r.Name)" $false) { 'true' } else { 'false' }
- X "$indent`t<xr:Value name=`"$rname`">$rval</xr:Value>"
- }
- }
- X "$indent</$tag>"
- }
- function Emit-CommonFlags {
- param($el, [string]$indent)
- if ((-not (Get-DslBool $el @('visible') $true)) -or (Get-DslBool $el @('hidden') $false)) { X "$indent<Visible>false</Visible>" }
- if ($null -ne $el.userVisible) { Emit-XrFlag -tag 'UserVisible' -val $el.userVisible -indent $indent }
- if ((-not (Get-DslBool $el @('enabled') $true)) -or (Get-DslBool $el @('disabled') $false)) { X "$indent<Enabled>false</Enabled>" }
- if ((Get-DslBool $el @('readOnly') $false)) { X "$indent<ReadOnly>true</ReadOnly>" }
- }
- function Emit-CommonElementProps {
- param($el, [string]$indent)
- if ((Get-DslBool $el @('defaultItem') $false)) { X "$indent<DefaultItem>true</DefaultItem>" }
- if ($el.PSObject.Properties['skipOnInput'] -and $null -ne $el.skipOnInput) {
- $siv = if ((Get-DslBool $el @('skipOnInput') $false)) { 'true' } else { 'false' }
- X "$indent<SkipOnInput>$siv</SkipOnInput>"
- }
- # EnableStartDrag — фактическое значение (платформа эмитит и явный false, напр. SpreadSheet)
- if ($null -ne $el.enableStartDrag) { X "$indent<EnableStartDrag>$(if ($el.enableStartDrag){'true'}else{'false'})</EnableStartDrag>" }
- if ($el.fileDragMode) { X "$indent<FileDragMode>$($el.fileDragMode)</FileDragMode>" }
- # Cell-свойства поля в таблице (общие для Input/Label/Picture/CheckBox): захват «как есть»
- foreach ($p in @(@('showInHeader','ShowInHeader'), @('showInFooter','ShowInFooter'), @('autoCellHeight','AutoCellHeight'))) {
- if ($null -ne $el.($p[0])) { X "$indent<$($p[1])>$(if ($el.($p[0])){'true'}else{'false'})</$($p[1])>" }
- }
- # Динамический заголовок колонки-группы из данных (HeaderDataPath) — перед HeaderHorizontalAlign (порядок XSD)
- if ($el.headerDataPath) { X "$indent<HeaderDataPath>$(Esc-XmlText "$($el.headerDataPath)")</HeaderDataPath>" }
- if ($el.footerHorizontalAlign) { X "$indent<FooterHorizontalAlign>$($el.footerHorizontalAlign)</FooterHorizontalAlign>" }
- if ($el.headerHorizontalAlign) { X "$indent<HeaderHorizontalAlign>$($el.headerHorizontalAlign)</HeaderHorizontalAlign>" }
- # Формат заголовка колонки-группы (ML-текст) — после HeaderHorizontalAlign (порядок XSD)
- if ($el.headerFormat) { Emit-MLText -tag "HeaderFormat" -text $el.headerFormat -indent $indent }
- }
- function Emit-PictureRef {
- param($val, [string]$picTag, [string]$indent)
- if (-not $val) { return }
- $src = $null; $lt = $false; $tpx = $null
- if ($val -is [string]) { $src = $val }
- else { $src = $val.src; if ((Get-DslBool $val @('loadTransparent') $false)) { $lt = $true }; $tpx = $val.transparentPixel }
- if (-not $src) { return }
- $srcStr = "$src"
- X "$indent<$picTag>"
- if ($srcStr -match '^abs:(.*)$') { X "$indent`t<xr:Abs>$(Esc-XmlText $matches[1])</xr:Abs>" }
- else { X "$indent`t<xr:Ref>$(Esc-XmlText $srcStr)</xr:Ref>" }
- X "$indent`t<xr:LoadTransparent>$(if ($lt) { 'true' } else { 'false' })</xr:LoadTransparent>"
- if ($tpx) { X "$indent`t<xr:TransparentPixel x=`"$($tpx.x)`" y=`"$($tpx.y)`"/>" }
- X "$indent</$picTag>"
- }
- function Emit-ColumnPics {
- param($el, [string]$indent)
- Emit-PictureRef -val $el.headerPicture -picTag 'HeaderPicture' -indent $indent
- Emit-PictureRef -val $el.footerPicture -picTag 'FooterPicture' -indent $indent
- }
- function Emit-CommandPicture {
- param($pic, $elemLt, [string]$indent)
- if (-not $pic) { return }
- $src = $null; $lt = $null; $tpx = $null
- if ($pic -is [string]) { $src = $pic }
- else { $src = $pic.src; if ($null -ne $pic.loadTransparent) { $lt = (ConvertTo-DslBool $pic.loadTransparent 'loadTransparent' $false) }; $tpx = $pic.transparentPixel }
- if (-not $src) { return }
- if ($null -eq $lt -and $null -ne $elemLt) { $lt = (ConvertTo-DslBool $elemLt 'loadTransparent' $false) }
- $srcStr = "$src"
- X "$indent<Picture>"
- if ($srcStr -match '^abs:(.*)$') { X "$indent`t<xr:Abs>$(Esc-XmlText $matches[1])</xr:Abs>" }
- else { X "$indent`t<xr:Ref>$(Esc-XmlText $srcStr)</xr:Ref>" }
- X "$indent`t<xr:LoadTransparent>$(if ($lt -eq $false) { 'false' } else { 'true' })</xr:LoadTransparent>"
- if ($tpx) { X "$indent`t<xr:TransparentPixel x=`"$($tpx.x)`" y=`"$($tpx.y)`"/>" }
- X "$indent</Picture>"
- }
- function Emit-GenericScalars {
- param($el, [string]$indent)
- if ($null -eq $el) { return }
- foreach ($s in $script:genericScalars) {
- $p = $el.PSObject.Properties[$s.Key]
- if (-not $p -or $null -eq $p.Value) { continue }
- if ($s.Kind -eq 'bool') {
- X "$indent<$($s.Tag)>$(if ($p.Value){'true'}else{'false'})</$($s.Tag)>"
- } else {
- $v = "$($p.Value)"; if ($v -eq '') { continue }
- X "$indent<$($s.Tag)>$(Esc-XmlText $v)</$($s.Tag)>"
- }
- }
- }
- function Get-AppearanceValue {
- param($el, [string]$canonical)
- if ($null -eq $el) { return $null }
- $p = $el.PSObject.Properties[$canonical]
- if ($p) { return $p.Value }
- foreach ($syn in $script:appearanceSynonyms.Keys) {
- if ($script:appearanceSynonyms[$syn] -eq $canonical) {
- $pp = $el.PSObject.Properties[$syn]
- if ($pp) { return $pp.Value }
- }
- }
- return $null
- }
- function Emit-FontTag {
- param([string]$tag, $val, [string]$indent)
- if ($val -is [string]) {
- X "$indent<$tag ref=`"$(Esc-Xml $val)`" kind=`"StyleItem`"/>"
- return
- }
- $attrs = @()
- foreach ($a in @('ref','faceName','height','bold','italic','underline','strikeout','kind','scale')) {
- $pp = $val.PSObject.Properties[$a]
- if ($pp -and $null -ne $pp.Value) {
- $v = $pp.Value
- if ($v -is [bool]) { $v = if ($v) {'true'} else {'false'} }
- $attrs += "$a=`"$(Esc-Xml "$v")`""
- }
- }
- X "$indent<$tag $($attrs -join ' ')/>"
- }
- function Emit-BorderTag {
- param($val, [string]$indent)
- if ($val -is [string]) { X "$indent<Border ref=`"$(Esc-Xml $val)`"/>"; return }
- $refP = $val.PSObject.Properties['ref']
- if ($refP -and $refP.Value) { X "$indent<Border ref=`"$(Esc-Xml "$($refP.Value)")`"/>"; return }
- $width = if ($val.PSObject.Properties['width'] -and $null -ne $val.width) { $val.width } else { 1 }
- $style = if ($val.PSObject.Properties['style']) { "$($val.style)" } else { $null }
- X "$indent<Border width=`"$width`">"
- if ($style) { X "$indent`t<v8ui:style xsi:type=`"v8ui:ControlBorderType`">$(Esc-XmlText $style)</v8ui:style>" }
- X "$indent</Border>"
- }
- function PL-Get {
- param($o, [string]$k, $def = $null)
- if ($null -ne $o -and $o.PSObject.Properties[$k] -and $null -ne $o.$k) { return $o.$k }
- return $def
- }
- function PL-Bool {
- param($v)
- if ($v -is [bool]) { if ($v) { 'true' } else { 'false' } }
- elseif ("$v" -eq 'True') { 'true' }
- elseif ("$v" -eq 'False') { 'false' }
- else { "$v" }
- }
- function Emit-PlannerColor {
- param([string]$tag, $o, [string]$key, [string]$ind)
- X "$ind<pl:$tag>$(Esc-XmlText "$(PL-Get $o $key 'auto')")</pl:$tag>"
- }
- function Emit-PlannerText {
- param([string]$tag, $v, [string]$ind)
- if ([string]::IsNullOrEmpty("$v")) { X "$ind<pl:$tag/>" }
- else { X "$ind<pl:$tag>$(Esc-XmlText "$v")</pl:$tag>" }
- }
- function Test-PlannerRef {
- param([string]$v)
- return ($v -match '^(Enum|Catalog|Document|ChartOfAccounts|ChartOfCalculationTypes|ChartOfCharacteristicTypes|ExchangePlan|BusinessProcess|Task)\.' -or `
- $v -match '\.EnumValue\.' -or $v -match 'EmptyRef$' -or `
- $v -match '^(Перечисление|Справочник|Документ|ПланСчетов|ПланВидовХарактеристик|ПланВидовРасчета|ПланОбмена|БизнесПроцесс|Задача)\.')
- }
- function Emit-PlannerValue {
- param($v, [string]$ind)
- if ($null -eq $v -or "$v" -eq '') { X "$ind<pl:value xsi:nil=`"true`"/>"; return }
- $t = if (Test-PlannerRef "$v") { 'xr:DesignTimeRef' } else { 'xs:string' }
- X "$ind<pl:value xsi:type=`"$t`">$(Esc-XmlText "$v")</pl:value>"
- }
- function Emit-PlannerFont {
- param($o, [string]$ind)
- $f = PL-Get $o 'font' $null
- if ($null -eq $f) { X "$ind<pl:font kind=`"AutoFont`"/>"; return }
- Emit-FontTag -tag 'pl:font' -val $f -indent $ind
- }
- function Emit-PlannerBorder {
- param($o, [string]$ind, [string]$key = 'border')
- $b = PL-Get $o $key $null
- $bw = if ($b) { PL-Get $b 'width' 1 } else { 1 }
- $bs = if ($b) { PL-Get $b 'style' 'Single' } else { 'Single' }
- X "$ind<pl:border width=`"$bw`">"
- X "$ind`t<v8ui:style xsi:type=`"v8ui:ControlBorderType`">$(Esc-XmlText "$bs")</v8ui:style>"
- X "$ind</pl:border>"
- }
- function Emit-PlannerLevel {
- param($lv, [string]$cns, [string]$ind)
- $li = "$ind`t"
- X "$ind<level xmlns=`"$cns`">"
- X "$li<measure>$(Esc-XmlText "$(PL-Get $lv 'measure' 'Hour')")</measure>"
- X "$li<interval>$(PL-Get $lv 'interval' 1)</interval>"
- X "$li<show>$(PL-Bool (PL-Get $lv 'show' $true))</show>"
- $line = PL-Get $lv 'line' $null
- $lw = if ($line) { PL-Get $line 'width' 1 } else { 1 }
- $lg = if ($line) { PL-Get $line 'gap' $false } else { $false }
- $lst = if ($line) { PL-Get $line 'style' 'Solid' } else { 'Solid' }
- X "$li<line width=`"$lw`" gap=`"$(PL-Bool $lg)`">"
- X "$li`t<v8ui:style xsi:type=`"v8ui:ChartLineType`">$(Esc-XmlText "$lst")</v8ui:style>"
- X "$li</line>"
- X "$li<scaleColor>$(Esc-XmlText "$(PL-Get $lv 'scaleColor' 'auto')")</scaleColor>"
- X "$li<dayFormatRule>$(Esc-XmlText "$(PL-Get $lv 'dayFormatRule' 'MonthDayWeekDay')")</dayFormatRule>"
- $fmt = PL-Get $lv 'format' $null
- if ($null -eq $fmt) { $fmt = [ordered]@{ '#' = 'DF="HH:mm"'; 'ru' = 'DF="HH:mm"' } }
- X "$li<format>"
- Emit-MLItems -val $fmt -indent "$li`t"
- X "$li</format>"
- $labels = PL-Get $lv 'labels' $null
- $ticks = if ($labels) { PL-Get $labels 'ticks' 0 } else { 0 }
- X "$li<labels>"
- X "$li`t<ticks>$ticks</ticks>"
- X "$li</labels>"
- X "$li<backColor>$(Esc-XmlText "$(PL-Get $lv 'backColor' 'auto')")</backColor>"
- X "$li<textColor>$(Esc-XmlText "$(PL-Get $lv 'textColor' 'auto')")</textColor>"
- X "$li<showPereodicalLabels>$(PL-Bool (PL-Get $lv 'showPereodicalLabels' $true))</showPereodicalLabels>"
- X "$ind</level>"
- }
- function Emit-PlannerTimeScale {
- param($ts, [string]$ind)
- $cns = $script:CHART_NS
- $ci = "$ind`t"
- X "$ind<pl:timeScale>"
- X "$ci<placement xmlns=`"$cns`">$(Esc-XmlText "$(if ($ts) { PL-Get $ts 'placement' 'Left' } else { 'Left' })")</placement>"
- $levels = if ($ts) { @(PL-Get $ts 'levels' @()) } else { @() }
- if (@($levels).Count -eq 0) { $levels = @($null) } # один уровень-дефолт
- foreach ($lv in $levels) { Emit-PlannerLevel $lv $cns $ci }
- $transp = if ($ts) { PL-Get $ts 'transparent' $false } else { $false }
- X "$ci<transparent xmlns=`"$cns`">$(PL-Bool $transp)</transparent>"
- X "$ci<backColor xmlns=`"$cns`">$(Esc-XmlText "$(if ($ts) { PL-Get $ts 'backColor' 'auto' } else { 'auto' })")</backColor>"
- X "$ci<textColor xmlns=`"$cns`">$(Esc-XmlText "$(if ($ts) { PL-Get $ts 'textColor' 'auto' } else { 'auto' })")</textColor>"
- X "$ci<currentLevel xmlns=`"$cns`">$(if ($ts) { PL-Get $ts 'currentLevel' 0 } else { 0 })</currentLevel>"
- X "$ind</pl:timeScale>"
- }
- function Emit-PlannerItem {
- param($it, [string]$ind)
- X "$ind<pl:item>"
- $ii = "$ind`t"
- Emit-PlannerValue (PL-Get $it 'value' $null) $ii
- Emit-PlannerText 'text' (PL-Get $it 'text' '') $ii
- Emit-PlannerText 'tooltip' (PL-Get $it 'tooltip' '') $ii
- X "$ii<pl:begin>$(PL-Get $it 'begin' '0001-01-01T00:00:00')</pl:begin>"
- X "$ii<pl:end>$(PL-Get $it 'end' '0001-01-01T00:00:00')</pl:end>"
- Emit-PlannerColor 'borderColor' $it 'borderColor' $ii
- Emit-PlannerColor 'backColor' $it 'backColor' $ii
- Emit-PlannerColor 'textColor' $it 'textColor' $ii
- Emit-PlannerFont $it $ii
- X "$ii<pl:dimensionValues/>"
- X "$ii<pl:replacementDate>$(PL-Get $it 'replacementDate' '0001-01-01T00:00:00')</pl:replacementDate>"
- X "$ii<pl:deleted>$(PL-Bool (PL-Get $it 'deleted' $false))</pl:deleted>"
- $id = PL-Get $it 'id' $null
- if ($null -eq $id) { $id = [guid]::NewGuid().ToString() }
- X "$ii<pl:id>$id</pl:id>"
- X "$ii<pl:textFormatted>$(PL-Bool (PL-Get $it 'textFormatted' $false))</pl:textFormatted>"
- Emit-PlannerBorder $it $ii 'border'
- X "$ii<pl:editMode>$(Esc-XmlText "$(PL-Get $it 'editMode' 'EnableEdit')")</pl:editMode>"
- X "$ind</pl:item>"
- }
- function Emit-PlannerDimElement {
- param($el, [string]$ind)
- X "$ind<pl:item>"
- $ii = "$ind`t"
- Emit-PlannerValue (PL-Get $el 'value' $null) $ii
- Emit-PlannerText 'text' (PL-Get $el 'text' '') $ii
- Emit-PlannerColor 'borderColor' $el 'borderColor' $ii
- Emit-PlannerColor 'backColor' $el 'backColor' $ii
- Emit-PlannerColor 'textColor' $el 'textColor' $ii
- Emit-PlannerFont $el $ii
- foreach ($sub in @(PL-Get $el 'elements' @())) { Emit-PlannerDimElement $sub $ii }
- X "$ii<pl:showOnlySubordinatesAreas>$(PL-Bool (PL-Get $el 'showOnlySubordinatesAreas' $true))</pl:showOnlySubordinatesAreas>"
- X "$ii<pl:textFormatted>$(PL-Bool (PL-Get $el 'textFormatted' $false))</pl:textFormatted>"
- X "$ind</pl:item>"
- }
- function Emit-PlannerDimension {
- param($d, [string]$ind)
- X "$ind<pl:dimension>"
- $di = "$ind`t"
- Emit-PlannerValue (PL-Get $d 'value' $null) $di
- Emit-PlannerText 'text' (PL-Get $d 'text' '') $di
- Emit-PlannerColor 'borderColor' $d 'borderColor' $di
- Emit-PlannerColor 'backColor' $d 'backColor' $di
- Emit-PlannerColor 'textColor' $d 'textColor' $di
- Emit-PlannerFont $d $di
- foreach ($el in @(PL-Get $d 'elements' @())) { Emit-PlannerDimElement $el $di }
- X "$di<pl:textFormatted>$(PL-Bool (PL-Get $d 'textFormatted' $false))</pl:textFormatted>"
- X "$ind</pl:dimension>"
- }
- function Emit-PlannerSettings {
- param($pl, [string]$ind)
- X "$ind<Settings xmlns:pl=`"$($script:PLANNER_NS)`" xsi:type=`"pl:Planner`">"
- $si = "$ind`t"
- foreach ($it in @(PL-Get $pl 'items' @())) { Emit-PlannerItem $it $si }
- foreach ($d in @(PL-Get $pl 'dimensions' @())) { Emit-PlannerDimension $d $si }
- Emit-PlannerColor 'borderColor' $pl 'borderColor' $si
- Emit-PlannerColor 'backColor' $pl 'backColor' $si
- Emit-PlannerColor 'textColor' $pl 'textColor' $si
- Emit-PlannerColor 'lineColor' $pl 'lineColor' $si
- Emit-PlannerFont $pl $si
- X "$si<pl:beginOfRepresentationPeriod>$(PL-Get $pl 'beginOfRepresentationPeriod' '0001-01-01T00:00:00')</pl:beginOfRepresentationPeriod>"
- X "$si<pl:endOfRepresentationPeriod>$(PL-Get $pl 'endOfRepresentationPeriod' '0001-01-01T00:00:00')</pl:endOfRepresentationPeriod>"
- X "$si<pl:alignElementsOfTimeScale>$(PL-Bool (PL-Get $pl 'alignElementsOfTimeScale' $true))</pl:alignElementsOfTimeScale>"
- X "$si<pl:displayTimeScaleWrapHeaders>$(PL-Bool (PL-Get $pl 'displayTimeScaleWrapHeaders' $true))</pl:displayTimeScaleWrapHeaders>"
- X "$si<pl:displayWrapHeaders>$(PL-Bool (PL-Get $pl 'displayWrapHeaders' $true))</pl:displayWrapHeaders>"
- $wfmt = PL-Get $pl 'timeScaleWrapHeadersFormat' $null
- if ($null -eq $wfmt) { $wfmt = [ordered]@{ '#' = 'DLF="DD"'; 'ru' = 'DLF="DD"' } }
- Emit-MLText -tag 'pl:timeScaleWrapHeadersFormat' -text $wfmt -indent $si
- X "$si<pl:periodicVariantUnit>$(Esc-XmlText "$(PL-Get $pl 'periodicVariantUnit' 'Day')")</pl:periodicVariantUnit>"
- X "$si<pl:periodicVariantRepetition>$(PL-Get $pl 'periodicVariantRepetition' 1)</pl:periodicVariantRepetition>"
- X "$si<pl:timeScaleWrapBeginIndent>$(PL-Get $pl 'timeScaleWrapBeginIndent' 0)</pl:timeScaleWrapBeginIndent>"
- X "$si<pl:timeScaleWrapEndIndent>$(PL-Get $pl 'timeScaleWrapEndIndent' 0)</pl:timeScaleWrapEndIndent>"
- Emit-PlannerTimeScale (PL-Get $pl 'timeScale' $null) $si
- $period = PL-Get $pl 'period' $null
- if ($period) {
- X "$si<pl:period>"
- X "$si`t<pl:begin>$(PL-Get $period 'begin' '0001-01-01T00:00:00')</pl:begin>"
- X "$si`t<pl:end>$(PL-Get $period 'end' '0001-01-01T00:00:00')</pl:end>"
- X "$si</pl:period>"
- }
- X "$si<pl:displayCurrentDate>$(PL-Bool (PL-Get $pl 'displayCurrentDate' $true))</pl:displayCurrentDate>"
- X "$si<pl:itemsTimeRepresentation>$(Esc-XmlText "$(PL-Get $pl 'itemsTimeRepresentation' 'BeginTime')")</pl:itemsTimeRepresentation>"
- X "$si<pl:itemsBehaviorWhenSpaceInsufficient>$(Esc-XmlText "$(PL-Get $pl 'itemsBehaviorWhenSpaceInsufficient' 'CollapseItems')")</pl:itemsBehaviorWhenSpaceInsufficient>"
- X "$si<pl:autoMinColumnWidth>$(PL-Bool (PL-Get $pl 'autoMinColumnWidth' $true))</pl:autoMinColumnWidth>"
- X "$si<pl:autoMinRowHeight>$(PL-Bool (PL-Get $pl 'autoMinRowHeight' $true))</pl:autoMinRowHeight>"
- X "$si<pl:minColumnWidth>$(PL-Get $pl 'minColumnWidth' 0)</pl:minColumnWidth>"
- X "$si<pl:minRowHeight>$(PL-Get $pl 'minRowHeight' 0)</pl:minRowHeight>"
- X "$si<pl:fixDimensionsHeader>$(Esc-XmlText "$(PL-Get $pl 'fixDimensionsHeader' 'auto')")</pl:fixDimensionsHeader>"
- X "$si<pl:fixTimeScaleHeader>$(Esc-XmlText "$(PL-Get $pl 'fixTimeScaleHeader' 'auto')")</pl:fixTimeScaleHeader>"
- Emit-PlannerBorder $pl $si 'border'
- X "$si<pl:newItemsTextType>$(Esc-XmlText "$(PL-Get $pl 'newItemsTextType' 'String')")</pl:newItemsTextType>"
- X "$ind</Settings>"
- }
- function Get-Keys { param($o) if ($o -is [System.Collections.IDictionary]) { return @($o.Keys) } else { return @($o.PSObject.Properties.Name) } }
- function Get-Prop { param($o, [string]$k) if ($o -is [System.Collections.IDictionary]) { return $o[$k] } else { $p = $o.PSObject.Properties[$k]; if ($p) { return $p.Value } else { return $null } } }
- function Emit-ChartNode {
- param([string]$name, $val, [string]$ind)
- if ($script:CHART_ML_FIELDS.Contains($name)) {
- if ($null -eq $val -or "$val" -eq '') { X "$ind<d4p1:$name/>"; return }
- X "$ind<d4p1:$name>"; Emit-MLItems -val $val -indent "$ind`t"; X "$ind</d4p1:$name>"; return
- }
- if (($val -is [System.Collections.IList]) -and ($val -isnot [string])) {
- foreach ($e in $val) { Emit-ChartNode $name $e $ind }
- return
- }
- if (($val -is [System.Management.Automation.PSCustomObject]) -or ($val -is [System.Collections.IDictionary])) {
- $keys = Get-Keys $val
- if ($script:CHART_ATTR_FIELDS.Contains($name)) {
- $attrs = @(); foreach ($k in $keys) { $v = Get-Prop $val $k; if ($v -is [bool]) { $v = PL-Bool $v }; $attrs += "$k=`"$(Esc-Xml "$v")`"" }
- X "$ind<d4p1:$name $($attrs -join ' ')/>"; return
- }
- if ($keys -contains 'gap') {
- $w = Get-Prop $val 'width'; $g = Get-Prop $val 'gap'; $st = Get-Prop $val 'style'
- X "$ind<d4p1:$name width=`"$w`" gap=`"$(PL-Bool $g)`">"
- X "$ind`t<v8ui:style xsi:type=`"v8ui:ChartLineType`">$(Esc-XmlText "$st")</v8ui:style>"
- X "$ind</d4p1:$name>"; return
- }
- if (($keys -contains 'style') -and ($keys -contains 'width')) {
- $w = Get-Prop $val 'width'; $st = Get-Prop $val 'style'
- X "$ind<d4p1:$name width=`"$w`">"
- X "$ind`t<v8ui:style xsi:type=`"v8ui:ControlBorderType`">$(Esc-XmlText "$st")</v8ui:style>"
- X "$ind</d4p1:$name>"; return
- }
- $isFont = $false; foreach ($fk in $script:CHART_FONT_KEYS) { if ($keys -contains $fk) { $isFont = $true; break } }
- if ($isFont) {
- $attrs = @(); foreach ($fk in $script:CHART_FONT_KEYS) { if ($keys -contains $fk) { $v = Get-Prop $val $fk; if ($v -is [bool]) { $v = PL-Bool $v }; $attrs += "$fk=`"$(Esc-Xml "$v")`"" } }
- X "$ind<d4p1:$name $($attrs -join ' ')/>"; return
- }
- if (@($keys).Count -eq 0) { X "$ind<d4p1:$name/>"; return }
- X "$ind<d4p1:$name>"
- foreach ($k in $keys) { Emit-ChartNode $k (Get-Prop $val $k) "$ind`t" }
- X "$ind</d4p1:$name>"
- return
- }
- if ($null -eq $val -or "$val" -eq '') { X "$ind<d4p1:$name/>"; return }
- if ($val -is [bool]) { X "$ind<d4p1:$name>$(PL-Bool $val)</d4p1:$name>"; return }
- X "$ind<d4p1:$name>$(Esc-XmlText "$val")</d4p1:$name>"
- }
- function Emit-ChartSettings {
- param($chart, [string]$ind, [string]$ctype = 'd4p1:Chart')
- X "$ind<Settings xmlns:d4p1=`"$($script:CHART_NS)`" xsi:type=`"$ctype`">"
- foreach ($k in (Get-Keys $chart)) { Emit-ChartNode $k (Get-Prop $chart $k) "$ind`t" }
- X "$ind</Settings>"
- }
- function Emit-Appearance {
- param($el, [string]$indent, [string]$profile = 'field')
- if ($null -eq $el) { return }
- $order = switch ($profile) {
- 'decoration' { $script:appOrderDecoration }
- 'button' { $script:appOrderButton }
- default { $script:appOrderField }
- }
- foreach ($key in $order) {
- $val = Get-AppearanceValue -el $el -canonical $key
- if ($null -eq $val -or ($val -is [string] -and $val -eq '')) { continue }
- $spec = $script:appearanceSpec[$key]
- switch ($spec.kind) {
- 'color' { X "$indent<$($spec.tag)>$(Esc-XmlText "$val")</$($spec.tag)>" }
- 'font' { Emit-FontTag -tag $spec.tag -val $val -indent $indent }
- 'border' { Emit-BorderTag -val $val -indent $indent }
- }
- }
- }
- function Emit-Layout {
- param($el, [string]$indent, [switch]$skipHeight, [bool]$multiLineDefault = $false)
- # CommandSet (отключённые команды редактора) — общее свойство поля (input/label/check/
- # spreadsheet/html/formatted/picture); в схеме рано (после TitleLocation, перед скалярами).
- if ($el.excludedCommands -and @($el.excludedCommands).Count -gt 0) {
- X "$indent<CommandSet>"
- foreach ($cmd in $el.excludedCommands) { X "$indent`t<ExcludedCommand>$cmd</ExcludedCommand>" }
- X "$indent</CommandSet>"
- }
- Emit-CommonElementProps -el $el -indent $indent
- $amwExplicit = ($el.PSObject.Properties.Name -contains 'autoMaxWidth')
- if ($amwExplicit) {
- if ((-not (Get-DslBool $el @('autoMaxWidth') $true))) { X "$indent<AutoMaxWidth>false</AutoMaxWidth>" }
- } elseif ($multiLineDefault) {
- X "$indent<AutoMaxWidth>false</AutoMaxWidth>"
- }
- if ($null -ne $el.maxWidth) { X "$indent<MaxWidth>$($el.maxWidth)</MaxWidth>" }
- if ((-not (Get-DslBool $el @('autoMaxHeight') $true))) { X "$indent<AutoMaxHeight>false</AutoMaxHeight>" }
- if ($null -ne $el.maxHeight) { X "$indent<MaxHeight>$($el.maxHeight)</MaxHeight>" }
- if ($el.width) { X "$indent<Width>$($el.width)</Width>" }
- if (-not $skipHeight -and $el.height) { X "$indent<Height>$($el.height)</Height>" }
- if ($null -ne $el.horizontalStretch) { X "$indent<HorizontalStretch>$(if ($el.horizontalStretch){'true'}else{'false'})</HorizontalStretch>" }
- if ($null -ne $el.verticalStretch) { X "$indent<VerticalStretch>$(if ($el.verticalStretch){'true'}else{'false'})</VerticalStretch>" }
- if ($el.groupHorizontalAlign) { X "$indent<GroupHorizontalAlign>$($el.groupHorizontalAlign)</GroupHorizontalAlign>" }
- if ($el.groupVerticalAlign) { X "$indent<GroupVerticalAlign>$($el.groupVerticalAlign)</GroupVerticalAlign>" }
- if ($el.horizontalAlign) { X "$indent<HorizontalAlign>$($el.horizontalAlign)</HorizontalAlign>" }
- Emit-GenericScalars -el $el -indent $indent
- }
- function Title-FromName {
- param([string]$name)
- if (-not $name) { return '' }
- $s = [regex]::Replace($name, '([А-ЯA-Z])([А-ЯA-Z][а-яa-z])', '$1 $2')
- $s = [regex]::Replace($s, '([а-яa-z0-9])([А-ЯA-Z])', '$1 $2')
- $parts = $s -split ' '
- if ($parts.Count -eq 0) { return $s }
- $out = New-Object System.Collections.ArrayList
- [void]$out.Add($parts[0])
- for ($i = 1; $i -lt $parts.Count; $i++) {
- $p = $parts[$i]
- if ($p.Length -gt 1 -and $p -ceq $p.ToUpper()) {
- [void]$out.Add($p)
- } else {
- [void]$out.Add($p.ToLower())
- }
- }
- return ($out -join ' ')
- }
- function Emit-Title {
- # Нет ключа title → авто-вывод из имени (помощь модели).
- # Явный title: "" (или null) → подавить (заголовок не эмитим).
- # Явный непустой → эмитим как есть.
- param($el, [string]$name, [string]$indent, [switch]$auto)
- $hasKey = $null -ne $el.PSObject.Properties['title']
- if ($hasKey) {
- if ($el.title) { Emit-MLText -tag "Title" -text $el.title -indent $indent }
- } elseif ($auto -and $name) {
- Emit-MLText -tag "Title" -text (Title-FromName -name $name) -indent $indent
- }
- # ToolTip элемента (всплывающая подсказка) — по схеме сразу после Title.
- if ($el.tooltip) { Emit-MLText -tag "ToolTip" -text $el.tooltip -indent $indent }
- # ToolTipRepresentation — режим показа подсказки (None/Button/ShowBottom/…), после ToolTip.
- if ($el.tooltipRepresentation) { X "$indent<ToolTipRepresentation>$($el.tooltipRepresentation)</ToolTipRepresentation>" }
- }
- function Map-TitleLoc {
- param([string]$v)
- switch ("$v".ToLower()) {
- "none" { "None" }
- "left" { "Left" }
- "right" { "Right" }
- "top" { "Top" }
- "bottom" { "Bottom" }
- "auto" { "Auto" }
- default { "$v" }
- }
- }
- function Emit-TitleLocation {
- param($el, [string]$indent, [string]$smartDefault)
- if ($null -ne $el.PSObject.Properties['titleLocation']) {
- if ($el.titleLocation) { X "$indent<TitleLocation>$(Map-TitleLoc "$($el.titleLocation)")</TitleLocation>" }
- } elseif ($smartDefault) {
- X "$indent<TitleLocation>$smartDefault</TitleLocation>"
- }
- }
- function Warn-Unrecognized {
- # drop-on-miss enum: значение не распознано → тег не эмитится. Громко, чтобы автор увидел потерю.
- param([string]$key, $raw, [string[]]$valid, [string]$owner)
- Write-Warning "Unrecognized $key '$raw' on '$owner'. Valid values: $($valid -join ', '). Value ignored."
- }
- function Emit-Group {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<UsualGroup name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- Emit-Title -el $el -name $name -indent $inner
- # Group orientation (направление). Legacy: group:'collapsible' = Vertical + behavior collapsible.
- $groupVal = "$($el.group)".ToLower()
- $orientation = switch ($groupVal) {
- "horizontal" { "Horizontal" }
- "vertical" { "Vertical" }
- "alwayshorizontal" { "AlwaysHorizontal" }
- "alwaysvertical" { "Vertical" } # старое написание; у группы такого значения нет
- "horizontalifpossible" { "HorizontalIfPossible" }
- "collapsible" { "Vertical" }
- default { $null }
- }
- if ($orientation) { X "$inner<Group>$orientation</Group>" }
- elseif ($groupVal) { Warn-Unrecognized 'group orientation' $el.group @('vertical','horizontalIfPossible','alwaysHorizontal') $name }
- # Behavior: ключ behavior (usual/collapsible/popup) → <Behavior>; отсутствие = Авто (не эмитим).
- # Legacy: group:'collapsible' эквивалентно behavior:'collapsible'.
- $behaviorVal = if ($el.behavior) { "$($el.behavior)".ToLower() } elseif ($groupVal -eq "collapsible") { "collapsible" } else { $null }
- $bmap = @{ "usual"="Usual"; "collapsible"="Collapsible"; "popup"="PopUp" }
- if ($behaviorVal -and $bmap.ContainsKey($behaviorVal)) {
- X "$inner<Behavior>$($bmap[$behaviorVal])</Behavior>"
- } elseif ($el.behavior -and -not $bmap.ContainsKey($behaviorVal)) {
- Warn-Unrecognized 'behavior' $el.behavior @('collapsible','popup') $name
- }
- # Collapsed — у Collapsible и PopUp (не привязано к одному behavior)
- if ((Get-DslBool $el @('collapsed') $false)) { X "$inner<Collapsed>true</Collapsed>" }
- # Representation
- if ($el.representation) {
- $repr = switch ("$($el.representation)") {
- "none" { "None" }
- "normal" { "NormalSeparation" }
- "weak" { "WeakSeparation" }
- "strong" { "StrongSeparation" }
- default { "$($el.representation)" }
- }
- X "$inner<Representation>$repr</Representation>"
- }
- # Использование текущей строки группы (после Representation, порядок XSD)
- if ($el.currentRowUse) { X "$inner<CurrentRowUse>$($el.currentRowUse)</CurrentRowUse>" }
- # ShowTitle
- # Обычная группа без showTitle: заголовок показан, если он задан (title или titleDataPath), иначе скрыт — служебная группа
- # раскладки без заголовка давала бы пустую строку-заголовок (умолчание платформы — показан).
- # У сворачиваемой/всплывающей заголовок — переключатель: умолчание платформы, пишется лишь явный false.
- if (@('collapsible','popup') -contains $behaviorVal) {
- if ($null -ne $el.showTitle -and -not $el.showTitle) { X "$inner<ShowTitle>false</ShowTitle>" }
- } elseif ($null -ne $el.showTitle) {
- if (-not ((Get-DslBool $el @('showTitle') $false))) { X "$inner<ShowTitle>false</ShowTitle>" }
- } elseif (-not $el.title -and -not $el.titleDataPath) { X "$inner<ShowTitle>false</ShowTitle>" }
- # Заголовок свёрнутого представления (collapsible/popup) — мультиязычный текст
- if ($el.collapsedTitle) { Emit-MLText -tag "CollapsedRepresentationTitle" -text $el.collapsedTitle -indent $inner }
- # United
- if ((-not (Get-DslBool $el @('united') $true))) { X "$inner<United>false</United>" }
- # Формат значения пути к данным заголовка (<Format>; парный к titleDataPath группы)
- if ($el.format) { Emit-MLText -tag "Format" -text $el.format -indent $inner }
- if ($el.editFormat) { Emit-MLText -tag "EditFormat" -text $el.editFormat -indent $inner }
- Emit-CommonFlags -el $el -indent $inner
- Emit-Layout -el $el -indent $inner
- # Оформление (цвета/шрифты/граница) — перед компаньоном
- Emit-Appearance -el $el -indent $inner -profile 'field'
- # Companion: ExtendedTooltip
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- Emit-Events -el $el -elementName $name -indent $inner -xmlTag "UsualGroup"
- # Children
- if ($el.children -and $el.children.Count -gt 0) {
- X "$inner<ChildItems>"
- foreach ($child in $el.children) {
- Emit-Element -el $child -indent "$inner`t"
- }
- X "$inner</ChildItems>"
- }
- X "$indent</UsualGroup>"
- }
- function Emit-ColumnGroup {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<ColumnGroup name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- Warn-EventsIgnored $el "ColumnGroup" $name
- Emit-Title -el $el -name $name -indent $inner
- # Group orientation (horizontal / vertical / inCell — последнее только здесь)
- $groupVal = "$($el.columnGroup)"
- $orientation = switch ($groupVal) {
- "horizontal" { "Horizontal" }
- "vertical" { "Vertical" }
- "inCell" { "InCell" }
- default { $null }
- }
- if ($orientation) { X "$inner<Group>$orientation</Group>" }
- elseif ($groupVal) { Warn-Unrecognized 'columnGroup orientation' $el.columnGroup @('vertical','horizontal','inCell') $name }
- # ShowTitle=true — умолчание платформы (в корпусе только false): пишем лишь false
- if ($null -ne $el.showTitle -and -not $el.showTitle) { X "$inner<ShowTitle>false</ShowTitle>" }
- # showInHeader эмитится общим Emit-CommonElementProps (через Emit-Layout)
- Emit-CommonFlags -el $el -indent $inner
- Emit-Layout -el $el -indent $inner
- # Картинка заголовка колонки-группы (после ShowInHeader/Layout, перед оформлением — порядок XSD)
- Emit-ColumnPics -el $el -indent $inner
- # Оформление (цвета/шрифты/граница) — перед компаньоном
- Emit-Appearance -el $el -indent $inner -profile 'field'
- # Companion: ExtendedTooltip
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- # Children
- if ($el.children -and $el.children.Count -gt 0) {
- X "$inner<ChildItems>"
- foreach ($child in $el.children) {
- Emit-Element -el $child -indent "$inner`t"
- }
- X "$inner</ChildItems>"
- }
- X "$indent</ColumnGroup>"
- }
- function Emit-Input {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<InputField name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
- Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
- Emit-CommonFlags -el $el -indent $inner
- if ($el.titleLocation) { X "$inner<TitleLocation>$(Map-TitleLoc "$($el.titleLocation)")</TitleLocation>" }
- if ($null -ne $el.multiLine) { X "$inner<MultiLine>$(if ($el.multiLine){'true'}else{'false'})</MultiLine>" }
- if ($null -ne $el.passwordMode) { X "$inner<PasswordMode>$(if ($el.passwordMode){'true'}else{'false'})</PasswordMode>" }
- # ChoiceButton — захват «как есть» (платформа эмитит явное значение; ref-поля выводят сама,
- # декомпилятор фиксирует факт. значение). Нет ключа → не эмитим (не додумываем по событию).
- if ($null -ne $el.choiceButton) { X "$inner<ChoiceButton>$(if ($el.choiceButton){'true'}else{'false'})</ChoiceButton>" }
- # Кнопки поля ввода — захват «как есть» (платформа эмитит явное значение, в т.ч. false)
- if ($null -ne $el.clearButton) { X "$inner<ClearButton>$(if ($el.clearButton){'true'}else{'false'})</ClearButton>" }
- if ($null -ne $el.spinButton) { X "$inner<SpinButton>$(if ($el.spinButton){'true'}else{'false'})</SpinButton>" }
- if ($null -ne $el.dropListButton) { X "$inner<DropListButton>$(if ($el.dropListButton){'true'}else{'false'})</DropListButton>" }
- if ($null -ne $el.choiceListButton) { X "$inner<ChoiceListButton>$(if ($el.choiceListButton){'true'}else{'false'})</ChoiceListButton>" }
- if ($null -ne $el.markIncomplete) { X "$inner<AutoMarkIncomplete>$(if ($el.markIncomplete){'true'}else{'false'})</AutoMarkIncomplete>" }
- if ($el.editMode) { X "$inner<EditMode>$($el.editMode)</EditMode>" }
- Emit-ColumnPics -el $el -indent $inner
- if ((-not (Get-DslBool $el @('textEdit') $true))) { X "$inner<TextEdit>false</TextEdit>" }
- # InputField-специфичные скаляры (захват «как есть»: платформа эмитит явное не-дефолтное значение)
- foreach ($p in @(
- @('wrap','Wrap'), @('openButton','OpenButton'), @('listChoiceMode','ListChoiceMode'),
- @('extendedEditMultipleValues','ExtendedEditMultipleValues'), @('chooseType','ChooseType'),
- @('quickChoice','QuickChoice'), @('autoChoiceIncomplete','AutoChoiceIncomplete')
- )) {
- if ($null -ne $el.($p[0])) { X "$inner<$($p[1])>$(if ($el.($p[0])){'true'}else{'false'})</$($p[1])>" }
- }
- # Ограничение доступных типов (поле на составном типе): домен типов + явный набор.
- # availableTypes — формат типа реквизита (§type); Emit-Type сам разбирает мультитип "a | b".
- if ($null -ne $el.typeDomainEnabled) { X "$inner<TypeDomainEnabled>$(if ($el.typeDomainEnabled){'true'}else{'false'})</TypeDomainEnabled>" }
- if ($el.availableTypes) { Emit-Type -typeStr $el.availableTypes -indent $inner -tag 'AvailableTypes' }
- # InputField-специфичные value-скаляры
- foreach ($p in @(
- @('choiceForm','ChoiceForm'), @('choiceHistoryOnInput','ChoiceHistoryOnInput'),
- @('choiceFoldersAndItems','ChoiceFoldersAndItems'), @('footerDataPath','FooterDataPath')
- )) {
- if ($el.($p[0])) { X "$inner<$($p[1])>$(Esc-XmlText "$($el.($p[0]))")</$($p[1])>" }
- }
- # MinValue/MaxValue — типизированное. JSON-число → xs:decimal, строка → xs:string (тип сохранён декомпилятором).
- foreach ($p in @(@('minValue','MinValue'), @('maxValue','MaxValue'))) {
- if ($null -ne $el.($p[0])) {
- $mvt = if ($el.($p[0]) -is [string]) { 'xs:string' } else { 'xs:decimal' }
- X "$inner<$($p[1]) xsi:type=`"$mvt`">$(Esc-XmlText "$($el.($p[0]))")</$($p[1])>"
- }
- }
- if ($el.choiceButtonRepresentation) { X "$inner<ChoiceButtonRepresentation>$($el.choiceButtonRepresentation)</ChoiceButtonRepresentation>" }
- Emit-PictureRef -val $el.choiceButtonPicture -picTag 'ChoiceButtonPicture' -indent $inner
- Emit-Layout -el $el -indent $inner -multiLineDefault ([bool]((Get-DslBool $el @('multiLine') $false)))
- if ($el.inputHint) {
- Emit-MLText -tag "InputHint" -text $el.inputHint -indent $inner
- }
- if ($null -ne $el.warningOnEdit) { Emit-MLText -tag "WarningOnEdit" -text $el.warningOnEdit -indent $inner }
- if ($null -ne $el.footerText) { Emit-MLText -tag "FooterText" -text $el.footerText -indent $inner }
- # Формат / формат редактирования (LocalStringType — строка или {ru,en})
- if ($el.format) { Emit-MLText -tag "Format" -text $el.format -indent $inner }
- if ($el.editFormat) { Emit-MLText -tag "EditFormat" -text $el.editFormat -indent $inner }
- Emit-ChoiceList -el $el -indent $inner
- # Связи по типу / связи параметров выбора / параметры выбора
- Emit-TypeLink -el $el -indent $inner
- Emit-ChoiceParameterLinks -el $el -indent $inner
- Emit-ChoiceParameters -el $el -indent $inner
- # Оформление (цвета/шрифты/граница) — перед компаньонами
- Emit-Appearance -el $el -indent $inner -profile 'field'
- # Companions
- Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- Emit-Events -el $el -elementName $name -indent $inner -xmlTag "InputField"
- X "$indent</InputField>"
- }
- function Emit-Check {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<CheckBoxField name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
- Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
- Emit-CommonFlags -el $el -indent $inner
- if ($el.editMode) { X "$inner<EditMode>$($el.editMode)</EditMode>" }
- Emit-ColumnPics -el $el -indent $inner
- # CheckBoxType: нет ключа → умный дефолт Auto; "" → подавить; значение → маппинг
- if ($null -ne $el.PSObject.Properties['checkBoxType']) {
- if ($el.checkBoxType) {
- $cbt = switch ("$($el.checkBoxType)".ToLower()) { 'auto' {'Auto'} 'checkbox' {'CheckBox'} 'switcher' {'Switcher'} 'tumbler' {'Tumbler'} default {"$($el.checkBoxType)"} }
- X "$inner<CheckBoxType>$cbt</CheckBoxType>"
- }
- } else { X "$inner<CheckBoxType>Auto</CheckBoxType>" }
- Emit-TitleLocation -el $el -indent $inner -smartDefault "Right"
- Emit-Layout -el $el -indent $inner
- if ($null -ne $el.warningOnEdit) { Emit-MLText -tag "WarningOnEdit" -text $el.warningOnEdit -indent $inner }
- # FooterDataPath / FooterText — общие cell-свойства колонки (как у input/labelField)
- if ($el.footerDataPath) { X "$inner<FooterDataPath>$(Esc-XmlText "$($el.footerDataPath)")</FooterDataPath>" }
- if ($null -ne $el.footerText) { Emit-MLText -tag "FooterText" -text $el.footerText -indent $inner }
- # Формат / формат редактирования (LocalStringType — строка или {ru,en})
- if ($el.format) { Emit-MLText -tag "Format" -text $el.format -indent $inner }
- if ($el.editFormat) { Emit-MLText -tag "EditFormat" -text $el.editFormat -indent $inner }
- # Оформление (цвета/шрифты/граница) — перед компаньонами
- Emit-Appearance -el $el -indent $inner -profile 'field'
- # Companions
- Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- Emit-Events -el $el -elementName $name -indent $inner -xmlTag "CheckBoxField"
- X "$indent</CheckBoxField>"
- }
- function Normalize-MetaTypeRef {
- param([string]$ref)
- if ([string]::IsNullOrEmpty($ref)) { return $ref }
- $dot = $ref.IndexOf('.')
- if ($dot -lt 1) { return $ref }
- $root = $ref.Substring(0, $dot)
- if ($script:refRootSynonyms.ContainsKey($root)) {
- return $script:refRootSynonyms[$root] + $ref.Substring($dot)
- }
- return $ref
- }
- function Normalize-ChoiceValue {
- param($value)
- # Booleans
- if ($value -is [bool]) {
- return @{ XsiType = "xs:boolean"; Text = if ($value) { "true" } else { "false" } }
- }
- # Numbers (int / decimal / double)
- if ($value -is [int] -or $value -is [long] -or $value -is [double] -or $value -is [decimal]) {
- return @{ XsiType = "xs:decimal"; Text = "$value" }
- }
- $s = "$value"
- if ([string]::IsNullOrEmpty($s)) {
- return @{ XsiType = "xs:string"; Text = "" }
- }
- # ISO datetime ("2020-01-01T00:00:00") → xs:dateTime
- if ($s -match '^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$') {
- return @{ XsiType = "xs:dateTime"; Text = $s }
- }
- # Raw-ссылка по GUID (метаданные.значение, оба GUID): "GUID.GUID" → xr:DesignTimeRef
- # (всегда ссылка, не строка; named-ссылки Enum.X.Y детектятся ниже).
- if ($s -match '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\.[0-9a-fA-F]{8}-[0-9a-fA-F-]+$') {
- return @{ XsiType = "xr:DesignTimeRef"; Text = $s }
- }
- # Try to detect typed reference path: "<Root>.<Type>[.<Member>.<Value>]"
- $parts = $s -split '\.'
- if ($parts.Count -ge 2) {
- $root = $parts[0]
- $canonRoot = $null
- if ($script:refRootSynonyms.ContainsKey($root)) { $canonRoot = $script:refRootSynonyms[$root] }
- elseif ($script:refRootSynonyms.Values -contains $root) { $canonRoot = $root }
- if ($canonRoot) {
- $typeName = $parts[1]
- $normalized = $null
- if ($canonRoot -eq "Enum") {
- if ($parts.Count -eq 2) {
- # "Enum.X" alone — not a value, treat as string
- } elseif ($parts.Count -eq 3) {
- # "Enum.X.Y" — insert .EnumValue. ("EmptyRef" — пустая ссылка, БЕЗ вставки)
- if ($parts[2] -eq 'EmptyRef') { $normalized = "Enum.$typeName.EmptyRef" }
- else { $normalized = "Enum.$typeName.EnumValue.$($parts[2])" }
- } else {
- # "Enum.X.<member>.Y..." — replace member with EnumValue (handles ЗначениеПеречисления too)
- $member = $parts[2]
- if ($script:enumValueSynonyms -contains $member) {
- $rest = $parts[3..($parts.Count-1)] -join '.'
- $normalized = "Enum.$typeName.EnumValue.$rest"
- } else {
- $rest = $parts[2..($parts.Count-1)] -join '.'
- $normalized = "Enum.$typeName.EnumValue.$rest"
- }
- }
- } else {
- # Other ref roots: just translate root, keep tail as-is
- if ($parts.Count -ge 3) {
- $tail = $parts[1..($parts.Count-1)] -join '.'
- $normalized = "$canonRoot.$tail"
- }
- }
- if ($normalized) {
- return @{ XsiType = "xr:DesignTimeRef"; Text = $normalized }
- }
- }
- }
- return @{ XsiType = "xs:string"; Text = $s }
- }
- function Emit-ChoicePresentation {
- param($pres, [string]$indent)
- if ($null -eq $pres -or ($pres -is [string] -and [string]::IsNullOrEmpty($pres))) {
- X "$indent<Presentation/>"
- return
- }
- $pairs = @()
- if ($pres -is [string]) {
- $pairs += ,@("ru", $pres)
- } elseif ($pres -is [hashtable] -or $pres -is [System.Collections.IDictionary]) {
- foreach ($k in $pres.Keys) { $pairs += ,@("$k", "$($pres[$k])") }
- } elseif ($pres.PSObject -and $pres.PSObject.Properties) {
- foreach ($p in $pres.PSObject.Properties) { $pairs += ,@("$($p.Name)", "$($p.Value)") }
- } else {
- $pairs += ,@("ru", "$pres")
- }
- X "$indent<Presentation>"
- foreach ($pair in $pairs) {
- X "$indent`t<v8:item>"
- X "$indent`t`t<v8:lang>$($pair[0])</v8:lang>"
- X "$indent`t`t<v8:content>$(Esc-XmlText $pair[1])</v8:content>"
- X "$indent`t</v8:item>"
- }
- X "$indent</Presentation>"
- }
- function Get-ChoiceValueTag {
- param($norm)
- if ([string]::IsNullOrEmpty($norm.Text)) { return "<Value xsi:type=`"$($norm.XsiType)`"/>" }
- return "<Value xsi:type=`"$($norm.XsiType)`">$(Esc-XmlText $norm.Text)</Value>"
- }
- function Emit-ChoiceList {
- param($el, [string]$indent)
- if (-not $el.choiceList -or $el.choiceList.Count -eq 0) { return }
- X "$indent<ChoiceList>"
- $itemIndent = "$indent`t"
- foreach ($item in $el.choiceList) {
- # value (+ рус. синоним "значение")
- $valRaw = $null
- if ($item -is [hashtable] -or $item -is [System.Collections.IDictionary]) {
- if ($item.Contains("value")) { $valRaw = $item["value"] }
- elseif ($item.Contains("значение")) { $valRaw = $item["значение"] }
- } else {
- if ($item.PSObject.Properties["value"]) { $valRaw = $item.value }
- elseif ($item.PSObject.Properties["значение"]) { $valRaw = $item."значение" }
- }
- # presentation (presentation OR title синоним)
- $presRaw = $null
- $hasPres = $false
- if ($item -is [hashtable] -or $item -is [System.Collections.IDictionary]) {
- if ($item.Contains("presentation")) { $presRaw = $item["presentation"]; $hasPres = $true }
- elseif ($item.Contains("представление")) { $presRaw = $item["представление"]; $hasPres = $true }
- elseif ($item.Contains("title")) { $presRaw = $item["title"]; $hasPres = $true }
- } else {
- if ($item.PSObject.Properties["presentation"]) { $presRaw = $item.presentation; $hasPres = $true }
- elseif ($item.PSObject.Properties["представление"]) { $presRaw = $item."представление"; $hasPres = $true }
- elseif ($item.PSObject.Properties["title"]) { $presRaw = $item.title; $hasPres = $true }
- }
- # valueType: явный xsi:type значения (системное перечисление ent:*, иной не-примитив) —
- # переопределяет авто-детект (Normalize-ChoiceValue вывела бы xs:string).
- $vtRaw = $null
- if ($item -is [hashtable] -or $item -is [System.Collections.IDictionary]) {
- if ($item.Contains("valueType")) { $vtRaw = "$($item["valueType"])" }
- } elseif ($item.PSObject.Properties["valueType"]) { $vtRaw = "$($item.valueType)" }
- if ($vtRaw -eq 'nil') { $norm = @{ XsiType = $null; Text = $null; Nil = $true } }
- elseif ($vtRaw) { $norm = @{ XsiType = $vtRaw; Text = "$valRaw" } }
- else { $norm = Normalize-ChoiceValue -value $valRaw }
- # авто-вывод presentation, если не задан
- if (-not $hasPres) {
- if ($norm.XsiType -eq "xr:DesignTimeRef") {
- $tail = ($norm.Text -split '\.')[-1]
- $presRaw = Title-FromName -name $tail
- } else {
- $presRaw = $norm.Text
- }
- }
- X "$itemIndent<xr:Item>"
- $valIndent = "$itemIndent`t"
- X "$valIndent<xr:Presentation/>"
- X "$valIndent<xr:CheckState>0</xr:CheckState>"
- X "$valIndent<xr:Value xsi:type=`"FormChoiceListDesTimeValue`">"
- Emit-ChoicePresentation -pres $presRaw -indent "$valIndent`t"
- X "$valIndent`t$(if ($norm.Nil) { '<Value xsi:nil="true"/>' } else { Get-ChoiceValueTag $norm })"
- X "$valIndent</xr:Value>"
- X "$itemIndent</xr:Item>"
- }
- X "$indent</ChoiceList>"
- }
- function Get-ElProp {
- param($obj, [string[]]$names)
- if ($null -eq $obj) { return $null }
- foreach ($n in $names) {
- if ($obj -is [System.Collections.IDictionary]) {
- if ($obj.Contains($n)) { return $obj[$n] }
- } elseif ($obj.PSObject -and $obj.PSObject.Properties[$n]) {
- return $obj.PSObject.Properties[$n].Value
- }
- }
- return $null
- }
- function ConvertTo-ScalarLiteral {
- param([string]$s)
- $t = "$s".Trim()
- if ($t -match '^(?i:true)$') { return $true }
- if ($t -match '^(?i:false)$') { return $false }
- if ($t -match '^-?\d+$') { return [int]$t }
- if ($t -match '^-?\d+\.\d+$') { return [double]::Parse($t, [System.Globalization.CultureInfo]::InvariantCulture) }
- return $t
- }
- function ConvertFrom-ChoiceParamShorthand {
- param([string]$s)
- $eq = $s.IndexOf('=')
- if ($eq -lt 0) { return @{ name = $s.Trim() } }
- $name = $s.Substring(0, $eq).Trim()
- $rest = $s.Substring($eq + 1)
- if ($rest -match ',') {
- $vals = @()
- foreach ($part in ($rest -split ',')) { $vals += ,(ConvertTo-ScalarLiteral $part) }
- return @{ name = $name; value = $vals }
- }
- return @{ name = $name; value = (ConvertTo-ScalarLiteral $rest) }
- }
- function ConvertFrom-ChoiceParamLinkShorthand {
- param([string]$s)
- $eq = $s.IndexOf('=')
- if ($eq -lt 0) { return @{ name = $s.Trim() } }
- $o = @{ name = $s.Substring(0, $eq).Trim() }
- $rest = $s.Substring($eq + 1).Trim()
- if ($rest -match '^(.*):(?i:(Clear|DontChange|очистить|неизменять))$') {
- $o['dataPath'] = $matches[1].Trim(); $o['valueChange'] = $matches[2]
- } else {
- $o['dataPath'] = $rest
- }
- return $o
- }
- function ConvertFrom-TypeLinkShorthand {
- param([string]$s)
- if ($s -match '^(.*)#(\d+)$') { return @{ dataPath = $matches[1].Trim(); linkItem = [int]$matches[2] } }
- return @{ dataPath = "$s".Trim() }
- }
- function Emit-ChoiceParamValue {
- # $isArray передаётся ЯВНО из вызывающего кода: PowerShell разворачивает одноэлементный массив
- # при биндинге параметра ($value становится скаляром), поэтому определять массив тут — ненадёжно
- # (1-элементный список `["X"]` эмитился бы скаляром вместо FixedArray). foreach по скаляру = 1 итерация.
- param($value, [string]$indent, [bool]$isArray)
- X "$indent<Presentation/>"
- if ($isArray) {
- X "$indent<Value xsi:type=`"v8:FixedArray`">"
- foreach ($v in $value) {
- $norm = Normalize-ChoiceValue -value $v
- X "$indent`t<v8:Value xsi:type=`"FormChoiceListDesTimeValue`">"
- X "$indent`t`t<Presentation/>"
- X "$indent`t`t$(Get-ChoiceValueTag $norm)"
- X "$indent`t</v8:Value>"
- }
- X "$indent</Value>"
- } else {
- $norm = Normalize-ChoiceValue -value $value
- X "$indent$(Get-ChoiceValueTag $norm)"
- }
- }
- function Emit-ChoiceParameters {
- param($el, [string]$indent)
- $cp = $el.choiceParameters
- if (-not $cp -or @($cp).Count -eq 0) { return }
- X "$indent<ChoiceParameters>"
- foreach ($item in @($cp)) {
- if ($item -is [string]) { $item = ConvertFrom-ChoiceParamShorthand $item }
- $name = Get-ElProp $item @('name','имя')
- # Наличие ключа value (≠ значения) + ПРЯМОЙ доступ к значению (без Get-ElProp): его return
- # разворачивает 1-элементный массив (PS unwrap), теряя массив-ность → FixedArray не эмитится.
- # Индексер/member-доступ массив сохраняет; if-выражение/функция-return — нет.
- $hasVal = $false; $val = $null
- if ($item -is [System.Collections.IDictionary]) {
- if ($item.Contains('value')) { $hasVal = $true; $val = $item['value'] }
- elseif ($item.Contains('значение')) { $hasVal = $true; $val = $item['значение'] }
- } else {
- if ($item.PSObject.Properties['value']) { $hasVal = $true; $val = $item.PSObject.Properties['value'].Value }
- elseif ($item.PSObject.Properties['значение']) { $hasVal = $true; $val = $item.PSObject.Properties['значение'].Value }
- }
- $valIsArray = ($val -is [System.Array]) -or ($val -is [System.Collections.IList] -and $val -isnot [string])
- X "$indent`t<app:item name=`"$(Esc-Xml "$name")`">"
- # Параметр выбора без значения → <app:value xsi:nil="true"/> (платформа, 13 в корпусе);
- # со значением (в т.ч. пустой строкой) → FormChoiceListDesTimeValue.
- if (-not $hasVal) {
- X "$indent`t`t<app:value xsi:nil=`"true`"/>"
- } else {
- X "$indent`t`t<app:value xsi:type=`"FormChoiceListDesTimeValue`">"
- Emit-ChoiceParamValue -value $val -indent "$indent`t`t`t" -isArray $valIsArray
- X "$indent`t`t</app:value>"
- }
- X "$indent`t</app:item>"
- }
- X "$indent</ChoiceParameters>"
- }
- function Emit-ChoiceParameterLinks {
- param($el, [string]$indent)
- $cpl = $el.choiceParameterLinks
- if (-not $cpl -or @($cpl).Count -eq 0) { return }
- X "$indent<ChoiceParameterLinks>"
- foreach ($lk in @($cpl)) {
- if ($lk -is [string]) { $lk = ConvertFrom-ChoiceParamLinkShorthand $lk }
- $name = Get-ElProp $lk @('name','имя')
- $dp = Get-ElProp $lk @('dataPath','path','путь')
- $vcRaw = Get-ElProp $lk @('valueChange','режимИзменения')
- $vc = "Clear"
- if ($vcRaw) {
- $vc = switch -Regex ("$vcRaw".ToLower()) {
- '^(clear|очистить|очистка)$' { "Clear"; break }
- '^(dontchange|неизменять|неменять|нет)$' { "DontChange"; break }
- default { "$vcRaw" }
- }
- }
- X "$indent`t<xr:Link>"
- X "$indent`t`t<xr:Name>$(Esc-XmlText "$name")</xr:Name>"
- X "$indent`t`t<xr:DataPath xsi:type=`"xs:string`">$(Esc-XmlText "$dp")</xr:DataPath>"
- X "$indent`t`t<xr:ValueChange>$vc</xr:ValueChange>"
- X "$indent`t</xr:Link>"
- }
- X "$indent</ChoiceParameterLinks>"
- }
- function Emit-TypeLink {
- param($el, [string]$indent)
- $tl = $el.typeLink
- if (-not $tl) { return }
- if ($tl -is [string]) { $tl = ConvertFrom-TypeLinkShorthand $tl }
- $dp = Get-ElProp $tl @('dataPath','path','путь')
- $li = Get-ElProp $tl @('linkItem','элементСвязи')
- if ($null -eq $li) { $li = 0 }
- X "$indent<TypeLink>"
- X "$indent`t<xr:DataPath>$(Esc-XmlText "$dp")</xr:DataPath>"
- X "$indent`t<xr:LinkItem>$li</xr:LinkItem>"
- X "$indent</TypeLink>"
- }
- function Emit-Radio {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<RadioButtonField name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
- Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
- Emit-CommonFlags -el $el -indent $inner
- if ($el.editMode) { X "$inner<EditMode>$($el.editMode)</EditMode>" }
- Emit-TitleLocation -el $el -indent $inner -smartDefault "None"
- # RadioButtonType: Auto | RadioButtons | Tumbler. Accept synonyms.
- $rbtRaw = if ($el.radioButtonType) { "$($el.radioButtonType)".Trim() } else { "Auto" }
- $rbt = switch -Regex ($rbtRaw.ToLower()) {
- '^(auto|авто)$' { "Auto"; break }
- '^(radiobuttons?|переключатель|радио)$' { "RadioButtons"; break }
- '^(tumbler|тумблер)$' { "Tumbler"; break }
- default { $rbtRaw }
- }
- X "$inner<RadioButtonType>$rbt</RadioButtonType>"
- if ($null -ne $el.columnsCount) {
- X "$inner<ColumnsCount>$($el.columnsCount)</ColumnsCount>"
- }
- Emit-ChoiceList -el $el -indent $inner
- Emit-Layout -el $el -indent $inner
- if ($null -ne $el.warningOnEdit) { Emit-MLText -tag "WarningOnEdit" -text $el.warningOnEdit -indent $inner }
- # Оформление (цвета/шрифты/граница) — перед компаньонами
- Emit-Appearance -el $el -indent $inner -profile 'field'
- # Companions
- Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- Emit-Events -el $el -elementName $name -indent $inner -xmlTag "RadioButtonField"
- X "$indent</RadioButtonField>"
- }
- function Emit-DecorationTitle {
- param($el, [string]$name, [string]$indent, [switch]$auto)
- $hasKey = $null -ne $el.PSObject.Properties['title']
- $titleVal = if ($hasKey) { $el.title } elseif ($auto -and $name) { Title-FromName -name $name } else { $null }
- if ($titleVal) {
- $r = Resolve-MLFormatted $titleVal
- $fmt = if ($null -ne $el.PSObject.Properties['formatted']) { (ConvertTo-DslBool $el.formatted 'formatted' $false) } else { $r.formatted }
- X "$indent<Title formatted=`"$(if ($fmt) { 'true' } else { 'false' })`">"
- Emit-MLItems -val $r.text -indent "$indent`t"
- X "$indent</Title>"
- }
- if ($el.tooltip) { Emit-MLText -tag "ToolTip" -text $el.tooltip -indent $indent }
- if ($el.tooltipRepresentation) { X "$indent<ToolTipRepresentation>$($el.tooltipRepresentation)</ToolTipRepresentation>" }
- }
- function Emit-Label {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<LabelDecoration name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- # Порядок как у платформы: own-content (флаги/hyperlink/layout/оформление) ПЕРЕД Title
- # (корпус layout-first 16970 vs 44 — заодно убирает шум атрибуции харнесса на многострочном Title).
- Emit-CommonFlags -el $el -indent $inner
- if ((Get-DslBool $el @('hyperlink') $false)) { X "$inner<Hyperlink>true</Hyperlink>" }
- Emit-Layout -el $el -indent $inner
- Emit-Appearance -el $el -indent $inner -profile 'decoration'
- Emit-DecorationTitle -el $el -name $name -indent $inner -auto
- # Companions
- Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- Emit-Events -el $el -elementName $name -indent $inner -xmlTag "LabelDecoration"
- X "$indent</LabelDecoration>"
- }
- function Emit-LabelField {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<LabelField name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
- Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
- Emit-CommonFlags -el $el -indent $inner
- if ($el.titleLocation) { X "$inner<TitleLocation>$(Map-TitleLoc "$($el.titleLocation)")</TitleLocation>" }
- if ($el.editMode) { X "$inner<EditMode>$($el.editMode)</EditMode>" }
- # FooterDataPath — путь данных подвала колонки (общий cell-prop, как у input); после EditMode
- if ($el.footerDataPath) { X "$inner<FooterDataPath>$(Esc-XmlText "$($el.footerDataPath)")</FooterDataPath>" }
- # PasswordMode на LabelField — платформа эмитит явный false (редко); факт. значение
- if ($null -ne $el.passwordMode) { X "$inner<PasswordMode>$(if ($el.passwordMode){'true'}else{'false'})</PasswordMode>" }
- Emit-ColumnPics -el $el -indent $inner
- # ВНИМАНИЕ: у LabelField платформенный тег именно <Hiperlink> (опечатка 1С), не <Hyperlink>.
- if ((Get-DslBool $el @('hyperlink') $false)) { X "$inner<Hiperlink>true</Hiperlink>" }
- Emit-Layout -el $el -indent $inner
- if ($null -ne $el.warningOnEdit) { Emit-MLText -tag "WarningOnEdit" -text $el.warningOnEdit -indent $inner }
- if ($null -ne $el.footerText) { Emit-MLText -tag "FooterText" -text $el.footerText -indent $inner }
- # Формат / формат редактирования (LocalStringType — строка или {ru,en})
- if ($el.format) { Emit-MLText -tag "Format" -text $el.format -indent $inner }
- if ($el.editFormat) { Emit-MLText -tag "EditFormat" -text $el.editFormat -indent $inner }
- # Оформление (цвета/шрифты/граница + header/footer) — перед компаньонами
- Emit-Appearance -el $el -indent $inner -profile 'field'
- # Companions
- Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- Emit-Events -el $el -elementName $name -indent $inner -xmlTag "LabelField"
- X "$indent</LabelField>"
- }
- function Emit-DynListTableBlock {
- param($el, [string]$indent)
- # (useAlternationRowColor — общее свойство таблицы, эмитится в Emit-Table)
- # Group A (гарант. блок, n=5079): дефолт + override
- $ar = if ((Get-DslBool $el @('autoRefresh') $false)) { "true" } else { "false" }
- X "$indent<AutoRefresh>$ar</AutoRefresh>"
- $arp = if ($el.PSObject.Properties["autoRefreshPeriod"] -and $null -ne $el.autoRefreshPeriod) { $el.autoRefreshPeriod } else { 60 }
- X "$indent<AutoRefreshPeriod>$arp</AutoRefreshPeriod>"
- X "$indent<Period>"
- X "$indent`t<v8:variant xsi:type=`"v8:StandardPeriodVariant`">Custom</v8:variant>"
- X "$indent`t<v8:startDate>0001-01-01T00:00:00</v8:startDate>"
- X "$indent`t<v8:endDate>0001-01-01T00:00:00</v8:endDate>"
- X "$indent</Period>"
- $cfi = if ($el.choiceFoldersAndItems) { $el.choiceFoldersAndItems } else { "Items" }
- X "$indent<ChoiceFoldersAndItems>$cfi</ChoiceFoldersAndItems>"
- $rcr = if ((Get-DslBool $el @('restoreCurrentRow') $false)) { "true" } else { "false" }
- X "$indent<RestoreCurrentRow>$rcr</RestoreCurrentRow>"
- X "$indent<TopLevelParent xsi:nil=`"true`"/>"
- $sr = if ((-not (Get-DslBool $el @('showRoot') $true))) { "false" } else { "true" }
- X "$indent<ShowRoot>$sr</ShowRoot>"
- $arc = if ((Get-DslBool $el @('allowRootChoice') $false)) { "true" } else { "false" }
- X "$indent<AllowRootChoice>$arc</AllowRootChoice>"
- $uodc = if ($el.updateOnDataChange) { $el.updateOnDataChange } else { "Auto" }
- X "$indent<UpdateOnDataChange>$uodc</UpdateOnDataChange>"
- if ($el.userSettingsGroup) { X "$indent<UserSettingsGroup>$($el.userSettingsGroup)</UserSettingsGroup>" }
- $agcru = if ((-not (Get-DslBool $el @('allowGettingCurrentRowURL') $true))) { "false" } else { "true" }
- X "$indent<AllowGettingCurrentRowURL>$agcru</AllowGettingCurrentRowURL>"
- }
- function Emit-Table {
- param($el, [string]$name, [int]$id, [string]$indent)
- $script:currentTableName = $name # дефолт source для кастомных дополнений в commandBar
- X "$indent<Table name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
- Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
- Emit-CommonFlags -el $el -indent $inner
- if ($el.representation) {
- X "$inner<Representation>$($el.representation)</Representation>"
- }
- if ($el.titleLocation) { X "$inner<TitleLocation>$(Map-TitleLoc "$($el.titleLocation)")</TitleLocation>" }
- # ChangeRowSet/Order — эмитим явное значение (в т.ч. false: платформа пишет его на ValueTable)
- if ($el.PSObject.Properties['changeRowSet'] -and $null -ne $el.changeRowSet) {
- X "$inner<ChangeRowSet>$(if ((Get-DslBool $el @('changeRowSet') $false)){'true'}else{'false'})</ChangeRowSet>"
- }
- if ($el.PSObject.Properties['changeRowOrder'] -and $null -ne $el.changeRowOrder) {
- X "$inner<ChangeRowOrder>$(if ((Get-DslBool $el @('changeRowOrder') $false)){'true'}else{'false'})</ChangeRowOrder>"
- }
- if ((Get-DslBool $el @('autoInsertNewRow') $false)) { X "$inner<AutoInsertNewRow>true</AutoInsertNewRow>" }
- # RowFilter — nil-плейсхолдер (всегда пустой); ключ присутствует → эмитим
- if ($el.PSObject.Properties['rowFilter']) { X "$inner<RowFilter xsi:nil=`"true`"/>" }
- # Высота в строках таблицы (<HeightInTableRows>) — отдельное свойство от <Height> (высота элемента,
- # эмитится generic-ом Emit-Layout ниже). Таблица может нести оба (237 в корпусе).
- if ($el.heightInTableRows) { X "$inner<HeightInTableRows>$($el.heightInTableRows)</HeightInTableRows>" }
- if ((-not (Get-DslBool $el @('header') $true))) { X "$inner<Header>false</Header>" }
- if ((Get-DslBool $el @('footer') $false)) { X "$inner<Footer>true</Footer>" }
- if ($el.commandBarLocation) {
- X "$inner<CommandBarLocation>$($el.commandBarLocation)</CommandBarLocation>"
- }
- if ($el.searchStringLocation) {
- X "$inner<SearchStringLocation>$($el.searchStringLocation)</SearchStringLocation>"
- }
- if ((Get-DslBool $el @('choiceMode') $false)) { X "$inner<ChoiceMode>true</ChoiceMode>" }
- # Скаляры таблицы (захват «как есть»). Autofill — СВОЁ свойство таблицы (≠ AutoCommandBar autofill = tableAutofill).
- if ($null -ne $el.autofill) { X "$inner<Autofill>$(if ($el.autofill){'true'}else{'false'})</Autofill>" }
- if ((Get-DslBool $el @('multipleChoice') $false)) { X "$inner<MultipleChoice>true</MultipleChoice>" }
- if ($el.searchOnInput) { X "$inner<SearchOnInput>$($el.searchOnInput)</SearchOnInput>" }
- if ($null -ne $el.markIncomplete) { X "$inner<AutoMarkIncomplete>$(if ($el.markIncomplete){'true'}else{'false'})</AutoMarkIncomplete>" }
- # Высота шапки/подвала в строках (pass-through; 1С толерантна к порядку детей Table)
- if ($null -ne $el.headerHeight) { X "$inner<HeaderHeight>$($el.headerHeight)</HeaderHeight>" }
- if ($null -ne $el.footerHeight) { X "$inner<FooterHeight>$($el.footerHeight)</FooterHeight>" }
- if ((Get-DslBool $el @('useAlternationRowColor') $false)) { X "$inner<UseAlternationRowColor>true</UseAlternationRowColor>" }
- if ($el.selectionMode) { X "$inner<SelectionMode>$($el.selectionMode)</SelectionMode>" }
- if ($el.rowSelectionMode) { X "$inner<RowSelectionMode>$($el.rowSelectionMode)</RowSelectionMode>" }
- if ((-not (Get-DslBool $el @('verticalLines') $true))) { X "$inner<VerticalLines>false</VerticalLines>" }
- if ((-not (Get-DslBool $el @('horizontalLines') $true))) { X "$inner<HorizontalLines>false</HorizontalLines>" }
- if ($el.initialTreeView) { X "$inner<InitialTreeView>$($el.initialTreeView)</InitialTreeView>" }
- if ($null -ne $el.enableDrag) { X "$inner<EnableDrag>$(if ($el.enableDrag){'true'}else{'false'})</EnableDrag>" }
- if ($el.rowPictureDataPath) { X "$inner<RowPictureDataPath>$($el.rowPictureDataPath)</RowPictureDataPath>" }
- # RowsPicture — та же конвенция, что ValuesPicture (дефолт LoadTransparent=false; abs/TransparentPixel)
- Emit-PictureRef -val $el.rowsPicture -picTag 'RowsPicture' -indent $inner
- # Использование текущей строки таблицы (pass-through; в корпусе соседствует с блоком дин-списка)
- if ($el.currentRowUse) { X "$inner<CurrentRowUse>$($el.currentRowUse)</CurrentRowUse>" }
- # Запрос обновления дин-списка (pass-through; в корпусе всегда PullFromTop)
- if ($el.refreshRequest) { X "$inner<RefreshRequest>$($el.refreshRequest)</RefreshRequest>" }
- # Блок свойств дин-список-таблицы (помечена эвристикой 11b.4)
- if ($el.PSObject.Properties["_dynList"] -and $el._dynList) { Emit-DynListTableBlock -el $el -indent $inner }
- if ($el.viewStatusLocation) { X "$inner<ViewStatusLocation>$($el.viewStatusLocation)</ViewStatusLocation>" }
- if ($el.searchControlLocation) { X "$inner<SearchControlLocation>$($el.searchControlLocation)</SearchControlLocation>" }
- Emit-Layout -el $el -indent $inner
- # CommandSet таблицы эмитится через Emit-Layout (общий механизм поля)
- # Оформление (цвета/граница таблицы) — перед компаньонами
- Emit-Appearance -el $el -indent $inner -profile 'field'
- # Companions
- Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
- # AutoCommandBar: приоритет commandBar-свойства (контент); иначе tableAutofill-shorthand; иначе пусто.
- if ($null -ne $el.commandBar) {
- Emit-CompanionPanel -tag "AutoCommandBar" -name "${name}КоманднаяПанель" -indent $inner -panel $el.commandBar
- } elseif ($null -ne $el.tableAutofill) {
- $acbId = New-Id
- X "$inner<AutoCommandBar name=`"${name}КоманднаяПанель`" id=`"$acbId`">"
- $afVal = if ($el.tableAutofill) { "true" } else { "false" }
- X "$inner`t<Autofill>$afVal</Autofill>"
- X "$inner</AutoCommandBar>"
- } else {
- Emit-Companion -tag "AutoCommandBar" -name "${name}КоманднаяПанель" -indent $inner
- }
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- $adds = $el.additions
- Emit-TableAddition -typeKey 'searchString' -tableName $name -indent $inner -override (Get-AdditionOverride $adds 'searchString')
- Emit-TableAddition -typeKey 'viewStatus' -tableName $name -indent $inner -override (Get-AdditionOverride $adds 'viewStatus')
- Emit-TableAddition -typeKey 'searchControl' -tableName $name -indent $inner -override (Get-AdditionOverride $adds 'searchControl')
- # Columns
- if ($el.columns -and $el.columns.Count -gt 0) {
- X "$inner<ChildItems>"
- $prevTable = $script:handlerTable; $script:handlerTable = $name
- foreach ($col in $el.columns) {
- Emit-Element -el $col -indent "$inner`t"
- }
- $script:handlerTable = $prevTable
- X "$inner</ChildItems>"
- }
- Emit-Events -el $el -elementName $name -indent $inner -xmlTag "Table" -source (Get-TableSource $el)
- X "$indent</Table>"
- }
- function Emit-Pages {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<Pages name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- Emit-Title -el $el -name $name -indent $inner
- if ($el.pagesRepresentation) {
- X "$inner<PagesRepresentation>$($el.pagesRepresentation)</PagesRepresentation>"
- }
- # Использование текущей строки (после PagesRepresentation, порядок XSD)
- if ($el.currentRowUse) { X "$inner<CurrentRowUse>$($el.currentRowUse)</CurrentRowUse>" }
- Emit-CommonFlags -el $el -indent $inner
- Emit-Layout -el $el -indent $inner
- # Оформление (цвета/шрифты/граница) заголовка группы страниц — TitleFont/TitleTextColor/… (как у Page)
- Emit-Appearance -el $el -indent $inner -profile 'field'
- # Companion
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- Emit-Events -el $el -elementName $name -indent $inner -xmlTag "Pages"
- # Children (pages)
- if ($el.children -and $el.children.Count -gt 0) {
- X "$inner<ChildItems>"
- foreach ($child in $el.children) {
- Emit-Element -el $child -indent "$inner`t"
- }
- X "$inner</ChildItems>"
- }
- X "$indent</Pages>"
- }
- function Emit-Page {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<Page name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- Warn-EventsIgnored $el "Page" $name
- Emit-Title -el $el -name $name -indent $inner -auto
- Emit-CommonFlags -el $el -indent $inner
- # Картинка страницы (иконка вкладки): после Title/флагов, перед Group (порядок XSD).
- # Конвенция как у ValuesPicture (дефолт LoadTransparent=false): скаляр-Ref/'abs:X' или объект.
- Emit-PictureRef -val $el.picture -picTag 'Picture' -indent $inner
- if ($el.group) {
- # Доступные значения страницы/обычной группы: Vertical / HorizontalIfPossible / AlwaysHorizontal
- # (InCell — только у columnGroup). Horizontal и старое alwaysVertical (→ Vertical) — прощающий ввод.
- $orientation = switch ("$($el.group)") {
- "horizontal" { "Horizontal" }
- "vertical" { "Vertical" }
- "alwaysHorizontal" { "AlwaysHorizontal" }
- "alwaysVertical" { "Vertical" } # старое написание; у страницы такого значения нет
- "horizontalIfPossible" { "HorizontalIfPossible" }
- default { $null }
- }
- if ($orientation) { X "$inner<Group>$orientation</Group>" }
- else { Warn-Unrecognized 'page group orientation' $el.group @('vertical','horizontalIfPossible','alwaysHorizontal') $name }
- }
- # ShowTitle=true — умолчание платформы (в корпусе только false): пишем лишь false
- if ($null -ne $el.showTitle -and -not $el.showTitle) { X "$inner<ShowTitle>false</ShowTitle>" }
- # Формат значения пути к данным заголовка (<Format>; парный к titleDataPath страницы)
- if ($el.format) { Emit-MLText -tag "Format" -text $el.format -indent $inner }
- if ($el.editFormat) { Emit-MLText -tag "EditFormat" -text $el.editFormat -indent $inner }
- Emit-Layout -el $el -indent $inner
- # Оформление страницы (BackColor / TitleTextColor / TitleFont) — после ShowTitle, перед компаньоном
- Emit-Appearance -el $el -indent $inner -profile 'field'
- # Companion
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- # Children
- if ($el.children -and $el.children.Count -gt 0) {
- X "$inner<ChildItems>"
- foreach ($child in $el.children) {
- Emit-Element -el $child -indent "$inner`t"
- }
- X "$inner</ChildItems>"
- }
- X "$indent</Page>"
- }
- function Emit-Button {
- param($el, [string]$name, [int]$id, [string]$indent, [bool]$inCmdBar = $false)
- X "$indent<Button name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- # (общие свойства — через Emit-Layout ниже; отдельный вызов был бы двойной эмиссией)
- # Type — context-aware:
- # Inside command bar (cmdBar/autoCmdBar/popup) only CommandBarButton/CommandBarHyperlink are valid.
- # UsualButton/Hyperlink would be silently ignored by 1C.
- $btnType = $null
- if ($el.type) {
- $rawType = "$($el.type)"
- if ($inCmdBar) {
- # Be forgiving: any "ordinary button" hint resolves to CommandBarButton,
- # any "hyperlink" hint resolves to CommandBarHyperlink. The model can pass
- # either DSL ("usual"/"hyperlink") or XML names — all map to the right kind.
- switch ($rawType) {
- "usual" { $btnType = "CommandBarButton" }
- "UsualButton" { $btnType = "CommandBarButton" }
- "commandBar" { $btnType = "CommandBarButton" }
- "CommandBarButton" { $btnType = "CommandBarButton" }
- "hyperlink" { $btnType = "CommandBarHyperlink" }
- "Hyperlink" { $btnType = "CommandBarHyperlink" }
- "CommandBarHyperlink" { $btnType = "CommandBarHyperlink" }
- default { $btnType = $rawType }
- }
- } else {
- # Symmetric: any "ordinary button" hint → UsualButton, any "hyperlink" → Hyperlink.
- switch ($rawType) {
- "usual" { $btnType = "UsualButton" }
- "UsualButton" { $btnType = "UsualButton" }
- "commandBar" { $btnType = "UsualButton" }
- "CommandBarButton" { $btnType = "UsualButton" }
- "hyperlink" { $btnType = "Hyperlink" }
- "Hyperlink" { $btnType = "Hyperlink" }
- "CommandBarHyperlink" { $btnType = "Hyperlink" }
- default { $btnType = $rawType }
- }
- }
- } elseif ($inCmdBar) {
- $btnType = "CommandBarButton"
- }
- if ($btnType) {
- X "$inner<Type>$btnType</Type>"
- }
- # CommandName
- if ($el.command) {
- X "$inner<CommandName>Form.Command.$($el.command)</CommandName>"
- }
- # commandName — глобальная команда «как есть» (CommonCommand.X, Catalog.X.Command.Y …), без обёртки Form.
- if ($el.commandName -and -not $el.command) {
- X "$inner<CommandName>$($el.commandName)</CommandName>"
- }
- if ($el.stdCommand) {
- $sc = "$($el.stdCommand)"
- if ($sc -match '^(.+)\.(.+)$') {
- X "$inner<CommandName>Form.Item.$($Matches[1]).StandardCommand.$($Matches[2])</CommandName>"
- } else {
- X "$inner<CommandName>Form.StandardCommand.$sc</CommandName>"
- }
- }
- # Parameter команды (после CommandName): строка → xr:MDObjectRef (объект метаданных);
- # объект {type} → v8:TypeDescription (грамматика типа). Forgiving-синоним 'параметр'.
- $btnParam = if ($null -ne $el.PSObject.Properties['parameter']) { $el.parameter } elseif ($null -ne $el.PSObject.Properties['параметр']) { $el.параметр } else { $null }
- if ($null -ne $btnParam) {
- if (($btnParam -is [System.Management.Automation.PSCustomObject] -or $btnParam -is [hashtable]) -and $btnParam.type) {
- Emit-Type -typeStr "$($btnParam.type)" -indent $inner -tag "Parameter" -tagAttrs ' xsi:type="v8:TypeDescription"'
- } else {
- X "$inner<Parameter xsi:type=`"xr:MDObjectRef`">$(Esc-XmlText "$btnParam")</Parameter>"
- }
- }
- # DataPath — привязка команды кнопки к контексту (Объект.Ref, Items.X.CurrentData.Поле)
- if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
- $btnAuto = -not ($el.command -or $el.commandName -or $el.stdCommand)
- Emit-Title -el $el -name $name -indent $inner -auto:$btnAuto
- Emit-CommonFlags -el $el -indent $inner
- if ((Get-DslBool $el @('defaultButton') $false)) { X "$inner<DefaultButton>true</DefaultButton>" }
- # Check (пометка toggle-кнопки командной панели) — платформа эмитит только true.
- # Ключ 'checked' (не 'check': 'check' — тип-ключ CheckBoxField, был бы конфликт диспетчера типов)
- if ((Get-DslBool $el @('checked') $false)) { X "$inner<Check>true</Check>" }
- # Picture
- Emit-CommandPicture -pic $el.picture -elemLt $el.loadTransparent -indent $inner
- if ($el.representation) {
- X "$inner<Representation>$($el.representation)</Representation>"
- }
- if ($el.locationInCommandBar) {
- X "$inner<LocationInCommandBar>$($el.locationInCommandBar)</LocationInCommandBar>"
- }
- Emit-Layout -el $el -indent $inner
- # Оформление (цвета/шрифт/граница) — перед компаньоном (профиль кнопки)
- Emit-Appearance -el $el -indent $inner -profile 'button'
- # Companion
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- Emit-Events -el $el -elementName $name -indent $inner -xmlTag "Button"
- X "$indent</Button>"
- }
- function Emit-PictureDecoration {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<PictureDecoration name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- Emit-DecorationTitle -el $el -name $name -indent $inner
- # Текст при невыбранной картинке (NonselectedPictureText) — после Title (порядок корпуса)
- if ($null -ne $el.nonselectedPictureText) { Emit-MLText -tag "NonselectedPictureText" -text $el.nonselectedPictureText -indent $inner }
- Emit-CommonFlags -el $el -indent $inner
- # Источник картинки — ТОЛЬКО $el.src (у PictureDecoration ключ 'picture' = тип/имя элемента, не источник).
- # Префикс "abs:" → встроенная картинка <xr:Abs>; иначе именованная/стилевая <xr:Ref>.
- if ($el.src) {
- $srcStr = "$($el.src)"
- $lt = if ((Get-DslBool $el @('loadTransparent') $false)) { "true" } else { "false" }
- X "$inner<Picture>"
- if ($srcStr -match '^abs:(.*)$') { X "$inner`t<xr:Abs>$(Esc-XmlText $matches[1])</xr:Abs>" }
- else { X "$inner`t<xr:Ref>$(Esc-XmlText $srcStr)</xr:Ref>" }
- X "$inner`t<xr:LoadTransparent>$lt</xr:LoadTransparent>"
- if ($el.transparentPixel) { X "$inner`t<xr:TransparentPixel x=`"$($el.transparentPixel.x)`" y=`"$($el.transparentPixel.y)`"/>" }
- X "$inner</Picture>"
- }
- if ((Get-DslBool $el @('hyperlink') $false)) { X "$inner<Hyperlink>true</Hyperlink>" }
- Emit-Layout -el $el -indent $inner
- # EnableDrag — фактическое значение (декорация-картинка перетаскиваема; декомпилятор ловит generic-ом)
- if ($null -ne $el.enableDrag) { X "$inner<EnableDrag>$(if ($el.enableDrag){'true'}else{'false'})</EnableDrag>" }
- # Оформление (цвета/шрифт/граница) — профиль декорации (1С толерантна к порядку appearance)
- Emit-Appearance -el $el -indent $inner -profile 'decoration'
- # Companions
- Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- Emit-Events -el $el -elementName $name -indent $inner -xmlTag "PictureDecoration"
- X "$indent</PictureDecoration>"
- }
- function Emit-PictureField {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<PictureField name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
- Emit-Title -el $el -name $name -indent $inner
- Emit-CommonFlags -el $el -indent $inner
- if ($el.editMode) { X "$inner<EditMode>$($el.editMode)</EditMode>" }
- Emit-ColumnPics -el $el -indent $inner
- if ($el.titleLocation) { X "$inner<TitleLocation>$(Map-TitleLoc "$($el.titleLocation)")</TitleLocation>" }
- if ((Get-DslBool $el @('hyperlink') $false)) { X "$inner<Hyperlink>true</Hyperlink>" }
- Emit-Layout -el $el -indent $inner
- # EnableDrag — фактическое значение (поле картинки перетаскиваемо; декомпилятор ловит generic-ом)
- if ($null -ne $el.enableDrag) { X "$inner<EnableDrag>$(if ($el.enableDrag){'true'}else{'false'})</EnableDrag>" }
- # FooterDataPath / FooterText — общие cell-свойства колонки (как у input/labelField)
- if ($el.footerDataPath) { X "$inner<FooterDataPath>$(Esc-XmlText "$($el.footerDataPath)")</FooterDataPath>" }
- if ($null -ne $el.footerText) { Emit-MLText -tag "FooterText" -text $el.footerText -indent $inner }
- # ValuesPicture — picture (collection) used to render the field's value.
- # Required for a Boolean-bound PictureField to actually show an icon.
- # Скаляр (Ref) или объект {src, loadTransparent}; LoadTransparent эмитится всегда.
- Emit-PictureRef -val $el.valuesPicture -picTag 'ValuesPicture' -indent $inner
- if ($null -ne $el.nonselectedPictureText) { Emit-MLText -tag "NonselectedPictureText" -text $el.nonselectedPictureText -indent $inner }
- # Оформление (цвета/шрифты/граница) — перед компаньонами
- Emit-Appearance -el $el -indent $inner -profile 'field'
- # Companions
- Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- Emit-Events -el $el -elementName $name -indent $inner -xmlTag "PictureField"
- X "$indent</PictureField>"
- }
- function Emit-Calendar {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<CalendarField name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
- Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
- Emit-CommonFlags -el $el -indent $inner
- if ($el.titleLocation) {
- $loc = Map-TitleLoc "$($el.titleLocation)"
- X "$inner<TitleLocation>$loc</TitleLocation>"
- }
- Emit-Layout -el $el -indent $inner
- # Календарно-специфичные свойства (порядок схемы: после layout, до companions)
- if ($el.selectionMode) { X "$inner<SelectionMode>$($el.selectionMode)</SelectionMode>" }
- if ($null -ne $el.showCurrentDate) { $v = if ($el.showCurrentDate) { "true" } else { "false" }; X "$inner<ShowCurrentDate>$v</ShowCurrentDate>" }
- if ($null -ne $el.widthInMonths) { X "$inner<WidthInMonths>$($el.widthInMonths)</WidthInMonths>" }
- if ($null -ne $el.heightInMonths) { X "$inner<HeightInMonths>$($el.heightInMonths)</HeightInMonths>" }
- if ($null -ne $el.showMonthsPanel) { $v = if ($el.showMonthsPanel) { "true" } else { "false" }; X "$inner<ShowMonthsPanel>$v</ShowMonthsPanel>" }
- # Оформление (цвета/шрифты/граница) — перед компаньонами
- Emit-Appearance -el $el -indent $inner -profile 'field'
- # Companions
- Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- Emit-Events -el $el -elementName $name -indent $inner -xmlTag "CalendarField"
- X "$indent</CalendarField>"
- }
- function Emit-SimpleField {
- param($el, [string]$name, [int]$id, [string]$indent, [string]$xmlTag, [string]$typeKey)
- X "$indent<$xmlTag name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
- Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
- Emit-CommonFlags -el $el -indent $inner
- if ($el.titleLocation) { X "$inner<TitleLocation>$(Map-TitleLoc "$($el.titleLocation)")</TitleLocation>" }
- if ($el.editMode) { X "$inner<EditMode>$($el.editMode)</EditMode>" }
- Emit-Layout -el $el -indent $inner
- # EnableDrag — фактическое значение (SpreadSheet; платформа эмитит явный false). enableStartDrag — через Emit-Layout.
- if ($null -ne $el.enableDrag) { X "$inner<EnableDrag>$(if ($el.enableDrag){'true'}else{'false'})</EnableDrag>" }
- # Датчики (ProgressBar/TrackBar) — числовые скаляры (без xsi:type)
- foreach ($p in @(@('minValue','MinValue'), @('maxValue','MaxValue'), @('largeStep','LargeStep'), @('markingStep','MarkingStep'), @('step','Step'))) {
- if ($null -ne $el.($p[0])) { X "$inner<$($p[1])>$($el.($p[0]))</$($p[1])>" }
- }
- # Оформление (цвета/шрифты/граница) — перед компаньонами
- Emit-Appearance -el $el -indent $inner -profile 'field'
- # Companions
- Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- Emit-Events -el $el -elementName $name -indent $inner -xmlTag $xmlTag
- X "$indent</$xmlTag>"
- }
- function Emit-GanttChart {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<GanttChartField name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
- Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
- Emit-CommonFlags -el $el -indent $inner
- if ($el.titleLocation) { X "$inner<TitleLocation>$(Map-TitleLoc "$($el.titleLocation)")</TitleLocation>" }
- Emit-Layout -el $el -indent $inner
- Emit-Appearance -el $el -indent $inner -profile 'field'
- Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- # Вложенная таблица диаграммы Ганта (стандартный Table — переиспользуем Emit-Element)
- if ($el.ganttTable) { Emit-Element -el $el.ganttTable -indent $inner }
- Emit-Events -el $el -elementName $name -indent $inner -xmlTag "GanttChartField"
- X "$indent</GanttChartField>"
- }
- function Emit-CommandBar {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<CommandBar name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- Warn-EventsIgnored $el "CommandBar" $name
- Emit-Title -el $el -name $name -indent $inner
- if ($el.commandSource) { X "$inner<CommandSource>$($el.commandSource)</CommandSource>" }
- if ((Get-DslBool $el @('autofill') $false)) { X "$inner<Autofill>true</Autofill>" }
- # CommandBar хранит HorizontalLocation фактически (включая Auto — декомпилятор ловит только при наличии);
- # ≠ дополнениям, где Auto = умолчание-скип (Get-HLocation).
- if ($el.horizontalLocation) {
- $hlv = switch ("$($el.horizontalLocation)".ToLower()) { 'auto' {'Auto'} 'left' {'Left'} 'right' {'Right'} 'center' {'Center'} default {"$($el.horizontalLocation)"} }
- X "$inner<HorizontalLocation>$hlv</HorizontalLocation>"
- }
- Emit-CommonFlags -el $el -indent $inner
- Emit-Layout -el $el -indent $inner
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- # Children
- if ($el.children -and $el.children.Count -gt 0) {
- X "$inner<ChildItems>"
- foreach ($child in $el.children) {
- Emit-Element -el $child -indent "$inner`t" -inCmdBar $true
- }
- X "$inner</ChildItems>"
- }
- X "$indent</CommandBar>"
- }
- function Emit-ButtonGroup {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<ButtonGroup name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- Warn-EventsIgnored $el "ButtonGroup" $name
- Emit-Title -el $el -name $name -indent $inner
- if ($el.commandSource) { X "$inner<CommandSource>$($el.commandSource)</CommandSource>" }
- if ($el.representation) {
- X "$inner<Representation>$($el.representation)</Representation>"
- }
- Emit-CommonFlags -el $el -indent $inner
- Emit-Layout -el $el -indent $inner
- # Companion: ExtendedTooltip
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- # Children (кнопки в контексте командной панели)
- if ($el.children -and $el.children.Count -gt 0) {
- X "$inner<ChildItems>"
- foreach ($child in $el.children) {
- Emit-Element -el $child -indent "$inner`t" -inCmdBar $true
- }
- X "$inner</ChildItems>"
- }
- X "$indent</ButtonGroup>"
- }
- function Emit-Popup {
- param($el, [string]$name, [int]$id, [string]$indent)
- X "$indent<Popup name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
- $inner = "$indent`t"
- Warn-EventsIgnored $el "Popup" $name
- Emit-Title -el $el -name $name -indent $inner -auto
- Emit-CommonFlags -el $el -indent $inner
- # Источник команд попапа (после Title/ToolTip, перед компаньоном) — как у ButtonGroup/CommandBar
- if ($el.commandSource) { X "$inner<CommandSource>$($el.commandSource)</CommandSource>" }
- Emit-CommandPicture -pic $el.picture -elemLt $el.loadTransparent -indent $inner
- if ($el.representation) {
- X "$inner<Representation>$($el.representation)</Representation>"
- }
- Emit-Layout -el $el -indent $inner
- # Оформление попапа (TitleTextColor / TitleFont) — перед компаньоном
- Emit-Appearance -el $el -indent $inner -profile 'field'
- Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
- # Children
- if ($el.children -and $el.children.Count -gt 0) {
- X "$inner<ChildItems>"
- foreach ($child in $el.children) {
- Emit-Element -el $child -indent "$inner`t" -inCmdBar $true
- }
- X "$inner</ChildItems>"
- }
- X "$indent</Popup>"
- }
- function Emit-FunctionalOptions {
- param($fo, [string]$indent)
- if (-not $fo -or @($fo).Count -eq 0) { return }
- X "$indent<FunctionalOptions>"
- foreach ($opt in @($fo)) {
- $v = "$opt"
- if ($v -match '^[0-9a-fA-F]{8}-[0-9a-fA-F-]{27,}$') { } # GUID — как есть
- elseif ($v -match '^FunctionalOption\.') { } # уже с префиксом
- else { $v = "FunctionalOption.$v" }
- X "$indent`t<Item>$v</Item>"
- }
- X "$indent</FunctionalOptions>"
- }
- function Emit-AttrColumn {
- param($col, [string]$indent)
- $colId = New-Id
- X "$indent<Column name=`"$($col.name)`" id=`"$colId`">"
- if ($col.title) { Emit-MLText -tag "Title" -text $col.title -indent "$indent`t" }
- Emit-Type -typeStr "$($col.type)" -indent "$indent`t"
- # Проверка заполнения колонки → <FillCheck> (как у реквизита; bool true→ShowError / строка verbatim)
- $cfcRaw = if ($null -ne $col.PSObject.Properties['fillCheck']) { $col.fillCheck } elseif ($null -ne $col.PSObject.Properties['fillChecking']) { $col.fillChecking } else { $null }
- if ($null -ne $cfcRaw) { $cfcv = if ($cfcRaw -is [bool]) { if ($cfcRaw) { 'ShowError' } else { $null } } else { "$cfcRaw" }; if ($cfcv) { X "$indent`t<FillCheck>$cfcv</FillCheck>" } }
- Emit-FunctionalOptions -fo $col.functionalOptions -indent "$indent`t"
- # Ролевой доступ колонки (View/Edit) — xr-флаг, как у самого реквизита
- if ($null -ne $col.view) { Emit-XrFlag -tag 'View' -val $col.view -indent "$indent`t" }
- if ($null -ne $col.edit) { Emit-XrFlag -tag 'Edit' -val $col.edit -indent "$indent`t" }
- X "$indent</Column>"
- }
- function Emit-DLMLText {
- param([string]$tag, $text, [string]$indent)
- X "$indent<$tag xsi:type=`"v8:LocalStringType`">"
- Emit-MLItems -val $text -indent "$indent`t"
- X "$indent</$tag>"
- }
- function Has-DLProp {
- param($obj, [string]$name)
- if ($null -eq $obj) { return $false }
- if ($obj -is [System.Collections.IDictionary]) { return $obj.Contains($name) }
- if ($obj.PSObject -and $obj.PSObject.Properties[$name]) { return $true }
- return $false
- }
- function Split-DLValueListCsv {
- param([string]$s)
- $result = @()
- if ($null -eq $s) { return ,$result }
- $items = @(); $buf = New-Object System.Text.StringBuilder; $inQuote = $null
- for ($i = 0; $i -lt $s.Length; $i++) {
- $ch = $s[$i]
- if ($inQuote) { [void]$buf.Append($ch); if ($ch -eq $inQuote) { $inQuote = $null } }
- elseif ($ch -eq "'" -or $ch -eq '"') { $inQuote = $ch; [void]$buf.Append($ch) }
- elseif ($ch -eq ',') { $items += $buf.ToString(); [void]$buf.Clear() }
- else { [void]$buf.Append($ch) }
- }
- if ($buf.Length -gt 0) { $items += $buf.ToString() }
- foreach ($raw in $items) {
- $t = $raw.Trim()
- if ($t.Length -ge 2 -and (($t[0] -eq "'" -and $t[-1] -eq "'") -or ($t[0] -eq '"' -and $t[-1] -eq '"'))) { $t = $t.Substring(1, $t.Length - 2) }
- if ($t -ne "") { $result += $t }
- }
- return ,$result
- }
- function Parse-DLParamShorthand {
- param([string]$s)
- $result = @{ name = ""; type = ""; value = $null; title = $null }
- if ($s -match '@valueList') { $result.valueListAllowed = $true; $s = $s -replace '\s*@valueList', '' }
- if ($s -match '@hidden') { $result.hidden = $true; $s = $s -replace '\s*@hidden', '' }
- if ($s -match '\[([^\]]*)\]') { $result.title = $Matches[1].Trim(); $s = ($s -replace '\s*\[[^\]]*\]\s*', ' ').Trim() }
- # Тип может быть СОСТАВНЫМ (A | B | C — с пробелами); значение — после '=' (тип '=' не содержит).
- if ($s -match '^([^:]+):\s*([^=]+?)(\s*=\s*(.*))?$') {
- $result.name = $Matches[1].Trim()
- $typeRaw = $Matches[2].Trim()
- if ($typeRaw -match '[|+]') {
- $result.type = (($typeRaw -split '\s*[|+]\s*') | ForEach-Object { Resolve-TypeStr ($_.Trim()) }) -join ' | '
- } else {
- $result.type = Resolve-TypeStr $typeRaw
- }
- if ($Matches[4]) {
- $rhs = $Matches[4].Trim()
- $items = Split-DLValueListCsv $rhs
- if ($items.Count -ge 2) { $result.value = $items; $result.valueListAllowed = $true }
- elseif ($items.Count -eq 1) { $result.value = $items[0] }
- else { $result.value = $rhs }
- }
- } else { $result.name = $s.Trim() }
- return $result
- }
- function Test-DLEmptyValue {
- param($v)
- if ($null -eq $v) { return $true }
- $s = "$v".Trim()
- if ($s -eq "" -or $s -eq "_" -or $s.ToLowerInvariant() -eq "null") { return $true }
- return $false
- }
- # Вид значения для ветвлений эмиттеров значений (параметры, пустые значения): примитив любого
- # написания (Число(15,2), numeric, String(10)) → decimal / string / date / dateTime / time, прочее —
- # через синонимы навыка. Квалификаторы значению не нужны и отбрасываются.
- function Get-ValueKindType {
- param([string]$typeStr)
- if (-not $typeStr) { return $typeStr }
- $prim = Parse-PrimitiveType $typeStr 0 0 0
- if ($prim -and -not $prim.Error) {
- if ($prim.Kind -eq 'Number') { return 'decimal' }
- if ($prim.Kind -eq 'String') { return 'string' }
- if ($prim.Fractions -eq 'Date') { return 'date' }
- if ($prim.Fractions -eq 'Time') { return 'time' }
- return 'dateTime'
- }
- return Resolve-TypeStr $typeStr
- }
- function Emit-DLValue {
- param([string]$type, $val, [string]$indent, [bool]$valueListAllowed = $false)
- $type = Get-ValueKindType $type
- if (Test-DLEmptyValue $val) {
- # Дин-список: пустое значение платформа ВСЕГДА пишет как xsi:nil, даже при известном
- # типе (в отличие от типизированного пустого в параметрах отчёта СКД).
- if ($valueListAllowed) { return }
- X "$indent<dcssch:value xsi:nil=`"true`"/>"
- return
- }
- $valStr = if ($val -is [bool]) { if ($val) { 'true' } else { 'false' } } else { "$val" }
- if ($type -match '^(date|dateTime|time)') { X "$indent<dcssch:value xsi:type=`"xs:dateTime`">$(Esc-XmlText $valStr)</dcssch:value>" }
- elseif ($type -eq "boolean") { X "$indent<dcssch:value xsi:type=`"xs:boolean`">$(Esc-XmlText $valStr)</dcssch:value>" }
- elseif ($type -eq 'v8:Type') { $nsAttr = Get-ValueTypeNsAttr -valueType 'v8:Type' -value $valStr; X "$indent<dcssch:value$nsAttr xsi:type=`"v8:Type`">$(Esc-XmlText $valStr)</dcssch:value>" }
- elseif ($type -match '^ent:') { X "$indent<dcssch:value xsi:type=`"$type`">$(Esc-XmlText $valStr)</dcssch:value>" } # системное перечисление (ent:X) — value несёт тот же xsi:type
- elseif ($type -match '^decimal') { X "$indent<dcssch:value xsi:type=`"xs:decimal`">$(Esc-XmlText $valStr)</dcssch:value>" }
- elseif ($type -match '^string') { X "$indent<dcssch:value xsi:type=`"xs:string`">$(Esc-XmlText $valStr)</dcssch:value>" }
- elseif ($type -match '^(CatalogRef|DocumentRef|EnumRef|ChartOfAccountsRef|ChartOfCharacteristicTypesRef|ChartOfCalculationTypesRef|BusinessProcessRef|TaskRef|ExchangePlanRef)\.') { X "$indent<dcssch:value xsi:type=`"dcscor:DesignTimeValue`">$(Esc-XmlText (Normalize-DesignTimeValue $valStr))</dcssch:value>" }
- else {
- if ($valStr -match '^\d{4}-\d{2}-\d{2}T') { X "$indent<dcssch:value xsi:type=`"xs:dateTime`">$(Esc-XmlText $valStr)</dcssch:value>" }
- elseif ($valStr -eq "true" -or $valStr -eq "false") { X "$indent<dcssch:value xsi:type=`"xs:boolean`">$(Esc-XmlText $valStr)</dcssch:value>" }
- elseif ($valStr -match '^(ПланСчетов|Справочник|Перечисление|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|РегистрСведений|ПланОбмена)\.' -or $valStr -match '^(ChartOfAccounts|Catalog|Enum|Document|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|InformationRegister|ExchangePlan)\.') { X "$indent<dcssch:value xsi:type=`"dcscor:DesignTimeValue`">$(Esc-XmlText (Normalize-DesignTimeValue $valStr))</dcssch:value>" }
- else { X "$indent<dcssch:value xsi:type=`"xs:string`">$(Esc-XmlText $valStr)</dcssch:value>" }
- }
- }
- function Emit-DLValueType {
- param($typeStr, [string]$indent)
- if (-not $typeStr) { return }
- X "$indent<dcssch:valueType>"
- $parts = "$typeStr" -split '\s*[|+]\s*'
- foreach ($part in $parts) { Emit-SingleType -typeStr $part.Trim() -indent "$indent`t" }
- X "$indent</dcssch:valueType>"
- }
- function Emit-DLAvailableValue {
- param($av, [string]$type, [string]$indent)
- X "$indent<dcssch:availableValue>"
- $avVal = if (Has-DLProp $av 'value') { $av.value } else { $null }
- Emit-DLValue -type $type -val $avVal -indent "$indent`t" -valueListAllowed $false
- $pres = if ($av.presentation) { $av.presentation } elseif ($av.title) { $av.title } else { $null }
- if ($pres) { Emit-DLMLText -tag "dcssch:presentation" -text $pres -indent "$indent`t" }
- X "$indent</dcssch:availableValue>"
- }
- function Emit-DLInputParameters {
- param($ip, [string]$indent)
- if ($null -eq $ip) { return }
- $items = @($ip)
- if ($items.Count -eq 0) { return }
- X "$indent<dcssch:inputParameters>"
- foreach ($item in $items) {
- X "$indent`t<dcscor:item>"
- if ((Has-DLProp $item 'use') -and $null -ne $item.use -and -not $item.use) { X "$indent`t`t<dcscor:use>false</dcscor:use>" }
- X "$indent`t`t<dcscor:parameter>$(Esc-XmlText "$($item.parameter)")</dcscor:parameter>"
- if (Has-DLProp $item 'choiceParameters') {
- $cpItems = if ($null -ne $item.choiceParameters) { @($item.choiceParameters) } else { @() }
- if ($cpItems.Count -eq 0) { X "$indent`t`t<dcscor:value xsi:type=`"dcscor:ChoiceParameters`"/>" }
- else {
- X "$indent`t`t<dcscor:value xsi:type=`"dcscor:ChoiceParameters`">"
- foreach ($cpItem in $cpItems) {
- X "$indent`t`t`t<dcscor:item>"
- X "$indent`t`t`t`t<dcscor:choiceParameter>$(Esc-XmlText "$($cpItem.name)")</dcscor:choiceParameter>"
- foreach ($v in @($cpItem.values)) {
- if ($v -is [bool]) { X "$indent`t`t`t`t<dcscor:value xsi:type=`"xs:boolean`">$(if ($v) { 'true' } else { 'false' })</dcscor:value>" }
- elseif ($v -is [int] -or $v -is [long] -or $v -is [double] -or $v -is [decimal]) { X "$indent`t`t`t`t<dcscor:value xsi:type=`"xs:decimal`">$v</dcscor:value>" }
- else { X "$indent`t`t`t`t<dcscor:value xsi:type=`"dcscor:DesignTimeValue`">$(Esc-XmlText (Normalize-DesignTimeValue "$v"))</dcscor:value>" }
- }
- X "$indent`t`t`t</dcscor:item>"
- }
- X "$indent`t`t</dcscor:value>"
- }
- } elseif (Has-DLProp $item 'choiceParameterLinks') {
- $cplItems = if ($null -ne $item.choiceParameterLinks) { @($item.choiceParameterLinks) } else { @() }
- if ($cplItems.Count -eq 0) { X "$indent`t`t<dcscor:value xsi:type=`"dcscor:ChoiceParameterLinks`"/>" }
- else {
- X "$indent`t`t<dcscor:value xsi:type=`"dcscor:ChoiceParameterLinks`">"
- foreach ($cplItem in $cplItems) {
- X "$indent`t`t`t<dcscor:item>"
- X "$indent`t`t`t`t<dcscor:choiceParameter>$(Esc-XmlText "$($cplItem.name)")</dcscor:choiceParameter>"
- X "$indent`t`t`t`t<dcscor:value>$(Esc-XmlText "$($cplItem.value)")</dcscor:value>"
- $mode = if ($cplItem.mode) { "$($cplItem.mode)" } else { 'Auto' }
- X "$indent`t`t`t`t<dcscor:mode xmlns:d8p1=`"http://v8.1c.ru/8.1/data/enterprise`" xsi:type=`"d8p1:LinkedValueChangeMode`">$mode</dcscor:mode>"
- X "$indent`t`t`t</dcscor:item>"
- }
- X "$indent`t`t</dcscor:value>"
- }
- } elseif (Has-DLProp $item 'typeLink') {
- # Связь по типу (dcscor:TypeLink) — field + linkItem (структурное значение параметра).
- $tl = $item.typeLink
- X "$indent`t`t<dcscor:value xsi:type=`"dcscor:TypeLink`">"
- $tlf = Get-Prop $tl 'field'; if ($null -ne $tlf) { X "$indent`t`t`t<dcscor:field>$(Esc-XmlText "$tlf")</dcscor:field>" }
- $tli = Get-Prop $tl 'linkItem'; if ($null -ne $tli) { X "$indent`t`t`t<dcscor:linkItem>$(Esc-XmlText "$tli")</dcscor:linkItem>" }
- X "$indent`t`t</dcscor:value>"
- } elseif (Has-DLProp $item 'value') {
- $val = $item.value
- if ($val -is [bool]) { X "$indent`t`t<dcscor:value xsi:type=`"xs:boolean`">$(if ($val) { 'true' } else { 'false' })</dcscor:value>" }
- elseif ($val -is [int] -or $val -is [long] -or $val -is [double] -or $val -is [decimal]) { X "$indent`t`t<dcscor:value xsi:type=`"xs:decimal`">$val</dcscor:value>" }
- elseif ($val -is [hashtable] -or $val -is [System.Collections.IDictionary] -or $val -is [PSCustomObject]) { Emit-DLMLText -tag "dcscor:value" -text $val -indent "$indent`t`t" }
- else { X "$indent`t`t<dcscor:value xsi:type=`"xs:string`">$(Esc-XmlText "$val")</dcscor:value>" }
- }
- X "$indent`t</dcscor:item>"
- }
- X "$indent</dcssch:inputParameters>"
- }
- function Test-EmptyValue {
- param($v)
- if ($null -eq $v) { return $true }
- $s = "$v".Trim()
- if ($s -eq "") { return $true }
- if ($s -eq "_") { return $true }
- if ($s.ToLowerInvariant() -eq "null") { return $true }
- return $false
- }
- function Emit-EmptyValue {
- param([string]$type, [string]$indent, [string]$tagPrefix = "", [bool]$valueListAllowed = $false)
- $type = Get-ValueKindType $type
- if ($valueListAllowed) { return }
- $t = if ($null -eq $type) { "" } else { "$type" }
- $tBare = if ($t -match '^xs:(.+)$') { $matches[1] } else { $t }
- $pf = $tagPrefix
- if ($t -eq "") { X "$indent<${pf}value xsi:nil=`"true`"/>" }
- elseif ($t -eq "StandardPeriod") {
- X "$indent<${pf}value xsi:type=`"v8:StandardPeriod`">"
- X "$indent`t<v8:variant xsi:type=`"v8:StandardPeriodVariant`">Custom</v8:variant>"
- X "$indent`t<v8:startDate>0001-01-01T00:00:00</v8:startDate>"
- X "$indent`t<v8:endDate>0001-01-01T00:00:00</v8:endDate>"
- X "$indent</${pf}value>"
- }
- elseif ($tBare -match '^string') { X "$indent<${pf}value xsi:type=`"xs:string`"/>" }
- elseif ($tBare -match '^(date|time)') { X "$indent<${pf}value xsi:type=`"xs:dateTime`">0001-01-01T00:00:00</${pf}value>" }
- elseif ($tBare -match '^decimal') { X "$indent<${pf}value xsi:type=`"xs:decimal`">0</${pf}value>" }
- elseif ($tBare -eq "boolean") { X "$indent<${pf}value xsi:type=`"xs:boolean`">false</${pf}value>" }
- else { X "$indent<${pf}value xsi:nil=`"true`"/>" }
- }
- function Parse-DataParamShorthand {
- param([string]$s)
- $result = @{ parameter = ""; value = $null; use = $true; userSettingID = $null; viewMode = $null }
- if ($s -match '@user') { $result.userSettingID = "auto"; $s = $s -replace '\s*@user', '' }
- if ($s -match '@off') { $result.use = $false; $s = $s -replace '\s*@off', '' }
- if ($s -match '@quickAccess') { $result.viewMode = "QuickAccess"; $s = $s -replace '\s*@quickAccess', '' }
- if ($s -match '@normal') { $result.viewMode = "Normal"; $s = $s -replace '\s*@normal', '' }
- $s = $s.Trim()
- if ($s -match '^([^=]+)=\s*(.+)$') {
- $result.parameter = $Matches[1].Trim()
- $valStr = $Matches[2].Trim()
- $periodVariants = @("Custom","Today","ThisWeek","ThisTenDays","ThisMonth","ThisQuarter","ThisHalfYear","ThisYear","FromBeginningOfThisWeek","FromBeginningOfThisTenDays","FromBeginningOfThisMonth","FromBeginningOfThisQuarter","FromBeginningOfThisHalfYear","FromBeginningOfThisYear","LastWeek","LastTenDays","LastMonth","LastQuarter","LastHalfYear","LastYear","NextDay","NextWeek","NextTenDays","NextMonth","NextQuarter","NextHalfYear","NextYear","TillEndOfThisWeek","TillEndOfThisTenDays","TillEndOfThisMonth","TillEndOfThisQuarter","TillEndOfThisHalfYear","TillEndOfThisYear")
- if ($periodVariants -contains $valStr) { $result.value = @{ variant = $valStr } }
- elseif ($valStr -match '^\d{4}-\d{2}-\d{2}T') { $result.value = $valStr }
- elseif ($valStr -eq "true" -or $valStr -eq "false") { $result.value = [bool]($valStr -eq "true") }
- else { $result.value = $valStr }
- } else { $result.parameter = $s }
- return $result
- }
- function Emit-DataParameters {
- param($items, [string]$indent, $blockViewMode = $null)
- if (-not $items -or @($items).Count -eq 0) { return }
- X "$indent<dcsset:dataParameters>"
- foreach ($dp in @($items)) {
- if ($dp -is [string]) {
- $parsed = Parse-DataParamShorthand $dp
- $dpObj = New-Object PSObject
- $dpObj | Add-Member -NotePropertyName "parameter" -NotePropertyValue $parsed.parameter
- if ($null -ne $parsed.value) { $dpObj | Add-Member -NotePropertyName "value" -NotePropertyValue $parsed.value }
- if ((-not (Get-DslBool $parsed @('use') $true))) { $dpObj | Add-Member -NotePropertyName "use" -NotePropertyValue $false }
- if ($parsed.userSettingID) { $dpObj | Add-Member -NotePropertyName "userSettingID" -NotePropertyValue $parsed.userSettingID }
- if ($parsed.viewMode) { $dpObj | Add-Member -NotePropertyName "viewMode" -NotePropertyValue $parsed.viewMode }
- $dp = $dpObj
- }
- X "$indent`t<dcscor:item xsi:type=`"dcsset:SettingsParameterValue`">"
- if ((-not (Get-DslBool $dp @('use') $true))) { X "$indent`t`t<dcscor:use>false</dcscor:use>" }
- X "$indent`t`t<dcscor:parameter>$(Esc-XmlText "$($dp.parameter)")</dcscor:parameter>"
- $dpValIsArr = ($dp.value -is [array]) -or ($dp.value -is [System.Collections.IList] -and $dp.value -isnot [string])
- if ($dpValIsArr) {
- # Список значений параметра (valueListAllowed) — отдельный <dcscor:value> на каждое.
- $avtype = "$($dp.valueType)"
- foreach ($v in @($dp.value)) {
- $vStr = if ($v -is [bool]) { "$v".ToLower() } else { "$v" }
- if ($avtype -match '^[a-zA-Z]+:') { X "$indent`t`t<dcscor:value xsi:type=`"$avtype`">$(Esc-XmlText $(if ($avtype -eq 'dcscor:DesignTimeValue') { Normalize-DesignTimeValue $vStr } else { $vStr }))</dcscor:value>" }
- elseif ("$vStr" -match '^(ПланСчетов|Справочник|Перечисление|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|РегистрСведений|ПланОбмена)\.' -or "$vStr" -match '^(ChartOfAccounts|Catalog|Enum|Document|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|InformationRegister|ExchangePlan)\.') { X "$indent`t`t<dcscor:value xsi:type=`"dcscor:DesignTimeValue`">$(Esc-XmlText (Normalize-DesignTimeValue $vStr))</dcscor:value>" }
- else { X "$indent`t`t<dcscor:value xsi:type=`"xs:string`">$(Esc-XmlText $vStr)</dcscor:value>" }
- }
- } elseif ((Get-DslBool $dp @('nilValue') $false)) {
- X "$indent`t`t<dcscor:value xsi:nil=`"true`"/>"
- } elseif ((Test-EmptyValue $dp.value) -and $dp.valueType) {
- # Явный типизированный пустой (xs:string-плейсхолдер и т.п.)
- Emit-EmptyValue -type "$($dp.valueType)" -indent "$indent`t`t" -tagPrefix "dcscor:" -valueListAllowed $false
- } elseif (Test-EmptyValue $dp.value) {
- # Нет значения и нет valueType → НЕ эмитим value-узел (form дин-список: use=false плейсхолдер).
- # (В отличие от skd-settings, где значение всегда присутствует.)
- } elseif ($null -ne $dp.value) {
- $vtype = Get-ValueKindType "$($dp.valueType)"
- if (($dp.value -is [PSCustomObject] -or $dp.value -is [hashtable] -or $dp.value -is [System.Collections.IDictionary]) -and ($dp.value.variant)) {
- $_hasDate = $false; $_hasSD = $false
- if ($dp.value -is [PSCustomObject]) { $_hasDate = [bool]$dp.value.PSObject.Properties['date']; $_hasSD = [bool]$dp.value.PSObject.Properties['startDate'] }
- else { $_hasDate = $dp.value.Contains('date'); $_hasSD = $dp.value.Contains('startDate') }
- $_variantStr = "$($dp.value.variant)"
- $_isSBD = $_hasDate -or (-not $_hasSD -and $_variantStr -like 'BeginningOf*')
- if ($_isSBD) {
- $_d = $null
- if ($dp.value -is [PSCustomObject] -and $dp.value.PSObject.Properties['date']) { $_d = "$($dp.value.date)" }
- elseif (($dp.value -is [System.Collections.IDictionary]) -and $dp.value.Contains('date')) { $_d = "$($dp.value['date'])" }
- X "$indent`t`t<dcscor:value xsi:type=`"v8:StandardBeginningDate`">"
- X "$indent`t`t`t<v8:variant xsi:type=`"v8:StandardBeginningDateVariant`">$(Esc-XmlText $_variantStr)</v8:variant>"
- if ($_variantStr -eq 'Custom') { if (-not $_d) { $_d = '0001-01-01T00:00:00' }; X "$indent`t`t`t<v8:date>$(Esc-XmlText $_d)</v8:date>" }
- X "$indent`t`t</dcscor:value>"
- } else {
- $_sd = $null; $_ed = $null
- if ($dp.value -is [PSCustomObject]) { if ($dp.value.PSObject.Properties['startDate']) { $_sd = "$($dp.value.startDate)" }; if ($dp.value.PSObject.Properties['endDate']) { $_ed = "$($dp.value.endDate)" } }
- else { if ($dp.value.Contains('startDate')) { $_sd = "$($dp.value['startDate'])" }; if ($dp.value.Contains('endDate')) { $_ed = "$($dp.value['endDate'])" } }
- X "$indent`t`t<dcscor:value xsi:type=`"v8:StandardPeriod`">"
- X "$indent`t`t`t<v8:variant xsi:type=`"v8:StandardPeriodVariant`">$(Esc-XmlText $_variantStr)</v8:variant>"
- if ($_variantStr -eq 'Custom') { if (-not $_sd) { $_sd = '0001-01-01T00:00:00' }; if (-not $_ed) { $_ed = '0001-01-01T00:00:00' }; X "$indent`t`t`t<v8:startDate>$(Esc-XmlText $_sd)</v8:startDate>"; X "$indent`t`t`t<v8:endDate>$(Esc-XmlText $_ed)</v8:endDate>" }
- X "$indent`t`t</dcscor:value>"
- }
- } elseif ($vtype -match '^[a-zA-Z]+:') {
- $vStr = if ($dp.value -is [bool]) { "$($dp.value)".ToLower() } else { "$($dp.value)" }
- X "$indent`t`t<dcscor:value xsi:type=`"$vtype`">$(Esc-XmlText $vStr)</dcscor:value>"
- } elseif ($vtype -eq 'boolean' -or $dp.value -is [bool]) {
- X "$indent`t`t<dcscor:value xsi:type=`"xs:boolean`">$(Esc-XmlText ("$($dp.value)".ToLower()))</dcscor:value>"
- } elseif ($vtype -match '^date' -or "$($dp.value)" -match '^\d{4}-\d{2}-\d{2}T') {
- X "$indent`t`t<dcscor:value xsi:type=`"xs:dateTime`">$(Esc-XmlText "$($dp.value)")</dcscor:value>"
- } elseif ($vtype -match '^decimal') {
- X "$indent`t`t<dcscor:value xsi:type=`"xs:decimal`">$(Esc-XmlText "$($dp.value)")</dcscor:value>"
- } elseif ($vtype -match '^string') {
- X "$indent`t`t<dcscor:value xsi:type=`"xs:string`">$(Esc-XmlText "$($dp.value)")</dcscor:value>"
- } elseif ("$($dp.value)" -match '^(ПланСчетов|Справочник|Перечисление|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|РегистрСведений|ПланОбмена)\.' -or "$($dp.value)" -match '^(ChartOfAccounts|Catalog|Enum|Document|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|InformationRegister|ExchangePlan)\.') {
- X "$indent`t`t<dcscor:value xsi:type=`"dcscor:DesignTimeValue`">$(Esc-XmlText (Normalize-DesignTimeValue "$($dp.value)"))</dcscor:value>"
- } else {
- X "$indent`t`t<dcscor:value xsi:type=`"xs:string`">$(Esc-XmlText "$($dp.value)")</dcscor:value>"
- }
- }
- if ($dp.viewMode) { X "$indent`t`t<dcsset:viewMode>$(Esc-XmlText "$($dp.viewMode)")</dcsset:viewMode>" }
- if ($dp.userSettingID) { $uid = if ("$($dp.userSettingID)" -eq "auto") { New-Guid-String } else { "$($dp.userSettingID)" }; X "$indent`t`t<dcsset:userSettingID>$(Esc-XmlText $uid)</dcsset:userSettingID>" }
- if ($dp.userSettingPresentation) { Emit-USPresentation -val $dp.userSettingPresentation -tag "dcsset:userSettingPresentation" -indent "$indent`t`t" }
- X "$indent`t</dcscor:item>"
- }
- if ($null -ne $blockViewMode) { X "$indent`t<dcsset:viewMode>$(Esc-XmlText "$blockViewMode")</dcsset:viewMode>" }
- X "$indent</dcsset:dataParameters>"
- }
- function Emit-DLParameter {
- param($p, $parsed, [string]$indent)
- X "$indent<Parameter>"
- $ci = "$indent`t"
- X "$ci<dcssch:name>$(Esc-XmlText $parsed.name)</dcssch:name>"
- # Title: явный override (shorthand [..] / объект title/presentation) или авто из имени.
- $title = $null
- if ($parsed.title) { $title = $parsed.title }
- elseif ($p -isnot [string] -and (Has-DLProp $p 'title') -and $p.title) { $title = $p.title }
- elseif ($p -isnot [string] -and (Has-DLProp $p 'presentation') -and $p.presentation) { $title = $p.presentation }
- if ($null -eq $title -or ($title -is [string] -and $title -eq '')) { $title = Title-FromName -name $parsed.name }
- Emit-DLMLText -tag "dcssch:title" -text $title -indent $ci
- # valueType
- if ($parsed.type) { Emit-DLValueType -typeStr $parsed.type -indent $ci }
- # value (дефолт nil; при valueListAllowed пустое — опускаем)
- $vla = (ConvertTo-DslBool $parsed.valueListAllowed 'valueListAllowed' $false)
- $valIsArray = ($parsed.value -is [array]) -or ($parsed.value -is [System.Collections.IList] -and $parsed.value -isnot [string])
- if ($valIsArray) {
- foreach ($v in @($parsed.value)) { Emit-DLValue -type $parsed.type -val $v -indent $ci -valueListAllowed $false }
- } elseif ($parsed.valueExplicit -and ($null -ne $parsed.value) -and ("$($parsed.value)" -eq '') -and (("$($parsed.type)" -eq '') -or ((Get-ValueKindType "$($parsed.type)") -match '^string'))) {
- # Явный пустой СТРОКОВЫЙ параметр (value:"" от декомпилятора) → типизированный пустой
- # <dcssch:value xsi:type="xs:string"/>, НЕ nil. Решается ФОРМОЙ value (""→typed-empty,
- # null/отсутствие→nil), независимо от valueListAllowed; декомпилятор различает ""/null
- # (Convert-TypedValue пустого xs:string → "", nil → value опущен/null). Корпус: 26 xs:string.
- X "$ci<dcssch:value xsi:type=`"xs:string`"/>"
- } elseif ($vla -and (Test-DLEmptyValue $parsed.value) -and $parsed.valueExplicit) {
- # valueListAllowed + явный пустой (value:null от декомпилятора) → платформа здесь пишет nil
- X "$ci<dcssch:value xsi:nil=`"true`"/>"
- } else {
- Emit-DLValue -type $parsed.type -val $parsed.value -indent $ci -valueListAllowed $vla
- }
- # useRestriction — ВСЕГДА; дефолт true; false только при явном useRestriction:false.
- $ur = $true
- if ($p -isnot [string] -and (Has-DLProp $p 'useRestriction')) { $ur = (ConvertTo-DslBool $p.useRestriction 'useRestriction' $false) }
- X "$ci<dcssch:useRestriction>$(if ($ur) { 'true' } else { 'false' })</dcssch:useRestriction>"
- # expression
- $expr = $null
- if ($p -isnot [string] -and (Has-DLProp $p 'expression') -and $p.expression) { $expr = "$($p.expression)" }
- if ($expr) { X "$ci<dcssch:expression>$(Esc-XmlText $expr)</dcssch:expression>" }
- # availableValues
- if ($p -isnot [string] -and (Has-DLProp $p 'availableValues') -and $p.availableValues) {
- foreach ($av in @($p.availableValues)) { Emit-DLAvailableValue -av $av -type $parsed.type -indent $ci }
- }
- # valueListAllowed
- if ($vla) { X "$ci<dcssch:valueListAllowed>true</dcssch:valueListAllowed>" }
- # availableAsField=false (hidden или явный)
- $aaf = $null
- if ((Get-DslBool $parsed @('hidden') $false)) { $aaf = $false }
- if ($p -isnot [string] -and (Has-DLProp $p 'availableAsField')) { $aaf = (ConvertTo-DslBool $p.availableAsField 'availableAsField' $false) }
- if ($aaf -eq $false) { X "$ci<dcssch:availableAsField>false</dcssch:availableAsField>" }
- # inputParameters
- if ($p -isnot [string] -and (Has-DLProp $p 'inputParameters') -and $p.inputParameters) { Emit-DLInputParameters -ip $p.inputParameters -indent $ci }
- # denyIncompleteValues
- if ($p -isnot [string] -and (Has-DLProp $p 'denyIncompleteValues') -and (Get-DslBool $p @('denyIncompleteValues') $false)) { X "$ci<dcssch:denyIncompleteValues>true</dcssch:denyIncompleteValues>" }
- # use
- $useVal = $null
- if ($p -isnot [string] -and (Has-DLProp $p 'use') -and $p.use) { $useVal = "$($p.use)" }
- if ($useVal) { X "$ci<dcssch:use>$(Esc-XmlText $useVal)</dcssch:use>" }
- X "$indent</Parameter>"
- }
- function Emit-DLParameters {
- param($params, [string]$indent)
- if (-not $params) { return }
- foreach ($p in @($params)) {
- if ($p -is [string]) {
- $parsed = Parse-DLParamShorthand $p
- } else {
- $resolvedType = ""
- if ((Has-DLProp $p 'type') -and $p.type) {
- if ($p.type -is [array] -or ($p.type -is [System.Collections.IList] -and $p.type -isnot [string])) {
- $resolvedType = (@($p.type | ForEach-Object { Resolve-TypeStr "$_" })) -join ' | '
- } else { $resolvedType = Resolve-TypeStr "$($p.type)" }
- } elseif ((Has-DLProp $p 'valueType') -and $p.valueType) {
- $resolvedType = Resolve-TypeStr "$($p.valueType)"
- }
- $parsed = @{ name = "$($p.name)"; type = $resolvedType; value = $(if (Has-DLProp $p 'value') { $p.value } else { $null }); valueExplicit = (Has-DLProp $p 'value'); title = $null }
- if ((Has-DLProp $p 'valueListAllowed') -and (Get-DslBool $p @('valueListAllowed') $false)) { $parsed.valueListAllowed = $true }
- if ((Has-DLProp $p 'hidden') -and (Get-DslBool $p @('hidden') $false)) { $parsed.hidden = $true }
- }
- Emit-DLParameter -p $p -parsed $parsed -indent $indent
- }
- }
- function Emit-Attributes {
- param($attrs, [string]$indent, $conditionalAppearance = $null)
- $hasCA = $conditionalAppearance -and @($conditionalAppearance).Count -gt 0
- # Платформа ВСЕГДА эмитит <Attributes> (100% корпуса; 162 формы — пустой <Attributes/>).
- if ((-not $attrs -or $attrs.Count -eq 0) -and -not $hasCA) { X "$indent<Attributes/>"; return }
- if (-not $attrs -or $attrs.Count -eq 0) {
- # Нет реквизитов, но есть условное оформление (последний child <Attributes>)
- X "$indent<Attributes>"
- Emit-ConditionalAppearance -items $conditionalAppearance -indent "$indent`t" -wrapTag 'ConditionalAppearance'
- X "$indent</Attributes>"
- return
- }
- X "$indent<Attributes>"
- $seenAttrs = @{}
- foreach ($attr in $attrs) {
- $attrId = New-Id
- $attrName = "$($attr.name)"
- Assert-UniqueName -name $attrName -seen $seenAttrs -kind 'attribute'
- X "$indent`t<Attribute name=`"$attrName`" id=`"$attrId`">"
- $inner = "$indent`t`t"
- # Title атрибута (зеркало Emit-Title): нет ключа → авто-вывод из имени (кроме main);
- # title "" → подавить; непустой → эмитить как есть.
- $hasTitleKey = $null -ne $attr.PSObject.Properties['title']
- if ($hasTitleKey) {
- if ($attr.title) { Emit-MLText -tag "Title" -text $attr.title -indent $inner }
- } elseif ($attr.main -ne $true) {
- Emit-MLText -tag "Title" -text (Title-FromName -name $attrName) -indent $inner
- }
- # Type
- if ($attr.type) {
- Emit-Type -typeStr "$($attr.type)" -indent $inner
- } else {
- X "$inner<Type/>"
- }
- # valueType: уточнение типа значений ValueList → <Settings xsi:type="v8:TypeDescription">
- # (та же грамматика типа, что и Type, включая составной "A | B"). Forgiving-синонимы.
- # Три состояния: нет ключа → нет Settings; "" → пустой <Settings…/>; тип → с типом.
- $vtSpec = $null; $hasVt = $false
- foreach ($k in @('valueType','typeDescription','описаниеТипов','типЗначений')) {
- if ($attr.PSObject.Properties[$k]) { $vtSpec = $attr.$k; $hasVt = $true; break }
- }
- if ($hasVt) {
- Emit-Type -typeStr "$vtSpec" -indent $inner -tag "Settings" -tagAttrs ' xsi:type="v8:TypeDescription"'
- }
- # Planner design-time <Settings xsi:type="pl:Planner"> (встроенный конфиг планировщика).
- # Идёт сразу после <Type> (как valueType/DynamicList Settings — взаимоисключающи).
- if ($attr.PSObject.Properties['planner'] -and $null -ne $attr.planner) {
- Emit-PlannerSettings -pl $attr.planner -ind $inner
- }
- # Chart/GanttChart design-time <Settings xsi:type="d4p1:Chart"/"d4p1:GanttChart">.
- # Тип Settings выводится из типа реквизита (d5p1:GanttChart → d4p1:GanttChart).
- if ($attr.PSObject.Properties['chart'] -and $null -ne $attr.chart) {
- $ctype = if ("$($attr.type)" -match 'GanttChart') { 'd4p1:GanttChart' } else { 'd4p1:Chart' }
- Emit-ChartSettings -chart $attr.chart -ind $inner -ctype $ctype
- }
- if ((Get-DslBool $attr @('main') $false)) {
- X "$inner<MainAttribute>true</MainAttribute>"
- }
- # Доступ по ролям: просмотр/редактирование (порядок схемы: View → Edit, после MainAttribute)
- if ($null -ne $attr.view) { Emit-XrFlag -tag 'View' -val $attr.view -indent $inner }
- if ($null -ne $attr.edit) { Emit-XrFlag -tag 'Edit' -val $attr.edit -indent $inner }
- $mainSaved = $false
- if ((Get-DslBool $attr @('main') $false) -and $attr.type) {
- $mainSaved = ("$($attr.type)") -match '^(CatalogObject|DocumentObject|ChartOfAccountsObject|ChartOfCalculationTypesObject|ChartOfCharacteristicTypesObject|ExchangePlanObject|BusinessProcessObject|TaskObject)\.' -or ("$($attr.type)") -match 'RecordManager\.'
- }
- # Явный ключ savedData побеждает (в т.ч. false → суппресс авто-вывода $mainSaved); нет ключа → авто.
- $emitSaved = if ($null -ne $attr.PSObject.Properties['savedData']) { (Get-DslBool $attr @('savedData') $false) } else { $mainSaved }
- if ($emitSaved) {
- X "$inner<SavedData>true</SavedData>"
- }
- # Save: сохранение значения реквизита в пользовательских настройках. true → <Field>имя</Field>;
- # строка/массив → под-поля с авто-префиксом "имя." (путь с точкой / UUID / =имя — как есть).
- # Нет ключа или false → не эмитим.
- if ($null -ne $attr.PSObject.Properties['save'] -and $null -ne $attr.save) {
- $saveFields = New-Object System.Collections.ArrayList
- if ($attr.save -is [bool]) {
- if ($attr.save) { [void]$saveFields.Add($attrName) }
- } else {
- foreach ($e in @($attr.save)) {
- $fld = "$e"
- if ([string]::IsNullOrEmpty($fld)) { continue }
- if ($fld -ne $attrName -and $fld -notmatch '\.' -and $fld -notmatch '^\d+/\d+') { $fld = "$attrName.$fld" }
- if (-not $saveFields.Contains($fld)) { [void]$saveFields.Add($fld) }
- }
- }
- if ($saveFields.Count -gt 0) {
- X "$inner<Save>"
- foreach ($f in $saveFields) { X "$inner`t<Field>$(Esc-XmlText $f)</Field>" }
- X "$inner</Save>"
- }
- }
- # Проверка заполнения реквизита → <FillCheck> (реальный тег; <FillChecking> в схеме нет).
- # bool true → ShowError (единственное значение в корпусе); строка → verbatim. Синоним fillChecking.
- $fcRaw = if ($null -ne $attr.PSObject.Properties['fillCheck']) { $attr.fillCheck } elseif ($null -ne $attr.PSObject.Properties['fillChecking']) { $attr.fillChecking } else { $null }
- if ($fcRaw) {
- $fcv = if ($fcRaw -is [bool]) { 'ShowError' } else { "$fcRaw" }
- X "$inner<FillCheck>$fcv</FillCheck>"
- }
- # UseAlways: поля, всегда читаемые (дин-список/таблица). Две формы DSL сливаются:
- # attr.useAlways[] (короткие имена) + columns с useAlways:true → <Field>ИмяРеквизита.Поле</Field>.
- $uaFields = New-Object System.Collections.ArrayList
- if ($attr.useAlways) {
- foreach ($e in @($attr.useAlways)) {
- $fld = "$e"
- # Префикс "ИмяРеквизита." добавляем к коротким именам. Поля дин-списка с маркером "~"
- # (query-поля, ~13% корпуса) — префикс ставится ПОСЛЕ "~": ~Остановлен → ~Список.Остановлен.
- # Полная форма (~Список.Остановлен / Список.Остановлен) — verbatim (forgiving ввод).
- if ($fld.StartsWith('~')) {
- $bare = $fld.Substring(1)
- if ($bare -notmatch "^$([regex]::Escape($attrName))\.") { $bare = "$attrName.$bare" }
- $fld = "~$bare"
- } elseif ($fld -notmatch "^$([regex]::Escape($attrName))\." -and $fld -notmatch '^\d+/\d+') {
- # UUID-ссылка (1/0:GUID) — НЕ префиксуем (платформа хранит её без "имя.")
- $fld = "$attrName.$fld"
- }
- if (-not $uaFields.Contains($fld)) { [void]$uaFields.Add($fld) }
- }
- }
- if ($attr.columns) {
- foreach ($col in $attr.columns) {
- if ((Get-DslBool $col @('useAlways') $false)) {
- $fld = "$attrName.$($col.name)"
- if (-not $uaFields.Contains($fld)) { [void]$uaFields.Add($fld) }
- }
- }
- }
- if ($uaFields.Count -gt 0) {
- X "$inner<UseAlways>"
- foreach ($f in $uaFields) { X "$inner`t<Field>$f</Field>" }
- X "$inner</UseAlways>"
- }
- Emit-FunctionalOptions -fo $attr.functionalOptions -indent $inner
- # Columns: прямые <Column> (ValueTable/Tree) + <AdditionalColumns table="X"> (доп. колонки
- # табличных частей объекта). Порядок схемы: прямые сначала, затем AdditionalColumns-группы.
- # Для дин-списка (есть settings) прямые колонки НЕ эмитим (служат лишь для UseAlways).
- $hasDirectCols = $attr.columns -and $attr.columns.Count -gt 0 -and -not $attr.settings
- $hasAddCols = $attr.additionalColumns -and @($attr.additionalColumns).Count -gt 0
- if ($hasDirectCols -or $hasAddCols) {
- X "$inner<Columns>"
- if ($hasDirectCols) {
- $seenCols = @{} # колонки уникальны в пределах своего реквизита
- foreach ($col in $attr.columns) {
- Assert-UniqueName -name "$($col.name)" -seen $seenCols -kind "column of '$attrName'"
- Emit-AttrColumn -col $col -indent "$inner`t"
- }
- }
- if ($hasAddCols) {
- foreach ($ac in @($attr.additionalColumns)) {
- # Пустой список колонок задаётся ЯВНО (`"columns": []`) — это законная форма,
- # платформа так пишет таблицу, у которой доп. колонок нет. А вот отсутствие ключа
- # — недосказанность автора: «доп. колонки есть», а какие, не указано. Раньше на
- # этом PS падал с «Не удается индексировать в массив NULL» (@($null).Count = 1).
- if ($null -eq $ac.PSObject.Properties['columns'] -or $null -eq $ac.columns) {
- Write-Error "additionalColumns group for table '$($ac.table)': key 'columns' is missing — list the columns, or pass an empty array for a table without extra columns"
- exit 1
- }
- $acCols = @($ac.columns)
- if ($acCols.Count -eq 0) {
- # Явно пустая группа → self-closing (как платформа)
- X "$inner`t<AdditionalColumns table=`"$($ac.table)`"/>"
- continue
- }
- X "$inner`t<AdditionalColumns table=`"$($ac.table)`">"
- $seenAcCols = @{} # уникальность в пределах группы AdditionalColumns
- foreach ($col in $acCols) {
- Assert-UniqueName -name "$($col.name)" -seen $seenAcCols -kind "column of '$attrName'"
- Emit-AttrColumn -col $col -indent "$inner`t`t"
- }
- X "$inner`t</AdditionalColumns>"
- }
- }
- X "$inner</Columns>"
- }
- # Settings (динамический список)
- if ($attr.settings) {
- $st = $attr.settings
- X "$inner<Settings xsi:type=`"DynamicList`">"
- $si = "$inner`t"
- # Порядок платформы: AutoFillAvailableFields, ManualQuery, DynamicDataRead, QueryText, Field*, MainTable, ListSettings
- # AutoFillAvailableFields — дефолт true; эмитим только при заданном ключе (отклонение).
- if ($null -ne $st.autoFillAvailableFields) { X "$si<AutoFillAvailableFields>$(if ($st.autoFillAvailableFields){'true'}else{'false'})</AutoFillAvailableFields>" }
- $hasQuery = $st.query -and "$($st.query)".Trim()
- # Явный ключ manualQuery (в т.ч. false) ПОБЕЖДАЕТ эвристику hasQuery (платформа изредка
- # хранит QueryText при ManualQuery=false — декомпилятор фиксирует это отклонение).
- $hasMQKey = ($st.PSObject.Properties['manualQuery']) -and ($null -ne $st.manualQuery)
- $mq = if ($hasMQKey) { if ($st.manualQuery) { "true" } else { "false" } } elseif ($hasQuery) { "true" } else { "false" }
- X "$si<ManualQuery>$mq</ManualQuery>"
- # DynamicDataRead: дефолт true; false только при явном отключении
- $ddr = if ((-not (Get-DslBool $st @('dynamicDataRead') $true))) { "false" } else { "true" }
- X "$si<DynamicDataRead>$ddr</DynamicDataRead>"
- if ($hasQuery) {
- $qtext = Resolve-TextFromFile "$($st.query)" $script:queryBaseDir
- X "$si<QueryText>$(Esc-XmlText $qtext)</QueryText>"
- }
- # Явные поля набора (редко): override title/dataPath
- if ($st.fields) {
- foreach ($fld in $st.fields) {
- # Тип поля набора: DataSetFieldField (дефолт) vs DataSetFieldNestedDataSet
- # (поле-вложенный набор = реквизит табличной части; маркер nested).
- # folder = папка-группировка полей (DataSetFieldFolder, без <field>); nested = вложенный набор.
- $isFolder = (ConvertTo-DslBool (Get-Prop $fld 'folder') 'folder' $false)
- $ftype = if ($fld.nested) { "DataSetFieldNestedDataSet" } elseif ($isFolder) { "DataSetFieldFolder" } else { "DataSetFieldField" }
- X "$si<Field xsi:type=`"dcssch:$ftype`">"
- # dataPath: явный (включая пустой "" → self-closing <dcssch:dataPath/>) побеждает; иначе fallback на field.
- if ($null -ne (Get-Prop $fld 'dataPath')) { $dp = "$($fld.dataPath)" }
- elseif ($isFolder) { $dp = "" }
- else { $dp = "$($fld.field)" }
- if ($dp -eq "") { X "$si`t<dcssch:dataPath/>" } else { X "$si`t<dcssch:dataPath>$(Esc-XmlText "$dp")</dcssch:dataPath>" }
- if (-not $isFolder) { X "$si`t<dcssch:field>$(Esc-XmlText "$($fld.field)")</dcssch:field>" }
- if ($fld.title) {
- X "$si`t<dcssch:title xsi:type=`"v8:LocalStringType`">"
- Emit-MLItems -val $fld.title -indent "$si`t`t"
- X "$si`t</dcssch:title>"
- }
- # Ограничения использования поля — после title, перед presentationExpression (порядок исходника)
- Emit-RestrictBlock 'useRestriction' $fld.useRestriction "$si`t"
- Emit-RestrictBlock 'attributeUseRestriction' $fld.attributeUseRestriction "$si`t"
- # presentationExpression поля — перед valueType (порядок исходника)
- if ($fld.presentationExpression) { X "$si`t<dcssch:presentationExpression>$(Esc-XmlText "$($fld.presentationExpression)")</dcssch:presentationExpression>" }
- # valueType поля набора (тип значения; вычисляемые/кастомные поля)
- if ($fld.valueType) { Emit-DLValueType -typeStr "$($fld.valueType)" -indent "$si`t" }
- # appearance поля (формат/оформление) — после valueType (порядок исходника)
- if ($fld.appearance) {
- X "$si`t<dcssch:appearance>"
- foreach ($prop in $fld.appearance.PSObject.Properties) { Emit-AppearanceValue -key $prop.Name -val $prop.Value -indent "$si`t`t" }
- X "$si`t</dcssch:appearance>"
- }
- # inputParameters поля (связь по параметрам выбора) — в конце
- if ($fld.inputParameters) { Emit-DLInputParameters -ip $fld.inputParameters -indent "$si`t" }
- X "$si</Field>"
- }
- }
- # Вычисляемые поля DataSet (<CalculatedField>) — после Field*, до Parameter*.
- Emit-CalcFields -calcFields $st.calculatedFields -indent $si
- # Schema-параметры дин-списка (DataCompositionSchemaParameter) — после Field*, до MainTable.
- Emit-DLParameters -params $st.parameters -indent $si
- # Ключ набора (query-based список без MainTable): KeyType (RowNumber/FieldValue/RowKey)
- # + KeyField* — после Parameter*, до MainTable. Захват/эмит факт. значений.
- if ($st.keyType) { X "$si<KeyType>$(Esc-XmlText "$($st.keyType)")</KeyType>" }
- if ($st.keyFields) { foreach ($kf in @($st.keyFields)) { X "$si<KeyField>$(Esc-XmlText "$kf")</KeyField>" } }
- if ($st.mainTable) { X "$si<MainTable>$(Normalize-MetaTypeRef "$($st.mainTable)")</MainTable>" }
- # GetInvisibleFieldPresentations — после MainTable (дефолт true; эмитим только при заданном ключе = отклонении false).
- if ($null -ne $st.getInvisibleFieldPresentations) { X "$si<GetInvisibleFieldPresentations>$(if ($st.getInvisibleFieldPresentations){'true'}else{'false'})</GetInvisibleFieldPresentations>" }
- # AutoSaveUserSettings — после MainTable (дефолт true; эмитим только при заданном ключе = отклонении).
- if ($null -ne $st.autoSaveUserSettings) { X "$si<AutoSaveUserSettings>$(if ($st.autoSaveUserSettings){'true'}else{'false'})</AutoSaveUserSettings>" }
- # ListSettings: filter/order/conditionalAppearance (skd-грамматика) + каноничные блок-GUID.
- # Нет items → контейнеры всё равно эмитятся (blockMeta) = каноничный пустой скелет платформы.
- $lsi = "$si`t"
- $lsOpenLen = $script:xml.Length
- X "$si<ListSettings>"
- $lsAfterOpenLen = $script:xml.Length # для self-closing, если внутри ничего не эмитнётся
- if ($st.PSObject.Properties['listSettings'] -and $null -ne $st.listSettings) {
- # Частичная/минимальная форма скелета — эмитим ТОЛЬКО указанные части с их блок-метой.
- # meta: 'v'=viewMode, 'u'=userSettingID (контейнеры); itemsViewMode/itemsUserSettingID → present.
- foreach ($prop in $st.listSettings.PSObject.Properties) {
- $tag = $prop.Name; $pv = $prop.Value
- # Значение дескриптора: строка-код "vu" ИЛИ объект { meta:"vu", presentation:<текст/ML> }
- # (контейнер несёт собственный userSettingPresentation — кастомную подпись настройки).
- if (($pv -is [PSCustomObject]) -or ($pv -is [System.Collections.IDictionary])) {
- $meta = "$(Get-Prop $pv 'meta')"; $bpres = Get-Prop $pv 'presentation'
- } else { $meta = "$pv"; $bpres = $null }
- $bvm = if ($meta -match 'v') { 'Normal' } else { $null }
- switch ($tag) {
- 'filter' { $bus = if ($meta -match 'u') { $script:CANON_FILTER_ID } else { $null }; Emit-Filter -items $st.filter -indent $lsi -blockViewMode $bvm -blockUserSettingID $bus -blockUserSettingPresentation $bpres }
- 'order' { $bus = if ($meta -match 'u') { $script:CANON_ORDER_ID } else { $null }; Emit-Order -items $st.order -indent $lsi -blockViewMode $bvm -blockUserSettingID $bus -blockUserSettingPresentation $bpres }
- 'conditionalAppearance' { $bus = if ($meta -match 'u') { $script:CANON_CA_ID } else { $null }; Emit-ConditionalAppearance -items $st.conditionalAppearance -indent $lsi -blockViewMode $bvm -blockUserSettingID $bus -blockUserSettingPresentation $bpres }
- 'itemsViewMode' { X "$lsi<dcsset:itemsViewMode>Normal</dcsset:itemsViewMode>" }
- 'itemsUserSettingID' { X "$lsi<dcsset:itemsUserSettingID>$($script:CANON_ITEMS_ID)</dcsset:itemsUserSettingID>" }
- 'itemsUserSettingPresentation' { Emit-USPresentation -val $pv -tag "dcsset:itemsUserSettingPresentation" -indent $lsi }
- 'dataParameters' { Emit-DataParameters -items $st.dataParameters -indent $lsi }
- 'structure' { Emit-ListGrouping (Get-ListGroupingValue $st) $lsi }
- }
- }
- } else {
- # Полный каноничный скелет (умолчание, ~93% форм) — без изменений.
- Emit-Filter -items $st.filter -indent $lsi -blockViewMode 'Normal' -blockUserSettingID $script:CANON_FILTER_ID
- # dataParameters — после filter, до order (XSD-порядок ListSettings)
- if ($st.PSObject.Properties['dataParameters']) { Emit-DataParameters -items $st.dataParameters -indent $lsi }
- Emit-Order -items $st.order -indent $lsi -blockViewMode 'Normal' -blockUserSettingID $script:CANON_ORDER_ID
- Emit-ConditionalAppearance -items $st.conditionalAppearance -indent $lsi -blockViewMode 'Normal' -blockUserSettingID $script:CANON_CA_ID
- # Группировка строк списка (авторинг без round-trip дескриптора) — после CA, до itemsViewMode
- Emit-ListGrouping (Get-ListGroupingValue $st) $lsi
- X "$lsi<dcsset:itemsViewMode>Normal</dcsset:itemsViewMode>"
- X "$lsi<dcsset:itemsUserSettingID>$($script:CANON_ITEMS_ID)</dcsset:itemsUserSettingID>"
- }
- if ($script:xml.Length -eq $lsAfterOpenLen) {
- # Пустой дескриптор listSettings:{} (оригинал = <ListSettings/>) → зеркалим self-closing.
- $script:xml.Length = $lsOpenLen
- X "$si<ListSettings/>"
- } else {
- X "$si</ListSettings>"
- }
- X "$inner</Settings>"
- }
- X "$indent`t</Attribute>"
- }
- # Условное оформление формы — последний child <Attributes> (та же DCS-грамматика, что settings CA)
- Emit-ConditionalAppearance -items $conditionalAppearance -indent "$indent`t" -wrapTag 'ConditionalAppearance'
- X "$indent</Attributes>"
- }
- function Emit-Parameters {
- param($params, [string]$indent)
- if (-not $params -or $params.Count -eq 0) { return }
- X "$indent<Parameters>"
- $seenParams = @{}
- foreach ($param in $params) {
- Assert-UniqueName -name "$($param.name)" -seen $seenParams -kind 'parameter'
- X "$indent`t<Parameter name=`"$($param.name)`">"
- $inner = "$indent`t`t"
- Emit-Type -typeStr "$($param.type)" -indent $inner
- if ((Get-DslBool $param @('key') $false)) {
- X "$inner<KeyParameter>true</KeyParameter>"
- }
- X "$indent`t</Parameter>"
- }
- X "$indent</Parameters>"
- }
- function Emit-Commands {
- param($cmds, [string]$indent)
- if (-not $cmds -or $cmds.Count -eq 0) { return }
- X "$indent<Commands>"
- $seenCmds = @{}
- foreach ($cmd in $cmds) {
- $cmdId = New-Id
- Assert-UniqueName -name "$($cmd.name)" -seen $seenCmds -kind 'command'
- X "$indent`t<Command name=`"$($cmd.name)`" id=`"$cmdId`">"
- $inner = "$indent`t`t"
- # Заголовок команды (зеркало Emit-Title): ключ есть+непустой → эмитим; ключ есть+"" → суппресс
- # (в оригинале <Title> нет — не додумывать); ключ отсутствует → авто-вывод из имени (помощь модели).
- if ($null -ne $cmd.PSObject.Properties['title']) {
- if ($cmd.title) { Emit-MLText -tag "Title" -text $cmd.title -indent $inner }
- } else {
- $cmdTitle = Title-FromName -name "$($cmd.name)"
- if ($cmdTitle) { Emit-MLText -tag "Title" -text $cmdTitle -indent $inner }
- }
- if ($cmd.tooltip) {
- Emit-MLText -tag "ToolTip" -text $cmd.tooltip -indent $inner
- }
- # Порядок детей — как пишет платформа (XSD FormCommand, корпус без обратных случаев):
- # Title ToolTip Use Shortcut Picture Action FunctionalOptions Representation ModifiesSavedData
- # CurrentRowUse AssociatedTableElementId
- if ($null -ne $cmd.use) { Emit-XrFlag -tag 'Use' -val $cmd.use -indent $inner }
- if ($cmd.shortcut) {
- X "$inner<Shortcut>$($cmd.shortcut)</Shortcut>"
- }
- Emit-CommandPicture -pic $cmd.picture -elemLt $cmd.loadTransparent -indent $inner
- # Обработчик; в расширении — с видом вызова (callType), или несколько: actions [{handler, callType}]
- if ($cmd.actions) {
- foreach ($act in @($cmd.actions)) {
- $ct = Normalize-CallType "$($act.callType)" "$($cmd.name)" 'Action'
- $ctAttr = if ($ct) { " callType=`"$ct`"" } else { "" }
- X "$inner<Action$ctAttr>$($act.handler)</Action>"
- Register-Handler "$($act.handler)" 'command'
- }
- } elseif ($cmd.action) {
- $ct = Normalize-CallType "$($cmd.callType)" "$($cmd.name)" 'Action'
- $ctAttr = if ($ct) { " callType=`"$ct`"" } else { "" }
- X "$inner<Action$ctAttr>$($cmd.action)</Action>"
- Register-Handler "$($cmd.action)" 'command'
- }
- Emit-FunctionalOptions -fo $cmd.functionalOptions -indent $inner
- # Значение — к перечислению команды (Text/Picture/TextPicture/Auto) приводит Normalize-EnumTags
- if ($cmd.representation) {
- X "$inner<Representation>$($cmd.representation)</Representation>"
- }
- if ((Get-DslBool $cmd @('modifiesSavedData') $false)) { X "$inner<ModifiesSavedData>true</ModifiesSavedData>" }
- if ($cmd.currentRowUse) {
- X "$inner<CurrentRowUse>$($cmd.currentRowUse)</CurrentRowUse>"
- }
- # Используемая таблица — имя элемента-таблицы (xsi:type обязателен).
- # Forgiving-ключи: table / associatedTableElementId (XML-тег) / ИспользуемаяТаблица (рус., регистр-незав.)
- $cmdTable = $cmd.table
- if (-not $cmdTable) { $cmdTable = $cmd.associatedTableElementId }
- if (-not $cmdTable) { $cmdTable = $cmd.используемаяТаблица }
- if ($cmdTable) {
- X "$inner<AssociatedTableElementId xsi:type=`"xs:string`">$(Esc-XmlText "$cmdTable")</AssociatedTableElementId>"
- }
- X "$indent`t</Command>"
- }
- X "$indent</Commands>"
- }
- function Resolve-CommandGroupKey {
- param([string]$key, [string]$panelTag)
- $k = ($key -replace '\s','').ToLower()
- if ($panelTag -eq 'NavigationPanel') {
- switch ($k) {
- 'important' { return 'FormNavigationPanelImportant' }
- 'важное' { return 'FormNavigationPanelImportant' }
- 'goto' { return 'FormNavigationPanelGoTo' }
- 'перейти' { return 'FormNavigationPanelGoTo' }
- 'seealso' { return 'FormNavigationPanelSeeAlso' }
- 'смтакже' { return 'FormNavigationPanelSeeAlso' }
- }
- } else {
- switch ($k) {
- 'important' { return 'FormCommandBarImportant' }
- 'важное' { return 'FormCommandBarImportant' }
- 'createbasedon' { return 'FormCommandBarCreateBasedOn' }
- 'создатьнаосновании' { return 'FormCommandBarCreateBasedOn' }
- }
- }
- return $key # verbatim
- }
- function Emit-CommandInterface {
- param($ci, [string]$indent)
- if (-not $ci) { return }
- $inner = "$indent`t"
- $panels = @(
- # Порядок панелей — как в выгрузке: панель навигации раньше командной (607 из 607 форм корпуса)
- @{ Tag='NavigationPanel'; Syns=@('navigationPanel','панельНавигации','ПанельНавигации') },
- @{ Tag='CommandBar'; Syns=@('commandBar','команднаяПанель','КоманднаяПанель') }
- )
- $present = @()
- foreach ($p in $panels) {
- $items = $null
- foreach ($syn in $p.Syns) { if ($null -ne $ci.PSObject.Properties[$syn]) { $items = $ci.($syn); break } }
- if ($null -ne $items) { $present += ,@{ Tag=$p.Tag; Items=$items } }
- }
- if ($present.Count -eq 0) { return }
- X "$indent<CommandInterface>"
- foreach ($p in $present) {
- X "$inner<$($p.Tag)>"
- # Нормализация: плоский список пар (элемент, group-из-дерева). Объект → дерево.
- $flat = New-Object System.Collections.ArrayList
- if ($p.Items -is [System.Management.Automation.PSCustomObject]) {
- foreach ($prop in $p.Items.PSObject.Properties) {
- $grpFromTree = Resolve-CommandGroupKey -key $prop.Name -panelTag $p.Tag
- foreach ($it in @($prop.Value)) { [void]$flat.Add(@{ item=$it; treeGroup=$grpFromTree }) }
- }
- } else {
- foreach ($it in @($p.Items)) { [void]$flat.Add(@{ item=$it; treeGroup=$null }) }
- }
- foreach ($fi in $flat) {
- $item = $fi.item; $treeGroup = $fi.treeGroup
- if ($item -is [string]) {
- $cmd = $item; $type = 'Auto'; $attr = $null; $grp = $null; $idx = $null; $dv = $null; $vis = $null
- } else {
- $cmd = Get-ElProp $item @('command','команда')
- $type = Get-ElProp $item @('type','тип'); if (-not $type) { $type = 'Auto' }
- $attr = Get-ElProp $item @('attribute','реквизит')
- $grp = Get-ElProp $item @('group','группа','группаКоманд')
- $idx = Get-ElProp $item @('index','индекс')
- $dv = Get-ElProp $item @('defaultVisible','видимость','видимостьПоУмолчанию')
- $vis = Get-ElProp $item @('visible','видимостьПоРолям','настройкаВидимости')
- }
- # group из дерева побеждает (если задан и непустой); явный group элемента — фолбэк
- if ($treeGroup) { $grp = $treeGroup }
- X "$inner`t<Item>"
- X "$inner`t`t<Command>$(Esc-XmlText "$cmd")</Command>"
- X "$inner`t`t<Type>$type</Type>"
- if ($attr) { X "$inner`t`t<Attribute>$(Esc-XmlText "$attr")</Attribute>" }
- if ($grp) { X "$inner`t`t<CommandGroup>$(Esc-XmlText "$grp")</CommandGroup>" }
- if ($null -ne $idx) { X "$inner`t`t<Index>$idx</Index>" }
- if ($null -ne $dv) { X "$inner`t`t<DefaultVisible>$(if ($dv){'true'}else{'false'})</DefaultVisible>" }
- if ($null -ne $vis) { Emit-XrFlag -tag 'Visible' -val $vis -indent "$inner`t`t" }
- X "$inner`t</Item>"
- }
- X "$inner</$($p.Tag)>"
- }
- X "$indent</CommandInterface>"
- }
- function Get-FormRootRank([string]$tag) {
- $i = [array]::IndexOf(($script:formRootTagOrder -split ' '), $tag)
- if ($i -lt 0) { return [array]::IndexOf(($script:formRootTagOrder -split ' '), 'AutoCommandBar') - 0.5 }
- return $i
- }
- function Emit-Properties {
- param($props, [string]$indent)
- if (-not $props) { return }
- # camelCase -> PascalCase mapping for known properties
- $propMap = @{
- "autoTitle" = "AutoTitle"
- "windowOpeningMode" = "WindowOpeningMode"
- "commandBarLocation" = "CommandBarLocation"
- "saveDataInSettings" = "SaveDataInSettings"
- "autoSaveDataInSettings" = "AutoSaveDataInSettings"
- "autoTime" = "AutoTime"
- "usePostingMode" = "UsePostingMode"
- "repostOnWrite" = "RepostOnWrite"
- "autoURL" = "AutoURL"
- "autoFillCheck" = "AutoFillCheck"
- "customizable" = "Customizable"
- "enterKeyBehavior" = "EnterKeyBehavior"
- "verticalScroll" = "VerticalScroll"
- "scalingMode" = "ScalingMode"
- "useForFoldersAndItems" = "UseForFoldersAndItems"
- "reportResult" = "ReportResult"
- "detailsData" = "DetailsData"
- "reportFormType" = "ReportFormType"
- "autoShowState" = "AutoShowState"
- "width" = "Width"
- "height" = "Height"
- "group" = "Group"
- }
- foreach ($p in $props.PSObject.Properties) {
- $xmlName = if ($propMap.ContainsKey($p.Name)) { $propMap[$p.Name] } else {
- # Auto PascalCase: first letter uppercase
- $p.Name.Substring(0,1).ToUpper() + $p.Name.Substring(1)
- }
- # Convert boolean to lowercase string (PS renders as True/False)
- $val = $p.Value
- # Пустая строка = суппресс-маркер (напр. autoTitle:"" — не эмитить и не додумывать)
- if ($val -is [string] -and $val -eq '') { continue }
- if ($val -is [bool]) {
- $val = if ($val) { "true" } else { "false" }
- }
- X "$indent<$xmlName>$(Esc-XmlText "$val")</$xmlName>"
- }
- }
- function Normalize-PanelSynonyms {
- param($el)
- if ($null -eq $el) { return }
- $panelSyns = @{
- 'commandBar' = @('commandBar','autoCommandBar','AutoCommandBar','autoCmdBar','cmdBar','КоманднаяПанель')
- 'contextMenu' = @('contextMenu','ContextMenu','КонтекстноеМеню')
- }
- foreach ($canon in $panelSyns.Keys) {
- foreach ($syn in $panelSyns[$canon]) {
- $p = $el.PSObject.Properties[$syn]
- if ($null -ne $p -and ($p.Value -is [array] -or $p.Value -is [System.Management.Automation.PSCustomObject])) {
- if ($syn -ne $canon -and $null -eq $el.PSObject.Properties[$canon]) {
- $v = $p.Value
- $el.PSObject.Properties.Remove($syn) | Out-Null
- $el | Add-Member -NotePropertyName $canon -NotePropertyValue $v -Force
- }
- break
- }
- }
- }
- }
- function Normalize-ElementSynonyms {
- param($el)
- if ($null -eq $el) { return }
- Normalize-PanelSynonyms $el
- # Тип-синонимы (commandBar/autoCommandBar → элемент-тип) применяем ТОЛЬКО к строковому
- # значению (имя элемента); объект/массив уже отнесён к панель-свойству выше.
- $typeSyn = @{ "commandBar" = "cmdBar"; "autoCommandBar" = "autoCmdBar" }
- foreach ($pair in $typeSyn.GetEnumerator()) {
- $src = $el.PSObject.Properties[$pair.Key]
- if ($null -ne $src -and ($src.Value -is [string]) -and $null -eq $el.PSObject.Properties[$pair.Value]) {
- $val = $el.($pair.Key)
- $el.PSObject.Properties.Remove($pair.Key) | Out-Null
- $el | Add-Member -NotePropertyName $pair.Value -NotePropertyValue $val -Force
- }
- }
- if ($el.PSObject.Properties["extTooltip"] -and $null -eq $el.PSObject.Properties["extendedTooltip"]) {
- $val = $el.extTooltip
- $el.PSObject.Properties.Remove("extTooltip") | Out-Null
- $el | Add-Member -NotePropertyName "extendedTooltip" -NotePropertyValue $val -Force
- }
- # Рекурсия в детей панелей (commandBar/contextMenu) — нормализуем кнопки/группы внутри
- foreach ($pk in @('commandBar','contextMenu')) {
- $pp = $el.PSObject.Properties[$pk]
- if ($null -ne $pp) {
- $kids = if ($pp.Value -is [array]) { $pp.Value } elseif ($null -ne $pp.Value) { $pp.Value.children } else { $null }
- if ($kids) { foreach ($child in $kids) { Normalize-ElementSynonyms $child } }
- }
- }
- if ($el.PSObject.Properties["children"] -and $el.children) {
- foreach ($child in $el.children) { Normalize-ElementSynonyms $child }
- }
- if ($el.PSObject.Properties["columns"] -and $el.columns) {
- foreach ($child in $el.columns) { Normalize-ElementSynonyms $child }
- }
- }
- # Явный ключ набора (FieldValue/RowKey/RowNumber) у списка без основной таблицы: ссылки в строке нет —
- # нет и DefaultPicture. Признак берётся из XML реквизита (Settings/KeyType, Settings/MainTable).
- function Test-DynListExplicitKey($attrNode) {
- $kt = $attrNode.SelectSingleNode("f:Settings/f:KeyType", $nsMgr)
- if ($null -eq $kt) { return $false }
- $v = $kt.InnerText.Trim()
- if ($v -eq '' -or $v -eq 'Auto') { return $false }
- return ($null -eq $attrNode.SelectSingleNode("f:Settings/f:MainTable", $nsMgr))
- }
- function ApplyDynamicListTableHeuristic {
- param($el, [string]$listName, [bool]$hasMainTable, [bool]$hasKeyType = $false)
- if ($null -eq $el) { return }
- if ($el.PSObject.Properties["table"] -and $null -ne $el.table -and "$($el.path)" -eq $listName) {
- # Маркер дин-список-таблицы → Emit-Table эмитит блок свойств (Group A defaults)
- $el | Add-Member -NotePropertyName "_dynList" -NotePropertyValue $true -Force
- if ($null -eq $el.PSObject.Properties["tableAutofill"]) {
- $el | Add-Member -NotePropertyName "tableAutofill" -NotePropertyValue $false -Force
- }
- if ($null -eq $el.PSObject.Properties["commandBarLocation"]) {
- $el | Add-Member -NotePropertyName "commandBarLocation" -NotePropertyValue "None" -Force
- }
- # RowPictureDataPath: умный дефолт <Список>.DefaultPicture, если ключ ОТСУТСТВУЕТ.
- # Декомпилятор опускает ключ при rpdp == smart-default (ждёт реинъекции); реальное отсутствие
- # фиксирует ""-маркером (НЕ перезатирается). Гейт hasMainTable снят: дин-список без mainTable
- # (напр. query-based) тоже несёт RowPictureDataPath. Но не при явном keyType: строка без ссылки,
- # DefaultPicture платформа отвергает («Неверный путь к данным»); в корпусе у таких списков
- # RowPictureDataPath нет ни разу.
- if ($null -eq $el.PSObject.Properties["rowPictureDataPath"] -and -not $hasKeyType) {
- $el | Add-Member -NotePropertyName "rowPictureDataPath" -NotePropertyValue "$listName.DefaultPicture" -Force
- }
- }
- if ($el.PSObject.Properties["children"] -and $el.children) {
- foreach ($child in $el.children) { ApplyDynamicListTableHeuristic $child $listName $hasMainTable $hasKeyType }
- }
- }
- # === 6. Find element by name recursively ===
- function Find-Element($startNode, [string]$targetName) {
- foreach ($child in $startNode.ChildNodes) {
- if ($child.NodeType -ne 'Element') { continue }
- $childName = $child.GetAttribute("name")
- if ($childName -eq $targetName) { return $child }
- $ci = $child.SelectSingleNode("f:ChildItems", $nsMgr)
- if ($ci) {
- $found = Find-Element $ci $targetName
- if ($found) { return $found }
- }
- }
- return $null
- }
- # === 7. Detect indent level of a container's children ===
- function Get-ChildIndent($container) {
- foreach ($child in $container.ChildNodes) {
- if ($child.NodeType -eq 'Whitespace' -or $child.NodeType -eq 'SignificantWhitespace') {
- $text = $child.Value
- if ($text -match '^\r?\n(\t+)$') { return $Matches[1] }
- if ($text -match '^\r?\n(\t+)') { return $Matches[1] }
- }
- }
- # Fallback: count depth from root
- $depth = 0
- $current = $container
- while ($current -and $current -ne $xmlDoc.DocumentElement) {
- $depth++
- $current = $current.ParentNode
- }
- return "`t" * ($depth + 1)
- }
- # === 8. Insert node into container ===
- function Insert-IntoContainer($container, $newNode, $afterName, $childIndent) {
- $refNode = $null
- if ($afterName) {
- # Find the after-element, then insert after it
- $afterElem = $null
- foreach ($child in $container.ChildNodes) {
- if ($child.NodeType -eq 'Element' -and $child.GetAttribute("name") -eq $afterName) {
- $afterElem = $child
- break
- }
- }
- if ($afterElem) {
- $refNode = $afterElem.NextSibling
- } else {
- Write-Host "[WARN] after='$afterName' not found in target container, appending at end"
- }
- }
- if (-not $refNode) {
- # Append at end: insert before trailing whitespace
- $trailing = $container.LastChild
- if ($trailing -and ($trailing.NodeType -eq 'Whitespace' -or $trailing.NodeType -eq 'SignificantWhitespace')) {
- $refNode = $trailing
- }
- }
- $ws = $xmlDoc.CreateWhitespace("`r`n$childIndent")
- if ($refNode) {
- $container.InsertBefore($ws, $refNode) | Out-Null
- $container.InsertBefore($newNode, $refNode) | Out-Null
- } else {
- # Container is empty (self-closing) — add framing whitespace
- $container.AppendChild($ws) | Out-Null
- $container.AppendChild($newNode) | Out-Null
- $parentIndent = if ($childIndent.Length -gt 1) { $childIndent.Substring(0, $childIndent.Length - 1) } else { "" }
- $closeWs = $xmlDoc.CreateWhitespace("`r`n$parentIndent")
- $container.AppendChild($closeWs) | Out-Null
- }
- }
- # === 9. Generate fragment, parse, import nodes ===
- # Все пространства имён корня формы — эмиттер пишет xsi:type, ent:, style: и др.
- $allNsDecl = 'xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcssch="http://v8.1c.ru/8.1/data-composition-system/schema" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
- function Parse-Fragment([string]$xmlText) {
- $fragDoc = New-Object System.Xml.XmlDocument
- $fragDoc.PreserveWhitespace = $true
- $fragDoc.LoadXml($xmlText)
- return $fragDoc
- }
- function Import-ElementNodes($fragDoc) {
- $nodes = @()
- foreach ($child in $fragDoc.DocumentElement.ChildNodes) {
- if ($child.NodeType -eq 'Element') {
- $nodes += $xmlDoc.ImportNode($child, $true)
- }
- }
- return $nodes
- }
- # === 9c. Помощники операций над деревом элементов ===
- function Fail([string]$msg) {
- Write-Host "[ERROR] $msg"
- exit 1
- }
- function Same($a, $b) { return [object]::ReferenceEquals($a, $b) }
- function Test-IsWs($n) {
- return ($null -ne $n -and ($n.NodeType -eq 'Whitespace' -or $n.NodeType -eq 'SignificantWhitespace'))
- }
- function Get-NextElementSibling($n) {
- $s = $n.NextSibling
- while ($null -ne $s -and $s.NodeType -ne 'Element') { $s = $s.NextSibling }
- return $s
- }
- function Get-FirstElementChild($n) {
- foreach ($c in $n.ChildNodes) { if ($c.NodeType -eq 'Element') { return $c } }
- return $null
- }
- function Get-ContainerLabel($c) {
- if (Same $c $root) { return "корень формы" }
- return $c.GetAttribute("name")
- }
- # Вставка узла в контейнер: перед $ref или в конец. Перевод строки с отступом идёт перед каждым
- # дочерним узлом, у пустого контейнера — ещё и закрывающий с отступом родителя.
- function Insert-NodeAt($container, $node, $ref, [string]$indent) {
- if ($null -ne $ref) {
- $container.InsertBefore($node, $ref) | Out-Null
- $container.InsertBefore($xmlDoc.CreateWhitespace("`r`n$indent"), $ref) | Out-Null
- return
- }
- $trailing = $container.LastChild
- if (Test-IsWs $trailing) {
- $container.InsertBefore($xmlDoc.CreateWhitespace("`r`n$indent"), $trailing) | Out-Null
- $container.InsertBefore($node, $trailing) | Out-Null
- } else {
- $container.AppendChild($xmlDoc.CreateWhitespace("`r`n$indent")) | Out-Null
- $container.AppendChild($node) | Out-Null
- $parentIndent = if ($indent.Length -gt 0) { $indent.Substring(0, $indent.Length - 1) } else { "" }
- $container.AppendChild($xmlDoc.CreateWhitespace("`r`n$parentIndent")) | Out-Null
- }
- }
- # Дочерний узел элемента — на его каноническое место (см. 9b). Неизвестный тег — в конец.
- function Insert-ChildCanonical($parent, $child) {
- $rank = Get-ChildRank $parent.LocalName $child.LocalName
- $ref = $null
- if ($rank -ge 0) {
- foreach ($c in $parent.ChildNodes) {
- if ($c.NodeType -ne 'Element') { continue }
- if ((Get-ChildRank $parent.LocalName $c.LocalName) -gt $rank) { $ref = $c; break }
- }
- }
- Insert-NodeAt $parent $child $ref (Get-ChildIndent $parent)
- }
- # Узел вместе с переводом строки перед ним.
- function Remove-NodeWithWs($node) {
- $parent = $node.ParentNode
- $prev = $node.PreviousSibling
- if (Test-IsWs $prev) { $parent.RemoveChild($prev) | Out-Null }
- $parent.RemoveChild($node) | Out-Null
- }
- # Пустой ChildItems платформа не пишет никогда: у группы без элементов тега просто нет.
- function Remove-IfEmptyChildItems($ci) {
- if ($null -ne (Get-FirstElementChild $ci)) { return }
- Remove-NodeWithWs $ci
- if (Same $ci $script:rootCI) { $script:rootCI = $null }
- }
- $script:rootAfterChildItems = @('Attributes','Parameters','Commands','CommandInterface','ConditionalAppearance','BaseForm')
- function Get-OrCreateChildItems($container) {
- $ci = $container.SelectSingleNode("f:ChildItems", $nsMgr)
- if ($null -ne $ci) { return $ci }
- $ci = $xmlDoc.CreateElement("ChildItems", $formNs)
- if (Same $container $root) {
- # ChildItems формы — после Events или AutoCommandBar, иначе перед первой из следующих секций
- $insertAfter = $root.SelectSingleNode("f:Events", $nsMgr)
- if ($null -eq $insertAfter) { $insertAfter = $root.SelectSingleNode("f:AutoCommandBar", $nsMgr) }
- $ref = $null
- if ($null -ne $insertAfter) {
- $ref = Get-NextElementSibling $insertAfter
- } else {
- foreach ($c in $root.ChildNodes) {
- if ($c.NodeType -eq 'Element' -and $script:rootAfterChildItems -contains $c.LocalName) { $ref = $c; break }
- }
- }
- Insert-NodeAt $root $ci $ref "`t"
- $script:rootCI = $ci
- } else {
- Insert-ChildCanonical $container $ci
- }
- return $ci
- }
- function Get-NodeIndent($node) {
- $prev = $node.PreviousSibling
- if ((Test-IsWs $prev) -and $prev.Value -match '\n(\t*)$') { return $Matches[1] }
- return ""
- }
- # Сдвиг отступов поддерева при смене глубины: каждый перевод строки внутри узла начинается с отступа
- # старого места — меняем этот префикс на новый.
- function Set-SubtreeIndent($node, [string]$oldIndent, [string]$newIndent) {
- if ($oldIndent -eq $newIndent) { return }
- foreach ($c in $node.ChildNodes) {
- if (Test-IsWs $c) {
- if ($c.Value -match '^(\r?\n)(\t*)$' -and $Matches[2].StartsWith($oldIndent)) {
- $c.Value = $Matches[1] + $newIndent + $Matches[2].Substring($oldIndent.Length)
- }
- } elseif ($c.NodeType -eq 'Element') {
- Set-SubtreeIndent $c $oldIndent $newIndent
- }
- }
- }
- # Элемент формы по имени: дерево ChildItems и командная панель формы (с кнопками). BaseForm,
- # реквизиты и команды не просматриваются. Имена в 1С регистронезависимы.
- function Find-FormElement([string]$name) {
- $scopes = @()
- if ($null -ne $script:rootCI) { $scopes += $script:rootCI }
- $acb = $root.SelectSingleNode("f:AutoCommandBar", $nsMgr)
- if ($null -ne $acb) {
- if ($acb.GetAttribute("name") -eq $name) { return $acb }
- $scopes += $acb
- }
- # Элементы — узлы ChildItems и служебные узлы элемента (для внятного отказа); <Event name=…> и
- # прочие именованные свойства — не элементы.
- foreach ($s in $scopes) {
- foreach ($n in $s.SelectNodes(".//*[@name]")) {
- if ($n.NamespaceURI -ne $formNs -or $n.GetAttribute("name") -ne $name) { continue }
- if ($n.ParentNode.LocalName -eq 'ChildItems' -or $script:companionTags -contains $n.LocalName) { return $n }
- }
- }
- return $null
- }
- function Get-NearestTable($node, [bool]$inclusive) {
- $cur = if ($inclusive) { $node } else { $node.ParentNode }
- while ($null -ne $cur -and $cur.NodeType -eq 'Element') {
- if ($cur.LocalName -eq 'Table') { return $cur }
- $cur = $cur.ParentNode
- }
- return $null
- }
- function Test-IsInside($node, $anc) {
- $cur = $node
- while ($null -ne $cur -and $cur.NodeType -eq 'Element') {
- if (Same $cur $anc) { return $true }
- $cur = $cur.ParentNode
- }
- return $false
- }
- # Позиция операции: контейнер + узел, перед которым вставлять ($null — в конец).
- # after/before — контейнер якоря; into — в конец (first — в начало); first без into — начало формы.
- function Resolve-Position($op, [string]$ctx, [bool]$required) {
- $after = $op.after; $before = $op.before; $into = $op.into
- $first = (ConvertTo-DslBool $op.first "${ctx}: first" $false)
- if ($after -and $before) { Fail "${ctx}: укажи что-то одно — after или before" }
- $anchorName = if ($after) { "$after" } elseif ($before) { "$before" } else { $null }
- if ($first -and $anchorName) { Fail "${ctx}: first — это начало контейнера, вместе с after/before не задаётся" }
- $intoEl = $null
- if ($into) {
- $intoEl = Find-FormElement "$into"
- if ($null -eq $intoEl) { Fail "${ctx}: контейнер '$into' не найден в форме" }
- }
- if ($anchorName) {
- $anchor = Find-FormElement $anchorName
- if ($null -eq $anchor) { Fail "${ctx}: элемент '$anchorName' не найден в форме" }
- $ci = $anchor.ParentNode
- if ($ci.LocalName -ne 'ChildItems') { Fail "${ctx}: '$anchorName' — служебный узел ($($anchor.LocalName)), рядом с ним ставить нельзя" }
- $container = $ci.ParentNode
- if ($null -ne $intoEl -and -not (Same $intoEl $container)) {
- Fail "${ctx}: '$anchorName' лежит в '$(Get-ContainerLabel $container)', а не в '$into'"
- }
- if ($after) {
- return @{ Container = $container; Ref = (Get-NextElementSibling $anchor); Anchor = $anchor; Desc = "$(Get-ContainerLabel $container), после $anchorName" }
- }
- return @{ Container = $container; Ref = $anchor; Anchor = $anchor; Desc = "$(Get-ContainerLabel $container), перед $anchorName" }
- }
- if ($null -eq $intoEl -and $first) { $intoEl = $root }
- if ($null -ne $intoEl) {
- $ref = $null
- if ($first) {
- $ci = $intoEl.SelectSingleNode("f:ChildItems", $nsMgr)
- if ($null -ne $ci) { $ref = Get-FirstElementChild $ci }
- }
- $where = if ($first) { "первым" } else { "в конец" }
- return @{ Container = $intoEl; Ref = $ref; Anchor = $null; Desc = "$(Get-ContainerLabel $intoEl), $where" }
- }
- if ($required) { Fail "${ctx}: не указано, куда — нужен after, before или into" }
- return $null
- }
- $script:containerTags = @('UsualGroup','Page','Pages','Table','ColumnGroup','CommandBar','AutoCommandBar','ButtonGroup','Popup','ContextMenu')
- $script:barTags = @('CommandBar','AutoCommandBar','ButtonGroup','Popup','ContextMenu')
- $script:barItemTags = @('Button','ButtonGroup','Popup')
- $script:additionTags = @('SearchStringAddition','ViewStatusAddition','SearchControlAddition')
- $script:tableItemTags = @('InputField','CheckBoxField','LabelField','PictureField','ColumnGroup')
- $script:companionTags = @('ContextMenu','ExtendedTooltip','AutoCommandBar','SearchStringAddition','ViewStatusAddition','SearchControlAddition')
- $script:dslTagMap = @{
- "radio"="RadioButtonField"; "columnGroup"="ColumnGroup"; "buttonGroup"="ButtonGroup"
- "searchString"="SearchStringAddition"; "viewStatus"="ViewStatusAddition"; "searchControl"="SearchControlAddition"
- "spreadsheet"="SpreadSheetDocumentField"; "html"="HTMLDocumentField"; "textDoc"="TextDocumentField"
- "formattedDoc"="FormattedDocumentField"; "progressBar"="ProgressBarField"; "trackBar"="TrackBarField"
- "chart"="ChartField"; "ganttChart"="GanttChartField"; "graphicalSchema"="GraphicalSchemaField"
- "planner"="PlannerField"; "periodField"="PeriodField"; "dendrogram"="DendrogramField"
- "group"="UsualGroup"; "input"="InputField"; "check"="CheckBoxField"; "label"="LabelDecoration"
- "labelField"="LabelField"; "table"="Table"; "pages"="Pages"; "page"="Page"; "button"="Button"
- "picture"="PictureDecoration"; "picField"="PictureField"; "calendar"="CalendarField"; "cmdBar"="CommandBar"; "popup"="Popup"
- }
- # Может ли элемент типа $nt лечь в $container. $node — переносимый узел (у добавления $null).
- function Assert-Placement([string]$nt, [string]$name, $node, $container, [string]$ctx) {
- $isRoot = Same $container $root
- $ct = if ($isRoot) { "Form" } else { $container.LocalName }
- $cl = Get-ContainerLabel $container
- if (-not $isRoot -and $script:containerTags -notcontains $ct) { Fail "${ctx}: '$cl' ($ct) не контейнер — в него нельзя положить элемент" }
- if ($null -ne $node -and (Test-IsInside $container $node)) { Fail "${ctx}: '$name' нельзя перенести внутрь самого себя — '$cl' лежит внутри '$name'" }
- if ($nt -eq 'Page' -and $ct -ne 'Pages') { Fail "${ctx}: страница '$name' может лежать только в группе страниц (Pages), а '$cl' — $ct" }
- if ($ct -eq 'Pages' -and $nt -ne 'Page') { Fail "${ctx}: в группе страниц '$cl' лежат только страницы (Page), а '$name' — $nt" }
- if ($script:barTags -contains $ct -and $script:barItemTags -notcontains $nt -and $script:additionTags -notcontains $nt) { Fail "${ctx}: в командной панели '$cl' лежат только кнопки, группы кнопок, подменю и дополнения таблицы, а '$name' — $nt" }
- # Группа кнопок и подменю — только внутри командной панели, меню, подменю или группы кнопок (по корпусу)
- if (@('ButtonGroup','Popup') -contains $nt -and $script:barTags -notcontains $ct) { Fail "${ctx}: '$name' ($nt) лежит только в командной панели, контекстном меню, подменю или группе кнопок, а '$cl' — $ct" }
- if ($nt -eq 'ColumnGroup' -and $null -eq (Get-NearestTable $container $true)) { Fail "${ctx}: группа колонок '$name' может лежать только внутри таблицы" }
- # Колонки таблицы — только поля и группы колонок (по корпусу других типов там нет);
- # командная панель и контекстное меню таблицы — свои правила выше.
- $inTable = if ($isRoot) { $null } else { Get-NearestTable $container $true }
- if ($null -ne $inTable -and $script:barTags -notcontains $ct -and $script:tableItemTags -notcontains $nt) {
- Fail "${ctx}: в таблице '$($inTable.GetAttribute('name'))' лежат только колонки (поля и группы колонок), а '$name' — $nt"
- }
- # Граница таблицы: колонки и поля табличной части привязаны к своей таблице. Кнопки — нет
- # (стандартная команда таблицы законно стоит и в командной панели формы).
- if ($null -ne $node -and $script:barItemTags -notcontains $nt) {
- $from = Get-NearestTable $node $false
- $to = if ($isRoot) { $null } else { Get-NearestTable $container $true }
- if (-not (Same $from $to)) {
- if ($null -ne $from) { Fail "${ctx}: '$name' принадлежит таблице '$($from.GetAttribute('name'))' — вынести его за её пределы или в другую таблицу нельзя" }
- Fail "${ctx}: '$name' не принадлежит таблице — внутрь таблицы '$($to.GetAttribute('name'))' его перенести нельзя"
- }
- }
- }
- function Assert-OpKeys($op, [string[]]$allowed, [string]$ctx) {
- foreach ($p in $op.PSObject.Properties) {
- if ($allowed -notcontains $p.Name) { Fail "${ctx}: неизвестный ключ '$($p.Name)'; допустимы: $($allowed -join ', ')" }
- }
- }
- # --- Добавление ---
- $script:chainNode = $null
- $script:defaultPos = $null
- function Invoke-Add($op, [string]$typeKey, [int]$idx) {
- $name = Get-ElementName -el $op -typeKey $typeKey
- $ctx = "elements[$idx] $typeKey '$name'"
- # Имя уже есть в форме — на момент этой операции (удалённое раньше в списке — свободно)
- $existing = Find-FormElement $name
- if ($null -ne $existing) {
- Write-Host "[ERROR] Element '$name' already exists in form (id=$($existing.GetAttribute('id'))) — element names must be unique"
- exit 1
- }
- $pos = Resolve-Position $op $ctx $false
- if ($null -eq $pos) {
- # Без своей позиции — как раньше: верхние into/after, следующие встают за предыдущим.
- if ($null -ne $script:chainNode) {
- $c = $script:chainNode.ParentNode.ParentNode
- $pos = @{ Container = $c; Ref = (Get-NextElementSibling $script:chainNode); Anchor = $null; Desc = "$(Get-ContainerLabel $c), после $($script:chainNode.GetAttribute('name'))" }
- } else {
- if ($null -eq $script:defaultPos) {
- $script:defaultPos = Resolve-Position $def "elements (верхние into/after)" $false
- if ($null -eq $script:defaultPos) { $script:defaultPos = @{ Container = $root; Ref = $null; Anchor = $null; Desc = "корень формы, в конец" } }
- }
- $pos = $script:defaultPos
- }
- $chained = $true
- } else {
- $chained = $false
- }
- Assert-Placement $script:dslTagMap[$typeKey] $name $null $pos.Container $ctx
- # Эмиттеру — копия элемента без ключей позиции (это не свойства элемента)
- $el = (ConvertFrom-JsonInput ($op | ConvertTo-Json -Depth 100 -Compress) 'element copy') | Select-Object -Property * -ExcludeProperty into, after, before, first
- Normalize-ElementSynonyms $el
- # Таблица динамического списка получает поведение списка, как в form-compile
- foreach ($a in $root.SelectNodes("f:Attributes/f:Attribute", $nsMgr)) {
- $t = $a.SelectSingleNode("f:Type/v8:Type", $nsMgr)
- if ($null -ne $t -and $t.InnerText.Trim() -eq 'cfg:DynamicList') { ApplyDynamicListTableHeuristic $el $a.GetAttribute('name') $true (Test-DynListExplicitKey $a) }
- }
- # Пул имён эмиттера — имена элементов формы на момент операции (без узлов событий)
- $script:seenElementNames = @{}
- foreach ($sc in (Get-ElementScopes)) {
- foreach ($n in $sc.SelectNodes(".//*[@name]")) {
- if ($n.NamespaceURI -eq $formNs -and ($n.ParentNode.LocalName -eq 'ChildItems' -or $script:companionTags -contains $n.LocalName)) {
- $script:seenElementNames[$n.GetAttribute('name')] = $true
- }
- }
- }
- $script:currentTableName = $null
- # Дополнение таблицы: источник — source или таблица, внутри которой оно лежит
- if ($script:additionTags -contains $script:dslTagMap[$typeKey]) {
- if ($el.source) {
- $src = Find-FormElement "$($el.source)"
- if ($null -eq $src -or $src.LocalName -ne 'Table') { Fail "${ctx}: source '$($el.source)' — нет такой таблицы в форме" }
- $el.source = $src.GetAttribute('name')
- } else {
- $tbl = if (Same $pos.Container $root) { $null } else { Get-NearestTable $pos.Container $true }
- if ($null -eq $tbl) { Fail "${ctx}: укажите source — таблицу, к которой относится дополнение" }
- $script:currentTableName = $tbl.GetAttribute('name')
- }
- }
- $ci = Get-OrCreateChildItems $pos.Container
- $indent = Get-ChildIndent $ci
- $script:xml = New-Object System.Text.StringBuilder 4096
- # Внутри командной панели, меню, подменю или группы кнопок кнопка — кнопка панели
- $inBar = $false
- $cur = $pos.Container
- while ($null -ne $cur -and $cur.NodeType -eq 'Element') {
- if ($script:barTags -contains $cur.LocalName) { $inBar = $true; break }
- $cur = $cur.ParentNode
- }
- # Обработчики элементов внутри таблицы — в область этой таблицы
- $tbl = if (Same $pos.Container $root) { $null } else { Get-NearestTable $pos.Container $true }
- $script:handlerTable = if ($null -ne $tbl) { $tbl.GetAttribute('name') } else { '' }
- X "<_F $allNsDecl>"
- Emit-Element -el $el -indent $indent -inCmdBar $inBar
- X "</_F>"
- $script:handlerTable = ''
- $node = @(Import-ElementNodes (Parse-Fragment (Sort-ElementTagOrder (Normalize-EnumTags $script:xml.ToString()))))[0]
- Insert-NodeAt $ci $node $pos.Ref $indent
- if ($chained) { $script:chainNode = $node }
- $pathStr = if ($op.path) { " -> $($op.path)" } else { "" }
- $evtNames = @($node.SelectNodes("f:Events/f:Event", $nsMgr) | ForEach-Object { $_.GetAttribute('name') })
- $evtStr = if ($evtNames.Count -gt 0) { " {$($evtNames -join ', ')}" } else { "" }
- $script:opLog += " + [$($node.LocalName)] $name$pathStr$evtStr → $($pos.Desc)"
- $script:addedCount++
- }
- # --- Командная панель формы (autoCmdBar, как в form-compile) ---
- # Кнопки из children — в командную панель формы (в конец, по порядку); autofill и horizontalAlign — её свойства.
- function Invoke-AutoCmdBar($op, [int]$idx) {
- $ctx = "elements[$idx] autoCmdBar"
- $acbNode = $root.SelectSingleNode("f:AutoCommandBar", $nsMgr)
- if ($null -eq $acbNode) { Fail "${ctx}: у формы нет командной панели" }
- Assert-OpKeys $op @('autoCmdBar','children','autofill','horizontalAlign') $ctx
- if ($null -ne $op.PSObject.Properties['autofill']) {
- if ($null -eq $op.autofill) { Fail "${ctx}: autofill — true или false" }
- $af = (ConvertTo-DslBool $op.autofill "${ctx}: autofill" $false)
- Set-ValueTag $acbNode 'Autofill' $(if ($af) { 'true' } else { 'false' })
- $script:opLog += " * $($acbNode.GetAttribute('name')): autofill=$(if ($af) { 'true' } else { 'false' }) → Autofill"
- $script:changedCount++
- }
- if ($op.horizontalAlign) {
- Set-SimpleTag $acbNode 'HorizontalAlign' "$($op.horizontalAlign)"
- $script:opLog += " * $($acbNode.GetAttribute('name')): horizontalAlign=$($op.horizontalAlign) → HorizontalAlign"
- $script:changedCount++
- }
- foreach ($child in @($op.children)) {
- if ($null -eq $child) { continue }
- if (-not ($child -is [System.Management.Automation.PSCustomObject])) { Fail "${ctx}: в children — не элемент (нужна кнопка, группа кнопок или подменю)" }
- foreach ($pk in @('into','after','before','first')) {
- if ($null -ne $child.PSObject.Properties[$pk]) { Fail "${ctx}: у кнопок в children нет позиции — они встают в конец панели по порядку; для места укажите кнопку отдельным элементом с into и after/before" }
- }
- Normalize-ElementTypeSynonyms $child
- $tk = $null
- foreach ($k in $elemTypeKeys) { if ($null -ne $child.PSObject.Properties[$k]) { $tk = $k; break } }
- if ($null -eq $tk) { Fail "${ctx}: в children — не элемент (нужна кнопка, группа кнопок или подменю)" }
- $c = $child | Select-Object -Property *
- $c | Add-Member -NotePropertyName 'into' -NotePropertyValue $acbNode.GetAttribute('name') -Force
- Invoke-Add $c $tk $idx
- }
- }
- # --- Перенос ---
- function Invoke-Move($op, [int]$idx) {
- $ctx = "elements[$idx] move"
- Assert-OpKeys $op @('move','after','before','into','first') $ctx
- $names = @(@($op.move) | ForEach-Object { "$_" } | Where-Object { $_ })
- if ($names.Count -eq 0) { Fail "${ctx}: укажи имя элемента или список имён" }
- $nodes = @()
- $seen = @{}
- foreach ($n in $names) {
- if ($seen.ContainsKey($n)) { Fail "${ctx}: '$n' указан дважды" }
- $seen[$n] = $true
- $node = Find-FormElement $n
- if ($null -eq $node) { Fail "${ctx}: элемент '$n' не найден в форме" }
- if ($node.ParentNode.LocalName -ne 'ChildItems' -or $script:companionTags -contains $node.LocalName) {
- Fail "${ctx}: '$n' — служебный узел ($($node.LocalName)) своего элемента, переносится только вместе с ним"
- }
- $nodes += $node
- }
- $pos = Resolve-Position $op $ctx $true
- foreach ($node in $nodes) {
- if (Same $node $pos.Anchor) { Fail "${ctx}: '$($node.GetAttribute('name'))' не может быть якорем собственного переноса" }
- Assert-Placement $node.LocalName $node.GetAttribute('name') $node $pos.Container $ctx
- }
- $ref = $pos.Ref
- $desc = $pos.Desc
- $prev = $null
- foreach ($node in $nodes) {
- $name = $node.GetAttribute('name')
- if ($null -ne $prev) {
- $ref = Get-NextElementSibling $prev
- $desc = "$(Get-ContainerLabel $pos.Container), после $($prev.GetAttribute('name'))"
- }
- $fromCI = $node.ParentNode
- $targetCI = $pos.Container.SelectSingleNode("f:ChildItems", $nsMgr)
- if ((Same $fromCI $targetCI) -and ((Same $ref $node) -or (Same $ref (Get-NextElementSibling $node)))) {
- $script:opLog += " = ${name}: уже на месте ($desc)"
- $prev = $node
- continue
- }
- $fromLabel = Get-ContainerLabel $fromCI.ParentNode
- # Отступ цели — до отцепления: если узел был в ней единственным, после отцепления
- # первым пробельным узлом окажется закрывающий с отступом родителя.
- $newIndent = if ($null -ne $targetCI) { Get-ChildIndent $targetCI } else { $null }
- $oldIndent = Get-NodeIndent $node
- Remove-NodeWithWs $node
- $ci = Get-OrCreateChildItems $pos.Container
- if ($null -eq $newIndent) { $newIndent = Get-ChildIndent $ci }
- Insert-NodeAt $ci $node $ref $newIndent
- Set-SubtreeIndent $node $oldIndent $newIndent
- if (-not (Same $fromCI $ci)) { Remove-IfEmptyChildItems $fromCI }
- $script:opLog += " ~ ${name}: $fromLabel → $desc"
- $script:movedCount++
- $prev = $node
- }
- }
- # --- Изменение свойств ---
- # Умолчания платформы: в корпусе эти теги встречаются только с противоположным значением —
- # значение по умолчанию платформа не пишет, и set его не пишет, а убирает тег.
- $script:tagDefaults = @{
- 'Visible'='true'; 'Enabled'='true'; 'ReadOnly'='false'; 'ShowTitle'='true'; 'United'='true'; 'Collapsed'='false'
- 'AutoMaxWidth'='true'; 'AutoMaxHeight'='true'; 'Hyperlink'='false'; 'Hiperlink'='false'
- }
- # Умолчания перечислений зависят от типа элемента: значение из области, которого в корпусе нет ни
- # разу у этого типа (у таблицы TitleLocation=Auto пишется явно — там правило не действует).
- $script:enumDefaults = @{
- 'UsualGroup/Group'='HorizontalIfPossible'; 'Page/Group'='Vertical'; 'ColumnGroup/Group'='Vertical'
- 'UsualGroup/Representation'='WeakSeparation'; 'Button/Representation'='Auto'; 'Popup/Representation'='Auto'
- 'AutoCommandBar/Autofill'='true'
- }
- function Get-TagDefault([string]$nt, [string]$tag) {
- if ($script:tagDefaults.ContainsKey($tag)) { return $script:tagDefaults[$tag] }
- if ($script:enumDefaults.ContainsKey("$nt/$tag")) { return $script:enumDefaults["$nt/$tag"] }
- if ($script:enumDefaultValues.ContainsKey("$nt.$tag")) { return $script:enumDefaultValues["$nt.$tag"] }
- if ($tag -eq 'TitleLocation' -and $nt -ne 'Table') { return 'Auto' }
- return $null
- }
- # Значение по умолчанию платформа не пишет — и set его не пишет, а убирает тег.
- # Значение перечисления — к виду платформы (как эмиттер: Normalize-EnumValue по типу элемента)
- function Get-NormalizedEnumValue($node, [string]$tag, [string]$text) {
- if (-not $text -or -not $script:enumScopeTypes.ContainsKey($node.LocalName)) { return $text }
- $script:objType = $node.LocalName
- return (Normalize-EnumValue $tag (Resolve-EnumInputSynonym $node.LocalName $tag $text))
- }
- function Set-ValueTag($node, [string]$tag, [string]$text) {
- $text = Get-NormalizedEnumValue $node $tag $text
- if ((Get-TagDefault $node.LocalName $tag) -ceq $text) {
- $existing = $node.SelectSingleNode("f:$tag", $nsMgr)
- if ($null -ne $existing) { Remove-NodeWithWs $existing }
- return
- }
- Set-SimpleTag $node $tag $text
- }
- $script:titleLocMap = @{ 'none'='None'; 'left'='Left'; 'right'='Right'; 'top'='Top'; 'bottom'='Bottom'; 'auto'='Auto' }
- # Ключи — словарь form-compile; Tags — кандидаты по типу элемента (у LabelField платформа пишет Hiperlink).
- $script:setProps = [ordered]@{
- 'title'=@{ Tags=@('Title'); Kind='ml' }
- 'tooltip'=@{ Tags=@('ToolTip'); Kind='ml' }
- 'inputHint'=@{ Tags=@('InputHint'); Kind='ml' }
- 'visible'=@{ Tags=@('Visible'); Kind='bool' }
- 'hidden'=@{ Tags=@('Visible'); Kind='bool'; Invert=$true }
- 'enabled'=@{ Tags=@('Enabled'); Kind='bool' }
- 'disabled'=@{ Tags=@('Enabled'); Kind='bool'; Invert=$true }
- 'readOnly'=@{ Tags=@('ReadOnly'); Kind='bool' }
- 'skipOnInput'=@{ Tags=@('SkipOnInput'); Kind='bool' }
- 'titleLocation'=@{ Tags=@('TitleLocation'); Kind='enum'; Map=$script:titleLocMap }
- 'width'=@{ Tags=@('Width'); Kind='num' }
- 'height'=@{ Tags=@('HeightInTableRows','Height'); Kind='num' }
- 'maxWidth'=@{ Tags=@('MaxWidth'); Kind='num' }
- 'maxHeight'=@{ Tags=@('MaxHeight'); Kind='num' }
- 'autoMaxWidth'=@{ Tags=@('AutoMaxWidth'); Kind='bool' }
- 'autoMaxHeight'=@{ Tags=@('AutoMaxHeight'); Kind='bool' }
- 'horizontalStretch'=@{ Tags=@('HorizontalStretch'); Kind='bool' }
- 'verticalStretch'=@{ Tags=@('VerticalStretch'); Kind='bool' }
- 'multiLine'=@{ Tags=@('MultiLine'); Kind='bool' }
- 'passwordMode'=@{ Tags=@('PasswordMode'); Kind='bool' }
- 'choiceButton'=@{ Tags=@('ChoiceButton'); Kind='bool' }
- 'clearButton'=@{ Tags=@('ClearButton'); Kind='bool' }
- 'spinButton'=@{ Tags=@('SpinButton'); Kind='bool' }
- 'dropListButton'=@{ Tags=@('DropListButton'); Kind='bool' }
- 'markIncomplete'=@{ Tags=@('AutoMarkIncomplete'); Kind='bool' }
- 'hyperlink'=@{ Tags=@('Hyperlink','Hiperlink'); Kind='bool' }
- 'group'=@{ Tags=@('Group'); Kind='enum'; Map=@{ 'vertical'='Vertical'; 'horizontal'='Horizontal'; 'horizontalifpossible'='HorizontalIfPossible'; 'alwayshorizontal'='AlwaysHorizontal'; 'alwaysvertical'='Vertical'; 'incell'='InCell' } }
- 'behavior'=@{ Tags=@('Behavior'); Kind='enum'; Map=@{ 'usual'='Usual'; 'collapsible'='Collapsible'; 'popup'='PopUp' } }
- 'collapsed'=@{ Tags=@('Collapsed'); Kind='bool' }
- 'representation'=@{ Tags=@('Representation'); Kind='repr' }
- 'showTitle'=@{ Tags=@('ShowTitle'); Kind='bool' }
- 'united'=@{ Tags=@('United'); Kind='bool' }
- }
- # Значения Representation — свои у каждого типа (по корпусу); ключи — как в form-compile.
- $script:reprMaps = @{
- 'UsualGroup' = @{ 'none'='None'; 'normal'='NormalSeparation'; 'weak'='WeakSeparation'; 'strong'='StrongSeparation' }
- 'Table' = @{ 'list'='List'; 'tree'='Tree'; 'hierarchicallist'='HierarchicalList' }
- 'Button' = @{ 'auto'='Auto'; 'text'='Text'; 'picture'='Picture'; 'pictureandtext'='PictureAndText' }
- 'Popup' = @{ 'auto'='Auto'; 'text'='Text'; 'picture'='Picture'; 'pictureandtext'='PictureAndText' }
- 'ButtonGroup' = @{ 'auto'='Auto'; 'usual'='Usual'; 'compact'='Compact' }
- }
- $script:xmlTagToDsl = @{}
- foreach ($k in $script:dslTagMap.Keys) { $script:xmlTagToDsl[$script:dslTagMap[$k]] = $k }
- function Get-PropTag($spec, [string]$nt) {
- foreach ($t in $spec.Tags) { if ((Get-ChildRank $nt $t) -ge 0) { return $t } }
- return $null
- }
- function Get-ApplicableSetKeys([string]$nt) {
- $keys = @()
- foreach ($k in $script:setProps.Keys) {
- if ($k -in @('hidden','disabled')) { continue }
- if ($null -ne (Get-PropTag $script:setProps[$k] $nt)) { $keys += $k }
- }
- if ((Get-ChildRank $nt 'Events') -ge 0) { $keys += 'on' }
- return $keys
- }
- function Set-SimpleTag($node, [string]$tag, [string]$text) {
- $text = Get-NormalizedEnumValue $node $tag $text
- $existing = $node.SelectSingleNode("f:$tag", $nsMgr)
- if ($null -ne $existing) { $existing.InnerText = $text; return }
- $el = $xmlDoc.CreateElement($tag, $formNs)
- $el.InnerText = $text
- Insert-ChildCanonical $node $el
- }
- function Set-MLTag($node, [string]$tag, $value) {
- $indent = Get-ChildIndent $node
- $script:xml = New-Object System.Text.StringBuilder 512
- X "<_F $allNsDecl>"
- X "$indent<$tag>"
- if ($value -is [string]) {
- # Строка меняет только русский текст: переводы на другие языки остаются как были
- $items = @()
- $prevEl = $node.SelectSingleNode("f:$tag", $nsMgr)
- $hasRu = $false
- if ($null -ne $prevEl) {
- foreach ($it in $prevEl.SelectNodes("v8:item", $nsMgr)) {
- $lang = $it.SelectSingleNode("v8:lang", $nsMgr).InnerText
- if ($lang -eq 'ru') { $items += @{ Lang = 'ru'; Text = $value }; $hasRu = $true }
- else { $items += @{ Lang = $lang; Text = $it.SelectSingleNode("v8:content", $nsMgr).InnerText } }
- }
- }
- if (-not $hasRu) { $items = @(@{ Lang = 'ru'; Text = $value }) + $items }
- } else {
- $items = @($value.PSObject.Properties | ForEach-Object { @{ Lang = $_.Name; Text = "$($_.Value)" } })
- }
- foreach ($it in $items) {
- X "$indent`t<v8:item>"
- X "$indent`t`t<v8:lang>$($it.Lang)</v8:lang>"
- X "$indent`t`t<v8:content>$(Esc-XmlText $it.Text)</v8:content>"
- X "$indent`t</v8:item>"
- }
- X "$indent</$tag>"
- X "</_F>"
- $newEl = @(Import-ElementNodes (Parse-Fragment $script:xml.ToString()))[0]
- $existing = $node.SelectSingleNode("f:$tag", $nsMgr)
- if ($null -ne $existing) {
- # Атрибуты узла (formatted у заголовка надписи) переживают замену текста
- foreach ($a in @($existing.Attributes)) { $newEl.SetAttribute($a.LocalName, $a.Value) }
- $node.ReplaceChild($newEl, $existing) | Out-Null
- return
- }
- if ($tag -eq 'Title' -and $node.LocalName -eq 'LabelDecoration') { $newEl.SetAttribute('formatted', 'false') }
- Insert-ChildCanonical $node $newEl
- }
- # Узел, перед которым встаёт новое событие: первое существующее с большей позицией (Get-EventRank);
- # $null — в конец. Существующие события не переставляются.
- function Get-EventInsertRef($eventsNode, [string]$xmlTag, [string]$name, [string]$callType) {
- $r = Get-EventRank $xmlTag $name $callType
- foreach ($e in $eventsNode.SelectNodes("f:Event", $nsMgr)) {
- if ((Get-EventRank $xmlTag $e.GetAttribute('name') $e.GetAttribute('callType')) -gt $r) { return $e }
- }
- return $null
- }
- function Add-ElementEvents($node, $on, $handlers, [string]$ctx) {
- $nt = $node.LocalName
- $name = $node.GetAttribute('name')
- if ((Get-ChildRank $nt 'Events') -lt 0) { Fail "${ctx}: у $nt '$name' событий нет" }
- $source = ''
- if ($nt -eq 'Table') {
- $dp = $node.SelectSingleNode("f:DataPath", $nsMgr)
- if ($null -ne $dp) { $source = Get-DataPathSource $dp.InnerText }
- }
- $events = $node.SelectSingleNode("f:Events", $nsMgr)
- foreach ($evt in @($on)) {
- if (-not ($evt -is [System.Management.Automation.PSCustomObject])) {
- $evtName = "$evt"; $callType = ""; $handler = ""
- } else {
- $evtName = "$($evt.event)"; $callType = Normalize-CallType "$($evt.callType)" $name $evtName
- $handler = if ($evt.handler) { "$($evt.handler)" } else { "" }
- }
- $evtName = Resolve-EventName $nt $evtName "$ctx events"
- # В форме расширения обработчик без callType платформа читает как Before и так и пишет
- if (-not $callType -and $script:isExtension) { $callType = 'Before' }
- if (-not $handler) { $handler = if ($handlers -and $handlers.$evtName) { "$($handlers.$evtName)" } else { Get-HandlerName -elementName $name -eventName $evtName -xmlTag $nt -callType $callType } }
- Test-EventPairs -pairs @([pscustomobject]@{ name = $evtName }) -xmlTag $nt -elementName $name -source $source
- $tbl = Get-NearestTable $node $true
- Register-Handler $handler 'element' $nt $evtName $(if ($null -ne $tbl) { $tbl.GetAttribute('name') } else { '' })
- $ctStr = if ($callType) { "[$callType]" } else { "" }
- if ($null -ne $events) {
- $dup = $null
- foreach ($e in $events.SelectNodes("f:Event", $nsMgr)) {
- if ($e.GetAttribute('name') -eq $evtName -and $e.GetAttribute('callType') -eq $callType) { $dup = $e; break }
- }
- if ($null -ne $dup) {
- $old = $dup.InnerText
- if ($old -eq $handler) { $script:opLog += " = ${name}: event $evtName$ctStr -> $handler already bound"; continue }
- # Другое имя — замена: у события один обработчик (на вид вызова)
- $dup.InnerText = $handler
- Add-UnboundHandlers @($old)
- $script:opLog += " ~ ${name}: event $evtName${ctStr}: $old -> $handler"
- $script:changedCount++
- continue
- }
- }
- if ($null -eq $events) {
- $events = $xmlDoc.CreateElement("Events", $formNs)
- Insert-ChildCanonical $node $events
- }
- $ev = $xmlDoc.CreateElement("Event", $formNs)
- $ev.SetAttribute('name', $evtName)
- if ($callType) { $ev.SetAttribute('callType', $callType) }
- $ev.InnerText = $handler
- Insert-NodeAt $events $ev (Get-EventInsertRef $events $nt $evtName $callType) (Get-ChildIndent $events)
- $script:opLog += " * ${name}: event $evtName$ctStr -> $handler"
- $script:changedCount++
- }
- }
- function Invoke-Set($op, [int]$idx) {
- $ctx = "elements[$idx] set"
- $names = @(@($op.set) | ForEach-Object { "$_" } | Where-Object { $_ })
- if ($names.Count -eq 0) { Fail "${ctx}: укажи имя элемента или список имён" }
- $props = @($op.PSObject.Properties | Where-Object { $_.Name -ne 'set' })
- if ($props.Count -eq 0) { Fail "${ctx}: не указано, что менять" }
- $forbidden = @('name','path','children','columns')
- foreach ($n in $names) {
- $node = Find-FormElement $n
- if ($null -eq $node) { Fail "${ctx}: элемент '$n' не найден в форме" }
- $nt = $node.LocalName
- $c = "$ctx '$n'"
- $probeProps = [ordered]@{}
- foreach ($p in $props) {
- $key = $p.Name
- if ($key -eq 'handlers') { if (-not $op.on) { Fail "${c}: handlers задаются вместе с on" }; continue }
- if ($key -eq 'on') { Add-ElementEvents $node $p.Value $op.handlers $c; continue }
- if ($key -eq 'events') {
- # Список — имена по конвенции (в расширении вид вызова по умолчанию Before — его ставит Add-ElementEvents)
- if ($p.Value -is [array]) { Add-ElementEvents $node $p.Value $null $c; continue }
- if (-not ($p.Value -is [System.Management.Automation.PSCustomObject])) { Fail "${c}: events — объект { Событие: обработчик } или список событий" }
- # Объект: имя — повесить или заменить, null — снять (без callType — все привязки события)
- $on = @()
- foreach ($e in $p.Value.PSObject.Properties) {
- $evName = Resolve-EventName $nt $e.Name "$c events"
- if (@($e.Value).Count -eq 0) { Fail "${c}: событие $evName — пустой список; чтобы снять обработчик, укажите null" }
- foreach ($v in @($e.Value)) {
- $isObj = $v -is [System.Management.Automation.PSCustomObject]
- $h = if ($isObj) { "$($v.handler)" } else { "$v" }
- $ct = if ($isObj) { Normalize-CallType "$($v.callType)" $n $evName } else { '' }
- if ($h) { $on += [pscustomobject]@{ event = $evName; handler = $h; callType = $ct }; continue }
- $ctStr = if ($ct) { "[$ct]" } else { "" }
- $hits = Remove-EventBindings $node $evName $ct
- if ($hits.Count -eq 0) { Fail "${c}: событие $evName$ctStr у '$n' не обрабатывается — снимать нечего" }
- foreach ($x in $hits) {
- $xc = $x.GetAttribute('callType'); $xcStr = if ($xc) { "[$xc]" } else { "" }
- $script:opLog += " - ${n}: event $evName$xcStr -> $($x.InnerText)"
- $script:changedCount++
- }
- Add-UnboundHandlers @($hits | ForEach-Object { $_.InnerText })
- }
- }
- if ($on.Count -gt 0) { Add-ElementEvents $node $on $null $c }
- continue
- }
- if ($forbidden -contains $key -or ($key -eq $script:xmlTagToDsl[$nt] -and $key -ne 'group')) {
- Fail "${c}: '$key' через set не меняется (имя и привязку не трогаем — на них ссылаются модуль и расширения; состав — через move)"
- }
- if (@('into','after','before','first') -contains $key) { Fail "${c}: '$key' — место элемента меняет move, не set" }
- if (-not $script:setProps.Contains($key)) {
- # Остальные ключи элемента — как в form-compile, через общий эмиттер
- $probeProps[$key] = $p.Value
- continue
- }
- $spec = $script:setProps[$key]
- $tag = Get-PropTag $spec $nt
- if ($null -eq $tag) { Fail "${c}: свойство '$key' к $nt не применимо; доступно: $((Get-ApplicableSetKeys $nt) -join ', ') и остальные ключи элемента из form-compile" }
- $v = $p.Value
- if ($null -eq $v) {
- $existing = $node.SelectSingleNode("f:$tag", $nsMgr)
- if ($null -ne $existing) { Remove-NodeWithWs $existing }
- $script:opLog += " * ${n}: $key сброшено"
- $script:changedCount++
- continue
- }
- switch ($spec.Kind) {
- 'ml' {
- $mlOk = ($v -is [string]) -or (($v -is [System.Management.Automation.PSCustomObject]) -and @($v.PSObject.Properties).Count -gt 0 -and -not (@($v.PSObject.Properties) | Where-Object { -not ($_.Value -is [string]) }))
- if (-not $mlOk) { Fail "${c}: $key — строка или объект {ru, en, ...} со строковыми значениями" }
- Set-MLTag $node $tag $v
- $shown = if ($v -is [string]) { $v } else { ($v.PSObject.Properties | ForEach-Object { "$($_.Name):$($_.Value)" }) -join ' ' }
- $script:opLog += " * ${n}: $key=`"$shown`" → $tag"
- }
- 'bool' {
- $v = ConvertTo-DslBool $v "${c}: $key" $false
- if ($spec.Invert) { $v = -not $v }
- $text = if ($v) { 'true' } else { 'false' }
- Set-ValueTag $node $tag $text
- $script:opLog += " * ${n}: $key=$("$($p.Value)".ToLower()) → $tag=$text"
- }
- 'num' {
- if (-not ($v -is [int] -or $v -is [long]) -or $v -lt 0) { Fail "${c}: $key — целое неотрицательное число" }
- Set-SimpleTag $node $tag "$v"
- $script:opLog += " * ${n}: $key=$v → $tag=$v"
- }
- 'enum' {
- $mapped = $spec.Map["$v".ToLower()]
- if (-not $mapped) { Fail "${c}: $key='$v' — допустимо: $(($spec.Map.Keys | Sort-Object) -join ', ')" }
- Set-ValueTag $node $tag $mapped
- $script:opLog += " * ${n}: $key=$v → $tag=$mapped"
- }
- 'repr' {
- $rmap = $script:reprMaps[$nt]
- if ($null -eq $rmap) { Fail "${c}: свойство '$key' к $nt не применимо; доступно: $((Get-ApplicableSetKeys $nt) -join ', ') и остальные ключи элемента из form-compile" }
- $text = $rmap[(Resolve-EnumInputSynonym $nt 'Representation' "$v").ToLower()]
- if (-not $text) { Fail "${c}: representation='$v' — допустимо: $(($rmap.Keys | Sort-Object) -join ', ')" }
- Set-ValueTag $node $tag $text
- $script:opLog += " * ${n}: $key=$v → $tag=$text"
- }
- }
- $script:changedCount++
- }
- if ($probeProps.Count -gt 0) {
- # Контекст пробы — все свойства операции: от них зависит, как эмиттер пишет остальные
- $context = [ordered]@{}
- foreach ($p in $props) {
- if (@('on','handlers','events') -notcontains $p.Name -and $null -ne $p.Value -and -not $probeProps.Contains($p.Name)) { $context[$p.Name] = $p.Value }
- }
- Invoke-SetByEmitter $node $probeProps $context $op $c
- }
- }
- }
- # --- set: ключи элемента вне таблицы выше — через общий эмиттер form-compile ---
- # Элемент эмитится без свойства и с ним; что различается, то свойство и пишет в XML. Так set знает
- # все ключи form-compile и пишет их ровно так же, как при создании формы.
- $script:probeTypeValues = @{ 'group'='vertical'; 'columnGroup'='vertical' }
- function Invoke-SetProbe($node, $props) {
- $nt = $node.LocalName
- $dsl = $script:xmlTagToDsl[$nt]
- $name = $node.GetAttribute('name')
- $h = [ordered]@{}
- $h[$dsl] = if ($script:probeTypeValues.ContainsKey($dsl)) { $script:probeTypeValues[$dsl] } else { $name }
- $h['name'] = $name
- $dp = $node.SelectSingleNode("f:DataPath", $nsMgr)
- if ($null -ne $dp) { $h['path'] = $dp.InnerText }
- foreach ($k in $props.Keys) { $h[$k] = $props[$k] }
- $el = ConvertFrom-JsonInput ([pscustomobject]$h | ConvertTo-Json -Depth 100 -Compress) 'element from XML'
- Normalize-ElementSynonyms $el
- foreach ($a in $root.SelectNodes("f:Attributes/f:Attribute", $nsMgr)) {
- $t = $a.SelectSingleNode("f:Type/v8:Type", $nsMgr)
- if ($null -ne $t -and $t.InnerText.Trim() -eq 'cfg:DynamicList') { ApplyDynamicListTableHeuristic $el $a.GetAttribute('name') $true (Test-DynListExplicitKey $a) }
- }
- $saveId = $script:nextElemId
- $script:seenElementNames = @{}
- $tbl = Get-NearestTable $node $false
- $script:currentTableName = if ($null -ne $tbl) { $tbl.GetAttribute('name') } else { $null }
- $inBar = $false
- $cur = $node.ParentNode
- while ($null -ne $cur -and $cur.NodeType -eq 'Element') {
- if ($script:barTags -contains $cur.LocalName) { $inBar = $true; break }
- $cur = $cur.ParentNode
- }
- $script:xml = New-Object System.Text.StringBuilder 4096
- X "<_F $allNsDecl>"
- $msgs = @(& { Emit-Element -el $el -indent (Get-NodeIndent $node) -inCmdBar $inBar } 3>&1 6>&1 |
- Where-Object { $_ -is [System.Management.Automation.WarningRecord] -or $_ -is [System.Management.Automation.InformationRecord] } |
- ForEach-Object { "$_" })
- X "</_F>"
- $script:nextElemId = $saveId
- $frag = Parse-Fragment (Sort-ElementTagOrder (Normalize-EnumTags $script:xml.ToString() '' $true))
- $pe = $null
- foreach ($ch in $frag.DocumentElement.ChildNodes) { if ($ch.NodeType -eq 'Element') { $pe = $ch; break } }
- return @{ El = $pe; Messages = $msgs }
- }
- # Свойства узла: дочерние теги (без состава и событий) и атрибуты; спутники (меню, подсказка,
- # панель) — отдельно, их свойства сравниваются так же.
- function Get-ProbeParts($e) {
- $tags = [ordered]@{}; $comps = @{}; $attrs = @{}
- foreach ($ch in $e.ChildNodes) {
- if ($ch.NodeType -ne 'Element') { continue }
- $ln = $ch.LocalName
- if ($ln -eq 'Events') { continue }
- if ($ln -eq 'ChildItems') { $comps['#items'] = ($ch.OuterXml -replace ' id="-?\d+"', '') -replace '\s+', ' '; continue }
- if ($script:companionTags -contains $ln -and $ch.HasAttribute('name')) { $comps[$ln] = $ch; continue }
- $t = ($ch.OuterXml -replace ' id="-?\d+"', '') -replace '\s+', ' '
- if ($tags.Contains($ln)) { $tags[$ln] += $t } else { $tags[$ln] = $t }
- }
- foreach ($a in $e.Attributes) {
- if ($a.Name -ne 'name' -and $a.Name -ne 'id' -and -not $a.Name.StartsWith('xmlns')) { $attrs[$a.Name] = $a.Value }
- }
- return @{ Tags = $tags; Comps = $comps; Attrs = $attrs }
- }
- function Get-ProbeDiff($b, $p) {
- $pb = Get-ProbeParts $b; $pp = Get-ProbeParts $p
- $d = @{ Tags = @(); Attrs = @(); Comps = @(); Items = $false }
- foreach ($t in @($pb.Tags.Keys) + @($pp.Tags.Keys) | Select-Object -Unique) {
- if ($pb.Tags[$t] -cne $pp.Tags[$t]) { $d.Tags += $t }
- }
- foreach ($a in @($pb.Attrs.Keys) + @($pp.Attrs.Keys) | Sort-Object -Unique) {
- if ($pb.Attrs[$a] -cne $pp.Attrs[$a]) { $d.Attrs += $a }
- }
- if ($pb.Comps['#items'] -cne $pp.Comps['#items']) { $d.Items = $true }
- foreach ($cn in @($pp.Comps.Keys | Where-Object { $_ -ne '#items' } | Sort-Object)) {
- if ($null -eq $pb.Comps[$cn]) { continue }
- $sub = Get-ProbeDiff $pb.Comps[$cn] $pp.Comps[$cn]
- # Состав спутника (кнопки меню, панели) — тоже состав
- if ($sub.Items) { $d.Items = $true }
- if (Test-ProbeDiff $sub) { $d.Comps += @{ Tag = $cn; Diff = $sub } }
- }
- return $d
- }
- function Test-ProbeDiff($d) {
- return ($d.Tags.Count + $d.Attrs.Count + $d.Comps.Count) -gt 0 -or $d.Items
- }
- # Есть ли в узле хоть что-то из того, что описывает разница (для сброса к умолчанию).
- function Test-ProbeDiffPresent($target, $d) {
- foreach ($t in $d.Tags) { if ($null -ne $target.SelectSingleNode("f:$t", $nsMgr)) { return $true } }
- foreach ($a in $d.Attrs) { if ($target.HasAttribute($a)) { return $true } }
- foreach ($cd in $d.Comps) {
- $tc = $target.SelectSingleNode("f:$($cd.Tag)", $nsMgr)
- if ($null -ne $tc -and (Test-ProbeDiffPresent $tc $cd.Diff)) { return $true }
- }
- return $false
- }
- function Get-ProbeDiffLabel($d) {
- $parts = @($d.Tags) + @($d.Attrs | ForEach-Object { "@$_" })
- foreach ($cd in $d.Comps) { $parts += @(Get-ProbeDiffLabel $cd.Diff | ForEach-Object { "$($cd.Tag)/$_" }) }
- return $parts
- }
- # Перенести в узел то, что различается: теги пробы заменяют свои (нет в пробе — тег убирается).
- function Apply-ProbeDiff($target, $probeEl, $d, [bool]$removeOnly) {
- foreach ($t in $d.Tags) {
- foreach ($x in @($target.SelectNodes("f:$t", $nsMgr))) { Remove-NodeWithWs $x }
- if ($removeOnly) { continue }
- foreach ($pn in @($probeEl.SelectNodes("f:$t", $nsMgr))) {
- $imp = $xmlDoc.ImportNode($pn, $true)
- if ((Get-ChildRank $target.LocalName $t) -ge 0) { Insert-ChildCanonical $target $imp; continue }
- # Тега нет в корпусном порядке — встаёт перед первым следующим за ним в пробе тегом узла
- $ref = $null
- $sib = $pn.NextSibling
- while ($null -ne $sib -and $null -eq $ref) {
- if ($sib.NodeType -eq 'Element') { $ref = $target.SelectSingleNode("f:$($sib.LocalName)", $nsMgr) }
- $sib = $sib.NextSibling
- }
- Insert-NodeAt $target $imp $ref (Get-ChildIndent $target)
- }
- }
- foreach ($a in $d.Attrs) {
- if (-not $removeOnly -and $probeEl.HasAttribute($a)) { $target.SetAttribute($a, $probeEl.GetAttribute($a)) }
- else { $target.RemoveAttribute($a) }
- }
- foreach ($cd in $d.Comps) {
- $tc = $target.SelectSingleNode("f:$($cd.Tag)", $nsMgr)
- $pc = if ($null -ne $probeEl) { $probeEl.SelectSingleNode("f:$($cd.Tag)", $nsMgr) } else { $null }
- if ($null -ne $tc) { Apply-ProbeDiff $tc $pc $cd.Diff $removeOnly }
- elseif (-not $removeOnly) { Fail "у '$($target.GetAttribute('name'))' нет $($cd.Tag) — свойство некуда записать" }
- }
- }
- function Get-ProbeOwnerTags([string]$key) {
- foreach ($g in $script:genericScalars) { if ($g.Key -eq $key) { return @($g.Tag) } }
- if ($script:appearanceSpec.ContainsKey($key)) { return @($script:appearanceSpec[$key].tag) }
- return @()
- }
- # Теги, которые set через эмиттер не трогает: привязка и тип. Теги ручной таблицы (Title, ToolTip…)
- # проба переписывает, только если их ключ задан в той же операции, — иначе эмиттер, не зная их
- # значения, затёр бы его своим.
- $script:probeLockedTags = @('DataPath','CommandName','Type')
- function Assert-ProbeTags($d, [string]$k, $op, [string]$c) {
- foreach ($t in $d.Tags) {
- if ($script:probeLockedTags -contains $t) { Fail "${c}: '$k' меняет $t — привязка и тип элемента через set не меняются" }
- }
- foreach ($t in $d.Tags) {
- $owners = @($script:setProps.Keys | Where-Object { $script:setProps[$_].Tags -contains $t })
- if ($owners.Count -gt 0 -and -not ($owners | Where-Object { $null -ne $op.PSObject.Properties[$_] })) {
- Fail "${c}: '$k' меняет и $t — укажите в той же операции $($owners -join ' или ')"
- }
- }
- }
- function Invoke-SetByEmitter($node, $props, $context, $op, [string]$c) {
- $n = $node.GetAttribute('name')
- $nt = $node.LocalName
- if (-not $script:xmlTagToDsl.ContainsKey($nt)) { Fail "${c}: у $nt меняются только: $((Get-ApplicableSetKeys $nt) -join ', ')" }
- $set = [ordered]@{}
- foreach ($k in $context.Keys) { $set[$k] = $context[$k] }
- foreach ($k in $props.Keys) { if ($null -ne $props[$k]) { $set[$k] = $props[$k] } }
- $full = Invoke-SetProbe $node $set
- if ($full.El.LocalName -ne $nt) {
- $tk = @($props.Keys | Where-Object { $script:dslTagMap.ContainsKey($_) })
- Fail "${c}: '$($tk -join ', ')' — ключ типа элемента; тип через set не меняется"
- }
- $removals = @()
- $applies = @()
- foreach ($k in $props.Keys) {
- $v = $props[$k]
- $rest = [ordered]@{}
- foreach ($k2 in $set.Keys) { if ($k2 -ne $k) { $rest[$k2] = $set[$k2] } }
- $without = Invoke-SetProbe $node $rest
- if ($null -eq $v) {
- # Сброс: убрать то, что ключ пишет при любом значении
- $owned = @(Get-ProbeOwnerTags $k)
- $d = @{ Tags = $owned; Attrs = @(); Comps = @(); Items = $false }
- if ($owned.Count -eq 0) {
- foreach ($alt in @($true, $false)) {
- $wa = [ordered]@{}; foreach ($k2 in $rest.Keys) { $wa[$k2] = $rest[$k2] }; $wa[$k] = $alt
- $pa = Invoke-SetProbe $node $wa
- if (@($pa.Messages | Where-Object { $_ -match "unknown key '" }).Count -gt 0) { break }
- $da = Get-ProbeDiff $without.El $pa.El
- if (Test-ProbeDiff $da) { $d = $da; break }
- }
- }
- if (-not (Test-ProbeDiff $d)) { Fail "${c}: '$k' сбросить нельзя — неизвестное свойство или у него нет значения по умолчанию; укажите значение" }
- Assert-ProbeTags $d $k $op $c
- if (Test-ProbeDiffPresent $node $d) {
- $removals += $d
- $script:opLog += " * ${n}: $k сброшено"
- $script:changedCount++
- } else {
- $script:opLog += " = ${n}: $k — уже по умолчанию"
- }
- continue
- }
- $d = Get-ProbeDiff $without.El $full.El
- if (Test-ProbeDiff $d) {
- if ($d.Items) { Fail "${c}: '$k' меняет состав '$n' — элементы добавляются отдельными операциями" }
- Assert-ProbeTags $d $k $op $c
- $applies += $d
- $shown = if ($v -is [bool]) { "=$("$v".ToLower())" } elseif ($v -is [string] -or $v -is [int] -or $v -is [long]) { "=$v" } else { "" }
- $script:opLog += " * ${n}: $k$shown → $((Get-ProbeDiffLabel $d) -join ', ')"
- $script:changedCount++
- continue
- }
- # Разницы нет: ключ неизвестен, значение не распознано или совпадает с умолчанием платформы
- $msgs = @($full.Messages)
- if (@($msgs | Where-Object { $_ -match "unknown key '$([regex]::Escape($k))'" }).Count -gt 0) {
- Fail "${c}: неизвестное свойство '$k' — ключи те же, что у элемента в form-compile"
- }
- $vv = @($msgs | ForEach-Object { if ($_ -match 'Valid values: (.*?)\. Value ignored') { $Matches[1] } })
- if ($vv.Count -gt 0) { Fail "${c}: $k='$v' — значение не распознано; допустимо: $($vv[0])" }
- if ($v -is [bool]) {
- $wa = [ordered]@{}; foreach ($k2 in $rest.Keys) { $wa[$k2] = $rest[$k2] }; $wa[$k] = -not $v
- $pa = Invoke-SetProbe $node $wa
- $da = Get-ProbeDiff $without.El $pa.El
- if (Test-ProbeDiff $da) {
- Assert-ProbeTags $da $k $op $c
- if (Test-ProbeDiffPresent $node $da) {
- $removals += $da
- $script:opLog += " * ${n}: $k=$("$v".ToLower()) — умолчание платформы, $((Get-ProbeDiffLabel $da) -join ', ') не пишется"
- $script:changedCount++
- } else {
- $script:opLog += " = ${n}: $k=$("$v".ToLower()) — уже по умолчанию"
- }
- continue
- }
- }
- Fail "${c}: '$k' к $nt не применимо или значение совпадает с умолчанием (чтобы вернуть умолчание — null)"
- }
- foreach ($r in $removals) { Apply-ProbeDiff $node $null $r $true }
- foreach ($a in $applies) { Apply-ProbeDiff $node $full.El $a $false }
- # Значение-умолчание платформа не пишет — перенесённый тег с ним убирается
- # (не $c: это параметр [string] функции — PS привёл бы к нему каждый узел цикла)
- foreach ($ch in @($node.ChildNodes)) {
- if ($ch.NodeType -ne 'Element' -or $ch.SelectSingleNode("*")) { continue }
- if ($script:enumDefaultValues.ContainsKey("$($node.LocalName).$($ch.LocalName)") -and $script:enumDefaultValues["$($node.LocalName).$($ch.LocalName)"] -ceq $ch.InnerText) { Remove-NodeWithWs $ch }
- }
- }
- # --- Удаление ---
- $dcsSetNs = "http://v8.1c.ru/8.1/data-composition-system/settings"
- $nsMgr.AddNamespace("dcsset", $dcsSetNs)
- $script:removeLog = @()
- $script:removedCount = 0
- $script:leftHandlers = @()
- $script:changeLog = @()
- $script:sectionChanged = 0
- $script:warnLog = @()
- $script:moduleOutline = $null
- $script:moduleScan = $null
- # Сканер BSL: строковые литералы (с "" и многострочными продолжениями «|») и комментарии // отделяются
- # от кода, номера строк сохраняются. Lines — строки текста; Code — они же без комментариев, литерал
- # заменён на ""; Mask — строки той же длины, литералы и комментарии — пробелами (позиции в маске —
- # позиции в тексте); Literals — @{ Line; Text; Prefix — код этой строки слева от литерала; Col — начало
- # текста литерала в строке, -1 у многострочного }.
- function Get-BslScan([string]$text) {
- $lines = $text -replace "`r", "" -split "`n"
- $code = New-Object System.Collections.ArrayList
- $mask = New-Object System.Collections.ArrayList
- $lits = New-Object System.Collections.ArrayList
- $inStr = $false; $cur = $null; $curLine = 0; $curPrefix = ""; $curCol = -1
- for ($i = 0; $i -lt $lines.Count; $i++) {
- $line = $lines[$i]
- # строка без кавычек вне литерала — только отрезать комментарий (посимвольный разбор в PS медленный)
- if (-not $inStr -and $line.IndexOf('"') -lt 0) {
- $k = $line.IndexOf('//')
- [void]$code.Add($(if ($k -ge 0) { $line.Substring(0, $k) } else { $line }))
- [void]$mask.Add($(if ($k -ge 0) { $line.Substring(0, $k) + (' ' * ($line.Length - $k)) } else { $line }))
- continue
- }
- $sb = New-Object System.Text.StringBuilder
- $mk = $line.ToCharArray()
- $j = 0
- if ($inStr) {
- # продолжение многострочного литерала: пробелы, затем «|»
- while ($j -lt $line.Length -and ($line[$j] -eq ' ' -or $line[$j] -eq "`t")) { $j++ }
- # строка «//…» между строками литерала — комментарий, литерал продолжается на следующей
- if ($j + 1 -lt $line.Length -and $line[$j] -eq '/' -and $line[$j + 1] -eq '/') { [void]$code.Add(""); [void]$mask.Add(' ' * $line.Length); continue }
- if ($j -lt $line.Length -and $line[$j] -eq '|') { $mk[$j] = ' '; $j++ }
- $cur += "`n"
- $curCol = -1
- }
- while ($j -lt $line.Length) {
- $c = $line[$j]
- if ($inStr) {
- if ($c -eq '"') {
- if ($j + 1 -lt $line.Length -and $line[$j + 1] -eq '"') { $cur += '"'; $mk[$j] = ' '; $mk[$j + 1] = ' '; $j += 2; continue }
- $inStr = $false
- [void]$lits.Add(@{ Line = $curLine; Text = $cur; Prefix = $curPrefix; Col = $curCol })
- [void]$sb.Append('""')
- $j++
- continue
- }
- $cur += $c; $mk[$j] = ' '; $j++; continue
- }
- if ($c -eq '/' -and $j + 1 -lt $line.Length -and $line[$j + 1] -eq '/') { for ($q = $j; $q -lt $mk.Length; $q++) { $mk[$q] = ' ' }; break }
- if ($c -eq '"') { $inStr = $true; $cur = ""; $curLine = $i + 1; $curPrefix = $sb.ToString(); $curCol = $j + 1; $j++; continue }
- [void]$sb.Append($c); $j++
- }
- [void]$code.Add($sb.ToString())
- [void]$mask.Add([string]::new($mk))
- }
- return @{ Lines = $lines; Code = $code.ToArray(); Mask = $mask.ToArray(); Literals = $lits.ToArray() }
- }
- # Модуль формы — рядом с Form.xml: <...>/Ext/Form/Module.bsl.
- function Get-ModuleScan {
- if ($null -ne $script:moduleScan) { return $script:moduleScan }
- $scan = @{ Exists = $false; Raw = ""; RawLines = @(); Lines = @(); Code = @(); Mask = @(); Literals = @() }
- $path = Join-Path ([System.IO.Path]::GetDirectoryName($resolvedFormPath)) "Form/Module.bsl"
- if (Test-Path -LiteralPath $path) {
- $scan.Exists = $true
- $scan.Raw = [System.IO.File]::ReadAllText($path)
- $scan.RawLines = $scan.Raw -split "`n"
- $bsl = Get-BslScan $scan.Raw
- $scan.Lines = $bsl.Lines
- $scan.Code = $bsl.Code
- $scan.Mask = $bsl.Mask
- $scan.Literals = $bsl.Literals
- }
- $script:moduleScan = $scan
- return $scan
- }
- # Где имя элемента/команды передают строкой: Найти("X"), ПолеКомпоновкиДанных("X"), ПутьКДанным = "X",
- # УстановитьСвойствоЭлементаФормы(Элементы, "X", …); реквизита — ещё РеквизитФормыВЗначение("X") и
- # ЗначениеВРеквизитФормы(…, "X").
- $script:itemLiteralContext = '((?<!\w)(Найти|Find|ПолеКомпоновкиДанных|DataCompositionField)\s*\(\s*|(?<!\w)(ПутьКДанным|DataPath)\s*=\s*|(?<!\w)(Элементы|Items)\s*,\s*)$'
- $script:attrLiteralContext = '((?<!\w)(ПолеКомпоновкиДанных|DataCompositionField|РеквизитФормыВЗначение|FormAttributeToValue)\s*\(\s*|(?<!\w)(ЗначениеВРеквизитФормы|ValueToFormAttribute)\s*\(.*,\s*|(?<!\w)(ПутьКДанным|DataPath)\s*=\s*)$'
- # Номера строк модуля, где есть ссылка на имя. Kind: element | command | attribute.
- function Find-ModuleRefs([string]$name, [string]$kind) {
- $scan = Get-ModuleScan
- $hits = New-Object System.Collections.Generic.SortedSet[int]
- if (-not $scan.Exists) { return @() }
- $n = [regex]::Escape($name)
- $opt = [System.Text.RegularExpressions.RegexOptions]::IgnoreCase
- if ($kind -eq 'attribute') { $mm = Get-ModuleMethods; $locals = (Find-ModuleDecl $name).Locals }
- for ($i = 0; $i -lt $scan.Code.Count; $i++) {
- $code = $scan.Code[$i]
- if ($kind -eq 'element') {
- if ([regex]::IsMatch($code, "(?<!\w)(Элементы|Items|ПодчиненныеЭлементы|ChildItems)\s*\.\s*$n(?!\w)", $opt)) { [void]$hits.Add($i + 1) }
- } elseif ($kind -eq 'command') {
- if ([regex]::IsMatch($code, "(?<!\w)(Команды|Commands)\s*\.\s*$n(?!\w)", $opt)) { [void]$hits.Add($i + 1) }
- } elseif ($kind -eq 'parameter') {
- if ([regex]::IsMatch($code, "(?<!\w)(Параметры|Parameters)\s*\.\s*$n(?!\w)", $opt)) { [void]$hits.Add($i + 1) }
- } else {
- # Реквизит формы: имя целым словом не после точки; после точки — только ЭтаФорма./ЭтотОбъект.
- # В методе без контекста реквизитов формы нет; где имя объявлено локально, голое имя — локальное
- if ($code.IndexOf($name, [System.StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
- $meth = Get-MethodAt $mm ($i + 1)
- if ($null -ne $meth -and $meth.noCtx) { continue }
- $isLocal = $null -ne $meth -and $locals.ContainsKey($meth.name)
- foreach ($m in [regex]::Matches($code, "(?<!\w)$n(?!\w)", $opt)) {
- $before = $code.Substring(0, $m.Index)
- if ($before -match '\.\s*$') {
- if ([regex]::IsMatch($before, '(?<![\w.])(ЭтаФорма|ЭтотОбъект|ThisForm|ThisObject)\s*\.\s*$', $opt)) { [void]$hits.Add($i + 1) }
- } elseif (-not $isLocal) {
- [void]$hits.Add($i + 1)
- }
- }
- }
- }
- # Строкой имя передают только в узком наборе вызовов (по корпусу) — остальные литералы
- # (параметры запроса, ключи структур) с именем совпадают случайно и ссылкой не считаются.
- $ctxPat = if ($kind -eq 'attribute') { $script:attrLiteralContext } else { $script:itemLiteralContext }
- foreach ($lit in $scan.Literals) {
- $t = $lit.Text
- $match = ($t -eq $name -or ($kind -eq 'attribute' -and $t.StartsWith("$name.", [System.StringComparison]::OrdinalIgnoreCase)))
- if ($match -and [regex]::IsMatch($lit.Prefix, $ctxPat, $opt)) { [void]$hits.Add($lit.Line) }
- }
- return @($hits)
- }
- function Format-ModuleRefs([int[]]$lines) {
- $scan = Get-ModuleScan
- $out = @()
- foreach ($l in ($lines | Select-Object -First 5)) { $out += " Module.bsl:${l}: $($scan.Lines[$l - 1].Trim())" }
- if ($lines.Count -gt 5) { $out += " … и ещё $($lines.Count - 5)" }
- return ($out -join "`n")
- }
- # Обработчики удаляемого, которые есть процедурами в модуле, — в отчёт: мёртвый код, решает автор.
- function Add-LeftHandlers([string[]]$handlers) {
- $scan = Get-ModuleScan
- if (-not $scan.Exists) { return }
- foreach ($h in $handlers) {
- if (-not $h -or $script:leftHandlers -contains $h) { continue }
- $pat = "(?im)^\s*((Асинх|Async)\s+)?(Процедура|Функция|Procedure|Function)\s+$([regex]::Escape($h))\s*\("
- if ([regex]::IsMatch($scan.Raw, $pat)) { $script:leftHandlers += $h }
- }
- }
- function Test-Borrowed([string]$name, [string]$kind) {
- if (-not $script:isExtension) { return $false }
- $bf = $root.SelectSingleNode("f:BaseForm", $nsMgr)
- $xp = switch ($kind) {
- 'element' { ".//*[@name]" }
- 'command' { "f:Commands/f:Command" }
- 'attribute' { "f:Attributes/f:Attribute" }
- 'parameter' { "f:Parameters/f:Parameter" }
- }
- foreach ($n in $bf.SelectNodes($xp, $nsMgr)) {
- if ($n.NamespaceURI -eq $formNs -and $n.GetAttribute("name") -eq $name) {
- if ($kind -ne 'element' -or $n.ParentNode.LocalName -eq 'ChildItems') { return $true }
- }
- }
- return $false
- }
- # Ближайший именованный элемент формы, которому принадлежит узел.
- function Get-OwnerElement($node) {
- $cur = $node
- while ($null -ne $cur -and $cur.NodeType -eq 'Element') {
- if ($cur.NamespaceURI -eq $formNs -and $cur.HasAttribute("name") -and ($cur.ParentNode.LocalName -eq 'ChildItems' -or $script:companionTags -contains $cur.LocalName)) { return $cur }
- $cur = $cur.ParentNode
- }
- return $null
- }
- function Get-ElementScopes {
- $scopes = @()
- if ($null -ne $script:rootCI) { $scopes += $script:rootCI }
- $acbNode = $root.SelectSingleNode("f:AutoCommandBar", $nsMgr)
- if ($null -ne $acbNode) { $scopes += $acbNode }
- return $scopes
- }
- function Get-NamedInSubtree($node) {
- $names = @($node.GetAttribute("name"))
- foreach ($d in $node.SelectNodes(".//*[@name]")) {
- if ($d.NamespaceURI -eq $formNs -and ($d.ParentNode.LocalName -eq 'ChildItems' -or $script:companionTags -contains $d.LocalName)) { $names += $d.GetAttribute("name") }
- }
- return $names
- }
- # Общий удалитель элементов: каскад зависимых кнопок и дополнений поиска, отказ при ссылках из
- # модуля и из привязанных полей, чистка условного оформления. $roots — узлы, $reasons — подпись.
- function Remove-FormElements($roots, [string]$ctx, [string]$reason) {
- # Вложенные в другие удаляемые — поглощаются
- $set = New-Object System.Collections.ArrayList
- foreach ($r in $roots) {
- $inside = $false
- foreach ($o in $roots) { if (-not (Same $o $r) -and (Test-IsInside $r $o)) { $inside = $true; break } }
- if (-not $inside) { [void]$set.Add($r) }
- }
- $items = New-Object System.Collections.ArrayList # @{ Node; Reason }
- foreach ($r in $set) { [void]$items.Add(@{ Node = $r; Reason = $reason }) }
- foreach ($r in $set) {
- foreach ($nm in (Get-NamedInSubtree $r)) {
- if (Test-Borrowed $nm 'element') { Fail "${ctx}: '$nm' — заимствованный элемент, платформа не даёт удалять его в расширении; чтобы скрыть — {""set"": ""$nm"", ""visible"": false}" }
- }
- }
- # Каскад: кнопки, дополнения поиска; отказ: прочие привязки Items.X…
- $changed = $true
- while ($changed) {
- $changed = $false
- $removedNames = @{}
- foreach ($it in $items) { foreach ($nm in (Get-NamedInSubtree $it.Node)) { $removedNames[$nm] = $nm } }
- $blockers = @()
- foreach ($s in (Get-ElementScopes)) {
- foreach ($t in $s.SelectNodes(".//*")) {
- $ln = $t.LocalName
- if (-not ($ln -eq 'CommandName' -or $ln -eq 'CommandSource' -or $ln.EndsWith('DataPath') -or ($ln -eq 'Item' -and $t.ParentNode.LocalName -eq 'AdditionSource'))) { continue }
- $txt = $t.InnerText.Trim()
- $target = $null
- if ($txt -match '^Form\.Item\.([^.]+)\.') { $target = $Matches[1] }
- elseif ($ln -eq 'CommandSource' -and $txt -match '^Item\.([^.]+)$') { $target = $Matches[1] }
- elseif ($txt -match '^Items\.([^.]+)\.') { $target = $Matches[1] }
- elseif ($ln -eq 'Item') { $target = $txt }
- if (-not $target -or -not $removedNames.ContainsKey($target)) { continue }
- $owner = Get-OwnerElement $t
- if ($null -eq $owner) { continue }
- $inRemoved = $false
- foreach ($it in $items) { if (Test-IsInside $owner $it.Node) { $inRemoved = $true; break } }
- if ($inRemoved) { continue }
- $ol = $owner.LocalName
- if ($ol -in @('Button','ButtonGroup','Popup','CommandBar','SearchStringAddition','ViewStatusAddition','SearchControlAddition')) {
- [void]$items.Add(@{ Node = $owner; Reason = "зависел от удалённого $($removedNames[$target])" })
- $changed = $true
- break
- }
- $blockers += "$($owner.GetAttribute('name')) ($ol, $ln = $txt)"
- }
- if ($changed) { break }
- }
- }
- if ($blockers.Count -gt 0) {
- Fail "${ctx}: на удаляемое ссылаются элементы, которые остаются: $(($blockers | Select-Object -Unique) -join '; ') — удали их в том же remove или перепривяжи"
- }
- # Заимствованное и ссылки из модуля — по всем удаляемым именам
- $allNames = @()
- foreach ($it in $items) { $allNames += Get-NamedInSubtree $it.Node }
- $allNames = @($allNames | Select-Object -Unique)
- foreach ($nm in $allNames) {
- if (Test-Borrowed $nm 'element') { Fail "${ctx}: '$nm' — заимствованный элемент, платформа не даёт удалять его в расширении; чтобы скрыть — {""set"": ""$nm"", ""visible"": false}" }
- }
- foreach ($nm in $allNames) {
- $refs = Find-ModuleRefs $nm 'element'
- if ($refs.Count -gt 0) { Fail "${ctx}: на элемент '$nm' ссылается модуль формы — сначала убери обращения из кода:`n$(Format-ModuleRefs $refs)" }
- }
- # Командный интерфейс формы: пункт с параметром из текущей строки удаляемого — каскадом
- $cif = $root.SelectSingleNode("f:CommandInterface", $nsMgr)
- if ($null -ne $cif) {
- $lowerNames = @{}; foreach ($nm in $allNames) { $lowerNames[$nm.ToLower()] = $true }
- foreach ($a in @($cif.SelectNodes(".//f:Item/f:Attribute", $nsMgr))) {
- if ($a.InnerText.Trim() -match '^~?Items\.([^.]+)(\.|$)' -and $lowerNames.ContainsKey($Matches[1].ToLower())) {
- $item = $a.ParentNode
- $parent = $item.ParentNode
- Remove-NodeWithWs $item
- while (-not (Same $parent $root) -and $null -eq (Get-FirstElementChild $parent)) {
- $up = $parent.ParentNode
- Remove-NodeWithWs $parent
- $parent = $up
- }
- $script:removeLog += " - командный интерфейс: пункт с параметром $($a.InnerText.Trim())"
- }
- }
- }
- # Обработчики событий удаляемого
- $handlers = @()
- foreach ($it in $items) {
- foreach ($ev in $it.Node.SelectNodes(".//f:Event", $nsMgr)) { $handlers += $ev.InnerText.Trim() }
- }
- Add-LeftHandlers $handlers
- # Условное оформление: поле удаляемого элемента — из списка оформляемых; пустой список
- # означал бы «вся форма», поэтому такое правило уходит целиком.
- $ca = $root.SelectSingleNode("f:Attributes/f:ConditionalAppearance", $nsMgr)
- if ($null -ne $ca) {
- $lower = @{}; foreach ($nm in $allNames) { $lower[$nm.ToLower()] = $true }
- foreach ($rule in @($ca.SelectNodes("dcsset:item", $nsMgr))) {
- $sel = $rule.SelectSingleNode("dcsset:selection", $nsMgr)
- if ($null -eq $sel) { continue }
- $hit = $false
- foreach ($si in @($sel.SelectNodes("dcsset:item", $nsMgr))) {
- $f = $si.SelectSingleNode("dcsset:field", $nsMgr)
- if ($null -ne $f -and $lower.ContainsKey($f.InnerText.Trim().ToLower())) {
- $script:removeLog += " - условное оформление: поле $($f.InnerText.Trim()) убрано из правила"
- Remove-NodeWithWs $si
- $hit = $true
- }
- }
- if ($hit -and $null -eq (Get-FirstElementChild $sel)) {
- Remove-NodeWithWs $rule
- $script:removeLog += " - условное оформление: правило без оформляемых полей удалено"
- }
- }
- if ($null -eq (Get-FirstElementChild $ca)) { Remove-NodeWithWs $ca }
- }
- foreach ($it in $items) {
- $node = $it.Node
- $name = $node.GetAttribute("name")
- # вложенные элементы для отчёта — без служебных узлов
- $shown = @()
- foreach ($d in $node.SelectNodes(".//*[@name]")) {
- if ($d.NamespaceURI -eq $formNs -and $d.ParentNode.LocalName -eq 'ChildItems') { $shown += $d.GetAttribute("name") }
- }
- $tail = ""
- if ($shown.Count -gt 0) {
- $list = ($shown | Select-Object -First 10) -join ', '
- if ($shown.Count -gt 10) { $list += ", … и ещё $($shown.Count - 10)" }
- $tail = " (+ $list)"
- }
- $why = if ($it.Reason) { " — $($it.Reason)" } else { "" }
- $ci = $node.ParentNode
- $holder = $ci.ParentNode
- Remove-NodeWithWs $node
- Remove-IfEmptyChildItems $ci
- # Опустевшая командная панель или меню — пустым тегом, как пишет платформа
- if ($null -ne $holder -and $script:companionTags -contains $holder.LocalName -and $null -eq (Get-FirstElementChild $holder)) {
- while ($holder.HasChildNodes) { $holder.RemoveChild($holder.FirstChild) | Out-Null }
- $holder.IsEmpty = $true
- }
- $script:removeLog += " - $name [$($node.LocalName)]$tail$why"
- $script:removedCount++
- }
- }
- function Invoke-Remove($op, [int]$idx) {
- $ctx = "elements[$idx] remove"
- Assert-OpKeys $op @('remove') $ctx
- $names = @(@($op.remove) | ForEach-Object { "$_" } | Where-Object { $_ })
- if ($names.Count -eq 0) { Fail "${ctx}: укажи имя элемента или список имён" }
- $nodes = @()
- $seen = @{}
- foreach ($n in $names) {
- if ($seen.ContainsKey($n)) { Fail "${ctx}: '$n' указан дважды" }
- $seen[$n] = $true
- $node = Find-FormElement $n
- if ($null -eq $node) { Fail "${ctx}: элемент '$n' не найден в форме" }
- if ($node.ParentNode.LocalName -ne 'ChildItems' -or $script:companionTags -contains $node.LocalName) {
- Fail "${ctx}: '$n' — служебный узел ($($node.LocalName)) своего элемента, удаляется только вместе с ним"
- }
- $nodes += $node
- }
- Remove-FormElements $nodes $ctx ""
- }
- function Remove-FormCommand($op, [int]$idx) {
- $ctx = "commands[$idx] remove"
- Assert-OpKeys $op @('remove') $ctx
- $name = "$($op.remove)"
- $sec = $root.SelectSingleNode("f:Commands", $nsMgr)
- $cmd = $null
- if ($null -ne $sec) { foreach ($c in $sec.SelectNodes("f:Command", $nsMgr)) { if ($c.GetAttribute("name") -eq $name) { $cmd = $c; break } } }
- if ($null -eq $cmd) { Fail "${ctx}: команда '$name' не найдена в форме" }
- $name = $cmd.GetAttribute("name")
- if (Test-Borrowed $name 'command') { Fail "${ctx}: '$name' — заимствованная команда, платформа не даёт удалять её в расширении" }
- $refs = Find-ModuleRefs $name 'command'
- if ($refs.Count -gt 0) { Fail "${ctx}: на команду '$name' ссылается модуль формы — сначала убери обращения из кода:`n$(Format-ModuleRefs $refs)" }
- # Кнопки команды — через общий удалитель (их имена тоже проверяются по модулю)
- $buttons = @()
- foreach ($s in (Get-ElementScopes)) {
- foreach ($cn in $s.SelectNodes(".//f:CommandName", $nsMgr)) {
- if ($cn.InnerText.Trim() -eq "Form.Command.$name") {
- $b = Get-OwnerElement $cn
- if ($null -ne $b) { $buttons += $b }
- }
- }
- }
- if ($buttons.Count -gt 0) { Remove-FormElements $buttons $ctx "кнопка удалённой команды $name" }
- # Пункты командного интерфейса формы
- $ci = $root.SelectSingleNode("f:CommandInterface", $nsMgr)
- if ($null -ne $ci) {
- foreach ($c in @($ci.SelectNodes(".//f:Item/f:Command", $nsMgr))) {
- if ($c.InnerText.Trim() -ne "Form.Command.$name") { continue }
- $item = $c.ParentNode
- $parent = $item.ParentNode
- Remove-NodeWithWs $item
- while (-not (Same $parent $root) -and $null -eq (Get-FirstElementChild $parent)) {
- $up = $parent.ParentNode
- Remove-NodeWithWs $parent
- $parent = $up
- }
- $script:removeLog += " - командный интерфейс: пункт команды $name"
- }
- }
- Add-LeftHandlers @($cmd.SelectNodes("f:Action", $nsMgr) | ForEach-Object { $_.InnerText.Trim() })
- Remove-NodeWithWs $cmd
- if ($null -eq (Get-FirstElementChild $sec)) { Remove-NodeWithWs $sec }
- $script:removeLog += " - команда $name"
- $script:removedCount++
- }
- function Remove-FormAttribute($op, [int]$idx) {
- $ctx = "attributes[$idx] remove"
- Assert-OpKeys $op @('remove') $ctx
- $name = "$($op.remove)"
- $sec = $root.SelectSingleNode("f:Attributes", $nsMgr)
- $attr = $null
- if ($null -ne $sec) { foreach ($a in $sec.SelectNodes("f:Attribute", $nsMgr)) { if ($a.GetAttribute("name") -eq $name) { $attr = $a; break } } }
- if ($null -eq $attr) { Fail "${ctx}: реквизит '$name' не найден в форме" }
- $name = $attr.GetAttribute("name")
- $main = $attr.SelectSingleNode("f:MainAttribute", $nsMgr)
- if ($null -ne $main -and $main.InnerText.Trim() -eq 'true') { Fail "${ctx}: '$name' — основной реквизит формы, он не удаляется" }
- if (Test-Borrowed $name 'attribute') { Fail "${ctx}: '$name' — заимствованный реквизит, платформа не даёт удалять его в расширении" }
- $refs = Find-ModuleRefs $name 'attribute'
- if ($refs.Count -gt 0) { Fail "${ctx}: к реквизиту '$name' обращается модуль формы — сначала убери обращения из кода:`n$(Format-ModuleRefs $refs)" }
- # Привязки в форме: пути данных элементов и поля условного оформления
- $users = @()
- $isPath = { param($t) $t -eq $name -or $t.StartsWith("$name.", [System.StringComparison]::OrdinalIgnoreCase) }
- foreach ($s in (Get-ElementScopes)) {
- foreach ($t in $s.SelectNodes(".//*")) {
- if (-not $t.LocalName.EndsWith('DataPath')) { continue }
- if (& $isPath $t.InnerText.Trim()) {
- $o = Get-OwnerElement $t
- if ($null -ne $o) { $users += "$($o.GetAttribute('name')) ($($t.LocalName))" }
- }
- }
- }
- $ca = $root.SelectSingleNode("f:Attributes/f:ConditionalAppearance", $nsMgr)
- if ($null -ne $ca) {
- foreach ($t in $ca.SelectNodes(".//dcsset:left | .//dcsset:right", $nsMgr)) {
- $xt = $t.GetAttribute("type", "http://www.w3.org/2001/XMLSchema-instance")
- if ($xt.EndsWith(':Field') -and (& $isPath $t.InnerText.Trim())) { $users += "условное оформление (отбор по $($t.InnerText.Trim()))" }
- }
- }
- $cif = $root.SelectSingleNode("f:CommandInterface", $nsMgr)
- if ($null -ne $cif) {
- foreach ($a in $cif.SelectNodes(".//f:Item/f:Attribute", $nsMgr)) {
- $at = $a.InnerText.Trim().TrimStart('~')
- if (& $isPath $at) { $users += "командный интерфейс (параметр $($a.InnerText.Trim()))" }
- }
- }
- if ($users.Count -gt 0) {
- Fail "${ctx}: к реквизиту '$name' привязаны: $(($users | Select-Object -Unique) -join '; ') — удали или перепривяжи их раньше (elements выполняются до attributes)"
- }
- Remove-NodeWithWs $attr
- if ($null -eq (Get-FirstElementChild $sec)) {
- while ($sec.HasChildNodes) { $sec.RemoveChild($sec.FirstChild) | Out-Null }
- $sec.IsEmpty = $true
- }
- $script:removeLog += " - реквизит $name"
- $script:removedCount++
- }
- # === 9e. Секции формы ===
- # Узел-секция корня формы; нет — создаётся на своём месте (порядок корня — по корпусу).
- function Get-OrCreateRootSection([string]$tag) {
- $sec = $root.SelectSingleNode("f:$tag", $nsMgr)
- if ($null -ne $sec) { return $sec }
- $sec = $xmlDoc.CreateElement($tag, $formNs)
- Insert-RootChild $sec
- return $sec
- }
- function Insert-RootChild($node) {
- $rank = Get-FormRootRank $node.LocalName
- $ref = $null
- foreach ($c in $root.ChildNodes) {
- if ($c.NodeType -ne 'Element') { continue }
- if ((Get-FormRootRank $c.LocalName) -gt $rank) { $ref = $c; break }
- }
- Insert-NodeAt $root $node $ref (Get-ChildIndent $root)
- }
- # Вывод эмиттера form-compile во фрагмент: блок пишет через X; результат — узлы верхнего уровня.
- function Invoke-SectionEmit([scriptblock]$emit, [string]$rootType = '', [bool]$normalize = $false) {
- $saveId = $script:nextElemId
- $script:xml = New-Object System.Text.StringBuilder 2048
- X "<_F $allNsDecl>"
- . $emit
- X "</_F>"
- $script:nextElemId = $saveId
- # Перечисления — к виду платформы, как в form-compile: у тегов прямо под корнем фрагмента — по $rootType
- # (свойства формы); $normalize — у вложенных узлов по их типу (добавляемые реквизиты и команды)
- $text = $script:xml.ToString()
- if ($rootType -or $normalize) { $text = Normalize-EnumTags $text $rootType }
- return @(Import-ElementNodes (Parse-Fragment $text))
- }
- # Свойство формы: значение — как в form-compile; null — убрать.
- function Set-FormProperty([string]$key, $value) {
- if ($null -ne $value -and -not ($value -is [string] -or $value -is [bool] -or $value -is [int] -or $value -is [long] -or $value -is [double] -or $value -is [decimal])) {
- Fail "properties.${key}: значение — строка, число или true/false"
- }
- $probe = New-Object PSObject
- $probe | Add-Member -NotePropertyName $key -NotePropertyValue $(if ($null -eq $value -or "$value" -eq '') { 'x' } else { $value })
- $node = @(Invoke-SectionEmit { Emit-Properties -props $probe -indent "`t" } $(if ($null -eq $value -or "$value" -eq '') { '' } else { 'Form' }))[0]
- $tag = $node.LocalName
- $existing = $root.SelectSingleNode("f:$tag", $nsMgr)
- if ($null -eq $value -or "$value" -eq '') {
- if ($null -ne $existing) { Remove-NodeWithWs $existing; $script:formLog += " * $tag убрано"; $script:formChanged++ }
- return
- }
- if ($null -ne $existing) { $root.ReplaceChild($node, $existing) | Out-Null } else { Insert-RootChild $node }
- $script:formLog += " * ${tag}=$($node.InnerText)"
- $script:formChanged++
- }
- # Снять привязки события у формы или элемента: callType пуст — все (в расширении у события их бывает
- # несколько), иначе — только эту. Пустой <Events> убирается. Возвращает снятые узлы.
- function Remove-EventBindings($owner, [string]$evName, [string]$callType) {
- $sec = $owner.SelectSingleNode("f:Events", $nsMgr)
- $hits = @()
- if ($null -ne $sec) {
- foreach ($e in @($sec.SelectNodes("f:Event", $nsMgr))) {
- if ($e.GetAttribute('name') -eq $evName -and (-not $callType -or $e.GetAttribute('callType') -eq $callType)) { $hits += $e }
- }
- }
- foreach ($e in $hits) { Remove-NodeWithWs $e }
- if ($hits.Count -gt 0 -and $null -eq (Get-FirstElementChild $sec)) { Remove-NodeWithWs $sec }
- return ,$hits
- }
- # Обработчики, отвязанные снятием или заменой. Проверяются в конце запуска (Resolve-UnboundHandlers):
- # правка могла привязать то же имя к другому событию.
- $script:unboundHandlers = @()
- function Add-UnboundHandlers([string[]]$handlers) {
- foreach ($h in $handlers) { if ($h) { $script:unboundHandlers += $h } }
- }
- # Отвязанные, которые форма больше не вызывает, — в «Handlers left in module». Копия исходной формы
- # в <BaseForm> расширения не в счёт: её привязки — не привязки расширения.
- function Resolve-UnboundHandlers {
- if ($script:unboundHandlers.Count -eq 0) { return }
- $bound = @{}
- foreach ($e in $xmlDoc.SelectNodes("//f:Event[not(ancestor::f:BaseForm)]|//f:Action[not(ancestor::f:BaseForm)]", $nsMgr)) { $bound[$e.InnerText.Trim().ToLower()] = $true }
- $left = @($script:unboundHandlers | Where-Object { -not $bound.ContainsKey($_.ToLower()) })
- if ($left.Count -gt 0) { Add-LeftHandlers $left }
- }
- # События формы — как events элемента: объект { Событие: обработчик | { handler, callType } | [ … ] } вешает
- # или заменяет, null — снимает; список [ Событие | { event, callType } ] — имена по конвенции.
- function Add-FormEventsDsl($events) {
- Update-FormOwner
- $adds = @()
- if ($events -is [array]) {
- foreach ($v in $events) {
- $isObj = $v -is [System.Management.Automation.PSCustomObject]
- $n = Resolve-EventName 'Form' $(if ($isObj) { "$($v.event)" } else { "$v" }) 'Form events'
- $h = if ($isObj) { "$($v.handler)" } else { '' }
- $ct = if ($isObj) { Normalize-CallType "$($v.callType)" 'Form' $n } else { '' }
- if (-not $ct -and $script:isExtension) { $ct = 'Before' }
- if (-not $h) {
- # Имя по конвенции типовых (ПриСозданииНаСервере); у события вне каталога его нет
- if (-not (Get-EventEntry 'Form' $n)) { Fail "events: у события формы $n укажите имя обработчика — имени по конвенции для него нет" }
- $h = Get-HandlerName -elementName '' -eventName $n -xmlTag 'Form' -callType $ct
- }
- $adds += [pscustomobject]@{ name = $n; handler = $h; callType = $ct }
- }
- } elseif ($events -is [System.Management.Automation.PSCustomObject]) {
- foreach ($p in $events.PSObject.Properties) {
- $n = Resolve-EventName 'Form' $p.Name 'Form events'
- if (@($p.Value).Count -eq 0) { Fail "events: событие формы $n — пустой список; чтобы снять обработчик, укажите null" }
- foreach ($v in @($p.Value)) {
- $isObj = $v -is [System.Management.Automation.PSCustomObject]
- $h = if ($isObj) { "$($v.handler)" } else { "$v" }
- $ct = if ($isObj) { Normalize-CallType "$($v.callType)" 'Form' $n } else { '' }
- if (-not $h) {
- # null — снять: без callType — все привязки события, с callType — только эту
- $ctStr = if ($ct) { "[$ct]" } else { "" }
- $hits = Remove-EventBindings $root $n $ct
- if ($hits.Count -eq 0) { Fail "events: событие формы $n$ctStr не обрабатывается — снимать нечего" }
- foreach ($e in $hits) {
- $ec = $e.GetAttribute('callType'); $ecStr = if ($ec) { "[$ec]" } else { "" }
- $script:formLog += " - event $n$ecStr -> $($e.InnerText)"
- $script:formChanged++
- }
- Add-UnboundHandlers @($hits | ForEach-Object { $_.InnerText })
- continue
- }
- if (-not $ct -and $script:isExtension) { $ct = 'Before' }
- $adds += [pscustomobject]@{ name = $n; handler = $h; callType = $ct }
- }
- }
- } else { Fail "events — объект { Событие: обработчик } или список событий" }
- $sec = $null
- foreach ($a in $adds) {
- Test-EventPairs -pairs @([pscustomobject]@{ name = $a.name }) -xmlTag 'Form' -elementName ''
- $n = $a.name; $h = $a.handler; $ct = $a.callType
- $ctStr = if ($ct) { "[$ct]" } else { "" }
- Register-Handler $h 'form' 'Form' $n
- if ($null -eq $sec) { $sec = $root.SelectSingleNode("f:Events", $nsMgr) }
- if ($null -ne $sec) {
- $dup = $null
- foreach ($e in $sec.SelectNodes("f:Event", $nsMgr)) {
- if ($e.GetAttribute('name') -eq $n -and $e.GetAttribute('callType') -eq $ct) { $dup = $e; break }
- }
- if ($null -ne $dup) {
- $old = $dup.InnerText
- if ($old -eq $h) { $script:formLog += " = event $n$ctStr -> $h already bound"; continue }
- # Другое имя — замена: у события один обработчик (на вид вызова)
- $dup.InnerText = $h
- Add-UnboundHandlers @($old)
- $script:formLog += " ~ event $n${ctStr}: $old -> $h"
- $script:formChanged++
- continue
- }
- }
- if ($null -eq $sec) { $sec = Get-OrCreateRootSection 'Events' }
- $ev = $xmlDoc.CreateElement("Event", $formNs)
- $ev.SetAttribute('name', $n)
- if ($ct) { $ev.SetAttribute('callType', $ct) }
- $ev.InnerText = $h
- Insert-NodeAt $sec $ev (Get-EventInsertRef $sec 'Form' $n $ct) (Get-ChildIndent $sec)
- $script:formLog += " + event $n$ctStr -> $h"
- $script:formChanged++
- }
- }
- # Исключённые команды: список имён — исключить; { remove: [...] } — вернуть.
- function Update-ExcludedCommands($spec) {
- if ($spec -is [System.Management.Automation.PSCustomObject]) {
- Assert-OpKeys $spec @('remove') "excludedCommands"
- $sec = $root.SelectSingleNode("f:CommandSet", $nsMgr)
- foreach ($n in @(@($spec.remove) | ForEach-Object { "$_" })) {
- $hit = $null
- if ($null -ne $sec) { foreach ($e in $sec.SelectNodes("f:ExcludedCommand", $nsMgr)) { if ($e.InnerText.Trim() -eq $n) { $hit = $e; break } } }
- if ($null -eq $hit) { Fail "excludedCommands: команда '$n' не исключена в форме" }
- Remove-NodeWithWs $hit
- $script:formLog += " - исключение команды $n"
- $script:formChanged++
- }
- if ($null -ne $sec -and $null -eq (Get-FirstElementChild $sec)) { Remove-NodeWithWs $sec }
- return
- }
- $sec = $null
- foreach ($n in @(@($spec) | ForEach-Object { "$_" } | Where-Object { $_ })) {
- if ($null -eq $sec) { $sec = Get-OrCreateRootSection 'CommandSet' }
- $dup = $false
- foreach ($e in $sec.SelectNodes("f:ExcludedCommand", $nsMgr)) { if ($e.InnerText.Trim() -eq $n) { $dup = $true; break } }
- if ($dup) { $script:formLog += " = команда $n уже исключена"; continue }
- $e = $xmlDoc.CreateElement("ExcludedCommand", $formNs)
- $e.InnerText = $n
- Insert-NodeAt $sec $e $null (Get-ChildIndent $sec)
- $script:formLog += " + исключена команда $n"
- $script:formChanged++
- }
- }
- # Параметры формы — по порядку: определения — как в form-compile; { remove: имя | [...] } — удалить;
- # { set: имя, … } — изменить.
- function Update-FormParameters($list) {
- $i = 0
- foreach ($p in @($list)) {
- if ($null -ne $p.PSObject.Properties['remove']) {
- Assert-OpKeys $p @('remove') "parameters[$i] remove"
- foreach ($n in @(@($p.remove) | ForEach-Object { "$_" })) {
- $sec = $root.SelectSingleNode("f:Parameters", $nsMgr)
- $hit = $null
- if ($null -ne $sec) { foreach ($e in $sec.SelectNodes("f:Parameter", $nsMgr)) { if ($e.GetAttribute('name') -eq $n) { $hit = $e; break } } }
- if ($null -eq $hit) { Fail "parameters[$i] remove: параметр '$n' не найден в форме" }
- $refs = Find-ModuleRefs $n 'parameter'
- if ($refs.Count -gt 0) { Fail "parameters[$i] remove: к параметру '$n' обращается модуль формы — сначала убери обращения из кода:`n$(Format-ModuleRefs $refs)" }
- Remove-NodeWithWs $hit
- if ($null -eq (Get-FirstElementChild $sec)) { Remove-NodeWithWs $sec }
- $script:formLog += " - параметр $n"
- $script:formChanged++
- }
- } elseif ($null -ne $p.PSObject.Properties['set']) {
- Invoke-ParamSet $p $i
- } elseif ($null -ne $p.PSObject.Properties['rename']) {
- Invoke-ParamRename $p $i
- } else {
- Assert-OpKeys $p $script:paramKeys "parameters[$i] '$($p.name)'"
- $sec = Get-OrCreateRootSection 'Parameters'
- foreach ($e in $sec.SelectNodes("f:Parameter", $nsMgr)) {
- if ($e.GetAttribute('name') -eq "$($p.name)") { Fail "parameters: параметр '$($p.name)' уже есть в форме; изменить: { `"set`": `"$($p.name)`", … }" }
- }
- $wrap = @(Invoke-SectionEmit { Emit-Parameters -params @($p) -indent "`t" })[0]
- foreach ($node in @($wrap.SelectNodes("f:Parameter", $nsMgr))) {
- $wrap.RemoveChild($node) | Out-Null
- Insert-NodeAt $sec $node $null (Get-ChildIndent $sec)
- $script:formLog += " + параметр $($node.GetAttribute('name'))"
- $script:formChanged++
- }
- }
- $i++
- }
- }
- # Условное оформление: правила — как в form-compile; добавляются в конец оформления формы.
- function Add-FormConditionalAppearance($items) {
- $items = @($items)
- if ($items.Count -eq 0) { return }
- $attrs = Get-OrCreateRootSection 'Attributes'
- if ($attrs.IsEmpty) { $attrs.IsEmpty = $false }
- $ca = $attrs.SelectSingleNode("f:ConditionalAppearance", $nsMgr)
- $wrap = @(Invoke-SectionEmit { Emit-ConditionalAppearance -items $items -indent "`t`t" -wrapTag 'ConditionalAppearance' })[0]
- if ($null -eq $ca) {
- Insert-NodeAt $attrs $wrap $null (Get-ChildIndent $attrs)
- $n = @($wrap.ChildNodes | Where-Object { $_.NodeType -eq 'Element' }).Count
- } else {
- $n = 0
- foreach ($r in @($wrap.ChildNodes | Where-Object { $_.NodeType -eq 'Element' })) {
- $wrap.RemoveChild($r) | Out-Null
- Insert-NodeAt $ca $r $null (Get-ChildIndent $ca)
- $n++
- }
- }
- $script:formLog += " + условное оформление: правил $n"
- $script:formChanged += $n
- }
- # Командный интерфейс: пункты панелей — как в form-compile; добавляются в конец своей панели.
- function Add-FormCommandInterface($ci) {
- $wrap = @(Invoke-SectionEmit { Emit-CommandInterface -ci $ci -indent "`t" })
- if ($wrap.Count -eq 0) { return }
- $wrap = $wrap[0]
- $sec = $root.SelectSingleNode("f:CommandInterface", $nsMgr)
- if ($null -eq $sec) {
- Insert-RootChild $wrap
- foreach ($pn in @($wrap.ChildNodes | Where-Object { $_.NodeType -eq 'Element' })) {
- $script:formLog += " + командный интерфейс, $($pn.LocalName): пунктов $(@($pn.SelectNodes('f:Item', $nsMgr)).Count)"
- $script:formChanged++
- }
- return
- }
- foreach ($pn in @($wrap.ChildNodes | Where-Object { $_.NodeType -eq 'Element' })) {
- $target = $sec.SelectSingleNode("f:$($pn.LocalName)", $nsMgr)
- if ($null -eq $target) {
- $wrap.RemoveChild($pn) | Out-Null
- # Как в выгрузке: панель навигации раньше командной панели
- $ref = if ($pn.LocalName -eq 'NavigationPanel') { $sec.SelectSingleNode("f:CommandBar", $nsMgr) } else { $null }
- Insert-NodeAt $sec $pn $ref (Get-ChildIndent $sec)
- $cnt = @($pn.SelectNodes('f:Item', $nsMgr)).Count
- } else {
- $cnt = 0
- foreach ($it in @($pn.SelectNodes("f:Item", $nsMgr))) {
- $pn.RemoveChild($it) | Out-Null
- Insert-NodeAt $target $it $null (Get-ChildIndent $target)
- $cnt++
- }
- }
- $script:formLog += " + командный интерфейс, $($pn.LocalName): пунктов $cnt"
- $script:formChanged++
- }
- }
- # Обработчики, которые были в форме до правки: callType по умолчанию ставится только новым
- $script:preexistingHandlers = New-Object 'System.Collections.Generic.HashSet[System.Xml.XmlNode]'
- foreach ($n in $root.SelectNodes("//f:Event | //f:Action", $nsMgr)) { [void]$script:preexistingHandlers.Add($n) }
- # === 9f. Реквизиты, команды, параметры: изменение (set), колонки по пути ===
- # Ключи записей — те, что читают эмиттеры form-compile, с их синонимами. Эмиттер незнакомый ключ
- # молча пропустил бы — поэтому он ошибка.
- $script:attrKeys = @('name','title','type','valueType','typeDescription','описаниеТипов','типЗначений','planner','chart','main','view','edit','savedData','save','fillCheck','fillChecking','useAlways','functionalOptions','columns','additionalColumns','settings')
- $script:colKeys = @('name','title','type','fillCheck','fillChecking','functionalOptions','view','edit','useAlways')
- $script:cmdKeys = @('name','title','tooltip','use','shortcut','picture','loadTransparent','action','actions','callType','functionalOptions','representation','modifiesSavedData','currentRowUse','table','associatedTableElementId','используемаяТаблица')
- $script:paramKeys = @('name','type','key')
- # Тег, который пишет ключ. Ключи одного тега меняются одной пробой (action + callType, picture + loadTransparent).
- $script:attrKeyTags = @{ title='Title'; type='Type'; valueType='Settings'; typeDescription='Settings'; 'описаниеТипов'='Settings'; 'типЗначений'='Settings'; planner='Settings'; chart='Settings'; view='View'; edit='Edit'; savedData='SavedData'; save='Save'; fillCheck='FillCheck'; fillChecking='FillCheck'; useAlways='UseAlways'; functionalOptions='FunctionalOptions'; settings='Settings' }
- $script:colKeyTags = @{ title='Title'; type='Type'; fillCheck='FillCheck'; fillChecking='FillCheck'; functionalOptions='FunctionalOptions'; view='View'; edit='Edit' }
- $script:cmdKeyTags = @{ title='Title'; tooltip='ToolTip'; use='Use'; shortcut='Shortcut'; picture='Picture'; loadTransparent='Picture'; action='Action'; actions='Action'; callType='Action'; functionalOptions='FunctionalOptions'; representation='Representation'; modifiesSavedData='ModifiesSavedData'; currentRowUse='CurrentRowUse'; table='AssociatedTableElementId'; associatedTableElementId='AssociatedTableElementId'; 'используемаяТаблица'='AssociatedTableElementId' }
- $script:paramKeyTags = @{ type='Type'; key='KeyParameter' }
- # Ключи настроек динамического списка — теги, которые они пишут; отбор, параметры данных, сортировка и
- # оформление — части пользовательских настроек (ListSettings), меняются по отдельности
- $script:dlKeyTags = @{ query = @('ManualQuery','QueryText'); manualQuery = @('ManualQuery'); dynamicDataRead = @('DynamicDataRead'); autoFillAvailableFields = @('AutoFillAvailableFields'); fields = @('Field'); calculatedFields = @('CalculatedField'); parameters = @('Parameter'); keyType = @('KeyType'); keyFields = @('KeyField'); mainTable = @('MainTable'); getInvisibleFieldPresentations = @('GetInvisibleFieldPresentations'); autoSaveUserSettings = @('AutoSaveUserSettings'); listSettings = @('ListSettings') }
- $script:dlListParts = @{ filter = 'filter'; dataParameters = 'dataParameters'; order = 'order'; conditionalAppearance = 'conditionalAppearance' }
- # Порядок детей — как пишут эмиттеры (он же платформенный). Settings динамического списка — после Columns.
- $script:sectionChildOrder = @{
- Attribute = @('Title','Type','Settings','MainAttribute','View','Edit','SavedData','Save','FillCheck','UseAlways','FunctionalOptions','Columns','Settings#DynamicList')
- Column = @('Title','Type','FillCheck','FunctionalOptions','View','Edit')
- Command = @('Title','ToolTip','Use','Shortcut','Picture','Action','FunctionalOptions','Representation','ModifiesSavedData','CurrentRowUse','AssociatedTableElementId')
- Parameter = @('Type','KeyParameter')
- # Настройки динамического списка — порядок корпуса (ERP, БП, УТ); KeyField и MainTable вместе не встречаются — как в эмиттере
- ListSettings = @('filter','dataParameters','order','conditionalAppearance','item','itemsViewMode','itemsUserSettingID','itemsUserSettingPresentation')
- Settings = @('AutoFillAvailableFields','ManualQuery','DynamicDataRead','QueryText','Field','CalculatedField','Parameter','KeyType','KeyField','MainTable','AutoSaveUserSettings','GetInvisibleFieldPresentations','ListSettings')
- }
- function Get-SectionChildRank([string]$parentTag, $child) {
- $ln = $child.LocalName
- if ($ln -eq 'Settings' -and $child.GetAttribute('type', 'http://www.w3.org/2001/XMLSchema-instance') -eq 'DynamicList') { $ln = 'Settings#DynamicList' }
- return [array]::IndexOf($script:sectionChildOrder[$parentTag], $ln)
- }
- function Insert-SectionChild($parent, $child, [string]$indent = $null) {
- if (-not $indent) { $indent = Get-ChildIndent $parent }
- $rank = Get-SectionChildRank $parent.LocalName $child
- $ref = $null
- foreach ($c in $parent.ChildNodes) {
- if ($c.NodeType -ne 'Element') { continue }
- if ((Get-SectionChildRank $parent.LocalName $c) -gt $rank) { $ref = $c; break }
- }
- Insert-NodeAt $parent $child $ref $indent
- }
- function New-DslSpec($h) { return (ConvertFrom-JsonInput ([pscustomobject]$h | ConvertTo-Json -Depth 100 -Compress) 'DSL spec') }
- # Узел секции по имени (имена в 1С регистронезависимы)
- function Find-SectionItem([string]$section, [string]$tag, [string]$name) {
- foreach ($n in $root.SelectNodes("f:$section/f:$tag", $nsMgr)) { if ($n.GetAttribute('name') -eq $name) { return $n } }
- return $null
- }
- function Test-MainAttribute($node) {
- $m = $node.SelectSingleNode("f:MainAttribute", $nsMgr)
- return ($null -ne $m -and $m.InnerText.Trim() -eq 'true')
- }
- # Вид реквизита: таблица (свои колонки), динамический список или прочее
- function Get-AttrKind($node) {
- $ts = @($node.SelectNodes("f:Type/v8:Type", $nsMgr) | ForEach-Object { $_.InnerText.Trim() })
- if ($ts.Count -eq 1 -and @('v8:ValueTable','v8:ValueTree') -contains $ts[0]) { return 'table' }
- if ($ts.Count -eq 1 -and $ts[0] -eq 'cfg:DynamicList') { return 'dynlist' }
- return 'scalar'
- }
- # Тип для вывода — в записи DSL: string(150), decimal(15,2), CatalogRef.X, A | B
- function Format-TypeNode($t) {
- if ($null -eq $t -or $null -eq $t.SelectSingleNode("v8:Type | v8:TypeSet | v8:TypeId", $nsMgr)) { return '(no type)' }
- $parts = @()
- foreach ($ty in $t.SelectNodes("v8:Type | v8:TypeSet | v8:TypeId", $nsMgr)) {
- $v = $ty.InnerText.Trim() -replace '^(cfg|v8|xs|d\d+p\d+):', ''
- if ($v -eq 'string') {
- $l = $t.SelectSingleNode("v8:StringQualifiers/v8:Length", $nsMgr)
- if ($null -ne $l -and $l.InnerText.Trim() -ne '0') { $v = "string($($l.InnerText.Trim()))" }
- } elseif ($v -eq 'decimal') {
- $d = $t.SelectSingleNode("v8:NumberQualifiers/v8:Digits", $nsMgr); $f = $t.SelectSingleNode("v8:NumberQualifiers/v8:FractionDigits", $nsMgr)
- if ($null -ne $d) { $v = "decimal($($d.InnerText.Trim()),$(if ($null -ne $f) { $f.InnerText.Trim() } else { '0' }))" }
- } elseif ($v -eq 'dateTime') {
- $df = $t.SelectSingleNode("v8:DateQualifiers/v8:DateFractions", $nsMgr)
- if ($null -ne $df) { $v = @{ Date = 'date'; Time = 'time'; DateTime = 'dateTime' }[$df.InnerText.Trim()] }
- }
- $parts += $v
- }
- return ($parts -join ' | ')
- }
- # Пробы эмиттеров form-compile: узел, каким его пишет создание формы, — с отступами места назначения
- function Get-AttrProbe($spec, [string]$attrIndent) {
- $ind = if ($attrIndent.Length -gt 0) { $attrIndent.Substring(1) } else { '' }
- $wrap = @(Invoke-SectionEmit { Emit-Attributes -attrs @($spec) -indent $ind } '' $true)[0]
- return $wrap.SelectSingleNode("f:Attribute", $nsMgr)
- }
- function Get-ColumnProbe($spec, [string]$attrName) {
- $a = Get-AttrProbe (New-DslSpec ([ordered]@{ name = $attrName; title = ''; type = 'ValueTable'; columns = @($spec) })) "`t`t"
- return $a.SelectSingleNode("f:Columns/f:Column", $nsMgr)
- }
- function Get-CommandProbe($spec) {
- $wrap = @(Invoke-SectionEmit { Emit-Commands -cmds @($spec) -indent "`t" } '' $true)[0]
- return $wrap.SelectSingleNode("f:Command", $nsMgr)
- }
- function Get-ParameterProbe($spec) {
- $wrap = @(Invoke-SectionEmit { Emit-Parameters -params @($spec) -indent "`t" })[0]
- return $wrap.SelectSingleNode("f:Parameter", $nsMgr)
- }
- # Теги ключа: у узла снимаются, из пробы встают на своё место (в пробе нет — так и остаётся: false, null)
- function Set-SectionTags($target, $probe, [string[]]$tags) {
- # Отступ детей — до снятия тегов: без детей у узла остаётся только закрывающий перевод строки
- $ci = Get-ChildIndent $target
- foreach ($t in $tags) { foreach ($x in @($target.SelectNodes("f:$t", $nsMgr))) { Remove-NodeWithWs $x } }
- if ($null -eq $probe) { return }
- foreach ($t in $tags) {
- foreach ($pn in @($probe.SelectNodes("f:$t", $nsMgr))) {
- $old = Get-NodeIndent $pn
- $probe.RemoveChild($pn) | Out-Null
- Insert-SectionChild $target $pn $ci
- Set-SubtreeIndent $pn $old $ci
- }
- }
- }
- function Format-SetValue($v) {
- if ($null -eq $v) { return 'null' }
- if ($v -is [bool]) { return "$v".ToLower() }
- if ($v -is [string] -or $v -is [int] -or $v -is [long] -or $v -is [double]) { return "$v" }
- return ($v | ConvertTo-Json -Depth 20 -Compress)
- }
- # Общий ход set: ключи — по тегам; на каждый тег одна проба со всеми его ключами. $probeOf — проба по
- # ключам тега, $x — что ей нужно знать об узле (имя, отступ)
- function Set-SectionNode($node, $props, $keyTags, [scriptblock]$probeOf, $x, [string]$label, [string]$c) {
- $byTag = [ordered]@{}
- foreach ($p in $props) {
- $tag = $keyTags[$p.Name]
- if (-not $byTag.Contains($tag)) { $byTag[$tag] = @() }
- $byTag[$tag] += $p
- }
- foreach ($tag in $byTag.Keys) {
- $ps = @($byTag[$tag])
- $given = @($ps | Where-Object { $null -ne $_.Value })
- $probe = $null
- if ($given.Count -gt 0) {
- $h = [ordered]@{}
- foreach ($p in $given) { $h[$p.Name] = $p.Value }
- $probe = & $probeOf $h $x
- } elseif ($tag -eq 'Title' -and $x.AutoTitle) {
- # умолчание заголовка — как при добавлении: из имени
- $probe = & $probeOf ([ordered]@{ '#auto' = $true }) $x
- }
- $beforeType = if ($tag -eq 'Type') { Format-TypeNode ($node.SelectSingleNode("f:Type", $nsMgr)) } else { $null }
- Set-SectionTags $node $probe @($tag)
- if ($tag -eq 'Type') {
- $script:changeLog += " ~ ${label}: type $beforeType → $(Format-TypeNode ($node.SelectSingleNode("f:Type", $nsMgr)))"
- } else {
- $shown = ($ps | ForEach-Object { if ($null -eq $_.Value) { "$($_.Name) сброшено" } else { "$($_.Name)=$(Format-SetValue $_.Value)" } }) -join ', '
- $script:changeLog += " ~ ${label}: $shown"
- }
- $script:sectionChanged++
- }
- }
- function Assert-SetKeys($props, $keyTags, [string]$c, [string]$renameHint) {
- foreach ($p in $props) {
- if ($p.Name -eq 'name') { Fail "${c}: имя через set не меняется — переименование: $renameHint" }
- if (-not $keyTags.ContainsKey($p.Name)) {
- Fail "${c}: неизвестный ключ '$($p.Name)'; допустимы: $((@($keyTags.Keys) | Sort-Object -Unique) -join ', ')"
- }
- }
- }
- # Колонка по пути: Таблица.Колонка — своя колонка реквизита-таблицы; Объект.ТЧ.Колонка — доп. колонка
- # табличной части (группа AdditionalColumns table="Объект.ТЧ")
- function Resolve-ColumnPath([string]$path, [string]$c) {
- $segs = @($path -split '\.')
- if ($segs.Count -lt 2 -or @($segs | Where-Object { -not $_ }).Count -gt 0) { Fail "${c}: путь колонки — Таблица.Колонка или Объект.ТабличнаяЧасть.Колонка" }
- $attr = Find-SectionItem 'Attributes' 'Attribute' $segs[0]
- if ($null -eq $attr) { Fail "${c}: реквизит '$($segs[0])' не найден в форме" }
- $colName = $segs[$segs.Count - 1]
- $cols = $attr.SelectSingleNode("f:Columns", $nsMgr)
- $kind = Get-AttrKind $attr
- if ($kind -eq 'dynlist') { Fail "${c}: у динамического списка колонок нет — поля задаёт запрос (set + settings)" }
- if ($segs.Count -eq 2) {
- if ($kind -ne 'table') { Fail "${c}: у '$($segs[0])' нет своих колонок; доп. колонка табличной части — путь $($segs[0]).ТабличнаяЧасть.Колонка" }
- $container = $cols
- $table = $null
- } else {
- $table = ($segs[0..($segs.Count - 2)]) -join '.'
- $container = $null
- if ($null -ne $cols) { foreach ($g in $cols.SelectNodes("f:AdditionalColumns", $nsMgr)) { if ($g.GetAttribute('table') -eq $table) { $container = $g; break } } }
- }
- $col = $null
- if ($null -ne $container) { foreach ($x in $container.SelectNodes("f:Column", $nsMgr)) { if ($x.GetAttribute('name') -eq $colName) { $col = $x; break } } }
- return @{ Attr = $attr; Container = $container; Table = $table; Name = $colName; Column = $col; Columns = $cols; Segs = $segs; Kind = $kind }
- }
- # Табличные части объекта формы — из его описания рядом (<Объект>.xml над Forms); нет описания — $null
- function Get-ObjectTabularSections {
- $d = [System.IO.Path]::GetDirectoryName($resolvedFormPath)
- for ($k = 0; $k -lt 3; $k++) { $d = [System.IO.Path]::GetDirectoryName($d); if (-not $d) { return $null } }
- $xml = "$d.xml"
- if (-not (Test-Path -LiteralPath $xml)) { return $null }
- $t = [System.IO.File]::ReadAllText($xml)
- # пустой список — тоже ответ («частей нет»), не $null: запятая не даёт PS развернуть его в ничто
- return ,@([regex]::Matches($t, '<TabularSection uuid="[^"]*">[\s\S]*?<Properties>\s*<Name>([^<]+)</Name>') | ForEach-Object { $_.Groups[1].Value })
- }
- # Новая группа доп. колонок: путь таблицы — от колонки-таблицы реквизита или табличной части объекта.
- # Что можно проверить по форме и описанию объекта — проверяется; остальное проверит платформа при загрузке.
- function Assert-AdditionalTable($r, [string]$c) {
- $segs = $r.Segs
- $an = $r.Attr.GetAttribute('name')
- if ($r.Kind -eq 'table') {
- # Каждый уровень пути — колонка-таблица предыдущего (в корпусе только ValueTable/ValueTree)
- $level = $r.Columns
- for ($k = 1; $k -le $segs.Count - 2; $k++) {
- $prefix = ($segs[0..($k - 1)]) -join '.'
- if ($k -gt 1) {
- $level = $null
- foreach ($g in $r.Columns.SelectNodes("f:AdditionalColumns", $nsMgr)) { if ($g.GetAttribute('table') -eq $prefix) { $level = $g; break } }
- if ($null -eq $level) { Fail "${c}: вложенной таблицы '$prefix' в форме нет — сначала добавь её колонки" }
- }
- $owner = $null
- if ($null -ne $level) { foreach ($x in $level.SelectNodes("f:Column", $nsMgr)) { if ($x.GetAttribute('name') -eq $segs[$k]) { $owner = $x; break } } }
- if ($null -eq $owner) { Fail "${c}: у '$prefix' нет колонки '$($segs[$k])' — путь вложенной таблицы идёт от колонки реквизита" }
- $ot = @($owner.SelectNodes("f:Type/v8:Type", $nsMgr) | ForEach-Object { $_.InnerText.Trim() })
- if ($ot.Count -ne 1 -or @('v8:ValueTable','v8:ValueTree') -notcontains $ot[0]) { Fail "${c}: колонка '$prefix.$($segs[$k])' — не таблица значений, вложенных колонок у неё нет" }
- }
- return
- }
- if ($segs.Count -eq 3 -and (Test-MainAttribute $r.Attr) -and -not $script:isExtension) {
- $ts = Get-ObjectTabularSections
- if ($null -ne $ts) {
- if ($ts -notcontains $segs[1]) { Fail "${c}: у объекта нет табличной части '$($segs[1])'$(if ($ts.Count) { "; есть: $($ts -join ', ')" })" }
- return
- }
- }
- $script:warnLog += "[WARN] new additional columns of '$($r.Table)' — the table path is not checked here; the platform rejects a wrong one at load"
- }
- function Invoke-AttrSet($op, [int]$idx) {
- $ctx = "attributes[$idx] set"
- $targets = @(@($op.set) | ForEach-Object { "$_" } | Where-Object { $_ })
- if ($targets.Count -eq 0) { Fail "${ctx}: укажи имя реквизита (колонку — путём Таблица.Колонка) или список имён" }
- $props = @($op.PSObject.Properties | Where-Object { $_.Name -ne 'set' })
- if ($props.Count -eq 0) { Fail "${ctx}: не указано, что менять" }
- foreach ($t in $targets) {
- $c = "$ctx '$t'"
- if ($t.Contains('.')) {
- $r = Resolve-ColumnPath $t $c
- if ($null -eq $r.Column) { Fail "${c}: колонка не найдена" }
- if (Test-Borrowed $r.Attr.GetAttribute('name') 'attribute') { Fail "${c}: колонка заимствованного реквизита — её свойства задаёт исходная форма" }
- Assert-SetKeys $props $script:colKeyTags $c "{ `"rename`": `"$t`", `"to`": `"НовоеИмя`" }"
- foreach ($p in $props) { if ($p.Name -eq 'type' -and ($null -eq $p.Value -or "$($p.Value)" -eq '')) { Fail "${c}: тип обязателен — укажи новый" } }
- Set-SectionNode $r.Column $props $script:colKeyTags { param($h, $x) $h['name'] = $x.Col; Get-ColumnProbe (New-DslSpec $h) $x.Attr } @{ Col = $r.Column.GetAttribute('name'); Attr = $r.Attr.GetAttribute('name') } $t $c
- continue
- }
- $node = Find-SectionItem 'Attributes' 'Attribute' $t
- if ($null -eq $node) { Fail "${c}: реквизит не найден в форме" }
- $name = $node.GetAttribute('name')
- if (Test-Borrowed $name 'attribute') { Fail "${c}: заимствованный реквизит — его свойства задаёт исходная форма" }
- foreach ($p in $props) {
- if (@('columns','additionalColumns') -contains $p.Name) { Fail "${c}: колонки задаются путём: { `"name`": `"$name.Колонка`", … } — добавить, { `"set`": `"$name.Колонка`", … } — изменить, { `"remove`": `"$name.Колонка`" } — удалить" }
- if ($p.Name -eq 'main') { Fail "${c}: основной реквизит через set не назначается" }
- }
- Assert-SetKeys $props $script:attrKeyTags $c "{ `"rename`": `"$name`", `"to`": `"НовоеИмя`" }"
- $kind = Get-AttrKind $node
- $isMain = Test-MainAttribute $node
- $settingsOp = @($props | Where-Object { $_.Name -eq 'settings' })
- $rest = @($props | Where-Object { $_.Name -ne 'settings' })
- foreach ($p in $rest) {
- $tag = $script:attrKeyTags[$p.Name]
- if ($p.Name -eq 'type') {
- if ($null -eq $p.Value -or "$($p.Value)" -eq '') { Fail "${c}: тип обязателен — укажи новый" }
- if ($isMain) { Fail "${c}: тип основного реквизита не меняется — он задаёт, что редактирует форма" }
- }
- if ($tag -eq 'Settings' -and $kind -eq 'dynlist') { Fail "${c}: '$($p.Name)' к динамическому списку не применимо — его настройки меняет settings" }
- }
- $ind = Get-NodeIndent $node
- if ($rest.Count -gt 0) {
- $typeOp = @($rest | Where-Object { $_.Name -eq 'type' })
- if ($typeOp.Count -gt 0) {
- $pt = Get-AttrProbe (New-DslSpec ([ordered]@{ name = $name; title = ''; type = $typeOp[0].Value })) $ind
- $nk = Get-AttrKind $pt
- if ($nk -ne $kind) {
- $what = @{ table = 'таблица значений/дерево'; dynlist = 'динамический список'; scalar = 'значение' }
- Fail "${c}: тип меняет вид реквизита ($($what[$kind]) → $($what[$nk])) — колонки, настройки и привязанные элементы не переносятся; такой реквизит удаляют и добавляют заново"
- }
- }
- Set-SectionNode $node $rest $script:attrKeyTags { param($h, $x) $h['name'] = $x.Name; if ($h.Contains('#auto')) { $h.Remove('#auto') } elseif (-not $h.Contains('title')) { $h['title'] = '' }; Get-AttrProbe (New-DslSpec $h) $x.Ind } @{ Name = $name; Ind = $ind; AutoTitle = -not $isMain } $name $c
- }
- if ($settingsOp.Count -gt 0) { Set-DynListSettings $node $settingsOp[0].Value $ind $c }
- }
- }
- # Настройки динамического списка: перевыпускаются только переданные части (запрос, основная таблица,
- # поля…); остальное — в том числе пользовательские настройки списка — остаётся
- function Set-DynListSettings($node, $v, [string]$ind, [string]$c) {
- $name = $node.GetAttribute('name')
- if ((Get-AttrKind $node) -ne 'dynlist') { Fail "${c}: settings — настройки динамического списка, а '$name' не динамический список" }
- if (-not ($v -is [System.Management.Automation.PSCustomObject]) -or @($v.PSObject.Properties).Count -eq 0) { Fail "${c}: settings — объект с меняемыми настройками, напр. { `"query`": `"…`" }" }
- $keys = @($v.PSObject.Properties | ForEach-Object { $_.Name })
- foreach ($k in $keys) {
- if (-not $script:dlKeyTags.ContainsKey($k) -and -not $script:dlListParts.ContainsKey($k)) { Fail "${c}: settings — неизвестный ключ '$k'; допустимы: $((@($script:dlKeyTags.Keys) + @($script:dlListParts.Keys) | Sort-Object) -join ', ')" }
- }
- $parts = @($keys | Where-Object { $script:dlListParts.ContainsKey($_) })
- if ($parts.Count -gt 0 -and $keys -contains 'listSettings') { Fail "${c}: settings — listSettings целиком или $($parts -join ', ') по частям, не вместе" }
- $target = $null
- foreach ($s in $node.SelectNodes("f:Settings", $nsMgr)) { if ($s.GetAttribute('type', 'http://www.w3.org/2001/XMLSchema-instance') -eq 'DynamicList') { $target = $s; break } }
- if ($null -eq $target) { Fail "${c}: у '$name' нет настроек динамического списка" }
- $with = (Get-AttrProbe (New-DslSpec ([ordered]@{ name = $name; title = ''; settings = $v })) $ind).SelectSingleNode("f:Settings", $nsMgr)
- $without = (Get-AttrProbe (New-DslSpec ([ordered]@{ name = $name; title = ''; settings = [pscustomobject]@{ _ = $null } })) $ind).SelectSingleNode("f:Settings", $nsMgr)
- # Теги — по ключам (значение, равное умолчанию, тоже записывается) и всё, что проба меняет помимо
- # них; пользовательские настройки списка — только переданными частями
- $d = Get-ProbeDiff $without $with
- $tags = @()
- foreach ($k in $keys) { if ($script:dlKeyTags.ContainsKey($k)) { $tags += $script:dlKeyTags[$k] } }
- foreach ($t in $d.Tags) { if ($t -ne 'ListSettings' -or $keys -contains 'listSettings') { $tags += $t } }
- $tags = @($tags | Select-Object -Unique)
- $labels = @($tags)
- if ($tags.Count -gt 0) { Set-SectionTags $target $with $tags }
- if ($parts.Count -gt 0) {
- $tls = $target.SelectSingleNode("f:ListSettings", $nsMgr)
- $pls = $with.SelectSingleNode("f:ListSettings", $nsMgr)
- if ($null -eq $tls -or $null -eq (Get-FirstElementChild $tls)) {
- Set-SectionTags $target $with @('ListSettings')
- $labels += 'ListSettings'
- } else {
- $ci = Get-ChildIndent $tls
- foreach ($k in $parts) {
- $ln = $script:dlListParts[$k]
- foreach ($x in @($tls.SelectNodes("dcsset:$ln", $nsMgr))) { Remove-NodeWithWs $x }
- foreach ($pn in @($pls.SelectNodes("dcsset:$ln", $nsMgr))) {
- $old = Get-NodeIndent $pn
- $pls.RemoveChild($pn) | Out-Null
- Insert-SectionChild $tls $pn $ci
- Set-SubtreeIndent $pn $old $ci
- }
- $labels += "ListSettings/$ln"
.claude/skills/help-add/scripts/add-help.ps1 · Bundled script · 352 lines
- # help-add v1.26 — Add built-in help to 1C object (+write_xml_file/write_utf8_bom: общий эталон записи)
- # Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
- param(
- [Parameter(Mandatory)]
- [string]$ObjectName,
- [string]$Lang = "ru",
- [string]$SrcDir = "src"
- )
- $ErrorActionPreference = "Stop"
- [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
- [Console]::InputEncoding = [System.Text.Encoding]::UTF8
- # --- Support guard (Ext/ParentConfigurations.bin) ---
- # See docs/1c-support-state-spec.md. Blocks edits of vendor objects "на замке" /
- # read-only configs unless allowed. Trigger = bin present; reaction from
- # .v8-project.json editingAllowedCheck (deny|warn|off, default deny). Never
- # throws — guard errors degrade to allow.
- function Get-RootUuid([string]$xmlPath) {
- if (-not (Test-Path $xmlPath)) { return $null }
- try {
- [xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
- $el = $mx.DocumentElement.FirstChild
- while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
- if ($el) { $u = $el.GetAttribute("uuid"); if ($u) { return $u } }
- } catch {}
- return $null
- }
- function Test-ExternalObjectRoot([string]$xmlPath) {
- if (-not (Test-Path $xmlPath)) { return $false }
- try {
- [xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
- $el = $mx.DocumentElement.FirstChild
- while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
- if ($el) { return @('ExternalDataProcessor','ExternalReport') -contains $el.LocalName }
- } catch {}
- return $false
- }
- function Find-V8Project([string]$startDir) {
- $d = $startDir
- for ($i = 0; $i -lt 20 -and $d; $i++) {
- $pj = Join-Path $d ".v8-project.json"
- if (Test-Path $pj) { return $pj }
- $parent = [System.IO.Path]::GetDirectoryName($d)
- if ($parent -eq $d) { break }
- $d = $parent
- }
- return $null
- }
- function Get-EditMode([string]$cfgDir) {
- try {
- $pj = Find-V8Project (Get-Location).ProviderPath
- if (-not $pj) { $pj = Find-V8Project ([System.IO.Path]::GetFullPath($cfgDir)) }
- if (-not $pj) { return 'deny' }
- # UTF-8 явно: PS 5.1 читает файл без BOM как ANSI, и configSrc с кириллицей не совпал бы
- $proj = Get-Content -Raw -Encoding UTF8 $pj | ConvertFrom-Json
- # configSrc — от каталога .v8-project.json, а не от рабочего каталога: иначе из подкаталога
- # проекта база не сопоставляется и берётся правило проекта.
- $projDir = [System.IO.Path]::GetDirectoryName($pj)
- $cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
- if ($proj.databases) {
- foreach ($db in $proj.databases) {
- if ($db.configSrc) {
- $src = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($projDir, $db.configSrc)).TrimEnd('\', '/')
- if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
- if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
- }
- }
- }
- }
- if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
- return 'deny'
- } catch { return 'deny' }
- }
- function Assert-EditAllowed([string]$targetPath, [string]$require) {
- try {
- $rp = $targetPath
- try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).ProviderPath } catch {}
- # Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
- if (Test-ExternalObjectRoot $rp) { return }
- $elemUuid = Get-RootUuid $rp
- $cfgDir = $null; $binPath = $null
- $d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
- for ($i = 0; $i -lt 12 -and $d; $i++) {
- if (Test-ExternalObjectRoot "$d.xml") { return }
- if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
- if (-not $cfgDir) {
- $cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
- if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
- }
- if ($elemUuid -and $cfgDir) { break }
- $parent = [System.IO.Path]::GetDirectoryName($d)
- if ($parent -eq $d) { break }
- $d = $parent
- }
- # New object (no element file): fall back to config root uuid.
- if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
- if (-not $binPath -or -not (Test-Path $binPath)) { return }
- $bytes = [System.IO.File]::ReadAllBytes($binPath)
- if ($bytes.Length -le 32) { return }
- $start = 0
- if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
- $text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
- $hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
- if (-not $hm.Success) { return }
- $G = [int]$hm.Groups[1].Value
- $K = [int]$hm.Groups[2].Value
- if ($K -eq 0) { return }
- $best = $null
- if ($elemUuid) {
- $u = [regex]::Escape($elemUuid.ToLower())
- foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
- $f1 = [int]$m.Groups[1].Value
- if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
- }
- }
- $blocked = $false; $code = ""; $reason = ""
- if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
- elseif ($require -eq 'removed') {
- if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
- }
- else {
- if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
- }
- if (-not $blocked) { return }
- $mode = Get-EditMode $cfgDir
- if ($mode -eq 'off') { return }
- # Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
- # latter throws and would be swallowed by this function's own catch.
- if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
- $head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
- $cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
- $offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
- if ($code -eq "capability-off") {
- $state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
- $fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
- } elseif ($code -eq "not-removed") {
- $state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
- $fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
- } else {
- $state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
- $fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
- }
- [Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
- exit 1
- } catch { return }
- }
- # --- Detect format version ---
- function Detect-FormatVersion([string]$dir) {
- $d = $dir
- while ($d) {
- # Автономная внешняя обработка/отчёт: своего Configuration.xml у неё нет, версию несёт
- # корень самой обработки. Без этого форма и макет внутри обработки 2.21 писались бы 2.17.
- $extPath = "$d.xml"
- if (Test-Path $extPath) {
- $extText = [System.IO.File]::ReadAllText($extPath, [System.Text.Encoding]::UTF8)
- $extHead = $extText.Substring(0, [Math]::Min(2000, $extText.Length))
- if ($extHead -match '<(ExternalDataProcessor|ExternalReport)[ >]' -and $extHead -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
- }
- $cfgPath = Join-Path $d "Configuration.xml"
- if (Test-Path $cfgPath) {
- $cfgText = [System.IO.File]::ReadAllText($cfgPath, [System.Text.Encoding]::UTF8)
- # Длину среза берём по СТРОКЕ, а не по размеру файла: размер в БАЙТАХ, Substring считает
- # СИМВОЛЫ, и на кириллице байт больше — короткий Configuration.xml ронял навык исключением.
- $head = $cfgText.Substring(0, [Math]::Min(2000, $cfgText.Length))
- if ($head -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
- }
- $parent = Split-Path $d -Parent
- if ($parent -eq $d) { break }
- $d = $parent
- }
- return "2.17"
- }
- # --- Проверки ---
- $objectDir = Join-Path $SrcDir $ObjectName
- $extDir = Join-Path $objectDir "Ext"
- if (-not (Test-Path $extDir)) {
- Write-Error "Каталог объекта не найден: $extDir. Проверьте путь ObjectName (например Catalogs/МойСправочник)."
- exit 1
- }
- # Справка — тело объекта, а тело и дескриптор платформа загружает только в одной версии формата.
- # Поэтому версию берём прежде всего из дескриптора <объект>.xml (объект может быть старше выгрузки после
- # мержа веток), и только без него — подъёмом от каталога объекта. Не от SrcDir: у внешней обработки
- # корень <Имя>.xml лежит В SrcDir, подъём его не видел, и справка обработки 2.20 писалась 2.17.
- $formatVersion = $null
- # Resolve-Path сохраняет завершающий разделитель («Обр/» → «…\Обр\»): без обрезки искался бы «…\Обр\.xml».
- $objectFull = (Resolve-Path $objectDir).ProviderPath.TrimEnd('\', '/')
- $ownerXml = "$objectFull.xml"
- if (Test-Path $ownerXml) {
- $ownerHead = [System.IO.File]::ReadAllText($ownerXml, [System.Text.Encoding]::UTF8)
- $ownerHead = $ownerHead.Substring(0, [Math]::Min(2000, $ownerHead.Length))
- if ($ownerHead -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { $formatVersion = $Matches[1] }
- }
- if (-not $formatVersion) { $formatVersion = Detect-FormatVersion $objectFull }
- # Код языка идёт и в текст XML, и в имя файла страницы, поэтому проверяем его до записи:
- # пустое значение дало бы файл «.html» и пустой <Page></Page>, разделитель пути — запись мимо
- # каталога страниц, а зарезервированное имя устройства (nul, con, prn, aux, com1…, lpt1…) на
- # Windows уводит запись в само устройство. Все отказы платформы были бы тихими.
- #
- # Якоря `\A…\z`, а не `^…$`: последние в обоих языках допускают перевод строки в конце.
- #
- # Копия этой функции есть в template-add (навыки автономны, формат «дескриптор + страница»
- # у них общий). Держать копии одинаковыми — сознательно; за дрейфом следит check-inline-drift.
- function Test-LangCode([string]$code) {
- if ($code -notmatch '\A[A-Za-z0-9_-]+\z') { return $false }
- if ($code -match '\A(?i)(con|prn|aux|nul|com[1-9]|lpt[1-9])\z') { return $false }
- return $true
- }
- if (-not (Test-LangCode $Lang)) {
- Write-Error "Недопустимый код языка: '$Lang'`nОжидается код вида ru, en (буквы, цифры, дефис, подчёркивание; имена устройств Windows недопустимы)"
- exit 1
- }
- $helpXmlPath = Join-Path $extDir "Help.xml"
- if (Test-Path $helpXmlPath) {
- Write-Error "Справка уже существует: $helpXmlPath"
- exit 1
- }
- Assert-EditAllowed $objectDir 'editable'
- # --- Кодировка ---
- $encBom = New-Object System.Text.UTF8Encoding($true)
- # --- 1. Help.xml ---
- $helpXml = @"
- <?xml version="1.0" encoding="UTF-8"?>
- <Help xmlns="http://v8.1c.ru/8.3/xcf/extrnprops" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="$formatVersion">
- <Page>$Lang</Page>
- </Help>
- "@
- # XML в каноне выгрузки Конфигуратора: CRLF в разделителях, без перевода в конце.
- #
- # Копия этой функции есть в каждом навыке-эмиттере (навыки автономны). Держать
- # копии одинаковыми — сознательно: разошедшиеся копии сводят на нет весь смысл.
- #
- # HTML-страница сюда НЕ идёт — платформа хранит её с LF.
- function Write-XmlFile([string]$path, [string]$text, $encoding) {
- $t = ($text -replace "`r`n", "`n") -replace "`n", "`r`n"
- [System.IO.File]::WriteAllText($path, $t.TrimEnd("`r", "`n"), $encoding)
- }
- Write-XmlFile $helpXmlPath $helpXml $encBom
- # --- 2. Help/<lang>.html ---
- $helpDir = Join-Path $extDir "Help"
- New-Item -ItemType Directory -Path $helpDir -Force | Out-Null
- $helpHtmlPath = Join-Path $helpDir "$Lang.html"
- $helpHtml = @"
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
- <link rel="stylesheet" type="text/css" href="v8help://service_book/service_style"></link>
- </head>
- <body>
- <h1>$ObjectName</h1>
- <p>Описание.</p>
- </body>
- </html>
- "@
- # Файл страницы НЕ перезаписываем: отказ выше смотрит только на Help.xml, а страница может
- # пережить его (удалённый дескриптор, частичная выгрузка, справка, сделанная руками) — и тогда
- # безусловная запись молча стирала бы текст справки с кодом 0.
- if (Test-Path $helpHtmlPath) {
- Write-Host "[WARN] Страница $Lang.html уже лежала на диске — содержимое сохранено, создан только дескриптор."
- } else {
- [System.IO.File]::WriteAllText($helpHtmlPath, $helpHtml, $encBom)
- }
- # --- 3. Проверка IncludeHelpInContents в метаданных форм ---
- $formsDir = Join-Path $objectDir "Forms"
- if (Test-Path $formsDir) {
- $formMetaFiles = Get-ChildItem -Path $formsDir -Filter "*.xml" -File
- foreach ($formMeta in $formMetaFiles) {
- $xmlDoc = New-Object System.Xml.XmlDocument
- $xmlDoc.PreserveWhitespace = $true
- $xmlDoc.Load($formMeta.FullName)
- $nsMgr = New-Object System.Xml.XmlNamespaceManager($xmlDoc.NameTable)
- $nsMgr.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
- $includeHelp = $xmlDoc.SelectSingleNode("//md:IncludeHelpInContents", $nsMgr)
- if (-not $includeHelp) {
- # Добавить после <FormType>
- $formType = $xmlDoc.SelectSingleNode("//md:FormType", $nsMgr)
- if ($formType) {
- $newElem = $xmlDoc.CreateElement("IncludeHelpInContents", "http://v8.1c.ru/8.3/MDClasses")
- $newElem.InnerText = "false"
- $parent = $formType.ParentNode
- $nextSibling = $formType.NextSibling
- # Вставить перенос + табуляцию + элемент
- $ws = $xmlDoc.CreateWhitespace("`n`t`t`t")
- if ($nextSibling) {
- $parent.InsertBefore($ws, $nextSibling) | Out-Null
- $parent.InsertBefore($newElem, $ws) | Out-Null
- } else {
- $parent.AppendChild($ws) | Out-Null
- $parent.AppendChild($newElem) | Out-Null
- }
- $settings = New-Object System.Xml.XmlWriterSettings
- $settings.Encoding = $encBom
- $settings.Indent = $false
- $settings.NewLineHandling = [System.Xml.NewLineHandling]::None
- # Через MemoryStream, а не прямо в файл: нужен шаг пост-обработки строки.
- $memStream = New-Object System.IO.MemoryStream
- $writer = [System.Xml.XmlWriter]::Create($memStream, $settings)
- $xmlDoc.Save($writer)
- $writer.Flush(); $writer.Close()
- $xmlText = [System.Text.Encoding]::UTF8.GetString($memStream.ToArray())
- $memStream.Close()
- if ($xmlText.Length -gt 0 -and $xmlText[0] -eq [char]0xFEFF) { $xmlText = $xmlText.Substring(1) }
- $xmlText = $xmlText.Replace('encoding="utf-8"', 'encoding="UTF-8"')
- # Пустой элемент: XmlWriter отдаёт `<a />`, Конфигуратор пишет `<a/>`. Внутри
- # CDATA/комментария ` />` может быть содержимым (там `>` не экранируется),
- # поэтому они идут первыми ветками альтернации и возвращаются как есть.
- $xmlText = [regex]::Replace($xmlText, '(?s)<!\[CDATA\[.*?\]\]>|<!--.*?-->|(?<=\S) />', { param($m) if ($m.Value -eq ' />') { '/>' } else { $m.Value } })
- # Целевой перевод строки: стиль файла-назначения — правка наследует его (#44/#46/#47),
- # новый файл получает канон выгрузки CRLF. Зеркало _detect_xml_style в py-порту.
- $targetEol = if ((Test-Path -LiteralPath $formMeta.FullName) -and ([System.IO.File]::ReadAllText($formMeta.FullName) -notmatch "`r`n")) { "`n" } else { "`r`n" }
- $xmlText = ($xmlText -replace "`r`n", "`n") -replace "`n", $targetEol
- [System.IO.File]::WriteAllText($formMeta.FullName, $xmlText, $encBom)
- Write-Host " IncludeHelpInContents добавлен: $($formMeta.Name)"
- }
- }
- }
- }
- Write-Host "[OK] Создана справка: $ObjectName"
- Write-Host " Метаданные: $helpXmlPath"
- Write-Host " Страница: $helpHtmlPath"
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.