Skip to content
Back to search

cc-1c-skills

MarketplaceWorks with Claude CodeGitHub

Маркетплейс навыков для разработки на платформе 1С:Предприятие

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/nikolay-shirokov--cc-1c-skills/badge.svg)](/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.

  1. {
  2. "$schema": "https://json.schemastore.org/claude-code-marketplace-manifest.json",
  3. "name": "cc-1c-skills",
  4. "description": "Маркетплейс навыков для разработки на платформе 1С:Предприятие",
  5. "owner": {
  6. "name": "Nikolay Shirokov"
  7. },
  8. "plugins": [
  9. {
  10. "name": "1c-skills",
  11. "source": "./",
  12. "description": "[PowerShell] Навыки для разработки на 1С:Предприятие 8.3 — абстракции над XML-форматами и CLI конфигуратора, плюс глаза и руки для тестирования через веб-клиент."
  13. },
  14. {
  15. "name": "1c-skills-py",
  16. "source": {
  17. "source": "github",
  18. "repo": "Nikolay-Shirokov/cc-1c-skills",
  19. "ref": "port-claude-code-py"
  20. },
  21. "description": "[Python] То же — для Linux/Mac или когда PowerShell недоступен."
  22. }
  23. ]
  24. }
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.

  1. # 1C Skills for Claude Code
  2. > **Проект живой, активно развивается** — добавляются новые возможности, отлавливаются и исправляются баги, производится оптимизация. Следите за обновлениями.
  3. Набор навыков для AI-агентов (в первую очередь для [Claude Code](https://docs.anthropic.com/en/docs/claude-code/skills)), помогающий охватить полный цикл разработки на платформе 1С:Предприятие 8.3 — от создания конфигураций, расширений, внешних обработок и отчётов до загрузки изменений в информационную базу, обновления, запуска, публикации на веб-сервере (портативная версия Apache), тестирования через веб-клиент и записи видеоинструкций.
  4. Навыки дают модели готовые абстракции над XML-форматами и CLI конфигуратора — чтобы работать с сутью задачи, а не с деталями реализации. А веб-тестирование даёт ей глаза и руки для взаимодействия с интерфейсом 1С.
  5. ## Версии навыков для разных платформ
  6. > **PS** — версия со скриптами на PowerShell (стандартная, для Windows). **Py** — версия со скриптами на Python (если PowerShell не подходит). Можно начать с **PS** — это основной вариант.
  7. **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) — [Другие платформы →](#поддерживаемые-платформы)
  8. ## Быстрый старт
  9. Скопируйте каталог `.claude/skills/` из этого репозитория в корень вашего проекта. Навыки станут доступны при запуске Claude Code из этого каталога.
  10. ```
  11. МойПроект/
  12. ├── .claude/skills/ ← скопировать сюда
  13. └── ...
  14. ```
  15. Или установите как плагин Claude Code:
  16. ```
  17. /plugin marketplace add https://github.com/Nikolay-Shirokov/cc-1c-skills
  18. /plugin install 1c-skills@cc-1c-skills # PowerShell (Windows)
  19. /plugin install 1c-skills-py@cc-1c-skills # Python (Linux/Mac или если PS недоступен)
  20. ```
  21. Или установите как плагин OpenAI Codex:
  22. ```
  23. codex plugin marketplace add Nikolay-Shirokov/cc-1c-skills
  24. codex /plugins # выберите 1c-skills (PowerShell) или 1c-skills-py (Python) и нажмите Install
  25. ```
  26. Или используйте скрипт установки:
  27. ```bash
  28. git clone https://github.com/Nikolay-Shirokov/cc-1c-skills.git tools/cc-1c-skills
  29. # Копия (рекомендуется): независимая копия, обновление — повторный запуск
  30. python tools/cc-1c-skills/scripts/switch.py claude-code --project-dir .
  31. # Ссылки (экспериментально): обновления подхватываются через git pull
  32. python tools/cc-1c-skills/scripts/switch.py claude-code --project-dir . --link
  33. # Интерактивный режим: пошаговый выбор платформы, способа установки и рантайма
  34. python tools/cc-1c-skills/scripts/switch.py
  35. ```
  36. Не обязательно запоминать команды и параметры — просто опишите задачу своими словами, Claude сам подберёт нужные навыки. Слеш-команды (например `/epf-init МояОбработка`) тоже работают — для точного контроля.
  37. ## Группы навыков
  38. | Группа | Навыки | Описание | Гайд |
  39. |--------|--------|----------|------|
  40. | Внешние обработки (EPF) | 7 навыков `/epf-*` | Создание, сборка, разборка, валидация обработок из XML-исходников | [Подробнее](docs/epf-guide.md) |
  41. | Внешние отчёты (ERF) | 4 навыка `/erf-*` | Создание, сборка, разборка, валидация внешних отчётов | [Подробнее](docs/epf-guide.md#внешние-отчёты-erf) |
  42. | Универсальные операции | `/template-add`, `/template-remove`, `/help-add`, `/form-remove` | Добавление/удаление макетов, форм, справки для любых объектов | [Подробнее](docs/epf-guide.md#универсальные-навыки) |
  43. | Табличный документ (MXL) | 4 навыка `/mxl-*` | Анализ, создание, компиляция макетов печатных форм | [Подробнее](docs/mxl-guide.md) |
  44. | Управляемые формы (Form) | 5 навыков `/form-*` | Создание, анализ, генерация, модификация, валидация управляемых форм | [Подробнее](docs/form-guide.md) |
  45. | Роли (Role) | 3 навыка `/role-*` | Анализ прав роли, создание из JSON DSL, валидация | [Подробнее](docs/role-guide.md) |
  46. | Схема компоновки (СКД) | 4 навыка `/skd-*` | Анализ, генерация из JSON DSL, точечное редактирование, валидация схем компоновки данных | [Подробнее](docs/skd-guide.md) |
  47. | Метаданные конфигурации | 5 навыков `/meta-*` | Создание, анализ, редактирование, удаление, валидация объектов метаданных (23 типа) | [Подробнее](docs/meta-guide.md) |
  48. | Корневая конфигурация | 4 навыка `/cf-*` | Создание, анализ, редактирование, валидация корневых файлов конфигурации | [Подробнее](docs/cf-guide.md) |
  49. | Расширения (CFE) | 5 навыков `/cfe-*` | Создание, заимствование, перехват методов, валидация, анализ расширений | [Подробнее](docs/cfe-guide.md) |
  50. | Подсистемы (Subsystem) | 4 навыка `/subsystem-*` | Анализ, создание, редактирование, валидация подсистем конфигурации | [Подробнее](docs/subsystem-guide.md) |
  51. | Командный интерфейс (CI) | 2 навыка `/interface-*` | Редактирование и валидация CommandInterface.xml подсистем | [Подробнее](docs/subsystem-guide.md) |
  52. | Пакеты XDTO | 5 навыков `/xdto-*` | Анализ, создание из XML-схемы, выгрузка в схему, точечное редактирование, валидация пакетов XDTO | [Подробнее](docs/xdto-guide.md) |
  53. | Базы данных (DB) | 13 навыков `/db-*` | Создание баз, загрузка/выгрузка конфигураций, обновление БД, загрузка из Git, хранилище конфигурации, управление расширениями в базе | [Подробнее](docs/db-guide.md) |
  54. | Веб-публикация (Web) | 4 навыка `/web-*` | Публикация баз через Apache, статус, остановка, удаление публикаций | [Подробнее](docs/web-guide.md) |
  55. | Тестирование (Web) | `/web-test` | Взаимодействие с веб-клиентом 1С — навигация, формы, таблицы, отчёты, тестирование | [Подробнее](docs/web-test-guide.md) |
  56. | Запись видео (Web) | `/web-test` | Запись видеоинструкций с субтитрами, подсветкой и TTS-озвучкой | [Подробнее](docs/web-test-recording-guide.md) |
  57. | Регресс прикладного решения (Web) | `/web-test` | Автоматический регресс конфигурации: тесты, проверки, отчёты, прогон после правок | [Подробнее](docs/web-test-regression-guide.md) |
  58. | Утилиты | `/img-grid`, `/v8-xsd-fetch` | Сетка на изображении для определения пропорций колонок; загрузка XSD-схем платформы для проверки выгрузок | [Подробнее](docs/v8-project-guide.md#xsdpath--xsd-схемы-платформы) |
  59. ## Требования
  60. - **Windows** с PowerShell 5.1+ (входит в Windows) — рантайм по умолчанию
  61. - **1С:Предприятие 8.3** — для сборки/разборки EPF/ERF (навыки генерации XML работают без платформы)
  62. - **Node.js 18+** — для `/web-test` (тестирование через браузер)
  63. <a id="поддерживаемые-платформы"></a>
  64. ### Другие AI-платформы
  65. Навыки построены на открытом стандарте [Agent Skills](https://agentskills.io/specification) и совместимы с любой платформой, поддерживающей этот формат. Самый быстрый путь — скачать готовую сборку под нужную платформу из ветки ниже (**Code → Download ZIP**) и распаковать в корень своего проекта.
  66. #### Поддерживаемые платформы
  67. | Платформа | Целевой каталог | PowerShell | Python |
  68. |-----------|----------------|------------|--------|
  69. | 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) |
  70. | 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) |
  71. | 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) |
  72. | 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) |
  73. | 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) |
  74. | 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) |
  75. | 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) |
  76. | 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) |
  77. | 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) |
  78. | 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) |
  79. | 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) |
  80. | 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) |
  81. | 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) |
  82. | 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) |
  83. Готовые ветки `port-*` пересобираются автоматически на каждое изменение в навыках. Если нужна свежая сборка прямо сейчас — соберите [локально через `switch.py`](#альтернативный-способ--собрать-локально-через-switchpy).
  84. Некоторые платформы (Augment, Cline, VS Code/Copilot) также сканируют `.claude/skills/` как fallback — для них достаточно `main`.
  85. <a id="альтернативный-способ--собрать-локально-через-switchpy"></a>
  86. #### Альтернативный способ — собрать локально через `switch.py`
  87. Если нужна свежая сборка под свою платформу (или платформа ещё не в матрице port-веток):
  88. ```bash
  89. python scripts/switch.py # интерактивный режим
  90. python scripts/switch.py cursor # скопировать навыки для Cursor
  91. python scripts/switch.py cursor --runtime python # Cursor + Python-рантайм
  92. python scripts/switch.py claude-code --project-dir /my/proj # установить копию в проект
  93. python scripts/switch.py claude-code --project-dir /my/proj --link # ссылки вместо копий
  94. python scripts/switch.py --undo cursor # удалить копию / ссылки
  95. ```
  96. Если репозиторий склонирован внутрь проекта (например, в `tools/cc-1c-skills`), используйте `--project-dir` для установки навыков в целевой проект.
  97. **Сторонние навыки не трогаются.** В каталог навыков платформы `switch.py` кладёт манифест `.cc-1c-skills.json` со списком установленного. При обновлении и `--undo` удаляются только навыки набора: те, что есть в манифесте или в текущей версии. Чужие навыки в том же каталоге остаются на месте. Каталог с чужим навыком, имя которого совпадает с навыком набора, будет перезаписан.
  98. **Ссылки vs копии.** Флаг `--link` (экспериментальный) создаёт directory junction (Windows) или symlink (Linux/Mac) вместо копирования файлов. Обновления в источнике автоматически подхватываются во всех подключённых проектах — достаточно `git pull`. Ссылки доступны только для платформы Claude Code (для остальных платформ требуется перезапись путей в SKILL.md). Удаление ссылок: `--undo` — безопасно удаляет только ссылки, не трогая источник.
  99. > ⚠ **Известные ограничения `--link`:** Node.js резолвит `__dirname` через junction к реальному пути источника, а не к каталогу проекта. Это может приводить к тому, что навыки с Node.js-скриптами (например, `/web-test`) будут записывать файлы в каталог репозитория навыков вместо каталога проекта. При возникновении проблем переключитесь на копирование (без `--link`).
  100. Автоактивация — основной режим: просто опишите задачу своими словами, ассистент сам подберёт нужный навык по `description` в SKILL.md. Слеш-команды (например `/epf-init`) — для точного контроля, когда нужно вызвать конкретный навык.
  101. ### Переключение рантайма (PowerShell ↔ Python)
  102. На Windows рекомендуется PS1-рантайм (по умолчанию). Python-порты — для **Linux/Mac** или если PowerShell недоступен. PS1-скрипты — мастер-версия; Python-порты производные (см. [Python Porting Guide](docs/python-porting-guide.md)).
  103. ```bash
  104. python scripts/switch.py --runtime python # переключить на Python
  105. python scripts/switch.py --runtime powershell # вернуть на PowerShell
  106. ```
  107. Дополнительные зависимости Python-рантайма (Python 3.9+), одной командой — `pip install -r requirements.txt`:
  108. - `lxml>=4.9.0` — для навыков, работающих с DOM (edit/validate/info)
  109. - `Pillow>=10.0.0` — для `/img-grid` (чтение изображений и наложение сетки)
  110. - `psutil>=5.9.0` — для web-навыков (управление Apache)
  111. Параметры скриптов идентичны для обоих рантаймов — переключение меняет только интерпретатор в вызовах. Подробнее: [Python Porting Guide](docs/python-porting-guide.md).
  112. ## Спецификации
  113. Полный индекс с оглавлением по всем 44 типам объектов: **[Сводный индекс спецификаций](docs/1c-specs-index.md)**
  114. - [XML-формат выгрузки обработок](docs/1c-epf-spec.md) — структура XML-файлов, namespace, элементы форм
  115. - [XML-формат внешних отчётов](docs/1c-erf-spec.md) — отличия ERF от EPF, Properties, MainDataCompositionSchema
  116. - [Управляемая форма](docs/1c-form-spec.md) — Form.xml, элементы, команды, реквизиты
  117. - [Встроенная справка](docs/1c-help-spec.md) — Help.xml, HTML-страницы, кнопка справки на форме
  118. - [Пакетный режим конфигуратора 1С](docs/build-spec.md) — команды `1cv8.exe`, DESIGNER, ENTERPRISE, CREATEINFOBASE
  119. - [Табличный документ (MXL)](docs/1c-spreadsheet-spec.md) — XML-формат SpreadsheetDocument, совместимость версий
  120. - [MXL DSL](docs/mxl-dsl-spec.md) — JSON-формат описания макета для `/mxl-compile` и `/mxl-decompile`: структура, оформление, полный перечень свойств стиля
  121. - [Form DSL](docs/form-dsl-spec.md) — JSON-формат описания формы для `/form-compile`
  122. - [Роли (Rights.xml)](docs/1c-role-spec.md) — XML-формат прав роли, типы объектов, RLS
  123. - [Role DSL](docs/role-dsl-spec.md) — JSON-формат описания ролей для `/role-compile`
  124. - [Схема компоновки данных (DCS)](docs/1c-dcs-spec.md) — XML-формат DataCompositionSchema, 930 схем проанализировано
  125. - [SKD DSL](docs/skd-dsl-spec.md) — JSON-формат описания СКД для `/skd-compile`
  126. - [Объекты конфигурации](docs/1c-config-objects-spec.md) — XML-формат объектов метаданных конфигурации (23 типа)
  127. - [Подсистемы и командный интерфейс](docs/1c-subsystem-spec.md) — XML-формат подсистем, CommandInterface.xml, секции видимости/размещения/порядка
  128. - [Корневая конфигурация](docs/1c-configuration-spec.md) — XML-формат Configuration.xml, ConfigDumpInfo.xml, Languages/, 44 типа ChildObjects
  129. - [Расширения конфигурации (CFE)](docs/1c-extension-spec.md) — XML-формат выгрузки расширений конфигурации
  130. - [Веб-публикация 1С](docs/web-spec.md) — VRD, httpd.conf, wsap24.dll, portable Apache
  131. ## Структура репозитория
  132. ```
  133. .claude/skills/ # Навыки Claude Code
  134. ├── epf-init/ # Создание обработки
  135. ├── epf-build/ # Сборка EPF
  136. ├── epf-dump/ # Разборка EPF
  137. ├── epf-bsp-init/ # Регистрация БСП
  138. ├── epf-bsp-add-command/ # Команда БСП
  139. ├── epf-validate/ # Валидация обработки
  140. ├── erf-init/ # Создание внешнего отчёта
  141. ├── erf-build/ # Сборка ERF
  142. ├── erf-dump/ # Разборка ERF
  143. ├── erf-validate/ # Валидация отчёта
  144. ├── template-add/ # Добавление макета (универсальный)
  145. ├── template-remove/ # Удаление макета (универсальный)
  146. ├── form-add/ # Добавление формы (универсальный)
  147. ├── form-remove/ # Удаление формы (универсальный)
  148. ├── help-add/ # Добавление справки (универсальный)
  149. ├── mxl-info/ # Анализ макета
  150. ├── mxl-validate/ # Валидация макета
  151. ├── mxl-compile/ # Компиляция макета из JSON
  152. ├── mxl-decompile/ # Декомпиляция макета в JSON
  153. ├── form-info/ # Анализ структуры управляемой формы
  154. ├── form-compile/ # Компиляция формы из JSON
  155. ├── form-validate/ # Валидация формы
  156. ├── form-edit/ # Правка формы: добавление, перенос, изменение, удаление
  157. ├── role-info/ # Анализ прав роли
  158. ├── role-compile/ # Создание роли из JSON DSL
  159. ├── role-edit/ # Точечная правка прав существующей роли
  160. ├── role-validate/ # Валидация роли
  161. ├── skd-info/ # Анализ схемы компоновки данных
  162. ├── skd-compile/ # Компиляция СКД из JSON DSL
  163. ├── skd-edit/ # Точечное редактирование СКД (25 операций)
  164. ├── skd-validate/ # Валидация СКД
  165. ├── meta-info/ # Структура объекта метаданных
  166. ├── meta-compile/ # Создание объекта метаданных
  167. ├── meta-edit/ # Редактирование объекта метаданных
  168. ├── meta-remove/ # Удаление объекта метаданных
  169. ├── meta-validate/ # Валидация объекта метаданных
  170. ├── cf-info/ # Анализ структуры конфигурации
  171. ├── cf-init/ # Создание пустой конфигурации
  172. ├── cf-edit/ # Редактирование конфигурации
  173. ├── cf-validate/ # Валидация конфигурации
  174. ├── cfe-init/ # Создание расширения
  175. ├── cfe-borrow/ # Заимствование объектов
  176. ├── cfe-patch-method/ # Перехват методов
  177. ├── cfe-validate/ # Валидация расширения
  178. ├── cfe-diff/ # Анализ и сравнение
  179. ├── subsystem-info/ # Анализ структуры подсистемы
  180. ├── subsystem-compile/ # Создание подсистемы из JSON
  181. ├── subsystem-edit/ # Редактирование подсистемы
  182. ├── subsystem-validate/ # Валидация подсистемы
  183. ├── interface-edit/ # Редактирование CommandInterface.xml
  184. ├── interface-validate/ # Валидация CommandInterface.xml
  185. ├── db-list/ # Управление реестром баз данных
  186. ├── db-create/ # Создание информационной базы
  187. ├── db-dump-cf/ # Выгрузка конфигурации в CF
  188. ├── db-load-cf/ # Загрузка конфигурации из CF
  189. ├── db-dump-xml/ # Выгрузка конфигурации в XML
  190. ├── db-load-xml/ # Загрузка конфигурации из XML
  191. ├── db-dump-dt/ # Выгрузка информационной базы в DT
  192. ├── db-load-dt/ # Загрузка информационной базы из DT
  193. ├── db-update/ # Обновление конфигурации БД
  194. ├── db-run/ # Запуск 1С:Предприятие
  195. ├── db-load-git/ # Загрузка изменений из Git
  196. ├── db-repo/ # Хранилище конфигурации
  197. ├── db-cfe-admin/ # Расширения в базе: состав, проверки, свойства, удаление
  198. ├── web-publish/ # Публикация базы через Apache
  199. ├── web-info/ # Статус Apache и публикаций
  200. ├── web-stop/ # Остановка Apache
  201. ├── web-unpublish/ # Удаление публикации
  202. ├── web-test/ # Тестирование через веб-клиент 1С
  203. ├── img-grid/ # Сетка для анализа изображений
  204. └── v8-xsd-fetch/ # Загрузка XSD-схем платформы (.v8-xsd)
  205. scripts/
  206. └── switch.py # Переключение платформы и рантайма (13 платформ)
  207. docs/
  208. ├── epf-guide.md # Гайд: внешние обработки и отчёты
  209. ├── mxl-guide.md # Гайд: табличный документ
  210. ├── form-guide.md # Гайд: управляемые формы
  211. ├── role-guide.md # Гайд: роли
  212. ├── skd-guide.md # Гайд: схема компоновки данных
  213. ├── meta-guide.md # Гайд: объекты метаданных конфигурации
  214. ├── cf-guide.md # Гайд: корневые файлы конфигурации
  215. ├── cfe-guide.md # Гайд: расширения конфигурации (CFE)
  216. ├── subsystem-guide.md # Гайд: подсистемы и командный интерфейс
  217. ├── v8-project-guide.md # Гайд: конфигурация проекта (.v8-project.json)
  218. ├── db-guide.md # Гайд: базы данных 1С
  219. ├── web-guide.md # Гайд: веб-публикация через Apache
  220. ├── web-test-guide.md # Гайд: тестирование через веб-клиент
  221. ├── web-test-recording-guide.md # Гайд: запись видеоинструкций
  222. ├── web-test-regression-guide.md # Гайд: регресс прикладного решения
  223. ├── 1c-epf-spec.md # Спецификация XML-формата (EPF)
  224. ├── 1c-erf-spec.md # Спецификация XML-формата (ERF)
  225. ├── 1c-form-spec.md # Спецификация управляемых форм
  226. ├── 1c-help-spec.md # Спецификация встроенной справки
  227. ├── 1c-config-objects-spec.md # Спецификация объектов конфигурации
  228. ├── build-spec.md # Пакетный режим конфигуратора 1С
  229. ├── 1c-spreadsheet-spec.md # Спецификация табличного документа
  230. ├── mxl-dsl-spec.md # Спецификация MXL DSL
  231. ├── form-dsl-spec.md # Спецификация Form DSL
  232. ├── meta-dsl-spec.md # Спецификация Meta DSL
  233. ├── 1c-role-spec.md # Спецификация ролей (Rights.xml)
  234. ├── 1c-dcs-spec.md # Спецификация СКД (DataCompositionSchema)
  235. ├── skd-dsl-spec.md # Спецификация SKD DSL
  236. ├── role-dsl-spec.md # Спецификация Role DSL
  237. ├── 1c-extension-spec.md # Спецификация расширений конфигурации (CFE)
  238. ├── 1c-subsystem-spec.md # Спецификация подсистем и командного интерфейса
  239. ├── web-spec.md # Спецификация веб-публикации (VRD, httpd.conf, Apache)
  240. └── python-porting-guide.md # Руководство по Python-портам навыков
  241. ```
.claude/skills/cfe-borrow/scripts/cfe-borrow.ps1 · Bundled script · 5,270 lines
  1. # cfe-borrow v1.63 — Borrow objects from configuration into extension (CFE)
  2. # Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
  3. [CmdletBinding(PositionalBinding=$false)]
  4. param(
  5. [Parameter(Mandatory)][string]$ExtensionPath,
  6. [Parameter(Mandatory)][string]$ConfigPath,
  7. [string]$Object,
  8. [string]$BorrowMainAttribute,
  9. [string]$Module,
  10. [switch]$Check,
  11. [switch]$Actualize
  12. )
  13. $ErrorActionPreference = "Stop"
  14. [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
  15. function Info([string]$msg) { Write-Host "[INFO] $msg" }
  16. function Warn([string]$msg) { Write-Host "[WARN] $msg" }
  17. # Form data-binding tags (value = attribute path). A binding survives only if its root
  18. # attribute is borrowed into the form's <Attributes>; otherwise it must be stripped or the
  19. # platform rejects the form with "Неверный путь к данным" on load.
  20. # RowPictureDataPath тоже путь к данным («Объект.Товары.РасхождениеЗаказ», «Список.DefaultPicture»),
  21. # а не индекс картинки: эталон Конфигуратора сохраняет его с заимствованным основным реквизитом
  22. # и выбрасывает без него — то же правило, что у остальных путей.
  23. $script:formBindingDataTags = @('DataPath','TitleDataPath','FooterDataPath','HeaderDataPath','MultipleValueDataPath','MultipleValuePresentDataPath','RowPictureDataPath')
  24. # Picture-path binding tags (value = picture index path, never a data attribute) — always stripped in the skeleton.
  25. $script:formBindingPictureTags = @('MultipleValuePictureDataPath')
  26. # Пути ссылок параметров выбора, которые пришлось вырезать (для предупреждения в конце)
  27. $script:droppedLinks = @()
  28. # id основного реквизита в заимствованной форме — как у Конфигуратора
  29. $script:mainAttrId = "1000001"
  30. # Виды дочерних объектов, которые заимствуются в оболочку поимённо (табличные части — отдельно)
  31. $script:childObjectKinds = @('Attribute','Dimension','Resource','AddressingAttribute','AccountingFlag','ExtDimensionAccountingFlag')
  32. # Виды подобъектов в -Object (Тип.Имя.<Вид>.<Имя>). Признак учёта субконто идёт только вместе с
  33. # ТЧ видов субконто (свойства ExtDimensionTypes у оболочки) — по одному не заимствуется.
  34. $script:subObjectKinds = @('Attribute','TabularSection','Dimension','Resource','AddressingAttribute','AccountingFlag')
  35. # Своя колонка в заимствованной ТЧ: у этих видов — отказ UpdateDBCfg на любой платформе, у БП и
  36. # Задачи — ниже 8.3.25 (граница по версии платформы, не по режиму)
  37. $script:tsOwnColumnsBlocked = @('ChartOfCharacteristicTypes','ChartOfAccounts','ChartOfCalculationTypes')
  38. $script:tsOwnColumnsFromPlatform = @{ 'BusinessProcess' = '8.3.25'; 'Task' = '8.3.25' }
  39. # Прямые дети <Form>, которые в заимствованную форму не переносятся.
  40. # Структурные секции: AutoCommandBar и ChildItems забираются отдельно, остальные выбрасываются целиком.
  41. $script:formStructuralSections = @('Events','Attributes','Commands','Parameters','CommandInterface')
  42. # Свойства формы, значение которых — имя реквизита формы (реквизиты не заимствуются, ссылка повиснет).
  43. $script:formAttributeRefProps = @('ReportResult','DetailsData','VariantAppearance','GroupList')
  44. # Strip data-binding tags whose root attribute isn't borrowed.
  45. # $mainAttrName задан (BorrowMainAttribute): оставить привязки от его имени, остальные снять.
  46. # Пусто (скелет без основного реквизита): снять все. Картиночные пути снимаются всегда.
  47. function Strip-FormBindings {
  48. param([string]$xml, [string]$mainAttrName)
  49. foreach ($tag in $script:formBindingDataTags) {
  50. if ($mainAttrName) {
  51. # Оставить и «Список.Поле», и путь ровно на сам реквизит («Список» у таблицы формы)
  52. $root = [regex]::Escape($mainAttrName)
  53. $xml = [regex]::Replace($xml, "\s*<$tag>(?!$root(\.|<))[^<]*</$tag>", '')
  54. } else {
  55. $xml = [regex]::Replace($xml, "\s*<$tag>[^<]*</$tag>", '')
  56. }
  57. }
  58. foreach ($tag in $script:formBindingPictureTags) {
  59. $xml = [regex]::Replace($xml, "\s*<$tag>[^<]*</$tag>", '')
  60. }
  61. return $xml
  62. }
  63. # Сдвиг блока на уровень вглубь для <BaseForm>; $firstIndent — отступ первой строки.
  64. # Таб добавляется только в пробельные промежутки между тегами: строки продолжения многострочного
  65. # текста (<v8:content>, текст запроса) — часть значения. Со сдвигом снимок расходился с формой,
  66. # и Конфигуратор показывал такой текст изменённым в расширении. Пробельный промежуток между
  67. # открывающим и закрывающим тегом одного элемента — тоже значение, его не сдвигаем.
  68. function Get-BaseFormIndented {
  69. param([string]$xml, [string]$firstIndent)
  70. $parts = [regex]::Split($xml, '(<(?:[^>"'']|"[^"]*"|''[^'']*'')*>)')
  71. for ($i = 0; $i -lt $parts.Count; $i += 2) {
  72. $seg = $parts[$i]
  73. if (-not $seg.Contains("`n") -or $seg.Trim()) { continue }
  74. $prevTag = if ($i -gt 0) { $parts[$i - 1] } else { '' }
  75. $nextTag = if ($i + 1 -lt $parts.Count) { $parts[$i + 1] } else { '' }
  76. $m = [regex]::Match($prevTag, '^<([\w:.-]+)[^>]*(?<!/)>$')
  77. if ($m.Success -and $nextTag -ceq "</$($m.Groups[1].Value)>") { continue }
  78. $parts[$i] = $seg.Replace("`n", "`n`t")
  79. }
  80. return $firstIndent + ($parts -join '')
  81. }
  82. # Связи формы — параметров выбора (<ChoiceParameterLinks>/<xr:Link>) и по типу (<TypeLink>) —
  83. # хранят путь в <xr:DataPath>, обычным стриппингом он не снимается. Путь — внутренняя ссылка
  84. # платформы: в выгрузке она пишет имя, а если имя в контексте формы не разрешается — код.
  85. # Текстовое имя в расширении разрешается, только если его корень объявлен в <Attributes> самой
  86. # заимствованной формы; иначе платформа отвергает загрузку — «Неверный путь к полю - X».
  87. # Конфигуратор поэтому пишет текст там, где он разрешается, и код — где нет.
  88. # Грамматика кода (оракул «код в форму конфигурации → загрузка → выгрузка → имя», 8.3.27; эталоны
  89. # Конфигуратора УТ и Issue66Example4-7, JR2433, JR2976, JR49904):
  90. # первый сегмент <id> — реквизит ИСХОДНОЙ формы (в расширении реквизиты
  91. # перенумерованы в 1000000+, ссылка остаётся в нумерации базы);
  92. # <id>:<CurrentData> — элемент-таблица исходной формы, её текущая строка;
  93. # дальше 0:<uuid> — реквизит/ТЧ/измерение/ресурс метаданных источника;
  94. # <id> — колонка реквизита формы;
  95. # <id>:<AddColumn> — колонка AdditionalColumns;
  96. # -<k> — стандартный реквизит, код по виду объекта ($script:stdFieldCodes).
  97. # В расширении платформа код обратно в имя не переводит, а висячий код грузит молча — ошибка
  98. # кодирования не упадёт, а тихо не сработает. Поэтому кодируется только измеренное; прочее
  99. # вырезается с предупреждением: связь — удобство подбора, без неё форма работает, с неверной
  100. # текстовой — не грузится вовсе.
  101. $script:linkCurrentData = '02023637-7868-4a5f-8576-835a76e0c9ba'
  102. $script:linkAddColumn = '5bdad865-f2c5-434b-8041-ba4aad3b6687'
  103. # Коды стандартных реквизитов — свой порядок у каждого вида (оракул 8.3.27; в XML объекта
  104. # полного списка нет). Незамеренное (-1, скрытые поля, колонки ExtDimensionTypes) — не кодируем.
  105. $script:stdFieldCodes = @{
  106. 'Catalog' = @{ Code=-2; Description=-3; Parent=-4; Owner=-5; IsFolder=-6; DeletionMark=-7; Ref=-8; DataVersion=-9; Predefined=-10; PredefinedDataName=-13 }
  107. 'Document' = @{ Number=-2; Date=-3; DeletionMark=-4; Ref=-5; DataVersion=-6; Posted=-7; RegisterRecords=-8 }
  108. 'ChartOfCharacteristicTypes' = @{ Ref=-2; DataVersion=-3; DeletionMark=-4; Predefined=-5; Parent=-6; IsFolder=-7; Code=-8; Description=-9; ValueType=-11; PredefinedDataName=-14 }
  109. '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 }
  110. 'ChartOfCalculationTypes' = @{ Code=-2; Description=-3; ActionPeriodIsBasic=-4; DeletionMark=-5; Ref=-6; DataVersion=-7; Predefined=-8; PredefinedDataName=-11; DisplacingCalculationTypes=-20; LeadingCalculationTypes=-30 }
  111. 'ExchangePlan' = @{ Code=-2; Description=-3; DeletionMark=-4; Ref=-6; DataVersion=-7; SentNo=-9; ReceivedNo=-10; ThisNode=-13; ExchangeDate=-14 }
  112. 'BusinessProcess' = @{ Number=-2; Date=-3; DeletionMark=-4; Ref=-5; DataVersion=-6; Completed=-7; HeadTask=-8; Started=-9 }
  113. 'Task' = @{ Number=-2; Date=-3; DeletionMark=-4; Ref=-5; DataVersion=-6; BusinessProcess=-7; RoutePoint=-8; Description=-9; Executed=-10 }
  114. 'InformationRegisterRecord' = @{ Period=-2; Recorder=-3; LineNumber=-4; Active=-5 }
  115. 'AccumulationRegisterRow' = @{ Period=-2; Recorder=-3; LineNumber=-4; Active=-5; RecordType=-9; SecondPeriod=-10; MinutePeriod=-11; HourPeriod=-12; DayPeriod=-13; WeekPeriod=-14; TenDaysPeriod=-15 }
  116. 'TabularSectionRow' = @{ LineNumber=-2 }
  117. }
  118. # Тип основного реквизита → вид для таблицы стандартных кодов (запись РС — сам реквизит,
  119. # набор записей РН — строка таблицы на нём)
  120. $script:mainAttrKinds = @{
  121. 'CatalogObject'='Catalog'; 'DocumentObject'='Document'; 'ChartOfCharacteristicTypesObject'='ChartOfCharacteristicTypes'
  122. 'ChartOfAccountsObject'='ChartOfAccounts'; 'ChartOfCalculationTypesObject'='ChartOfCalculationTypes'
  123. 'ExchangePlanObject'='ExchangePlan'; 'BusinessProcessObject'='BusinessProcess'; 'TaskObject'='Task'
  124. 'InformationRegisterRecordManager'='InformationRegisterRecord'; 'AccumulationRegisterRecordSet'='AccumulationRegisterRow'
  125. 'ConstantsSet'='ConstantsSet'
  126. }
  127. # Путь связи → текст (разрешается в расширении), код или $null (вырезать).
  128. # $ctx: MainName, MainId, MainBorrowed, MainKind, BorrowedNames (реквизиты объекта в расширении;
  129. # $null — все), AttrUuids (имя/«ТЧ.Реквизит» → uuid),
  130. # FormAttrIds, FormAttrCols («Реквизит.Колонка» → id), AddCols («<путь таблицы>.Колонка» → id),
  131. # Tables (имя элемента-таблицы → @{ Id; Path }).
  132. function Resolve-LinkDataPath {
  133. param([string]$path, $ctx)
  134. # Уже код (форма-источник сама из расширения, или висячая ссылка в типовой) — как есть
  135. if ($path -match '^-?\d') { return $path }
  136. $main = $ctx.MainName
  137. # Текущая строка элемента-таблицы
  138. $cd = [regex]::Match($path, '^Items\.([^.]+)\.CurrentData\.([^.]+)$')
  139. if ($cd.Success) {
  140. $tbl = $ctx.Tables[$cd.Groups[1].Value]
  141. $field = $cd.Groups[2].Value
  142. if (-not $tbl) { return $null }
  143. $tp = $tbl.Path
  144. $prefix = "$($tbl.Id):$($script:linkCurrentData)"
  145. if ($main -and ($tp -ceq $main -or $tp.StartsWith("$main.", [StringComparison]::Ordinal))) {
  146. # Таблица на основном реквизите: с заимствованным — текст разрешается (эталоны 7_1, УТ)
  147. if ($ctx.MainBorrowed) { return $path }
  148. if ($tp -ceq $main) {
  149. # Строки самого основного реквизита — набор записей регистра накопления
  150. if ($ctx.MainKind -ne 'AccumulationRegisterRow') { return $null }
  151. if ($ctx.AttrUuids.ContainsKey($field)) { return "$prefix/0:$($ctx.AttrUuids[$field])" }
  152. $code = $script:stdFieldCodes['AccumulationRegisterRow'][$field]
  153. if ($code) { return "$prefix/$code" }
  154. return $null
  155. }
  156. $ts = $tp.Substring($main.Length + 1)
  157. if ($ts.Contains('.')) { return $null }
  158. if ($ctx.AttrUuids.ContainsKey("$ts.$field")) { return "$prefix/0:$($ctx.AttrUuids["$ts.$field"])" }
  159. if ($ctx.AddCols.ContainsKey("$tp.$field")) { return "$prefix/$($ctx.AddCols["$tp.$field"]):$($script:linkAddColumn)" }
  160. $code = $script:stdFieldCodes['TabularSectionRow'][$field]
  161. if ($code) { return "$prefix/$code" }
  162. return $null
  163. }
  164. # Таблица на реквизите формы: реквизиты формы не заимствуются никогда — только код
  165. # (текст платформа отвергает и с заимствованным основным реквизитом, оракул 8.3.27)
  166. if ($ctx.FormAttrIds.ContainsKey($tp) -and $ctx.FormAttrCols.ContainsKey("$tp.$field")) {
  167. return "$prefix/$($ctx.FormAttrCols["$tp.$field"])"
  168. }
  169. return $null
  170. }
  171. # Путь от основного реквизита формы
  172. if ($main -and $path.StartsWith("$main.", [StringComparison]::Ordinal)) {
  173. $rest = $path.Substring($main.Length + 1)
  174. if ($ctx.MainBorrowed) {
  175. # Заимствованный реквизит объекта разрешается текстом и остаётся читаемым. Стандартное
  176. # поле («Объект.Owner», «Объект.Date») и реквизит, который в расширение не попал (в режиме
  177. # Form заимствуется только используемое формой) — нет: платформа отвергает «Неверный путь
  178. # к полю». Конфигуратор в обоих случаях ставит ссылку на сам основной реквизит (эталоны
  179. # Issue66Example7_1 и УТ Претензии.ФормаЭлементаСамообслуживание).
  180. $borrowed = $null -eq $ctx.BorrowedNames -or $ctx.BorrowedNames.ContainsKey($rest.Split('.')[0])
  181. if ($borrowed -and $ctx.AttrUuids.ContainsKey($rest)) { return $path }
  182. return $ctx.MainId
  183. }
  184. # Код пути на константу набора не измерен — такую связь вырезаем, а не кодируем наугад
  185. if ($ctx.MainKind -eq 'ConstantsSet') { return $null }
  186. $segs = $rest.Split('.')
  187. if ($segs.Count -eq 1) {
  188. if ($ctx.AttrUuids.ContainsKey($rest)) { return "$($ctx.MainId)/0:$($ctx.AttrUuids[$rest])" }
  189. $codes = if ($ctx.MainKind) { $script:stdFieldCodes[$ctx.MainKind] } else { $null }
  190. if ($codes -and $codes.ContainsKey($rest)) { return "$($ctx.MainId)/$($codes[$rest])" }
  191. return $null
  192. }
  193. if ($segs.Count -eq 2 -and $ctx.AttrUuids.ContainsKey($segs[0]) -and $ctx.AttrUuids.ContainsKey($rest)) {
  194. return "$($ctx.MainId)/0:$($ctx.AttrUuids[$segs[0]])/0:$($ctx.AttrUuids[$rest])"
  195. }
  196. return $null
  197. }
  198. # Путь от реквизита формы — только по id исходной формы, в обоих режимах
  199. $segs = $path.Split('.')
  200. if ($ctx.FormAttrIds.ContainsKey($segs[0])) {
  201. $attrId = $ctx.FormAttrIds[$segs[0]]
  202. if ($segs.Count -eq 1) { return $attrId }
  203. if ($segs.Count -eq 2 -and $ctx.FormAttrCols.ContainsKey($path)) { return "$attrId/$($ctx.FormAttrCols[$path])" }
  204. return $null
  205. }
  206. # Прочее: с заимствованным основным реквизитом текст может разрешиться, без него — нет
  207. if ($ctx.MainBorrowed) { return $path }
  208. return $null
  209. }
  210. # Путь в <xr:DataPath> блока связи → разрешённый; неразрешимый блок вырезается целиком
  211. function Rewrite-LinkBlocks {
  212. param([string]$xml, [string]$blockPattern, $ctx)
  213. return [regex]::Replace($xml, $blockPattern, {
  214. param($m)
  215. $link = $m.Value
  216. $dp = [regex]::Match($link, '<xr:DataPath[^>]*>([^<]+)</xr:DataPath>')
  217. if (-not $dp.Success) { return $link }
  218. $path = $dp.Groups[1].Value
  219. $resolved = Resolve-LinkDataPath $path $ctx
  220. if ($null -eq $resolved) {
  221. $script:droppedLinks += $path
  222. return ''
  223. }
  224. if ($resolved -ceq $path) { return $link }
  225. return $link.Substring(0, $dp.Groups[1].Index) + $resolved + $link.Substring($dp.Groups[1].Index + $dp.Groups[1].Length)
  226. })
  227. }
  228. function Rewrite-ChoiceParameterLinks {
  229. param([string]$xml, $ctx)
  230. if ($xml -notmatch '<ChoiceParameterLinks>') { return $xml }
  231. $xml = Rewrite-LinkBlocks $xml '(?s)\s*<xr:Link>.*?</xr:Link>' $ctx
  232. # Опустевший контейнер платформе не нужен
  233. $xml = [regex]::Replace($xml, '(?s)\s*<ChoiceParameterLinks>\s*</ChoiceParameterLinks>', '')
  234. return $xml
  235. }
  236. # Связь по типу — тот же путь и то же правило (эталоны УТ ВводОстатков.ФормаРасчетыМеждуОрганизациями:
  237. # без основного реквизита — код, с ним — текст)
  238. function Rewrite-TypeLinks {
  239. param([string]$xml, $ctx)
  240. if ($xml -notmatch '<TypeLink>') { return $xml }
  241. return Rewrite-LinkBlocks $xml '(?s)\s*<TypeLink>.*?</TypeLink>' $ctx
  242. }
  243. # Имена ПРЯМЫХ детей собственного <ChildObjects> объекта — для дедупа при повторном
  244. # заимствовании. Текстом это не снять: regex «первый <ChildObjects> до первого </ChildObjects>»
  245. # у объекта с табличными частями обрывается на закрытии первой ТЧ, забирает имена её колонок и
  246. # теряет то, что идёт после неё.
  247. function Get-OwnChildObjectNames {
  248. param([string]$objFile)
  249. $names = @{}
  250. if (-not (Test-Path -LiteralPath $objFile)) { return $names }
  251. $doc = New-Object System.Xml.XmlDocument
  252. $doc.PreserveWhitespace = $false
  253. try { $doc.Load($objFile) } catch { return $names }
  254. $objEl = $null
  255. foreach ($c in $doc.DocumentElement.ChildNodes) {
  256. if ($c.NodeType -eq 'Element') { $objEl = $c; break }
  257. }
  258. if (-not $objEl) { return $names }
  259. $childObjs = $objEl.SelectSingleNode("*[local-name()='ChildObjects']")
  260. if (-not $childObjs) { return $names }
  261. foreach ($child in $childObjs.ChildNodes) {
  262. if ($child.NodeType -ne 'Element') { continue }
  263. $nameNode = $child.SelectSingleNode("*[local-name()='Properties']/*[local-name()='Name']")
  264. if ($nameNode) { $names[$nameNode.InnerText.Trim()] = $true }
  265. }
  266. return $names
  267. }
  268. # Порядок групп в <ChildObjects> объекта по виду. Это xs:sequence <Вид>ChildObjects из MDClasses XSD,
  269. # сверенный выгрузкой платформы: выгрузка сама ставит группы в этот порядок, так что вставка не на место
  270. # даёт дифф при следующей выгрузке. Единого порядка нет — у документа Form стоит до TabularSection.
  271. function Get-ObjectChildOrder {
  272. return @{
  273. "Catalog" = @("Attribute", "TabularSection", "Form", "Template", "Command")
  274. "Document" = @("Attribute", "Form", "TabularSection", "Template", "Command")
  275. "ExchangePlan" = @("Attribute", "TabularSection", "Form", "Template", "Command")
  276. "ChartOfCharacteristicTypes" = @("Attribute", "TabularSection", "Form", "Template", "Command")
  277. "ChartOfAccounts" = @("Attribute", "TabularSection", "AccountingFlag", "ExtDimensionAccountingFlag", "Form", "Template", "Command")
  278. "ChartOfCalculationTypes" = @("Attribute", "TabularSection", "Form", "Template", "Command")
  279. "BusinessProcess" = @("Attribute", "TabularSection", "Form", "Template", "Command")
  280. "Task" = @("Attribute", "TabularSection", "Form", "Template", "AddressingAttribute", "Command")
  281. "DataProcessor" = @("Attribute", "TabularSection", "Form", "Template", "Command")
  282. "Report" = @("Attribute", "TabularSection", "Form", "Template", "Command")
  283. "ExternalDataProcessor" = @("Attribute", "TabularSection", "Form", "Template")
  284. "ExternalReport" = @("Attribute", "TabularSection", "Form", "Template")
  285. "Enum" = @("EnumValue", "Form", "Template", "Command")
  286. "InformationRegister" = @("Resource", "Attribute", "Dimension", "Form", "Template", "Command")
  287. "AccumulationRegister" = @("Resource", "Attribute", "Dimension", "Form", "Template", "Command")
  288. "AccountingRegister" = @("Dimension", "Resource", "Attribute", "Form", "Template", "Command")
  289. "CalculationRegister" = @("Resource", "Attribute", "Dimension", "Recalculation", "Form", "Template", "Command")
  290. "DocumentJournal" = @("Column", "Form", "Template", "Command")
  291. "Table" = @("Field", "Form", "Command", "Template")
  292. "ExternalDataSource" = @("Table", "Cube", "Function")
  293. "Cube" = @("DimensionTable", "Dimension", "Resource", "Form", "Command", "Template")
  294. "DimensionTable" = @("Field", "Form", "Command", "Template")
  295. "FilterCriterion" = @("Form", "Command")
  296. "SettingsStorage" = @("Form", "Template")
  297. "TabularSection" = @("Attribute")
  298. }
  299. }
  300. # Элемент <ChildObjects>, ПЕРЕД которым встаёт новый <tag>; $null — дописать в конец.
  301. # Сразу за последним элементом своего тега, иначе перед первым элементом группы, идущей
  302. # по канону вида позже. Вид или тег вне канона — $null, как раньше.
  303. function Find-ChildAnchor($container, [string]$tag, [string]$objType) {
  304. $children = New-Object System.Collections.Generic.List[object]
  305. foreach ($c in $container.ChildNodes) { if ($c.NodeType -eq 'Element') { $children.Add($c) } }
  306. $lastIdx = -1
  307. for ($i = 0; $i -lt $children.Count; $i++) {
  308. if ($children[$i].LocalName -ceq $tag) { $lastIdx = $i }
  309. }
  310. if ($lastIdx -ge 0) {
  311. if ($lastIdx + 1 -lt $children.Count) { return $children[$lastIdx + 1] }
  312. return $null
  313. }
  314. $order = (Get-ObjectChildOrder)[$objType]
  315. if (-not $order) { return $null }
  316. $tagIdx = [array]::IndexOf([string[]]$order, $tag)
  317. if ($tagIdx -lt 0) { return $null }
  318. $later = @($order | Select-Object -Skip ($tagIdx + 1))
  319. foreach ($c in $children) {
  320. if ($later -ccontains $c.LocalName) { return $c }
  321. }
  322. return $null
  323. }
  324. # Вставка ОДНОГО узла <tag> ($fragment — с отступом прямого ребёнка) в СОБСТВЕННЫЙ <ChildObjects>
  325. # объекта на место по канону вида — как Find-ChildAnchor, только по тексту: за последним своим тегом,
  326. # иначе перед первой группой, идущей по канону позже, иначе перед закрывающим тегом. Свой контейнер
  327. # открывается первым (свойства объекта <ChildObjects> не содержат) и закрывается последним: вложенные
  328. # <ChildObjects> табличных частей лежат внутри него, поиск «первого </ChildObjects>» уводил вставку в ТЧ.
  329. # Прямые дети — по глубине вложенности, не по отступу. Строку с одним тегом дополняем целой строкой,
  330. # перевод строки — из самого файла. $null — своего <ChildObjects> у объекта нет.
  331. function Insert-IntoOwnChildObjectsByCanon {
  332. param([string]$text, [string]$fragment, [string]$tag, [string]$objType)
  333. $eol = if ($text.Contains("`r`n")) { "`r`n" } else { "`n" }
  334. $frag = ($fragment.TrimEnd().TrimStart([char[]]"`r`n") -replace "`r`n", "`n") -replace "`n", $eol
  335. $mOpen = [regex]::Match($text, '<ChildObjects\b[^>]*?(/?)>')
  336. if (-not $mOpen.Success) { return $null }
  337. # Начало строки и отступ до позиции p; Indent = $null — перед p на строке есть что-то кроме пробелов
  338. $lineAt = {
  339. param([int]$p)
  340. $ls = if ($p -gt 0) { $text.LastIndexOf("`n", $p - 1) + 1 } else { 0 }
  341. $pre = $text.Substring($ls, $p - $ls)
  342. @{ Start = $ls; Indent = $(if ($pre.Trim().Length -eq 0) { $pre } else { $null }) }
  343. }
  344. if ($mOpen.Groups[1].Value) {
  345. # Контейнер самозакрытый — детей у него нет, раскрыть с единственным узлом
  346. $ind = (& $lineAt $mOpen.Index).Indent
  347. if ($null -eq $ind) { $ind = "" }
  348. return $text.Substring(0, $mOpen.Index) + "<ChildObjects>" + $eol + $frag + $eol + $ind + "</ChildObjects>" + $text.Substring($mOpen.Index + $mOpen.Length)
  349. }
  350. $closes = [regex]::Matches($text, '</ChildObjects\s*>')
  351. if ($closes.Count -eq 0) { return $null }
  352. $mClose = $closes[$closes.Count - 1]
  353. $bodyStart = $mOpen.Index + $mOpen.Length
  354. if ($mClose.Index -lt $bodyStart) { return $null }
  355. $starts = New-Object System.Collections.Generic.List[object]
  356. $depth = 0
  357. foreach ($m in [regex]::Matches($text.Substring($bodyStart, $mClose.Index - $bodyStart), '<(/?)([\w:.-]+)[^>]*?(/?)>')) {
  358. if ($m.Groups[1].Value) { $depth--; continue }
  359. if ($depth -eq 0) {
  360. $nm = $m.Groups[2].Value
  361. $starts.Add(@{ Pos = $bodyStart + $m.Index; Tag = $nm.Substring($nm.LastIndexOf(':') + 1) })
  362. }
  363. if (-not $m.Groups[3].Value) { $depth++ }
  364. }
  365. $pos = $mClose.Index
  366. $lastIdx = -1
  367. for ($i = 0; $i -lt $starts.Count; $i++) { if ($starts[$i].Tag -ceq $tag) { $lastIdx = $i } }
  368. $order = (Get-ObjectChildOrder)[$objType]
  369. if ($lastIdx -ge 0) {
  370. if ($lastIdx + 1 -lt $starts.Count) { $pos = $starts[$lastIdx + 1].Pos }
  371. } elseif ($order -and ($order -ccontains $tag)) {
  372. $later = @($order | Select-Object -Skip ([array]::IndexOf([string[]]$order, $tag) + 1))
  373. foreach ($s in $starts) { if ($later -ccontains $s.Tag) { $pos = $s.Pos; break } }
  374. }
  375. $line = & $lineAt $pos
  376. if ($null -ne $line.Indent) {
  377. return $text.Substring(0, $line.Start) + $frag + $eol + $text.Substring($line.Start)
  378. }
  379. return $text.Substring(0, $pos) + $frag.TrimStart() + $text.Substring($pos)
  380. }
  381. # Insert-IntoOwnChildObjectsByCanon, но своего <ChildObjects> нет — создать его последним ребёнком
  382. # элемента объекта; вставить всё равно некуда — отказ, а не молчаливое «добавлено».
  383. function Insert-OwnChildOrDie {
  384. param([string]$text, [string]$fragment, [string]$tag, [string]$objType, [string]$objFile)
  385. if (-not [regex]::IsMatch($text, '<ChildObjects\b')) {
  386. $ends = [regex]::Matches($text, '</' + [regex]::Escape($objType) + '\s*>')
  387. if ($ends.Count -gt 0) {
  388. $mEnd = $ends[$ends.Count - 1]
  389. $ls = if ($mEnd.Index -gt 0) { $text.LastIndexOf("`n", $mEnd.Index - 1) + 1 } else { 0 }
  390. $pre = $text.Substring($ls, $mEnd.Index - $ls)
  391. if ($pre.Trim().Length -eq 0) {
  392. $eol = if ($text.Contains("`r`n")) { "`r`n" } else { "`n" }
  393. $text = $text.Substring(0, $ls) + $pre + "`t<ChildObjects/>" + $eol + $text.Substring($ls)
  394. } else {
  395. $text = $text.Substring(0, $mEnd.Index) + "<ChildObjects/>" + $text.Substring($mEnd.Index)
  396. }
  397. }
  398. }
  399. $result = Insert-IntoOwnChildObjectsByCanon $text $fragment $tag $objType
  400. if ($null -eq $result) {
  401. Write-Error "Cannot insert <${tag}>: no own <ChildObjects> in $objFile"
  402. exit 1
  403. }
  404. return $result
  405. }
  406. # --- 1. Resolve paths ---
  407. if (-not [System.IO.Path]::IsPathRooted($ExtensionPath)) {
  408. $ExtensionPath = Join-Path (Get-Location).ProviderPath $ExtensionPath
  409. }
  410. if (Test-Path $ExtensionPath -PathType Container) {
  411. $candidate = Join-Path $ExtensionPath "Configuration.xml"
  412. if (Test-Path $candidate) { $ExtensionPath = $candidate }
  413. else { Write-Error "No Configuration.xml in extension directory: $ExtensionPath"; exit 1 }
  414. }
  415. if (-not (Test-Path $ExtensionPath)) { Write-Error "Extension file not found: $ExtensionPath"; exit 1 }
  416. $extResolvedPath = (Resolve-Path $ExtensionPath).ProviderPath
  417. $extDir = Split-Path $extResolvedPath -Parent
  418. if (-not [System.IO.Path]::IsPathRooted($ConfigPath)) {
  419. $ConfigPath = Join-Path (Get-Location).ProviderPath $ConfigPath
  420. }
  421. if (Test-Path $ConfigPath -PathType Container) {
  422. $candidate = Join-Path $ConfigPath "Configuration.xml"
  423. if (Test-Path $candidate) { $ConfigPath = $candidate }
  424. else { Write-Error "No Configuration.xml in config directory: $ConfigPath"; exit 1 }
  425. }
  426. if (-not (Test-Path $ConfigPath)) { Write-Error "Config file not found: $ConfigPath"; exit 1 }
  427. $cfgResolvedPath = (Resolve-Path $ConfigPath).ProviderPath
  428. $cfgDir = Split-Path $cfgResolvedPath -Parent
  429. # --- 2. Load extension Configuration.xml ---
  430. $script:xmlDoc = New-Object System.Xml.XmlDocument
  431. $script:xmlDoc.PreserveWhitespace = $true
  432. $script:xmlDoc.Load($extResolvedPath)
  433. $script:mdNs = "http://v8.1c.ru/8.3/MDClasses"
  434. $script:xrNs = "http://v8.1c.ru/8.3/xcf/readable"
  435. $script:xsiNs = "http://www.w3.org/2001/XMLSchema-instance"
  436. $script:v8Ns = "http://v8.1c.ru/8.1/data/core"
  437. $root = $script:xmlDoc.DocumentElement
  438. $script:cfgEl = $null
  439. foreach ($child in $root.ChildNodes) {
  440. if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Configuration") {
  441. $script:cfgEl = $child; break
  442. }
  443. }
  444. if (-not $script:cfgEl) { Write-Error "No <Configuration> element found in extension"; exit 1 }
  445. $script:propsEl = $null
  446. $script:childObjsEl = $null
  447. foreach ($child in $script:cfgEl.ChildNodes) {
  448. if ($child.NodeType -ne 'Element') { continue }
  449. if ($child.LocalName -eq "Properties") { $script:propsEl = $child }
  450. if ($child.LocalName -eq "ChildObjects") { $script:childObjsEl = $child }
  451. }
  452. if (-not $script:propsEl) { Write-Error "No <Properties> element found in extension"; exit 1 }
  453. if (-not $script:childObjsEl) { Write-Error "No <ChildObjects> element found in extension"; exit 1 }
  454. # --- 3. Extract NamePrefix ---
  455. $script:namePrefix = ""
  456. foreach ($child in $script:propsEl.ChildNodes) {
  457. if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "NamePrefix") {
  458. $script:namePrefix = $child.InnerText.Trim(); break
  459. }
  460. }
  461. Info "Extension NamePrefix: $($script:namePrefix)"
  462. # --- 4. Type mappings ---
  463. $childTypeDirMap = @{
  464. "Catalog"="Catalogs"; "Document"="Documents"; "Enum"="Enums"
  465. "CommonModule"="CommonModules"; "CommonPicture"="CommonPictures"
  466. "CommonCommand"="CommonCommands"; "CommonTemplate"="CommonTemplates"
  467. "ExchangePlan"="ExchangePlans"; "Report"="Reports"; "DataProcessor"="DataProcessors"
  468. "InformationRegister"="InformationRegisters"; "AccumulationRegister"="AccumulationRegisters"
  469. "ChartOfCharacteristicTypes"="ChartsOfCharacteristicTypes"
  470. "ChartOfAccounts"="ChartsOfAccounts"; "AccountingRegister"="AccountingRegisters"
  471. "ChartOfCalculationTypes"="ChartsOfCalculationTypes"; "CalculationRegister"="CalculationRegisters"
  472. "BusinessProcess"="BusinessProcesses"; "Task"="Tasks"
  473. "Subsystem"="Subsystems"; "Role"="Roles"; "Constant"="Constants"
  474. "FunctionalOption"="FunctionalOptions"; "DefinedType"="DefinedTypes"
  475. "FunctionalOptionsParameter"="FunctionalOptionsParameters"
  476. "CommonForm"="CommonForms"; "DocumentJournal"="DocumentJournals"
  477. "SessionParameter"="SessionParameters"; "StyleItem"="StyleItems"
  478. "EventSubscription"="EventSubscriptions"; "ScheduledJob"="ScheduledJobs"
  479. "SettingsStorage"="SettingsStorages"; "FilterCriterion"="FilterCriteria"
  480. "CommandGroup"="CommandGroups"; "DocumentNumerator"="DocumentNumerators"
  481. "Sequence"="Sequences"; "ExternalDataSource"="ExternalDataSources"; "IntegrationService"="IntegrationServices"
  482. "XDTOPackage"="XDTOPackages"; "WebService"="WebServices"
  483. "HTTPService"="HTTPServices"; "WSReference"="WSReferences"
  484. "CommonAttribute"="CommonAttributes"; "Style"="Styles"; "Bot"="Bots"; "PaletteColor"="PaletteColors"; "Language"="Languages"
  485. }
  486. # --- 4a. Модули заимствованных объектов ---
  487. # Порядок внутри значения — порядок выгрузки Конфигуратора: сначала «объектный» модуль
  488. # (ObjectModule / RecordSetModule / ValueManagerModule), затем ManagerModule.
  489. $script:moduleKindsByType = @{
  490. "CommonModule"=@("Module"); "HTTPService"=@("Module"); "WebService"=@("Module")
  491. "Catalog"=@("ObjectModule","ManagerModule"); "Document"=@("ObjectModule","ManagerModule")
  492. "Report"=@("ObjectModule","ManagerModule"); "DataProcessor"=@("ObjectModule","ManagerModule")
  493. "ExchangePlan"=@("ObjectModule","ManagerModule")
  494. "ChartOfCharacteristicTypes"=@("ObjectModule","ManagerModule")
  495. "ChartOfAccounts"=@("ObjectModule","ManagerModule")
  496. "ChartOfCalculationTypes"=@("ObjectModule","ManagerModule")
  497. "BusinessProcess"=@("ObjectModule","ManagerModule"); "Task"=@("ObjectModule","ManagerModule")
  498. "InformationRegister"=@("RecordSetModule","ManagerModule")
  499. "AccumulationRegister"=@("RecordSetModule","ManagerModule")
  500. "AccountingRegister"=@("RecordSetModule","ManagerModule")
  501. "CalculationRegister"=@("RecordSetModule","ManagerModule")
  502. "Sequence"=@("RecordSetModule","ManagerModule")
  503. "Constant"=@("ValueManagerModule","ManagerModule")
  504. "Enum"=@("ManagerModule"); "DocumentJournal"=@("ManagerModule")
  505. "FilterCriterion"=@("ManagerModule")
  506. }
  507. # Типы с ЕДИНСТВЕННЫМ модулем: ради него объект и заимствуют, поэтому файл создаётся молча.
  508. # Отказ — `-Module None`.
  509. $script:autoModuleTypes = @("CommonModule", "HTTPService", "WebService")
  510. $script:moduleKindNames = @("Module", "ObjectModule", "ManagerModule", "RecordSetModule", "ValueManagerModule")
  511. # --- 4b. Russian synonym → English type ---
  512. $synonymMap = @{
  513. "Справочник"="Catalog"; "Документ"="Document"; "Перечисление"="Enum"
  514. "ОбщийМодуль"="CommonModule"; "ОбщаяКартинка"="CommonPicture"
  515. "ОбщаяКоманда"="CommonCommand"; "ОбщийМакет"="CommonTemplate"
  516. "ПланОбмена"="ExchangePlan"; "Отчет"="Report"; "Отчёт"="Report"
  517. "Обработка"="DataProcessor"; "РегистрСведений"="InformationRegister"
  518. "РегистрНакопления"="AccumulationRegister"
  519. "ПланВидовХарактеристик"="ChartOfCharacteristicTypes"
  520. "ПланСчетов"="ChartOfAccounts"; "РегистрБухгалтерии"="AccountingRegister"
  521. "ПланВидовРасчета"="ChartOfCalculationTypes"; "РегистрРасчета"="CalculationRegister"
  522. "БизнесПроцесс"="BusinessProcess"; "Задача"="Task"
  523. "Подсистема"="Subsystem"; "Роль"="Role"; "Константа"="Constant"
  524. "ФункциональнаяОпция"="FunctionalOption"; "ОпределяемыйТип"="DefinedType"
  525. "ОбщаяФорма"="CommonForm"; "ЖурналДокументов"="DocumentJournal"
  526. "ПараметрСеанса"="SessionParameter"; "ГруппаКоманд"="CommandGroup"
  527. "ПодпискаНаСобытие"="EventSubscription"; "РегламентноеЗадание"="ScheduledJob"
  528. "ОбщийРеквизит"="CommonAttribute"; "ПакетXDTO"="XDTOPackage"
  529. "HTTPСервис"="HTTPService"; "СервисИнтеграции"="IntegrationService"
  530. }
  531. # --- 5. Canonical type order (46 types) ---
  532. $script:typeOrder = @(
  533. "Language","Subsystem","StyleItem","Style",
  534. "CommonPicture","SessionParameter","Role","CommonTemplate",
  535. "FilterCriterion","CommonModule","CommonAttribute","ExchangePlan",
  536. "XDTOPackage","WebService","HTTPService","WSReference",
  537. "EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
  538. "FunctionalOptionsParameter","DefinedType","Bot","PaletteColor","CommonCommand","CommandGroup",
  539. "Constant","CommonForm","Catalog","Document",
  540. "DocumentNumerator","Sequence","DocumentJournal","Enum",
  541. "Report","DataProcessor","InformationRegister","AccumulationRegister",
  542. "ChartOfCharacteristicTypes","ChartOfAccounts","AccountingRegister",
  543. "ChartOfCalculationTypes","CalculationRegister",
  544. "BusinessProcess","Task","ExternalDataSource","IntegrationService"
  545. )
  546. # --- 6. GeneratedType patterns per type ---
  547. $script:generatedTypes = @{
  548. "Catalog" = @(
  549. @{ prefix = "CatalogObject"; category = "Object" }
  550. @{ prefix = "CatalogRef"; category = "Ref" }
  551. @{ prefix = "CatalogSelection"; category = "Selection" }
  552. @{ prefix = "CatalogList"; category = "List" }
  553. @{ prefix = "CatalogManager"; category = "Manager" }
  554. )
  555. "Document" = @(
  556. @{ prefix = "DocumentObject"; category = "Object" }
  557. @{ prefix = "DocumentRef"; category = "Ref" }
  558. @{ prefix = "DocumentSelection"; category = "Selection" }
  559. @{ prefix = "DocumentList"; category = "List" }
  560. @{ prefix = "DocumentManager"; category = "Manager" }
  561. )
  562. "Enum" = @(
  563. @{ prefix = "EnumRef"; category = "Ref" }
  564. @{ prefix = "EnumManager"; category = "Manager" }
  565. @{ prefix = "EnumList"; category = "List" }
  566. )
  567. "Constant" = @(
  568. @{ prefix = "ConstantManager"; category = "Manager" }
  569. @{ prefix = "ConstantValueManager"; category = "ValueManager" }
  570. @{ prefix = "ConstantValueKey"; category = "ValueKey" }
  571. )
  572. "InformationRegister" = @(
  573. @{ prefix = "InformationRegisterRecord"; category = "Record" }
  574. @{ prefix = "InformationRegisterManager"; category = "Manager" }
  575. @{ prefix = "InformationRegisterSelection"; category = "Selection" }
  576. @{ prefix = "InformationRegisterList"; category = "List" }
  577. @{ prefix = "InformationRegisterRecordSet"; category = "RecordSet" }
  578. @{ prefix = "InformationRegisterRecordKey"; category = "RecordKey" }
  579. @{ prefix = "InformationRegisterRecordManager"; category = "RecordManager" }
  580. )
  581. "AccumulationRegister" = @(
  582. @{ prefix = "AccumulationRegisterRecord"; category = "Record" }
  583. @{ prefix = "AccumulationRegisterManager"; category = "Manager" }
  584. @{ prefix = "AccumulationRegisterSelection"; category = "Selection" }
  585. @{ prefix = "AccumulationRegisterList"; category = "List" }
  586. @{ prefix = "AccumulationRegisterRecordSet"; category = "RecordSet" }
  587. @{ prefix = "AccumulationRegisterRecordKey"; category = "RecordKey" }
  588. )
  589. "AccountingRegister" = @(
  590. @{ prefix = "AccountingRegisterRecord"; category = "Record" }
  591. @{ prefix = "AccountingRegisterExtDimensions"; category = "ExtDimensions" }
  592. @{ prefix = "AccountingRegisterManager"; category = "Manager" }
  593. @{ prefix = "AccountingRegisterSelection"; category = "Selection" }
  594. @{ prefix = "AccountingRegisterList"; category = "List" }
  595. @{ prefix = "AccountingRegisterRecordSet"; category = "RecordSet" }
  596. @{ prefix = "AccountingRegisterRecordKey"; category = "RecordKey" }
  597. )
  598. "CalculationRegister" = @(
  599. @{ prefix = "CalculationRegisterRecord"; category = "Record" }
  600. @{ prefix = "CalculationRegisterManager"; category = "Manager" }
  601. @{ prefix = "CalculationRegisterSelection"; category = "Selection" }
  602. @{ prefix = "CalculationRegisterList"; category = "List" }
  603. @{ prefix = "CalculationRegisterRecordSet"; category = "RecordSet" }
  604. @{ prefix = "CalculationRegisterRecordKey"; category = "RecordKey" }
  605. @{ prefix = "RecalculationsManager"; category = "Recalcs" }
  606. )
  607. "ChartOfAccounts" = @(
  608. @{ prefix = "ChartOfAccountsObject"; category = "Object" }
  609. @{ prefix = "ChartOfAccountsRef"; category = "Ref" }
  610. @{ prefix = "ChartOfAccountsSelection"; category = "Selection" }
  611. @{ prefix = "ChartOfAccountsList"; category = "List" }
  612. @{ prefix = "ChartOfAccountsManager"; category = "Manager" }
  613. @{ prefix = "ChartOfAccountsExtDimensionTypes"; category = "ExtDimensionTypes" }
  614. @{ prefix = "ChartOfAccountsExtDimensionTypesRow"; category = "ExtDimensionTypesRow" }
  615. )
  616. "ChartOfCharacteristicTypes" = @(
  617. @{ prefix = "ChartOfCharacteristicTypesObject"; category = "Object" }
  618. @{ prefix = "ChartOfCharacteristicTypesRef"; category = "Ref" }
  619. @{ prefix = "ChartOfCharacteristicTypesSelection"; category = "Selection" }
  620. @{ prefix = "ChartOfCharacteristicTypesList"; category = "List" }
  621. @{ prefix = "Characteristic"; category = "Characteristic" }
  622. @{ prefix = "ChartOfCharacteristicTypesManager"; category = "Manager" }
  623. )
  624. "ChartOfCalculationTypes" = @(
  625. @{ prefix = "ChartOfCalculationTypesObject"; category = "Object" }
  626. @{ prefix = "ChartOfCalculationTypesRef"; category = "Ref" }
  627. @{ prefix = "ChartOfCalculationTypesSelection"; category = "Selection" }
  628. @{ prefix = "ChartOfCalculationTypesList"; category = "List" }
  629. @{ prefix = "ChartOfCalculationTypesManager"; category = "Manager" }
  630. @{ prefix = "DisplacingCalculationTypes"; category = "DisplacingCalculationTypes" }
  631. @{ prefix = "DisplacingCalculationTypesRow"; category = "DisplacingCalculationTypesRow" }
  632. @{ prefix = "BaseCalculationTypes"; category = "BaseCalculationTypes" }
  633. @{ prefix = "BaseCalculationTypesRow"; category = "BaseCalculationTypesRow" }
  634. @{ prefix = "LeadingCalculationTypes"; category = "LeadingCalculationTypes" }
  635. @{ prefix = "LeadingCalculationTypesRow"; category = "LeadingCalculationTypesRow" }
  636. )
  637. "BusinessProcess" = @(
  638. @{ prefix = "BusinessProcessObject"; category = "Object" }
  639. @{ prefix = "BusinessProcessRef"; category = "Ref" }
  640. @{ prefix = "BusinessProcessSelection"; category = "Selection" }
  641. @{ prefix = "BusinessProcessList"; category = "List" }
  642. @{ prefix = "BusinessProcessManager"; category = "Manager" }
  643. @{ prefix = "BusinessProcessRoutePointRef"; category = "RoutePointRef" }
  644. )
  645. "Task" = @(
  646. @{ prefix = "TaskObject"; category = "Object" }
  647. @{ prefix = "TaskRef"; category = "Ref" }
  648. @{ prefix = "TaskSelection"; category = "Selection" }
  649. @{ prefix = "TaskList"; category = "List" }
  650. @{ prefix = "TaskManager"; category = "Manager" }
  651. )
  652. "ExchangePlan" = @(
  653. @{ prefix = "ExchangePlanObject"; category = "Object" }
  654. @{ prefix = "ExchangePlanRef"; category = "Ref" }
  655. @{ prefix = "ExchangePlanSelection"; category = "Selection" }
  656. @{ prefix = "ExchangePlanList"; category = "List" }
  657. @{ prefix = "ExchangePlanManager"; category = "Manager" }
  658. )
  659. "DocumentJournal" = @(
  660. @{ prefix = "DocumentJournalSelection"; category = "Selection" }
  661. @{ prefix = "DocumentJournalList"; category = "List" }
  662. @{ prefix = "DocumentJournalManager"; category = "Manager" }
  663. )
  664. "Report" = @(
  665. @{ prefix = "ReportObject"; category = "Object" }
  666. @{ prefix = "ReportManager"; category = "Manager" }
  667. )
  668. "DataProcessor" = @(
  669. @{ prefix = "DataProcessorObject"; category = "Object" }
  670. @{ prefix = "DataProcessorManager"; category = "Manager" }
  671. )
  672. "DefinedType" = @(
  673. @{ prefix = "DefinedType"; category = "DefinedType" }
  674. )
  675. "ExternalDataSource" = @(
  676. @{ prefix = "ExternalDataSourceManager"; category = "Manager" }
  677. @{ prefix = "ExternalDataSourceTablesManager"; category = "TablesManager" }
  678. @{ prefix = "ExternalDataSourceCubesManager"; category = "CubesManager" }
  679. )
  680. "Sequence" = @(
  681. @{ prefix = "SequenceRecord"; category = "Record" }
  682. @{ prefix = "SequenceManager"; category = "Manager" }
  683. @{ prefix = "SequenceRecordSet"; category = "RecordSet" }
  684. )
  685. "FilterCriterion" = @(
  686. @{ prefix = "FilterCriterionManager"; category = "Manager" }
  687. @{ prefix = "FilterCriterionList"; category = "List" }
  688. )
  689. "SettingsStorage" = @(
  690. @{ prefix = "SettingsStorageManager"; category = "Manager" }
  691. )
  692. "IntegrationService" = @(
  693. @{ prefix = "IntegrationServiceManager"; category = "Manager" }
  694. )
  695. "WSReference" = @(
  696. @{ prefix = "WSReferenceManager"; category = "Manager" }
  697. )
  698. }
  699. # Types that need ChildObjects element — fallback when the source object cannot be probed.
  700. # The platform emits <ChildObjects> for every container type even when empty, and rejects
  701. # the file without it ("ожидаемое ChildObjects"); primary signal is the source object itself.
  702. $typesWithChildObjects = @(
  703. "Catalog","Document","ExchangePlan","ChartOfAccounts",
  704. "ChartOfCharacteristicTypes","ChartOfCalculationTypes",
  705. "BusinessProcess","Task","Enum",
  706. "InformationRegister","AccumulationRegister","AccountingRegister","CalculationRegister",
  707. "DataProcessor","Report","DocumentJournal","FilterCriterion","SettingsStorage",
  708. "Sequence","HTTPService","WebService","IntegrationService","Subsystem"
  709. )
  710. # CommonModule properties to copy from source
  711. $commonModuleProps = @("Global","ClientManagedApplication","Server","ExternalConnection","ClientOrdinaryApplication","ServerCall")
  712. # Свойства объекта, от которых зависит существование стандартного поля: без них платформа
  713. # отвергает загрузку — «Неверный путь к данным». Конфигуратор переносит ровно их (эталоны
  714. # Issue66Example7_1 и Issue66Example2). Проверено сплошным прогоном по типам: у регистра сведений
  715. # без InformationRegisterPeriodicity не разрешается «Запись.Period».
  716. # Тем же путём переносится код языка: платформа принимает заимствованный язык и без него, но
  717. # конфигуратор пишет LanguageCode у любого заимствованного языка, основного и неосновного (замер 8.3.24).
  718. $script:typeGateProps = @{
  719. "InformationRegister" = @("InformationRegisterPeriodicity","WriteMode")
  720. "Language" = @("LanguageCode")
  721. }
  722. # Владельцы справочника — список <xr:Item>, а не скаляр: переносится фрагментом, как __TypeXml
  723. $script:typesWithOwners = @("Catalog","ChartOfCharacteristicTypes")
  724. # Standard system fields to skip when collecting DataPath references
  725. $script:standardFields = @("Code","Description","Ref","Parent","DeletionMark","Predefined","IsFolder","LineNumber","RowsCount","PredefinedDataName")
  726. # --- 7. XML manipulation helpers (from cf-edit) ---
  727. function Get-ChildIndent($container) {
  728. foreach ($child in $container.ChildNodes) {
  729. if ($child.NodeType -eq 'Whitespace' -or $child.NodeType -eq 'SignificantWhitespace') {
  730. if ($child.Value -match '^\r?\n(\t+)$') { return $Matches[1] }
  731. if ($child.Value -match '^\r?\n(\t+)') { return $Matches[1] }
  732. }
  733. }
  734. $depth = 0; $current = $container
  735. while ($current -and $current -ne $script:xmlDoc.DocumentElement) { $depth++; $current = $current.ParentNode }
  736. return "`t" * ($depth + 1)
  737. }
  738. function Insert-BeforeElement($container, $newNode, $refNode, $childIndent) {
  739. $ws = $script:xmlDoc.CreateWhitespace("`r`n$childIndent")
  740. if ($refNode) {
  741. $container.InsertBefore($ws, $refNode) | Out-Null
  742. $container.InsertBefore($newNode, $ws) | Out-Null
  743. } else {
  744. $trailing = $container.LastChild
  745. if ($trailing -and ($trailing.NodeType -eq 'Whitespace' -or $trailing.NodeType -eq 'SignificantWhitespace')) {
  746. $container.InsertBefore($ws, $trailing) | Out-Null
  747. $container.InsertBefore($newNode, $trailing) | Out-Null
  748. } else {
  749. $container.AppendChild($ws) | Out-Null
  750. $container.AppendChild($newNode) | Out-Null
  751. $parentIndent = if ($childIndent.Length -gt 1) { $childIndent.Substring(0, $childIndent.Length - 1) } else { "" }
  752. $closeWs = $script:xmlDoc.CreateWhitespace("`r`n$parentIndent")
  753. $container.AppendChild($closeWs) | Out-Null
  754. }
  755. }
  756. }
  757. function Expand-SelfClosingElement($container, $parentIndent) {
  758. if (-not $container.HasChildNodes -or $container.IsEmpty) {
  759. $closeWs = $script:xmlDoc.CreateWhitespace("`r`n$parentIndent")
  760. $container.AppendChild($closeWs) | Out-Null
  761. }
  762. }
  763. # --- 7b. Detect format version ---
  764. function Detect-FormatVersion([string]$dir) {
  765. $d = $dir
  766. while ($d) {
  767. # Автономная внешняя обработка/отчёт: своего Configuration.xml у неё нет, версию несёт
  768. # корень самой обработки. Без этого форма и макет внутри обработки 2.21 писались бы 2.17.
  769. $extPath = "$d.xml"
  770. if (Test-Path $extPath) {
  771. $extText = [System.IO.File]::ReadAllText($extPath, [System.Text.Encoding]::UTF8)
  772. $extHead = $extText.Substring(0, [Math]::Min(2000, $extText.Length))
  773. if ($extHead -match '<(ExternalDataProcessor|ExternalReport)[ >]' -and $extHead -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
  774. }
  775. $cfgPath = Join-Path $d "Configuration.xml"
  776. if (Test-Path $cfgPath) {
  777. $cfgText = [System.IO.File]::ReadAllText($cfgPath, [System.Text.Encoding]::UTF8)
  778. # Длину среза берём по СТРОКЕ, а не по размеру файла: размер в БАЙТАХ, Substring считает
  779. # СИМВОЛЫ, и на кириллице байт больше — короткий Configuration.xml ронял навык исключением.
  780. $head = $cfgText.Substring(0, [Math]::Min(2000, $cfgText.Length))
  781. if ($head -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
  782. }
  783. $parent = Split-Path $d -Parent
  784. if ($parent -eq $d) { break }
  785. $d = $parent
  786. }
  787. return "2.17"
  788. }
  789. $script:formatVersion = Detect-FormatVersion $extDir
  790. # --- 8. Namespaces declaration for object XML ---
  791. $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"'
  792. # Версия формата как число для сравнений: "2.20" → 220, "2.9" → 209.
  793. # Строковое сравнение здесь неверно ("2.9" > "2.17" лексикографически) — известная ловушка.
  794. function Get-FormatRank([string]$ver) {
  795. if ($ver -match '^(\d+)\.(\d+)$') { return [int]$Matches[1] * 100 + [int]$Matches[2] }
  796. return 0
  797. }
  798. # 2.21 (8.5) добавила в шапку пространство палитры — ради <Color> у значений перечисления.
  799. # Вставляем НА МЕСТО (после lf, перед style): платформа держит объявления по алфавиту,
  800. # дописать в конец нельзя.
  801. if ((Get-FormatRank $script:formatVersion) -ge 221) {
  802. $script:xmlnsDecl = $script:xmlnsDecl -replace ' xmlns:style=', ' xmlns:pal="http://v8.1c.ru/8.1/data/ui/colors/palette" xmlns:style='
  803. }
  804. # --- 9. Parse -Object into items ---
  805. if ($Check -and $Actualize) {
  806. Write-Error "-Check and -Actualize cannot be combined"
  807. exit 1
  808. }
  809. if (($Check -or $Actualize) -and ($Module -or $BorrowMainAttribute)) {
  810. Write-Error "-Check and -Actualize cannot be combined with -Module or -BorrowMainAttribute"
  811. exit 1
  812. }
  813. $items = @()
  814. if ($Object) {
  815. foreach ($part in $Object.Split(";;")) {
  816. $trimmed = $part.Trim()
  817. if ($trimmed) { $items += $trimmed }
  818. }
  819. }
  820. if ($items.Count -eq 0 -and -not ($Check -or $Actualize)) {
  821. Write-Error "No objects specified in -Object"
  822. exit 1
  823. }
  824. # --- 9b. Validate -BorrowMainAttribute ---
  825. if ($BorrowMainAttribute) {
  826. if ($BorrowMainAttribute -notin @("Form","All")) {
  827. Write-Error "-BorrowMainAttribute accepts 'Form' or 'All' (default: Form)"
  828. exit 1
  829. }
  830. # Validate: only with a form — .Form. pattern or a common form
  831. $hasForm = $false
  832. foreach ($item in $items) { if ($item -match '\.Form\.' -or $item -match '^(CommonForm|ОбщаяФорма)\.') { $hasForm = $true; break } }
  833. if (-not $hasForm) {
  834. Write-Error "-BorrowMainAttribute requires a form in -Object (e.g. 'Catalog.X.Form.Y')"
  835. exit 1
  836. }
  837. }
  838. # --- 9c. Validate -Module ---
  839. $script:requestedModules = @()
  840. $script:noModule = $false
  841. if ($Module) {
  842. foreach ($raw in ($Module -split '[,;]')) {
  843. $kind = $raw.Trim()
  844. if (-not $kind) { continue }
  845. # Сравнение РЕГИСТРОНЕЗАВИСИМОЕ явно (-ieq): в py-порте это отдельная ветка, и молчаливое
  846. # расхождение портов на «none» ловится только глазами.
  847. if ($kind -ieq "None") { $script:noModule = $true; continue }
  848. $canon = @($script:moduleKindNames | Where-Object { $_ -ieq $kind })
  849. if ($canon.Count -eq 0) {
  850. Write-Error "Неизвестный вид модуля '$kind'. Допустимо: $($script:moduleKindNames -join ', '), None"
  851. exit 1
  852. }
  853. $script:requestedModules += $canon[0]
  854. }
  855. if ($script:noModule -and $script:requestedModules.Count -gt 0) {
  856. Write-Error "-Module None нельзя сочетать с видами модулей"
  857. exit 1
  858. }
  859. }
  860. # Какие модули создать для объекта. Тип с единственным модулем получает его всегда — уточнять
  861. # там нечего; -Module разбирает только неоднозначные типы. Иначе батч смешанных типов
  862. # (`CommonModule.X ;; Catalog.Y`) не выражался бы одним вызовом.
  863. function Resolve-ModuleKinds {
  864. param([string]$typeName)
  865. if ($script:noModule) { return @() }
  866. $allowed = @($script:moduleKindsByType[$typeName])
  867. if ($allowed.Count -eq 0) { return @() }
  868. if ($script:autoModuleTypes -contains $typeName) { return @($allowed[0]) }
  869. if ($script:requestedModules.Count -eq 0) { return @() }
  870. # Порядок берём из таблицы типа, а не из порядка ключей в -Module.
  871. $selected = @($allowed | Where-Object { $script:requestedModules -contains $_ })
  872. if ($selected.Count -eq 0) {
  873. Warn " Тип $typeName не имеет запрошенных модулей — пропущено. Допустимо: $($allowed -join ', ')"
  874. }
  875. return $selected
  876. }
  877. # --- 10. Helper: read source object XML ---
  878. # Имена реквизитов исходного объекта → uuid: реквизиты, ТЧ, измерения и ресурсы регистра, реквизиты
  879. # ТЧ — ключом «ТЧ.Реквизит». Нужны для кода пути в связях формы (см. Resolve-LinkDataPath).
  880. function Get-SourceAttributeUuids {
  881. param([string]$typeName, [string]$objName)
  882. $result = @{}
  883. $dirName = $childTypeDirMap[$typeName]
  884. if (-not $dirName) { return $result }
  885. $srcFile = Join-Path (Join-Path $cfgDir $dirName) "${objName}.xml"
  886. if (-not (Test-Path $srcFile)) { return $result }
  887. $doc = New-Object System.Xml.XmlDocument
  888. $doc.PreserveWhitespace = $false
  889. $doc.Load($srcFile)
  890. $objEl = $null
  891. foreach ($c in $doc.DocumentElement.ChildNodes) {
  892. if ($c.NodeType -eq 'Element') { $objEl = $c; break }
  893. }
  894. if (-not $objEl) { return $result }
  895. $childObjects = $objEl.SelectSingleNode("*[local-name()='ChildObjects']")
  896. if (-not $childObjects) { return $result }
  897. foreach ($child in $childObjects.ChildNodes) {
  898. if ($child.NodeType -ne 'Element') { continue }
  899. if ($child.LocalName -notin @('Attribute','TabularSection','Dimension','Resource')) { continue }
  900. $uuid = $child.GetAttribute("uuid")
  901. $nameNode = $child.SelectSingleNode("*[local-name()='Properties']/*[local-name()='Name']")
  902. if (-not ($uuid -and $nameNode)) { continue }
  903. $name = $nameNode.InnerText.Trim()
  904. $result[$name] = $uuid
  905. if ($child.LocalName -ne 'TabularSection') { continue }
  906. foreach ($tsAttr in @($child.SelectNodes("*[local-name()='ChildObjects']/*[local-name()='Attribute']"))) {
  907. $tsUuid = $tsAttr.GetAttribute("uuid")
  908. $tsName = $tsAttr.SelectSingleNode("*[local-name()='Properties']/*[local-name()='Name']")
  909. if ($tsUuid -and $tsName) { $result["$name.$($tsName.InnerText.Trim())"] = $tsUuid }
  910. }
  911. }
  912. return $result
  913. }
  914. function Read-SourceObject {
  915. param([string]$typeName, [string]$objName)
  916. $dirName = $childTypeDirMap[$typeName]
  917. if (-not $dirName) {
  918. Write-Error "Unknown type '$typeName'"
  919. exit 1
  920. }
  921. $srcFile = Join-Path (Join-Path $cfgDir $dirName) "${objName}.xml"
  922. if (-not (Test-Path $srcFile)) {
  923. Write-Error "Source object not found: $srcFile"
  924. exit 1
  925. }
  926. $srcDoc = New-Object System.Xml.XmlDocument
  927. $srcDoc.PreserveWhitespace = $false
  928. $srcDoc.Load($srcFile)
  929. $srcNs = New-Object System.Xml.XmlNamespaceManager($srcDoc.NameTable)
  930. $srcNs.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
  931. $srcNs.AddNamespace("xr", "http://v8.1c.ru/8.3/xcf/readable")
  932. # Find the type element (e.g. <Catalog uuid="...">)
  933. $srcRoot = $srcDoc.DocumentElement
  934. $srcEl = $null
  935. foreach ($c in $srcRoot.ChildNodes) {
  936. if ($c.NodeType -eq 'Element') { $srcEl = $c; break }
  937. }
  938. if (-not $srcEl) {
  939. Write-Error "No metadata element found in ${dirName}/${objName}.xml"
  940. exit 1
  941. }
  942. # Extract uuid
  943. $srcUuid = $srcEl.GetAttribute("uuid")
  944. if (-not $srcUuid) {
  945. Write-Error "No uuid attribute on source element in ${dirName}/${objName}.xml"
  946. exit 1
  947. }
  948. # Extract properties for CommonModule
  949. $srcProps = @{}
  950. $propsNode = $srcEl.SelectSingleNode("md:Properties", $srcNs)
  951. if ($propsNode) {
  952. foreach ($propName in $commonModuleProps) {
  953. $propNode = $propsNode.SelectSingleNode("md:${propName}", $srcNs)
  954. if ($propNode) {
  955. $srcProps[$propName] = $propNode.InnerText.Trim()
  956. }
  957. }
  958. # DefinedType: carry the <Type> definition. A type alias is meaningless as a bare shell —
  959. # the platform needs its underlying type (e.g. to know a column is a summable Number for totals).
  960. if ($typeName -eq "DefinedType") {
  961. $typeNode = $propsNode.SelectSingleNode("md:Type", $srcNs)
  962. if ($typeNode) {
  963. $srcProps["__TypeXml"] = [regex]::Replace($typeNode.OuterXml, '\s+xmlns(?::\w+)?="[^"]*"', '')
  964. }
  965. }
  966. # Владельцы: стандартное поле «Owner» появляется у справочника, только если задан Owners
  967. if ($script:typesWithOwners -ccontains $typeName) {
  968. $ownersNode = $propsNode.SelectSingleNode("md:Owners", $srcNs)
  969. if ($ownersNode -and $ownersNode.HasChildNodes) {
  970. $srcProps["__OwnersXml"] = [regex]::Replace($ownersNode.OuterXml, '\s+xmlns(?::\w+)?="[^"]*"', '')
  971. }
  972. }
  973. # Скалярные свойства, включающие стандартные поля своего типа
  974. foreach ($gp in @($script:typeGateProps[$typeName])) {
  975. if (-not $gp) { continue }
  976. $gpNode = $propsNode.SelectSingleNode("md:${gp}", $srcNs)
  977. if ($gpNode) { $srcProps[$gp] = $gpNode.InnerText.Trim() }
  978. }
  979. }
  980. # Whether the platform emits <ChildObjects> for this type — the source object is the ground truth
  981. $srcProps["__HasChildObjects"] = ($srcEl.SelectSingleNode("md:ChildObjects", $srcNs) -ne $null)
  982. return @{
  983. Uuid = $srcUuid
  984. Properties = $srcProps
  985. Element = $srcEl
  986. NsManager = $srcNs
  987. }
  988. }
  989. # --- 10b. Helper: read source form UUID ---
  990. function Read-SourceFormUuid {
  991. param([string]$typeName, [string]$objName, [string]$formName)
  992. $dirName = $childTypeDirMap[$typeName]
  993. # Общая форма — сама объект конфигурации: её описание лежит рядом с другими, а не в Forms владельца
  994. $srcFile = if ($typeName -eq 'CommonForm') { Join-Path (Join-Path $cfgDir $dirName) "${objName}.xml" }
  995. else { Join-Path (Join-Path (Join-Path (Join-Path $cfgDir $dirName) $objName) "Forms") "${formName}.xml" }
  996. if (-not (Test-Path $srcFile)) {
  997. Write-Error "Source form not found: $srcFile"
  998. exit 1
  999. }
  1000. $srcDoc = New-Object System.Xml.XmlDocument
  1001. $srcDoc.PreserveWhitespace = $false
  1002. $srcDoc.Load($srcFile)
  1003. $srcEl = $null
  1004. foreach ($c in $srcDoc.DocumentElement.ChildNodes) {
  1005. if ($c.NodeType -eq 'Element') { $srcEl = $c; break }
  1006. }
  1007. if (-not $srcEl) {
  1008. Write-Error "No metadata element found in source form: $srcFile"
  1009. exit 1
  1010. }
  1011. $srcUuid = $srcEl.GetAttribute("uuid")
  1012. if (-not $srcUuid) {
  1013. Write-Error "No uuid attribute on source form element: $srcFile"
  1014. exit 1
  1015. }
  1016. return $srcUuid
  1017. }
  1018. # --- 10c. Helper: borrow a form ---
  1019. function Borrow-Form {
  1020. param([string]$typeName, [string]$objName, [string]$formName, [switch]$BorrowMainAttr, [switch]$RenderOnly, [switch]$Rebuild)
  1021. $dirName = $childTypeDirMap[$typeName]
  1022. $enc = New-Object System.Text.UTF8Encoding($true)
  1023. # Общая форма — сама объект конфигурации: описание CommonForms/<Имя>.xml с корнем <CommonForm>,
  1024. # тело CommonForms/<Имя>/Ext/Form.xml, регистрация в Configuration.xml. Форма объекта — в Forms
  1025. # владельца. Остальное (скелет, BaseForm, связи, оформление, картинки) одинаково (эталон УТ link).
  1026. $isCommonForm = $typeName -eq 'CommonForm'
  1027. # Уже заимствованная общая форма (в т.ч. оболочкой от прежних версий навыка) в Configuration.xml
  1028. # уже есть — повторно не регистрируем
  1029. $commonFormRegistered = $isCommonForm -and (Test-ObjectBorrowed $typeName $objName)
  1030. if ($isCommonForm) {
  1031. $srcFormDir = Join-Path (Join-Path $cfgDir $dirName) $objName
  1032. $formMetaFile = Join-Path (Join-Path $extDir $dirName) "${objName}.xml"
  1033. $extFormDir = Join-Path (Join-Path $extDir $dirName) $objName
  1034. $formMetaTag = 'CommonForm'
  1035. } else {
  1036. $srcFormDir = Join-Path (Join-Path (Join-Path (Join-Path $cfgDir $dirName) $objName) "Forms") $formName
  1037. $formMetaFile = Join-Path (Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Forms") "${formName}.xml"
  1038. $extFormDir = Join-Path (Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Forms") $formName
  1039. $formMetaTag = 'Form'
  1040. }
  1041. # 1. Read source form UUID
  1042. # -RenderOnly: только текст Form.xml по текущему источнику — для сравнения с заимствованной
  1043. # формой; ничего не пишет и попутно ничего не заимствует
  1044. $formUuid = Read-SourceFormUuid $typeName $objName $formName
  1045. if (-not $RenderOnly) { Info " Source form UUID: $formUuid" }
  1046. # 2. Read source Form.xml content
  1047. $srcFormXmlPath = Join-Path $srcFormDir "Ext/Form.xml"
  1048. if (-not (Test-Path $srcFormXmlPath)) {
  1049. Write-Error "Source Form.xml not found: $srcFormXmlPath"
  1050. exit 1
  1051. }
  1052. $srcFormContent = [System.IO.File]::ReadAllText($srcFormXmlPath, $enc)
  1053. # 3. Generate form metadata XML (ФормаЭлемента.xml).
  1054. # If the wrapper was already borrowed, reuse its uuid so re-borrow is idempotent
  1055. # (regenerating it would churn the form's identity on every rerun).
  1056. $newFormUuid = ""
  1057. if (Test-Path $formMetaFile) {
  1058. try {
  1059. $existingDoc = New-Object System.Xml.XmlDocument
  1060. $existingDoc.Load($formMetaFile)
  1061. $existingFormNode = $existingDoc.DocumentElement.SelectSingleNode("*[local-name()='$formMetaTag']")
  1062. if ($existingFormNode) {
  1063. $existingUuid = $existingFormNode.GetAttribute("uuid")
  1064. if ($existingUuid) { $newFormUuid = $existingUuid }
  1065. }
  1066. } catch { }
  1067. }
  1068. if (-not $newFormUuid) { $newFormUuid = [guid]::NewGuid().ToString() }
  1069. $formMetaSb = New-Object System.Text.StringBuilder
  1070. $formMetaSb.AppendLine("<?xml version=`"1.0`" encoding=`"UTF-8`"?>") | Out-Null
  1071. $formMetaSb.AppendLine("<MetaDataObject $($script:xmlnsDecl) version=`"$($script:formatVersion)`">") | Out-Null
  1072. $formMetaSb.AppendLine("`t<$formMetaTag uuid=`"${newFormUuid}`">") | Out-Null
  1073. $formMetaSb.AppendLine("`t`t<InternalInfo/>") | Out-Null
  1074. $formMetaSb.AppendLine("`t`t<Properties>") | Out-Null
  1075. $formMetaSb.AppendLine("`t`t`t<ObjectBelonging>Adopted</ObjectBelonging>") | Out-Null
  1076. $formMetaSb.AppendLine("`t`t`t<Name>${formName}</Name>") | Out-Null
  1077. $formMetaSb.AppendLine("`t`t`t<Comment/>") | Out-Null
  1078. $formMetaSb.AppendLine("`t`t`t<ExtendedConfigurationObject>${formUuid}</ExtendedConfigurationObject>") | Out-Null
  1079. $formMetaSb.AppendLine("`t`t`t<FormType>Managed</FormType>") | Out-Null
  1080. $formMetaSb.AppendLine("`t`t</Properties>") | Out-Null
  1081. $formMetaSb.AppendLine("`t</$formMetaTag>") | Out-Null
  1082. $formMetaSb.Append("</MetaDataObject>") | Out-Null
  1083. # 4. Create directories
  1084. $formMetaDir = Split-Path $formMetaFile -Parent
  1085. if (-not $RenderOnly -and -not (Test-Path $formMetaDir)) {
  1086. New-Item -ItemType Directory -Path $formMetaDir -Force | Out-Null
  1087. }
  1088. # Write form metadata
  1089. # -Rebuild: форма уже заимствована — пересобирается только Form.xml, метаданные и регистрация как есть
  1090. if (-not $RenderOnly -and -not $Rebuild) {
  1091. [System.IO.File]::WriteAllText($formMetaFile, $formMetaSb.ToString(), $enc)
  1092. Info " Created: $formMetaFile"
  1093. }
  1094. # 5. Generate Form.xml with BaseForm (visual elements only)
  1095. # Parse source Form.xml as XmlDocument
  1096. $srcFormDoc = New-Object System.Xml.XmlDocument
  1097. $srcFormDoc.PreserveWhitespace = $true
  1098. $srcFormDoc.Load($srcFormXmlPath)
  1099. $srcFormEl = $srcFormDoc.DocumentElement
  1100. # Borrowed form must use the extension's format version (not the source form's), so the whole
  1101. # extension stays uniform — otherwise the platform rejects the import on a version mismatch
  1102. # (e.g. a 2.13 form inside a 2.17 extension). The platform itself upgrades the form to the root version.
  1103. $formVersion = $script:formatVersion
  1104. # Find direct children: form properties, AutoCommandBar, ChildItems.
  1105. # Секции формы отбираются по имени, а не по позиции: свойства лежат и до, и после <CommandSet>
  1106. # (корпусная проверка: у всех 794 форм документов ERP с CommandSet он стоит раньше AutoCommandBar,
  1107. # а AutoTime/UsePostingMode/RepostOnWrite — после него). Позиционная отсечка теряла весь хвост,
  1108. # и платформа молча подставляла дефолты вместо потерянных свойств.
  1109. $srcAutoCmd = $null
  1110. $srcChildItems = $null
  1111. $formProps = @()
  1112. foreach ($fc in $srcFormEl.ChildNodes) {
  1113. if ($fc.NodeType -ne 'Element') { continue }
  1114. if ($fc.LocalName -eq 'AutoCommandBar' -and -not $srcAutoCmd) {
  1115. $srcAutoCmd = $fc; continue
  1116. }
  1117. if ($fc.LocalName -eq 'ChildItems' -and -not $srcChildItems) {
  1118. $srcChildItems = $fc; continue
  1119. }
  1120. # Структурные секции: в расширении их содержимое недействительно (обработчики, команды и
  1121. # параметры базовой формы, ссылки командного интерфейса на команды базовой конфигурации).
  1122. if ($script:formStructuralSections -ccontains $fc.LocalName) { continue }
  1123. # Свойства, значение которых — имя реквизита формы. Реквизиты в заимствованную форму не
  1124. # переносятся, поэтому Конфигуратор такие свойства выбрасывает (проверено на форме отчёта:
  1125. # ReportResult и DetailsData выброшены, CustomSettingsFolder — имя элемента — сохранён).
  1126. if ($script:formAttributeRefProps -ccontains $fc.LocalName) { continue }
  1127. $formProps += $fc.OuterXml
  1128. }
  1129. # Get OuterXml and strip redundant namespace redeclarations (they're on root <Form>)
  1130. $nsStripPattern = '\s+xmlns(?::\w+)?="[^"]*"'
  1131. # Основной реквизит исходной формы: его имя — корень путей к данным, которые нужно сохранить
  1132. # («Объект.» у формы объекта, «Список.» у формы списка, «Запись.» у формы записи регистра)
  1133. # Имя основного реквизита источника нужно в обоих режимах: по нему опознаётся корень путей
  1134. # в ссылках параметров выбора. А $mainAttrName управляет вырезанием привязок и потому остаётся
  1135. # пустым в скелетном режиме — там привязки снимаются все.
  1136. $srcMainInfo = Get-MainAttributeInfo $srcFormEl $nsStripPattern
  1137. $srcMainAttrName = if ($srcMainInfo) { $srcMainInfo.Name } else { "" }
  1138. $formAttrIds = Get-FormAttributeIds $srcFormEl
  1139. # Условное оформление формы Конфигуратор копирует как есть в обе части, внутрь <Attributes>
  1140. # после реквизитов — и без основного реквизита тоже; ссылки на незаимствованные реквизиты формы
  1141. # платформа принимает (эталоны УТ StdPic, StdPic_WithMain, CAStyle, УНФ Номенклатура)
  1142. $srcCondAppearance = $srcFormEl.SelectSingleNode("*[local-name()='Attributes']/*[local-name()='ConditionalAppearance']")
  1143. $srcCondAppearanceXml = if ($srcCondAppearance) { [regex]::Replace($srcCondAppearance.OuterXml, $nsStripPattern, '') } else { "" }
  1144. $mainAttrInfo = if ($BorrowMainAttr) { $srcMainInfo } else { $null }
  1145. $mainAttrName = if ($mainAttrInfo) { $mainAttrInfo.Name } else { "" }
  1146. if ($BorrowMainAttr -and -not $mainAttrInfo -and -not $RenderOnly) {
  1147. Warn " У формы нет основного реквизита — -BorrowMainAttribute проигнорирован"
  1148. }
  1149. # Имена реквизитов объекта нужны в обоих режимах: без заимствования — для кода пути в связях
  1150. # формы, с заимствованием — чтобы отличить реквизит (разрешается текстом) от стандартного поля
  1151. # У общей формы реквизиты берутся у владельца, выведенного из типа основного реквизита;
  1152. # у набора констант — ничего: код пути на константу не измерен, связь без основного реквизита
  1153. # вырезается с предупреждением, с ним — остаётся текстом
  1154. if ($isCommonForm) {
  1155. $cfOwner = Resolve-CommonFormOwner $srcFormEl
  1156. $srcAttrUuids = @{}
  1157. if ($cfOwner -and $cfOwner.Kind -eq 'Object') {
  1158. $srcAttrUuids = Get-SourceAttributeUuids $cfOwner.TypeName $cfOwner.ObjName
  1159. } elseif ($cfOwner -and $cfOwner.Kind -eq 'Constants') {
  1160. # Константы, на которые есть пути: с основным реквизитом путь на заимствованную — текстом
  1161. foreach ($cName in @((Collect-FormDataPaths $srcFormXmlPath $cfOwner.MainName).FirstLevel.Keys)) {
  1162. $cFile = Join-Path (Join-Path $cfgDir "Constants") "${cName}.xml"
  1163. if (-not (Test-Path $cFile)) { continue }
  1164. $cm = [regex]::Match([System.IO.File]::ReadAllText($cFile), '<Constant uuid="([^"]+)"')
  1165. if ($cm.Success) { $srcAttrUuids[$cName] = $cm.Groups[1].Value }
  1166. }
  1167. }
  1168. } else {
  1169. $maObj = Resolve-MainAttributeObject $srcFormEl $typeName $objName
  1170. $srcAttrUuids = Get-SourceAttributeUuids $maObj.TypeName $maObj.ObjName
  1171. }
  1172. # Реквизиты объекта, которые попадут в расширение: в режиме Form — только используемые формой
  1173. # (тот же сбор, что в Borrow-MainAttribute), в режиме All — все ($null)
  1174. $borrowedNames = $null
  1175. if ($mainAttrInfo -and $BorrowMainAttribute -eq 'Form') {
  1176. $borrowedNames = (Collect-FormDataPaths $srcFormXmlPath $srcMainAttrName).FirstLevel
  1177. }
  1178. $linkCtx = Get-LinkContext $srcFormEl $srcMainAttrName ([bool]$mainAttrInfo) $borrowedNames $srcAttrUuids $formAttrIds
  1179. # AutoCommandBar: keep ChildItems (buttons with CommandName→0). Autofill — как в источнике: Конфигуратор
  1180. # копирует значение, а true (умолчание) не пишет (замер М7б, эталон заимствования Конфигуратором)
  1181. $autoCmdXml = ""
  1182. if ($srcAutoCmd) {
  1183. $autoCmdXml = $srcAutoCmd.OuterXml
  1184. $autoCmdXml = [regex]::Replace($autoCmdXml, $nsStripPattern, '')
  1185. $autoCmdXml = [regex]::Replace($autoCmdXml, '<CommandName>[^<]*</CommandName>', '<CommandName>0</CommandName>')
  1186. $autoCmdXml = [regex]::Replace($autoCmdXml, '^(<AutoCommandBar\b[^>]*>)\s*<Autofill>true</Autofill>', '$1')
  1187. # Вложенный CommandSet выбрасывается целиком, а не опустошается: Конфигуратор в заимствованной
  1188. # форме оставляет только корневой (тот идёт свойством формы, здесь его нет).
  1189. $autoCmdXml = [regex]::Replace($autoCmdXml, '(?s)\s*<CommandSet>.*?</CommandSet>', '')
  1190. $autoCmdXml = [regex]::Replace($autoCmdXml, '\s*<CommandSet/>', '')
  1191. # Strip data-binding tags whose root attribute isn't borrowed
  1192. $autoCmdXml = Strip-FormBindings $autoCmdXml $mainAttrName
  1193. $autoCmdXml = Rewrite-ChoiceParameterLinks $autoCmdXml $linkCtx
  1194. $autoCmdXml = [regex]::Replace($autoCmdXml, '^<AutoCommandBar\b([^>]*[^/])>\s*</AutoCommandBar>$', '<AutoCommandBar$1/>')
  1195. }
  1196. # Картинка декорации в заимствованную форму не переносится: Конфигуратор выбрасывает <Picture>
  1197. # у PictureDecoration из обеих частей формы при любом виде картинки (своя, общая, стандартная)
  1198. # и не тянет за ней ни файл, ни общую картинку. Замер 8.3.27: 10 декораций в 5 формах УТ.
  1199. # Картинки кнопок, таблиц и полей картинки остаются — вместе с файлами, см. копирование ниже.
  1200. if ($srcChildItems) {
  1201. foreach ($decoPic in @($srcChildItems.SelectNodes(".//*[local-name()='PictureDecoration']/*[local-name()='Picture']"))) {
  1202. $prevWs = $decoPic.PreviousSibling
  1203. if ($prevWs -and ($prevWs.NodeType -eq 'Whitespace' -or $prevWs.NodeType -eq 'SignificantWhitespace')) {
  1204. $decoPic.ParentNode.RemoveChild($prevWs) | Out-Null
  1205. }
  1206. $decoPic.ParentNode.RemoveChild($decoPic) | Out-Null
  1207. }
  1208. }
  1209. # ChildItems: copy full tree, clean up base-config references
  1210. $childItemsXml = ""
  1211. if ($srcChildItems) {
  1212. $childItemsXml = $srcChildItems.OuterXml
  1213. $childItemsXml = [regex]::Replace($childItemsXml, $nsStripPattern, '')
  1214. # Replace all CommandName values with 0
  1215. $childItemsXml = [regex]::Replace($childItemsXml, '<CommandName>[^<]*</CommandName>', '<CommandName>0</CommandName>')
  1216. # Strip data-binding tags whose root attribute isn't borrowed
  1217. # (DataPath/TitleDataPath/FooterDataPath/HeaderDataPath/MultipleValue*/RowPicture*)
  1218. $childItemsXml = Strip-FormBindings $childItemsXml $mainAttrName
  1219. $childItemsXml = Rewrite-ChoiceParameterLinks $childItemsXml $linkCtx
  1220. # Вложенные CommandSet (у таблиц, полей табличного документа и т.п.) — целиком, см. выше.
  1221. # Исключение — набор таблицы самого основного реквизита, когда он заимствован: его команды
  1222. # (Find/CancelSearch динамического списка) снова разрешимы, и Конфигуратор набор оставляет
  1223. # (эталоны УТ CommonMain/ФайлыВТоме, StdPic_WithMain/ЖурналСкладскихАктов; без основного
  1224. # реквизита и у прочих элементов — выброшен во всех эталонах).
  1225. $keptCmdSets = [ordered]@{}
  1226. if ($mainAttrName) {
  1227. $mainTablePat = '(?s)(<Table name="[^"]+" id="\d+">(?:(?!<ChildItems>|</Table>|<CommandSet>).)*?<DataPath>' +
  1228. [regex]::Escape($mainAttrName) + '</DataPath>(?:(?!<ChildItems>|</Table>|<CommandSet>).)*?)(<CommandSet>.*?</CommandSet>)'
  1229. $childItemsXml = [regex]::Replace($childItemsXml, $mainTablePat, {
  1230. param($m)
  1231. $key = "@@KEPTCMDSET$($keptCmdSets.Count)@@"
  1232. $keptCmdSets[$key] = $m.Groups[2].Value
  1233. $m.Groups[1].Value + $key
  1234. })
  1235. }
  1236. $childItemsXml = [regex]::Replace($childItemsXml, '(?s)\s*<CommandSet>.*?</CommandSet>', '')
  1237. $childItemsXml = [regex]::Replace($childItemsXml, '\s*<CommandSet/>', '')
  1238. foreach ($key in $keptCmdSets.Keys) { $childItemsXml = $childItemsXml.Replace($key, $keptCmdSets[$key]) }
  1239. $childItemsXml = Rewrite-TypeLinks $childItemsXml $linkCtx
  1240. # Strip element-level Events (base form handlers not in extension)
  1241. $childItemsXml = [regex]::Replace($childItemsXml, '(?s)\s*<Events>.*?</Events>', '')
  1242. # Collect CommonPicture references from ChildItems and AutoCommandBar
  1243. $referencedPictures = @{}
  1244. $picRefs = [regex]::Matches($childItemsXml, '<xr:Ref>CommonPicture\.(\w+)</xr:Ref>')
  1245. foreach ($m in $picRefs) { $referencedPictures[$m.Groups[1].Value] = $true }
  1246. if ($autoCmdXml) {
  1247. $picRefs2 = [regex]::Matches($autoCmdXml, '<xr:Ref>CommonPicture\.(\w+)</xr:Ref>')
  1248. foreach ($m in $picRefs2) { $referencedPictures[$m.Groups[1].Value] = $true }
  1249. }
  1250. # Auto-borrow referenced CommonPictures (if not already borrowed)
  1251. $autoBorrowedPics = @()
  1252. $renderPics = @{}
  1253. foreach ($picName in $referencedPictures.Keys) {
  1254. if (-not (Test-ObjectBorrowed "CommonPicture" $picName)) {
  1255. $picSrcFile = Join-Path (Join-Path $cfgDir "CommonPictures") "${picName}.xml"
  1256. if ($RenderOnly) { if (Test-Path $picSrcFile) { $renderPics[$picName] = $true }; continue }
  1257. if (Test-Path $picSrcFile) {
  1258. $src = Read-SourceObject "CommonPicture" $picName
  1259. $borrowedXml = Build-BorrowedObjectXml "CommonPicture" $picName $src.Uuid $src.Properties
  1260. $targetDir = Join-Path $extDir "CommonPictures"
  1261. if (-not (Test-Path $targetDir)) {
  1262. New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
  1263. }
  1264. $targetFile = Join-Path $targetDir "${picName}.xml"
  1265. $encBom = New-Object System.Text.UTF8Encoding($true)
  1266. [System.IO.File]::WriteAllText($targetFile, $borrowedXml, $encBom)
  1267. Add-ToChildObjects "CommonPicture" $picName
  1268. $autoBorrowedPics += $picName
  1269. $script:borrowedFiles += $targetFile
  1270. Info " Auto-borrowed: CommonPicture.${picName}"
  1271. } else {
  1272. Warn " CommonPicture.${picName} not found in source config — will strip from form"
  1273. }
  1274. }
  1275. }
  1276. # Collect all borrowed CommonPictures (including previously borrowed)
  1277. $borrowedPicSet = @{}
  1278. $nsMgr2 = New-Object System.Xml.XmlNamespaceManager($script:xmlDoc.NameTable)
  1279. $nsMgr2.AddNamespace("md", $script:mdNs)
  1280. $picNodes = $script:xmlDoc.SelectNodes("//md:ChildObjects/md:CommonPicture", $nsMgr2)
  1281. foreach ($pn in $picNodes) { $borrowedPicSet[$pn.InnerText] = $true }
  1282. foreach ($rp in $renderPics.Keys) { $borrowedPicSet[$rp] = $true }
  1283. # Strip <Picture> blocks referencing non-borrowed CommonPictures
  1284. $picBlockPattern = '(?s)\s*<Picture>\s*<xr:Ref>CommonPicture\.(\w+)</xr:Ref>.*?</Picture>'
  1285. $picMatches = [regex]::Matches($childItemsXml, $picBlockPattern)
  1286. # Process in reverse order to preserve positions
  1287. for ($mi = $picMatches.Count - 1; $mi -ge 0; $mi--) {
  1288. $pm = $picMatches[$mi]
  1289. $cpName = $pm.Groups[1].Value
  1290. if (-not $borrowedPicSet.ContainsKey($cpName)) {
  1291. $childItemsXml = $childItemsXml.Remove($pm.Index, $pm.Length)
  1292. }
  1293. }
  1294. # Стандартные картинки (StdPicture.*) не вырезаются: Конфигуратор оставляет их у кнопок, подменю
  1295. # и страниц в обеих частях формы (эталоны 8.3.27, 26 элементов в 3 формах).
  1296. # Same Picture strip for AutoCommandBar
  1297. if ($autoCmdXml) {
  1298. $acPicMatches = [regex]::Matches($autoCmdXml, $picBlockPattern)
  1299. for ($mi = $acPicMatches.Count - 1; $mi -ge 0; $mi--) {
  1300. $pm = $acPicMatches[$mi]
  1301. $cpName = $pm.Groups[1].Value
  1302. if (-not $borrowedPicSet.ContainsKey($cpName)) {
  1303. $autoCmdXml = $autoCmdXml.Remove($pm.Index, $pm.Length)
  1304. }
  1305. }
  1306. }
  1307. # Auto-borrow Enums + EnumValues referenced via DesignTimeRef in ChoiceParameters
  1308. # Collect Enum -> [EnumValue names] map
  1309. $dtRefs = [regex]::Matches($childItemsXml, 'xr:DesignTimeRef">Enum\.(\w+)\.EnumValue\.(\w+)')
  1310. $referencedEnumValues = @{}
  1311. foreach ($m in $dtRefs) {
  1312. $eName = $m.Groups[1].Value
  1313. $evName = $m.Groups[2].Value
  1314. if (-not $referencedEnumValues.ContainsKey($eName)) { $referencedEnumValues[$eName] = @{} }
  1315. $referencedEnumValues[$eName][$evName] = $true
  1316. }
  1317. foreach ($enumName in $referencedEnumValues.Keys) {
  1318. if (-not $RenderOnly -and -not (Test-ObjectBorrowed "Enum" $enumName)) {
  1319. $enumSrcFile = Join-Path (Join-Path $cfgDir "Enums") "${enumName}.xml"
  1320. if (Test-Path $enumSrcFile) {
  1321. # Read source Enum to get UUID and EnumValue UUIDs
  1322. $srcParser = New-Object System.Xml.XmlDocument
  1323. $srcParser.PreserveWhitespace = $true
  1324. $srcParser.Load($enumSrcFile)
  1325. $srcEnumEl = $null
  1326. foreach ($cn in $srcParser.DocumentElement.ChildNodes) {
  1327. if ($cn.NodeType -eq 'Element') { $srcEnumEl = $cn; break }
  1328. }
  1329. $srcEnumUuid = $srcEnumEl.GetAttribute("uuid")
  1330. # Find source EnumValues by name
  1331. $enumValueXmls = @()
  1332. $neededValues = $referencedEnumValues[$enumName]
  1333. $srcNsMgr = New-Object System.Xml.XmlNamespaceManager($srcParser.NameTable)
  1334. $srcNsMgr.AddNamespace("md", $script:mdNs)
  1335. $srcEvNodes = $srcEnumEl.SelectNodes("md:ChildObjects/md:EnumValue", $srcNsMgr)
  1336. foreach ($evNode in $srcEvNodes) {
  1337. $evUuid = $evNode.GetAttribute("uuid")
  1338. $evNameNode = $evNode.SelectSingleNode("md:Properties/md:Name", $srcNsMgr)
  1339. if ($evNameNode -and $neededValues.ContainsKey($evNameNode.InnerText)) {
  1340. $newEvUuid = [guid]::NewGuid().ToString()
  1341. $enumValueXmls += @"
  1342. <EnumValue uuid="${newEvUuid}">
  1343. <InternalInfo/>
  1344. <Properties>
  1345. <ObjectBelonging>Adopted</ObjectBelonging>
  1346. <Name>$($evNameNode.InnerText)</Name>
  1347. <Comment/>
  1348. <ExtendedConfigurationObject>${evUuid}</ExtendedConfigurationObject>
  1349. </Properties>
  1350. </EnumValue>
  1351. "@
  1352. }
  1353. }
  1354. # Build borrowed Enum with EnumValues in ChildObjects
  1355. $src = Read-SourceObject "Enum" $enumName
  1356. $borrowedXml = Build-BorrowedObjectXml "Enum" $enumName $src.Uuid $src.Properties
  1357. if ($enumValueXmls.Count -gt 0) {
  1358. $evBlock = ($enumValueXmls -join "`r`n")
  1359. $borrowedXml = $borrowedXml -replace '<ChildObjects/>', "<ChildObjects>`r`n${evBlock}`r`n`t`t</ChildObjects>"
  1360. }
  1361. $targetDir = Join-Path $extDir "Enums"
  1362. if (-not (Test-Path $targetDir)) {
  1363. New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
  1364. }
  1365. $targetFile = Join-Path $targetDir "${enumName}.xml"
  1366. $encBom = New-Object System.Text.UTF8Encoding($true)
  1367. [System.IO.File]::WriteAllText($targetFile, $borrowedXml, $encBom)
  1368. Add-ToChildObjects "Enum" $enumName
  1369. $script:borrowedFiles += $targetFile
  1370. Info " Auto-borrowed: Enum.${enumName} (with $($enumValueXmls.Count) EnumValue(s))"
  1371. } else {
  1372. Warn " Enum.${enumName} not found in source config"
  1373. }
  1374. }
  1375. }
  1376. }
  1377. # Вне блока ChildItems: стили нужны и оформлению формы без элементов
  1378. # Auto-borrow StyleItems referenced in ChildItems and in the form's conditional appearance
  1379. # (стиль только из оформления Конфигуратор тоже заимствует — эталон УТ CAStyle)
  1380. # Pattern 1: <Font ref="style:XXX" kind="StyleItem"/>, <TitleFont ref="style:XXX" ... kind="StyleItem"/>
  1381. # Pattern 2: <BackColor>style:XXX</BackColor>, <TextColor>style:XXX</TextColor>, etc.
  1382. # Порядок первого упоминания — как в Python-порте (от него зависит порядок в ChildObjects)
  1383. $styleScanXml = $childItemsXml + $srcCondAppearanceXml
  1384. $referencedStyles = [ordered]@{}
  1385. $styleRefs1 = [regex]::Matches($styleScanXml, 'ref="style:(\w+)"[^>]*kind="StyleItem"')
  1386. foreach ($m in $styleRefs1) { $referencedStyles[$m.Groups[1].Value] = $true }
  1387. # Закрывающий тег может быть с префиксом: в оформлении значение — <dcscor:value>style:X</dcscor:value>
  1388. $styleRefs2 = [regex]::Matches($styleScanXml, '>style:(\w+)</[\w:]+>')
  1389. foreach ($m in $styleRefs2) { $referencedStyles[$m.Groups[1].Value] = $true }
  1390. foreach ($styleName in $referencedStyles.Keys) {
  1391. if (-not $RenderOnly -and -not (Test-ObjectBorrowed "StyleItem" $styleName)) {
  1392. $styleSrcFile = Join-Path (Join-Path $cfgDir "StyleItems") "${styleName}.xml"
  1393. if (Test-Path $styleSrcFile) {
  1394. $src = Read-SourceObject "StyleItem" $styleName
  1395. $borrowedXml = Build-BorrowedObjectXml "StyleItem" $styleName $src.Uuid $src.Properties
  1396. $targetDir = Join-Path $extDir "StyleItems"
  1397. if (-not (Test-Path $targetDir)) {
  1398. New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
  1399. }
  1400. $targetFile = Join-Path $targetDir "${styleName}.xml"
  1401. $encBom = New-Object System.Text.UTF8Encoding($true)
  1402. [System.IO.File]::WriteAllText($targetFile, $borrowedXml, $encBom)
  1403. Add-ToChildObjects "StyleItem" $styleName
  1404. $script:borrowedFiles += $targetFile
  1405. Info " Auto-borrowed: StyleItem.${styleName}"
  1406. }
  1407. # Файла нет — встроенный стиль платформы (ImportantColor, AccentColor…): заимствовать
  1408. # нечего, пропускаем молча. Пользовательский стиль, на который ссылается форма, в
  1409. # валидном источнике существует всегда — предупреждение было только шумом.
  1410. }
  1411. }
  1412. # Открывающий тег <Form ...> берём из исходной формы — ради её объявлений пространств имён,
  1413. # но version подставляем СВОЮ: форма обязана нести версию расширения, иначе платформа
  1414. # отвергает импорт (форма 2.13 внутри расширения 2.17). Раньше тег копировался целиком,
  1415. # и версия источника молча побеждала.
  1416. $xmlDecl = '<?xml version="1.0" encoding="UTF-8"?>'
  1417. $formTag = "<Form version=`"${formVersion}`">"
  1418. if ($srcFormContent -match '(?s)^(<\?xml[^?]*\?>)') { $xmlDecl = $Matches[1] }
  1419. if ($srcFormContent -match '(<Form[^>]*>)') {
  1420. $srcTag = $Matches[1]
  1421. $srcNs = $srcTag -replace '^<Form\s*', '' -replace '\s*/?>$', '' -replace '\s*version="[^"]*"', ''
  1422. # 2.21 (8.5): пространство палитры. Место строгое — после lf, перед style.
  1423. if ((Get-FormatRank $formVersion) -ge 221 -and $srcNs -notmatch 'xmlns:pal=') {
  1424. $srcNs = $srcNs -replace ' xmlns:style=', ' xmlns:pal="http://v8.1c.ru/8.1/data/ui/colors/palette" xmlns:style='
  1425. }
  1426. $formTag = if ($srcNs) { "<Form $srcNs version=`"${formVersion}`">" } else { "<Form version=`"${formVersion}`">" }
  1427. }
  1428. # Build output Form.xml
  1429. $formXmlSb = New-Object System.Text.StringBuilder
  1430. $formXmlSb.Append($xmlDecl) | Out-Null
  1431. $formXmlSb.Append("`r`n") | Out-Null
  1432. $formXmlSb.Append($formTag) | Out-Null
  1433. $formXmlSb.Append("`r`n") | Out-Null
  1434. # Part 1: form properties + AutoCommandBar + ChildItems
  1435. foreach ($propXml in $formProps) {
  1436. $propXml = [regex]::Replace($propXml, $nsStripPattern, '')
  1437. $formXmlSb.Append("`t$propXml`r`n") | Out-Null
  1438. }
  1439. if ($autoCmdXml) {
  1440. $formXmlSb.Append("`t$autoCmdXml") | Out-Null
  1441. $formXmlSb.Append("`r`n") | Out-Null
  1442. }
  1443. if ($childItemsXml) {
  1444. $formXmlSb.Append("`t$childItemsXml") | Out-Null
  1445. $formXmlSb.Append("`r`n") | Out-Null
  1446. }
  1447. # Attributes: основной реквизит (с -BorrowMainAttribute) и условное оформление формы — после него
  1448. $withMainAttr = $BorrowMainAttr -and $mainAttrInfo
  1449. if ($withMainAttr -or $srcCondAppearanceXml) {
  1450. $formXmlSb.Append("`t<Attributes>`r`n") | Out-Null
  1451. if ($withMainAttr) { $formXmlSb.Append("`t`t$($mainAttrInfo.Xml)`r`n") | Out-Null }
  1452. if ($srcCondAppearanceXml) { $formXmlSb.Append("`t`t$srcCondAppearanceXml`r`n") | Out-Null }
  1453. $formXmlSb.Append("`t</Attributes>") | Out-Null
  1454. } else {
  1455. $formXmlSb.Append("`t<Attributes/>") | Out-Null
  1456. }
  1457. $formXmlSb.Append("`r`n") | Out-Null
  1458. # BaseForm: same content, indented one more level (многострочный текст не сдвигается)
  1459. $formXmlSb.Append("`t<BaseForm version=`"${formVersion}`">") | Out-Null
  1460. $formXmlSb.Append("`r`n") | Out-Null
  1461. foreach ($propXml in $formProps) {
  1462. $propXml = [regex]::Replace($propXml, $nsStripPattern, '')
  1463. $formXmlSb.Append((Get-BaseFormIndented $propXml "`t`t") + "`r`n") | Out-Null
  1464. }
  1465. if ($autoCmdXml) {
  1466. $formXmlSb.Append((Get-BaseFormIndented $autoCmdXml "`t`t") + "`r`n") | Out-Null
  1467. }
  1468. if ($childItemsXml) {
  1469. $formXmlSb.Append((Get-BaseFormIndented $childItemsXml "`t`t") + "`r`n") | Out-Null
  1470. }
  1471. # BaseForm Attributes: same as main section
  1472. if ($withMainAttr -or $srcCondAppearanceXml) {
  1473. $formXmlSb.Append("`t`t<Attributes>`r`n") | Out-Null
  1474. # В BaseForm та же секция на уровень глубже — сдвиг тот же, что у ChildItems
  1475. if ($withMainAttr) { $formXmlSb.Append((Get-BaseFormIndented $mainAttrInfo.Xml "`t`t`t") + "`r`n") | Out-Null }
  1476. if ($srcCondAppearanceXml) { $formXmlSb.Append((Get-BaseFormIndented $srcCondAppearanceXml "`t`t`t") + "`r`n") | Out-Null }
  1477. $formXmlSb.Append("`t`t</Attributes>") | Out-Null
  1478. } else {
  1479. $formXmlSb.Append("`t`t<Attributes/>") | Out-Null
  1480. }
  1481. $formXmlSb.Append("`r`n") | Out-Null
  1482. $formXmlSb.Append("`t</BaseForm>") | Out-Null
  1483. $formXmlSb.Append("`r`n") | Out-Null
  1484. $formXmlSb.Append("</Form>") | Out-Null
  1485. # Динамический список: оболочка его основной таблицы и тильда у путей полей — в конце запуска
  1486. # (шаги 14a и 14c), по итоговому составу расширения — реквизиты основной таблицы заимствует
  1487. # Borrow-MainAttribute уже после формы, а в пакете — и соседние формы.
  1488. $formXmlText = $formXmlSb.ToString()
  1489. $pendingDynList = ($withMainAttr -and ($mainAttrInfo.Xml -match ':DynamicList<' -or $mainAttrInfo.Xml -match 'xsi:type="DynamicList"'))
  1490. # Write Form.xml
  1491. $formXmlDir = Join-Path $extFormDir "Ext"
  1492. if (-not $RenderOnly -and -not (Test-Path $formXmlDir)) {
  1493. New-Item -ItemType Directory -Path $formXmlDir -Force | Out-Null
  1494. }
  1495. $formXmlFile = Join-Path $formXmlDir "Form.xml"
  1496. # Пустой элемент: XmlWriter отдаёт `<a />`, Конфигуратор пишет `<a/>`. Внутри
  1497. # CDATA/комментария ` />` может быть содержимым (там `>` не экранируется),
  1498. # поэтому они идут первыми ветками альтернации и возвращаются как есть.
  1499. # Здесь источник не XmlWriter, а OuterXml исходного документа — спацовывает так же.
  1500. $formXmlText = [regex]::Replace($formXmlText, '(?s)<!\[CDATA\[.*?\]\]>|<!--.*?-->|(?<=\S) />', { param($m) if ($m.Value -eq ' />') { '/>' } else { $m.Value } })
  1501. # Файл создаём мы — канон выгрузки: CRLF в разделителях строк.
  1502. $formXmlText = ($formXmlText -replace "`r`n", "`n") -replace "`n", "`r`n"
  1503. if ($RenderOnly) {
  1504. $script:droppedLinks = @()
  1505. return $formXmlText
  1506. }
  1507. [System.IO.File]::WriteAllText($formXmlFile, $formXmlText, $enc)
  1508. if ($pendingDynList) {
  1509. $dlMt = [regex]::Match($mainAttrInfo.Xml, '<MainTable>([^<]*)</MainTable>')
  1510. $dlQt = [regex]::Match($mainAttrInfo.Xml, '(?s)<QueryText>(.*?)</QueryText>')
  1511. $script:dynListForms += @{
  1512. File = $formXmlFile; MainName = $mainAttrInfo.Name
  1513. Manual = ($mainAttrInfo.Xml -match '<ManualQuery>true</ManualQuery>')
  1514. MainTable = $(if ($dlMt.Success) { $dlMt.Groups[1].Value.Trim() } else { '' })
  1515. Query = $(if ($dlQt.Success) { [System.Net.WebUtility]::HtmlDecode($dlQt.Groups[1].Value) } else { '' })
  1516. }
  1517. }
  1518. Info " Created: $formXmlFile"
  1519. if ($script:droppedLinks.Count -gt 0) {
  1520. $uniq = @($script:droppedLinks | Sort-Object -Unique)
  1521. Warn " Вырезано связей формы: $($uniq.Count) — путь не разрешается в расширении: $($uniq -join ', ')"
  1522. $script:droppedLinks = @()
  1523. }
  1524. # 6. Create empty Module.bsl — but NEVER overwrite an existing one (re-borrow must
  1525. # not clobber user code added to the form module).
  1526. $moduleDir = Join-Path $formXmlDir "Form"
  1527. if (-not (Test-Path $moduleDir)) {
  1528. New-Item -ItemType Directory -Path $moduleDir -Force | Out-Null
  1529. }
  1530. $moduleBslFile = Join-Path $moduleDir "Module.bsl"
  1531. if (Test-Path $moduleBslFile) {
  1532. Info " Preserved existing Module.bsl"
  1533. } else {
  1534. [System.IO.File]::WriteAllText($moduleBslFile, "", $enc)
  1535. Info " Created: $moduleBslFile"
  1536. }
  1537. # 6b. Встроенные картинки элементов. Form.xml ссылается на них как <xr:Abs>Файл</xr:Abs>, а сам файл
  1538. # лежит в Ext/Form/Items/<Элемент>/<Файл>; без него платформа отвергает расширение («Файл не найден»).
  1539. # Конфигуратор копирует их байт в байт. Берём ровно то, на что ссылается скелет (картинки декораций
  1540. # выброшены выше). Уже лежащий файл не перезаписываем: его могли заменить в расширении.
  1541. $picFiles = @()
  1542. $srcItemsDir = Join-Path (Join-Path (Split-Path $srcFormXmlPath -Parent) "Form") "Items"
  1543. $picRels = New-Object System.Collections.Generic.List[string]
  1544. foreach ($sect in @($srcAutoCmd, $srcChildItems)) {
  1545. if (-not $sect) { continue }
  1546. foreach ($absNode in @($sect.SelectNodes(".//*[local-name()='Abs' and namespace-uri()='http://v8.1c.ru/8.3/xcf/readable']"))) {
  1547. $picOwner = $absNode.ParentNode.ParentNode
  1548. $picElName = $picOwner.GetAttribute("name")
  1549. $picFileName = $absNode.InnerText.Trim()
  1550. if (-not $picElName -or -not $picFileName) { continue }
  1551. # Платформа пишет сюда голое имя файла. Иное (путь, «..») — не наша выгрузка: мимо Items не ходим.
  1552. if ($picElName -match '[\\/]' -or $picFileName -match '[\\/]' -or
  1553. $picElName -match '^\.\.?$' -or $picFileName -match '^\.\.?$') {
  1554. Warn " Картинка элемента пропущена — не имя файла: $picElName / $picFileName"
  1555. continue
  1556. }
  1557. $rel = "$picElName/$picFileName"
  1558. if (-not $picRels.Contains($rel)) { $picRels.Add($rel) }
  1559. }
  1560. }
  1561. $picRelArr = $picRels.ToArray()
  1562. [Array]::Sort($picRelArr, [System.StringComparer]::Ordinal)
  1563. foreach ($rel in $picRelArr) {
  1564. $picParts = $rel.Split('/')
  1565. $srcPic = Join-Path (Join-Path $srcItemsDir $picParts[0]) $picParts[1]
  1566. $dstPicDir = Join-Path (Join-Path $moduleDir "Items") $picParts[0]
  1567. $dstPic = Join-Path $dstPicDir $picParts[1]
  1568. if (Test-Path -LiteralPath $dstPic) {
  1569. Info " Preserved existing: $dstPic"
  1570. continue
  1571. }
  1572. if (-not (Test-Path -LiteralPath $srcPic -PathType Leaf)) {
  1573. Warn " Картинка элемента не найдена в источнике: $srcPic"
  1574. continue
  1575. }
  1576. if (-not (Test-Path -LiteralPath $dstPicDir)) { New-Item -ItemType Directory -Path $dstPicDir -Force | Out-Null }
  1577. Copy-Item -LiteralPath $srcPic -Destination $dstPic
  1578. $picFiles += $dstPic
  1579. Info " Copied: $dstPic"
  1580. }
  1581. # 7. Register form: общая форма — в Configuration.xml, форма объекта — в ChildObjects владельца
  1582. if ($isCommonForm) {
  1583. if (-not $commonFormRegistered) { Add-ToChildObjects $typeName $objName }
  1584. } else {
  1585. if (-not $Rebuild) { Register-FormInObject $typeName $objName $formName }
  1586. }
  1587. return @($formMetaFile, $formXmlFile, $moduleBslFile) + $picFiles
  1588. }
  1589. # --- 10d. Helper: register form in parent object's ChildObjects ---
  1590. function Register-FormInObject {
  1591. param([string]$typeName, [string]$objName, [string]$formName)
  1592. $dirName = $childTypeDirMap[$typeName]
  1593. $objFile = Join-Path (Join-Path $extDir $dirName) "${objName}.xml"
  1594. if (-not (Test-Path $objFile)) {
  1595. Warn "Parent object file not found: $objFile — form not registered in ChildObjects"
  1596. return
  1597. }
  1598. $objDoc = New-Object System.Xml.XmlDocument
  1599. $objDoc.PreserveWhitespace = $true
  1600. $objDoc.Load($objFile)
  1601. $objNs = New-Object System.Xml.XmlNamespaceManager($objDoc.NameTable)
  1602. $objNs.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
  1603. # Find the type element
  1604. $objEl = $null
  1605. foreach ($c in $objDoc.DocumentElement.ChildNodes) {
  1606. if ($c.NodeType -eq 'Element') { $objEl = $c; break }
  1607. }
  1608. if (-not $objEl) {
  1609. Warn "No type element in $objFile — form not registered"
  1610. return
  1611. }
  1612. # Find or create ChildObjects
  1613. $childObjs = $objEl.SelectSingleNode("md:ChildObjects", $objNs)
  1614. if (-not $childObjs) {
  1615. # Create ChildObjects element
  1616. $childObjs = $objDoc.CreateElement("ChildObjects", "http://v8.1c.ru/8.3/MDClasses")
  1617. $objEl.AppendChild($objDoc.CreateWhitespace("`r`n`t`t")) | Out-Null
  1618. $objEl.AppendChild($childObjs) | Out-Null
  1619. $objEl.AppendChild($objDoc.CreateWhitespace("`r`n`t")) | Out-Null
  1620. }
  1621. # Check dedup
  1622. foreach ($c in $childObjs.ChildNodes) {
  1623. if ($c.NodeType -eq 'Element' -and $c.LocalName -eq "Form" -and $c.InnerText -eq $formName) {
  1624. Warn "Form '$formName' already in ChildObjects of ${typeName}.${objName}"
  1625. return
  1626. }
  1627. }
  1628. # Expand self-closing if needed
  1629. if (-not $childObjs.HasChildNodes -or $childObjs.IsEmpty) {
  1630. $closeWs = $objDoc.CreateWhitespace("`r`n`t`t")
  1631. $childObjs.AppendChild($closeWs) | Out-Null
  1632. }
  1633. # Add <Form>formName</Form>
  1634. $formEl = $objDoc.CreateElement("Form", "http://v8.1c.ru/8.3/MDClasses")
  1635. $formEl.InnerText = $formName
  1636. $trailing = $childObjs.LastChild
  1637. $ws = $objDoc.CreateWhitespace("`r`n`t`t`t")
  1638. # Место — по канону вида (у документа форма до ТЧ, у справочника после)
  1639. $anchor = Find-ChildAnchor $childObjs "Form" $objEl.LocalName
  1640. if ($anchor) {
  1641. $childObjs.InsertBefore($formEl, $anchor) | Out-Null
  1642. $childObjs.InsertBefore($ws, $anchor) | Out-Null
  1643. } elseif ($trailing -and ($trailing.NodeType -eq 'Whitespace' -or $trailing.NodeType -eq 'SignificantWhitespace')) {
  1644. $childObjs.InsertBefore($ws, $trailing) | Out-Null
  1645. $childObjs.InsertBefore($formEl, $trailing) | Out-Null
  1646. } else {
  1647. $childObjs.AppendChild($ws) | Out-Null
  1648. $childObjs.AppendChild($formEl) | Out-Null
  1649. }
  1650. # Save object XML
  1651. # Стиль исходника снимаем ДО записи: правка чужого файла наследует его BOM/EOL/заголовок
  1652. # (#44/#46/#47), новый файл получает канон выгрузки. Зеркало _detect_xml_style в py-порту.
  1653. $style2 = Detect-XmlStyle $objFile
  1654. $settings2 = New-Object System.Xml.XmlWriterSettings
  1655. $settings2.Encoding = New-Object System.Text.UTF8Encoding($true)
  1656. $settings2.Indent = $false
  1657. $settings2.NewLineHandling = [System.Xml.NewLineHandling]::None
  1658. $memStream2 = New-Object System.IO.MemoryStream
  1659. $writer2 = [System.Xml.XmlWriter]::Create($memStream2, $settings2)
  1660. $objDoc.Save($writer2)
  1661. $writer2.Flush(); $writer2.Close()
  1662. $text2 = [System.Text.Encoding]::UTF8.GetString($memStream2.ToArray())
  1663. $memStream2.Close()
  1664. $text2 = Finalize-XmlText $text2 $style2
  1665. $writeBom2 = ($null -eq $style2) -or $style2.bom
  1666. [System.IO.File]::WriteAllText($objFile, $text2, (New-Object System.Text.UTF8Encoding($writeBom2)))
  1667. Info " Registered form in: $objFile"
  1668. }
  1669. # --- 10e. Helper: check if object is already borrowed in extension ---
  1670. function Test-ObjectBorrowed {
  1671. param([string]$typeName, [string]$objName)
  1672. $dirName = $childTypeDirMap[$typeName]
  1673. $objFile = Join-Path (Join-Path $extDir $dirName) "${objName}.xml"
  1674. return (Test-Path $objFile)
  1675. }
  1676. # --- 10f. Helper: пометка расширенного свойства (<xr:PropertyState>) ---
  1677. # Свойство появилось в формате 2.19 (8.3.26): на 2.18 и ниже платформа молча выбрасывает элемент
  1678. # при загрузке. С 2.19 Конфигуратор ставит его сам при выгрузке — эмитим, чтобы исходники навыка
  1679. # совпадали с эталоном. Имя свойства = базовое имя файла модуля (Module / ObjectModule / …),
  1680. # у заимствованной формы — Form. Ставит тот, кто создал файл модуля (или форму).
  1681. function Build-PropertyStateXml {
  1682. param([string]$propertyName, [string]$indent)
  1683. $sb = New-Object System.Text.StringBuilder
  1684. $sb.AppendLine("${indent}<xr:PropertyState>") | Out-Null
  1685. $sb.AppendLine("${indent}`t<xr:Property>${propertyName}</xr:Property>") | Out-Null
  1686. $sb.AppendLine("${indent}`t<xr:State>Extended</xr:State>") | Out-Null
  1687. $sb.Append("${indent}</xr:PropertyState>") | Out-Null
  1688. return $sb.ToString()
  1689. }
  1690. function Set-PropertyStateFlag {
  1691. param([string]$objFile, [string]$propertyName, [string]$formatVersion)
  1692. if ((Get-FormatRank $formatVersion) -lt 219) { return }
  1693. if (-not (Test-Path $objFile)) { return }
  1694. $enc = New-Object System.Text.UTF8Encoding($true)
  1695. $text = [System.IO.File]::ReadAllText($objFile, $enc)
  1696. $nl = if ($text -match "`r`n") { "`r`n" } else { "`n" }
  1697. # ПЕРВЫЙ <InternalInfo> в файле — собственный у объекта: у реквизитов и подобъектов свои,
  1698. # но они лежат ниже, внутри <ChildObjects>.
  1699. $empty = [regex]::Match($text, '([ \t]*)<InternalInfo\s*/>')
  1700. $open = [regex]::Match($text, '(?s)([ \t]*)<InternalInfo>(.*?)</InternalInfo>')
  1701. if ($empty.Success -and (-not $open.Success -or $empty.Index -lt $open.Index)) {
  1702. $ind = $empty.Groups[1].Value
  1703. $block = Build-PropertyStateXml $propertyName ($ind + "`t")
  1704. $replacement = "${ind}<InternalInfo>${nl}${block}${nl}${ind}</InternalInfo>"
  1705. $text = $text.Remove($empty.Index, $empty.Length).Insert($empty.Index, $replacement)
  1706. } elseif ($open.Success) {
  1707. if ($open.Groups[2].Value -match "<xr:Property>$([regex]::Escape($propertyName))</xr:Property>") { return }
  1708. $ind = $open.Groups[1].Value
  1709. $block = Build-PropertyStateXml $propertyName ($ind + "`t")
  1710. # Дописываем в КОНЕЦ InternalInfo: у Конфигуратора PropertyState идёт после GeneratedType.
  1711. $closeAt = $open.Index + $open.Length - "</InternalInfo>".Length - $ind.Length
  1712. $text = $text.Insert($closeAt, "${block}${nl}")
  1713. } else {
  1714. return
  1715. }
  1716. [System.IO.File]::WriteAllText($objFile, $text, $enc)
  1717. }
  1718. # --- 10g. Helper: пустой модуль заимствованного объекта ---
  1719. function New-BorrowedModuleFile {
  1720. param([string]$typeName, [string]$objName, [string]$moduleKind)
  1721. $dirName = $childTypeDirMap[$typeName]
  1722. $objDir = Join-Path (Join-Path $extDir $dirName) $objName
  1723. $moduleDir = Join-Path $objDir "Ext"
  1724. if (-not (Test-Path $moduleDir)) { New-Item -ItemType Directory -Path $moduleDir -Force | Out-Null }
  1725. # NEVER overwrite an existing one: повторное заимствование не должно затирать дописанный код
  1726. # (то же правило, что у модуля формы).
  1727. $moduleFile = Join-Path $moduleDir "${moduleKind}.bsl"
  1728. if (Test-Path $moduleFile) {
  1729. Info " Preserved existing ${moduleKind}.bsl"
  1730. } else {
  1731. $enc = New-Object System.Text.UTF8Encoding($true)
  1732. [System.IO.File]::WriteAllText($moduleFile, "", $enc)
  1733. Info " Created: $moduleFile"
  1734. }
  1735. # Флаг ставим и для уже существовавшего файла: состояние объекта должно отражать факт модуля.
  1736. Set-PropertyStateFlag (Join-Path (Join-Path $extDir $dirName) "${objName}.xml") $moduleKind $script:formatVersion
  1737. return $moduleFile
  1738. }
  1739. # --- 11. Helper: generate InternalInfo XML ---
  1740. function Build-InternalInfoXml {
  1741. param([string]$typeName, [string]$objName, [string]$indent)
  1742. $types = $script:generatedTypes[$typeName]
  1743. if (-not $types -or $types.Count -eq 0) {
  1744. return "${indent}<InternalInfo/>"
  1745. }
  1746. $sb = New-Object System.Text.StringBuilder
  1747. $sb.AppendLine("${indent}<InternalInfo>") | Out-Null
  1748. # ExchangePlan: ThisNode UUID before GeneratedTypes
  1749. if ($typeName -eq "ExchangePlan") {
  1750. $thisNodeUuid = [guid]::NewGuid().ToString()
  1751. $sb.AppendLine("${indent}`t<xr:ThisNode>${thisNodeUuid}</xr:ThisNode>") | Out-Null
  1752. }
  1753. foreach ($gt in $types) {
  1754. $fullName = "$($gt.prefix).${objName}"
  1755. $typeId = [guid]::NewGuid().ToString()
  1756. $valueId = [guid]::NewGuid().ToString()
  1757. $sb.AppendLine("${indent}`t<xr:GeneratedType name=`"${fullName}`" category=`"$($gt.category)`">") | Out-Null
  1758. $sb.AppendLine("${indent}`t`t<xr:TypeId>${typeId}</xr:TypeId>") | Out-Null
  1759. $sb.AppendLine("${indent}`t`t<xr:ValueId>${valueId}</xr:ValueId>") | Out-Null
  1760. $sb.AppendLine("${indent}`t</xr:GeneratedType>") | Out-Null
  1761. }
  1762. $sb.Append("${indent}</InternalInfo>") | Out-Null
  1763. return $sb.ToString()
  1764. }
  1765. # --- 11b. Collect DataPath references from source Form.xml ---
  1766. # --- 11b1. Основной реквизит исходной формы ---
  1767. # Переносится ЦЕЛИКОМ, а не собирается из констант: имя, тип и состав детей зависят от вида формы.
  1768. # У формы объекта это «Объект»/<Тип>Object + SavedData/UseAlways/Columns, у формы списка —
  1769. # «Список»/DynamicList + Settings, у формы записи регистра — «Запись»/RecordManager + SavedData.
  1770. # Синтез фиксированного набора давал для необъектных форм «Исключение XDTO» при загрузке.
  1771. # Конфигуратор меняет у скопированного реквизита только id (эталоны Issue64UtB, Issue66Example2).
  1772. # Имена реквизитов ИСХОДНОЙ формы → их id. Ссылки параметров выбора адресуют реквизит формы
  1773. # именно по id базовой формы (см. Rewrite-ChoiceParameterLinks).
  1774. function Get-FormAttributeIds {
  1775. param($formEl)
  1776. $result = @{}
  1777. $attrs = $formEl.SelectSingleNode("*[local-name()='Attributes']")
  1778. if (-not $attrs) { return $result }
  1779. foreach ($a in $attrs.ChildNodes) {
  1780. if ($a.NodeType -ne 'Element' -or $a.LocalName -ne 'Attribute') { continue }
  1781. $nm = $a.GetAttribute("name"); $id = $a.GetAttribute("id")
  1782. if ($nm -and $id) { $result[$nm] = $id }
  1783. }
  1784. return $result
  1785. }
  1786. # Контекст разрешения путей в связях формы (см. Resolve-LinkDataPath) — всё по ИСХОДНОЙ форме:
  1787. # колонки реквизитов формы, колонки AdditionalColumns, элементы-таблицы и вид основного реквизита.
  1788. function Get-LinkContext {
  1789. param($formEl, [string]$mainName, [bool]$mainBorrowed, $borrowedNames, $attrUuids, $formAttrIds)
  1790. $cols = @{}; $addCols = @{}; $tables = @{}; $kind = $null
  1791. $attrs = $formEl.SelectSingleNode("*[local-name()='Attributes']")
  1792. if ($attrs) {
  1793. foreach ($a in $attrs.ChildNodes) {
  1794. if ($a.NodeType -ne 'Element' -or $a.LocalName -ne 'Attribute') { continue }
  1795. $nm = $a.GetAttribute("name")
  1796. $columns = $a.SelectSingleNode("*[local-name()='Columns']")
  1797. if ($columns) {
  1798. foreach ($c in $columns.ChildNodes) {
  1799. if ($c.NodeType -ne 'Element') { continue }
  1800. if ($c.LocalName -eq 'Column') {
  1801. $cols["$nm.$($c.GetAttribute('name'))"] = $c.GetAttribute('id')
  1802. } elseif ($c.LocalName -eq 'AdditionalColumns') {
  1803. $tblPath = $c.GetAttribute('table')
  1804. foreach ($ac in @($c.SelectNodes("*[local-name()='Column']"))) {
  1805. $addCols["$tblPath.$($ac.GetAttribute('name'))"] = $ac.GetAttribute('id')
  1806. }
  1807. }
  1808. }
  1809. }
  1810. if ($mainName -and $nm -ceq $mainName) {
  1811. $typeNode = $a.SelectSingleNode("*[local-name()='Type']/*[local-name()='Type']")
  1812. if ($typeNode) {
  1813. # Тип без имени объекта (cfg:ConstantsSet) — тоже вид
  1814. $tm = [regex]::Match($typeNode.InnerText.Trim(), '^(?:\w+:)?(\w+)(?:\.|$)')
  1815. if ($tm.Success -and $script:mainAttrKinds.ContainsKey($tm.Groups[1].Value)) { $kind = $script:mainAttrKinds[$tm.Groups[1].Value] }
  1816. }
  1817. }
  1818. }
  1819. }
  1820. $items = $formEl.SelectSingleNode("*[local-name()='ChildItems']")
  1821. if ($items) {
  1822. foreach ($t in @($items.SelectNodes(".//*[local-name()='Table']"))) {
  1823. $dp = $t.SelectSingleNode("*[local-name()='DataPath']")
  1824. if ($dp) { $tables[$t.GetAttribute('name')] = @{ Id = $t.GetAttribute('id'); Path = $dp.InnerText.Trim() } }
  1825. }
  1826. }
  1827. $mainId = if ($mainName -and $formAttrIds.ContainsKey($mainName)) { $formAttrIds[$mainName] } else { "1" }
  1828. return @{
  1829. MainName = $mainName; MainId = $mainId; MainBorrowed = $mainBorrowed; MainKind = $kind; BorrowedNames = $borrowedNames
  1830. AttrUuids = $attrUuids; FormAttrIds = $formAttrIds; FormAttrCols = $cols; AddCols = $addCols; Tables = $tables
  1831. }
  1832. }
  1833. # Ключ сравнения имён в тексте запроса: язык запросов регистронезависим, Ё и Е — одна буква.
  1834. function Get-QueryKey([string]$s) {
  1835. return $s.ToUpperInvariant().Replace([string][char]0x0401, [string][char]0x0415)
  1836. }
  1837. # Виды таблиц языка запросов (рус. и англ.) → вид метаданных. Ключи — через Get-QueryKey.
  1838. $script:queryTableKinds = @{}
  1839. foreach ($qk in @(
  1840. @("Справочник","Catalog"), @("Документ","Document"), @("Перечисление","Enum"),
  1841. @("ПланВидовХарактеристик","ChartOfCharacteristicTypes"), @("ПланСчетов","ChartOfAccounts"),
  1842. @("ПланВидовРасчета","ChartOfCalculationTypes"), @("ПланОбмена","ExchangePlan"),
  1843. @("БизнесПроцесс","BusinessProcess"), @("Задача","Task"),
  1844. @("РегистрСведений","InformationRegister"), @("РегистрНакопления","AccumulationRegister"),
  1845. @("РегистрБухгалтерии","AccountingRegister"), @("РегистрРасчета","CalculationRegister"),
  1846. @("ЖурналДокументов","DocumentJournal"), @("Константа","Constant"),
  1847. @("Последовательность","Sequence"), @("КритерийОтбора","FilterCriterion"),
  1848. @("ВнешнийИсточникДанных","ExternalDataSource"))) {
  1849. $script:queryTableKinds[(Get-QueryKey $qk[0])] = $qk[1]
  1850. $script:queryTableKinds[(Get-QueryKey $qk[1])] = $qk[1]
  1851. }
  1852. # Ключевые слова языка запросов, которые могут стоять сразу за таблицей вместо псевдонима.
  1853. $script:queryAliasStopWords = @{}
  1854. foreach ($kw in @("ГДЕ","WHERE","ЛЕВОЕ","LEFT","ПРАВОЕ","RIGHT","ПОЛНОЕ","FULL","ВНУТРЕННЕЕ","INNER",
  1855. "ВНЕШНЕЕ","OUTER","СОЕДИНЕНИЕ","JOIN","ПО","ON","СГРУППИРОВАТЬ","GROUP","УПОРЯДОЧИТЬ","ORDER",
  1856. "ИМЕЮЩИЕ","HAVING","ОБЪЕДИНИТЬ","UNION","ДЛЯ","FOR","ИТОГИ","TOTALS","ИНДЕКСИРОВАТЬ","INDEX",
  1857. "ИЗ","FROM","ВЫБРАТЬ","SELECT","И","AND","ИЛИ","OR","НЕ","NOT","КОГДА","WHEN","ТОГДА","THEN",
  1858. "ИНАЧЕ","ELSE","КОНЕЦ","END","ПОМЕСТИТЬ","INTO","ССЫЛКА","REFS","В","IN","МЕЖДУ","BETWEEN",
  1859. "ПОДОБНО","LIKE","ЕСТЬ","IS","ИЕРАРХИИ","HIERARCHY","ВОЗР","ASC","УБЫВ","DESC","АВТОУПОРЯДОЧИВАНИЕ",
  1860. "AUTOORDER","ИЗМЕНЕНИЯ","UPDATE","ВСЕ","ALL")) { $script:queryAliasStopWords[(Get-QueryKey $kw)] = $true }
  1861. # Стандартные поля по видам объектов (рус. и англ.) — есть у таблицы без заимствования реквизитов.
  1862. # У каждого вида свои: Номер/Дата — стандартные у документа, а у справочника это обычные реквизиты,
  1863. # которых в оболочке нет. Неизвестный вид — только общие поля. Поля, которые включаются свойством
  1864. # объекта (Родитель, Владелец, Период регистра сведений…), — в $script:queryGatedStd. Ключи — Get-QueryKey.
  1865. $script:queryStdByKind = @{}
  1866. $qsCommon = @("Ссылка","Ref","ПометкаУдаления","DeletionMark","Предопределенный","Predefined",
  1867. "ИмяПредопределенныхДанных","PredefinedDataName","ВерсияДанных","DataVersion","Представление",
  1868. "Presentation","DefaultPicture")
  1869. $qsByKind = @{
  1870. "Catalog" = @("Код","Code","Наименование","Description")
  1871. "Document" = @("Номер","Number","Дата","Date","Проведен","Posted","МоментВремени","PointInTime")
  1872. "ChartOfCharacteristicTypes" = @("Код","Code","Наименование","Description","ТипЗначения","ValueType")
  1873. "ChartOfAccounts" = @("Код","Code","Наименование","Description","Родитель","Parent","Порядок","Order","Вид","Type","Забалансовый","OffBalance")
  1874. "ChartOfCalculationTypes" = @("Код","Code","Наименование","Description")
  1875. "ExchangePlan" = @("Код","Code","Наименование","Description","НомерОтправленного","SentNo","НомерПринятого","ReceivedNo","ЭтотУзел","ThisNode")
  1876. "BusinessProcess" = @("Номер","Number","Дата","Date","Завершен","Completed","Стартован","Started","ВедущаяЗадача","HeadTask")
  1877. "Task" = @("Номер","Number","Дата","Date","Наименование","Description","Выполнена","Executed","БизнесПроцесс","BusinessProcess","ТочкаМаршрута","RoutePoint")
  1878. "Enum" = @("Порядок","Order")
  1879. "DocumentJournal" = @("Номер","Number","Дата","Date","Проведен","Posted","Тип","Type")
  1880. "InformationRegister" = @()
  1881. "AccumulationRegister" = @("Период","Period","Регистратор","Recorder","НомерСтроки","LineNumber","Активность","Active","ВидДвижения","RecordType")
  1882. "AccountingRegister" = @("Период","Period","Регистратор","Recorder","НомерСтроки","LineNumber","Активность","Active")
  1883. "CalculationRegister" = @("Регистратор","Recorder","НомерСтроки","LineNumber","Активность","Active")
  1884. }
  1885. $script:queryStdCommon = @{}
  1886. foreach ($sf in $qsCommon) { $script:queryStdCommon[(Get-QueryKey $sf)] = $true }
  1887. foreach ($qsk in $qsByKind.Keys) {
  1888. $set = @{}
  1889. foreach ($sf in $qsCommon + $qsByKind[$qsk]) { $set[(Get-QueryKey $sf)] = $true }
  1890. $script:queryStdByKind[$qsk] = $set
  1891. }
  1892. # Стандартные поля, которые есть, только если это включено свойством объекта: у заимствованного
  1893. # объекта в расширении их нет, пока свойства нет в его копии (замер 8.3.24: Родитель у иерархического
  1894. # справочника на оболочке без <Hierarchical> — «Неверный путь к данным»; Код, Наименование — есть).
  1895. $script:queryGatedStd = @{}
  1896. foreach ($g in @(
  1897. @("Catalog", "Hierarchical", @("Родитель","Parent","ЭтоГруппа","IsFolder")),
  1898. @("ChartOfCharacteristicTypes", "Hierarchical", @("Родитель","Parent","ЭтоГруппа","IsFolder")),
  1899. @("Catalog", "Owners", @("Владелец","Owner")),
  1900. @("InformationRegister", "Periodic", @("Период","Period")),
  1901. @("InformationRegister", "Recorder", @("Регистратор","Recorder","НомерСтроки","LineNumber","Активность","Active")))) {
  1902. foreach ($f in $g[2]) { $script:queryGatedStd["$($g[0])|$(Get-QueryKey $f)"] = $g[1] }
  1903. }
  1904. function Test-QueryStdField($info, [string]$fieldKey) {
  1905. $gate = $script:queryGatedStd["$($info.Kind)|$fieldKey"]
  1906. if ($gate) { return [bool]$info.Gates[$gate] }
  1907. if ($script:queryStdByKind.ContainsKey($info.Kind)) { return $script:queryStdByKind[$info.Kind].ContainsKey($fieldKey) }
  1908. return $script:queryStdCommon.ContainsKey($fieldKey)
  1909. }
  1910. # Псевдоним таблицы, ссылка на которую кончается в позиции $pos: «КАК имя» / «AS имя», имя без
  1911. # КАК (если это не ключевое слово); параметры виртуальной таблицы в скобках пропускаются.
  1912. # $null — псевдонима нет, тогда псевдоним — последний сегмент имени таблицы. Иначе — имя и позиция:
  1913. # имя без КАК — тоже определение псевдонима, а не поле.
  1914. $script:reTableAlias = New-Object System.Text.RegularExpressions.Regex '\G(?:(КАК|AS)\s+)?([^\W\d]\w*)', ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
  1915. function Get-QueryTableAlias([string]$q, [int]$pos) {
  1916. $i = $pos
  1917. while ($i -lt $q.Length -and [char]::IsWhiteSpace($q[$i])) { $i++ }
  1918. if ($i -lt $q.Length -and $q[$i] -eq '(') {
  1919. $depth = 0
  1920. while ($i -lt $q.Length) {
  1921. if ($q[$i] -eq '(') { $depth++ } elseif ($q[$i] -eq ')') { $depth--; if ($depth -eq 0) { $i++; break } }
  1922. $i++
  1923. }
  1924. while ($i -lt $q.Length -and [char]::IsWhiteSpace($q[$i])) { $i++ }
  1925. }
  1926. $m = $script:reTableAlias.Match($q, $i)
  1927. if (-not $m.Success) { return $null }
  1928. if (-not $m.Groups[1].Success -and $script:queryAliasStopWords.ContainsKey((Get-QueryKey $m.Groups[2].Value))) { return $null }
  1929. return @{ Name = $m.Groups[2].Value; Index = $m.Groups[2].Index }
  1930. }
  1931. # Зарезервированные слова языка запросов — полем быть не могут: стоп-слова псевдонима плюс
  1932. # литералы и модификаторы. Имена типов (СТРОКА, ДАТА…) и периодов (МЕСЯЦ, ГОД…) сюда не входят:
  1933. # это бывают и имена полей. Тип пропускается по позиции — после КАК, как всякое определение
  1934. # псевдонима; период — аргументом после запятой внутри скобок (НАЧАЛОПЕРИОДА(Д.Дата, МЕСЯЦ)).
  1935. $script:queryReservedWords = @{}
  1936. foreach ($kw in $script:queryAliasStopWords.Keys) { $script:queryReservedWords[$kw] = $true }
  1937. foreach ($kw in @("КАК","AS","РАЗРЕШЕННЫЕ","ALLOWED","РАЗЛИЧНЫЕ","DISTINCT","ПЕРВЫЕ","TOP","NULL","ИСТИНА",
  1938. "TRUE","ЛОЖЬ","FALSE","НЕОПРЕДЕЛЕНО","UNDEFINED","ВЫБОР","CASE","СПЕЦСИМВОЛ","ESCAPE","BY",
  1939. "ИЕРАРХИЯ","ОБЩИЕ","OVERALL","ПЕРИОДАМИ","PERIODS","УНИЧТОЖИТЬ","DROP","ГРУППИРУЮЩИМ","НАБОРАМ",
  1940. "GROUPING","SETS")) {
  1941. $script:queryReservedWords[(Get-QueryKey $kw)] = $true
  1942. }
  1943. $script:queryPeriodNames = @{}
  1944. foreach ($kw in @("СЕКУНДА","SECOND","МИНУТА","MINUTE","ЧАС","HOUR","ДЕНЬ","DAY","НЕДЕЛЯ","WEEK",
  1945. "МЕСЯЦ","MONTH","КВАРТАЛ","QUARTER","ГОД","YEAR","ДЕКАДА","TENDAYS","ПОЛУГОДИЕ","HALFYEAR","АВТО","AUTO")) {
  1946. $script:queryPeriodNames[(Get-QueryKey $kw)] = $true
  1947. }
  1948. $script:reFuncParen = New-Object System.Text.RegularExpressions.Regex '\G\s*\('
  1949. # Слова, после которых в запросе стоит таблица-источник
  1950. $script:querySourceKeywords = @{}
  1951. foreach ($kw in @("ИЗ","FROM","СОЕДИНЕНИЕ","JOIN")) { $script:querySourceKeywords[(Get-QueryKey $kw)] = $true }
  1952. # Ссылочный тип → вид метаданных: CatalogRef → Catalog и т.п. (у DefinedType и прочих — $null).
  1953. function Get-RefKindFromType([string]$typeText) {
  1954. $t = $typeText.Trim()
  1955. $ci = $t.IndexOf(':'); if ($ci -ge 0) { $t = $t.Substring($ci + 1) }
  1956. if ($t -match '^(\w+)Ref\.(\w+)$') { return @{ Kind = $Matches[1]; Name = $Matches[2] } }
  1957. return $null
  1958. }
  1959. # Что объект предоставляет запросу в контексте расширения — по итоговому составу расширения.
  1960. # $null — объекта в расширении нет. Fields: имена заимствованных подобъектов (реквизиты, измерения,
  1961. # ресурсы, ТЧ, признаки учёта…); TSCols: колонки заимствованных ТЧ; EnumValues: значения
  1962. # перечисления; Types: поле → ссылочный тип (одиночный) для разыменования. Ключи — Get-QueryKey.
  1963. $script:extTableInfoCache = @{}
  1964. $script:queryFieldKinds = @('Attribute','Dimension','Resource','TabularSection','AddressingAttribute','AccountingFlag','ExtDimensionAccountingFlag','Column','EnumValue')
  1965. function Get-ExtTableInfo([string]$kind, [string]$nameKey) {
  1966. $cacheKey = "$kind|$nameKey"
  1967. if ($script:extTableInfoCache.ContainsKey($cacheKey)) { return $script:extTableInfoCache[$cacheKey] }
  1968. $info = $null
  1969. $dir = $childTypeDirMap[$kind]
  1970. $actual = $null
  1971. if ($dir) {
  1972. # Имя — каноническое, из состава расширения: в запросе регистр и Ё/Е произвольны
  1973. foreach ($c in $script:childObjsEl.ChildNodes) {
  1974. if ($c.NodeType -ne 'Element' -or $c.LocalName -ne $kind) { continue }
  1975. if ((Get-QueryKey $c.InnerText.Trim()) -ceq $nameKey) { $actual = $c.InnerText.Trim(); break }
  1976. }
  1977. }
  1978. if ($actual) {
  1979. $f = Join-Path (Join-Path $extDir $dir) "$actual.xml"
  1980. if (Test-Path -LiteralPath $f) {
  1981. $doc = New-Object System.Xml.XmlDocument
  1982. $doc.Load($f)
  1983. $el = $null
  1984. foreach ($c in $doc.DocumentElement.ChildNodes) { if ($c.NodeType -eq 'Element') { $el = $c; break } }
  1985. $info = @{ Kind = $kind; Fields = @{}; TSCols = @{}; EnumValues = @{}; Types = @{}; Gates = @{} }
  1986. if ($el) {
  1987. $pr = $el.SelectSingleNode("*[local-name()='Properties']")
  1988. if ($pr) {
  1989. $hv = $pr.SelectSingleNode("*[local-name()='Hierarchical']")
  1990. $info.Gates['Hierarchical'] = [bool]($hv -and $hv.InnerText.Trim() -ceq 'true')
  1991. $info.Gates['Owners'] = [bool]($pr.SelectSingleNode("*[local-name()='Owners']/*"))
  1992. $pv = $pr.SelectSingleNode("*[local-name()='InformationRegisterPeriodicity']")
  1993. $info.Gates['Periodic'] = [bool]($pv -and $pv.InnerText.Trim() -and $pv.InnerText.Trim() -cne 'Nonperiodical')
  1994. $wv = $pr.SelectSingleNode("*[local-name()='WriteMode']")
  1995. $info.Gates['Recorder'] = [bool]($wv -and $wv.InnerText.Trim() -ceq 'RecorderSubordinate')
  1996. }
  1997. foreach ($sub in $el.SelectNodes("*[local-name()='ChildObjects']/*")) {
  1998. # Поля таблицы — только данные: команды, формы, макеты и т.п. полями не бывают
  1999. if ($script:queryFieldKinds -notcontains $sub.LocalName) { continue }
  2000. $nm = $sub.SelectSingleNode("*[local-name()='Properties']/*[local-name()='Name']")
  2001. if (-not $nm) { continue }
  2002. $k = Get-QueryKey $nm.InnerText.Trim()
  2003. if ($sub.LocalName -eq 'EnumValue') { $info.EnumValues[$k] = $true; continue }
  2004. $info.Fields[$k] = $true
  2005. $types = @($sub.SelectNodes("*[local-name()='Properties']/*[local-name()='Type']/*[local-name()='Type']"))
  2006. if ($types.Count -eq 1) {
  2007. $rk = Get-RefKindFromType $types[0].InnerText
  2008. if ($rk) { $info.Types[$k] = $rk }
  2009. }
  2010. if ($sub.LocalName -eq 'TabularSection') {
  2011. $cols = @{}
  2012. foreach ($cn in $sub.SelectNodes("*[local-name()='ChildObjects']/*/*[local-name()='Properties']/*[local-name()='Name']")) {
  2013. $cols[(Get-QueryKey $cn.InnerText.Trim())] = $true
  2014. }
  2015. $info.TSCols[$k] = $cols
  2016. }
  2017. }
  2018. }
  2019. }
  2020. }
  2021. $script:extTableInfoCache[$cacheKey] = $info
  2022. return $info
  2023. }
  2024. # Что в ручном запросе динамического списка не разрешится в контексте расширения — список причин;
  2025. # пустой — запрос разрешим, тильда не нужна. Проверяется по ИТОГОВОМУ составу расширения, а не по
  2026. # прогнозу заимствования: каждая таблица запроса (её объект) должна быть в расширении, её ТЧ,
  2027. # значения перечисления — тоже; каждое поле — заимствованным подобъектом или стандартным полем,
  2028. # разыменование — по одиночному ссылочному типу до объекта, который тоже есть в расширении.
  2029. # Предопределённые, виртуальные таблицы, «*», обращения через скобку и неизвестные слова — не
  2030. # разрешаются. Правило консервативное: лишняя тильда — лишь шум, пропущенная — отказ загрузки.
  2031. # Сверено с платформой 8.3.24 (оракул — загрузка без тильды).
  2032. function Get-DynListQueryUnresolved([string]$queryText) {
  2033. $reasons = New-Object System.Collections.Generic.List[string]
  2034. # Строковые литералы и комментарии — не код запроса; пробелы вокруг точки — часть пути
  2035. $q = [regex]::Replace($queryText, '"(?:[^"]|"")*"|//[^\r\n]*', ' ')
  2036. $q = [regex]::Replace($q, '(?<=[\w)])\s*\.\s*(?=[^\W\d]|\*)', '.')
  2037. $emptyRefKeys = @((Get-QueryKey "ПустаяСсылка"), (Get-QueryKey "EmptyRef"))
  2038. $tsStdKeys = @((Get-QueryKey "Ссылка"), (Get-QueryKey "Ref"), (Get-QueryKey "НомерСтроки"), (Get-QueryKey "LineNumber"))
  2039. $sameObjStd = @((Get-QueryKey "Ссылка"), (Get-QueryKey "Ref"), (Get-QueryKey "Родитель"), (Get-QueryKey "Parent"))
  2040. $refKeys = @((Get-QueryKey "Ссылка"), (Get-QueryKey "Ref"))
  2041. # «*» (кроме КОЛИЧЕСТВО(*)) и обращение через скобку — состав полей не виден
  2042. if ([regex]::IsMatch($q, '(?i)\.\*|(?:(?<![\w.])(?:ВЫБРАТЬ|SELECT|РАЗЛИЧНЫЕ|DISTINCT|РАЗРЕШЕННЫЕ|ALLOWED)|,|\{|(?<![\w.])(?:ПЕРВЫЕ|TOP)\s+\d+)\s*\*')) { $reasons.Add("*") }
  2043. # Области запроса не разбираются: части ОБЪЕДИНИТЬ и вложенные запросы — со своими таблицами
  2044. if ([regex]::IsMatch($q, '(?i)(?<![\w.])(?:ОБЪЕДИНИТЬ|UNION)(?![\w.])')) { $reasons.Add("ОБЪЕДИНИТЬ") }
  2045. if ([regex]::Matches($q, '(?i)(?<![\w.])(?:ВЫБРАТЬ|SELECT)(?![\w.])').Count -gt 1) { $reasons.Add("вложенный запрос") }
  2046. if ([regex]::IsMatch($q, '\)\.[^\W\d]')) { $reasons.Add(").Поле") }
  2047. $pathMatches = @([regex]::Matches($q, '(?<![\w.&])[^\W\d]\w*(?:\.[^\W\d]\w*)+'))
  2048. $aliasPos = New-Object 'System.Collections.Generic.HashSet[int]'
  2049. # Таблицы и их псевдонимы: псевдоним → @{ Info; TS ('' — сам объект) }
  2050. $aliasMap = @{}
  2051. foreach ($pm in $pathMatches) {
  2052. $segs = $pm.Value.Split('.')
  2053. $k0 = Get-QueryKey $segs[0]
  2054. if (-not $script:queryTableKinds.ContainsKey($k0)) { continue }
  2055. $kind = $script:queryTableKinds[$k0]
  2056. $info = Get-ExtTableInfo $kind (Get-QueryKey $segs[1])
  2057. if ($null -eq $info) { $reasons.Add("$($segs[0]).$($segs[1])"); continue }
  2058. $tsKey = ''
  2059. if ($segs.Count -ge 3) {
  2060. $k2 = Get-QueryKey $segs[2]
  2061. if ($segs.Count -eq 3 -and ($emptyRefKeys -ccontains $k2 -or $info.EnumValues.ContainsKey($k2))) { continue }
  2062. if ($segs.Count -eq 3 -and $info.TSCols.ContainsKey($k2)) { $tsKey = $k2 }
  2063. else { $reasons.Add($pm.Value); continue }
  2064. }
  2065. # Псевдоним — только у таблицы-источника (после ИЗ/СОЕДИНЕНИЕ или запятой в их списке). У
  2066. # ссылок в ЗНАЧЕНИЕ(), ТИП(), ВЫРАЗИТЬ(... КАК …), ССЫЛКА … псевдонима нет: фантомный псевдоним
  2067. # закрыл бы от проверки одноимённое поле.
  2068. $bi = $pm.Index - 1
  2069. while ($bi -ge 0 -and [char]::IsWhiteSpace($q[$bi])) { $bi-- }
  2070. $isSource = $false
  2071. if ($bi -ge 0 -and $q[$bi] -eq ',') { $isSource = $true }
  2072. elseif ($bi -ge 0) {
  2073. $we = $bi + 1
  2074. while ($bi -ge 0 -and [char]::IsLetterOrDigit($q[$bi])) { $bi-- }
  2075. $isSource = $script:querySourceKeywords.ContainsKey((Get-QueryKey $q.Substring($bi + 1, $we - $bi - 1)))
  2076. }
  2077. if (-not $isSource) { continue }
  2078. $al = Get-QueryTableAlias $q ($pm.Index + $pm.Length)
  2079. $alias = $segs[-1]
  2080. if ($al) { $alias = $al.Name; [void]$aliasPos.Add($al.Index) }
  2081. $aliasMap[(Get-QueryKey $alias)] = @{ Info = $info; TS = $tsKey }
  2082. }
  2083. # Поле Источник.Поле[.Подполе…]: каждое звено — заимствованный подобъект или стандартное поле
  2084. foreach ($pm in $pathMatches) {
  2085. $segs = $pm.Value.Split('.')
  2086. $k0 = Get-QueryKey $segs[0]
  2087. if ($script:queryTableKinds.ContainsKey($k0)) { continue }
  2088. if (-not $aliasMap.ContainsKey($k0)) { $reasons.Add($pm.Value); continue }
  2089. $curInfo = $aliasMap[$k0].Info; $curTS = $aliasMap[$k0].TS
  2090. $ok = $true
  2091. for ($i = 1; $i -lt $segs.Count; $i++) {
  2092. $fk = Get-QueryKey $segs[$i]
  2093. $last = ($i -eq $segs.Count - 1)
  2094. if ($curTS) {
  2095. # Поле строки ТЧ: колонка (без разыменования) или Ссылка/НомерСтроки
  2096. if ($last -and ($curInfo.TSCols[$curTS].ContainsKey($fk) -or $tsStdKeys -ccontains $fk)) { break }
  2097. if (-not $last -and $refKeys -ccontains $fk) { $curTS = ''; continue }
  2098. $ok = $false; break
  2099. }
  2100. if ($last) {
  2101. if (-not ($curInfo.Fields.ContainsKey($fk) -or (Test-QueryStdField $curInfo $fk))) { $ok = $false }
  2102. break
  2103. }
  2104. # Разыменование: Ссылка/Родитель — тот же объект; реквизит — по его ссылочному типу
  2105. if ($sameObjStd -ccontains $fk -and (Test-QueryStdField $curInfo $fk)) { continue }
  2106. if ($curInfo.Types.ContainsKey($fk)) {
  2107. $t = $curInfo.Types[$fk]
  2108. $curInfo = Get-ExtTableInfo $t.Kind (Get-QueryKey $t.Name)
  2109. if ($null -eq $curInfo) { $ok = $false; break }
  2110. continue
  2111. }
  2112. $ok = $false; break
  2113. }
  2114. if (-not $ok) { $reasons.Add($pm.Value) }
  2115. }
  2116. # Слова без точки. Пропускаются: определение псевдонима (после КАК/AS — в т.ч. имя типа в
  2117. # ВЫРАЗИТЬ), имя функции (перед «(»), зарезервированное слово, период аргументом после запятой
  2118. # внутри скобок. Остальное — поле одной из таблиц запроса: Месяц, Документ, Сумма — и имена полей.
  2119. $aliasDefs = New-Object 'System.Collections.Generic.HashSet[int]'
  2120. foreach ($m in [regex]::Matches($q, '(?i)(?<![\w.])(?:КАК|AS)\s+([^\W\d]\w*)')) { [void]$aliasDefs.Add($m.Groups[1].Index) }
  2121. $commaArgs = New-Object 'System.Collections.Generic.HashSet[int]'
  2122. foreach ($m in [regex]::Matches($q, ',\s*([^\W\d]\w*)')) { [void]$commaArgs.Add($m.Groups[1].Index) }
  2123. $depthAt = New-Object 'int[]' ($q.Length + 1)
  2124. $depth = 0
  2125. for ($ci = 0; $ci -lt $q.Length; $ci++) {
  2126. $depthAt[$ci] = $depth
  2127. if ($q[$ci] -eq '(') { $depth++ } elseif ($q[$ci] -eq ')') { $depth-- }
  2128. }
  2129. foreach ($wm in [regex]::Matches($q, '(?<![\w.&])[^\W\d]\w*(?![\w.])')) {
  2130. if ($aliasDefs.Contains($wm.Index) -or $aliasPos.Contains($wm.Index)) { continue }
  2131. $wk = Get-QueryKey $wm.Value
  2132. if ($script:queryReservedWords.ContainsKey($wk)) { continue }
  2133. if ($script:queryPeriodNames.ContainsKey($wk) -and $commaArgs.Contains($wm.Index) -and $depthAt[$wm.Index] -gt 0) { continue }
  2134. if ($script:reFuncParen.Match($q, $wm.Index + $wm.Length).Success) { continue }
  2135. $found = $false
  2136. foreach ($src in $aliasMap.Values) {
  2137. if ($src.TS) {
  2138. if ($src.Info.TSCols[$src.TS].ContainsKey($wk) -or $tsStdKeys -ccontains $wk) { $found = $true; break }
  2139. } elseif ($src.Info.Fields.ContainsKey($wk) -or (Test-QueryStdField $src.Info $wk)) { $found = $true; break }
  2140. }
  2141. if (-not $found) { $reasons.Add($wm.Value) }
  2142. }
  2143. # Дедуп с учётом регистра — как в py-порте (хеш-таблица PowerShell регистронезависима)
  2144. $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::Ordinal)
  2145. return @($reasons | Where-Object { $seen.Add($_) })
  2146. }
  2147. function Get-MainAttributeInfo {
  2148. param($formEl, [string]$nsStripPattern)
  2149. $mainAttr = $formEl.SelectSingleNode("*[local-name()='Attributes']/*[local-name()='Attribute'][*[local-name()='MainAttribute']='true']")
  2150. if (-not $mainAttr) { return $null }
  2151. $xml = [regex]::Replace($mainAttr.OuterXml, $nsStripPattern, '')
  2152. # id заменяется только в открывающем теге самого реквизита — у вложенных элементов свои
  2153. $xml = [regex]::Replace($xml, '^(<Attribute\s[^>]*?)id="[^"]*"', "`${1}id=`"$script:mainAttrId`"")
  2154. return @{ Name = $mainAttr.GetAttribute("name"); Xml = $xml }
  2155. }
  2156. function Collect-FormDataPaths {
  2157. param([string]$formXmlPath, [string]$mainAttrName)
  2158. # Корень путей — имя основного реквизита формы: «Объект» у формы объекта, «Список» у формы
  2159. # списка, «Запись» у формы записи регистра. Зашитый «Объект» не находил ничего у необъектных
  2160. # форм, и в оболочку не заимствовалось ни одного дочернего объекта.
  2161. $root = [regex]::Escape($mainAttrName)
  2162. $enc = New-Object System.Text.UTF8Encoding($true)
  2163. $content = [System.IO.File]::ReadAllText($formXmlPath, $enc)
  2164. $firstLevel = @{}
  2165. $deepPaths = @()
  2166. # Scan every data-binding tag (DataPath/TitleDataPath/FooterDataPath/HeaderDataPath/MultipleValue*)
  2167. # for Объект.* references — picture-path tags carry picture indices, not data attributes.
  2168. foreach ($tag in $script:formBindingDataTags) {
  2169. $bms = [regex]::Matches($content, "<$tag>[^<]*\b$root\.(\w+(?:\.\w+)*)</$tag>")
  2170. foreach ($m in $bms) {
  2171. $path = $m.Groups[1].Value
  2172. $segments = $path.Split(".")
  2173. $seg0 = $segments[0]
  2174. if ($script:standardFields -contains $seg0) { continue }
  2175. $firstLevel[$seg0] = $true
  2176. if ($segments.Count -ge 2) {
  2177. if ($script:standardFields -contains $segments[1]) { continue }
  2178. $deepPaths += ,$segments
  2179. }
  2180. }
  2181. }
  2182. # Also scan <Field>Объект.X</Field> — object attributes referenced by filter/conditional-appearance
  2183. # fields (and dynamic lists), not via a *DataPath binding (e.g. УдалитьЮрФизЛицо). Designer borrows these too.
  2184. $fieldMatches = [regex]::Matches($content, "<Field>[^<]*\b$root\.(\w+(?:\.\w+)*)</Field>")
  2185. foreach ($m in $fieldMatches) {
  2186. $path = $m.Groups[1].Value
  2187. $segments = $path.Split(".")
  2188. $seg0 = $segments[0]
  2189. if ($script:standardFields -contains $seg0) { continue }
  2190. $firstLevel[$seg0] = $true
  2191. if ($segments.Count -ge 2) {
  2192. if ($script:standardFields -contains $segments[1]) { continue }
  2193. $deepPaths += ,$segments
  2194. }
  2195. }
  2196. # Also scan <AdditionalColumns table="Объект.X"> — доп. колонки табличной части, объявленные в
  2197. # самой форме (напр. Объект.Товары.Артикул). Такая ТЧ может больше нигде на форме не встречаться,
  2198. # и без её заимствования платформа отвергает форму: «Неверный путь к данным».
  2199. $acMatches = [regex]::Matches($content, "<AdditionalColumns table=`"$root\.(\w+)`"")
  2200. foreach ($m in $acMatches) {
  2201. $seg0 = $m.Groups[1].Value
  2202. if ($script:standardFields -contains $seg0) { continue }
  2203. $firstLevel[$seg0] = $true
  2204. }
  2205. # Текст запроса динамического списка — такое же место ссылки на реквизиты объекта, как DataPath.
  2206. # Конфигуратор заимствует всё, что упомянуто в запросе: на эталоне Issue66Example2 это 21 из 27
  2207. # дочерних объектов, совпадение с ним точное в обе стороны. У списка без ручного запроса
  2208. # (<QueryText> нет) заимствуется только видимое на форме — эталон Issue66Example3.
  2209. # Разбирать язык запросов не нужно: имена-кандидаты отфильтрует Resolve-SourceAttributes по
  2210. # реальному составу объекта, поэтому лишние слова из запроса безвредны.
  2211. foreach ($qm in [regex]::Matches($content, '(?s)<QueryText>(.*?)</QueryText>')) {
  2212. foreach ($w in [regex]::Matches($qm.Groups[1].Value, '[\w]+')) {
  2213. $word = $w.Value
  2214. if ($script:standardFields -contains $word) { continue }
  2215. $firstLevel[$word] = $true
  2216. }
  2217. }
  2218. # Deduplicate deep paths (each is the full segment list after the root)
  2219. $seen = @{}
  2220. $uniqueDeep = @()
  2221. foreach ($dp in $deepPaths) {
  2222. $key = $dp -join "."
  2223. if (-not $seen.ContainsKey($key)) {
  2224. $seen[$key] = $true
  2225. $uniqueDeep += ,$dp
  2226. }
  2227. }
  2228. return @{ FirstLevel = $firstLevel; DeepPaths = $uniqueDeep }
  2229. }
  2230. # --- 11c. Resolve source attributes and tabular sections ---
  2231. function Resolve-SourceAttributes {
  2232. param([string]$typeName, [string]$objName, $firstLevelNames)
  2233. # $firstLevelNames: hashtable of names, or $null for "all"
  2234. # Имена сверяются ключом запроса (регистр, Ё/Е): слова приходят и из текста запроса списка,
  2235. # а правило тильды (Get-DynListQueryUnresolved) считает их найденными по тому же ключу.
  2236. $flKeys = $null
  2237. if ($null -ne $firstLevelNames) {
  2238. $flKeys = @{}
  2239. foreach ($flk in $firstLevelNames.Keys) { $flKeys[(Get-QueryKey $flk)] = $true }
  2240. }
  2241. $dirName = $childTypeDirMap[$typeName]
  2242. $srcFile = Join-Path (Join-Path $cfgDir $dirName) "${objName}.xml"
  2243. if (-not (Test-Path $srcFile)) {
  2244. Write-Error "Source object not found: $srcFile"
  2245. exit 1
  2246. }
  2247. $srcDoc = New-Object System.Xml.XmlDocument
  2248. $srcDoc.PreserveWhitespace = $false
  2249. $srcDoc.Load($srcFile)
  2250. $srcNs = New-Object System.Xml.XmlNamespaceManager($srcDoc.NameTable)
  2251. $srcNs.AddNamespace("md", $script:mdNs)
  2252. $srcNs.AddNamespace("xr", $script:xrNs)
  2253. $srcNs.AddNamespace("v8", $script:v8Ns)
  2254. $srcEl = $null
  2255. foreach ($c in $srcDoc.DocumentElement.ChildNodes) {
  2256. if ($c.NodeType -eq 'Element') { $srcEl = $c; break }
  2257. }
  2258. if (-not $srcEl) { Write-Error "No metadata element in source: $srcFile"; exit 1 }
  2259. $childObjs = $srcEl.SelectSingleNode("md:ChildObjects", $srcNs)
  2260. if (-not $childObjs) { return @{ Attributes = @(); TabularSections = @(); ExtraProps = @{} } }
  2261. $attrs = @()
  2262. $tabSections = @()
  2263. # Стандартная ТЧ видов субконто плана счетов: нужна форме (или режим All) — переносятся свойства
  2264. # ExtDimensionTypes/MaxExtDimensionCount и признаки учёта субконто
  2265. $wantExtDim = $typeName -eq 'ChartOfAccounts' -and ($null -eq $flKeys -or $flKeys.ContainsKey((Get-QueryKey 'ExtDimensionTypes')) -or
  2266. $flKeys.ContainsKey((Get-QueryKey 'ВидыСубконто')))
  2267. foreach ($child in $childObjs.ChildNodes) {
  2268. if ($child.NodeType -ne 'Element') { continue }
  2269. # Реквизит объекта, измерение и ресурс регистра — один и тот же вид дочернего объекта с
  2270. # точки зрения заимствования, различается только имя элемента. Конфигуратор переносит их
  2271. # своим видом (эталон Issue66Example2: у регистра <Dimension> x3 и <Resource>), поэтому вид
  2272. # запоминается и выпускается как есть — иначе измерение уехало бы в файл как <Attribute>.
  2273. if ($script:childObjectKinds -ccontains $child.LocalName) {
  2274. $nameNode = $child.SelectSingleNode("md:Properties/md:Name", $srcNs)
  2275. if (-not $nameNode) { continue }
  2276. $attrName = $nameNode.InnerText
  2277. # Признак учёта субконто — колонка стандартной ТЧ видов субконто (Объект.ВидыСубконто.<Признак>):
  2278. # идёт вместе с ней, а не по первому сегменту пути
  2279. if ($child.LocalName -eq 'ExtDimensionAccountingFlag') {
  2280. if (-not $wantExtDim) { continue }
  2281. } elseif ($null -ne $flKeys -and -not $flKeys.ContainsKey((Get-QueryKey $attrName))) { continue }
  2282. $uuid = $child.GetAttribute("uuid")
  2283. $typeNode = $child.SelectSingleNode("md:Properties/md:Type", $srcNs)
  2284. $typeXml = if ($typeNode) { $typeNode.OuterXml } else { "" }
  2285. # Strip namespace declarations from Type
  2286. $typeXml = [regex]::Replace($typeXml, '\s+xmlns(?::\w+)?="[^"]*"', '')
  2287. $attrs += @{ Name = $attrName; Uuid = $uuid; TypeXml = $typeXml; Kind = $child.LocalName }
  2288. }
  2289. elseif ($child.LocalName -eq 'TabularSection') {
  2290. $nameNode = $child.SelectSingleNode("md:Properties/md:Name", $srcNs)
  2291. if (-not $nameNode) { continue }
  2292. $tsName = $nameNode.InnerText
  2293. if ($null -ne $flKeys -and -not $flKeys.ContainsKey((Get-QueryKey $tsName))) { continue }
  2294. $tsUuid = $child.GetAttribute("uuid")
  2295. # Extract GeneratedTypes from InternalInfo
  2296. $tsGenTypes = @()
  2297. $iiNode = $child.SelectSingleNode("md:InternalInfo", $srcNs)
  2298. if ($iiNode) {
  2299. $gtNodes = $iiNode.SelectNodes("xr:GeneratedType", $srcNs)
  2300. foreach ($gt in $gtNodes) {
  2301. $tsGenTypes += @{
  2302. Name = $gt.GetAttribute("name")
  2303. Category = $gt.GetAttribute("category")
  2304. TypeId = $gt.SelectSingleNode("xr:TypeId", $srcNs).InnerText
  2305. ValueId = $gt.SelectSingleNode("xr:ValueId", $srcNs).InnerText
  2306. }
  2307. }
  2308. }
  2309. # Extract ALL child attributes of TabularSection
  2310. $tsAttrs = @()
  2311. $tsChildObjs = $child.SelectSingleNode("md:ChildObjects", $srcNs)
  2312. if ($tsChildObjs) {
  2313. foreach ($tsChild in $tsChildObjs.ChildNodes) {
  2314. if ($tsChild.NodeType -ne 'Element' -or $tsChild.LocalName -ne 'Attribute') { continue }
  2315. $tsAttrName = $tsChild.SelectSingleNode("md:Properties/md:Name", $srcNs)
  2316. if (-not $tsAttrName) { continue }
  2317. $tsAttrUuid = $tsChild.GetAttribute("uuid")
  2318. $tsTypeNode = $tsChild.SelectSingleNode("md:Properties/md:Type", $srcNs)
  2319. $tsTypeXml = if ($tsTypeNode) { $tsTypeNode.OuterXml } else { "" }
  2320. $tsTypeXml = [regex]::Replace($tsTypeXml, '\s+xmlns(?::\w+)?="[^"]*"', '')
  2321. $tsAttrs += @{ Name = $tsAttrName.InnerText; Uuid = $tsAttrUuid; TypeXml = $tsTypeXml }
  2322. }
  2323. }
  2324. $tabSections += @{ Name = $tsName; Uuid = $tsUuid; GeneratedTypes = $tsGenTypes; Attributes = $tsAttrs }
  2325. }
  2326. }
  2327. # Extract extra Properties for main object enrichment (Hierarchical, CodeLength, etc.)
  2328. # Ordered so PS emits the same property order as the Python port (dict preserves insertion order).
  2329. $extraProps = [ordered]@{}
  2330. $propsNode = $srcEl.SelectSingleNode("md:Properties", $srcNs)
  2331. if ($propsNode) {
  2332. # NumberPeriodicity сюда НЕ входит: платформа считает его модификацией настроек нумерации и
  2333. # тогда требует объявить ещё и <Numerator/>, иначе /UpdateDBCfg падает — «отключать
  2334. # контролируемость свойства "Нумератор" недопустимо». Конфигуратор его не переносит
  2335. # (эталон заимствования документа: NumberType/NumberLength/NumberAllowedLength и всё).
  2336. # Загрузку это не ломает, ошибка вылезает только на обновлении конфигурации БД.
  2337. # FoldersOnTop сюда НЕ входит: платформа его у заимствованной оболочки не хранит — при
  2338. # загрузке молча выбрасывает (проверено раундтрипом: записали, выгрузили обратно, свойства
  2339. # нет). Конфигуратор его тоже не переносит. Остальные из списка сохраняются.
  2340. $propsToExtract = @("Hierarchical","CodeLength","DescriptionLength","CodeType","CodeAllowedLength",
  2341. "NumberType","NumberLength","NumberAllowedLength")
  2342. foreach ($pName in $propsToExtract) {
  2343. $pNode = $propsNode.SelectSingleNode("md:${pName}", $srcNs)
  2344. if ($pNode) { $extraProps[$pName] = $pNode.InnerText }
  2345. }
  2346. # Стандартная ТЧ видов субконто плана счетов видна форме расширения, только если в оболочке есть
  2347. # ExtDimensionTypes и MaxExtDimensionCount, а ПВХ видов субконто заимствован (замер 8.3.24, 8.3.27).
  2348. # ПВХ нет в источнике — свойства не переносим: ссылка на незаимствованный объект не загрузится.
  2349. $edtNode = $propsNode.SelectSingleNode("md:ExtDimensionTypes", $srcNs)
  2350. $maxNode = $propsNode.SelectSingleNode("md:MaxExtDimensionCount", $srcNs)
  2351. if ($wantExtDim -and $edtNode -and $maxNode -and $edtNode.InnerText.Trim()) {
  2352. $edm = [regex]::Match($edtNode.InnerText.Trim(), '^(\w+)\.(.+)$')
  2353. $edFound = $edm.Success -and $childTypeDirMap.ContainsKey($edm.Groups[1].Value) -and
  2354. (Test-Path (Join-Path (Join-Path $cfgDir $childTypeDirMap[$edm.Groups[1].Value]) "$($edm.Groups[2].Value).xml"))
  2355. if ($edFound) {
  2356. $extraProps["ExtDimensionTypes"] = $edtNode.InnerText.Trim()
  2357. $extraProps["MaxExtDimensionCount"] = $maxNode.InnerText.Trim()
  2358. } else {
  2359. Warn " ${typeName}.${objName}: виды субконто $($edtNode.InnerText.Trim()) не найдены в конфигурации-источнике — ТЧ видов субконто форме расширения не будет видна"
  2360. }
  2361. }
  2362. }
  2363. return @{ Attributes = $attrs; TabularSections = $tabSections; ExtraProps = $extraProps }
  2364. }
  2365. # --- 11d. Build adopted attribute XML ---
  2366. function Build-AdoptedAttributeXml {
  2367. param([string]$name, [string]$sourceUuid, [string]$typeXml, [string]$indent, [string]$kind = "Attribute")
  2368. $newUuid = [guid]::NewGuid().ToString()
  2369. $sb = New-Object System.Text.StringBuilder
  2370. $sb.AppendLine("${indent}<${kind} uuid=`"${newUuid}`">") | Out-Null
  2371. $sb.AppendLine("${indent}`t<InternalInfo/>") | Out-Null
  2372. $sb.AppendLine("${indent}`t<Properties>") | Out-Null
  2373. $sb.AppendLine("${indent}`t`t<ObjectBelonging>Adopted</ObjectBelonging>") | Out-Null
  2374. $sb.AppendLine("${indent}`t`t<Name>${name}</Name>") | Out-Null
  2375. $sb.AppendLine("${indent}`t`t<Comment/>") | Out-Null
  2376. $sb.AppendLine("${indent}`t`t<ExtendedConfigurationObject>${sourceUuid}</ExtendedConfigurationObject>") | Out-Null
  2377. $sb.AppendLine("${indent}`t`t${typeXml}") | Out-Null
  2378. $sb.AppendLine("${indent}`t</Properties>") | Out-Null
  2379. $sb.Append("${indent}</${kind}>") | Out-Null
  2380. return $sb.ToString()
  2381. }
  2382. # --- 11e. Build adopted tabular section XML ---
  2383. function Build-AdoptedTabularSectionXml {
  2384. param([string]$tsName, [string]$sourceUuid, $generatedTypes, $childAttrs, [string]$indent)
  2385. $newUuid = [guid]::NewGuid().ToString()
  2386. $sb = New-Object System.Text.StringBuilder
  2387. $sb.AppendLine("${indent}<TabularSection uuid=`"${newUuid}`">") | Out-Null
  2388. # InternalInfo with GeneratedTypes (new UUIDs, referencing source names)
  2389. if ($generatedTypes -and $generatedTypes.Count -gt 0) {
  2390. $sb.AppendLine("${indent}`t<InternalInfo>") | Out-Null
  2391. foreach ($gt in $generatedTypes) {
  2392. $newTid = [guid]::NewGuid().ToString()
  2393. $newVid = [guid]::NewGuid().ToString()
  2394. $sb.AppendLine("${indent}`t`t<xr:GeneratedType name=`"$($gt.Name)`" category=`"$($gt.Category)`">") | Out-Null
  2395. $sb.AppendLine("${indent}`t`t`t<xr:TypeId>${newTid}</xr:TypeId>") | Out-Null
  2396. $sb.AppendLine("${indent}`t`t`t<xr:ValueId>${newVid}</xr:ValueId>") | Out-Null
  2397. $sb.AppendLine("${indent}`t`t</xr:GeneratedType>") | Out-Null
  2398. }
  2399. $sb.AppendLine("${indent}`t</InternalInfo>") | Out-Null
  2400. } else {
  2401. $sb.AppendLine("${indent}`t<InternalInfo/>") | Out-Null
  2402. }
  2403. $sb.AppendLine("${indent}`t<Properties>") | Out-Null
  2404. $sb.AppendLine("${indent}`t`t<ObjectBelonging>Adopted</ObjectBelonging>") | Out-Null
  2405. $sb.AppendLine("${indent}`t`t<Name>${tsName}</Name>") | Out-Null
  2406. $sb.AppendLine("${indent}`t`t<Comment/>") | Out-Null
  2407. $sb.AppendLine("${indent}`t`t<ExtendedConfigurationObject>${sourceUuid}</ExtendedConfigurationObject>") | Out-Null
  2408. $sb.AppendLine("${indent}`t</Properties>") | Out-Null
  2409. # ChildObjects with all attributes
  2410. if ($childAttrs -and $childAttrs.Count -gt 0) {
  2411. $sb.AppendLine("${indent}`t<ChildObjects>") | Out-Null
  2412. foreach ($ca in $childAttrs) {
  2413. $caXml = Build-AdoptedAttributeXml $ca.Name $ca.Uuid $ca.TypeXml "${indent}`t`t"
  2414. $sb.AppendLine($caXml) | Out-Null
  2415. }
  2416. $sb.AppendLine("${indent}`t</ChildObjects>") | Out-Null
  2417. } else {
  2418. $sb.AppendLine("${indent}`t<ChildObjects/>") | Out-Null
  2419. }
  2420. $sb.Append("${indent}</TabularSection>") | Out-Null
  2421. return $sb.ToString()
  2422. }
  2423. # --- 11f. Collect reference types from attribute Type XML strings ---
  2424. function Collect-ReferenceTypes {
  2425. param([string[]]$typeXmls)
  2426. # Порядок первого упоминания: от него зависит порядок заимствования в ChildObjects
  2427. $result = [ordered]@{}
  2428. foreach ($typeXml in $typeXmls) {
  2429. # cfg:CatalogRef.XXX, cfg:EnumRef.XXX, cfg:DocumentRef.XXX, etc.
  2430. $refMatches = [regex]::Matches($typeXml, 'cfg:(\w+)Ref\.(\w+)')
  2431. foreach ($m in $refMatches) {
  2432. $refPrefix = $m.Groups[1].Value # e.g. "Catalog", "Enum", "Document"
  2433. $objName = $m.Groups[2].Value
  2434. $key = "${refPrefix}.${objName}"
  2435. if (-not $result.Contains($key)) {
  2436. $result[$key] = @{ TypeName = $refPrefix; ObjName = $objName }
  2437. }
  2438. }
  2439. # cfg:DefinedType.XXX (via v8:TypeSet or v8:Type)
  2440. $dtMatches = [regex]::Matches($typeXml, 'cfg:DefinedType\.(\w+)')
  2441. foreach ($m in $dtMatches) {
  2442. $dtName = $m.Groups[1].Value
  2443. $key = "DefinedType.${dtName}"
  2444. if (-not $result.Contains($key)) {
  2445. $result[$key] = @{ TypeName = "DefinedType"; ObjName = $dtName }
  2446. }
  2447. }
  2448. }
  2449. return @($result.Values)
  2450. }
  2451. # --- 11g. Merge adopted attributes into existing extension object XML ---
  2452. function Merge-AttributesIntoObject {
  2453. param([string]$typeName, [string]$objName, $attrsToAdd)
  2454. $dirName = $childTypeDirMap[$typeName]
  2455. $objFile = Join-Path (Join-Path $extDir $dirName) "${objName}.xml"
  2456. if (-not (Test-Path $objFile)) {
  2457. Warn "Cannot merge attributes: $objFile not found"
  2458. return
  2459. }
  2460. $objDoc = New-Object System.Xml.XmlDocument
  2461. $objDoc.PreserveWhitespace = $true
  2462. $objDoc.Load($objFile)
  2463. $objNs = New-Object System.Xml.XmlNamespaceManager($objDoc.NameTable)
  2464. $objNs.AddNamespace("md", $script:mdNs)
  2465. $objEl = $null
  2466. foreach ($c in $objDoc.DocumentElement.ChildNodes) {
  2467. if ($c.NodeType -eq 'Element') { $objEl = $c; break }
  2468. }
  2469. if (-not $objEl) { Warn "No type element in $objFile"; return }
  2470. # Нет своего <ChildObjects> — его создаст Insert-OwnChildOrDie
  2471. $childObjs = $objEl.SelectSingleNode("md:ChildObjects", $objNs)
  2472. # Имена всех прямых детей своего ChildObjects — дедуп для любого вида (реквизит, измерение, признак)
  2473. $existingNames = @{}
  2474. if ($childObjs) {
  2475. foreach ($c in $childObjs.ChildNodes) {
  2476. if ($c.NodeType -ne 'Element') { continue }
  2477. $nameNode = $c.SelectSingleNode("md:Properties/md:Name", $objNs)
  2478. if ($nameNode) { $existingNames[$nameNode.InnerText.Trim()] = $true }
  2479. }
  2480. }
  2481. $added = 0
  2482. foreach ($attr in $attrsToAdd) {
  2483. if ($existingNames.ContainsKey($attr.Name)) { continue }
  2484. $added++
  2485. }
  2486. if ($added -gt 0) {
  2487. # Build all adopted attributes as text and do string-level insertion
  2488. $attrParts = New-Object System.Collections.Generic.List[object]
  2489. foreach ($attr in $attrsToAdd) {
  2490. if ($existingNames.ContainsKey($attr.Name)) { continue }
  2491. $kind = if ($attr.Kind) { $attr.Kind } else { "Attribute" }
  2492. $attrParts.Add(@{ Tag = $kind; Xml = (Build-AdoptedAttributeXml $attr.Name $attr.Uuid $attr.TypeXml "`t`t`t" $kind) })
  2493. }
  2494. # Save via text manipulation to avoid namespace issues with InnerXml
  2495. # Стиль исходника снимаем ДО записи: правка чужого файла наследует его BOM/EOL/заголовок
  2496. # (#44/#46/#47), новый файл получает канон выгрузки. Зеркало _detect_xml_style в py-порту.
  2497. $style3 = Detect-XmlStyle $objFile
  2498. $settings3 = New-Object System.Xml.XmlWriterSettings
  2499. $settings3.Encoding = New-Object System.Text.UTF8Encoding($true)
  2500. $settings3.Indent = $false
  2501. $settings3.NewLineHandling = [System.Xml.NewLineHandling]::None
  2502. $memStream3 = New-Object System.IO.MemoryStream
  2503. $writer3 = [System.Xml.XmlWriter]::Create($memStream3, $settings3)
  2504. $objDoc.Save($writer3)
  2505. $writer3.Flush(); $writer3.Close()
  2506. $text3 = [System.Text.Encoding]::UTF8.GetString($memStream3.ToArray())
  2507. $memStream3.Close()
  2508. # Самозакрытый элемент раскрывается текстом, а не пробельным узлом в DOM: тот давал
  2509. # лишнюю строку с табуляцией перед первым <Attribute> (у Конфигуратора пустых строк нет).
  2510. # Стоит ДО Finalize-XmlText, чтобы схлопывание пустых тегов накрыло и вставленные реквизиты.
  2511. foreach ($part in $attrParts) {
  2512. $text3 = Insert-OwnChildOrDie $text3 $part.Xml $part.Tag $typeName $objFile
  2513. }
  2514. $text3 = Finalize-XmlText $text3 $style3
  2515. $writeBom3 = ($null -eq $style3) -or $style3.bom
  2516. [System.IO.File]::WriteAllText($objFile, $text3, (New-Object System.Text.UTF8Encoding($writeBom3)))
  2517. Info " Merged $added attribute(s) into: $objFile"
  2518. }
  2519. }
  2520. # Блок <TabularSection> с именем $tsName среди прямых детей СОБСТВЕННОГО <ChildObjects> объекта:
  2521. # @{ Start; End } в тексте, $null — нет. Прямые дети — по глубине, как в Insert-IntoOwnChildObjectsByCanon;
  2522. # имя ТЧ — первый <Name> блока (в InternalInfo имён нет), без учёта регистра, как имена 1С. Реквизит с тем же
  2523. # именем — не ТЧ.
  2524. function Find-OwnTabularSectionSpan([string]$text, [string]$tsName) {
  2525. $mOpen = [regex]::Match($text, '<ChildObjects\b[^>]*?(/?)>')
  2526. if (-not $mOpen.Success -or $mOpen.Groups[1].Value) { return $null }
  2527. $closes = [regex]::Matches($text, '</ChildObjects\s*>')
  2528. if ($closes.Count -eq 0) { return $null }
  2529. $bodyStart = $mOpen.Index + $mOpen.Length
  2530. $bodyEnd = $closes[$closes.Count - 1].Index
  2531. if ($bodyEnd -lt $bodyStart) { return $null }
  2532. $depth = 0
  2533. $tsStart = -1
  2534. foreach ($m in [regex]::Matches($text.Substring($bodyStart, $bodyEnd - $bodyStart), '<(/?)([\w:.-]+)[^>]*?(/?)>')) {
  2535. if ($m.Groups[1].Value) {
  2536. $depth--
  2537. if ($depth -eq 0 -and $tsStart -ge 0) {
  2538. $end = $bodyStart + $m.Index + $m.Length
  2539. $nm = [regex]::Match($text.Substring($tsStart, $end - $tsStart), '<Name>([^<]*)</Name>')
  2540. if ($nm.Success -and $nm.Groups[1].Value -eq $tsName) { return @{ Start = $tsStart; End = $end } }
  2541. $tsStart = -1
  2542. }
  2543. continue
  2544. }
  2545. if ($depth -eq 0) { $tsStart = if ($m.Groups[2].Value -ceq 'TabularSection') { $bodyStart + $m.Index } else { -1 } }
  2546. if (-not $m.Groups[3].Value) { $depth++ }
  2547. }
  2548. return $null
  2549. }
  2550. # Колонки источника — в уже заимствованную ТЧ объекта расширения (недостающие по имени; свои колонки
  2551. # и порядок остальных не трогаем). Возвращает число добавленных; ТЧ нет — -1.
  2552. function Merge-ColumnsIntoTabularSection {
  2553. param([string]$typeName, [string]$objName, [string]$tsName, $cols)
  2554. $objFile = Join-Path (Join-Path $extDir $childTypeDirMap[$typeName]) "${objName}.xml"
  2555. $style = Detect-XmlStyle $objFile
  2556. $text = [System.IO.File]::ReadAllText($objFile, (New-Object System.Text.UTF8Encoding($true)))
  2557. $span = Find-OwnTabularSectionSpan $text $tsName
  2558. if (-not $span) { return -1 }
  2559. $block = $text.Substring($span.Start, $span.End - $span.Start)
  2560. # Имена колонок — все <Name> блока, кроме первого (имя самой ТЧ)
  2561. $existing = @{}
  2562. $first = $true
  2563. foreach ($nm in [regex]::Matches($block, '<Name>([^<]*)</Name>')) {
  2564. if ($first) { $first = $false; continue }
  2565. $existing[$nm.Groups[1].Value] = $true
  2566. }
  2567. $ls = if ($span.Start -gt 0) { $text.LastIndexOf("`n", $span.Start - 1) + 1 } else { 0 }
  2568. $colIndent = $text.Substring($ls, $span.Start - $ls) + "`t`t"
  2569. $added = 0
  2570. foreach ($c in $cols) {
  2571. if ($existing.ContainsKey($c.Name)) { continue }
  2572. $newBlock = Insert-IntoOwnChildObjectsByCanon $block (Build-AdoptedAttributeXml $c.Name $c.Uuid $c.TypeXml $colIndent) "Attribute" "TabularSection"
  2573. if ($null -eq $newBlock) { Warn " Tabular section ${tsName} has no <ChildObjects> — attribute $($c.Name) not added"; break }
  2574. $block = $newBlock
  2575. $existing[$c.Name] = $true
  2576. $added++
  2577. }
  2578. if ($added -gt 0) {
  2579. $text = $text.Substring(0, $span.Start) + $block + $text.Substring($span.End)
  2580. [System.IO.File]::WriteAllText($objFile, $text, (Get-StyleEncoding $style))
  2581. Info " Merged $added attribute(s) into tabular section ${tsName}: $objFile"
  2582. }
  2583. return $added
  2584. }
  2585. # --- 11h. Borrow-MainAttribute orchestrator ---
  2586. # Ссылочные типы → объекты-оболочки в расширении (кто уже заимствован — пропускается)
  2587. # Объект-оболочка в расширении: кто уже заимствован — пропускается, без источника — предупреждение.
  2588. function Borrow-ObjectShell([string]$typeName, [string]$objName) {
  2589. if (-not $childTypeDirMap.ContainsKey($typeName)) {
  2590. Warn " Unknown object type: ${typeName}.${objName}"
  2591. return
  2592. }
  2593. if (Test-ObjectBorrowed $typeName $objName) {
  2594. Info " Already borrowed: ${typeName}.${objName}"
  2595. return
  2596. }
  2597. $srcFile = Join-Path (Join-Path $cfgDir $childTypeDirMap[$typeName]) "${objName}.xml"
  2598. if (-not (Test-Path $srcFile)) {
  2599. Warn " Source not found: ${typeName}.${objName}"
  2600. return
  2601. }
  2602. $src = Read-SourceObject $typeName $objName
  2603. $borrowedXml = Build-BorrowedObjectXml $typeName $objName $src.Uuid $src.Properties
  2604. $targetDir = Join-Path $extDir $childTypeDirMap[$typeName]
  2605. if (-not (Test-Path $targetDir)) {
  2606. New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
  2607. }
  2608. $targetFile = Join-Path $targetDir "${objName}.xml"
  2609. [System.IO.File]::WriteAllText($targetFile, $borrowedXml, (New-Object System.Text.UTF8Encoding($true)))
  2610. Add-ToChildObjects $typeName $objName
  2611. $script:borrowedFiles += $targetFile
  2612. Info " Auto-borrowed: ${typeName}.${objName}"
  2613. # Оболочка определяемого типа несёт его состав: объекты из состава — оболочками (эталон
  2614. # Конфигуратора). Без них ниже 8.3.25 загрузка падает: «Неизвестное имя типа».
  2615. if ($typeName -eq "DefinedType" -and $src.Properties.ContainsKey("__TypeXml")) {
  2616. foreach ($rt in (Collect-ReferenceTypes @($src.Properties["__TypeXml"]))) {
  2617. Borrow-ObjectShell $rt.TypeName $rt.ObjName
  2618. }
  2619. }
  2620. }
  2621. # Единственный объект, на который ведёт ссылочный тип: <Вид>Ref.<Имя> или определяемый тип из одной
  2622. # такой ссылки (состав — из источника). Составной, примитивный, неизвестный вид — $null: дальше
  2623. # такого типа путь формы не продолжается. Определяемый тип раскрывается один раз: в его составе
  2624. # определяемых типов не бывает.
  2625. function Resolve-SingleRefTarget([string]$typeXml, [bool]$allowDefined = $true) {
  2626. $types = @([regex]::Matches($typeXml, '<v8:(?:Type|TypeSet)>([^<]+)</v8:(?:Type|TypeSet)>') | ForEach-Object { $_.Groups[1].Value })
  2627. if ($types.Count -ne 1) { return $null }
  2628. $dt = [regex]::Match($types[0], '^(?:\w+:)?DefinedType\.(\w+)$')
  2629. if ($dt.Success -and -not $allowDefined) { return $null }
  2630. if ($dt.Success) {
  2631. $dtFile = Join-Path (Join-Path $cfgDir $childTypeDirMap["DefinedType"]) "$($dt.Groups[1].Value).xml"
  2632. if (-not (Test-Path $dtFile)) { return $null }
  2633. $dtSrc = Read-SourceObject "DefinedType" $dt.Groups[1].Value
  2634. if (-not $dtSrc.Properties.ContainsKey("__TypeXml")) { return $null }
  2635. return Resolve-SingleRefTarget $dtSrc.Properties["__TypeXml"] $false
  2636. }
  2637. $ref = [regex]::Match($types[0], '^(?:\w+:)?(\w+)Ref\.(\w+)$')
  2638. if (-not $ref.Success -or -not $childTypeDirMap.ContainsKey($ref.Groups[1].Value)) { return $null }
  2639. return @{ TypeName = $ref.Groups[1].Value; ObjName = $ref.Groups[2].Value }
  2640. }
  2641. function Borrow-ReferenceTypeShells {
  2642. param([string[]]$typeXmls)
  2643. $refTypes = @(Collect-ReferenceTypes $typeXmls)
  2644. Info " Reference types to borrow: $($refTypes.Count)"
  2645. foreach ($rt in $refTypes) {
  2646. Borrow-ObjectShell $rt.TypeName $rt.ObjName
  2647. }
  2648. }
  2649. # Владелец общей формы — из ТИПА её основного реквизита (эталон УТ CommonMain):
  2650. # <Вид>Object.Имя / <Вид>RecordManager.Имя → объект; DynamicList → объект из <MainTable>;
  2651. # ConstantsSet → константы по путям формы. Примитив, тип без имени (ReportObject — любой отчёт),
  2652. # список без MainTable → владельца нет: в расширение идёт только сам реквизит формы.
  2653. $script:commonFormOwnerKinds = [ordered]@{
  2654. 'CatalogObject'='Catalog'; 'DocumentObject'='Document'; 'DataProcessorObject'='DataProcessor'; 'ReportObject'='Report'
  2655. 'ChartOfCharacteristicTypesObject'='ChartOfCharacteristicTypes'; 'ChartOfAccountsObject'='ChartOfAccounts'
  2656. 'ChartOfCalculationTypesObject'='ChartOfCalculationTypes'; 'ExchangePlanObject'='ExchangePlan'
  2657. 'BusinessProcessObject'='BusinessProcess'; 'TaskObject'='Task'
  2658. 'InformationRegisterRecordManager'='InformationRegister'; 'InformationRegisterRecordSet'='InformationRegister'
  2659. 'AccumulationRegisterRecordSet'='AccumulationRegister'
  2660. }
  2661. function Resolve-CommonFormOwner {
  2662. param($formEl)
  2663. $mainAttr = $formEl.SelectSingleNode("*[local-name()='Attributes']/*[local-name()='Attribute'][*[local-name()='MainAttribute']='true']")
  2664. if (-not $mainAttr) { return $null }
  2665. $typeNode = $mainAttr.SelectSingleNode("*[local-name()='Type']/*[local-name()='Type']")
  2666. $typeText = if ($typeNode) { $typeNode.InnerText.Trim() } else { "" }
  2667. if ($typeText -ceq 'cfg:ConstantsSet') { return @{ Kind = 'Constants'; MainName = $mainAttr.GetAttribute("name") } }
  2668. $m = [regex]::Match($typeText, '^cfg:(\w+)\.(\w+)$')
  2669. if ($m.Success -and $script:commonFormOwnerKinds.Contains($m.Groups[1].Value)) {
  2670. return @{ Kind = 'Object'; TypeName = $script:commonFormOwnerKinds[$m.Groups[1].Value]; ObjName = $m.Groups[2].Value; ByType = $true }
  2671. }
  2672. if ($typeText -ceq 'cfg:DynamicList') {
  2673. $mt = $mainAttr.SelectSingleNode(".//*[local-name()='MainTable']")
  2674. if ($mt) {
  2675. $mtm = [regex]::Match($mt.InnerText.Trim(), '^(\w+)\.(\w+)$')
  2676. if ($mtm.Success -and $childTypeDirMap.ContainsKey($mtm.Groups[1].Value)) {
  2677. return @{ Kind = 'Object'; TypeName = $mtm.Groups[1].Value; ObjName = $mtm.Groups[2].Value }
  2678. }
  2679. }
  2680. }
  2681. return $null
  2682. }
  2683. # Объект, по которому разрешаются пути формы объекта: тип основного реквизита <Вид>Object.Имя и т.п.,
  2684. # а не владелец формы — форма обработки с основным реквизитом DocumentObject.X видит реквизиты X (замер
  2685. # 8.3.24, #120). Список (DynamicList) и прочие типы — владелец формы, как раньше.
  2686. function Resolve-MainAttributeObject {
  2687. param($formEl, [string]$typeName, [string]$objName)
  2688. $o = Resolve-CommonFormOwner $formEl
  2689. if ($o -and $o.Kind -eq 'Object' -and $o.ByType) { return @{ TypeName = $o.TypeName; ObjName = $o.ObjName } }
  2690. return @{ TypeName = $typeName; ObjName = $objName }
  2691. }
  2692. # Набор констант как основной реквизит общей формы: заимствуются константы, пути на которые есть
  2693. # в форме (<Реквизит>.<Константа>), — с типом как в источнике; их ссылочные типы — оболочками
  2694. # (эталон УТ CommonMain: НастройкаПереводаТекста → две константы + перечисление из типа).
  2695. function Borrow-FormConstants {
  2696. param([string]$srcFormXmlPath, [string]$mainName)
  2697. Info "Borrowing constants for main attribute ${mainName} (ConstantsSet)..."
  2698. $names = (Collect-FormDataPaths $srcFormXmlPath $mainName).FirstLevel
  2699. $encBom = New-Object System.Text.UTF8Encoding($true)
  2700. $typeXmls = @()
  2701. foreach ($cName in @($names.Keys)) {
  2702. $cSrcFile = Join-Path (Join-Path $cfgDir "Constants") "${cName}.xml"
  2703. if (-not (Test-Path $cSrcFile)) { continue }
  2704. $cDoc = New-Object System.Xml.XmlDocument
  2705. # С пробелами: вложенные отступы типа в источнике — ровно та же глубина, что в расширении
  2706. $cDoc.PreserveWhitespace = $true
  2707. $cDoc.Load($cSrcFile)
  2708. $cTypeNode = $cDoc.SelectSingleNode("//*[local-name()='Constant']/*[local-name()='Properties']/*[local-name()='Type']")
  2709. $cTypeXml = if ($cTypeNode) { ([regex]::Replace($cTypeNode.OuterXml, '\s+xmlns(?::\w+)?="[^"]*"', '') -replace "`r?`n", "`r`n") } else { "" }
  2710. if ($cTypeXml) { $typeXmls += $cTypeXml }
  2711. # Тип — последним свойством, после ExtendedConfigurationObject (как у Конфигуратора)
  2712. $addType = {
  2713. param([string]$xml)
  2714. ([regex]'(?<ind>[ \t]*)<ExtendedConfigurationObject>[^<]*</ExtendedConfigurationObject>').Replace($xml, {
  2715. param($mm) $mm.Value + "`r`n" + $mm.Groups['ind'].Value + $cTypeXml
  2716. }, 1)
  2717. }
  2718. if (Test-ObjectBorrowed "Constant" $cName) {
  2719. # Заимствованная раньше оболочкой (-Object Constant.X) — без типа: дописываем, как при
  2720. # слиянии реквизитов в уже заимствованный объект
  2721. $extCFile = Join-Path (Join-Path $extDir "Constants") "${cName}.xml"
  2722. $extCText = [System.IO.File]::ReadAllText($extCFile, $encBom)
  2723. if ($cTypeXml -and $extCText -cnotmatch '<Type>') {
  2724. [System.IO.File]::WriteAllText($extCFile, (& $addType $extCText), $encBom)
  2725. Info " Added type: Constant.${cName}"
  2726. } else {
  2727. Info " Already borrowed: Constant.${cName}"
  2728. }
  2729. continue
  2730. }
  2731. $src = Read-SourceObject "Constant" $cName
  2732. $borrowedXml = Build-BorrowedObjectXml "Constant" $cName $src.Uuid $src.Properties
  2733. if ($cTypeXml) { $borrowedXml = & $addType $borrowedXml }
  2734. $targetDir = Join-Path $extDir "Constants"
  2735. if (-not (Test-Path $targetDir)) { New-Item -ItemType Directory -Path $targetDir -Force | Out-Null }
  2736. $targetFile = Join-Path $targetDir "${cName}.xml"
  2737. [System.IO.File]::WriteAllText($targetFile, $borrowedXml, $encBom)
  2738. Add-ToChildObjects "Constant" $cName
  2739. $script:borrowedFiles += $targetFile
  2740. Info " Borrowed: Constant.${cName}"
  2741. }
  2742. Borrow-ReferenceTypeShells $typeXmls
  2743. }
  2744. function Borrow-MainAttribute {
  2745. param([string]$typeName, [string]$objName, [string]$formName, [string]$mode, [string]$srcFormXmlPath = "")
  2746. $dirName = $childTypeDirMap[$typeName]
  2747. Info "Borrowing main attribute for ${typeName}.${objName} (mode: $mode)..."
  2748. # Путь к исходной форме: у общей формы его передают явно (владелец выведен из типа реквизита)
  2749. if (-not $srcFormXmlPath) {
  2750. $srcFormXmlPath = Join-Path (Join-Path (Join-Path (Join-Path (Join-Path $cfgDir $dirName) $objName) "Forms") $formName) "Ext/Form.xml"
  2751. }
  2752. # Step 1: Collect DataPaths (Form mode) or take all (All mode)
  2753. $firstLevelNames = $null
  2754. $deepPaths = @()
  2755. if ($mode -eq "Form") {
  2756. if (-not (Test-Path $srcFormXmlPath)) {
  2757. Write-Error "Source Form.xml not found: $srcFormXmlPath"
  2758. exit 1
  2759. }
  2760. # Имя основного реквизита исходной формы — корень путей, которые надо собрать
  2761. $dpDoc = New-Object System.Xml.XmlDocument
  2762. $dpDoc.PreserveWhitespace = $true
  2763. $dpDoc.Load($srcFormXmlPath)
  2764. $dpInfo = Get-MainAttributeInfo $dpDoc.DocumentElement '\s+xmlns(?::\w+)?="[^"]*"'
  2765. if (-not $dpInfo) {
  2766. Warn " У формы нет основного реквизита — заимствовать нечего"
  2767. return
  2768. }
  2769. $dp = Collect-FormDataPaths $srcFormXmlPath $dpInfo.Name
  2770. $firstLevelNames = $dp.FirstLevel
  2771. $deepPaths = $dp.DeepPaths
  2772. Info " Collected $($firstLevelNames.Count) first-level DataPath references, $($deepPaths.Count) deep paths"
  2773. } else {
  2774. Info " Mode All: borrowing all attributes and tabular sections"
  2775. # Первый уровень — все реквизиты, но глубокие пути формы те же: объекты по ссылкам из них
  2776. # нужны с показанными реквизитами в любом режиме
  2777. if (Test-Path $srcFormXmlPath) {
  2778. $dpDoc = New-Object System.Xml.XmlDocument
  2779. $dpDoc.PreserveWhitespace = $true
  2780. $dpDoc.Load($srcFormXmlPath)
  2781. $dpInfo = Get-MainAttributeInfo $dpDoc.DocumentElement '\s+xmlns(?::\w+)?="[^"]*"'
  2782. if ($dpInfo) { $deepPaths = (Collect-FormDataPaths $srcFormXmlPath $dpInfo.Name).DeepPaths }
  2783. }
  2784. }
  2785. # Step 2: Resolve source attributes
  2786. $resolved = Resolve-SourceAttributes $typeName $objName $firstLevelNames
  2787. $srcAttrs = $resolved.Attributes
  2788. $srcTS = $resolved.TabularSections
  2789. $extraProps = $resolved.ExtraProps
  2790. Info " Resolved: $($srcAttrs.Count) attributes, $($srcTS.Count) tabular section(s)"
  2791. # Identify which FirstLevel names are TabularSections (for deep path filtering)
  2792. $tsNames = @{}
  2793. foreach ($ts in $srcTS) { $tsNames[$ts.Name] = $true }
  2794. # Step 3: Build the adopted content and insert into main object XML
  2795. $objFile = Join-Path (Join-Path $extDir $dirName) "${objName}.xml"
  2796. # Read existing object XML (needed for dedup + enrichment)
  2797. $objStyle = Detect-XmlStyle $objFile
  2798. $objContent = [System.IO.File]::ReadAllText($objFile, (New-Object System.Text.UTF8Encoding($true)))
  2799. # Dedup: skip attributes/TS already present in object's ChildObjects (idempotent re-borrow)
  2800. $existingChildNames = Get-OwnChildObjectNames $objFile
  2801. $insertAttrs = @($srcAttrs | Where-Object { -not $existingChildNames.ContainsKey($_.Name) })
  2802. $insertTS = @($srcTS | Where-Object { -not $existingChildNames.ContainsKey($_.Name) })
  2803. # Узлы заимствуемого содержимого: тег + XML. Место каждому — по канону вида при вставке
  2804. $contentParts = New-Object System.Collections.Generic.List[object]
  2805. foreach ($attr in $insertAttrs) {
  2806. $attrKind = if ($attr.Kind) { $attr.Kind } else { "Attribute" }
  2807. $contentParts.Add(@{ Tag = $attrKind; Xml = (Build-AdoptedAttributeXml $attr.Name $attr.Uuid $attr.TypeXml "`t`t`t" $attrKind) })
  2808. }
  2809. foreach ($ts in $insertTS) {
  2810. $contentParts.Add(@{ Tag = "TabularSection"; Xml = (Build-AdoptedTabularSectionXml $ts.Name $ts.Uuid $ts.GeneratedTypes $ts.Attributes "`t`t`t") })
  2811. }
  2812. # Inject extra properties into the object's OWN Properties only — idempotent and anchored to the
  2813. # first ExtendedConfigurationObject (the object's). On re-borrow, adopted attributes each have their
  2814. # own ExtendedConfigurationObject; a global replace would push object props inside every <Attribute>.
  2815. if ($extraProps.Count -gt 0) {
  2816. $objPropsBlock = ""
  2817. if ($objContent -match '(?s)<Properties>(.*?)</Properties>') { $objPropsBlock = $Matches[1] }
  2818. $propsSb = New-Object System.Text.StringBuilder
  2819. foreach ($pName in $extraProps.Keys) {
  2820. if ($objPropsBlock -match "<$pName>") { continue }
  2821. $propsSb.Append("`r`n`t`t`t<${pName}>$($extraProps[$pName])</${pName}>") | Out-Null
  2822. }
  2823. if ($propsSb.Length -gt 0) {
  2824. $objContent = ([regex]'</ExtendedConfigurationObject>').Replace($objContent, "</ExtendedConfigurationObject>$($propsSb.ToString())", 1)
  2825. }
  2826. }
  2827. # Добавить заимствованное содержимое в ChildObjects объекта (там уже может лежать <Form>)
  2828. foreach ($part in $contentParts) {
  2829. $objContent = Insert-OwnChildOrDie $objContent $part.Xml $part.Tag $typeName $objFile
  2830. }
  2831. [System.IO.File]::WriteAllText($objFile, $objContent, (Get-StyleEncoding $objStyle))
  2832. Info " Enriched object: $objFile"
  2833. # ТЧ уже в расширении (заимствована без формы, своими колонками) — колонки, которые нужны форме,
  2834. # доливаются в неё: пропуск по имени оставил бы форму с «Неверный путь к данным Объект.<ТЧ>.<Колонка>»
  2835. foreach ($ts in $srcTS) {
  2836. if (-not $existingChildNames.ContainsKey($ts.Name)) { continue }
  2837. if ((Merge-ColumnsIntoTabularSection $typeName $objName $ts.Name $ts.Attributes) -lt 0) {
  2838. Warn " $($ts.Name): name is taken in ${typeName}.${objName}, but not by a tabular section — its attributes not borrowed"
  2839. }
  2840. }
  2841. # Step 4: Collect all reference types and borrow as shells
  2842. $allTypeXmls = @()
  2843. foreach ($a in $srcAttrs) { $allTypeXmls += $a.TypeXml }
  2844. foreach ($ts in $srcTS) {
  2845. foreach ($tsa in $ts.Attributes) { $allTypeXmls += $tsa.TypeXml }
  2846. }
  2847. # Типы из <Columns> основного реквизита формы: колонку мы переносим (Borrow-Form), значит и её
  2848. # тип должен быть заимствован — иначе колонка ссылается на DefinedType/справочник, которого в
  2849. # расширении нет. Конфигуратор поступает так же (эталон: DefinedTypes/Артикул при заимствовании
  2850. # формы заказа поставщику).
  2851. $srcFormForCols = $srcFormXmlPath
  2852. if (Test-Path $srcFormForCols) {
  2853. $colsDoc = New-Object System.Xml.XmlDocument
  2854. $colsDoc.PreserveWhitespace = $true
  2855. $colsDoc.Load($srcFormForCols)
  2856. $colsInfo = Get-MainAttributeInfo $colsDoc.DocumentElement '\s+xmlns(?::\w+)?="[^"]*"'
  2857. if ($colsInfo) {
  2858. foreach ($m in [regex]::Matches($colsInfo.Xml, '(?s)<Columns>.*?</Columns>')) { $allTypeXmls += $m.Value }
  2859. }
  2860. }
  2861. Borrow-ReferenceTypeShells $allTypeXmls
  2862. # ПВХ видов субконто, на который ссылается перенесённое свойство ExtDimensionTypes, — оболочкой:
  2863. # иначе «Неизвестный объект метаданных» при загрузке
  2864. if ($extraProps.Contains('ExtDimensionTypes')) {
  2865. $edm = [regex]::Match($extraProps['ExtDimensionTypes'], '^(\w+)\.(.+)$')
  2866. if ($edm.Success) { Borrow-ObjectShell $edm.Groups[1].Value $edm.Groups[2].Value }
  2867. }
  2868. # Step 5: Deep paths — Объект.<Реквизит>.<…> and Объект.<ТЧ>.<Колонка>.<…>. Each reference step borrows
  2869. # its target object with the next segment's attribute (Designer etalon), down the whole chain
  2870. if ($deepPaths.Count -gt 0) {
  2871. Info " Processing $($deepPaths.Count) deep path(s)..."
  2872. foreach ($segs in $deepPaths) {
  2873. if ($tsNames.ContainsKey($segs[0])) {
  2874. $tsInfo = $srcTS | Where-Object { $_.Name -eq $segs[0] } | Select-Object -First 1
  2875. $startAttr = $tsInfo.Attributes | Where-Object { $_.Name -eq $segs[1] } | Select-Object -First 1
  2876. $next = 2
  2877. } else {
  2878. $startAttr = $srcAttrs | Where-Object { $_.Name -eq $segs[0] } | Select-Object -First 1
  2879. $next = 1
  2880. }
  2881. if (-not $startAttr) { continue }
  2882. $typeXml = $startAttr.TypeXml
  2883. for ($i = $next; $i -lt $segs.Count; $i++) {
  2884. if ($script:standardFields -contains $segs[$i]) { break }
  2885. $target = Resolve-SingleRefTarget $typeXml
  2886. if (-not $target) { break }
  2887. $merged = @(Borrow-DeepTargetAttrs $target.TypeName $target.ObjName @($segs[$i]))
  2888. if ($merged.Count -eq 0) { break }
  2889. $typeXml = $merged[0].TypeXml
  2890. }
  2891. }
  2892. }
  2893. Info " Main attribute borrowing complete"
  2894. }
  2895. # --- 11i. Helper: borrow a deep-path target object together with the referenced sub-attributes ---
  2896. # Mirrors Designer: the referenced object is adopted WITH the sub-attributes the form shows, otherwise
  2897. # the platform rejects the deep DataPath ("Неверный путь к данным"). Returns the merged source attributes
  2898. # (Name/TypeXml) — the chain walk continues along their types.
  2899. function Borrow-DeepTargetAttrs {
  2900. param([string]$targetTypeName, [string]$targetObjName, $subAttrNames)
  2901. Borrow-ObjectShell $targetTypeName $targetObjName
  2902. if (-not (Test-ObjectBorrowed $targetTypeName $targetObjName)) { return @() }
  2903. $subNames = @{}
  2904. foreach ($sn in $subAttrNames) { $subNames[$sn] = $true }
  2905. $subResolved = Resolve-SourceAttributes $targetTypeName $targetObjName $subNames
  2906. if ($subResolved.Attributes.Count -eq 0) { return @() }
  2907. Merge-AttributesIntoObject $targetTypeName $targetObjName $subResolved.Attributes
  2908. # Ссылочные типы смёрженных реквизитов — оболочками
  2909. Borrow-ReferenceTypeShells @($subResolved.Attributes | ForEach-Object { $_.TypeXml })
  2910. return $subResolved.Attributes
  2911. }
  2912. # --- 12. Helper: build borrowed object XML ---
  2913. function Build-BorrowedObjectXml {
  2914. param(
  2915. [string]$typeName,
  2916. [string]$objName,
  2917. [string]$sourceUuid,
  2918. [hashtable]$sourceProps
  2919. )
  2920. $newUuid = [guid]::NewGuid().ToString()
  2921. $internalInfoXml = Build-InternalInfoXml $typeName $objName "`t`t"
  2922. $sb = New-Object System.Text.StringBuilder
  2923. $sb.AppendLine("<?xml version=`"1.0`" encoding=`"UTF-8`"?>") | Out-Null
  2924. $sb.AppendLine("<MetaDataObject $($script:xmlnsDecl) version=`"$($script:formatVersion)`">") | Out-Null
  2925. $sb.AppendLine("`t<${typeName} uuid=`"${newUuid}`">") | Out-Null
  2926. # InternalInfo
  2927. $sb.AppendLine($internalInfoXml) | Out-Null
  2928. # Properties
  2929. $sb.AppendLine("`t`t<Properties>") | Out-Null
  2930. $sb.AppendLine("`t`t`t<ObjectBelonging>Adopted</ObjectBelonging>") | Out-Null
  2931. $sb.AppendLine("`t`t`t<Name>${objName}</Name>") | Out-Null
  2932. $sb.AppendLine("`t`t`t<Comment/>") | Out-Null
  2933. $sb.AppendLine("`t`t`t<ExtendedConfigurationObject>${sourceUuid}</ExtendedConfigurationObject>") | Out-Null
  2934. # CommonModule: extra properties from source
  2935. if ($typeName -eq "CommonModule") {
  2936. foreach ($propName in $commonModuleProps) {
  2937. $propVal = "false"
  2938. if ($sourceProps.ContainsKey($propName)) {
  2939. $propVal = $sourceProps[$propName]
  2940. }
  2941. $sb.AppendLine("`t`t`t<${propName}>${propVal}</${propName}>") | Out-Null
  2942. }
  2943. }
  2944. # DefinedType: emit the carried <Type> definition (needed for the alias to resolve, e.g. totals)
  2945. if ($typeName -eq "DefinedType" -and $sourceProps.ContainsKey("__TypeXml")) {
  2946. $sb.AppendLine("`t`t`t$($sourceProps['__TypeXml'])") | Out-Null
  2947. }
  2948. # Свойства, от которых зависят стандартные поля (см. $script:typeGateProps / $script:typesWithOwners)
  2949. foreach ($gp in @($script:typeGateProps[$typeName])) {
  2950. if ($gp -and $sourceProps.ContainsKey($gp)) {
  2951. $sb.AppendLine("`t`t`t<${gp}>$($sourceProps[$gp])</${gp}>") | Out-Null
  2952. }
  2953. }
  2954. if ($sourceProps.ContainsKey("__OwnersXml")) {
  2955. $sb.AppendLine("`t`t`t$($sourceProps['__OwnersXml'])") | Out-Null
  2956. }
  2957. $sb.AppendLine("`t`t</Properties>") | Out-Null
  2958. # ChildObjects (for types that need it)
  2959. if ($sourceProps["__HasChildObjects"] -or ($typesWithChildObjects -contains $typeName)) {
  2960. $sb.AppendLine("`t`t<ChildObjects/>") | Out-Null
  2961. }
  2962. $sb.AppendLine("`t</${typeName}>") | Out-Null
  2963. $sb.Append("</MetaDataObject>") | Out-Null
  2964. return $sb.ToString()
  2965. }
  2966. # --- 13. Helper: add object to extension ChildObjects ---
  2967. # Стиль существующего файла для round-trip-сохранения: BOM / EOL / регистр encoding /
  2968. # финальный перенос. $null → файл новый (сохранить текущее поведение).
  2969. # Реестр семьи: tests/skills/check-inline-drift.mjs.
  2970. # Кодировка записи с BOM, как был у файла ($style — Detect-XmlStyle до записи; файла не было — с BOM)
  2971. function Get-StyleEncoding($style) {
  2972. return (New-Object System.Text.UTF8Encoding(($null -eq $style) -or $style.bom))
  2973. }
  2974. function Detect-XmlStyle([string]$path) {
  2975. if (-not (Test-Path -LiteralPath $path)) { return $null }
  2976. $raw = [System.IO.File]::ReadAllBytes($path)
  2977. $bom = ($raw.Length -ge 3 -and $raw[0] -eq 0xEF -and $raw[1] -eq 0xBB -and $raw[2] -eq 0xBF)
  2978. $body = if ($bom) { [System.Text.Encoding]::UTF8.GetString($raw, 3, $raw.Length - 3) } else { [System.Text.Encoding]::UTF8.GetString($raw) }
  2979. $head = if ($body.Length -gt 200) { $body.Substring(0, 200) } else { $body }
  2980. $m = [regex]::Match($head, 'encoding="([^"]+)"')
  2981. return @{
  2982. bom = $bom
  2983. crlf = $body.Contains("`r`n")
  2984. enc = $(if ($m.Success) { $m.Groups[1].Value } else { "utf-8" })
  2985. finalNl = $body.EndsWith("`n")
  2986. }
  2987. }
  2988. # Привести текст XmlWriter к стилю оригинала; для НОВОГО файла ($null) — к канону выгрузки
  2989. # Конфигуратора: encoding="UTF-8", CRLF, без перевода строки в конце.
  2990. # Реестр семьи: tests/skills/check-inline-drift.mjs.
  2991. function Finalize-XmlText([string]$text, $style) {
  2992. if ($text.Length -gt 0 -and $text[0] -eq [char]0xFEFF) { $text = $text.Substring(1) }
  2993. $encDecl = $(if ($style) { $style.enc } else { "UTF-8" })
  2994. $text = $text.Replace('encoding="utf-8"', 'encoding="' + $encDecl + '"')
  2995. # Пустой элемент: XmlWriter отдаёт `<a />`, Конфигуратор пишет `<a/>`. Внутри
  2996. # CDATA/комментария ` />` может быть содержимым (там `>` не экранируется),
  2997. # поэтому они идут первыми ветками альтернации и возвращаются как есть.
  2998. $text = [regex]::Replace($text, '(?s)<!\[CDATA\[.*?\]\]>|<!--.*?-->|(?<=\S) />', { param($m) if ($m.Value -eq ' />') { '/>' } else { $m.Value } })
  2999. $text = ($text -replace "`r`n", "`n").TrimEnd("`n")
  3000. if ($style -and $style.finalNl) { $text += "`n" }
  3001. if (-not $style -or $style.crlf) { $text = $text -replace "`n", "`r`n" }
  3002. return $text
  3003. }
  3004. function Find-V8Project([string]$startDir) {
  3005. $d = $startDir
  3006. for ($i = 0; $i -lt 20 -and $d; $i++) {
  3007. $pj = Join-Path $d ".v8-project.json"
  3008. if (Test-Path $pj) { return $pj }
  3009. $parent = [System.IO.Path]::GetDirectoryName($d)
  3010. if ($parent -eq $d) { break }
  3011. $d = $parent
  3012. }
  3013. return $null
  3014. }
  3015. # Куда навык ставит новую запись в <ChildObjects> — настройка newObjectPosition.
  3016. # databases[].newObjectPosition базы, чей configSrc охватывает каталог родительского XML,
  3017. # иначе корневое поле, иначе end. Значения: end — после последнего объекта того же вида
  3018. # (так дописывает Конфигуратор); byName — по имени среди объектов того же вида.
  3019. # Файл ищем от рабочего каталога вверх, каталог конфигурации — запасной путь: так же
  3020. # его ищут support-guard и группа db-*, а скрипт навыка зовут по абсолютному пути, и cwd
  3021. # остаётся рабочим каталогом проекта.
  3022. # configSrc считается от каталога .v8-project.json, как задокументировано в
  3023. # docs/v8-project-guide.md. Реестр семьи: tests/skills/check-inline-drift.mjs.
  3024. function Get-NewObjectPosition([string]$cfgDir) {
  3025. try {
  3026. if (-not $cfgDir) { $cfgDir = "." }
  3027. $pj = Find-V8Project (Get-Location).ProviderPath
  3028. if (-not $pj) { $pj = Find-V8Project ([System.IO.Path]::GetFullPath($cfgDir)) }
  3029. if (-not $pj) { return "end" }
  3030. # UTF-8 явно: PS 5.1 читает файл без BOM как ANSI, и configSrc с кириллицей не совпал бы
  3031. $proj = Get-Content -Raw -Encoding UTF8 $pj | ConvertFrom-Json
  3032. $projDir = [System.IO.Path]::GetDirectoryName($pj)
  3033. $cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
  3034. if ($proj.databases) {
  3035. foreach ($db in $proj.databases) {
  3036. if ($db.configSrc -and $db.newObjectPosition) {
  3037. $src = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($projDir, $db.configSrc)).TrimEnd('\', '/')
  3038. if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
  3039. if ("$($db.newObjectPosition)" -eq "byName") { return "byName" }
  3040. return "end"
  3041. }
  3042. }
  3043. }
  3044. }
  3045. if ("$($proj.newObjectPosition)" -eq "byName") { return "byName" }
  3046. return "end"
  3047. } catch { return "end" }
  3048. }
  3049. # Виды, у которых порядок в дереве несёт смысл: автоматически их не упорядочиваем.
  3050. # CommonAttribute — исключение самого стандарта (#std467): у общих реквизитов-разделителей
  3051. # порядок в дереве задаёт порядок установки параметров сеанса. Subsystem и CommandGroup:
  3052. # пока они не перечислены в <SubsystemsOrder> / <GroupsOrder> файла Ext/CommandInterface.xml,
  3053. # порядок дерева задаёт порядок в интерфейсе, а платформа эти списки сама не заводит
  3054. # (в выгрузке ACC вне GroupsOrder 15 живых групп из 39). Language исключён из осторожности,
  3055. # без замера: языков обычно один-два, и в типовых их порядок не алфавитный.
  3056. # Явно названный вид сортируется в любом случае.
  3057. # Реестр семьи: tests/skills/check-inline-drift.mjs.
  3058. function Test-OrderSensitiveType([string]$typeName) {
  3059. return @("CommonAttribute", "Subsystem", "CommandGroup", "Language") -ccontains $typeName
  3060. }
  3061. # Порядок имён объектов метаданных, как в дереве Конфигуратора.
  3062. # Ключ — пары «ранг+символ»: регистр не учитывается, подчёркивание раньше цифр, цифры раньше
  3063. # букв, буквы по кодам (латиница раньше кириллицы), ё на месте е. Культурные таблицы не
  3064. # используются — они разные на разных ОС и в разных рантаймах, а так оба порта сравнивают
  3065. # одинаково везде. Равные ключи разводит ordinal-сравнение исходных строк.
  3066. # Возвращает -1 | 0 | 1. Реестр семьи: tests/skills/check-inline-drift.mjs.
  3067. function Compare-MetadataNames([string]$a, [string]$b) {
  3068. $keys = @("", "")
  3069. $names = @($a, $b)
  3070. for ($i = 0; $i -lt 2; $i++) {
  3071. $sb = New-Object System.Text.StringBuilder
  3072. foreach ($ch in $names[$i].ToLowerInvariant().ToCharArray()) {
  3073. if ($ch -eq [char]0x0451) { $ch = [char]0x0435 }
  3074. if ([char]::IsDigit($ch)) { [void]$sb.Append('1') }
  3075. elseif ([char]::IsLetter($ch)) { [void]$sb.Append('2') }
  3076. else { [void]$sb.Append('0') }
  3077. [void]$sb.Append($ch)
  3078. }
  3079. $keys[$i] = $sb.ToString()
  3080. }
  3081. $r = [string]::CompareOrdinal($keys[0], $keys[1])
  3082. if ($r -eq 0) { $r = [string]::CompareOrdinal($a, $b) }
  3083. if ($r -lt 0) { return -1 }
  3084. if ($r -gt 0) { return 1 }
  3085. return 0
  3086. }
  3087. function Add-ToChildObjects {
  3088. param([string]$typeName, [string]$objName)
  3089. $cfgIndent = Get-ChildIndent $script:cfgEl
  3090. # Expand self-closing ChildObjects if needed
  3091. if (-not $script:childObjsEl.HasChildNodes -or $script:childObjsEl.IsEmpty) {
  3092. Expand-SelfClosingElement $script:childObjsEl $cfgIndent
  3093. }
  3094. $childIndent = Get-ChildIndent $script:childObjsEl
  3095. $typeIdx = $script:typeOrder.IndexOf($typeName)
  3096. if ($typeIdx -lt 0) {
  3097. Write-Error "Unknown type '$typeName' for ChildObjects ordering"
  3098. exit 1
  3099. }
  3100. # Dedup check
  3101. foreach ($child in $script:childObjsEl.ChildNodes) {
  3102. if ($child.NodeType -eq 'Element' -and $child.LocalName -eq $typeName -and $child.InnerText -eq $objName) {
  3103. Warn "Already in ChildObjects: ${typeName}.${objName}"
  3104. return
  3105. }
  3106. }
  3107. # Место вставки. Вид — по $script:typeOrder; внутри вида — по newObjectPosition: end
  3108. # (по умолчанию) кладёт после последнего объекта того же вида, byName — по имени. Так же
  3109. # заимствует Конфигуратор: в боевых выгрузках расширений ChildObjects не отсортирован.
  3110. # Subsystem по имени не упорядочиваем никогда: порядок подсистем в дереве задаёт порядок
  3111. # разделов в панели.
  3112. $byName = (-not (Test-OrderSensitiveType $typeName) -and (Get-NewObjectPosition $extDir) -eq "byName")
  3113. $insertBefore = $null
  3114. $lastSameType = $null
  3115. foreach ($child in $script:childObjsEl.ChildNodes) {
  3116. if ($child.NodeType -ne 'Element') { continue }
  3117. $childTypeIdx = $script:typeOrder.IndexOf($child.LocalName)
  3118. if ($childTypeIdx -lt 0) { continue }
  3119. if ($child.LocalName -eq $typeName) {
  3120. if ($byName -and -not $insertBefore -and (Compare-MetadataNames $child.InnerText $objName) -gt 0) {
  3121. $insertBefore = $child
  3122. }
  3123. $lastSameType = $child
  3124. } elseif ($childTypeIdx -gt $typeIdx -and -not $insertBefore) {
  3125. # First element of a later type -- insert before it
  3126. $insertBefore = $child
  3127. }
  3128. }
  3129. # Create element
  3130. $newEl = $script:xmlDoc.CreateElement($typeName, $script:mdNs)
  3131. $newEl.InnerText = $objName
  3132. if ($insertBefore) {
  3133. Insert-BeforeElement $script:childObjsEl $newEl $insertBefore $childIndent
  3134. } else {
  3135. Insert-BeforeElement $script:childObjsEl $newEl $null $childIndent
  3136. }
  3137. Info "Added to ChildObjects: ${typeName}.${objName}"
  3138. }
  3139. # --- 14. Process each item ---
  3140. $script:borrowedFiles = @()
  3141. # Формы с динамическим списком — основная таблица и тильда решаются в конце запуска (шаги 14a, 14c)
  3142. $script:dynListForms = @()
  3143. $borrowedCount = 0
  3144. # Элемент -Object: тип (синоним → английское имя), объект, форма и путь к её Form.xml в источнике.
  3145. # Error — текст отказа для неверного элемента.
  3146. function Split-BorrowItem([string]$item) {
  3147. $fmtHint = "expected 'Type.Name', 'Type.Name.Form.FormName', 'Type.Name.<Kind>.<SubName>' or 'Type.Name.TabularSection.<TS>.Attribute.<Attribute>'"
  3148. $dotIdx = $item.IndexOf(".")
  3149. if ($dotIdx -lt 1) { return @{ Error = "Invalid format '${item}', $fmtHint" } }
  3150. $typeName = $item.Substring(0, $dotIdx)
  3151. $remainder = $item.Substring($dotIdx + 1)
  3152. # Resolve Russian synonym to English type name
  3153. if ($synonymMap.ContainsKey($typeName)) { $typeName = $synonymMap[$typeName] }
  3154. if (-not $childTypeDirMap.ContainsKey($typeName)) { return @{ Error = "Unknown type '${typeName}'" } }
  3155. # Имена метаданных без точек — разбор по сегментам: Имя | Имя.Form.Ф | Имя.<Вид>.<П> | Имя.TabularSection.<ТЧ>.Attribute.<К>
  3156. $segs = $remainder.Split('.')
  3157. if ($segs -contains '') { return @{ Error = "Invalid format '${item}', $fmtHint" } }
  3158. $objName = $segs[0]
  3159. $formName = $null; $subKind = $null; $subName = $null; $colName = $null
  3160. if ($segs.Count -eq 1) {
  3161. } elseif ($segs.Count -eq 3 -and $segs[1] -ceq 'Form') {
  3162. $formName = $segs[2]
  3163. } elseif ($segs.Count -eq 3 -and $script:subObjectKinds -ccontains $segs[1]) {
  3164. $subKind = $segs[1]; $subName = $segs[2]
  3165. } elseif ($segs.Count -eq 5 -and $segs[1] -ceq 'TabularSection' -and $segs[3] -ceq 'Attribute') {
  3166. $subKind = 'TabularSection'; $subName = $segs[2]; $colName = $segs[4]
  3167. } elseif ($segs.Count -eq 3) {
  3168. return @{ Error = "Unsupported child object kind '$($segs[1])' in '${item}': expected Form, $($script:subObjectKinds -join ', ')" }
  3169. } else {
  3170. return @{ Error = "Invalid format '${item}', $fmtHint" }
  3171. }
  3172. # Вид подобъекта — из канона ChildObjects своего типа: измерения у документа нет
  3173. if ($subKind) {
  3174. $order = (Get-ObjectChildOrder)[$typeName]
  3175. if (-not $order -or $order -cnotcontains $subKind) { return @{ Error = "${typeName} has no child objects of kind ${subKind} ('${item}')" } }
  3176. }
  3177. # Общая форма — сама форма: «CommonForm.X» заимствуется вместе с содержимым, владельца у неё нет
  3178. $isCommonForm = $typeName -eq 'CommonForm'
  3179. if ($isCommonForm) {
  3180. if ($segs.Count -ne 1) { return @{ Error = "Invalid format '${item}': общая форма задаётся как 'CommonForm.Имя'" } }
  3181. $formName = $objName
  3182. }
  3183. $dirName = $childTypeDirMap[$typeName]
  3184. $srcFormXml = $null
  3185. if ($isCommonForm) { $srcFormXml = Join-Path (Join-Path (Join-Path $cfgDir $dirName) $objName) "Ext/Form.xml" }
  3186. elseif ($formName) { $srcFormXml = Join-Path (Join-Path (Join-Path (Join-Path (Join-Path $cfgDir $dirName) $objName) "Forms") $formName) "Ext/Form.xml" }
  3187. return @{ TypeName = $typeName; ObjName = $objName; FormName = $formName; IsCommonForm = $isCommonForm; DirName = $dirName; SrcFormXml = $srcFormXml
  3188. SubKind = $subKind; SubName = $subName; ColName = $colName }
  3189. }
  3190. # Подобъект в источнике: реквизит/измерение/… своего вида, ТЧ и колонка. Имя сверяется ключом
  3191. # запроса, как у Resolve-SourceAttributes; в расширение идёт имя из источника. Нет — Error.
  3192. function Resolve-SubObjectSource($pi) {
  3193. $res = Resolve-SourceAttributes $pi.TypeName $pi.ObjName @{ $pi.SubName = $true }
  3194. $key = Get-QueryKey $pi.SubName
  3195. $where = "$($pi.TypeName).$($pi.ObjName)"
  3196. if ($pi.SubKind -ceq 'TabularSection') {
  3197. $ts = $res.TabularSections | Where-Object { (Get-QueryKey $_.Name) -ceq $key } | Select-Object -First 1
  3198. if (-not $ts) { return @{ Error = "TabularSection '$($pi.SubName)' not found in ${where}" } }
  3199. $col = $null
  3200. if ($pi.ColName) {
  3201. $colKey = Get-QueryKey $pi.ColName
  3202. $col = $ts.Attributes | Where-Object { (Get-QueryKey $_.Name) -ceq $colKey } | Select-Object -First 1
  3203. if (-not $col) { return @{ Error = "Attribute '$($pi.ColName)' not found in tabular section ${where}.$($ts.Name)" } }
  3204. }
  3205. return @{ TS = $ts; Col = $col }
  3206. }
  3207. $attr = $res.Attributes | Where-Object { $_.Kind -ceq $pi.SubKind -and (Get-QueryKey $_.Name) -ceq $key } | Select-Object -First 1
  3208. if (-not $attr) { return @{ Error = "$($pi.SubKind) '$($pi.SubName)' not found in ${where}" } }
  3209. return @{ Attr = $attr }
  3210. }
  3211. # Объект-родитель формы или подобъекта: не заимствован — заимствовать заготовкой
  3212. function Ensure-ParentBorrowed([string]$typeName, [string]$objName) {
  3213. if (Test-ObjectBorrowed $typeName $objName) { return }
  3214. Info " Parent object ${typeName}.${objName} not yet borrowed — borrowing first..."
  3215. $src = Read-SourceObject $typeName $objName
  3216. Info " Source UUID: $($src.Uuid)"
  3217. $borrowedXml = Build-BorrowedObjectXml $typeName $objName $src.Uuid $src.Properties
  3218. $targetDir = Join-Path $extDir $childTypeDirMap[$typeName]
  3219. if (-not (Test-Path $targetDir)) {
  3220. New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
  3221. }
  3222. $targetFile = Join-Path $targetDir "${objName}.xml"
  3223. $enc = New-Object System.Text.UTF8Encoding($true)
  3224. [System.IO.File]::WriteAllText($targetFile, $borrowedXml, $enc)
  3225. Info " Created: $targetFile"
  3226. Add-ToChildObjects $typeName $objName
  3227. $script:borrowedFiles += $targetFile
  3228. }
  3229. # Подобъект без формы — как «Добавить в расширение» Конфигуратора: ТЧ пустая (свои колонки — потом,
  3230. # meta-edit), реквизит/измерение/колонка — по одному, ссылочные типы — оболочками. Свойства объекта
  3231. # (Hierarchical, CodeLength…) не переносятся — Конфигуратор их тут тоже не пишет.
  3232. function Borrow-SubObject($pi, $src) {
  3233. $typeName = $pi.TypeName; $objName = $pi.ObjName
  3234. Ensure-ParentBorrowed $typeName $objName
  3235. $objFile = Join-Path (Join-Path $extDir $pi.DirName) "${objName}.xml"
  3236. if ($pi.SubKind -cne 'TabularSection') {
  3237. $attr = $src.Attr
  3238. if ((Get-OwnChildObjectNames $objFile).ContainsKey($attr.Name)) {
  3239. Info " Already borrowed: $($pi.SubKind) $($attr.Name)"
  3240. } else {
  3241. Merge-AttributesIntoObject $typeName $objName @($attr)
  3242. }
  3243. Borrow-ReferenceTypeShells @($attr.TypeXml)
  3244. return
  3245. }
  3246. $ts = $src.TS
  3247. $style = Detect-XmlStyle $objFile
  3248. $text = [System.IO.File]::ReadAllText($objFile, (New-Object System.Text.UTF8Encoding($true)))
  3249. if (Find-OwnTabularSectionSpan $text $ts.Name) {
  3250. Info " Already borrowed: TabularSection $($ts.Name)"
  3251. } else {
  3252. $text = Insert-OwnChildOrDie $text (Build-AdoptedTabularSectionXml $ts.Name $ts.Uuid $ts.GeneratedTypes @() "`t`t`t") "TabularSection" $typeName $objFile
  3253. [System.IO.File]::WriteAllText($objFile, $text, (Get-StyleEncoding $style))
  3254. Info " Borrowed TabularSection $($ts.Name) (no attributes): $objFile"
  3255. }
  3256. # Собственный реквизит в заимствованную ТЧ этих видов платформа не примет — отказ на обновлении БД.
  3257. # Предупреждаем, когда ТЧ заимствуется под собственные реквизиты — элемент без реквизита источника
  3258. if (-not $src.Col) {
  3259. if ($script:tsOwnColumnsBlocked -ccontains $typeName) {
  3260. Warn " ${typeName}: own attributes cannot be added to a borrowed tabular section of this kind — the platform rejects them on database update"
  3261. } elseif ($script:tsOwnColumnsFromPlatform.ContainsKey($typeName)) {
  3262. Warn " ${typeName}: own attributes in a borrowed tabular section are accepted only from platform $($script:tsOwnColumnsFromPlatform[$typeName])"
  3263. }
  3264. }
  3265. if ($src.Col) {
  3266. Merge-ColumnsIntoTabularSection $typeName $objName $ts.Name @($src.Col) | Out-Null
  3267. Borrow-ReferenceTypeShells @($src.Col.TypeXml)
  3268. }
  3269. }
  3270. # --- 13b. Актуализация заимствованного (повтор, -Check, -Actualize) ---
  3271. # Заимствованное сверяется с источником: связь (ExtendedConfigurationObject) и объявленные свойства.
  3272. # Платформа связывает заимствованное ПО ИМЕНИ, ECO — сверка подлинности; контролируется то, что
  3273. # объявлено в Properties, режим — <xr:PropertyState> в InternalInfo: нет — проверять и запрещать,
  3274. # Notify — проверять, не запрещать, Extended — переопределять, MultiState — у составного типа свой
  3275. # режим на часть типов (xr:CheckValue / xr:ExtendValue / xr:NotifyValue). Свойства, которого нет в
  3276. # расширении, нет и контроля — его не добавляем. Правки — текстом на месте: XmlDocument переписал бы
  3277. # пустые элементы и пробелы файла.
  3278. # Режим: Check — только отчёт; Apply (повтор -Object, -Actualize) — правки. Все правки идут по тому же
  3279. # UUID (связь, свойства, имя вслед за источником), поэтому данные целы; перепривязку к объекту с другим
  3280. # UUID — единственное, что грозит потерей данных, — не делаем, только сообщаем.
  3281. $script:actMode = 'Apply'
  3282. $script:actRows = New-Object System.Collections.Generic.List[object]
  3283. $script:srcHeadCache = @{}
  3284. $script:srcUuidIndex = @{}
  3285. function New-ActRow([string]$path) {
  3286. $row = @{ Path = $path; Status = $null; Notes = (New-Object System.Collections.Generic.List[object]) }
  3287. $script:actRows.Add($row)
  3288. return $row
  3289. }
  3290. # Заметка строки отчёта: Applied — правка сделана (в -Check — нет)
  3291. # Info — заметка для сведения: на статус строки и код возврата не влияет
  3292. function Add-ActNote($row, [string]$text, [bool]$applied, [bool]$info = $false) {
  3293. $row.Notes.Add(@{ Text = $text; Applied = $applied; Info = $info })
  3294. }
  3295. function Test-EditAllowed {
  3296. return ($script:actMode -ne 'Check')
  3297. }
  3298. # Элемент XML текстом: позиции тега, содержимого и конца. $pos — на «<» открывающего тега.
  3299. $script:reXmlOpen = [regex]'\G<([\w:.-]+)((?:\s+[\w:.-]+\s*=\s*"[^"]*")*)\s*(/?)>'
  3300. function Get-XmlElementAt([string]$text, [int]$pos) {
  3301. $m = $script:reXmlOpen.Match($text, $pos)
  3302. if (-not $m.Success) { return $null }
  3303. $name = $m.Groups[1].Value
  3304. $local = if ($name.Contains(':')) { $name.Substring($name.IndexOf(':') + 1) } else { $name }
  3305. $openEnd = $pos + $m.Length
  3306. if ($m.Groups[3].Value -eq '/') {
  3307. return @{ Name = $name; Local = $local; Attrs = $m.Groups[2].Value; Start = $pos; OpenEnd = $openEnd; CloseStart = $openEnd; End = $openEnd; Empty = $true }
  3308. }
  3309. $re = [regex]('<(/?)' + [regex]::Escape($name) + '(?=[\s/>])')
  3310. $depth = 1; $i = $openEnd
  3311. while ($true) {
  3312. $t = $re.Match($text, $i)
  3313. if (-not $t.Success) { return $null }
  3314. $gt = $text.IndexOf('>', $t.Index)
  3315. if ($gt -lt 0) { return $null }
  3316. if ($t.Groups[1].Value -eq '/') {
  3317. $depth--
  3318. if ($depth -eq 0) {
  3319. return @{ Name = $name; Local = $local; Attrs = $m.Groups[2].Value; Start = $pos; OpenEnd = $openEnd; CloseStart = $t.Index; End = $gt + 1; Empty = $false }
  3320. }
  3321. } elseif ($text[$gt - 1] -ne '/') {
  3322. $depth++
  3323. }
  3324. $i = $gt + 1
  3325. }
  3326. }
  3327. function Get-XmlChildren([string]$text, $el) {
  3328. $res = New-Object System.Collections.Generic.List[object]
  3329. if (-not $el -or $el.Empty) { return ,$res }
  3330. $i = $el.OpenEnd
  3331. while ($i -lt $el.CloseStart) {
  3332. $lt = $text.IndexOf('<', $i)
  3333. if ($lt -lt 0 -or $lt -ge $el.CloseStart) { break }
  3334. $c = Get-XmlElementAt $text $lt
  3335. if (-not $c) { break }
  3336. $res.Add($c)
  3337. $i = $c.End
  3338. }
  3339. return ,$res
  3340. }
  3341. function Get-XmlChild([string]$text, $el, [string]$local) {
  3342. foreach ($c in (Get-XmlChildren $text $el)) { if ($c.Local -ceq $local) { return $c } }
  3343. return $null
  3344. }
  3345. function Get-XmlInner([string]$text, $el) {
  3346. if ($el.Empty) { return '' }
  3347. return $text.Substring($el.OpenEnd, $el.CloseStart - $el.OpenEnd)
  3348. }
  3349. function Get-XmlOuter([string]$text, $el) { return $text.Substring($el.Start, $el.End - $el.Start) }
  3350. function Get-XmlAttr($el, [string]$name) {
  3351. $m = [regex]::Match($el.Attrs, '(?:^|\s)' + [regex]::Escape($name) + '\s*=\s*"([^"]*)"')
  3352. if ($m.Success) { return $m.Groups[1].Value }
  3353. return $null
  3354. }
  3355. # Корневой элемент описания объекта (<Catalog uuid=…>) — первый ребёнок <MetaDataObject>
  3356. function Get-MdRoot([string]$text) {
  3357. $mdo = [regex]::Match($text, '<MetaDataObject[\s>]')
  3358. if (-not $mdo.Success) { return $null }
  3359. $doc = Get-XmlElementAt $text $mdo.Index
  3360. if (-not $doc) { return $null }
  3361. $kids = Get-XmlChildren $text $doc
  3362. if ($kids.Count -eq 0) { return $null }
  3363. return $kids[0]
  3364. }
  3365. function Get-NormXml([string]$s) { return ([regex]::Replace($s, '>\s+<', '><')).Trim() }
  3366. function Get-LineIndent([string]$text, [int]$pos) {
  3367. $ls = if ($pos -gt 0) { $text.LastIndexOf("`n", $pos - 1) } else { -1 }
  3368. $ls = $ls + 1
  3369. $pre = $text.Substring($ls, $pos - $ls)
  3370. if ($pre -match '^[ \t]*$') { return $pre }
  3371. return ''
  3372. }
  3373. # Фрагмент из другого файла — отступы строк с исходного уровня на целевой, переводы строк — как в цели
  3374. function Set-FragmentIndent([string]$frag, [string]$from, [string]$to, [string]$eol) {
  3375. $lines = $frag -split "\r?\n"
  3376. for ($i = 1; $i -lt $lines.Count; $i++) {
  3377. if ($lines[$i].StartsWith($from)) { $lines[$i] = $to + $lines[$i].Substring($from.Length) }
  3378. }
  3379. return ($lines -join $eol)
  3380. }
  3381. function Get-TextEol([string]$text) { if ($text.Contains("`r`n")) { return "`r`n" } else { return "`n" } }
  3382. function Apply-TextEdits([string]$text, $edits) {
  3383. $sorted = @($edits | Sort-Object -Property @{ Expression = { $_.Start }; Descending = $true }, @{ Expression = { $_.End }; Descending = $true })
  3384. foreach ($e in $sorted) { $text = $text.Substring(0, $e.Start) + $e.Text + $text.Substring($e.End) }
  3385. return $text
  3386. }
  3387. # Правка в файл расширения, если режим её разрешает; заметка в отчёт — в любом случае
  3388. function Add-ActEdit($ctx, $row, [int]$start, [int]$end, [string]$newText, [string]$note) {
  3389. $ok = Test-EditAllowed
  3390. if ($ok) { $ctx.Edits.Add(@{ Start = $start; End = $end; Text = $newText }) }
  3391. Add-ActNote $row $note $ok
  3392. }
  3393. # Режимы свойств элемента: имя свойства → состояние из <xr:PropertyState>
  3394. function Get-PropertyStates([string]$text, $el) {
  3395. $states = @{}
  3396. $ii = Get-XmlChild $text $el 'InternalInfo'
  3397. if (-not $ii) { return $states }
  3398. foreach ($ps in (Get-XmlChildren $text $ii)) {
  3399. if ($ps.Local -cne 'PropertyState') { continue }
  3400. $p = Get-XmlChild $text $ps 'Property'; $s = Get-XmlChild $text $ps 'State'
  3401. if ($p -and $s) { $states[(Get-XmlInner $text $p).Trim()] = (Get-XmlInner $text $s).Trim() }
  3402. }
  3403. return $states
  3404. }
  3405. # Элемент <xr:PropertyState> свойства (для удаления недопустимого режима) или $null
  3406. function Get-PropertyStateEl([string]$text, $el, [string]$prop) {
  3407. $ii = Get-XmlChild $text $el 'InternalInfo'
  3408. if (-not $ii) { return $null }
  3409. foreach ($ps in (Get-XmlChildren $text $ii)) {
  3410. if ($ps.Local -cne 'PropertyState') { continue }
  3411. $p = Get-XmlChild $text $ps 'Property'
  3412. if ($p -and (Get-XmlInner $text $p).Trim() -ceq $prop) { return $ps }
  3413. }
  3414. return $null
  3415. }
  3416. # Описание типов: состав (Type / TypeSet / TypeId) и квалификаторы по виду
  3417. function Get-TypeModel([string]$text, $typeEl) {
  3418. $types = New-Object System.Collections.Generic.List[string]
  3419. $quals = @{}
  3420. foreach ($c in (Get-XmlChildren $text $typeEl)) {
  3421. if ($c.Local -ceq 'Type' -or $c.Local -ceq 'TypeSet' -or $c.Local -ceq 'TypeId') {
  3422. $types.Add($c.Local + '|' + (Get-XmlInner $text $c).Trim())
  3423. } elseif ($c.Local.EndsWith('Qualifiers')) {
  3424. $quals[$c.Local] = $c
  3425. }
  3426. }
  3427. return @{ Types = $types; Quals = $quals }
  3428. }
  3429. # Квалификатор, который нужен типу из состава
  3430. $script:qualKindByType = @{ 'Type|xs:string' = 'StringQualifiers'; 'Type|xs:decimal' = 'NumberQualifiers'; 'Type|xs:dateTime' = 'DateQualifiers'; 'Type|xs:base64Binary' = 'BinaryDataQualifiers' }
  3431. $script:qualOrder = @('NumberQualifiers', 'StringQualifiers', 'DateQualifiers', 'BinaryDataQualifiers')
  3432. function Get-QualValue([string]$text, $q, [string]$local) {
  3433. $c = Get-XmlChild $text $q $local
  3434. if ($c) { return (Get-XmlInner $text $c).Trim() }
  3435. return ''
  3436. }
  3437. # Короткое описание состава типа для отчёта: String(10), Number(10,2), CatalogRef.X
  3438. function Format-TypeSummary([string]$text, $model, $kinds) {
  3439. $parts = @()
  3440. foreach ($t in $model.Types) {
  3441. if ($kinds -and $kinds -cnotcontains $t) { continue }
  3442. $v = $t.Substring($t.IndexOf('|') + 1)
  3443. switch ($t) {
  3444. 'Type|xs:string' { $q = $model.Quals['StringQualifiers']; $v = if ($q) { "String($(Get-QualValue $text $q 'Length'))" } else { 'String' } }
  3445. 'Type|xs:decimal' { $q = $model.Quals['NumberQualifiers']; $v = if ($q) { "Number($(Get-QualValue $text $q 'Digits'),$(Get-QualValue $text $q 'FractionDigits'))" } else { 'Number' } }
  3446. 'Type|xs:boolean' { $v = 'Boolean' }
  3447. 'Type|xs:dateTime' { $v = 'Date' }
  3448. default { $v = $v -replace '^\w+:', '' }
  3449. }
  3450. $parts += $v
  3451. }
  3452. return ($parts -join ', ')
  3453. }
  3454. # Сравнение состава типа с источником: те же типы и те же квалификаторы нужных видов
  3455. function Test-TypeModelEqual([string]$aText, $a, [string]$bText, $b) {
  3456. if ($a.Types.Count -ne $b.Types.Count) { return $false }
  3457. foreach ($t in $a.Types) { if ($b.Types -cnotcontains $t) { return $false } }
  3458. $keys = @($a.Quals.Keys) + @($b.Quals.Keys) | Select-Object -Unique
  3459. foreach ($k in $keys) {
  3460. $qa = $a.Quals[$k]; $qb = $b.Quals[$k]
  3461. if (-not $qa -or -not $qb) { return $false }
  3462. if ((Get-NormXml (Get-XmlOuter $aText $qa)) -cne (Get-NormXml (Get-XmlOuter $bText $qb))) { return $false }
  3463. }
  3464. return $true
  3465. }
  3466. # Карта переименований заимствованных объектов: «Вид.ИмяВРасширении» → имя в источнике (ECO найден
  3467. # под другим именем). Ссылки расширения на такие объекты сверяются с источником через неё — иначе
  3468. # CatalogRef.Старое в типе выглядело бы пропавшим из источника, а фрагмент из источника, вписанный
  3469. # до переименования, сослался бы на имя, которого в расширении ещё нет.
  3470. $script:extRenames = $null
  3471. function Get-ExtRenames {
  3472. if ($null -ne $script:extRenames) { return $script:extRenames }
  3473. $script:extRenames = @{}
  3474. foreach ($it in (Get-AllAdoptedItems)) {
  3475. $t = $it.Substring(0, $it.IndexOf('.')); $n = $it.Substring($it.IndexOf('.') + 1)
  3476. $text = [System.IO.File]::ReadAllText((Join-Path (Join-Path $extDir $childTypeDirMap[$t]) "$n.xml"))
  3477. $root = Get-MdRoot $text
  3478. if (-not $root) { continue }
  3479. $link = Get-ElementLink $text $root
  3480. if (-not $link) { continue }
  3481. $id = Resolve-FileIdentity (Join-Path $cfgDir $childTypeDirMap[$t]) $n $link
  3482. if ($id.Kind -eq 'Renamed') { $script:extRenames["$t.$n"] = $id.Src.Name }
  3483. }
  3484. return $script:extRenames
  3485. }
  3486. # Префиксы ссылок на объект вида: сам вид (MDObjectRef), его порождённые типы (CatalogRef, …) и типы
  3487. # табличных частей (CatalogTabularSection.Имя.ТЧ, CatalogTabularSectionRow.Имя.ТЧ)
  3488. function Get-TypeRefPrefixes([string]$typeName) {
  3489. return @($typeName, "${typeName}TabularSection", "${typeName}TabularSectionRow") + @($script:generatedTypes[$typeName] | ForEach-Object { $_.prefix })
  3490. }
  3491. # Ссылки на переименованные объекты: $toSource — имена расширения → имена источника, иначе обратно
  3492. # Один проход на вид: по очереди обмен именами (A ↔ B) вернул бы первую замену второй, и тип молча
  3493. # указал бы на другой объект
  3494. function Convert-RenamedRefs([string]$s, [bool]$toSource) {
  3495. $map = Get-ExtRenames
  3496. $byType = @{}
  3497. foreach ($k in @($map.Keys)) {
  3498. $t = $k.Substring(0, $k.IndexOf('.')); $old = $k.Substring($k.IndexOf('.') + 1); $new = $map[$k]
  3499. if (-not $byType.ContainsKey($t)) { $byType[$t] = @{} }
  3500. if ($toSource) { $byType[$t][$old] = $new } else { $byType[$t][$new] = $old }
  3501. }
  3502. foreach ($t in @($byType.Keys)) {
  3503. $tm = $byType[$t]
  3504. $alt = (Get-TypeRefPrefixes $t | Sort-Object -Property Length -Descending | ForEach-Object { [regex]::Escape($_) }) -join '|'
  3505. $re = [regex]('(?<![\w.])((?:' + $alt + ')\.)(' + (New-RenameRegexAlt $tm) + ')(?![\wА-Яа-яЁё])')
  3506. $s = $re.Replace($s, { param($m) $m.Groups[1].Value + $tm[$m.Groups[2].Value] })
  3507. }
  3508. return $s
  3509. }
  3510. # Часть составного типа (xr:CheckValue / xr:NotifyValue) против источника: типы, которых в источнике
  3511. # нет, удаляются (заявленного в источнике больше нет — расширение с ним не применится), квалификаторы — из источника. ExtendValue — переопределение, не трогаем.
  3512. # Новые типы источника не добавляем: платформа сверяет заявленное как подмножество (замер М5).
  3513. function Sync-TypePart($ctx, $row, $part, [string]$srcText, $srcModel, [string]$label) {
  3514. $text = $ctx.Text
  3515. $pm = Get-TypeModel $text $part
  3516. $keep = @($pm.Types | Where-Object { $srcModel.Types -ccontains (Convert-RenamedRefs $_ $true) })
  3517. $gone = @($pm.Types | Where-Object { $srcModel.Types -cnotcontains (Convert-RenamedRefs $_ $true) })
  3518. $needKinds = @($keep | ForEach-Object { $script:qualKindByType[$_] } | Where-Object { $_ })
  3519. $qualsDiffer = $false
  3520. foreach ($k in $script:qualOrder) {
  3521. $has = $pm.Quals.ContainsKey($k); $need = ($needKinds -ccontains $k) -and $srcModel.Quals.ContainsKey($k)
  3522. if ($has -ne $need) { $qualsDiffer = $true; break }
  3523. if ($has -and (Get-NormXml (Get-XmlOuter $text $pm.Quals[$k])) -cne (Get-NormXml (Get-XmlOuter $srcText $srcModel.Quals[$k]))) { $qualsDiffer = $true; break }
  3524. }
  3525. if ($gone.Count -eq 0 -and -not $qualsDiffer) { return }
  3526. $eol = $ctx.Eol
  3527. $partIndent = Get-LineIndent $text $part.Start
  3528. $kids = Get-XmlChildren $text $part
  3529. $childIndent = if ($kids.Count -gt 0) { Get-LineIndent $text $kids[0].Start } else { $partIndent + "`t" }
  3530. $before = Format-TypeSummary $text $pm $null
  3531. if ($keep.Count -eq 0) {
  3532. # Часть опустела — убираем элемент целиком вместе с его строкой
  3533. $ls = $part.Start - $partIndent.Length
  3534. $cut = $ls; if ($cut -ge $eol.Length -and $text.Substring($cut - $eol.Length, $eol.Length) -eq $eol) { $cut -= $eol.Length }
  3535. Add-ActEdit $ctx $row $cut $part.End '' "${label}: $before -> (removed: not in the source)"
  3536. return
  3537. }
  3538. $sb = New-Object System.Text.StringBuilder
  3539. $sb.Append($text.Substring($part.Start, $part.OpenEnd - $part.Start)) | Out-Null
  3540. foreach ($c in $kids) {
  3541. 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())) {
  3542. $sb.Append($eol + $childIndent + (Get-XmlOuter $text $c)) | Out-Null
  3543. }
  3544. }
  3545. foreach ($k in $script:qualOrder) {
  3546. if (($needKinds -ccontains $k) -and $srcModel.Quals.ContainsKey($k)) {
  3547. $sq = $srcModel.Quals[$k]
  3548. $frag = Set-FragmentIndent (Get-XmlOuter $srcText $sq) (Get-LineIndent $srcText $sq.Start) $childIndent $eol
  3549. $sb.Append($eol + $childIndent + $frag) | Out-Null
  3550. }
  3551. }
  3552. $sb.Append($eol + $partIndent + "</$($part.Name)>") | Out-Null
  3553. $afterModel = @{ Types = $keep; Quals = $srcModel.Quals }
  3554. $after = Format-TypeSummary $srcText $afterModel $null
  3555. $note = "${label}: $before -> $after"
  3556. if ($gone.Count -gt 0) { $note += " (removed: not in the source)" }
  3557. Add-ActEdit $ctx $row $part.Start $part.End $sb.ToString() $note
  3558. }
  3559. # Группы объявленных свойств. Контролируемые (замеры М2/М4/М5, ПР #99) приводятся к источнику по режимам.
  3560. # Дополнения — список расширения сливается со списком источника (замер М10: движения документа, состав
  3561. # подсистемы): там своё расширения, к источнику не приводим. Прочие — не трогаем, только сообщаем о
  3562. # расхождении: свойство может оказаться дополнением, и замена стёрла бы чужое.
  3563. $script:controlledProps = @('Type', 'Owners', 'Global', 'ClientManagedApplication', 'Server', 'ExternalConnection',
  3564. 'ClientOrdinaryApplication', 'ServerCall', 'Hierarchical', 'CodeLength', 'DescriptionLength', 'CodeType',
  3565. 'CodeAllowedLength', 'NumberType', 'NumberLength', 'NumberAllowedLength', 'InformationRegisterPeriodicity',
  3566. 'WriteMode', 'LanguageCode', 'RegisteredDocuments', 'ExtDimensionTypes', 'MaxExtDimensionCount')
  3567. $script:additiveProps = @('RegisterRecords', 'Content')
  3568. # Свойства, для которых Конфигуратор переопределения не предлагает (замер М4). Платформа Extended у них
  3569. # принимает, но при выгрузке теряет, и своя же выгрузка не грузится (замеры М15, М16: Hierarchical,
  3570. # InformationRegisterPeriodicity) — сверяем как контролируемые, режим убираем
  3571. $script:noOverrideProps = @('Hierarchical', 'InformationRegisterPeriodicity', 'WriteMode', 'Global',
  3572. 'ClientManagedApplication', 'Server', 'ExternalConnection', 'ClientOrdinaryApplication', 'ServerCall', 'CodeAllowedLength', 'LanguageCode')
  3573. # Свойства заимствованного элемента против источника — по режимам
  3574. function Sync-AdoptedProperties($ctx, $row, $extEl, [string]$srcText, $srcEl) {
  3575. $text = $ctx.Text
  3576. $props = Get-XmlChild $text $extEl 'Properties'
  3577. $srcProps = Get-XmlChild $srcText $srcEl 'Properties'
  3578. if (-not $props -or -not $srcProps) { return }
  3579. $states = Get-PropertyStates $text $extEl
  3580. $srcKids = @{}
  3581. foreach ($sc in (Get-XmlChildren $srcText $srcProps)) { if (-not $srcKids.ContainsKey($sc.Local)) { $srcKids[$sc.Local] = $sc } }
  3582. foreach ($c in (Get-XmlChildren $text $props)) {
  3583. if (@('ObjectBelonging', 'Name', 'Comment', 'ExtendedConfigurationObject') -ccontains $c.Local) { continue }
  3584. $state = $states[$c.Local]
  3585. if ($state -ceq 'Extended' -and $script:noOverrideProps -ccontains $c.Local) {
  3586. $psEl = Get-PropertyStateEl $text $extEl $c.Local
  3587. if ($psEl) {
  3588. $ls = $text.LastIndexOf("`n", $psEl.Start) + 1
  3589. $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++ }
  3590. 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"
  3591. }
  3592. $state = $null
  3593. }
  3594. # Переопределение типа платформа принимает только частями (MultiState, xr:ExtendValue); одиночный
  3595. # Extended у Type она не применяет и сверяет тип как контролируемый (замер М13, 8.3.27)
  3596. if ($state -ceq 'Extended' -and $c.Local -cne 'Type') { continue }
  3597. if ($script:additiveProps -ccontains $c.Local) { continue }
  3598. $sc = $srcKids[$c.Local]
  3599. if (-not $sc) { continue }
  3600. if ($script:controlledProps -cnotcontains $c.Local) {
  3601. if ((Get-NormXml (Convert-RenamedRefs (Get-XmlOuter $text $c) $true)) -cne (Get-NormXml (Get-XmlOuter $srcText $sc))) {
  3602. Add-ActNote $row "$($c.Local): differs from the source, not refreshed (not a known controlled property)" $false $true
  3603. }
  3604. continue
  3605. }
  3606. $modeTag = if ($state -ceq 'Notify') { ' (mode: Notify)' } else { '' }
  3607. if ($c.Local -ceq 'Owners') {
  3608. $srcItems = @((Get-XmlChildren $srcText $sc) | ForEach-Object { (Get-XmlInner $srcText $_).Trim() })
  3609. $items = Get-XmlChildren $text $c
  3610. $gone = @($items | Where-Object { $srcItems -cnotcontains (Convert-RenamedRefs (Get-XmlInner $text $_).Trim() $true) })
  3611. if ($gone.Count -eq 0) { continue }
  3612. $ind = Get-LineIndent $text $c.Start
  3613. $kept = @($items | Where-Object { $srcItems -ccontains (Convert-RenamedRefs (Get-XmlInner $text $_).Trim() $true) })
  3614. if ($kept.Count -eq 0) { $new = "<$($c.Name)/>" }
  3615. else {
  3616. $ci = Get-LineIndent $text $kept[0].Start
  3617. $new = "<$($c.Name)>" + (($kept | ForEach-Object { $ctx.Eol + $ci + (Get-XmlOuter $text $_) }) -join '') + $ctx.Eol + $ind + "</$($c.Name)>"
  3618. }
  3619. $goneNames = ($gone | ForEach-Object { (Get-XmlInner $text $_).Trim() }) -join ', '
  3620. Add-ActEdit $ctx $row $c.Start $c.End $new "Owners: removed $goneNames (not in the source)"
  3621. continue
  3622. }
  3623. if ($c.Local -ceq 'Type') {
  3624. $srcModel = Get-TypeModel $srcText $sc
  3625. if ($state -ceq 'MultiState' -or $c.Attrs -match 'ExtendedProperty') {
  3626. foreach ($part in (Get-XmlChildren $text $c)) {
  3627. if ($part.Local -ceq 'CheckValue') { Sync-TypePart $ctx $row $part $srcText $srcModel 'Type (check part)' }
  3628. elseif ($part.Local -ceq 'NotifyValue') { Sync-TypePart $ctx $row $part $srcText $srcModel 'Type (notify part)' }
  3629. }
  3630. continue
  3631. }
  3632. $model = Get-TypeModel $text $c
  3633. $cmpModel = @{ Types = @($model.Types | ForEach-Object { Convert-RenamedRefs $_ $true }); Quals = $model.Quals }
  3634. if (Test-TypeModelEqual $text $cmpModel $srcText $srcModel) { continue }
  3635. $new = Convert-RenamedRefs (Set-FragmentIndent (Get-XmlOuter $srcText $sc) (Get-LineIndent $srcText $sc.Start) (Get-LineIndent $text $c.Start) $ctx.Eol) $false
  3636. Add-ActEdit $ctx $row $c.Start $c.End $new "Type$($modeTag): $(Format-TypeSummary $text $model $null) -> $(Format-TypeSummary $srcText $srcModel $null)"
  3637. # Новые ссылочные типы — оболочками, как при первом заимствовании (ниже 8.3.25 иначе «Неизвестное имя типа»)
  3638. if (Test-EditAllowed) { $ctx.Shells.Add(@{ Row = $row; Xml = $new }) }
  3639. continue
  3640. }
  3641. $extNorm = Get-NormXml (Convert-RenamedRefs (Get-XmlOuter $text $c) $true); $srcNorm = Get-NormXml (Get-XmlOuter $srcText $sc)
  3642. if ($extNorm -ceq $srcNorm) { continue }
  3643. $new = Convert-RenamedRefs (Set-FragmentIndent (Get-XmlOuter $srcText $sc) (Get-LineIndent $srcText $sc.Start) (Get-LineIndent $text $c.Start) $ctx.Eol) $false
  3644. $was = (Get-XmlInner $text $c).Trim(); $now = (Get-XmlInner $srcText $sc).Trim()
  3645. if ($was.Contains('<') -or $now.Contains('<')) { $was = '…'; $now = '(source value)' }
  3646. Add-ActEdit $ctx $row $c.Start $c.End $new "$($c.Local)$($modeTag): $was -> $now"
  3647. # Виды субконто — ссылка на ПВХ: он обязан быть в расширении (иначе «ВидыСубконто не совпадает»,
  3648. # замер 8.3.27), как при первом заимствовании
  3649. if ($c.Local -ceq 'ExtDimensionTypes' -and (Test-EditAllowed) -and $now -match '^(\w+)\.([^.]+)$') {
  3650. $ctx.Shells.Add(@{ Row = $row; Ref = @{ TypeName = $Matches[1]; ObjName = $Matches[2] } })
  3651. }
  3652. }
  3653. }
  3654. # Связь заимствованного элемента: дописать отсутствующий ECO (данные своих реквизитов при этом целы — М3)
  3655. function Add-MissingLink($ctx, $row, $extEl, [string]$uuid) {
  3656. $text = $ctx.Text
  3657. $props = Get-XmlChild $text $extEl 'Properties'
  3658. if (-not $props) { return }
  3659. $anchor = Get-XmlChild $text $props 'Comment'
  3660. if (-not $anchor) { $anchor = Get-XmlChild $text $props 'Name' }
  3661. if (-not $anchor) { return }
  3662. # Нулевой UUID (cfe-init без -ConfigPath) ни с чем не совпадает — заменяем значение на месте
  3663. $zero = Get-XmlChild $text $props 'ExtendedConfigurationObject'
  3664. if ($zero) {
  3665. Add-ActEdit $ctx $row $zero.Start $zero.End "<ExtendedConfigurationObject>$uuid</ExtendedConfigurationObject>" "ExtendedConfigurationObject: zero link replaced ($uuid)"
  3666. return
  3667. }
  3668. $ind = Get-LineIndent $text $anchor.Start
  3669. Add-ActEdit $ctx $row $anchor.End $anchor.End ($ctx.Eol + $ind + "<ExtendedConfigurationObject>$uuid</ExtendedConfigurationObject>") "ExtendedConfigurationObject: link restored ($uuid)"
  3670. }
  3671. function Get-MdElementName([string]$text, $el) {
  3672. $props = Get-XmlChild $text $el 'Properties'
  3673. if (-not $props) { return $null }
  3674. $n = Get-XmlChild $text $props 'Name'
  3675. if ($n) { return (Get-XmlInner $text $n).Trim() }
  3676. return $null
  3677. }
  3678. function Get-ElementLink([string]$text, $el) {
  3679. $props = Get-XmlChild $text $el 'Properties'
  3680. if (-not $props) { return $null }
  3681. $e = Get-XmlChild $text $props 'ExtendedConfigurationObject'
  3682. if ($e) {
  3683. # Нулевой UUID — связи нет (след cfe-init без -ConfigPath), а не пересозданный объект
  3684. $v = (Get-XmlInner $text $e).Trim()
  3685. if ($v -ceq '00000000-0000-0000-0000-000000000000') { return $null }
  3686. return $v
  3687. }
  3688. return $null
  3689. }
  3690. function Test-ElementAdopted([string]$text, $el) {
  3691. $props = Get-XmlChild $text $el 'Properties'
  3692. if (-not $props) { return $false }
  3693. $ob = Get-XmlChild $text $props 'ObjectBelonging'
  3694. return ($ob -and (Get-XmlInner $text $ob).Trim() -ceq 'Adopted')
  3695. }
  3696. # Начало файла источника: uuid и имя объекта (первый <Name> — имя самого объекта)
  3697. function Read-SourceHead([string]$file) {
  3698. if ($script:srcHeadCache.ContainsKey($file)) { return $script:srcHeadCache[$file] }
  3699. # Читаем порциями до первого </Name>: файл объекта бывает в мегабайты, а нужна только шапка
  3700. $sr = New-Object System.IO.StreamReader($file, [System.Text.Encoding]::UTF8)
  3701. $sb = New-Object System.Text.StringBuilder
  3702. $buf = New-Object char[] 16384
  3703. try {
  3704. while (($k = $sr.Read($buf, 0, $buf.Length)) -gt 0) {
  3705. $from = [Math]::Max(0, $sb.Length - 6)
  3706. $sb.Append($buf, 0, $k) | Out-Null
  3707. if ($sb.ToString($from, $sb.Length - $from).Contains('</Name>')) { break }
  3708. }
  3709. } finally { $sr.Close() }
  3710. $text = $sb.ToString()
  3711. $u = [regex]::Match($text, '<MetaDataObject[^>]*>\s*<\w+\s+uuid="([^"]+)"')
  3712. $n = [regex]::Match($text, '<Name>([^<]*)</Name>')
  3713. $h = @{ Uuid = $(if ($u.Success) { $u.Groups[1].Value.ToLowerInvariant() } else { '' }); Name = $(if ($n.Success) { $n.Groups[1].Value } else { '' }); File = $file }
  3714. $script:srcHeadCache[$file] = $h
  3715. return $h
  3716. }
  3717. # Связи заимствованных объектов вида в расширении: UUID источника → имена (больше одного — дубль). Строится
  3718. # один раз за запуск по состоянию до правок
  3719. $script:extLinkIndex = @{}
  3720. function Get-ExtLinkIndex([string]$typeName) {
  3721. if ($script:extLinkIndex.ContainsKey($typeName)) { return $script:extLinkIndex[$typeName] }
  3722. $idx = @{}
  3723. $dir = Join-Path $extDir $childTypeDirMap[$typeName]
  3724. if (Test-Path -LiteralPath $dir) {
  3725. foreach ($f in (Get-ChildItem -LiteralPath $dir -Filter '*.xml' -File)) {
  3726. if ($f.Extension -ne '.xml') { continue }
  3727. $t = [System.IO.File]::ReadAllText($f.FullName)
  3728. $root = Get-MdRoot $t
  3729. if (-not $root -or -not (Test-ElementAdopted $t $root)) { continue }
  3730. $l = Get-ElementLink $t $root
  3731. if (-not $l) { continue }
  3732. $l = $l.ToLowerInvariant()
  3733. if (-not $idx.ContainsKey($l)) { $idx[$l] = @() }
  3734. $idx[$l] += (Get-MdElementName $t $root)
  3735. }
  3736. }
  3737. $script:extLinkIndex[$typeName] = $idx
  3738. return $idx
  3739. }
  3740. # Элемент пакета назван именем источника, а в расширении он заимствован под прежним (источник его
  3741. # переименовал): тот же UUID связи. Возвращает элемент под именем расширения — актуализация переименует
  3742. # его вслед за источником, а не заимствует второй с той же связью (платформа такой не грузит, замер М15)
  3743. function Resolve-ItemByLink([string]$item) {
  3744. $pi = Split-BorrowItem $item
  3745. if ($pi.Error -or $pi.IsCommonForm) { return $item }
  3746. $srcDir = Join-Path $cfgDir $pi.DirName
  3747. if (-not (Test-ObjectBorrowed $pi.TypeName $pi.ObjName)) {
  3748. $sf = Join-Path $srcDir "$($pi.ObjName).xml"
  3749. if (-not (Test-Path -LiteralPath $sf)) { return $item }
  3750. $h = Read-SourceHead $sf
  3751. $names = @((Get-ExtLinkIndex $pi.TypeName)[$h.Uuid] | Where-Object { $_ })
  3752. if ($names.Count -gt 1) {
  3753. # Дубль уже есть — ещё одна копия с той же связью только усугубит
  3754. 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"
  3755. exit 1
  3756. }
  3757. if ($names.Count -ne 1) { return $item }
  3758. Info "$($pi.TypeName).$($pi.ObjName) is borrowed as $($pi.TypeName).$($names[0]) (renamed in the source)"
  3759. $item = $item -replace ('^([^.]+)\.' + [regex]::Escape($pi.ObjName) + '(?=\.|$)'), ('$1.' + $names[0].Replace('$', '$$'))
  3760. $pi = Split-BorrowItem $item
  3761. }
  3762. if ($pi.SubKind -and -not (Test-SubBorrowed $pi)) {
  3763. $ext = [System.IO.File]::ReadAllText((Join-Path (Join-Path $extDir $pi.DirName) "$($pi.ObjName).xml"))
  3764. # Объект источника — по связи объекта расширения (его тоже могли переименовать), иначе по имени
  3765. $sf = Join-Path $srcDir "$($pi.ObjName).xml"
  3766. $ol = Get-ElementLink $ext (Get-MdRoot $ext)
  3767. if ($ol) { $hs = (Get-SourceUuidIndex $srcDir)[$ol.ToLowerInvariant()]; if ($hs) { $sf = $hs.File } }
  3768. if (-not (Test-Path -LiteralPath $sf)) { return $item }
  3769. $st = [System.IO.File]::ReadAllText($sf)
  3770. $sEl = $null
  3771. foreach ($sc in (Get-XmlChildren $st (Get-XmlChild $st (Get-MdRoot $st) 'ChildObjects'))) {
  3772. if ($sc.Local -ceq $pi.SubKind -and (Get-MdElementName $st $sc) -ceq $pi.SubName) { $sEl = $sc; break }
  3773. }
  3774. if (-not $sEl) { return $item }
  3775. $su = (Get-XmlAttr $sEl 'uuid')
  3776. if (-not $su) { return $item }
  3777. foreach ($ec in (Get-XmlChildren $ext (Get-XmlChild $ext (Get-MdRoot $ext) 'ChildObjects'))) {
  3778. if ($ec.Local -cne $pi.SubKind -or -not (Get-XmlChild $ext $ec 'Properties') -or -not (Test-ElementAdopted $ext $ec)) { continue }
  3779. $el = Get-ElementLink $ext $ec
  3780. if ($el -and $el.ToLowerInvariant() -eq $su.ToLowerInvariant()) {
  3781. $en = Get-MdElementName $ext $ec
  3782. Info "$($pi.TypeName).$($pi.ObjName).$($pi.SubKind).$($pi.SubName) is borrowed as $($pi.SubKind) $en (renamed in the source)"
  3783. $item = "$($pi.TypeName).$($pi.ObjName).$($pi.SubKind).$en"
  3784. if ($pi.ColName) { $item += ".Attribute.$($pi.ColName)" }
  3785. break
  3786. }
  3787. }
  3788. }
  3789. # Форма: заимствована под прежним именем (переименована в источнике) — та же связь
  3790. if ($pi.FormName -and (Test-ObjectBorrowed $pi.TypeName $pi.ObjName) -and -not (Test-FormBorrowed $pi)) {
  3791. $ext = [System.IO.File]::ReadAllText((Join-Path (Join-Path $extDir $pi.DirName) "$($pi.ObjName).xml"))
  3792. $srcObj = $pi.ObjName
  3793. $ol = Get-ElementLink $ext (Get-MdRoot $ext)
  3794. if ($ol) { $hs = (Get-SourceUuidIndex $srcDir)[$ol.ToLowerInvariant()]; if ($hs) { $srcObj = $hs.Name } }
  3795. $sff = Join-Path (Join-Path (Join-Path $srcDir $srcObj) "Forms") "$($pi.FormName).xml"
  3796. $extForms = Join-Path (Join-Path (Join-Path $extDir $pi.DirName) $pi.ObjName) "Forms"
  3797. if ((Test-Path -LiteralPath $sff) -and (Test-Path -LiteralPath $extForms)) {
  3798. $fu = (Read-SourceHead $sff).Uuid
  3799. foreach ($ef in (Get-ChildItem -LiteralPath $extForms -Filter '*.xml' -File)) {
  3800. if ($ef.Extension -ne '.xml') { continue }
  3801. $et = [System.IO.File]::ReadAllText($ef.FullName)
  3802. $el = Get-ElementLink $et (Get-MdRoot $et)
  3803. if ($fu -and $el -and $el.ToLowerInvariant() -eq $fu) {
  3804. $en = Get-MdElementName $et (Get-MdRoot $et)
  3805. Info "$($pi.TypeName).$($pi.ObjName).Form.$($pi.FormName) is borrowed as form $en (renamed in the source)"
  3806. $item = "$($pi.TypeName).$($pi.ObjName).Form.$en"
  3807. break
  3808. }
  3809. }
  3810. }
  3811. }
  3812. return $item
  3813. }
  3814. function Get-SourceUuidIndex([string]$dir) {
  3815. if ($script:srcUuidIndex.ContainsKey($dir)) { return $script:srcUuidIndex[$dir] }
  3816. $idx = @{}
  3817. if (Test-Path -LiteralPath $dir) {
  3818. foreach ($f in (Get-ChildItem -LiteralPath $dir -Filter '*.xml' -File)) {
  3819. if ($f.Extension -ne '.xml') { continue }
  3820. $h = Read-SourceHead $f.FullName
  3821. if ($h.Uuid -and -not $idx.ContainsKey($h.Uuid)) { $idx[$h.Uuid] = $h }
  3822. }
  3823. }
  3824. $script:srcUuidIndex[$dir] = $idx
  3825. return $idx
  3826. }
  3827. # Чей это объект в источнике: по ECO и по имени. Kind: Match | NoLink (ECO нет, имя есть) |
  3828. # Renamed (ECO под другим именем) | Replaced (по ECO нет, тёзка с другим UUID) | Missing
  3829. function Resolve-FileIdentity([string]$srcDir, [string]$name, [string]$link) {
  3830. $byName = $null
  3831. $f = Join-Path $srcDir "$name.xml"
  3832. if (Test-Path -LiteralPath $f -PathType Leaf) {
  3833. $h = Read-SourceHead $f
  3834. if ($h.Name -ceq $name) { $byName = $h }
  3835. }
  3836. $link = if ($link) { $link.ToLowerInvariant() } else { '' }
  3837. if (-not $link) {
  3838. if ($byName) { return @{ Kind = 'NoLink'; Src = $byName } }
  3839. return @{ Kind = 'Missing' }
  3840. }
  3841. if ($byName -and $byName.Uuid -eq $link) { return @{ Kind = 'Match'; Src = $byName } }
  3842. $idx = Get-SourceUuidIndex $srcDir
  3843. if ($idx.ContainsKey($link)) { return @{ Kind = 'Renamed'; Src = $idx[$link] } }
  3844. if ($byName) { return @{ Kind = 'Replaced'; Src = $byName } }
  3845. return @{ Kind = 'Missing' }
  3846. }
  3847. # То же для подобъекта — среди детей того же вида в элементе источника
  3848. function Resolve-ChildIdentity([string]$srcText, $srcParent, [string]$kind, [string]$name, [string]$link) {
  3849. $co = Get-XmlChild $srcText $srcParent 'ChildObjects'
  3850. $byName = $null; $byLink = $null
  3851. $link = if ($link) { $link.ToLowerInvariant() } else { '' }
  3852. foreach ($c in (Get-XmlChildren $srcText $co)) {
  3853. if ($c.Local -cne $kind) { continue }
  3854. $u = (Get-XmlAttr $c 'uuid'); $u = if ($u) { $u.ToLowerInvariant() } else { '' }
  3855. $n = Get-MdElementName $srcText $c
  3856. if ($link -and $u -eq $link) { $byLink = @{ El = $c; Name = $n; Uuid = $u } }
  3857. if ($n -ceq $name) { $byName = @{ El = $c; Name = $n; Uuid = $u } }
  3858. }
  3859. if (-not $link) { if ($byName) { return @{ Kind = 'NoLink'; Src = $byName } }; return @{ Kind = 'Missing' } }
  3860. if ($byLink) {
  3861. if ($byLink.Name -ceq $name) { return @{ Kind = 'Match'; Src = $byLink } }
  3862. return @{ Kind = 'Renamed'; Src = $byLink }
  3863. }
  3864. if ($byName) { return @{ Kind = 'Replaced'; Src = $byName } }
  3865. return @{ Kind = 'Missing' }
  3866. }
  3867. function Set-IdentityStatus($row, $id, [string]$oldName) {
  3868. switch ($id.Kind) {
  3869. 'Replaced' {
  3870. $row.Status = 'REPLACED'
  3871. 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
  3872. }
  3873. 'Missing' {
  3874. $row.Status = 'NOT FOUND'
  3875. Add-ActNote $row "not found in the source by link or by name — not changed" $false
  3876. }
  3877. }
  3878. }
  3879. # Переименования одного уровня применяются ОДНИМ проходом по карте «старое → новое»: по очереди обмен
  3880. # именами (A ↔ B) вернул бы первое переименование вторым, и поле формы молча показало бы другой реквизит.
  3881. # Возвращают число замен по каждому старому имени.
  3882. function New-RenameRegexAlt($map) {
  3883. return (@($map.Keys) | Sort-Object -Property Length -Descending | ForEach-Object { [regex]::Escape($_) }) -join '|'
  3884. }
  3885. # Сегменты путей к данным формы: <Основной>[.<ТЧ>].<Старое> → .<Новое> (DataPath*, Field, в форме и BaseForm)
  3886. function Rename-FormDataPaths([string]$formXml, [string]$prefixPath, $map) {
  3887. $counts = @{}
  3888. if (-not (Test-Path -LiteralPath $formXml)) { return $counts }
  3889. $style = Detect-XmlStyle $formXml
  3890. $text = [System.IO.File]::ReadAllText($formXml)
  3891. $main = [regex]::Match($text, '<Attribute name="([^"]+)"[^>]*>(?:(?!</Attribute>).)*?<MainAttribute>true</MainAttribute>', 'Singleline')
  3892. if (-not $main.Success) { return $counts }
  3893. $pre = [regex]::Escape($main.Groups[1].Value + $prefixPath + '.')
  3894. $re = [regex]('(<(?:\w*DataPath|Field)>~?' + $pre + ')(' + (New-RenameRegexAlt $map) + ')(?=[.<])')
  3895. $n = $re.Replace($text, { param($m) $o = $m.Groups[2].Value; $counts[$o] = 1 + [int]$counts[$o]; $m.Groups[1].Value + $map[$o] })
  3896. if ($counts.Count -gt 0) { [System.IO.File]::WriteAllText($formXml, $n, (Get-StyleEncoding $style)) }
  3897. return $counts
  3898. }
  3899. # Ссылки на переименованный подобъект в XML расширения — MDObjectRef вида Enum.X.EnumValue.Старое,
  3900. # Catalog.X.Attribute.Старое (параметры выбора форм, права ролей, поля блокировки). Configuration.xml
  3901. # пишется в конце из $script:xmlDoc — подобъектов в нём нет.
  3902. function Rename-SubObjectRefs([string]$refPath, $map) {
  3903. $counts = @{}
  3904. $re = [regex]('(?<![\w.])(' + [regex]::Escape("$refPath.") + ')(' + (New-RenameRegexAlt $map) + ')(?![\wА-Яа-яЁё])')
  3905. $cfgLong = (Get-Item -LiteralPath $extResolvedPath).FullName
  3906. foreach ($f in (Get-ChildItem -LiteralPath $extDir -Recurse -File -Filter '*.xml')) {
  3907. if ($f.FullName -eq $cfgLong) { continue }
  3908. $t = [System.IO.File]::ReadAllText($f.FullName)
  3909. if (-not $re.IsMatch($t)) { continue }
  3910. $n = $re.Replace($t, { param($m) $o = $m.Groups[2].Value; $counts[$o] = 1 + [int]$counts[$o]; $m.Groups[1].Value + $map[$o] })
  3911. [System.IO.File]::WriteAllText($f.FullName, $n, (Get-StyleEncoding (Detect-XmlStyle $f.FullName)))
  3912. }
  3913. return $counts
  3914. }
  3915. # Оставшиеся упоминания старых имён в коде расширения — для ручной правки: модули целиком, в XML —
  3916. # только тексты запросов (<QueryText> динамического списка, <query> схемы компоновки); заголовки и
  3917. # имена элементов формы к ссылкам не относятся. Один проход по файлам на все имена.
  3918. function Find-NameMentions([string[]]$names) {
  3919. $res = @{}
  3920. foreach ($n in $names) { $res[$n] = @() }
  3921. if ($names.Count -eq 0) { return $res }
  3922. $alt = ($names | Sort-Object -Property Length -Descending | ForEach-Object { [regex]::Escape($_) }) -join '|'
  3923. $re = New-Object System.Text.RegularExpressions.Regex(('(?<![\wА-Яа-яЁё])(?:' + $alt + ')(?![\wА-Яа-яЁё])'), 'IgnoreCase')
  3924. # Get-ChildItem отдаёт длинные пути, а $extDir из Resolve-Path может быть коротким (NSHIRO~1)
  3925. $base = (Get-Item -LiteralPath $extDir).FullName
  3926. foreach ($f in (Get-ChildItem -LiteralPath $extDir -Recurse -File -Include '*.bsl', '*.xml')) {
  3927. $rel = $f.FullName.Substring($base.Length).TrimStart('\', '/') -replace '\\', '/'
  3928. $text = [System.IO.File]::ReadAllText($f.FullName)
  3929. $hits = New-Object System.Collections.Generic.List[object]
  3930. if ($f.Extension -ieq '.bsl') {
  3931. foreach ($m in $re.Matches($text)) { $hits.Add(@($m.Value, $m.Index)) }
  3932. } else {
  3933. foreach ($q in [regex]::Matches($text, '(?s)<(QueryText|query)>(.*?)</\1>')) {
  3934. foreach ($m in $re.Matches($q.Groups[2].Value)) { $hits.Add(@($m.Value, ($q.Groups[2].Index + $m.Index))) }
  3935. }
  3936. }
  3937. foreach ($h in $hits) {
  3938. $key = $names | Where-Object { $_ -ieq $h[0] } | Select-Object -First 1
  3939. $loc = "${rel}:$($text.Substring(0, $h[1]).Split("`n").Count)"
  3940. if ($res[$key] -notcontains $loc) { $res[$key] += $loc }
  3941. }
  3942. }
  3943. return $res
  3944. }
  3945. # Упоминания ищутся в конце запуска — по итоговым файлам и путям, после всех переименований.
  3946. # Смена только регистра — не повод: имена в коде 1С регистронезависимы.
  3947. $script:pendingMentions = New-Object System.Collections.Generic.List[object]
  3948. # $takenBy — кем старое имя теперь занято в источнике (тёзка, обмен именами): код со старым именем
  3949. # скомпилируется и молча будет работать с другим объектом — упоминания становятся предупреждением
  3950. function Add-MentionsNote($row, [string]$old, [string]$new, [string]$takenBy = '') {
  3951. if ($old -ieq $new) { return }
  3952. $script:pendingMentions.Add(@{ Row = $row; Name = $old; TakenBy = $takenBy })
  3953. }
  3954. function Resolve-PendingMentions {
  3955. if ($script:pendingMentions.Count -eq 0) { return }
  3956. $found = Find-NameMentions @($script:pendingMentions | ForEach-Object { $_.Name } | Select-Object -Unique)
  3957. foreach ($pm in $script:pendingMentions) {
  3958. $m = @($found[$pm.Name])
  3959. if ($m.Count -eq 0) { continue }
  3960. $shown = ($m | Select-Object -First 10) -join ', '
  3961. if ($m.Count -gt 10) { $shown += ", … ($($m.Count) total)" }
  3962. if ($pm.TakenBy) {
  3963. 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
  3964. } else {
  3965. Add-ActNote $pm.Row "'$($pm.Name)' is still mentioned in the code — fix by hand: $shown" $false
  3966. }
  3967. }
  3968. $script:pendingMentions.Clear()
  3969. }
  3970. # Переименование файла или каталога через временное имя: Move-Item в PS 5.1 не меняет регистр имени
  3971. function Move-PathViaTemp([string]$from, [string]$to) {
  3972. $tmp = Join-Path (Split-Path $from -Parent) ("__rename_" + [guid]::NewGuid().ToString('N'))
  3973. Move-Item -LiteralPath $from -Destination $tmp
  3974. Move-Item -LiteralPath $tmp -Destination $to
  3975. }
  3976. # Переименование заимствованного объекта следом за источником (как «Переименовать, сохранив
  3977. # соответствие» Конфигуратора): файл и каталог, Name, ChildObjects расширения, имена GeneratedType,
  3978. # ссылки в XML расширения (cfg:CatalogRef.Old, Catalog.Old, …). Код и тексты запросов — не трогаем.
  3979. function Rename-BorrowedObject([string]$typeName, [string]$old, [string]$new, $row) {
  3980. $dir = Join-Path $extDir $childTypeDirMap[$typeName]
  3981. $newFile = Join-Path $dir "$new.xml"
  3982. if ((Test-Path -LiteralPath $newFile) -and ($old -ine $new)) {
  3983. # Обмен именами в источнике (A ↔ B): имя занято заимствованным объектом, который сам переименован
  3984. # в источнике, — уводим его на временное имя, своё новое имя он получит в свою очередь
  3985. $renamesMap = Get-ExtRenames
  3986. $blockerTo = $renamesMap["$typeName.$new"]
  3987. if (-not $blockerTo) {
  3988. Add-ActNote $row "cannot rename: $typeName.$new already exists in the extension" $false
  3989. return $false
  3990. }
  3991. $tmp = "__swap_" + [guid]::NewGuid().ToString('N').Substring(0, 8)
  3992. Move-BorrowedObjectName $typeName $new $tmp
  3993. $renamesMap.Remove("$typeName.$new")
  3994. $renamesMap["$typeName.$tmp"] = $blockerTo
  3995. $script:objRenamed["$typeName.$new"] = $tmp
  3996. $script:swapPending.Add(@{ TypeName = $typeName; Tmp = $tmp; Shown = $new })
  3997. }
  3998. Move-BorrowedObjectName $typeName $old $new
  3999. if ($null -ne $script:extRenames) { $script:extRenames.Remove("$typeName.$old") }
  4000. $script:objRenamed["$typeName.$old"] = $new
  4001. return $true
  4002. }
  4003. # Файлы, имена, ссылки в XML расширения и ChildObjects — от старого имени объекта к новому
  4004. $script:swapPending = New-Object System.Collections.Generic.List[object]
  4005. function Move-BorrowedObjectName([string]$typeName, [string]$old, [string]$new) {
  4006. $dir = Join-Path $extDir $childTypeDirMap[$typeName]
  4007. $oldFile = Join-Path $dir "$old.xml"; $newFile = Join-Path $dir "$new.xml"
  4008. Move-PathViaTemp $oldFile $newFile
  4009. $oldDir = Join-Path $dir $old
  4010. if (Test-Path -LiteralPath $oldDir -PathType Container) { Move-PathViaTemp $oldDir (Join-Path $dir $new) }
  4011. $prefixes = Get-TypeRefPrefixes $typeName
  4012. $alt = ($prefixes | Sort-Object -Property Length -Descending | ForEach-Object { [regex]::Escape($_) }) -join '|'
  4013. $re = [regex]('(?<![\w.])((?:' + $alt + ')\.)' + [regex]::Escape($old) + '(?![\wА-Яа-яЁё])')
  4014. $cfgLong = (Get-Item -LiteralPath $extResolvedPath).FullName
  4015. foreach ($f in (Get-ChildItem -LiteralPath $extDir -Recurse -File -Filter '*.xml')) {
  4016. # Configuration.xml пишется в конце из $script:xmlDoc
  4017. if ($f.FullName -eq $cfgLong) { continue }
  4018. $t = [System.IO.File]::ReadAllText($f.FullName)
  4019. $n = $re.Replace($t, '${1}' + $new.Replace('$', '$$'))
  4020. if ($n -cne $t) {
  4021. $style = Detect-XmlStyle $f.FullName
  4022. [System.IO.File]::WriteAllText($f.FullName, $n, (Get-StyleEncoding $style))
  4023. }
  4024. }
  4025. # Имя самого объекта — первый <Name> в его Properties
  4026. $t = [System.IO.File]::ReadAllText($newFile)
  4027. $n = ([regex]('(<Properties>\s*(?:<ObjectBelonging>[^<]*</ObjectBelonging>\s*)?<Name>)' + [regex]::Escape($old) + '(</Name>)')).Replace($t, '${1}' + $new.Replace('$', '$$') + '${2}', 1)
  4028. [System.IO.File]::WriteAllText($newFile, $n, (Get-StyleEncoding (Detect-XmlStyle $newFile)))
  4029. # ChildObjects расширения — Configuration.xml пишется в конце из $script:xmlDoc
  4030. foreach ($child in @($script:childObjsEl.ChildNodes)) {
  4031. if ($child.NodeType -eq 'Element' -and $child.LocalName -eq $typeName -and $child.InnerText -ceq $old) {
  4032. $prev = $child.PreviousSibling
  4033. if ($prev -and ($prev.NodeType -eq 'Whitespace' -or $prev.NodeType -eq 'SignificantWhitespace')) { $script:childObjsEl.RemoveChild($prev) | Out-Null }
  4034. $script:childObjsEl.RemoveChild($child) | Out-Null
  4035. }
  4036. }
  4037. Add-ToChildObjects $typeName $new
  4038. }
  4039. # Заимствованная форма против формы источника. Своей пересборки на этом этапе нет: в рантайме
  4040. # платформа сама сливает BaseForm / форму расширения / текущую форму источника (замер М1), поэтому
  4041. # Form.xml не переписываем, а сообщаем, что поменялось, и где правка расширения столкнётся с источником.
  4042. # Сравнивается заготовка: текущая форма источника проходит тот же путь, что при заимствовании
  4043. # (Borrow-Form -RenderOnly), и её BaseForm сверяется с BaseForm расширения. Связи параметров выбора
  4044. # зависят от состава заимствованных реквизитов — их не сравниваем.
  4045. $script:formIgnoredTags = @('ChildItems', 'Events', 'ChoiceParameterLinks', 'TypeLink')
  4046. function Get-FormElementFlat([string]$text, $el) {
  4047. $sb = New-Object System.Text.StringBuilder
  4048. $sb.Append($el.Local + ' ' + ([regex]::Replace($el.Attrs, '\s+', ' ')).Trim()) | Out-Null
  4049. foreach ($c in (Get-XmlChildren $text $el)) {
  4050. if ($script:formIgnoredTags -ccontains $c.Local) { continue }
  4051. if (Get-XmlAttr $c 'name') { continue }
  4052. $sb.Append('|' + (Get-NormXml (Get-XmlOuter $text $c))) | Out-Null
  4053. }
  4054. # Тильда у путей динамического списка ставится после заимствования (шаг 14c)
  4055. return ($sb.ToString() -replace '(<(?:\w*DataPath|Field)>)~', '$1')
  4056. }
  4057. function Add-FormElementsFlat([string]$text, $el, $map) {
  4058. foreach ($c in (Get-XmlChildren $text $el)) {
  4059. if (@('Events', 'Attributes', 'Commands', 'Parameters', 'CommandInterface', 'BaseForm') -ccontains $c.Local) { continue }
  4060. $n = Get-XmlAttr $c 'name'
  4061. if ($n) { $map[$n] = Get-FormElementFlat $text $c }
  4062. Add-FormElementsFlat $text $c $map
  4063. }
  4064. }
  4065. function Get-FormFlatMap([string]$text, $formEl) {
  4066. $map = New-Object System.Collections.Hashtable ([System.StringComparer]::Ordinal)
  4067. $own = New-Object System.Text.StringBuilder
  4068. foreach ($c in (Get-XmlChildren $text $formEl)) {
  4069. if (@('AutoCommandBar', 'ChildItems') -ccontains $c.Local) { Add-FormElementsFlat $text $c $map; continue }
  4070. if (@('Events', 'Attributes', 'Commands', 'Parameters', 'CommandInterface', 'BaseForm') -ccontains $c.Local) { continue }
  4071. if ($script:formAttributeRefProps -ccontains $c.Local) { continue }
  4072. $own.Append('|' + (Get-NormXml (Get-XmlOuter $text $c))) | Out-Null
  4073. }
  4074. $map['(form properties)'] = $own.ToString()
  4075. return $map
  4076. }
  4077. function Compare-BorrowedForm($row, [string]$extFormXml, [string]$typeName, [string]$srcObjName, [string]$srcFormName, [string]$srcFormXml) {
  4078. if (-not (Test-Path -LiteralPath $extFormXml) -or -not (Test-Path -LiteralPath $srcFormXml)) { return }
  4079. $eText = [System.IO.File]::ReadAllText($extFormXml)
  4080. $eForm = Get-XmlElementAt $eText ([regex]::Match($eText, '<Form[\s>]').Index)
  4081. if (-not $eForm) { return }
  4082. $base = Get-XmlChild $eText $eForm 'BaseForm'
  4083. if (-not $base) { return }
  4084. $hasMain = (Get-XmlOuter $eText $base) -match '<MainAttribute>true</MainAttribute>'
  4085. $sText = Borrow-Form $typeName $srcObjName $srcFormName -BorrowMainAttr:$hasMain -RenderOnly
  4086. $sForm = Get-XmlElementAt $sText ([regex]::Match($sText, '<Form[\s>]').Index)
  4087. $sBase = if ($sForm) { Get-XmlChild $sText $sForm 'BaseForm' } else { $null }
  4088. if (-not $sBase) { return }
  4089. $old = Get-FormFlatMap $eText $base
  4090. $new = Get-FormFlatMap $sText $sBase
  4091. $mine = Get-FormFlatMap $eText $eForm
  4092. $added = @($new.Keys | Where-Object { -not $old.ContainsKey($_) } | Sort-Object)
  4093. $removed = @($old.Keys | Where-Object { -not $new.ContainsKey($_) } | Sort-Object)
  4094. $changed = @($old.Keys | Where-Object { $new.ContainsKey($_) -and $old[$_] -cne $new[$_] } | Sort-Object)
  4095. if ($added.Count + $removed.Count + $changed.Count -eq 0) { return }
  4096. $row.Status = 'FORM CHANGED IN SOURCE'
  4097. $fmt = { param($a) $s = ($a | Select-Object -First 5) -join ', '; if ($a.Count -gt 5) { $s += ", … ($($a.Count))" }; $s }
  4098. if ($added.Count) { Add-ActNote $row "added in the source: $(& $fmt $added)" $false }
  4099. if ($removed.Count) { Add-ActNote $row "removed in the source: $(& $fmt $removed)" $false }
  4100. if ($changed.Count) { Add-ActNote $row "changed in the source: $(& $fmt $changed)" $false }
  4101. foreach ($k in ($changed + $removed)) {
  4102. if (-not $mine.ContainsKey($k) -or $mine[$k] -ceq $old[$k]) { continue }
  4103. 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 }
  4104. else { Add-ActNote $row "conflict: $k is edited by the extension and removed in the source — at runtime the extension edit is lost" $false }
  4105. }
  4106. Add-ActNote $row "Form.xml is kept as is: the platform merges the source changes at runtime" $false
  4107. }
  4108. # Заимствованная форма объекта: связь с формой источника и сравнение содержимого
  4109. function Actualize-BorrowedForm($objCtx, [string]$typeName, [string]$objName, [string]$formName, [string]$srcObjName) {
  4110. $dirName = $childTypeDirMap[$typeName]
  4111. $row = New-ActRow "$typeName.$objName.Form.$formName"
  4112. $metaFile = Join-Path (Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Forms") "$formName.xml"
  4113. if (-not (Test-Path -LiteralPath $metaFile)) {
  4114. $row.Status = 'NOT FOUND'
  4115. 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
  4116. return
  4117. }
  4118. $mText = [System.IO.File]::ReadAllText($metaFile)
  4119. $mRoot = Get-MdRoot $mText
  4120. if (-not $mRoot -or -not (Test-ElementAdopted $mText $mRoot)) { $script:actRows.Remove($row) | Out-Null; return }
  4121. $srcFormsDir = Join-Path (Join-Path (Join-Path $cfgDir $dirName) $srcObjName) "Forms"
  4122. $id = Resolve-FileIdentity $srcFormsDir $formName (Get-ElementLink $mText $mRoot)
  4123. Set-IdentityStatus $row $id $formName
  4124. if ($id.Kind -eq 'Replaced' -or $id.Kind -eq 'Missing') { return }
  4125. $srcFormName = $id.Src.Name
  4126. if ($id.Kind -eq 'NoLink') {
  4127. $mCtx = @{ Text = $mText; Edits = (New-Object System.Collections.Generic.List[object]); Eol = (Get-TextEol $mText) }
  4128. Add-MissingLink $mCtx $row $mRoot $id.Src.Uuid
  4129. if ($mCtx.Edits.Count -gt 0) {
  4130. $style = Detect-XmlStyle $metaFile
  4131. [System.IO.File]::WriteAllText($metaFile, (Apply-TextEdits $mText $mCtx.Edits), (Get-StyleEncoding $style))
  4132. }
  4133. }
  4134. $extFormXml = Join-Path (Join-Path (Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Forms") $formName) "Ext/Form.xml"
  4135. $srcFormXml = Join-Path (Join-Path $srcFormsDir $srcFormName) "Ext/Form.xml"
  4136. if ($id.Kind -eq 'Renamed') {
  4137. $row.Status = 'RENAMED'
  4138. $fDir = Split-Path $metaFile -Parent
  4139. if ((Test-EditAllowed) -and ($formName -ine $srcFormName) -and (Test-Path -LiteralPath (Join-Path $fDir "$srcFormName.xml"))) {
  4140. Add-ActNote $row "cannot rename: form $srcFormName already exists in the extension" $false
  4141. } elseif (Test-EditAllowed) {
  4142. $t = [System.IO.File]::ReadAllText($metaFile)
  4143. $t = [regex]::Replace($t, '(<Name>)' + [regex]::Escape($formName) + '(</Name>)', '${1}' + $srcFormName.Replace('$', '$$') + '${2}', 1)
  4144. [System.IO.File]::WriteAllText($metaFile, $t, (Get-StyleEncoding (Detect-XmlStyle $metaFile)))
  4145. Move-PathViaTemp $metaFile (Join-Path $fDir "$srcFormName.xml")
  4146. if (Test-Path -LiteralPath (Join-Path $fDir $formName)) { Move-PathViaTemp (Join-Path $fDir $formName) (Join-Path $fDir $srcFormName) }
  4147. $extFormXml = Join-Path (Join-Path $fDir $srcFormName) "Ext/Form.xml"
  4148. # Регистрация формы в ChildObjects владельца — правкой его текста
  4149. $reg = [regex]::Match($objCtx.Text, '<Form>' + [regex]::Escape($formName) + '</Form>')
  4150. if ($reg.Success) { $objCtx.Edits.Add(@{ Start = $reg.Index; End = $reg.Index + $reg.Length; Text = "<Form>$srcFormName</Form>" }) }
  4151. Add-ActNote $row "renamed: $formName -> $srcFormName" $true
  4152. Add-MentionsNote $row $formName $srcFormName
  4153. # Ссылки Catalog.X.Form.Old в XML расширения — после записи файла владельца (его текст ещё правится)
  4154. $objCtx.FormRenames[$formName] = $srcFormName
  4155. $script:formRenamed["$typeName.$objName.$formName"] = $srcFormName
  4156. } else {
  4157. Add-ActNote $row "renamed in the source: $formName -> $srcFormName" $false
  4158. }
  4159. }
  4160. Compare-BorrowedForm $row $extFormXml $typeName $srcObjName $srcFormName $srcFormXml
  4161. }
  4162. # Заимствованные подобъекты одного уровня (реквизиты, ТЧ, измерения…) против источника.
  4163. # $only — @{ Kind; Name } (один подобъект) или $null (все); $colOnly — одна колонка ТЧ из $only.
  4164. # $refPrefix — путь элемента в ссылках MDObjectRef (Catalog.X / Catalog.X.TabularSection.ТЧ) по именам, какие
  4165. # будут в расширении: по нему переименованный подобъект ищется в XML расширения.
  4166. function Sync-AdoptedChildren($ctx, $extParent, [string]$srcText, $srcParent, [string]$pathPrefix, [string]$formPrefix, $only, $colOnly, $renames, [string]$refPrefix) {
  4167. $text = $ctx.Text
  4168. $co = Get-XmlChild $text $extParent 'ChildObjects'
  4169. # Связи заимствованных подобъектов этого уровня: одна связь у двух — дубль (замер М15)
  4170. $linkCount = @{}
  4171. foreach ($c in (Get-XmlChildren $text $co)) {
  4172. if (-not (Get-XmlChild $text $c 'Properties') -or -not (Test-ElementAdopted $text $c)) { continue }
  4173. $l = Get-ElementLink $text $c
  4174. if ($l) { $k = "$($c.Local)|$($l.ToLowerInvariant())"; $linkCount[$k] = 1 + [int]$linkCount[$k] }
  4175. }
  4176. foreach ($c in (Get-XmlChildren $text $co)) {
  4177. # Значения перечисления заимствуются вместе с формой (параметры выбора) — сверяются так же
  4178. if (-not ($script:childObjectKinds -ccontains $c.Local -or $c.Local -ceq 'TabularSection' -or $c.Local -ceq 'EnumValue')) { continue }
  4179. if (-not (Test-ElementAdopted $text $c)) {
  4180. # Собственный подобъект, одноимённый (без учёта регистра) с подобъектом источника того же вида:
  4181. # платформа не обновит базу («Уже существует объект с именем …», замер М14). Переименовать своё —
  4182. # решение человека: у него данные
  4183. if (-not $only) {
  4184. $own = Get-MdElementName $text $c
  4185. foreach ($sc in (Get-XmlChildren $srcText (Get-XmlChild $srcText $srcParent 'ChildObjects'))) {
  4186. if ($sc.Local -cne $c.Local) { continue }
  4187. $sn = Get-MdElementName $srcText $sc
  4188. if ($sn -ine $own) { continue }
  4189. $cr = New-ActRow "$pathPrefix.$($c.Local).$own"
  4190. $cr.Status = 'NAME CONFLICT'
  4191. 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
  4192. break
  4193. }
  4194. }
  4195. continue
  4196. }
  4197. $name = Get-MdElementName $text $c
  4198. if ($only -and -not ($c.Local -ceq $only.Kind -and $name -ceq $only.Name)) { continue }
  4199. $isTs = $c.Local -ceq 'TabularSection'
  4200. # ТЧ ради одной колонки в отчёт сама не идёт — только если её нет в источнике
  4201. $inScope = -not ($isTs -and $colOnly)
  4202. $cLink = Get-ElementLink $text $c
  4203. if ($cLink -and $linkCount["$($c.Local)|$($cLink.ToLowerInvariant())"] -gt 1) {
  4204. $row = New-ActRow "$pathPrefix.$($c.Local).$name"
  4205. $row.Status = 'DUPLICATE LINK'
  4206. 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
  4207. continue
  4208. }
  4209. $id = Resolve-ChildIdentity $srcText $srcParent $c.Local $name $cLink
  4210. $row = $null
  4211. if ($inScope -or $id.Kind -eq 'Replaced' -or $id.Kind -eq 'Missing') {
  4212. $row = New-ActRow "$pathPrefix.$($c.Local).$name"
  4213. Set-IdentityStatus $row $id $name
  4214. }
  4215. if ($id.Kind -eq 'Replaced' -or $id.Kind -eq 'Missing') { continue }
  4216. if ($inScope) {
  4217. if ($id.Kind -eq 'NoLink') { Add-MissingLink $ctx $row $c $id.Src.Uuid }
  4218. if ($id.Kind -eq 'Renamed') {
  4219. $row.Status = 'RENAMED'
  4220. $props = Get-XmlChild $text $c 'Properties'
  4221. $nEl = Get-XmlChild $text $props 'Name'
  4222. $newName = $id.Src.Name
  4223. $ok = Test-EditAllowed
  4224. if ($ok) {
  4225. $ctx.Edits.Add(@{ Start = $nEl.Start; End = $nEl.End; Text = "<Name>$newName</Name>" })
  4226. # Старое имя в источнике занято другим подобъектом того же вида (тёзка, обмен именами)?
  4227. $taken = ''
  4228. foreach ($sc in (Get-XmlChildren $srcText (Get-XmlChild $srcText $srcParent 'ChildObjects'))) {
  4229. if ($sc.Local -ceq $c.Local -and (Get-MdElementName $srcText $sc) -ceq $name) { $taken = "another $($c.Local) $name of this object"; break }
  4230. }
  4231. $renames.Add(@{ Prefix = $formPrefix; Old = $name; New = $newName; Row = $row; RefPath = "$refPrefix.$($c.Local)"; TakenBy = $taken })
  4232. $script:subRenamed["$pathPrefix.$($c.Local).$name"] = $newName
  4233. }
  4234. Add-ActNote $row $(if ($ok) { "renamed: $name -> $newName" } else { "renamed in the source: $name -> $newName" }) $ok
  4235. }
  4236. Sync-AdoptedProperties $ctx $row $c $srcText $id.Src.El
  4237. }
  4238. if ($isTs) {
  4239. $nested = if ($colOnly) { @{ Kind = 'Attribute'; Name = $colOnly } } else { $null }
  4240. # Пути колонок в формах — по имени ТЧ, какое будет в расширении: новое, если ТЧ переименована здесь же
  4241. $tsPathName = if ($inScope -and $id.Kind -eq 'Renamed' -and (Test-EditAllowed)) { $id.Src.Name } else { $name }
  4242. Sync-AdoptedChildren $ctx $c $srcText $id.Src.El "$pathPrefix.TabularSection.$name" "$formPrefix.$tsPathName" $nested $null $renames "$refPrefix.TabularSection.$tsPathName"
  4243. }
  4244. }
  4245. }
  4246. # UUID заимствованных подобъектов объекта (реквизиты, ТЧ и их колонки, значения перечисления…)
  4247. function Get-AdoptedChildLinks([string]$text, $el) {
  4248. $res = @()
  4249. foreach ($c in (Get-XmlChildren $text (Get-XmlChild $text $el 'ChildObjects'))) {
  4250. if (-not (Get-XmlChild $text $c 'Properties')) { continue }
  4251. if (Test-ElementAdopted $text $c) {
  4252. $l = Get-ElementLink $text $c
  4253. if ($l) { $res += $l.ToLowerInvariant() }
  4254. }
  4255. $res += @(Get-AdoptedChildLinks $text $c)
  4256. }
  4257. return $res
  4258. }
  4259. # Связи у объекта нет — по имени нельзя отличить переименование с тёзкой от того же объекта. Подсказка —
  4260. # заимствованные подобъекты: их ECO указывают, в каком объекте источника они теперь (замер М14: по имени
  4261. # расширение привязалось к тёзке, а данные своих реквизитов остались у переименованного объекта).
  4262. function Resolve-IdentityByChildren($id, [string]$srcDir, [string]$text, $root, $row) {
  4263. $links = @(Get-AdoptedChildLinks $text $root | Select-Object -Unique)
  4264. if ($links.Count -eq 0) {
  4265. 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 }
  4266. return $id
  4267. }
  4268. # Частый случай — подобъекты там же, в файле с этим именем: он один и читается без индекса каталога
  4269. if ($id.Kind -eq 'NoLink') {
  4270. $ft = [System.IO.File]::ReadAllText($id.Src.File).ToLowerInvariant()
  4271. foreach ($u in $links) { if ($ft.Contains("uuid=`"$u`"")) { return $id } }
  4272. }
  4273. $idx = Get-SourceChildUuidIndex $srcDir
  4274. $files = @($links | ForEach-Object { $idx[$_] } | Where-Object { $_ } | Select-Object -Unique)
  4275. # Каталог один — сравниваем по имени файла (пути бывают в короткой и длинной форме)
  4276. $own = if ($id.Src) { [System.IO.Path]::GetFileName($id.Src.File) } else { '' }
  4277. if ($id.Kind -eq 'NoLink' -and (@($files | ForEach-Object { [System.IO.Path]::GetFileName($_) }) -contains $own)) { return $id }
  4278. foreach ($f in $files) {
  4279. if ($own -and [System.IO.Path]::GetFileName($f) -eq $own) { continue }
  4280. $h = Read-SourceHead $f
  4281. 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
  4282. return @{ Kind = 'Renamed'; Src = $h }
  4283. }
  4284. return $id
  4285. }
  4286. # UUID подобъектов источника → файл объекта; по каталогу вида один раз за запуск (объектов без связи
  4287. # бывает много — выгрузка без ECO целиком, ПР #138)
  4288. $script:srcChildUuidIndex = @{}
  4289. function Get-SourceChildUuidIndex([string]$dir) {
  4290. if ($script:srcChildUuidIndex.ContainsKey($dir)) { return $script:srcChildUuidIndex[$dir] }
  4291. $idx = @{}
  4292. if (Test-Path -LiteralPath $dir) {
  4293. foreach ($f in (Get-ChildItem -LiteralPath $dir -Filter '*.xml' -File)) {
  4294. if ($f.Extension -ne '.xml') { continue }
  4295. foreach ($m in [regex]::Matches([System.IO.File]::ReadAllText($f.FullName), '\buuid="([^"]+)"')) {
  4296. $u = $m.Groups[1].Value.ToLowerInvariant()
  4297. if (-not $idx.ContainsKey($u)) { $idx[$u] = $f.FullName }
  4298. }
  4299. }
  4300. }
  4301. $script:srcChildUuidIndex[$dir] = $idx
  4302. return $idx
  4303. }
  4304. # Один заимствованный объект (с подобъектами и формами — по области): возвращает итоговое имя
  4305. function Actualize-BorrowedObject([string]$typeName, [string]$objName, $scope) {
  4306. $dirName = $childTypeDirMap[$typeName]
  4307. $objFile = Join-Path (Join-Path $extDir $dirName) "$objName.xml"
  4308. $text = [System.IO.File]::ReadAllText($objFile)
  4309. $root = Get-MdRoot $text
  4310. if (-not $root -or -not (Test-ElementAdopted $text $root)) {
  4311. Info "${typeName}.${objName}: own object of the extension — nothing to actualize"
  4312. return $objName
  4313. }
  4314. $ctx = @{ Text = $text; Edits = (New-Object System.Collections.Generic.List[object]); Eol = (Get-TextEol $text); Shells = (New-Object System.Collections.Generic.List[object]); FormRenames = @{} }
  4315. # На временном имени (обмен именами) объект показывается под прежним
  4316. $shown = $objName
  4317. foreach ($sw in $script:swapPending) { if ($sw.TypeName -eq $typeName -and $sw.Tmp -ceq $objName) { $shown = $sw.Shown } }
  4318. $row = New-ActRow "$typeName.$shown"
  4319. $objLink = Get-ElementLink $text $root
  4320. # Два заимствованных объекта связаны с одним объектом источника: платформа не грузит расширение
  4321. # («Не найден объект …», замер М15). Какой лишний — решает человек: у обоих могут быть данные
  4322. if ($objLink) {
  4323. # Индекс — по состоянию до правок; за запуск имена меняются (обмен через временное имя), поэтому
  4324. # двойник подтверждается текущей связью в его файле
  4325. $twins = @((Get-ExtLinkIndex $typeName)[$objLink.ToLowerInvariant()] | Where-Object {
  4326. # Имена в 1С без учёта регистра: «goods» в ChildObjects и «Goods» в файле — один объект
  4327. if ($_ -ieq $objName -or -not (Test-ObjectBorrowed $typeName $_)) { return $false }
  4328. $tt = [System.IO.File]::ReadAllText((Join-Path (Join-Path $extDir $dirName) "$_.xml"))
  4329. $tl = Get-ElementLink $tt (Get-MdRoot $tt)
  4330. return [bool]($tl -and $tl.ToLowerInvariant() -eq $objLink.ToLowerInvariant())
  4331. })
  4332. if ($twins.Count -gt 0) {
  4333. $row.Status = 'DUPLICATE LINK'
  4334. 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
  4335. $script:actBlocked["$typeName.$objName"] = $true
  4336. return $objName
  4337. }
  4338. }
  4339. $id = Resolve-FileIdentity (Join-Path $cfgDir $dirName) $objName $objLink
  4340. if (-not $objLink) { $id = Resolve-IdentityByChildren $id (Join-Path $cfgDir $dirName) $text $root $row }
  4341. Set-IdentityStatus $row $id $objName
  4342. if ($id.Kind -eq 'Replaced' -or $id.Kind -eq 'Missing') { $script:actBlocked["$typeName.$objName"] = $true; return $objName }
  4343. $srcText = [System.IO.File]::ReadAllText($id.Src.File)
  4344. $srcRoot = Get-MdRoot $srcText
  4345. $srcName = $id.Src.Name
  4346. if (-not $objLink -and $id.Src) { Add-MissingLink $ctx $row $root $id.Src.Uuid }
  4347. if ($scope.Kind -eq 'Object') {
  4348. Sync-AdoptedProperties $ctx $row $root $srcText $srcRoot
  4349. }
  4350. $renames = New-Object System.Collections.Generic.List[object]
  4351. if ($scope.Kind -eq 'Object') {
  4352. Sync-AdoptedChildren $ctx $root $srcText $srcRoot "$typeName.$shown" '' $null $null $renames "$typeName.$objName"
  4353. } elseif ($scope.Kind -eq 'Sub') {
  4354. Sync-AdoptedChildren $ctx $root $srcText $srcRoot "$typeName.$shown" '' @{ Kind = $scope.SubKind; Name = $scope.SubName } $scope.ColName $renames "$typeName.$objName"
  4355. }
  4356. if ($typeName -eq 'CommonForm' -and $scope.Kind -eq 'Object') {
  4357. 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")
  4358. } elseif ($scope.Kind -ne 'Sub') {
  4359. foreach ($fm in [regex]::Matches($text, '<Form>([^<]+)</Form>')) {
  4360. $fn = $fm.Groups[1].Value
  4361. if ($scope.Kind -eq 'Form' -and $fn -cne $scope.FormName) { continue }
  4362. Actualize-BorrowedForm $ctx $typeName $objName $fn $srcName
  4363. }
  4364. }
  4365. # Строка самого объекта при повторе по подобъекту или форме — только если с объектом что-то произошло
  4366. $row.Optional = ($scope.Kind -ne 'Object')
  4367. if ($ctx.Edits.Count -gt 0) {
  4368. $style = Detect-XmlStyle $objFile
  4369. [System.IO.File]::WriteAllText($objFile, (Apply-TextEdits $text $ctx.Edits), (Get-StyleEncoding $style))
  4370. }
  4371. # Переименованные формы — ссылки на них (основная форма объекта, команды, подсистемы…), одним проходом
  4372. if ($ctx.FormRenames.Count -gt 0) { Rename-SubObjectRefs "$typeName.$objName.Form" $ctx.FormRenames | Out-Null }
  4373. foreach ($sh in $ctx.Shells) {
  4374. $refs = if ($sh.Ref) { @($sh.Ref) } else { @(Collect-ReferenceTypes @($sh.Xml)) }
  4375. foreach ($rt in $refs) {
  4376. if (Test-ObjectBorrowed $rt.TypeName $rt.ObjName) { continue }
  4377. Borrow-ObjectShell $rt.TypeName $rt.ObjName
  4378. if (Test-ObjectBorrowed $rt.TypeName $rt.ObjName) { Add-ActNote $sh.Row "borrowed as a shell: $($rt.TypeName).$($rt.ObjName)" $true }
  4379. }
  4380. }
  4381. # Переименованные подобъекты — пути к данным в формах этого объекта
  4382. # Группы по уровню (путь формы, путь ссылки) — в порядке появления: ТЧ переименовывается раньше
  4383. # своих колонок, их пути уже идут по новому имени ТЧ
  4384. $formsDir = Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Forms"
  4385. $pathGroups = [ordered]@{}; $refGroups = [ordered]@{}
  4386. foreach ($rn in $renames) {
  4387. if (-not $pathGroups.Contains($rn.Prefix)) { $pathGroups[$rn.Prefix] = New-Object System.Collections.Hashtable ([System.StringComparer]::Ordinal) }
  4388. if (-not $refGroups.Contains($rn.RefPath)) { $refGroups[$rn.RefPath] = New-Object System.Collections.Hashtable ([System.StringComparer]::Ordinal) }
  4389. $pathGroups[$rn.Prefix][$rn.Old] = $rn.New
  4390. $refGroups[$rn.RefPath][$rn.Old] = $rn.New
  4391. }
  4392. $pathCounts = @{}; $refCounts = @{}
  4393. foreach ($pfx in $pathGroups.Keys) {
  4394. if (-not (Test-Path -LiteralPath $formsDir)) { break }
  4395. foreach ($fx in (Get-ChildItem -LiteralPath $formsDir -Recurse -File -Filter 'Form.xml')) {
  4396. $c = Rename-FormDataPaths $fx.FullName $pfx $pathGroups[$pfx]
  4397. foreach ($k in $c.Keys) { $pathCounts["$pfx|$k"] = $c[$k] + [int]$pathCounts["$pfx|$k"] }
  4398. }
  4399. }
  4400. foreach ($rp in $refGroups.Keys) {
  4401. $c = Rename-SubObjectRefs $rp $refGroups[$rp]
  4402. foreach ($k in $c.Keys) { $refCounts["$rp|$k"] = $c[$k] }
  4403. }
  4404. foreach ($rn in $renames) {
  4405. $cnt = [int]$pathCounts["$($rn.Prefix)|$($rn.Old)"]
  4406. if ($cnt -gt 0) { Add-ActNote $rn.Row "form data paths updated: $cnt" $true }
  4407. $refCnt = [int]$refCounts["$($rn.RefPath)|$($rn.Old)"]
  4408. if ($refCnt -gt 0) { Add-ActNote $rn.Row "references in the extension XML updated: $refCnt" $true }
  4409. Add-MentionsNote $rn.Row $rn.Old $rn.New $rn.TakenBy
  4410. }
  4411. if ($id.Kind -eq 'Renamed') {
  4412. $row.Status = 'RENAMED'
  4413. if (Test-EditAllowed) {
  4414. if (Rename-BorrowedObject $typeName $objName $srcName $row) {
  4415. Add-ActNote $row "renamed: $shown -> $srcName (files, ChildObjects, type references in the extension XML)" $true
  4416. $oldSrc = Join-Path (Join-Path $cfgDir $dirName) "$shown.xml"
  4417. $taken = if ((Test-Path -LiteralPath $oldSrc) -and (Read-SourceHead $oldSrc).Name -ceq $shown) { "$typeName.$shown" } else { '' }
  4418. Add-MentionsNote $row $shown $srcName $taken
  4419. return $srcName
  4420. }
  4421. } else {
  4422. Add-ActNote $row "renamed in the source: $objName -> $srcName" $false
  4423. }
  4424. }
  4425. return $objName
  4426. }
  4427. # Отчёт актуализации: строка на элемент, отложенные правки — с пометкой
  4428. $script:actUnresolved = @()
  4429. $script:objRenamed = @{}
  4430. $script:subRenamed = @{}
  4431. # Объекты, оставленные без изменений до решения человека (подмена, нет в источнике, дубль связи)
  4432. $script:actBlocked = @{}
  4433. $script:formRenamed = @{}
  4434. function Write-ActReport {
  4435. Resolve-PendingMentions
  4436. if ($script:actRows.Count -eq 0) { return 0 }
  4437. Write-Host ""
  4438. Write-Host $(if ($script:actMode -eq 'Check') { "=== Actualization check ===" } else { "=== Actualization ===" })
  4439. $notUpToDate = 0
  4440. foreach ($r in $script:actRows) {
  4441. if ($r.Optional -and $r.Notes.Count -eq 0 -and -not $r.Status) { continue }
  4442. $changes = @($r.Notes | Where-Object { $_.Applied })
  4443. $counted = @($r.Notes | Where-Object { -not $_.Info })
  4444. $st = $r.Status
  4445. if (-not $st) {
  4446. if ($counted.Count -eq 0) { $st = 'UP-TO-DATE' }
  4447. elseif ($script:actMode -eq 'Check') { $st = 'OUTDATED' }
  4448. elseif ($changes.Count -gt 0) { $st = 'ACTUALIZED' }
  4449. else { $st = 'OUTDATED' }
  4450. }
  4451. if ($st -ne 'UP-TO-DATE') { $notUpToDate++ }
  4452. 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()))" }
  4453. Write-Host "[$st] $($r.Path)"
  4454. foreach ($n in $r.Notes) { Write-Host " - $($n.Text)" }
  4455. }
  4456. return $notUpToDate
  4457. }
  4458. # Все заимствованные объекты расширения (область -Check / -Actualize без -Object)
  4459. function Get-AllAdoptedItems {
  4460. $res = @()
  4461. foreach ($child in $script:childObjsEl.ChildNodes) {
  4462. if ($child.NodeType -ne 'Element') { continue }
  4463. $t = $child.LocalName; $n = $child.InnerText.Trim()
  4464. if (-not $childTypeDirMap.ContainsKey($t) -or $t -eq 'Language') { continue }
  4465. $f = Join-Path (Join-Path $extDir $childTypeDirMap[$t]) "$n.xml"
  4466. if (-not (Test-Path -LiteralPath $f)) { continue }
  4467. $head = [System.IO.File]::ReadAllText($f)
  4468. if ($head -match '<ObjectBelonging>Adopted</ObjectBelonging>') { $res += "$t.$n" }
  4469. }
  4470. return $res
  4471. }
  4472. # Подобъект из -Object уже заимствован? (тогда его актуализируем, а не заимствуем)
  4473. function Test-SubBorrowed($pi) {
  4474. if (-not (Test-ObjectBorrowed $pi.TypeName $pi.ObjName)) { return $false }
  4475. $objFile = Join-Path (Join-Path $extDir $pi.DirName) "$($pi.ObjName).xml"
  4476. $text = [System.IO.File]::ReadAllText($objFile)
  4477. $root = Get-MdRoot $text
  4478. $co = Get-XmlChild $text $root 'ChildObjects'
  4479. foreach ($c in (Get-XmlChildren $text $co)) {
  4480. if ($c.Local -cne $pi.SubKind -or (Get-MdElementName $text $c) -cne $pi.SubName) { continue }
  4481. if (-not $pi.ColName) { return $true }
  4482. foreach ($cc in (Get-XmlChildren $text (Get-XmlChild $text $c 'ChildObjects'))) {
  4483. if ($cc.Local -ceq 'Attribute' -and (Get-MdElementName $text $cc) -ceq $pi.ColName) { return $true }
  4484. }
  4485. return $false
  4486. }
  4487. return $false
  4488. }
  4489. # В заимствованной форме нет правок расширения: основная часть совпадает с BaseForm (так её и создаёт
  4490. # заимствование). Тогда пересобрать её — например, с основным реквизитом — нечего терять.
  4491. function Test-FormUnedited([string]$formXml) {
  4492. if (-not (Test-Path -LiteralPath $formXml)) { return $false }
  4493. $text = [System.IO.File]::ReadAllText($formXml)
  4494. $form = Get-XmlElementAt $text ([regex]::Match($text, '<Form[\s>]').Index)
  4495. if (-not $form) { return $false }
  4496. $base = Get-XmlChild $text $form 'BaseForm'
  4497. if (-not $base) { return $false }
  4498. $main = New-Object System.Text.StringBuilder
  4499. foreach ($c in (Get-XmlChildren $text $form)) { if ($c.Local -cne 'BaseForm') { $main.Append((Get-NormXml (Get-XmlOuter $text $c))) | Out-Null } }
  4500. $orig = New-Object System.Text.StringBuilder
  4501. foreach ($c in (Get-XmlChildren $text $base)) { $orig.Append((Get-NormXml (Get-XmlOuter $text $c))) | Out-Null }
  4502. return ($main.ToString() -ceq $orig.ToString())
  4503. }
  4504. function Test-FormBorrowed($pi) {
  4505. if ($pi.IsCommonForm) { return (Test-ObjectBorrowed $pi.TypeName $pi.ObjName) }
  4506. $f = Join-Path (Join-Path (Join-Path (Join-Path $extDir $pi.DirName) $pi.ObjName) "Forms") "$($pi.FormName).xml"
  4507. return (Test-Path -LiteralPath $f)
  4508. }
  4509. # С -BorrowMainAttribute реквизиты берутся у объекта из типа основного реквизита формы. Если это не
  4510. # владелец формы и его нет в конфигурации-источнике, форма в расширении не загрузится — отказываем
  4511. # до записи, расширение не трогаем.
  4512. if ($BorrowMainAttribute) {
  4513. foreach ($item in $items) {
  4514. $pi = Split-BorrowItem $item
  4515. # Неверный элемент и нет самой формы — об этом скажет основной цикл
  4516. if ($pi.Error -or -not $pi.SrcFormXml -or -not (Test-Path $pi.SrcFormXml)) { continue }
  4517. $pDoc = New-Object System.Xml.XmlDocument
  4518. $pDoc.Load($pi.SrcFormXml)
  4519. if ($pi.IsCommonForm) {
  4520. $pOwner = Resolve-CommonFormOwner $pDoc.DocumentElement
  4521. if (-not $pOwner -or $pOwner.Kind -ne 'Object') { continue }
  4522. } else {
  4523. $pOwner = Resolve-MainAttributeObject $pDoc.DocumentElement $pi.TypeName $pi.ObjName
  4524. if ($pOwner.TypeName -eq $pi.TypeName -and $pOwner.ObjName -eq $pi.ObjName) { continue }
  4525. }
  4526. $pFound = $childTypeDirMap.ContainsKey($pOwner.TypeName) -and
  4527. (Test-Path (Join-Path (Join-Path $cfgDir $childTypeDirMap[$pOwner.TypeName]) "$($pOwner.ObjName).xml"))
  4528. if (-not $pFound) {
  4529. Write-Error "Основной реквизит формы ${item} ссылается на $($pOwner.TypeName).$($pOwner.ObjName), а его нет в конфигурации-источнике — форма в расширении не загрузится. Расширение не изменено"
  4530. exit 1
  4531. }
  4532. }
  4533. }
  4534. # Элементы разобраны и подобъекты найдены в источнике ДО записи: ошибка в любом элементе пакета —
  4535. # расширение не тронуто
  4536. $script:subObjectSources = @{}
  4537. # Элементы, названные именем источника, но заимствованные под прежним, — к имени расширения
  4538. $items = @($items | ForEach-Object { Resolve-ItemByLink $_ })
  4539. foreach ($item in $items) {
  4540. $pi = Split-BorrowItem $item
  4541. if ($pi.Error) {
  4542. Write-Error $pi.Error
  4543. exit 1
  4544. }
  4545. if (-not $pi.SubKind) { continue }
  4546. # Уже заимствованный подобъект актуализируется — его может не быть в источнике под этим именем
  4547. if (Test-SubBorrowed $pi) { continue }
  4548. $subSrc = Resolve-SubObjectSource $pi
  4549. if ($subSrc.Error) {
  4550. Write-Error "$($subSrc.Error). Extension not changed"
  4551. exit 1
  4552. }
  4553. $script:subObjectSources[$item] = $subSrc
  4554. }
  4555. # Повтор по заимствованному и -Actualize — актуализация (с -Actualize без -Object — всё расширение); -Check — отчёт
  4556. $script:actMode = if ($Check) { 'Check' } else { 'Apply' }
  4557. if ($items.Count -eq 0) { $items = @(Get-AllAdoptedItems) }
  4558. if ($Check) {
  4559. foreach ($item in $items) {
  4560. $pi = Split-BorrowItem $item
  4561. if ($pi.SubKind) { $borrowed = Test-SubBorrowed $pi }
  4562. elseif ($pi.FormName) { $borrowed = Test-FormBorrowed $pi }
  4563. else { $borrowed = Test-ObjectBorrowed $pi.TypeName $pi.ObjName }
  4564. if (-not $borrowed) {
  4565. $nb = New-ActRow $item
  4566. $nb.Status = 'NOT BORROWED'
  4567. continue
  4568. }
  4569. if ($pi.SubKind) { Actualize-BorrowedObject $pi.TypeName $pi.ObjName @{ Kind = 'Sub'; SubKind = $pi.SubKind; SubName = $pi.SubName; ColName = $pi.ColName } | Out-Null }
  4570. elseif ($pi.FormName -and -not $pi.IsCommonForm) { Actualize-BorrowedObject $pi.TypeName $pi.ObjName @{ Kind = 'Form'; FormName = $pi.FormName } | Out-Null }
  4571. else { Actualize-BorrowedObject $pi.TypeName $pi.ObjName @{ Kind = 'Object' } | Out-Null }
  4572. }
  4573. $bad = Write-ActReport
  4574. exit $(if ($bad -gt 0) { 1 } else { 0 })
  4575. }
  4576. foreach ($item in $items) {
  4577. $pi = Split-BorrowItem $item
  4578. if ($pi.Error) {
  4579. Write-Error $pi.Error
  4580. exit 1
  4581. }
  4582. # Объект переименован раньше в этом запуске (вслед за источником) — элемент пакета идёт под новым именем
  4583. $origObjName = $pi.ObjName
  4584. $renamedTo = $script:objRenamed["$($pi.TypeName).$($pi.ObjName)"]
  4585. if ($renamedTo) {
  4586. $item = $item -replace ('^([^.]+)\.' + [regex]::Escape($pi.ObjName) + '(?=\.|$)'), ('$1.' + $renamedTo.Replace('$', '$$'))
  4587. $pi = Split-BorrowItem $item
  4588. }
  4589. # То же для подобъекта (и колонки ТЧ), переименованного раньше в этом запуске. Ключ — под тем именем
  4590. # объекта, какое было при переименовании подобъекта: прежним, если объект переименован следом
  4591. if ($pi.SubKind) {
  4592. $subKey = "$($pi.TypeName).$($pi.ObjName).$($pi.SubKind).$($pi.SubName)"
  4593. $oldKey = "$($pi.TypeName).$origObjName.$($pi.SubKind).$($pi.SubName)"
  4594. $subNew = if ($script:subRenamed[$subKey]) { $script:subRenamed[$subKey] } else { $script:subRenamed[$oldKey] }
  4595. $colNew = $null
  4596. if ($pi.ColName) { $colNew = if ($script:subRenamed["$subKey.Attribute.$($pi.ColName)"]) { $script:subRenamed["$subKey.Attribute.$($pi.ColName)"] } else { $script:subRenamed["$oldKey.Attribute.$($pi.ColName)"] } }
  4597. if ($subNew -or $colNew) {
  4598. $item = "$($pi.TypeName).$($pi.ObjName).$($pi.SubKind).$(if ($subNew) { $subNew } else { $pi.SubName })"
  4599. if ($pi.ColName) { $item += ".Attribute.$(if ($colNew) { $colNew } else { $pi.ColName })" }
  4600. $pi = Split-BorrowItem $item
  4601. }
  4602. }
  4603. # И для формы, переименованной раньше в этом запуске (ключ — под именем объекта на момент переименования)
  4604. if ($pi.FormName -and -not $pi.IsCommonForm) {
  4605. $fNew = $script:formRenamed["$($pi.TypeName).$($pi.ObjName).$($pi.FormName)"]
  4606. if (-not $fNew) { $fNew = $script:formRenamed["$($pi.TypeName).$origObjName.$($pi.FormName)"] }
  4607. if ($fNew) {
  4608. $item = "$($pi.TypeName).$($pi.ObjName).Form.$fNew"
  4609. $pi = Split-BorrowItem $item
  4610. }
  4611. }
  4612. $typeName = $pi.TypeName; $objName = $pi.ObjName; $formName = $pi.FormName; $isCommonForm = $pi.IsCommonForm
  4613. $dirName = $childTypeDirMap[$typeName]
  4614. if ($pi.SubKind) {
  4615. if (Test-SubBorrowed $pi) {
  4616. Info "Actualizing ${item}..."
  4617. $objName = Actualize-BorrowedObject $typeName $objName @{ Kind = 'Sub'; SubKind = $pi.SubKind; SubName = $pi.SubName; ColName = $pi.ColName }
  4618. # ТЧ целиком просят под собственные реквизиты — то же предупреждение, что при первом заимствовании
  4619. if ($pi.SubKind -ceq 'TabularSection' -and -not $pi.ColName) {
  4620. if ($script:tsOwnColumnsBlocked -ccontains $typeName) {
  4621. Warn " ${typeName}: own attributes cannot be added to a borrowed tabular section of this kind — the platform rejects them on database update"
  4622. } elseif ($script:tsOwnColumnsFromPlatform.ContainsKey($typeName)) {
  4623. Warn " ${typeName}: own attributes in a borrowed tabular section are accepted only from platform $($script:tsOwnColumnsFromPlatform[$typeName])"
  4624. }
  4625. }
  4626. } else {
  4627. Info "Borrowing ${item}..."
  4628. Borrow-SubObject $pi $script:subObjectSources[$item]
  4629. $borrowedCount++
  4630. }
  4631. } elseif ($formName) {
  4632. # --- Form borrowing ---
  4633. $formExists = Test-FormBorrowed $pi
  4634. $verb = if ($formExists) { "Actualizing" } else { "Borrowing" }
  4635. if ($isCommonForm) { Info "$verb common form ${typeName}.${objName}..." }
  4636. else { Info "$verb form ${typeName}.${objName}.Form.${formName}..." }
  4637. # Auto-borrow parent object if not yet borrowed
  4638. if (-not $isCommonForm) { Ensure-ParentBorrowed $typeName $objName }
  4639. $hasBMA = [bool]$BorrowMainAttribute
  4640. $rebuildForm = $false
  4641. if ($formExists) {
  4642. # Уже заимствованную форму не переписываем: в Form.xml правки расширения
  4643. if ($isCommonForm) { $newName = Actualize-BorrowedObject $typeName $objName @{ Kind = 'Object' } }
  4644. else { $newName = Actualize-BorrowedObject $typeName $objName @{ Kind = 'Form'; FormName = $formName } }
  4645. # Форма (и объект) могли переименоваться вслед за источником — дальше идём под новыми именами
  4646. $newForm = if ($isCommonForm) { $null } else { $script:formRenamed["$typeName.$objName.$formName"] }
  4647. if ($newName -cne $objName -or $newForm) {
  4648. if ($newForm) { $formName = $newForm }
  4649. $item = if ($isCommonForm) { "$typeName.$newName" } else { "$typeName.$newName.Form.$formName" }
  4650. $pi = Split-BorrowItem $item
  4651. $objName = $newName
  4652. }
  4653. if ($hasBMA) {
  4654. $exFormXml = if ($isCommonForm) { Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Ext/Form.xml" }
  4655. else { Join-Path (Join-Path (Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Forms") $formName) "Ext/Form.xml" }
  4656. if ((Test-Path -LiteralPath $exFormXml) -and -not ([System.IO.File]::ReadAllText($exFormXml) -match '<MainAttribute>true</MainAttribute>')) {
  4657. # Форма без основного реквизита: правок расширения нет — пересобираем с ним, есть — не трогаем
  4658. if (Test-FormUnedited $exFormXml) {
  4659. Info " The form has no edits of the extension — rebuilt with its main attribute"
  4660. $rebuildForm = $true
  4661. } else {
  4662. 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"
  4663. }
  4664. }
  4665. }
  4666. }
  4667. if (-not $formExists -or $rebuildForm) {
  4668. $formFiles = Borrow-Form $typeName $objName $formName -BorrowMainAttr:$hasBMA -Rebuild:$rebuildForm
  4669. $script:borrowedFiles += $formFiles
  4670. # Замер на 8.3.26: платформа помечает форму расширенной сразу при заимствовании,
  4671. # даже если элементы не менялись. Флаг живёт в метаданных формы, не у владельца.
  4672. Set-PropertyStateFlag $formFiles[0] "Form" $script:formatVersion
  4673. if (-not $rebuildForm) { $borrowedCount++ }
  4674. }
  4675. # Borrow main attribute if requested
  4676. if ($hasBMA -and $isCommonForm) {
  4677. # У общей формы владельца нет — он выводится из типа основного реквизита
  4678. $cfSrcFormXmlPath = $pi.SrcFormXml
  4679. $cfDoc = New-Object System.Xml.XmlDocument
  4680. $cfDoc.PreserveWhitespace = $true
  4681. $cfDoc.Load($cfSrcFormXmlPath)
  4682. $cfOwner = Resolve-CommonFormOwner $cfDoc.DocumentElement
  4683. if (-not $cfOwner) {
  4684. Info " Основной реквизит общей формы не ссылается на объект — заимствуется только сам реквизит"
  4685. } elseif ($cfOwner.Kind -eq 'Constants') {
  4686. Borrow-FormConstants $cfSrcFormXmlPath $cfOwner.MainName
  4687. } else {
  4688. Borrow-ObjectShell $cfOwner.TypeName $cfOwner.ObjName
  4689. if (Test-ObjectBorrowed $cfOwner.TypeName $cfOwner.ObjName) {
  4690. Borrow-MainAttribute $cfOwner.TypeName $cfOwner.ObjName $null $BorrowMainAttribute $cfSrcFormXmlPath
  4691. }
  4692. }
  4693. } elseif ($hasBMA) {
  4694. # Реквизиты заимствуются у объекта из типа основного реквизита: у формы обработки с
  4695. # DocumentObject.X это X, и его нужно заимствовать — иначе форма не загрузится
  4696. $srcFormXmlPath = $pi.SrcFormXml
  4697. $maObj = @{ TypeName = $typeName; ObjName = $objName }
  4698. if (Test-Path $srcFormXmlPath) {
  4699. $maDoc = New-Object System.Xml.XmlDocument
  4700. $maDoc.PreserveWhitespace = $true
  4701. $maDoc.Load($srcFormXmlPath)
  4702. $maObj = Resolve-MainAttributeObject $maDoc.DocumentElement $typeName $objName
  4703. }
  4704. if ($maObj.TypeName -eq $typeName -and $maObj.ObjName -eq $objName) {
  4705. Borrow-MainAttribute $typeName $objName $formName $BorrowMainAttribute
  4706. } else {
  4707. Info " Основной реквизит формы — $($maObj.TypeName).$($maObj.ObjName): реквизиты заимствуются у него"
  4708. Borrow-ObjectShell $maObj.TypeName $maObj.ObjName
  4709. if (Test-ObjectBorrowed $maObj.TypeName $maObj.ObjName) {
  4710. Borrow-MainAttribute $maObj.TypeName $maObj.ObjName $null $BorrowMainAttribute $srcFormXmlPath
  4711. }
  4712. }
  4713. }
  4714. } else {
  4715. # --- Object borrowing (existing logic) ---
  4716. $targetDir = Join-Path $extDir $dirName
  4717. $targetFile = Join-Path $targetDir "${objName}.xml"
  4718. # Уже заимствованный объект НЕ переписываем: в его XML лежат собственные реквизиты
  4719. # расширения, заимствованные подобъекты и состояния, которые из источника не выводятся.
  4720. # Повторный вызов — законный способ доделать модуль (-Module), а не переиздать заготовку.
  4721. $src = $null
  4722. $isNew = -not (Test-ObjectBorrowed $typeName $objName)
  4723. if (-not $isNew) {
  4724. Info "Actualizing ${typeName}.${objName}..."
  4725. $objName = Actualize-BorrowedObject $typeName $objName @{ Kind = 'Object' }
  4726. $targetFile = Join-Path $targetDir "${objName}.xml"
  4727. } else {
  4728. Info "Borrowing ${typeName}.${objName}..."
  4729. $src = Read-SourceObject $typeName $objName
  4730. Info " Source UUID: $($src.Uuid)"
  4731. $borrowedXml = Build-BorrowedObjectXml $typeName $objName $src.Uuid $src.Properties
  4732. if (-not (Test-Path $targetDir)) {
  4733. New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
  4734. }
  4735. $enc = New-Object System.Text.UTF8Encoding($true)
  4736. [System.IO.File]::WriteAllText($targetFile, $borrowedXml, $enc)
  4737. Info " Created: $targetFile"
  4738. }
  4739. if ($isNew) {
  4740. Add-ToChildObjects $typeName $objName
  4741. # Определяемый тип — с оболочками объектов своего состава, как у Конфигуратора
  4742. if ($src -and $typeName -eq "DefinedType" -and $src.Properties.ContainsKey("__TypeXml")) {
  4743. foreach ($rt in (Collect-ReferenceTypes @($src.Properties["__TypeXml"]))) {
  4744. Borrow-ObjectShell $rt.TypeName $rt.ObjName
  4745. }
  4746. }
  4747. $script:borrowedFiles += $targetFile
  4748. $borrowedCount++
  4749. }
  4750. # У заимствованного раньше модуль создаётся при явном вызове по объекту (-Object): у типа с единственным
  4751. # модулем — всегда, у прочих — по -Module. Массовый -Actualize модулей не добавляет (оболочки остаются без них)
  4752. if (($isNew -or $Module -or $Object) -and -not $script:actBlocked["$typeName.$objName"]) {
  4753. foreach ($kind in (Resolve-ModuleKinds $typeName)) {
  4754. $script:borrowedFiles += (New-BorrowedModuleFile $typeName $objName $kind)
  4755. }
  4756. }
  4757. }
  4758. }
  4759. # --- 14. (хвост) Обмен именами: объект, уведённый на временное имя, получает своё новое имя, даже если
  4760. # сам не был в области запуска — временное имя в расширении не остаётся
  4761. foreach ($sw in $script:swapPending.ToArray()) {
  4762. if ($script:objRenamed.ContainsKey("$($sw.TypeName).$($sw.Tmp)")) { continue }
  4763. Actualize-BorrowedObject $sw.TypeName $sw.Tmp @{ Kind = 'Object' } | Out-Null
  4764. }
  4765. # --- 14a. Основные таблицы динамических списков заимствованных форм — оболочками ---
  4766. # Объект основной таблицы списка обязан быть в расширении («Неверно указана главная таблица
  4767. # динамического списка»), даже если форма принадлежит другому объекту. Для виртуальной таблицы или
  4768. # ТЧ (InformationRegister.Цены.SliceLast) — объект по первым двум сегментам. До шага 14b: оболочке
  4769. # справочника нужны и его владельцы.
  4770. foreach ($dl in $script:dynListForms) {
  4771. if ($dl.MainTable -match '^(\w+)\.(\w+)(?:\.\w+)*$' -and $childTypeDirMap.ContainsKey($Matches[1])) {
  4772. $mtKind = $Matches[1]; $mtName = $Matches[2]
  4773. if (-not (Test-ObjectBorrowed $mtKind $mtName)) {
  4774. Info "Основная таблица динамического списка ${mtKind}.${mtName} — в расширение оболочкой"
  4775. Borrow-ObjectShell $mtKind $mtName
  4776. }
  4777. }
  4778. }
  4779. # --- 14b. Владельцы заимствованных справочников ---
  4780. # Ссылка в <Owners> должна вести на объект, который в расширении есть: иначе платформа падает при
  4781. # загрузке (проверено — access violation, не сообщение об ошибке). Конфигуратор владельца
  4782. # заимствует (эталон Issue66Example7_1: вместе со справочником перенесён и его ПВХ-владелец).
  4783. # Проход общий и повторяется, пока находятся новые: у владельца может быть свой владелец.
  4784. $ownerPass = 0
  4785. while ($true) {
  4786. $ownerPass++
  4787. if ($ownerPass -gt 10) { break }
  4788. $newOwners = @()
  4789. foreach ($shell in (Get-ChildItem -Path $extDir -Filter "*.xml" -Recurse -File)) {
  4790. $shellText = [System.IO.File]::ReadAllText($shell.FullName)
  4791. if ($shellText -notmatch '<Owners>') { continue }
  4792. foreach ($om in [regex]::Matches($shellText, '<xr:Item[^>]*>(\w+)\.(\w+)</xr:Item>')) {
  4793. $oType = $om.Groups[1].Value; $oName = $om.Groups[2].Value
  4794. if (-not $childTypeDirMap.ContainsKey($oType)) { continue }
  4795. if (Test-ObjectBorrowed $oType $oName) { continue }
  4796. if ($newOwners | Where-Object { $_.T -eq $oType -and $_.N -eq $oName }) { continue }
  4797. $newOwners += @{ T = $oType; N = $oName }
  4798. }
  4799. }
  4800. if ($newOwners.Count -eq 0) { break }
  4801. foreach ($ow in $newOwners) {
  4802. $owSrcFile = Join-Path (Join-Path $cfgDir $childTypeDirMap[$ow.T]) "$($ow.N).xml"
  4803. if (-not (Test-Path $owSrcFile)) {
  4804. Warn " Владелец $($ow.T).$($ow.N) не найден в источнике — ссылка останется висячей"
  4805. continue
  4806. }
  4807. $owSrc = Read-SourceObject $ow.T $ow.N
  4808. $owXml = Build-BorrowedObjectXml $ow.T $ow.N $owSrc.Uuid $owSrc.Properties
  4809. $owDir = Join-Path $extDir $childTypeDirMap[$ow.T]
  4810. if (-not (Test-Path $owDir)) { New-Item -ItemType Directory -Path $owDir -Force | Out-Null }
  4811. $owFile = Join-Path $owDir "$($ow.N).xml"
  4812. $owEnc = New-Object System.Text.UTF8Encoding($true)
  4813. [System.IO.File]::WriteAllText($owFile, $owXml, $owEnc)
  4814. Add-ToChildObjects $ow.T $ow.N
  4815. $script:borrowedFiles += $owFile
  4816. Info " Auto-borrowed owner: $($ow.T).$($ow.N)"
  4817. }
  4818. }
  4819. # --- 14c. Тильда у путей полей динамических списков заимствованных форм ---
  4820. # Запрос списка компилируется в контексте расширения, и что-то из него, чего там нет, делает
  4821. # невалидными все поля списка («Неверный путь к данным»). Конфигуратор такие пути пишет с тильдой —
  4822. # платформа разрешает их после наложения на основную конфигурацию. Тильду ставим, только если
  4823. # список не разрешится в расширении (Get-DynListQueryUnresolved): лишняя тильда безвредна, но первая
  4824. # выгрузка из базы её снимет — шум в истории файлов. У списка без ручного запроса поля — пути формы
  4825. # по основной таблице: проверяем их как запрос «ВЫБРАТЬ Т.Поле… ИЗ <таблица> КАК Т». Решаем здесь,
  4826. # по итоговому составу расширения (после 14a и 14b): реквизиты заимствуются уже после формы, в пакете —
  4827. # и соседними формами. Помечаются привязки, которые платформа проверяет при загрузке: *DataPath
  4828. # элементов (DataPath, FooterDataPath, RowPictureDataPath…) и <Field> в UseAlways; в форме и в
  4829. # BaseForm. Сам список (DataPath без поля) — как есть; пути отбора и оформления (dcsset:/dcscor:)
  4830. # не проверяются.
  4831. foreach ($dl in $script:dynListForms) {
  4832. $dlText = [System.IO.File]::ReadAllText($dl.File, [System.Text.Encoding]::UTF8)
  4833. if ($dl.Manual) {
  4834. $dlQuery = $dl.Query
  4835. } else {
  4836. if (-not $dl.MainTable) { continue }
  4837. $dlPathPat = '<(?:\w*DataPath|Field)>~?' + [regex]::Escape($dl.MainName) + '\.([^<]+)<'
  4838. $dlFields = @([regex]::Matches($dlText, $dlPathPat) | ForEach-Object { "Т." + $_.Groups[1].Value } | Select-Object -Unique)
  4839. if ($dlFields.Count -eq 0) { continue }
  4840. $dlQuery = "ВЫБРАТЬ " + ($dlFields -join ", ") + " ИЗ $($dl.MainTable) КАК Т"
  4841. }
  4842. $dlUnresolved = @(Get-DynListQueryUnresolved $dlQuery)
  4843. if ($dlUnresolved.Count -eq 0) { continue }
  4844. $dlFieldPat = '(<(?:\w*DataPath|Field)>)(?=' + [regex]::Escape($dl.MainName) + '\.)'
  4845. $script:dlCount = 0
  4846. $dlText = [regex]::Replace($dlText, $dlFieldPat, { param($m) $script:dlCount++; $m.Groups[1].Value + '~' })
  4847. if ($script:dlCount -gt 0) {
  4848. [System.IO.File]::WriteAllText($dl.File, $dlText, (New-Object System.Text.UTF8Encoding($true)))
  4849. $dlShown = ($dlUnresolved | Select-Object -First 5) -join ', '
  4850. if ($dlUnresolved.Count -gt 5) { $dlShown += ", …" }
  4851. $dlRel = $dl.File.Substring($extDir.Length).TrimStart('\', '/') -replace '\\', '/'
  4852. Info "Поля динамического списка ($dlRel): пути с тильдой ($($script:dlCount)) — список использует то, чего нет в расширении ($dlShown); разрешатся после наложения"
  4853. }
  4854. }
  4855. # --- 15. Save modified Configuration.xml ---
  4856. # Стиль исходника снимаем ДО записи: правка чужого файла наследует его BOM/EOL/заголовок
  4857. # (#44/#46/#47), новый файл получает канон выгрузки. Зеркало _detect_xml_style в py-порту.
  4858. $style = Detect-XmlStyle $extResolvedPath
  4859. $settings = New-Object System.Xml.XmlWriterSettings
  4860. $settings.Encoding = New-Object System.Text.UTF8Encoding($true)
  4861. $settings.Indent = $false
  4862. $settings.NewLineHandling = [System.Xml.NewLineHandling]::None
  4863. $memStream = New-Object System.IO.MemoryStream
  4864. $writer = [System.Xml.XmlWriter]::Create($memStream, $settings)
  4865. $script:xmlDoc.Save($writer)
  4866. $writer.Flush(); $writer.Close()
  4867. $text = [System.Text.Encoding]::UTF8.GetString($memStream.ToArray())
  4868. $memStream.Close()
  4869. $text = Finalize-XmlText $text $style
  4870. $writeBom = ($null -eq $style) -or $style.bom
  4871. [System.IO.File]::WriteAllText($extResolvedPath, $text, (New-Object System.Text.UTF8Encoding($writeBom)))
  4872. Info "Saved: $extResolvedPath"
  4873. # --- 16. Summary ---
  4874. Write-Host ""
  4875. Write-Host "=== cfe-borrow summary ==="
  4876. Write-Host " Extension: $extDir"
  4877. Write-Host " Config: $cfgDir"
  4878. Write-Host " Borrowed: $borrowedCount object(s)"
  4879. foreach ($f in $script:borrowedFiles) {
  4880. Write-Host " - $f"
  4881. }
  4882. Write-ActReport | Out-Null
  4883. # Заимствованное, которое не удалось сопоставить с источником (пересоздано, пропало), осталось как было —
  4884. # остальное применено, поэтому код 0, а не отказ; решение по ним — за человеком
  4885. if ($script:actUnresolved.Count -gt 0) {
  4886. $shown = ($script:actUnresolved | Select-Object -First 5) -join ', '
  4887. if ($script:actUnresolved.Count -gt 5) { $shown += ", …" }
  4888. Warn "$($script:actUnresolved.Count) element(s) left unresolved ($shown): all other changes are applied; these need a decision"
  4889. }
  4890. exit 0
.claude/skills/form-decompile/scripts/form-decompile.ps1 · Bundled script · 2,993 lines
  1. # form-decompile v0.160 — Decompile 1C managed Form.xml to JSON DSL (draft)
  2. # Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
  3. # ВНИМАНИЕ: раундтрип не гарантируется. Навык исключён из авто-использования моделью.
  4. [CmdletBinding(PositionalBinding=$false)]
  5. param(
  6. [Parameter(Mandatory)]
  7. [Alias('Path')]
  8. [string]$FormPath,
  9. [string]$OutputPath
  10. )
  11. $ErrorActionPreference = "Stop"
  12. [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
  13. # --- 0. Resolve and validate input ---
  14. if (-not (Test-Path $FormPath)) {
  15. Write-Error "Form not found: $FormPath"
  16. exit 1
  17. }
  18. $FormPath = (Resolve-Path $FormPath).ProviderPath
  19. $xmlDoc = New-Object System.Xml.XmlDocument
  20. $xmlDoc.PreserveWhitespace = $false
  21. $xmlDoc.Load($FormPath)
  22. $root = $xmlDoc.DocumentElement
  23. # Второй документ с сохранением whitespace — только для восстановления ТОЧНОГО числа пробелов
  24. # в whitespace-only <v8:content> (декорации-распорки без width: число пробелов = ширина). Основной
  25. # парс (PreserveWhitespace=false) не трогаем; элементная структура обоих документов идентична →
  26. # навигация по индекс-пути элементов (Resolve-WS). Загрузка лениво-безопасная.
  27. $script:xmlDocWS = $null
  28. try { $script:xmlDocWS = New-Object System.Xml.XmlDocument; $script:xmlDocWS.PreserveWhitespace = $true; $script:xmlDocWS.Load($FormPath) } catch { $script:xmlDocWS = $null }
  29. # Ring 2: not a managed Form
  30. if ($root.LocalName -ne 'Form') {
  31. [Console]::Error.WriteLine("form-decompile: корневой элемент <$($root.LocalName)> не <Form> — это не управляемая форма.")
  32. exit 2
  33. }
  34. # --- 1. Namespaces ---
  35. $NS_LF = "http://v8.1c.ru/8.3/xcf/logform"
  36. $NS_V8 = "http://v8.1c.ru/8.1/data/core"
  37. $NS_XR = "http://v8.1c.ru/8.3/xcf/readable"
  38. $NS_XSI = "http://www.w3.org/2001/XMLSchema-instance"
  39. $NS_DCSSET = "http://v8.1c.ru/8.1/data-composition-system/settings"
  40. $NS_DCSSCH = "http://v8.1c.ru/8.1/data-composition-system/schema"
  41. $NS_DCSCOR = "http://v8.1c.ru/8.1/data-composition-system/core"
  42. $NS_V8UI = "http://v8.1c.ru/8.1/data/ui"
  43. $NS_APP = "http://v8.1c.ru/8.2/managed-application/core"
  44. $ns = New-Object System.Xml.XmlNamespaceManager($xmlDoc.NameTable)
  45. $ns.AddNamespace("lf", $NS_LF)
  46. $ns.AddNamespace("v8", $NS_V8)
  47. $ns.AddNamespace("xr", $NS_XR)
  48. $ns.AddNamespace("xsi", $NS_XSI)
  49. $ns.AddNamespace("dcsset", $NS_DCSSET)
  50. $ns.AddNamespace("dcssch", $NS_DCSSCH)
  51. $ns.AddNamespace("dcscor", $NS_DCSCOR)
  52. $ns.AddNamespace("v8ui", $NS_V8UI)
  53. $ns.AddNamespace("app", $NS_APP)
  54. # Список с явным ключом набора (FieldValue/RowKey/RowNumber) без основной таблицы: ссылки в строке нет,
  55. # умный дефолт RowPictureDataPath = <Список>.DefaultPicture компилятор ему не ставит.
  56. function Test-DynListExplicitKey([string]$listName) {
  57. foreach ($a in $root.SelectNodes("lf:Attributes/lf:Attribute", $ns)) {
  58. if ($a.GetAttribute('name') -ne $listName) { continue }
  59. $kt = $a.SelectSingleNode("lf:Settings/lf:KeyType", $ns)
  60. $v = if ($null -ne $kt) { $kt.InnerText.Trim() } else { '' }
  61. return ($v -ne '' -and $v -ne 'Auto' -and $null -eq $a.SelectSingleNode("lf:Settings/lf:MainTable", $ns))
  62. }
  63. return $false
  64. }
  65. # Каноничные GUID пустых контейнеров ListSettings (умолчание платформы, ~90% форм).
  66. # Если ListSettings = пустой скелет с этими GUID → декомпилятор опускает настройки вовсе,
  67. # компилятор регенерит тот же скелет → чистый раундтрип.
  68. $CANON_FILTER_ID = 'dfcece9d-5077-440b-b6b3-45a5cb4538eb'
  69. $CANON_ORDER_ID = '88619765-ccb3-46c6-ac52-38e9c992ebd4'
  70. $CANON_CA_ID = 'b75fecce-942b-4aed-abc9-e6a02e460fb3'
  71. $CANON_ITEMS_ID = '911b6018-f537-43e8-a417-da56b22f9aec'
  72. # --- Вынос запроса динсписка в .sql рядом с output (зеркало skd-decompile) ---
  73. $script:outputDir = $null
  74. $script:outputBasename = $null
  75. if ($OutputPath) {
  76. $od = Split-Path -Parent $OutputPath
  77. if (-not $od) { $od = (Get-Location).ProviderPath }
  78. $script:outputDir = $od
  79. $script:outputBasename = [System.IO.Path]::GetFileNameWithoutExtension($OutputPath)
  80. }
  81. $script:queryFilesAccumulator = @()
  82. $script:queryFileNamesUsed = @{}
  83. # Запрос ≥3 строк + есть outputDir → вынести в `<basename>-<listName>.sql`, вернуть "@file".
  84. function Maybe-ExternalizeQuery {
  85. param([string]$queryText, [string]$listName)
  86. if (-not $queryText) { return $queryText }
  87. if (-not $script:outputDir) { return $queryText }
  88. $lineCount = ([regex]::Matches($queryText, "`n")).Count + 1
  89. if ($lineCount -lt 3) { return $queryText }
  90. $safe = ($listName -replace '[^\w\-]', '_'); if (-not $safe) { $safe = 'query' }
  91. $prefix = if ($script:outputBasename) { "$($script:outputBasename)-" } else { '' }
  92. $fileName = "$prefix$safe.sql"
  93. $suffix = 1
  94. while ($script:queryFileNamesUsed.ContainsKey($fileName)) { $suffix++; $fileName = "$prefix$safe`_$suffix.sql" }
  95. $script:queryFileNamesUsed[$fileName] = $true
  96. $script:queryFilesAccumulator += [ordered]@{ fileName = $fileName; text = $queryText }
  97. return "@$fileName"
  98. }
  99. function Save-QueryFiles {
  100. if ($script:queryFilesAccumulator.Count -eq 0) { return }
  101. if (-not $script:outputDir) { return }
  102. $enc = New-Object System.Text.UTF8Encoding($false)
  103. foreach ($qf in $script:queryFilesAccumulator) {
  104. [System.IO.File]::WriteAllText((Join-Path $script:outputDir $qf.fileName), $qf.text, $enc)
  105. }
  106. [Console]::Error.WriteLine("Saved $($script:queryFilesAccumulator.Count) external query file(s)")
  107. }
  108. # Есть ли в ListSettings содержательные настройки (реальные items фильтра/порядка/
  109. # условного оформления/параметров)? Пустой скелет (только viewMode+GUID) → false:
  110. # декомпилятор опускает настройки, компилятор регенерит каноничный скелет, harness
  111. # нормализует GUID → чистый раундтрип. true → контент захватывается (см. ниже).
  112. function Test-ListSettingsHasContent {
  113. param($lsNode)
  114. if (-not $lsNode) { return $false }
  115. foreach ($cont in @('filter','order','conditionalAppearance','dataParameters')) {
  116. $cn = $lsNode.SelectSingleNode("dcsset:$cont", $ns)
  117. if ($cn -and $cn.SelectSingleNode("dcsset:item", $ns)) { return $true }
  118. }
  119. return $false
  120. }
  121. # Форма ListSettings: ordered-карта present top-level элементов (filter/order/conditionalAppearance →
  122. # блок-мета 'v'/'u'/'vu'/''; itemsViewMode/itemsUserSettingID → $true). Возвращает $null, если форма ==
  123. # полному каноничному скелету (компилятор регенерит сам) ИЛИ содержит неподдержанные top-level элементы
  124. # (item/dataParameters/viewMode/userSettingID/… → fallback на канон). Иначе — дескриптор для компилятора.
  125. function Get-ListSettingsShape {
  126. param($lsNode, [bool]$hasGrouping = $false)
  127. if (-not $lsNode) { return $null }
  128. $shape = [ordered]@{}
  129. foreach ($child in $lsNode.ChildNodes) {
  130. if ($child.NodeType -ne [System.Xml.XmlNodeType]::Element) { continue }
  131. $tag = $child.LocalName
  132. if ($tag -in @('filter','order','conditionalAppearance')) {
  133. $hasVM = $null -ne $child.SelectSingleNode("dcsset:viewMode", $ns)
  134. $hasUS = $null -ne $child.SelectSingleNode("dcsset:userSettingID", $ns)
  135. $code = "$(if ($hasVM) {'v'})$(if ($hasUS) {'u'})"
  136. # Контейнер может нести собственный <dcsset:userSettingPresentation> (кастомная подпись
  137. # настройки) — сохраняем форму по xsi:type (Get-PresByType: ru-only LocalString ≠ xs:string).
  138. $uspNode = $child.SelectSingleNode("dcsset:userSettingPresentation", $ns)
  139. if ($uspNode) {
  140. $usp = Get-PresByType $uspNode
  141. $shape[$tag] = [ordered]@{ meta = $code; presentation = $usp }
  142. } else { $shape[$tag] = $code }
  143. } elseif ($tag -eq 'itemsViewMode') { $shape['itemsViewMode'] = $true }
  144. elseif ($tag -eq 'itemsUserSettingID') { $shape['itemsUserSettingID'] = $true }
  145. elseif ($tag -eq 'itemsUserSettingPresentation') { $shape['itemsUserSettingPresentation'] = Get-PresByType $child } # items-уровневая подпись (форма по xsi:type)
  146. elseif ($tag -eq 'dataParameters') { $shape['dataParameters'] = $true } # значения параметров запроса (контент в settings.dataParameters)
  147. elseif ($tag -eq 'item') { if ($hasGrouping) { $shape['structure'] = $true } else { return $null } }
  148. else { return $null } # неизвестный top-level → канон-fallback
  149. }
  150. # Полный каноничный скелет → опускаем (компилятор регенерит)
  151. if ($shape.Count -eq 5 -and $shape['filter'] -eq 'vu' -and $shape['order'] -eq 'vu' -and `
  152. $shape['conditionalAppearance'] -eq 'vu' -and $shape['itemsViewMode'] -eq $true -and $shape['itemsUserSettingID'] -eq $true) { return $null }
  153. return $shape
  154. }
  155. # Группировка строк динамического списка: цепочка <dcsset:item StructureItemGroup> (каждый уровень =
  156. # один groupItems-field; вложенность через дочерний <dcsset:item>). Возвращает ПЛОСКИЙ массив уровней
  157. # (string для дефолтного поля; объект {field,groupType?,periodAdditionType?,periodAdditionBegin?,periodAdditionEnd?}
  158. # для нестандартного) ИЛИ $null, если структура не «чистая линейная цепочка одно-польных уровней»
  159. # (ветвление/мультиполе/доп.содержимое) → честный fallback на канон (LOST), а не тихая порча.
  160. function Build-GroupLevel {
  161. param($fn)
  162. $field = Get-Child $fn 'field'
  163. $gt = Get-Child $fn 'groupType'
  164. $pat = Get-Child $fn 'periodAdditionType'
  165. $pabN = $fn.SelectSingleNode("dcsset:periodAdditionBegin", $ns)
  166. $paeN = $fn.SelectSingleNode("dcsset:periodAdditionEnd", $ns)
  167. $pab = $null; $pae = $null
  168. 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 } }
  169. 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 } }
  170. $isDefault = ((-not $gt) -or $gt -eq 'Items') -and ((-not $pat) -or $pat -eq 'None') -and (-not $pab) -and (-not $pae)
  171. if ($isDefault) { return $field }
  172. $o = [ordered]@{ field = $field }
  173. if ($gt -and $gt -ne 'Items') { $o['groupType'] = $gt }
  174. if ($pat -and $pat -ne 'None') { $o['periodAdditionType'] = $pat }
  175. if ($pab) { $o['periodAdditionBegin'] = $pab }
  176. if ($pae) { $o['periodAdditionEnd'] = $pae }
  177. return $o
  178. }
  179. function Build-ListGrouping {
  180. param($itemNode)
  181. $levels = New-Object System.Collections.ArrayList
  182. $cur = $itemNode
  183. while ($cur) {
  184. if (($cur.GetAttribute("type", $NS_XSI)) -notmatch 'StructureItemGroup$') { return $null }
  185. $gi = $null; $nested = @()
  186. foreach ($ch in $cur.ChildNodes) {
  187. if ($ch.NodeType -ne [System.Xml.XmlNodeType]::Element) { continue }
  188. switch ($ch.LocalName) {
  189. 'groupItems' { if ($gi) { return $null }; $gi = $ch }
  190. 'item' { $nested += $ch }
  191. default { return $null } # use/name/filter/order/… — здесь не поддержано
  192. }
  193. }
  194. if (-not $gi) { return $null }
  195. $fieldItems = @($gi.SelectNodes("dcsset:item", $ns))
  196. if ($fieldItems.Count -ne 1) { return $null }
  197. $fn = $fieldItems[0]
  198. if (($fn.GetAttribute("type", $NS_XSI)) -notmatch 'GroupItemField$') { return $null }
  199. [void]$levels.Add((Build-GroupLevel $fn))
  200. if ($nested.Count -eq 0) { break }
  201. if ($nested.Count -gt 1) { return $null } # ветвление — не линейно
  202. $cur = $nested[0]
  203. }
  204. if ($levels.Count -eq 0) { return $null }
  205. return ,@($levels)
  206. }
  207. # --- 1b. Ring-3 scan: конструкции вне зоны поддержки (draft list) ---
  208. function Fail-Ring3 {
  209. param([string]$kind, [string]$loc)
  210. [Console]::Error.WriteLine("form-decompile: декомпиляция пока не поддерживает $kind (path: $loc)")
  211. [Console]::Error.WriteLine("Для точечной работы с этой формой используй /form-edit.")
  212. exit 3
  213. }
  214. # ConditionalAppearance со scope (привязка к области) пока не воспроизводим — fail-ring3 только в этом случае.
  215. 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" }
  216. # Реквизит с design-time конфигурацией (<Settings> chart-типа: Диаграмма/ДиаграммаГанта/… —
  217. # d4p1:GanttChart и т.п.). Поддержаны только TypeDescription (valueType) и DynamicList; прочие
  218. # (встроенная конфигурация диаграммы) пока НЕ воспроизводим → честный скип, чтобы не потерять молча.
  219. foreach ($s in $xmlDoc.SelectNodes("//*[local-name()='Attribute']/*[local-name()='Settings']")) {
  220. $st = $s.GetAttribute("type", $NS_XSI)
  221. if ($st -and $st -notmatch 'TypeDescription$' -and $st -notmatch 'DynamicList$' -and $st -notmatch 'Planner$' -and $st -notmatch 'd4p1:(Gantt)?Chart$') {
  222. Fail-Ring3 -kind "Attribute>Settings типа '$st' (design-time конфигурация, напр. диаграмма)" -loc "Attribute/Settings"
  223. }
  224. # Chart/GanttChart с точками/осями: типизированные значения (xsi:type), xsi:nil и ML с
  225. # префиксом d4p1: (а не v8:) генерик-движок не сохраняет → честный скип. Частые
  226. # дашборд-диаграммы/гант (серии/легенда/оформление/шкала) поддержаны.
  227. 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[ >]')) {
  228. Fail-Ring3 -kind "Attribute>Settings $st с точками/осями (типизированные значения/d4p1-ML)" -loc "Attribute/Settings"
  229. }
  230. }
  231. # --- 1c. Compact JSON serializer (созвучно skd-decompile: 2-проб. indent, inline в пределах lineLimit) ---
  232. function Convert-StringToJsonLiteral {
  233. param([string]$s)
  234. if ($null -eq $s) { return 'null' }
  235. $sb = New-Object System.Text.StringBuilder
  236. [void]$sb.Append('"')
  237. foreach ($ch in $s.ToCharArray()) {
  238. $code = [int]$ch
  239. if ($code -eq 0x22) { [void]$sb.Append('\"') }
  240. elseif ($code -eq 0x5C) { [void]$sb.Append('\\') }
  241. elseif ($code -eq 0x08) { [void]$sb.Append('\b') }
  242. elseif ($code -eq 0x09) { [void]$sb.Append('\t') }
  243. elseif ($code -eq 0x0A) { [void]$sb.Append('\n') }
  244. elseif ($code -eq 0x0C) { [void]$sb.Append('\f') }
  245. elseif ($code -eq 0x0D) { [void]$sb.Append('\r') }
  246. elseif ($code -lt 0x20) { [void]$sb.AppendFormat('\u{0:x4}', $code) }
  247. else { [void]$sb.Append($ch) }
  248. }
  249. [void]$sb.Append('"')
  250. return $sb.ToString()
  251. }
  252. function Try-InlineJson {
  253. param($obj)
  254. if ($null -eq $obj) { return 'null' }
  255. if ($obj -is [bool]) { if ($obj) { return 'true' } else { return 'false' } }
  256. if ($obj -is [string]) { return (Convert-StringToJsonLiteral $obj) }
  257. if ($obj -is [int] -or $obj -is [long]) { return "$obj" }
  258. if ($obj -is [double] -or $obj -is [single] -or $obj -is [decimal]) {
  259. return ([System.Convert]::ToString($obj, [System.Globalization.CultureInfo]::InvariantCulture))
  260. }
  261. if ($obj -is [System.Collections.IDictionary]) {
  262. if ($obj.Count -eq 0) { return '{}' }
  263. $parts = @()
  264. foreach ($k in $obj.Keys) {
  265. $v = Try-InlineJson $obj[$k]
  266. if ($null -eq $v) { return $null }
  267. $parts += "$(Convert-StringToJsonLiteral "$k"): $v"
  268. }
  269. return '{ ' + ($parts -join ', ') + ' }'
  270. }
  271. if ($obj -is [array] -or $obj -is [System.Collections.IList]) {
  272. $items = @($obj)
  273. if ($items.Count -eq 0) { return '[]' }
  274. $parts = @()
  275. foreach ($it in $items) {
  276. $v = Try-InlineJson $it
  277. if ($null -eq $v) { return $null }
  278. $parts += $v
  279. }
  280. return '[' + ($parts -join ', ') + ']'
  281. }
  282. return $null
  283. }
  284. function ConvertTo-CompactJson {
  285. param($obj, [int]$depth = 0, [string]$indentUnit = ' ', [int]$lineLimit = 120)
  286. $indent = $indentUnit * $depth
  287. $childIndent = $indentUnit * ($depth + 1)
  288. if ($null -eq $obj) { return 'null' }
  289. if ($obj -is [bool]) { if ($obj) { return 'true' } else { return 'false' } }
  290. if ($obj -is [string]) { return (Convert-StringToJsonLiteral $obj) }
  291. if ($obj -is [int] -or $obj -is [long]) { return "$obj" }
  292. if ($obj -is [double] -or $obj -is [single] -or $obj -is [decimal]) {
  293. return ([System.Convert]::ToString($obj, [System.Globalization.CultureInfo]::InvariantCulture))
  294. }
  295. $isContainer = ($obj -is [System.Collections.IDictionary]) -or ($obj -is [array]) -or ($obj -is [System.Collections.IList])
  296. if ($isContainer) {
  297. $inlineAttempt = Try-InlineJson $obj
  298. if ($null -ne $inlineAttempt -and ($indent.Length + $inlineAttempt.Length) -le $lineLimit) { return $inlineAttempt }
  299. }
  300. if ($obj -is [System.Collections.IDictionary]) {
  301. $keys = @($obj.Keys)
  302. if ($keys.Count -eq 0) { return '{}' }
  303. $parts = @()
  304. foreach ($k in $keys) {
  305. $val = ConvertTo-CompactJson -obj $obj[$k] -depth ($depth + 1) -indentUnit $indentUnit -lineLimit $lineLimit
  306. $parts += "$childIndent$(Convert-StringToJsonLiteral "$k"): $val"
  307. }
  308. return "{`n" + ($parts -join ",`n") + "`n$indent}"
  309. }
  310. if ($obj -is [array] -or $obj -is [System.Collections.IList]) {
  311. $items = @($obj)
  312. if ($items.Count -eq 0) { return '[]' }
  313. $parts = @($items | ForEach-Object { "$childIndent$(ConvertTo-CompactJson -obj $_ -depth ($depth + 1) -indentUnit $indentUnit -lineLimit $lineLimit)" })
  314. return "[`n" + ($parts -join ",`n") + "`n$indent]"
  315. }
  316. return (Convert-StringToJsonLiteral "$obj")
  317. }
  318. # --- 2. Helpers ---
  319. # Companion-элементы (авто-генерируемые компилятором) — пропускаем при обходе детей.
  320. # Дополнения (Search*/ViewStatus) БОЛЬШЕ не companion — декомпилируются как тип-элементы
  321. # (кастомные в AutoCommandBar/ChildItems → commandBar.children; стандартные на уровне таблицы → карта additions).
  322. $COMPANION_TAGS = @('ContextMenu','ExtendedTooltip','AutoCommandBar')
  323. # Извлечь мультиязычный Title/Presentation → string (ru) или ordered hash {ru,en,...}
  324. function Get-LangText {
  325. param($node)
  326. if ($null -eq $node) { return $null }
  327. $items = @($node.SelectNodes("v8:item", $ns))
  328. if ($items.Count -eq 0) { return $null }
  329. $map = [ordered]@{}
  330. foreach ($it in $items) {
  331. $lang = $it.SelectSingleNode("v8:lang", $ns)
  332. $content = $it.SelectSingleNode("v8:content", $ns)
  333. if ($lang) { $map[$lang.InnerText] = if ($content) { $content.InnerText } else { "" } }
  334. }
  335. if ($map.Count -eq 1 -and $map.Contains('ru')) { return $map['ru'] }
  336. return $map
  337. }
  338. # Get-LangText с восстановлением значимого пробела: PreserveWhitespace=false стрипает
  339. # <v8:content> </v8:content> → "" (неотличимо от суппресса). Платформа НЕ эмитит пустой
  340. # Title/ToolTip, значит исходно был пробел → возвращаем " " (как Get-MLFormattedValue).
  341. # Покрывает и одиночную строку (ru-only), и мультиязычную мапу (напр. декорация-разделитель
  342. # «Пробел» с ru+en пробелами): восстанавливаем " " в каждом языке, где content-узел есть, но пуст.
  343. # Точное число пробелов whitespace-only <v8:content> из PreserveWhitespace-документа (основной
  344. # парс стрипает его в ""). Навигация по индекс-пути элементов (структура обоих документов идентична).
  345. function Resolve-WS {
  346. param($contentNode)
  347. if (-not $contentNode -or -not $script:xmlDocWS) { return $null }
  348. $idxs = New-Object System.Collections.ArrayList
  349. $cur = $contentNode
  350. while ($cur.ParentNode -and $cur.ParentNode.NodeType -eq [System.Xml.XmlNodeType]::Element) {
  351. $i = 0; $sib = $cur.PreviousSibling
  352. while ($sib) { if ($sib.NodeType -eq [System.Xml.XmlNodeType]::Element) { $i++ }; $sib = $sib.PreviousSibling }
  353. [void]$idxs.Insert(0, $i)
  354. $cur = $cur.ParentNode
  355. }
  356. $wcur = $script:xmlDocWS.DocumentElement
  357. foreach ($ix in $idxs) {
  358. $els = @(); foreach ($ch in $wcur.ChildNodes) { if ($ch.NodeType -eq [System.Xml.XmlNodeType]::Element) { $els += $ch } }
  359. if ($ix -ge $els.Count) { return $null }
  360. $wcur = $els[$ix]
  361. }
  362. return $wcur.InnerText
  363. }
  364. # Точное восстановление пробела (число): whitespace-only content → реальная строка пробелов из WS-дока.
  365. function Restore-WSContent {
  366. param($contentNode)
  367. $ws = Resolve-WS $contentNode
  368. if ($ws -and $ws.Trim() -eq '') { return $ws } # только если действительно whitespace
  369. return ' '
  370. }
  371. function Get-LangTextWS {
  372. param($node)
  373. $t = Get-LangText $node
  374. if ($null -eq $t) { return $null }
  375. if ($t -is [string]) {
  376. $cn = $node.SelectSingleNode("v8:item/v8:content", $ns)
  377. if ($t -eq '' -and $cn) { return (Restore-WSContent $cn) }
  378. return $t
  379. }
  380. foreach ($it in @($node.SelectNodes("v8:item", $ns))) {
  381. $lang = $it.SelectSingleNode("v8:lang", $ns)
  382. $content = $it.SelectSingleNode("v8:content", $ns)
  383. if ($lang -and $content -and $t.Contains($lang.InnerText) -and $t[$lang.InnerText] -eq '') {
  384. $t[$lang.InnerText] = (Restore-WSContent $content)
  385. }
  386. }
  387. return $t
  388. }
  389. # Авто-вывод заголовка из имени — ТОЧНОЕ зеркало Title-FromName из form-compile.
  390. # Нужен, чтобы опускать ru-only заголовки, которые компилятор воспроизведёт сам.
  391. function Title-FromName {
  392. param([string]$name)
  393. if (-not $name) { return '' }
  394. $s = [regex]::Replace($name, '([А-ЯA-Z])([А-ЯA-Z][а-яa-z])', '$1 $2')
  395. $s = [regex]::Replace($s, '([а-яa-z0-9])([А-ЯA-Z])', '$1 $2')
  396. $parts = $s -split ' '
  397. if ($parts.Count -eq 0) { return $s }
  398. $out = New-Object System.Collections.ArrayList
  399. [void]$out.Add($parts[0])
  400. for ($i = 1; $i -lt $parts.Count; $i++) {
  401. $p = $parts[$i]
  402. if ($p.Length -gt 1 -and $p -ceq $p.ToUpper()) {
  403. [void]$out.Add($p)
  404. } else {
  405. [void]$out.Add($p.ToLower())
  406. }
  407. }
  408. return ($out -join ' ')
  409. }
  410. # Детектор «настоящей» inline-разметки форматированного текста (идентичен form-compile!).
  411. $script:fmtMarkupRe = '</>|<\s*(?:link|b|i|u|s|color|colorStyle|bgColor|bgColorStyle|font|fontSize|fontStyle|img)(?:\s|>)'
  412. function Test-HasRealMarkup {
  413. param($text)
  414. if ($null -eq $text) { return $false }
  415. $vals = if ($text -is [System.Collections.IDictionary]) { @($text.Values) }
  416. elseif ($text -is [System.Management.Automation.PSCustomObject]) { @($text.PSObject.Properties.Value) }
  417. else { @("$text") }
  418. foreach ($v in $vals) { if ("$v" -match $script:fmtMarkupRe) { return $true } }
  419. return $false
  420. }
  421. # Title-узел → DSL-значение ML-поля (гибрид): строка/мапа когда авто-детект formatted
  422. # совпал с атрибутом; иначе явный {text, formatted}.
  423. function Get-MLFormattedValue {
  424. param($titleNode)
  425. if (-not $titleNode) { return $null }
  426. # Get-LangTextWS восстанавливает значимый пробел в <v8:content> </v8:content> (одиночный и
  427. # мультиязычный случай) — иначе декорация-разделитель «Пробел» спуталась бы с суппресс-маркером "".
  428. $text = Get-LangTextWS $titleNode
  429. if ($null -eq $text) { return $null }
  430. $fmtAttr = ($titleNode.GetAttribute('formatted') -eq 'true')
  431. if ($fmtAttr -eq (Test-HasRealMarkup $text)) { return $text }
  432. $o = [ordered]@{}; $o['text'] = $text; $o['formatted'] = $fmtAttr; return $o
  433. }
  434. # Прочитать дочерний скаляр (по local-name, без namespace)
  435. function Get-Child {
  436. param($node, [string]$name)
  437. $c = $node.SelectSingleNode("*[local-name()='$name']")
  438. if ($c) { return $c.InnerText } else { return $null }
  439. }
  440. function Has-Child { param($node, [string]$name) return $null -ne $node.SelectSingleNode("*[local-name()='$name']") }
  441. function To-Bool { param([string]$v) return ($v -eq 'true') }
  442. # Значение с учётом xsi:type → нативный JSON-тип (число/булево/строка).
  443. # Нужно, чтобы авто-детект типа в компиляторе восстановил тот же xsi:type.
  444. function Convert-TypedValue {
  445. param([string]$raw, [string]$xsiType)
  446. switch -regex ($xsiType) {
  447. 'decimal$' {
  448. if ($raw -match '^-?\d+$') { return [int]$raw }
  449. return [double]::Parse($raw, [System.Globalization.CultureInfo]::InvariantCulture)
  450. }
  451. 'boolean$' { return ($raw -eq 'true') }
  452. default { return $raw }
  453. }
  454. }
  455. # =====================================================================
  456. # Захват настроек компоновщика динамического списка (ListSettings):
  457. # filter / order / conditionalAppearance. Логика портирована из навыка
  458. # skd-decompile (Build-FilterItem/Build-Order/Build-ConditionalAppearance
  459. # и сериализаторы оформления). Механизм New-Sentinel/Add-Warning из skd
  460. # заменён на запись в stderr + пропуск элемента (form-decompile — draft,
  461. # скрипт не падает на непокрытых конструкциях).
  462. # =====================================================================
  463. # Прочитать дочерний скаляр по xpath (с $ns). Аналог skd Get-Text.
  464. function Get-Text {
  465. param($node, [string]$xpath)
  466. if (-not $node) { return $null }
  467. if ([string]::IsNullOrEmpty($xpath)) { return $node.InnerText }
  468. $n = $node.SelectSingleNode($xpath, $ns)
  469. if ($n) { return $n.InnerText } else { return $null }
  470. }
  471. # Мультиязычный текст (LocalStringType) → string (ru) или ordered hash.
  472. # Алиас на уже существующий Get-LangText (тот же контракт).
  473. function Get-MLText { param($node) return (Get-LangText $node) }
  474. # Презентация: либо мультиязычный LocalStringType, либо плоский xs:string.
  475. # Get-MLText даёт $null для xs:string (нет v8:item) → откат к InnerText.
  476. function Get-PresText {
  477. param($node)
  478. if (-not $node) { return $null }
  479. $ml = Get-MLText $node
  480. if ($null -ne $ml) { return $ml }
  481. if ($node.InnerText) { return $node.InnerText }
  482. return $null
  483. }
  484. # Presentation, сохраняющий ФОРМУ по xsi:type (не схлопывает ru-only LocalStringType в строку):
  485. # <… xsi:type="v8:LocalStringType"> → объект {lang:text} (даже один ru), иначе xs:string → плоская строка.
  486. # Нужно, чтобы компилятор воспроизвёл точный xsi:type (LocalStringType vs xs:string). Пустой LocalStringType → $null.
  487. function Get-PresByType {
  488. param($node)
  489. if (-not $node) { return $null }
  490. $xt = $node.GetAttribute("type", $NS_XSI)
  491. if ($xt -match 'LocalStringType$') {
  492. $d = [ordered]@{}
  493. foreach ($it in $node.SelectNodes("v8:item", $ns)) {
  494. $lang = Get-Text $it "v8:lang"; $content = Get-Text $it "v8:content"
  495. if ($lang) { $d[$lang] = $content }
  496. }
  497. if ($d.Count -gt 0) { return $d }
  498. return $null
  499. }
  500. if ($node.InnerText) { return $node.InnerText }
  501. return $null
  502. }
  503. # Снять namespace-префикс с xsi:type ("dcsset:Foo" → "Foo")
  504. function Get-LocalXsiType {
  505. param($node)
  506. if (-not $node) { return $null }
  507. $t = $node.GetAttribute("type", $NS_XSI)
  508. if ($t -match ':(.+)$') { return $matches[1] }
  509. return $t
  510. }
  511. # Шрифт оформления → объект {@type:Font, ...} (bit-perfect для compile).
  512. function Get-FontValue {
  513. param($valNode)
  514. $f = [ordered]@{ '@type' = 'Font' }
  515. foreach ($attrName in @('ref','faceName','height','bold','italic','underline','strikeout','kind','scale')) {
  516. $a = $valNode.Attributes[$attrName]
  517. if ($null -ne $a) { $f[$attrName] = $a.Value }
  518. }
  519. return $f
  520. }
  521. # Линия (граница) оформления → объект {@type:Line, width, gap, style}.
  522. function Get-LineValue {
  523. param($valNode)
  524. $obj = [ordered]@{ '@type' = 'Line' }
  525. $w = $valNode.GetAttribute("width")
  526. $g = $valNode.GetAttribute("gap")
  527. if ($w -ne '') { $obj['width'] = if ($w -match '^-?\d+$') { [int]$w } else { $w } }
  528. if ($g -ne '') { $obj['gap'] = ($g -eq 'true') }
  529. $styleNode = $valNode.SelectSingleNode("v8ui:style", $ns)
  530. if ($styleNode) { $obj['style'] = $styleNode.InnerText }
  531. return $obj
  532. }
  533. # Прочитать <dcscor:value> в JSON-значение: Font/Line/Field/multilang/raw text.
  534. function Read-AppearanceValueNode {
  535. param($valNode)
  536. if (-not $valNode) { return $null }
  537. $vt = Get-LocalXsiType $valNode
  538. if ($vt -eq 'LocalStringType') {
  539. # НЕ схлопываем одноязычный в строку: значение параметра оформления различает
  540. # xs:string (плоская строка) и LocalStringType (локализуемый текст) — обе формы
  541. # одноязычно дают одну строку. Всегда объект-карта языков → компилятор эмитит LocalStringType.
  542. $map = [ordered]@{}
  543. foreach ($it in @($valNode.SelectNodes("v8:item", $ns))) {
  544. $lang = $it.SelectSingleNode("v8:lang", $ns); $content = $it.SelectSingleNode("v8:content", $ns)
  545. if ($lang) { $map[$lang.InnerText] = if ($content) { $content.InnerText } else { "" } }
  546. }
  547. return $map
  548. }
  549. if ($vt -eq 'Font') { return (Get-FontValue $valNode) }
  550. if ($vt -eq 'Line') { return (Get-LineValue $valNode) }
  551. # dcscor:Field — значение = ссылка на поле компоновки → объект {field:путь}
  552. if ($vt -eq 'Field') { return [ordered]@{ field = $valNode.InnerText } }
  553. return $valNode.InnerText
  554. }
  555. # Обратная карта comparisonType → короткий оператор фильтра (зеркало skd).
  556. $script:filterOpMap = @{
  557. 'Equal'='='; 'NotEqual'='<>'; 'Greater'='>'; 'GreaterOrEqual'='>=';
  558. 'Less'='<'; 'LessOrEqual'='<='; 'InList'='in'; 'NotInList'='notIn';
  559. 'InHierarchy'='inHierarchy'; 'InListByHierarchy'='inListByHierarchy';
  560. 'Contains'='contains'; 'NotContains'='notContains';
  561. 'BeginsWith'='beginsWith'; 'NotBeginsWith'='notBeginsWith';
  562. 'Like'='like'; 'NotLike'='notLike';
  563. 'Filled'='filled'; 'NotFilled'='notFilled'
  564. }
  565. # Render filter value node → shorthand-acceptable scalar string
  566. function Get-FilterValue {
  567. param($valNode)
  568. if (-not $valNode) { return '_' }
  569. $nil = $valNode.GetAttribute("nil", $NS_XSI)
  570. if ($nil -eq 'true') { return '_' }
  571. $vType = Get-LocalXsiType $valNode
  572. if ($vType -eq 'DesignTimeValue') { return $valNode.InnerText }
  573. if ($vType -eq 'LocalStringType') { return (Get-MLText $valNode) }
  574. $txt = $valNode.InnerText
  575. if (-not $txt) { return '_' }
  576. return $txt
  577. }
  578. # Get-FilterValue + xsi:type значения (для valueType, например dcscor:Field).
  579. function Get-FilterValueWithType {
  580. param($valNode)
  581. if (-not $valNode) { return @{ value = '_'; type = $null } }
  582. $rawType = $valNode.GetAttribute("type", $NS_XSI)
  583. $nil = $valNode.GetAttribute("nil", $NS_XSI)
  584. if ($nil -eq 'true') { return @{ value = '_'; type = $null } }
  585. $vType = Get-LocalXsiType $valNode
  586. if ($vType -eq 'LocalStringType') {
  587. return @{ value = (Get-MLText $valNode); type = $rawType }
  588. }
  589. # Стандартная дата начала/окончания. Формы (от самой компактной):
  590. # SBD Custom+date → голая ISO-дата без valueType (компилятор выводит SBD Custom — дефолт
  591. # даты в фильтре, корпус 268 vs 2 xs:dateTime); именованный вариант → строка + valueType;
  592. # SED Custom / нетипичное → объект {variant, date} + valueType. Иначе InnerText склеивал.
  593. if ($vType -eq 'StandardBeginningDate' -or $vType -eq 'StandardEndDate') {
  594. $variantN = $valNode.SelectSingleNode("v8:variant", $ns)
  595. $dateN = $valNode.SelectSingleNode("v8:date", $ns)
  596. $variantStr = if ($variantN) { $variantN.InnerText } else { '' }
  597. if ($dateN) {
  598. if ($vType -eq 'StandardBeginningDate' -and $variantStr -eq 'Custom') {
  599. return @{ value = $dateN.InnerText; type = $null } # голая дата = SBD Custom шорткат
  600. }
  601. return @{ value = [ordered]@{ variant = $variantStr; date = $dateN.InnerText }; type = $rawType }
  602. }
  603. return @{ value = $variantStr; type = $rawType } # именованный вариант
  604. }
  605. $txt = $valNode.InnerText
  606. if (-not $txt) { return @{ value = '_'; type = $rawType } }
  607. if ($vType -eq 'boolean') { return @{ value = ($txt -eq 'true'); type = $rawType } }
  608. if ($vType -eq 'decimal') {
  609. if ($txt -match '^-?\d+$') { return @{ value = [int]$txt; type = $rawType } }
  610. return @{ value = [double]$txt; type = $rawType }
  611. }
  612. return @{ value = $txt; type = $rawType }
  613. }
  614. # Convert filter item node → shorthand string или object form (рекурсивно для групп).
  615. function Build-FilterItem {
  616. param($itemNode, [string]$loc)
  617. $xtype = Get-LocalXsiType $itemNode
  618. if ($xtype -eq 'FilterItemGroup') {
  619. $gt = Get-Text $itemNode "dcsset:groupType"
  620. $groupName = switch ($gt) { 'OrGroup' { 'Or' } 'NotGroup' { 'Not' } default { 'And' } }
  621. $items = @()
  622. foreach ($c in $itemNode.SelectNodes("dcsset:item", $ns)) {
  623. $bi = (Build-FilterItem -itemNode $c -loc "$loc/item")
  624. if ($null -ne $bi) { $items += $bi }
  625. }
  626. $gObj = [ordered]@{ group = $groupName; items = $items }
  627. if ((Get-Text $itemNode "dcsset:use") -eq 'false') { $gObj['use'] = $false } # группа отключена (@off)
  628. $gPresNode = $itemNode.SelectSingleNode("dcsset:presentation", $ns)
  629. if ($gPresNode) {
  630. # Сохраняем форму по xsi:type (LocalStringType ru-only ≠ xs:string)
  631. $gPres = Get-PresByType $gPresNode
  632. if ($null -ne $gPres -and $gPres -ne '') { $gObj['presentation'] = $gPres }
  633. }
  634. $gVMNode = $itemNode.SelectSingleNode("dcsset:viewMode", $ns)
  635. if ($gVMNode) { $gObj['viewMode'] = $gVMNode.InnerText }
  636. $gUSID = Get-Text $itemNode "dcsset:userSettingID"
  637. if ($gUSID) { $gObj['userSettingID'] = 'auto' }
  638. $gUSPN = $itemNode.SelectSingleNode("dcsset:userSettingPresentation", $ns)
  639. if ($gUSPN) {
  640. $gUSP = Get-PresText $gUSPN
  641. if ($gUSP) { $gObj['userSettingPresentation'] = $gUSP }
  642. }
  643. return $gObj
  644. }
  645. if ($xtype -ne 'FilterItemComparison') {
  646. [Console]::Error.WriteLine("form-decompile: пропущен фильтр неизвестного типа '$xtype' (path: $loc)")
  647. return $null
  648. }
  649. $leftNode = $itemNode.SelectSingleNode("dcsset:left", $ns)
  650. $field = if ($leftNode) { $leftNode.InnerText } else { $null }
  651. $ct = Get-Text $itemNode "dcsset:comparisonType"
  652. $op = $script:filterOpMap[$ct]
  653. if (-not $op) { $op = $ct }
  654. $rightNodes = @($itemNode.SelectNodes("dcsset:right", $ns))
  655. $value = $null
  656. $valueIsArrayFlag = $false
  657. $valueTypeAttr = $null
  658. if ($rightNodes.Count -eq 1) {
  659. $rn = $rightNodes[0]
  660. if ((Get-LocalXsiType $rn) -eq 'ValueListType') {
  661. $value = @()
  662. $valueIsArrayFlag = $true
  663. } else {
  664. $vt = Get-FilterValueWithType $rn
  665. $value = $vt.value
  666. $autoDetectsDTV = ($vt.type -eq 'dcscor:DesignTimeValue') -and `
  667. ("$($vt.value)" -match '^(Перечисление|Справочник|ПланСчетов|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|РегистрСведений|ПланОбмена|Catalog|Enum|Document|ChartOfAccounts|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|InformationRegister|ExchangePlan)\.')
  668. if ($vt.type -and $vt.type -notmatch '^xs:' -and -not $autoDetectsDTV) {
  669. $valueTypeAttr = $vt.type
  670. } elseif ($vt.type -eq 'xs:string' -and ($value -is [string]) -and ($value -match '^(-?\d+(\.\d+)?|\d{4}-\d{2}-\d{2}T)')) {
  671. # Значение-строка "1"/"2020-..." с xsi:type="xs:string": компилятор авто-детектит число/дату
  672. # (теряет xs:string). Когда авто-вывод дал бы ДРУГОЙ тип — фиксируем явный valueType.
  673. $valueTypeAttr = 'xs:string'
  674. }
  675. }
  676. } elseif ($rightNodes.Count -gt 1) {
  677. $arr = @()
  678. $rawTypes = @()
  679. foreach ($rn in $rightNodes) {
  680. $arr += (Get-FilterValue $rn)
  681. $rawTypes += $rn.GetAttribute("type", $NS_XSI)
  682. }
  683. $value = $arr
  684. $valueIsArrayFlag = $true
  685. $uniqTypes = @($rawTypes | Sort-Object -Unique)
  686. if ($uniqTypes.Count -eq 1 -and $uniqTypes[0]) {
  687. $autoDetectsDTV = ($uniqTypes[0] -eq 'dcscor:DesignTimeValue') -and `
  688. ($arr.Count -gt 0) -and `
  689. (@($arr | Where-Object { "$_" -notmatch '^(Перечисление|Справочник|ПланСчетов|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|РегистрСведений|ПланОбмена|Catalog|Enum|Document|ChartOfAccounts|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|InformationRegister|ExchangePlan)\.' }).Count -eq 0)
  690. if (-not $autoDetectsDTV) {
  691. $valueTypeAttr = $uniqTypes[0]
  692. }
  693. }
  694. }
  695. $use = Get-Text $itemNode "dcsset:use"
  696. $userId = Get-Text $itemNode "dcsset:userSettingID"
  697. $vmNode = $itemNode.SelectSingleNode("dcsset:viewMode", $ns)
  698. $viewMode = if ($vmNode) { $vmNode.InnerText } else { $null }
  699. $userPresNode = $itemNode.SelectSingleNode("dcsset:userSettingPresentation", $ns)
  700. $fiPresNode = $itemNode.SelectSingleNode("dcsset:presentation", $ns)
  701. $fiPres = $null
  702. if ($fiPresNode) {
  703. # Сохраняем форму по xsi:type (LocalStringType ru-only ≠ xs:string)
  704. $fiPres = Get-PresByType $fiPresNode
  705. }
  706. $flags = @()
  707. if ($use -eq 'false') { $flags += '@off' }
  708. if ($userId) { $flags += '@user' }
  709. if ($viewMode -eq 'QuickAccess') { $flags += '@quickAccess' }
  710. elseif ($viewMode -eq 'Inaccessible') { $flags += '@inaccessible' }
  711. elseif ($viewMode -eq 'Normal') { $flags += '@normal' }
  712. $noValueOps = @('filled','notFilled')
  713. # Пустой xs:string right (<dcsset:right xsi:type="xs:string"/>) ≠ отсутствие <right>:
  714. # Get-FilterValueWithType маппит наличие пустого/nil right в value='_' (отсутствие → $null).
  715. # Shorthand `_` неоднозначен (схлопывает оба, компилятор → нет right). Пробельные значения рвут
  716. # shorthand-парсинг (split по пробелам). → форсим объектную форму (value='_' → self-closing;
  717. # пробелы — как есть в <right>).
  718. $valNeedsObj = $false
  719. if ($rightNodes.Count -eq 1 -and -not $valueIsArrayFlag -and $op -notin $noValueOps) {
  720. if ("$value" -eq '_') {
  721. # Truly-empty <right xsi:type="xs:string"/> ИЛИ whitespace-only <right> </right>
  722. # (PreserveWhitespace=false стрипнул пробелы в '' → Get-FilterValueWithType вернул '_').
  723. # Восстанавливаем реальные пробелы из WS-дока (как у whitespace-заголовков).
  724. $ws = Resolve-WS $rightNodes[0]
  725. if ($ws -and $ws.Length -gt 0 -and $ws.Trim() -eq '') { $value = $ws }
  726. $valNeedsObj = $true
  727. }
  728. elseif ($null -ne $value -and "$value" -match '\s') { $valNeedsObj = $true }
  729. }
  730. if ($userPresNode -or $valueIsArrayFlag -or $valueTypeAttr -or $fiPres -or $valNeedsObj) {
  731. $obj = [ordered]@{ field = $field; op = $op }
  732. if ($op -notin $noValueOps -and $null -ne $value) {
  733. if ($valueIsArrayFlag) {
  734. $arrAsList = New-Object System.Collections.ArrayList
  735. foreach ($vv in @($value)) { [void]$arrAsList.Add($vv) }
  736. $obj['value'] = $arrAsList
  737. } else {
  738. $obj['value'] = $value
  739. }
  740. }
  741. if ($valueTypeAttr) { $obj['valueType'] = $valueTypeAttr }
  742. if ($use -eq 'false') { $obj['use'] = $false }
  743. if ($userId) { $obj['userSettingID'] = 'auto' }
  744. if ($fiPres) { $obj['presentation'] = $fiPres }
  745. if ($viewMode) { $obj['viewMode'] = $viewMode }
  746. if ($userPresNode) { $obj['userSettingPresentation'] = Get-PresText $userPresNode }
  747. return $obj
  748. }
  749. $s = $field
  750. if ($op -in $noValueOps) {
  751. $s += " $op"
  752. } else {
  753. $vDisplay = '_'
  754. if ($null -ne $value) {
  755. if ($value -is [bool]) { $vDisplay = if ($value) { 'true' } else { 'false' } }
  756. elseif ("$value" -ne '') { $vDisplay = "$value" }
  757. }
  758. $s += " $op $vDisplay"
  759. }
  760. if ($flags) { $s += ' ' + ($flags -join ' ') }
  761. return $s
  762. }
  763. # Рекурсивный хелпер одного элемента selection (для conditionalAppearance).
  764. function Build-SelectionItem {
  765. param($item, [string]$loc)
  766. $xt = Get-LocalXsiType $item
  767. if (-not $xt) {
  768. $fName = Get-Text $item "dcsset:field"
  769. if ($fName) { return $fName }
  770. $fieldEl = $item.SelectSingleNode("dcsset:field", $ns)
  771. if ($fieldEl) { return 'Auto' }
  772. }
  773. switch ($xt) {
  774. 'SelectedItemAuto' {
  775. $useV = Get-Text $item "dcsset:use"
  776. if ($useV -eq 'false') {
  777. return [ordered]@{ auto = $true; use = $false }
  778. }
  779. return 'Auto'
  780. }
  781. 'SelectedItemField' {
  782. $fName = Get-Text $item "dcsset:field"
  783. $titleNode = $item.SelectSingleNode("dcsset:lwsTitle", $ns)
  784. $title = Get-MLText $titleNode
  785. $vmN = $item.SelectSingleNode("dcsset:viewMode", $ns)
  786. $useV = Get-Text $item "dcsset:use"
  787. $useFalse = ($useV -eq 'false')
  788. if ($title -or $vmN -or $useFalse) {
  789. $obj = [ordered]@{ field = $fName }
  790. if ($useFalse) { $obj['use'] = $false }
  791. if ($title) { $obj['title'] = $title }
  792. if ($vmN) { $obj['viewMode'] = $vmN.InnerText }
  793. return $obj
  794. }
  795. return $fName
  796. }
  797. 'SelectedItemFolder' {
  798. $titleNode = $item.SelectSingleNode("dcsset:lwsTitle", $ns)
  799. $folderTitle = Get-MLText $titleNode
  800. $inner = @()
  801. foreach ($sub in $item.SelectNodes("dcsset:item", $ns)) {
  802. $bi = (Build-SelectionItem -item $sub -loc "$loc/folder")
  803. if ($null -ne $bi) { $inner += $bi }
  804. }
  805. $entry = [ordered]@{ folder = $folderTitle; items = $inner }
  806. $folderField = Get-Text $item "dcsset:field"
  807. if ($folderField) { $entry['field'] = $folderField }
  808. $plN = $item.SelectSingleNode("dcsset:placement", $ns)
  809. if ($plN -and $plN.InnerText -and $plN.InnerText -ne 'Auto') {
  810. $entry['placement'] = $plN.InnerText
  811. }
  812. return $entry
  813. }
  814. default {
  815. [Console]::Error.WriteLine("form-decompile: пропущен элемент selection неизвестного типа '$xt' (path: $loc)")
  816. return $null
  817. }
  818. }
  819. }
  820. # Build selection items array (для conditionalAppearance).
  821. function Build-Selection {
  822. param($selNode, [string]$loc)
  823. if (-not $selNode) { return @() }
  824. $out = @()
  825. foreach ($it in $selNode.SelectNodes("dcsset:item", $ns)) {
  826. $bi = (Build-SelectionItem -item $it -loc $loc)
  827. if ($null -ne $bi) { $out += $bi }
  828. }
  829. return ,$out
  830. }
  831. # Build order items array.
  832. function Build-Order {
  833. param($ordNode, [string]$loc)
  834. if (-not $ordNode) { return @() }
  835. $out = @()
  836. foreach ($it in $ordNode.SelectNodes("dcsset:item", $ns)) {
  837. $xt = Get-LocalXsiType $it
  838. switch ($xt) {
  839. 'OrderItemAuto' { $out += 'Auto' }
  840. 'OrderItemField' {
  841. $fn = Get-Text $it "dcsset:field"
  842. $ot = Get-Text $it "dcsset:orderType"
  843. $vmN = $it.SelectSingleNode("dcsset:viewMode", $ns)
  844. $useV = Get-Text $it "dcsset:use"
  845. $useFalse = ($useV -eq 'false')
  846. if ($vmN -or $useFalse) {
  847. $obj = [ordered]@{ field = $fn }
  848. if ($useFalse) { $obj['use'] = $false }
  849. if ($ot -eq 'Desc') { $obj['direction'] = 'desc' }
  850. if ($vmN) { $obj['viewMode'] = $vmN.InnerText }
  851. $out += $obj
  852. } else {
  853. if ($ot -eq 'Desc') { $out += "$fn desc" } else { $out += $fn }
  854. }
  855. }
  856. default {
  857. [Console]::Error.WriteLine("form-decompile: пропущен элемент сортировки неизвестного типа '$xt' (path: $loc)")
  858. }
  859. }
  860. }
  861. return ,$out
  862. }
  863. # Build appearance dict из <dcsset:appearance> (Line/Font/multilang/nested items).
  864. function Get-SettingsAppearance {
  865. param($appNode)
  866. if (-not $appNode) { return $null }
  867. $dict = [ordered]@{}
  868. foreach ($it in $appNode.SelectNodes("dcscor:item", $ns)) {
  869. $pName = Get-Text $it "dcscor:parameter"
  870. $val = $it.SelectSingleNode("dcscor:value", $ns)
  871. if (-not $pName -or -not $val) { continue }
  872. $rawVal = Read-AppearanceValueNode $val
  873. $useV = Get-Text $it "dcscor:use"
  874. $nestedItems = [ordered]@{}
  875. foreach ($sub in $it.SelectNodes("dcscor:item", $ns)) {
  876. $subName = Get-Text $sub "dcscor:parameter"
  877. $subVal = $sub.SelectSingleNode("dcscor:value", $ns)
  878. if (-not $subName) { continue }
  879. $subRaw = Read-AppearanceValueNode $subVal
  880. $subUse = Get-Text $sub "dcscor:use"
  881. $subEntry = [ordered]@{ value = $subRaw }
  882. if ($subUse -eq 'false') { $subEntry['use'] = $false }
  883. $nestedItems[$subName] = $subEntry
  884. }
  885. $valIsLine = ($rawVal -is [System.Collections.IDictionary]) -and $rawVal.Contains('@type') -and ($rawVal['@type'] -eq 'Line')
  886. if ($valIsLine) {
  887. if ($useV -eq 'false') { $rawVal['use'] = $false }
  888. if ($nestedItems.Count -gt 0) { $rawVal['items'] = $nestedItems }
  889. $dict[$pName] = $rawVal
  890. } elseif (($useV -eq 'false') -or ($nestedItems.Count -gt 0)) {
  891. $wrap = [ordered]@{ value = $rawVal }
  892. if ($useV -eq 'false') { $wrap['use'] = $false }
  893. if ($nestedItems.Count -gt 0) { $wrap['items'] = $nestedItems }
  894. $dict[$pName] = $wrap
  895. } else {
  896. $dict[$pName] = $rawVal
  897. }
  898. }
  899. return $dict
  900. }
  901. # Build conditionalAppearance array.
  902. function Build-ConditionalAppearance {
  903. param($caNode, [string]$loc)
  904. if (-not $caNode) { return @() }
  905. $out = @()
  906. $i = 0
  907. foreach ($it in $caNode.SelectNodes("dcsset:item", $ns)) {
  908. $entry = [ordered]@{}
  909. $scopeNode = $it.SelectSingleNode("dcsset:scope", $ns)
  910. if ($scopeNode -and $scopeNode.HasChildNodes) {
  911. [Console]::Error.WriteLine("form-decompile: conditionalAppearance item имеет scope — не воспроизводится в DSL (path: $loc/$i/scope)")
  912. }
  913. $selNode = $it.SelectSingleNode("dcsset:selection", $ns)
  914. if ($selNode -and $selNode.SelectNodes("dcsset:item", $ns).Count -gt 0) {
  915. $entry['selection'] = Build-Selection -selNode $selNode -loc "$loc/$i/selection"
  916. }
  917. $filterNode = $it.SelectSingleNode("dcsset:filter", $ns)
  918. if ($filterNode -and $filterNode.SelectNodes("dcsset:item", $ns).Count -gt 0) {
  919. $f = @()
  920. foreach ($fc in $filterNode.SelectNodes("dcsset:item", $ns)) {
  921. $bi = (Build-FilterItem -itemNode $fc -loc "$loc/$i/filter")
  922. if ($null -ne $bi) { $f += $bi }
  923. }
  924. $entry['filter'] = $f
  925. }
  926. $appNode = $it.SelectSingleNode("dcsset:appearance", $ns)
  927. $ap = Get-SettingsAppearance $appNode
  928. if ($ap -and $ap.Count -gt 0) { $entry['appearance'] = $ap }
  929. $presNode = $it.SelectSingleNode("dcsset:presentation", $ns)
  930. if ($presNode) {
  931. # Сохраняем форму по xsi:type: LocalStringType (даже ru-only) → объект → компилятор эмитит LocalStringType.
  932. $pres = Get-PresByType $presNode
  933. if ($null -ne $pres -and $pres -ne '') { $entry['presentation'] = $pres }
  934. }
  935. $vmN = $it.SelectSingleNode("dcsset:viewMode", $ns)
  936. if ($vmN) { $entry['viewMode'] = $vmN.InnerText }
  937. $usid = Get-Text $it "dcsset:userSettingID"
  938. if ($usid) { $entry['userSettingID'] = 'auto' }
  939. $uspN = $it.SelectSingleNode("dcsset:userSettingPresentation", $ns)
  940. if ($uspN) {
  941. $usp = Get-PresText $uspN
  942. if ($usp) { $entry['userSettingPresentation'] = $usp }
  943. }
  944. $useV = Get-Text $it "dcsset:use"
  945. if ($useV -eq 'false') { $entry['use'] = $false }
  946. $useInDontUse = @()
  947. foreach ($ch in $it.ChildNodes) {
  948. if ($ch.NodeType -ne 'Element' -or $ch.NamespaceURI -ne $NS_DCSSET) { continue }
  949. if ($ch.LocalName -match '^useIn(.+)$' -and $ch.InnerText -eq 'DontUse') {
  950. $shortName = ($matches[1]).Substring(0, 1).ToLower() + ($matches[1]).Substring(1)
  951. $useInDontUse += $shortName
  952. }
  953. }
  954. if ($useInDontUse.Count -gt 0) { $entry['useInDontUse'] = $useInDontUse }
  955. $out += $entry
  956. $i++
  957. }
  958. return ,$out
  959. }
  960. # Общие layout-свойства → в $obj (симметрично Emit-Layout компилятора).
  961. # Вызывается один раз для любого элемента. Height тут — высота элемента (<Height>),
  962. # в т.ч. у Table; высоту в строках (<HeightInTableRows>) Table ловит отдельно в heightInTableRows.
  963. function Add-Layout {
  964. param($obj, $node)
  965. # Общие свойства элемента (любой тип): default/drag/skip
  966. if ((Get-Child $node 'DefaultItem') -eq 'true') { $obj['defaultItem'] = $true }
  967. $soi = Get-Child $node 'SkipOnInput'; if ($null -ne $soi) { $obj['skipOnInput'] = ($soi -eq 'true') }
  968. # EnableStartDrag/EnableDrag — фактическое значение (платформа эмитит и явный false, напр. SpreadSheet)
  969. $esd = Get-Child $node 'EnableStartDrag'; if ($null -ne $esd) { $obj['enableStartDrag'] = ($esd -eq 'true') }
  970. $edr = Get-Child $node 'EnableDrag'; if ($null -ne $edr) { $obj['enableDrag'] = ($edr -eq 'true') }
  971. $fdm = Get-Child $node 'FileDragMode'; if ($fdm) { $obj['fileDragMode'] = $fdm }
  972. # AutoMaxWidth: компилятор додумывает false для multiLine-input без явного ключа (multiLineDefault).
  973. # Захват факт. значения; multiLine-input без тега → autoMaxWidth:true (суппресс эвристики).
  974. $amwNode = Get-Child $node 'AutoMaxWidth'
  975. if ($amwNode -eq 'false') { $obj['autoMaxWidth'] = $false }
  976. elseif ($amwNode -eq 'true') { $obj['autoMaxWidth'] = $true }
  977. elseif ((Get-Child $node 'MultiLine') -eq 'true') { $obj['autoMaxWidth'] = $true }
  978. $mw = Get-Child $node 'MaxWidth'; if ($mw) { $obj['maxWidth'] = [int]$mw }
  979. if ((Get-Child $node 'AutoMaxHeight') -eq 'false') { $obj['autoMaxHeight'] = $false }
  980. $mh = Get-Child $node 'MaxHeight'; if ($mh) { $obj['maxHeight'] = [int]$mh }
  981. $w = Get-Child $node 'Width'; if ($w) { $obj['width'] = [int]$w }
  982. $h = Get-Child $node 'Height'; if ($h) { $obj['height'] = [int]$h }
  983. # Stretch: захват фактического значения (true И false — платформа эмитит явное)
  984. $hs = Get-Child $node 'HorizontalStretch'; if ($null -ne $hs) { $obj['horizontalStretch'] = ($hs -eq 'true') }
  985. $vs = Get-Child $node 'VerticalStretch'; if ($null -ne $vs) { $obj['verticalStretch'] = ($vs -eq 'true') }
  986. $gha = Get-Child $node 'GroupHorizontalAlign'; if ($gha) { $obj['groupHorizontalAlign'] = $gha }
  987. $gva = Get-Child $node 'GroupVerticalAlign'; if ($gva) { $obj['groupVerticalAlign'] = $gva }
  988. $ha = Get-Child $node 'HorizontalAlign'; if ($ha) { $obj['horizontalAlign'] = $ha }
  989. # Cell-свойства поля в таблице (общие для Input/Label/Picture/CheckBox): захват «как есть»
  990. foreach ($p in @('ShowInHeader','ShowInFooter','AutoCellHeight')) {
  991. $v = Get-Child $node $p; if ($null -ne $v) { $obj[($p.Substring(0,1).ToLower()+$p.Substring(1))] = ($v -eq 'true') }
  992. }
  993. $fha = Get-Child $node 'FooterHorizontalAlign'; if ($fha) { $obj['footerHorizontalAlign'] = $fha }
  994. $hha = Get-Child $node 'HeaderHorizontalAlign'; if ($hha) { $obj['headerHorizontalAlign'] = $hha }
  995. # ColumnGroup: динамический заголовок из данных + формат заголовка (ML-текст)
  996. $hdp = Get-Child $node 'HeaderDataPath'; if ($hdp) { $obj['headerDataPath'] = $hdp }
  997. $hfNode = $node.SelectSingleNode("lf:HeaderFormat", $ns); if ($hfNode) { $hf = Get-LangText $hfNode; if ($null -ne $hf) { $obj['headerFormat'] = $hf } }
  998. }
  999. # TitleLocation у check/radio (зеркало Emit-TitleLocation):
  1000. # тега нет → "" (дефолт платформы); значение = умный дефолт → опускаем; иначе пишем.
  1001. function Add-TitleLocation {
  1002. param($obj, $node, [string]$smartDefault)
  1003. $tl = Get-Child $node 'TitleLocation'
  1004. if ($null -eq $tl) { $obj['titleLocation'] = '' }
  1005. elseif ($tl -ne $smartDefault) { $obj['titleLocation'] = $tl.ToLower() }
  1006. }
  1007. # Разобрать <Events> формы или элемента → упорядоченная мапа { ИмяСобытия: ИмяОбработчика }
  1008. # в порядке документа. Имена обработчиков всегда явные. Привязка с видом вызова (расширение) —
  1009. # { handler, callType }; несколько привязок одного события (Before и After) — массив таких объектов.
  1010. function Get-Events {
  1011. param($node, [string]$elName)
  1012. $ev = $node.SelectSingleNode("lf:Events", $ns)
  1013. if (-not $ev) { return $null }
  1014. $events = [ordered]@{}
  1015. foreach ($e in @($ev.SelectNodes("lf:Event", $ns))) {
  1016. $n = $e.GetAttribute("name"); $ct = $e.GetAttribute("callType")
  1017. $v = if ($ct) { [ordered]@{ handler = $e.InnerText; callType = $ct } } else { $e.InnerText }
  1018. if ($events.Contains($n)) { $events[$n] = @(@($events[$n]) + , $v) } else { $events[$n] = $v }
  1019. }
  1020. if ($events.Count -eq 0) { return $null }
  1021. return $events
  1022. }
  1023. # Инверсия Emit-XrFlag: role-adjustable boolean (UserVisible/View/Edit/Use).
  1024. # <TAG><xr:Common/>[<xr:Value name="Role.X"/>…]</TAG> → скаляр bool (без ролей) или объект { common, roles:{Имя:bool} }.
  1025. # Имя роли отдаём без префикса "Role.". Возвращает $null, если тег отсутствует.
  1026. function Decompile-XrFlag {
  1027. param($node, [string]$tag)
  1028. $el = $node.SelectSingleNode("*[local-name()='$tag']")
  1029. if (-not $el) { return $null }
  1030. $commonNode = $el.SelectSingleNode("*[local-name()='Common']")
  1031. $common = ($commonNode -and $commonNode.InnerText -eq 'true')
  1032. $valNodes = @($el.SelectNodes("*[local-name()='Value']"))
  1033. if ($valNodes.Count -eq 0) { return $common }
  1034. $roles = [ordered]@{}
  1035. foreach ($v in $valNodes) {
  1036. $rn = $v.GetAttribute("name")
  1037. if ($rn -match '^Role\.') { $rn = $rn.Substring(5) }
  1038. $roles[$rn] = ($v.InnerText -eq 'true')
  1039. }
  1040. $o = [ordered]@{}
  1041. $o['common'] = $common
  1042. $o['roles'] = $roles
  1043. return $o
  1044. }
  1045. # Командный интерфейс формы (<CommandInterface>): панели CommandBar + NavigationPanel,
  1046. # каждая — список переопределений команд (платформа эмитит ТОЛЬКО отклонения от авто-расстановки).
  1047. # Элемент: command (verbatim, "0"=пустой) + type (Auto опускаем) + attribute/group(CommandGroup)/index +
  1048. # defaultVisible(bool) + visible(xr-flag bool/{common,roles} — тот же механизм, что userVisible).
  1049. # Голый элемент (только команда, Type=Auto) → строковый shorthand.
  1050. function Decompile-CommandInterface {
  1051. $ciNode = $root.SelectSingleNode("lf:CommandInterface", $ns)
  1052. if (-not $ciNode) { return $null }
  1053. $ci = [ordered]@{}
  1054. foreach ($panel in @(@('CommandBar','commandBar'), @('NavigationPanel','navigationPanel'))) {
  1055. $pn = $ciNode.SelectSingleNode("lf:$($panel[0])", $ns)
  1056. if (-not $pn) { continue }
  1057. $items = New-Object System.Collections.ArrayList
  1058. foreach ($it in @($pn.SelectNodes("lf:Item", $ns))) {
  1059. $o = [ordered]@{}
  1060. $cmd = Get-Child $it 'Command'
  1061. $o['command'] = "$cmd"
  1062. $ty = Get-Child $it 'Type'; if ($ty -and $ty -ne 'Auto') { $o['type'] = $ty }
  1063. $at = Get-Child $it 'Attribute'; if ($at) { $o['attribute'] = $at }
  1064. $cg = Get-Child $it 'CommandGroup'; if ($cg) { $o['group'] = $cg }
  1065. $idx = Get-Child $it 'Index'; if ($null -ne $idx) { $o['index'] = [int]$idx }
  1066. $dv = Get-Child $it 'DefaultVisible'; if ($null -ne $dv) { $o['defaultVisible'] = ($dv -eq 'true') }
  1067. $vis = Decompile-XrFlag $it 'Visible'; if ($null -ne $vis) { $o['visible'] = $vis }
  1068. # Голый элемент (только command) → строка-shorthand; иначе объект
  1069. if ($o.Count -eq 1) { [void]$items.Add("$cmd") } else { [void]$items.Add($o) }
  1070. }
  1071. if ($items.Count -gt 0) { $ci[$panel[1]] = @($items) }
  1072. }
  1073. if ($ci.Count -gt 0) { return $ci }
  1074. return $null
  1075. }
  1076. # <FunctionalOptions><Item>FunctionalOption.X</Item>…> → массив строк (префикс FunctionalOption. снят; GUID — как есть).
  1077. function Decompile-FunctionalOptions {
  1078. param($node)
  1079. $foNode = $node.SelectSingleNode("lf:FunctionalOptions", $ns)
  1080. if (-not $foNode) { return $null }
  1081. $opts = New-Object System.Collections.ArrayList
  1082. foreach ($it in @($foNode.SelectNodes("lf:Item", $ns))) {
  1083. $t = $it.InnerText.Trim() -replace '^FunctionalOption\.', ''
  1084. [void]$opts.Add($t)
  1085. }
  1086. if ($opts.Count -gt 0) { return ,@($opts) }
  1087. return $null
  1088. }
  1089. # Колонка реквизита (прямая или внутри AdditionalColumns): name/type/title/functionalOptions.
  1090. function Decompile-AttrColumn {
  1091. param($c)
  1092. $co = [ordered]@{}; $co['name'] = $c.GetAttribute("name")
  1093. $cty = Decompile-Type ($c.SelectSingleNode("lf:Type", $ns)); if ($cty) { $co['type'] = $cty }
  1094. $ctNode = $c.SelectSingleNode("lf:Title", $ns); if ($ctNode) { $t = Get-LangTextWS $ctNode; if ($null -ne $t) { $co['title'] = $t } }
  1095. $cfc = Get-Child $c 'FillCheck'; if ($cfc) { $co['fillCheck'] = $cfc } # проверка заполнения колонки (как у реквизита)
  1096. $cfo = Decompile-FunctionalOptions $c; if ($cfo) { $co['functionalOptions'] = $cfo }
  1097. # Ролевой доступ колонки (View/Edit) — xr-флаг, как у самого реквизита (bool | {common,roles})
  1098. $cv = Decompile-XrFlag $c 'View'; if ($null -ne $cv) { $co['view'] = $cv }
  1099. $ce = Decompile-XrFlag $c 'Edit'; if ($null -ne $ce) { $co['edit'] = $ce }
  1100. return $co
  1101. }
  1102. # Общие свойства элемента (visible/enabled/readonly/title/events) → в hash
  1103. # Картинка-ссылка с прозрачностью (HeaderPicture/FooterPicture/ValuesPicture/Page Picture).
  1104. # Платформа ВСЕГДА эмитит <xr:LoadTransparent> (и true, и false) → дефолт DSL = false.
  1105. # Источник: <xr:Ref> (именованная/стилевая) ИЛИ <xr:Abs> (встроенная → префикс "abs:").
  1106. # Скаляр (src) при loadTransparent=false и без TransparentPixel; иначе объект
  1107. # {src, loadTransparent?, transparentPixel?}.
  1108. function Get-PictureRef {
  1109. param($node, [string]$picTag)
  1110. $ref = $node.SelectSingleNode("lf:$picTag/xr:Ref", $ns)
  1111. $abs = $node.SelectSingleNode("lf:$picTag/xr:Abs", $ns)
  1112. if (-not $ref -and -not $abs) { return $null }
  1113. $src = if ($ref) { $ref.InnerText } else { "abs:$($abs.InnerText)" }
  1114. $lt = $node.SelectSingleNode("lf:$picTag/xr:LoadTransparent", $ns)
  1115. $ltTrue = ($lt -and $lt.InnerText -eq 'true')
  1116. $tpx = $node.SelectSingleNode("lf:$picTag/xr:TransparentPixel", $ns)
  1117. if (-not $ltTrue -and -not $tpx) { return $src }
  1118. $o = [ordered]@{ src = $src }
  1119. if ($ltTrue) { $o['loadTransparent'] = $true }
  1120. if ($tpx) { $o['transparentPixel'] = [ordered]@{ x = [int]$tpx.GetAttribute('x'); y = [int]$tpx.GetAttribute('y') } }
  1121. return $o
  1122. }
  1123. # <Picture> кнопки/попапа/команды. Дефолт LoadTransparent=true (обратная конвенция к header/values):
  1124. # фиксируем только отклонение false. Источник <xr:Ref> или <xr:Abs> (→ "abs:"). При наличии
  1125. # <xr:TransparentPixel> → объектная форма {src, loadTransparent?, transparentPixel}, иначе скаляр picture
  1126. # + отдельный loadTransparent:false.
  1127. function Set-CommandPicture {
  1128. param($obj, $node)
  1129. $ref = $node.SelectSingleNode("lf:Picture/xr:Ref", $ns)
  1130. $abs = $node.SelectSingleNode("lf:Picture/xr:Abs", $ns)
  1131. if (-not $ref -and -not $abs) { return }
  1132. $src = if ($ref) { $ref.InnerText } else { "abs:$($abs.InnerText)" }
  1133. $lt = $node.SelectSingleNode("lf:Picture/xr:LoadTransparent", $ns)
  1134. $ltFalse = ($lt -and $lt.InnerText -eq 'false')
  1135. $tpx = $node.SelectSingleNode("lf:Picture/xr:TransparentPixel", $ns)
  1136. if ($tpx) {
  1137. $o = [ordered]@{ src = $src }
  1138. if ($ltFalse) { $o['loadTransparent'] = $false }
  1139. $o['transparentPixel'] = [ordered]@{ x = [int]$tpx.GetAttribute('x'); y = [int]$tpx.GetAttribute('y') }
  1140. $obj['picture'] = $o
  1141. } else {
  1142. $obj['picture'] = $src
  1143. if ($ltFalse) { $obj['loadTransparent'] = $false }
  1144. }
  1145. }
  1146. # Шрифт <Font ...> → строка-ref (если только ref+kind=StyleItem) или объект-атрибуты.
  1147. function Build-FontValue {
  1148. param($f)
  1149. $present = @()
  1150. foreach ($a in @('ref','faceName','height','bold','italic','underline','strikeout','kind','scale')) {
  1151. if ($f.HasAttribute($a)) { $present += $a }
  1152. }
  1153. # Чистый style-ref (ref + kind=StyleItem) → строка-шорткат
  1154. if ($present.Count -eq 2 -and ($present -contains 'ref') -and $f.GetAttribute('kind') -eq 'StyleItem') {
  1155. return $f.GetAttribute('ref')
  1156. }
  1157. $o = [ordered]@{}
  1158. foreach ($k in $present) {
  1159. $v = $f.GetAttribute($k)
  1160. if ($k -in @('height','scale') -and $v -match '^-?\d+$') { $o[$k] = [int]$v }
  1161. elseif ($k -in @('bold','italic','underline','strikeout')) { $o[$k] = ($v -eq 'true') }
  1162. else { $o[$k] = $v }
  1163. }
  1164. return $o
  1165. }
  1166. # Граница <Border> → строка-ref (из стиля) или объект {width, style}.
  1167. function Build-BorderValue {
  1168. param($b)
  1169. if ($b.HasAttribute('ref')) { return $b.GetAttribute('ref') }
  1170. $o = [ordered]@{}
  1171. if ($b.HasAttribute('width')) { $w = $b.GetAttribute('width'); $o['width'] = if ($w -match '^-?\d+$') { [int]$w } else { $w } }
  1172. $st = $b.SelectSingleNode("v8ui:style", $ns)
  1173. if ($st) { $o['style'] = $st.InnerText }
  1174. return $o
  1175. }
  1176. # Оформление элемента (цвета/шрифты/граница) → canonical DSL-ключи. Цвет — verbatim-строка.
  1177. function Add-Appearance {
  1178. param($obj, $node)
  1179. $colorMap = @{
  1180. 'TitleTextColor'='titleTextColor'; 'TitleBackColor'='titleBackColor'
  1181. 'FooterTextColor'='footerTextColor'; 'FooterBackColor'='footerBackColor'
  1182. 'TextColor'='textColor'; 'BackColor'='backColor'; 'BorderColor'='borderColor'
  1183. }
  1184. foreach ($tag in $colorMap.Keys) {
  1185. $c = $node.SelectSingleNode("lf:$tag", $ns)
  1186. if ($c) { $obj[$colorMap[$tag]] = $c.InnerText }
  1187. }
  1188. foreach ($pair in @(@('Font','font'), @('TitleFont','titleFont'), @('FooterFont','footerFont'))) {
  1189. $f = $node.SelectSingleNode("lf:$($pair[0])", $ns)
  1190. if ($f) { $obj[$pair[1]] = (Build-FontValue $f) }
  1191. }
  1192. $b = $node.SelectSingleNode("lf:Border", $ns)
  1193. if ($b) { $obj['border'] = (Build-BorderValue $b) }
  1194. }
  1195. function Add-CommonProps {
  1196. param($obj, $node, [string]$elName)
  1197. Add-Appearance $obj $node
  1198. if ((Get-Child $node 'Visible') -eq 'false') { $obj['hidden'] = $true }
  1199. if ((Get-Child $node 'Enabled') -eq 'false') { $obj['disabled'] = $true }
  1200. if ((Get-Child $node 'ReadOnly') -eq 'true') { $obj['readOnly'] = $true }
  1201. $uv = Decompile-XrFlag $node 'UserVisible'; if ($null -ne $uv) { $obj['userVisible'] = $uv }
  1202. $titleNode = $node.SelectSingleNode("lf:Title", $ns)
  1203. if ($titleNode) {
  1204. $t = Get-LangTextWS $titleNode # восстановление значимого пробела (whitespace-заголовок)
  1205. if ($null -ne $t) { $obj['title'] = $t }
  1206. # formatted у LabelDecoration выводится компилятором из hyperlink — отдельный ключ не нужен (#16 хвост)
  1207. }
  1208. $ttNode = $node.SelectSingleNode("lf:ToolTip", $ns)
  1209. if ($ttNode) { $tt = Get-LangTextWS $ttNode; if ($null -ne $tt) { $obj['tooltip'] = $tt } }
  1210. $ttr = Get-Child $node 'ToolTipRepresentation'; if ($ttr) { $obj['tooltipRepresentation'] = $ttr }
  1211. # Картинки заголовка/подвала колонки (любой field-тип, эмитятся платформой как column header/footer icon)
  1212. $hp = Get-PictureRef $node 'HeaderPicture'; if ($null -ne $hp) { $obj['headerPicture'] = $hp }
  1213. $fp = Get-PictureRef $node 'FooterPicture'; if ($null -ne $fp) { $obj['footerPicture'] = $fp }
  1214. $ev = Get-Events $node $elName
  1215. if ($ev) { $obj['events'] = $ev }
  1216. # CommandSet — общий для полей (input/label/check/spreadsheet/html/formatted/picture):
  1217. # список отключённых команд редактора. Только <ExcludedCommand>, пустого не бывает.
  1218. $csNode = $node.SelectSingleNode("lf:CommandSet", $ns)
  1219. if ($csNode) {
  1220. $exc = New-Object System.Collections.ArrayList
  1221. foreach ($ec in @($csNode.SelectNodes("lf:ExcludedCommand", $ns))) { [void]$exc.Add($ec.InnerText) }
  1222. if ($exc.Count -gt 0) { $obj['excludedCommands'] = @($exc) }
  1223. }
  1224. }
  1225. # --- 3. Type decompile (inverse of Emit-Type) ---
  1226. function Decompile-Type {
  1227. param($typeNode)
  1228. if (-not $typeNode) { return $null }
  1229. $parts = New-Object System.Collections.ArrayList
  1230. foreach ($vt in @($typeNode.SelectNodes("v8:Type", $ns))) {
  1231. $raw = $vt.InnerText.Trim()
  1232. $short = $raw
  1233. # break обязателен: иначе общий case ^(v8|v8ui|cfg): перетирает специфичные (напр. v8:ValueListType → ValueList).
  1234. switch -regex ($raw) {
  1235. '^xs:string$' {
  1236. $len = $typeNode.SelectSingleNode("v8:StringQualifiers/v8:Length", $ns)
  1237. $al = $typeNode.SelectSingleNode("v8:StringQualifiers/v8:AllowedLength", $ns)
  1238. $fixed = ($al -and $al.InnerText -eq 'Fixed') # Variable = дефолт (опускаем); Fixed — явно
  1239. $ll = if ($len) { $len.InnerText } else { '0' }
  1240. if ($fixed -and [int]$ll -gt 0) { $short = "string($ll,fixed)" } # Fixed при длине 0 платформа не хранит
  1241. elseif ([int]$ll -gt 0) { $short = "string($ll)" }
  1242. else { $short = "string" } # голая строка у form-compile — неограниченная
  1243. break
  1244. }
  1245. '^xs:decimal$' {
  1246. $d = $typeNode.SelectSingleNode("v8:NumberQualifiers/v8:Digits", $ns)
  1247. $f = $typeNode.SelectSingleNode("v8:NumberQualifiers/v8:FractionDigits", $ns)
  1248. $sgn = $typeNode.SelectSingleNode("v8:NumberQualifiers/v8:AllowedSign", $ns)
  1249. $dd = if ($d) { $d.InnerText } else { '0' }
  1250. $ff = if ($f) { $f.InnerText } else { '0' }
  1251. if ($sgn -and $sgn.InnerText -eq 'Nonnegative') { $short = "decimal($dd,$ff,nonneg)" }
  1252. elseif ($dd -eq '10' -and $ff -eq '0') { $short = "decimal" } # голое число у form-compile — 10,0
  1253. else { $short = "decimal($dd,$ff)" }
  1254. break
  1255. }
  1256. '^xs:boolean$' { $short = "boolean"; break }
  1257. '^xs:dateTime$' {
  1258. $df = $typeNode.SelectSingleNode("v8:DateQualifiers/v8:DateFractions", $ns)
  1259. $dfv = if ($df) { $df.InnerText } else { 'DateTime' }
  1260. switch ($dfv) { 'Date' { $short = 'date' } 'Time' { $short = 'time' } default { $short = 'dateTime' } }
  1261. break
  1262. }
  1263. '^cfg:(.+)$' { $short = $matches[1]; break }
  1264. '^(v8|v8ui):' {
  1265. # Платформенный тип: friendly-шорткат если есть, иначе оставляем с префиксом
  1266. # (компилятор эмитит verbatim) — чтобы не терять v8:UUID и прочий хвост.
  1267. $rev = @{
  1268. 'v8:ValueTable'='ValueTable'; 'v8:ValueTree'='ValueTree'; 'v8:ValueListType'='ValueList'
  1269. 'v8:TypeDescription'='TypeDescription'; 'v8:Universal'='Universal'
  1270. 'v8:FixedArray'='FixedArray'; 'v8:FixedStructure'='FixedStructure'
  1271. 'v8ui:FormattedString'='FormattedString'; 'v8ui:Picture'='Picture'; 'v8ui:Color'='Color'; 'v8ui:Font'='Font'
  1272. }
  1273. if ($rev.ContainsKey($raw)) { $short = $rev[$raw] } else { $short = $raw }
  1274. break
  1275. }
  1276. default { $short = $raw }
  1277. }
  1278. [void]$parts.Add($short)
  1279. }
  1280. # TypeSet (набор типов): определяемый тип / характеристика / «любая ссылка вида».
  1281. # Префикс cfg:/v8: снимаем — обратный роутинг в компиляторе по форме токена.
  1282. foreach ($ts in @($typeNode.SelectNodes("v8:TypeSet", $ns))) {
  1283. $raw = $ts.InnerText.Trim()
  1284. $short = $raw -replace '^(v8ui|v8|cfg):', ''
  1285. [void]$parts.Add($short)
  1286. }
  1287. # TypeId — тип, заданный глобальным стабильным GUID (<v8:TypeId>, не <v8:Type>). Платформа так
  1288. # сериализует типы, чьё имя в этом контексте недоступно (определяемые/характеристики). GUID глобально
  1289. # стабилен → эмитим verbatim как маркер 'typeid:GUID' (компилятор разворачивает обратно; как роль-по-GUID).
  1290. foreach ($ti in @($typeNode.SelectNodes("v8:TypeId", $ns))) {
  1291. [void]$parts.Add("typeid:" + $ti.InnerText.Trim())
  1292. }
  1293. if ($parts.Count -eq 0) { return $null }
  1294. if ($parts.Count -eq 1) { return $parts[0] }
  1295. return ($parts -join ' | ')
  1296. }
  1297. # Ограничения использования (useRestriction/attributeUseRestriction) → объект {field?,condition?,group?,order?}.
  1298. function Build-RestrictObj {
  1299. param($node)
  1300. $r = [ordered]@{}
  1301. foreach ($k in 'field','condition','group','order') { if ((Get-Child $node $k) -eq 'true') { $r[$k] = $true } }
  1302. return $r
  1303. }
  1304. # Вычисляемое поле DataSet динамического списка (<CalculatedField>) → объектная модель.
  1305. # Зеркало эмиссии form-compile (Emit-CalcFields). Грамматика — как skd calculatedFields,
  1306. # + форм-extras presentationExpression/orderExpression (в namespace dcscommon).
  1307. function Build-CalcField {
  1308. param($cfNode)
  1309. $o = [ordered]@{}
  1310. $o['dataPath'] = Get-Child $cfNode 'dataPath'
  1311. $o['expression'] = Get-Child $cfNode 'expression'
  1312. $tn = $cfNode.SelectSingleNode("dcssch:title", $ns)
  1313. if ($tn) { $t = Get-LangText $tn; if ($null -ne $t) { $o['title'] = $t } }
  1314. $vt = $cfNode.SelectSingleNode("dcssch:valueType", $ns)
  1315. if ($vt) { $v = Decompile-Type $vt; if ($v) { $o['valueType'] = $v } }
  1316. $ur = $cfNode.SelectSingleNode("dcssch:useRestriction", $ns)
  1317. if ($ur) {
  1318. $r = [ordered]@{}
  1319. foreach ($k in 'field','condition','group','order') { if ((Get-Child $ur $k) -eq 'true') { $r[$k] = $true } }
  1320. if ($r.Count -gt 0) { $o['useRestriction'] = $r }
  1321. }
  1322. $pe = Get-Child $cfNode 'presentationExpression'
  1323. if ($null -ne $pe -and $pe -ne '') { $o['presentationExpression'] = $pe }
  1324. $oeNodes = @($cfNode.SelectNodes("dcssch:orderExpression", $ns))
  1325. if ($oeNodes.Count -gt 0) {
  1326. $oes = New-Object System.Collections.ArrayList
  1327. foreach ($oen in $oeNodes) {
  1328. $eo = [ordered]@{}
  1329. $exprN = $oen.SelectSingleNode("*[local-name()='expression']")
  1330. $otN = $oen.SelectSingleNode("*[local-name()='orderType']")
  1331. $aoN = $oen.SelectSingleNode("*[local-name()='autoOrder']")
  1332. $eo['expression'] = if ($exprN) { $exprN.InnerText } else { '' }
  1333. if ($otN -and $otN.InnerText -ne 'Asc') { $eo['orderType'] = $otN.InnerText }
  1334. if ($aoN -and $aoN.InnerText -eq 'true') { $eo['autoOrder'] = $true }
  1335. [void]$oes.Add($eo)
  1336. }
  1337. $o['orderExpression'] = @($oes)
  1338. }
  1339. return $o
  1340. }
  1341. # Schema-параметры динамического списка (<Parameter> под <Settings>) — зеркало эмиссии
  1342. # form-compile (Emit-DLParameters). Инверсия контекстных дефолтов: useRestriction=true и
  1343. # title==Title-FromName опускаем (компилятор восстановит). Сущность = DataCompositionSchemaParameter.
  1344. function Build-DLInputParameters {
  1345. param($ipNode)
  1346. $items = New-Object System.Collections.ArrayList
  1347. foreach ($it in @($ipNode.SelectNodes("dcscor:item", $ns))) {
  1348. $io = [ordered]@{}
  1349. $io['parameter'] = Get-Child $it 'parameter'
  1350. $useN = $it.SelectSingleNode("dcscor:use", $ns)
  1351. if ($useN -and $useN.InnerText -eq 'false') { $io['use'] = $false }
  1352. $valN = $it.SelectSingleNode("dcscor:value", $ns)
  1353. if ($valN) {
  1354. $vt = $valN.GetAttribute("type", $NS_XSI)
  1355. if ($vt -match 'ChoiceParameters$') {
  1356. $cps = New-Object System.Collections.ArrayList
  1357. foreach ($cpi in @($valN.SelectNodes("dcscor:item", $ns))) {
  1358. $cpo = [ordered]@{}
  1359. $cpo['name'] = Get-Child $cpi 'choiceParameter'
  1360. $vals = New-Object System.Collections.ArrayList
  1361. foreach ($cv in @($cpi.SelectNodes("dcscor:value", $ns))) {
  1362. [void]$vals.Add((Convert-TypedValue -raw $cv.InnerText -xsiType ($cv.GetAttribute("type", $NS_XSI))))
  1363. }
  1364. $cpo['values'] = @($vals)
  1365. [void]$cps.Add($cpo)
  1366. }
  1367. $io['choiceParameters'] = @($cps)
  1368. } elseif ($vt -match 'ChoiceParameterLinks$') {
  1369. $cpls = New-Object System.Collections.ArrayList
  1370. foreach ($cpi in @($valN.SelectNodes("dcscor:item", $ns))) {
  1371. $cpo = [ordered]@{}
  1372. $cpo['name'] = Get-Child $cpi 'choiceParameter'
  1373. $cpo['value'] = Get-Child $cpi 'value'
  1374. $md = Get-Child $cpi 'mode'; if ($md -and $md -ne 'Auto') { $cpo['mode'] = $md }
  1375. [void]$cpls.Add($cpo)
  1376. }
  1377. $io['choiceParameterLinks'] = @($cpls)
  1378. } elseif ($vt -match 'TypeLink$') {
  1379. # Связь по типу (dcscor:TypeLink): field + linkItem — структурное значение,
  1380. # НЕ склеивать InnerText в строку ("СчетДт"+"1"="СчетДт1").
  1381. $tlo = [ordered]@{}
  1382. $tlf = Get-Child $valN 'field'; if ($null -ne $tlf) { $tlo['field'] = $tlf }
  1383. $tli = Get-Child $valN 'linkItem'; if ($null -ne $tli) { $tlo['linkItem'] = if ($tli -match '^-?\d+$') { [int]$tli } else { $tli } }
  1384. $io['typeLink'] = $tlo
  1385. } else {
  1386. if ($valN.GetAttribute("nil", $NS_XSI) -ne 'true') { $io['value'] = Convert-TypedValue -raw $valN.InnerText -xsiType $vt }
  1387. }
  1388. }
  1389. [void]$items.Add($io)
  1390. }
  1391. return @($items)
  1392. }
  1393. # dcsset:dataParameters → массив (shorthand "Имя @off" для value-less / объект для типизированного
  1394. # значения). Грамматика зеркалит skd-compile Emit-DataParameters (form-контекст: значение опционально,
  1395. # в отличие от skd-settings). Без «auto»-компактизации (нужна машинерия сравнения с top-level).
  1396. function Build-FormDataParameters {
  1397. param($dpNode)
  1398. $entries = @()
  1399. foreach ($it in @($dpNode.SelectNodes("dcscor:item", $ns))) {
  1400. $pn = Get-Text $it "dcscor:parameter"
  1401. $use = Get-Text $it "dcscor:use"
  1402. $valNodes = @($it.SelectNodes("dcscor:value", $ns))
  1403. $valNode = if ($valNodes.Count -ge 1) { $valNodes[0] } else { $null }
  1404. $usidN = $it.SelectSingleNode("dcsset:userSettingID", $ns)
  1405. $vmN = $it.SelectSingleNode("dcsset:viewMode", $ns)
  1406. $uspN = $it.SelectSingleNode("dcsset:userSettingPresentation", $ns)
  1407. if ($valNode -or $usidN -or $vmN -or $uspN) {
  1408. $obj = [ordered]@{ parameter = $pn }
  1409. if ($valNodes.Count -gt 1) {
  1410. # Список значений параметра (valueListAllowed) — захватываем ВСЕ <dcscor:value> массивом
  1411. $obj['value'] = @($valNodes | ForEach-Object { $_.InnerText })
  1412. $vt0 = $valNodes[0].GetAttribute("type", $NS_XSI); if ($vt0) { $obj['valueType'] = $vt0 }
  1413. } elseif ($valNode) {
  1414. if ($valNode.GetAttribute("nil", $NS_XSI) -eq 'true') { $obj['nilValue'] = $true }
  1415. else {
  1416. $vType = $valNode.GetAttribute("type", $NS_XSI); $vVal = $valNode.InnerText
  1417. if ($vType -match 'decimal$' -and $vVal -match '^-?\d+$') { $obj['value'] = [int]$vVal }
  1418. elseif ($vType -match 'boolean$') { $obj['value'] = ($vVal -eq 'true') }
  1419. else { $obj['value'] = $vVal }
  1420. if ($vType) { $obj['valueType'] = $vType }
  1421. }
  1422. }
  1423. if ($use -eq 'false') { $obj['use'] = $false }
  1424. if ($usidN) { $obj['userSettingID'] = 'auto' }
  1425. if ($vmN) { $obj['viewMode'] = $vmN.InnerText }
  1426. if ($uspN) { $usp = Get-PresText $uspN; if ($null -ne $usp) { $obj['userSettingPresentation'] = $usp } }
  1427. $entries += $obj
  1428. } else {
  1429. $s = $pn; if ($use -eq 'false') { $s += ' @off' }
  1430. $entries += $s
  1431. }
  1432. }
  1433. return ,$entries
  1434. }
  1435. function Build-DLParameter {
  1436. param($pNode)
  1437. $name = Get-Child $pNode 'name'
  1438. $o = [ordered]@{}
  1439. $o['name'] = $name
  1440. # title — опускаем, если совпадает с авто-выводом из имени (ru-only)
  1441. $titleNode = $pNode.SelectSingleNode("dcssch:title", $ns)
  1442. if ($titleNode) {
  1443. $t = Get-LangTextWS $titleNode # восстановление значимого пробела: заголовком-пробелом гасят подпись
  1444. if ($null -ne $t) {
  1445. # Сравнение байт в байт: эталон — компилятор, он пишет заголовок как есть. -eq
  1446. # регистронезависим, и заголовок, отличающийся от авто-вывода только регистром
  1447. # («Организации ВетИС» при авто «Организации ВЕТИС»), терялся молча. Даже -ceq мало:
  1448. # он культурный, мягкий перенос и NFD-разложение для него — ноль. Нужен Ordinal,
  1449. # он же и есть зеркало питоновского ==.
  1450. $auto = Title-FromName -name $name
  1451. if (-not (($t -is [string]) -and [string]::Equals($t, $auto, [StringComparison]::Ordinal))) { $o['title'] = $t }
  1452. }
  1453. }
  1454. # valueType
  1455. $vtNode = $pNode.SelectSingleNode("dcssch:valueType", $ns)
  1456. $typeVal = $null
  1457. if ($vtNode) { $typeVal = Decompile-Type $vtNode; if ($typeVal) { $o['type'] = $typeVal } }
  1458. # value — опускаем nil (дефолт), КРОМЕ valueListAllowed+nil: платформа пишет <value xsi:nil/>
  1459. # не всегда (корпус 27 с / 47 без), а компилятор при valueListAllowed по умолчанию его НЕ эмитит →
  1460. # явный маркер value:null, чтобы реэмитить nil. (Различается через Has-DLProp в компиляторе.)
  1461. $vNodes = @($pNode.SelectNodes("dcssch:value", $ns))
  1462. if ($vNodes.Count -gt 1) {
  1463. # valueListAllowed: список значений — захватываем ВСЕ <dcssch:value> массивом
  1464. $o['value'] = @($vNodes | ForEach-Object { Convert-TypedValue -raw $_.InnerText -xsiType ($_.GetAttribute("type", $NS_XSI)) })
  1465. } elseif ($vNodes.Count -eq 1) {
  1466. $vNode = $vNodes[0]
  1467. if ($vNode.GetAttribute("nil", $NS_XSI) -ne 'true') {
  1468. $o['value'] = Convert-TypedValue -raw $vNode.InnerText -xsiType ($vNode.GetAttribute("type", $NS_XSI))
  1469. } elseif ((Get-Child $pNode 'valueListAllowed') -eq 'true') {
  1470. $o['value'] = $null
  1471. }
  1472. }
  1473. # useRestriction — опускаем true (дефолт), фиксируем false
  1474. if ((Get-Child $pNode 'useRestriction') -eq 'false') { $o['useRestriction'] = $false }
  1475. # expression
  1476. $expr = Get-Child $pNode 'expression'; if ($null -ne $expr -and $expr -ne '') { $o['expression'] = $expr }
  1477. # availableValues
  1478. $avNodes = @($pNode.SelectNodes("dcssch:availableValue", $ns))
  1479. if ($avNodes.Count -gt 0) {
  1480. $avs = New-Object System.Collections.ArrayList
  1481. foreach ($avn in $avNodes) {
  1482. $avo = [ordered]@{}
  1483. $avv = $avn.SelectSingleNode("dcssch:value", $ns)
  1484. if ($avv -and ($avv.GetAttribute("nil", $NS_XSI) -ne 'true')) { $avo['value'] = Convert-TypedValue -raw $avv.InnerText -xsiType ($avv.GetAttribute("type", $NS_XSI)) }
  1485. else { $avo['value'] = $null }
  1486. $avp = $avn.SelectSingleNode("dcssch:presentation", $ns)
  1487. if ($avp) { $pres = Get-LangText $avp; if ($null -ne $pres) { $avo['presentation'] = $pres } }
  1488. [void]$avs.Add($avo)
  1489. }
  1490. $o['availableValues'] = @($avs)
  1491. }
  1492. # valueListAllowed / availableAsField
  1493. if ((Get-Child $pNode 'valueListAllowed') -eq 'true') { $o['valueListAllowed'] = $true }
  1494. if ((Get-Child $pNode 'availableAsField') -eq 'false') { $o['availableAsField'] = $false }
  1495. # inputParameters
  1496. $ipNode = $pNode.SelectSingleNode("dcssch:inputParameters", $ns)
  1497. if ($ipNode) { $ip = Build-DLInputParameters $ipNode; if (@($ip).Count -gt 0) { $o['inputParameters'] = $ip } }
  1498. # denyIncompleteValues / use
  1499. if ((Get-Child $pNode 'denyIncompleteValues') -eq 'true') { $o['denyIncompleteValues'] = $true }
  1500. $use = Get-Child $pNode 'use'; if ($null -ne $use -and $use -ne '') { $o['use'] = $use }
  1501. # Компактизация: {name} → строка "name"; {name, type} → "name: type"; иначе объект.
  1502. $keys = @($o.Keys)
  1503. if ($keys.Count -eq 1) { return $name }
  1504. if ($keys.Count -eq 2 -and $o.Contains('type') -and ($typeVal -is [string])) { return ("{0}: {1}" -f $name, $typeVal) }
  1505. return $o
  1506. }
  1507. # --- 4. Element dispatch ---
  1508. $ELEMENT_KEY = @{
  1509. 'UsualGroup'='group'; 'ColumnGroup'='columnGroup'; 'ButtonGroup'='buttonGroup'; 'InputField'='input'; 'CheckBoxField'='check';
  1510. 'RadioButtonField'='radio'; 'LabelDecoration'='label'; 'LabelField'='labelField';
  1511. 'PictureDecoration'='picture'; 'PictureField'='picField'; 'CalendarField'='calendar';
  1512. 'Table'='table'; 'Pages'='pages'; 'Page'='page'; 'Button'='button'; 'CommandBar'='cmdBar'; 'Popup'='popup';
  1513. 'SearchStringAddition'='searchString'; 'ViewStatusAddition'='viewStatus'; 'SearchControlAddition'='searchControl';
  1514. 'SpreadSheetDocumentField'='spreadsheet'; 'HTMLDocumentField'='html'; 'TextDocumentField'='textDoc';
  1515. 'FormattedDocumentField'='formattedDoc'; 'ProgressBarField'='progressBar'; 'TrackBarField'='trackBar';
  1516. 'ChartField'='chart'; 'GraphicalSchemaField'='graphicalSchema'; 'PlannerField'='planner';
  1517. 'PeriodField'='periodField'; 'DendrogramField'='dendrogram'; 'GanttChartField'='ganttChart'
  1518. }
  1519. # Простые скаляры элемента (pass-through, зеркало $script:genericScalars компилятора). kind bool/value.
  1520. $GENERIC_SCALARS = @(
  1521. @{ Tag='VerticalAlign'; Key='verticalAlign'; Kind='value' }
  1522. @{ Tag='ThroughAlign'; Key='throughAlign'; Kind='value' }
  1523. @{ Tag='EnableContentChange'; Key='enableContentChange'; Kind='bool' }
  1524. @{ Tag='PictureSize'; Key='pictureSize'; Kind='value' }
  1525. @{ Tag='TitleHeight'; Key='titleHeight'; Kind='value' }
  1526. @{ Tag='ChildItemsWidth'; Key='childItemsWidth'; Kind='value' }
  1527. @{ Tag='ShowLeftMargin'; Key='showLeftMargin'; Kind='bool' }
  1528. @{ Tag='CellHyperlink'; Key='cellHyperlink'; Kind='bool' }
  1529. @{ Tag='ViewMode'; Key='viewMode'; Kind='value' }
  1530. @{ Tag='VerticalScrollBar'; Key='verticalScrollBar'; Kind='value' }
  1531. @{ Tag='RowInputMode'; Key='rowInputMode'; Kind='value' }
  1532. @{ Tag='Mask'; Key='mask'; Kind='value' }
  1533. @{ Tag='CreateButton'; Key='createButton'; Kind='bool' }
  1534. @{ Tag='FixingInTable'; Key='fixingInTable'; Kind='value' }
  1535. @{ Tag='VerticalSpacing'; Key='verticalSpacing'; Kind='value' }
  1536. # Спец-поля (документ/датчик) — типоспец. enum/bool скаляры pass-through (зеркало компилятора)
  1537. @{ Tag='HorizontalScrollBar'; Key='horizontalScrollBar'; Kind='value' }
  1538. @{ Tag='ViewScalingMode'; Key='viewScalingMode'; Kind='value' }
  1539. @{ Tag='Output'; Key='output'; Kind='value' }
  1540. @{ Tag='SelectionShowMode'; Key='selectionShowMode'; Kind='value' }
  1541. @{ Tag='PointerType'; Key='pointerType'; Kind='value' }
  1542. @{ Tag='DrawingSelectionShowMode'; Key='drawingSelectionShowMode'; Kind='value' }
  1543. @{ Tag='WarningOnEditRepresentation'; Key='warningOnEditRepresentation'; Kind='value' }
  1544. @{ Tag='MarkingAppearance'; Key='markingAppearance'; Kind='value' }
  1545. @{ Tag='Protection'; Key='protection'; Kind='bool' }
  1546. @{ Tag='Edit'; Key='edit'; Kind='bool' }
  1547. @{ Tag='ShowGrid'; Key='showGrid'; Kind='bool' }
  1548. @{ Tag='ShowGroups'; Key='showGroups'; Kind='bool' }
  1549. @{ Tag='ShowHeaders'; Key='showHeaders'; Kind='bool' }
  1550. @{ Tag='ShowRowAndColumnNames'; Key='showRowAndColumnNames'; Kind='bool' }
  1551. @{ Tag='ShowCellNames'; Key='showCellNames'; Kind='bool' }
  1552. @{ Tag='ShowPercent'; Key='showPercent'; Kind='bool' }
  1553. # Report-form контекст: интервал группы / представление кнопки в контекстном меню / детальное представление настройки таблицы
  1554. @{ Tag='HorizontalSpacing'; Key='horizontalSpacing'; Kind='value' }
  1555. @{ Tag='RepresentationInContextMenu'; Key='representationInContextMenu'; Kind='value' }
  1556. @{ Tag='SettingsNamedItemDetailedRepresentation'; Key='settingsNamedItemDetailedRepresentation'; Kind='bool' }
  1557. # Хвост: высота элемента списка (radio) / ширина выпадающего списка (input)
  1558. @{ Tag='ItemHeight'; Key='itemHeight'; Kind='value' }
  1559. @{ Tag='DropListWidth'; Key='dropListWidth'; Kind='value' }
  1560. # Хвост CI-форм: динамический заголовок (Page/Group) / расширенное ред. (input) / высота таблицы по строкам
  1561. @{ Tag='TitleDataPath'; Key='titleDataPath'; Kind='value' }
  1562. @{ Tag='ExtendedEdit'; Key='extendedEdit'; Kind='bool' }
  1563. @{ Tag='MaxRowsCount'; Key='maxRowsCount'; Kind='value' }
  1564. @{ Tag='AutoMaxRowsCount'; Key='autoMaxRowsCount'; Kind='bool' }
  1565. @{ Tag='HeightControlVariant'; Key='heightControlVariant'; Kind='value' }
  1566. @{ Tag='EditTextUpdate'; Key='editTextUpdate'; Kind='value' }
  1567. # Корпусный хвост (zеркало компилятора): свёртка группы / форма попапа / авто-добавление /
  1568. # выделение отрицательных / нач. позиция списка / высота списка выбора / три состояния / прокрутка
  1569. @{ Tag='ControlRepresentation'; Key='controlRepresentation'; Kind='value' }
  1570. @{ Tag='ShapeRepresentation'; Key='shapeRepresentation'; Kind='value' }
  1571. @{ Tag='AutoAddIncomplete'; Key='autoAddIncomplete'; Kind='bool' }
  1572. @{ Tag='MarkNegatives'; Key='markNegatives'; Kind='bool' }
  1573. @{ Tag='InitialListView'; Key='initialListView'; Kind='value' }
  1574. @{ Tag='ChoiceListHeight'; Key='choiceListHeight'; Kind='value' }
  1575. @{ Tag='ThreeState'; Key='threeState'; Kind='bool' }
  1576. @{ Tag='ScrollOnCompress'; Key='scrollOnCompress'; Kind='bool' }
  1577. # Сочетание клавиш — общее свойство элемента (команда — отдельный путь)
  1578. @{ Tag='Shortcut'; Key='shortcut'; Kind='value' }
  1579. # Батч простых скаляров (зеркало компилятора; Table HeaderHeight/FooterHeight/CurrentRowUse — отдельно)
  1580. @{ Tag='IncompleteChoiceMode'; Key='incompleteChoiceMode'; Kind='value' }
  1581. @{ Tag='EqualColumnsWidth'; Key='equalColumnsWidth'; Kind='bool' }
  1582. @{ Tag='ChildrenAlign'; Key='childrenAlign'; Kind='value' }
  1583. @{ Tag='ImageScale'; Key='imageScale'; Kind='value' }
  1584. @{ Tag='Zoomable'; Key='zoomable'; Kind='bool' }
  1585. @{ Tag='Shape'; Key='shape'; Kind='value' }
  1586. @{ Tag='PictureLocation'; Key='pictureLocation'; Kind='value' }
  1587. # Равная ширина элементов (check/radio) / высота заголовка пункта (radio)
  1588. @{ Tag='EqualItemsWidth'; Key='equalItemsWidth'; Kind='bool' }
  1589. @{ Tag='ItemTitleHeight'; Key='itemTitleHeight'; Kind='value' }
  1590. # Спец-режим ввода текста (input, моб.: Email/PhoneNumber/...) — листовой enum-скаляр
  1591. @{ Tag='SpecialTextInputMode'; Key='specialTextInputMode'; Kind='value' }
  1592. # Ширина пункта (radio/check) / выбор нескольких значений из выпадающего (input)
  1593. @{ Tag='ItemWidth'; Key='itemWidth'; Kind='value' }
  1594. @{ Tag='ShowCheckBoxesInDropList'; Key='showCheckBoxesInDropList'; Kind='bool' }
  1595. @{ Tag='MultipleValueDataPath'; Key='multipleValueDataPath'; Kind='value' }
  1596. @{ Tag='MultipleValuePresentDataPath'; Key='multipleValuePresentDataPath'; Kind='value' }
  1597. # Режим авто-показа кнопок открытия/очистки (input, enum)
  1598. @{ Tag='AutoShowOpenButtonMode'; Key='autoShowOpenButtonMode'; Kind='value' }
  1599. @{ Tag='AutoShowClearButtonMode'; Key='autoShowClearButtonMode'; Kind='value' }
  1600. # Оформление/картинка множественного выбора (input, редко; цвета — текст-контент)
  1601. @{ Tag='MultipleValuesTextColor'; Key='multipleValuesTextColor'; Kind='value' }
  1602. @{ Tag='MultipleValuesBackColor'; Key='multipleValuesBackColor'; Kind='value' }
  1603. @{ Tag='MultipleValuePictureShape'; Key='multipleValuePictureShape'; Kind='value' }
  1604. @{ Tag='MultipleValuePictureDataPath'; Key='multipleValuePictureDataPath'; Kind='value' }
  1605. # Хвост листовых скаляров (по 1): автокоррекция / уникальность команды / пустое множ.значение / гориз.сжатие
  1606. @{ Tag='AutoCorrectionOnTextInput'; Key='autoCorrectionOnTextInput'; Kind='value' }
  1607. @{ Tag='SpellCheckingOnTextInput'; Key='spellCheckingOnTextInput'; Kind='value' }
  1608. @{ Tag='CommandUniqueness'; Key='commandUniqueness'; Kind='bool' }
  1609. @{ Tag='AllowInputEmptyMultipleValues'; Key='allowInputEmptyMultipleValues'; Kind='bool' }
  1610. @{ Tag='BehaviorOnHorizontalCompression'; Key='behaviorOnHorizontalCompression'; Kind='value' }
  1611. )
  1612. # Захват generic-скаляров. Специфичная обработка (если ключ уже задан) — побеждает.
  1613. function Add-GenericScalars {
  1614. param($obj, $node)
  1615. foreach ($s in $GENERIC_SCALARS) {
  1616. if ($obj.Contains($s.Key)) { continue }
  1617. $v = Get-Child $node $s.Tag
  1618. if ($null -eq $v) { continue }
  1619. if ($s.Kind -eq 'bool') { $obj[$s.Key] = ($v -eq 'true') } else { $obj[$s.Key] = $v }
  1620. }
  1621. }
  1622. function Decompile-Children {
  1623. param($parentNode, [string]$childContainer = 'ChildItems')
  1624. $container = $parentNode.SelectSingleNode("lf:$childContainer", $ns)
  1625. if (-not $container) { return $null }
  1626. $list = New-Object System.Collections.ArrayList
  1627. foreach ($child in $container.ChildNodes) {
  1628. if ($child.NodeType -ne [System.Xml.XmlNodeType]::Element) { continue }
  1629. if ($COMPANION_TAGS -contains $child.LocalName) { continue }
  1630. $el = Decompile-Element $child
  1631. if ($el) { [void]$list.Add($el) }
  1632. }
  1633. if ($list.Count -eq 0) { return $null }
  1634. return ,@($list)
  1635. }
  1636. # Инверсия Emit-CompanionPanel: companion-командная-панель (ContextMenu/AutoCommandBar) с контентом
  1637. # → { autofill?, horizontalAlign?, children?[] } либо $null, если companion пустой (self-closing).
  1638. # Дин-список-таблица: компилятор-эвристика додумывает Autofill=false. Выражаем только ОТКЛОНЕНИЕ:
  1639. # autofill=false (нет детей) → совпадает с дефолтом → молчим;
  1640. # голый <AutoCommandBar/> (autofill=true по умолчанию) → маркер { autofill: true } (панель не скрыта).
  1641. function Decompile-CompanionPanel {
  1642. param($node, [string]$tag, [bool]$isDynListTable = $false)
  1643. $p = $node.SelectSingleNode("lf:$tag", $ns)
  1644. if (-not $p) { return $null }
  1645. $autofillRaw = Get-Child $p 'Autofill'
  1646. $halign = Get-Child $p 'HorizontalAlign'
  1647. $kids = Decompile-Children $p
  1648. $hasKids = $kids -and @($kids).Count -gt 0
  1649. if ($isDynListTable -and $tag -eq 'AutoCommandBar' -and -not $hasKids -and -not $halign) {
  1650. if ($autofillRaw -eq 'false') { return $null } # = дефолт эвристики → молчим
  1651. return [ordered]@{ autofill = $true } # голая панель → отклонение
  1652. }
  1653. if (-not $hasKids -and $null -eq $autofillRaw -and -not $halign) { return $null }
  1654. $o = [ordered]@{}
  1655. if ($halign) { $o['horizontalAlign'] = $halign }
  1656. if ($autofillRaw -eq 'false') { $o['autofill'] = $false }
  1657. elseif ($autofillRaw -eq 'true') { $o['autofill'] = $true }
  1658. if ($hasKids) { $o['children'] = $kids }
  1659. return $o
  1660. }
  1661. # Инверсия Emit-ChoiceList: <ChoiceList><xr:Item>… → [ { value, presentation? } ] либо $null.
  1662. # У RadioButtonField и InputField.
  1663. function Decompile-ChoiceList {
  1664. param($node)
  1665. $cl = $node.SelectSingleNode("lf:ChoiceList", $ns)
  1666. if (-not $cl) { return $null }
  1667. $items = New-Object System.Collections.ArrayList
  1668. foreach ($it in @($cl.SelectNodes("xr:Item", $ns))) {
  1669. $valNode = $it.SelectSingleNode("xr:Value/lf:Value", $ns)
  1670. $presNode = $it.SelectSingleNode("xr:Value/lf:Presentation", $ns)
  1671. $ci = [ordered]@{}
  1672. if ($valNode) {
  1673. if ($valNode.GetAttribute("nil", $NS_XSI) -eq 'true') {
  1674. # nil-значение элемента choiceList — компилятор эмитит <Value xsi:nil="true"/>
  1675. # (иначе Convert-TypedValue вернул бы "" → typed-empty xs:string).
  1676. $ci['valueType'] = 'nil'
  1677. } else {
  1678. $xsiType = $valNode.GetAttribute("type", $NS_XSI)
  1679. $ci['value'] = Convert-TypedValue $valNode.InnerText $xsiType
  1680. # Системное перечисление (ent:*) / иной не-примитивный тип → сохраняем valueType
  1681. # (Normalize-ChoiceValue вывела бы xs:string). DesignTimeRef обычно авто-детектится
  1682. # компилятором по named-ref (Enum.X.Y), НО raw-ссылка по GUID (GUID.GUID) — нет → сохраняем.
  1683. if ($xsiType -and $xsiType -notmatch '^xs:(string|decimal|boolean|dateTime)$' -and `
  1684. ($xsiType -ne 'xr:DesignTimeRef' -or "$($valNode.InnerText)" -match '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-')) {
  1685. $ci['valueType'] = $xsiType
  1686. }
  1687. }
  1688. }
  1689. # Presentation: непустой → текст/мультиязык; пустой <Presentation/> → "" — суппресс-маркер,
  1690. # подавляет авто-вывод компилятора (иначе компилятор додумает presentation из значения).
  1691. if ($presNode) {
  1692. $p = Get-LangTextWS $presNode # восстановление значимого пробела (whitespace-presentation)
  1693. if ($null -ne $p -and $p -ne '') { $ci['presentation'] = $p } else { $ci['presentation'] = '' }
  1694. }
  1695. [void]$items.Add($ci)
  1696. }
  1697. if ($items.Count -gt 0) { return ,@($items) }
  1698. return $null
  1699. }
  1700. # Значение Параметра выбора (<lf:Value>): скаляр через Convert-TypedValue, либо
  1701. # v8:FixedArray → массив скаляров (каждый — FormChoiceListDesTimeValue с внутренним lf:Value).
  1702. function Convert-ChoiceParamValue {
  1703. param($valNode)
  1704. $vt = $valNode.GetAttribute("type", $NS_XSI)
  1705. if ($vt -match 'FixedArray$') {
  1706. $arr = New-Object System.Collections.ArrayList
  1707. foreach ($it in @($valNode.SelectNodes("v8:Value", $ns))) {
  1708. $inner = $it.SelectSingleNode("lf:Value", $ns)
  1709. if ($inner) { [void]$arr.Add((Convert-TypedValue -raw $inner.InnerText -xsiType ($inner.GetAttribute("type", $NS_XSI)))) }
  1710. }
  1711. return ,@($arr)
  1712. }
  1713. return Convert-TypedValue -raw $valNode.InnerText -xsiType $vt
  1714. }
  1715. # Инверсия Emit-ChoiceParameters: <ChoiceParameters><app:item name="X"><app:value><Value…> → [{name, value}].
  1716. function Decompile-ChoiceParameters {
  1717. param($node)
  1718. $cpn = $node.SelectSingleNode("lf:ChoiceParameters", $ns)
  1719. if (-not $cpn) { return $null }
  1720. $items = New-Object System.Collections.ArrayList
  1721. foreach ($it in @($cpn.SelectNodes("app:item", $ns))) {
  1722. $o = [ordered]@{}
  1723. $o['name'] = $it.GetAttribute("name")
  1724. $valNode = $it.SelectSingleNode("app:value/lf:Value", $ns)
  1725. if ($valNode) { $o['value'] = Convert-ChoiceParamValue $valNode }
  1726. [void]$items.Add($o)
  1727. }
  1728. if ($items.Count -gt 0) { return ,@($items) }
  1729. return $null
  1730. }
  1731. # Инверсия Emit-ChoiceParameterLinks: <ChoiceParameterLinks><xr:Link><xr:Name><xr:DataPath><xr:ValueChange> →
  1732. # [{name, dataPath, valueChange?}]. valueChange дефолт Clear → опускаем (компилятор восстановит).
  1733. function Decompile-ChoiceParameterLinks {
  1734. param($node)
  1735. $cln = $node.SelectSingleNode("lf:ChoiceParameterLinks", $ns)
  1736. if (-not $cln) { return $null }
  1737. $items = New-Object System.Collections.ArrayList
  1738. foreach ($lk in @($cln.SelectNodes("xr:Link", $ns))) {
  1739. $o = [ordered]@{}
  1740. $o['name'] = Get-Text $lk "xr:Name"
  1741. $o['dataPath'] = Get-Text $lk "xr:DataPath"
  1742. $vc = Get-Text $lk "xr:ValueChange"
  1743. if ($vc -and $vc -ne 'Clear') { $o['valueChange'] = $vc }
  1744. [void]$items.Add($o)
  1745. }
  1746. if ($items.Count -gt 0) { return ,@($items) }
  1747. return $null
  1748. }
  1749. # Инверсия Emit-TypeLink: <TypeLink><xr:DataPath><xr:LinkItem> → {dataPath, linkItem}.
  1750. function Decompile-TypeLink {
  1751. param($node)
  1752. $tn = $node.SelectSingleNode("lf:TypeLink", $ns)
  1753. if (-not $tn) { return $null }
  1754. $o = [ordered]@{}
  1755. $o['dataPath'] = Get-Text $tn "xr:DataPath"
  1756. $li = Get-Text $tn "xr:LinkItem"
  1757. if ($null -ne $li -and $li -ne '') { $o['linkItem'] = [int]$li }
  1758. return $o
  1759. }
  1760. # Захват <Format>/<EditFormat> (LocalStringType) → format/editFormat (строка или {ru,en}).
  1761. function Add-FormatProps {
  1762. param($obj, $node)
  1763. $fmt = $node.SelectSingleNode("lf:Format", $ns); if ($fmt) { $t = Get-LangText $fmt; if ($null -ne $t -and $t -ne '') { $obj['format'] = $t } }
  1764. $efmt = $node.SelectSingleNode("lf:EditFormat", $ns); if ($efmt) { $t = Get-LangText $efmt; if ($null -ne $t -and $t -ne '') { $obj['editFormat'] = $t } }
  1765. }
  1766. # Ядро дополнения: source + общие свойства (Add-CommonProps) + horizontalLocation.
  1767. # Layout (Add-Layout) добавляется ОТДЕЛЬНО (в Decompile-Element — пост-обработкой, в standalone — явно).
  1768. function Add-AdditionCore {
  1769. param($obj, $node, [string]$elName)
  1770. $src = $node.SelectSingleNode("lf:AdditionSource/lf:Item", $ns); if ($src) { $obj['source'] = $src.InnerText }
  1771. Add-CommonProps $obj $node $elName
  1772. $hl = Get-Child $node 'HorizontalLocation'; if ($hl) { $obj['horizontalLocation'] = $hl.ToLower() }
  1773. }
  1774. # Стандартные дополнения уровня таблицы (прямые дети <Table>): извлечь ТОЛЬКО отклонения в карту
  1775. # { тип: {свойства} }. Имя (=tableName+suffix) и source (=tableName) — дефолтные, опускаем.
  1776. function Decompile-TableAdditions {
  1777. param($tableNode, [string]$tableName)
  1778. $tagToKey = @{ 'SearchStringAddition'='searchString'; 'ViewStatusAddition'='viewStatus'; 'SearchControlAddition'='searchControl' }
  1779. $map = [ordered]@{}
  1780. foreach ($child in $tableNode.ChildNodes) {
  1781. if ($child.NodeType -ne [System.Xml.XmlNodeType]::Element) { continue }
  1782. if (-not $tagToKey.ContainsKey($child.LocalName)) { continue }
  1783. $key = $tagToKey[$child.LocalName]
  1784. $nm = $child.GetAttribute("name")
  1785. $o = [ordered]@{}; $o[$key] = $nm
  1786. Add-AdditionCore $o $child $nm
  1787. Add-Layout $o $child
  1788. $o.Remove($key) # имя авто
  1789. if ($o.Contains('source') -and $o['source'] -eq $tableName) { $o.Remove('source') } # source=таблица дефолт
  1790. if ($o.Count -gt 0) { $map[$key] = $o }
  1791. }
  1792. if ($map.Count -gt 0) { return $map }
  1793. return $null
  1794. }
  1795. # Спец-поля «документ/датчик» — общий скелет поля (имя/path/CommonProps/TitleLocation/editMode).
  1796. # Типоспец. enum/bool скаляры ловит пост-switch Add-GenericScalars; layout/companions — общий хвост.
  1797. function Decompile-SimpleField {
  1798. param($obj, $node, [string]$name, [string]$key)
  1799. $obj[$key] = $name
  1800. $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
  1801. Add-CommonProps $obj $node $name
  1802. $tl = Get-Child $node 'TitleLocation'; if ($tl) { $obj['titleLocation'] = $tl.ToLower() }
  1803. $em = Get-Child $node 'EditMode'; if ($em) { $obj['editMode'] = $em }
  1804. }
  1805. # Числовые скаляры датчиков (ProgressBar/TrackBar) — без xsi:type (≠ типизированных InputField).
  1806. function Add-GaugeScalars {
  1807. param($obj, $node, $tags)
  1808. foreach ($p in $tags) {
  1809. $v = Get-Child $node $p
  1810. if ($null -eq $v) { continue }
  1811. $key = $p.Substring(0,1).ToLower() + $p.Substring(1)
  1812. if ($v -match '^-?\d+$') { $obj[$key] = [int]$v } else { $obj[$key] = $v }
  1813. }
  1814. }
  1815. function Decompile-Element {
  1816. param($node)
  1817. $tag = $node.LocalName
  1818. if (-not $ELEMENT_KEY.ContainsKey($tag)) {
  1819. Fail-Ring3 -kind "элемент <$tag>" -loc "ChildItems/$tag"
  1820. }
  1821. $key = $ELEMENT_KEY[$tag]
  1822. $name = $node.GetAttribute("name")
  1823. $obj = [ordered]@{}
  1824. switch ($tag) {
  1825. 'UsualGroup' {
  1826. # group = направление (<Group>); behavior = <Behavior> (Авто = нет тега → ключ опускаем).
  1827. # group = направление (<Group>). Нет тега → '' (тип-маркер сохраняется, направление
  1828. # не эмитим). Платформа явно пишет Vertical в большинстве случаев, поэтому '' ≠ 'vertical'
  1829. # — иначе компилятор додумает <Group>Vertical</Group> там, где его нет.
  1830. $g = Get-Child $node 'Group'
  1831. $gmap = @{ 'Horizontal'='horizontal'; 'Vertical'='vertical'; 'AlwaysHorizontal'='alwaysHorizontal'; 'AlwaysVertical'='alwaysVertical'; 'HorizontalIfPossible'='horizontalIfPossible' }
  1832. if ($g -and $gmap.ContainsKey($g)) { $obj[$key] = $gmap[$g] } else { $obj[$key] = '' }
  1833. $behavior = Get-Child $node 'Behavior'
  1834. if ($behavior) {
  1835. $bmap = @{ 'Usual'='usual'; 'Collapsible'='collapsible'; 'PopUp'='popup' }
  1836. if ($bmap.ContainsKey($behavior)) { $obj['behavior'] = $bmap[$behavior] } else { $obj['behavior'] = $behavior }
  1837. }
  1838. $obj['name'] = $name
  1839. Add-CommonProps $obj $node $name
  1840. $rep = Get-Child $node 'Representation'
  1841. if ($rep) { $repmap=@{'None'='none';'NormalSeparation'='normal';'WeakSeparation'='weak';'StrongSeparation'='strong'}; if ($repmap.ContainsKey($rep)) { $obj['representation']=$repmap[$rep] } else { $obj['representation']=$rep } }
  1842. # Зеркало компилятора. Обычная группа без showTitle: с заголовком (title/titleDataPath) — показан, без — скрыт; ключ
  1843. # пишется, только когда факт расходится с этим умолчанием. Сворачиваемая/всплывающая — факт. значение.
  1844. $st = Get-Child $node 'ShowTitle'
  1845. if (@('Collapsible','PopUp') -contains $behavior) { if ($null -ne $st) { $obj['showTitle'] = ($st -eq 'true') } }
  1846. elseif ($obj['title'] -or (Get-Child $node 'TitleDataPath')) { if ($st -eq 'false') { $obj['showTitle'] = $false } }
  1847. elseif ($st -ne 'false') { $obj['showTitle'] = $true }
  1848. $cru = Get-Child $node 'CurrentRowUse'; if ($cru) { $obj['currentRowUse'] = $cru } # использование текущей строки группы
  1849. $crt = $node.SelectSingleNode("lf:CollapsedRepresentationTitle", $ns); if ($crt) { $ct = Get-LangText $crt; if ($null -ne $ct -and $ct -ne '') { $obj['collapsedTitle'] = $ct } }
  1850. if ((Get-Child $node 'United') -eq 'false') { $obj['united'] = $false }
  1851. if ((Get-Child $node 'Collapsed') -eq 'true') { $obj['collapsed'] = $true }
  1852. # Формат значения пути к данным заголовка (<Format>; парный к titleDataPath группы)
  1853. Add-FormatProps $obj $node
  1854. $kids = Decompile-Children $node
  1855. if ($kids) { $obj['children'] = $kids }
  1856. }
  1857. 'ColumnGroup' {
  1858. # columnGroup = направление (<Group>). Нет тега → '' (тип-маркер сохраняется, направление
  1859. # не эмитим). Иначе компилятор додумает <Group>Horizontal</Group> там, где его нет.
  1860. $g = Get-Child $node 'Group'
  1861. $gmap = @{ 'Horizontal'='horizontal'; 'Vertical'='vertical'; 'InCell'='inCell' }
  1862. if ($g -and $gmap.ContainsKey($g)) { $obj[$key] = $gmap[$g] } else { $obj[$key] = '' }
  1863. $obj['name'] = $name
  1864. Add-CommonProps $obj $node $name
  1865. $st = Get-Child $node 'ShowTitle'; if ($null -ne $st) { $obj['showTitle'] = ($st -eq 'true') } # факт. значение (явный true тоже)
  1866. $sih = Get-Child $node 'ShowInHeader'; if ($null -ne $sih) { $obj['showInHeader'] = (To-Bool $sih) }
  1867. $kids = Decompile-Children $node
  1868. if ($kids) { $obj['children'] = $kids }
  1869. }
  1870. 'InputField' {
  1871. $obj[$key] = $name
  1872. $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
  1873. Add-CommonProps $obj $node $name
  1874. # MultiLine: факт. значение (платформа эмитит и явный false — 425 в корпусе; ≠ «if true»)
  1875. $mlIn = Get-Child $node 'MultiLine'; if ($null -ne $mlIn) { $obj['multiLine'] = ($mlIn -eq 'true') }
  1876. # PasswordMode: факт. значение (платформа эмитит и false — 349/504 в корпусе; ≠ «if true»)
  1877. $pmIn = Get-Child $node 'PasswordMode'; if ($null -ne $pmIn) { $obj['passwordMode'] = ($pmIn -eq 'true') }
  1878. $mi = Get-Child $node 'AutoMarkIncomplete'; if ($null -ne $mi) { $obj['markIncomplete'] = ($mi -eq 'true') }
  1879. $em = Get-Child $node 'EditMode'; if ($em) { $obj['editMode'] = $em }
  1880. $tl = Get-Child $node 'TitleLocation'; if ($tl) { $obj['titleLocation'] = $tl.ToLower() }
  1881. $ih = $node.SelectSingleNode("lf:InputHint", $ns); if ($ih) { $t = Get-LangTextWS $ih; if ($t) { $obj['inputHint'] = $t } }
  1882. $woe = $node.SelectSingleNode("lf:WarningOnEdit", $ns); if ($woe) { $t = Get-LangTextWS $woe; if ($null -ne $t) { $obj['warningOnEdit'] = $t } }
  1883. $ftxt = $node.SelectSingleNode("lf:FooterText", $ns); if ($ftxt) { $t = Get-LangTextWS $ftxt; if ($null -ne $t) { $obj['footerText'] = $t } }
  1884. foreach ($p in @('ChoiceButton','ClearButton','SpinButton','DropListButton','ChoiceListButton')) {
  1885. $v = Get-Child $node $p; if ($null -ne $v) { $obj[($p.Substring(0,1).ToLower()+$p.Substring(1))] = (To-Bool $v) }
  1886. }
  1887. # InputField-специфичные bool-скаляры (захват «как есть»)
  1888. foreach ($p in @('Wrap','OpenButton','ListChoiceMode','ExtendedEditMultipleValues','ChooseType','QuickChoice','AutoChoiceIncomplete')) {
  1889. $v = Get-Child $node $p; if ($null -ne $v) { $obj[($p.Substring(0,1).ToLower()+$p.Substring(1))] = (To-Bool $v) }
  1890. }
  1891. # InputField-специфичные value-скаляры (захват «как есть»)
  1892. foreach ($p in @('ChoiceForm','ChoiceHistoryOnInput','ChoiceFoldersAndItems','FooterDataPath')) {
  1893. $v = Get-Child $node $p; if ($null -ne $v) { $obj[($p.Substring(0,1).ToLower()+$p.Substring(1))] = $v }
  1894. }
  1895. # MinValue/MaxValue — типизированное (<MinValue xsi:type="xs:decimal">N). Тип кодируем в JSON-тип:
  1896. # xs:decimal/int → число (компилятор → xs:decimal), иначе → строка (компилятор → xs:string).
  1897. foreach ($p in @('MinValue','MaxValue')) {
  1898. $mn = $node.SelectSingleNode("lf:$p", $ns)
  1899. if ($mn) {
  1900. $xt = $mn.GetAttribute("type", $NS_XSI); $txt = $mn.InnerText
  1901. $key = $p.Substring(0,1).ToLower() + $p.Substring(1)
  1902. if ($xt -match 'decimal|int') {
  1903. if ($txt -match '^-?\d+$') { $obj[$key] = [int]$txt } elseif ($txt -match '^-?\d+\.\d+$') { $obj[$key] = [decimal]$txt } else { $obj[$key] = $txt }
  1904. } else { $obj[$key] = $txt }
  1905. }
  1906. }
  1907. # Ограничение доступных типов (поле на составном/характеристика-типе): домен типов + явный набор.
  1908. # availableTypes — тот же формат типа, что у реквизитов (§type), захват через Decompile-Type.
  1909. $tde = Get-Child $node 'TypeDomainEnabled'; if ($null -ne $tde) { $obj['typeDomainEnabled'] = (To-Bool $tde) }
  1910. $atNode = $node.SelectSingleNode("lf:AvailableTypes", $ns); if ($atNode) { $at = Decompile-Type $atNode; if ($at) { $obj['availableTypes'] = $at } }
  1911. $cbr = Get-Child $node 'ChoiceButtonRepresentation'; if ($cbr) { $obj['choiceButtonRepresentation'] = $cbr }
  1912. $cbp = Get-PictureRef $node 'ChoiceButtonPicture'; if ($null -ne $cbp) { $obj['choiceButtonPicture'] = $cbp }
  1913. if ((Get-Child $node 'TextEdit') -eq 'false') { $obj['textEdit'] = $false }
  1914. $cl = Decompile-ChoiceList $node; if ($cl) { $obj['choiceList'] = $cl }
  1915. Add-FormatProps $obj $node
  1916. # Параметры выбора / Связи параметров выбора / Связь по типу
  1917. $cp = Decompile-ChoiceParameters $node; if ($cp) { $obj['choiceParameters'] = $cp }
  1918. $cpl = Decompile-ChoiceParameterLinks $node; if ($cpl) { $obj['choiceParameterLinks'] = $cpl }
  1919. $tlk = Decompile-TypeLink $node; if ($tlk) { $obj['typeLink'] = $tlk }
  1920. }
  1921. 'CheckBoxField' {
  1922. $obj[$key] = $name
  1923. $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
  1924. Add-CommonProps $obj $node $name
  1925. $em = Get-Child $node 'EditMode'; if ($em) { $obj['editMode'] = $em }
  1926. # CheckBoxType: Auto = умный дефолт → опустить; нет тега → ""; иначе значение
  1927. $cbt = Get-Child $node 'CheckBoxType'
  1928. if ($null -eq $cbt) { $obj['checkBoxType'] = '' }
  1929. elseif ($cbt -ne 'Auto') { $obj['checkBoxType'] = $cbt.Substring(0,1).ToLower() + $cbt.Substring(1) }
  1930. Add-TitleLocation $obj $node 'Right'
  1931. $woe = $node.SelectSingleNode("lf:WarningOnEdit", $ns); if ($woe) { $t = Get-LangTextWS $woe; if ($null -ne $t) { $obj['warningOnEdit'] = $t } }
  1932. # FooterDataPath / FooterText — общие cell-свойства колонки (как у input/labelField)
  1933. $fdp = Get-Child $node 'FooterDataPath'; if ($fdp) { $obj['footerDataPath'] = $fdp }
  1934. $ftxt = $node.SelectSingleNode("lf:FooterText", $ns); if ($ftxt) { $t = Get-LangTextWS $ftxt; if ($null -ne $t) { $obj['footerText'] = $t } }
  1935. Add-FormatProps $obj $node
  1936. }
  1937. 'RadioButtonField' {
  1938. $obj[$key] = $name
  1939. $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
  1940. Add-CommonProps $obj $node $name
  1941. Add-TitleLocation $obj $node 'None'
  1942. $em = Get-Child $node 'EditMode'; if ($em) { $obj['editMode'] = $em }
  1943. $rbt = Get-Child $node 'RadioButtonType'; if ($rbt) { $obj['radioButtonType'] = $rbt }
  1944. $cc = Get-Child $node 'ColumnsCount'; if ($cc) { $obj['columnsCount'] = [int]$cc }
  1945. $woe = $node.SelectSingleNode("lf:WarningOnEdit", $ns); if ($woe) { $t = Get-LangTextWS $woe; if ($null -ne $t) { $obj['warningOnEdit'] = $t } }
  1946. $cl = Decompile-ChoiceList $node; if ($cl) { $obj['choiceList'] = $cl }
  1947. }
  1948. 'LabelDecoration' {
  1949. $obj[$key] = $name
  1950. Add-CommonProps $obj $node $name
  1951. if ((Get-Child $node 'Hyperlink') -eq 'true') { $obj['hyperlink'] = $true }
  1952. # title декорации — единая ML-text форма с авто-детектом formatted (как extendedTooltip)
  1953. $tiNode = $node.SelectSingleNode("lf:Title", $ns)
  1954. if ($tiNode) { $tv = Get-MLFormattedValue $tiNode; if ($null -ne $tv) { $obj['title'] = $tv } }
  1955. }
  1956. 'LabelField' {
  1957. $obj[$key] = $name
  1958. $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
  1959. Add-CommonProps $obj $node $name
  1960. $tl = Get-Child $node 'TitleLocation'; if ($tl) { $obj['titleLocation'] = $tl.ToLower() }
  1961. $em = Get-Child $node 'EditMode'; if ($em) { $obj['editMode'] = $em }
  1962. # LabelField: тег <Hiperlink> (опечатка платформы), не <Hyperlink>
  1963. if ((Get-Child $node 'Hiperlink') -eq 'true') { $obj['hyperlink'] = $true }
  1964. # PasswordMode на LabelField — платформа эмитит явный false (редко); захват факт. значения
  1965. $pm = Get-Child $node 'PasswordMode'; if ($null -ne $pm) { $obj['passwordMode'] = ($pm -eq 'true') }
  1966. $woe = $node.SelectSingleNode("lf:WarningOnEdit", $ns); if ($woe) { $t = Get-LangTextWS $woe; if ($null -ne $t) { $obj['warningOnEdit'] = $t } }
  1967. # FooterDataPath / FooterText — общие cell-свойства колонки (как у input), не только input
  1968. $fdp = Get-Child $node 'FooterDataPath'; if ($fdp) { $obj['footerDataPath'] = $fdp }
  1969. $ftxt = $node.SelectSingleNode("lf:FooterText", $ns); if ($ftxt) { $t = Get-LangTextWS $ftxt; if ($null -ne $t) { $obj['footerText'] = $t } }
  1970. Add-FormatProps $obj $node
  1971. }
  1972. 'PictureDecoration' {
  1973. $obj[$key] = $name
  1974. Add-CommonProps $obj $node $name
  1975. # title декорации — единая ML-text форма с formatted (атрибут <Title formatted> у PictureDecoration)
  1976. $tiNode = $node.SelectSingleNode("lf:Title", $ns)
  1977. if ($tiNode) { $tv = Get-MLFormattedValue $tiNode; if ($null -ne $tv) { $obj['title'] = $tv } }
  1978. $npt = $node.SelectSingleNode("lf:NonselectedPictureText", $ns); if ($npt) { $t = Get-LangTextWS $npt; if ($null -ne $t) { $obj['nonselectedPictureText'] = $t } }
  1979. $ref = $node.SelectSingleNode("lf:Picture/xr:Ref", $ns)
  1980. $abs = $node.SelectSingleNode("lf:Picture/xr:Abs", $ns)
  1981. if ($ref) { $obj['src'] = $ref.InnerText } elseif ($abs) { $obj['src'] = "abs:$($abs.InnerText)" } # встроенная картинка → префикс abs:
  1982. $lt = $node.SelectSingleNode("lf:Picture/xr:LoadTransparent", $ns); if ($lt -and $lt.InnerText -eq 'true') { $obj['loadTransparent'] = $true }
  1983. # Прозрачный пиксель картинки (<xr:TransparentPixel x y/>) — координаты фона прозрачности
  1984. $tpx = $node.SelectSingleNode("lf:Picture/xr:TransparentPixel", $ns)
  1985. if ($tpx) { $obj['transparentPixel'] = [ordered]@{ x = [int]$tpx.GetAttribute('x'); y = [int]$tpx.GetAttribute('y') } }
  1986. if ((Get-Child $node 'Hyperlink') -eq 'true') { $obj['hyperlink'] = $true }
  1987. }
  1988. 'PictureField' {
  1989. $obj[$key] = $name
  1990. $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
  1991. Add-CommonProps $obj $node $name
  1992. $em = Get-Child $node 'EditMode'; if ($em) { $obj['editMode'] = $em }
  1993. $tl = Get-Child $node 'TitleLocation'; if ($tl) { $obj['titleLocation'] = $tl.ToLower() }
  1994. if ((Get-Child $node 'Hyperlink') -eq 'true') { $obj['hyperlink'] = $true }
  1995. $vp = Get-PictureRef $node 'ValuesPicture'; if ($null -ne $vp) { $obj['valuesPicture'] = $vp }
  1996. $npt = $node.SelectSingleNode("lf:NonselectedPictureText", $ns); if ($npt) { $t = Get-LangTextWS $npt; if ($null -ne $t) { $obj['nonselectedPictureText'] = $t } }
  1997. # FooterDataPath / FooterText — общие cell-свойства колонки (как у input/labelField)
  1998. $fdp = Get-Child $node 'FooterDataPath'; if ($fdp) { $obj['footerDataPath'] = $fdp }
  1999. $ftxt = $node.SelectSingleNode("lf:FooterText", $ns); if ($ftxt) { $t = Get-LangTextWS $ftxt; if ($null -ne $t) { $obj['footerText'] = $t } }
  2000. }
  2001. 'CalendarField' {
  2002. $obj[$key] = $name
  2003. $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
  2004. Add-CommonProps $obj $node $name
  2005. $tl = Get-Child $node 'TitleLocation'; if ($tl) { $obj['titleLocation'] = $tl.ToLower() }
  2006. $sm = Get-Child $node 'SelectionMode'; if ($sm) { $obj['selectionMode'] = $sm }
  2007. $scd = Get-Child $node 'ShowCurrentDate'; if ($null -ne $scd) { $obj['showCurrentDate'] = ($scd -eq 'true') }
  2008. $wim = Get-Child $node 'WidthInMonths'; if ($null -ne $wim) { $obj['widthInMonths'] = [int]$wim }
  2009. $him = Get-Child $node 'HeightInMonths'; if ($null -ne $him) { $obj['heightInMonths'] = [int]$him }
  2010. $smp = Get-Child $node 'ShowMonthsPanel'; if ($null -ne $smp) { $obj['showMonthsPanel'] = ($smp -eq 'true') }
  2011. }
  2012. 'Table' {
  2013. $obj[$key] = $name
  2014. $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
  2015. Add-CommonProps $obj $node $name
  2016. $tl = Get-Child $node 'TitleLocation'; if ($tl) { $obj['titleLocation'] = $tl.ToLower() }
  2017. $rep = Get-Child $node 'Representation'; if ($rep) { $obj['representation'] = $rep }
  2018. $crs = Get-Child $node 'ChangeRowSet'; if ($null -ne $crs) { $obj['changeRowSet'] = ($crs -eq 'true') }
  2019. $cro = Get-Child $node 'ChangeRowOrder'; if ($null -ne $cro) { $obj['changeRowOrder'] = ($cro -eq 'true') }
  2020. if ((Get-Child $node 'AutoInsertNewRow') -eq 'true') { $obj['autoInsertNewRow'] = $true }
  2021. # enableDrag — теперь общий (Add-Layout, фактическое значение)
  2022. if ($node.SelectSingleNode("lf:RowFilter", $ns)) { $obj['rowFilter'] = $null }
  2023. if ((Get-Child $node 'Header') -eq 'false') { $obj['header'] = $false }
  2024. if ((Get-Child $node 'Footer') -eq 'true') { $obj['footer'] = $true }
  2025. # Высота в строках — отдельный ключ heightInTableRows (≠ height = <Height>, его ловит Add-Layout)
  2026. $htr = Get-Child $node 'HeightInTableRows'; if ($htr) { $obj['heightInTableRows'] = [int]$htr }
  2027. # Высота шапки/подвала таблицы в строках (pass-through; компилятор эмитит в Emit-Table)
  2028. $hh = Get-Child $node 'HeaderHeight'; if ($null -ne $hh) { $obj['headerHeight'] = [int]$hh }
  2029. $fh = Get-Child $node 'FooterHeight'; if ($null -ne $fh) { $obj['footerHeight'] = [int]$fh }
  2030. # Использование текущей строки (Table-уровень; ≠ command-level CurrentRowUse) — pass-through
  2031. $cru = Get-Child $node 'CurrentRowUse'; if ($cru) { $obj['currentRowUse'] = $cru }
  2032. # Запрос обновления дин-списка (всегда PullFromTop в корпусе) — pass-through
  2033. $rr = Get-Child $node 'RefreshRequest'; if ($rr) { $obj['refreshRequest'] = $rr }
  2034. # CommandBarLocation: для дин-список-таблицы компилятор авто-инжектит "None" → инвертируем
  2035. # (нет тега → суппресс-маркер ""; "None" → опускаем = авто-дефолт; иначе → захват).
  2036. $cbl = Get-Child $node 'CommandBarLocation'
  2037. if (Has-Child $node 'UpdateOnDataChange') {
  2038. if ($null -eq $cbl) { $obj['commandBarLocation'] = '' }
  2039. elseif ($cbl -ne 'None') { $obj['commandBarLocation'] = $cbl }
  2040. } elseif ($cbl) { $obj['commandBarLocation'] = $cbl }
  2041. $ssl = Get-Child $node 'SearchStringLocation'; if ($ssl) { $obj['searchStringLocation'] = $ssl }
  2042. $vsl = Get-Child $node 'ViewStatusLocation'; if ($vsl) { $obj['viewStatusLocation'] = $vsl }
  2043. $scl = Get-Child $node 'SearchControlLocation'; if ($scl) { $obj['searchControlLocation'] = $scl }
  2044. # --- Общие свойства таблицы (любой тип таблицы, не только динсписок) ---
  2045. if ((Get-Child $node 'ChoiceMode') -eq 'true') { $obj['choiceMode'] = $true }
  2046. $selm = Get-Child $node 'SelectionMode'; if ($selm) { $obj['selectionMode'] = $selm }
  2047. $rsm = Get-Child $node 'RowSelectionMode'; if ($rsm) { $obj['rowSelectionMode'] = $rsm }
  2048. if ((Get-Child $node 'VerticalLines') -eq 'false') { $obj['verticalLines'] = $false }
  2049. if ((Get-Child $node 'HorizontalLines') -eq 'false') { $obj['horizontalLines'] = $false }
  2050. if ((Get-Child $node 'UseAlternationRowColor') -eq 'true') { $obj['useAlternationRowColor'] = $true }
  2051. # Скаляры таблицы (захват «как есть»). Autofill — СВОЁ свойство таблицы (≠ AutoCommandBar autofill).
  2052. $taf = Get-Child $node 'Autofill'; if ($null -ne $taf) { $obj['autofill'] = ($taf -eq 'true') }
  2053. if ((Get-Child $node 'MultipleChoice') -eq 'true') { $obj['multipleChoice'] = $true }
  2054. $soin = Get-Child $node 'SearchOnInput'; if ($soin) { $obj['searchOnInput'] = $soin }
  2055. $mi = Get-Child $node 'AutoMarkIncomplete'; if ($null -ne $mi) { $obj['markIncomplete'] = ($mi -eq 'true') }
  2056. $itv = Get-Child $node 'InitialTreeView'; if ($itv) { $obj['initialTreeView'] = $itv }
  2057. # RowsPicture — конвенция ValuesPicture (Ref/Abs + LoadTransparent дефолт false + TransparentPixel)
  2058. $rp = Get-PictureRef $node 'RowsPicture'; if ($null -ne $rp) { $obj['rowsPicture'] = $rp }
  2059. $rpdp = Get-Child $node 'RowPictureDataPath'
  2060. # --- Блок дин-список-таблицы (признак: дочерний <UpdateOnDataChange>) ---
  2061. if (Has-Child $node 'UpdateOnDataChange') {
  2062. if ((Get-Child $node 'AutoRefresh') -eq 'true') { $obj['autoRefresh'] = $true }
  2063. $arp = Get-Child $node 'AutoRefreshPeriod'; if ($arp -and $arp -ne '60') { $obj['autoRefreshPeriod'] = [int]$arp }
  2064. $cfi = Get-Child $node 'ChoiceFoldersAndItems'; if ($cfi -and $cfi -ne 'Items') { $obj['choiceFoldersAndItems'] = $cfi }
  2065. if ((Get-Child $node 'RestoreCurrentRow') -eq 'true') { $obj['restoreCurrentRow'] = $true }
  2066. if ((Get-Child $node 'ShowRoot') -eq 'false') { $obj['showRoot'] = $false }
  2067. if ((Get-Child $node 'AllowRootChoice') -eq 'true') { $obj['allowRootChoice'] = $true }
  2068. $uodc = Get-Child $node 'UpdateOnDataChange'; if ($uodc -and $uodc -ne 'Auto') { $obj['updateOnDataChange'] = $uodc }
  2069. if ((Get-Child $node 'AllowGettingCurrentRowURL') -eq 'false') { $obj['allowGettingCurrentRowURL'] = $false }
  2070. # RowPictureDataPath: инверсия умного дефолта <Список>.DefaultPicture. У списка с явным ключом
  2071. # без основной таблицы умолчание — отсутствие (компилятор его не ставит): ""-маркер не нужен,
  2072. # а любое значение — явное.
  2073. if (Test-DynListExplicitKey "$($obj['path'])") {
  2074. if ($null -ne $rpdp) { $obj['rowPictureDataPath'] = $rpdp }
  2075. }
  2076. elseif ($null -eq $rpdp) { $obj['rowPictureDataPath'] = '' }
  2077. elseif ($rpdp -ne "$($obj['path']).DefaultPicture") { $obj['rowPictureDataPath'] = $rpdp }
  2078. $usg = Get-Child $node 'UserSettingsGroup'
  2079. if ($usg) { if ($usg -match '^\d+:[0-9a-fA-F]{8}-') { [Console]::Error.WriteLine("form-decompile: UserSettingsGroup '$usg' ($name) — ссылка по id, не воспроизводима, опущена") } else { $obj['userSettingsGroup'] = $usg } }
  2080. } elseif ($rpdp) { $obj['rowPictureDataPath'] = $rpdp }
  2081. $csNode = $node.SelectSingleNode("lf:CommandSet", $ns)
  2082. if ($csNode) {
  2083. $exc = New-Object System.Collections.ArrayList
  2084. foreach ($ec in @($csNode.SelectNodes("lf:ExcludedCommand", $ns))) { [void]$exc.Add($ec.InnerText) }
  2085. if ($exc.Count -gt 0) { $obj['excludedCommands'] = @($exc) }
  2086. }
  2087. $cols = Decompile-Children $node
  2088. if ($cols) { $obj['columns'] = $cols }
  2089. # Стандартные дополнения уровня таблицы (прямые дети) → карта отклонений additions
  2090. $addMap = Decompile-TableAdditions $node $name
  2091. if ($addMap) { $obj['additions'] = $addMap }
  2092. }
  2093. 'Pages' {
  2094. $obj[$key] = $name
  2095. Add-CommonProps $obj $node $name
  2096. $pr = Get-Child $node 'PagesRepresentation'; if ($pr) { $obj['pagesRepresentation'] = $pr }
  2097. $cru = Get-Child $node 'CurrentRowUse'; if ($cru) { $obj['currentRowUse'] = $cru }
  2098. $kids = Decompile-Children $node
  2099. if ($kids) { $obj['children'] = $kids }
  2100. }
  2101. 'Page' {
  2102. $obj[$key] = $name
  2103. Add-CommonProps $obj $node $name
  2104. $g = Get-Child $node 'Group'
  2105. $gmap = @{ 'Horizontal'='horizontal'; 'Vertical'='vertical'; 'AlwaysHorizontal'='alwaysHorizontal'; 'AlwaysVertical'='alwaysVertical'; 'HorizontalIfPossible'='horizontalIfPossible' }
  2106. if ($g -and $gmap.ContainsKey($g)) { $obj['group'] = $gmap[$g] }
  2107. # Картинка страницы (иконка вкладки) — конвенция ValuesPicture (дефолт LoadTransparent=false)
  2108. $pp = Get-PictureRef $node 'Picture'; if ($null -ne $pp) { $obj['picture'] = $pp }
  2109. $st = Get-Child $node 'ShowTitle'; if ($null -ne $st) { $obj['showTitle'] = ($st -eq 'true') } # факт. значение (явный true тоже)
  2110. # Формат значения пути к данным заголовка (<Format>; парный к titleDataPath страницы)
  2111. Add-FormatProps $obj $node
  2112. $kids = Decompile-Children $node
  2113. if ($kids) { $obj['children'] = $kids }
  2114. }
  2115. 'Button' {
  2116. $obj[$key] = $name
  2117. $cmd = Get-Child $node 'CommandName'
  2118. if ($cmd) {
  2119. if ($cmd -match '^Form\.Command\.(.+)$') { $obj['command'] = $matches[1] }
  2120. elseif ($cmd -match '^Form\.StandardCommand\.(.+)$') { $obj['stdCommand'] = $matches[1] }
  2121. elseif ($cmd -match '^Form\.Item\.(.+)\.StandardCommand\.(.+)$') { $obj['stdCommand'] = "$($matches[1]).$($matches[2])" }
  2122. else { $obj['commandName'] = $cmd }
  2123. }
  2124. $dp = Get-Child $node 'DataPath'; if ($dp) { $obj['path'] = $dp }
  2125. # Parameter команды: xr:MDObjectRef (объект метаданных, строка) или v8:TypeDescription (тип → {type})
  2126. $btnParam = $node.SelectSingleNode("lf:Parameter", $ns)
  2127. if ($btnParam) {
  2128. $pxt = $btnParam.GetAttribute("type", $NS_XSI)
  2129. if ($pxt -match 'TypeDescription$') { $pt = Decompile-Type $btnParam; if ($pt) { $obj['parameter'] = [ordered]@{ type = $pt } } }
  2130. elseif ($btnParam.InnerText) { $obj['parameter'] = $btnParam.InnerText }
  2131. }
  2132. Add-CommonProps $obj $node $name
  2133. $type = Get-Child $node 'Type'
  2134. if ($type) { $tmap=@{'CommandBarButton'='commandBar';'UsualButton'='usual';'Hyperlink'='hyperlink';'CommandBarHyperlink'='hyperlink'}; if ($tmap.ContainsKey($type)) { $obj['type']=$tmap[$type] } else { $obj['type']=$type } }
  2135. if ((Get-Child $node 'DefaultButton') -eq 'true') { $obj['defaultButton'] = $true }
  2136. if ((Get-Child $node 'Check') -eq 'true') { $obj['checked'] = $true }
  2137. Set-CommandPicture $obj $node
  2138. $rep = Get-Child $node 'Representation'; if ($rep) { $obj['representation'] = $rep }
  2139. $lic = Get-Child $node 'LocationInCommandBar'; if ($lic) { $obj['locationInCommandBar'] = $lic }
  2140. }
  2141. 'ButtonGroup' {
  2142. $obj[$key] = $name
  2143. Add-CommonProps $obj $node $name
  2144. $cs = Get-Child $node 'CommandSource'
  2145. if ($cs) { if ($cs -match '^\d+:[0-9a-fA-F]{8}-') { [Console]::Error.WriteLine("form-decompile: CommandSource '$cs' ($name) — ссылка по id, не воспроизводима, опущена") } else { $obj['commandSource'] = $cs } }
  2146. $rep = Get-Child $node 'Representation'; if ($rep) { $obj['representation'] = $rep }
  2147. $kids = Decompile-Children $node
  2148. if ($kids) { $obj['children'] = $kids }
  2149. }
  2150. 'CommandBar' {
  2151. $obj[$key] = $name
  2152. Add-CommonProps $obj $node $name
  2153. $cs = Get-Child $node 'CommandSource'
  2154. if ($cs) { if ($cs -match '^\d+:[0-9a-fA-F]{8}-') { [Console]::Error.WriteLine("form-decompile: CommandSource '$cs' ($name) — ссылка по id, не воспроизводима, опущена") } else { $obj['commandSource'] = $cs } }
  2155. $hl = Get-Child $node 'HorizontalLocation'; if ($hl) { $obj['horizontalLocation'] = $hl.ToLower() }
  2156. if ((Get-Child $node 'Autofill') -eq 'true') { $obj['autofill'] = $true }
  2157. $kids = Decompile-Children $node
  2158. if ($kids) { $obj['children'] = $kids }
  2159. }
  2160. 'Popup' {
  2161. $obj[$key] = $name
  2162. Add-CommonProps $obj $node $name
  2163. Set-CommandPicture $obj $node
  2164. $rep = Get-Child $node 'Representation'; if ($rep) { $obj['representation'] = $rep }
  2165. # Источник команд попапа (Form / FormCommandPanelGlobalCommands / Item.X) — как у ButtonGroup/CommandBar
  2166. $cs = Get-Child $node 'CommandSource'
  2167. if ($cs) { if ($cs -match '^\d+:[0-9a-fA-F]{8}-') { [Console]::Error.WriteLine("form-decompile: CommandSource '$cs' ($name) — ссылка по id, не воспроизводима, опущена") } else { $obj['commandSource'] = $cs } }
  2168. $kids = Decompile-Children $node
  2169. if ($kids) { $obj['children'] = $kids }
  2170. }
  2171. 'SearchStringAddition' { $obj[$key] = $name; Add-AdditionCore $obj $node $name }
  2172. 'ViewStatusAddition' { $obj[$key] = $name; Add-AdditionCore $obj $node $name }
  2173. 'SearchControlAddition' { $obj[$key] = $name; Add-AdditionCore $obj $node $name }
  2174. 'SpreadSheetDocumentField' { Decompile-SimpleField $obj $node $name $key }
  2175. 'HTMLDocumentField' { Decompile-SimpleField $obj $node $name $key }
  2176. 'TextDocumentField' { Decompile-SimpleField $obj $node $name $key }
  2177. 'FormattedDocumentField' { Decompile-SimpleField $obj $node $name $key }
  2178. 'ProgressBarField' { Decompile-SimpleField $obj $node $name $key; Add-GaugeScalars $obj $node @('MinValue','MaxValue') }
  2179. 'TrackBarField' { Decompile-SimpleField $obj $node $name $key; Add-GaugeScalars $obj $node @('MinValue','MaxValue','LargeStep','MarkingStep','Step') }
  2180. 'ChartField' { Decompile-SimpleField $obj $node $name $key }
  2181. 'GraphicalSchemaField' { Decompile-SimpleField $obj $node $name $key }
  2182. 'PlannerField' { Decompile-SimpleField $obj $node $name $key }
  2183. 'PeriodField' { Decompile-SimpleField $obj $node $name $key }
  2184. 'DendrogramField' { Decompile-SimpleField $obj $node $name $key }
  2185. 'GanttChartField' {
  2186. Decompile-SimpleField $obj $node $name $key
  2187. # Вложенная <Table> (полноценная таблица) — переиспользуем общий Decompile-Element.
  2188. # Ключ ganttTable (не 'table' — во избежание коллизии с тип-ключом таблицы в диспетчере).
  2189. $tblNode = $node.SelectSingleNode("lf:Table", $ns)
  2190. if ($tblNode) { $obj['ganttTable'] = Decompile-Element $tblNode }
  2191. }
  2192. }
  2193. # DisplayImportance — атрибут открывающего тега (адаптивная важность отображения), захват «как есть».
  2194. $di = $node.GetAttribute("DisplayImportance"); if ($di) { $obj['displayImportance'] = $di }
  2195. # title: "" — подавление авто-вывода: для типов, где компилятор вывел бы
  2196. # заголовок из имени, а в оригинале <Title> отсутствует.
  2197. if (-not $obj.Contains('title')) {
  2198. $autoTitle = $false
  2199. if ($tag -in @('LabelDecoration','Page','Popup')) { $autoTitle = $true }
  2200. elseif ($tag -eq 'Button') { $autoTitle = -not ($obj.Contains('command') -or $obj.Contains('commandName') -or $obj.Contains('stdCommand')) }
  2201. elseif ($tag -in @('InputField','CheckBoxField','RadioButtonField','LabelField','Table','CalendarField')) { $autoTitle = -not $obj.Contains('path') }
  2202. if ($autoTitle) { $obj['title'] = '' }
  2203. }
  2204. Add-Layout $obj $node
  2205. Add-GenericScalars $obj $node
  2206. # extendedTooltip: companion <ExtendedTooltip> (это LabelDecoration). Текст-форма (только <Title>) →
  2207. # строка/{text,formatted}. Own-content (layout/оформление/флаги/hyperlink/events) → объект { text?, … }.
  2208. $etNode = $node.SelectSingleNode("lf:ExtendedTooltip", $ns)
  2209. if ($etNode) {
  2210. $etTitle = $etNode.SelectSingleNode("lf:Title", $ns)
  2211. $textVal = if ($etTitle) { Get-MLFormattedValue $etTitle } else { $null }
  2212. $etObj = [ordered]@{}
  2213. Add-Layout $etObj $etNode
  2214. Add-GenericScalars $etObj $etNode
  2215. Add-Appearance $etObj $etNode
  2216. # ToolTip самого компаньона (подсказка расширенной подсказки) — реальный текст (ML), не пустой Title
  2217. $etTT = $etNode.SelectSingleNode("lf:ToolTip", $ns)
  2218. if ($etTT) { $ttVal = Get-LangText $etTT; if ($null -ne $ttVal) { $etObj['tooltip'] = $ttVal } }
  2219. if ((Get-Child $etNode 'Visible') -eq 'false') { $etObj['hidden'] = $true }
  2220. if ((Get-Child $etNode 'Enabled') -eq 'false') { $etObj['disabled'] = $true }
  2221. if ((Get-Child $etNode 'Hyperlink') -eq 'true') { $etObj['hyperlink'] = $true }
  2222. # События компаньона (напр. URLProcessing у hyperlink-подсказки) — переиспользуем механизм событий элемента
  2223. $etEv = Get-Events $etNode $name; if ($etEv) { $etObj['events'] = $etEv }
  2224. if ($etObj.Count -gt 0) {
  2225. if ($null -ne $textVal) {
  2226. if ($textVal -is [System.Collections.IDictionary] -and $textVal.Contains('text')) { $etObj['text'] = $textVal['text']; if ($textVal['formatted']) { $etObj['formatted'] = $true } }
  2227. else { $etObj['text'] = $textVal }
  2228. # formatted ЯВНО из атрибута Title — компилятор не re-детектит markup на мультиязычном тексте
  2229. if (-not $etObj.Contains('formatted') -and $etTitle -and $etTitle.GetAttribute('formatted') -eq 'true') { $etObj['formatted'] = $true }
  2230. }
  2231. $obj['extendedTooltip'] = $etObj
  2232. } elseif ($null -ne $textVal) {
  2233. $obj['extendedTooltip'] = $textVal
  2234. }
  2235. }
  2236. # companion-панели с контентом: AutoCommandBar → commandBar, ContextMenu → contextMenu (любой элемент)
  2237. $isDynListTable = ($tag -eq 'Table') -and (Has-Child $node 'UpdateOnDataChange')
  2238. $cb = Decompile-CompanionPanel $node 'AutoCommandBar' $isDynListTable
  2239. if ($null -ne $cb) { $obj['commandBar'] = $cb }
  2240. $cm = Decompile-CompanionPanel $node 'ContextMenu'
  2241. if ($null -ne $cm) { $obj['contextMenu'] = $cm }
  2242. return $obj
  2243. }
  2244. # ─────────────────────────────────────────────────────────────────────────────
  2245. # Planner design-time <Settings xsi:type="pl:Planner"> → объект planner на реквизите.
  2246. # Полный захват каждого поля (раундтрип бит-в-бит); зеркало Emit-PlannerSettings.
  2247. function PLD-Bool { param($v) if ($null -eq $v) { return $null } return ($v -eq 'true') }
  2248. function PLD-Int { param($v) if ($null -eq $v) { return $null } return [int]$v }
  2249. # <pl:value> → текст (тип xr:DesignTimeRef/xs:string выводится компилятором из вида значения); nil → $null.
  2250. function Get-PlannerValue {
  2251. param($node)
  2252. if (-not $node) { return $null }
  2253. if ($node.GetAttribute('nil', $NS_XSI) -eq 'true') { return $null }
  2254. if ($node.InnerText) { return $node.InnerText } else { return $null }
  2255. }
  2256. function Build-PlannerFont {
  2257. param($node)
  2258. if (-not $node) { return $null }
  2259. $o = [ordered]@{}
  2260. foreach ($a in @('ref','faceName','height','bold','italic','underline','strikeout','kind','scale')) {
  2261. $av = $node.GetAttribute($a); if ($av -ne '') { $o[$a] = $av }
  2262. }
  2263. if ($o.Count -eq 0) { return $null }
  2264. return $o
  2265. }
  2266. function Build-PlannerBorder {
  2267. param($node)
  2268. if (-not $node) { return $null }
  2269. $o = [ordered]@{}
  2270. $w = $node.GetAttribute('width'); if ($w -ne '') { $o['width'] = [int]$w }
  2271. $st = $node.SelectSingleNode("*[local-name()='style']"); if ($st) { $o['style'] = $st.InnerText }
  2272. return $o
  2273. }
  2274. function Build-PlannerItem {
  2275. param($itn)
  2276. $o = [ordered]@{}
  2277. $valNode = $itn.SelectSingleNode("*[local-name()='value']")
  2278. if ($valNode -and $valNode.GetAttribute('nil', $NS_XSI) -ne 'true' -and $valNode.InnerText) { $o['value'] = $valNode.InnerText }
  2279. $o['text'] = (Get-Child $itn 'text')
  2280. $tt = Get-Child $itn 'tooltip'; if ($tt) { $o['tooltip'] = $tt }
  2281. $o['begin'] = (Get-Child $itn 'begin')
  2282. $o['end'] = (Get-Child $itn 'end')
  2283. $o['borderColor'] = (Get-Child $itn 'borderColor')
  2284. $o['backColor'] = (Get-Child $itn 'backColor')
  2285. $o['textColor'] = (Get-Child $itn 'textColor')
  2286. $fnt = Build-PlannerFont ($itn.SelectSingleNode("*[local-name()='font']")); if ($fnt) { $o['font'] = $fnt }
  2287. $o['replacementDate'] = (Get-Child $itn 'replacementDate')
  2288. $o['deleted'] = (PLD-Bool (Get-Child $itn 'deleted'))
  2289. $o['id'] = (Get-Child $itn 'id')
  2290. $o['textFormatted'] = (PLD-Bool (Get-Child $itn 'textFormatted'))
  2291. $brd = Build-PlannerBorder ($itn.SelectSingleNode("*[local-name()='border']")); if ($brd) { $o['border'] = $brd }
  2292. $o['editMode'] = (Get-Child $itn 'editMode')
  2293. return $o
  2294. }
  2295. function Build-PlannerDimElement {
  2296. param($eln)
  2297. $o = [ordered]@{}
  2298. $v = Get-PlannerValue ($eln.SelectSingleNode("*[local-name()='value']")); if ($null -ne $v) { $o['value'] = $v }
  2299. $o['text'] = (Get-Child $eln 'text')
  2300. $o['borderColor'] = (Get-Child $eln 'borderColor')
  2301. $o['backColor'] = (Get-Child $eln 'backColor')
  2302. $o['textColor'] = (Get-Child $eln 'textColor')
  2303. $fnt = Build-PlannerFont ($eln.SelectSingleNode("*[local-name()='font']")); if ($fnt) { $o['font'] = $fnt }
  2304. $subs = New-Object System.Collections.ArrayList
  2305. foreach ($s in @($eln.SelectNodes("*[local-name()='item']"))) { [void]$subs.Add((Build-PlannerDimElement $s)) }
  2306. if ($subs.Count -gt 0) { $o['elements'] = @($subs) }
  2307. $sos = Get-Child $eln 'showOnlySubordinatesAreas'; if ($null -ne $sos) { $o['showOnlySubordinatesAreas'] = ($sos -eq 'true') }
  2308. $o['textFormatted'] = (PLD-Bool (Get-Child $eln 'textFormatted'))
  2309. return $o
  2310. }
  2311. function Build-PlannerDimension {
  2312. param($dn)
  2313. $o = [ordered]@{}
  2314. $v = Get-PlannerValue ($dn.SelectSingleNode("*[local-name()='value']")); if ($null -ne $v) { $o['value'] = $v }
  2315. $o['text'] = (Get-Child $dn 'text')
  2316. $o['borderColor'] = (Get-Child $dn 'borderColor')
  2317. $o['backColor'] = (Get-Child $dn 'backColor')
  2318. $o['textColor'] = (Get-Child $dn 'textColor')
  2319. $fnt = Build-PlannerFont ($dn.SelectSingleNode("*[local-name()='font']")); if ($fnt) { $o['font'] = $fnt }
  2320. $els = New-Object System.Collections.ArrayList
  2321. foreach ($e in @($dn.SelectNodes("*[local-name()='item']"))) { [void]$els.Add((Build-PlannerDimElement $e)) }
  2322. if ($els.Count -gt 0) { $o['elements'] = @($els) }
  2323. $o['textFormatted'] = (PLD-Bool (Get-Child $dn 'textFormatted'))
  2324. return $o
  2325. }
  2326. function Build-PlannerLevel {
  2327. param($lvn)
  2328. $o = [ordered]@{}
  2329. $o['measure'] = (Get-Child $lvn 'measure')
  2330. $o['interval'] = (PLD-Int (Get-Child $lvn 'interval'))
  2331. $o['show'] = (PLD-Bool (Get-Child $lvn 'show'))
  2332. $lineNode = $lvn.SelectSingleNode("*[local-name()='line']")
  2333. if ($lineNode) {
  2334. $ln = [ordered]@{}
  2335. $w = $lineNode.GetAttribute('width'); if ($w -ne '') { $ln['width'] = [int]$w }
  2336. $g = $lineNode.GetAttribute('gap'); if ($g -ne '') { $ln['gap'] = ($g -eq 'true') }
  2337. $st = $lineNode.SelectSingleNode("*[local-name()='style']"); if ($st) { $ln['style'] = $st.InnerText }
  2338. $o['line'] = $ln
  2339. }
  2340. $o['scaleColor'] = (Get-Child $lvn 'scaleColor')
  2341. $o['dayFormatRule'] = (Get-Child $lvn 'dayFormatRule')
  2342. $fmtNode = $lvn.SelectSingleNode("*[local-name()='format']")
  2343. if ($fmtNode) { $f = Get-LangText $fmtNode; if ($null -ne $f) { $o['format'] = $f } }
  2344. $labelsNode = $lvn.SelectSingleNode("*[local-name()='labels']")
  2345. if ($labelsNode) { $o['labels'] = [ordered]@{ ticks = (PLD-Int (Get-Child $labelsNode 'ticks')) } }
  2346. $o['backColor'] = (Get-Child $lvn 'backColor')
  2347. $o['textColor'] = (Get-Child $lvn 'textColor')
  2348. $o['showPereodicalLabels'] = (PLD-Bool (Get-Child $lvn 'showPereodicalLabels'))
  2349. return $o
  2350. }
  2351. function Build-PlannerTimeScale {
  2352. param($tsn)
  2353. $o = [ordered]@{}
  2354. $o['placement'] = (Get-Child $tsn 'placement')
  2355. $levels = New-Object System.Collections.ArrayList
  2356. foreach ($lvn in @($tsn.SelectNodes("*[local-name()='level']"))) { [void]$levels.Add((Build-PlannerLevel $lvn)) }
  2357. $o['levels'] = @($levels)
  2358. $o['transparent'] = (PLD-Bool (Get-Child $tsn 'transparent'))
  2359. $o['backColor'] = (Get-Child $tsn 'backColor')
  2360. $o['textColor'] = (Get-Child $tsn 'textColor')
  2361. $o['currentLevel'] = (PLD-Int (Get-Child $tsn 'currentLevel'))
  2362. return $o
  2363. }
  2364. function Build-PlannerSettings {
  2365. param($setNode)
  2366. $pl = [ordered]@{}
  2367. $itemNodes = @($setNode.SelectNodes("*[local-name()='item']"))
  2368. if ($itemNodes.Count -gt 0) {
  2369. $items = New-Object System.Collections.ArrayList
  2370. foreach ($itn in $itemNodes) { [void]$items.Add((Build-PlannerItem $itn)) }
  2371. $pl['items'] = @($items)
  2372. }
  2373. $dimNodes = @($setNode.SelectNodes("*[local-name()='dimension']"))
  2374. if ($dimNodes.Count -gt 0) {
  2375. $dims = New-Object System.Collections.ArrayList
  2376. foreach ($dn in $dimNodes) { [void]$dims.Add((Build-PlannerDimension $dn)) }
  2377. $pl['dimensions'] = @($dims)
  2378. }
  2379. $pl['borderColor'] = (Get-Child $setNode 'borderColor')
  2380. $pl['backColor'] = (Get-Child $setNode 'backColor')
  2381. $pl['textColor'] = (Get-Child $setNode 'textColor')
  2382. $pl['lineColor'] = (Get-Child $setNode 'lineColor')
  2383. $fnt = Build-PlannerFont ($setNode.SelectSingleNode("*[local-name()='font']")); if ($fnt) { $pl['font'] = $fnt }
  2384. $pl['beginOfRepresentationPeriod'] = (Get-Child $setNode 'beginOfRepresentationPeriod')
  2385. $pl['endOfRepresentationPeriod'] = (Get-Child $setNode 'endOfRepresentationPeriod')
  2386. $pl['alignElementsOfTimeScale'] = (PLD-Bool (Get-Child $setNode 'alignElementsOfTimeScale'))
  2387. $pl['displayTimeScaleWrapHeaders'] = (PLD-Bool (Get-Child $setNode 'displayTimeScaleWrapHeaders'))
  2388. $pl['displayWrapHeaders'] = (PLD-Bool (Get-Child $setNode 'displayWrapHeaders'))
  2389. $wfNode = $setNode.SelectSingleNode("*[local-name()='timeScaleWrapHeadersFormat']")
  2390. if ($wfNode) { $wf = Get-LangText $wfNode; if ($null -ne $wf) { $pl['timeScaleWrapHeadersFormat'] = $wf } }
  2391. $pl['periodicVariantUnit'] = (Get-Child $setNode 'periodicVariantUnit')
  2392. $pl['periodicVariantRepetition'] = (PLD-Int (Get-Child $setNode 'periodicVariantRepetition'))
  2393. $pl['timeScaleWrapBeginIndent'] = (PLD-Int (Get-Child $setNode 'timeScaleWrapBeginIndent'))
  2394. $pl['timeScaleWrapEndIndent'] = (PLD-Int (Get-Child $setNode 'timeScaleWrapEndIndent'))
  2395. $tsNode = $setNode.SelectSingleNode("*[local-name()='timeScale']")
  2396. if ($tsNode) { $pl['timeScale'] = (Build-PlannerTimeScale $tsNode) }
  2397. $perNode = $setNode.SelectSingleNode("*[local-name()='period']")
  2398. if ($perNode) { $pl['period'] = [ordered]@{ begin = (Get-Child $perNode 'begin'); end = (Get-Child $perNode 'end') } }
  2399. $pl['displayCurrentDate'] = (PLD-Bool (Get-Child $setNode 'displayCurrentDate'))
  2400. $pl['itemsTimeRepresentation'] = (Get-Child $setNode 'itemsTimeRepresentation')
  2401. $pl['itemsBehaviorWhenSpaceInsufficient'] = (Get-Child $setNode 'itemsBehaviorWhenSpaceInsufficient')
  2402. $pl['autoMinColumnWidth'] = (PLD-Bool (Get-Child $setNode 'autoMinColumnWidth'))
  2403. $pl['autoMinRowHeight'] = (PLD-Bool (Get-Child $setNode 'autoMinRowHeight'))
  2404. $pl['minColumnWidth'] = (PLD-Int (Get-Child $setNode 'minColumnWidth'))
  2405. $pl['minRowHeight'] = (PLD-Int (Get-Child $setNode 'minRowHeight'))
  2406. $pl['fixDimensionsHeader'] = (Get-Child $setNode 'fixDimensionsHeader')
  2407. $pl['fixTimeScaleHeader'] = (Get-Child $setNode 'fixTimeScaleHeader')
  2408. $brd = Build-PlannerBorder ($setNode.SelectSingleNode("*[local-name()='border']")); if ($brd) { $pl['border'] = $brd }
  2409. $pl['newItemsTextType'] = (Get-Child $setNode 'newItemsTextType')
  2410. return $pl
  2411. }
  2412. # ─────────────────────────────────────────────────────────────────────────────
  2413. # Chart design-time <Settings xsi:type="d4p1:Chart"> → объект chart. Генерик-движок:
  2414. # рекурсивный захват поддерева d4p1; структуры (line/border/font/ML/области/серии)
  2415. # детектируются по форме узла. Малые name-set'ы: ML-поля (даже ru-only/пустые → ML),
  2416. # серии (всегда массив), attrs-узлы. Порядок ключей JSON = порядок XML (раундтрип).
  2417. $CHART_ML_FIELDS = @{ 'title'=1;'lbFormat'=1;'lbpFormat'=1;'vsFormat'=1;'dtFormat'=1;'dataSourceDescription'=1;'labelFormat'=1;'text'=1 }
  2418. $CHART_SERIES_FIELDS = @{ 'realSeriesData'=1;'realExSeriesData'=1;'realPointData'=1;'realDataItems'=1 }
  2419. $CHART_ATTR_FIELDS = @{ 'gaugeQualityBands'=1 }
  2420. function Conv-ChartScalar {
  2421. param([string]$v)
  2422. if ($v -eq 'true') { return $true }
  2423. if ($v -eq 'false') { return $false }
  2424. return $v
  2425. }
  2426. function Build-ChartNode {
  2427. param($n, [string]$name)
  2428. # ML-поле → строка/мапа/"" (даже ru-only форсим в ML на эмите по имени)
  2429. if ($CHART_ML_FIELDS.Contains($name)) {
  2430. $ml = Get-LangText $n
  2431. if ($null -eq $ml) { return '' } else { return $ml }
  2432. }
  2433. $kids = @($n.SelectNodes("*"))
  2434. if ($kids.Count -eq 0) {
  2435. # лист: attrs-only (шрифт/gaugeQualityBands) или текст
  2436. $attrs = @($n.Attributes | Where-Object { $_.Name -ne 'xmlns' -and -not $_.Name.StartsWith('xmlns:') -and $_.Name -ne 'xsi:type' -and $_.Name -ne 'xsi:nil' })
  2437. if ($attrs.Count -gt 0) {
  2438. $o = [ordered]@{}; foreach ($a in $attrs) { $o[$a.Name] = (Conv-ChartScalar $a.Value) }; return $o
  2439. }
  2440. return (Conv-ChartScalar $n.InnerText)
  2441. }
  2442. # line/border: дочерний v8ui:style (+ width[/gap])
  2443. $styleChild = $n.SelectSingleNode("*[local-name()='style']")
  2444. if ($styleChild) {
  2445. $o = [ordered]@{}
  2446. $w = $n.GetAttribute('width'); if ($w -ne '') { $o['width'] = [int]$w }
  2447. $g = $n.GetAttribute('gap'); if ($g -ne '') { $o['gap'] = ($g -eq 'true') }
  2448. $o['style'] = $styleChild.InnerText
  2449. return $o
  2450. }
  2451. # вложенный объект d4p1 (область/шкала/titleArea/серия): группируем детей по имени
  2452. $o = [ordered]@{}
  2453. foreach ($c in $kids) {
  2454. $ln = $c.LocalName
  2455. $val = Build-ChartNode $c $ln
  2456. if ($CHART_SERIES_FIELDS.Contains($ln)) {
  2457. if (-not $o.Contains($ln)) { $o[$ln] = New-Object System.Collections.ArrayList }
  2458. [void]$o[$ln].Add($val)
  2459. } elseif ($o.Contains($ln)) {
  2460. if ($o[$ln] -isnot [System.Collections.IList]) { $tmp = New-Object System.Collections.ArrayList; [void]$tmp.Add($o[$ln]); $o[$ln] = $tmp }
  2461. [void]$o[$ln].Add($val)
  2462. } else {
  2463. $o[$ln] = $val
  2464. }
  2465. }
  2466. # нормализуем ArrayList → @() для сериализации
  2467. foreach ($k in @($o.Keys)) { if ($o[$k] -is [System.Collections.ArrayList]) { $o[$k] = @($o[$k]) } }
  2468. return $o
  2469. }
  2470. function Build-ChartSettings {
  2471. param($setNode)
  2472. return (Build-ChartNode $setNode '')
  2473. }
  2474. # --- 5. Form-level assembly ---
  2475. $dsl = [ordered]@{}
  2476. $titleNode = $root.SelectSingleNode("lf:Title", $ns)
  2477. if ($titleNode) { $t = Get-LangText $titleNode; if ($null -ne $t) { $dsl['title'] = $t } }
  2478. # properties (прямые скаляры под <Form>, PascalCase → camelCase)
  2479. $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')
  2480. $props = [ordered]@{}
  2481. foreach ($pn in $KNOWN_FORM_PROPS) {
  2482. $v = Get-Child $root $pn
  2483. if ($null -ne $v) {
  2484. $camel = $pn.Substring(0,1).ToLower() + $pn.Substring(1)
  2485. if ($v -eq 'true') { $props[$camel] = $true }
  2486. elseif ($v -eq 'false') { $props[$camel] = $false }
  2487. elseif ($v -match '^\d+$') { $props[$camel] = [int]$v }
  2488. else { $props[$camel] = $v }
  2489. }
  2490. }
  2491. # Ссылка на члена формы по id ("N:uuid") в groupList/customSettingsFolder НЕ воспроизводима: наш
  2492. # компилятор переназначает id, и ссылка указала бы не туда (либо вовсе dangling — платформа сама их
  2493. # часто не разрешает). Резолв в имя ненадёжен (N не всегда соответствует named-элементу). Игнорируем
  2494. # с предупреждением (имя задаётся вручную через form-edit). Имя-форма захватывается как есть.
  2495. foreach ($refKey in 'groupList','customSettingsFolder') {
  2496. if ($props.Contains($refKey) -and "$($props[$refKey])" -match '^\d+:[0-9a-fA-F]{8}-') {
  2497. [Console]::Error.WriteLine("form-decompile: $refKey = '$($props[$refKey])' — ссылка на члена формы по id, не воспроизводима (id переназначаются), опущена. Задайте по имени через form-edit.")
  2498. $props.Remove($refKey)
  2499. }
  2500. }
  2501. # AutoTitle при наличии title: компилятор инъектит false (~95% форм). Зеркалим:
  2502. # - оригинал имеет AutoTitle=false → опускаем ключ (компилятор реинъектит при наличии title);
  2503. # - оригинал НЕ имеет AutoTitle (редкие 5%, напр. вспом. формы) → суппресс-маркер "" (не инъектить).
  2504. if ($dsl.Contains('title')) {
  2505. if (-not $props.Contains('autoTitle')) { $props['autoTitle'] = '' }
  2506. elseif ($props['autoTitle'] -eq $false) { $props.Remove('autoTitle') }
  2507. }
  2508. if ($props.Count -gt 0) { $dsl['properties'] = $props }
  2509. # MobileDeviceCommandBarContent (form-level) → список имён командных панелей/кнопок
  2510. $mdcb = $root.SelectSingleNode("lf:MobileDeviceCommandBarContent", $ns)
  2511. if ($mdcb) {
  2512. $names = New-Object System.Collections.ArrayList
  2513. foreach ($it in @($mdcb.SelectNodes("xr:Item", $ns))) {
  2514. $v = $it.SelectSingleNode("xr:Value", $ns); if ($v) { [void]$names.Add($v.InnerText) }
  2515. }
  2516. if ($names.Count -gt 0) { $dsl['mobileCommandBarContent'] = @($names) }
  2517. }
  2518. # excludedCommands (form-level <CommandSet>)
  2519. $csForm = $root.SelectSingleNode("lf:CommandSet", $ns)
  2520. if ($csForm) {
  2521. $excForm = New-Object System.Collections.ArrayList
  2522. foreach ($ec in @($csForm.SelectNodes("lf:ExcludedCommand", $ns))) { [void]$excForm.Add($ec.InnerText) }
  2523. if ($excForm.Count -gt 0) { $dsl['excludedCommands'] = @($excForm) }
  2524. }
  2525. # events (form-level)
  2526. $evForm = Get-Events $root $null
  2527. if ($evForm) { $dsl['events'] = $evForm }
  2528. # Зеркало компилятор-эвристики B3 (Compute-MainAcbAutofill): наличие cmdBar-элемента где-либо
  2529. # в дереве → форменный AutoCommandBar autofill=false. Нужно, чтобы предсказать вывод и выразить
  2530. # отклонение (голый корень при наличии cmdBar).
  2531. function Test-AnyCmdBar {
  2532. param($list)
  2533. if (-not $list) { return $false }
  2534. foreach ($e in $list) {
  2535. if ($e -is [System.Collections.IDictionary] -and $e.Contains('cmdBar')) { return $true }
  2536. if ($e -is [System.Collections.IDictionary]) {
  2537. if ($e.Contains('children') -and (Test-AnyCmdBar $e['children'])) { return $true }
  2538. if ($e.Contains('columns') -and (Test-AnyCmdBar $e['columns'])) { return $true }
  2539. }
  2540. }
  2541. return $false
  2542. }
  2543. # elements (+ форменный AutoCommandBar как autoCmdBar-элемент, если у него есть содержимое/отклонение)
  2544. $elemList = New-Object System.Collections.ArrayList
  2545. $elements = Decompile-Children $root
  2546. $formHasCmdBar = Test-AnyCmdBar $elements
  2547. $acb = $root.SelectSingleNode("lf:AutoCommandBar", $ns)
  2548. if ($acb) {
  2549. $haln = Get-Child $acb 'HorizontalAlign'
  2550. $acbAutofill = Get-Child $acb 'Autofill'
  2551. $acbDI = $acb.GetAttribute("DisplayImportance") # адаптивная важность форменной панели (атрибут тега)
  2552. $acbKids = Decompile-Children $acb
  2553. $acbObj = $null
  2554. if ($haln -or ($acbAutofill -eq 'false') -or $acbKids -or $acbDI) {
  2555. $acbObj = [ordered]@{}
  2556. $acbObj['autoCmdBar'] = $acb.GetAttribute("name")
  2557. if ($acbDI) { $acbObj['displayImportance'] = $acbDI }
  2558. if ($haln) { $acbObj['horizontalAlign'] = $haln }
  2559. if ($acbAutofill -eq 'false') { $acbObj['autofill'] = $false }
  2560. if ($acbKids) { $acbObj['children'] = $acbKids }
  2561. } elseif ($formHasCmdBar -and $null -eq $acbAutofill) {
  2562. # Корень голый (autofill=true по умолчанию), но эвристика B3 дала бы false (есть cmdBar) → маркер
  2563. $acbObj = [ordered]@{}
  2564. $acbObj['autoCmdBar'] = $acb.GetAttribute("name")
  2565. $acbObj['autofill'] = $true
  2566. }
  2567. if ($acbObj) { [void]$elemList.Add($acbObj) }
  2568. }
  2569. if ($elements) { foreach ($e in $elements) { [void]$elemList.Add($e) } }
  2570. if ($elemList.Count -gt 0) { $dsl['elements'] = @($elemList) }
  2571. # attributes
  2572. # Объектный тип (зеркало Test-IsObjectLikeType компилятора) — кандидат на авто-main эвристики 11b.3.
  2573. function Test-IsObjectLikeTypeDec([string]$type) {
  2574. if ([string]::IsNullOrEmpty($type)) { return $false }
  2575. if ($type -eq 'DynamicList' -or $type -eq 'ConstantsSet') { return $true }
  2576. return ($type -match '^(CatalogObject|DocumentObject|DataProcessorObject|ReportObject|ExternalDataProcessorObject|ExternalReportObject|BusinessProcessObject|TaskObject|ChartOfAccountsObject|ChartOfCharacteristicTypesObject|ChartOfCalculationTypesObject|ExchangePlanObject|InformationRegisterRecordSet|AccumulationRegisterRecordSet|AccountingRegisterRecordSet|CalculationRegisterRecordSet|InformationRegisterRecordManager)\.')
  2577. }
  2578. $attrsNode = $root.SelectSingleNode("lf:Attributes", $ns)
  2579. if ($attrsNode) {
  2580. $attrs = New-Object System.Collections.ArrayList
  2581. # Подавление авто-main (эвристика компилятора 11b.3): если НЕТ ни одного <MainAttribute> И ровно
  2582. # один реквизит объектного типа — компилятор пометит его main. В оригинале он НЕ main (раз тега нет)
  2583. # → ставим суппресс-маркер main:false. На формах с >1 объектным реквизитом / с явным main — не нужно.
  2584. $allAttrNodes = @($attrsNode.SelectNodes("lf:Attribute", $ns))
  2585. $anyMainAttr = $false; $objLikeNodes = @()
  2586. foreach ($an in $allAttrNodes) {
  2587. if ((Get-Child $an 'MainAttribute') -eq 'true') { $anyMainAttr = $true }
  2588. $atype = Decompile-Type ($an.SelectSingleNode("lf:Type", $ns))
  2589. if (Test-IsObjectLikeTypeDec "$atype") { $objLikeNodes += $an }
  2590. }
  2591. $suppressMainName = if ((-not $anyMainAttr) -and $objLikeNodes.Count -eq 1) { $objLikeNodes[0].GetAttribute("name") } else { $null }
  2592. foreach ($a in $allAttrNodes) {
  2593. $ao = [ordered]@{}
  2594. $ao['name'] = $a.GetAttribute("name")
  2595. $ty = Decompile-Type ($a.SelectSingleNode("lf:Type", $ns)); if ($ty) { $ao['type'] = $ty }
  2596. # valueType: <Settings xsi:type="v8:TypeDescription"> — уточнение типа значений ValueList
  2597. # (та же грамматика типа). Дин-список Settings (xsi:type="DynamicList") обрабатывается отдельно.
  2598. $setNode = $a.SelectSingleNode("lf:Settings", $ns)
  2599. if ($setNode -and $setNode.GetAttribute("type", $NS_XSI) -match 'TypeDescription$') {
  2600. $vt = Decompile-Type $setNode
  2601. $ao['valueType'] = if ($vt) { $vt } else { '' } # пустой Settings → маркер ""
  2602. }
  2603. # Planner design-time <Settings xsi:type="pl:Planner"> → объект planner (полный захват).
  2604. elseif ($setNode -and $setNode.GetAttribute("type", $NS_XSI) -match 'Planner$') {
  2605. $ao['planner'] = Build-PlannerSettings $setNode
  2606. }
  2607. # Chart/GanttChart design-time <Settings xsi:type="d4p1:Chart"/"d4p1:GanttChart"> → chart (генерик).
  2608. elseif ($setNode -and $setNode.GetAttribute("type", $NS_XSI) -match 'd4p1:(Gantt)?Chart$') {
  2609. $ao['chart'] = Build-ChartSettings $setNode
  2610. }
  2611. if ((Get-Child $a 'MainAttribute') -eq 'true') { $ao['main'] = $true }
  2612. elseif ($suppressMainName -and $ao['name'] -eq $suppressMainName) { $ao['main'] = $false }
  2613. $vw = Decompile-XrFlag $a 'View'; if ($null -ne $vw) { $ao['view'] = $vw }
  2614. $ed = Decompile-XrFlag $a 'Edit'; if ($null -ne $ed) { $ao['edit'] = $ed }
  2615. # Title атрибута. Компилятор для не-main атрибута без ключа title додумывает заголовок
  2616. # из имени. Поэтому: нет <Title> → суппресс-маркер ''; ru-only == авто-вывод → опускаем
  2617. # ключ (компилятор воспроизведёт); иначе → явный заголовок.
  2618. $isMain = ($ao['main'] -eq $true) # именно true; main:false (суппресс-маркер) → не-main для Title
  2619. $tNode = $a.SelectSingleNode("lf:Title", $ns)
  2620. if ($tNode) {
  2621. $t = Get-LangTextWS $tNode # восстановление значимого пробела (whitespace-заголовок реквизита)
  2622. if ($null -ne $t) {
  2623. # Ordinal, а не -ne/-ceq: заголовок опускаем только при ТОЧНОМ, побайтовом совпадении
  2624. # с авто-выводом — компилятор восстановит его как есть, значим и регистр, и мягкий
  2625. # перенос, и форма нормализации.
  2626. if ($isMain -or -not ($t -is [string]) -or -not [string]::Equals($t, (Title-FromName $ao['name']), [StringComparison]::Ordinal)) { $ao['title'] = $t }
  2627. }
  2628. } elseif (-not $isMain) {
  2629. $ao['title'] = ''
  2630. }
  2631. # SavedData: компилятор додумывает true для main-реквизита объектного типа (эвристика $mainSaved:
  2632. # Catalog/Document/ChartOf*/ExchangePlan/BusinessProcess/Task Object + RecordManager). Если оригинал
  2633. # тега не имеет — ставим суппресс-маркер savedData:false (как с MainAttribute).
  2634. if ((Get-Child $a 'SavedData') -eq 'true') { $ao['savedData'] = $true }
  2635. elseif ($ao['main'] -eq $true -and "$($ao['type'])" -match '^(CatalogObject|DocumentObject|ChartOfAccountsObject|ChartOfCalculationTypesObject|ChartOfCharacteristicTypesObject|ExchangePlanObject|BusinessProcessObject|TaskObject)\.|RecordManager\.') { $ao['savedData'] = $false }
  2636. # Save: сохранение значения реквизита в пользовательских настройках. Один Field=имя → save:true;
  2637. # иначе снимаем префикс "имя." (голое имя/UUID/прочее — как есть) → строка (1) или массив.
  2638. $saveNode = $a.SelectSingleNode("lf:Save", $ns)
  2639. if ($saveNode) {
  2640. $nm = "$($ao['name'])"
  2641. $flds = @($saveNode.SelectNodes("lf:Field", $ns) | ForEach-Object { $_.InnerText })
  2642. if ($flds.Count -eq 1 -and $flds[0] -eq $nm) {
  2643. $ao['save'] = $true
  2644. } elseif ($flds.Count -gt 0) {
  2645. # Снимаем префикс "имя." ТОЛЬКО когда остаток — простое подполе, которое компилятор
  2646. # реинъектит (зеркало его условия: ≠имя, без точки, не UUID-ссылка ^N/M). Многоуровневый
  2647. # путь "имя.Settings.Filter" и UUID-ссылка "имя.1/0:GUID" компилятор эмитит как есть
  2648. # (префикс не вернёт) → храним ПОЛНЫЙ путь, иначе префикс теряется.
  2649. $stripped = @($flds | ForEach-Object {
  2650. if ($_ -match "^$([regex]::Escape($nm))\.([^.]+)$" -and $matches[1] -notmatch '^\d+/\d+') { $matches[1] } else { $_ }
  2651. })
  2652. if ($stripped.Count -eq 1) { $ao['save'] = $stripped[0] } else { $ao['save'] = $stripped }
  2653. }
  2654. }
  2655. $fc = Get-Child $a 'FillCheck'; if ($fc) { $ao['fillCheck'] = $fc }
  2656. $afo = Decompile-FunctionalOptions $a; if ($afo) { $ao['functionalOptions'] = $afo }
  2657. $colsNode = $a.SelectSingleNode("lf:Columns", $ns)
  2658. if ($colsNode) {
  2659. $cols = New-Object System.Collections.ArrayList
  2660. foreach ($c in @($colsNode.SelectNodes("lf:Column", $ns))) { [void]$cols.Add((Decompile-AttrColumn $c)) }
  2661. if ($cols.Count -gt 0) { $ao['columns'] = @($cols) }
  2662. # AdditionalColumns: доп. колонки табличных частей объекта (группа на табличную часть)
  2663. $addNodes = @($colsNode.SelectNodes("lf:AdditionalColumns", $ns))
  2664. if ($addNodes.Count -gt 0) {
  2665. $addList = New-Object System.Collections.ArrayList
  2666. foreach ($an in $addNodes) {
  2667. $acObj = [ordered]@{}; $acObj['table'] = $an.GetAttribute("table")
  2668. $acCols = New-Object System.Collections.ArrayList
  2669. foreach ($c in @($an.SelectNodes("lf:Column", $ns))) { [void]$acCols.Add((Decompile-AttrColumn $c)) }
  2670. $acObj['columns'] = @($acCols)
  2671. [void]$addList.Add($acObj)
  2672. }
  2673. $ao['additionalColumns'] = @($addList)
  2674. }
  2675. }
  2676. # UseAlways: поля, всегда читаемые. Префикс "ИмяРеквизита." снимаем.
  2677. # ValueTable (есть columns): useAlways:true на совпавшей колонке; остальные → массив атрибута.
  2678. # Дин-список/прочие (нет columns): массив useAlways на атрибуте.
  2679. $uaNode = $a.SelectSingleNode("lf:UseAlways", $ns)
  2680. if ($uaNode) {
  2681. $prefix = "$($ao['name'])."
  2682. $shorts = New-Object System.Collections.ArrayList
  2683. foreach ($fn in @($uaNode.SelectNodes("lf:Field", $ns))) {
  2684. $t = $fn.InnerText.Trim()
  2685. # Снимаем префикс "ИмяРеквизита.". Маркер "~" (query-поле дин-списка) сохраняем,
  2686. # префикс снимаем ПОСЛЕ него: ~Список.Остановлен → ~Остановлен (компилятор развернёт обратно).
  2687. if ($t.StartsWith('~')) {
  2688. $rest = $t.Substring(1)
  2689. if ($rest.StartsWith($prefix)) { $rest = $rest.Substring($prefix.Length) }
  2690. $t = "~$rest"
  2691. } elseif ($t.StartsWith($prefix)) {
  2692. $t = $t.Substring($prefix.Length)
  2693. }
  2694. [void]$shorts.Add($t)
  2695. }
  2696. if ($ao.Contains('columns')) {
  2697. $rest = New-Object System.Collections.ArrayList
  2698. foreach ($s in $shorts) {
  2699. $col = $ao['columns'] | Where-Object { $_['name'] -eq $s } | Select-Object -First 1
  2700. if ($col) { $col['useAlways'] = $true } else { [void]$rest.Add($s) }
  2701. }
  2702. if ($rest.Count -gt 0) { $ao['useAlways'] = @($rest) }
  2703. } elseif ($shorts.Count -gt 0) {
  2704. $ao['useAlways'] = @($shorts)
  2705. }
  2706. }
  2707. # Settings динамического списка (только xsi:type=DynamicList; Planner/TypeDescription — выше)
  2708. $setNode = $a.SelectSingleNode("lf:Settings", $ns)
  2709. if ($setNode -and $setNode.GetAttribute("type", $NS_XSI) -match 'DynamicList$') {
  2710. $so = [ordered]@{}
  2711. # AutoFillAvailableFields — дефолт true, платформа эмитит только отклонение (false). Захват «как есть».
  2712. $afaf = Get-Child $setNode 'AutoFillAvailableFields'; if ($null -ne $afaf) { $so['autoFillAvailableFields'] = ($afaf -eq 'true') }
  2713. $mt = Get-Child $setNode 'MainTable'; if ($mt) { $so['mainTable'] = $mt }
  2714. # GetInvisibleFieldPresentations — дефолт true, платформа эмитит только отклонение (false, корпус 20/20). Факт. значение.
  2715. $gifp = Get-Child $setNode 'GetInvisibleFieldPresentations'; if ($null -ne $gifp) { $so['getInvisibleFieldPresentations'] = ($gifp -eq 'true') }
  2716. # Ключ набора (query-based список): KeyType (RowNumber/FieldValue/RowKey) + KeyField* (0+).
  2717. $kt = Get-Child $setNode 'KeyType'; if ($kt) { $so['keyType'] = $kt }
  2718. $kfNodes = @($setNode.SelectNodes("lf:KeyField", $ns) | ForEach-Object { $_.InnerText })
  2719. if ($kfNodes.Count -gt 0) { $so['keyFields'] = @($kfNodes) }
  2720. # AutoSaveUserSettings — авто-сохранение польз. настроек дин-списка (в корпусе только false;
  2721. # дефолт true → платформа эмитит отклонение). Захват факт. значения.
  2722. $asus = Get-Child $setNode 'AutoSaveUserSettings'; if ($null -ne $asus) { $so['autoSaveUserSettings'] = ($asus -eq 'true') }
  2723. $qtNode = $setNode.SelectSingleNode("lf:QueryText", $ns)
  2724. $hasQ = [bool]($qtNode -and $qtNode.InnerText)
  2725. if ($hasQ) { $so['query'] = Maybe-ExternalizeQuery -queryText $qtNode.InnerText -listName "$($ao['name'])" }
  2726. # ManualQuery: компилятор выводит из наличия query (hasQuery → true). Платформа в редких
  2727. # случаях (корпус 16) хранит QueryText при ManualQuery=false → фиксируем отклонение от эвристики.
  2728. $mqV = Get-Child $setNode 'ManualQuery'
  2729. if ($null -ne $mqV) { $mqActual = ($mqV -eq 'true'); if ($mqActual -ne $hasQ) { $so['manualQuery'] = $mqActual } }
  2730. # DynamicDataRead: дефолт true → эмитим только false
  2731. if ((Get-Child $setNode 'DynamicDataRead') -eq 'false') { $so['dynamicDataRead'] = $false }
  2732. # Явные поля набора (редко, ~4.5%) — захват только при наличии Field
  2733. $fieldNodes = @($setNode.SelectNodes("lf:Field", $ns))
  2734. if ($fieldNodes.Count -gt 0) {
  2735. $fields = New-Object System.Collections.ArrayList
  2736. foreach ($fn in $fieldNodes) {
  2737. $fo = [ordered]@{}
  2738. $fld = Get-Child $fn 'field'
  2739. $dp = Get-Child $fn 'dataPath'
  2740. if ($fld) { $fo['field'] = $fld }
  2741. if ((Has-Child $fn 'dataPath') -and $dp -ne $fld) { $fo['dataPath'] = $dp }
  2742. # Тип поля набора: DataSetFieldField (дефолт, компилятор хардкодит) vs
  2743. # DataSetFieldNestedDataSet (поле-вложенный набор = реквизит табличной части). Маркер nested.
  2744. $fTypeAttr = $fn.GetAttribute("type", $NS_XSI)
  2745. if ($fTypeAttr -match 'NestedDataSet$') { $fo['nested'] = $true }
  2746. elseif ($fTypeAttr -match 'Folder$') { $fo['folder'] = $true }
  2747. $ftn = $fn.SelectSingleNode("dcssch:title", $ns)
  2748. if ($ftn) { $t = Get-LangText $ftn; if ($null -ne $t) { $fo['title'] = $t } }
  2749. # valueType поля набора (тип значения; вычисляемые/кастомные поля). Грамматика типа.
  2750. $fvt = $fn.SelectSingleNode("dcssch:valueType", $ns)
  2751. if ($fvt) { $fvtVal = Decompile-Type $fvt; if ($fvtVal) { $fo['valueType'] = $fvtVal } }
  2752. # presentationExpression (выражение представления поля) + appearance (формат/оформление поля)
  2753. $fpe = Get-Child $fn 'presentationExpression'
  2754. if ($null -ne $fpe -and $fpe -ne '') { $fo['presentationExpression'] = $fpe }
  2755. $fappNode = $fn.SelectSingleNode("dcssch:appearance", $ns)
  2756. if ($fappNode) { $fap = Get-SettingsAppearance $fappNode; if ($fap -and $fap.Count -gt 0) { $fo['appearance'] = $fap } }
  2757. $furNode = $fn.SelectSingleNode("dcssch:useRestriction", $ns)
  2758. if ($furNode) { $fur = Build-RestrictObj $furNode; if ($fur.Count -gt 0) { $fo['useRestriction'] = $fur } }
  2759. $faurNode = $fn.SelectSingleNode("dcssch:attributeUseRestriction", $ns)
  2760. if ($faurNode) { $faur = Build-RestrictObj $faurNode; if ($faur.Count -gt 0) { $fo['attributeUseRestriction'] = $faur } }
  2761. $fipNode = $fn.SelectSingleNode("dcssch:inputParameters", $ns)
  2762. if ($fipNode) { $fip = Build-DLInputParameters $fipNode; if (@($fip).Count -gt 0) { $fo['inputParameters'] = $fip } }
  2763. [void]$fields.Add($fo)
  2764. }
  2765. $so['fields'] = @($fields)
  2766. }
  2767. # Вычисляемые поля DataSet (<CalculatedField>) — после Field*, до Parameter*.
  2768. $calcNodes = @($setNode.SelectNodes("lf:CalculatedField", $ns))
  2769. if ($calcNodes.Count -gt 0) {
  2770. $cfs = New-Object System.Collections.ArrayList
  2771. foreach ($cn in $calcNodes) { [void]$cfs.Add((Build-CalcField $cn)) }
  2772. $so['calculatedFields'] = @($cfs)
  2773. }
  2774. # Schema-параметры дин-списка (прямые <Parameter> под Settings, не в ListSettings)
  2775. $paramNodes = @($setNode.SelectNodes("lf:Parameter", $ns))
  2776. if ($paramNodes.Count -gt 0) {
  2777. $dlPars = New-Object System.Collections.ArrayList
  2778. foreach ($pn in $paramNodes) { [void]$dlPars.Add((Build-DLParameter $pn)) }
  2779. $so['parameters'] = @($dlPars)
  2780. }
  2781. # ListSettings: пустой скелет (только viewMode+GUID) опускаем — компилятор
  2782. # регенерит каноничный скелет. Захватываем только контейнеры с реальными
  2783. # dcsset:item (filter/order/conditionalAppearance) в формат компилятора.
  2784. $lsNode = $setNode.SelectSingleNode("lf:ListSettings", $ns)
  2785. if ($lsNode) {
  2786. $fNode = $lsNode.SelectSingleNode("dcsset:filter", $ns)
  2787. if ($fNode -and $fNode.SelectSingleNode("dcsset:item", $ns)) {
  2788. $flt = @()
  2789. foreach ($fc in $fNode.SelectNodes("dcsset:item", $ns)) {
  2790. $bi = (Build-FilterItem -itemNode $fc -loc "settings/filter")
  2791. if ($null -ne $bi) { $flt += $bi }
  2792. }
  2793. if ($flt.Count -gt 0) { $so['filter'] = @($flt) }
  2794. }
  2795. $oNode = $lsNode.SelectSingleNode("dcsset:order", $ns)
  2796. if ($oNode -and $oNode.SelectSingleNode("dcsset:item", $ns)) {
  2797. $ord = Build-Order -ordNode $oNode -loc "settings/order"
  2798. if (@($ord).Count -gt 0) { $so['order'] = @($ord) }
  2799. }
  2800. $caNode = $lsNode.SelectSingleNode("dcsset:conditionalAppearance", $ns)
  2801. if ($caNode -and $caNode.SelectSingleNode("dcsset:item", $ns)) {
  2802. $ca = Build-ConditionalAppearance -caNode $caNode -loc "settings/conditionalAppearance"
  2803. if (@($ca).Count -gt 0) { $so['conditionalAppearance'] = @($ca) }
  2804. }
  2805. # Параметры данных компоновки (dcsset:dataParameters) — значения параметров запроса в
  2806. # настройках. Грамматика как у СКД (shorthand "Имя @off" / объект). См. Build-FormDataParameters.
  2807. $dpNode = $lsNode.SelectSingleNode("dcsset:dataParameters", $ns)
  2808. if ($dpNode -and $dpNode.SelectSingleNode("dcscor:item", $ns)) {
  2809. $dp = Build-FormDataParameters $dpNode
  2810. if (@($dp).Count -gt 0) { $so['dataParameters'] = @($dp) }
  2811. }
  2812. # Форма скелета ListSettings: дескриптор только для НЕ-каноничных форм (частичные/минимальные).
  2813. # Канон → $null (компилятор регенерит полный скелет, как раньше).
  2814. # Группировка строк списка: прямой <dcsset:item> ListSettings (не в filter/order/CA).
  2815. $grpItemNode = $lsNode.SelectSingleNode("dcsset:item", $ns)
  2816. $grouping = $null
  2817. if ($grpItemNode) { $grouping = Build-ListGrouping $grpItemNode }
  2818. if ($null -ne $grouping) { $so['grouping'] = $grouping }
  2819. $lsShape = Get-ListSettingsShape $lsNode ($null -ne $grouping)
  2820. if ($null -ne $lsShape) { $so['listSettings'] = $lsShape }
  2821. }
  2822. if ($so.Count -gt 0) { $ao['settings'] = $so }
  2823. }
  2824. [void]$attrs.Add($ao)
  2825. }
  2826. if ($attrs.Count -gt 0) { $dsl['attributes'] = @($attrs) }
  2827. }
  2828. # conditionalAppearance формы (<ConditionalAppearance> — последний child <Attributes>;
  2829. # та же DCS-грамматика, что settings.conditionalAppearance → переиспользуем Build-ConditionalAppearance)
  2830. if ($attrsNode) {
  2831. $caNode = $attrsNode.SelectSingleNode("lf:ConditionalAppearance", $ns)
  2832. if ($caNode) {
  2833. $ca = Build-ConditionalAppearance -caNode $caNode -loc "form/conditionalAppearance"
  2834. if (@($ca).Count -gt 0) { $dsl['conditionalAppearance'] = @($ca) }
  2835. }
  2836. }
  2837. # parameters
  2838. $parsNode = $root.SelectSingleNode("lf:Parameters", $ns)
  2839. if ($parsNode) {
  2840. $pars = New-Object System.Collections.ArrayList
  2841. foreach ($p in @($parsNode.SelectNodes("lf:Parameter", $ns))) {
  2842. $po = [ordered]@{}; $po['name'] = $p.GetAttribute("name")
  2843. $ty = Decompile-Type ($p.SelectSingleNode("lf:Type", $ns)); if ($ty) { $po['type'] = $ty }
  2844. if ((Get-Child $p 'KeyParameter') -eq 'true') { $po['key'] = $true }
  2845. [void]$pars.Add($po)
  2846. }
  2847. if ($pars.Count -gt 0) { $dsl['parameters'] = @($pars) }
  2848. }
  2849. # commands
  2850. $cmdsNode = $root.SelectSingleNode("lf:Commands", $ns)
  2851. if ($cmdsNode) {
  2852. $cmds = New-Object System.Collections.ArrayList
  2853. foreach ($c in @($cmdsNode.SelectNodes("lf:Command", $ns))) {
  2854. $co = [ordered]@{}; $co['name'] = $c.GetAttribute("name")
  2855. $act = Get-Child $c 'Action'; if ($act) { $co['action'] = $act }
  2856. if ((Get-Child $c 'ModifiesSavedData') -eq 'true') { $co['modifiesSavedData'] = $true }
  2857. # Заголовок команды: есть <Title> → захват; нет → суппресс-маркер "" (иначе компилятор
  2858. # додумает из имени — авто-вывод неверен для ~0.13% команд без заголовка в оригинале).
  2859. $tNode = $c.SelectSingleNode("lf:Title", $ns)
  2860. if ($tNode) { $t = Get-LangText $tNode; if ($null -ne $t) { $co['title'] = $t } }
  2861. else { $co['title'] = '' }
  2862. $ttNode = $c.SelectSingleNode("lf:ToolTip", $ns); if ($ttNode) { $t = Get-LangText $ttNode; if ($null -ne $t) { $co['tooltip'] = $t } }
  2863. $us = Decompile-XrFlag $c 'Use'; if ($null -ne $us) { $co['use'] = $us }
  2864. $cfo = Decompile-FunctionalOptions $c; if ($cfo) { $co['functionalOptions'] = $cfo }
  2865. $cru = Get-Child $c 'CurrentRowUse'; if ($cru) { $co['currentRowUse'] = $cru }
  2866. # Используемая таблица — ссылка по имени элемента-таблицы (<AssociatedTableElementId xsi:type="xs:string">Имя</…>)
  2867. $ate = Get-Child $c 'AssociatedTableElementId'; if ($ate) { $co['table'] = $ate }
  2868. $sc = Get-Child $c 'Shortcut'; if ($sc) { $co['shortcut'] = $sc }
  2869. Set-CommandPicture $co $c
  2870. $rep = Get-Child $c 'Representation'; if ($rep) { $co['representation'] = $rep }
  2871. [void]$cmds.Add($co)
  2872. }
  2873. if ($cmds.Count -gt 0) { $dsl['commands'] = @($cmds) }
  2874. }
  2875. # commandInterface (форменный <CommandInterface> — последний дочерний Form)
  2876. $ci = Decompile-CommandInterface
  2877. if ($null -ne $ci) { $dsl['commandInterface'] = $ci }
  2878. # --- 6. Output ---
  2879. $json = ConvertTo-CompactJson -obj $dsl
  2880. if ($OutputPath) {
  2881. [System.IO.File]::WriteAllText($OutputPath, $json, (New-Object System.Text.UTF8Encoding($false)))
  2882. Save-QueryFiles
  2883. Write-Host "form-decompile: $OutputPath"
  2884. } else {
  2885. Write-Output $json
  2886. }
.claude/skills/form-edit/scripts/form-edit.ps1 · Bundled script · 9,026 lines
  1. # form-edit v1.60 — Edit 1C managed form elements
  2. # Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
  3. [CmdletBinding(PositionalBinding=$false)]
  4. param(
  5. [Parameter(Mandatory)]
  6. [Alias('Path')]
  7. [string]$FormPath,
  8. [Parameter(Mandatory)]
  9. [string]$JsonPath
  10. )
  11. $ErrorActionPreference = "Stop"
  12. # --- Булевы флаги DSL: прощающий ввод ---
  13. # Флаг строкой или числом — однозначная ошибка автора JSON: true|да|истина|1 / false|нет|ложь|0 (без
  14. # регистра; 1/0 — и числом) приводим к bool молча. Иное — ошибка без записи: молчаливое «false» из «yes»
  15. # хуже отказа. Без общего читателя порты расходились: PS (-eq) принимал "false", py (is) — нет.
  16. function ConvertTo-DslBool {
  17. param($Value, [string]$Key, [bool]$Default)
  18. if ($null -eq $Value) { return $Default }
  19. if ($Value -is [bool]) { return $Value }
  20. if ($Value -is [string]) {
  21. $t = $Value.Trim().ToLowerInvariant()
  22. if (@('true', 'да', 'истина', '1') -ccontains $t) { return $true }
  23. if (@('false', 'нет', 'ложь', '0') -ccontains $t) { return $false }
  24. } elseif ($Value -is [int] -or $Value -is [long] -or $Value -is [double] -or $Value -is [decimal]) {
  25. if ($Value -eq 1) { return $true }
  26. if ($Value -eq 0) { return $false }
  27. }
  28. $shown = if ($Value -is [string]) { '"' + $Value + '"' } else { "$Value" }
  29. [Console]::Error.WriteLine("[ERROR] $Key = ${shown}: expected true or false")
  30. exit 1
  31. }
  32. # Первый найденный ключ из $Keys (синонимы, без регистра) → ConvertTo-DslBool; не объект / нет ключа → $Default.
  33. function Get-DslBool {
  34. param($Obj, [string[]]$Keys, [bool]$Default)
  35. if ($null -eq $Obj -or $Obj -is [string] -or $Obj -is [ValueType]) { return $Default }
  36. foreach ($k in $Keys) {
  37. if ($Obj -is [System.Collections.IDictionary]) {
  38. if ($Obj.Contains($k)) { return (ConvertTo-DslBool $Obj[$k] $k $Default) }
  39. } elseif ($Obj.PSObject.Properties[$k]) {
  40. return (ConvertTo-DslBool $Obj.PSObject.Properties[$k].Value $k $Default)
  41. }
  42. }
  43. return $Default
  44. }
  45. # --- Разбор пользовательского JSON ---
  46. # Одна строка в stderr вместо дампа исключения ConvertFrom-Json (issue #80): агент по стектрейсу
  47. # идёт чинить скрипт, а не свой вызов. $source — файл или параметр. $expected заполняем только
  48. # для полиморфного входа: у файла подсказка была бы наполнителем. -Inline печатает ещё и то,
  49. # что доехало: у файла такого вопроса нет — путь назван, позицию дал парсер, файл на диске.
  50. # Возврат через запятую: без неё одноэлементный JSON-массив разворачивался бы в скаляр
  51. # вторым анруллингом. Не Write-Output -NoEnumerate: pwsh 7.6 заворачивает им в List
  52. # и одиночный объект (issue #136).
  53. function ConvertFrom-JsonInput([string]$text, [string]$source, [string]$expected, [switch]$Inline) {
  54. try {
  55. # PS 5.1 на пустой строке отдаёт $null, а не ошибку — навык уходил дальше с $null,
  56. # тогда как py-порт падал. Проверяем сами, чтобы порты вели себя одинаково.
  57. if ([string]::IsNullOrWhiteSpace($text)) { throw 'input is empty' }
  58. # pwsh 7+ сам разворачивает массив верхнего уровня ([x] → x, [] → $null). Ключ -NoEnumerate
  59. # появился там же: в 5.1 и pwsh 6 его нет, поэтому спрашиваем командлет, а не версию.
  60. $cfj = @{}
  61. $cfjKeys = (Get-Command ConvertFrom-Json).Parameters
  62. if ($cfjKeys.ContainsKey('NoEnumerate')) { $cfj.NoEnumerate = $true }
  63. # pwsh 7.5+ без -DateKind String превращает ISO-строки дат в DateTime, и в XML уходит формат
  64. # локали; в 5.1 и pwsh до 7.5 ключа нет (5.1 даты и так не трогает).
  65. if ($cfjKeys.ContainsKey('DateKind')) { $cfj.DateKind = 'String' }
  66. $parsed = $text | ConvertFrom-Json @cfj
  67. } catch {
  68. $what = if ($expected) { "$source expects $expected" } else { "Invalid JSON in $source" }
  69. if ($Inline) {
  70. $got = ($text -replace '\s+', ' ').Trim()
  71. $label = 'got'
  72. if (-not $got) { $got = '(empty)' }
  73. elseif ($got.Length -gt 60) { $label = 'got (first 60 chars)'; $got = $got.Substring(0, 60) }
  74. $what = "${what}, ${label}: ${got}"
  75. }
  76. [Console]::Error.WriteLine("[ERROR] ${what} ($($_.Exception.Message))")
  77. exit 1
  78. }
  79. return ,$parsed
  80. }
  81. # --- Чтение входного JSON-файла ---
  82. # Кодировку берём из BOM — это объявление самого файла, а не догадка. Без BOM ждём строгий UTF-8:
  83. # Get-Content -Encoding UTF8 на файле в cp1251 тихо меняет кириллицу на U+FFFD, JSON после этого
  84. # разбирается успешно, и в конфигурацию уезжает имя из «замен». Кодовую страницу не подбираем:
  85. # угаданное имя уйдёт в метаданные так же молча.
  86. function Read-JsonInputFile([string]$path) {
  87. # Проверка здесь, а не по навыкам: часть навыков проверяла путь сама, часть — нет, и один и тот
  88. # же промах давал то внятную строку, то дамп MethodInvocationException. Навыки со своей
  89. # проверкой срабатывают раньше и сохраняют свой текст.
  90. if (-not (Test-Path -LiteralPath $path)) {
  91. [Console]::Error.WriteLine("[ERROR] File not found: $path")
  92. exit 1
  93. }
  94. if (Test-Path -LiteralPath $path -PathType Container) {
  95. [Console]::Error.WriteLine("[ERROR] Expected a JSON file, got a directory: $path")
  96. exit 1
  97. }
  98. $bytes = [System.IO.File]::ReadAllBytes($path)
  99. if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) {
  100. return [System.Text.Encoding]::UTF8.GetString($bytes, 3, $bytes.Length - 3)
  101. }
  102. if ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFF -and $bytes[1] -eq 0xFE) {
  103. return [System.Text.Encoding]::Unicode.GetString($bytes, 2, $bytes.Length - 2)
  104. }
  105. if ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFE -and $bytes[1] -eq 0xFF) {
  106. return [System.Text.Encoding]::BigEndianUnicode.GetString($bytes, 2, $bytes.Length - 2)
  107. }
  108. try {
  109. return (New-Object System.Text.UTF8Encoding($false, $true)).GetString($bytes)
  110. } catch {
  111. $detail = if ($_.Exception.InnerException) { $_.Exception.InnerException.Message } else { $_.Exception.Message }
  112. [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")
  113. exit 1
  114. }
  115. }
  116. [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
  117. # --- Support guard (Ext/ParentConfigurations.bin) ---
  118. # See docs/1c-support-state-spec.md. Blocks edits of vendor objects "на замке" /
  119. # read-only configs unless allowed. Trigger = bin present; reaction from
  120. # .v8-project.json editingAllowedCheck (deny|warn|off, default deny). Never
  121. # throws — guard errors degrade to allow.
  122. function Get-RootUuid([string]$xmlPath) {
  123. if (-not (Test-Path $xmlPath)) { return $null }
  124. try {
  125. [xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
  126. $el = $mx.DocumentElement.FirstChild
  127. while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
  128. if ($el) { $u = $el.GetAttribute("uuid"); if ($u) { return $u } }
  129. } catch {}
  130. return $null
  131. }
  132. function Test-ExternalObjectRoot([string]$xmlPath) {
  133. if (-not (Test-Path $xmlPath)) { return $false }
  134. try {
  135. [xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
  136. $el = $mx.DocumentElement.FirstChild
  137. while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
  138. if ($el) { return @('ExternalDataProcessor','ExternalReport') -contains $el.LocalName }
  139. } catch {}
  140. return $false
  141. }
  142. function Find-V8Project([string]$startDir) {
  143. $d = $startDir
  144. for ($i = 0; $i -lt 20 -and $d; $i++) {
  145. $pj = Join-Path $d ".v8-project.json"
  146. if (Test-Path $pj) { return $pj }
  147. $parent = [System.IO.Path]::GetDirectoryName($d)
  148. if ($parent -eq $d) { break }
  149. $d = $parent
  150. }
  151. return $null
  152. }
  153. function Get-EditMode([string]$cfgDir) {
  154. try {
  155. $pj = Find-V8Project (Get-Location).ProviderPath
  156. if (-not $pj) { $pj = Find-V8Project ([System.IO.Path]::GetFullPath($cfgDir)) }
  157. if (-not $pj) { return 'deny' }
  158. # UTF-8 явно: PS 5.1 читает файл без BOM как ANSI, и configSrc с кириллицей не совпал бы
  159. $proj = Get-Content -Raw -Encoding UTF8 $pj | ConvertFrom-Json
  160. # configSrc — от каталога .v8-project.json, а не от рабочего каталога: иначе из подкаталога
  161. # проекта база не сопоставляется и берётся правило проекта.
  162. $projDir = [System.IO.Path]::GetDirectoryName($pj)
  163. $cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
  164. if ($proj.databases) {
  165. foreach ($db in $proj.databases) {
  166. if ($db.configSrc) {
  167. $src = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($projDir, $db.configSrc)).TrimEnd('\', '/')
  168. if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
  169. if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
  170. }
  171. }
  172. }
  173. }
  174. if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
  175. return 'deny'
  176. } catch { return 'deny' }
  177. }
  178. function Assert-EditAllowed([string]$targetPath, [string]$require) {
  179. try {
  180. $rp = $targetPath
  181. try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).ProviderPath } catch {}
  182. # Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
  183. if (Test-ExternalObjectRoot $rp) { return }
  184. $elemUuid = Get-RootUuid $rp
  185. $cfgDir = $null; $binPath = $null
  186. $d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
  187. for ($i = 0; $i -lt 12 -and $d; $i++) {
  188. if (Test-ExternalObjectRoot "$d.xml") { return }
  189. if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
  190. if (-not $cfgDir) {
  191. $cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
  192. if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
  193. }
  194. if ($elemUuid -and $cfgDir) { break }
  195. $parent = [System.IO.Path]::GetDirectoryName($d)
  196. if ($parent -eq $d) { break }
  197. $d = $parent
  198. }
  199. # New object (no element file): fall back to config root uuid.
  200. if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
  201. if (-not $binPath -or -not (Test-Path $binPath)) { return }
  202. $bytes = [System.IO.File]::ReadAllBytes($binPath)
  203. if ($bytes.Length -le 32) { return }
  204. $start = 0
  205. if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
  206. $text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
  207. $hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
  208. if (-not $hm.Success) { return }
  209. $G = [int]$hm.Groups[1].Value
  210. $K = [int]$hm.Groups[2].Value
  211. if ($K -eq 0) { return }
  212. $best = $null
  213. if ($elemUuid) {
  214. $u = [regex]::Escape($elemUuid.ToLower())
  215. foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
  216. $f1 = [int]$m.Groups[1].Value
  217. if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
  218. }
  219. }
  220. $blocked = $false; $code = ""; $reason = ""
  221. if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
  222. elseif ($require -eq 'removed') {
  223. if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
  224. }
  225. else {
  226. if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
  227. }
  228. if (-not $blocked) { return }
  229. $mode = Get-EditMode $cfgDir
  230. if ($mode -eq 'off') { return }
  231. # Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
  232. # latter throws and would be swallowed by this function's own catch.
  233. if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
  234. $head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
  235. $cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
  236. $offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
  237. if ($code -eq "capability-off") {
  238. $state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
  239. $fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
  240. } elseif ($code -eq "not-removed") {
  241. $state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
  242. $fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
  243. } else {
  244. $state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
  245. $fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
  246. }
  247. [Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
  248. exit 1
  249. } catch { return }
  250. }
  251. # === 1. Load Form.xml ===
  252. if (-not (Test-Path $FormPath)) {
  253. Write-Error "File not found: $FormPath"
  254. exit 1
  255. }
  256. if (-not (Test-Path $JsonPath)) {
  257. Write-Error "File not found: $JsonPath"
  258. exit 1
  259. }
  260. $resolvedFormPath = (Resolve-Path $FormPath).ProviderPath
  261. Assert-EditAllowed $resolvedFormPath 'editable'
  262. $xmlDoc = New-Object System.Xml.XmlDocument
  263. $xmlDoc.PreserveWhitespace = $true
  264. try {
  265. $xmlDoc.Load($resolvedFormPath)
  266. } catch {
  267. Write-Host "[ERROR] XML parse error: $($_.Exception.Message)"
  268. exit 1
  269. }
  270. $formNs = "http://v8.1c.ru/8.3/xcf/logform"
  271. $v8Ns = "http://v8.1c.ru/8.1/data/core"
  272. $nsMgr = New-Object System.Xml.XmlNamespaceManager($xmlDoc.NameTable)
  273. $nsMgr.AddNamespace("f", $formNs)
  274. $nsMgr.AddNamespace("v8", $v8Ns)
  275. $root = $xmlDoc.DocumentElement
  276. # === 2. Load JSON ===
  277. $def = ConvertFrom-JsonInput (Read-JsonInputFile $JsonPath) $JsonPath
  278. # Флаг main строкой или числом ("true", 1) — как булево: иначе порты расходятся (PS `-eq $true` принимает
  279. # строку и 1, Python `is True` — нет)
  280. function Normalize-MainFlag($attrs) {
  281. foreach ($a in @($attrs)) {
  282. if ($a -isnot [System.Management.Automation.PSCustomObject]) { continue }
  283. $p = $a.PSObject.Properties['main']
  284. if ($null -eq $p) { continue }
  285. $v = $p.Value
  286. if ($v -is [string]) {
  287. $s = $v.Trim().ToLower()
  288. if ($s -eq 'true') { $p.Value = $true } elseif ($s -eq 'false') { $p.Value = $false }
  289. } elseif (($v -is [int] -or $v -is [long]) -and ($v -eq 0 -or $v -eq 1)) {
  290. $p.Value = ($v -eq 1)
  291. }
  292. }
  293. }
  294. Normalize-MainFlag $def.attributes
  295. # === 3. Form name + header ===
  296. $formName = [System.IO.Path]::GetFileNameWithoutExtension($FormPath)
  297. $parentDir = [System.IO.Path]::GetDirectoryName($resolvedFormPath)
  298. if ($parentDir) {
  299. $extDir = [System.IO.Path]::GetFileName($parentDir)
  300. if ($extDir -eq "Ext") {
  301. $formDir = [System.IO.Path]::GetDirectoryName($parentDir)
  302. if ($formDir) { $formName = [System.IO.Path]::GetFileName($formDir) }
  303. }
  304. }
  305. Write-Host "=== form-edit: $formName ==="
  306. Write-Host ""
  307. # === 4. Scan max IDs per pool ===
  308. $script:nextElemId = 0
  309. $script:nextAttrId = 0
  310. $script:nextCmdId = 0
  311. # Scan ALL element IDs via XPath (includes companions like ExtendedTooltip, ContextMenu)
  312. $rootCI = $root.SelectSingleNode("f:ChildItems", $nsMgr)
  313. if ($rootCI) {
  314. foreach ($elem in $rootCI.SelectNodes(".//*[@id]")) {
  315. $id = $elem.GetAttribute("id")
  316. if ($id -and $id -ne "-1") {
  317. try { $intId = [int]$id; if ($intId -gt $script:nextElemId) { $script:nextElemId = $intId } } catch {}
  318. }
  319. }
  320. }
  321. # Командная панель формы: сама (id=-1) и её кнопки — из того же пула, что и элементы
  322. $acb = $root.SelectSingleNode("f:AutoCommandBar", $nsMgr)
  323. if ($acb) {
  324. $acbIds = New-Object System.Collections.ArrayList
  325. [void]$acbIds.Add($acb.GetAttribute("id"))
  326. foreach ($elem in $acb.SelectNodes(".//*[@id]")) { [void]$acbIds.Add($elem.GetAttribute("id")) }
  327. foreach ($id in $acbIds) {
  328. if ($id -and $id -ne "-1") {
  329. try { $intId = [int]$id; if ($intId -gt $script:nextElemId) { $script:nextElemId = $intId } } catch {}
  330. }
  331. }
  332. }
  333. # Scan attribute IDs (including column IDs — same pool)
  334. foreach ($attr in $root.SelectNodes("f:Attributes/f:Attribute", $nsMgr)) {
  335. $id = $attr.GetAttribute("id")
  336. if ($id) {
  337. try { $intId = [int]$id; if ($intId -gt $script:nextAttrId) { $script:nextAttrId = $intId } } catch {}
  338. }
  339. # Column IDs are in the same pool as attribute IDs
  340. foreach ($col in $attr.SelectNodes("f:Columns/f:Column", $nsMgr)) {
  341. $colId = $col.GetAttribute("id")
  342. if ($colId) {
  343. try { $intColId = [int]$colId; if ($intColId -gt $script:nextAttrId) { $script:nextAttrId = $intColId } } catch {}
  344. }
  345. }
  346. }
  347. # Scan command IDs
  348. foreach ($cmd in $root.SelectNodes("f:Commands/f:Command", $nsMgr)) {
  349. $id = $cmd.GetAttribute("id")
  350. if ($id) {
  351. try { $intId = [int]$id; if ($intId -gt $script:nextCmdId) { $script:nextCmdId = $intId } } catch {}
  352. }
  353. }
  354. $script:nextElemId++
  355. $script:nextAttrId++
  356. $script:nextCmdId++
  357. # Префикс имён расширения — <NamePrefix> ближайшего вверх Configuration.xml; "" — не расширение или не задан.
  358. function Get-ExtensionNamePrefix([string]$dir) {
  359. $d = $dir
  360. while ($d) {
  361. $cfg = Join-Path $d 'Configuration.xml'
  362. if (Test-Path -LiteralPath $cfg) {
  363. $m = [regex]::Match([System.IO.File]::ReadAllText($cfg), '<NamePrefix>([^<]*)</NamePrefix>')
  364. if ($m.Success) { return $m.Groups[1].Value }
  365. return ''
  366. }
  367. $parent = Split-Path $d -Parent
  368. if (-not $parent -or $parent -eq $d) { break }
  369. $d = $parent
  370. }
  371. return ''
  372. }
  373. # --- 4b. Auto-detect extension mode (BaseForm present) ---
  374. $script:isExtension = $false
  375. $script:extNamePrefix = ''
  376. $baseForm = $root.SelectSingleNode("f:BaseForm", $nsMgr)
  377. if ($baseForm) {
  378. $script:isExtension = $true
  379. $script:extNamePrefix = Get-ExtensionNamePrefix ([System.IO.Path]::GetDirectoryName($resolvedFormPath))
  380. if ($script:nextAttrId -lt 1000000) { $script:nextAttrId = 1000000 }
  381. if ($script:nextCmdId -lt 1000000) { $script:nextCmdId = 1000000 }
  382. if ($script:nextElemId -lt 1000000) { $script:nextElemId = 1000000 }
  383. }
  384. function New-ElemId { $id = $script:nextElemId; $script:nextElemId++; return $id }
  385. function New-AttrId { $id = $script:nextAttrId; $script:nextAttrId++; return $id }
  386. function New-CmdId { $id = $script:nextCmdId; $script:nextCmdId++; return $id }
  387. # For element emitters, New-Id = New-ElemId
  388. function New-Id { return New-ElemId }
  389. # === 5. Fragment helpers (StringBuilder + Emit-* from form-compile) ===
  390. $script:xml = New-Object System.Text.StringBuilder 4096
  391. function X {
  392. param([string]$text)
  393. $script:xml.AppendLine($text) | Out-Null
  394. }
  395. # --- Type emitter ---
  396. $script:formTypeSynonyms = New-Object System.Collections.Hashtable
  397. $script:formTypeSynonyms["строка"] = "string"
  398. $script:formTypeSynonyms["число"] = "decimal"
  399. $script:formTypeSynonyms["булево"] = "boolean"
  400. $script:formTypeSynonyms["дата"] = "date"
  401. $script:formTypeSynonyms["датавремя"]= "dateTime"
  402. $script:formTypeSynonyms["number"] = "decimal"
  403. $script:formTypeSynonyms["bool"] = "boolean"
  404. $script:formTypeSynonyms["справочникссылка"] = "CatalogRef"
  405. $script:formTypeSynonyms["справочникобъект"] = "CatalogObject"
  406. $script:formTypeSynonyms["документссылка"] = "DocumentRef"
  407. $script:formTypeSynonyms["документобъект"] = "DocumentObject"
  408. $script:formTypeSynonyms["перечислениессылка"] = "EnumRef"
  409. $script:formTypeSynonyms["плансчетовссылка"] = "ChartOfAccountsRef"
  410. $script:formTypeSynonyms["планвидовхарактеристикссылка"] = "ChartOfCharacteristicTypesRef"
  411. $script:formTypeSynonyms["планвидоврасчётассылка"] = "ChartOfCalculationTypesRef"
  412. $script:formTypeSynonyms["планвидоврасчетассылка"] = "ChartOfCalculationTypesRef"
  413. $script:formTypeSynonyms["планобменассылка"] = "ExchangePlanRef"
  414. $script:formTypeSynonyms["бизнеспроцессссылка"] = "BusinessProcessRef"
  415. $script:formTypeSynonyms["задачассылка"] = "TaskRef"
  416. $script:formTypeSynonyms["определяемыйтип"] = "DefinedType"
  417. $script:formTypeSynonyms["характеристика"] = "Characteristic"
  418. $script:formTypeSynonyms["любаяссылка"] = "AnyRef"
  419. $script:formTypeSynonyms["любаяссылкаиб"] = "AnyIBRef"
  420. # Платформенные v8-типы (forgiving: англ. без префикса + рус.) → каноничный с префиксом v8: (эмитим verbatim)
  421. $script:formTypeSynonyms["standardperiod"] = "v8:StandardPeriod"
  422. $script:formTypeSynonyms["стандартныйпериод"] = "v8:StandardPeriod"
  423. $script:formTypeSynonyms["standardbeginningdate"] = "v8:StandardBeginningDate"
  424. $script:formTypeSynonyms["стандартнаядатаначала"] = "v8:StandardBeginningDate"
  425. $script:formTypeSynonyms["uuid"] = "v8:UUID"
  426. $script:formTypeSynonyms["уникальныйидентификатор"] = "v8:UUID"
  427. $script:formTypeSynonyms["списокзначений"] = "ValueList"
  428. # Алиас на локальный словарь: тело Resolve-TypeStr ниже — общая реализация,
  429. # одинаковая во всех навыках (реестр в tests/skills/check-inline-drift.mjs).
  430. $script:typeSynonyms = $script:formTypeSynonyms
  431. # --- Event handler name generator ---
  432. # --- Element helpers ---
  433. # Уникальность имён внутри JSON-определения (1С: своя коллекция — свой неймспейс).
  434. function Assert-EditUnique {
  435. param([string]$name, [hashtable]$seen, [string]$ctx)
  436. if ($seen.ContainsKey($name)) {
  437. Write-Host "[ERROR] Duplicate $ctx '$name' in JSON definition — names must be unique in 1C form"
  438. exit 1
  439. }
  440. $seen[$name] = $true
  441. }
  442. # --- Element emitters ---
  443. # --- Element dispatcher ---
  444. # === 5b. Эмиттер элементов — общий с form-compile (эталон там; копии держит check-inline-drift) ===
  445. $script:queryBaseDir = if ($JsonPath) { [System.IO.Path]::GetDirectoryName((Resolve-Path $JsonPath).ProviderPath) } else { (Get-Location).ProviderPath }
  446. $script:fmtMarkupRe = '</>|<\s*(?:link|b|i|u|s|color|colorStyle|bgColor|bgColorStyle|font|fontSize|fontStyle|img)(?:\s|>)'
  447. $script:CANON_FILTER_ID = 'dfcece9d-5077-440b-b6b3-45a5cb4538eb'
  448. $script:CANON_ORDER_ID = '88619765-ccb3-46c6-ac52-38e9c992ebd4'
  449. $script:CANON_CA_ID = 'b75fecce-942b-4aed-abc9-e6a02e460fb3'
  450. $script:CANON_ITEMS_ID = '911b6018-f537-43e8-a417-da56b22f9aec'
  451. $script:comparisonTypes = @{
  452. "=" = "Equal"; "<>" = "NotEqual"
  453. ">" = "Greater"; ">=" = "GreaterOrEqual"
  454. "<" = "Less"; "<=" = "LessOrEqual"
  455. "in" = "InList"; "notIn" = "NotInList"
  456. "inHierarchy" = "InHierarchy"; "inListByHierarchy" = "InListByHierarchy"
  457. "contains" = "Contains"; "notContains" = "NotContains"
  458. "beginsWith" = "BeginsWith"; "notBeginsWith" = "NotBeginsWith"
  459. "like" = "Like"; "notLike" = "NotLike"
  460. "подобно" = "Like"; "неподобно" = "NotLike" # рус. синоним (хэш регистронезависим: ПОДОБНО=подобно)
  461. "filled" = "Filled"; "notFilled" = "NotFilled"
  462. }
  463. $script:calcRestrictMap = @{ 'noField'='field'; 'noFilter'='condition'; 'noCondition'='condition'; 'noGroup'='group'; 'noOrder'='order' }
  464. $script:dcsCommonNs = 'http://v8.1c.ru/8.1/data-composition-system/common'
  465. $script:knownInvalidTypes = @{
  466. "FormDataStructure" = "Runtime type. Use object type without cfg: prefix (e.g. CatalogObject.Контрагенты, DocumentObject.Приход)"
  467. "FormDataCollection" = "Runtime type. Use ValueTable"
  468. "FormDataTree" = "Runtime type. Use ValueTree"
  469. "FormDataTreeItem" = "Runtime type, not valid in XML"
  470. "FormDataCollectionItem"= "Runtime type, not valid in XML"
  471. "FormGroup" = "UI element type, not a data type"
  472. "FormField" = "UI element type, not a data type"
  473. "FormButton" = "UI element type, not a data type"
  474. "FormDecoration" = "UI element type, not a data type"
  475. "FormTable" = "UI element type, not a data type"
  476. }
  477. # --- Каталог событий формы (генерируется) ---
  478. # Тег элемента («Form» — сама форма) → событие → @(суффикс имени обработчика, директива компиляции,
  479. # параметры, с какой платформы событие есть ("" — с 8.3.20), ограничение). Параметры — строка или
  480. # @("платформа", "параметры", …) — сигнатура с этой платформы. Ограничение: у таблицы — источник
  481. # (DynamicList), у формы — владельцы, у форм которых событие есть (по основному реквизиту). Последнее —
  482. # позиция события в <Events>: платформа пишет события в этом порядке, какой бы ни был на входе.
  483. # Источники: синтакс-помощник 8.3.20–8.5, типовые конфигурации (28.5 тыс. форм), замер загрузкой на 7 платформах.
  484. # Перегенерировать: python debug/form-handlers/gen_event_catalog.py
  485. function Get-FormEventCatalog {
  486. return @{
  487. "CalendarField" = @{
  488. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  489. "DragCheck" = @("ПроверкаПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, ВыбраннаяДата", "", "", 1)
  490. "OnPeriodOutput" = @("ПриВыводеПериода", "НаКлиенте", "Элемент, ОформлениеПериода", "", "", 2)
  491. "Selection" = @("Выбор", "НаКлиенте", "Элемент, ВыбраннаяДата", "", "", 3)
  492. "OnActivateDate" = @("ПриАктивизацииДаты", "НаКлиенте", "Элемент", "", "", 4)
  493. "DragStart" = @("НачалоПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, Выполнение", "", "", 5)
  494. "Drag" = @("Перетаскивание", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, ВыбраннаяДата", "", "", 6)
  495. "DragEnd" = @("ОкончаниеПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 7)
  496. }
  497. "ChartField" = @{
  498. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  499. "Selection" = @("Выбор", "НаКлиенте", "Элемент, ЗначениеДиаграммы, СтандартнаяОбработка", "", "", 1)
  500. "DetailProcessing" = @("ОбработкаРасшифровки", "НаКлиенте", "Элемент, Расшифровка, СтандартнаяОбработка", "", "", 2)
  501. "OnActivate" = @("ПриАктивизации", "НаКлиенте", "Элемент", "", "", 3)
  502. }
  503. "CheckBoxField" = @{
  504. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  505. }
  506. "DendrogramField" = @{
  507. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  508. "DetailProcessing" = @("ОбработкаРасшифровки", "НаКлиенте", "Элемент, Расшифровка, СтандартнаяОбработка", "", "", 1)
  509. "Selection" = @("Выбор", "НаКлиенте", "Элемент, ЗначениеДендрограммы, СтандартнаяОбработка", "", "", 2)
  510. }
  511. "ExtendedTooltip" = @{
  512. "Click" = @("Нажатие", "НаКлиенте", "Элемент", "", "", 0)
  513. "URLProcessing" = @("ОбработкаНавигационнойСсылки", "НаКлиенте", "Элемент, НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка", "", "", 1)
  514. }
  515. "Form" = @{
  516. "AfterWrite" = @("ПослеЗаписи", "НаКлиенте", "ПараметрыЗаписи", "", "Document, Catalog, ChartOfCharacteristicTypes, BusinessProcess, Task, InformationRegisterRecord, InformationRegisterRecordSet, Constants, ExchangePlan, ChartOfAccounts, ChartOfCalculationTypes", 0)
  517. "BeforeReopenFromOtherServer" = @("ПередПереоткрытиемСДругогоСервера", "НаКлиенте", "Параметры, Отказ", "", "", 1)
  518. "ValueChoice" = @("ВыборЗначения", "НаКлиенте", "СтандартнаяОбработка", "", "Document, Catalog, ChartOfCharacteristicTypes, BusinessProcess, Task, ExchangePlan, ChartOfAccounts, ChartOfCalculationTypes", 2)
  519. "OnReopenFromOtherServer" = @("ПриПереоткрытииСДругогоСервера", "НаКлиенте", "Источник, ПараметрыЗаполнения, СтандартнаяОбработка", "", "", 3)
  520. "OnSaveDataInSettingsAtServer" = @("ПриСохраненииДанныхВНастройкахНаСервере", "НаСервере", "Настройки", "", "", 4)
  521. "ChoiceProcessing" = @("ОбработкаВыбора", "НаКлиенте", "ВыбранноеЗначение, ИсточникВыбора", "", "", 5)
  522. "BeforeLoadVariantAtServer" = @("ПередЗагрузкойВариантаНаСервере", "НаСервере", "Настройки", "", "Report", 6)
  523. "AfterWriteAtServer" = @("ПослеЗаписиНаСервере", "НаСервере", "ТекущийОбъект, ПараметрыЗаписи", "", "Document, Catalog, ChartOfCharacteristicTypes, BusinessProcess, Task, InformationRegisterRecord, InformationRegisterRecordSet, Constants, ExchangePlan, ChartOfAccounts, ChartOfCalculationTypes", 7)
  524. "OnPasteFromClipboard" = @("ПриВставкеИзБуфераОбмена", "НаКлиенте", "Значение, СтандартнаяОбработка", "8.3.24", "", 8)
  525. "BeforeStart" = @("ПередСтартом", "НаКлиенте", "Отказ", "", "BusinessProcess", 9)
  526. "NotificationProcessing" = @("ОбработкаОповещения", "НаКлиенте", "ИмяСобытия, Параметр, Источник", "", "", 10)
  527. "OnReadAtServer" = @("ПриЧтенииНаСервере", "НаСервере", "ТекущийОбъект", "", "Document, Catalog, ChartOfCharacteristicTypes, BusinessProcess, Task, InformationRegisterRecord, InformationRegisterRecordSet, Constants, ExchangePlan, ChartOfAccounts, ChartOfCalculationTypes", 11)
  528. "NewWriteProcessing" = @("ОбработкаЗаписиНового", "НаКлиенте", "НовыйОбъект, Источник, СтандартнаяОбработка", "", "", 12)
  529. "OnOpen" = @("ПриОткрытии", "НаКлиенте", "Отказ", "", "", 13)
  530. "BeforeLoadUserSettingsAtServer" = @("ПередЗагрузкойПользовательскихНастроекНаСервере", "НаСервере", "Настройки, ИспользуютсяСтандартныеНастройки", "", "Report", 14)
  531. "URLListGetProcessing" = @("ОбработкаПолученияСпискаНавигационныхСсылок", "НаКлиенте", "СписокНавигационыхСсылок, КлючПоУмолчанию", "", "", 15)
  532. "OnSaveVariantAtServer" = @("ПриСохраненииВариантаНаСервере", "НаСервере", "Настройки", "", "Report", 16)
  533. "BeforeClose" = @("ПередЗакрытием", "НаКлиенте", "Отказ, ЗавершениеРаботы, ТекстПредупреждения, СтандартнаяОбработка", "", "", 17)
  534. "ExternalEvent" = @("ВнешнееСобытие", "НаКлиенте", "Источник, Событие, Данные", "", "", 18)
  535. "CollaborationSystemUsersAutoComplete" = @("АвтоПодборПользователейСистемыВзаимодействия", "НаКлиенте", "Текст, ДанныеВыбора, НазначениеВыбора, СтандартнаяОбработка", "", "", 19)
  536. "OnSettingsChange" = @("ПриИзмененииНастроек", "НаКлиенте", "СтандартнаяОбработка", "8.5", "Report", 20)
  537. "URLGetProcessing" = @("ОбработкаПолученияНавигационнойСсылки", "НаКлиенте", "Ключ, Представление, НавигационнаяСсылка, СтандартнаяОбработка", "", "", 21)
  538. "OnReopen" = @("ПриПовторномОткрытии", "НаКлиенте", "", "", "", 22)
  539. "OnLoadDataFromSettingsAtServer" = @("ПриЗагрузкеДанныхИзНастроекНаСервере", "НаСервере", "Настройки", "", "", 23)
  540. "OnLoadUserSettingsAtServer" = @("ПриЗагрузкеПользовательскихНастроекНаСервере", "НаСервере", "Настройки, ИспользуютсяСтандартныеНастройки", "", "Report", 24)
  541. "OnLoadVariantAtServer" = @("ПриЗагрузкеВариантаНаСервере", "НаСервере", "Настройки", "", "Report", 25)
  542. "NavigationProcessing" = @("ОбработкаПерехода", "НаКлиенте", "ОбъектПерехода, СтандартнаяОбработка", "", "", 26)
  543. "OnSaveUserSettingsAtServer" = @("ПриСохраненииПользовательскихНастроекНаСервере", "НаСервере", "Настройки", "", "Report", 27)
  544. "BeforeWrite" = @("ПередЗаписью", "НаКлиенте", "Отказ, ПараметрыЗаписи", "", "Document, Catalog, ChartOfCharacteristicTypes, BusinessProcess, Task, InformationRegisterRecord, InformationRegisterRecordSet, Constants, ExchangePlan, ChartOfAccounts, ChartOfCalculationTypes", 28)
  545. "OnCreateAtServer" = @("ПриСозданииНаСервере", "НаСервере", "Отказ, СтандартнаяОбработка", "", "", 29)
  546. "CollaborationSystemUsersChoiceFormGetProcessing" = @("ОбработкаПолученияФормыВыбораПользователейСистемыВзаимодействия", "НаКлиенте", "НазначениеВыбора, Параметры, ВыбраннаяФорма, СтандартнаяОбработка", "", "", 30)
  547. "OnComposeResult" = @("ПриКомпоновкеРезультата", "НаКлиенте", "СтандартнаяОбработка", "8.5", "Report", 31)
  548. "ActivationProcessing" = @("ОбработкаАктивизации", "НаКлиенте", "АктивныйОбъект, Источник", "", "", 32)
  549. "AfterComposeResult" = @("ПослеКомпоновкиРезультата", "НаКлиенте", "Результат, СтандартнаяОбработка", "8.5", "Report", 33)
  550. "OnChangeDisplaySettings" = @("ПриИзмененииПараметровЭкрана", "НаКлиенте", "", "", "", 34)
  551. "BeforeWriteAtServer" = @("ПередЗаписьюНаСервере", "НаСервере", "Отказ, ТекущийОбъект, ПараметрыЗаписи", "", "Document, Catalog, ChartOfCharacteristicTypes, BusinessProcess, Task, InformationRegisterRecord, InformationRegisterRecordSet, Constants, ExchangePlan, ChartOfAccounts, ChartOfCalculationTypes", 35)
  552. "OnWriteAtServer" = @("ПриЗаписиНаСервере", "НаСервере", "Отказ, ТекущийОбъект, ПараметрыЗаписи", "", "Document, Catalog, ChartOfCharacteristicTypes, BusinessProcess, Task, InformationRegisterRecord, InformationRegisterRecordSet, Constants, ExchangePlan, ChartOfAccounts, ChartOfCalculationTypes", 36)
  553. "OnClose" = @("ПриЗакрытии", "НаКлиенте", "ЗавершениеРаботы", "", "", 37)
  554. "OnMainServerAvailabilityChange" = @("ПриИзмененииДоступностиОсновногоСервера", "НаКлиенте", "СтандартнаяОбработка", "", "", 38)
  555. "OnUpdateUserSettingSetAtServer" = @("ПриОбновленииСоставаПользовательскихНастроекНаСервере", "НаСервере", "СтандартнаяОбработка", "", "Report, SettingsComposer", 39)
  556. "URLProcessing" = @("ОбработкаНавигационнойСсылки", "НаКлиенте", "НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка", "", "", 40)
  557. "FillCheckProcessingAtServer" = @("ОбработкаПроверкиЗаполненияНаСервере", "НаСервере", "Отказ, ПроверяемыеРеквизиты", "", "", 41)
  558. "BeforeLoadDataFromSettingsAtServer" = @("ПередЗагрузкойДанныхИзНастроекНаСервере", "НаСервере", "Настройки", "", "", 42)
  559. "BeforeExecute" = @("ПередВыполнением", "НаКлиенте", "Отказ", "", "Task", 43)
  560. "AddInDetachmentOnError" = @("ОтключениеВнешнейКомпонентыПриОшибке", "НаКлиенте", "Имя, Местоположение", "8.3.23", "", 44)
  561. }
  562. "FormattedDocumentField" = @{
  563. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  564. "BeforePrint" = @("ПередПечатью", "НаКлиенте", "Элемент, ДиалогПечати, Отказ", "", "", 1)
  565. "AfterWrite" = @("ПослеЗаписи", "НаКлиенте", "Элемент", "", "", 2)
  566. "BeforeWrite" = @("ПередЗаписью", "НаКлиенте", "Элемент, Копирование, Отказ", "", "", 3)
  567. }
  568. "GanttChartField" = @{
  569. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  570. "Selection" = @("Выбор", "НаКлиенте", "Элемент, Значения, СтандартнаяОбработка, Дата", "", "", 1)
  571. "DetailProcessing" = @("ОбработкаРасшифровки", "НаКлиенте", "Элемент, Расшифровка, СтандартнаяОбработка, Дата", "", "", 2)
  572. "BeforeCollapse" = @("ПередСворачиванием", "НаКлиенте", "Элемент, ИдентификаторЗначения, Отказ", "8.3.23", "", 3)
  573. "OnActivateInterval" = @("ПриАктивизацииИнтервала", "НаКлиенте", "Элемент", "8.3.23", "", 4)
  574. "OnActivateValue" = @("ПриАктивизацииЗначения", "НаКлиенте", "Элемент", "8.3.23", "", 5)
  575. "BeforeExpand" = @("ПередРазворачиванием", "НаКлиенте", "Элемент, ИдентификаторЗначения, Отказ", "8.3.23", "", 6)
  576. "OnIntervalEditEnd" = @("ПриОкончанииРедактированияИнтервала", "НаКлиенте", "Элемент, Интервал, ОтменаРедактирования", "", "", 7)
  577. }
  578. "GeographicalSchemaField" = @{
  579. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  580. "DetailProcessing" = @("ОбработкаРасшифровки", "НаКлиенте", "Элемент, Расшифровка, СтандартнаяОбработка", "", "", 1)
  581. "BeforePrint" = @("ПередПечатью", "НаКлиенте", "Элемент, ДиалогПечати, Отказ", "", "", 2)
  582. }
  583. "GraphicalSchemaField" = @{
  584. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  585. "Selection" = @("Выбор", "НаКлиенте", "Элемент", "", "", 1)
  586. "AfterWrite" = @("ПослеЗаписи", "НаКлиенте", "Элемент", "", "", 2)
  587. "OnActivate" = @("ПриАктивизации", "НаКлиенте", "Элемент", "", "", 3)
  588. "BeforeWrite" = @("ПередЗаписью", "НаКлиенте", "Элемент, Копирование, Отказ", "", "", 4)
  589. "BeforePrint" = @("ПередПечатью", "НаКлиенте", "Элемент, ДиалогПечати, Отказ", "", "", 5)
  590. }
  591. "HTMLDocumentField" = @{
  592. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  593. "DocumentComplete" = @("ДокументСформирован", "НаКлиенте", "Элемент", "", "", 1)
  594. "BeforeWrite" = @("ПередЗаписью", "НаКлиенте", "Элемент, Копирование, Отказ", "", "", 2)
  595. "BeforePrint" = @("ПередПечатью", "НаКлиенте", "Элемент, ДиалогПечати, Отказ", "", "", 3)
  596. "AfterWrite" = @("ПослеЗаписи", "НаКлиенте", "Элемент", "", "", 4)
  597. "OnClick" = @("ПриНажатии", "НаКлиенте", "Элемент, ДанныеСобытия, СтандартнаяОбработка", "", "", 5)
  598. }
  599. "InputField" = @{
  600. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  601. "EditTextChange" = @("ИзменениеТекстаРедактирования", "НаКлиенте", "Элемент, Текст, СтандартнаяОбработка", "", "", 1)
  602. "AutoComplete" = @("АвтоПодбор", "НаКлиенте", "Элемент, Текст, ДанныеВыбора, ПараметрыПолученияДанных, Ожидание, СтандартнаяОбработка", "", "", 2)
  603. "StartChoice" = @("НачалоВыбора", "НаКлиенте", @("8.3.20", "Элемент, ДанныеВыбора, СтандартнаяОбработка", "8.3.23", "Элемент, ДанныеВыбора, ВыборДобавлением, СтандартнаяОбработка"), "", "", 3)
  604. "MultipleValueURLProcessing" = @("ОбработкаНавигационнойСсылкиМножественногоЗначения", "НаКлиенте", "Элемент, Идентификатор, НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка", "8.3.23", "", 4)
  605. "MultipleValuesDelete" = @("УдалениеМножественныхЗначений", "НаКлиенте", "Элемент, Идентификаторы, СтандартнаяОбработка", "8.3.23", "", 5)
  606. "Tuning" = @("Регулирование", "НаКлиенте", "Элемент, Направление, СтандартнаяОбработка", "", "", 6)
  607. "MultipleValuesAdd" = @("ДобавлениеМножественныхЗначений", "НаКлиенте", "Элемент, Значения, СтандартнаяОбработка", "8.3.23", "", 7)
  608. "Opening" = @("Открытие", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 8)
  609. "Creating" = @("Создание", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 9)
  610. "StartListChoice" = @("НачалоВыбораИзСписка", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 10)
  611. "Clearing" = @("Очистка", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 11)
  612. "TextEditEnd" = @("ОкончаниеВводаТекста", "НаКлиенте", "Элемент, Текст, ДанныеВыбора, ПараметрыПолученияДанных, СтандартнаяОбработка", "", "", 12)
  613. "MultipleValueOpening" = @("ОткрытиеМножественногоЗначения", "НаКлиенте", "Элемент, Идентификатор, СтандартнаяОбработка", "8.3.23", "", 13)
  614. "ChoiceProcessing" = @("ОбработкаВыбора", "НаКлиенте", @("8.3.20", "Элемент, ВыбранноеЗначение, СтандартнаяОбработка", "8.3.23", "Элемент, ВыбранноеЗначение, ДополнительныеДанные, ВыборДобавлением, СтандартнаяОбработка"), "", "", 14)
  615. "CommandGenerateProcessing" = @("ОбработкаФормированияКоманд", "НаКлиенте", "Элемент, ПараметрыКоманд, Команды", "8.3.23", "", 15)
  616. }
  617. "LabelDecoration" = @{
  618. "Click" = @("Нажатие", "НаКлиенте", "Элемент", "", "", 0)
  619. "URLProcessing" = @("ОбработкаНавигационнойСсылки", "НаКлиенте", "Элемент, НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка", "", "", 1)
  620. }
  621. "LabelField" = @{
  622. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  623. "URLProcessing" = @("ОбработкаНавигационнойСсылки", "НаКлиенте", "Элемент, НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка", "", "", 1)
  624. "Click" = @("Нажатие", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 2)
  625. }
  626. "PDFDocumentField" = @{
  627. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "8.3.23", "", 0)
  628. "URLClick" = @("НажатиеНаНавигационнойСсылке", "НаКлиенте", "Элемент, НавигационнаяСсылка, СтандартнаяОбработка", "8.3.23", "", 1)
  629. }
  630. "Pages" = @{
  631. "OnCurrentPageChange" = @("ПриСменеСтраницы", "НаКлиенте", "Элемент, ТекущаяСтраница", "", "", 0)
  632. }
  633. "PeriodField" = @{
  634. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  635. "Selection" = @("Выбор", "НаКлиенте", "Элемент, ВыбраннаяДата", "", "", 1)
  636. }
  637. "PictureDecoration" = @{
  638. "DragCheck" = @("ПроверкаПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 0)
  639. "DragStart" = @("НачалоПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, Выполнение", "", "", 1)
  640. "Drag" = @("Перетаскивание", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 2)
  641. "Click" = @("Нажатие", "НаКлиенте", "Элемент", "", "", 3)
  642. "DragEnd" = @("ОкончаниеПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 4)
  643. }
  644. "PictureField" = @{
  645. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  646. "DragCheck" = @("ПроверкаПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 1)
  647. "DragStart" = @("НачалоПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, Выполнение", "", "", 2)
  648. "Drag" = @("Перетаскивание", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 3)
  649. "Click" = @("Нажатие", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 4)
  650. "DragEnd" = @("ОкончаниеПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 5)
  651. }
  652. "PlannerField" = @{
  653. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  654. "DragCheck" = @("ПроверкаПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, Дата, ЗначенияИзмерений", "", "", 1)
  655. "BeforeCollapseDimensionItem" = @("ПередСворачиваниемЭлементаИзмерения", "НаКлиенте", "Элемент, ЭлементИзмерения, ЗначенияИзмерений, Отказ", "", "", 2)
  656. "TimeScaleItemClick" = @("НажатиеНаЭлементеШкалыВремени", "НаКлиенте", "Элемент, ЭлементШкалыВремени, Дата", "", "", 3)
  657. "BeforeCreate" = @("ПередСозданием", "НаКлиенте", "Элемент, Начало, Конец, ЗначенияИзмерений, Текст, СтандартнаяОбработка", "", "", 4)
  658. "InsideDragCheck" = @("ПроверкаПеретаскиванияВнутри", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, ВариантИзмененияГраниц, ДействиеПеретаскивания, Отказ", "", "", 5)
  659. "BeforePrint" = @("ПередПечатью", "НаКлиенте", "Элемент, ДиалогПечати, Отказ", "", "", 6)
  660. "DimensionItemClick" = @("НажатиеНаЭлементеИзмерения", "НаКлиенте", "Элемент, ЭлементИзмерения, ЗначенияИзмерений, СтандартнаяОбработка", "", "", 7)
  661. "OnCurrentRepresentationPeriodChange" = @("ПриСменеТекущегоПериодаОтображения", "НаКлиенте", "Элемент, ТекущиеПериодыОтображения, СтандартнаяОбработка", "", "", 8)
  662. "OnEditEnd" = @("ПриОкончанииРедактирования", "НаКлиенте", "Элемент, НовыйЭлемент, ОтменаРедактирования", "", "", 9)
  663. "WrappedTimeScaleHeaderClick" = @("НажатиеНаПеренесенномЗаголовкеШкалыВремени", "НаКлиенте", "Элемент, Дата", "", "", 10)
  664. "DragStart" = @("НачалоПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, Выполнение", "", "", 11)
  665. "BeforeDelete" = @("ПередУдалением", "НаКлиенте", "Элемент, Отказ", "", "", 12)
  666. "BeforeExpandDimensionItem" = @("ПередРазворачиваниемЭлементаИзмерения", "НаКлиенте", "Элемент, ЭлементИзмерения, ЗначенияИзмерений, Отказ", "", "", 13)
  667. "BeforeStartEdit" = @("ПередНачаломРедактирования", "НаКлиенте", "Элемент, НовыйЭлемент, СтандартнаяОбработка", "", "", 14)
  668. "Drag" = @("Перетаскивание", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, Дата, ЗначенияИзмерений", "", "", 15)
  669. "CommandGenerateProcessing" = @("ОбработкаФормированияКоманд", "НаКлиенте", @("8.3.20", "Элемент, Параметры, Команды, КомандаПоУмолчанию", "8.3.23", "Элемент, ПараметрыКоманд, Команды, КомандаПоУмолчанию"), "", "", 16)
  670. "BeforeStartQuickEdit" = @("ПередНачаломБыстрогоРедактирования", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 17)
  671. "Selection" = @("Выбор", "НаКлиенте", "Элемент, СтандартнаяОбработка", "", "", 18)
  672. "OnActivate" = @("ПриАктивизации", "НаКлиенте", "Элемент", "", "", 19)
  673. "URLClick" = @("НажатиеНаНавигационнойСсылке", "НаКлиенте", "Элемент, Источник, НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка", "", "", 20)
  674. "DragEnd" = @("ОкончаниеПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 21)
  675. "PlannerActionClick" = @("НажатиеНаДействиеПланировщика", "НаКлиенте", "Элемент, ЭлементПланировщика, ДействиеЭлементаПланировщика", "", "", 22)
  676. }
  677. "ProgressBarField" = @{
  678. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  679. }
  680. "RadioButtonField" = @{
  681. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  682. }
  683. "SpreadSheetDocumentField" = @{
  684. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  685. "URLProcessing" = @("ОбработкаНавигационнойСсылки", "НаКлиенте", "Элемент, НавигационнаяСсылкаФорматированнойСтроки, СтандартнаяОбработка", "8.3.24", "", 1)
  686. "AdditionalDetailProcessing" = @("ОбработкаДополнительнойРасшифровки", "НаКлиенте", @("8.3.20", "Элемент, Расшифровка, СтандартнаяОбработка, ДополнительныеПараметры", "8.5", "Элемент, Расшифровка, СтандартнаяОбработка, ДополнительныеПараметры, ВсеРасшифровкиОбласти, ДляПанелиДействий"), "", "", 2)
  687. "DragCheck" = @("ПроверкаПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, Область", "", "", 3)
  688. "OnActivate" = @("ПриАктивизации", "НаКлиенте", "Элемент", "", "", 4)
  689. "Selection" = @("Выбор", "НаКлиенте", "Элемент, Область, СтандартнаяОбработка", "", "", 5)
  690. "DetailProcessing" = @("ОбработкаРасшифровки", "НаКлиенте", "Элемент, Расшифровка, СтандартнаяОбработка, ДополнительныеПараметры", "", "", 6)
  691. "OnChangeAreaContent" = @("ПриИзмененииСодержимогоОбласти", "НаКлиенте", "Элемент, Область, ДополнительныеПараметры", "", "", 7)
  692. "BeforePrint" = @("ПередПечатью", "НаКлиенте", "Элемент, ДиалогПечати, Отказ", "", "", 8)
  693. "DragStart" = @("НачалоПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, Выполнение", "", "", 9)
  694. "Drag" = @("Перетаскивание", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, Область", "", "", 10)
  695. "AfterWrite" = @("ПослеЗаписи", "НаКлиенте", "Элемент", "", "", 11)
  696. "BeforeWrite" = @("ПередЗаписью", "НаКлиенте", "Элемент, Копирование, Отказ", "", "", 12)
  697. "OnGenerateToolTipText" = @("ПриФормированииТекстаПодсказки", "НаКлиенте", "Элемент, Область, ТекстПодсказки, СтандартнаяОбработка", "8.5", "", 13)
  698. "DragEnd" = @("ОкончаниеПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 14)
  699. }
  700. "Table" = @{
  701. "OnEditEnd" = @("ПриОкончанииРедактирования", "НаКлиенте", "Элемент, НоваяСтрока, ОтменаРедактирования", "", "", 0)
  702. "DragCheck" = @("ПроверкаПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, Строка, Поле", "", "", 1)
  703. "ValueChoice" = @("ВыборЗначения", "НаКлиенте", "Элемент, Значение, СтандартнаяОбработка", "", "", 2)
  704. "Selection" = @("Выбор", "НаКлиенте", "Элемент, ВыбраннаяСтрока, Поле, СтандартнаяОбработка", "", "", 3)
  705. "OnSelectedRowsSetChange" = @("ПриИзмененииСоставаВыделенныхСтрок", "НаКлиенте", "Элемент", "8.5", "", 4)
  706. "BeforeAddRow" = @("ПередНачаломДобавления", "НаКлиенте", "Элемент, Отказ, Копирование, Родитель, ЭтоГруппа, Параметр", "", "", 5)
  707. "OnCurrentParentChange" = @("ПриСменеТекущегоРодителя", "НаКлиенте", "Элемент", "", "", 6)
  708. "BeforeDeleteRow" = @("ПередУдалением", "НаКлиенте", "Элемент, Отказ", "", "", 7)
  709. "OnLoadUserSettingsAtServer" = @("ПриЗагрузкеПользовательскихНастроекНаСервере", "НаСервере", "Элемент, Настройки, ИспользуютсяСтандартныеНастройки", "", "DynamicList", 8)
  710. "URLListGetProcessing" = @("ОбработкаПолученияСпискаНавигационныхСсылок", "НаКлиенте", "Элемент, СписокНавигационыхСсылок, КлючПоУмолчанию", "8.3.23", "DynamicList", 9)
  711. "BeforeEditEnd" = @("ПередОкончаниемРедактирования", "НаКлиенте", "Элемент, НоваяСтрока, ОтменаРедактирования, Отказ", "", "", 10)
  712. "OnActivateRow" = @("ПриАктивизацииСтроки", "НаКлиенте", "Элемент", "", "", 11)
  713. "URLGetProcessing" = @("ОбработкаПолученияНавигационнойСсылки", "НаКлиенте", "Элемент, Ключ, Представление, НавигационнаяСсылка, СтандартнаяОбработка", "8.3.23", "DynamicList", 12)
  714. "DragStart" = @("НачалоПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, Выполнение", "", "", 13)
  715. "OnActivateField" = @("ПриАктивизацииПоля", "НаКлиенте", "Элемент", "", "", 14)
  716. "BeforeExpand" = @("ПередРазворачиванием", "НаКлиенте", "Элемент, Строка, Отказ", "", "", 15)
  717. "Drag" = @("Перетаскивание", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка, Строка, Поле", "", "", 16)
  718. "ChoiceProcessing" = @("ОбработкаВыбора", "НаКлиенте", "Элемент, ВыбранноеЗначение, СтандартнаяОбработка", "", "", 17)
  719. "OnGetDataAtServer" = @("ПриПолученииДанныхНаСервере", "НаСервереБезКонтекста", "ИмяЭлемента, Настройки, Строки", "", "DynamicList", 18)
  720. "OnSaveUserSettingsAtServer" = @("ПриСохраненииПользовательскихНастроекНаСервере", "НаСервере", "Элемент, Настройки", "", "DynamicList", 19)
  721. "BeforeCollapse" = @("ПередСворачиванием", "НаКлиенте", "Элемент, Строка, Отказ", "", "", 20)
  722. "BeforeRowChange" = @("ПередНачаломИзменения", "НаКлиенте", "Элемент, Отказ", "", "", 21)
  723. "OnStartEdit" = @("ПриНачалеРедактирования", "НаКлиенте", "Элемент, НоваяСтрока, Копирование", "", "", 22)
  724. "BeforeLoadUserSettingsAtServer" = @("ПередЗагрузкойПользовательскихНастроекНаСервере", "НаСервере", "Элемент, Настройки, ИспользуютсяСтандартныеНастройки", "", "DynamicList", 23)
  725. "OnHover" = @("ПриНаведении", "НаКлиенте", "Элемент, Строка, Поле", "8.5", "", 24)
  726. "DragEnd" = @("ОкончаниеПеретаскивания", "НаКлиенте", "Элемент, ПараметрыПеретаскивания, СтандартнаяОбработка", "", "", 25)
  727. "NewWriteProcessing" = @("ОбработкаЗаписиНового", "НаКлиенте", "НовыйОбъект, Источник, СтандартнаяОбработка", "", "", 26)
  728. "AfterDeleteRow" = @("ПослеУдаления", "НаКлиенте", "Элемент", "", "", 27)
  729. "OnUpdateUserSettingSetAtServer" = @("ПриОбновленииСоставаПользовательскихНастроекНаСервере", "НаСервере", "СтандартнаяОбработка", "", "DynamicList", 28)
  730. "OnActivateCell" = @("ПриАктивизацииЯчейки", "НаКлиенте", "Элемент", "", "", 29)
  731. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 30)
  732. "RefreshRequestProcessing" = @("ОбработкаЗапросаОбновления", "НаКлиенте", "", "", "", 31)
  733. }
  734. "TextDocumentField" = @{
  735. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  736. "BeforePrint" = @("ПередПечатью", "НаКлиенте", "Элемент, ДиалогПечати, Отказ", "", "", 1)
  737. "BeforeWrite" = @("ПередЗаписью", "НаКлиенте", "Элемент, Копирование, Отказ", "", "", 2)
  738. "AfterWrite" = @("ПослеЗаписи", "НаКлиенте", "Элемент", "", "", 3)
  739. }
  740. "TrackBarField" = @{
  741. "OnChange" = @("ПриИзменении", "НаКлиенте", "Элемент", "", "", 0)
  742. }
  743. "UsualGroup" = @{
  744. "Click" = @("Нажатие", "НаКлиенте", "Элемент", "8.5", "", 0)
  745. }
  746. }
  747. }
  748. # Порядок событий формы у владельцев, у которых он отличается от позиций каталога
  749. function Get-FormEventOrder {
  750. return @{
  751. "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")
  752. }
  753. }
  754. # --- конец каталога событий формы ---
  755. $script:eventCatalog = Get-FormEventCatalog
  756. $script:formEventOrder = Get-FormEventOrder
  757. function Detect-FormatVersion([string]$dir) {
  758. $d = $dir
  759. while ($d) {
  760. # Автономная внешняя обработка/отчёт: своего Configuration.xml у неё нет, версию несёт
  761. # корень самой обработки. Без этого форма и макет внутри обработки 2.21 писались бы 2.17.
  762. $extPath = "$d.xml"
  763. if (Test-Path $extPath) {
  764. $extText = [System.IO.File]::ReadAllText($extPath, [System.Text.Encoding]::UTF8)
  765. $extHead = $extText.Substring(0, [Math]::Min(2000, $extText.Length))
  766. if ($extHead -match '<(ExternalDataProcessor|ExternalReport)[ >]' -and $extHead -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
  767. }
  768. $cfgPath = Join-Path $d "Configuration.xml"
  769. if (Test-Path $cfgPath) {
  770. $cfgText = [System.IO.File]::ReadAllText($cfgPath, [System.Text.Encoding]::UTF8)
  771. # Длину среза берём по СТРОКЕ, а не по размеру файла: размер в БАЙТАХ, Substring считает
  772. # СИМВОЛЫ, и на кириллице байт больше — короткий Configuration.xml ронял навык исключением.
  773. $head = $cfgText.Substring(0, [Math]::Min(2000, $cfgText.Length))
  774. if ($head -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
  775. }
  776. $parent = Split-Path $d -Parent
  777. if ($parent -eq $d) { break }
  778. $d = $parent
  779. }
  780. return "2.17"
  781. }
  782. # Версия формата формы: событие новой платформы в форме старого формата — предупреждение.
  783. # Нет атрибута version — как у form-compile: по конфигурации, иначе 2.17.
  784. $script:formatVersion = $root.GetAttribute('version')
  785. if (-not $script:formatVersion) { $script:formatVersion = Detect-FormatVersion ([System.IO.Path]::GetDirectoryName($resolvedFormPath)) }
  786. function Get-EventEntry([string]$xmlTag, [string]$eventName) {
  787. if (-not $xmlTag -or -not $script:eventCatalog.ContainsKey($xmlTag)) { return $null }
  788. $evs = $script:eventCatalog[$xmlTag]
  789. foreach ($k in $evs.Keys) { if ($k -ceq $eventName) { return ,$evs[$k] } }
  790. return $null
  791. }
  792. # Позиция события в <Events>: платформа пишет события в порядке каталога (у формы — в порядке владельца,
  793. # если он у владельца свой), внутри события — Before, затем After. Событие вне каталога — после известных.
  794. function Get-EventRank([string]$xmlTag, [string]$name, [string]$callType = '') {
  795. $ct = 0
  796. if ($callType -eq 'After') { $ct = 1 } elseif ($callType -eq 'Override') { $ct = 2 }
  797. $pos = [int]::MaxValue
  798. $own = $null
  799. if ($xmlTag -eq 'Form' -and $script:formOwner) { $own = $script:formEventOrder[$script:formOwner] }
  800. if ($null -ne $own) {
  801. $i = [Array]::IndexOf([string[]]$own, $name)
  802. if ($i -ge 0) { $pos = $i }
  803. } else {
  804. $e = Get-EventEntry $xmlTag $name
  805. if ($e) { $pos = [int]$e[5] }
  806. }
  807. return [long]$pos * 4 + $ct
  808. }
  809. # Расстояние Левенштейна — для подсказки к неизвестному событию.
  810. function Get-EditDistance([string]$a, [string]$b) {
  811. $prev = New-Object int[] ($b.Length + 1)
  812. for ($j = 0; $j -le $b.Length; $j++) { $prev[$j] = $j }
  813. for ($i = 1; $i -le $a.Length; $i++) {
  814. $cur = New-Object int[] ($b.Length + 1)
  815. $cur[0] = $i
  816. for ($j = 1; $j -le $b.Length; $j++) {
  817. $cost = if ($a[$i - 1] -ceq $b[$j - 1]) { 0 } else { 1 }
  818. $cur[$j] = [Math]::Min([Math]::Min($prev[$j] + 1, $cur[$j - 1] + 1), $prev[$j - 1] + $cost)
  819. }
  820. $prev = $cur
  821. }
  822. return $prev[$b.Length]
  823. }
  824. # Подсказка к неизвестному событию: ближайшие по написанию события вида элемента и виды, у которых такое событие есть.
  825. function Get-EventHint([string]$xmlTag, [string]$name) {
  826. $parts = @()
  827. $evs = $script:eventCatalog[$xmlTag]
  828. if ($evs) {
  829. $lim = [Math]::Max(2, [int][Math]::Floor($name.Length / 3))
  830. $near = [string[]]@(foreach ($k in $evs.Keys) {
  831. $d = Get-EditDistance $name.ToLowerInvariant() "$k".ToLowerInvariant()
  832. if ($d -le $lim) { '{0:D3}|{1}' -f $d, $k }
  833. })
  834. [Array]::Sort($near, [StringComparer]::Ordinal)
  835. if ($near.Count) { $parts += 'Did you mean: ' + ((@($near | Select-Object -First 3) | ForEach-Object { $_.Split('|')[1] }) -join ', ') + '?' }
  836. }
  837. $tags = [string[]]@(foreach ($t in $script:eventCatalog.Keys) { if ("$t" -ne $xmlTag -and $null -ne (Get-EventEntry "$t" $name)) { "$t" } })
  838. [Array]::Sort($tags, [StringComparer]::Ordinal)
  839. if ($tags.Count) { $parts += "'$name' is an event of: $($tags -join ', ')." }
  840. return ($parts -join ' ')
  841. }
  842. function Test-EventPairs {
  843. param($pairs, [string]$xmlTag, [string]$elementName, [string]$source = '')
  844. $what = if ($xmlTag -eq 'Form') { 'the form' } else { "$xmlTag '$elementName'" }
  845. $evs = $script:eventCatalog[$xmlTag]
  846. foreach ($pr in $pairs) {
  847. $ev = "$($pr.name)"
  848. $entry = if ($evs) { Get-EventEntry $xmlTag $ev } else { $null }
  849. if (-not $entry) {
  850. # сводкой перед записью формы (Report-UnknownEvents): модель исправит все сразу
  851. [void]$script:unknownEvents.Add([pscustomobject]@{ tag = $xmlTag; name = $elementName; ev = $ev; noEvents = (-not $evs) })
  852. continue
  853. }
  854. $since = "$($entry[3])"
  855. if ($since -and (Get-FormatRank $script:formatVersion) -lt $script:platformFormatRank[$since]) {
  856. Write-Host "[WARN] Event '$ev' of $what exists since platform $since — earlier platforms drop it on load"
  857. }
  858. $only = "$($entry[4])"
  859. if ($only -and $xmlTag -eq 'Form') {
  860. if ($script:formOwner -and @($only -split ',\s*') -notcontains $script:formOwner) {
  861. Write-Host "[WARN] Event '$ev' of $what exists only for forms of $only (this form: $($script:formOwner)) — the platform drops it on load"
  862. }
  863. } elseif ($only -and $source -and $source -ne $only) {
  864. Write-Host "[WARN] Event '$ev' of $what exists only for a table bound to $only (bound to $source) — the platform drops it on load"
  865. }
  866. }
  867. }
  868. # Сводка неизвестных событий за запуск — одним блоком перед записью формы. Формы ветки 8.3 — ошибка (форма не
  869. # пишется), 8.5 — предупреждение. Перечень событий вида — только если подсказать нечего, один раз на вид.
  870. function Report-UnknownEvents {
  871. if ($script:unknownEvents.Count -eq 0) { return }
  872. # одно событие у нескольких элементов вида — одной строкой (одна и та же опечатка — одно исправление)
  873. $groups = [ordered]@{}
  874. foreach ($u in $script:unknownEvents) {
  875. $key = "$($u.tag)|$($u.ev)"
  876. if (-not $groups.Contains($key)) { $groups[$key] = [pscustomobject]@{ u = $u; names = New-Object System.Collections.ArrayList } }
  877. if ($u.name -and -not $groups[$key].names.Contains($u.name)) { [void]$groups[$key].names.Add($u.name) }
  878. }
  879. $lines = New-Object System.Collections.ArrayList
  880. $knownTags = New-Object System.Collections.ArrayList
  881. foreach ($g in $groups.Values) {
  882. $u = $g.u
  883. $where = if ($u.tag -eq 'Form') { 'the form' } else { "$($u.tag) " + ((@($g.names) | ForEach-Object { "'$_'" }) -join ', ') }
  884. $hint = Get-EventHint $u.tag $u.ev
  885. $line = " '$($u.ev)' for $where"
  886. if ($u.noEvents) { $line += " — $($u.tag) has no events." + $(if ($hint) { " $hint" } else { '' }) }
  887. elseif ($hint) { $line += " — $hint" }
  888. elseif (-not $knownTags.Contains($u.tag)) { [void]$knownTags.Add($u.tag) }
  889. [void]$lines.Add($line)
  890. }
  891. foreach ($t in $knownTags) {
  892. $known = [string[]]@($script:eventCatalog[$t].Keys); [Array]::Sort($known, [StringComparer]::Ordinal)
  893. [void]$lines.Add(" Events of ${t}: $($known -join ', ')")
  894. }
  895. if ((Get-FormatRank $script:formatVersion) -le $script:eventCatalogClosedRank) {
  896. [Console]::Error.WriteLine("[ERROR] Unknown events — the platform drops them on load; the form is not written:`n" + ($lines -join "`n"))
  897. exit 1
  898. }
  899. Write-Host ("[WARN] Unknown events — the platform drops them on load (8.5 builds may add events):`n" + ($lines -join "`n"))
  900. }
  901. # Владелец формы по типу основного реквизита — как в ограничениях каталога событий ("" — не определить
  902. # или вид не замерен: события формы по владельцу тогда не сверяются).
  903. function Get-FormOwnerKind([string]$type) {
  904. $t = $type -replace '^\w+:(?=\w)', ''
  905. if ($t -eq 'SettingsComposer') { return 'SettingsComposer' }
  906. switch (($t -split '\.')[0]) {
  907. 'DataProcessorObject' { return 'DataProcessor' }
  908. 'ExternalDataProcessorObject' { return 'DataProcessor' }
  909. 'ReportObject' { return 'Report' }
  910. 'ExternalReportObject' { return 'Report' }
  911. 'DocumentObject' { return 'Document' }
  912. 'CatalogObject' { return 'Catalog' }
  913. 'ChartOfCharacteristicTypesObject' { return 'ChartOfCharacteristicTypes' }
  914. 'ExchangePlanObject' { return 'ExchangePlan' }
  915. 'ChartOfAccountsObject' { return 'ChartOfAccounts' }
  916. 'ChartOfCalculationTypesObject' { return 'ChartOfCalculationTypes' }
  917. 'BusinessProcessObject' { return 'BusinessProcess' }
  918. 'TaskObject' { return 'Task' }
  919. 'InformationRegisterRecordManager' { return 'InformationRegisterRecord' }
  920. 'InformationRegisterRecordSet' { return 'InformationRegisterRecordSet' }
  921. 'ConstantsSet' { return 'Constants' }
  922. 'DynamicList' { return 'List' }
  923. }
  924. return ''
  925. }
  926. # Владелец формы — по основному реквизиту в Form.xml. Считается перед сверкой событий формы:
  927. # реквизиты правятся раньше событий, и основной реквизит мог появиться или смениться в этом же вызове.
  928. $script:formOwner = ''
  929. function Update-FormOwner {
  930. $script:formOwner = ''
  931. foreach ($a in $root.SelectNodes("f:Attributes/f:Attribute", $nsMgr)) {
  932. $ma = $a.SelectSingleNode("f:MainAttribute", $nsMgr)
  933. if ($null -ne $ma -and $ma.InnerText.Trim() -eq 'true') {
  934. $tn = $a.SelectSingleNode("f:Type/v8:Type", $nsMgr)
  935. if ($null -ne $tn) { $script:formOwner = Get-FormOwnerKind $tn.InnerText }
  936. break
  937. }
  938. }
  939. }
  940. function Warn-EventsIgnored($el, [string]$xmlTag, [string]$elementName) {
  941. $names = @()
  942. $list = @($el.on)
  943. if ($el.events -is [array]) { $list = @($el.events) + $list }
  944. elseif ($el.events -is [System.Management.Automation.PSCustomObject]) { $names += @($el.events.PSObject.Properties | ForEach-Object { $_.Name }) }
  945. elseif ($el.events) { $names += "$($el.events)" }
  946. foreach ($evt in $list) { if ($null -ne $evt) { $names += if ($evt -is [System.Management.Automation.PSCustomObject]) { "$($evt.event)" } else { "$evt" } } }
  947. if ($names.Count -gt 0) {
  948. Write-Host "[WARN] $xmlTag '$elementName' has no events — ignored: $($names -join ', ')"
  949. }
  950. }
  951. function Get-FormatRank([string]$ver) {
  952. if ($ver -match '^(\d+)\.(\d+)$') { return [int]$Matches[1] * 100 + [int]$Matches[2] }
  953. return 0
  954. }
  955. # Первая версия формата выгрузки платформы, на которой появилось событие каталога.
  956. $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 }
  957. # Каталог событий полон по формат 2.20 включительно (ветка 8.3 закрыта): неизвестное событие — ошибка; выше — предупреждение
  958. $script:eventCatalogClosedRank = 220
  959. $script:unknownEvents = New-Object System.Collections.ArrayList
  960. # --- Заготовки обработчиков в модуле формы ---
  961. # Привязки, которые затронул запуск, собираются в $script:handlerBindings; после записи Form.xml
  962. # Update-FormModule дописывает в модуль процедуры, которых там ещё нет, — в области по стандарту БСП.
  963. $script:handlerBindings = New-Object System.Collections.ArrayList
  964. $script:handlerTable = '' # таблица, колонки которой сейчас эмитятся
  965. # kind: form | element | command; table — таблица, внутри которой элемент (область «…ТаблицыФормы<Имя>»).
  966. # Одно имя на несколько событий — одна процедура: сигнатуру даёт первая привязка.
  967. function Register-Handler([string]$handler, [string]$kind, [string]$xmlTag = '', [string]$eventName = '', [string]$table = '') {
  968. if (-not $handler) { return }
  969. foreach ($b in $script:handlerBindings) { if ($b.handler -eq $handler) { return } }
  970. [void]$script:handlerBindings.Add([pscustomobject]@{ handler = $handler; kind = $kind; xmlTag = $xmlTag; eventName = $eventName; table = $table })
  971. }
  972. # Пустой модуль формы. Табличных областей нет: имя таблицы при создании формы неизвестно.
  973. function Get-FormModuleTemplate {
  974. $out = @()
  975. foreach ($r in @('ОбработчикиСобытийФормы', 'ОбработчикиСобытийЭлементовШапкиФормы', 'ОбработчикиКомандФормы', 'ОбработчикиОповещений', 'СлужебныеПроцедурыИФункции')) {
  976. if ($out.Count -gt 0) { $out += '' }
  977. $out += @("#Область $r", '', '#КонецОбласти')
  978. }
  979. return $out
  980. }
  981. # Процедуры и функции модуля (имя, первая и последняя строка; первая — с аннотациями над заголовком)
  982. # и области (имя, строки #Область и #КонецОбласти, вложенность). Строки нумеруются с 1.
  983. # Заголовок — только в начале строки: продолжение литерала («|…») и комментарий заголовком не станут.
  984. function Get-ModuleOutline([string[]]$lines) {
  985. $procs = New-Object System.Collections.ArrayList
  986. $regions = New-Object System.Collections.ArrayList
  987. $open = New-Object System.Collections.ArrayList
  988. $cur = $null
  989. for ($i = 0; $i -lt $lines.Count; $i++) {
  990. $l = $lines[$i]
  991. if ($null -ne $cur) {
  992. # конец процедуры — в начале строки или после «;» (`Возврат Х;КонецФункции`)
  993. if ($l -match '(^|;)\s*(КонецПроцедуры|КонецФункции|EndProcedure|EndFunction)(?![\w])') { $cur.end = $i + 1; [void]$procs.Add($cur); $cur = $null }
  994. continue
  995. }
  996. $m = [regex]::Match($l, '^\s*(?:(?:Асинх|Async)\s+)?(?:Процедура|Функция|Procedure|Function)\s+(\w+)\s*\(', 'IgnoreCase')
  997. if ($m.Success) {
  998. $s = $i
  999. while ($s -gt 0 -and $lines[$s - 1] -match '^\s*&') { $s-- }
  1000. $cur = [pscustomobject]@{ name = $m.Groups[1].Value; start = $s + 1; end = $i + 1 }
  1001. continue
  1002. }
  1003. $m = [regex]::Match($l, '^\s*#(?:Область|Region)\s+(\S+)', 'IgnoreCase')
  1004. if ($m.Success) { [void]$open.Add([pscustomobject]@{ name = $m.Groups[1].Value; start = $i + 1; end = 0; depth = $open.Count }); continue }
  1005. if ($l -match '^\s*#(КонецОбласти|EndRegion)(?![\w])' -and $open.Count -gt 0) {
  1006. $r = $open[$open.Count - 1]; $open.RemoveAt($open.Count - 1)
  1007. $r.end = $i + 1; [void]$regions.Add($r)
  1008. }
  1009. }
  1010. return @{ procs = $procs; regions = $regions }
  1011. }
  1012. # Разметка модуля по коду без литералов и комментариев: «;КонецПроцедуры» в строке не закроет процедуру.
  1013. function Get-ModuleCodeOutline([string[]]$lines) {
  1014. return Get-ModuleOutline (Get-BslScan ($lines -join "`n")).Code
  1015. }
  1016. # Параметры обработчика события по версии формата формы: строка — одна сигнатура для всех платформ;
  1017. # массив @("8.3.20", "А, Б", "8.3.23", "А, Б, В") — сигнатура с указанной платформы (по возрастанию).
  1018. # Формат формы не определён — новейшая сигнатура.
  1019. function Get-EventParams($entry) {
  1020. $p = $entry[2]
  1021. if (-not ($p -is [array])) { return "$p" }
  1022. $rank = Get-FormatRank $script:formatVersion
  1023. $res = "$($p[1])"
  1024. for ($i = 0; $i -lt $p.Count; $i += 2) {
  1025. $since = $script:platformFormatRank["$($p[$i])"]
  1026. if ($null -eq $since) { continue }
  1027. if ($rank -eq 0 -or $rank -ge $since) { $res = "$($p[$i + 1])" }
  1028. }
  1029. return $res
  1030. }
  1031. # Текст заготовки: директива и параметры — из каталога событий, у команды — (Команда) на клиенте.
  1032. # $null — событие вне каталога, сигнатура неизвестна.
  1033. function Get-HandlerStub($b) {
  1034. if ($b.kind -eq 'command') { $dir = 'НаКлиенте'; $params = 'Команда' }
  1035. else {
  1036. $entry = Get-EventEntry $b.xmlTag $b.eventName
  1037. if (-not $entry) { return $null }
  1038. $dir = "$($entry[1])"; $params = Get-EventParams $entry
  1039. }
  1040. return @("&$dir", "Процедура $($b.handler)($params)", "`t// Вставить содержимое обработчика.", 'КонецПроцедуры')
  1041. }
  1042. # Порядок областей модуля формы по стандарту (типовые): куда встаёт новая область.
  1043. function Get-RegionRank([string]$name) {
  1044. $n = $name.ToLower()
  1045. if ($n -eq 'описаниепеременных') { return 0 }
  1046. if ($n -eq 'обработчикисобытийформы') { return 1 }
  1047. if ($n -eq 'обработчикисобытийэлементовшапкиформы' -or $n -eq 'обработчикисобытийэлементовформы') { return 2 }
  1048. if ($n.StartsWith('обработчикисобытийэлементовтаблицыформы')) { return 3 }
  1049. if ($n -eq 'обработчикикомандформы') { return 4 }
  1050. if ($n -eq 'обработчикиоповещений') { return 5 }
  1051. if ($n -eq 'служебныепроцедурыифункции') { return 6 }
  1052. return -1
  1053. }
  1054. # Область для привязки. Общая область элементов (без «шапки») — для всех элементов, и табличных тоже:
  1055. # модуль уже так устроен.
  1056. function Get-HandlerRegionName($b, $regions) {
  1057. if ($b.kind -eq 'form') { return 'ОбработчикиСобытийФормы' }
  1058. if ($b.kind -eq 'command') { return 'ОбработчикиКомандФормы' }
  1059. $has = @{}
  1060. foreach ($r in $regions) { $has[$r.name.ToLower()] = $true }
  1061. # своя область таблицы, если она уже есть, — важнее общей
  1062. if ($b.table -and $has["обработчикисобытийэлементовтаблицыформы$($b.table)".ToLower()]) { return "ОбработчикиСобытийЭлементовТаблицыФормы$($b.table)" }
  1063. if ($has['обработчикисобытийэлементовформы'] -and -not $has['обработчикисобытийэлементовшапкиформы']) { return 'ОбработчикиСобытийЭлементовФормы' }
  1064. if ($b.table) { return "ОбработчикиСобытийЭлементовТаблицыФормы$($b.table)" }
  1065. return 'ОбработчикиСобытийЭлементовШапкиФормы'
  1066. }
  1067. # Вставить заготовку в модуль (список строк): в конец своей области, нет области — создать её на месте
  1068. # по порядку областей, нет областей вообще — в конец модуля. Отделяется одной пустой строкой.
  1069. function Add-StubToModule([System.Collections.ArrayList]$lines, [string[]]$stub, $b) {
  1070. $outline = Get-ModuleCodeOutline $lines.ToArray()
  1071. if ($outline.regions.Count -eq 0) {
  1072. while ($lines.Count -gt 0 -and -not $lines[$lines.Count - 1].Trim()) { $lines.RemoveAt($lines.Count - 1) }
  1073. if ($lines.Count -gt 0) { [void]$lines.Add('') }
  1074. $lines.AddRange($stub)
  1075. return
  1076. }
  1077. $name = Get-HandlerRegionName $b $outline.regions
  1078. $target = $null
  1079. foreach ($r in $outline.regions) { if ($r.name -eq $name -and ($null -eq $target -or $r.start -lt $target.start)) { $target = $r } }
  1080. if ($null -ne $target) {
  1081. # перед #КонецОбласти, сняв пустые строки над ним
  1082. $k = $target.end - 1
  1083. while ($k - 1 -gt $target.start - 1 -and -not $lines[$k - 1].Trim()) { $k--; $lines.RemoveAt($k) }
  1084. $lines.InsertRange($k, [string[]](@('') + $stub + @('')))
  1085. return
  1086. }
  1087. $block = [string[]](@("#Область $name", '') + $stub + @('', '#КонецОбласти'))
  1088. $rank = Get-RegionRank $name
  1089. $top = @($outline.regions | Where-Object { $_.depth -eq 0 } | Sort-Object start)
  1090. $after = $null; $before = $null
  1091. foreach ($r in $top) {
  1092. $rr = Get-RegionRank $r.name
  1093. if ($rr -lt 0) { continue }
  1094. if ($rr -le $rank) { $after = $r } elseif ($null -eq $before) { $before = $r }
  1095. }
  1096. if ($null -ne $after) { $lines.InsertRange($after.end, [string[]](@('') + $block)); return }
  1097. if ($null -ne $before) { $lines.InsertRange($before.start - 1, [string[]]($block + @(''))); return }
  1098. while ($lines.Count -gt 0 -and -not $lines[$lines.Count - 1].Trim()) { $lines.RemoveAt($lines.Count - 1) }
  1099. $lines.InsertRange($lines.Count, [string[]](@('') + $block))
  1100. }
  1101. # Дописать в модуль формы процедуры для привязок, которых в нём нет. Модуль — <каталог Form.xml>/Form/Module.bsl;
  1102. # нет модуля — создаётся из шаблона, но только в раскладке выгрузки (Form.xml в каталоге Ext).
  1103. # Кодировка и переводы строк существующего модуля сохраняются; новый — UTF-8 с BOM, CRLF, как у form-add.
  1104. # Возвращает строки отчёта: что добавлено, что уже было, с диапазонами строк по итоговому тексту.
  1105. function Update-FormModule([string]$formXmlPath, [string]$shownFormPath) {
  1106. if ($script:handlerBindings.Count -eq 0) { return @() }
  1107. $xmlDir = [System.IO.Path]::GetDirectoryName($formXmlPath)
  1108. $path = [System.IO.Path]::Combine($xmlDir, 'Form', 'Module.bsl')
  1109. # путь для вывода — в том же виде, что путь к Form.xml в выводе навыка
  1110. $sep = if ($shownFormPath.Contains('\') -and -not $shownFormPath.Contains('/')) { '\' } else { '/' }
  1111. $shown = ($shownFormPath -replace '[^\\/]+$', '') + "Form${sep}Module.bsl"
  1112. $created = $false
  1113. if (Test-Path -LiteralPath $path) {
  1114. $bytes = [System.IO.File]::ReadAllBytes($path)
  1115. $bom = ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF)
  1116. # строго: модуль не в UTF-8 перезапись испортила бы — такой не трогаем
  1117. try { $text = (New-Object System.Text.UTF8Encoding($false, $true)).GetString($bytes) }
  1118. catch { return @("[WARN] Form module is not UTF-8: $shown — handler stubs not created") }
  1119. if ($bom) { $text = $text.Substring(1) }
  1120. $eol = if ($text.Contains("`r`n") -or -not $text.Contains("`n")) { "`r`n" } else { "`n" }
  1121. $norm = $text -replace "`r`n", "`n"
  1122. # сколько переводов строк в конце — столько и запишем: модуль не должен меняться вне вставок
  1123. $tail = $norm.Length - $norm.TrimEnd("`n").Length
  1124. $src = @($norm.TrimEnd("`n") -split "`n")
  1125. if (-not $text.Trim()) { $src = Get-FormModuleTemplate }
  1126. } elseif ([System.IO.Path]::GetFileName($xmlDir) -eq 'Ext') {
  1127. $created = $true; $bom = $true; $eol = "`r`n"; $tail = 0
  1128. $src = Get-FormModuleTemplate
  1129. } else {
  1130. return @("[WARN] Form module not found: $shown — handler stubs not created")
  1131. }
  1132. $lines = New-Object System.Collections.ArrayList
  1133. $lines.AddRange([string[]]$src)
  1134. $status = @{}
  1135. $changed = $false
  1136. foreach ($b in $script:handlerBindings) {
  1137. $outline = Get-ModuleCodeOutline $lines.ToArray()
  1138. if (@($outline.procs | Where-Object { $_.name -eq $b.handler }).Count -gt 0) { $status[$b.handler] = 'exists'; continue }
  1139. $stub = Get-HandlerStub $b
  1140. if ($null -eq $stub) { $status[$b.handler] = "not added: no signature known for event '$($b.eventName)' of $($b.xmlTag)"; continue }
  1141. Add-StubToModule $lines $stub $b
  1142. $status[$b.handler] = 'added'
  1143. $changed = $true
  1144. }
  1145. if ($changed -or $created) {
  1146. $dir = [System.IO.Path]::GetDirectoryName($path)
  1147. if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
  1148. $out = ($lines.ToArray() -join $eol) + ($eol * $tail)
  1149. [System.IO.File]::WriteAllText($path, $out, (New-Object System.Text.UTF8Encoding($bom)))
  1150. }
  1151. $outline = Get-ModuleCodeOutline $lines.ToArray()
  1152. # в порядке строк модуля; не добавленные — в конце
  1153. $rows = @()
  1154. foreach ($b in $script:handlerBindings) {
  1155. $st = $status[$b.handler]
  1156. $p = @($outline.procs | Where-Object { $_.name -eq $b.handler })[0]
  1157. if ($st -eq 'added') { $rows += [pscustomobject]@{ line = $p.start; n = $rows.Count; text = " + $($b.handler) — empty stub added, lines $($p.start)-$($p.end)" } }
  1158. elseif ($st -eq 'exists') { $rows += [pscustomobject]@{ line = $p.start; n = $rows.Count; text = " = $($b.handler) — exists, lines $($p.start)-$($p.end)" } }
  1159. else { $rows += [pscustomobject]@{ line = [int]::MaxValue; n = $rows.Count; text = " ? $($b.handler) — $st" } }
  1160. }
  1161. $report = @(if ($created) { "Handlers ($shown, module created):" } else { "Handlers ($shown):" })
  1162. foreach ($r in @($rows | Sort-Object line, n)) { $report += $r.text }
  1163. return $report
  1164. }
  1165. # Тип реквизита формы, к которому привязана таблица ("" — не определить: пути нет или реквизита нет в форме).
  1166. function Get-TableSource($el) {
  1167. if ($el.PSObject.Properties["_dynList"] -and $el._dynList) { return 'DynamicList' }
  1168. return Get-DataPathSource "$($el.path)"
  1169. }
  1170. function Get-DataPathSource([string]$path) {
  1171. $rootName = ($path -split '\.')[0]
  1172. if (-not $rootName) { return '' }
  1173. foreach ($a in $root.SelectNodes("f:Attributes/f:Attribute", $nsMgr)) {
  1174. if ($a.GetAttribute('name') -eq $rootName) {
  1175. $t = $a.SelectSingleNode("f:Type/v8:Type", $nsMgr)
  1176. if ($null -ne $t) { return ($t.InnerText -replace '^[^:]*:', '') }
  1177. return ''
  1178. }
  1179. }
  1180. return ''
  1181. }
  1182. $script:companionStructKeys = @(
  1183. 'width','autoMaxWidth','maxWidth','height','autoMaxHeight','maxHeight','verticalAlign','titleHeight',
  1184. 'horizontalStretch','verticalStretch','horizontalAlign','groupHorizontalAlign','groupVerticalAlign',
  1185. 'visible','hidden','enabled','disabled','hyperlink','events','tooltip',
  1186. 'textColor','backColor','borderColor','font','border','цветтекста','цветфона','цветрамки','шрифт','рамка'
  1187. )
  1188. $script:additionTypeMap = [ordered]@{
  1189. 'searchString' = @{ Tag = 'SearchStringAddition'; Type = 'SearchStringRepresentation'; Suffix = 'СтрокаПоиска' }
  1190. 'viewStatus' = @{ Tag = 'ViewStatusAddition'; Type = 'ViewStatusRepresentation'; Suffix = 'СостояниеПросмотра' }
  1191. 'searchControl' = @{ Tag = 'SearchControlAddition'; Type = 'SearchControl'; Suffix = 'УправлениеПоиском' }
  1192. }
  1193. $script:additionKeySynonyms = @{
  1194. 'searchString' = @('SearchStringAddition','SearchStringRepresentation','строкаПоиска','отображениеСтрокиПоиска')
  1195. 'viewStatus' = @('ViewStatusAddition','ViewStatusRepresentation','состояниеПросмотра')
  1196. 'searchControl' = @('SearchControlAddition','SearchControl','управлениеПоиском')
  1197. }
  1198. $script:elementTypeStrOnlyKeys = @('commandBar','autoCommandBar','КоманднаяПанель')
  1199. $script:elementTypeSynonyms = @{
  1200. "commandBar" = "cmdBar"
  1201. "autoCommandBar" = "autoCmdBar"
  1202. "КоманднаяПанель" = "cmdBar"
  1203. "InputField" = "input"
  1204. "ПолеВвода" = "input"
  1205. "CheckBoxField" = "check"
  1206. "ПолеФлажка" = "check"
  1207. "RadioButtonField" = "radio"
  1208. "ПолеПереключателя" = "radio"
  1209. "radioButton" = "radio"
  1210. "PictureField" = "picField"
  1211. "ПолеКартинки" = "picField"
  1212. "LabelField" = "labelField"
  1213. "ПолеНадписи" = "labelField"
  1214. "CalendarField" = "calendar"
  1215. "ПолеКалендаря" = "calendar"
  1216. "LabelDecoration" = "label"
  1217. "Надпись" = "label"
  1218. "PictureDecoration" = "picture"
  1219. "Картинка" = "picture"
  1220. "UsualGroup" = "group"
  1221. "Группа" = "group"
  1222. "ОбычнаяГруппа" = "group"
  1223. "ColumnGroup" = "columnGroup"
  1224. "ГруппаКолонок" = "columnGroup"
  1225. "Pages" = "pages"
  1226. "ГруппаСтраниц" = "pages"
  1227. "Page" = "page"
  1228. "Страница" = "page"
  1229. "Table" = "table"
  1230. "Таблица" = "table"
  1231. "Button" = "button"
  1232. "Кнопка" = "button"
  1233. "Popup" = "popup"
  1234. "ВсплывающееМеню" = "popup"
  1235. # Дополнения командной панели таблицы (тип-как-ключ) — forgiving: XML-тег/Type/рус.имя → канон
  1236. "SearchStringAddition" = "searchString"
  1237. "SearchStringRepresentation" = "searchString"
  1238. "строкаПоиска" = "searchString"
  1239. "отображениеСтрокиПоиска" = "searchString"
  1240. "Отображение строки поиска" = "searchString"
  1241. "ViewStatusAddition" = "viewStatus"
  1242. "ViewStatusRepresentation" = "viewStatus"
  1243. "состояниеПросмотра" = "viewStatus"
  1244. "Состояние просмотра" = "viewStatus"
  1245. "SearchControlAddition" = "searchControl"
  1246. "SearchControl" = "searchControl"
  1247. "управлениеПоиском" = "searchControl"
  1248. "Управление поиском" = "searchControl"
  1249. # Спец-поля (документ/датчик) — XML-имя/рус. → канон
  1250. "SpreadSheetDocumentField" = "spreadsheet"
  1251. "ПолеТабличногоДокумента" = "spreadsheet"
  1252. "HTMLDocumentField" = "html"
  1253. "ПолеHTMLДокумента" = "html"
  1254. "TextDocumentField" = "textDoc"
  1255. "ПолеТекстовогоДокумента" = "textDoc"
  1256. "FormattedDocumentField" = "formattedDoc"
  1257. "ПолеФорматированногоДокумента" = "formattedDoc"
  1258. "ProgressBarField" = "progressBar"
  1259. "ПолеИндикатора" = "progressBar"
  1260. "TrackBarField" = "trackBar"
  1261. "ПолеПолосыРегулирования" = "trackBar"
  1262. "ChartField" = "chart"
  1263. "ПолеДиаграммы" = "chart"
  1264. "GanttChartField" = "ganttChart"
  1265. "ПолеДиаграммыГанта" = "ganttChart"
  1266. "GraphicalSchemaField" = "graphicalSchema"
  1267. "ПолеГрафическойСхемы" = "graphicalSchema"
  1268. "PlannerField" = "planner"
  1269. "ПолеПланировщика" = "planner"
  1270. "PeriodField" = "periodField"
  1271. "ПолеПериода" = "periodField"
  1272. "DendrogramField" = "dendrogram"
  1273. "ПолеДендрограммы" = "dendrogram"
  1274. }
  1275. $script:validEnumValues = @{
  1276. "ActionPurpose" = @("Usual","Create","Finish")
  1277. "AppearanceInCard" = @("Auto","Extended")
  1278. "AppearanceMode" = @("Auto","CommandBar","UsualGroup")
  1279. "AutoAddIncomplete" = @("true","false","auto")
  1280. "AutoCapitalizationOnTextInput" = @("Auto","None","Words","Sentences","AllCharacters")
  1281. "AutoChoiceIncomplete" = @("true","false","auto")
  1282. "AutoCorrectionOnTextInput" = @("Auto","Use","DontUse")
  1283. "AutoMarkIncomplete" = @("true","false","auto")
  1284. "AutoSaveDataInSettings" = @("DontUse","Use")
  1285. "AutoShowClearButtonMode" = @("Auto","Always","FilledOnly")
  1286. "AutoShowOpenButtonMode" = @("Auto","Always","FilledOnly")
  1287. "AutoShowState" = @("Auto","DontShow","Show","ShowOnComposition")
  1288. "AutoTime" = @("DontUse","Last","First","CurrentOrLast","CurrentOrFirst")
  1289. "AutoWidthInTable" = @("Auto","ByData","None","ByDataAndTitle")
  1290. "AutofillHint" = @("DontUse","FullName","GivenName","FamilyName","MiddleName","NamePrefix","NameSuffix","Street","City","Region","Country","PostalCode","UserName","Password","NewPassword","OneTimeCode","Email","PhoneNumber","CreditCardNumber")
  1291. "BackPictureEffect" = @("Auto","None","Semitransparency","SemitransparencyAndBlur")
  1292. "BackgroundShowMode" = @("Auto","DontShow","ShowAndIncreaseSize","ShowAndDontIncreaseSize")
  1293. "Behavior" = @("Usual","Collapsible","PopUp","Auto")
  1294. "BehaviorOnHorizontalCompression" = @("Auto","HideItemsByImportance","MoveItemsByImportance")
  1295. "ButtonImportance" = @("Main","Normal","Supplementary")
  1296. "CardBehaviorOnVerticalCompression" = @("Auto","MoveItemsToSwipeablePages","HideItems")
  1297. "CardPictureAndTitleAlign" = @("Auto","LeftHorizontallySidesVertically","CenterHorizontallySidesVertically","CenterHorizontallyCenterVertically")
  1298. "CardRepresentationType" = @("Usual","Group")
  1299. "CellActionsButtonViewMode" = @("Auto","DontShow","ShowOnHover")
  1300. "CellHyperlinkDisplayVariant" = @("Auto","Always","OnRowHover")
  1301. "CellHyperlinkRepresentation" = @("Auto","Show","DontShow")
  1302. "CellHyperlinksRepresentation" = @("Auto","AutoForSingle","ForAll","DontShow")
  1303. "CellMark" = @("None","ShapeUnderTextOval","IconCircle")
  1304. "CheckBoxType" = @("Auto","CheckBox","Tumbler","Switcher")
  1305. "ChildItemsTitleLocation" = @("Auto","Left","LeftIfPossible","Top")
  1306. "ChildItemsWidth" = @("Auto","Equal","LeftWide","LeftWidest","LeftNarrow","LeftNarrowest")
  1307. "ChildrenAlign" = @("Auto","None","ItemsLeftTitlesLeft","ItemsRightTitlesLeft","ItemsLeftTitlesRight","ItemsRightTitlesRight","TitlesLeftDataLeft","TitlesLeftDataRight","TitlesRightDataLeft","TitlesRightDataRight","TitlesLeftDataAuto")
  1308. "ChoiceButton" = @("true","false","auto")
  1309. "ChoiceButtonRepresentation" = @("Auto","ShowInDropList","ShowInDropListAndInInputField","ShowInInputField")
  1310. "InputField.ChoiceFoldersAndItems" = @("Items","Folders","FoldersAndItems","Auto")
  1311. "Table.ChoiceFoldersAndItems" = @("Items","Folders","FoldersAndItems")
  1312. "ChoiceHistoryOnInput" = @("Auto","DontUse")
  1313. "ChoiceListButton" = @("true","false","auto")
  1314. "ClearButton" = @("true","false","auto")
  1315. "CollapseItemsByImportanceVariant" = @("Auto","Use","DontUse")
  1316. "CommandBarLocation" = @("None","Auto","Top","Bottom")
  1317. "ComplexSettingsViewMode" = @("Show","DontShow")
  1318. "ControlRepresentation" = @("TitleHyperlink","Picture","Button","ButtonInParentElement")
  1319. "ConversationsRepresentation" = @("Auto","Show","DontShow")
  1320. "CreateButton" = @("true","false","auto")
  1321. "Command.CurrentRowUse" = @("Use","DontUse","Auto")
  1322. "Pages.CurrentRowUse" = @("Use","DontUse","Auto")
  1323. "Table.CurrentRowUse" = @("Auto","Choice","SelectionPresentation","SelectionPresentationAndChoice")
  1324. "UsualGroup.CurrentRowUse" = @("Use","DontUse","Auto")
  1325. "DisplayImportance" = @("Auto","VeryHigh","High","Usual","Low","VeryLow")
  1326. "DrawingSelectionShowMode" = @("Show","DontShow","Auto")
  1327. "DropListButton" = @("true","false","auto")
  1328. "EditMode" = @("Directly","Enter","EnterOnInput","Auto")
  1329. "EditTextUpdate" = @("Auto","DontUse","OnValueChange","Always")
  1330. "EnterKeyBehavior" = @("ControlNavigation","DefaultButton")
  1331. "EqualColumnsWidth" = @("true","false","auto")
  1332. "EqualItemsWidth" = @("true","false","auto")
  1333. "ExtendedEdit" = @("true","false","auto")
  1334. "FileDragMode" = @("AsFile","AsFileRef")
  1335. "FillCheck" = @("DontCheck","ShowError")
  1336. "FixInCard" = @("true","false","auto")
  1337. "FixingInTable" = @("None","Left","Right")
  1338. "FooterHorizontalAlign" = @("Left","Center","Right","Auto")
  1339. "ColumnGroup.Group" = @("Horizontal","Vertical","InCell")
  1340. "Form.Group" = @("Horizontal","Vertical","HorizontalIfPossible","AlwaysHorizontal","Auto","AutoScreenTypeSensitive")
  1341. "Page.Group" = @("Horizontal","Vertical","HorizontalIfPossible","AlwaysHorizontal","Auto","AutoScreenTypeSensitive")
  1342. "UsualGroup.Group" = @("Horizontal","Vertical","HorizontalIfPossible","AlwaysHorizontal","Auto","AutoScreenTypeSensitive")
  1343. "GroupHorizontalAlign" = @("Left","Center","Right","Auto")
  1344. "GroupVerticalAlign" = @("Top","Center","Bottom","Auto")
  1345. "HeaderHorizontalAlign" = @("Left","Center","Right","Auto")
  1346. "InputField.HeightControlVariant" = @("Auto","UseHeightInFormRows","UseContentHeight")
  1347. "Table.HeightControlVariant" = @("Auto","UseHeightInFormRows","UseHeightInTableRows","UseContentHeight")
  1348. "HierarchyPanelLocation" = @("Auto","None")
  1349. "HorizontalAlign" = @("Left","Center","Right","Auto")
  1350. "HorizontalLinesBWA" = @("true","false","auto")
  1351. "HorizontalLocation" = @("Left","Center","Right","Auto")
  1352. "Table.HorizontalScrollBar" = @("DontUse","UseAlways","AutoUse")
  1353. "HorizontalSpacing" = @("Auto","None","Half","Single","OneAndHalf","Double")
  1354. "AutoCommandBar.HorizontalStretch" = @("true","false","auto")
  1355. "ButtonGroup.HorizontalStretch" = @("true","false","auto")
  1356. "CheckBoxField.HorizontalStretch" = @("true","false","auto")
  1357. "ColumnGroup.HorizontalStretch" = @("true","false","auto")
  1358. "CommandBar.HorizontalStretch" = @("true","false","auto")
  1359. "ContextMenu.HorizontalStretch" = @("true","false","auto")
  1360. "ExtendedTooltip.HorizontalStretch" = @("true","false","auto")
  1361. "InputField.HorizontalStretch" = @("true","false","auto")
  1362. "LabelDecoration.HorizontalStretch" = @("true","false","auto")
  1363. "LabelField.HorizontalStretch" = @("true","false","auto")
  1364. "Page.HorizontalStretch" = @("true","false","auto")
  1365. "Pages.HorizontalStretch" = @("true","false","auto")
  1366. "PictureDecoration.HorizontalStretch" = @("true","false","auto")
  1367. "Popup.HorizontalStretch" = @("true","false","auto")
  1368. "RadioButtonField.HorizontalStretch" = @("true","false","auto")
  1369. "SearchControlAddition.HorizontalStretch" = @("true","false","auto")
  1370. "SearchStringAddition.HorizontalStretch" = @("true","false","auto")
  1371. "UsualGroup.HorizontalStretch" = @("true","false","auto")
  1372. "ViewStatusAddition.HorizontalStretch" = @("true","false","auto")
  1373. "Importance" = @("Main","Normal","Supplementary")
  1374. "IncompleteChoiceMode" = @("OnEnterPressed","OnActivate")
  1375. "InitialListView" = @("Beginning","End","Auto")
  1376. "InitialRowActivation" = @("Auto","Activate","NoActivate")
  1377. "InitialTreeView" = @("NoExpand","ExpandTopLevel","ExpandAllLevels")
  1378. "IntervalsSelectionMode" = @("Auto","Multiple","Single","None")
  1379. "KeyType" = @("Auto","FieldValue","RowKey","RowNumber")
  1380. "LocationInCommandBar" = @("Auto","InAdditionalSubmenu","InCommandBar","InCommandBarAndInAdditionalSubmenu")
  1381. "MarkNegatives" = @("true","false","auto")
  1382. "MarkRequiredComplete" = @("true","false","auto")
  1383. "MarkingAppearance" = @("DontShow","TopLeft","BottomRight","BothSides")
  1384. "MobileDeviceTableType" = @("Auto","List","Cards")
  1385. "MultiLine" = @("true","false","auto")
  1386. "MultipleValuePictureShape" = @("Auto","Rect","Circle","Square")
  1387. "MultipleValuePictureSize" = @("Auto","Small","Medium","Large")
  1388. "MultipleValuesHyperlink" = @("true","false","auto")
  1389. "OnMainServerUnavalableBehavior" = @("Auto","MakeDisable","DontChangeBehavior")
  1390. "OnScreenKeyboardReturnKeyText" = @("Auto","Return","Go","Join","Next","Search","Send","Done","Continue")
  1391. "OnlyInAllActions" = @("true","false","auto")
  1392. "OpenButton" = @("true","false","auto")
  1393. "Orientation" = @("Horizontal","Vertical","HorizontalIfPossible")
  1394. "Output" = @("Auto","Enable","Disable")
  1395. "PagesRepresentation" = @("None","TabsOnTop","TabsOnBottom","TabsOnLeftHorizontal","TabsOnRightHorizontal","Swipe","Auto")
  1396. "PasswordMode" = @("true","false","auto")
  1397. "PictureLocation" = @("Auto","Left","Right","Top","Bottom")
  1398. "PictureSize" = @("RealSize","Stretch","Proportionally","Tile","AutoSize","RealSizeIgnoreScale","AutoSizeIgnoreScale","ByFontSize")
  1399. "PlacementArea" = @("mainCmdsLeft","autoCmds","userCmds","mainCmdsRight")
  1400. "PointerType" = @("Special","Regular")
  1401. "QuickChoice" = @("true","false","auto")
  1402. "RadioButtonType" = @("Auto","RadioButtons","Tumbler")
  1403. "RefreshRequest" = @("None","PullFromTop","PullFromBottom","PullFromTopOrBottom")
  1404. "ReportFormType" = @("Main","Settings","Variant")
  1405. "ReportResultViewMode" = @("Auto","Default","Compact")
  1406. "Button.Representation" = @("Text","Picture","PictureAndText","Auto")
  1407. "ButtonGroup.Representation" = @("Auto","Usual","Compact")
  1408. "Command.Representation" = @("Text","Picture","TextPicture","Auto")
  1409. "Popup.Representation" = @("Text","Picture","PictureAndText","Auto")
  1410. "ProgressBarField.Representation" = @("Smooth","Broken","BrokenTilt")
  1411. "Table.Representation" = @("List","HierarchicalList","Tree")
  1412. "UsualGroup.Representation" = @("Auto","None","StrongSeparation","WeakSeparation","NormalSeparation","GroupBox","Line","Margin")
  1413. "RepresentationInContextMenu" = @("None","AdditionalInContextMenu","OnlyInContextMenu","Auto")
  1414. "RowActionsShowType" = @("Auto","DontShow","ShowOnHover","ShowAlways")
  1415. "RowInputMode" = @("EndOfList","EndOfWindow","AfterCurrentRow","BeforeCurrentRow")
  1416. "RowSelectionMode" = @("Auto","Cell","Row")
  1417. "SaveColors" = @("Auto","ForUser","ByKeyForUser","DontUse")
  1418. "SaveDataInSettings" = @("DontUse","UseList")
  1419. "ScaleVariant" = @("Auto","Normal","Compact","NormalIfPossible")
  1420. "ScalingMode" = @("Auto","Normal","Compact")
  1421. "Page.ScrollOnCompress" = @("true","false","auto")
  1422. "UsualGroup.ScrollOnCompress" = @("true","false","auto")
  1423. "SearchControlLocation" = @("Auto","None","CommandBar")
  1424. "SearchOnInput" = @("Use","DontUse","Auto")
  1425. "SearchStringLocation" = @("Auto","None","CommandBar","Top","Bottom","FormCaption","PullFromTop")
  1426. "SelectedRowsUse" = @("Use","DontUse","Auto")
  1427. "CalendarField.SelectionMode" = @("Single","Multiple","Interval")
  1428. "Table.SelectionMode" = @("SingleRow","MultiRow")
  1429. "SelectionShowMode" = @("WhenActive","Always","DontShow","WhenMultipleCellsSelected","WhenMultipleCellsSelectedWhenActive")
  1430. "Shape" = @("Auto","Usual","Oval")
  1431. "ShapeRepresentation" = @("Auto","Always","WhenActive","None")
  1432. "ShowCheckBoxesInDropList" = @("true","false","auto")
  1433. "ShowCommandBar" = @("true","false","auto")
  1434. "ShowHorizontalLinesFlag" = @("true","false","auto")
  1435. "ColumnGroup.ShowTitle" = @("true","false","auto")
  1436. "Form.ShowTitle" = @("true","false","auto")
  1437. "Page.ShowTitle" = @("true","false","auto")
  1438. "UsualGroup.ShowTitle" = @("true","false","auto")
  1439. "ShowTitleInCard" = @("true","false","auto")
  1440. "ShowVerticalLinesFlag" = @("true","false","auto")
  1441. "SkipOnInput" = @("true","false","auto")
  1442. "SpecialTextInputMode" = @("Auto","None","DigitsAndPunctuation","URL","Email","PhoneNumber","Digits")
  1443. "SpellCheckingOnTextInput" = @("Auto","Use","DontUse")
  1444. "SpinButton" = @("true","false","auto")
  1445. "SpreadsheetDocumentMultipleSelectionPanelViewMode" = @("Auto","DontShow","ShowOnMultipleSelection","ShowAlways")
  1446. "TableLocation" = @("Auto","Left","Right","None")
  1447. "TextSize" = @("Enlarged","Normal","Reduced")
  1448. "ThroughAlign" = @("Use","DontUse","Auto")
  1449. "TimeChoiceMode" = @("Auto","DontChoose","CustomTime","Interval1Minute","Interval5Minutes","Interval10Minutes","Interval15Minutes","Interval15And20Minutes","Interval20Minutes","Interval30Minutes","Interval60Minutes")
  1450. "TitleLocation" = @("None","Auto","Left","Top","Right","Bottom")
  1451. "ToolTipRepresentation" = @("Auto","None","Balloon","Button","ShowAuto","ShowTop","ShowLeft","ShowBottom","ShowRight")
  1452. "TumblerRepresentation" = @("Text","Picture","Auto")
  1453. "Button.Type" = @("CommandBarButton","UsualButton","Hyperlink","CommandBarHyperlink")
  1454. "UpdateOnDataChange" = @("Auto","DontUpdate")
  1455. "UseAlternationRowColorBWA" = @("true","false","auto")
  1456. "UseCopy" = @("true","false","auto")
  1457. "UseForFoldersAndItems" = @("Items","Folders","FoldersAndItems")
  1458. "UsePostingMode" = @("Regular","RealTime","Ask","Auto")
  1459. "ValuesSelectionMode" = @("Auto","Multiple","Single","None")
  1460. "VerticalAlign" = @("Top","Center","Bottom","Auto")
  1461. "VerticalLinesBWA" = @("true","false","auto")
  1462. "VerticalScroll" = @("auto","use","useIfNecessary","useWithoutStretch")
  1463. "Table.VerticalScrollBar" = @("DontUse","UseAlways","AutoUse")
  1464. "VerticalSpacing" = @("Auto","None","Half","Single","OneAndHalf","Double")
  1465. "AutoCommandBar.VerticalStretch" = @("true","false","auto")
  1466. "ButtonGroup.VerticalStretch" = @("true","false","auto")
  1467. "ColumnGroup.VerticalStretch" = @("true","false","auto")
  1468. "CommandBar.VerticalStretch" = @("true","false","auto")
  1469. "ContextMenu.VerticalStretch" = @("true","false","auto")
  1470. "ExtendedTooltip.VerticalStretch" = @("true","false","auto")
  1471. "InputField.VerticalStretch" = @("true","false","auto")
  1472. "LabelDecoration.VerticalStretch" = @("true","false","auto")
  1473. "LabelField.VerticalStretch" = @("true","false","auto")
  1474. "Page.VerticalStretch" = @("true","false","auto")
  1475. "Pages.VerticalStretch" = @("true","false","auto")
  1476. "PictureDecoration.VerticalStretch" = @("true","false","auto")
  1477. "Popup.VerticalStretch" = @("true","false","auto")
  1478. "UsualGroup.VerticalStretch" = @("true","false","auto")
  1479. "ViewMode" = @("All","QuickAccess")
  1480. "ViewModeApplicationOnSetReportResult" = @("Auto","Apply","DontApply")
  1481. "ViewScalingMode" = @("Auto","Normal","Large")
  1482. "ViewStatusLocation" = @("Auto","None","Top","Bottom")
  1483. "WarningOnEditRepresentation" = @("Show","DontShow","Auto")
  1484. "WidthInCard" = @("Auto","Full","Half")
  1485. "WindowOpeningMode" = @("Auto","DontBlock","LockOwner","LockWholeInterface","Independent","LockOwnerWindow")
  1486. }
  1487. $script:enumValueAliases = @{
  1488. "TitlesLeftDataLeft" = "ItemsLeftTitlesLeft"
  1489. "TitlesLeftDataRight" = "ItemsRightTitlesLeft"
  1490. "TitlesRightDataLeft" = "ItemsLeftTitlesRight"
  1491. "TitlesRightDataRight" = "ItemsRightTitlesRight"
  1492. "GroupBox" = "StrongSeparation"
  1493. "Margin" = "NormalSeparation"
  1494. "Square" = "Rect"
  1495. }
  1496. $script:enumDefaultValues = @{
  1497. "Attribute.FillCheck" = "DontCheck"
  1498. "AutoCommandBar.GroupHorizontalAlign" = "Auto"
  1499. "AutoCommandBar.GroupVerticalAlign" = "Auto"
  1500. "AutoCommandBar.HorizontalAlign" = "Left"
  1501. "AutoCommandBar.HorizontalStretch" = "auto"
  1502. "AutoCommandBar.ToolTipRepresentation" = "Auto"
  1503. "AutoCommandBar.VerticalStretch" = "auto"
  1504. "Button.GroupHorizontalAlign" = "Auto"
  1505. "Button.GroupVerticalAlign" = "Auto"
  1506. "Button.LocationInCommandBar" = "Auto"
  1507. "Button.OnMainServerUnavalableBehavior" = "Auto"
  1508. "Button.PictureLocation" = "Auto"
  1509. "Button.PlacementArea" = "userCmds"
  1510. "Button.Representation" = "Auto"
  1511. "Button.RepresentationInContextMenu" = "Auto"
  1512. "Button.Shape" = "Auto"
  1513. "Button.ShapeRepresentation" = "Auto"
  1514. "Button.SkipOnInput" = "auto"
  1515. "Button.ToolTipRepresentation" = "Auto"
  1516. "ButtonGroup.GroupHorizontalAlign" = "Auto"
  1517. "ButtonGroup.GroupVerticalAlign" = "Auto"
  1518. "ButtonGroup.HorizontalStretch" = "auto"
  1519. "ButtonGroup.PlacementArea" = "userCmds"
  1520. "ButtonGroup.Representation" = "Auto"
  1521. "ButtonGroup.ToolTipRepresentation" = "Auto"
  1522. "ButtonGroup.VerticalStretch" = "auto"
  1523. "CalendarField.EditMode" = "Enter"
  1524. "CalendarField.FixingInTable" = "None"
  1525. "CalendarField.FooterHorizontalAlign" = "Auto"
  1526. "CalendarField.GroupHorizontalAlign" = "Auto"
  1527. "CalendarField.GroupVerticalAlign" = "Auto"
  1528. "CalendarField.HeaderHorizontalAlign" = "Left"
  1529. "CalendarField.HorizontalAlign" = "Auto"
  1530. "CalendarField.OnMainServerUnavalableBehavior" = "Auto"
  1531. "CalendarField.SelectionMode" = "Single"
  1532. "CalendarField.SkipOnInput" = "auto"
  1533. "CalendarField.TitleLocation" = "Auto"
  1534. "CalendarField.ToolTipRepresentation" = "Auto"
  1535. "CalendarField.VerticalAlign" = "Auto"
  1536. "CalendarField.WarningOnEditRepresentation" = "Auto"
  1537. "ChartField.EditMode" = "Enter"
  1538. "ChartField.FixingInTable" = "None"
  1539. "ChartField.FooterHorizontalAlign" = "Auto"
  1540. "ChartField.GroupHorizontalAlign" = "Auto"
  1541. "ChartField.GroupVerticalAlign" = "Auto"
  1542. "ChartField.HeaderHorizontalAlign" = "Left"
  1543. "ChartField.HorizontalAlign" = "Auto"
  1544. "ChartField.OnMainServerUnavalableBehavior" = "Auto"
  1545. "ChartField.SkipOnInput" = "auto"
  1546. "ChartField.TitleLocation" = "Auto"
  1547. "ChartField.ToolTipRepresentation" = "Auto"
  1548. "ChartField.VerticalAlign" = "Auto"
  1549. "ChartField.WarningOnEditRepresentation" = "Auto"
  1550. "CheckBoxField.EditMode" = "Enter"
  1551. "CheckBoxField.EqualItemsWidth" = "auto"
  1552. "CheckBoxField.FixingInTable" = "None"
  1553. "CheckBoxField.FooterHorizontalAlign" = "Auto"
  1554. "CheckBoxField.GroupHorizontalAlign" = "Auto"
  1555. "CheckBoxField.GroupVerticalAlign" = "Auto"
  1556. "CheckBoxField.HeaderHorizontalAlign" = "Left"
  1557. "CheckBoxField.HorizontalAlign" = "Auto"
  1558. "CheckBoxField.OnMainServerUnavalableBehavior" = "Auto"
  1559. "CheckBoxField.SkipOnInput" = "auto"
  1560. "CheckBoxField.TitleLocation" = "Auto"
  1561. "CheckBoxField.ToolTipRepresentation" = "Auto"
  1562. "CheckBoxField.VerticalAlign" = "Auto"
  1563. "CheckBoxField.WarningOnEditRepresentation" = "Auto"
  1564. "Column.FillCheck" = "DontCheck"
  1565. "ColumnGroup.FixingInTable" = "None"
  1566. "ColumnGroup.Group" = "Vertical"
  1567. "ColumnGroup.GroupHorizontalAlign" = "Auto"
  1568. "ColumnGroup.GroupVerticalAlign" = "Auto"
  1569. "ColumnGroup.HeaderHorizontalAlign" = "Auto"
  1570. "ColumnGroup.HorizontalStretch" = "auto"
  1571. "ColumnGroup.ToolTipRepresentation" = "Auto"
  1572. "ColumnGroup.VerticalStretch" = "auto"
  1573. "Command.CurrentRowUse" = "Auto"
  1574. "Command.Representation" = "Auto"
  1575. "CommandBar.GroupHorizontalAlign" = "Auto"
  1576. "CommandBar.GroupVerticalAlign" = "Auto"
  1577. "CommandBar.HorizontalLocation" = "Left"
  1578. "CommandBar.HorizontalStretch" = "auto"
  1579. "CommandBar.ToolTipRepresentation" = "Auto"
  1580. "CommandBar.VerticalStretch" = "auto"
  1581. "ContextMenu.GroupHorizontalAlign" = "Auto"
  1582. "ContextMenu.GroupVerticalAlign" = "Auto"
  1583. "ContextMenu.HorizontalStretch" = "auto"
  1584. "ContextMenu.ToolTipRepresentation" = "Auto"
  1585. "ContextMenu.VerticalStretch" = "auto"
  1586. "ExtendedTooltip.GroupHorizontalAlign" = "Auto"
  1587. "ExtendedTooltip.GroupVerticalAlign" = "Auto"
  1588. "ExtendedTooltip.HorizontalAlign" = "Left"
  1589. "ExtendedTooltip.HorizontalStretch" = "auto"
  1590. "ExtendedTooltip.OnMainServerUnavalableBehavior" = "Auto"
  1591. "ExtendedTooltip.SkipOnInput" = "auto"
  1592. "ExtendedTooltip.ToolTipRepresentation" = "Auto"
  1593. "ExtendedTooltip.VerticalAlign" = "Auto"
  1594. "ExtendedTooltip.VerticalStretch" = "auto"
  1595. "Form.AutoSaveDataInSettings" = "DontUse"
  1596. "Form.ChildItemsWidth" = "Auto"
  1597. "Form.ChildrenAlign" = "Auto"
  1598. "Form.CollapseItemsByImportanceVariant" = "Auto"
  1599. "Form.CommandBarLocation" = "Auto"
  1600. "Form.ConversationsRepresentation" = "Auto"
  1601. "Form.EnterKeyBehavior" = "ControlNavigation"
  1602. "Form.Group" = "Vertical"
  1603. "Form.HorizontalAlign" = "Auto"
  1604. "Form.HorizontalSpacing" = "Auto"
  1605. "Form.SaveDataInSettings" = "DontUse"
  1606. "Form.ScalingMode" = "Auto"
  1607. "Form.VerticalAlign" = "Auto"
  1608. "Form.VerticalScroll" = "auto"
  1609. "Form.VerticalSpacing" = "Auto"
  1610. "Form.WindowOpeningMode" = "Independent"
  1611. "FormattedDocumentField.EditMode" = "Enter"
  1612. "FormattedDocumentField.FixingInTable" = "None"
  1613. "FormattedDocumentField.FooterHorizontalAlign" = "Auto"
  1614. "FormattedDocumentField.GroupHorizontalAlign" = "Auto"
  1615. "FormattedDocumentField.GroupVerticalAlign" = "Auto"
  1616. "FormattedDocumentField.HeaderHorizontalAlign" = "Left"
  1617. "FormattedDocumentField.HorizontalAlign" = "Auto"
  1618. "FormattedDocumentField.OnMainServerUnavalableBehavior" = "Auto"
  1619. "FormattedDocumentField.Output" = "Auto"
  1620. "FormattedDocumentField.SkipOnInput" = "auto"
  1621. "FormattedDocumentField.TitleLocation" = "Auto"
  1622. "FormattedDocumentField.ToolTipRepresentation" = "Auto"
  1623. "FormattedDocumentField.VerticalAlign" = "Auto"
  1624. "FormattedDocumentField.WarningOnEditRepresentation" = "Auto"
  1625. "GraphicalSchemaField.EditMode" = "Enter"
  1626. "GraphicalSchemaField.FixingInTable" = "None"
  1627. "GraphicalSchemaField.FooterHorizontalAlign" = "Auto"
  1628. "GraphicalSchemaField.GroupHorizontalAlign" = "Auto"
  1629. "GraphicalSchemaField.GroupVerticalAlign" = "Auto"
  1630. "GraphicalSchemaField.HeaderHorizontalAlign" = "Left"
  1631. "GraphicalSchemaField.HorizontalAlign" = "Auto"
  1632. "GraphicalSchemaField.OnMainServerUnavalableBehavior" = "Auto"
  1633. "GraphicalSchemaField.Output" = "Auto"
  1634. "GraphicalSchemaField.SkipOnInput" = "auto"
  1635. "GraphicalSchemaField.TitleLocation" = "Auto"
  1636. "GraphicalSchemaField.ToolTipRepresentation" = "Auto"
  1637. "GraphicalSchemaField.VerticalAlign" = "Auto"
  1638. "GraphicalSchemaField.WarningOnEditRepresentation" = "Auto"
  1639. "HTMLDocumentField.EditMode" = "Enter"
  1640. "HTMLDocumentField.FixingInTable" = "None"
  1641. "HTMLDocumentField.FooterHorizontalAlign" = "Auto"
  1642. "HTMLDocumentField.GroupHorizontalAlign" = "Auto"
  1643. "HTMLDocumentField.GroupVerticalAlign" = "Auto"
  1644. "HTMLDocumentField.HeaderHorizontalAlign" = "Left"
  1645. "HTMLDocumentField.HorizontalAlign" = "Auto"
  1646. "HTMLDocumentField.OnMainServerUnavalableBehavior" = "Auto"
  1647. "HTMLDocumentField.Output" = "Auto"
  1648. "HTMLDocumentField.SkipOnInput" = "auto"
  1649. "HTMLDocumentField.TitleLocation" = "Auto"
  1650. "HTMLDocumentField.ToolTipRepresentation" = "Auto"
  1651. "HTMLDocumentField.VerticalAlign" = "Auto"
  1652. "HTMLDocumentField.WarningOnEditRepresentation" = "Auto"
  1653. "InputField.AutoCapitalizationOnTextInput" = "Auto"
  1654. "InputField.AutoChoiceIncomplete" = "auto"
  1655. "InputField.AutoCorrectionOnTextInput" = "Auto"
  1656. "InputField.AutoMarkIncomplete" = "auto"
  1657. "InputField.AutoShowClearButtonMode" = "Auto"
  1658. "InputField.AutoShowOpenButtonMode" = "Auto"
  1659. "InputField.AutofillHint" = "DontUse"
  1660. "InputField.ChoiceButton" = "auto"
  1661. "InputField.ChoiceButtonRepresentation" = "Auto"
  1662. "InputField.ChoiceFoldersAndItems" = "Auto"
  1663. "InputField.ChoiceHistoryOnInput" = "Auto"
  1664. "InputField.ChoiceListButton" = "auto"
  1665. "InputField.ClearButton" = "auto"
  1666. "InputField.CreateButton" = "auto"
  1667. "InputField.DropListButton" = "auto"
  1668. "InputField.EditMode" = "Enter"
  1669. "InputField.EditTextUpdate" = "Auto"
  1670. "InputField.ExtendedEdit" = "auto"
  1671. "InputField.FixingInTable" = "None"
  1672. "InputField.FooterHorizontalAlign" = "Auto"
  1673. "InputField.GroupHorizontalAlign" = "Auto"
  1674. "InputField.GroupVerticalAlign" = "Auto"
  1675. "InputField.HeaderHorizontalAlign" = "Left"
  1676. "InputField.HeightControlVariant" = "Auto"
  1677. "InputField.HorizontalAlign" = "Auto"
  1678. "InputField.HorizontalStretch" = "auto"
  1679. "InputField.IncompleteChoiceMode" = "OnEnterPressed"
  1680. "InputField.MarkNegatives" = "auto"
  1681. "InputField.MultiLine" = "auto"
  1682. "InputField.MultipleValuePictureShape" = "Auto"
  1683. "InputField.MultipleValuePictureSize" = "Auto"
  1684. "InputField.MultipleValuesHyperlink" = "auto"
  1685. "InputField.OnMainServerUnavalableBehavior" = "Auto"
  1686. "InputField.OnScreenKeyboardReturnKeyText" = "Auto"
  1687. "InputField.OpenButton" = "auto"
  1688. "InputField.PasswordMode" = "auto"
  1689. "InputField.QuickChoice" = "auto"
  1690. "InputField.ShowCheckBoxesInDropList" = "auto"
  1691. "InputField.SkipOnInput" = "auto"
  1692. "InputField.SpecialTextInputMode" = "Auto"
  1693. "InputField.SpellCheckingOnTextInput" = "Auto"
  1694. "InputField.SpinButton" = "auto"
  1695. "InputField.TitleLocation" = "Auto"
  1696. "InputField.ToolTipRepresentation" = "Auto"
  1697. "InputField.VerticalAlign" = "Auto"
  1698. "InputField.VerticalStretch" = "auto"
  1699. "InputField.WarningOnEditRepresentation" = "Auto"
  1700. "LabelDecoration.GroupHorizontalAlign" = "Auto"
  1701. "LabelDecoration.GroupVerticalAlign" = "Auto"
  1702. "LabelDecoration.HorizontalAlign" = "Left"
  1703. "LabelDecoration.HorizontalStretch" = "auto"
  1704. "LabelDecoration.OnMainServerUnavalableBehavior" = "Auto"
  1705. "LabelDecoration.SkipOnInput" = "auto"
  1706. "LabelDecoration.ToolTipRepresentation" = "Auto"
  1707. "LabelDecoration.VerticalAlign" = "Auto"
  1708. "LabelDecoration.VerticalStretch" = "auto"
  1709. "LabelField.EditMode" = "Enter"
  1710. "LabelField.FixingInTable" = "None"
  1711. "LabelField.FooterHorizontalAlign" = "Auto"
  1712. "LabelField.GroupHorizontalAlign" = "Auto"
  1713. "LabelField.GroupVerticalAlign" = "Auto"
  1714. "LabelField.HeaderHorizontalAlign" = "Left"
  1715. "LabelField.HorizontalAlign" = "Auto"
  1716. "LabelField.HorizontalStretch" = "auto"
  1717. "LabelField.MarkNegatives" = "auto"
  1718. "LabelField.OnMainServerUnavalableBehavior" = "Auto"
  1719. "LabelField.PasswordMode" = "auto"
  1720. "LabelField.SkipOnInput" = "auto"
  1721. "LabelField.TitleLocation" = "Auto"
  1722. "LabelField.ToolTipRepresentation" = "Auto"
  1723. "LabelField.VerticalAlign" = "Auto"
  1724. "LabelField.VerticalStretch" = "auto"
  1725. "LabelField.WarningOnEditRepresentation" = "Auto"
  1726. "Page.ChildItemsWidth" = "Auto"
  1727. "Page.ChildrenAlign" = "Auto"
  1728. "Page.Group" = "Vertical"
  1729. "Page.GroupHorizontalAlign" = "Auto"
  1730. "Page.GroupVerticalAlign" = "Auto"
  1731. "Page.HorizontalAlign" = "Auto"
  1732. "Page.HorizontalSpacing" = "Auto"
  1733. "Page.HorizontalStretch" = "auto"
  1734. "Page.ToolTipRepresentation" = "Auto"
  1735. "Page.VerticalAlign" = "Auto"
  1736. "Page.VerticalSpacing" = "Auto"
  1737. "Page.VerticalStretch" = "auto"
  1738. "Pages.CurrentRowUse" = "Auto"
  1739. "Pages.GroupHorizontalAlign" = "Auto"
  1740. "Pages.GroupVerticalAlign" = "Auto"
  1741. "Pages.HorizontalStretch" = "auto"
  1742. "Pages.PagesRepresentation" = "Auto"
  1743. "Pages.ToolTipRepresentation" = "Auto"
  1744. "Pages.VerticalStretch" = "auto"
  1745. "PeriodField.EditMode" = "Enter"
  1746. "PeriodField.FixingInTable" = "None"
  1747. "PeriodField.FooterHorizontalAlign" = "Auto"
  1748. "PeriodField.GroupHorizontalAlign" = "Auto"
  1749. "PeriodField.GroupVerticalAlign" = "Auto"
  1750. "PeriodField.HeaderHorizontalAlign" = "Left"
  1751. "PeriodField.HorizontalAlign" = "Auto"
  1752. "PeriodField.OnMainServerUnavalableBehavior" = "Auto"
  1753. "PeriodField.SkipOnInput" = "auto"
  1754. "PeriodField.TitleLocation" = "Auto"
  1755. "PeriodField.ToolTipRepresentation" = "Auto"
  1756. "PeriodField.VerticalAlign" = "Auto"
  1757. "PeriodField.WarningOnEditRepresentation" = "Auto"
  1758. "PictureDecoration.FileDragMode" = "AsFileRef"
  1759. "PictureDecoration.GroupHorizontalAlign" = "Auto"
  1760. "PictureDecoration.GroupVerticalAlign" = "Auto"
  1761. "PictureDecoration.HorizontalStretch" = "auto"
  1762. "PictureDecoration.OnMainServerUnavalableBehavior" = "Auto"
  1763. "PictureDecoration.PictureSize" = "RealSize"
  1764. "PictureDecoration.SkipOnInput" = "auto"
  1765. "PictureDecoration.ToolTipRepresentation" = "Auto"
  1766. "PictureDecoration.VerticalStretch" = "auto"
  1767. "PictureField.EditMode" = "Enter"
  1768. "PictureField.FileDragMode" = "AsFileRef"
  1769. "PictureField.FixingInTable" = "None"
  1770. "PictureField.FooterHorizontalAlign" = "Auto"
  1771. "PictureField.GroupHorizontalAlign" = "Auto"
  1772. "PictureField.GroupVerticalAlign" = "Auto"
  1773. "PictureField.HeaderHorizontalAlign" = "Left"
  1774. "PictureField.HorizontalAlign" = "Auto"
  1775. "PictureField.OnMainServerUnavalableBehavior" = "Auto"
  1776. "PictureField.PictureSize" = "RealSize"
  1777. "PictureField.SkipOnInput" = "auto"
  1778. "PictureField.TitleLocation" = "Auto"
  1779. "PictureField.ToolTipRepresentation" = "Auto"
  1780. "PictureField.VerticalAlign" = "Auto"
  1781. "PictureField.WarningOnEditRepresentation" = "Auto"
  1782. "PlannerField.EditMode" = "Enter"
  1783. "PlannerField.FixingInTable" = "None"
  1784. "PlannerField.FooterHorizontalAlign" = "Auto"
  1785. "PlannerField.GroupHorizontalAlign" = "Auto"
  1786. "PlannerField.GroupVerticalAlign" = "Auto"
  1787. "PlannerField.HeaderHorizontalAlign" = "Left"
  1788. "PlannerField.HorizontalAlign" = "Auto"
  1789. "PlannerField.OnMainServerUnavalableBehavior" = "Auto"
  1790. "PlannerField.SkipOnInput" = "auto"
  1791. "PlannerField.TitleLocation" = "Auto"
  1792. "PlannerField.ToolTipRepresentation" = "Auto"
  1793. "PlannerField.VerticalAlign" = "Auto"
  1794. "PlannerField.WarningOnEditRepresentation" = "Auto"
  1795. "Popup.GroupHorizontalAlign" = "Auto"
  1796. "Popup.GroupVerticalAlign" = "Auto"
  1797. "Popup.HorizontalStretch" = "auto"
  1798. "Popup.PlacementArea" = "userCmds"
  1799. "Popup.Representation" = "Auto"
  1800. "Popup.Shape" = "Auto"
  1801. "Popup.ShapeRepresentation" = "Auto"
  1802. "Popup.ToolTipRepresentation" = "Auto"
  1803. "Popup.VerticalStretch" = "auto"
  1804. "ProgressBarField.EditMode" = "Enter"
  1805. "ProgressBarField.FixingInTable" = "None"
  1806. "ProgressBarField.FooterHorizontalAlign" = "Auto"
  1807. "ProgressBarField.GroupHorizontalAlign" = "Auto"
  1808. "ProgressBarField.GroupVerticalAlign" = "Auto"
  1809. "ProgressBarField.HeaderHorizontalAlign" = "Left"
  1810. "ProgressBarField.HorizontalAlign" = "Auto"
  1811. "ProgressBarField.OnMainServerUnavalableBehavior" = "Auto"
  1812. "ProgressBarField.Orientation" = "Horizontal"
  1813. "ProgressBarField.Representation" = "Smooth"
  1814. "ProgressBarField.SkipOnInput" = "auto"
  1815. "ProgressBarField.TitleLocation" = "Auto"
  1816. "ProgressBarField.ToolTipRepresentation" = "Auto"
  1817. "ProgressBarField.VerticalAlign" = "Auto"
  1818. "ProgressBarField.WarningOnEditRepresentation" = "Auto"
  1819. "RadioButtonField.EditMode" = "Enter"
  1820. "RadioButtonField.EqualColumnsWidth" = "auto"
  1821. "RadioButtonField.FixingInTable" = "None"
  1822. "RadioButtonField.FooterHorizontalAlign" = "Auto"
  1823. "RadioButtonField.GroupHorizontalAlign" = "Auto"
  1824. "RadioButtonField.GroupVerticalAlign" = "Auto"
  1825. "RadioButtonField.HeaderHorizontalAlign" = "Left"
  1826. "RadioButtonField.HorizontalAlign" = "Auto"
  1827. "RadioButtonField.OnMainServerUnavalableBehavior" = "Auto"
  1828. "RadioButtonField.SkipOnInput" = "auto"
  1829. "RadioButtonField.TitleLocation" = "Auto"
  1830. "RadioButtonField.ToolTipRepresentation" = "Auto"
  1831. "RadioButtonField.VerticalAlign" = "Auto"
  1832. "RadioButtonField.WarningOnEditRepresentation" = "Auto"
  1833. "SearchControlAddition.GroupHorizontalAlign" = "Auto"
  1834. "SearchControlAddition.GroupVerticalAlign" = "Auto"
  1835. "SearchControlAddition.HorizontalStretch" = "auto"
  1836. "SearchControlAddition.PlacementArea" = "userCmds"
  1837. "SearchControlAddition.ToolTipRepresentation" = "Auto"
  1838. "SearchStringAddition.GroupHorizontalAlign" = "Auto"
  1839. "SearchStringAddition.GroupVerticalAlign" = "Auto"
  1840. "SearchStringAddition.HorizontalStretch" = "auto"
  1841. "SearchStringAddition.PlacementArea" = "userCmds"
  1842. "SearchStringAddition.ToolTipRepresentation" = "Auto"
  1843. "Settings.KeyType" = "Auto"
  1844. "SpreadSheetDocumentField.DrawingSelectionShowMode" = "Auto"
  1845. "SpreadSheetDocumentField.EditMode" = "Enter"
  1846. "SpreadSheetDocumentField.FixingInTable" = "None"
  1847. "SpreadSheetDocumentField.FooterHorizontalAlign" = "Auto"
  1848. "SpreadSheetDocumentField.GroupHorizontalAlign" = "Auto"
  1849. "SpreadSheetDocumentField.GroupVerticalAlign" = "Auto"
  1850. "SpreadSheetDocumentField.HeaderHorizontalAlign" = "Left"
  1851. "SpreadSheetDocumentField.HorizontalAlign" = "Auto"
  1852. "SpreadSheetDocumentField.OnMainServerUnavalableBehavior" = "Auto"
  1853. "SpreadSheetDocumentField.Output" = "Auto"
  1854. "SpreadSheetDocumentField.PointerType" = "Special"
  1855. "SpreadSheetDocumentField.SelectionShowMode" = "Always"
  1856. "SpreadSheetDocumentField.SkipOnInput" = "auto"
  1857. "SpreadSheetDocumentField.TitleLocation" = "Auto"
  1858. "SpreadSheetDocumentField.ToolTipRepresentation" = "Auto"
  1859. "SpreadSheetDocumentField.VerticalAlign" = "Auto"
  1860. "SpreadSheetDocumentField.ViewScalingMode" = "Auto"
  1861. "SpreadSheetDocumentField.WarningOnEditRepresentation" = "Auto"
  1862. "Table.AutoAddIncomplete" = "auto"
  1863. "Table.AutoMarkIncomplete" = "auto"
  1864. "Table.BehaviorOnHorizontalCompression" = "Auto"
  1865. "Table.CommandBarLocation" = "Auto"
  1866. "Table.CurrentRowUse" = "Auto"
  1867. "Table.FileDragMode" = "AsFileRef"
  1868. "Table.GroupHorizontalAlign" = "Auto"
  1869. "Table.GroupVerticalAlign" = "Auto"
  1870. "Table.HeightControlVariant" = "Auto"
  1871. "Table.HorizontalScrollBar" = "AutoUse"
  1872. "Table.InitialListView" = "Auto"
  1873. "Table.InitialTreeView" = "NoExpand"
  1874. "Table.OnMainServerUnavalableBehavior" = "Auto"
  1875. "Table.Output" = "Auto"
  1876. "Table.RefreshRequest" = "None"
  1877. "Table.Representation" = "HierarchicalList"
  1878. "Table.RowInputMode" = "EndOfList"
  1879. "Table.RowSelectionMode" = "Cell"
  1880. "Table.SearchControlLocation" = "Auto"
  1881. "Table.SearchOnInput" = "Auto"
  1882. "Table.SearchStringLocation" = "Auto"
  1883. "Table.SelectionMode" = "MultiRow"
  1884. "Table.SkipOnInput" = "auto"
  1885. "Table.TitleLocation" = "None"
  1886. "Table.ToolTipRepresentation" = "Auto"
  1887. "Table.VerticalScrollBar" = "AutoUse"
  1888. "Table.ViewStatusLocation" = "Auto"
  1889. "TextDocumentField.EditMode" = "Enter"
  1890. "TextDocumentField.FixingInTable" = "None"
  1891. "TextDocumentField.FooterHorizontalAlign" = "Auto"
  1892. "TextDocumentField.GroupHorizontalAlign" = "Auto"
  1893. "TextDocumentField.GroupVerticalAlign" = "Auto"
  1894. "TextDocumentField.HeaderHorizontalAlign" = "Left"
  1895. "TextDocumentField.HorizontalAlign" = "Auto"
  1896. "TextDocumentField.OnMainServerUnavalableBehavior" = "Auto"
  1897. "TextDocumentField.Output" = "Auto"
  1898. "TextDocumentField.SkipOnInput" = "auto"
  1899. "TextDocumentField.TitleLocation" = "Auto"
  1900. "TextDocumentField.ToolTipRepresentation" = "Auto"
  1901. "TextDocumentField.VerticalAlign" = "Auto"
  1902. "TextDocumentField.WarningOnEditRepresentation" = "Auto"
  1903. "TrackBarField.EditMode" = "Enter"
  1904. "TrackBarField.FixingInTable" = "None"
  1905. "TrackBarField.FooterHorizontalAlign" = "Auto"
  1906. "TrackBarField.GroupHorizontalAlign" = "Auto"
  1907. "TrackBarField.GroupVerticalAlign" = "Auto"
  1908. "TrackBarField.HeaderHorizontalAlign" = "Left"
  1909. "TrackBarField.HorizontalAlign" = "Auto"
  1910. "TrackBarField.MarkingAppearance" = "BottomRight"
  1911. "TrackBarField.OnMainServerUnavalableBehavior" = "Auto"
  1912. "TrackBarField.Orientation" = "Horizontal"
  1913. "TrackBarField.SkipOnInput" = "auto"
  1914. "TrackBarField.TitleLocation" = "Auto"
  1915. "TrackBarField.ToolTipRepresentation" = "Auto"
  1916. "TrackBarField.VerticalAlign" = "Auto"
  1917. "TrackBarField.WarningOnEditRepresentation" = "Auto"
  1918. "UsualGroup.Behavior" = "Auto"
  1919. "UsualGroup.ChildItemsWidth" = "Auto"
  1920. "UsualGroup.ChildrenAlign" = "Auto"
  1921. "UsualGroup.ControlRepresentation" = "TitleHyperlink"
  1922. "UsualGroup.CurrentRowUse" = "Auto"
  1923. "UsualGroup.Group" = "HorizontalIfPossible"
  1924. "UsualGroup.GroupHorizontalAlign" = "Auto"
  1925. "UsualGroup.GroupVerticalAlign" = "Auto"
  1926. "UsualGroup.HorizontalAlign" = "Auto"
  1927. "UsualGroup.HorizontalSpacing" = "Auto"
  1928. "UsualGroup.HorizontalStretch" = "auto"
  1929. "UsualGroup.Representation" = "WeakSeparation"
  1930. "UsualGroup.ThroughAlign" = "Auto"
  1931. "UsualGroup.ToolTipRepresentation" = "Auto"
  1932. "UsualGroup.VerticalAlign" = "Auto"
  1933. "UsualGroup.VerticalSpacing" = "Auto"
  1934. "UsualGroup.VerticalStretch" = "auto"
  1935. "ViewStatusAddition.GroupHorizontalAlign" = "Auto"
  1936. "ViewStatusAddition.GroupVerticalAlign" = "Auto"
  1937. "ViewStatusAddition.HorizontalLocation" = "Auto"
  1938. "ViewStatusAddition.HorizontalStretch" = "auto"
  1939. "ViewStatusAddition.PlacementArea" = "userCmds"
  1940. "ViewStatusAddition.ToolTipRepresentation" = "Auto"
  1941. }
  1942. $script:enumScopeTypes = @{
  1943. 'Attribute' = $true
  1944. 'AutoCommandBar' = $true
  1945. 'Button' = $true
  1946. 'ButtonGroup' = $true
  1947. 'CalendarField' = $true
  1948. 'ChartField' = $true
  1949. 'CheckBoxField' = $true
  1950. 'Column' = $true
  1951. 'ColumnGroup' = $true
  1952. 'Command' = $true
  1953. 'CommandBar' = $true
  1954. 'ContextMenu' = $true
  1955. 'ExtendedTooltip' = $true
  1956. 'Form' = $true
  1957. 'FormattedDocumentField' = $true
  1958. 'GanttChartField' = $true
  1959. 'GraphicalSchemaField' = $true
  1960. 'HTMLDocumentField' = $true
  1961. 'InputField' = $true
  1962. 'LabelDecoration' = $true
  1963. 'LabelField' = $true
  1964. 'Page' = $true
  1965. 'Pages' = $true
  1966. 'PeriodField' = $true
  1967. 'PictureDecoration' = $true
  1968. 'PictureField' = $true
  1969. 'PlannerField' = $true
  1970. 'Popup' = $true
  1971. 'ProgressBarField' = $true
  1972. 'RadioButtonField' = $true
  1973. 'SearchControlAddition' = $true
  1974. 'SearchStringAddition' = $true
  1975. 'Settings' = $true
  1976. 'SpreadSheetDocumentField' = $true
  1977. 'Table' = $true
  1978. 'TextDocumentField' = $true
  1979. 'TrackBarField' = $true
  1980. 'UsualGroup' = $true
  1981. 'ViewStatusAddition' = $true
  1982. }
  1983. $script:enumInputSynonyms = @{
  1984. "Command.Representation" = @{ "PictureAndText" = "TextPicture" }
  1985. "Button.Representation" = @{ "TextPicture" = "PictureAndText" }
  1986. "Popup.Representation" = @{ "TextPicture" = "PictureAndText" }
  1987. "Table.SelectionMode" = @{ "Single" = "SingleRow"; "Multiple" = "MultiRow" }
  1988. "CalendarField.SelectionMode" = @{ "SingleRow" = "Single"; "MultiRow" = "Multiple" }
  1989. }
  1990. $script:objType = $null
  1991. $script:childTagOrder = @{
  1992. 'AutoCommandBar' = 'HorizontalAlign Autofill ChildItems'
  1993. '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'
  1994. 'ButtonGroup' = 'EnableContentChange Visible Title GroupVerticalAlign ToolTip HorizontalStretch GroupHorizontalAlign ToolTipRepresentation CommandSource Representation VerticalStretch ExtendedTooltip ChildItems'
  1995. 'CalendarField' = 'DataPath SkipOnInput Title TitleLocation ToolTip ToolTipRepresentation Width AutoMaxWidth Height HorizontalStretch SelectionMode ShowCurrentDate ShowMonthsPanel WidthInMonths HeightInMonths ContextMenu ExtendedTooltip Events'
  1996. 'ChartField' = 'DataPath Enabled Title TitleFont Visible TitleLocation GroupHorizontalAlign Width AutoMaxWidth MaxHeight MaxWidth Height AutoMaxHeight HorizontalStretch VerticalStretch ContextMenu ExtendedTooltip Events'
  1997. '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'
  1998. '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'
  1999. 'CommandBar' = 'Enabled Visible EnableContentChange Title ToolTip ToolTipRepresentation Width Height HorizontalStretch VerticalStretch GroupHorizontalAlign GroupVerticalAlign HorizontalLocation CommandSource ExtendedTooltip ChildItems'
  2000. 'FormattedDocumentField' = 'DataPath DefaultItem Enabled ReadOnly SkipOnInput Title TitleLocation CommandSet Font ToolTip EditMode Width AutoMaxWidth Height AutoMaxHeight BorderColor HorizontalStretch MaxWidth ContextMenu ExtendedTooltip Events'
  2001. 'GanttChartField' = 'DataPath DefaultItem TitleLocation Width Height HorizontalStretch VerticalStretch ContextMenu ExtendedTooltip Table Events'
  2002. 'GraphicalSchemaField' = 'DataPath DefaultItem ReadOnly Title TitleLocation WarningOnEditRepresentation Width Height Edit ContextMenu ExtendedTooltip Events'
  2003. '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'
  2004. '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'
  2005. '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'
  2006. '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'
  2007. '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'
  2008. 'Pages' = 'Enabled ReadOnly EnableContentChange UserVisible Visible Title TitleFont ToolTip ToolTipRepresentation Width Height HorizontalStretch VerticalStretch GroupHorizontalAlign GroupVerticalAlign PagesRepresentation CurrentRowUse ExtendedTooltip Events ChildItems'
  2009. 'PeriodField' = 'DataPath TitleLocation ContextMenu ExtendedTooltip'
  2010. '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'
  2011. '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'
  2012. 'PlannerField' = 'DataPath TitleLocation ContextMenu ExtendedTooltip Events'
  2013. 'Popup' = 'UserVisible Visible EnableContentChange Title Shape TitleTextColor TitleFont ToolTip ToolTipRepresentation VerticalStretch Width HorizontalStretch Picture CommandSource Representation BackColor ShapeRepresentation BorderColor ExtendedTooltip ChildItems'
  2014. 'ProgressBarField' = 'DataPath Title Visible ReadOnly TitleLocation ToolTip ToolTipRepresentation Width AutoMaxHeight AutoMaxWidth HorizontalStretch MaxValue ShowPercent ContextMenu ExtendedTooltip'
  2015. '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'
  2016. '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'
  2017. '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'
  2018. 'TextDocumentField' = 'DataPath DefaultItem ReadOnly Title TitleFont TitleLocation EditMode ToolTip Width AutoMaxWidth Font MaxWidth Height AutoMaxHeight ContextMenu ExtendedTooltip Events'
  2019. 'TrackBarField' = 'DataPath Title TitleLocation HorizontalAlign ToolTip ToolTipRepresentation Width AutoMaxWidth HorizontalStretch MaxWidth Height AutoMaxHeight MinValue MarkingAppearance MaxValue LargeStep Step MarkingStep ContextMenu ExtendedTooltip Events'
  2020. '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'
  2021. }
  2022. $script:childRank = $null
  2023. $script:appearanceSpec = @{
  2024. titleTextColor = @{ tag='TitleTextColor'; kind='color' }
  2025. titleBackColor = @{ tag='TitleBackColor'; kind='color' }
  2026. titleFont = @{ tag='TitleFont'; kind='font' }
  2027. footerTextColor = @{ tag='FooterTextColor'; kind='color' }
  2028. footerBackColor = @{ tag='FooterBackColor'; kind='color' }
  2029. footerFont = @{ tag='FooterFont'; kind='font' }
  2030. textColor = @{ tag='TextColor'; kind='color' }
  2031. backColor = @{ tag='BackColor'; kind='color' }
  2032. borderColor = @{ tag='BorderColor'; kind='color' }
  2033. border = @{ tag='Border'; kind='border'}
  2034. font = @{ tag='Font'; kind='font' }
  2035. }
  2036. $script:appearanceSynonyms = @{
  2037. 'цветтекста'='textColor'; 'цветфона'='backColor'; 'цветрамки'='borderColor'
  2038. 'цветтекстазаголовка'='titleTextColor'; 'цветфоназаголовка'='titleBackColor'; 'шрифтзаголовка'='titleFont'
  2039. 'цветтекстаподвала'='footerTextColor'; 'цветфонаподвала'='footerBackColor'; 'шрифтподвала'='footerFont'
  2040. 'шрифт'='font'; 'рамка'='border'
  2041. }
  2042. $script:propSynonyms = @{
  2043. 'пометка'='checked'
  2044. 'кнопкавыбора'='choiceButton'; 'кнопкаочистки'='clearButton'; 'кнопкарегулирования'='spinButton'
  2045. 'кнопкавыпадающегосписка'='dropListButton'; 'кнопкасписковоговыбора'='choiceListButton'
  2046. 'кнопкаоткрытия'='openButton'; 'кнопкапоумолчанию'='defaultButton'
  2047. 'быстрыйвыбор'='quickChoice'; 'формавыбора'='choiceForm'; 'историявыборапривводе'='choiceHistoryOnInput'
  2048. 'выборгруппиэлементов'='choiceFoldersAndItems'; 'фиксациявтаблице'='fixingInTable'
  2049. 'путькданнымподвала'='footerDataPath'; 'автоотметканезаполненного'='markIncomplete'
  2050. 'многострочныйрежим'='multiLine'; 'режимпароля'='passwordMode'; 'переноспословам'='wrap'
  2051. 'расположениезаголовка'='titleLocation'; 'пропускатьпривводе'='skipOnInput'
  2052. 'заголовок'='title'; 'ширина'='width'; 'высота'='height'; 'подсказкаввода'='inputHint'
  2053. }
  2054. $script:appOrderField = @('titleTextColor','titleBackColor','titleFont','footerTextColor','footerBackColor','footerFont','textColor','backColor','borderColor','border','font')
  2055. $script:appOrderDecoration = @('textColor','font','backColor','borderColor','border')
  2056. $script:appOrderButton = @('textColor','backColor','borderColor','font')
  2057. $script:genericScalars = @(
  2058. @{ Tag='VerticalAlign'; Key='verticalAlign'; Kind='value' }
  2059. @{ Tag='ThroughAlign'; Key='throughAlign'; Kind='value' }
  2060. @{ Tag='EnableContentChange'; Key='enableContentChange'; Kind='bool' }
  2061. @{ Tag='PictureSize'; Key='pictureSize'; Kind='value' }
  2062. @{ Tag='TitleHeight'; Key='titleHeight'; Kind='value' }
  2063. @{ Tag='ChildItemsWidth'; Key='childItemsWidth'; Kind='value' }
  2064. @{ Tag='ShowLeftMargin'; Key='showLeftMargin'; Kind='bool' }
  2065. @{ Tag='CellHyperlink'; Key='cellHyperlink'; Kind='bool' }
  2066. @{ Tag='ViewMode'; Key='viewMode'; Kind='value' }
  2067. @{ Tag='VerticalScrollBar'; Key='verticalScrollBar'; Kind='value' }
  2068. @{ Tag='RowInputMode'; Key='rowInputMode'; Kind='value' }
  2069. @{ Tag='Mask'; Key='mask'; Kind='value' }
  2070. @{ Tag='CreateButton'; Key='createButton'; Kind='bool' }
  2071. @{ Tag='FixingInTable'; Key='fixingInTable'; Kind='value' }
  2072. @{ Tag='VerticalSpacing'; Key='verticalSpacing'; Kind='value' }
  2073. # Спец-поля (документ/датчик) — типоспец. enum/bool скаляры pass-through
  2074. @{ Tag='HorizontalScrollBar'; Key='horizontalScrollBar'; Kind='value' }
  2075. @{ Tag='ViewScalingMode'; Key='viewScalingMode'; Kind='value' }
  2076. @{ Tag='Output'; Key='output'; Kind='value' }
  2077. @{ Tag='SelectionShowMode'; Key='selectionShowMode'; Kind='value' }
  2078. @{ Tag='PointerType'; Key='pointerType'; Kind='value' }
  2079. @{ Tag='DrawingSelectionShowMode'; Key='drawingSelectionShowMode'; Kind='value' }
  2080. @{ Tag='WarningOnEditRepresentation'; Key='warningOnEditRepresentation'; Kind='value' }
  2081. @{ Tag='MarkingAppearance'; Key='markingAppearance'; Kind='value' }
  2082. @{ Tag='Protection'; Key='protection'; Kind='bool' }
  2083. @{ Tag='Edit'; Key='edit'; Kind='bool' }
  2084. @{ Tag='ShowGrid'; Key='showGrid'; Kind='bool' }
  2085. @{ Tag='ShowGroups'; Key='showGroups'; Kind='bool' }
  2086. @{ Tag='ShowHeaders'; Key='showHeaders'; Kind='bool' }
  2087. @{ Tag='ShowRowAndColumnNames'; Key='showRowAndColumnNames'; Kind='bool' }
  2088. @{ Tag='ShowCellNames'; Key='showCellNames'; Kind='bool' }
  2089. @{ Tag='ShowPercent'; Key='showPercent'; Kind='bool' }
  2090. # Report-form контекст: интервал группы / представление кнопки в контекстном меню / детальное представление настройки таблицы
  2091. @{ Tag='HorizontalSpacing'; Key='horizontalSpacing'; Kind='value' }
  2092. @{ Tag='RepresentationInContextMenu'; Key='representationInContextMenu'; Kind='value' }
  2093. @{ Tag='SettingsNamedItemDetailedRepresentation'; Key='settingsNamedItemDetailedRepresentation'; Kind='bool' }
  2094. # Хвост: высота элемента списка (radio) / ширина выпадающего списка (input)
  2095. @{ Tag='ItemHeight'; Key='itemHeight'; Kind='value' }
  2096. @{ Tag='DropListWidth'; Key='dropListWidth'; Kind='value' }
  2097. # Хвост CI-форм: динамический заголовок (Page/Group) / расширенное ред. (input) / высота таблицы по строкам
  2098. @{ Tag='TitleDataPath'; Key='titleDataPath'; Kind='value' }
  2099. @{ Tag='ExtendedEdit'; Key='extendedEdit'; Kind='bool' }
  2100. @{ Tag='MaxRowsCount'; Key='maxRowsCount'; Kind='value' }
  2101. @{ Tag='AutoMaxRowsCount'; Key='autoMaxRowsCount'; Kind='bool' }
  2102. @{ Tag='HeightControlVariant'; Key='heightControlVariant'; Kind='value' }
  2103. @{ Tag='EditTextUpdate'; Key='editTextUpdate'; Kind='value' }
  2104. # Корпусный хвост: представление управления свёрткой группы / форма кнопки-попапа /
  2105. # авто-добавление незаполненной строки / выделение отрицательных / нач. позиция списка /
  2106. # высота списка выбора / три состояния флажка / прокрутка страницы при сжатии
  2107. @{ Tag='ControlRepresentation'; Key='controlRepresentation'; Kind='value' }
  2108. @{ Tag='ShapeRepresentation'; Key='shapeRepresentation'; Kind='value' }
  2109. @{ Tag='AutoAddIncomplete'; Key='autoAddIncomplete'; Kind='bool' }
  2110. @{ Tag='MarkNegatives'; Key='markNegatives'; Kind='bool' }
  2111. @{ Tag='InitialListView'; Key='initialListView'; Kind='value' }
  2112. @{ Tag='ChoiceListHeight'; Key='choiceListHeight'; Kind='value' }
  2113. @{ Tag='ThreeState'; Key='threeState'; Kind='bool' }
  2114. @{ Tag='ScrollOnCompress'; Key='scrollOnCompress'; Kind='bool' }
  2115. # Сочетание клавиш — общее свойство (input/group/radio/page/picField/label/table/check; команда — отд. путь, §7)
  2116. @{ Tag='Shortcut'; Key='shortcut'; Kind='value' }
  2117. # Батч простых скаляров (input/radio/group/picDecoration/button): режим выбора незаполненного,
  2118. # равная ширина колонок, выравнивание детей, масштаб/зум картинки, форма/положение картинки кнопки.
  2119. # (Table HeaderHeight/FooterHeight/CurrentRowUse — НЕ здесь, а в Emit-Table: pass-through,
  2120. # 1С толерантна к порядку детей Table — в корпусе те же теги встречаются в разных позициях.)
  2121. @{ Tag='IncompleteChoiceMode'; Key='incompleteChoiceMode'; Kind='value' }
  2122. @{ Tag='EqualColumnsWidth'; Key='equalColumnsWidth'; Kind='bool' }
  2123. @{ Tag='ChildrenAlign'; Key='childrenAlign'; Kind='value' }
  2124. @{ Tag='ImageScale'; Key='imageScale'; Kind='value' }
  2125. @{ Tag='Zoomable'; Key='zoomable'; Kind='bool' }
  2126. @{ Tag='Shape'; Key='shape'; Kind='value' }
  2127. @{ Tag='PictureLocation'; Key='pictureLocation'; Kind='value' }
  2128. # Равная ширина элементов (check/radio) / высота заголовка пункта (radio)
  2129. @{ Tag='EqualItemsWidth'; Key='equalItemsWidth'; Kind='bool' }
  2130. @{ Tag='ItemTitleHeight'; Key='itemTitleHeight'; Kind='value' }
  2131. # Спец-режим ввода текста (input, моб.: Email/PhoneNumber/...) — листовой enum-скаляр
  2132. @{ Tag='SpecialTextInputMode'; Key='specialTextInputMode'; Kind='value' }
  2133. # Ширина пункта (radio/check) / выбор нескольких значений из выпадающего (input)
  2134. @{ Tag='ItemWidth'; Key='itemWidth'; Kind='value' }
  2135. @{ Tag='ShowCheckBoxesInDropList'; Key='showCheckBoxesInDropList'; Kind='bool' }
  2136. @{ Tag='MultipleValueDataPath'; Key='multipleValueDataPath'; Kind='value' }
  2137. @{ Tag='MultipleValuePresentDataPath'; Key='multipleValuePresentDataPath'; Kind='value' }
  2138. # Режим авто-показа кнопок открытия/очистки (input, enum Auto/Always/FilledOnly/…)
  2139. @{ Tag='AutoShowOpenButtonMode'; Key='autoShowOpenButtonMode'; Kind='value' }
  2140. @{ Tag='AutoShowClearButtonMode'; Key='autoShowClearButtonMode'; Kind='value' }
  2141. # Оформление/картинка множественного выбора (input, редко; цвета — текст-контент, не атрибуты)
  2142. @{ Tag='MultipleValuesTextColor'; Key='multipleValuesTextColor'; Kind='value' }
  2143. @{ Tag='MultipleValuesBackColor'; Key='multipleValuesBackColor'; Kind='value' }
  2144. @{ Tag='MultipleValuePictureShape'; Key='multipleValuePictureShape'; Kind='value' }
  2145. @{ Tag='MultipleValuePictureDataPath'; Key='multipleValuePictureDataPath'; Kind='value' }
  2146. # Хвост листовых скаляров (по 1 в корпусе): автокоррекция ввода (input) / уникальность команды
  2147. # (button) / допуск пустого множ. значения (input) / поведение при гориз. сжатии (table)
  2148. @{ Tag='AutoCorrectionOnTextInput'; Key='autoCorrectionOnTextInput'; Kind='value' }
  2149. @{ Tag='SpellCheckingOnTextInput'; Key='spellCheckingOnTextInput'; Kind='value' }
  2150. @{ Tag='CommandUniqueness'; Key='commandUniqueness'; Kind='bool' }
  2151. @{ Tag='AllowInputEmptyMultipleValues';Key='allowInputEmptyMultipleValues';Kind='bool' }
  2152. @{ Tag='BehaviorOnHorizontalCompression'; Key='behaviorOnHorizontalCompression'; Kind='value' }
  2153. )
  2154. $script:PLANNER_NS = 'http://v8.1c.ru/8.3/data/planner'
  2155. $script:CHART_NS = 'http://v8.1c.ru/8.2/data/chart'
  2156. $script:CHART_ML_FIELDS = @{ 'title'=1;'lbFormat'=1;'lbpFormat'=1;'vsFormat'=1;'dtFormat'=1;'dataSourceDescription'=1;'labelFormat'=1;'text'=1 }
  2157. $script:CHART_ATTR_FIELDS = @{ 'gaugeQualityBands'=1 }
  2158. $script:CHART_FONT_KEYS = @('ref','faceName','height','bold','italic','underline','strikeout','kind','scale')
  2159. $script:refRootSynonyms = @{
  2160. "Перечисление" = "Enum"
  2161. "Справочник" = "Catalog"
  2162. "Документ" = "Document"
  2163. "ПланСчетов" = "ChartOfAccounts"
  2164. "ПланВидовХарактеристик" = "ChartOfCharacteristicTypes"
  2165. "ПланВидовРасчета" = "ChartOfCalculationTypes"
  2166. "ПланВидовРасчёта" = "ChartOfCalculationTypes"
  2167. "ПланОбмена" = "ExchangePlan"
  2168. "БизнесПроцесс" = "BusinessProcess"
  2169. "Задача" = "Task"
  2170. "РегистрСведений" = "InformationRegister"
  2171. "РегистрНакопления" = "AccumulationRegister"
  2172. "РегистрБухгалтерии" = "AccountingRegister"
  2173. "РегистрРасчета" = "CalculationRegister"
  2174. "РегистрРасчёта" = "CalculationRegister"
  2175. "ЖурналДокументов" = "DocumentJournal"
  2176. "КритерийОтбора" = "FilterCriterion"
  2177. }
  2178. $script:enumValueSynonyms = @("EnumValue","ЗначениеПеречисления")
  2179. # Значение ссылки в dcscor:DesignTimeValue (отборы, параметры) — к виду Конфигуратора:
  2180. # "Enum.X.EnumValue.Y" / "Enum.X.Y" → "Перечисление.X.Y", "Catalog.X.EmptyRef" → "Справочник.X.ПустаяСсылка".
  2181. # Вид с сегментом EnumValue платформа не разрешает: сравнение с ним всегда ложно (замер 8.3.24).
  2182. $script:designTimeRefRoots = @{
  2183. "Enum" = "Перечисление"; "Catalog" = "Справочник"; "Document" = "Документ"; "ChartOfAccounts" = "ПланСчетов"
  2184. "ChartOfCharacteristicTypes" = "ПланВидовХарактеристик"; "ChartOfCalculationTypes" = "ПланВидовРасчета"
  2185. "ExchangePlan" = "ПланОбмена"; "BusinessProcess" = "БизнесПроцесс"; "Task" = "Задача"
  2186. }
  2187. function Normalize-DesignTimeValue([string]$v) {
  2188. $parts = @($v -split '\.')
  2189. if ($parts.Count -lt 3) { return $v }
  2190. if ($script:designTimeRefRoots.ContainsKey($parts[0])) { $parts[0] = $script:designTimeRefRoots[$parts[0]] }
  2191. if ($parts[0] -ceq 'Перечисление' -and $parts.Count -ge 4 -and $script:enumValueSynonyms -contains $parts[2]) {
  2192. $parts = @($parts[0], $parts[1]) + $parts[3..($parts.Count - 1)]
  2193. }
  2194. if ($parts[-1] -ceq 'EmptyRef') { $parts[-1] = 'ПустаяСсылка' }
  2195. return ($parts -join '.')
  2196. }
  2197. $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'
  2198. function Resolve-TextFromFile {
  2199. param([string]$val, [string]$baseDir)
  2200. if (-not $val.StartsWith("@")) { return $val }
  2201. $filePath = $val.Substring(1)
  2202. if ([System.IO.Path]::IsPathRooted($filePath)) {
  2203. $candidates = @($filePath)
  2204. } else {
  2205. $candidates = @(
  2206. (Join-Path $baseDir $filePath),
  2207. (Join-Path (Get-Location).ProviderPath $filePath)
  2208. )
  2209. }
  2210. foreach ($c in $candidates) {
  2211. if (Test-Path $c) {
  2212. return (Get-Content -Raw -Encoding UTF8 $c).TrimEnd()
  2213. }
  2214. }
  2215. Write-Error "Файл значения не найден: $filePath (искали: $($candidates -join ', '))"
  2216. exit 1
  2217. }
  2218. function Assert-UniqueName {
  2219. param([string]$name, [hashtable]$seen, [string]$kind)
  2220. if ($seen.ContainsKey($name)) {
  2221. Write-Error "Duplicate $kind name '$name' — names must be unique within their collection in a 1C form (set a unique 'name')"
  2222. exit 1
  2223. }
  2224. $seen[$name] = $true
  2225. }
  2226. function Esc-Xml {
  2227. param([string]$s)
  2228. # Эскейп ЗНАЧЕНИЯ АТРИБУТА: & < > и кавычка — внутри "..." литеральная " невалидна.
  2229. return $s.Replace('&','&amp;').Replace('<','&lt;').Replace('>','&gt;').Replace('"','&quot;')
  2230. }
  2231. function Esc-XmlText {
  2232. # Экранирование ТЕКСТА элемента (<v8:content>, <Value>): только & < > .
  2233. # Кавычки/апострофы в тексте экранировать НЕ нужно (1С их не экранирует — пишет литерально);
  2234. # &quot; ломал бы раундтрип. Кавычки спецсимвольны лишь в значениях атрибутов.
  2235. param([string]$s)
  2236. return $s.Replace('&','&amp;').Replace('<','&lt;').Replace('>','&gt;')
  2237. }
  2238. function Emit-MLItems {
  2239. param($val, [string]$indent)
  2240. if ($val -is [System.Collections.IDictionary]) {
  2241. foreach ($k in $val.Keys) {
  2242. 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>"
  2243. }
  2244. } elseif ($val -is [System.Management.Automation.PSCustomObject]) {
  2245. foreach ($p in $val.PSObject.Properties) {
  2246. 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>"
  2247. }
  2248. } else {
  2249. 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>"
  2250. }
  2251. }
  2252. function Emit-MLText {
  2253. param([string]$tag, $text, [string]$indent, [string]$xsiType)
  2254. $attr = if ($xsiType) { " xsi:type=`"$xsiType`"" } else { "" }
  2255. X "$indent<$tag$attr>"
  2256. Emit-MLItems -val $text -indent "$indent`t"
  2257. X "$indent</$tag>"
  2258. }
  2259. function Emit-USPresentation {
  2260. param($val, [string]$tag, [string]$indent)
  2261. if ($null -eq $val) { return }
  2262. if ($val -is [string]) {
  2263. X "$indent<$tag xsi:type=`"xs:string`">$(Esc-XmlText $val)</$tag>"
  2264. } else {
  2265. Emit-MLText -tag $tag -text $val -indent $indent -xsiType "v8:LocalStringType"
  2266. }
  2267. }
  2268. function Test-HasRealMarkup {
  2269. param($text)
  2270. if ($null -eq $text) { return $false }
  2271. $vals = if ($text -is [System.Collections.IDictionary]) { @($text.Values) }
  2272. elseif ($text -is [System.Management.Automation.PSCustomObject]) { @($text.PSObject.Properties.Value) }
  2273. else { @("$text") }
  2274. foreach ($v in $vals) { if ("$v" -match $script:fmtMarkupRe) { return $true } }
  2275. return $false
  2276. }
  2277. function Resolve-MLFormatted {
  2278. param($val)
  2279. $hasText = $false
  2280. if ($val -is [System.Management.Automation.PSCustomObject]) { $hasText = [bool]$val.PSObject.Properties['text'] }
  2281. elseif ($val -is [System.Collections.IDictionary]) { $hasText = $val.Contains('text') }
  2282. if ($hasText) {
  2283. $t = if ($val -is [System.Collections.IDictionary]) { $val['text'] } else { $val.text }
  2284. $f = if ($val -is [System.Collections.IDictionary]) { $val['formatted'] } else { $val.formatted }
  2285. return @{ text = $t; formatted = (ConvertTo-DslBool $f 'formatted' $false) }
  2286. }
  2287. return @{ text = $val; formatted = (Test-HasRealMarkup $val) }
  2288. }
  2289. function New-Guid-String { return [System.Guid]::NewGuid().ToString() }
  2290. function Parse-FilterShorthand {
  2291. param([string]$s)
  2292. $result = @{ field = ""; op = "Equal"; value = $null; use = $true; userSettingID = $null; viewMode = $null; presentation = $null }
  2293. if ($s -match '@user') { $result.userSettingID = "auto"; $s = $s -replace '\s*@user', '' }
  2294. if ($s -match '@off') { $result.use = $false; $s = $s -replace '\s*@off', '' }
  2295. if ($s -match '@quickAccess') { $result.viewMode = "QuickAccess"; $s = $s -replace '\s*@quickAccess', '' }
  2296. if ($s -match '@normal') { $result.viewMode = "Normal"; $s = $s -replace '\s*@normal', '' }
  2297. if ($s -match '@inaccessible') { $result.viewMode = "Inaccessible"; $s = $s -replace '\s*@inaccessible', '' }
  2298. $s = $s.Trim()
  2299. $opPatterns = @('<>', '>=', '<=', '=', '>', '<',
  2300. 'notIn\b', 'in\b', 'inHierarchy\b', 'inListByHierarchy\b',
  2301. 'notContains\b', 'contains\b', 'notBeginsWith\b', 'beginsWith\b',
  2302. 'notLike\b', 'like\b', 'неподобно\b', 'подобно\b',
  2303. 'notFilled\b', 'filled\b')
  2304. $opJoined = $opPatterns -join '|'
  2305. if ($s -match "^(.+?)\s+($opJoined)\s*(.*)?$") {
  2306. $result.field = $Matches[1].Trim()
  2307. $result.op = $Matches[2].Trim()
  2308. $valPart = if ($Matches[3]) { $Matches[3].Trim() } else { "" }
  2309. if ($valPart -and $valPart -ne "_") {
  2310. if ($valPart -eq "true" -or $valPart -eq "false") { $result.value = [bool]($valPart -eq "true"); $result["valueType"] = "xs:boolean" }
  2311. elseif ($valPart -match '^\d{4}-\d{2}-\d{2}T') { $result.value = $valPart } # дата без valueType → Emit-FilterItem выведет StandardBeginningDate Custom (дефолт даты в фильтре)
  2312. elseif ($valPart -match '^\d+(\.\d+)?$') { $result.value = $valPart; $result["valueType"] = "xs:decimal" }
  2313. elseif ($valPart -match '^(Перечисление|Справочник|ПланСчетов|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|ПланОбмена|Enum|Catalog|Document|ChartOfAccounts|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|ExchangePlan)\.[^.]+\.[^.]+') { $result.value = $valPart; $result["valueType"] = "dcscor:DesignTimeValue" }
  2314. else { $result.value = $valPart; $result["valueType"] = "xs:string" }
  2315. }
  2316. } else { $result.field = $s }
  2317. return $result
  2318. }
  2319. function Get-ValueTypeNsAttr {
  2320. param([string]$valueType, [string]$value)
  2321. if ($valueType -eq 'v8:Type' -and "$value" -match '^([A-Za-z]\w*):') {
  2322. $pref = $Matches[1]
  2323. if ($pref -notin @('xs','cfg','v8','v8ui','ent','dcscor','dcsset','dcssch')) {
  2324. return " xmlns:$pref=`"http://v8.1c.ru/8.2/data/types`""
  2325. }
  2326. }
  2327. return ""
  2328. }
  2329. function Emit-FilterItem {
  2330. param($item, [string]$indent)
  2331. if ($item.group) {
  2332. $groupType = switch ("$($item.group)") { "And" { "AndGroup" } "Or" { "OrGroup" } "Not" { "NotGroup" } default { "$($item.group)Group" } }
  2333. X "$indent<dcsset:item xsi:type=`"dcsset:FilterItemGroup`">"
  2334. if ((-not (Get-DslBool $item @('use') $true))) { X "$indent`t<dcsset:use>false</dcsset:use>" } # группа отключена (перед groupType, порядок исходника)
  2335. X "$indent`t<dcsset:groupType>$groupType</dcsset:groupType>"
  2336. if ($item.items) {
  2337. foreach ($sub in $item.items) {
  2338. if ($sub -is [string]) {
  2339. $parsed = Parse-FilterShorthand $sub
  2340. $obj = @{ field = $parsed.field; op = $parsed.op }
  2341. if ((-not (Get-DslBool $parsed @('use') $true))) { $obj.use = $false }
  2342. if ($null -ne $parsed.value) { $obj.value = $parsed.value }
  2343. if ($parsed["valueType"]) { $obj.valueType = $parsed["valueType"] }
  2344. if ($parsed.userSettingID) { $obj.userSettingID = $parsed.userSettingID }
  2345. if ($parsed.viewMode) { $obj.viewMode = $parsed.viewMode }
  2346. $sub = [pscustomobject]$obj
  2347. }
  2348. Emit-FilterItem -item $sub -indent "$indent`t"
  2349. }
  2350. }
  2351. if ($item.presentation) { Emit-USPresentation -val $item.presentation -tag "dcsset:presentation" -indent "$indent`t" }
  2352. if ($item.viewMode) { X "$indent`t<dcsset:viewMode>$(Esc-XmlText "$($item.viewMode)")</dcsset:viewMode>" }
  2353. if ($item.userSettingID) {
  2354. $guid = if ("$($item.userSettingID)" -eq "auto") { New-Guid-String } else { "$($item.userSettingID)" }
  2355. X "$indent`t<dcsset:userSettingID>$(Esc-XmlText $guid)</dcsset:userSettingID>"
  2356. }
  2357. if ($item.userSettingPresentation) { Emit-USPresentation -val $item.userSettingPresentation -tag "dcsset:userSettingPresentation" -indent "$indent`t" }
  2358. X "$indent</dcsset:item>"
  2359. return
  2360. }
  2361. X "$indent<dcsset:item xsi:type=`"dcsset:FilterItemComparison`">"
  2362. if ((-not (Get-DslBool $item @('use') $true))) { X "$indent`t<dcsset:use>false</dcsset:use>" }
  2363. X "$indent`t<dcsset:left xsi:type=`"dcscor:Field`">$(Esc-XmlText "$($item.field)")</dcsset:left>"
  2364. $compType = $script:comparisonTypes["$($item.op)"]
  2365. if (-not $compType) { $compType = "$($item.op)" }
  2366. X "$indent`t<dcsset:comparisonType>$(Esc-XmlText $compType)</dcsset:comparisonType>"
  2367. $valIsArray = ($item.value -is [array]) -or ($item.value -is [System.Collections.IList] -and $item.value -isnot [string])
  2368. if ($valIsArray) {
  2369. if (@($item.value).Count -eq 0) {
  2370. X "$indent`t<dcsset:right xsi:type=`"v8:ValueListType`">"
  2371. X "$indent`t`t<v8:valueType/>"
  2372. X "$indent`t`t<v8:lastId xsi:type=`"xs:decimal`">-1</v8:lastId>"
  2373. X "$indent`t</dcsset:right>"
  2374. } else {
  2375. foreach ($v in $item.value) {
  2376. $vt = if ($item.valueType) { "$($item.valueType)" } else { "" }
  2377. if (-not $vt) {
  2378. if ($v -is [bool]) { $vt = 'xs:boolean' }
  2379. elseif ($v -is [int] -or $v -is [long] -or $v -is [double]) { $vt = 'xs:decimal' }
  2380. elseif ("$v" -match '^\d{4}-\d{2}-\d{2}T') { $vt = 'xs:dateTime' }
  2381. elseif ("$v" -match '^-?\d+(\.\d+)?$') { $vt = 'xs:decimal' }
  2382. elseif ("$v" -match '^(Перечисление|Справочник|ПланСчетов|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|РегистрСведений|ПланОбмена|Catalog|Enum|Document|ChartOfAccounts|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|InformationRegister|ExchangePlan)\.') { $vt = 'dcscor:DesignTimeValue' }
  2383. else { $vt = 'xs:string' }
  2384. }
  2385. $vStr = if ($v -is [bool]) { "$v".ToLower() } elseif ($vt -eq 'dcscor:DesignTimeValue') { Esc-XmlText (Normalize-DesignTimeValue "$v") } else { Esc-XmlText "$v" }
  2386. $nsAttr = Get-ValueTypeNsAttr -valueType $vt -value "$v"
  2387. X "$indent`t<dcsset:right$nsAttr xsi:type=`"$vt`">$vStr</dcsset:right>"
  2388. }
  2389. }
  2390. } elseif ($null -ne $item.value -and (
  2391. "$($item.valueType)" -match 'Standard(Beginning|End)Date$' -or
  2392. (-not $item.valueType -and "$($item.value)" -match '^\d{4}-\d{2}-\d{2}T'))) {
  2393. # Стандартная дата начала/окончания. Формы значения:
  2394. # объект {variant, date?} — полная (Custom несёт <v8:date>);
  2395. # строка-вариант "BeginningOfThisDay" — именованный вариант без даты;
  2396. # голая ISO-дата без valueType — шорткат для Custom+date (дата в фильтре платформой
  2397. # почти всегда хранится как StandardBeginningDate Custom, корпус 268 vs 2 xs:dateTime;
  2398. # явный valueType="xs:dateTime" → плоская дата, ветка ниже).
  2399. $sdType = if ($item.valueType) { "$($item.valueType)" -replace '^v8:','' } else { 'StandardBeginningDate' }
  2400. $sv = $item.value
  2401. if (($sv -is [PSCustomObject]) -or ($sv -is [System.Collections.IDictionary])) {
  2402. $variant = if ($sv -is [PSCustomObject]) { "$($sv.variant)" } else { "$($sv['variant'])" }
  2403. $hasDate = if ($sv -is [PSCustomObject]) { [bool]$sv.PSObject.Properties['date'] } else { $sv.Contains('date') }
  2404. $dateV = if ($hasDate) { if ($sv -is [PSCustomObject]) { "$($sv.date)" } else { "$($sv['date'])" } } else { $null }
  2405. } elseif ("$sv" -match '^\d{4}-\d{2}-\d{2}T') {
  2406. $variant = 'Custom'; $hasDate = $true; $dateV = "$sv"
  2407. } else {
  2408. $variant = "$sv"; $hasDate = $false; $dateV = $null
  2409. }
  2410. X "$indent`t<dcsset:right xsi:type=`"v8:$sdType`">"
  2411. X "$indent`t`t<v8:variant xsi:type=`"v8:${sdType}Variant`">$(Esc-XmlText $variant)</v8:variant>"
  2412. if ($hasDate) { X "$indent`t`t<v8:date>$(Esc-XmlText $dateV)</v8:date>" }
  2413. X "$indent`t</dcsset:right>"
  2414. } elseif ("$($item.value)" -eq '_') {
  2415. # "_" — маркер пустого значения: платформа эмитит пустой self-closing <dcsset:right>
  2416. # (напр. <dcsset:right xsi:type="dcscor:Field"/> — сравнение с незаданным полем).
  2417. $vt = if ($item.valueType) { "$($item.valueType)" } else { 'xs:string' }
  2418. X "$indent`t<dcsset:right xsi:type=`"$vt`"/>"
  2419. } elseif ($null -ne $item.value) {
  2420. $vt = if ($item.valueType) { "$($item.valueType)" } else { "" }
  2421. if (-not $vt) {
  2422. $v = $item.value
  2423. if ($v -is [bool]) { $vt = "xs:boolean" }
  2424. elseif ($v -is [int] -or $v -is [long] -or $v -is [double]) { $vt = "xs:decimal" }
  2425. elseif ("$v" -match '^\d{4}-\d{2}-\d{2}T') { $vt = "xs:dateTime" }
  2426. elseif ("$v" -match '^-?\d+(\.\d+)?$') { $vt = "xs:decimal" }
  2427. elseif ("$v" -match '^(Перечисление|Справочник|ПланСчетов|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|РегистрСведений|ПланОбмена|Catalog|Enum|Document|ChartOfAccounts|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|InformationRegister|ExchangePlan)\.') { $vt = "dcscor:DesignTimeValue" }
  2428. else { $vt = "xs:string" }
  2429. }
  2430. $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)" }
  2431. $nsAttr = Get-ValueTypeNsAttr -valueType $vt -value "$($item.value)"
  2432. X "$indent`t<dcsset:right$nsAttr xsi:type=`"$vt`">$vStr</dcsset:right>"
  2433. }
  2434. if ($item.presentation) { Emit-USPresentation -val $item.presentation -tag "dcsset:presentation" -indent "$indent`t" }
  2435. if ($item.viewMode) { X "$indent`t<dcsset:viewMode>$(Esc-XmlText "$($item.viewMode)")</dcsset:viewMode>" }
  2436. if ($item.userSettingID) {
  2437. $uid = if ("$($item.userSettingID)" -eq "auto") { New-Guid-String } else { "$($item.userSettingID)" }
  2438. X "$indent`t<dcsset:userSettingID>$(Esc-XmlText $uid)</dcsset:userSettingID>"
  2439. }
  2440. if ($item.userSettingPresentation) { Emit-USPresentation -val $item.userSettingPresentation -tag "dcsset:userSettingPresentation" -indent "$indent`t" }
  2441. X "$indent</dcsset:item>"
  2442. }
  2443. function Emit-Filter {
  2444. param($items, [string]$indent, $blockViewMode = $null, $blockUserSettingID = $null, $blockUserSettingPresentation = $null)
  2445. $hasItems = $items -and $items.Count -gt 0
  2446. $hasBlockMeta = ($null -ne $blockViewMode) -or ($null -ne $blockUserSettingID) -or ($null -ne $blockUserSettingPresentation)
  2447. if (-not $hasItems -and -not $hasBlockMeta) { return }
  2448. X "$indent<dcsset:filter>"
  2449. foreach ($item in $items) {
  2450. if ($item -is [string]) {
  2451. $parsed = Parse-FilterShorthand $item
  2452. $obj = @{ field = $parsed.field; op = $parsed.op }
  2453. if ((-not (Get-DslBool $parsed @('use') $true))) { $obj.use = $false }
  2454. if ($null -ne $parsed.value) { $obj.value = $parsed.value }
  2455. if ($parsed["valueType"]) { $obj.valueType = $parsed["valueType"] }
  2456. if ($parsed.userSettingID) { $obj.userSettingID = $parsed.userSettingID }
  2457. if ($parsed.viewMode) { $obj.viewMode = $parsed.viewMode }
  2458. Emit-FilterItem -item ([pscustomobject]$obj) -indent "$indent`t"
  2459. } else { Emit-FilterItem -item $item -indent "$indent`t" }
  2460. }
  2461. if ($null -ne $blockViewMode) { X "$indent`t<dcsset:viewMode>$(Esc-XmlText "$blockViewMode")</dcsset:viewMode>" }
  2462. if ($null -ne $blockUserSettingID) {
  2463. $uid = if ("$blockUserSettingID" -eq 'auto') { New-Guid-String } else { "$blockUserSettingID" }
  2464. X "$indent`t<dcsset:userSettingID>$(Esc-XmlText $uid)</dcsset:userSettingID>"
  2465. }
  2466. if ($null -ne $blockUserSettingPresentation) { Emit-USPresentation -val $blockUserSettingPresentation -tag "dcsset:userSettingPresentation" -indent "$indent`t" }
  2467. X "$indent</dcsset:filter>"
  2468. }
  2469. function Emit-Order {
  2470. param($items, [string]$indent, [switch]$skipAuto, $blockViewMode = $null, $blockUserSettingID = $null, $blockUserSettingPresentation = $null)
  2471. $hasItems = $items -and $items.Count -gt 0
  2472. $hasBlockMeta = ($null -ne $blockViewMode) -or ($null -ne $blockUserSettingID) -or ($null -ne $blockUserSettingPresentation)
  2473. if (-not $hasItems -and -not $hasBlockMeta) { return }
  2474. X "$indent<dcsset:order>"
  2475. foreach ($item in $items) {
  2476. if ($item -is [string]) {
  2477. if ($item -eq "Auto") { if (-not $skipAuto) { X "$indent`t<dcsset:item xsi:type=`"dcsset:OrderItemAuto`"/>" } }
  2478. else {
  2479. $parts = $item -split '\s+'
  2480. $field = $parts[0]
  2481. $dir = "Asc"
  2482. if ($parts.Count -gt 1 -and $parts[1] -match '^(?i)(desc|убыв)') { $dir = "Desc" }
  2483. elseif ($parts.Count -gt 1 -and $parts[1] -match '^(?i)(asc|возр)') { $dir = "Asc" }
  2484. X "$indent`t<dcsset:item xsi:type=`"dcsset:OrderItemField`">"
  2485. X "$indent`t`t<dcsset:field>$(Esc-XmlText $field)</dcsset:field>"
  2486. X "$indent`t`t<dcsset:orderType>$dir</dcsset:orderType>"
  2487. X "$indent`t</dcsset:item>"
  2488. }
  2489. } else {
  2490. if ($item.field -eq "Auto" -or $item.type -eq "auto") { if (-not $skipAuto) { X "$indent`t<dcsset:item xsi:type=`"dcsset:OrderItemAuto`"/>" }; continue }
  2491. $dir = if ($item.direction) { "$($item.direction)" } else { "Asc" }
  2492. if ($dir -match '^(?i)(desc|убыв)') { $dir = "Desc" } elseif ($dir -match '^(?i)(asc|возр)') { $dir = "Asc" }
  2493. X "$indent`t<dcsset:item xsi:type=`"dcsset:OrderItemField`">"
  2494. if ((-not (Get-DslBool $item @('use') $true))) { X "$indent`t`t<dcsset:use>false</dcsset:use>" }
  2495. X "$indent`t`t<dcsset:field>$(Esc-XmlText "$($item.field)")</dcsset:field>"
  2496. X "$indent`t`t<dcsset:orderType>$dir</dcsset:orderType>"
  2497. if ($item.viewMode) { X "$indent`t`t<dcsset:viewMode>$(Esc-XmlText "$($item.viewMode)")</dcsset:viewMode>" }
  2498. X "$indent`t</dcsset:item>"
  2499. }
  2500. }
  2501. if ($null -ne $blockViewMode) { X "$indent`t<dcsset:viewMode>$(Esc-XmlText "$blockViewMode")</dcsset:viewMode>" }
  2502. if ($null -ne $blockUserSettingID) {
  2503. $uid = if ("$blockUserSettingID" -eq 'auto') { New-Guid-String } else { "$blockUserSettingID" }
  2504. X "$indent`t<dcsset:userSettingID>$(Esc-XmlText $uid)</dcsset:userSettingID>"
  2505. }
  2506. if ($null -ne $blockUserSettingPresentation) { Emit-USPresentation -val $blockUserSettingPresentation -tag "dcsset:userSettingPresentation" -indent "$indent`t" }
  2507. X "$indent</dcsset:order>"
  2508. }
  2509. function Emit-AppearanceValue {
  2510. param([string]$key, $val, [string]$indent)
  2511. X "$indent<dcscor:item xsi:type=`"dcsset:SettingsParameterValue`">"
  2512. function _HasKey { param($o, [string]$k)
  2513. if ($o -is [PSCustomObject]) { return [bool]$o.PSObject.Properties[$k] }
  2514. if ($o -is [System.Collections.IDictionary]) { return $o.Contains($k) }
  2515. return $false
  2516. }
  2517. function _Get { param($o, [string]$k)
  2518. if ($o -is [PSCustomObject]) { return $o.$k }
  2519. if ($o -is [System.Collections.IDictionary]) { return $o[$k] }
  2520. return $null
  2521. }
  2522. $isTopLevelLine = (_HasKey $val '@type') -and ("$(_Get $val '@type')" -eq 'Line')
  2523. $useWrapper = $false
  2524. $innerVal = $val
  2525. $nestedItems = $null
  2526. if ($isTopLevelLine) {
  2527. if ((_HasKey $val 'use') -and -not (ConvertTo-DslBool (_Get $val 'use') 'use' $true)) { $useWrapper = $true }
  2528. if (_HasKey $val 'items') { $nestedItems = (_Get $val 'items') }
  2529. } elseif ((_HasKey $val 'value') -and (($val -is [PSCustomObject]) -or ($val -is [System.Collections.IDictionary]))) {
  2530. $innerVal = (_Get $val 'value')
  2531. if ((_HasKey $val 'use') -and -not (ConvertTo-DslBool (_Get $val 'use') 'use' $true)) { $useWrapper = $true }
  2532. if (_HasKey $val 'items') { $nestedItems = (_Get $val 'items') }
  2533. }
  2534. if ($useWrapper) { X "$indent`t<dcscor:use>false</dcscor:use>" }
  2535. X "$indent`t<dcscor:parameter>$(Esc-XmlText $key)</dcscor:parameter>"
  2536. $isFontDict = $false
  2537. if ($innerVal -is [PSCustomObject]) {
  2538. $tProp = $innerVal.PSObject.Properties['@type']
  2539. if ($tProp -and "$($tProp.Value)" -eq 'Font') { $isFontDict = $true }
  2540. } elseif ($innerVal -is [System.Collections.IDictionary]) {
  2541. if ($innerVal.Contains('@type') -and "$($innerVal['@type'])" -eq 'Font') { $isFontDict = $true }
  2542. }
  2543. $isLineDict = $false
  2544. if (_HasKey $innerVal '@type') { $isLineDict = ("$(_Get $innerVal '@type')" -eq 'Line') }
  2545. $isDict = ($innerVal -is [hashtable]) -or ($innerVal -is [System.Collections.IDictionary]) -or ($innerVal -is [PSCustomObject])
  2546. if ($isLineDict) {
  2547. $lw = if (_HasKey $innerVal 'width') { _Get $innerVal 'width' } else { 0 }
  2548. $lg = if (_HasKey $innerVal 'gap') { if ((_Get $innerVal 'gap')) { 'true' } else { 'false' } } else { 'false' }
  2549. $ls = if (_HasKey $innerVal 'style') { "$(_Get $innerVal 'style')" } else { 'None' }
  2550. X "$indent`t<dcscor:value xsi:type=`"v8ui:Line`" width=`"$lw`" gap=`"$lg`">"
  2551. X "$indent`t`t<v8ui:style xsi:type=`"v8ui:SpreadsheetDocumentCellLineType`">$(Esc-XmlText $ls)</v8ui:style>"
  2552. X "$indent`t</dcscor:value>"
  2553. } elseif ($isFontDict) {
  2554. $attrParts = @()
  2555. foreach ($attrName in @('ref','faceName','height','bold','italic','underline','strikeout','kind','scale')) {
  2556. $av = $null
  2557. if ($innerVal -is [PSCustomObject]) { $ap = $innerVal.PSObject.Properties[$attrName]; if ($ap) { $av = $ap.Value } }
  2558. else { if ($innerVal.Contains($attrName)) { $av = $innerVal[$attrName] } }
  2559. if ($null -ne $av) { $attrParts += "$attrName=`"$(Esc-Xml "$av")`"" }
  2560. }
  2561. X "$indent`t<dcscor:value xsi:type=`"v8ui:Font`" $($attrParts -join ' ')/>"
  2562. } elseif ($isDict -and (_HasKey $innerVal 'field')) {
  2563. # Ссылка на поле (dcscor:Field) — значение параметра оформления = поле компоновки
  2564. X "$indent`t<dcscor:value xsi:type=`"dcscor:Field`">$(Esc-XmlText "$(_Get $innerVal 'field')")</dcscor:value>"
  2565. } elseif ($isDict) {
  2566. # Локализуемый текст параметра оформления: платформа объявляет xsi:type на dcscor:value
  2567. Emit-MLText -tag "dcscor:value" -text $innerVal -indent "$indent`t" -xsiType "v8:LocalStringType"
  2568. } else {
  2569. $actualVal = if ($innerVal -is [bool]) { "$innerVal".ToLower() } else { "$innerVal" }
  2570. $keyTypeMap = @{
  2571. 'Размещение' = 'dcscor:DataCompositionTextPlacementType'
  2572. 'ГоризонтальноеПоложение' = 'v8ui:HorizontalAlign'
  2573. 'ВертикальноеПоложение' = 'v8ui:VerticalAlign'
  2574. 'ОриентацияТекста' = 'xs:decimal'
  2575. 'РасположениеИтогов' = 'dcscor:DataCompositionTotalPlacement'
  2576. 'ТипМакета' = 'dcsset:DataCompositionGroupTemplateType'
  2577. }
  2578. $keyType = $keyTypeMap[$key]
  2579. if ($keyType) { X "$indent`t<dcscor:value xsi:type=`"$keyType`">$(Esc-XmlText $actualVal)</dcscor:value>" }
  2580. elseif ($actualVal -match '^(style|web|win):') { X "$indent`t<dcscor:value xsi:type=`"v8ui:Color`">$(Esc-XmlText $actualVal)</dcscor:value>" }
  2581. elseif ($actualVal -eq "true" -or $actualVal -eq "false") { X "$indent`t<dcscor:value xsi:type=`"xs:boolean`">$actualVal</dcscor:value>" }
  2582. elseif ($key -eq "Текст" -or $key -eq "Заголовок" -or $key -eq "Формат") {
  2583. # Текст/Заголовок/Формат: голая строка = плоский xs:string (так платформа хранит
  2584. # нелокализованный литерал). Локализуемый текст → объект {ru,en} (ветка isDict выше).
  2585. # Пустая строка → самозакрывающийся тег (как у платформы).
  2586. if ($actualVal -eq '') { X "$indent`t<dcscor:value xsi:type=`"xs:string`"/>" }
  2587. else { X "$indent`t<dcscor:value xsi:type=`"xs:string`">$(Esc-XmlText $actualVal)</dcscor:value>" }
  2588. }
  2589. elseif ($actualVal -match '^-?\d+(\.\d+)?$') { X "$indent`t<dcscor:value xsi:type=`"xs:decimal`">$actualVal</dcscor:value>" }
  2590. elseif ($key -eq 'ЦветТекста' -or $key -eq 'ЦветФона' -or $key -eq 'ЦветГраницы') { X "$indent`t<dcscor:value xsi:type=`"v8ui:Color`">$(Esc-XmlText $actualVal)</dcscor:value>" }
  2591. else { X "$indent`t<dcscor:value xsi:type=`"xs:string`">$(Esc-XmlText $actualVal)</dcscor:value>" }
  2592. }
  2593. if ($nestedItems) {
  2594. $niProps = if ($nestedItems -is [PSCustomObject]) { $nestedItems.PSObject.Properties } else { $null }
  2595. if ($niProps) { foreach ($np in $niProps) { Emit-AppearanceValue -key $np.Name -val $np.Value -indent "$indent`t" } }
  2596. elseif ($nestedItems -is [System.Collections.IDictionary]) { foreach ($nk in $nestedItems.Keys) { Emit-AppearanceValue -key $nk -val $nestedItems[$nk] -indent "$indent`t" } }
  2597. }
  2598. X "$indent</dcscor:item>"
  2599. }
  2600. function Emit-ConditionalAppearance {
  2601. param($items, [string]$indent, $blockViewMode = $null, $blockUserSettingID = $null, [string]$wrapTag = 'dcsset:conditionalAppearance', $blockUserSettingPresentation = $null)
  2602. $hasItems = $items -and $items.Count -gt 0
  2603. $hasBlockMeta = ($null -ne $blockViewMode) -or ($null -ne $blockUserSettingID) -or ($null -ne $blockUserSettingPresentation)
  2604. if (-not $hasItems -and -not $hasBlockMeta) { return }
  2605. X "$indent<$wrapTag>"
  2606. foreach ($ca in $items) {
  2607. X "$indent`t<dcsset:item>"
  2608. if ((-not (Get-DslBool $ca @('use') $true))) { X "$indent`t`t<dcsset:use>false</dcsset:use>" }
  2609. if ($ca.selection -and $ca.selection.Count -gt 0) {
  2610. X "$indent`t`t<dcsset:selection>"
  2611. foreach ($sel in $ca.selection) {
  2612. X "$indent`t`t`t<dcsset:item>"
  2613. X "$indent`t`t`t`t<dcsset:field>$(Esc-XmlText "$sel")</dcsset:field>"
  2614. X "$indent`t`t`t</dcsset:item>"
  2615. }
  2616. X "$indent`t`t</dcsset:selection>"
  2617. } else { X "$indent`t`t<dcsset:selection/>" }
  2618. if ($ca.filter -and $ca.filter.Count -gt 0) { Emit-Filter -items $ca.filter -indent "$indent`t`t" }
  2619. else { X "$indent`t`t<dcsset:filter/>" }
  2620. if ($ca.appearance) {
  2621. X "$indent`t`t<dcsset:appearance>"
  2622. foreach ($prop in $ca.appearance.PSObject.Properties) { Emit-AppearanceValue -key $prop.Name -val $prop.Value -indent "$indent`t`t`t" }
  2623. X "$indent`t`t</dcsset:appearance>"
  2624. }
  2625. if ($ca.presentation) {
  2626. if ($ca.presentation -is [hashtable] -or $ca.presentation -is [System.Collections.IDictionary] -or $ca.presentation -is [PSCustomObject]) {
  2627. # Мультиязык → LocalStringType (платформа объявляет тип у локализованного presentation)
  2628. X "$indent`t`t<dcsset:presentation xsi:type=`"v8:LocalStringType`">"
  2629. Emit-MLItems -val $ca.presentation -indent "$indent`t`t`t"
  2630. X "$indent`t`t</dcsset:presentation>"
  2631. }
  2632. else { X "$indent`t`t<dcsset:presentation xsi:type=`"xs:string`">$(Esc-XmlText "$($ca.presentation)")</dcsset:presentation>" }
  2633. }
  2634. if ($ca.viewMode) { X "$indent`t`t<dcsset:viewMode>$(Esc-XmlText "$($ca.viewMode)")</dcsset:viewMode>" }
  2635. if ($ca.userSettingID) {
  2636. $uid = if ("$($ca.userSettingID)" -eq "auto") { New-Guid-String } else { "$($ca.userSettingID)" }
  2637. X "$indent`t`t<dcsset:userSettingID>$(Esc-XmlText $uid)</dcsset:userSettingID>"
  2638. }
  2639. if ($ca.userSettingPresentation) { Emit-USPresentation -val $ca.userSettingPresentation -tag "dcsset:userSettingPresentation" -indent "$indent`t`t" }
  2640. if ($ca.useInDontUse -and $ca.useInDontUse.Count -gt 0) {
  2641. $useInOrder = @('group','hierarchicalGroup','overall','fieldsHeader','header','parameters','filter','resourceFieldsHeader','overallHeader','overallResourceFieldsHeader')
  2642. $set = @{}
  2643. foreach ($n in $ca.useInDontUse) { $set["$n"] = $true }
  2644. foreach ($n in $useInOrder) {
  2645. if ($set.ContainsKey($n)) {
  2646. $tag = "useIn" + ($n.Substring(0,1).ToUpper()) + ($n.Substring(1))
  2647. X "$indent`t`t<dcsset:$tag>DontUse</dcsset:$tag>"
  2648. }
  2649. }
  2650. }
  2651. X "$indent`t</dcsset:item>"
  2652. }
  2653. if ($null -ne $blockViewMode) { X "$indent`t<dcsset:viewMode>$(Esc-XmlText "$blockViewMode")</dcsset:viewMode>" }
  2654. if ($null -ne $blockUserSettingID) {
  2655. $uid = if ("$blockUserSettingID" -eq 'auto') { New-Guid-String } else { "$blockUserSettingID" }
  2656. X "$indent`t<dcsset:userSettingID>$(Esc-XmlText $uid)</dcsset:userSettingID>"
  2657. }
  2658. if ($null -ne $blockUserSettingPresentation) { Emit-USPresentation -val $blockUserSettingPresentation -tag "dcsset:userSettingPresentation" -indent "$indent`t" }
  2659. X "$indent</$wrapTag>"
  2660. }
  2661. function Get-ListGroupingValue {
  2662. param($st)
  2663. foreach ($k in 'grouping','structure','группировка') {
  2664. if ($st.PSObject.Properties[$k] -and $st.$k) { return $st.$k }
  2665. }
  2666. return $null
  2667. }
  2668. function Parse-ListGrouping {
  2669. param($grouping)
  2670. # Шорткат "A > B > C" → массив имён; массив строк/объектов → как есть.
  2671. # Unary comma: иначе PS разворачивает одноэлементный массив при return → строка → индексация даёт char.
  2672. if (-not $grouping) { return ,@() }
  2673. if ($grouping -is [string]) { return ,@($grouping -split '\s*>\s*' | Where-Object { "$_" -ne '' }) }
  2674. return ,@($grouping)
  2675. }
  2676. function Emit-GroupItemField {
  2677. param($level, [string]$indent)
  2678. if ($level -is [string]) {
  2679. $field = $level; $gt = 'Items'; $pat = 'None'; $pab = '0001-01-01T00:00:00'; $pae = '0001-01-01T00:00:00'
  2680. } else {
  2681. $field = "$($level.field)"
  2682. $gt = if ($level.groupType) { "$($level.groupType)" } else { 'Items' }
  2683. $pat = if ($level.periodAdditionType) { "$($level.periodAdditionType)" } else { 'None' }
  2684. $pab = if ($level.periodAdditionBegin) { "$($level.periodAdditionBegin)" } else { '0001-01-01T00:00:00' }
  2685. $pae = if ($level.periodAdditionEnd) { "$($level.periodAdditionEnd)" } else { '0001-01-01T00:00:00' }
  2686. }
  2687. X "$indent<dcsset:item xsi:type=`"dcsset:GroupItemField`">"
  2688. X "$indent`t<dcsset:field>$(Esc-XmlText $field)</dcsset:field>"
  2689. X "$indent`t<dcsset:groupType>$(Esc-XmlText $gt)</dcsset:groupType>"
  2690. X "$indent`t<dcsset:periodAdditionType>$(Esc-XmlText $pat)</dcsset:periodAdditionType>"
  2691. # Авто-детект: ISO-дата → xs:dateTime, иначе путь → dcscor:Field.
  2692. $pabT = if ($pab -match '^\d{4}-\d{2}-\d{2}T') { 'xs:dateTime' } else { 'dcscor:Field' }
  2693. $paeT = if ($pae -match '^\d{4}-\d{2}-\d{2}T') { 'xs:dateTime' } else { 'dcscor:Field' }
  2694. X "$indent`t<dcsset:periodAdditionBegin xsi:type=`"$pabT`">$(Esc-XmlText $pab)</dcsset:periodAdditionBegin>"
  2695. X "$indent`t<dcsset:periodAdditionEnd xsi:type=`"$paeT`">$(Esc-XmlText $pae)</dcsset:periodAdditionEnd>"
  2696. X "$indent</dcsset:item>"
  2697. }
  2698. function Emit-ListGroupingLevels {
  2699. param($levels, [int]$i, [string]$indent)
  2700. X "$indent<dcsset:item xsi:type=`"dcsset:StructureItemGroup`">"
  2701. X "$indent`t<dcsset:groupItems>"
  2702. Emit-GroupItemField $levels[$i] "$indent`t`t"
  2703. X "$indent`t</dcsset:groupItems>"
  2704. if ($i -lt $levels.Count - 1) { Emit-ListGroupingLevels $levels ($i + 1) "$indent`t" }
  2705. X "$indent</dcsset:item>"
  2706. }
  2707. function Emit-ListGrouping {
  2708. param($grouping, [string]$indent)
  2709. $levels = Parse-ListGrouping $grouping
  2710. if ($levels.Count -eq 0) { return }
  2711. Emit-ListGroupingLevels $levels 0 $indent
  2712. }
  2713. function Parse-CalcShorthand {
  2714. param([string]$s)
  2715. $restrict = @()
  2716. foreach ($m in [regex]::Matches($s, '#(noField|noFilter|noCondition|noGroup|noOrder)\b')) { $restrict += $m.Groups[1].Value }
  2717. $s = [regex]::Replace($s, '\s*#(noField|noFilter|noCondition|noGroup|noOrder)\b', '')
  2718. $eq = $s.IndexOf('=')
  2719. if ($eq -gt 0) { $lhs = $s.Substring(0, $eq); $rhs = $s.Substring($eq + 1).Trim() } else { $lhs = $s; $rhs = '' }
  2720. $title = ''
  2721. if ($lhs -match '\[([^\]]+)\]') { $title = $Matches[1]; $lhs = $lhs -replace '\s*\[[^\]]+\]', '' }
  2722. $lhs = $lhs.Trim()
  2723. $type = ''; $dataPath = $lhs
  2724. if ($lhs.Contains(':')) { $parts = $lhs -split ':', 2; $dataPath = $parts[0].Trim(); $type = Resolve-TypeStr ($parts[1].Trim()) }
  2725. return @{ dataPath = $dataPath; expression = $rhs; type = $type; title = $title; restrict = $restrict }
  2726. }
  2727. function Emit-CalcFields {
  2728. param($calcFields, [string]$indent)
  2729. if (-not $calcFields) { return }
  2730. foreach ($cf in $calcFields) {
  2731. $pres = $null; $orderExpr = $null; $restrict = @()
  2732. if ($cf -is [string]) {
  2733. $p = Parse-CalcShorthand $cf
  2734. $dataPath = "$($p.dataPath)"; $expression = "$($p.expression)"; $title = $p.title; $typeStr = "$($p.type)"
  2735. foreach ($r in $p.restrict) { if ($script:calcRestrictMap[$r]) { $restrict += $script:calcRestrictMap[$r] } }
  2736. } else {
  2737. $dataPath = if ($cf.dataPath) { "$($cf.dataPath)" } elseif ($cf.field) { "$($cf.field)" } else { "$($cf.name)" }
  2738. $expression = "$($cf.expression)"
  2739. $title = $cf.title
  2740. $typeStr = if ($cf.valueType) { "$($cf.valueType)" } elseif ($cf.type) { "$($cf.type)" } else { '' }
  2741. $ur = if ($cf.useRestriction) { $cf.useRestriction } elseif ($cf.restrict) { $cf.restrict } else { $null }
  2742. if ($ur -is [System.Management.Automation.PSCustomObject] -or $ur -is [hashtable]) {
  2743. foreach ($k in 'field','condition','group','order') { if (ConvertTo-DslBool $ur.$k $k $false) { $restrict += $k } }
  2744. } elseif ($ur -is [string]) {
  2745. foreach ($tok in ($ur -split '\s+')) { $t = $tok.Trim().TrimStart('#'); if ($t) { $restrict += $(if ($script:calcRestrictMap[$t]) { $script:calcRestrictMap[$t] } else { $t }) } }
  2746. } elseif ($ur) {
  2747. foreach ($r in $ur) { $rr = "$r"; $restrict += $(if ($script:calcRestrictMap[$rr]) { $script:calcRestrictMap[$rr] } else { $rr }) }
  2748. }
  2749. $pres = $cf.presentationExpression
  2750. $orderExpr = $cf.orderExpression
  2751. }
  2752. $ci = "$indent`t"
  2753. X "$indent<CalculatedField>"
  2754. X "$ci<dcssch:dataPath>$(Esc-XmlText $dataPath)</dcssch:dataPath>"
  2755. X "$ci<dcssch:expression>$(Esc-XmlText $expression)</dcssch:expression>"
  2756. if ($title) { Emit-MLText -tag 'dcssch:title' -text $title -indent $ci -xsiType 'v8:LocalStringType' }
  2757. if ($restrict.Count -gt 0) {
  2758. X "$ci<dcssch:useRestriction>"
  2759. foreach ($r in @('field','condition','group','order')) { if ($restrict -contains $r) { X "$ci`t<dcssch:$r>true</dcssch:$r>" } }
  2760. X "$ci</dcssch:useRestriction>"
  2761. }
  2762. if ($pres) { X "$ci<dcssch:presentationExpression>$(Esc-XmlText "$pres")</dcssch:presentationExpression>" }
  2763. if ($orderExpr) {
  2764. $oeList = if ($orderExpr -is [System.Collections.IList]) { $orderExpr } else { @($orderExpr) }
  2765. foreach ($oe in $oeList) {
  2766. if ($oe -is [string]) { $exprV = $oe; $oType = 'Asc'; $auto = 'false' }
  2767. else { $exprV = "$($oe.expression)"; $oType = if ($oe.orderType) { "$($oe.orderType)" } else { 'Asc' }; $auto = if ($oe.autoOrder) { 'true' } else { 'false' } }
  2768. X "$ci<dcssch:orderExpression>"
  2769. X "$ci`t<expression xmlns=`"$($script:dcsCommonNs)`">$(Esc-XmlText $exprV)</expression>"
  2770. X "$ci`t<orderType xmlns=`"$($script:dcsCommonNs)`">$oType</orderType>"
  2771. X "$ci`t<autoOrder xmlns=`"$($script:dcsCommonNs)`">$auto</autoOrder>"
  2772. X "$ci</dcssch:orderExpression>"
  2773. }
  2774. }
  2775. if ($typeStr) { Emit-DLValueType -typeStr $typeStr -indent $ci }
  2776. X "$indent</CalculatedField>"
  2777. }
  2778. }
  2779. function Get-RestrictList {
  2780. param($ur)
  2781. $out = @()
  2782. if (-not $ur) { return ,$out }
  2783. if ($ur -is [System.Management.Automation.PSCustomObject] -or $ur -is [hashtable]) {
  2784. foreach ($k in 'field','condition','group','order') { if (ConvertTo-DslBool $ur.$k $k $false) { $out += $k } }
  2785. } elseif ($ur -is [string]) {
  2786. foreach ($tok in ($ur -split '\s+')) { $t = $tok.Trim().TrimStart('#'); if ($t) { $out += $(if ($script:calcRestrictMap[$t]) { $script:calcRestrictMap[$t] } else { $t }) } }
  2787. } else {
  2788. foreach ($r in $ur) { $rr = "$r"; $out += $(if ($script:calcRestrictMap[$rr]) { $script:calcRestrictMap[$rr] } else { $rr }) }
  2789. }
  2790. return ,$out
  2791. }
  2792. function Emit-RestrictBlock {
  2793. param([string]$tag, $ur, [string]$indent)
  2794. $r = Get-RestrictList $ur
  2795. if ($r.Count -eq 0) { return }
  2796. X "$indent<dcssch:$tag>"
  2797. foreach ($k in @('field','condition','group','order')) { if ($r -contains $k) { X "$indent`t<dcssch:$k>true</dcssch:$k>" } }
  2798. X "$indent</dcssch:$tag>"
  2799. }
  2800. function Resolve-TypeStr {
  2801. param([string]$typeStr)
  2802. if (-not $typeStr) { return $typeStr }
  2803. # Прощающий ввод: ведущий префикс приходит копипастой из выгрузки. Без срезания он ломает
  2804. # поиск в словаре — русское имя типа остаётся непереведённым, и платформа отвечает
  2805. # «Неизвестное имя типа». cfg: снимаем всегда — он однозначно означает текущую конфигурацию.
  2806. # Сгенерированный dNpM: (в корпусе на этом URI встречаются d4p1, d5p1, d6p1 — имя префикса
  2807. # платформа выдаёт по порядку объявления) снимаем ТОЛЬКО у ссылочных типов, с точкой:
  2808. # сам по себе префикс многозначен — в формах d5p1:Chart, d5p1:TextDocument,
  2809. # d5p1:GeographicalSchema адресуют чужие пространства имён, и там он часть значения.
  2810. if ($typeStr.StartsWith('cfg:')) {
  2811. $typeStr = $typeStr.Substring(4)
  2812. } elseif ($typeStr.Contains('.') -and $typeStr -match '^d\d+p\d+:') {
  2813. $typeStr = $typeStr.Substring($typeStr.IndexOf(':') + 1)
  2814. }
  2815. # Хвосты, которые дописывает вывод meta-info к множествам типов: суффикс обобщённого метатипа
  2816. # и счётчик состава. Копипаста строки оттуда — обычный путь, поэтому хвост снимаем молча.
  2817. # Срезаем ТОЛЬКО эти известные формы: круглые скобки заняты параметризованными типами
  2818. # (Число(15,2)), слепой срез скобок сломал бы их.
  2819. $typeStr = ($typeStr -replace '\s*\((?:все|all)\)\s*$', '').Trim()
  2820. $typeStr = ($typeStr -replace '\s*[—-]\s*(?:типов|types):\s*\d+\s*$', '').Trim()
  2821. $typeStr = ($typeStr -replace '\s*\((?:типов|types):\s*\d+\)\s*$', '').Trim()
  2822. # Параметризованные типы: Number(15,2), Строка(100)
  2823. if ($typeStr -match '^([^(]+)\((.+)\)$') {
  2824. $baseName = $Matches[1].Trim()
  2825. $params = $Matches[2]
  2826. $resolved = $script:typeSynonyms[$baseName.ToLower()]
  2827. if ($resolved) { return "$resolved($params)" }
  2828. return $typeStr
  2829. }
  2830. # Ссылочные типы: СправочникСсылка.Организации → CatalogRef.Организации
  2831. if ($typeStr.Contains('.')) {
  2832. $dotIdx = $typeStr.IndexOf('.')
  2833. $prefix = $typeStr.Substring(0, $dotIdx)
  2834. $suffix = $typeStr.Substring($dotIdx) # includes the dot
  2835. $resolved = $script:typeSynonyms[$prefix.ToLower()]
  2836. if ($resolved) { return "$resolved$suffix" }
  2837. return $typeStr
  2838. }
  2839. # Простое имя
  2840. $resolved = $script:typeSynonyms[$typeStr.ToLower()]
  2841. if ($resolved) { return $resolved }
  2842. return $typeStr
  2843. }
  2844. function Emit-Type {
  2845. # $tag/$tagAttrs — обёртка (по умолчанию <Type>); для уточнения типа значений ValueList
  2846. # вызывается с tag="Settings", tagAttrs=' xsi:type="v8:TypeDescription"'.
  2847. param($typeStr, [string]$indent, [string]$tag = "Type", [string]$tagAttrs = "")
  2848. if (-not $typeStr) {
  2849. X "$indent<$tag$tagAttrs/>"
  2850. return
  2851. }
  2852. $typeString = "$typeStr"
  2853. # Composite type: "Type1 | Type2" or "Type1 + Type2"
  2854. $parts = $typeString -split '\s*[|+]\s*'
  2855. X "$indent<$tag$tagAttrs>"
  2856. foreach ($part in $parts) {
  2857. $part = $part.Trim()
  2858. Emit-SingleType -typeStr $part -indent "$indent`t"
  2859. }
  2860. X "$indent</$tag>"
  2861. }
  2862. # Разбор примитивного типа DSL: Number / String / Date / DateTime / Time — с синонимами
  2863. # (decimal, numeric, Число, Строка, Дата …), в любом регистре, с пробелами в скобках.
  2864. # Тело общее у всех навыков-компиляторов (семья в check-inline-drift); умолчание для голого типа
  2865. # зависит от места (хранимый реквизит — 10,0 и 10, СКД — без ограничения) и приходит аргументами.
  2866. # Возврат: $null — не примитив (ссылки, Boolean, …); @{ Error } — база примитива узнана, а
  2867. # параметры нет (вызывающий сообщает ошибку своим способом); иначе описание квалификаторов.
  2868. function Parse-PrimitiveType {
  2869. param([string]$typeStr, [int]$defDigits, [int]$defFraction, [int]$defLength)
  2870. if ($typeStr -notmatch '^\s*([^\s(]+)\s*(\(.*)?$') { return $null }
  2871. $rest = if ($Matches.ContainsKey(2)) { $Matches[2] } else { '' }
  2872. $kind = switch -exact ($Matches[1].ToLowerInvariant()) {
  2873. 'number' { 'Number' } 'decimal' { 'Number' } 'numeric' { 'Number' } 'число' { 'Number' }
  2874. 'string' { 'String' } 'строка' { 'String' }
  2875. 'date' { 'Date' } 'дата' { 'Date' } 'datetime' { 'DateTime' } 'датавремя' { 'DateTime' }
  2876. 'time' { 'Time' } 'время' { 'Time' }
  2877. default { $null }
  2878. }
  2879. if (-not $kind) { return $null }
  2880. $bad = @{ Error = ("Invalid type '$typeStr'. Expected Number, Number(D), Number(D,F), Number(D,F,nonneg), " +
  2881. "String, String(N), String(N,fixed), Date, DateTime, Time") }
  2882. $parts = @()
  2883. if ($rest) {
  2884. if ($rest -notmatch '^\((.*)\)\s*$') { return $bad }
  2885. $parts = @($Matches[1] -split ',' | ForEach-Object { $_.Trim().ToLowerInvariant() })
  2886. }
  2887. if ($kind -eq 'Number') {
  2888. $sign = 'Any'
  2889. if ($parts.Count -gt 0 -and ($parts[-1] -eq 'nonneg' -or $parts[-1] -eq 'any')) {
  2890. if ($parts[-1] -eq 'nonneg') { $sign = 'Nonnegative' }
  2891. $parts = @(if ($parts.Count -gt 1) { $parts[0..($parts.Count - 2)] })
  2892. }
  2893. if ($parts.Count -gt 2) { return $bad }
  2894. foreach ($p in $parts) { if ($p -notmatch '^[0-9]{1,9}$') { return $bad } }
  2895. $d = if ($parts.Count -ge 1) { [int]$parts[0] } else { $defDigits }
  2896. $f = if ($parts.Count -ge 2) { [int]$parts[1] } elseif ($parts.Count -eq 1) { 0 } else { $defFraction }
  2897. # Дробная часть у числа без ограничения (0,F) платформа молча обнуляет — это ошибка ввода
  2898. if ($d -gt 38 -or $f -gt $d) { return $bad }
  2899. return @{ Kind = 'Number'; Digits = $d; Fraction = $f; Sign = $sign }
  2900. }
  2901. if ($kind -eq 'String') {
  2902. $allowed = 'Variable'
  2903. if ($parts.Count -eq 2) {
  2904. if ($parts[1] -eq 'fixed' -or $parts[1] -eq 'fix') { $allowed = 'Fixed' }
  2905. elseif ($parts[1] -ne 'variable') { return $bad }
  2906. }
  2907. if ($parts.Count -gt 2 -or ($parts.Count -ge 1 -and $parts[0] -notmatch '^[0-9]{1,9}$')) { return $bad }
  2908. $len = if ($parts.Count -ge 1) { [int]$parts[0] } else { $defLength }
  2909. # Фиксированную длину у неограниченной строки платформа молча снимает — это ошибка ввода
  2910. if ($allowed -eq 'Fixed' -and $len -eq 0) { return $bad }
  2911. return @{ Kind = 'String'; Length = $len; Allowed = $allowed }
  2912. }
  2913. if ($parts.Count -gt 0) { return $bad }
  2914. return @{ Kind = 'Date'; Fractions = $kind }
  2915. }
  2916. function Emit-SingleType {
  2917. param([string]$typeStr, [string]$indent)
  2918. $typeStr = Resolve-TypeStr $typeStr
  2919. # TypeId — тип, заданный глобальным стабильным GUID (<v8:TypeId>, не <v8:Type>). Платформа так
  2920. # сериализует типы, чьё имя в этом контексте недоступно (определяемые/характеристики). GUID
  2921. # глобально стабилен → эмитим verbatim (как роль-по-GUID). Маркер декомпилятора: 'typeid:GUID'.
  2922. if ($typeStr -match '^typeid:([0-9a-fA-F-]{36})$') {
  2923. X "$indent<v8:TypeId>$($Matches[1])</v8:TypeId>"
  2924. return
  2925. }
  2926. # boolean
  2927. if ($typeStr -eq "boolean") {
  2928. X "$indent<v8:Type>xs:boolean</v8:Type>"
  2929. return
  2930. }
  2931. # Примитивы: string / decimal / date / dateTime / time. Голое число реквизита формы — 10,0,
  2932. # голая строка — неограниченная.
  2933. $prim = Parse-PrimitiveType $typeStr 10 0 0
  2934. if ($prim) {
  2935. if ($prim.Error) { throw $prim.Error }
  2936. if ($prim.Kind -eq 'String') {
  2937. X "$indent<v8:Type>xs:string</v8:Type>"
  2938. X "$indent<v8:StringQualifiers>"
  2939. X "$indent`t<v8:Length>$($prim.Length)</v8:Length>"
  2940. X "$indent`t<v8:AllowedLength>$($prim.Allowed)</v8:AllowedLength>"
  2941. X "$indent</v8:StringQualifiers>"
  2942. } elseif ($prim.Kind -eq 'Number') {
  2943. X "$indent<v8:Type>xs:decimal</v8:Type>"
  2944. X "$indent<v8:NumberQualifiers>"
  2945. X "$indent`t<v8:Digits>$($prim.Digits)</v8:Digits>"
  2946. X "$indent`t<v8:FractionDigits>$($prim.Fraction)</v8:FractionDigits>"
  2947. X "$indent`t<v8:AllowedSign>$($prim.Sign)</v8:AllowedSign>"
  2948. X "$indent</v8:NumberQualifiers>"
  2949. } else {
  2950. X "$indent<v8:Type>xs:dateTime</v8:Type>"
  2951. X "$indent<v8:DateQualifiers>"
  2952. X "$indent`t<v8:DateFractions>$($prim.Fractions)</v8:DateFractions>"
  2953. X "$indent</v8:DateQualifiers>"
  2954. }
  2955. return
  2956. }
  2957. # ValueTable, ValueTree, ValueList, etc.
  2958. $v8Types = @{
  2959. "ValueTable" = "v8:ValueTable"
  2960. "ValueTree" = "v8:ValueTree"
  2961. "ValueList" = "v8:ValueListType"
  2962. "TypeDescription" = "v8:TypeDescription"
  2963. "Universal" = "v8:Universal"
  2964. "FixedArray" = "v8:FixedArray"
  2965. "FixedStructure" = "v8:FixedStructure"
  2966. }
  2967. if ($v8Types.ContainsKey($typeStr)) {
  2968. X "$indent<v8:Type>$($v8Types[$typeStr])</v8:Type>"
  2969. return
  2970. }
  2971. # UI types
  2972. $uiTypes = @{
  2973. "FormattedString" = "v8ui:FormattedString"
  2974. "Picture" = "v8ui:Picture"
  2975. "Color" = "v8ui:Color"
  2976. "Font" = "v8ui:Font"
  2977. }
  2978. if ($uiTypes.ContainsKey($typeStr)) {
  2979. X "$indent<v8:Type>$($uiTypes[$typeStr])</v8:Type>"
  2980. return
  2981. }
  2982. # DCS types
  2983. if ($typeStr -match '^DataComposition') {
  2984. $dcsMap = @{
  2985. "DataCompositionSettings" = "dcsset:DataCompositionSettings"
  2986. "DataCompositionSchema" = "dcssch:DataCompositionSchema"
  2987. "DataCompositionComparisonType" = "dcscor:DataCompositionComparisonType"
  2988. }
  2989. if ($dcsMap.ContainsKey($typeStr)) {
  2990. X "$indent<v8:Type>$($dcsMap[$typeStr])</v8:Type>"
  2991. return
  2992. }
  2993. }
  2994. # Голые конфигурационные типы (cfg: без .Имя): дин-список, набор констант, общий объект отчёта.
  2995. # Корпус (acc+erp 8.3.24): DynamicList 5205, ConstantsSet 103, ReportObject 10. (Дотированные формы
  2996. # ConstantsSet.X / ReportObject.X ловит общий cfg:-regex ниже.)
  2997. if ($typeStr -in @("DynamicList","ConstantsSet","ReportObject")) {
  2998. X "$indent<v8:Type>cfg:$typeStr</v8:Type>"
  2999. return
  3000. }
  3001. # TypeSet (набор типов) → <v8:TypeSet>: определяемый тип / характеристика (именованные)
  3002. # + «любая ссылка вида» (голый ref-вид без .Имя). Развязка с обычным типом — по наличию точки.
  3003. if ($typeStr -match '^(DefinedType|Characteristic)\.') {
  3004. X "$indent<v8:TypeSet>cfg:$typeStr</v8:TypeSet>"
  3005. return
  3006. }
  3007. if ($typeStr -match '^(AnyRef|AnyIBRef|CatalogRef|DocumentRef|EnumRef|ExchangePlanRef|TaskRef|BusinessProcessRef|ChartOfAccountsRef|ChartOfCharacteristicTypesRef|ChartOfCalculationTypesRef)$') {
  3008. X "$indent<v8:TypeSet>cfg:$typeStr</v8:TypeSet>"
  3009. return
  3010. }
  3011. # cfg: references (CatalogRef.XXX, DocumentObject.XXX, etc.)
  3012. 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)\.') {
  3013. X "$indent<v8:Type>cfg:$typeStr</v8:Type>"
  3014. return
  3015. }
  3016. # Спец-типы платформы с собственным namespace (объявляется ЛОКАЛЬНО на <v8:Type>).
  3017. # Префикс d5p1 неоднозначен (5 разных URI), поэтому маппинг по полному значению типа.
  3018. # К таким типам привязаны спец-поля: mxl→SpreadSheetDocumentField, fd→FormattedDocumentField,
  3019. # d5p1:TextDocument→TextDocumentField, pdfdoc→PDF, pl→Planner, chart/geo/graphscheme/data-analysis.
  3020. $specialTypeNs = @{
  3021. "mxl:SpreadsheetDocument" = "http://v8.1c.ru/8.2/data/spreadsheet"
  3022. "fd:FormattedDocument" = "http://v8.1c.ru/8.2/data/formatted-document"
  3023. "d5p1:TextDocument" = "http://v8.1c.ru/8.1/data/txtedt"
  3024. "d5p1:Chart" = "http://v8.1c.ru/8.2/data/chart"
  3025. "d5p1:GanttChart" = "http://v8.1c.ru/8.2/data/chart"
  3026. "d5p1:Dendrogram" = "http://v8.1c.ru/8.2/data/chart"
  3027. "d5p1:FlowchartContextType" = "http://v8.1c.ru/8.2/data/graphscheme"
  3028. "d5p1:DataAnalysisTimeIntervalUnitType" = "http://v8.1c.ru/8.2/data/data-analysis"
  3029. "d5p1:GeographicalSchema" = "http://v8.1c.ru/8.2/data/geo"
  3030. "pdfdoc:PDFDocument" = "http://v8.1c.ru/8.3/data/pdf"
  3031. "pl:Planner" = "http://v8.1c.ru/8.3/data/planner"
  3032. }
  3033. if ($specialTypeNs.ContainsKey($typeStr)) {
  3034. $pref = $typeStr.Substring(0, $typeStr.IndexOf(':'))
  3035. X "$indent<v8:Type xmlns:$pref=`"$($specialTypeNs[$typeStr])`">$typeStr</v8:Type>"
  3036. return
  3037. }
  3038. # Fallback with validation
  3039. if ($script:knownInvalidTypes.ContainsKey($typeStr)) {
  3040. throw "Invalid form attribute type '$typeStr': $($script:knownInvalidTypes[$typeStr])"
  3041. }
  3042. # Платформенный тип с префиксом (v8:/v8ui:/xs:/dcs*:) — эмитим verbatim (напр. v8:UUID, v8:StandardPeriod).
  3043. if ($typeStr -match '^(v8|v8ui|xs|ent|style|sys|web|win|dcs\w*):') {
  3044. X "$indent<v8:Type>$typeStr</v8:Type>"
  3045. } elseif ($typeStr.Contains('.')) {
  3046. X "$indent<v8:Type>cfg:$typeStr</v8:Type>"
  3047. } else {
  3048. Write-Warning "Unrecognized bare type '$typeStr' — will be emitted without namespace prefix"
  3049. X "$indent<v8:Type>$typeStr</v8:Type>"
  3050. }
  3051. }
  3052. function Get-HandlerName {
  3053. param([string]$elementName, [string]$eventName, [string]$xmlTag, [string]$callType = '')
  3054. $entry = Get-EventEntry $xmlTag $eventName
  3055. $name = if ($entry -and $entry[0]) { "$elementName$($entry[0])" } else { "$elementName$eventName" }
  3056. # Обработчик с видом вызова (расширение) — как называет Конфигуратор: префикс расширения + имя + вид вызова.
  3057. # Без этого имя совпало бы с процедурой исходной формы.
  3058. if ($callType) { $name = "$($script:extNamePrefix)$name$(@{ Before = 'Перед'; After = 'После'; Override = 'Вместо' }[$callType])" }
  3059. return $name
  3060. }
  3061. function Get-ElementName {
  3062. param($el, [string]$typeKey)
  3063. if ($el.name) { return "$($el.name)" }
  3064. return "$($el.$typeKey)"
  3065. }
  3066. function Resolve-EventName([string]$xmlTag, [string]$name, [string]$ctx) {
  3067. if (-not $name) {
  3068. Write-Error "${ctx}: event name is empty — a list item object needs `"event`": { `"event`": `"OnChange`", `"handler`": `"Name`" }"
  3069. exit 1
  3070. }
  3071. if ($xmlTag -and $script:eventCatalog.ContainsKey($xmlTag)) {
  3072. foreach ($k in $script:eventCatalog[$xmlTag].Keys) { if ($k -eq $name) { return $k } }
  3073. }
  3074. if ($name -cmatch '^[A-Z]') { return $name }
  3075. $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' }
  3076. Write-Error "${ctx}: '$name' is not an event name — $hint"
  3077. exit 1
  3078. }
  3079. function Get-EventPairs {
  3080. param($el, [string]$elementName, [string]$xmlTag)
  3081. $pairs = New-Object System.Collections.ArrayList
  3082. $ctx = if ($xmlTag -eq 'Form') { 'Form events' } else { "Element '$elementName' events" }
  3083. $list = $null
  3084. if ($el.events -is [array]) { $list = @($el.events) }
  3085. elseif ($el.events) {
  3086. if (-not ($el.events -is [System.Management.Automation.PSCustomObject])) {
  3087. Write-Error "${ctx}: events — an object { `"OnChange`": `"Handler`" } or a list of events [`"OnChange`"]"
  3088. exit 1
  3089. }
  3090. foreach ($p in $el.events.PSObject.Properties) {
  3091. $evName = Resolve-EventName $xmlTag $p.Name $ctx
  3092. # Значение — имя обработчика; объект { handler, callType } или массив таких объектов
  3093. # (в расширении на одно событие вешают и Before, и After)
  3094. $vals = @($p.Value) # массив — как есть, одно значение (в т.ч. null) — один элемент
  3095. if ($vals.Count -eq 0) { Write-Error "${ctx}: '$evName' — empty list, specify the handler name"; exit 1 }
  3096. foreach ($v in $vals) {
  3097. $h = ""; $ct = ""
  3098. if ($v -is [System.Management.Automation.PSCustomObject]) { $h = "$($v.handler)"; $ct = Normalize-CallType "$($v.callType)" $elementName $evName } else { $h = "$v" }
  3099. if ([string]::IsNullOrEmpty($h)) {
  3100. 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`"]"
  3101. exit 1
  3102. }
  3103. [void]$pairs.Add([pscustomobject]@{ name = $evName; handler = $h; callType = $ct })
  3104. }
  3105. }
  3106. } elseif ($el.on) { $list = @($el.on) }
  3107. if ($null -ne $list) {
  3108. foreach ($evt in $list) {
  3109. if ($evt -is [System.Management.Automation.PSCustomObject]) {
  3110. $evtName = Resolve-EventName $xmlTag "$($evt.event)" $ctx; $h = "$($evt.handler)"; $ct = Normalize-CallType "$($evt.callType)" $elementName $evtName
  3111. } else {
  3112. $evtName = Resolve-EventName $xmlTag "$evt" $ctx; $h = ""; $ct = ""
  3113. }
  3114. 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 } }
  3115. [void]$pairs.Add([pscustomobject]@{ name = $evtName; handler = $h; callType = $ct })
  3116. }
  3117. }
  3118. return $pairs
  3119. }
  3120. # Пары событий в порядке, в котором их пишет платформа (Get-EventRank); равные — в порядке ввода.
  3121. # Только для вывода <Events>: заготовки в модуле идут в порядке ввода.
  3122. function Sort-EventPairs($pairs, [string]$xmlTag) {
  3123. $i = 0
  3124. $keyed = @(foreach ($pr in @($pairs)) { [pscustomobject]@{ k = (Get-EventRank $xmlTag $pr.name $pr.callType); i = $i++; p = $pr } })
  3125. return @($keyed | Sort-Object k, i | ForEach-Object { $_.p })
  3126. }
  3127. function Normalize-CallType([string]$raw, [string]$elementName, [string]$eventName) {
  3128. if ([string]::IsNullOrEmpty($raw)) { return '' }
  3129. foreach ($v in @('Before','After','Override')) { if ($raw -eq $v) { return $v } }
  3130. Write-Error "Element '$elementName', event '$eventName': callType '$raw' — expected Before, After or Override"
  3131. exit 1
  3132. }
  3133. function Emit-Events {
  3134. param($el, [string]$elementName, [string]$indent, [string]$xmlTag, [string]$source = '')
  3135. $pairs = Get-EventPairs -el $el -elementName $elementName -xmlTag $xmlTag
  3136. if ($pairs.Count -eq 0) { return }
  3137. Test-EventPairs -pairs $pairs -xmlTag $xmlTag -elementName $elementName -source $source
  3138. $table = if ($xmlTag -eq 'Table') { $elementName } else { $script:handlerTable }
  3139. foreach ($pr in $pairs) { Register-Handler $pr.handler 'element' $xmlTag $pr.name $table }
  3140. X "$indent<Events>"
  3141. foreach ($pr in (Sort-EventPairs $pairs $xmlTag)) {
  3142. $ctAttr = if ($pr.callType) { " callType=`"$($pr.callType)`"" } else { "" }
  3143. X "$indent`t<Event name=`"$($pr.name)`"$ctAttr>$($pr.handler)</Event>"
  3144. }
  3145. X "$indent</Events>"
  3146. }
  3147. function Test-CompanionStructured {
  3148. param($content)
  3149. if (-not (($content -is [System.Collections.IDictionary]) -or ($content -is [System.Management.Automation.PSCustomObject]))) { return $false }
  3150. foreach ($k in $script:companionStructKeys) {
  3151. $present = if ($content -is [System.Collections.IDictionary]) { $content.Contains($k) } else { [bool]$content.PSObject.Properties[$k] }
  3152. if ($present) { return $true }
  3153. }
  3154. return $false
  3155. }
  3156. function Emit-CompanionTitle {
  3157. param($content, [string]$indent)
  3158. $r = Resolve-MLFormatted $content
  3159. $fmt = if ($r.formatted) { 'true' } else { 'false' }
  3160. X "$indent<Title formatted=`"$fmt`">"
  3161. Emit-MLItems -val $r.text -indent "$indent`t"
  3162. X "$indent</Title>"
  3163. }
  3164. function DI-Attr {
  3165. param($el)
  3166. if ($null -ne $el -and $el.displayImportance) { return " DisplayImportance=`"$(Esc-Xml "$($el.displayImportance)")`"" }
  3167. return ""
  3168. }
  3169. function Emit-Companion {
  3170. param([string]$tag, [string]$name, [string]$indent, $content = $null)
  3171. $id = New-Id
  3172. $hasContent = $null -ne $content -and -not ($content -is [string] -and "$content" -eq '')
  3173. if (-not $hasContent) {
  3174. X "$indent<$tag name=`"$name`" id=`"$id`"/>"
  3175. return
  3176. }
  3177. $inner = "$indent`t"
  3178. # DI-Attr берём от СОБСТВЕННОГО объекта компаньона ($content), НЕ от ambient $el родителя
  3179. # (PowerShell dynamic scope — иначе companion наследует DisplayImportance владельца: баг).
  3180. X "$indent<$tag name=`"$name`" id=`"$id`"$(DI-Attr $content)>"
  3181. if (Test-CompanionStructured $content) {
  3182. # структурированная форма (own-content). Порядок как у платформы: own-content (флаги/hyperlink/
  3183. # layout/оформление) ПЕРЕД Title (в корпусе layout-first 582 vs 10).
  3184. $txtPresent = if ($content -is [System.Collections.IDictionary]) { $content.Contains('text') } else { [bool]$content.PSObject.Properties['text'] }
  3185. Emit-CommonFlags -el $content -indent $inner
  3186. if ((Get-DslBool $content @('hyperlink') $false)) { X "$inner<Hyperlink>true</Hyperlink>" }
  3187. Emit-Layout -el $content -indent $inner
  3188. Emit-Appearance -el $content -indent $inner -profile 'decoration'
  3189. if ($txtPresent) { Emit-CompanionTitle -content $content -indent $inner }
  3190. # ToolTip компаньона (подсказка самой расширенной подсказки) — после Title (порядок схемы LabelDecoration)
  3191. if ($content.tooltip) { Emit-MLText -tag "ToolTip" -text $content.tooltip -indent $inner }
  3192. # События компаньона (ExtendedTooltip = LabelDecoration: напр. URLProcessing у hyperlink-подсказки)
  3193. Emit-Events -el $content -elementName $name -indent $inner -xmlTag 'ExtendedTooltip'
  3194. } else {
  3195. Emit-CompanionTitle -content $content -indent $inner
  3196. }
  3197. X "$indent</$tag>"
  3198. }
  3199. function Emit-CompanionPanel {
  3200. param([string]$tag, [string]$name, [string]$indent, $panel)
  3201. $id = New-Id
  3202. $autofill = $null
  3203. $children = $null
  3204. $halign = $null
  3205. if ($panel -is [array]) {
  3206. $children = $panel
  3207. } elseif ($null -ne $panel) {
  3208. if ($null -ne $panel.PSObject.Properties['autofill'] -and $null -ne $panel.autofill) { $autofill = (ConvertTo-DslBool $panel.autofill 'autofill' $false) }
  3209. if ($null -ne $panel.PSObject.Properties['horizontalAlign'] -and "$($panel.horizontalAlign)" -ne '') { $halign = "$($panel.horizontalAlign)" }
  3210. $children = $panel.children
  3211. }
  3212. $hasChildren = $children -and @($children).Count -gt 0
  3213. # Платформа пишет <Autofill> только при false; true = дефолт (тег опускается).
  3214. $emitAfFalse = ($autofill -eq $false)
  3215. if (-not $emitAfFalse -and -not $hasChildren -and -not $halign) {
  3216. X "$indent<$tag name=`"$name`" id=`"$id`"/>"
  3217. return
  3218. }
  3219. X "$indent<$tag name=`"$name`" id=`"$id`"$(DI-Attr $panel)>"
  3220. if ($halign) { X "$indent`t<HorizontalAlign>$halign</HorizontalAlign>" }
  3221. if ($emitAfFalse) { X "$indent`t<Autofill>false</Autofill>" }
  3222. if ($hasChildren) {
  3223. X "$indent`t<ChildItems>"
  3224. foreach ($c in @($children)) { Emit-Element -el $c -indent "$indent`t`t" -inCmdBar $true }
  3225. X "$indent`t</ChildItems>"
  3226. }
  3227. X "$indent</$tag>"
  3228. }
  3229. function Get-HLocation {
  3230. param($el)
  3231. $v = if ($el -and $el.PSObject.Properties['horizontalLocation']) { $el.horizontalLocation } else { $null }
  3232. if (-not $v) { return $null }
  3233. switch -Regex ("$v".ToLower()) {
  3234. '^(auto|авто)$' { return $null } # дефолт — не эмитим
  3235. '^(left|слева|лево)$' { return 'Left' }
  3236. '^(right|справа|право)$' { return 'Right' }
  3237. '^(center|центр|по центру)$' { return 'Center' }
  3238. default { return "$v" }
  3239. }
  3240. }
  3241. function Emit-AdditionBody {
  3242. param($props, [string]$source, [string]$srcType, [string]$addName, [string]$indent)
  3243. $inner = "$indent`t"
  3244. X "$inner<AdditionSource>"
  3245. X "$inner`t<Item>$source</Item>"
  3246. X "$inner`t<Type>$srcType</Type>"
  3247. X "$inner</AdditionSource>"
  3248. if ($props) {
  3249. if ($props.PSObject.Properties['title'] -and $props.title) { Emit-MLText -tag "Title" -text $props.title -indent $inner }
  3250. Emit-CommonFlags -el $props -indent $inner
  3251. if ($props.tooltip) { Emit-MLText -tag "ToolTip" -text $props.tooltip -indent $inner }
  3252. if ($props.tooltipRepresentation) { X "$inner<ToolTipRepresentation>$($props.tooltipRepresentation)</ToolTipRepresentation>" }
  3253. $hl = Get-HLocation $props; if ($hl) { X "$inner<HorizontalLocation>$hl</HorizontalLocation>" }
  3254. Emit-Layout -el $props -indent $inner
  3255. Emit-Appearance -el $props -indent $inner -profile 'field'
  3256. }
  3257. Emit-Companion -tag "ContextMenu" -name "${addName}КонтекстноеМеню" -indent $inner
  3258. Emit-Companion -tag "ExtendedTooltip" -name "${addName}РасширеннаяПодсказка" -indent $inner
  3259. }
  3260. function Emit-Addition {
  3261. param($el, [string]$name, [int]$id, [string]$typeKey, [string]$indent)
  3262. $map = $script:additionTypeMap[$typeKey]
  3263. $source = if ($el.source) { "$($el.source)" } elseif ($script:currentTableName) { $script:currentTableName } else { '' }
  3264. X "$indent<$($map.Tag) name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  3265. Emit-AdditionBody -props $el -source $source -srcType $map.Type -addName $name -indent $indent
  3266. X "$indent</$($map.Tag)>"
  3267. }
  3268. function Emit-TableAddition {
  3269. param([string]$typeKey, [string]$tableName, [string]$indent, $override = $null)
  3270. $map = $script:additionTypeMap[$typeKey]
  3271. $addName = "$tableName$($map.Suffix)"
  3272. $id = New-Id
  3273. X "$indent<$($map.Tag) name=`"$addName`" id=`"$id`">"
  3274. Emit-AdditionBody -props $override -source $tableName -srcType $map.Type -addName $addName -indent $indent
  3275. X "$indent</$($map.Tag)>"
  3276. }
  3277. function Get-AdditionOverride {
  3278. param($additions, [string]$typeKey)
  3279. if ($null -eq $additions) { return $null }
  3280. foreach ($k in @($typeKey) + $script:additionKeySynonyms[$typeKey]) {
  3281. $p = $additions.PSObject.Properties[$k]
  3282. if ($p) { return $p.Value }
  3283. }
  3284. return $null
  3285. }
  3286. function Normalize-ElementTypeSynonyms {
  3287. param($el)
  3288. foreach ($pair in $script:elementTypeSynonyms.GetEnumerator()) {
  3289. if ($null -ne $el.PSObject.Properties[$pair.Key] -and $null -eq $el.PSObject.Properties[$pair.Value]) {
  3290. if ($script:elementTypeStrOnlyKeys -contains $pair.Key -and -not ($el.($pair.Key) -is [string])) { continue }
  3291. $val = $el.($pair.Key)
  3292. $el.PSObject.Properties.Remove($pair.Key) | Out-Null
  3293. $el | Add-Member -NotePropertyName $pair.Value -NotePropertyValue $val -Force
  3294. }
  3295. }
  3296. }
  3297. function Normalize-EnumValue {
  3298. param([string]$propName, [string]$value)
  3299. $valid = $script:validEnumValues["$script:objType.$propName"]
  3300. if (-not $valid) { $valid = $script:validEnumValues[$propName] }
  3301. # 1. Check alias dictionary — silent auto-correct. Словарь общий для всех свойств: у свойства со
  3302. # списком алиас берётся, только если его результат в списке (иначе «None» дало бы Nonperiodical везде)
  3303. if ($script:enumValueAliases.ContainsKey($value)) {
  3304. $aliased = $script:enumValueAliases[$value]
  3305. if (-not $valid -or $valid -ccontains $aliased) { return $aliased }
  3306. }
  3307. # 2. Case-insensitive match against valid values — silent. Список вида объекта — раньше общего.
  3308. if ($valid) {
  3309. foreach ($v in $valid) {
  3310. if ($v -ieq $value) { return $v }
  3311. }
  3312. # 3. Known property, unknown value — error with hint
  3313. Write-Error "Invalid value '$value' for property '$propName'. Valid values: $($valid -join ', ')"
  3314. exit 1
  3315. }
  3316. # 4. Unknown property — pass-through (no validation data)
  3317. return $value
  3318. }
  3319. function Resolve-EnumInputSynonym([string]$type, [string]$tag, [string]$value) {
  3320. $syn = $script:enumInputSynonyms["$type.$tag"]
  3321. if ($syn) { foreach ($k in $syn.Keys) { if ($k -ieq $value) { return $syn[$k] } } }
  3322. return $value
  3323. }
  3324. function Normalize-EnumTags([string]$text, [string]$rootType = '', [bool]$keepDefaults = $false) {
  3325. $crlf = $text.Contains("`r`n")
  3326. $lines = $text.Replace("`r`n", "`n") -split "`n"
  3327. $stack = New-Object System.Collections.ArrayList
  3328. $drop = @{}
  3329. for ($i = 0; $i -lt $lines.Count; $i++) {
  3330. $line = $lines[$i]
  3331. if ($line -cmatch '^\t*</([A-Za-z_][\w.:-]*)>$') {
  3332. if ($stack.Count -gt 0 -and $stack[$stack.Count - 1].Name -ceq $Matches[1]) { $stack.RemoveAt($stack.Count - 1) }
  3333. continue
  3334. }
  3335. if ($line -cmatch '^(\t*)<([A-Za-z_][\w.:-]*)(\s[^>]*)?>$' -and -not $line.EndsWith('/>')) {
  3336. [void]$stack.Add(@{ Name = $Matches[2]; Ind = $Matches[1].Length; Attrs = $Matches[3] })
  3337. continue
  3338. }
  3339. if ($stack.Count -eq 0) { continue }
  3340. $m = [regex]::Match($line, '^(\t*)<([A-Za-z]\w*)>([^<]+)</([A-Za-z]\w*)>$')
  3341. if (-not $m.Success -or $m.Groups[2].Value -cne $m.Groups[4].Value) { continue }
  3342. $top = $stack[$stack.Count - 1]
  3343. if ($m.Groups[1].Value.Length -ne $top.Ind + 1) { continue }
  3344. $ptype = if ($stack.Count -eq 1) { if ($top.Name -ceq 'Form') { 'Form' } else { $rootType } } else { $top.Name }
  3345. if (-not $ptype -or -not $script:enumScopeTypes.ContainsKey($ptype)) { continue }
  3346. # Settings — только настройки динамического списка (у ValueList/Planner/Chart свои), как в form-validate
  3347. if ($ptype -ceq 'Settings' -and "$($top.Attrs)" -cnotmatch 'xsi:type="DynamicList"') { continue }
  3348. $script:objType = $ptype
  3349. $tag = $m.Groups[2].Value
  3350. $v = Normalize-EnumValue $tag (Resolve-EnumInputSynonym $ptype $tag $m.Groups[3].Value)
  3351. if (-not $keepDefaults -and $script:enumDefaultValues.ContainsKey("$ptype.$tag") -and $script:enumDefaultValues["$ptype.$tag"] -ceq $v) { $drop[$i] = $true; continue }
  3352. if ($v -cne $m.Groups[3].Value) { $lines[$i] = "$($m.Groups[1].Value)<$tag>$v</$tag>" }
  3353. }
  3354. # Строки-умолчания пропускаются по номеру: $null в строковом массиве PS 5.1 становится пустой строкой
  3355. $keep = New-Object System.Collections.Generic.List[string]
  3356. for ($i = 0; $i -lt $lines.Count; $i++) { if (-not $drop.ContainsKey($i)) { $keep.Add($lines[$i]) } }
  3357. $out = $keep -join "`n"
  3358. if ($crlf) { $out = $out.Replace("`n", "`r`n") }
  3359. return $out
  3360. }
  3361. function Get-ChildRank([string]$parentTag, [string]$childTag) {
  3362. if ($null -eq $script:childRank) {
  3363. $script:childRank = @{}
  3364. foreach ($t in $script:childTagOrder.Keys) {
  3365. $idx = @{}; $i = 0
  3366. foreach ($c in ($script:childTagOrder[$t] -split ' ')) { $idx[$c] = $i; $i++ }
  3367. $script:childRank[$t] = $idx
  3368. }
  3369. }
  3370. $idx = $script:childRank[$parentTag]
  3371. if ($idx -and $idx.ContainsKey($childTag)) { return $idx[$childTag] }
  3372. return -1
  3373. }
  3374. function Sort-ElementTagOrder([string]$text) {
  3375. $crlf = $text.Contains("`r`n")
  3376. $lines = New-Object System.Collections.Generic.List[string]
  3377. $lines.AddRange([string[]]($text.Replace("`r`n", "`n") -split "`n"))
  3378. Sort-TagBlocks $lines 0 $lines.Count ''
  3379. $out = $lines -join "`n"
  3380. if ($crlf) { $out = $out.Replace("`n", "`r`n") }
  3381. return $out
  3382. }
  3383. function Get-TagBlockEnd($lines, [int]$i, [string]$ind, [string]$name) {
  3384. $line = $lines[$i]
  3385. if ($line.EndsWith('/>') -and -not $line.Contains('</')) { return $i + 1 }
  3386. if ($line.EndsWith("</$name>")) { return $i + 1 }
  3387. if ($line -cmatch ('^\t*<' + [regex]::Escape($name) + '(\s[^>]*)?>$')) {
  3388. $close = "$ind</$name>"
  3389. $j = $i + 1
  3390. while ($j -lt $lines.Count -and $lines[$j] -cne $close) { $j++ }
  3391. return $j + 1
  3392. }
  3393. # многострочный текст — до строки, которая кончается закрывающим тегом
  3394. $j = $i + 1
  3395. while ($j -lt $lines.Count -and -not $lines[$j - 1].EndsWith("</$name>")) { $j++ }
  3396. return $j
  3397. }
  3398. function Sort-TagBlocks($lines, [int]$lo, [int]$hi, [string]$parent) {
  3399. $ind = $null
  3400. for ($i = $lo; $i -lt $hi; $i++) {
  3401. if ($lines[$i] -cmatch '^(\t*)<[A-Za-z_]') { $ind = $Matches[1]; break }
  3402. }
  3403. if ($null -eq $ind) { return }
  3404. $blocks = New-Object System.Collections.ArrayList
  3405. $i = $lo
  3406. while ($i -lt $hi) {
  3407. $m = [regex]::Match($lines[$i], '^(\t*)<([A-Za-z_][\w.:-]*)(?=[\s/>])')
  3408. if ($m.Success -and $m.Groups[1].Value -ceq $ind) {
  3409. $e = Get-TagBlockEnd $lines $i $ind $m.Groups[2].Value
  3410. [void]$blocks.Add(@{ Name = $m.Groups[2].Value; S = $i; E = $e })
  3411. $i = $e
  3412. } else { $i++ }
  3413. }
  3414. foreach ($b in $blocks) {
  3415. if ($b.E - $b.S -gt 2 -and $lines[$b.S] -cmatch ('^\t*<' + [regex]::Escape($b.Name) + '(\s[^>]*)?>$')) {
  3416. Sort-TagBlocks $lines ($b.S + 1) ($b.E - 1) $b.Name
  3417. }
  3418. }
  3419. if ($blocks.Count -lt 2 -or -not $parent) { return }
  3420. $ptag = ($parent -split ':')[-1]
  3421. if (-not $script:childTagOrder.ContainsKey($ptag)) { return }
  3422. $total = 0
  3423. foreach ($b in $blocks) { $total += $b.E - $b.S }
  3424. $a = $blocks[0].S; $z = $blocks[$blocks.Count - 1].E
  3425. if ($total -ne $z - $a) { return } # между детьми есть посторонние строки — не трогаем
  3426. $last = -1
  3427. $keyed = New-Object System.Collections.ArrayList
  3428. for ($k = 0; $k -lt $blocks.Count; $k++) {
  3429. $r = Get-ChildRank $ptag (($blocks[$k].Name -split ':')[-1])
  3430. if ($r -lt 0) { $r = $last }
  3431. $last = $r
  3432. [void]$keyed.Add([pscustomobject]@{ Key = ($r + 1) * 100000 + $k; K = $k })
  3433. }
  3434. $sorted = @($keyed | Sort-Object Key)
  3435. $same = $true
  3436. for ($k = 0; $k -lt $sorted.Count; $k++) { if ($sorted[$k].K -ne $k) { $same = $false; break } }
  3437. if ($same) { return }
  3438. $seq = New-Object System.Collections.Generic.List[string]
  3439. foreach ($s in $sorted) { $b = $blocks[$s.K]; for ($x = $b.S; $x -lt $b.E; $x++) { $seq.Add($lines[$x]) } }
  3440. $lines.RemoveRange($a, $z - $a)
  3441. $lines.InsertRange($a, $seq)
  3442. }
  3443. function Emit-Element {
  3444. param($el, [string]$indent, [bool]$inCmdBar = $false)
  3445. # Companion-панели (объект/массив-значение) → commandBar/contextMenu, до тип-синонимов.
  3446. Normalize-PanelSynonyms $el
  3447. # Синонимы типа (XML-имя, русское имя) → канонический ключ DSL
  3448. Normalize-ElementTypeSynonyms $el
  3449. # Синонимы ключей-свойств (русские имена 1С → канон. англ.). Case/space-insensitive.
  3450. # Канон побеждает: если задан и русский, и англ. ключ — англ. остаётся, русский отбрасываем.
  3451. foreach ($pn in @($el.PSObject.Properties.Name)) {
  3452. $norm = ($pn -replace '\s','').ToLower()
  3453. $canon = $script:propSynonyms[$norm]
  3454. if ($canon -and $pn -ne $canon) {
  3455. if ($null -eq $el.PSObject.Properties[$canon]) {
  3456. $val = $el.($pn)
  3457. $el | Add-Member -NotePropertyName $canon -NotePropertyValue $val -Force
  3458. }
  3459. $el.PSObject.Properties.Remove($pn) | Out-Null
  3460. }
  3461. }
  3462. # Determine element type from key
  3463. $typeKey = $null
  3464. $xmlTag = $null
  3465. # picture/picField — НИЗКИЙ приоритет: 'picture' это и тип (PictureDecoration), и свойство-иконка
  3466. # у popup/button/cmdBar. Тип-ключ владельца (popup/button/…) должен выиграть.
  3467. # pages/page ПЕРЕД group: у Page/Pages ключ 'group' — это направление раскладки детей
  3468. # (<Group>Horizontal</Group>), а не тип UsualGroup. Реальная UsualGroup ключа page/pages не несёт.
  3469. 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")) {
  3470. if ($el.$key -ne $null) {
  3471. $typeKey = $key
  3472. break
  3473. }
  3474. }
  3475. if (-not $typeKey) {
  3476. Write-Warning "Unknown element type, skipping"
  3477. return
  3478. }
  3479. # Validate known keys — warn about typos and unknown properties
  3480. $knownKeys = @{
  3481. # type keys
  3482. "group"=1;"columnGroup"=1;"buttonGroup"=1;"input"=1;"check"=1;"radio"=1;"label"=1;"labelField"=1;"table"=1;"pages"=1;"page"=1
  3483. "button"=1;"picture"=1;"picField"=1;"calendar"=1;"cmdBar"=1;"popup"=1
  3484. # спец-поля (документ/датчик/диаграмма) — тип-ключи + типоспец. скаляры
  3485. "spreadsheet"=1;"html"=1;"textDoc"=1;"formattedDoc"=1;"progressBar"=1;"trackBar"=1
  3486. "chart"=1;"ganttChart"=1;"graphicalSchema"=1;"planner"=1;"periodField"=1;"dendrogram"=1;"ganttTable"=1
  3487. "showPercent"=1;"largeStep"=1;"markingStep"=1;"step"=1
  3488. "horizontalScrollBar"=1;"viewScalingMode"=1;"output"=1;"selectionShowMode"=1;"protection"=1
  3489. "edit"=1;"showGrid"=1;"showGroups"=1;"showHeaders"=1;"showRowAndColumnNames"=1;"showCellNames"=1
  3490. "pointerType"=1;"drawingSelectionShowMode"=1;"warningOnEditRepresentation"=1;"markingAppearance"=1
  3491. # report-form контекст (generic-скаляры элементов)
  3492. "horizontalSpacing"=1;"representationInContextMenu"=1;"settingsNamedItemDetailedRepresentation"=1
  3493. # хвост: высота элемента списка / ширина выпадающего списка / картинка кнопки выбора / прозрачный пиксель
  3494. "itemHeight"=1;"dropListWidth"=1;"choiceButtonPicture"=1;"transparentPixel"=1
  3495. # хвост CI-форм: динамический заголовок / расширенное редактирование / высота таблицы
  3496. "titleDataPath"=1;"extendedEdit"=1;"maxRowsCount"=1;"autoMaxRowsCount"=1;"heightControlVariant"=1
  3497. "warningOnEdit"=1;"nonselectedPictureText"=1;"editTextUpdate"=1;"footerText"=1
  3498. # columnGroup-specific
  3499. "showInHeader"=1
  3500. # radio-specific
  3501. "radioButtonType"=1;"choiceList"=1;"columnsCount"=1;"checkBoxType"=1;"editMode"=1
  3502. # naming & binding
  3503. "name"=1;"path"=1;"title"=1;"tooltip"=1;"tooltipRepresentation"=1;"extendedTooltip"=1
  3504. # companion-панели (свойства): командная панель + контекстное меню
  3505. "commandBar"=1;"contextMenu"=1
  3506. # источник команд группы/панели (ButtonGroup/CommandBar)
  3507. "commandSource"=1
  3508. # visibility & state
  3509. "visible"=1;"hidden"=1;"enabled"=1;"disabled"=1;"readOnly"=1;"userVisible"=1
  3510. # events ("events" — основной формат; on/handlers — legacy, принимаются ради совместимости)
  3511. "events"=1;"on"=1;"handlers"=1
  3512. # layout
  3513. "titleLocation"=1;"representation"=1;"width"=1;"height"=1
  3514. "horizontalStretch"=1;"verticalStretch"=1;"autoMaxWidth"=1;"autoMaxHeight"=1
  3515. "maxWidth"=1;"maxHeight"=1
  3516. "groupHorizontalAlign"=1;"groupVerticalAlign"=1;"horizontalAlign"=1
  3517. # input-specific
  3518. "multiLine"=1;"passwordMode"=1;"choiceButton"=1;"clearButton"=1
  3519. "spinButton"=1;"dropListButton"=1;"markIncomplete"=1;"skipOnInput"=1;"inputHint"=1
  3520. "textEdit"=1
  3521. "wrap"=1;"openButton"=1;"listChoiceMode"=1;"showInFooter"=1
  3522. "extendedEditMultipleValues"=1;"chooseType"=1;"autoCellHeight"=1
  3523. "choiceButtonRepresentation"=1;"footerHorizontalAlign"=1;"headerHorizontalAlign"=1
  3524. "headerDataPath"=1;"headerFormat"=1;"currentRowUse"=1
  3525. "format"=1;"editFormat"=1;"choiceParameters"=1;"choiceParameterLinks"=1;"typeLink"=1
  3526. # label/hyperlink
  3527. "hyperlink"=1;"formatted"=1
  3528. # group-specific
  3529. "collapsedTitle"=1;"showTitle"=1;"united"=1;"collapsed"=1;"behavior"=1
  3530. # hierarchy
  3531. "children"=1;"columns"=1
  3532. # table-specific
  3533. "changeRowSet"=1;"changeRowOrder"=1;"autoInsertNewRow"=1;"rowFilter"=1;"header"=1;"footer"=1
  3534. "commandBarLocation"=1;"searchStringLocation"=1;"viewStatusLocation"=1;"searchControlLocation"=1
  3535. "excludedCommands"=1
  3536. "choiceMode"=1;"initialTreeView"=1;"enableDrag"=1;"enableStartDrag"=1
  3537. "rowPictureDataPath"=1;"tableAutofill"=1;"heightInTableRows"=1
  3538. "multipleChoice"=1;"searchOnInput"=1;"shortcut"=1
  3539. "rowSelectionMode"=1;"verticalLines"=1;"horizontalLines"=1
  3540. # dynamic-list table block
  3541. "defaultItem"=1;"useAlternationRowColor"=1;"fileDragMode"=1;"autoRefresh"=1
  3542. "autoRefreshPeriod"=1;"choiceFoldersAndItems"=1;"restoreCurrentRow"=1;"showRoot"=1
  3543. "allowRootChoice"=1;"updateOnDataChange"=1;"allowGettingCurrentRowURL"=1
  3544. "userSettingsGroup"=1;"rowsPicture"=1
  3545. # calendar-specific
  3546. "selectionMode"=1;"showCurrentDate"=1;"widthInMonths"=1;"heightInMonths"=1;"showMonthsPanel"=1
  3547. # pages-specific
  3548. "pagesRepresentation"=1
  3549. # button-specific
  3550. "type"=1;"command"=1;"commandName"=1;"stdCommand"=1;"parameter"=1;"defaultButton"=1;"locationInCommandBar"=1;"displayImportance"=1
  3551. # picture/decoration
  3552. "src"=1;"valuesPicture"=1;"loadTransparent"=1;"headerPicture"=1;"footerPicture"=1
  3553. # cmdBar-specific
  3554. "autofill"=1
  3555. # AutoCommandBar-маркер (autofill heuristic) на элементе/таблице
  3556. "autoCmdBar"=1
  3557. # дополнения командной панели таблицы (тип-ключи + свойства)
  3558. "searchString"=1;"viewStatus"=1;"searchControl"=1;"source"=1;"horizontalLocation"=1;"additions"=1
  3559. # generic-скаляры (pass-through) + точечные
  3560. "verticalAlign"=1;"throughAlign"=1;"enableContentChange"=1;"pictureSize"=1;"titleHeight"=1
  3561. "childItemsWidth"=1;"showLeftMargin"=1;"cellHyperlink"=1;"viewMode"=1;"verticalScrollBar"=1
  3562. "rowInputMode"=1;"mask"=1;"createButton"=1;"fixingInTable"=1;"verticalSpacing"=1
  3563. # InputField choice-скаляры
  3564. "choiceListButton"=1;"quickChoice"=1;"autoChoiceIncomplete"=1
  3565. "choiceForm"=1;"choiceHistoryOnInput"=1;"footerDataPath"=1;"minValue"=1;"maxValue"=1
  3566. # Button — пометка toggle-кнопки (ключ 'checked', не 'check' — во избежание конфликта с типом)
  3567. "checked"=1
  3568. }
  3569. # Оформление (цвета/шрифты/граница) — авто-регистрация из самих структур, чтобы allowlist
  3570. # не дрейфовал при добавлении новых ключей/синонимов. Канонические + forgiving-синонимы.
  3571. foreach ($k in $script:appearanceSpec.Keys) { $knownKeys[$k] = 1 }
  3572. foreach ($k in $script:appearanceSynonyms.Keys) { $knownKeys[$k] = 1 }
  3573. foreach ($k in $script:propSynonyms.Keys) { $knownKeys[$k] = 1 }
  3574. # Простые скаляры (pass-through) — тоже из своей таблицы: компилятор их выводит, значит, они известны
  3575. foreach ($g in $script:genericScalars) { $knownKeys[$g.Key] = 1 }
  3576. foreach ($p in $el.PSObject.Properties) {
  3577. if ($p.Name -like '_*') { continue } # внутренние маркеры (напр. _dynList)
  3578. if (-not $knownKeys.ContainsKey($p.Name)) {
  3579. Write-Warning "Element '$($el.$typeKey)': unknown key '$($p.Name)' — ignored. Check SKILL.md for valid keys."
  3580. }
  3581. }
  3582. $name = Get-ElementName -el $el -typeKey $typeKey
  3583. Assert-UniqueName -name $name -seen $script:seenElementNames -kind 'element'
  3584. $id = New-Id
  3585. switch ($typeKey) {
  3586. "group" { Emit-Group -el $el -name $name -id $id -indent $indent }
  3587. "columnGroup" { Emit-ColumnGroup -el $el -name $name -id $id -indent $indent }
  3588. "buttonGroup" { Emit-ButtonGroup -el $el -name $name -id $id -indent $indent }
  3589. "input" { Emit-Input -el $el -name $name -id $id -indent $indent }
  3590. "check" { Emit-Check -el $el -name $name -id $id -indent $indent }
  3591. "radio" { Emit-Radio -el $el -name $name -id $id -indent $indent }
  3592. "label" { Emit-Label -el $el -name $name -id $id -indent $indent }
  3593. "labelField" { Emit-LabelField -el $el -name $name -id $id -indent $indent }
  3594. "table" { Emit-Table -el $el -name $name -id $id -indent $indent }
  3595. "pages" { Emit-Pages -el $el -name $name -id $id -indent $indent }
  3596. "page" { Emit-Page -el $el -name $name -id $id -indent $indent }
  3597. "button" { Emit-Button -el $el -name $name -id $id -indent $indent -inCmdBar $inCmdBar }
  3598. "picture" { Emit-PictureDecoration -el $el -name $name -id $id -indent $indent }
  3599. "searchString" { Emit-Addition -el $el -name $name -typeKey "searchString" -id $id -indent $indent }
  3600. "viewStatus" { Emit-Addition -el $el -name $name -typeKey "viewStatus" -id $id -indent $indent }
  3601. "searchControl" { Emit-Addition -el $el -name $name -typeKey "searchControl" -id $id -indent $indent }
  3602. "picField" { Emit-PictureField -el $el -name $name -id $id -indent $indent }
  3603. "calendar" { Emit-Calendar -el $el -name $name -id $id -indent $indent }
  3604. "cmdBar" { Emit-CommandBar -el $el -name $name -id $id -indent $indent }
  3605. "popup" { Emit-Popup -el $el -name $name -id $id -indent $indent }
  3606. "spreadsheet" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "SpreadSheetDocumentField" -typeKey "spreadsheet" }
  3607. "html" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "HTMLDocumentField" -typeKey "html" }
  3608. "textDoc" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "TextDocumentField" -typeKey "textDoc" }
  3609. "formattedDoc" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "FormattedDocumentField" -typeKey "formattedDoc" }
  3610. "progressBar" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "ProgressBarField" -typeKey "progressBar" }
  3611. "trackBar" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "TrackBarField" -typeKey "trackBar" }
  3612. "chart" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "ChartField" -typeKey "chart" }
  3613. "graphicalSchema" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "GraphicalSchemaField" -typeKey "graphicalSchema" }
  3614. "planner" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "PlannerField" -typeKey "planner" }
  3615. "periodField" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "PeriodField" -typeKey "periodField" }
  3616. "dendrogram" { Emit-SimpleField -el $el -name $name -id $id -indent $indent -xmlTag "DendrogramField" -typeKey "dendrogram" }
  3617. "ganttChart" { Emit-GanttChart -el $el -name $name -id $id -indent $indent }
  3618. }
  3619. }
  3620. function Emit-XrFlag {
  3621. param([string]$tag, $val, [string]$indent)
  3622. if ($null -eq $val) { return }
  3623. if ($val -isnot [System.Management.Automation.PSCustomObject] -and $val -isnot [System.Collections.IDictionary]) {
  3624. $flag = ConvertTo-DslBool $val $tag $false
  3625. X "$indent<$tag>"
  3626. X "$indent`t<xr:Common>$(if ($flag){'true'}else{'false'})</xr:Common>"
  3627. X "$indent</$tag>"
  3628. return
  3629. }
  3630. # объектная форма { common, roles }
  3631. $common = if ($null -ne $val.common) { (ConvertTo-DslBool $val.common 'common' $false) } else { $false }
  3632. X "$indent<$tag>"
  3633. X "$indent`t<xr:Common>$(if ($common){'true'}else{'false'})</xr:Common>"
  3634. if ($val.roles) {
  3635. foreach ($r in $val.roles.PSObject.Properties) {
  3636. # Forgiving: принимаем имя без префикса, с "Role." или кириллическим "Роль." → нормализуем в "Role.".
  3637. # Роль по GUID (заимствованная/расширение — name="<guid>" без префикса) эмитим как есть.
  3638. $rname = "$($r.Name)" -replace '^(Role|Роль)\.', ''
  3639. 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" }
  3640. $rval = if (ConvertTo-DslBool $r.Value "$($r.Name)" $false) { 'true' } else { 'false' }
  3641. X "$indent`t<xr:Value name=`"$rname`">$rval</xr:Value>"
  3642. }
  3643. }
  3644. X "$indent</$tag>"
  3645. }
  3646. function Emit-CommonFlags {
  3647. param($el, [string]$indent)
  3648. if ((-not (Get-DslBool $el @('visible') $true)) -or (Get-DslBool $el @('hidden') $false)) { X "$indent<Visible>false</Visible>" }
  3649. if ($null -ne $el.userVisible) { Emit-XrFlag -tag 'UserVisible' -val $el.userVisible -indent $indent }
  3650. if ((-not (Get-DslBool $el @('enabled') $true)) -or (Get-DslBool $el @('disabled') $false)) { X "$indent<Enabled>false</Enabled>" }
  3651. if ((Get-DslBool $el @('readOnly') $false)) { X "$indent<ReadOnly>true</ReadOnly>" }
  3652. }
  3653. function Emit-CommonElementProps {
  3654. param($el, [string]$indent)
  3655. if ((Get-DslBool $el @('defaultItem') $false)) { X "$indent<DefaultItem>true</DefaultItem>" }
  3656. if ($el.PSObject.Properties['skipOnInput'] -and $null -ne $el.skipOnInput) {
  3657. $siv = if ((Get-DslBool $el @('skipOnInput') $false)) { 'true' } else { 'false' }
  3658. X "$indent<SkipOnInput>$siv</SkipOnInput>"
  3659. }
  3660. # EnableStartDrag — фактическое значение (платформа эмитит и явный false, напр. SpreadSheet)
  3661. if ($null -ne $el.enableStartDrag) { X "$indent<EnableStartDrag>$(if ($el.enableStartDrag){'true'}else{'false'})</EnableStartDrag>" }
  3662. if ($el.fileDragMode) { X "$indent<FileDragMode>$($el.fileDragMode)</FileDragMode>" }
  3663. # Cell-свойства поля в таблице (общие для Input/Label/Picture/CheckBox): захват «как есть»
  3664. foreach ($p in @(@('showInHeader','ShowInHeader'), @('showInFooter','ShowInFooter'), @('autoCellHeight','AutoCellHeight'))) {
  3665. if ($null -ne $el.($p[0])) { X "$indent<$($p[1])>$(if ($el.($p[0])){'true'}else{'false'})</$($p[1])>" }
  3666. }
  3667. # Динамический заголовок колонки-группы из данных (HeaderDataPath) — перед HeaderHorizontalAlign (порядок XSD)
  3668. if ($el.headerDataPath) { X "$indent<HeaderDataPath>$(Esc-XmlText "$($el.headerDataPath)")</HeaderDataPath>" }
  3669. if ($el.footerHorizontalAlign) { X "$indent<FooterHorizontalAlign>$($el.footerHorizontalAlign)</FooterHorizontalAlign>" }
  3670. if ($el.headerHorizontalAlign) { X "$indent<HeaderHorizontalAlign>$($el.headerHorizontalAlign)</HeaderHorizontalAlign>" }
  3671. # Формат заголовка колонки-группы (ML-текст) — после HeaderHorizontalAlign (порядок XSD)
  3672. if ($el.headerFormat) { Emit-MLText -tag "HeaderFormat" -text $el.headerFormat -indent $indent }
  3673. }
  3674. function Emit-PictureRef {
  3675. param($val, [string]$picTag, [string]$indent)
  3676. if (-not $val) { return }
  3677. $src = $null; $lt = $false; $tpx = $null
  3678. if ($val -is [string]) { $src = $val }
  3679. else { $src = $val.src; if ((Get-DslBool $val @('loadTransparent') $false)) { $lt = $true }; $tpx = $val.transparentPixel }
  3680. if (-not $src) { return }
  3681. $srcStr = "$src"
  3682. X "$indent<$picTag>"
  3683. if ($srcStr -match '^abs:(.*)$') { X "$indent`t<xr:Abs>$(Esc-XmlText $matches[1])</xr:Abs>" }
  3684. else { X "$indent`t<xr:Ref>$(Esc-XmlText $srcStr)</xr:Ref>" }
  3685. X "$indent`t<xr:LoadTransparent>$(if ($lt) { 'true' } else { 'false' })</xr:LoadTransparent>"
  3686. if ($tpx) { X "$indent`t<xr:TransparentPixel x=`"$($tpx.x)`" y=`"$($tpx.y)`"/>" }
  3687. X "$indent</$picTag>"
  3688. }
  3689. function Emit-ColumnPics {
  3690. param($el, [string]$indent)
  3691. Emit-PictureRef -val $el.headerPicture -picTag 'HeaderPicture' -indent $indent
  3692. Emit-PictureRef -val $el.footerPicture -picTag 'FooterPicture' -indent $indent
  3693. }
  3694. function Emit-CommandPicture {
  3695. param($pic, $elemLt, [string]$indent)
  3696. if (-not $pic) { return }
  3697. $src = $null; $lt = $null; $tpx = $null
  3698. if ($pic -is [string]) { $src = $pic }
  3699. else { $src = $pic.src; if ($null -ne $pic.loadTransparent) { $lt = (ConvertTo-DslBool $pic.loadTransparent 'loadTransparent' $false) }; $tpx = $pic.transparentPixel }
  3700. if (-not $src) { return }
  3701. if ($null -eq $lt -and $null -ne $elemLt) { $lt = (ConvertTo-DslBool $elemLt 'loadTransparent' $false) }
  3702. $srcStr = "$src"
  3703. X "$indent<Picture>"
  3704. if ($srcStr -match '^abs:(.*)$') { X "$indent`t<xr:Abs>$(Esc-XmlText $matches[1])</xr:Abs>" }
  3705. else { X "$indent`t<xr:Ref>$(Esc-XmlText $srcStr)</xr:Ref>" }
  3706. X "$indent`t<xr:LoadTransparent>$(if ($lt -eq $false) { 'false' } else { 'true' })</xr:LoadTransparent>"
  3707. if ($tpx) { X "$indent`t<xr:TransparentPixel x=`"$($tpx.x)`" y=`"$($tpx.y)`"/>" }
  3708. X "$indent</Picture>"
  3709. }
  3710. function Emit-GenericScalars {
  3711. param($el, [string]$indent)
  3712. if ($null -eq $el) { return }
  3713. foreach ($s in $script:genericScalars) {
  3714. $p = $el.PSObject.Properties[$s.Key]
  3715. if (-not $p -or $null -eq $p.Value) { continue }
  3716. if ($s.Kind -eq 'bool') {
  3717. X "$indent<$($s.Tag)>$(if ($p.Value){'true'}else{'false'})</$($s.Tag)>"
  3718. } else {
  3719. $v = "$($p.Value)"; if ($v -eq '') { continue }
  3720. X "$indent<$($s.Tag)>$(Esc-XmlText $v)</$($s.Tag)>"
  3721. }
  3722. }
  3723. }
  3724. function Get-AppearanceValue {
  3725. param($el, [string]$canonical)
  3726. if ($null -eq $el) { return $null }
  3727. $p = $el.PSObject.Properties[$canonical]
  3728. if ($p) { return $p.Value }
  3729. foreach ($syn in $script:appearanceSynonyms.Keys) {
  3730. if ($script:appearanceSynonyms[$syn] -eq $canonical) {
  3731. $pp = $el.PSObject.Properties[$syn]
  3732. if ($pp) { return $pp.Value }
  3733. }
  3734. }
  3735. return $null
  3736. }
  3737. function Emit-FontTag {
  3738. param([string]$tag, $val, [string]$indent)
  3739. if ($val -is [string]) {
  3740. X "$indent<$tag ref=`"$(Esc-Xml $val)`" kind=`"StyleItem`"/>"
  3741. return
  3742. }
  3743. $attrs = @()
  3744. foreach ($a in @('ref','faceName','height','bold','italic','underline','strikeout','kind','scale')) {
  3745. $pp = $val.PSObject.Properties[$a]
  3746. if ($pp -and $null -ne $pp.Value) {
  3747. $v = $pp.Value
  3748. if ($v -is [bool]) { $v = if ($v) {'true'} else {'false'} }
  3749. $attrs += "$a=`"$(Esc-Xml "$v")`""
  3750. }
  3751. }
  3752. X "$indent<$tag $($attrs -join ' ')/>"
  3753. }
  3754. function Emit-BorderTag {
  3755. param($val, [string]$indent)
  3756. if ($val -is [string]) { X "$indent<Border ref=`"$(Esc-Xml $val)`"/>"; return }
  3757. $refP = $val.PSObject.Properties['ref']
  3758. if ($refP -and $refP.Value) { X "$indent<Border ref=`"$(Esc-Xml "$($refP.Value)")`"/>"; return }
  3759. $width = if ($val.PSObject.Properties['width'] -and $null -ne $val.width) { $val.width } else { 1 }
  3760. $style = if ($val.PSObject.Properties['style']) { "$($val.style)" } else { $null }
  3761. X "$indent<Border width=`"$width`">"
  3762. if ($style) { X "$indent`t<v8ui:style xsi:type=`"v8ui:ControlBorderType`">$(Esc-XmlText $style)</v8ui:style>" }
  3763. X "$indent</Border>"
  3764. }
  3765. function PL-Get {
  3766. param($o, [string]$k, $def = $null)
  3767. if ($null -ne $o -and $o.PSObject.Properties[$k] -and $null -ne $o.$k) { return $o.$k }
  3768. return $def
  3769. }
  3770. function PL-Bool {
  3771. param($v)
  3772. if ($v -is [bool]) { if ($v) { 'true' } else { 'false' } }
  3773. elseif ("$v" -eq 'True') { 'true' }
  3774. elseif ("$v" -eq 'False') { 'false' }
  3775. else { "$v" }
  3776. }
  3777. function Emit-PlannerColor {
  3778. param([string]$tag, $o, [string]$key, [string]$ind)
  3779. X "$ind<pl:$tag>$(Esc-XmlText "$(PL-Get $o $key 'auto')")</pl:$tag>"
  3780. }
  3781. function Emit-PlannerText {
  3782. param([string]$tag, $v, [string]$ind)
  3783. if ([string]::IsNullOrEmpty("$v")) { X "$ind<pl:$tag/>" }
  3784. else { X "$ind<pl:$tag>$(Esc-XmlText "$v")</pl:$tag>" }
  3785. }
  3786. function Test-PlannerRef {
  3787. param([string]$v)
  3788. return ($v -match '^(Enum|Catalog|Document|ChartOfAccounts|ChartOfCalculationTypes|ChartOfCharacteristicTypes|ExchangePlan|BusinessProcess|Task)\.' -or `
  3789. $v -match '\.EnumValue\.' -or $v -match 'EmptyRef$' -or `
  3790. $v -match '^(Перечисление|Справочник|Документ|ПланСчетов|ПланВидовХарактеристик|ПланВидовРасчета|ПланОбмена|БизнесПроцесс|Задача)\.')
  3791. }
  3792. function Emit-PlannerValue {
  3793. param($v, [string]$ind)
  3794. if ($null -eq $v -or "$v" -eq '') { X "$ind<pl:value xsi:nil=`"true`"/>"; return }
  3795. $t = if (Test-PlannerRef "$v") { 'xr:DesignTimeRef' } else { 'xs:string' }
  3796. X "$ind<pl:value xsi:type=`"$t`">$(Esc-XmlText "$v")</pl:value>"
  3797. }
  3798. function Emit-PlannerFont {
  3799. param($o, [string]$ind)
  3800. $f = PL-Get $o 'font' $null
  3801. if ($null -eq $f) { X "$ind<pl:font kind=`"AutoFont`"/>"; return }
  3802. Emit-FontTag -tag 'pl:font' -val $f -indent $ind
  3803. }
  3804. function Emit-PlannerBorder {
  3805. param($o, [string]$ind, [string]$key = 'border')
  3806. $b = PL-Get $o $key $null
  3807. $bw = if ($b) { PL-Get $b 'width' 1 } else { 1 }
  3808. $bs = if ($b) { PL-Get $b 'style' 'Single' } else { 'Single' }
  3809. X "$ind<pl:border width=`"$bw`">"
  3810. X "$ind`t<v8ui:style xsi:type=`"v8ui:ControlBorderType`">$(Esc-XmlText "$bs")</v8ui:style>"
  3811. X "$ind</pl:border>"
  3812. }
  3813. function Emit-PlannerLevel {
  3814. param($lv, [string]$cns, [string]$ind)
  3815. $li = "$ind`t"
  3816. X "$ind<level xmlns=`"$cns`">"
  3817. X "$li<measure>$(Esc-XmlText "$(PL-Get $lv 'measure' 'Hour')")</measure>"
  3818. X "$li<interval>$(PL-Get $lv 'interval' 1)</interval>"
  3819. X "$li<show>$(PL-Bool (PL-Get $lv 'show' $true))</show>"
  3820. $line = PL-Get $lv 'line' $null
  3821. $lw = if ($line) { PL-Get $line 'width' 1 } else { 1 }
  3822. $lg = if ($line) { PL-Get $line 'gap' $false } else { $false }
  3823. $lst = if ($line) { PL-Get $line 'style' 'Solid' } else { 'Solid' }
  3824. X "$li<line width=`"$lw`" gap=`"$(PL-Bool $lg)`">"
  3825. X "$li`t<v8ui:style xsi:type=`"v8ui:ChartLineType`">$(Esc-XmlText "$lst")</v8ui:style>"
  3826. X "$li</line>"
  3827. X "$li<scaleColor>$(Esc-XmlText "$(PL-Get $lv 'scaleColor' 'auto')")</scaleColor>"
  3828. X "$li<dayFormatRule>$(Esc-XmlText "$(PL-Get $lv 'dayFormatRule' 'MonthDayWeekDay')")</dayFormatRule>"
  3829. $fmt = PL-Get $lv 'format' $null
  3830. if ($null -eq $fmt) { $fmt = [ordered]@{ '#' = 'DF="HH:mm"'; 'ru' = 'DF="HH:mm"' } }
  3831. X "$li<format>"
  3832. Emit-MLItems -val $fmt -indent "$li`t"
  3833. X "$li</format>"
  3834. $labels = PL-Get $lv 'labels' $null
  3835. $ticks = if ($labels) { PL-Get $labels 'ticks' 0 } else { 0 }
  3836. X "$li<labels>"
  3837. X "$li`t<ticks>$ticks</ticks>"
  3838. X "$li</labels>"
  3839. X "$li<backColor>$(Esc-XmlText "$(PL-Get $lv 'backColor' 'auto')")</backColor>"
  3840. X "$li<textColor>$(Esc-XmlText "$(PL-Get $lv 'textColor' 'auto')")</textColor>"
  3841. X "$li<showPereodicalLabels>$(PL-Bool (PL-Get $lv 'showPereodicalLabels' $true))</showPereodicalLabels>"
  3842. X "$ind</level>"
  3843. }
  3844. function Emit-PlannerTimeScale {
  3845. param($ts, [string]$ind)
  3846. $cns = $script:CHART_NS
  3847. $ci = "$ind`t"
  3848. X "$ind<pl:timeScale>"
  3849. X "$ci<placement xmlns=`"$cns`">$(Esc-XmlText "$(if ($ts) { PL-Get $ts 'placement' 'Left' } else { 'Left' })")</placement>"
  3850. $levels = if ($ts) { @(PL-Get $ts 'levels' @()) } else { @() }
  3851. if (@($levels).Count -eq 0) { $levels = @($null) } # один уровень-дефолт
  3852. foreach ($lv in $levels) { Emit-PlannerLevel $lv $cns $ci }
  3853. $transp = if ($ts) { PL-Get $ts 'transparent' $false } else { $false }
  3854. X "$ci<transparent xmlns=`"$cns`">$(PL-Bool $transp)</transparent>"
  3855. X "$ci<backColor xmlns=`"$cns`">$(Esc-XmlText "$(if ($ts) { PL-Get $ts 'backColor' 'auto' } else { 'auto' })")</backColor>"
  3856. X "$ci<textColor xmlns=`"$cns`">$(Esc-XmlText "$(if ($ts) { PL-Get $ts 'textColor' 'auto' } else { 'auto' })")</textColor>"
  3857. X "$ci<currentLevel xmlns=`"$cns`">$(if ($ts) { PL-Get $ts 'currentLevel' 0 } else { 0 })</currentLevel>"
  3858. X "$ind</pl:timeScale>"
  3859. }
  3860. function Emit-PlannerItem {
  3861. param($it, [string]$ind)
  3862. X "$ind<pl:item>"
  3863. $ii = "$ind`t"
  3864. Emit-PlannerValue (PL-Get $it 'value' $null) $ii
  3865. Emit-PlannerText 'text' (PL-Get $it 'text' '') $ii
  3866. Emit-PlannerText 'tooltip' (PL-Get $it 'tooltip' '') $ii
  3867. X "$ii<pl:begin>$(PL-Get $it 'begin' '0001-01-01T00:00:00')</pl:begin>"
  3868. X "$ii<pl:end>$(PL-Get $it 'end' '0001-01-01T00:00:00')</pl:end>"
  3869. Emit-PlannerColor 'borderColor' $it 'borderColor' $ii
  3870. Emit-PlannerColor 'backColor' $it 'backColor' $ii
  3871. Emit-PlannerColor 'textColor' $it 'textColor' $ii
  3872. Emit-PlannerFont $it $ii
  3873. X "$ii<pl:dimensionValues/>"
  3874. X "$ii<pl:replacementDate>$(PL-Get $it 'replacementDate' '0001-01-01T00:00:00')</pl:replacementDate>"
  3875. X "$ii<pl:deleted>$(PL-Bool (PL-Get $it 'deleted' $false))</pl:deleted>"
  3876. $id = PL-Get $it 'id' $null
  3877. if ($null -eq $id) { $id = [guid]::NewGuid().ToString() }
  3878. X "$ii<pl:id>$id</pl:id>"
  3879. X "$ii<pl:textFormatted>$(PL-Bool (PL-Get $it 'textFormatted' $false))</pl:textFormatted>"
  3880. Emit-PlannerBorder $it $ii 'border'
  3881. X "$ii<pl:editMode>$(Esc-XmlText "$(PL-Get $it 'editMode' 'EnableEdit')")</pl:editMode>"
  3882. X "$ind</pl:item>"
  3883. }
  3884. function Emit-PlannerDimElement {
  3885. param($el, [string]$ind)
  3886. X "$ind<pl:item>"
  3887. $ii = "$ind`t"
  3888. Emit-PlannerValue (PL-Get $el 'value' $null) $ii
  3889. Emit-PlannerText 'text' (PL-Get $el 'text' '') $ii
  3890. Emit-PlannerColor 'borderColor' $el 'borderColor' $ii
  3891. Emit-PlannerColor 'backColor' $el 'backColor' $ii
  3892. Emit-PlannerColor 'textColor' $el 'textColor' $ii
  3893. Emit-PlannerFont $el $ii
  3894. foreach ($sub in @(PL-Get $el 'elements' @())) { Emit-PlannerDimElement $sub $ii }
  3895. X "$ii<pl:showOnlySubordinatesAreas>$(PL-Bool (PL-Get $el 'showOnlySubordinatesAreas' $true))</pl:showOnlySubordinatesAreas>"
  3896. X "$ii<pl:textFormatted>$(PL-Bool (PL-Get $el 'textFormatted' $false))</pl:textFormatted>"
  3897. X "$ind</pl:item>"
  3898. }
  3899. function Emit-PlannerDimension {
  3900. param($d, [string]$ind)
  3901. X "$ind<pl:dimension>"
  3902. $di = "$ind`t"
  3903. Emit-PlannerValue (PL-Get $d 'value' $null) $di
  3904. Emit-PlannerText 'text' (PL-Get $d 'text' '') $di
  3905. Emit-PlannerColor 'borderColor' $d 'borderColor' $di
  3906. Emit-PlannerColor 'backColor' $d 'backColor' $di
  3907. Emit-PlannerColor 'textColor' $d 'textColor' $di
  3908. Emit-PlannerFont $d $di
  3909. foreach ($el in @(PL-Get $d 'elements' @())) { Emit-PlannerDimElement $el $di }
  3910. X "$di<pl:textFormatted>$(PL-Bool (PL-Get $d 'textFormatted' $false))</pl:textFormatted>"
  3911. X "$ind</pl:dimension>"
  3912. }
  3913. function Emit-PlannerSettings {
  3914. param($pl, [string]$ind)
  3915. X "$ind<Settings xmlns:pl=`"$($script:PLANNER_NS)`" xsi:type=`"pl:Planner`">"
  3916. $si = "$ind`t"
  3917. foreach ($it in @(PL-Get $pl 'items' @())) { Emit-PlannerItem $it $si }
  3918. foreach ($d in @(PL-Get $pl 'dimensions' @())) { Emit-PlannerDimension $d $si }
  3919. Emit-PlannerColor 'borderColor' $pl 'borderColor' $si
  3920. Emit-PlannerColor 'backColor' $pl 'backColor' $si
  3921. Emit-PlannerColor 'textColor' $pl 'textColor' $si
  3922. Emit-PlannerColor 'lineColor' $pl 'lineColor' $si
  3923. Emit-PlannerFont $pl $si
  3924. X "$si<pl:beginOfRepresentationPeriod>$(PL-Get $pl 'beginOfRepresentationPeriod' '0001-01-01T00:00:00')</pl:beginOfRepresentationPeriod>"
  3925. X "$si<pl:endOfRepresentationPeriod>$(PL-Get $pl 'endOfRepresentationPeriod' '0001-01-01T00:00:00')</pl:endOfRepresentationPeriod>"
  3926. X "$si<pl:alignElementsOfTimeScale>$(PL-Bool (PL-Get $pl 'alignElementsOfTimeScale' $true))</pl:alignElementsOfTimeScale>"
  3927. X "$si<pl:displayTimeScaleWrapHeaders>$(PL-Bool (PL-Get $pl 'displayTimeScaleWrapHeaders' $true))</pl:displayTimeScaleWrapHeaders>"
  3928. X "$si<pl:displayWrapHeaders>$(PL-Bool (PL-Get $pl 'displayWrapHeaders' $true))</pl:displayWrapHeaders>"
  3929. $wfmt = PL-Get $pl 'timeScaleWrapHeadersFormat' $null
  3930. if ($null -eq $wfmt) { $wfmt = [ordered]@{ '#' = 'DLF="DD"'; 'ru' = 'DLF="DD"' } }
  3931. Emit-MLText -tag 'pl:timeScaleWrapHeadersFormat' -text $wfmt -indent $si
  3932. X "$si<pl:periodicVariantUnit>$(Esc-XmlText "$(PL-Get $pl 'periodicVariantUnit' 'Day')")</pl:periodicVariantUnit>"
  3933. X "$si<pl:periodicVariantRepetition>$(PL-Get $pl 'periodicVariantRepetition' 1)</pl:periodicVariantRepetition>"
  3934. X "$si<pl:timeScaleWrapBeginIndent>$(PL-Get $pl 'timeScaleWrapBeginIndent' 0)</pl:timeScaleWrapBeginIndent>"
  3935. X "$si<pl:timeScaleWrapEndIndent>$(PL-Get $pl 'timeScaleWrapEndIndent' 0)</pl:timeScaleWrapEndIndent>"
  3936. Emit-PlannerTimeScale (PL-Get $pl 'timeScale' $null) $si
  3937. $period = PL-Get $pl 'period' $null
  3938. if ($period) {
  3939. X "$si<pl:period>"
  3940. X "$si`t<pl:begin>$(PL-Get $period 'begin' '0001-01-01T00:00:00')</pl:begin>"
  3941. X "$si`t<pl:end>$(PL-Get $period 'end' '0001-01-01T00:00:00')</pl:end>"
  3942. X "$si</pl:period>"
  3943. }
  3944. X "$si<pl:displayCurrentDate>$(PL-Bool (PL-Get $pl 'displayCurrentDate' $true))</pl:displayCurrentDate>"
  3945. X "$si<pl:itemsTimeRepresentation>$(Esc-XmlText "$(PL-Get $pl 'itemsTimeRepresentation' 'BeginTime')")</pl:itemsTimeRepresentation>"
  3946. X "$si<pl:itemsBehaviorWhenSpaceInsufficient>$(Esc-XmlText "$(PL-Get $pl 'itemsBehaviorWhenSpaceInsufficient' 'CollapseItems')")</pl:itemsBehaviorWhenSpaceInsufficient>"
  3947. X "$si<pl:autoMinColumnWidth>$(PL-Bool (PL-Get $pl 'autoMinColumnWidth' $true))</pl:autoMinColumnWidth>"
  3948. X "$si<pl:autoMinRowHeight>$(PL-Bool (PL-Get $pl 'autoMinRowHeight' $true))</pl:autoMinRowHeight>"
  3949. X "$si<pl:minColumnWidth>$(PL-Get $pl 'minColumnWidth' 0)</pl:minColumnWidth>"
  3950. X "$si<pl:minRowHeight>$(PL-Get $pl 'minRowHeight' 0)</pl:minRowHeight>"
  3951. X "$si<pl:fixDimensionsHeader>$(Esc-XmlText "$(PL-Get $pl 'fixDimensionsHeader' 'auto')")</pl:fixDimensionsHeader>"
  3952. X "$si<pl:fixTimeScaleHeader>$(Esc-XmlText "$(PL-Get $pl 'fixTimeScaleHeader' 'auto')")</pl:fixTimeScaleHeader>"
  3953. Emit-PlannerBorder $pl $si 'border'
  3954. X "$si<pl:newItemsTextType>$(Esc-XmlText "$(PL-Get $pl 'newItemsTextType' 'String')")</pl:newItemsTextType>"
  3955. X "$ind</Settings>"
  3956. }
  3957. function Get-Keys { param($o) if ($o -is [System.Collections.IDictionary]) { return @($o.Keys) } else { return @($o.PSObject.Properties.Name) } }
  3958. 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 } } }
  3959. function Emit-ChartNode {
  3960. param([string]$name, $val, [string]$ind)
  3961. if ($script:CHART_ML_FIELDS.Contains($name)) {
  3962. if ($null -eq $val -or "$val" -eq '') { X "$ind<d4p1:$name/>"; return }
  3963. X "$ind<d4p1:$name>"; Emit-MLItems -val $val -indent "$ind`t"; X "$ind</d4p1:$name>"; return
  3964. }
  3965. if (($val -is [System.Collections.IList]) -and ($val -isnot [string])) {
  3966. foreach ($e in $val) { Emit-ChartNode $name $e $ind }
  3967. return
  3968. }
  3969. if (($val -is [System.Management.Automation.PSCustomObject]) -or ($val -is [System.Collections.IDictionary])) {
  3970. $keys = Get-Keys $val
  3971. if ($script:CHART_ATTR_FIELDS.Contains($name)) {
  3972. $attrs = @(); foreach ($k in $keys) { $v = Get-Prop $val $k; if ($v -is [bool]) { $v = PL-Bool $v }; $attrs += "$k=`"$(Esc-Xml "$v")`"" }
  3973. X "$ind<d4p1:$name $($attrs -join ' ')/>"; return
  3974. }
  3975. if ($keys -contains 'gap') {
  3976. $w = Get-Prop $val 'width'; $g = Get-Prop $val 'gap'; $st = Get-Prop $val 'style'
  3977. X "$ind<d4p1:$name width=`"$w`" gap=`"$(PL-Bool $g)`">"
  3978. X "$ind`t<v8ui:style xsi:type=`"v8ui:ChartLineType`">$(Esc-XmlText "$st")</v8ui:style>"
  3979. X "$ind</d4p1:$name>"; return
  3980. }
  3981. if (($keys -contains 'style') -and ($keys -contains 'width')) {
  3982. $w = Get-Prop $val 'width'; $st = Get-Prop $val 'style'
  3983. X "$ind<d4p1:$name width=`"$w`">"
  3984. X "$ind`t<v8ui:style xsi:type=`"v8ui:ControlBorderType`">$(Esc-XmlText "$st")</v8ui:style>"
  3985. X "$ind</d4p1:$name>"; return
  3986. }
  3987. $isFont = $false; foreach ($fk in $script:CHART_FONT_KEYS) { if ($keys -contains $fk) { $isFont = $true; break } }
  3988. if ($isFont) {
  3989. $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")`"" } }
  3990. X "$ind<d4p1:$name $($attrs -join ' ')/>"; return
  3991. }
  3992. if (@($keys).Count -eq 0) { X "$ind<d4p1:$name/>"; return }
  3993. X "$ind<d4p1:$name>"
  3994. foreach ($k in $keys) { Emit-ChartNode $k (Get-Prop $val $k) "$ind`t" }
  3995. X "$ind</d4p1:$name>"
  3996. return
  3997. }
  3998. if ($null -eq $val -or "$val" -eq '') { X "$ind<d4p1:$name/>"; return }
  3999. if ($val -is [bool]) { X "$ind<d4p1:$name>$(PL-Bool $val)</d4p1:$name>"; return }
  4000. X "$ind<d4p1:$name>$(Esc-XmlText "$val")</d4p1:$name>"
  4001. }
  4002. function Emit-ChartSettings {
  4003. param($chart, [string]$ind, [string]$ctype = 'd4p1:Chart')
  4004. X "$ind<Settings xmlns:d4p1=`"$($script:CHART_NS)`" xsi:type=`"$ctype`">"
  4005. foreach ($k in (Get-Keys $chart)) { Emit-ChartNode $k (Get-Prop $chart $k) "$ind`t" }
  4006. X "$ind</Settings>"
  4007. }
  4008. function Emit-Appearance {
  4009. param($el, [string]$indent, [string]$profile = 'field')
  4010. if ($null -eq $el) { return }
  4011. $order = switch ($profile) {
  4012. 'decoration' { $script:appOrderDecoration }
  4013. 'button' { $script:appOrderButton }
  4014. default { $script:appOrderField }
  4015. }
  4016. foreach ($key in $order) {
  4017. $val = Get-AppearanceValue -el $el -canonical $key
  4018. if ($null -eq $val -or ($val -is [string] -and $val -eq '')) { continue }
  4019. $spec = $script:appearanceSpec[$key]
  4020. switch ($spec.kind) {
  4021. 'color' { X "$indent<$($spec.tag)>$(Esc-XmlText "$val")</$($spec.tag)>" }
  4022. 'font' { Emit-FontTag -tag $spec.tag -val $val -indent $indent }
  4023. 'border' { Emit-BorderTag -val $val -indent $indent }
  4024. }
  4025. }
  4026. }
  4027. function Emit-Layout {
  4028. param($el, [string]$indent, [switch]$skipHeight, [bool]$multiLineDefault = $false)
  4029. # CommandSet (отключённые команды редактора) — общее свойство поля (input/label/check/
  4030. # spreadsheet/html/formatted/picture); в схеме рано (после TitleLocation, перед скалярами).
  4031. if ($el.excludedCommands -and @($el.excludedCommands).Count -gt 0) {
  4032. X "$indent<CommandSet>"
  4033. foreach ($cmd in $el.excludedCommands) { X "$indent`t<ExcludedCommand>$cmd</ExcludedCommand>" }
  4034. X "$indent</CommandSet>"
  4035. }
  4036. Emit-CommonElementProps -el $el -indent $indent
  4037. $amwExplicit = ($el.PSObject.Properties.Name -contains 'autoMaxWidth')
  4038. if ($amwExplicit) {
  4039. if ((-not (Get-DslBool $el @('autoMaxWidth') $true))) { X "$indent<AutoMaxWidth>false</AutoMaxWidth>" }
  4040. } elseif ($multiLineDefault) {
  4041. X "$indent<AutoMaxWidth>false</AutoMaxWidth>"
  4042. }
  4043. if ($null -ne $el.maxWidth) { X "$indent<MaxWidth>$($el.maxWidth)</MaxWidth>" }
  4044. if ((-not (Get-DslBool $el @('autoMaxHeight') $true))) { X "$indent<AutoMaxHeight>false</AutoMaxHeight>" }
  4045. if ($null -ne $el.maxHeight) { X "$indent<MaxHeight>$($el.maxHeight)</MaxHeight>" }
  4046. if ($el.width) { X "$indent<Width>$($el.width)</Width>" }
  4047. if (-not $skipHeight -and $el.height) { X "$indent<Height>$($el.height)</Height>" }
  4048. if ($null -ne $el.horizontalStretch) { X "$indent<HorizontalStretch>$(if ($el.horizontalStretch){'true'}else{'false'})</HorizontalStretch>" }
  4049. if ($null -ne $el.verticalStretch) { X "$indent<VerticalStretch>$(if ($el.verticalStretch){'true'}else{'false'})</VerticalStretch>" }
  4050. if ($el.groupHorizontalAlign) { X "$indent<GroupHorizontalAlign>$($el.groupHorizontalAlign)</GroupHorizontalAlign>" }
  4051. if ($el.groupVerticalAlign) { X "$indent<GroupVerticalAlign>$($el.groupVerticalAlign)</GroupVerticalAlign>" }
  4052. if ($el.horizontalAlign) { X "$indent<HorizontalAlign>$($el.horizontalAlign)</HorizontalAlign>" }
  4053. Emit-GenericScalars -el $el -indent $indent
  4054. }
  4055. function Title-FromName {
  4056. param([string]$name)
  4057. if (-not $name) { return '' }
  4058. $s = [regex]::Replace($name, '([А-ЯA-Z])([А-ЯA-Z][а-яa-z])', '$1 $2')
  4059. $s = [regex]::Replace($s, '([а-яa-z0-9])([А-ЯA-Z])', '$1 $2')
  4060. $parts = $s -split ' '
  4061. if ($parts.Count -eq 0) { return $s }
  4062. $out = New-Object System.Collections.ArrayList
  4063. [void]$out.Add($parts[0])
  4064. for ($i = 1; $i -lt $parts.Count; $i++) {
  4065. $p = $parts[$i]
  4066. if ($p.Length -gt 1 -and $p -ceq $p.ToUpper()) {
  4067. [void]$out.Add($p)
  4068. } else {
  4069. [void]$out.Add($p.ToLower())
  4070. }
  4071. }
  4072. return ($out -join ' ')
  4073. }
  4074. function Emit-Title {
  4075. # Нет ключа title → авто-вывод из имени (помощь модели).
  4076. # Явный title: "" (или null) → подавить (заголовок не эмитим).
  4077. # Явный непустой → эмитим как есть.
  4078. param($el, [string]$name, [string]$indent, [switch]$auto)
  4079. $hasKey = $null -ne $el.PSObject.Properties['title']
  4080. if ($hasKey) {
  4081. if ($el.title) { Emit-MLText -tag "Title" -text $el.title -indent $indent }
  4082. } elseif ($auto -and $name) {
  4083. Emit-MLText -tag "Title" -text (Title-FromName -name $name) -indent $indent
  4084. }
  4085. # ToolTip элемента (всплывающая подсказка) — по схеме сразу после Title.
  4086. if ($el.tooltip) { Emit-MLText -tag "ToolTip" -text $el.tooltip -indent $indent }
  4087. # ToolTipRepresentation — режим показа подсказки (None/Button/ShowBottom/…), после ToolTip.
  4088. if ($el.tooltipRepresentation) { X "$indent<ToolTipRepresentation>$($el.tooltipRepresentation)</ToolTipRepresentation>" }
  4089. }
  4090. function Map-TitleLoc {
  4091. param([string]$v)
  4092. switch ("$v".ToLower()) {
  4093. "none" { "None" }
  4094. "left" { "Left" }
  4095. "right" { "Right" }
  4096. "top" { "Top" }
  4097. "bottom" { "Bottom" }
  4098. "auto" { "Auto" }
  4099. default { "$v" }
  4100. }
  4101. }
  4102. function Emit-TitleLocation {
  4103. param($el, [string]$indent, [string]$smartDefault)
  4104. if ($null -ne $el.PSObject.Properties['titleLocation']) {
  4105. if ($el.titleLocation) { X "$indent<TitleLocation>$(Map-TitleLoc "$($el.titleLocation)")</TitleLocation>" }
  4106. } elseif ($smartDefault) {
  4107. X "$indent<TitleLocation>$smartDefault</TitleLocation>"
  4108. }
  4109. }
  4110. function Warn-Unrecognized {
  4111. # drop-on-miss enum: значение не распознано → тег не эмитится. Громко, чтобы автор увидел потерю.
  4112. param([string]$key, $raw, [string[]]$valid, [string]$owner)
  4113. Write-Warning "Unrecognized $key '$raw' on '$owner'. Valid values: $($valid -join ', '). Value ignored."
  4114. }
  4115. function Emit-Group {
  4116. param($el, [string]$name, [int]$id, [string]$indent)
  4117. X "$indent<UsualGroup name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  4118. $inner = "$indent`t"
  4119. Emit-Title -el $el -name $name -indent $inner
  4120. # Group orientation (направление). Legacy: group:'collapsible' = Vertical + behavior collapsible.
  4121. $groupVal = "$($el.group)".ToLower()
  4122. $orientation = switch ($groupVal) {
  4123. "horizontal" { "Horizontal" }
  4124. "vertical" { "Vertical" }
  4125. "alwayshorizontal" { "AlwaysHorizontal" }
  4126. "alwaysvertical" { "Vertical" } # старое написание; у группы такого значения нет
  4127. "horizontalifpossible" { "HorizontalIfPossible" }
  4128. "collapsible" { "Vertical" }
  4129. default { $null }
  4130. }
  4131. if ($orientation) { X "$inner<Group>$orientation</Group>" }
  4132. elseif ($groupVal) { Warn-Unrecognized 'group orientation' $el.group @('vertical','horizontalIfPossible','alwaysHorizontal') $name }
  4133. # Behavior: ключ behavior (usual/collapsible/popup) → <Behavior>; отсутствие = Авто (не эмитим).
  4134. # Legacy: group:'collapsible' эквивалентно behavior:'collapsible'.
  4135. $behaviorVal = if ($el.behavior) { "$($el.behavior)".ToLower() } elseif ($groupVal -eq "collapsible") { "collapsible" } else { $null }
  4136. $bmap = @{ "usual"="Usual"; "collapsible"="Collapsible"; "popup"="PopUp" }
  4137. if ($behaviorVal -and $bmap.ContainsKey($behaviorVal)) {
  4138. X "$inner<Behavior>$($bmap[$behaviorVal])</Behavior>"
  4139. } elseif ($el.behavior -and -not $bmap.ContainsKey($behaviorVal)) {
  4140. Warn-Unrecognized 'behavior' $el.behavior @('collapsible','popup') $name
  4141. }
  4142. # Collapsed — у Collapsible и PopUp (не привязано к одному behavior)
  4143. if ((Get-DslBool $el @('collapsed') $false)) { X "$inner<Collapsed>true</Collapsed>" }
  4144. # Representation
  4145. if ($el.representation) {
  4146. $repr = switch ("$($el.representation)") {
  4147. "none" { "None" }
  4148. "normal" { "NormalSeparation" }
  4149. "weak" { "WeakSeparation" }
  4150. "strong" { "StrongSeparation" }
  4151. default { "$($el.representation)" }
  4152. }
  4153. X "$inner<Representation>$repr</Representation>"
  4154. }
  4155. # Использование текущей строки группы (после Representation, порядок XSD)
  4156. if ($el.currentRowUse) { X "$inner<CurrentRowUse>$($el.currentRowUse)</CurrentRowUse>" }
  4157. # ShowTitle
  4158. # Обычная группа без showTitle: заголовок показан, если он задан (title или titleDataPath), иначе скрыт — служебная группа
  4159. # раскладки без заголовка давала бы пустую строку-заголовок (умолчание платформы — показан).
  4160. # У сворачиваемой/всплывающей заголовок — переключатель: умолчание платформы, пишется лишь явный false.
  4161. if (@('collapsible','popup') -contains $behaviorVal) {
  4162. if ($null -ne $el.showTitle -and -not $el.showTitle) { X "$inner<ShowTitle>false</ShowTitle>" }
  4163. } elseif ($null -ne $el.showTitle) {
  4164. if (-not ((Get-DslBool $el @('showTitle') $false))) { X "$inner<ShowTitle>false</ShowTitle>" }
  4165. } elseif (-not $el.title -and -not $el.titleDataPath) { X "$inner<ShowTitle>false</ShowTitle>" }
  4166. # Заголовок свёрнутого представления (collapsible/popup) — мультиязычный текст
  4167. if ($el.collapsedTitle) { Emit-MLText -tag "CollapsedRepresentationTitle" -text $el.collapsedTitle -indent $inner }
  4168. # United
  4169. if ((-not (Get-DslBool $el @('united') $true))) { X "$inner<United>false</United>" }
  4170. # Формат значения пути к данным заголовка (<Format>; парный к titleDataPath группы)
  4171. if ($el.format) { Emit-MLText -tag "Format" -text $el.format -indent $inner }
  4172. if ($el.editFormat) { Emit-MLText -tag "EditFormat" -text $el.editFormat -indent $inner }
  4173. Emit-CommonFlags -el $el -indent $inner
  4174. Emit-Layout -el $el -indent $inner
  4175. # Оформление (цвета/шрифты/граница) — перед компаньоном
  4176. Emit-Appearance -el $el -indent $inner -profile 'field'
  4177. # Companion: ExtendedTooltip
  4178. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  4179. Emit-Events -el $el -elementName $name -indent $inner -xmlTag "UsualGroup"
  4180. # Children
  4181. if ($el.children -and $el.children.Count -gt 0) {
  4182. X "$inner<ChildItems>"
  4183. foreach ($child in $el.children) {
  4184. Emit-Element -el $child -indent "$inner`t"
  4185. }
  4186. X "$inner</ChildItems>"
  4187. }
  4188. X "$indent</UsualGroup>"
  4189. }
  4190. function Emit-ColumnGroup {
  4191. param($el, [string]$name, [int]$id, [string]$indent)
  4192. X "$indent<ColumnGroup name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  4193. $inner = "$indent`t"
  4194. Warn-EventsIgnored $el "ColumnGroup" $name
  4195. Emit-Title -el $el -name $name -indent $inner
  4196. # Group orientation (horizontal / vertical / inCell — последнее только здесь)
  4197. $groupVal = "$($el.columnGroup)"
  4198. $orientation = switch ($groupVal) {
  4199. "horizontal" { "Horizontal" }
  4200. "vertical" { "Vertical" }
  4201. "inCell" { "InCell" }
  4202. default { $null }
  4203. }
  4204. if ($orientation) { X "$inner<Group>$orientation</Group>" }
  4205. elseif ($groupVal) { Warn-Unrecognized 'columnGroup orientation' $el.columnGroup @('vertical','horizontal','inCell') $name }
  4206. # ShowTitle=true — умолчание платформы (в корпусе только false): пишем лишь false
  4207. if ($null -ne $el.showTitle -and -not $el.showTitle) { X "$inner<ShowTitle>false</ShowTitle>" }
  4208. # showInHeader эмитится общим Emit-CommonElementProps (через Emit-Layout)
  4209. Emit-CommonFlags -el $el -indent $inner
  4210. Emit-Layout -el $el -indent $inner
  4211. # Картинка заголовка колонки-группы (после ShowInHeader/Layout, перед оформлением — порядок XSD)
  4212. Emit-ColumnPics -el $el -indent $inner
  4213. # Оформление (цвета/шрифты/граница) — перед компаньоном
  4214. Emit-Appearance -el $el -indent $inner -profile 'field'
  4215. # Companion: ExtendedTooltip
  4216. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  4217. # Children
  4218. if ($el.children -and $el.children.Count -gt 0) {
  4219. X "$inner<ChildItems>"
  4220. foreach ($child in $el.children) {
  4221. Emit-Element -el $child -indent "$inner`t"
  4222. }
  4223. X "$inner</ChildItems>"
  4224. }
  4225. X "$indent</ColumnGroup>"
  4226. }
  4227. function Emit-Input {
  4228. param($el, [string]$name, [int]$id, [string]$indent)
  4229. X "$indent<InputField name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  4230. $inner = "$indent`t"
  4231. if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
  4232. Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
  4233. Emit-CommonFlags -el $el -indent $inner
  4234. if ($el.titleLocation) { X "$inner<TitleLocation>$(Map-TitleLoc "$($el.titleLocation)")</TitleLocation>" }
  4235. if ($null -ne $el.multiLine) { X "$inner<MultiLine>$(if ($el.multiLine){'true'}else{'false'})</MultiLine>" }
  4236. if ($null -ne $el.passwordMode) { X "$inner<PasswordMode>$(if ($el.passwordMode){'true'}else{'false'})</PasswordMode>" }
  4237. # ChoiceButton — захват «как есть» (платформа эмитит явное значение; ref-поля выводят сама,
  4238. # декомпилятор фиксирует факт. значение). Нет ключа → не эмитим (не додумываем по событию).
  4239. if ($null -ne $el.choiceButton) { X "$inner<ChoiceButton>$(if ($el.choiceButton){'true'}else{'false'})</ChoiceButton>" }
  4240. # Кнопки поля ввода — захват «как есть» (платформа эмитит явное значение, в т.ч. false)
  4241. if ($null -ne $el.clearButton) { X "$inner<ClearButton>$(if ($el.clearButton){'true'}else{'false'})</ClearButton>" }
  4242. if ($null -ne $el.spinButton) { X "$inner<SpinButton>$(if ($el.spinButton){'true'}else{'false'})</SpinButton>" }
  4243. if ($null -ne $el.dropListButton) { X "$inner<DropListButton>$(if ($el.dropListButton){'true'}else{'false'})</DropListButton>" }
  4244. if ($null -ne $el.choiceListButton) { X "$inner<ChoiceListButton>$(if ($el.choiceListButton){'true'}else{'false'})</ChoiceListButton>" }
  4245. if ($null -ne $el.markIncomplete) { X "$inner<AutoMarkIncomplete>$(if ($el.markIncomplete){'true'}else{'false'})</AutoMarkIncomplete>" }
  4246. if ($el.editMode) { X "$inner<EditMode>$($el.editMode)</EditMode>" }
  4247. Emit-ColumnPics -el $el -indent $inner
  4248. if ((-not (Get-DslBool $el @('textEdit') $true))) { X "$inner<TextEdit>false</TextEdit>" }
  4249. # InputField-специфичные скаляры (захват «как есть»: платформа эмитит явное не-дефолтное значение)
  4250. foreach ($p in @(
  4251. @('wrap','Wrap'), @('openButton','OpenButton'), @('listChoiceMode','ListChoiceMode'),
  4252. @('extendedEditMultipleValues','ExtendedEditMultipleValues'), @('chooseType','ChooseType'),
  4253. @('quickChoice','QuickChoice'), @('autoChoiceIncomplete','AutoChoiceIncomplete')
  4254. )) {
  4255. if ($null -ne $el.($p[0])) { X "$inner<$($p[1])>$(if ($el.($p[0])){'true'}else{'false'})</$($p[1])>" }
  4256. }
  4257. # Ограничение доступных типов (поле на составном типе): домен типов + явный набор.
  4258. # availableTypes — формат типа реквизита (§type); Emit-Type сам разбирает мультитип "a | b".
  4259. if ($null -ne $el.typeDomainEnabled) { X "$inner<TypeDomainEnabled>$(if ($el.typeDomainEnabled){'true'}else{'false'})</TypeDomainEnabled>" }
  4260. if ($el.availableTypes) { Emit-Type -typeStr $el.availableTypes -indent $inner -tag 'AvailableTypes' }
  4261. # InputField-специфичные value-скаляры
  4262. foreach ($p in @(
  4263. @('choiceForm','ChoiceForm'), @('choiceHistoryOnInput','ChoiceHistoryOnInput'),
  4264. @('choiceFoldersAndItems','ChoiceFoldersAndItems'), @('footerDataPath','FooterDataPath')
  4265. )) {
  4266. if ($el.($p[0])) { X "$inner<$($p[1])>$(Esc-XmlText "$($el.($p[0]))")</$($p[1])>" }
  4267. }
  4268. # MinValue/MaxValue — типизированное. JSON-число → xs:decimal, строка → xs:string (тип сохранён декомпилятором).
  4269. foreach ($p in @(@('minValue','MinValue'), @('maxValue','MaxValue'))) {
  4270. if ($null -ne $el.($p[0])) {
  4271. $mvt = if ($el.($p[0]) -is [string]) { 'xs:string' } else { 'xs:decimal' }
  4272. X "$inner<$($p[1]) xsi:type=`"$mvt`">$(Esc-XmlText "$($el.($p[0]))")</$($p[1])>"
  4273. }
  4274. }
  4275. if ($el.choiceButtonRepresentation) { X "$inner<ChoiceButtonRepresentation>$($el.choiceButtonRepresentation)</ChoiceButtonRepresentation>" }
  4276. Emit-PictureRef -val $el.choiceButtonPicture -picTag 'ChoiceButtonPicture' -indent $inner
  4277. Emit-Layout -el $el -indent $inner -multiLineDefault ([bool]((Get-DslBool $el @('multiLine') $false)))
  4278. if ($el.inputHint) {
  4279. Emit-MLText -tag "InputHint" -text $el.inputHint -indent $inner
  4280. }
  4281. if ($null -ne $el.warningOnEdit) { Emit-MLText -tag "WarningOnEdit" -text $el.warningOnEdit -indent $inner }
  4282. if ($null -ne $el.footerText) { Emit-MLText -tag "FooterText" -text $el.footerText -indent $inner }
  4283. # Формат / формат редактирования (LocalStringType — строка или {ru,en})
  4284. if ($el.format) { Emit-MLText -tag "Format" -text $el.format -indent $inner }
  4285. if ($el.editFormat) { Emit-MLText -tag "EditFormat" -text $el.editFormat -indent $inner }
  4286. Emit-ChoiceList -el $el -indent $inner
  4287. # Связи по типу / связи параметров выбора / параметры выбора
  4288. Emit-TypeLink -el $el -indent $inner
  4289. Emit-ChoiceParameterLinks -el $el -indent $inner
  4290. Emit-ChoiceParameters -el $el -indent $inner
  4291. # Оформление (цвета/шрифты/граница) — перед компаньонами
  4292. Emit-Appearance -el $el -indent $inner -profile 'field'
  4293. # Companions
  4294. Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
  4295. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  4296. Emit-Events -el $el -elementName $name -indent $inner -xmlTag "InputField"
  4297. X "$indent</InputField>"
  4298. }
  4299. function Emit-Check {
  4300. param($el, [string]$name, [int]$id, [string]$indent)
  4301. X "$indent<CheckBoxField name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  4302. $inner = "$indent`t"
  4303. if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
  4304. Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
  4305. Emit-CommonFlags -el $el -indent $inner
  4306. if ($el.editMode) { X "$inner<EditMode>$($el.editMode)</EditMode>" }
  4307. Emit-ColumnPics -el $el -indent $inner
  4308. # CheckBoxType: нет ключа → умный дефолт Auto; "" → подавить; значение → маппинг
  4309. if ($null -ne $el.PSObject.Properties['checkBoxType']) {
  4310. if ($el.checkBoxType) {
  4311. $cbt = switch ("$($el.checkBoxType)".ToLower()) { 'auto' {'Auto'} 'checkbox' {'CheckBox'} 'switcher' {'Switcher'} 'tumbler' {'Tumbler'} default {"$($el.checkBoxType)"} }
  4312. X "$inner<CheckBoxType>$cbt</CheckBoxType>"
  4313. }
  4314. } else { X "$inner<CheckBoxType>Auto</CheckBoxType>" }
  4315. Emit-TitleLocation -el $el -indent $inner -smartDefault "Right"
  4316. Emit-Layout -el $el -indent $inner
  4317. if ($null -ne $el.warningOnEdit) { Emit-MLText -tag "WarningOnEdit" -text $el.warningOnEdit -indent $inner }
  4318. # FooterDataPath / FooterText — общие cell-свойства колонки (как у input/labelField)
  4319. if ($el.footerDataPath) { X "$inner<FooterDataPath>$(Esc-XmlText "$($el.footerDataPath)")</FooterDataPath>" }
  4320. if ($null -ne $el.footerText) { Emit-MLText -tag "FooterText" -text $el.footerText -indent $inner }
  4321. # Формат / формат редактирования (LocalStringType — строка или {ru,en})
  4322. if ($el.format) { Emit-MLText -tag "Format" -text $el.format -indent $inner }
  4323. if ($el.editFormat) { Emit-MLText -tag "EditFormat" -text $el.editFormat -indent $inner }
  4324. # Оформление (цвета/шрифты/граница) — перед компаньонами
  4325. Emit-Appearance -el $el -indent $inner -profile 'field'
  4326. # Companions
  4327. Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
  4328. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  4329. Emit-Events -el $el -elementName $name -indent $inner -xmlTag "CheckBoxField"
  4330. X "$indent</CheckBoxField>"
  4331. }
  4332. function Normalize-MetaTypeRef {
  4333. param([string]$ref)
  4334. if ([string]::IsNullOrEmpty($ref)) { return $ref }
  4335. $dot = $ref.IndexOf('.')
  4336. if ($dot -lt 1) { return $ref }
  4337. $root = $ref.Substring(0, $dot)
  4338. if ($script:refRootSynonyms.ContainsKey($root)) {
  4339. return $script:refRootSynonyms[$root] + $ref.Substring($dot)
  4340. }
  4341. return $ref
  4342. }
  4343. function Normalize-ChoiceValue {
  4344. param($value)
  4345. # Booleans
  4346. if ($value -is [bool]) {
  4347. return @{ XsiType = "xs:boolean"; Text = if ($value) { "true" } else { "false" } }
  4348. }
  4349. # Numbers (int / decimal / double)
  4350. if ($value -is [int] -or $value -is [long] -or $value -is [double] -or $value -is [decimal]) {
  4351. return @{ XsiType = "xs:decimal"; Text = "$value" }
  4352. }
  4353. $s = "$value"
  4354. if ([string]::IsNullOrEmpty($s)) {
  4355. return @{ XsiType = "xs:string"; Text = "" }
  4356. }
  4357. # ISO datetime ("2020-01-01T00:00:00") → xs:dateTime
  4358. if ($s -match '^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$') {
  4359. return @{ XsiType = "xs:dateTime"; Text = $s }
  4360. }
  4361. # Raw-ссылка по GUID (метаданные.значение, оба GUID): "GUID.GUID" → xr:DesignTimeRef
  4362. # (всегда ссылка, не строка; named-ссылки Enum.X.Y детектятся ниже).
  4363. 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-]+$') {
  4364. return @{ XsiType = "xr:DesignTimeRef"; Text = $s }
  4365. }
  4366. # Try to detect typed reference path: "<Root>.<Type>[.<Member>.<Value>]"
  4367. $parts = $s -split '\.'
  4368. if ($parts.Count -ge 2) {
  4369. $root = $parts[0]
  4370. $canonRoot = $null
  4371. if ($script:refRootSynonyms.ContainsKey($root)) { $canonRoot = $script:refRootSynonyms[$root] }
  4372. elseif ($script:refRootSynonyms.Values -contains $root) { $canonRoot = $root }
  4373. if ($canonRoot) {
  4374. $typeName = $parts[1]
  4375. $normalized = $null
  4376. if ($canonRoot -eq "Enum") {
  4377. if ($parts.Count -eq 2) {
  4378. # "Enum.X" alone — not a value, treat as string
  4379. } elseif ($parts.Count -eq 3) {
  4380. # "Enum.X.Y" — insert .EnumValue. ("EmptyRef" — пустая ссылка, БЕЗ вставки)
  4381. if ($parts[2] -eq 'EmptyRef') { $normalized = "Enum.$typeName.EmptyRef" }
  4382. else { $normalized = "Enum.$typeName.EnumValue.$($parts[2])" }
  4383. } else {
  4384. # "Enum.X.<member>.Y..." — replace member with EnumValue (handles ЗначениеПеречисления too)
  4385. $member = $parts[2]
  4386. if ($script:enumValueSynonyms -contains $member) {
  4387. $rest = $parts[3..($parts.Count-1)] -join '.'
  4388. $normalized = "Enum.$typeName.EnumValue.$rest"
  4389. } else {
  4390. $rest = $parts[2..($parts.Count-1)] -join '.'
  4391. $normalized = "Enum.$typeName.EnumValue.$rest"
  4392. }
  4393. }
  4394. } else {
  4395. # Other ref roots: just translate root, keep tail as-is
  4396. if ($parts.Count -ge 3) {
  4397. $tail = $parts[1..($parts.Count-1)] -join '.'
  4398. $normalized = "$canonRoot.$tail"
  4399. }
  4400. }
  4401. if ($normalized) {
  4402. return @{ XsiType = "xr:DesignTimeRef"; Text = $normalized }
  4403. }
  4404. }
  4405. }
  4406. return @{ XsiType = "xs:string"; Text = $s }
  4407. }
  4408. function Emit-ChoicePresentation {
  4409. param($pres, [string]$indent)
  4410. if ($null -eq $pres -or ($pres -is [string] -and [string]::IsNullOrEmpty($pres))) {
  4411. X "$indent<Presentation/>"
  4412. return
  4413. }
  4414. $pairs = @()
  4415. if ($pres -is [string]) {
  4416. $pairs += ,@("ru", $pres)
  4417. } elseif ($pres -is [hashtable] -or $pres -is [System.Collections.IDictionary]) {
  4418. foreach ($k in $pres.Keys) { $pairs += ,@("$k", "$($pres[$k])") }
  4419. } elseif ($pres.PSObject -and $pres.PSObject.Properties) {
  4420. foreach ($p in $pres.PSObject.Properties) { $pairs += ,@("$($p.Name)", "$($p.Value)") }
  4421. } else {
  4422. $pairs += ,@("ru", "$pres")
  4423. }
  4424. X "$indent<Presentation>"
  4425. foreach ($pair in $pairs) {
  4426. X "$indent`t<v8:item>"
  4427. X "$indent`t`t<v8:lang>$($pair[0])</v8:lang>"
  4428. X "$indent`t`t<v8:content>$(Esc-XmlText $pair[1])</v8:content>"
  4429. X "$indent`t</v8:item>"
  4430. }
  4431. X "$indent</Presentation>"
  4432. }
  4433. function Get-ChoiceValueTag {
  4434. param($norm)
  4435. if ([string]::IsNullOrEmpty($norm.Text)) { return "<Value xsi:type=`"$($norm.XsiType)`"/>" }
  4436. return "<Value xsi:type=`"$($norm.XsiType)`">$(Esc-XmlText $norm.Text)</Value>"
  4437. }
  4438. function Emit-ChoiceList {
  4439. param($el, [string]$indent)
  4440. if (-not $el.choiceList -or $el.choiceList.Count -eq 0) { return }
  4441. X "$indent<ChoiceList>"
  4442. $itemIndent = "$indent`t"
  4443. foreach ($item in $el.choiceList) {
  4444. # value (+ рус. синоним "значение")
  4445. $valRaw = $null
  4446. if ($item -is [hashtable] -or $item -is [System.Collections.IDictionary]) {
  4447. if ($item.Contains("value")) { $valRaw = $item["value"] }
  4448. elseif ($item.Contains("значение")) { $valRaw = $item["значение"] }
  4449. } else {
  4450. if ($item.PSObject.Properties["value"]) { $valRaw = $item.value }
  4451. elseif ($item.PSObject.Properties["значение"]) { $valRaw = $item."значение" }
  4452. }
  4453. # presentation (presentation OR title синоним)
  4454. $presRaw = $null
  4455. $hasPres = $false
  4456. if ($item -is [hashtable] -or $item -is [System.Collections.IDictionary]) {
  4457. if ($item.Contains("presentation")) { $presRaw = $item["presentation"]; $hasPres = $true }
  4458. elseif ($item.Contains("представление")) { $presRaw = $item["представление"]; $hasPres = $true }
  4459. elseif ($item.Contains("title")) { $presRaw = $item["title"]; $hasPres = $true }
  4460. } else {
  4461. if ($item.PSObject.Properties["presentation"]) { $presRaw = $item.presentation; $hasPres = $true }
  4462. elseif ($item.PSObject.Properties["представление"]) { $presRaw = $item."представление"; $hasPres = $true }
  4463. elseif ($item.PSObject.Properties["title"]) { $presRaw = $item.title; $hasPres = $true }
  4464. }
  4465. # valueType: явный xsi:type значения (системное перечисление ent:*, иной не-примитив) —
  4466. # переопределяет авто-детект (Normalize-ChoiceValue вывела бы xs:string).
  4467. $vtRaw = $null
  4468. if ($item -is [hashtable] -or $item -is [System.Collections.IDictionary]) {
  4469. if ($item.Contains("valueType")) { $vtRaw = "$($item["valueType"])" }
  4470. } elseif ($item.PSObject.Properties["valueType"]) { $vtRaw = "$($item.valueType)" }
  4471. if ($vtRaw -eq 'nil') { $norm = @{ XsiType = $null; Text = $null; Nil = $true } }
  4472. elseif ($vtRaw) { $norm = @{ XsiType = $vtRaw; Text = "$valRaw" } }
  4473. else { $norm = Normalize-ChoiceValue -value $valRaw }
  4474. # авто-вывод presentation, если не задан
  4475. if (-not $hasPres) {
  4476. if ($norm.XsiType -eq "xr:DesignTimeRef") {
  4477. $tail = ($norm.Text -split '\.')[-1]
  4478. $presRaw = Title-FromName -name $tail
  4479. } else {
  4480. $presRaw = $norm.Text
  4481. }
  4482. }
  4483. X "$itemIndent<xr:Item>"
  4484. $valIndent = "$itemIndent`t"
  4485. X "$valIndent<xr:Presentation/>"
  4486. X "$valIndent<xr:CheckState>0</xr:CheckState>"
  4487. X "$valIndent<xr:Value xsi:type=`"FormChoiceListDesTimeValue`">"
  4488. Emit-ChoicePresentation -pres $presRaw -indent "$valIndent`t"
  4489. X "$valIndent`t$(if ($norm.Nil) { '<Value xsi:nil="true"/>' } else { Get-ChoiceValueTag $norm })"
  4490. X "$valIndent</xr:Value>"
  4491. X "$itemIndent</xr:Item>"
  4492. }
  4493. X "$indent</ChoiceList>"
  4494. }
  4495. function Get-ElProp {
  4496. param($obj, [string[]]$names)
  4497. if ($null -eq $obj) { return $null }
  4498. foreach ($n in $names) {
  4499. if ($obj -is [System.Collections.IDictionary]) {
  4500. if ($obj.Contains($n)) { return $obj[$n] }
  4501. } elseif ($obj.PSObject -and $obj.PSObject.Properties[$n]) {
  4502. return $obj.PSObject.Properties[$n].Value
  4503. }
  4504. }
  4505. return $null
  4506. }
  4507. function ConvertTo-ScalarLiteral {
  4508. param([string]$s)
  4509. $t = "$s".Trim()
  4510. if ($t -match '^(?i:true)$') { return $true }
  4511. if ($t -match '^(?i:false)$') { return $false }
  4512. if ($t -match '^-?\d+$') { return [int]$t }
  4513. if ($t -match '^-?\d+\.\d+$') { return [double]::Parse($t, [System.Globalization.CultureInfo]::InvariantCulture) }
  4514. return $t
  4515. }
  4516. function ConvertFrom-ChoiceParamShorthand {
  4517. param([string]$s)
  4518. $eq = $s.IndexOf('=')
  4519. if ($eq -lt 0) { return @{ name = $s.Trim() } }
  4520. $name = $s.Substring(0, $eq).Trim()
  4521. $rest = $s.Substring($eq + 1)
  4522. if ($rest -match ',') {
  4523. $vals = @()
  4524. foreach ($part in ($rest -split ',')) { $vals += ,(ConvertTo-ScalarLiteral $part) }
  4525. return @{ name = $name; value = $vals }
  4526. }
  4527. return @{ name = $name; value = (ConvertTo-ScalarLiteral $rest) }
  4528. }
  4529. function ConvertFrom-ChoiceParamLinkShorthand {
  4530. param([string]$s)
  4531. $eq = $s.IndexOf('=')
  4532. if ($eq -lt 0) { return @{ name = $s.Trim() } }
  4533. $o = @{ name = $s.Substring(0, $eq).Trim() }
  4534. $rest = $s.Substring($eq + 1).Trim()
  4535. if ($rest -match '^(.*):(?i:(Clear|DontChange|очистить|неизменять))$') {
  4536. $o['dataPath'] = $matches[1].Trim(); $o['valueChange'] = $matches[2]
  4537. } else {
  4538. $o['dataPath'] = $rest
  4539. }
  4540. return $o
  4541. }
  4542. function ConvertFrom-TypeLinkShorthand {
  4543. param([string]$s)
  4544. if ($s -match '^(.*)#(\d+)$') { return @{ dataPath = $matches[1].Trim(); linkItem = [int]$matches[2] } }
  4545. return @{ dataPath = "$s".Trim() }
  4546. }
  4547. function Emit-ChoiceParamValue {
  4548. # $isArray передаётся ЯВНО из вызывающего кода: PowerShell разворачивает одноэлементный массив
  4549. # при биндинге параметра ($value становится скаляром), поэтому определять массив тут — ненадёжно
  4550. # (1-элементный список `["X"]` эмитился бы скаляром вместо FixedArray). foreach по скаляру = 1 итерация.
  4551. param($value, [string]$indent, [bool]$isArray)
  4552. X "$indent<Presentation/>"
  4553. if ($isArray) {
  4554. X "$indent<Value xsi:type=`"v8:FixedArray`">"
  4555. foreach ($v in $value) {
  4556. $norm = Normalize-ChoiceValue -value $v
  4557. X "$indent`t<v8:Value xsi:type=`"FormChoiceListDesTimeValue`">"
  4558. X "$indent`t`t<Presentation/>"
  4559. X "$indent`t`t$(Get-ChoiceValueTag $norm)"
  4560. X "$indent`t</v8:Value>"
  4561. }
  4562. X "$indent</Value>"
  4563. } else {
  4564. $norm = Normalize-ChoiceValue -value $value
  4565. X "$indent$(Get-ChoiceValueTag $norm)"
  4566. }
  4567. }
  4568. function Emit-ChoiceParameters {
  4569. param($el, [string]$indent)
  4570. $cp = $el.choiceParameters
  4571. if (-not $cp -or @($cp).Count -eq 0) { return }
  4572. X "$indent<ChoiceParameters>"
  4573. foreach ($item in @($cp)) {
  4574. if ($item -is [string]) { $item = ConvertFrom-ChoiceParamShorthand $item }
  4575. $name = Get-ElProp $item @('name','имя')
  4576. # Наличие ключа value (≠ значения) + ПРЯМОЙ доступ к значению (без Get-ElProp): его return
  4577. # разворачивает 1-элементный массив (PS unwrap), теряя массив-ность → FixedArray не эмитится.
  4578. # Индексер/member-доступ массив сохраняет; if-выражение/функция-return — нет.
  4579. $hasVal = $false; $val = $null
  4580. if ($item -is [System.Collections.IDictionary]) {
  4581. if ($item.Contains('value')) { $hasVal = $true; $val = $item['value'] }
  4582. elseif ($item.Contains('значение')) { $hasVal = $true; $val = $item['значение'] }
  4583. } else {
  4584. if ($item.PSObject.Properties['value']) { $hasVal = $true; $val = $item.PSObject.Properties['value'].Value }
  4585. elseif ($item.PSObject.Properties['значение']) { $hasVal = $true; $val = $item.PSObject.Properties['значение'].Value }
  4586. }
  4587. $valIsArray = ($val -is [System.Array]) -or ($val -is [System.Collections.IList] -and $val -isnot [string])
  4588. X "$indent`t<app:item name=`"$(Esc-Xml "$name")`">"
  4589. # Параметр выбора без значения → <app:value xsi:nil="true"/> (платформа, 13 в корпусе);
  4590. # со значением (в т.ч. пустой строкой) → FormChoiceListDesTimeValue.
  4591. if (-not $hasVal) {
  4592. X "$indent`t`t<app:value xsi:nil=`"true`"/>"
  4593. } else {
  4594. X "$indent`t`t<app:value xsi:type=`"FormChoiceListDesTimeValue`">"
  4595. Emit-ChoiceParamValue -value $val -indent "$indent`t`t`t" -isArray $valIsArray
  4596. X "$indent`t`t</app:value>"
  4597. }
  4598. X "$indent`t</app:item>"
  4599. }
  4600. X "$indent</ChoiceParameters>"
  4601. }
  4602. function Emit-ChoiceParameterLinks {
  4603. param($el, [string]$indent)
  4604. $cpl = $el.choiceParameterLinks
  4605. if (-not $cpl -or @($cpl).Count -eq 0) { return }
  4606. X "$indent<ChoiceParameterLinks>"
  4607. foreach ($lk in @($cpl)) {
  4608. if ($lk -is [string]) { $lk = ConvertFrom-ChoiceParamLinkShorthand $lk }
  4609. $name = Get-ElProp $lk @('name','имя')
  4610. $dp = Get-ElProp $lk @('dataPath','path','путь')
  4611. $vcRaw = Get-ElProp $lk @('valueChange','режимИзменения')
  4612. $vc = "Clear"
  4613. if ($vcRaw) {
  4614. $vc = switch -Regex ("$vcRaw".ToLower()) {
  4615. '^(clear|очистить|очистка)$' { "Clear"; break }
  4616. '^(dontchange|неизменять|неменять|нет)$' { "DontChange"; break }
  4617. default { "$vcRaw" }
  4618. }
  4619. }
  4620. X "$indent`t<xr:Link>"
  4621. X "$indent`t`t<xr:Name>$(Esc-XmlText "$name")</xr:Name>"
  4622. X "$indent`t`t<xr:DataPath xsi:type=`"xs:string`">$(Esc-XmlText "$dp")</xr:DataPath>"
  4623. X "$indent`t`t<xr:ValueChange>$vc</xr:ValueChange>"
  4624. X "$indent`t</xr:Link>"
  4625. }
  4626. X "$indent</ChoiceParameterLinks>"
  4627. }
  4628. function Emit-TypeLink {
  4629. param($el, [string]$indent)
  4630. $tl = $el.typeLink
  4631. if (-not $tl) { return }
  4632. if ($tl -is [string]) { $tl = ConvertFrom-TypeLinkShorthand $tl }
  4633. $dp = Get-ElProp $tl @('dataPath','path','путь')
  4634. $li = Get-ElProp $tl @('linkItem','элементСвязи')
  4635. if ($null -eq $li) { $li = 0 }
  4636. X "$indent<TypeLink>"
  4637. X "$indent`t<xr:DataPath>$(Esc-XmlText "$dp")</xr:DataPath>"
  4638. X "$indent`t<xr:LinkItem>$li</xr:LinkItem>"
  4639. X "$indent</TypeLink>"
  4640. }
  4641. function Emit-Radio {
  4642. param($el, [string]$name, [int]$id, [string]$indent)
  4643. X "$indent<RadioButtonField name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  4644. $inner = "$indent`t"
  4645. if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
  4646. Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
  4647. Emit-CommonFlags -el $el -indent $inner
  4648. if ($el.editMode) { X "$inner<EditMode>$($el.editMode)</EditMode>" }
  4649. Emit-TitleLocation -el $el -indent $inner -smartDefault "None"
  4650. # RadioButtonType: Auto | RadioButtons | Tumbler. Accept synonyms.
  4651. $rbtRaw = if ($el.radioButtonType) { "$($el.radioButtonType)".Trim() } else { "Auto" }
  4652. $rbt = switch -Regex ($rbtRaw.ToLower()) {
  4653. '^(auto|авто)$' { "Auto"; break }
  4654. '^(radiobuttons?|переключатель|радио)$' { "RadioButtons"; break }
  4655. '^(tumbler|тумблер)$' { "Tumbler"; break }
  4656. default { $rbtRaw }
  4657. }
  4658. X "$inner<RadioButtonType>$rbt</RadioButtonType>"
  4659. if ($null -ne $el.columnsCount) {
  4660. X "$inner<ColumnsCount>$($el.columnsCount)</ColumnsCount>"
  4661. }
  4662. Emit-ChoiceList -el $el -indent $inner
  4663. Emit-Layout -el $el -indent $inner
  4664. if ($null -ne $el.warningOnEdit) { Emit-MLText -tag "WarningOnEdit" -text $el.warningOnEdit -indent $inner }
  4665. # Оформление (цвета/шрифты/граница) — перед компаньонами
  4666. Emit-Appearance -el $el -indent $inner -profile 'field'
  4667. # Companions
  4668. Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
  4669. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  4670. Emit-Events -el $el -elementName $name -indent $inner -xmlTag "RadioButtonField"
  4671. X "$indent</RadioButtonField>"
  4672. }
  4673. function Emit-DecorationTitle {
  4674. param($el, [string]$name, [string]$indent, [switch]$auto)
  4675. $hasKey = $null -ne $el.PSObject.Properties['title']
  4676. $titleVal = if ($hasKey) { $el.title } elseif ($auto -and $name) { Title-FromName -name $name } else { $null }
  4677. if ($titleVal) {
  4678. $r = Resolve-MLFormatted $titleVal
  4679. $fmt = if ($null -ne $el.PSObject.Properties['formatted']) { (ConvertTo-DslBool $el.formatted 'formatted' $false) } else { $r.formatted }
  4680. X "$indent<Title formatted=`"$(if ($fmt) { 'true' } else { 'false' })`">"
  4681. Emit-MLItems -val $r.text -indent "$indent`t"
  4682. X "$indent</Title>"
  4683. }
  4684. if ($el.tooltip) { Emit-MLText -tag "ToolTip" -text $el.tooltip -indent $indent }
  4685. if ($el.tooltipRepresentation) { X "$indent<ToolTipRepresentation>$($el.tooltipRepresentation)</ToolTipRepresentation>" }
  4686. }
  4687. function Emit-Label {
  4688. param($el, [string]$name, [int]$id, [string]$indent)
  4689. X "$indent<LabelDecoration name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  4690. $inner = "$indent`t"
  4691. # Порядок как у платформы: own-content (флаги/hyperlink/layout/оформление) ПЕРЕД Title
  4692. # (корпус layout-first 16970 vs 44 — заодно убирает шум атрибуции харнесса на многострочном Title).
  4693. Emit-CommonFlags -el $el -indent $inner
  4694. if ((Get-DslBool $el @('hyperlink') $false)) { X "$inner<Hyperlink>true</Hyperlink>" }
  4695. Emit-Layout -el $el -indent $inner
  4696. Emit-Appearance -el $el -indent $inner -profile 'decoration'
  4697. Emit-DecorationTitle -el $el -name $name -indent $inner -auto
  4698. # Companions
  4699. Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
  4700. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  4701. Emit-Events -el $el -elementName $name -indent $inner -xmlTag "LabelDecoration"
  4702. X "$indent</LabelDecoration>"
  4703. }
  4704. function Emit-LabelField {
  4705. param($el, [string]$name, [int]$id, [string]$indent)
  4706. X "$indent<LabelField name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  4707. $inner = "$indent`t"
  4708. if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
  4709. Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
  4710. Emit-CommonFlags -el $el -indent $inner
  4711. if ($el.titleLocation) { X "$inner<TitleLocation>$(Map-TitleLoc "$($el.titleLocation)")</TitleLocation>" }
  4712. if ($el.editMode) { X "$inner<EditMode>$($el.editMode)</EditMode>" }
  4713. # FooterDataPath — путь данных подвала колонки (общий cell-prop, как у input); после EditMode
  4714. if ($el.footerDataPath) { X "$inner<FooterDataPath>$(Esc-XmlText "$($el.footerDataPath)")</FooterDataPath>" }
  4715. # PasswordMode на LabelField — платформа эмитит явный false (редко); факт. значение
  4716. if ($null -ne $el.passwordMode) { X "$inner<PasswordMode>$(if ($el.passwordMode){'true'}else{'false'})</PasswordMode>" }
  4717. Emit-ColumnPics -el $el -indent $inner
  4718. # ВНИМАНИЕ: у LabelField платформенный тег именно <Hiperlink> (опечатка 1С), не <Hyperlink>.
  4719. if ((Get-DslBool $el @('hyperlink') $false)) { X "$inner<Hiperlink>true</Hiperlink>" }
  4720. Emit-Layout -el $el -indent $inner
  4721. if ($null -ne $el.warningOnEdit) { Emit-MLText -tag "WarningOnEdit" -text $el.warningOnEdit -indent $inner }
  4722. if ($null -ne $el.footerText) { Emit-MLText -tag "FooterText" -text $el.footerText -indent $inner }
  4723. # Формат / формат редактирования (LocalStringType — строка или {ru,en})
  4724. if ($el.format) { Emit-MLText -tag "Format" -text $el.format -indent $inner }
  4725. if ($el.editFormat) { Emit-MLText -tag "EditFormat" -text $el.editFormat -indent $inner }
  4726. # Оформление (цвета/шрифты/граница + header/footer) — перед компаньонами
  4727. Emit-Appearance -el $el -indent $inner -profile 'field'
  4728. # Companions
  4729. Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
  4730. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  4731. Emit-Events -el $el -elementName $name -indent $inner -xmlTag "LabelField"
  4732. X "$indent</LabelField>"
  4733. }
  4734. function Emit-DynListTableBlock {
  4735. param($el, [string]$indent)
  4736. # (useAlternationRowColor — общее свойство таблицы, эмитится в Emit-Table)
  4737. # Group A (гарант. блок, n=5079): дефолт + override
  4738. $ar = if ((Get-DslBool $el @('autoRefresh') $false)) { "true" } else { "false" }
  4739. X "$indent<AutoRefresh>$ar</AutoRefresh>"
  4740. $arp = if ($el.PSObject.Properties["autoRefreshPeriod"] -and $null -ne $el.autoRefreshPeriod) { $el.autoRefreshPeriod } else { 60 }
  4741. X "$indent<AutoRefreshPeriod>$arp</AutoRefreshPeriod>"
  4742. X "$indent<Period>"
  4743. X "$indent`t<v8:variant xsi:type=`"v8:StandardPeriodVariant`">Custom</v8:variant>"
  4744. X "$indent`t<v8:startDate>0001-01-01T00:00:00</v8:startDate>"
  4745. X "$indent`t<v8:endDate>0001-01-01T00:00:00</v8:endDate>"
  4746. X "$indent</Period>"
  4747. $cfi = if ($el.choiceFoldersAndItems) { $el.choiceFoldersAndItems } else { "Items" }
  4748. X "$indent<ChoiceFoldersAndItems>$cfi</ChoiceFoldersAndItems>"
  4749. $rcr = if ((Get-DslBool $el @('restoreCurrentRow') $false)) { "true" } else { "false" }
  4750. X "$indent<RestoreCurrentRow>$rcr</RestoreCurrentRow>"
  4751. X "$indent<TopLevelParent xsi:nil=`"true`"/>"
  4752. $sr = if ((-not (Get-DslBool $el @('showRoot') $true))) { "false" } else { "true" }
  4753. X "$indent<ShowRoot>$sr</ShowRoot>"
  4754. $arc = if ((Get-DslBool $el @('allowRootChoice') $false)) { "true" } else { "false" }
  4755. X "$indent<AllowRootChoice>$arc</AllowRootChoice>"
  4756. $uodc = if ($el.updateOnDataChange) { $el.updateOnDataChange } else { "Auto" }
  4757. X "$indent<UpdateOnDataChange>$uodc</UpdateOnDataChange>"
  4758. if ($el.userSettingsGroup) { X "$indent<UserSettingsGroup>$($el.userSettingsGroup)</UserSettingsGroup>" }
  4759. $agcru = if ((-not (Get-DslBool $el @('allowGettingCurrentRowURL') $true))) { "false" } else { "true" }
  4760. X "$indent<AllowGettingCurrentRowURL>$agcru</AllowGettingCurrentRowURL>"
  4761. }
  4762. function Emit-Table {
  4763. param($el, [string]$name, [int]$id, [string]$indent)
  4764. $script:currentTableName = $name # дефолт source для кастомных дополнений в commandBar
  4765. X "$indent<Table name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  4766. $inner = "$indent`t"
  4767. if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
  4768. Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
  4769. Emit-CommonFlags -el $el -indent $inner
  4770. if ($el.representation) {
  4771. X "$inner<Representation>$($el.representation)</Representation>"
  4772. }
  4773. if ($el.titleLocation) { X "$inner<TitleLocation>$(Map-TitleLoc "$($el.titleLocation)")</TitleLocation>" }
  4774. # ChangeRowSet/Order — эмитим явное значение (в т.ч. false: платформа пишет его на ValueTable)
  4775. if ($el.PSObject.Properties['changeRowSet'] -and $null -ne $el.changeRowSet) {
  4776. X "$inner<ChangeRowSet>$(if ((Get-DslBool $el @('changeRowSet') $false)){'true'}else{'false'})</ChangeRowSet>"
  4777. }
  4778. if ($el.PSObject.Properties['changeRowOrder'] -and $null -ne $el.changeRowOrder) {
  4779. X "$inner<ChangeRowOrder>$(if ((Get-DslBool $el @('changeRowOrder') $false)){'true'}else{'false'})</ChangeRowOrder>"
  4780. }
  4781. if ((Get-DslBool $el @('autoInsertNewRow') $false)) { X "$inner<AutoInsertNewRow>true</AutoInsertNewRow>" }
  4782. # RowFilter — nil-плейсхолдер (всегда пустой); ключ присутствует → эмитим
  4783. if ($el.PSObject.Properties['rowFilter']) { X "$inner<RowFilter xsi:nil=`"true`"/>" }
  4784. # Высота в строках таблицы (<HeightInTableRows>) — отдельное свойство от <Height> (высота элемента,
  4785. # эмитится generic-ом Emit-Layout ниже). Таблица может нести оба (237 в корпусе).
  4786. if ($el.heightInTableRows) { X "$inner<HeightInTableRows>$($el.heightInTableRows)</HeightInTableRows>" }
  4787. if ((-not (Get-DslBool $el @('header') $true))) { X "$inner<Header>false</Header>" }
  4788. if ((Get-DslBool $el @('footer') $false)) { X "$inner<Footer>true</Footer>" }
  4789. if ($el.commandBarLocation) {
  4790. X "$inner<CommandBarLocation>$($el.commandBarLocation)</CommandBarLocation>"
  4791. }
  4792. if ($el.searchStringLocation) {
  4793. X "$inner<SearchStringLocation>$($el.searchStringLocation)</SearchStringLocation>"
  4794. }
  4795. if ((Get-DslBool $el @('choiceMode') $false)) { X "$inner<ChoiceMode>true</ChoiceMode>" }
  4796. # Скаляры таблицы (захват «как есть»). Autofill — СВОЁ свойство таблицы (≠ AutoCommandBar autofill = tableAutofill).
  4797. if ($null -ne $el.autofill) { X "$inner<Autofill>$(if ($el.autofill){'true'}else{'false'})</Autofill>" }
  4798. if ((Get-DslBool $el @('multipleChoice') $false)) { X "$inner<MultipleChoice>true</MultipleChoice>" }
  4799. if ($el.searchOnInput) { X "$inner<SearchOnInput>$($el.searchOnInput)</SearchOnInput>" }
  4800. if ($null -ne $el.markIncomplete) { X "$inner<AutoMarkIncomplete>$(if ($el.markIncomplete){'true'}else{'false'})</AutoMarkIncomplete>" }
  4801. # Высота шапки/подвала в строках (pass-through; 1С толерантна к порядку детей Table)
  4802. if ($null -ne $el.headerHeight) { X "$inner<HeaderHeight>$($el.headerHeight)</HeaderHeight>" }
  4803. if ($null -ne $el.footerHeight) { X "$inner<FooterHeight>$($el.footerHeight)</FooterHeight>" }
  4804. if ((Get-DslBool $el @('useAlternationRowColor') $false)) { X "$inner<UseAlternationRowColor>true</UseAlternationRowColor>" }
  4805. if ($el.selectionMode) { X "$inner<SelectionMode>$($el.selectionMode)</SelectionMode>" }
  4806. if ($el.rowSelectionMode) { X "$inner<RowSelectionMode>$($el.rowSelectionMode)</RowSelectionMode>" }
  4807. if ((-not (Get-DslBool $el @('verticalLines') $true))) { X "$inner<VerticalLines>false</VerticalLines>" }
  4808. if ((-not (Get-DslBool $el @('horizontalLines') $true))) { X "$inner<HorizontalLines>false</HorizontalLines>" }
  4809. if ($el.initialTreeView) { X "$inner<InitialTreeView>$($el.initialTreeView)</InitialTreeView>" }
  4810. if ($null -ne $el.enableDrag) { X "$inner<EnableDrag>$(if ($el.enableDrag){'true'}else{'false'})</EnableDrag>" }
  4811. if ($el.rowPictureDataPath) { X "$inner<RowPictureDataPath>$($el.rowPictureDataPath)</RowPictureDataPath>" }
  4812. # RowsPicture — та же конвенция, что ValuesPicture (дефолт LoadTransparent=false; abs/TransparentPixel)
  4813. Emit-PictureRef -val $el.rowsPicture -picTag 'RowsPicture' -indent $inner
  4814. # Использование текущей строки таблицы (pass-through; в корпусе соседствует с блоком дин-списка)
  4815. if ($el.currentRowUse) { X "$inner<CurrentRowUse>$($el.currentRowUse)</CurrentRowUse>" }
  4816. # Запрос обновления дин-списка (pass-through; в корпусе всегда PullFromTop)
  4817. if ($el.refreshRequest) { X "$inner<RefreshRequest>$($el.refreshRequest)</RefreshRequest>" }
  4818. # Блок свойств дин-список-таблицы (помечена эвристикой 11b.4)
  4819. if ($el.PSObject.Properties["_dynList"] -and $el._dynList) { Emit-DynListTableBlock -el $el -indent $inner }
  4820. if ($el.viewStatusLocation) { X "$inner<ViewStatusLocation>$($el.viewStatusLocation)</ViewStatusLocation>" }
  4821. if ($el.searchControlLocation) { X "$inner<SearchControlLocation>$($el.searchControlLocation)</SearchControlLocation>" }
  4822. Emit-Layout -el $el -indent $inner
  4823. # CommandSet таблицы эмитится через Emit-Layout (общий механизм поля)
  4824. # Оформление (цвета/граница таблицы) — перед компаньонами
  4825. Emit-Appearance -el $el -indent $inner -profile 'field'
  4826. # Companions
  4827. Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
  4828. # AutoCommandBar: приоритет commandBar-свойства (контент); иначе tableAutofill-shorthand; иначе пусто.
  4829. if ($null -ne $el.commandBar) {
  4830. Emit-CompanionPanel -tag "AutoCommandBar" -name "${name}КоманднаяПанель" -indent $inner -panel $el.commandBar
  4831. } elseif ($null -ne $el.tableAutofill) {
  4832. $acbId = New-Id
  4833. X "$inner<AutoCommandBar name=`"${name}КоманднаяПанель`" id=`"$acbId`">"
  4834. $afVal = if ($el.tableAutofill) { "true" } else { "false" }
  4835. X "$inner`t<Autofill>$afVal</Autofill>"
  4836. X "$inner</AutoCommandBar>"
  4837. } else {
  4838. Emit-Companion -tag "AutoCommandBar" -name "${name}КоманднаяПанель" -indent $inner
  4839. }
  4840. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  4841. $adds = $el.additions
  4842. Emit-TableAddition -typeKey 'searchString' -tableName $name -indent $inner -override (Get-AdditionOverride $adds 'searchString')
  4843. Emit-TableAddition -typeKey 'viewStatus' -tableName $name -indent $inner -override (Get-AdditionOverride $adds 'viewStatus')
  4844. Emit-TableAddition -typeKey 'searchControl' -tableName $name -indent $inner -override (Get-AdditionOverride $adds 'searchControl')
  4845. # Columns
  4846. if ($el.columns -and $el.columns.Count -gt 0) {
  4847. X "$inner<ChildItems>"
  4848. $prevTable = $script:handlerTable; $script:handlerTable = $name
  4849. foreach ($col in $el.columns) {
  4850. Emit-Element -el $col -indent "$inner`t"
  4851. }
  4852. $script:handlerTable = $prevTable
  4853. X "$inner</ChildItems>"
  4854. }
  4855. Emit-Events -el $el -elementName $name -indent $inner -xmlTag "Table" -source (Get-TableSource $el)
  4856. X "$indent</Table>"
  4857. }
  4858. function Emit-Pages {
  4859. param($el, [string]$name, [int]$id, [string]$indent)
  4860. X "$indent<Pages name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  4861. $inner = "$indent`t"
  4862. Emit-Title -el $el -name $name -indent $inner
  4863. if ($el.pagesRepresentation) {
  4864. X "$inner<PagesRepresentation>$($el.pagesRepresentation)</PagesRepresentation>"
  4865. }
  4866. # Использование текущей строки (после PagesRepresentation, порядок XSD)
  4867. if ($el.currentRowUse) { X "$inner<CurrentRowUse>$($el.currentRowUse)</CurrentRowUse>" }
  4868. Emit-CommonFlags -el $el -indent $inner
  4869. Emit-Layout -el $el -indent $inner
  4870. # Оформление (цвета/шрифты/граница) заголовка группы страниц — TitleFont/TitleTextColor/… (как у Page)
  4871. Emit-Appearance -el $el -indent $inner -profile 'field'
  4872. # Companion
  4873. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  4874. Emit-Events -el $el -elementName $name -indent $inner -xmlTag "Pages"
  4875. # Children (pages)
  4876. if ($el.children -and $el.children.Count -gt 0) {
  4877. X "$inner<ChildItems>"
  4878. foreach ($child in $el.children) {
  4879. Emit-Element -el $child -indent "$inner`t"
  4880. }
  4881. X "$inner</ChildItems>"
  4882. }
  4883. X "$indent</Pages>"
  4884. }
  4885. function Emit-Page {
  4886. param($el, [string]$name, [int]$id, [string]$indent)
  4887. X "$indent<Page name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  4888. $inner = "$indent`t"
  4889. Warn-EventsIgnored $el "Page" $name
  4890. Emit-Title -el $el -name $name -indent $inner -auto
  4891. Emit-CommonFlags -el $el -indent $inner
  4892. # Картинка страницы (иконка вкладки): после Title/флагов, перед Group (порядок XSD).
  4893. # Конвенция как у ValuesPicture (дефолт LoadTransparent=false): скаляр-Ref/'abs:X' или объект.
  4894. Emit-PictureRef -val $el.picture -picTag 'Picture' -indent $inner
  4895. if ($el.group) {
  4896. # Доступные значения страницы/обычной группы: Vertical / HorizontalIfPossible / AlwaysHorizontal
  4897. # (InCell — только у columnGroup). Horizontal и старое alwaysVertical (→ Vertical) — прощающий ввод.
  4898. $orientation = switch ("$($el.group)") {
  4899. "horizontal" { "Horizontal" }
  4900. "vertical" { "Vertical" }
  4901. "alwaysHorizontal" { "AlwaysHorizontal" }
  4902. "alwaysVertical" { "Vertical" } # старое написание; у страницы такого значения нет
  4903. "horizontalIfPossible" { "HorizontalIfPossible" }
  4904. default { $null }
  4905. }
  4906. if ($orientation) { X "$inner<Group>$orientation</Group>" }
  4907. else { Warn-Unrecognized 'page group orientation' $el.group @('vertical','horizontalIfPossible','alwaysHorizontal') $name }
  4908. }
  4909. # ShowTitle=true — умолчание платформы (в корпусе только false): пишем лишь false
  4910. if ($null -ne $el.showTitle -and -not $el.showTitle) { X "$inner<ShowTitle>false</ShowTitle>" }
  4911. # Формат значения пути к данным заголовка (<Format>; парный к titleDataPath страницы)
  4912. if ($el.format) { Emit-MLText -tag "Format" -text $el.format -indent $inner }
  4913. if ($el.editFormat) { Emit-MLText -tag "EditFormat" -text $el.editFormat -indent $inner }
  4914. Emit-Layout -el $el -indent $inner
  4915. # Оформление страницы (BackColor / TitleTextColor / TitleFont) — после ShowTitle, перед компаньоном
  4916. Emit-Appearance -el $el -indent $inner -profile 'field'
  4917. # Companion
  4918. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  4919. # Children
  4920. if ($el.children -and $el.children.Count -gt 0) {
  4921. X "$inner<ChildItems>"
  4922. foreach ($child in $el.children) {
  4923. Emit-Element -el $child -indent "$inner`t"
  4924. }
  4925. X "$inner</ChildItems>"
  4926. }
  4927. X "$indent</Page>"
  4928. }
  4929. function Emit-Button {
  4930. param($el, [string]$name, [int]$id, [string]$indent, [bool]$inCmdBar = $false)
  4931. X "$indent<Button name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  4932. $inner = "$indent`t"
  4933. # (общие свойства — через Emit-Layout ниже; отдельный вызов был бы двойной эмиссией)
  4934. # Type — context-aware:
  4935. # Inside command bar (cmdBar/autoCmdBar/popup) only CommandBarButton/CommandBarHyperlink are valid.
  4936. # UsualButton/Hyperlink would be silently ignored by 1C.
  4937. $btnType = $null
  4938. if ($el.type) {
  4939. $rawType = "$($el.type)"
  4940. if ($inCmdBar) {
  4941. # Be forgiving: any "ordinary button" hint resolves to CommandBarButton,
  4942. # any "hyperlink" hint resolves to CommandBarHyperlink. The model can pass
  4943. # either DSL ("usual"/"hyperlink") or XML names — all map to the right kind.
  4944. switch ($rawType) {
  4945. "usual" { $btnType = "CommandBarButton" }
  4946. "UsualButton" { $btnType = "CommandBarButton" }
  4947. "commandBar" { $btnType = "CommandBarButton" }
  4948. "CommandBarButton" { $btnType = "CommandBarButton" }
  4949. "hyperlink" { $btnType = "CommandBarHyperlink" }
  4950. "Hyperlink" { $btnType = "CommandBarHyperlink" }
  4951. "CommandBarHyperlink" { $btnType = "CommandBarHyperlink" }
  4952. default { $btnType = $rawType }
  4953. }
  4954. } else {
  4955. # Symmetric: any "ordinary button" hint → UsualButton, any "hyperlink" → Hyperlink.
  4956. switch ($rawType) {
  4957. "usual" { $btnType = "UsualButton" }
  4958. "UsualButton" { $btnType = "UsualButton" }
  4959. "commandBar" { $btnType = "UsualButton" }
  4960. "CommandBarButton" { $btnType = "UsualButton" }
  4961. "hyperlink" { $btnType = "Hyperlink" }
  4962. "Hyperlink" { $btnType = "Hyperlink" }
  4963. "CommandBarHyperlink" { $btnType = "Hyperlink" }
  4964. default { $btnType = $rawType }
  4965. }
  4966. }
  4967. } elseif ($inCmdBar) {
  4968. $btnType = "CommandBarButton"
  4969. }
  4970. if ($btnType) {
  4971. X "$inner<Type>$btnType</Type>"
  4972. }
  4973. # CommandName
  4974. if ($el.command) {
  4975. X "$inner<CommandName>Form.Command.$($el.command)</CommandName>"
  4976. }
  4977. # commandName — глобальная команда «как есть» (CommonCommand.X, Catalog.X.Command.Y …), без обёртки Form.
  4978. if ($el.commandName -and -not $el.command) {
  4979. X "$inner<CommandName>$($el.commandName)</CommandName>"
  4980. }
  4981. if ($el.stdCommand) {
  4982. $sc = "$($el.stdCommand)"
  4983. if ($sc -match '^(.+)\.(.+)$') {
  4984. X "$inner<CommandName>Form.Item.$($Matches[1]).StandardCommand.$($Matches[2])</CommandName>"
  4985. } else {
  4986. X "$inner<CommandName>Form.StandardCommand.$sc</CommandName>"
  4987. }
  4988. }
  4989. # Parameter команды (после CommandName): строка → xr:MDObjectRef (объект метаданных);
  4990. # объект {type} → v8:TypeDescription (грамматика типа). Forgiving-синоним 'параметр'.
  4991. $btnParam = if ($null -ne $el.PSObject.Properties['parameter']) { $el.parameter } elseif ($null -ne $el.PSObject.Properties['параметр']) { $el.параметр } else { $null }
  4992. if ($null -ne $btnParam) {
  4993. if (($btnParam -is [System.Management.Automation.PSCustomObject] -or $btnParam -is [hashtable]) -and $btnParam.type) {
  4994. Emit-Type -typeStr "$($btnParam.type)" -indent $inner -tag "Parameter" -tagAttrs ' xsi:type="v8:TypeDescription"'
  4995. } else {
  4996. X "$inner<Parameter xsi:type=`"xr:MDObjectRef`">$(Esc-XmlText "$btnParam")</Parameter>"
  4997. }
  4998. }
  4999. # DataPath — привязка команды кнопки к контексту (Объект.Ref, Items.X.CurrentData.Поле)
  5000. if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
  5001. $btnAuto = -not ($el.command -or $el.commandName -or $el.stdCommand)
  5002. Emit-Title -el $el -name $name -indent $inner -auto:$btnAuto
  5003. Emit-CommonFlags -el $el -indent $inner
  5004. if ((Get-DslBool $el @('defaultButton') $false)) { X "$inner<DefaultButton>true</DefaultButton>" }
  5005. # Check (пометка toggle-кнопки командной панели) — платформа эмитит только true.
  5006. # Ключ 'checked' (не 'check': 'check' — тип-ключ CheckBoxField, был бы конфликт диспетчера типов)
  5007. if ((Get-DslBool $el @('checked') $false)) { X "$inner<Check>true</Check>" }
  5008. # Picture
  5009. Emit-CommandPicture -pic $el.picture -elemLt $el.loadTransparent -indent $inner
  5010. if ($el.representation) {
  5011. X "$inner<Representation>$($el.representation)</Representation>"
  5012. }
  5013. if ($el.locationInCommandBar) {
  5014. X "$inner<LocationInCommandBar>$($el.locationInCommandBar)</LocationInCommandBar>"
  5015. }
  5016. Emit-Layout -el $el -indent $inner
  5017. # Оформление (цвета/шрифт/граница) — перед компаньоном (профиль кнопки)
  5018. Emit-Appearance -el $el -indent $inner -profile 'button'
  5019. # Companion
  5020. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  5021. Emit-Events -el $el -elementName $name -indent $inner -xmlTag "Button"
  5022. X "$indent</Button>"
  5023. }
  5024. function Emit-PictureDecoration {
  5025. param($el, [string]$name, [int]$id, [string]$indent)
  5026. X "$indent<PictureDecoration name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  5027. $inner = "$indent`t"
  5028. Emit-DecorationTitle -el $el -name $name -indent $inner
  5029. # Текст при невыбранной картинке (NonselectedPictureText) — после Title (порядок корпуса)
  5030. if ($null -ne $el.nonselectedPictureText) { Emit-MLText -tag "NonselectedPictureText" -text $el.nonselectedPictureText -indent $inner }
  5031. Emit-CommonFlags -el $el -indent $inner
  5032. # Источник картинки — ТОЛЬКО $el.src (у PictureDecoration ключ 'picture' = тип/имя элемента, не источник).
  5033. # Префикс "abs:" → встроенная картинка <xr:Abs>; иначе именованная/стилевая <xr:Ref>.
  5034. if ($el.src) {
  5035. $srcStr = "$($el.src)"
  5036. $lt = if ((Get-DslBool $el @('loadTransparent') $false)) { "true" } else { "false" }
  5037. X "$inner<Picture>"
  5038. if ($srcStr -match '^abs:(.*)$') { X "$inner`t<xr:Abs>$(Esc-XmlText $matches[1])</xr:Abs>" }
  5039. else { X "$inner`t<xr:Ref>$(Esc-XmlText $srcStr)</xr:Ref>" }
  5040. X "$inner`t<xr:LoadTransparent>$lt</xr:LoadTransparent>"
  5041. if ($el.transparentPixel) { X "$inner`t<xr:TransparentPixel x=`"$($el.transparentPixel.x)`" y=`"$($el.transparentPixel.y)`"/>" }
  5042. X "$inner</Picture>"
  5043. }
  5044. if ((Get-DslBool $el @('hyperlink') $false)) { X "$inner<Hyperlink>true</Hyperlink>" }
  5045. Emit-Layout -el $el -indent $inner
  5046. # EnableDrag — фактическое значение (декорация-картинка перетаскиваема; декомпилятор ловит generic-ом)
  5047. if ($null -ne $el.enableDrag) { X "$inner<EnableDrag>$(if ($el.enableDrag){'true'}else{'false'})</EnableDrag>" }
  5048. # Оформление (цвета/шрифт/граница) — профиль декорации (1С толерантна к порядку appearance)
  5049. Emit-Appearance -el $el -indent $inner -profile 'decoration'
  5050. # Companions
  5051. Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
  5052. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  5053. Emit-Events -el $el -elementName $name -indent $inner -xmlTag "PictureDecoration"
  5054. X "$indent</PictureDecoration>"
  5055. }
  5056. function Emit-PictureField {
  5057. param($el, [string]$name, [int]$id, [string]$indent)
  5058. X "$indent<PictureField name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  5059. $inner = "$indent`t"
  5060. if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
  5061. Emit-Title -el $el -name $name -indent $inner
  5062. Emit-CommonFlags -el $el -indent $inner
  5063. if ($el.editMode) { X "$inner<EditMode>$($el.editMode)</EditMode>" }
  5064. Emit-ColumnPics -el $el -indent $inner
  5065. if ($el.titleLocation) { X "$inner<TitleLocation>$(Map-TitleLoc "$($el.titleLocation)")</TitleLocation>" }
  5066. if ((Get-DslBool $el @('hyperlink') $false)) { X "$inner<Hyperlink>true</Hyperlink>" }
  5067. Emit-Layout -el $el -indent $inner
  5068. # EnableDrag — фактическое значение (поле картинки перетаскиваемо; декомпилятор ловит generic-ом)
  5069. if ($null -ne $el.enableDrag) { X "$inner<EnableDrag>$(if ($el.enableDrag){'true'}else{'false'})</EnableDrag>" }
  5070. # FooterDataPath / FooterText — общие cell-свойства колонки (как у input/labelField)
  5071. if ($el.footerDataPath) { X "$inner<FooterDataPath>$(Esc-XmlText "$($el.footerDataPath)")</FooterDataPath>" }
  5072. if ($null -ne $el.footerText) { Emit-MLText -tag "FooterText" -text $el.footerText -indent $inner }
  5073. # ValuesPicture — picture (collection) used to render the field's value.
  5074. # Required for a Boolean-bound PictureField to actually show an icon.
  5075. # Скаляр (Ref) или объект {src, loadTransparent}; LoadTransparent эмитится всегда.
  5076. Emit-PictureRef -val $el.valuesPicture -picTag 'ValuesPicture' -indent $inner
  5077. if ($null -ne $el.nonselectedPictureText) { Emit-MLText -tag "NonselectedPictureText" -text $el.nonselectedPictureText -indent $inner }
  5078. # Оформление (цвета/шрифты/граница) — перед компаньонами
  5079. Emit-Appearance -el $el -indent $inner -profile 'field'
  5080. # Companions
  5081. Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
  5082. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  5083. Emit-Events -el $el -elementName $name -indent $inner -xmlTag "PictureField"
  5084. X "$indent</PictureField>"
  5085. }
  5086. function Emit-Calendar {
  5087. param($el, [string]$name, [int]$id, [string]$indent)
  5088. X "$indent<CalendarField name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  5089. $inner = "$indent`t"
  5090. if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
  5091. Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
  5092. Emit-CommonFlags -el $el -indent $inner
  5093. if ($el.titleLocation) {
  5094. $loc = Map-TitleLoc "$($el.titleLocation)"
  5095. X "$inner<TitleLocation>$loc</TitleLocation>"
  5096. }
  5097. Emit-Layout -el $el -indent $inner
  5098. # Календарно-специфичные свойства (порядок схемы: после layout, до companions)
  5099. if ($el.selectionMode) { X "$inner<SelectionMode>$($el.selectionMode)</SelectionMode>" }
  5100. if ($null -ne $el.showCurrentDate) { $v = if ($el.showCurrentDate) { "true" } else { "false" }; X "$inner<ShowCurrentDate>$v</ShowCurrentDate>" }
  5101. if ($null -ne $el.widthInMonths) { X "$inner<WidthInMonths>$($el.widthInMonths)</WidthInMonths>" }
  5102. if ($null -ne $el.heightInMonths) { X "$inner<HeightInMonths>$($el.heightInMonths)</HeightInMonths>" }
  5103. if ($null -ne $el.showMonthsPanel) { $v = if ($el.showMonthsPanel) { "true" } else { "false" }; X "$inner<ShowMonthsPanel>$v</ShowMonthsPanel>" }
  5104. # Оформление (цвета/шрифты/граница) — перед компаньонами
  5105. Emit-Appearance -el $el -indent $inner -profile 'field'
  5106. # Companions
  5107. Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
  5108. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  5109. Emit-Events -el $el -elementName $name -indent $inner -xmlTag "CalendarField"
  5110. X "$indent</CalendarField>"
  5111. }
  5112. function Emit-SimpleField {
  5113. param($el, [string]$name, [int]$id, [string]$indent, [string]$xmlTag, [string]$typeKey)
  5114. X "$indent<$xmlTag name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  5115. $inner = "$indent`t"
  5116. if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
  5117. Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
  5118. Emit-CommonFlags -el $el -indent $inner
  5119. if ($el.titleLocation) { X "$inner<TitleLocation>$(Map-TitleLoc "$($el.titleLocation)")</TitleLocation>" }
  5120. if ($el.editMode) { X "$inner<EditMode>$($el.editMode)</EditMode>" }
  5121. Emit-Layout -el $el -indent $inner
  5122. # EnableDrag — фактическое значение (SpreadSheet; платформа эмитит явный false). enableStartDrag — через Emit-Layout.
  5123. if ($null -ne $el.enableDrag) { X "$inner<EnableDrag>$(if ($el.enableDrag){'true'}else{'false'})</EnableDrag>" }
  5124. # Датчики (ProgressBar/TrackBar) — числовые скаляры (без xsi:type)
  5125. foreach ($p in @(@('minValue','MinValue'), @('maxValue','MaxValue'), @('largeStep','LargeStep'), @('markingStep','MarkingStep'), @('step','Step'))) {
  5126. if ($null -ne $el.($p[0])) { X "$inner<$($p[1])>$($el.($p[0]))</$($p[1])>" }
  5127. }
  5128. # Оформление (цвета/шрифты/граница) — перед компаньонами
  5129. Emit-Appearance -el $el -indent $inner -profile 'field'
  5130. # Companions
  5131. Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
  5132. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  5133. Emit-Events -el $el -elementName $name -indent $inner -xmlTag $xmlTag
  5134. X "$indent</$xmlTag>"
  5135. }
  5136. function Emit-GanttChart {
  5137. param($el, [string]$name, [int]$id, [string]$indent)
  5138. X "$indent<GanttChartField name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  5139. $inner = "$indent`t"
  5140. if ($el.path) { X "$inner<DataPath>$($el.path)</DataPath>" }
  5141. Emit-Title -el $el -name $name -indent $inner -auto:(-not $el.path)
  5142. Emit-CommonFlags -el $el -indent $inner
  5143. if ($el.titleLocation) { X "$inner<TitleLocation>$(Map-TitleLoc "$($el.titleLocation)")</TitleLocation>" }
  5144. Emit-Layout -el $el -indent $inner
  5145. Emit-Appearance -el $el -indent $inner -profile 'field'
  5146. Emit-CompanionPanel -tag "ContextMenu" -name "${name}КонтекстноеМеню" -indent $inner -panel $el.contextMenu
  5147. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  5148. # Вложенная таблица диаграммы Ганта (стандартный Table — переиспользуем Emit-Element)
  5149. if ($el.ganttTable) { Emit-Element -el $el.ganttTable -indent $inner }
  5150. Emit-Events -el $el -elementName $name -indent $inner -xmlTag "GanttChartField"
  5151. X "$indent</GanttChartField>"
  5152. }
  5153. function Emit-CommandBar {
  5154. param($el, [string]$name, [int]$id, [string]$indent)
  5155. X "$indent<CommandBar name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  5156. $inner = "$indent`t"
  5157. Warn-EventsIgnored $el "CommandBar" $name
  5158. Emit-Title -el $el -name $name -indent $inner
  5159. if ($el.commandSource) { X "$inner<CommandSource>$($el.commandSource)</CommandSource>" }
  5160. if ((Get-DslBool $el @('autofill') $false)) { X "$inner<Autofill>true</Autofill>" }
  5161. # CommandBar хранит HorizontalLocation фактически (включая Auto — декомпилятор ловит только при наличии);
  5162. # ≠ дополнениям, где Auto = умолчание-скип (Get-HLocation).
  5163. if ($el.horizontalLocation) {
  5164. $hlv = switch ("$($el.horizontalLocation)".ToLower()) { 'auto' {'Auto'} 'left' {'Left'} 'right' {'Right'} 'center' {'Center'} default {"$($el.horizontalLocation)"} }
  5165. X "$inner<HorizontalLocation>$hlv</HorizontalLocation>"
  5166. }
  5167. Emit-CommonFlags -el $el -indent $inner
  5168. Emit-Layout -el $el -indent $inner
  5169. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  5170. # Children
  5171. if ($el.children -and $el.children.Count -gt 0) {
  5172. X "$inner<ChildItems>"
  5173. foreach ($child in $el.children) {
  5174. Emit-Element -el $child -indent "$inner`t" -inCmdBar $true
  5175. }
  5176. X "$inner</ChildItems>"
  5177. }
  5178. X "$indent</CommandBar>"
  5179. }
  5180. function Emit-ButtonGroup {
  5181. param($el, [string]$name, [int]$id, [string]$indent)
  5182. X "$indent<ButtonGroup name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  5183. $inner = "$indent`t"
  5184. Warn-EventsIgnored $el "ButtonGroup" $name
  5185. Emit-Title -el $el -name $name -indent $inner
  5186. if ($el.commandSource) { X "$inner<CommandSource>$($el.commandSource)</CommandSource>" }
  5187. if ($el.representation) {
  5188. X "$inner<Representation>$($el.representation)</Representation>"
  5189. }
  5190. Emit-CommonFlags -el $el -indent $inner
  5191. Emit-Layout -el $el -indent $inner
  5192. # Companion: ExtendedTooltip
  5193. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  5194. # Children (кнопки в контексте командной панели)
  5195. if ($el.children -and $el.children.Count -gt 0) {
  5196. X "$inner<ChildItems>"
  5197. foreach ($child in $el.children) {
  5198. Emit-Element -el $child -indent "$inner`t" -inCmdBar $true
  5199. }
  5200. X "$inner</ChildItems>"
  5201. }
  5202. X "$indent</ButtonGroup>"
  5203. }
  5204. function Emit-Popup {
  5205. param($el, [string]$name, [int]$id, [string]$indent)
  5206. X "$indent<Popup name=`"$name`" id=`"$id`"$(DI-Attr $el)>"
  5207. $inner = "$indent`t"
  5208. Warn-EventsIgnored $el "Popup" $name
  5209. Emit-Title -el $el -name $name -indent $inner -auto
  5210. Emit-CommonFlags -el $el -indent $inner
  5211. # Источник команд попапа (после Title/ToolTip, перед компаньоном) — как у ButtonGroup/CommandBar
  5212. if ($el.commandSource) { X "$inner<CommandSource>$($el.commandSource)</CommandSource>" }
  5213. Emit-CommandPicture -pic $el.picture -elemLt $el.loadTransparent -indent $inner
  5214. if ($el.representation) {
  5215. X "$inner<Representation>$($el.representation)</Representation>"
  5216. }
  5217. Emit-Layout -el $el -indent $inner
  5218. # Оформление попапа (TitleTextColor / TitleFont) — перед компаньоном
  5219. Emit-Appearance -el $el -indent $inner -profile 'field'
  5220. Emit-Companion -tag "ExtendedTooltip" -name "${name}РасширеннаяПодсказка" -indent $inner -content $el.extendedTooltip
  5221. # Children
  5222. if ($el.children -and $el.children.Count -gt 0) {
  5223. X "$inner<ChildItems>"
  5224. foreach ($child in $el.children) {
  5225. Emit-Element -el $child -indent "$inner`t" -inCmdBar $true
  5226. }
  5227. X "$inner</ChildItems>"
  5228. }
  5229. X "$indent</Popup>"
  5230. }
  5231. function Emit-FunctionalOptions {
  5232. param($fo, [string]$indent)
  5233. if (-not $fo -or @($fo).Count -eq 0) { return }
  5234. X "$indent<FunctionalOptions>"
  5235. foreach ($opt in @($fo)) {
  5236. $v = "$opt"
  5237. if ($v -match '^[0-9a-fA-F]{8}-[0-9a-fA-F-]{27,}$') { } # GUID — как есть
  5238. elseif ($v -match '^FunctionalOption\.') { } # уже с префиксом
  5239. else { $v = "FunctionalOption.$v" }
  5240. X "$indent`t<Item>$v</Item>"
  5241. }
  5242. X "$indent</FunctionalOptions>"
  5243. }
  5244. function Emit-AttrColumn {
  5245. param($col, [string]$indent)
  5246. $colId = New-Id
  5247. X "$indent<Column name=`"$($col.name)`" id=`"$colId`">"
  5248. if ($col.title) { Emit-MLText -tag "Title" -text $col.title -indent "$indent`t" }
  5249. Emit-Type -typeStr "$($col.type)" -indent "$indent`t"
  5250. # Проверка заполнения колонки → <FillCheck> (как у реквизита; bool true→ShowError / строка verbatim)
  5251. $cfcRaw = if ($null -ne $col.PSObject.Properties['fillCheck']) { $col.fillCheck } elseif ($null -ne $col.PSObject.Properties['fillChecking']) { $col.fillChecking } else { $null }
  5252. if ($null -ne $cfcRaw) { $cfcv = if ($cfcRaw -is [bool]) { if ($cfcRaw) { 'ShowError' } else { $null } } else { "$cfcRaw" }; if ($cfcv) { X "$indent`t<FillCheck>$cfcv</FillCheck>" } }
  5253. Emit-FunctionalOptions -fo $col.functionalOptions -indent "$indent`t"
  5254. # Ролевой доступ колонки (View/Edit) — xr-флаг, как у самого реквизита
  5255. if ($null -ne $col.view) { Emit-XrFlag -tag 'View' -val $col.view -indent "$indent`t" }
  5256. if ($null -ne $col.edit) { Emit-XrFlag -tag 'Edit' -val $col.edit -indent "$indent`t" }
  5257. X "$indent</Column>"
  5258. }
  5259. function Emit-DLMLText {
  5260. param([string]$tag, $text, [string]$indent)
  5261. X "$indent<$tag xsi:type=`"v8:LocalStringType`">"
  5262. Emit-MLItems -val $text -indent "$indent`t"
  5263. X "$indent</$tag>"
  5264. }
  5265. function Has-DLProp {
  5266. param($obj, [string]$name)
  5267. if ($null -eq $obj) { return $false }
  5268. if ($obj -is [System.Collections.IDictionary]) { return $obj.Contains($name) }
  5269. if ($obj.PSObject -and $obj.PSObject.Properties[$name]) { return $true }
  5270. return $false
  5271. }
  5272. function Split-DLValueListCsv {
  5273. param([string]$s)
  5274. $result = @()
  5275. if ($null -eq $s) { return ,$result }
  5276. $items = @(); $buf = New-Object System.Text.StringBuilder; $inQuote = $null
  5277. for ($i = 0; $i -lt $s.Length; $i++) {
  5278. $ch = $s[$i]
  5279. if ($inQuote) { [void]$buf.Append($ch); if ($ch -eq $inQuote) { $inQuote = $null } }
  5280. elseif ($ch -eq "'" -or $ch -eq '"') { $inQuote = $ch; [void]$buf.Append($ch) }
  5281. elseif ($ch -eq ',') { $items += $buf.ToString(); [void]$buf.Clear() }
  5282. else { [void]$buf.Append($ch) }
  5283. }
  5284. if ($buf.Length -gt 0) { $items += $buf.ToString() }
  5285. foreach ($raw in $items) {
  5286. $t = $raw.Trim()
  5287. 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) }
  5288. if ($t -ne "") { $result += $t }
  5289. }
  5290. return ,$result
  5291. }
  5292. function Parse-DLParamShorthand {
  5293. param([string]$s)
  5294. $result = @{ name = ""; type = ""; value = $null; title = $null }
  5295. if ($s -match '@valueList') { $result.valueListAllowed = $true; $s = $s -replace '\s*@valueList', '' }
  5296. if ($s -match '@hidden') { $result.hidden = $true; $s = $s -replace '\s*@hidden', '' }
  5297. if ($s -match '\[([^\]]*)\]') { $result.title = $Matches[1].Trim(); $s = ($s -replace '\s*\[[^\]]*\]\s*', ' ').Trim() }
  5298. # Тип может быть СОСТАВНЫМ (A | B | C — с пробелами); значение — после '=' (тип '=' не содержит).
  5299. if ($s -match '^([^:]+):\s*([^=]+?)(\s*=\s*(.*))?$') {
  5300. $result.name = $Matches[1].Trim()
  5301. $typeRaw = $Matches[2].Trim()
  5302. if ($typeRaw -match '[|+]') {
  5303. $result.type = (($typeRaw -split '\s*[|+]\s*') | ForEach-Object { Resolve-TypeStr ($_.Trim()) }) -join ' | '
  5304. } else {
  5305. $result.type = Resolve-TypeStr $typeRaw
  5306. }
  5307. if ($Matches[4]) {
  5308. $rhs = $Matches[4].Trim()
  5309. $items = Split-DLValueListCsv $rhs
  5310. if ($items.Count -ge 2) { $result.value = $items; $result.valueListAllowed = $true }
  5311. elseif ($items.Count -eq 1) { $result.value = $items[0] }
  5312. else { $result.value = $rhs }
  5313. }
  5314. } else { $result.name = $s.Trim() }
  5315. return $result
  5316. }
  5317. function Test-DLEmptyValue {
  5318. param($v)
  5319. if ($null -eq $v) { return $true }
  5320. $s = "$v".Trim()
  5321. if ($s -eq "" -or $s -eq "_" -or $s.ToLowerInvariant() -eq "null") { return $true }
  5322. return $false
  5323. }
  5324. # Вид значения для ветвлений эмиттеров значений (параметры, пустые значения): примитив любого
  5325. # написания (Число(15,2), numeric, String(10)) → decimal / string / date / dateTime / time, прочее —
  5326. # через синонимы навыка. Квалификаторы значению не нужны и отбрасываются.
  5327. function Get-ValueKindType {
  5328. param([string]$typeStr)
  5329. if (-not $typeStr) { return $typeStr }
  5330. $prim = Parse-PrimitiveType $typeStr 0 0 0
  5331. if ($prim -and -not $prim.Error) {
  5332. if ($prim.Kind -eq 'Number') { return 'decimal' }
  5333. if ($prim.Kind -eq 'String') { return 'string' }
  5334. if ($prim.Fractions -eq 'Date') { return 'date' }
  5335. if ($prim.Fractions -eq 'Time') { return 'time' }
  5336. return 'dateTime'
  5337. }
  5338. return Resolve-TypeStr $typeStr
  5339. }
  5340. function Emit-DLValue {
  5341. param([string]$type, $val, [string]$indent, [bool]$valueListAllowed = $false)
  5342. $type = Get-ValueKindType $type
  5343. if (Test-DLEmptyValue $val) {
  5344. # Дин-список: пустое значение платформа ВСЕГДА пишет как xsi:nil, даже при известном
  5345. # типе (в отличие от типизированного пустого в параметрах отчёта СКД).
  5346. if ($valueListAllowed) { return }
  5347. X "$indent<dcssch:value xsi:nil=`"true`"/>"
  5348. return
  5349. }
  5350. $valStr = if ($val -is [bool]) { if ($val) { 'true' } else { 'false' } } else { "$val" }
  5351. if ($type -match '^(date|dateTime|time)') { X "$indent<dcssch:value xsi:type=`"xs:dateTime`">$(Esc-XmlText $valStr)</dcssch:value>" }
  5352. elseif ($type -eq "boolean") { X "$indent<dcssch:value xsi:type=`"xs:boolean`">$(Esc-XmlText $valStr)</dcssch:value>" }
  5353. 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>" }
  5354. elseif ($type -match '^ent:') { X "$indent<dcssch:value xsi:type=`"$type`">$(Esc-XmlText $valStr)</dcssch:value>" } # системное перечисление (ent:X) — value несёт тот же xsi:type
  5355. elseif ($type -match '^decimal') { X "$indent<dcssch:value xsi:type=`"xs:decimal`">$(Esc-XmlText $valStr)</dcssch:value>" }
  5356. elseif ($type -match '^string') { X "$indent<dcssch:value xsi:type=`"xs:string`">$(Esc-XmlText $valStr)</dcssch:value>" }
  5357. 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>" }
  5358. else {
  5359. if ($valStr -match '^\d{4}-\d{2}-\d{2}T') { X "$indent<dcssch:value xsi:type=`"xs:dateTime`">$(Esc-XmlText $valStr)</dcssch:value>" }
  5360. elseif ($valStr -eq "true" -or $valStr -eq "false") { X "$indent<dcssch:value xsi:type=`"xs:boolean`">$(Esc-XmlText $valStr)</dcssch:value>" }
  5361. 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>" }
  5362. else { X "$indent<dcssch:value xsi:type=`"xs:string`">$(Esc-XmlText $valStr)</dcssch:value>" }
  5363. }
  5364. }
  5365. function Emit-DLValueType {
  5366. param($typeStr, [string]$indent)
  5367. if (-not $typeStr) { return }
  5368. X "$indent<dcssch:valueType>"
  5369. $parts = "$typeStr" -split '\s*[|+]\s*'
  5370. foreach ($part in $parts) { Emit-SingleType -typeStr $part.Trim() -indent "$indent`t" }
  5371. X "$indent</dcssch:valueType>"
  5372. }
  5373. function Emit-DLAvailableValue {
  5374. param($av, [string]$type, [string]$indent)
  5375. X "$indent<dcssch:availableValue>"
  5376. $avVal = if (Has-DLProp $av 'value') { $av.value } else { $null }
  5377. Emit-DLValue -type $type -val $avVal -indent "$indent`t" -valueListAllowed $false
  5378. $pres = if ($av.presentation) { $av.presentation } elseif ($av.title) { $av.title } else { $null }
  5379. if ($pres) { Emit-DLMLText -tag "dcssch:presentation" -text $pres -indent "$indent`t" }
  5380. X "$indent</dcssch:availableValue>"
  5381. }
  5382. function Emit-DLInputParameters {
  5383. param($ip, [string]$indent)
  5384. if ($null -eq $ip) { return }
  5385. $items = @($ip)
  5386. if ($items.Count -eq 0) { return }
  5387. X "$indent<dcssch:inputParameters>"
  5388. foreach ($item in $items) {
  5389. X "$indent`t<dcscor:item>"
  5390. if ((Has-DLProp $item 'use') -and $null -ne $item.use -and -not $item.use) { X "$indent`t`t<dcscor:use>false</dcscor:use>" }
  5391. X "$indent`t`t<dcscor:parameter>$(Esc-XmlText "$($item.parameter)")</dcscor:parameter>"
  5392. if (Has-DLProp $item 'choiceParameters') {
  5393. $cpItems = if ($null -ne $item.choiceParameters) { @($item.choiceParameters) } else { @() }
  5394. if ($cpItems.Count -eq 0) { X "$indent`t`t<dcscor:value xsi:type=`"dcscor:ChoiceParameters`"/>" }
  5395. else {
  5396. X "$indent`t`t<dcscor:value xsi:type=`"dcscor:ChoiceParameters`">"
  5397. foreach ($cpItem in $cpItems) {
  5398. X "$indent`t`t`t<dcscor:item>"
  5399. X "$indent`t`t`t`t<dcscor:choiceParameter>$(Esc-XmlText "$($cpItem.name)")</dcscor:choiceParameter>"
  5400. foreach ($v in @($cpItem.values)) {
  5401. if ($v -is [bool]) { X "$indent`t`t`t`t<dcscor:value xsi:type=`"xs:boolean`">$(if ($v) { 'true' } else { 'false' })</dcscor:value>" }
  5402. 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>" }
  5403. else { X "$indent`t`t`t`t<dcscor:value xsi:type=`"dcscor:DesignTimeValue`">$(Esc-XmlText (Normalize-DesignTimeValue "$v"))</dcscor:value>" }
  5404. }
  5405. X "$indent`t`t`t</dcscor:item>"
  5406. }
  5407. X "$indent`t`t</dcscor:value>"
  5408. }
  5409. } elseif (Has-DLProp $item 'choiceParameterLinks') {
  5410. $cplItems = if ($null -ne $item.choiceParameterLinks) { @($item.choiceParameterLinks) } else { @() }
  5411. if ($cplItems.Count -eq 0) { X "$indent`t`t<dcscor:value xsi:type=`"dcscor:ChoiceParameterLinks`"/>" }
  5412. else {
  5413. X "$indent`t`t<dcscor:value xsi:type=`"dcscor:ChoiceParameterLinks`">"
  5414. foreach ($cplItem in $cplItems) {
  5415. X "$indent`t`t`t<dcscor:item>"
  5416. X "$indent`t`t`t`t<dcscor:choiceParameter>$(Esc-XmlText "$($cplItem.name)")</dcscor:choiceParameter>"
  5417. X "$indent`t`t`t`t<dcscor:value>$(Esc-XmlText "$($cplItem.value)")</dcscor:value>"
  5418. $mode = if ($cplItem.mode) { "$($cplItem.mode)" } else { 'Auto' }
  5419. 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>"
  5420. X "$indent`t`t`t</dcscor:item>"
  5421. }
  5422. X "$indent`t`t</dcscor:value>"
  5423. }
  5424. } elseif (Has-DLProp $item 'typeLink') {
  5425. # Связь по типу (dcscor:TypeLink) — field + linkItem (структурное значение параметра).
  5426. $tl = $item.typeLink
  5427. X "$indent`t`t<dcscor:value xsi:type=`"dcscor:TypeLink`">"
  5428. $tlf = Get-Prop $tl 'field'; if ($null -ne $tlf) { X "$indent`t`t`t<dcscor:field>$(Esc-XmlText "$tlf")</dcscor:field>" }
  5429. $tli = Get-Prop $tl 'linkItem'; if ($null -ne $tli) { X "$indent`t`t`t<dcscor:linkItem>$(Esc-XmlText "$tli")</dcscor:linkItem>" }
  5430. X "$indent`t`t</dcscor:value>"
  5431. } elseif (Has-DLProp $item 'value') {
  5432. $val = $item.value
  5433. if ($val -is [bool]) { X "$indent`t`t<dcscor:value xsi:type=`"xs:boolean`">$(if ($val) { 'true' } else { 'false' })</dcscor:value>" }
  5434. 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>" }
  5435. 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" }
  5436. else { X "$indent`t`t<dcscor:value xsi:type=`"xs:string`">$(Esc-XmlText "$val")</dcscor:value>" }
  5437. }
  5438. X "$indent`t</dcscor:item>"
  5439. }
  5440. X "$indent</dcssch:inputParameters>"
  5441. }
  5442. function Test-EmptyValue {
  5443. param($v)
  5444. if ($null -eq $v) { return $true }
  5445. $s = "$v".Trim()
  5446. if ($s -eq "") { return $true }
  5447. if ($s -eq "_") { return $true }
  5448. if ($s.ToLowerInvariant() -eq "null") { return $true }
  5449. return $false
  5450. }
  5451. function Emit-EmptyValue {
  5452. param([string]$type, [string]$indent, [string]$tagPrefix = "", [bool]$valueListAllowed = $false)
  5453. $type = Get-ValueKindType $type
  5454. if ($valueListAllowed) { return }
  5455. $t = if ($null -eq $type) { "" } else { "$type" }
  5456. $tBare = if ($t -match '^xs:(.+)$') { $matches[1] } else { $t }
  5457. $pf = $tagPrefix
  5458. if ($t -eq "") { X "$indent<${pf}value xsi:nil=`"true`"/>" }
  5459. elseif ($t -eq "StandardPeriod") {
  5460. X "$indent<${pf}value xsi:type=`"v8:StandardPeriod`">"
  5461. X "$indent`t<v8:variant xsi:type=`"v8:StandardPeriodVariant`">Custom</v8:variant>"
  5462. X "$indent`t<v8:startDate>0001-01-01T00:00:00</v8:startDate>"
  5463. X "$indent`t<v8:endDate>0001-01-01T00:00:00</v8:endDate>"
  5464. X "$indent</${pf}value>"
  5465. }
  5466. elseif ($tBare -match '^string') { X "$indent<${pf}value xsi:type=`"xs:string`"/>" }
  5467. elseif ($tBare -match '^(date|time)') { X "$indent<${pf}value xsi:type=`"xs:dateTime`">0001-01-01T00:00:00</${pf}value>" }
  5468. elseif ($tBare -match '^decimal') { X "$indent<${pf}value xsi:type=`"xs:decimal`">0</${pf}value>" }
  5469. elseif ($tBare -eq "boolean") { X "$indent<${pf}value xsi:type=`"xs:boolean`">false</${pf}value>" }
  5470. else { X "$indent<${pf}value xsi:nil=`"true`"/>" }
  5471. }
  5472. function Parse-DataParamShorthand {
  5473. param([string]$s)
  5474. $result = @{ parameter = ""; value = $null; use = $true; userSettingID = $null; viewMode = $null }
  5475. if ($s -match '@user') { $result.userSettingID = "auto"; $s = $s -replace '\s*@user', '' }
  5476. if ($s -match '@off') { $result.use = $false; $s = $s -replace '\s*@off', '' }
  5477. if ($s -match '@quickAccess') { $result.viewMode = "QuickAccess"; $s = $s -replace '\s*@quickAccess', '' }
  5478. if ($s -match '@normal') { $result.viewMode = "Normal"; $s = $s -replace '\s*@normal', '' }
  5479. $s = $s.Trim()
  5480. if ($s -match '^([^=]+)=\s*(.+)$') {
  5481. $result.parameter = $Matches[1].Trim()
  5482. $valStr = $Matches[2].Trim()
  5483. $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")
  5484. if ($periodVariants -contains $valStr) { $result.value = @{ variant = $valStr } }
  5485. elseif ($valStr -match '^\d{4}-\d{2}-\d{2}T') { $result.value = $valStr }
  5486. elseif ($valStr -eq "true" -or $valStr -eq "false") { $result.value = [bool]($valStr -eq "true") }
  5487. else { $result.value = $valStr }
  5488. } else { $result.parameter = $s }
  5489. return $result
  5490. }
  5491. function Emit-DataParameters {
  5492. param($items, [string]$indent, $blockViewMode = $null)
  5493. if (-not $items -or @($items).Count -eq 0) { return }
  5494. X "$indent<dcsset:dataParameters>"
  5495. foreach ($dp in @($items)) {
  5496. if ($dp -is [string]) {
  5497. $parsed = Parse-DataParamShorthand $dp
  5498. $dpObj = New-Object PSObject
  5499. $dpObj | Add-Member -NotePropertyName "parameter" -NotePropertyValue $parsed.parameter
  5500. if ($null -ne $parsed.value) { $dpObj | Add-Member -NotePropertyName "value" -NotePropertyValue $parsed.value }
  5501. if ((-not (Get-DslBool $parsed @('use') $true))) { $dpObj | Add-Member -NotePropertyName "use" -NotePropertyValue $false }
  5502. if ($parsed.userSettingID) { $dpObj | Add-Member -NotePropertyName "userSettingID" -NotePropertyValue $parsed.userSettingID }
  5503. if ($parsed.viewMode) { $dpObj | Add-Member -NotePropertyName "viewMode" -NotePropertyValue $parsed.viewMode }
  5504. $dp = $dpObj
  5505. }
  5506. X "$indent`t<dcscor:item xsi:type=`"dcsset:SettingsParameterValue`">"
  5507. if ((-not (Get-DslBool $dp @('use') $true))) { X "$indent`t`t<dcscor:use>false</dcscor:use>" }
  5508. X "$indent`t`t<dcscor:parameter>$(Esc-XmlText "$($dp.parameter)")</dcscor:parameter>"
  5509. $dpValIsArr = ($dp.value -is [array]) -or ($dp.value -is [System.Collections.IList] -and $dp.value -isnot [string])
  5510. if ($dpValIsArr) {
  5511. # Список значений параметра (valueListAllowed) — отдельный <dcscor:value> на каждое.
  5512. $avtype = "$($dp.valueType)"
  5513. foreach ($v in @($dp.value)) {
  5514. $vStr = if ($v -is [bool]) { "$v".ToLower() } else { "$v" }
  5515. 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>" }
  5516. 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>" }
  5517. else { X "$indent`t`t<dcscor:value xsi:type=`"xs:string`">$(Esc-XmlText $vStr)</dcscor:value>" }
  5518. }
  5519. } elseif ((Get-DslBool $dp @('nilValue') $false)) {
  5520. X "$indent`t`t<dcscor:value xsi:nil=`"true`"/>"
  5521. } elseif ((Test-EmptyValue $dp.value) -and $dp.valueType) {
  5522. # Явный типизированный пустой (xs:string-плейсхолдер и т.п.)
  5523. Emit-EmptyValue -type "$($dp.valueType)" -indent "$indent`t`t" -tagPrefix "dcscor:" -valueListAllowed $false
  5524. } elseif (Test-EmptyValue $dp.value) {
  5525. # Нет значения и нет valueType → НЕ эмитим value-узел (form дин-список: use=false плейсхолдер).
  5526. # (В отличие от skd-settings, где значение всегда присутствует.)
  5527. } elseif ($null -ne $dp.value) {
  5528. $vtype = Get-ValueKindType "$($dp.valueType)"
  5529. if (($dp.value -is [PSCustomObject] -or $dp.value -is [hashtable] -or $dp.value -is [System.Collections.IDictionary]) -and ($dp.value.variant)) {
  5530. $_hasDate = $false; $_hasSD = $false
  5531. if ($dp.value -is [PSCustomObject]) { $_hasDate = [bool]$dp.value.PSObject.Properties['date']; $_hasSD = [bool]$dp.value.PSObject.Properties['startDate'] }
  5532. else { $_hasDate = $dp.value.Contains('date'); $_hasSD = $dp.value.Contains('startDate') }
  5533. $_variantStr = "$($dp.value.variant)"
  5534. $_isSBD = $_hasDate -or (-not $_hasSD -and $_variantStr -like 'BeginningOf*')
  5535. if ($_isSBD) {
  5536. $_d = $null
  5537. if ($dp.value -is [PSCustomObject] -and $dp.value.PSObject.Properties['date']) { $_d = "$($dp.value.date)" }
  5538. elseif (($dp.value -is [System.Collections.IDictionary]) -and $dp.value.Contains('date')) { $_d = "$($dp.value['date'])" }
  5539. X "$indent`t`t<dcscor:value xsi:type=`"v8:StandardBeginningDate`">"
  5540. X "$indent`t`t`t<v8:variant xsi:type=`"v8:StandardBeginningDateVariant`">$(Esc-XmlText $_variantStr)</v8:variant>"
  5541. 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>" }
  5542. X "$indent`t`t</dcscor:value>"
  5543. } else {
  5544. $_sd = $null; $_ed = $null
  5545. 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)" } }
  5546. else { if ($dp.value.Contains('startDate')) { $_sd = "$($dp.value['startDate'])" }; if ($dp.value.Contains('endDate')) { $_ed = "$($dp.value['endDate'])" } }
  5547. X "$indent`t`t<dcscor:value xsi:type=`"v8:StandardPeriod`">"
  5548. X "$indent`t`t`t<v8:variant xsi:type=`"v8:StandardPeriodVariant`">$(Esc-XmlText $_variantStr)</v8:variant>"
  5549. 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>" }
  5550. X "$indent`t`t</dcscor:value>"
  5551. }
  5552. } elseif ($vtype -match '^[a-zA-Z]+:') {
  5553. $vStr = if ($dp.value -is [bool]) { "$($dp.value)".ToLower() } else { "$($dp.value)" }
  5554. X "$indent`t`t<dcscor:value xsi:type=`"$vtype`">$(Esc-XmlText $vStr)</dcscor:value>"
  5555. } elseif ($vtype -eq 'boolean' -or $dp.value -is [bool]) {
  5556. X "$indent`t`t<dcscor:value xsi:type=`"xs:boolean`">$(Esc-XmlText ("$($dp.value)".ToLower()))</dcscor:value>"
  5557. } elseif ($vtype -match '^date' -or "$($dp.value)" -match '^\d{4}-\d{2}-\d{2}T') {
  5558. X "$indent`t`t<dcscor:value xsi:type=`"xs:dateTime`">$(Esc-XmlText "$($dp.value)")</dcscor:value>"
  5559. } elseif ($vtype -match '^decimal') {
  5560. X "$indent`t`t<dcscor:value xsi:type=`"xs:decimal`">$(Esc-XmlText "$($dp.value)")</dcscor:value>"
  5561. } elseif ($vtype -match '^string') {
  5562. X "$indent`t`t<dcscor:value xsi:type=`"xs:string`">$(Esc-XmlText "$($dp.value)")</dcscor:value>"
  5563. } elseif ("$($dp.value)" -match '^(ПланСчетов|Справочник|Перечисление|Документ|ПланВидовХарактеристик|ПланВидовРасчета|БизнесПроцесс|Задача|РегистрСведений|ПланОбмена)\.' -or "$($dp.value)" -match '^(ChartOfAccounts|Catalog|Enum|Document|ChartOfCharacteristicTypes|ChartOfCalculationTypes|BusinessProcess|Task|InformationRegister|ExchangePlan)\.') {
  5564. X "$indent`t`t<dcscor:value xsi:type=`"dcscor:DesignTimeValue`">$(Esc-XmlText (Normalize-DesignTimeValue "$($dp.value)"))</dcscor:value>"
  5565. } else {
  5566. X "$indent`t`t<dcscor:value xsi:type=`"xs:string`">$(Esc-XmlText "$($dp.value)")</dcscor:value>"
  5567. }
  5568. }
  5569. if ($dp.viewMode) { X "$indent`t`t<dcsset:viewMode>$(Esc-XmlText "$($dp.viewMode)")</dcsset:viewMode>" }
  5570. 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>" }
  5571. if ($dp.userSettingPresentation) { Emit-USPresentation -val $dp.userSettingPresentation -tag "dcsset:userSettingPresentation" -indent "$indent`t`t" }
  5572. X "$indent`t</dcscor:item>"
  5573. }
  5574. if ($null -ne $blockViewMode) { X "$indent`t<dcsset:viewMode>$(Esc-XmlText "$blockViewMode")</dcsset:viewMode>" }
  5575. X "$indent</dcsset:dataParameters>"
  5576. }
  5577. function Emit-DLParameter {
  5578. param($p, $parsed, [string]$indent)
  5579. X "$indent<Parameter>"
  5580. $ci = "$indent`t"
  5581. X "$ci<dcssch:name>$(Esc-XmlText $parsed.name)</dcssch:name>"
  5582. # Title: явный override (shorthand [..] / объект title/presentation) или авто из имени.
  5583. $title = $null
  5584. if ($parsed.title) { $title = $parsed.title }
  5585. elseif ($p -isnot [string] -and (Has-DLProp $p 'title') -and $p.title) { $title = $p.title }
  5586. elseif ($p -isnot [string] -and (Has-DLProp $p 'presentation') -and $p.presentation) { $title = $p.presentation }
  5587. if ($null -eq $title -or ($title -is [string] -and $title -eq '')) { $title = Title-FromName -name $parsed.name }
  5588. Emit-DLMLText -tag "dcssch:title" -text $title -indent $ci
  5589. # valueType
  5590. if ($parsed.type) { Emit-DLValueType -typeStr $parsed.type -indent $ci }
  5591. # value (дефолт nil; при valueListAllowed пустое — опускаем)
  5592. $vla = (ConvertTo-DslBool $parsed.valueListAllowed 'valueListAllowed' $false)
  5593. $valIsArray = ($parsed.value -is [array]) -or ($parsed.value -is [System.Collections.IList] -and $parsed.value -isnot [string])
  5594. if ($valIsArray) {
  5595. foreach ($v in @($parsed.value)) { Emit-DLValue -type $parsed.type -val $v -indent $ci -valueListAllowed $false }
  5596. } elseif ($parsed.valueExplicit -and ($null -ne $parsed.value) -and ("$($parsed.value)" -eq '') -and (("$($parsed.type)" -eq '') -or ((Get-ValueKindType "$($parsed.type)") -match '^string'))) {
  5597. # Явный пустой СТРОКОВЫЙ параметр (value:"" от декомпилятора) → типизированный пустой
  5598. # <dcssch:value xsi:type="xs:string"/>, НЕ nil. Решается ФОРМОЙ value (""→typed-empty,
  5599. # null/отсутствие→nil), независимо от valueListAllowed; декомпилятор различает ""/null
  5600. # (Convert-TypedValue пустого xs:string → "", nil → value опущен/null). Корпус: 26 xs:string.
  5601. X "$ci<dcssch:value xsi:type=`"xs:string`"/>"
  5602. } elseif ($vla -and (Test-DLEmptyValue $parsed.value) -and $parsed.valueExplicit) {
  5603. # valueListAllowed + явный пустой (value:null от декомпилятора) → платформа здесь пишет nil
  5604. X "$ci<dcssch:value xsi:nil=`"true`"/>"
  5605. } else {
  5606. Emit-DLValue -type $parsed.type -val $parsed.value -indent $ci -valueListAllowed $vla
  5607. }
  5608. # useRestriction — ВСЕГДА; дефолт true; false только при явном useRestriction:false.
  5609. $ur = $true
  5610. if ($p -isnot [string] -and (Has-DLProp $p 'useRestriction')) { $ur = (ConvertTo-DslBool $p.useRestriction 'useRestriction' $false) }
  5611. X "$ci<dcssch:useRestriction>$(if ($ur) { 'true' } else { 'false' })</dcssch:useRestriction>"
  5612. # expression
  5613. $expr = $null
  5614. if ($p -isnot [string] -and (Has-DLProp $p 'expression') -and $p.expression) { $expr = "$($p.expression)" }
  5615. if ($expr) { X "$ci<dcssch:expression>$(Esc-XmlText $expr)</dcssch:expression>" }
  5616. # availableValues
  5617. if ($p -isnot [string] -and (Has-DLProp $p 'availableValues') -and $p.availableValues) {
  5618. foreach ($av in @($p.availableValues)) { Emit-DLAvailableValue -av $av -type $parsed.type -indent $ci }
  5619. }
  5620. # valueListAllowed
  5621. if ($vla) { X "$ci<dcssch:valueListAllowed>true</dcssch:valueListAllowed>" }
  5622. # availableAsField=false (hidden или явный)
  5623. $aaf = $null
  5624. if ((Get-DslBool $parsed @('hidden') $false)) { $aaf = $false }
  5625. if ($p -isnot [string] -and (Has-DLProp $p 'availableAsField')) { $aaf = (ConvertTo-DslBool $p.availableAsField 'availableAsField' $false) }
  5626. if ($aaf -eq $false) { X "$ci<dcssch:availableAsField>false</dcssch:availableAsField>" }
  5627. # inputParameters
  5628. if ($p -isnot [string] -and (Has-DLProp $p 'inputParameters') -and $p.inputParameters) { Emit-DLInputParameters -ip $p.inputParameters -indent $ci }
  5629. # denyIncompleteValues
  5630. if ($p -isnot [string] -and (Has-DLProp $p 'denyIncompleteValues') -and (Get-DslBool $p @('denyIncompleteValues') $false)) { X "$ci<dcssch:denyIncompleteValues>true</dcssch:denyIncompleteValues>" }
  5631. # use
  5632. $useVal = $null
  5633. if ($p -isnot [string] -and (Has-DLProp $p 'use') -and $p.use) { $useVal = "$($p.use)" }
  5634. if ($useVal) { X "$ci<dcssch:use>$(Esc-XmlText $useVal)</dcssch:use>" }
  5635. X "$indent</Parameter>"
  5636. }
  5637. function Emit-DLParameters {
  5638. param($params, [string]$indent)
  5639. if (-not $params) { return }
  5640. foreach ($p in @($params)) {
  5641. if ($p -is [string]) {
  5642. $parsed = Parse-DLParamShorthand $p
  5643. } else {
  5644. $resolvedType = ""
  5645. if ((Has-DLProp $p 'type') -and $p.type) {
  5646. if ($p.type -is [array] -or ($p.type -is [System.Collections.IList] -and $p.type -isnot [string])) {
  5647. $resolvedType = (@($p.type | ForEach-Object { Resolve-TypeStr "$_" })) -join ' | '
  5648. } else { $resolvedType = Resolve-TypeStr "$($p.type)" }
  5649. } elseif ((Has-DLProp $p 'valueType') -and $p.valueType) {
  5650. $resolvedType = Resolve-TypeStr "$($p.valueType)"
  5651. }
  5652. $parsed = @{ name = "$($p.name)"; type = $resolvedType; value = $(if (Has-DLProp $p 'value') { $p.value } else { $null }); valueExplicit = (Has-DLProp $p 'value'); title = $null }
  5653. if ((Has-DLProp $p 'valueListAllowed') -and (Get-DslBool $p @('valueListAllowed') $false)) { $parsed.valueListAllowed = $true }
  5654. if ((Has-DLProp $p 'hidden') -and (Get-DslBool $p @('hidden') $false)) { $parsed.hidden = $true }
  5655. }
  5656. Emit-DLParameter -p $p -parsed $parsed -indent $indent
  5657. }
  5658. }
  5659. function Emit-Attributes {
  5660. param($attrs, [string]$indent, $conditionalAppearance = $null)
  5661. $hasCA = $conditionalAppearance -and @($conditionalAppearance).Count -gt 0
  5662. # Платформа ВСЕГДА эмитит <Attributes> (100% корпуса; 162 формы — пустой <Attributes/>).
  5663. if ((-not $attrs -or $attrs.Count -eq 0) -and -not $hasCA) { X "$indent<Attributes/>"; return }
  5664. if (-not $attrs -or $attrs.Count -eq 0) {
  5665. # Нет реквизитов, но есть условное оформление (последний child <Attributes>)
  5666. X "$indent<Attributes>"
  5667. Emit-ConditionalAppearance -items $conditionalAppearance -indent "$indent`t" -wrapTag 'ConditionalAppearance'
  5668. X "$indent</Attributes>"
  5669. return
  5670. }
  5671. X "$indent<Attributes>"
  5672. $seenAttrs = @{}
  5673. foreach ($attr in $attrs) {
  5674. $attrId = New-Id
  5675. $attrName = "$($attr.name)"
  5676. Assert-UniqueName -name $attrName -seen $seenAttrs -kind 'attribute'
  5677. X "$indent`t<Attribute name=`"$attrName`" id=`"$attrId`">"
  5678. $inner = "$indent`t`t"
  5679. # Title атрибута (зеркало Emit-Title): нет ключа → авто-вывод из имени (кроме main);
  5680. # title "" → подавить; непустой → эмитить как есть.
  5681. $hasTitleKey = $null -ne $attr.PSObject.Properties['title']
  5682. if ($hasTitleKey) {
  5683. if ($attr.title) { Emit-MLText -tag "Title" -text $attr.title -indent $inner }
  5684. } elseif ($attr.main -ne $true) {
  5685. Emit-MLText -tag "Title" -text (Title-FromName -name $attrName) -indent $inner
  5686. }
  5687. # Type
  5688. if ($attr.type) {
  5689. Emit-Type -typeStr "$($attr.type)" -indent $inner
  5690. } else {
  5691. X "$inner<Type/>"
  5692. }
  5693. # valueType: уточнение типа значений ValueList → <Settings xsi:type="v8:TypeDescription">
  5694. # (та же грамматика типа, что и Type, включая составной "A | B"). Forgiving-синонимы.
  5695. # Три состояния: нет ключа → нет Settings; "" → пустой <Settings…/>; тип → с типом.
  5696. $vtSpec = $null; $hasVt = $false
  5697. foreach ($k in @('valueType','typeDescription','описаниеТипов','типЗначений')) {
  5698. if ($attr.PSObject.Properties[$k]) { $vtSpec = $attr.$k; $hasVt = $true; break }
  5699. }
  5700. if ($hasVt) {
  5701. Emit-Type -typeStr "$vtSpec" -indent $inner -tag "Settings" -tagAttrs ' xsi:type="v8:TypeDescription"'
  5702. }
  5703. # Planner design-time <Settings xsi:type="pl:Planner"> (встроенный конфиг планировщика).
  5704. # Идёт сразу после <Type> (как valueType/DynamicList Settings — взаимоисключающи).
  5705. if ($attr.PSObject.Properties['planner'] -and $null -ne $attr.planner) {
  5706. Emit-PlannerSettings -pl $attr.planner -ind $inner
  5707. }
  5708. # Chart/GanttChart design-time <Settings xsi:type="d4p1:Chart"/"d4p1:GanttChart">.
  5709. # Тип Settings выводится из типа реквизита (d5p1:GanttChart → d4p1:GanttChart).
  5710. if ($attr.PSObject.Properties['chart'] -and $null -ne $attr.chart) {
  5711. $ctype = if ("$($attr.type)" -match 'GanttChart') { 'd4p1:GanttChart' } else { 'd4p1:Chart' }
  5712. Emit-ChartSettings -chart $attr.chart -ind $inner -ctype $ctype
  5713. }
  5714. if ((Get-DslBool $attr @('main') $false)) {
  5715. X "$inner<MainAttribute>true</MainAttribute>"
  5716. }
  5717. # Доступ по ролям: просмотр/редактирование (порядок схемы: View → Edit, после MainAttribute)
  5718. if ($null -ne $attr.view) { Emit-XrFlag -tag 'View' -val $attr.view -indent $inner }
  5719. if ($null -ne $attr.edit) { Emit-XrFlag -tag 'Edit' -val $attr.edit -indent $inner }
  5720. $mainSaved = $false
  5721. if ((Get-DslBool $attr @('main') $false) -and $attr.type) {
  5722. $mainSaved = ("$($attr.type)") -match '^(CatalogObject|DocumentObject|ChartOfAccountsObject|ChartOfCalculationTypesObject|ChartOfCharacteristicTypesObject|ExchangePlanObject|BusinessProcessObject|TaskObject)\.' -or ("$($attr.type)") -match 'RecordManager\.'
  5723. }
  5724. # Явный ключ savedData побеждает (в т.ч. false → суппресс авто-вывода $mainSaved); нет ключа → авто.
  5725. $emitSaved = if ($null -ne $attr.PSObject.Properties['savedData']) { (Get-DslBool $attr @('savedData') $false) } else { $mainSaved }
  5726. if ($emitSaved) {
  5727. X "$inner<SavedData>true</SavedData>"
  5728. }
  5729. # Save: сохранение значения реквизита в пользовательских настройках. true → <Field>имя</Field>;
  5730. # строка/массив → под-поля с авто-префиксом "имя." (путь с точкой / UUID / =имя — как есть).
  5731. # Нет ключа или false → не эмитим.
  5732. if ($null -ne $attr.PSObject.Properties['save'] -and $null -ne $attr.save) {
  5733. $saveFields = New-Object System.Collections.ArrayList
  5734. if ($attr.save -is [bool]) {
  5735. if ($attr.save) { [void]$saveFields.Add($attrName) }
  5736. } else {
  5737. foreach ($e in @($attr.save)) {
  5738. $fld = "$e"
  5739. if ([string]::IsNullOrEmpty($fld)) { continue }
  5740. if ($fld -ne $attrName -and $fld -notmatch '\.' -and $fld -notmatch '^\d+/\d+') { $fld = "$attrName.$fld" }
  5741. if (-not $saveFields.Contains($fld)) { [void]$saveFields.Add($fld) }
  5742. }
  5743. }
  5744. if ($saveFields.Count -gt 0) {
  5745. X "$inner<Save>"
  5746. foreach ($f in $saveFields) { X "$inner`t<Field>$(Esc-XmlText $f)</Field>" }
  5747. X "$inner</Save>"
  5748. }
  5749. }
  5750. # Проверка заполнения реквизита → <FillCheck> (реальный тег; <FillChecking> в схеме нет).
  5751. # bool true → ShowError (единственное значение в корпусе); строка → verbatim. Синоним fillChecking.
  5752. $fcRaw = if ($null -ne $attr.PSObject.Properties['fillCheck']) { $attr.fillCheck } elseif ($null -ne $attr.PSObject.Properties['fillChecking']) { $attr.fillChecking } else { $null }
  5753. if ($fcRaw) {
  5754. $fcv = if ($fcRaw -is [bool]) { 'ShowError' } else { "$fcRaw" }
  5755. X "$inner<FillCheck>$fcv</FillCheck>"
  5756. }
  5757. # UseAlways: поля, всегда читаемые (дин-список/таблица). Две формы DSL сливаются:
  5758. # attr.useAlways[] (короткие имена) + columns с useAlways:true → <Field>ИмяРеквизита.Поле</Field>.
  5759. $uaFields = New-Object System.Collections.ArrayList
  5760. if ($attr.useAlways) {
  5761. foreach ($e in @($attr.useAlways)) {
  5762. $fld = "$e"
  5763. # Префикс "ИмяРеквизита." добавляем к коротким именам. Поля дин-списка с маркером "~"
  5764. # (query-поля, ~13% корпуса) — префикс ставится ПОСЛЕ "~": ~Остановлен → ~Список.Остановлен.
  5765. # Полная форма (~Список.Остановлен / Список.Остановлен) — verbatim (forgiving ввод).
  5766. if ($fld.StartsWith('~')) {
  5767. $bare = $fld.Substring(1)
  5768. if ($bare -notmatch "^$([regex]::Escape($attrName))\.") { $bare = "$attrName.$bare" }
  5769. $fld = "~$bare"
  5770. } elseif ($fld -notmatch "^$([regex]::Escape($attrName))\." -and $fld -notmatch '^\d+/\d+') {
  5771. # UUID-ссылка (1/0:GUID) — НЕ префиксуем (платформа хранит её без "имя.")
  5772. $fld = "$attrName.$fld"
  5773. }
  5774. if (-not $uaFields.Contains($fld)) { [void]$uaFields.Add($fld) }
  5775. }
  5776. }
  5777. if ($attr.columns) {
  5778. foreach ($col in $attr.columns) {
  5779. if ((Get-DslBool $col @('useAlways') $false)) {
  5780. $fld = "$attrName.$($col.name)"
  5781. if (-not $uaFields.Contains($fld)) { [void]$uaFields.Add($fld) }
  5782. }
  5783. }
  5784. }
  5785. if ($uaFields.Count -gt 0) {
  5786. X "$inner<UseAlways>"
  5787. foreach ($f in $uaFields) { X "$inner`t<Field>$f</Field>" }
  5788. X "$inner</UseAlways>"
  5789. }
  5790. Emit-FunctionalOptions -fo $attr.functionalOptions -indent $inner
  5791. # Columns: прямые <Column> (ValueTable/Tree) + <AdditionalColumns table="X"> (доп. колонки
  5792. # табличных частей объекта). Порядок схемы: прямые сначала, затем AdditionalColumns-группы.
  5793. # Для дин-списка (есть settings) прямые колонки НЕ эмитим (служат лишь для UseAlways).
  5794. $hasDirectCols = $attr.columns -and $attr.columns.Count -gt 0 -and -not $attr.settings
  5795. $hasAddCols = $attr.additionalColumns -and @($attr.additionalColumns).Count -gt 0
  5796. if ($hasDirectCols -or $hasAddCols) {
  5797. X "$inner<Columns>"
  5798. if ($hasDirectCols) {
  5799. $seenCols = @{} # колонки уникальны в пределах своего реквизита
  5800. foreach ($col in $attr.columns) {
  5801. Assert-UniqueName -name "$($col.name)" -seen $seenCols -kind "column of '$attrName'"
  5802. Emit-AttrColumn -col $col -indent "$inner`t"
  5803. }
  5804. }
  5805. if ($hasAddCols) {
  5806. foreach ($ac in @($attr.additionalColumns)) {
  5807. # Пустой список колонок задаётся ЯВНО (`"columns": []`) — это законная форма,
  5808. # платформа так пишет таблицу, у которой доп. колонок нет. А вот отсутствие ключа
  5809. # — недосказанность автора: «доп. колонки есть», а какие, не указано. Раньше на
  5810. # этом PS падал с «Не удается индексировать в массив NULL» (@($null).Count = 1).
  5811. if ($null -eq $ac.PSObject.Properties['columns'] -or $null -eq $ac.columns) {
  5812. 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"
  5813. exit 1
  5814. }
  5815. $acCols = @($ac.columns)
  5816. if ($acCols.Count -eq 0) {
  5817. # Явно пустая группа → self-closing (как платформа)
  5818. X "$inner`t<AdditionalColumns table=`"$($ac.table)`"/>"
  5819. continue
  5820. }
  5821. X "$inner`t<AdditionalColumns table=`"$($ac.table)`">"
  5822. $seenAcCols = @{} # уникальность в пределах группы AdditionalColumns
  5823. foreach ($col in $acCols) {
  5824. Assert-UniqueName -name "$($col.name)" -seen $seenAcCols -kind "column of '$attrName'"
  5825. Emit-AttrColumn -col $col -indent "$inner`t`t"
  5826. }
  5827. X "$inner`t</AdditionalColumns>"
  5828. }
  5829. }
  5830. X "$inner</Columns>"
  5831. }
  5832. # Settings (динамический список)
  5833. if ($attr.settings) {
  5834. $st = $attr.settings
  5835. X "$inner<Settings xsi:type=`"DynamicList`">"
  5836. $si = "$inner`t"
  5837. # Порядок платформы: AutoFillAvailableFields, ManualQuery, DynamicDataRead, QueryText, Field*, MainTable, ListSettings
  5838. # AutoFillAvailableFields — дефолт true; эмитим только при заданном ключе (отклонение).
  5839. if ($null -ne $st.autoFillAvailableFields) { X "$si<AutoFillAvailableFields>$(if ($st.autoFillAvailableFields){'true'}else{'false'})</AutoFillAvailableFields>" }
  5840. $hasQuery = $st.query -and "$($st.query)".Trim()
  5841. # Явный ключ manualQuery (в т.ч. false) ПОБЕЖДАЕТ эвристику hasQuery (платформа изредка
  5842. # хранит QueryText при ManualQuery=false — декомпилятор фиксирует это отклонение).
  5843. $hasMQKey = ($st.PSObject.Properties['manualQuery']) -and ($null -ne $st.manualQuery)
  5844. $mq = if ($hasMQKey) { if ($st.manualQuery) { "true" } else { "false" } } elseif ($hasQuery) { "true" } else { "false" }
  5845. X "$si<ManualQuery>$mq</ManualQuery>"
  5846. # DynamicDataRead: дефолт true; false только при явном отключении
  5847. $ddr = if ((-not (Get-DslBool $st @('dynamicDataRead') $true))) { "false" } else { "true" }
  5848. X "$si<DynamicDataRead>$ddr</DynamicDataRead>"
  5849. if ($hasQuery) {
  5850. $qtext = Resolve-TextFromFile "$($st.query)" $script:queryBaseDir
  5851. X "$si<QueryText>$(Esc-XmlText $qtext)</QueryText>"
  5852. }
  5853. # Явные поля набора (редко): override title/dataPath
  5854. if ($st.fields) {
  5855. foreach ($fld in $st.fields) {
  5856. # Тип поля набора: DataSetFieldField (дефолт) vs DataSetFieldNestedDataSet
  5857. # (поле-вложенный набор = реквизит табличной части; маркер nested).
  5858. # folder = папка-группировка полей (DataSetFieldFolder, без <field>); nested = вложенный набор.
  5859. $isFolder = (ConvertTo-DslBool (Get-Prop $fld 'folder') 'folder' $false)
  5860. $ftype = if ($fld.nested) { "DataSetFieldNestedDataSet" } elseif ($isFolder) { "DataSetFieldFolder" } else { "DataSetFieldField" }
  5861. X "$si<Field xsi:type=`"dcssch:$ftype`">"
  5862. # dataPath: явный (включая пустой "" → self-closing <dcssch:dataPath/>) побеждает; иначе fallback на field.
  5863. if ($null -ne (Get-Prop $fld 'dataPath')) { $dp = "$($fld.dataPath)" }
  5864. elseif ($isFolder) { $dp = "" }
  5865. else { $dp = "$($fld.field)" }
  5866. if ($dp -eq "") { X "$si`t<dcssch:dataPath/>" } else { X "$si`t<dcssch:dataPath>$(Esc-XmlText "$dp")</dcssch:dataPath>" }
  5867. if (-not $isFolder) { X "$si`t<dcssch:field>$(Esc-XmlText "$($fld.field)")</dcssch:field>" }
  5868. if ($fld.title) {
  5869. X "$si`t<dcssch:title xsi:type=`"v8:LocalStringType`">"
  5870. Emit-MLItems -val $fld.title -indent "$si`t`t"
  5871. X "$si`t</dcssch:title>"
  5872. }
  5873. # Ограничения использования поля — после title, перед presentationExpression (порядок исходника)
  5874. Emit-RestrictBlock 'useRestriction' $fld.useRestriction "$si`t"
  5875. Emit-RestrictBlock 'attributeUseRestriction' $fld.attributeUseRestriction "$si`t"
  5876. # presentationExpression поля — перед valueType (порядок исходника)
  5877. if ($fld.presentationExpression) { X "$si`t<dcssch:presentationExpression>$(Esc-XmlText "$($fld.presentationExpression)")</dcssch:presentationExpression>" }
  5878. # valueType поля набора (тип значения; вычисляемые/кастомные поля)
  5879. if ($fld.valueType) { Emit-DLValueType -typeStr "$($fld.valueType)" -indent "$si`t" }
  5880. # appearance поля (формат/оформление) — после valueType (порядок исходника)
  5881. if ($fld.appearance) {
  5882. X "$si`t<dcssch:appearance>"
  5883. foreach ($prop in $fld.appearance.PSObject.Properties) { Emit-AppearanceValue -key $prop.Name -val $prop.Value -indent "$si`t`t" }
  5884. X "$si`t</dcssch:appearance>"
  5885. }
  5886. # inputParameters поля (связь по параметрам выбора) — в конце
  5887. if ($fld.inputParameters) { Emit-DLInputParameters -ip $fld.inputParameters -indent "$si`t" }
  5888. X "$si</Field>"
  5889. }
  5890. }
  5891. # Вычисляемые поля DataSet (<CalculatedField>) — после Field*, до Parameter*.
  5892. Emit-CalcFields -calcFields $st.calculatedFields -indent $si
  5893. # Schema-параметры дин-списка (DataCompositionSchemaParameter) — после Field*, до MainTable.
  5894. Emit-DLParameters -params $st.parameters -indent $si
  5895. # Ключ набора (query-based список без MainTable): KeyType (RowNumber/FieldValue/RowKey)
  5896. # + KeyField* — после Parameter*, до MainTable. Захват/эмит факт. значений.
  5897. if ($st.keyType) { X "$si<KeyType>$(Esc-XmlText "$($st.keyType)")</KeyType>" }
  5898. if ($st.keyFields) { foreach ($kf in @($st.keyFields)) { X "$si<KeyField>$(Esc-XmlText "$kf")</KeyField>" } }
  5899. if ($st.mainTable) { X "$si<MainTable>$(Normalize-MetaTypeRef "$($st.mainTable)")</MainTable>" }
  5900. # GetInvisibleFieldPresentations — после MainTable (дефолт true; эмитим только при заданном ключе = отклонении false).
  5901. if ($null -ne $st.getInvisibleFieldPresentations) { X "$si<GetInvisibleFieldPresentations>$(if ($st.getInvisibleFieldPresentations){'true'}else{'false'})</GetInvisibleFieldPresentations>" }
  5902. # AutoSaveUserSettings — после MainTable (дефолт true; эмитим только при заданном ключе = отклонении).
  5903. if ($null -ne $st.autoSaveUserSettings) { X "$si<AutoSaveUserSettings>$(if ($st.autoSaveUserSettings){'true'}else{'false'})</AutoSaveUserSettings>" }
  5904. # ListSettings: filter/order/conditionalAppearance (skd-грамматика) + каноничные блок-GUID.
  5905. # Нет items → контейнеры всё равно эмитятся (blockMeta) = каноничный пустой скелет платформы.
  5906. $lsi = "$si`t"
  5907. $lsOpenLen = $script:xml.Length
  5908. X "$si<ListSettings>"
  5909. $lsAfterOpenLen = $script:xml.Length # для self-closing, если внутри ничего не эмитнётся
  5910. if ($st.PSObject.Properties['listSettings'] -and $null -ne $st.listSettings) {
  5911. # Частичная/минимальная форма скелета — эмитим ТОЛЬКО указанные части с их блок-метой.
  5912. # meta: 'v'=viewMode, 'u'=userSettingID (контейнеры); itemsViewMode/itemsUserSettingID → present.
  5913. foreach ($prop in $st.listSettings.PSObject.Properties) {
  5914. $tag = $prop.Name; $pv = $prop.Value
  5915. # Значение дескриптора: строка-код "vu" ИЛИ объект { meta:"vu", presentation:<текст/ML> }
  5916. # (контейнер несёт собственный userSettingPresentation — кастомную подпись настройки).
  5917. if (($pv -is [PSCustomObject]) -or ($pv -is [System.Collections.IDictionary])) {
  5918. $meta = "$(Get-Prop $pv 'meta')"; $bpres = Get-Prop $pv 'presentation'
  5919. } else { $meta = "$pv"; $bpres = $null }
  5920. $bvm = if ($meta -match 'v') { 'Normal' } else { $null }
  5921. switch ($tag) {
  5922. '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 }
  5923. '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 }
  5924. '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 }
  5925. 'itemsViewMode' { X "$lsi<dcsset:itemsViewMode>Normal</dcsset:itemsViewMode>" }
  5926. 'itemsUserSettingID' { X "$lsi<dcsset:itemsUserSettingID>$($script:CANON_ITEMS_ID)</dcsset:itemsUserSettingID>" }
  5927. 'itemsUserSettingPresentation' { Emit-USPresentation -val $pv -tag "dcsset:itemsUserSettingPresentation" -indent $lsi }
  5928. 'dataParameters' { Emit-DataParameters -items $st.dataParameters -indent $lsi }
  5929. 'structure' { Emit-ListGrouping (Get-ListGroupingValue $st) $lsi }
  5930. }
  5931. }
  5932. } else {
  5933. # Полный каноничный скелет (умолчание, ~93% форм) — без изменений.
  5934. Emit-Filter -items $st.filter -indent $lsi -blockViewMode 'Normal' -blockUserSettingID $script:CANON_FILTER_ID
  5935. # dataParameters — после filter, до order (XSD-порядок ListSettings)
  5936. if ($st.PSObject.Properties['dataParameters']) { Emit-DataParameters -items $st.dataParameters -indent $lsi }
  5937. Emit-Order -items $st.order -indent $lsi -blockViewMode 'Normal' -blockUserSettingID $script:CANON_ORDER_ID
  5938. Emit-ConditionalAppearance -items $st.conditionalAppearance -indent $lsi -blockViewMode 'Normal' -blockUserSettingID $script:CANON_CA_ID
  5939. # Группировка строк списка (авторинг без round-trip дескриптора) — после CA, до itemsViewMode
  5940. Emit-ListGrouping (Get-ListGroupingValue $st) $lsi
  5941. X "$lsi<dcsset:itemsViewMode>Normal</dcsset:itemsViewMode>"
  5942. X "$lsi<dcsset:itemsUserSettingID>$($script:CANON_ITEMS_ID)</dcsset:itemsUserSettingID>"
  5943. }
  5944. if ($script:xml.Length -eq $lsAfterOpenLen) {
  5945. # Пустой дескриптор listSettings:{} (оригинал = <ListSettings/>) → зеркалим self-closing.
  5946. $script:xml.Length = $lsOpenLen
  5947. X "$si<ListSettings/>"
  5948. } else {
  5949. X "$si</ListSettings>"
  5950. }
  5951. X "$inner</Settings>"
  5952. }
  5953. X "$indent`t</Attribute>"
  5954. }
  5955. # Условное оформление формы — последний child <Attributes> (та же DCS-грамматика, что settings CA)
  5956. Emit-ConditionalAppearance -items $conditionalAppearance -indent "$indent`t" -wrapTag 'ConditionalAppearance'
  5957. X "$indent</Attributes>"
  5958. }
  5959. function Emit-Parameters {
  5960. param($params, [string]$indent)
  5961. if (-not $params -or $params.Count -eq 0) { return }
  5962. X "$indent<Parameters>"
  5963. $seenParams = @{}
  5964. foreach ($param in $params) {
  5965. Assert-UniqueName -name "$($param.name)" -seen $seenParams -kind 'parameter'
  5966. X "$indent`t<Parameter name=`"$($param.name)`">"
  5967. $inner = "$indent`t`t"
  5968. Emit-Type -typeStr "$($param.type)" -indent $inner
  5969. if ((Get-DslBool $param @('key') $false)) {
  5970. X "$inner<KeyParameter>true</KeyParameter>"
  5971. }
  5972. X "$indent`t</Parameter>"
  5973. }
  5974. X "$indent</Parameters>"
  5975. }
  5976. function Emit-Commands {
  5977. param($cmds, [string]$indent)
  5978. if (-not $cmds -or $cmds.Count -eq 0) { return }
  5979. X "$indent<Commands>"
  5980. $seenCmds = @{}
  5981. foreach ($cmd in $cmds) {
  5982. $cmdId = New-Id
  5983. Assert-UniqueName -name "$($cmd.name)" -seen $seenCmds -kind 'command'
  5984. X "$indent`t<Command name=`"$($cmd.name)`" id=`"$cmdId`">"
  5985. $inner = "$indent`t`t"
  5986. # Заголовок команды (зеркало Emit-Title): ключ есть+непустой → эмитим; ключ есть+"" → суппресс
  5987. # (в оригинале <Title> нет — не додумывать); ключ отсутствует → авто-вывод из имени (помощь модели).
  5988. if ($null -ne $cmd.PSObject.Properties['title']) {
  5989. if ($cmd.title) { Emit-MLText -tag "Title" -text $cmd.title -indent $inner }
  5990. } else {
  5991. $cmdTitle = Title-FromName -name "$($cmd.name)"
  5992. if ($cmdTitle) { Emit-MLText -tag "Title" -text $cmdTitle -indent $inner }
  5993. }
  5994. if ($cmd.tooltip) {
  5995. Emit-MLText -tag "ToolTip" -text $cmd.tooltip -indent $inner
  5996. }
  5997. # Порядок детей — как пишет платформа (XSD FormCommand, корпус без обратных случаев):
  5998. # Title ToolTip Use Shortcut Picture Action FunctionalOptions Representation ModifiesSavedData
  5999. # CurrentRowUse AssociatedTableElementId
  6000. if ($null -ne $cmd.use) { Emit-XrFlag -tag 'Use' -val $cmd.use -indent $inner }
  6001. if ($cmd.shortcut) {
  6002. X "$inner<Shortcut>$($cmd.shortcut)</Shortcut>"
  6003. }
  6004. Emit-CommandPicture -pic $cmd.picture -elemLt $cmd.loadTransparent -indent $inner
  6005. # Обработчик; в расширении — с видом вызова (callType), или несколько: actions [{handler, callType}]
  6006. if ($cmd.actions) {
  6007. foreach ($act in @($cmd.actions)) {
  6008. $ct = Normalize-CallType "$($act.callType)" "$($cmd.name)" 'Action'
  6009. $ctAttr = if ($ct) { " callType=`"$ct`"" } else { "" }
  6010. X "$inner<Action$ctAttr>$($act.handler)</Action>"
  6011. Register-Handler "$($act.handler)" 'command'
  6012. }
  6013. } elseif ($cmd.action) {
  6014. $ct = Normalize-CallType "$($cmd.callType)" "$($cmd.name)" 'Action'
  6015. $ctAttr = if ($ct) { " callType=`"$ct`"" } else { "" }
  6016. X "$inner<Action$ctAttr>$($cmd.action)</Action>"
  6017. Register-Handler "$($cmd.action)" 'command'
  6018. }
  6019. Emit-FunctionalOptions -fo $cmd.functionalOptions -indent $inner
  6020. # Значение — к перечислению команды (Text/Picture/TextPicture/Auto) приводит Normalize-EnumTags
  6021. if ($cmd.representation) {
  6022. X "$inner<Representation>$($cmd.representation)</Representation>"
  6023. }
  6024. if ((Get-DslBool $cmd @('modifiesSavedData') $false)) { X "$inner<ModifiesSavedData>true</ModifiesSavedData>" }
  6025. if ($cmd.currentRowUse) {
  6026. X "$inner<CurrentRowUse>$($cmd.currentRowUse)</CurrentRowUse>"
  6027. }
  6028. # Используемая таблица — имя элемента-таблицы (xsi:type обязателен).
  6029. # Forgiving-ключи: table / associatedTableElementId (XML-тег) / ИспользуемаяТаблица (рус., регистр-незав.)
  6030. $cmdTable = $cmd.table
  6031. if (-not $cmdTable) { $cmdTable = $cmd.associatedTableElementId }
  6032. if (-not $cmdTable) { $cmdTable = $cmd.используемаяТаблица }
  6033. if ($cmdTable) {
  6034. X "$inner<AssociatedTableElementId xsi:type=`"xs:string`">$(Esc-XmlText "$cmdTable")</AssociatedTableElementId>"
  6035. }
  6036. X "$indent`t</Command>"
  6037. }
  6038. X "$indent</Commands>"
  6039. }
  6040. function Resolve-CommandGroupKey {
  6041. param([string]$key, [string]$panelTag)
  6042. $k = ($key -replace '\s','').ToLower()
  6043. if ($panelTag -eq 'NavigationPanel') {
  6044. switch ($k) {
  6045. 'important' { return 'FormNavigationPanelImportant' }
  6046. 'важное' { return 'FormNavigationPanelImportant' }
  6047. 'goto' { return 'FormNavigationPanelGoTo' }
  6048. 'перейти' { return 'FormNavigationPanelGoTo' }
  6049. 'seealso' { return 'FormNavigationPanelSeeAlso' }
  6050. 'смтакже' { return 'FormNavigationPanelSeeAlso' }
  6051. }
  6052. } else {
  6053. switch ($k) {
  6054. 'important' { return 'FormCommandBarImportant' }
  6055. 'важное' { return 'FormCommandBarImportant' }
  6056. 'createbasedon' { return 'FormCommandBarCreateBasedOn' }
  6057. 'создатьнаосновании' { return 'FormCommandBarCreateBasedOn' }
  6058. }
  6059. }
  6060. return $key # verbatim
  6061. }
  6062. function Emit-CommandInterface {
  6063. param($ci, [string]$indent)
  6064. if (-not $ci) { return }
  6065. $inner = "$indent`t"
  6066. $panels = @(
  6067. # Порядок панелей — как в выгрузке: панель навигации раньше командной (607 из 607 форм корпуса)
  6068. @{ Tag='NavigationPanel'; Syns=@('navigationPanel','панельНавигации','ПанельНавигации') },
  6069. @{ Tag='CommandBar'; Syns=@('commandBar','команднаяПанель','КоманднаяПанель') }
  6070. )
  6071. $present = @()
  6072. foreach ($p in $panels) {
  6073. $items = $null
  6074. foreach ($syn in $p.Syns) { if ($null -ne $ci.PSObject.Properties[$syn]) { $items = $ci.($syn); break } }
  6075. if ($null -ne $items) { $present += ,@{ Tag=$p.Tag; Items=$items } }
  6076. }
  6077. if ($present.Count -eq 0) { return }
  6078. X "$indent<CommandInterface>"
  6079. foreach ($p in $present) {
  6080. X "$inner<$($p.Tag)>"
  6081. # Нормализация: плоский список пар (элемент, group-из-дерева). Объект → дерево.
  6082. $flat = New-Object System.Collections.ArrayList
  6083. if ($p.Items -is [System.Management.Automation.PSCustomObject]) {
  6084. foreach ($prop in $p.Items.PSObject.Properties) {
  6085. $grpFromTree = Resolve-CommandGroupKey -key $prop.Name -panelTag $p.Tag
  6086. foreach ($it in @($prop.Value)) { [void]$flat.Add(@{ item=$it; treeGroup=$grpFromTree }) }
  6087. }
  6088. } else {
  6089. foreach ($it in @($p.Items)) { [void]$flat.Add(@{ item=$it; treeGroup=$null }) }
  6090. }
  6091. foreach ($fi in $flat) {
  6092. $item = $fi.item; $treeGroup = $fi.treeGroup
  6093. if ($item -is [string]) {
  6094. $cmd = $item; $type = 'Auto'; $attr = $null; $grp = $null; $idx = $null; $dv = $null; $vis = $null
  6095. } else {
  6096. $cmd = Get-ElProp $item @('command','команда')
  6097. $type = Get-ElProp $item @('type','тип'); if (-not $type) { $type = 'Auto' }
  6098. $attr = Get-ElProp $item @('attribute','реквизит')
  6099. $grp = Get-ElProp $item @('group','группа','группаКоманд')
  6100. $idx = Get-ElProp $item @('index','индекс')
  6101. $dv = Get-ElProp $item @('defaultVisible','видимость','видимостьПоУмолчанию')
  6102. $vis = Get-ElProp $item @('visible','видимостьПоРолям','настройкаВидимости')
  6103. }
  6104. # group из дерева побеждает (если задан и непустой); явный group элемента — фолбэк
  6105. if ($treeGroup) { $grp = $treeGroup }
  6106. X "$inner`t<Item>"
  6107. X "$inner`t`t<Command>$(Esc-XmlText "$cmd")</Command>"
  6108. X "$inner`t`t<Type>$type</Type>"
  6109. if ($attr) { X "$inner`t`t<Attribute>$(Esc-XmlText "$attr")</Attribute>" }
  6110. if ($grp) { X "$inner`t`t<CommandGroup>$(Esc-XmlText "$grp")</CommandGroup>" }
  6111. if ($null -ne $idx) { X "$inner`t`t<Index>$idx</Index>" }
  6112. if ($null -ne $dv) { X "$inner`t`t<DefaultVisible>$(if ($dv){'true'}else{'false'})</DefaultVisible>" }
  6113. if ($null -ne $vis) { Emit-XrFlag -tag 'Visible' -val $vis -indent "$inner`t`t" }
  6114. X "$inner`t</Item>"
  6115. }
  6116. X "$inner</$($p.Tag)>"
  6117. }
  6118. X "$indent</CommandInterface>"
  6119. }
  6120. function Get-FormRootRank([string]$tag) {
  6121. $i = [array]::IndexOf(($script:formRootTagOrder -split ' '), $tag)
  6122. if ($i -lt 0) { return [array]::IndexOf(($script:formRootTagOrder -split ' '), 'AutoCommandBar') - 0.5 }
  6123. return $i
  6124. }
  6125. function Emit-Properties {
  6126. param($props, [string]$indent)
  6127. if (-not $props) { return }
  6128. # camelCase -> PascalCase mapping for known properties
  6129. $propMap = @{
  6130. "autoTitle" = "AutoTitle"
  6131. "windowOpeningMode" = "WindowOpeningMode"
  6132. "commandBarLocation" = "CommandBarLocation"
  6133. "saveDataInSettings" = "SaveDataInSettings"
  6134. "autoSaveDataInSettings" = "AutoSaveDataInSettings"
  6135. "autoTime" = "AutoTime"
  6136. "usePostingMode" = "UsePostingMode"
  6137. "repostOnWrite" = "RepostOnWrite"
  6138. "autoURL" = "AutoURL"
  6139. "autoFillCheck" = "AutoFillCheck"
  6140. "customizable" = "Customizable"
  6141. "enterKeyBehavior" = "EnterKeyBehavior"
  6142. "verticalScroll" = "VerticalScroll"
  6143. "scalingMode" = "ScalingMode"
  6144. "useForFoldersAndItems" = "UseForFoldersAndItems"
  6145. "reportResult" = "ReportResult"
  6146. "detailsData" = "DetailsData"
  6147. "reportFormType" = "ReportFormType"
  6148. "autoShowState" = "AutoShowState"
  6149. "width" = "Width"
  6150. "height" = "Height"
  6151. "group" = "Group"
  6152. }
  6153. foreach ($p in $props.PSObject.Properties) {
  6154. $xmlName = if ($propMap.ContainsKey($p.Name)) { $propMap[$p.Name] } else {
  6155. # Auto PascalCase: first letter uppercase
  6156. $p.Name.Substring(0,1).ToUpper() + $p.Name.Substring(1)
  6157. }
  6158. # Convert boolean to lowercase string (PS renders as True/False)
  6159. $val = $p.Value
  6160. # Пустая строка = суппресс-маркер (напр. autoTitle:"" — не эмитить и не додумывать)
  6161. if ($val -is [string] -and $val -eq '') { continue }
  6162. if ($val -is [bool]) {
  6163. $val = if ($val) { "true" } else { "false" }
  6164. }
  6165. X "$indent<$xmlName>$(Esc-XmlText "$val")</$xmlName>"
  6166. }
  6167. }
  6168. function Normalize-PanelSynonyms {
  6169. param($el)
  6170. if ($null -eq $el) { return }
  6171. $panelSyns = @{
  6172. 'commandBar' = @('commandBar','autoCommandBar','AutoCommandBar','autoCmdBar','cmdBar','КоманднаяПанель')
  6173. 'contextMenu' = @('contextMenu','ContextMenu','КонтекстноеМеню')
  6174. }
  6175. foreach ($canon in $panelSyns.Keys) {
  6176. foreach ($syn in $panelSyns[$canon]) {
  6177. $p = $el.PSObject.Properties[$syn]
  6178. if ($null -ne $p -and ($p.Value -is [array] -or $p.Value -is [System.Management.Automation.PSCustomObject])) {
  6179. if ($syn -ne $canon -and $null -eq $el.PSObject.Properties[$canon]) {
  6180. $v = $p.Value
  6181. $el.PSObject.Properties.Remove($syn) | Out-Null
  6182. $el | Add-Member -NotePropertyName $canon -NotePropertyValue $v -Force
  6183. }
  6184. break
  6185. }
  6186. }
  6187. }
  6188. }
  6189. function Normalize-ElementSynonyms {
  6190. param($el)
  6191. if ($null -eq $el) { return }
  6192. Normalize-PanelSynonyms $el
  6193. # Тип-синонимы (commandBar/autoCommandBar → элемент-тип) применяем ТОЛЬКО к строковому
  6194. # значению (имя элемента); объект/массив уже отнесён к панель-свойству выше.
  6195. $typeSyn = @{ "commandBar" = "cmdBar"; "autoCommandBar" = "autoCmdBar" }
  6196. foreach ($pair in $typeSyn.GetEnumerator()) {
  6197. $src = $el.PSObject.Properties[$pair.Key]
  6198. if ($null -ne $src -and ($src.Value -is [string]) -and $null -eq $el.PSObject.Properties[$pair.Value]) {
  6199. $val = $el.($pair.Key)
  6200. $el.PSObject.Properties.Remove($pair.Key) | Out-Null
  6201. $el | Add-Member -NotePropertyName $pair.Value -NotePropertyValue $val -Force
  6202. }
  6203. }
  6204. if ($el.PSObject.Properties["extTooltip"] -and $null -eq $el.PSObject.Properties["extendedTooltip"]) {
  6205. $val = $el.extTooltip
  6206. $el.PSObject.Properties.Remove("extTooltip") | Out-Null
  6207. $el | Add-Member -NotePropertyName "extendedTooltip" -NotePropertyValue $val -Force
  6208. }
  6209. # Рекурсия в детей панелей (commandBar/contextMenu) — нормализуем кнопки/группы внутри
  6210. foreach ($pk in @('commandBar','contextMenu')) {
  6211. $pp = $el.PSObject.Properties[$pk]
  6212. if ($null -ne $pp) {
  6213. $kids = if ($pp.Value -is [array]) { $pp.Value } elseif ($null -ne $pp.Value) { $pp.Value.children } else { $null }
  6214. if ($kids) { foreach ($child in $kids) { Normalize-ElementSynonyms $child } }
  6215. }
  6216. }
  6217. if ($el.PSObject.Properties["children"] -and $el.children) {
  6218. foreach ($child in $el.children) { Normalize-ElementSynonyms $child }
  6219. }
  6220. if ($el.PSObject.Properties["columns"] -and $el.columns) {
  6221. foreach ($child in $el.columns) { Normalize-ElementSynonyms $child }
  6222. }
  6223. }
  6224. # Явный ключ набора (FieldValue/RowKey/RowNumber) у списка без основной таблицы: ссылки в строке нет —
  6225. # нет и DefaultPicture. Признак берётся из XML реквизита (Settings/KeyType, Settings/MainTable).
  6226. function Test-DynListExplicitKey($attrNode) {
  6227. $kt = $attrNode.SelectSingleNode("f:Settings/f:KeyType", $nsMgr)
  6228. if ($null -eq $kt) { return $false }
  6229. $v = $kt.InnerText.Trim()
  6230. if ($v -eq '' -or $v -eq 'Auto') { return $false }
  6231. return ($null -eq $attrNode.SelectSingleNode("f:Settings/f:MainTable", $nsMgr))
  6232. }
  6233. function ApplyDynamicListTableHeuristic {
  6234. param($el, [string]$listName, [bool]$hasMainTable, [bool]$hasKeyType = $false)
  6235. if ($null -eq $el) { return }
  6236. if ($el.PSObject.Properties["table"] -and $null -ne $el.table -and "$($el.path)" -eq $listName) {
  6237. # Маркер дин-список-таблицы → Emit-Table эмитит блок свойств (Group A defaults)
  6238. $el | Add-Member -NotePropertyName "_dynList" -NotePropertyValue $true -Force
  6239. if ($null -eq $el.PSObject.Properties["tableAutofill"]) {
  6240. $el | Add-Member -NotePropertyName "tableAutofill" -NotePropertyValue $false -Force
  6241. }
  6242. if ($null -eq $el.PSObject.Properties["commandBarLocation"]) {
  6243. $el | Add-Member -NotePropertyName "commandBarLocation" -NotePropertyValue "None" -Force
  6244. }
  6245. # RowPictureDataPath: умный дефолт <Список>.DefaultPicture, если ключ ОТСУТСТВУЕТ.
  6246. # Декомпилятор опускает ключ при rpdp == smart-default (ждёт реинъекции); реальное отсутствие
  6247. # фиксирует ""-маркером (НЕ перезатирается). Гейт hasMainTable снят: дин-список без mainTable
  6248. # (напр. query-based) тоже несёт RowPictureDataPath. Но не при явном keyType: строка без ссылки,
  6249. # DefaultPicture платформа отвергает («Неверный путь к данным»); в корпусе у таких списков
  6250. # RowPictureDataPath нет ни разу.
  6251. if ($null -eq $el.PSObject.Properties["rowPictureDataPath"] -and -not $hasKeyType) {
  6252. $el | Add-Member -NotePropertyName "rowPictureDataPath" -NotePropertyValue "$listName.DefaultPicture" -Force
  6253. }
  6254. }
  6255. if ($el.PSObject.Properties["children"] -and $el.children) {
  6256. foreach ($child in $el.children) { ApplyDynamicListTableHeuristic $child $listName $hasMainTable $hasKeyType }
  6257. }
  6258. }
  6259. # === 6. Find element by name recursively ===
  6260. function Find-Element($startNode, [string]$targetName) {
  6261. foreach ($child in $startNode.ChildNodes) {
  6262. if ($child.NodeType -ne 'Element') { continue }
  6263. $childName = $child.GetAttribute("name")
  6264. if ($childName -eq $targetName) { return $child }
  6265. $ci = $child.SelectSingleNode("f:ChildItems", $nsMgr)
  6266. if ($ci) {
  6267. $found = Find-Element $ci $targetName
  6268. if ($found) { return $found }
  6269. }
  6270. }
  6271. return $null
  6272. }
  6273. # === 7. Detect indent level of a container's children ===
  6274. function Get-ChildIndent($container) {
  6275. foreach ($child in $container.ChildNodes) {
  6276. if ($child.NodeType -eq 'Whitespace' -or $child.NodeType -eq 'SignificantWhitespace') {
  6277. $text = $child.Value
  6278. if ($text -match '^\r?\n(\t+)$') { return $Matches[1] }
  6279. if ($text -match '^\r?\n(\t+)') { return $Matches[1] }
  6280. }
  6281. }
  6282. # Fallback: count depth from root
  6283. $depth = 0
  6284. $current = $container
  6285. while ($current -and $current -ne $xmlDoc.DocumentElement) {
  6286. $depth++
  6287. $current = $current.ParentNode
  6288. }
  6289. return "`t" * ($depth + 1)
  6290. }
  6291. # === 8. Insert node into container ===
  6292. function Insert-IntoContainer($container, $newNode, $afterName, $childIndent) {
  6293. $refNode = $null
  6294. if ($afterName) {
  6295. # Find the after-element, then insert after it
  6296. $afterElem = $null
  6297. foreach ($child in $container.ChildNodes) {
  6298. if ($child.NodeType -eq 'Element' -and $child.GetAttribute("name") -eq $afterName) {
  6299. $afterElem = $child
  6300. break
  6301. }
  6302. }
  6303. if ($afterElem) {
  6304. $refNode = $afterElem.NextSibling
  6305. } else {
  6306. Write-Host "[WARN] after='$afterName' not found in target container, appending at end"
  6307. }
  6308. }
  6309. if (-not $refNode) {
  6310. # Append at end: insert before trailing whitespace
  6311. $trailing = $container.LastChild
  6312. if ($trailing -and ($trailing.NodeType -eq 'Whitespace' -or $trailing.NodeType -eq 'SignificantWhitespace')) {
  6313. $refNode = $trailing
  6314. }
  6315. }
  6316. $ws = $xmlDoc.CreateWhitespace("`r`n$childIndent")
  6317. if ($refNode) {
  6318. $container.InsertBefore($ws, $refNode) | Out-Null
  6319. $container.InsertBefore($newNode, $refNode) | Out-Null
  6320. } else {
  6321. # Container is empty (self-closing) — add framing whitespace
  6322. $container.AppendChild($ws) | Out-Null
  6323. $container.AppendChild($newNode) | Out-Null
  6324. $parentIndent = if ($childIndent.Length -gt 1) { $childIndent.Substring(0, $childIndent.Length - 1) } else { "" }
  6325. $closeWs = $xmlDoc.CreateWhitespace("`r`n$parentIndent")
  6326. $container.AppendChild($closeWs) | Out-Null
  6327. }
  6328. }
  6329. # === 9. Generate fragment, parse, import nodes ===
  6330. # Все пространства имён корня формы — эмиттер пишет xsi:type, ent:, style: и др.
  6331. $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"'
  6332. function Parse-Fragment([string]$xmlText) {
  6333. $fragDoc = New-Object System.Xml.XmlDocument
  6334. $fragDoc.PreserveWhitespace = $true
  6335. $fragDoc.LoadXml($xmlText)
  6336. return $fragDoc
  6337. }
  6338. function Import-ElementNodes($fragDoc) {
  6339. $nodes = @()
  6340. foreach ($child in $fragDoc.DocumentElement.ChildNodes) {
  6341. if ($child.NodeType -eq 'Element') {
  6342. $nodes += $xmlDoc.ImportNode($child, $true)
  6343. }
  6344. }
  6345. return $nodes
  6346. }
  6347. # === 9c. Помощники операций над деревом элементов ===
  6348. function Fail([string]$msg) {
  6349. Write-Host "[ERROR] $msg"
  6350. exit 1
  6351. }
  6352. function Same($a, $b) { return [object]::ReferenceEquals($a, $b) }
  6353. function Test-IsWs($n) {
  6354. return ($null -ne $n -and ($n.NodeType -eq 'Whitespace' -or $n.NodeType -eq 'SignificantWhitespace'))
  6355. }
  6356. function Get-NextElementSibling($n) {
  6357. $s = $n.NextSibling
  6358. while ($null -ne $s -and $s.NodeType -ne 'Element') { $s = $s.NextSibling }
  6359. return $s
  6360. }
  6361. function Get-FirstElementChild($n) {
  6362. foreach ($c in $n.ChildNodes) { if ($c.NodeType -eq 'Element') { return $c } }
  6363. return $null
  6364. }
  6365. function Get-ContainerLabel($c) {
  6366. if (Same $c $root) { return "корень формы" }
  6367. return $c.GetAttribute("name")
  6368. }
  6369. # Вставка узла в контейнер: перед $ref или в конец. Перевод строки с отступом идёт перед каждым
  6370. # дочерним узлом, у пустого контейнера — ещё и закрывающий с отступом родителя.
  6371. function Insert-NodeAt($container, $node, $ref, [string]$indent) {
  6372. if ($null -ne $ref) {
  6373. $container.InsertBefore($node, $ref) | Out-Null
  6374. $container.InsertBefore($xmlDoc.CreateWhitespace("`r`n$indent"), $ref) | Out-Null
  6375. return
  6376. }
  6377. $trailing = $container.LastChild
  6378. if (Test-IsWs $trailing) {
  6379. $container.InsertBefore($xmlDoc.CreateWhitespace("`r`n$indent"), $trailing) | Out-Null
  6380. $container.InsertBefore($node, $trailing) | Out-Null
  6381. } else {
  6382. $container.AppendChild($xmlDoc.CreateWhitespace("`r`n$indent")) | Out-Null
  6383. $container.AppendChild($node) | Out-Null
  6384. $parentIndent = if ($indent.Length -gt 0) { $indent.Substring(0, $indent.Length - 1) } else { "" }
  6385. $container.AppendChild($xmlDoc.CreateWhitespace("`r`n$parentIndent")) | Out-Null
  6386. }
  6387. }
  6388. # Дочерний узел элемента — на его каноническое место (см. 9b). Неизвестный тег — в конец.
  6389. function Insert-ChildCanonical($parent, $child) {
  6390. $rank = Get-ChildRank $parent.LocalName $child.LocalName
  6391. $ref = $null
  6392. if ($rank -ge 0) {
  6393. foreach ($c in $parent.ChildNodes) {
  6394. if ($c.NodeType -ne 'Element') { continue }
  6395. if ((Get-ChildRank $parent.LocalName $c.LocalName) -gt $rank) { $ref = $c; break }
  6396. }
  6397. }
  6398. Insert-NodeAt $parent $child $ref (Get-ChildIndent $parent)
  6399. }
  6400. # Узел вместе с переводом строки перед ним.
  6401. function Remove-NodeWithWs($node) {
  6402. $parent = $node.ParentNode
  6403. $prev = $node.PreviousSibling
  6404. if (Test-IsWs $prev) { $parent.RemoveChild($prev) | Out-Null }
  6405. $parent.RemoveChild($node) | Out-Null
  6406. }
  6407. # Пустой ChildItems платформа не пишет никогда: у группы без элементов тега просто нет.
  6408. function Remove-IfEmptyChildItems($ci) {
  6409. if ($null -ne (Get-FirstElementChild $ci)) { return }
  6410. Remove-NodeWithWs $ci
  6411. if (Same $ci $script:rootCI) { $script:rootCI = $null }
  6412. }
  6413. $script:rootAfterChildItems = @('Attributes','Parameters','Commands','CommandInterface','ConditionalAppearance','BaseForm')
  6414. function Get-OrCreateChildItems($container) {
  6415. $ci = $container.SelectSingleNode("f:ChildItems", $nsMgr)
  6416. if ($null -ne $ci) { return $ci }
  6417. $ci = $xmlDoc.CreateElement("ChildItems", $formNs)
  6418. if (Same $container $root) {
  6419. # ChildItems формы — после Events или AutoCommandBar, иначе перед первой из следующих секций
  6420. $insertAfter = $root.SelectSingleNode("f:Events", $nsMgr)
  6421. if ($null -eq $insertAfter) { $insertAfter = $root.SelectSingleNode("f:AutoCommandBar", $nsMgr) }
  6422. $ref = $null
  6423. if ($null -ne $insertAfter) {
  6424. $ref = Get-NextElementSibling $insertAfter
  6425. } else {
  6426. foreach ($c in $root.ChildNodes) {
  6427. if ($c.NodeType -eq 'Element' -and $script:rootAfterChildItems -contains $c.LocalName) { $ref = $c; break }
  6428. }
  6429. }
  6430. Insert-NodeAt $root $ci $ref "`t"
  6431. $script:rootCI = $ci
  6432. } else {
  6433. Insert-ChildCanonical $container $ci
  6434. }
  6435. return $ci
  6436. }
  6437. function Get-NodeIndent($node) {
  6438. $prev = $node.PreviousSibling
  6439. if ((Test-IsWs $prev) -and $prev.Value -match '\n(\t*)$') { return $Matches[1] }
  6440. return ""
  6441. }
  6442. # Сдвиг отступов поддерева при смене глубины: каждый перевод строки внутри узла начинается с отступа
  6443. # старого места — меняем этот префикс на новый.
  6444. function Set-SubtreeIndent($node, [string]$oldIndent, [string]$newIndent) {
  6445. if ($oldIndent -eq $newIndent) { return }
  6446. foreach ($c in $node.ChildNodes) {
  6447. if (Test-IsWs $c) {
  6448. if ($c.Value -match '^(\r?\n)(\t*)$' -and $Matches[2].StartsWith($oldIndent)) {
  6449. $c.Value = $Matches[1] + $newIndent + $Matches[2].Substring($oldIndent.Length)
  6450. }
  6451. } elseif ($c.NodeType -eq 'Element') {
  6452. Set-SubtreeIndent $c $oldIndent $newIndent
  6453. }
  6454. }
  6455. }
  6456. # Элемент формы по имени: дерево ChildItems и командная панель формы (с кнопками). BaseForm,
  6457. # реквизиты и команды не просматриваются. Имена в 1С регистронезависимы.
  6458. function Find-FormElement([string]$name) {
  6459. $scopes = @()
  6460. if ($null -ne $script:rootCI) { $scopes += $script:rootCI }
  6461. $acb = $root.SelectSingleNode("f:AutoCommandBar", $nsMgr)
  6462. if ($null -ne $acb) {
  6463. if ($acb.GetAttribute("name") -eq $name) { return $acb }
  6464. $scopes += $acb
  6465. }
  6466. # Элементы — узлы ChildItems и служебные узлы элемента (для внятного отказа); <Event name=…> и
  6467. # прочие именованные свойства — не элементы.
  6468. foreach ($s in $scopes) {
  6469. foreach ($n in $s.SelectNodes(".//*[@name]")) {
  6470. if ($n.NamespaceURI -ne $formNs -or $n.GetAttribute("name") -ne $name) { continue }
  6471. if ($n.ParentNode.LocalName -eq 'ChildItems' -or $script:companionTags -contains $n.LocalName) { return $n }
  6472. }
  6473. }
  6474. return $null
  6475. }
  6476. function Get-NearestTable($node, [bool]$inclusive) {
  6477. $cur = if ($inclusive) { $node } else { $node.ParentNode }
  6478. while ($null -ne $cur -and $cur.NodeType -eq 'Element') {
  6479. if ($cur.LocalName -eq 'Table') { return $cur }
  6480. $cur = $cur.ParentNode
  6481. }
  6482. return $null
  6483. }
  6484. function Test-IsInside($node, $anc) {
  6485. $cur = $node
  6486. while ($null -ne $cur -and $cur.NodeType -eq 'Element') {
  6487. if (Same $cur $anc) { return $true }
  6488. $cur = $cur.ParentNode
  6489. }
  6490. return $false
  6491. }
  6492. # Позиция операции: контейнер + узел, перед которым вставлять ($null — в конец).
  6493. # after/before — контейнер якоря; into — в конец (first — в начало); first без into — начало формы.
  6494. function Resolve-Position($op, [string]$ctx, [bool]$required) {
  6495. $after = $op.after; $before = $op.before; $into = $op.into
  6496. $first = (ConvertTo-DslBool $op.first "${ctx}: first" $false)
  6497. if ($after -and $before) { Fail "${ctx}: укажи что-то одно — after или before" }
  6498. $anchorName = if ($after) { "$after" } elseif ($before) { "$before" } else { $null }
  6499. if ($first -and $anchorName) { Fail "${ctx}: first — это начало контейнера, вместе с after/before не задаётся" }
  6500. $intoEl = $null
  6501. if ($into) {
  6502. $intoEl = Find-FormElement "$into"
  6503. if ($null -eq $intoEl) { Fail "${ctx}: контейнер '$into' не найден в форме" }
  6504. }
  6505. if ($anchorName) {
  6506. $anchor = Find-FormElement $anchorName
  6507. if ($null -eq $anchor) { Fail "${ctx}: элемент '$anchorName' не найден в форме" }
  6508. $ci = $anchor.ParentNode
  6509. if ($ci.LocalName -ne 'ChildItems') { Fail "${ctx}: '$anchorName' — служебный узел ($($anchor.LocalName)), рядом с ним ставить нельзя" }
  6510. $container = $ci.ParentNode
  6511. if ($null -ne $intoEl -and -not (Same $intoEl $container)) {
  6512. Fail "${ctx}: '$anchorName' лежит в '$(Get-ContainerLabel $container)', а не в '$into'"
  6513. }
  6514. if ($after) {
  6515. return @{ Container = $container; Ref = (Get-NextElementSibling $anchor); Anchor = $anchor; Desc = "$(Get-ContainerLabel $container), после $anchorName" }
  6516. }
  6517. return @{ Container = $container; Ref = $anchor; Anchor = $anchor; Desc = "$(Get-ContainerLabel $container), перед $anchorName" }
  6518. }
  6519. if ($null -eq $intoEl -and $first) { $intoEl = $root }
  6520. if ($null -ne $intoEl) {
  6521. $ref = $null
  6522. if ($first) {
  6523. $ci = $intoEl.SelectSingleNode("f:ChildItems", $nsMgr)
  6524. if ($null -ne $ci) { $ref = Get-FirstElementChild $ci }
  6525. }
  6526. $where = if ($first) { "первым" } else { "в конец" }
  6527. return @{ Container = $intoEl; Ref = $ref; Anchor = $null; Desc = "$(Get-ContainerLabel $intoEl), $where" }
  6528. }
  6529. if ($required) { Fail "${ctx}: не указано, куда — нужен after, before или into" }
  6530. return $null
  6531. }
  6532. $script:containerTags = @('UsualGroup','Page','Pages','Table','ColumnGroup','CommandBar','AutoCommandBar','ButtonGroup','Popup','ContextMenu')
  6533. $script:barTags = @('CommandBar','AutoCommandBar','ButtonGroup','Popup','ContextMenu')
  6534. $script:barItemTags = @('Button','ButtonGroup','Popup')
  6535. $script:additionTags = @('SearchStringAddition','ViewStatusAddition','SearchControlAddition')
  6536. $script:tableItemTags = @('InputField','CheckBoxField','LabelField','PictureField','ColumnGroup')
  6537. $script:companionTags = @('ContextMenu','ExtendedTooltip','AutoCommandBar','SearchStringAddition','ViewStatusAddition','SearchControlAddition')
  6538. $script:dslTagMap = @{
  6539. "radio"="RadioButtonField"; "columnGroup"="ColumnGroup"; "buttonGroup"="ButtonGroup"
  6540. "searchString"="SearchStringAddition"; "viewStatus"="ViewStatusAddition"; "searchControl"="SearchControlAddition"
  6541. "spreadsheet"="SpreadSheetDocumentField"; "html"="HTMLDocumentField"; "textDoc"="TextDocumentField"
  6542. "formattedDoc"="FormattedDocumentField"; "progressBar"="ProgressBarField"; "trackBar"="TrackBarField"
  6543. "chart"="ChartField"; "ganttChart"="GanttChartField"; "graphicalSchema"="GraphicalSchemaField"
  6544. "planner"="PlannerField"; "periodField"="PeriodField"; "dendrogram"="DendrogramField"
  6545. "group"="UsualGroup"; "input"="InputField"; "check"="CheckBoxField"; "label"="LabelDecoration"
  6546. "labelField"="LabelField"; "table"="Table"; "pages"="Pages"; "page"="Page"; "button"="Button"
  6547. "picture"="PictureDecoration"; "picField"="PictureField"; "calendar"="CalendarField"; "cmdBar"="CommandBar"; "popup"="Popup"
  6548. }
  6549. # Может ли элемент типа $nt лечь в $container. $node — переносимый узел (у добавления $null).
  6550. function Assert-Placement([string]$nt, [string]$name, $node, $container, [string]$ctx) {
  6551. $isRoot = Same $container $root
  6552. $ct = if ($isRoot) { "Form" } else { $container.LocalName }
  6553. $cl = Get-ContainerLabel $container
  6554. if (-not $isRoot -and $script:containerTags -notcontains $ct) { Fail "${ctx}: '$cl' ($ct) не контейнер — в него нельзя положить элемент" }
  6555. if ($null -ne $node -and (Test-IsInside $container $node)) { Fail "${ctx}: '$name' нельзя перенести внутрь самого себя — '$cl' лежит внутри '$name'" }
  6556. if ($nt -eq 'Page' -and $ct -ne 'Pages') { Fail "${ctx}: страница '$name' может лежать только в группе страниц (Pages), а '$cl' — $ct" }
  6557. if ($ct -eq 'Pages' -and $nt -ne 'Page') { Fail "${ctx}: в группе страниц '$cl' лежат только страницы (Page), а '$name' — $nt" }
  6558. if ($script:barTags -contains $ct -and $script:barItemTags -notcontains $nt -and $script:additionTags -notcontains $nt) { Fail "${ctx}: в командной панели '$cl' лежат только кнопки, группы кнопок, подменю и дополнения таблицы, а '$name' — $nt" }
  6559. # Группа кнопок и подменю — только внутри командной панели, меню, подменю или группы кнопок (по корпусу)
  6560. if (@('ButtonGroup','Popup') -contains $nt -and $script:barTags -notcontains $ct) { Fail "${ctx}: '$name' ($nt) лежит только в командной панели, контекстном меню, подменю или группе кнопок, а '$cl' — $ct" }
  6561. if ($nt -eq 'ColumnGroup' -and $null -eq (Get-NearestTable $container $true)) { Fail "${ctx}: группа колонок '$name' может лежать только внутри таблицы" }
  6562. # Колонки таблицы — только поля и группы колонок (по корпусу других типов там нет);
  6563. # командная панель и контекстное меню таблицы — свои правила выше.
  6564. $inTable = if ($isRoot) { $null } else { Get-NearestTable $container $true }
  6565. if ($null -ne $inTable -and $script:barTags -notcontains $ct -and $script:tableItemTags -notcontains $nt) {
  6566. Fail "${ctx}: в таблице '$($inTable.GetAttribute('name'))' лежат только колонки (поля и группы колонок), а '$name' — $nt"
  6567. }
  6568. # Граница таблицы: колонки и поля табличной части привязаны к своей таблице. Кнопки — нет
  6569. # (стандартная команда таблицы законно стоит и в командной панели формы).
  6570. if ($null -ne $node -and $script:barItemTags -notcontains $nt) {
  6571. $from = Get-NearestTable $node $false
  6572. $to = if ($isRoot) { $null } else { Get-NearestTable $container $true }
  6573. if (-not (Same $from $to)) {
  6574. if ($null -ne $from) { Fail "${ctx}: '$name' принадлежит таблице '$($from.GetAttribute('name'))' — вынести его за её пределы или в другую таблицу нельзя" }
  6575. Fail "${ctx}: '$name' не принадлежит таблице — внутрь таблицы '$($to.GetAttribute('name'))' его перенести нельзя"
  6576. }
  6577. }
  6578. }
  6579. function Assert-OpKeys($op, [string[]]$allowed, [string]$ctx) {
  6580. foreach ($p in $op.PSObject.Properties) {
  6581. if ($allowed -notcontains $p.Name) { Fail "${ctx}: неизвестный ключ '$($p.Name)'; допустимы: $($allowed -join ', ')" }
  6582. }
  6583. }
  6584. # --- Добавление ---
  6585. $script:chainNode = $null
  6586. $script:defaultPos = $null
  6587. function Invoke-Add($op, [string]$typeKey, [int]$idx) {
  6588. $name = Get-ElementName -el $op -typeKey $typeKey
  6589. $ctx = "elements[$idx] $typeKey '$name'"
  6590. # Имя уже есть в форме — на момент этой операции (удалённое раньше в списке — свободно)
  6591. $existing = Find-FormElement $name
  6592. if ($null -ne $existing) {
  6593. Write-Host "[ERROR] Element '$name' already exists in form (id=$($existing.GetAttribute('id'))) — element names must be unique"
  6594. exit 1
  6595. }
  6596. $pos = Resolve-Position $op $ctx $false
  6597. if ($null -eq $pos) {
  6598. # Без своей позиции — как раньше: верхние into/after, следующие встают за предыдущим.
  6599. if ($null -ne $script:chainNode) {
  6600. $c = $script:chainNode.ParentNode.ParentNode
  6601. $pos = @{ Container = $c; Ref = (Get-NextElementSibling $script:chainNode); Anchor = $null; Desc = "$(Get-ContainerLabel $c), после $($script:chainNode.GetAttribute('name'))" }
  6602. } else {
  6603. if ($null -eq $script:defaultPos) {
  6604. $script:defaultPos = Resolve-Position $def "elements (верхние into/after)" $false
  6605. if ($null -eq $script:defaultPos) { $script:defaultPos = @{ Container = $root; Ref = $null; Anchor = $null; Desc = "корень формы, в конец" } }
  6606. }
  6607. $pos = $script:defaultPos
  6608. }
  6609. $chained = $true
  6610. } else {
  6611. $chained = $false
  6612. }
  6613. Assert-Placement $script:dslTagMap[$typeKey] $name $null $pos.Container $ctx
  6614. # Эмиттеру — копия элемента без ключей позиции (это не свойства элемента)
  6615. $el = (ConvertFrom-JsonInput ($op | ConvertTo-Json -Depth 100 -Compress) 'element copy') | Select-Object -Property * -ExcludeProperty into, after, before, first
  6616. Normalize-ElementSynonyms $el
  6617. # Таблица динамического списка получает поведение списка, как в form-compile
  6618. foreach ($a in $root.SelectNodes("f:Attributes/f:Attribute", $nsMgr)) {
  6619. $t = $a.SelectSingleNode("f:Type/v8:Type", $nsMgr)
  6620. if ($null -ne $t -and $t.InnerText.Trim() -eq 'cfg:DynamicList') { ApplyDynamicListTableHeuristic $el $a.GetAttribute('name') $true (Test-DynListExplicitKey $a) }
  6621. }
  6622. # Пул имён эмиттера — имена элементов формы на момент операции (без узлов событий)
  6623. $script:seenElementNames = @{}
  6624. foreach ($sc in (Get-ElementScopes)) {
  6625. foreach ($n in $sc.SelectNodes(".//*[@name]")) {
  6626. if ($n.NamespaceURI -eq $formNs -and ($n.ParentNode.LocalName -eq 'ChildItems' -or $script:companionTags -contains $n.LocalName)) {
  6627. $script:seenElementNames[$n.GetAttribute('name')] = $true
  6628. }
  6629. }
  6630. }
  6631. $script:currentTableName = $null
  6632. # Дополнение таблицы: источник — source или таблица, внутри которой оно лежит
  6633. if ($script:additionTags -contains $script:dslTagMap[$typeKey]) {
  6634. if ($el.source) {
  6635. $src = Find-FormElement "$($el.source)"
  6636. if ($null -eq $src -or $src.LocalName -ne 'Table') { Fail "${ctx}: source '$($el.source)' — нет такой таблицы в форме" }
  6637. $el.source = $src.GetAttribute('name')
  6638. } else {
  6639. $tbl = if (Same $pos.Container $root) { $null } else { Get-NearestTable $pos.Container $true }
  6640. if ($null -eq $tbl) { Fail "${ctx}: укажите source — таблицу, к которой относится дополнение" }
  6641. $script:currentTableName = $tbl.GetAttribute('name')
  6642. }
  6643. }
  6644. $ci = Get-OrCreateChildItems $pos.Container
  6645. $indent = Get-ChildIndent $ci
  6646. $script:xml = New-Object System.Text.StringBuilder 4096
  6647. # Внутри командной панели, меню, подменю или группы кнопок кнопка — кнопка панели
  6648. $inBar = $false
  6649. $cur = $pos.Container
  6650. while ($null -ne $cur -and $cur.NodeType -eq 'Element') {
  6651. if ($script:barTags -contains $cur.LocalName) { $inBar = $true; break }
  6652. $cur = $cur.ParentNode
  6653. }
  6654. # Обработчики элементов внутри таблицы — в область этой таблицы
  6655. $tbl = if (Same $pos.Container $root) { $null } else { Get-NearestTable $pos.Container $true }
  6656. $script:handlerTable = if ($null -ne $tbl) { $tbl.GetAttribute('name') } else { '' }
  6657. X "<_F $allNsDecl>"
  6658. Emit-Element -el $el -indent $indent -inCmdBar $inBar
  6659. X "</_F>"
  6660. $script:handlerTable = ''
  6661. $node = @(Import-ElementNodes (Parse-Fragment (Sort-ElementTagOrder (Normalize-EnumTags $script:xml.ToString()))))[0]
  6662. Insert-NodeAt $ci $node $pos.Ref $indent
  6663. if ($chained) { $script:chainNode = $node }
  6664. $pathStr = if ($op.path) { " -> $($op.path)" } else { "" }
  6665. $evtNames = @($node.SelectNodes("f:Events/f:Event", $nsMgr) | ForEach-Object { $_.GetAttribute('name') })
  6666. $evtStr = if ($evtNames.Count -gt 0) { " {$($evtNames -join ', ')}" } else { "" }
  6667. $script:opLog += " + [$($node.LocalName)] $name$pathStr$evtStr → $($pos.Desc)"
  6668. $script:addedCount++
  6669. }
  6670. # --- Командная панель формы (autoCmdBar, как в form-compile) ---
  6671. # Кнопки из children — в командную панель формы (в конец, по порядку); autofill и horizontalAlign — её свойства.
  6672. function Invoke-AutoCmdBar($op, [int]$idx) {
  6673. $ctx = "elements[$idx] autoCmdBar"
  6674. $acbNode = $root.SelectSingleNode("f:AutoCommandBar", $nsMgr)
  6675. if ($null -eq $acbNode) { Fail "${ctx}: у формы нет командной панели" }
  6676. Assert-OpKeys $op @('autoCmdBar','children','autofill','horizontalAlign') $ctx
  6677. if ($null -ne $op.PSObject.Properties['autofill']) {
  6678. if ($null -eq $op.autofill) { Fail "${ctx}: autofill — true или false" }
  6679. $af = (ConvertTo-DslBool $op.autofill "${ctx}: autofill" $false)
  6680. Set-ValueTag $acbNode 'Autofill' $(if ($af) { 'true' } else { 'false' })
  6681. $script:opLog += " * $($acbNode.GetAttribute('name')): autofill=$(if ($af) { 'true' } else { 'false' }) → Autofill"
  6682. $script:changedCount++
  6683. }
  6684. if ($op.horizontalAlign) {
  6685. Set-SimpleTag $acbNode 'HorizontalAlign' "$($op.horizontalAlign)"
  6686. $script:opLog += " * $($acbNode.GetAttribute('name')): horizontalAlign=$($op.horizontalAlign) → HorizontalAlign"
  6687. $script:changedCount++
  6688. }
  6689. foreach ($child in @($op.children)) {
  6690. if ($null -eq $child) { continue }
  6691. if (-not ($child -is [System.Management.Automation.PSCustomObject])) { Fail "${ctx}: в children — не элемент (нужна кнопка, группа кнопок или подменю)" }
  6692. foreach ($pk in @('into','after','before','first')) {
  6693. if ($null -ne $child.PSObject.Properties[$pk]) { Fail "${ctx}: у кнопок в children нет позиции — они встают в конец панели по порядку; для места укажите кнопку отдельным элементом с into и after/before" }
  6694. }
  6695. Normalize-ElementTypeSynonyms $child
  6696. $tk = $null
  6697. foreach ($k in $elemTypeKeys) { if ($null -ne $child.PSObject.Properties[$k]) { $tk = $k; break } }
  6698. if ($null -eq $tk) { Fail "${ctx}: в children — не элемент (нужна кнопка, группа кнопок или подменю)" }
  6699. $c = $child | Select-Object -Property *
  6700. $c | Add-Member -NotePropertyName 'into' -NotePropertyValue $acbNode.GetAttribute('name') -Force
  6701. Invoke-Add $c $tk $idx
  6702. }
  6703. }
  6704. # --- Перенос ---
  6705. function Invoke-Move($op, [int]$idx) {
  6706. $ctx = "elements[$idx] move"
  6707. Assert-OpKeys $op @('move','after','before','into','first') $ctx
  6708. $names = @(@($op.move) | ForEach-Object { "$_" } | Where-Object { $_ })
  6709. if ($names.Count -eq 0) { Fail "${ctx}: укажи имя элемента или список имён" }
  6710. $nodes = @()
  6711. $seen = @{}
  6712. foreach ($n in $names) {
  6713. if ($seen.ContainsKey($n)) { Fail "${ctx}: '$n' указан дважды" }
  6714. $seen[$n] = $true
  6715. $node = Find-FormElement $n
  6716. if ($null -eq $node) { Fail "${ctx}: элемент '$n' не найден в форме" }
  6717. if ($node.ParentNode.LocalName -ne 'ChildItems' -or $script:companionTags -contains $node.LocalName) {
  6718. Fail "${ctx}: '$n' — служебный узел ($($node.LocalName)) своего элемента, переносится только вместе с ним"
  6719. }
  6720. $nodes += $node
  6721. }
  6722. $pos = Resolve-Position $op $ctx $true
  6723. foreach ($node in $nodes) {
  6724. if (Same $node $pos.Anchor) { Fail "${ctx}: '$($node.GetAttribute('name'))' не может быть якорем собственного переноса" }
  6725. Assert-Placement $node.LocalName $node.GetAttribute('name') $node $pos.Container $ctx
  6726. }
  6727. $ref = $pos.Ref
  6728. $desc = $pos.Desc
  6729. $prev = $null
  6730. foreach ($node in $nodes) {
  6731. $name = $node.GetAttribute('name')
  6732. if ($null -ne $prev) {
  6733. $ref = Get-NextElementSibling $prev
  6734. $desc = "$(Get-ContainerLabel $pos.Container), после $($prev.GetAttribute('name'))"
  6735. }
  6736. $fromCI = $node.ParentNode
  6737. $targetCI = $pos.Container.SelectSingleNode("f:ChildItems", $nsMgr)
  6738. if ((Same $fromCI $targetCI) -and ((Same $ref $node) -or (Same $ref (Get-NextElementSibling $node)))) {
  6739. $script:opLog += " = ${name}: уже на месте ($desc)"
  6740. $prev = $node
  6741. continue
  6742. }
  6743. $fromLabel = Get-ContainerLabel $fromCI.ParentNode
  6744. # Отступ цели — до отцепления: если узел был в ней единственным, после отцепления
  6745. # первым пробельным узлом окажется закрывающий с отступом родителя.
  6746. $newIndent = if ($null -ne $targetCI) { Get-ChildIndent $targetCI } else { $null }
  6747. $oldIndent = Get-NodeIndent $node
  6748. Remove-NodeWithWs $node
  6749. $ci = Get-OrCreateChildItems $pos.Container
  6750. if ($null -eq $newIndent) { $newIndent = Get-ChildIndent $ci }
  6751. Insert-NodeAt $ci $node $ref $newIndent
  6752. Set-SubtreeIndent $node $oldIndent $newIndent
  6753. if (-not (Same $fromCI $ci)) { Remove-IfEmptyChildItems $fromCI }
  6754. $script:opLog += " ~ ${name}: $fromLabel → $desc"
  6755. $script:movedCount++
  6756. $prev = $node
  6757. }
  6758. }
  6759. # --- Изменение свойств ---
  6760. # Умолчания платформы: в корпусе эти теги встречаются только с противоположным значением —
  6761. # значение по умолчанию платформа не пишет, и set его не пишет, а убирает тег.
  6762. $script:tagDefaults = @{
  6763. 'Visible'='true'; 'Enabled'='true'; 'ReadOnly'='false'; 'ShowTitle'='true'; 'United'='true'; 'Collapsed'='false'
  6764. 'AutoMaxWidth'='true'; 'AutoMaxHeight'='true'; 'Hyperlink'='false'; 'Hiperlink'='false'
  6765. }
  6766. # Умолчания перечислений зависят от типа элемента: значение из области, которого в корпусе нет ни
  6767. # разу у этого типа (у таблицы TitleLocation=Auto пишется явно — там правило не действует).
  6768. $script:enumDefaults = @{
  6769. 'UsualGroup/Group'='HorizontalIfPossible'; 'Page/Group'='Vertical'; 'ColumnGroup/Group'='Vertical'
  6770. 'UsualGroup/Representation'='WeakSeparation'; 'Button/Representation'='Auto'; 'Popup/Representation'='Auto'
  6771. 'AutoCommandBar/Autofill'='true'
  6772. }
  6773. function Get-TagDefault([string]$nt, [string]$tag) {
  6774. if ($script:tagDefaults.ContainsKey($tag)) { return $script:tagDefaults[$tag] }
  6775. if ($script:enumDefaults.ContainsKey("$nt/$tag")) { return $script:enumDefaults["$nt/$tag"] }
  6776. if ($script:enumDefaultValues.ContainsKey("$nt.$tag")) { return $script:enumDefaultValues["$nt.$tag"] }
  6777. if ($tag -eq 'TitleLocation' -and $nt -ne 'Table') { return 'Auto' }
  6778. return $null
  6779. }
  6780. # Значение по умолчанию платформа не пишет — и set его не пишет, а убирает тег.
  6781. # Значение перечисления — к виду платформы (как эмиттер: Normalize-EnumValue по типу элемента)
  6782. function Get-NormalizedEnumValue($node, [string]$tag, [string]$text) {
  6783. if (-not $text -or -not $script:enumScopeTypes.ContainsKey($node.LocalName)) { return $text }
  6784. $script:objType = $node.LocalName
  6785. return (Normalize-EnumValue $tag (Resolve-EnumInputSynonym $node.LocalName $tag $text))
  6786. }
  6787. function Set-ValueTag($node, [string]$tag, [string]$text) {
  6788. $text = Get-NormalizedEnumValue $node $tag $text
  6789. if ((Get-TagDefault $node.LocalName $tag) -ceq $text) {
  6790. $existing = $node.SelectSingleNode("f:$tag", $nsMgr)
  6791. if ($null -ne $existing) { Remove-NodeWithWs $existing }
  6792. return
  6793. }
  6794. Set-SimpleTag $node $tag $text
  6795. }
  6796. $script:titleLocMap = @{ 'none'='None'; 'left'='Left'; 'right'='Right'; 'top'='Top'; 'bottom'='Bottom'; 'auto'='Auto' }
  6797. # Ключи — словарь form-compile; Tags — кандидаты по типу элемента (у LabelField платформа пишет Hiperlink).
  6798. $script:setProps = [ordered]@{
  6799. 'title'=@{ Tags=@('Title'); Kind='ml' }
  6800. 'tooltip'=@{ Tags=@('ToolTip'); Kind='ml' }
  6801. 'inputHint'=@{ Tags=@('InputHint'); Kind='ml' }
  6802. 'visible'=@{ Tags=@('Visible'); Kind='bool' }
  6803. 'hidden'=@{ Tags=@('Visible'); Kind='bool'; Invert=$true }
  6804. 'enabled'=@{ Tags=@('Enabled'); Kind='bool' }
  6805. 'disabled'=@{ Tags=@('Enabled'); Kind='bool'; Invert=$true }
  6806. 'readOnly'=@{ Tags=@('ReadOnly'); Kind='bool' }
  6807. 'skipOnInput'=@{ Tags=@('SkipOnInput'); Kind='bool' }
  6808. 'titleLocation'=@{ Tags=@('TitleLocation'); Kind='enum'; Map=$script:titleLocMap }
  6809. 'width'=@{ Tags=@('Width'); Kind='num' }
  6810. 'height'=@{ Tags=@('HeightInTableRows','Height'); Kind='num' }
  6811. 'maxWidth'=@{ Tags=@('MaxWidth'); Kind='num' }
  6812. 'maxHeight'=@{ Tags=@('MaxHeight'); Kind='num' }
  6813. 'autoMaxWidth'=@{ Tags=@('AutoMaxWidth'); Kind='bool' }
  6814. 'autoMaxHeight'=@{ Tags=@('AutoMaxHeight'); Kind='bool' }
  6815. 'horizontalStretch'=@{ Tags=@('HorizontalStretch'); Kind='bool' }
  6816. 'verticalStretch'=@{ Tags=@('VerticalStretch'); Kind='bool' }
  6817. 'multiLine'=@{ Tags=@('MultiLine'); Kind='bool' }
  6818. 'passwordMode'=@{ Tags=@('PasswordMode'); Kind='bool' }
  6819. 'choiceButton'=@{ Tags=@('ChoiceButton'); Kind='bool' }
  6820. 'clearButton'=@{ Tags=@('ClearButton'); Kind='bool' }
  6821. 'spinButton'=@{ Tags=@('SpinButton'); Kind='bool' }
  6822. 'dropListButton'=@{ Tags=@('DropListButton'); Kind='bool' }
  6823. 'markIncomplete'=@{ Tags=@('AutoMarkIncomplete'); Kind='bool' }
  6824. 'hyperlink'=@{ Tags=@('Hyperlink','Hiperlink'); Kind='bool' }
  6825. 'group'=@{ Tags=@('Group'); Kind='enum'; Map=@{ 'vertical'='Vertical'; 'horizontal'='Horizontal'; 'horizontalifpossible'='HorizontalIfPossible'; 'alwayshorizontal'='AlwaysHorizontal'; 'alwaysvertical'='Vertical'; 'incell'='InCell' } }
  6826. 'behavior'=@{ Tags=@('Behavior'); Kind='enum'; Map=@{ 'usual'='Usual'; 'collapsible'='Collapsible'; 'popup'='PopUp' } }
  6827. 'collapsed'=@{ Tags=@('Collapsed'); Kind='bool' }
  6828. 'representation'=@{ Tags=@('Representation'); Kind='repr' }
  6829. 'showTitle'=@{ Tags=@('ShowTitle'); Kind='bool' }
  6830. 'united'=@{ Tags=@('United'); Kind='bool' }
  6831. }
  6832. # Значения Representation — свои у каждого типа (по корпусу); ключи — как в form-compile.
  6833. $script:reprMaps = @{
  6834. 'UsualGroup' = @{ 'none'='None'; 'normal'='NormalSeparation'; 'weak'='WeakSeparation'; 'strong'='StrongSeparation' }
  6835. 'Table' = @{ 'list'='List'; 'tree'='Tree'; 'hierarchicallist'='HierarchicalList' }
  6836. 'Button' = @{ 'auto'='Auto'; 'text'='Text'; 'picture'='Picture'; 'pictureandtext'='PictureAndText' }
  6837. 'Popup' = @{ 'auto'='Auto'; 'text'='Text'; 'picture'='Picture'; 'pictureandtext'='PictureAndText' }
  6838. 'ButtonGroup' = @{ 'auto'='Auto'; 'usual'='Usual'; 'compact'='Compact' }
  6839. }
  6840. $script:xmlTagToDsl = @{}
  6841. foreach ($k in $script:dslTagMap.Keys) { $script:xmlTagToDsl[$script:dslTagMap[$k]] = $k }
  6842. function Get-PropTag($spec, [string]$nt) {
  6843. foreach ($t in $spec.Tags) { if ((Get-ChildRank $nt $t) -ge 0) { return $t } }
  6844. return $null
  6845. }
  6846. function Get-ApplicableSetKeys([string]$nt) {
  6847. $keys = @()
  6848. foreach ($k in $script:setProps.Keys) {
  6849. if ($k -in @('hidden','disabled')) { continue }
  6850. if ($null -ne (Get-PropTag $script:setProps[$k] $nt)) { $keys += $k }
  6851. }
  6852. if ((Get-ChildRank $nt 'Events') -ge 0) { $keys += 'on' }
  6853. return $keys
  6854. }
  6855. function Set-SimpleTag($node, [string]$tag, [string]$text) {
  6856. $text = Get-NormalizedEnumValue $node $tag $text
  6857. $existing = $node.SelectSingleNode("f:$tag", $nsMgr)
  6858. if ($null -ne $existing) { $existing.InnerText = $text; return }
  6859. $el = $xmlDoc.CreateElement($tag, $formNs)
  6860. $el.InnerText = $text
  6861. Insert-ChildCanonical $node $el
  6862. }
  6863. function Set-MLTag($node, [string]$tag, $value) {
  6864. $indent = Get-ChildIndent $node
  6865. $script:xml = New-Object System.Text.StringBuilder 512
  6866. X "<_F $allNsDecl>"
  6867. X "$indent<$tag>"
  6868. if ($value -is [string]) {
  6869. # Строка меняет только русский текст: переводы на другие языки остаются как были
  6870. $items = @()
  6871. $prevEl = $node.SelectSingleNode("f:$tag", $nsMgr)
  6872. $hasRu = $false
  6873. if ($null -ne $prevEl) {
  6874. foreach ($it in $prevEl.SelectNodes("v8:item", $nsMgr)) {
  6875. $lang = $it.SelectSingleNode("v8:lang", $nsMgr).InnerText
  6876. if ($lang -eq 'ru') { $items += @{ Lang = 'ru'; Text = $value }; $hasRu = $true }
  6877. else { $items += @{ Lang = $lang; Text = $it.SelectSingleNode("v8:content", $nsMgr).InnerText } }
  6878. }
  6879. }
  6880. if (-not $hasRu) { $items = @(@{ Lang = 'ru'; Text = $value }) + $items }
  6881. } else {
  6882. $items = @($value.PSObject.Properties | ForEach-Object { @{ Lang = $_.Name; Text = "$($_.Value)" } })
  6883. }
  6884. foreach ($it in $items) {
  6885. X "$indent`t<v8:item>"
  6886. X "$indent`t`t<v8:lang>$($it.Lang)</v8:lang>"
  6887. X "$indent`t`t<v8:content>$(Esc-XmlText $it.Text)</v8:content>"
  6888. X "$indent`t</v8:item>"
  6889. }
  6890. X "$indent</$tag>"
  6891. X "</_F>"
  6892. $newEl = @(Import-ElementNodes (Parse-Fragment $script:xml.ToString()))[0]
  6893. $existing = $node.SelectSingleNode("f:$tag", $nsMgr)
  6894. if ($null -ne $existing) {
  6895. # Атрибуты узла (formatted у заголовка надписи) переживают замену текста
  6896. foreach ($a in @($existing.Attributes)) { $newEl.SetAttribute($a.LocalName, $a.Value) }
  6897. $node.ReplaceChild($newEl, $existing) | Out-Null
  6898. return
  6899. }
  6900. if ($tag -eq 'Title' -and $node.LocalName -eq 'LabelDecoration') { $newEl.SetAttribute('formatted', 'false') }
  6901. Insert-ChildCanonical $node $newEl
  6902. }
  6903. # Узел, перед которым встаёт новое событие: первое существующее с большей позицией (Get-EventRank);
  6904. # $null — в конец. Существующие события не переставляются.
  6905. function Get-EventInsertRef($eventsNode, [string]$xmlTag, [string]$name, [string]$callType) {
  6906. $r = Get-EventRank $xmlTag $name $callType
  6907. foreach ($e in $eventsNode.SelectNodes("f:Event", $nsMgr)) {
  6908. if ((Get-EventRank $xmlTag $e.GetAttribute('name') $e.GetAttribute('callType')) -gt $r) { return $e }
  6909. }
  6910. return $null
  6911. }
  6912. function Add-ElementEvents($node, $on, $handlers, [string]$ctx) {
  6913. $nt = $node.LocalName
  6914. $name = $node.GetAttribute('name')
  6915. if ((Get-ChildRank $nt 'Events') -lt 0) { Fail "${ctx}: у $nt '$name' событий нет" }
  6916. $source = ''
  6917. if ($nt -eq 'Table') {
  6918. $dp = $node.SelectSingleNode("f:DataPath", $nsMgr)
  6919. if ($null -ne $dp) { $source = Get-DataPathSource $dp.InnerText }
  6920. }
  6921. $events = $node.SelectSingleNode("f:Events", $nsMgr)
  6922. foreach ($evt in @($on)) {
  6923. if (-not ($evt -is [System.Management.Automation.PSCustomObject])) {
  6924. $evtName = "$evt"; $callType = ""; $handler = ""
  6925. } else {
  6926. $evtName = "$($evt.event)"; $callType = Normalize-CallType "$($evt.callType)" $name $evtName
  6927. $handler = if ($evt.handler) { "$($evt.handler)" } else { "" }
  6928. }
  6929. $evtName = Resolve-EventName $nt $evtName "$ctx events"
  6930. # В форме расширения обработчик без callType платформа читает как Before и так и пишет
  6931. if (-not $callType -and $script:isExtension) { $callType = 'Before' }
  6932. if (-not $handler) { $handler = if ($handlers -and $handlers.$evtName) { "$($handlers.$evtName)" } else { Get-HandlerName -elementName $name -eventName $evtName -xmlTag $nt -callType $callType } }
  6933. Test-EventPairs -pairs @([pscustomobject]@{ name = $evtName }) -xmlTag $nt -elementName $name -source $source
  6934. $tbl = Get-NearestTable $node $true
  6935. Register-Handler $handler 'element' $nt $evtName $(if ($null -ne $tbl) { $tbl.GetAttribute('name') } else { '' })
  6936. $ctStr = if ($callType) { "[$callType]" } else { "" }
  6937. if ($null -ne $events) {
  6938. $dup = $null
  6939. foreach ($e in $events.SelectNodes("f:Event", $nsMgr)) {
  6940. if ($e.GetAttribute('name') -eq $evtName -and $e.GetAttribute('callType') -eq $callType) { $dup = $e; break }
  6941. }
  6942. if ($null -ne $dup) {
  6943. $old = $dup.InnerText
  6944. if ($old -eq $handler) { $script:opLog += " = ${name}: event $evtName$ctStr -> $handler already bound"; continue }
  6945. # Другое имя — замена: у события один обработчик (на вид вызова)
  6946. $dup.InnerText = $handler
  6947. Add-UnboundHandlers @($old)
  6948. $script:opLog += " ~ ${name}: event $evtName${ctStr}: $old -> $handler"
  6949. $script:changedCount++
  6950. continue
  6951. }
  6952. }
  6953. if ($null -eq $events) {
  6954. $events = $xmlDoc.CreateElement("Events", $formNs)
  6955. Insert-ChildCanonical $node $events
  6956. }
  6957. $ev = $xmlDoc.CreateElement("Event", $formNs)
  6958. $ev.SetAttribute('name', $evtName)
  6959. if ($callType) { $ev.SetAttribute('callType', $callType) }
  6960. $ev.InnerText = $handler
  6961. Insert-NodeAt $events $ev (Get-EventInsertRef $events $nt $evtName $callType) (Get-ChildIndent $events)
  6962. $script:opLog += " * ${name}: event $evtName$ctStr -> $handler"
  6963. $script:changedCount++
  6964. }
  6965. }
  6966. function Invoke-Set($op, [int]$idx) {
  6967. $ctx = "elements[$idx] set"
  6968. $names = @(@($op.set) | ForEach-Object { "$_" } | Where-Object { $_ })
  6969. if ($names.Count -eq 0) { Fail "${ctx}: укажи имя элемента или список имён" }
  6970. $props = @($op.PSObject.Properties | Where-Object { $_.Name -ne 'set' })
  6971. if ($props.Count -eq 0) { Fail "${ctx}: не указано, что менять" }
  6972. $forbidden = @('name','path','children','columns')
  6973. foreach ($n in $names) {
  6974. $node = Find-FormElement $n
  6975. if ($null -eq $node) { Fail "${ctx}: элемент '$n' не найден в форме" }
  6976. $nt = $node.LocalName
  6977. $c = "$ctx '$n'"
  6978. $probeProps = [ordered]@{}
  6979. foreach ($p in $props) {
  6980. $key = $p.Name
  6981. if ($key -eq 'handlers') { if (-not $op.on) { Fail "${c}: handlers задаются вместе с on" }; continue }
  6982. if ($key -eq 'on') { Add-ElementEvents $node $p.Value $op.handlers $c; continue }
  6983. if ($key -eq 'events') {
  6984. # Список — имена по конвенции (в расширении вид вызова по умолчанию Before — его ставит Add-ElementEvents)
  6985. if ($p.Value -is [array]) { Add-ElementEvents $node $p.Value $null $c; continue }
  6986. if (-not ($p.Value -is [System.Management.Automation.PSCustomObject])) { Fail "${c}: events — объект { Событие: обработчик } или список событий" }
  6987. # Объект: имя — повесить или заменить, null — снять (без callType — все привязки события)
  6988. $on = @()
  6989. foreach ($e in $p.Value.PSObject.Properties) {
  6990. $evName = Resolve-EventName $nt $e.Name "$c events"
  6991. if (@($e.Value).Count -eq 0) { Fail "${c}: событие $evName — пустой список; чтобы снять обработчик, укажите null" }
  6992. foreach ($v in @($e.Value)) {
  6993. $isObj = $v -is [System.Management.Automation.PSCustomObject]
  6994. $h = if ($isObj) { "$($v.handler)" } else { "$v" }
  6995. $ct = if ($isObj) { Normalize-CallType "$($v.callType)" $n $evName } else { '' }
  6996. if ($h) { $on += [pscustomobject]@{ event = $evName; handler = $h; callType = $ct }; continue }
  6997. $ctStr = if ($ct) { "[$ct]" } else { "" }
  6998. $hits = Remove-EventBindings $node $evName $ct
  6999. if ($hits.Count -eq 0) { Fail "${c}: событие $evName$ctStr у '$n' не обрабатывается — снимать нечего" }
  7000. foreach ($x in $hits) {
  7001. $xc = $x.GetAttribute('callType'); $xcStr = if ($xc) { "[$xc]" } else { "" }
  7002. $script:opLog += " - ${n}: event $evName$xcStr -> $($x.InnerText)"
  7003. $script:changedCount++
  7004. }
  7005. Add-UnboundHandlers @($hits | ForEach-Object { $_.InnerText })
  7006. }
  7007. }
  7008. if ($on.Count -gt 0) { Add-ElementEvents $node $on $null $c }
  7009. continue
  7010. }
  7011. if ($forbidden -contains $key -or ($key -eq $script:xmlTagToDsl[$nt] -and $key -ne 'group')) {
  7012. Fail "${c}: '$key' через set не меняется (имя и привязку не трогаем — на них ссылаются модуль и расширения; состав — через move)"
  7013. }
  7014. if (@('into','after','before','first') -contains $key) { Fail "${c}: '$key' — место элемента меняет move, не set" }
  7015. if (-not $script:setProps.Contains($key)) {
  7016. # Остальные ключи элемента — как в form-compile, через общий эмиттер
  7017. $probeProps[$key] = $p.Value
  7018. continue
  7019. }
  7020. $spec = $script:setProps[$key]
  7021. $tag = Get-PropTag $spec $nt
  7022. if ($null -eq $tag) { Fail "${c}: свойство '$key' к $nt не применимо; доступно: $((Get-ApplicableSetKeys $nt) -join ', ') и остальные ключи элемента из form-compile" }
  7023. $v = $p.Value
  7024. if ($null -eq $v) {
  7025. $existing = $node.SelectSingleNode("f:$tag", $nsMgr)
  7026. if ($null -ne $existing) { Remove-NodeWithWs $existing }
  7027. $script:opLog += " * ${n}: $key сброшено"
  7028. $script:changedCount++
  7029. continue
  7030. }
  7031. switch ($spec.Kind) {
  7032. 'ml' {
  7033. $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]) }))
  7034. if (-not $mlOk) { Fail "${c}: $key — строка или объект {ru, en, ...} со строковыми значениями" }
  7035. Set-MLTag $node $tag $v
  7036. $shown = if ($v -is [string]) { $v } else { ($v.PSObject.Properties | ForEach-Object { "$($_.Name):$($_.Value)" }) -join ' ' }
  7037. $script:opLog += " * ${n}: $key=`"$shown`" → $tag"
  7038. }
  7039. 'bool' {
  7040. $v = ConvertTo-DslBool $v "${c}: $key" $false
  7041. if ($spec.Invert) { $v = -not $v }
  7042. $text = if ($v) { 'true' } else { 'false' }
  7043. Set-ValueTag $node $tag $text
  7044. $script:opLog += " * ${n}: $key=$("$($p.Value)".ToLower()) → $tag=$text"
  7045. }
  7046. 'num' {
  7047. if (-not ($v -is [int] -or $v -is [long]) -or $v -lt 0) { Fail "${c}: $key — целое неотрицательное число" }
  7048. Set-SimpleTag $node $tag "$v"
  7049. $script:opLog += " * ${n}: $key=$v → $tag=$v"
  7050. }
  7051. 'enum' {
  7052. $mapped = $spec.Map["$v".ToLower()]
  7053. if (-not $mapped) { Fail "${c}: $key='$v' — допустимо: $(($spec.Map.Keys | Sort-Object) -join ', ')" }
  7054. Set-ValueTag $node $tag $mapped
  7055. $script:opLog += " * ${n}: $key=$v → $tag=$mapped"
  7056. }
  7057. 'repr' {
  7058. $rmap = $script:reprMaps[$nt]
  7059. if ($null -eq $rmap) { Fail "${c}: свойство '$key' к $nt не применимо; доступно: $((Get-ApplicableSetKeys $nt) -join ', ') и остальные ключи элемента из form-compile" }
  7060. $text = $rmap[(Resolve-EnumInputSynonym $nt 'Representation' "$v").ToLower()]
  7061. if (-not $text) { Fail "${c}: representation='$v' — допустимо: $(($rmap.Keys | Sort-Object) -join ', ')" }
  7062. Set-ValueTag $node $tag $text
  7063. $script:opLog += " * ${n}: $key=$v → $tag=$text"
  7064. }
  7065. }
  7066. $script:changedCount++
  7067. }
  7068. if ($probeProps.Count -gt 0) {
  7069. # Контекст пробы — все свойства операции: от них зависит, как эмиттер пишет остальные
  7070. $context = [ordered]@{}
  7071. foreach ($p in $props) {
  7072. if (@('on','handlers','events') -notcontains $p.Name -and $null -ne $p.Value -and -not $probeProps.Contains($p.Name)) { $context[$p.Name] = $p.Value }
  7073. }
  7074. Invoke-SetByEmitter $node $probeProps $context $op $c
  7075. }
  7076. }
  7077. }
  7078. # --- set: ключи элемента вне таблицы выше — через общий эмиттер form-compile ---
  7079. # Элемент эмитится без свойства и с ним; что различается, то свойство и пишет в XML. Так set знает
  7080. # все ключи form-compile и пишет их ровно так же, как при создании формы.
  7081. $script:probeTypeValues = @{ 'group'='vertical'; 'columnGroup'='vertical' }
  7082. function Invoke-SetProbe($node, $props) {
  7083. $nt = $node.LocalName
  7084. $dsl = $script:xmlTagToDsl[$nt]
  7085. $name = $node.GetAttribute('name')
  7086. $h = [ordered]@{}
  7087. $h[$dsl] = if ($script:probeTypeValues.ContainsKey($dsl)) { $script:probeTypeValues[$dsl] } else { $name }
  7088. $h['name'] = $name
  7089. $dp = $node.SelectSingleNode("f:DataPath", $nsMgr)
  7090. if ($null -ne $dp) { $h['path'] = $dp.InnerText }
  7091. foreach ($k in $props.Keys) { $h[$k] = $props[$k] }
  7092. $el = ConvertFrom-JsonInput ([pscustomobject]$h | ConvertTo-Json -Depth 100 -Compress) 'element from XML'
  7093. Normalize-ElementSynonyms $el
  7094. foreach ($a in $root.SelectNodes("f:Attributes/f:Attribute", $nsMgr)) {
  7095. $t = $a.SelectSingleNode("f:Type/v8:Type", $nsMgr)
  7096. if ($null -ne $t -and $t.InnerText.Trim() -eq 'cfg:DynamicList') { ApplyDynamicListTableHeuristic $el $a.GetAttribute('name') $true (Test-DynListExplicitKey $a) }
  7097. }
  7098. $saveId = $script:nextElemId
  7099. $script:seenElementNames = @{}
  7100. $tbl = Get-NearestTable $node $false
  7101. $script:currentTableName = if ($null -ne $tbl) { $tbl.GetAttribute('name') } else { $null }
  7102. $inBar = $false
  7103. $cur = $node.ParentNode
  7104. while ($null -ne $cur -and $cur.NodeType -eq 'Element') {
  7105. if ($script:barTags -contains $cur.LocalName) { $inBar = $true; break }
  7106. $cur = $cur.ParentNode
  7107. }
  7108. $script:xml = New-Object System.Text.StringBuilder 4096
  7109. X "<_F $allNsDecl>"
  7110. $msgs = @(& { Emit-Element -el $el -indent (Get-NodeIndent $node) -inCmdBar $inBar } 3>&1 6>&1 |
  7111. Where-Object { $_ -is [System.Management.Automation.WarningRecord] -or $_ -is [System.Management.Automation.InformationRecord] } |
  7112. ForEach-Object { "$_" })
  7113. X "</_F>"
  7114. $script:nextElemId = $saveId
  7115. $frag = Parse-Fragment (Sort-ElementTagOrder (Normalize-EnumTags $script:xml.ToString() '' $true))
  7116. $pe = $null
  7117. foreach ($ch in $frag.DocumentElement.ChildNodes) { if ($ch.NodeType -eq 'Element') { $pe = $ch; break } }
  7118. return @{ El = $pe; Messages = $msgs }
  7119. }
  7120. # Свойства узла: дочерние теги (без состава и событий) и атрибуты; спутники (меню, подсказка,
  7121. # панель) — отдельно, их свойства сравниваются так же.
  7122. function Get-ProbeParts($e) {
  7123. $tags = [ordered]@{}; $comps = @{}; $attrs = @{}
  7124. foreach ($ch in $e.ChildNodes) {
  7125. if ($ch.NodeType -ne 'Element') { continue }
  7126. $ln = $ch.LocalName
  7127. if ($ln -eq 'Events') { continue }
  7128. if ($ln -eq 'ChildItems') { $comps['#items'] = ($ch.OuterXml -replace ' id="-?\d+"', '') -replace '\s+', ' '; continue }
  7129. if ($script:companionTags -contains $ln -and $ch.HasAttribute('name')) { $comps[$ln] = $ch; continue }
  7130. $t = ($ch.OuterXml -replace ' id="-?\d+"', '') -replace '\s+', ' '
  7131. if ($tags.Contains($ln)) { $tags[$ln] += $t } else { $tags[$ln] = $t }
  7132. }
  7133. foreach ($a in $e.Attributes) {
  7134. if ($a.Name -ne 'name' -and $a.Name -ne 'id' -and -not $a.Name.StartsWith('xmlns')) { $attrs[$a.Name] = $a.Value }
  7135. }
  7136. return @{ Tags = $tags; Comps = $comps; Attrs = $attrs }
  7137. }
  7138. function Get-ProbeDiff($b, $p) {
  7139. $pb = Get-ProbeParts $b; $pp = Get-ProbeParts $p
  7140. $d = @{ Tags = @(); Attrs = @(); Comps = @(); Items = $false }
  7141. foreach ($t in @($pb.Tags.Keys) + @($pp.Tags.Keys) | Select-Object -Unique) {
  7142. if ($pb.Tags[$t] -cne $pp.Tags[$t]) { $d.Tags += $t }
  7143. }
  7144. foreach ($a in @($pb.Attrs.Keys) + @($pp.Attrs.Keys) | Sort-Object -Unique) {
  7145. if ($pb.Attrs[$a] -cne $pp.Attrs[$a]) { $d.Attrs += $a }
  7146. }
  7147. if ($pb.Comps['#items'] -cne $pp.Comps['#items']) { $d.Items = $true }
  7148. foreach ($cn in @($pp.Comps.Keys | Where-Object { $_ -ne '#items' } | Sort-Object)) {
  7149. if ($null -eq $pb.Comps[$cn]) { continue }
  7150. $sub = Get-ProbeDiff $pb.Comps[$cn] $pp.Comps[$cn]
  7151. # Состав спутника (кнопки меню, панели) — тоже состав
  7152. if ($sub.Items) { $d.Items = $true }
  7153. if (Test-ProbeDiff $sub) { $d.Comps += @{ Tag = $cn; Diff = $sub } }
  7154. }
  7155. return $d
  7156. }
  7157. function Test-ProbeDiff($d) {
  7158. return ($d.Tags.Count + $d.Attrs.Count + $d.Comps.Count) -gt 0 -or $d.Items
  7159. }
  7160. # Есть ли в узле хоть что-то из того, что описывает разница (для сброса к умолчанию).
  7161. function Test-ProbeDiffPresent($target, $d) {
  7162. foreach ($t in $d.Tags) { if ($null -ne $target.SelectSingleNode("f:$t", $nsMgr)) { return $true } }
  7163. foreach ($a in $d.Attrs) { if ($target.HasAttribute($a)) { return $true } }
  7164. foreach ($cd in $d.Comps) {
  7165. $tc = $target.SelectSingleNode("f:$($cd.Tag)", $nsMgr)
  7166. if ($null -ne $tc -and (Test-ProbeDiffPresent $tc $cd.Diff)) { return $true }
  7167. }
  7168. return $false
  7169. }
  7170. function Get-ProbeDiffLabel($d) {
  7171. $parts = @($d.Tags) + @($d.Attrs | ForEach-Object { "@$_" })
  7172. foreach ($cd in $d.Comps) { $parts += @(Get-ProbeDiffLabel $cd.Diff | ForEach-Object { "$($cd.Tag)/$_" }) }
  7173. return $parts
  7174. }
  7175. # Перенести в узел то, что различается: теги пробы заменяют свои (нет в пробе — тег убирается).
  7176. function Apply-ProbeDiff($target, $probeEl, $d, [bool]$removeOnly) {
  7177. foreach ($t in $d.Tags) {
  7178. foreach ($x in @($target.SelectNodes("f:$t", $nsMgr))) { Remove-NodeWithWs $x }
  7179. if ($removeOnly) { continue }
  7180. foreach ($pn in @($probeEl.SelectNodes("f:$t", $nsMgr))) {
  7181. $imp = $xmlDoc.ImportNode($pn, $true)
  7182. if ((Get-ChildRank $target.LocalName $t) -ge 0) { Insert-ChildCanonical $target $imp; continue }
  7183. # Тега нет в корпусном порядке — встаёт перед первым следующим за ним в пробе тегом узла
  7184. $ref = $null
  7185. $sib = $pn.NextSibling
  7186. while ($null -ne $sib -and $null -eq $ref) {
  7187. if ($sib.NodeType -eq 'Element') { $ref = $target.SelectSingleNode("f:$($sib.LocalName)", $nsMgr) }
  7188. $sib = $sib.NextSibling
  7189. }
  7190. Insert-NodeAt $target $imp $ref (Get-ChildIndent $target)
  7191. }
  7192. }
  7193. foreach ($a in $d.Attrs) {
  7194. if (-not $removeOnly -and $probeEl.HasAttribute($a)) { $target.SetAttribute($a, $probeEl.GetAttribute($a)) }
  7195. else { $target.RemoveAttribute($a) }
  7196. }
  7197. foreach ($cd in $d.Comps) {
  7198. $tc = $target.SelectSingleNode("f:$($cd.Tag)", $nsMgr)
  7199. $pc = if ($null -ne $probeEl) { $probeEl.SelectSingleNode("f:$($cd.Tag)", $nsMgr) } else { $null }
  7200. if ($null -ne $tc) { Apply-ProbeDiff $tc $pc $cd.Diff $removeOnly }
  7201. elseif (-not $removeOnly) { Fail "у '$($target.GetAttribute('name'))' нет $($cd.Tag) — свойство некуда записать" }
  7202. }
  7203. }
  7204. function Get-ProbeOwnerTags([string]$key) {
  7205. foreach ($g in $script:genericScalars) { if ($g.Key -eq $key) { return @($g.Tag) } }
  7206. if ($script:appearanceSpec.ContainsKey($key)) { return @($script:appearanceSpec[$key].tag) }
  7207. return @()
  7208. }
  7209. # Теги, которые set через эмиттер не трогает: привязка и тип. Теги ручной таблицы (Title, ToolTip…)
  7210. # проба переписывает, только если их ключ задан в той же операции, — иначе эмиттер, не зная их
  7211. # значения, затёр бы его своим.
  7212. $script:probeLockedTags = @('DataPath','CommandName','Type')
  7213. function Assert-ProbeTags($d, [string]$k, $op, [string]$c) {
  7214. foreach ($t in $d.Tags) {
  7215. if ($script:probeLockedTags -contains $t) { Fail "${c}: '$k' меняет $t — привязка и тип элемента через set не меняются" }
  7216. }
  7217. foreach ($t in $d.Tags) {
  7218. $owners = @($script:setProps.Keys | Where-Object { $script:setProps[$_].Tags -contains $t })
  7219. if ($owners.Count -gt 0 -and -not ($owners | Where-Object { $null -ne $op.PSObject.Properties[$_] })) {
  7220. Fail "${c}: '$k' меняет и $t — укажите в той же операции $($owners -join ' или ')"
  7221. }
  7222. }
  7223. }
  7224. function Invoke-SetByEmitter($node, $props, $context, $op, [string]$c) {
  7225. $n = $node.GetAttribute('name')
  7226. $nt = $node.LocalName
  7227. if (-not $script:xmlTagToDsl.ContainsKey($nt)) { Fail "${c}: у $nt меняются только: $((Get-ApplicableSetKeys $nt) -join ', ')" }
  7228. $set = [ordered]@{}
  7229. foreach ($k in $context.Keys) { $set[$k] = $context[$k] }
  7230. foreach ($k in $props.Keys) { if ($null -ne $props[$k]) { $set[$k] = $props[$k] } }
  7231. $full = Invoke-SetProbe $node $set
  7232. if ($full.El.LocalName -ne $nt) {
  7233. $tk = @($props.Keys | Where-Object { $script:dslTagMap.ContainsKey($_) })
  7234. Fail "${c}: '$($tk -join ', ')' — ключ типа элемента; тип через set не меняется"
  7235. }
  7236. $removals = @()
  7237. $applies = @()
  7238. foreach ($k in $props.Keys) {
  7239. $v = $props[$k]
  7240. $rest = [ordered]@{}
  7241. foreach ($k2 in $set.Keys) { if ($k2 -ne $k) { $rest[$k2] = $set[$k2] } }
  7242. $without = Invoke-SetProbe $node $rest
  7243. if ($null -eq $v) {
  7244. # Сброс: убрать то, что ключ пишет при любом значении
  7245. $owned = @(Get-ProbeOwnerTags $k)
  7246. $d = @{ Tags = $owned; Attrs = @(); Comps = @(); Items = $false }
  7247. if ($owned.Count -eq 0) {
  7248. foreach ($alt in @($true, $false)) {
  7249. $wa = [ordered]@{}; foreach ($k2 in $rest.Keys) { $wa[$k2] = $rest[$k2] }; $wa[$k] = $alt
  7250. $pa = Invoke-SetProbe $node $wa
  7251. if (@($pa.Messages | Where-Object { $_ -match "unknown key '" }).Count -gt 0) { break }
  7252. $da = Get-ProbeDiff $without.El $pa.El
  7253. if (Test-ProbeDiff $da) { $d = $da; break }
  7254. }
  7255. }
  7256. if (-not (Test-ProbeDiff $d)) { Fail "${c}: '$k' сбросить нельзя — неизвестное свойство или у него нет значения по умолчанию; укажите значение" }
  7257. Assert-ProbeTags $d $k $op $c
  7258. if (Test-ProbeDiffPresent $node $d) {
  7259. $removals += $d
  7260. $script:opLog += " * ${n}: $k сброшено"
  7261. $script:changedCount++
  7262. } else {
  7263. $script:opLog += " = ${n}: $k — уже по умолчанию"
  7264. }
  7265. continue
  7266. }
  7267. $d = Get-ProbeDiff $without.El $full.El
  7268. if (Test-ProbeDiff $d) {
  7269. if ($d.Items) { Fail "${c}: '$k' меняет состав '$n' — элементы добавляются отдельными операциями" }
  7270. Assert-ProbeTags $d $k $op $c
  7271. $applies += $d
  7272. $shown = if ($v -is [bool]) { "=$("$v".ToLower())" } elseif ($v -is [string] -or $v -is [int] -or $v -is [long]) { "=$v" } else { "" }
  7273. $script:opLog += " * ${n}: $k$shown → $((Get-ProbeDiffLabel $d) -join ', ')"
  7274. $script:changedCount++
  7275. continue
  7276. }
  7277. # Разницы нет: ключ неизвестен, значение не распознано или совпадает с умолчанием платформы
  7278. $msgs = @($full.Messages)
  7279. if (@($msgs | Where-Object { $_ -match "unknown key '$([regex]::Escape($k))'" }).Count -gt 0) {
  7280. Fail "${c}: неизвестное свойство '$k' — ключи те же, что у элемента в form-compile"
  7281. }
  7282. $vv = @($msgs | ForEach-Object { if ($_ -match 'Valid values: (.*?)\. Value ignored') { $Matches[1] } })
  7283. if ($vv.Count -gt 0) { Fail "${c}: $k='$v' — значение не распознано; допустимо: $($vv[0])" }
  7284. if ($v -is [bool]) {
  7285. $wa = [ordered]@{}; foreach ($k2 in $rest.Keys) { $wa[$k2] = $rest[$k2] }; $wa[$k] = -not $v
  7286. $pa = Invoke-SetProbe $node $wa
  7287. $da = Get-ProbeDiff $without.El $pa.El
  7288. if (Test-ProbeDiff $da) {
  7289. Assert-ProbeTags $da $k $op $c
  7290. if (Test-ProbeDiffPresent $node $da) {
  7291. $removals += $da
  7292. $script:opLog += " * ${n}: $k=$("$v".ToLower()) — умолчание платформы, $((Get-ProbeDiffLabel $da) -join ', ') не пишется"
  7293. $script:changedCount++
  7294. } else {
  7295. $script:opLog += " = ${n}: $k=$("$v".ToLower()) — уже по умолчанию"
  7296. }
  7297. continue
  7298. }
  7299. }
  7300. Fail "${c}: '$k' к $nt не применимо или значение совпадает с умолчанием (чтобы вернуть умолчание — null)"
  7301. }
  7302. foreach ($r in $removals) { Apply-ProbeDiff $node $null $r $true }
  7303. foreach ($a in $applies) { Apply-ProbeDiff $node $full.El $a $false }
  7304. # Значение-умолчание платформа не пишет — перенесённый тег с ним убирается
  7305. # (не $c: это параметр [string] функции — PS привёл бы к нему каждый узел цикла)
  7306. foreach ($ch in @($node.ChildNodes)) {
  7307. if ($ch.NodeType -ne 'Element' -or $ch.SelectSingleNode("*")) { continue }
  7308. if ($script:enumDefaultValues.ContainsKey("$($node.LocalName).$($ch.LocalName)") -and $script:enumDefaultValues["$($node.LocalName).$($ch.LocalName)"] -ceq $ch.InnerText) { Remove-NodeWithWs $ch }
  7309. }
  7310. }
  7311. # --- Удаление ---
  7312. $dcsSetNs = "http://v8.1c.ru/8.1/data-composition-system/settings"
  7313. $nsMgr.AddNamespace("dcsset", $dcsSetNs)
  7314. $script:removeLog = @()
  7315. $script:removedCount = 0
  7316. $script:leftHandlers = @()
  7317. $script:changeLog = @()
  7318. $script:sectionChanged = 0
  7319. $script:warnLog = @()
  7320. $script:moduleOutline = $null
  7321. $script:moduleScan = $null
  7322. # Сканер BSL: строковые литералы (с "" и многострочными продолжениями «|») и комментарии // отделяются
  7323. # от кода, номера строк сохраняются. Lines — строки текста; Code — они же без комментариев, литерал
  7324. # заменён на ""; Mask — строки той же длины, литералы и комментарии — пробелами (позиции в маске —
  7325. # позиции в тексте); Literals — @{ Line; Text; Prefix — код этой строки слева от литерала; Col — начало
  7326. # текста литерала в строке, -1 у многострочного }.
  7327. function Get-BslScan([string]$text) {
  7328. $lines = $text -replace "`r", "" -split "`n"
  7329. $code = New-Object System.Collections.ArrayList
  7330. $mask = New-Object System.Collections.ArrayList
  7331. $lits = New-Object System.Collections.ArrayList
  7332. $inStr = $false; $cur = $null; $curLine = 0; $curPrefix = ""; $curCol = -1
  7333. for ($i = 0; $i -lt $lines.Count; $i++) {
  7334. $line = $lines[$i]
  7335. # строка без кавычек вне литерала — только отрезать комментарий (посимвольный разбор в PS медленный)
  7336. if (-not $inStr -and $line.IndexOf('"') -lt 0) {
  7337. $k = $line.IndexOf('//')
  7338. [void]$code.Add($(if ($k -ge 0) { $line.Substring(0, $k) } else { $line }))
  7339. [void]$mask.Add($(if ($k -ge 0) { $line.Substring(0, $k) + (' ' * ($line.Length - $k)) } else { $line }))
  7340. continue
  7341. }
  7342. $sb = New-Object System.Text.StringBuilder
  7343. $mk = $line.ToCharArray()
  7344. $j = 0
  7345. if ($inStr) {
  7346. # продолжение многострочного литерала: пробелы, затем «|»
  7347. while ($j -lt $line.Length -and ($line[$j] -eq ' ' -or $line[$j] -eq "`t")) { $j++ }
  7348. # строка «//…» между строками литерала — комментарий, литерал продолжается на следующей
  7349. if ($j + 1 -lt $line.Length -and $line[$j] -eq '/' -and $line[$j + 1] -eq '/') { [void]$code.Add(""); [void]$mask.Add(' ' * $line.Length); continue }
  7350. if ($j -lt $line.Length -and $line[$j] -eq '|') { $mk[$j] = ' '; $j++ }
  7351. $cur += "`n"
  7352. $curCol = -1
  7353. }
  7354. while ($j -lt $line.Length) {
  7355. $c = $line[$j]
  7356. if ($inStr) {
  7357. if ($c -eq '"') {
  7358. if ($j + 1 -lt $line.Length -and $line[$j + 1] -eq '"') { $cur += '"'; $mk[$j] = ' '; $mk[$j + 1] = ' '; $j += 2; continue }
  7359. $inStr = $false
  7360. [void]$lits.Add(@{ Line = $curLine; Text = $cur; Prefix = $curPrefix; Col = $curCol })
  7361. [void]$sb.Append('""')
  7362. $j++
  7363. continue
  7364. }
  7365. $cur += $c; $mk[$j] = ' '; $j++; continue
  7366. }
  7367. 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 }
  7368. if ($c -eq '"') { $inStr = $true; $cur = ""; $curLine = $i + 1; $curPrefix = $sb.ToString(); $curCol = $j + 1; $j++; continue }
  7369. [void]$sb.Append($c); $j++
  7370. }
  7371. [void]$code.Add($sb.ToString())
  7372. [void]$mask.Add([string]::new($mk))
  7373. }
  7374. return @{ Lines = $lines; Code = $code.ToArray(); Mask = $mask.ToArray(); Literals = $lits.ToArray() }
  7375. }
  7376. # Модуль формы — рядом с Form.xml: <...>/Ext/Form/Module.bsl.
  7377. function Get-ModuleScan {
  7378. if ($null -ne $script:moduleScan) { return $script:moduleScan }
  7379. $scan = @{ Exists = $false; Raw = ""; RawLines = @(); Lines = @(); Code = @(); Mask = @(); Literals = @() }
  7380. $path = Join-Path ([System.IO.Path]::GetDirectoryName($resolvedFormPath)) "Form/Module.bsl"
  7381. if (Test-Path -LiteralPath $path) {
  7382. $scan.Exists = $true
  7383. $scan.Raw = [System.IO.File]::ReadAllText($path)
  7384. $scan.RawLines = $scan.Raw -split "`n"
  7385. $bsl = Get-BslScan $scan.Raw
  7386. $scan.Lines = $bsl.Lines
  7387. $scan.Code = $bsl.Code
  7388. $scan.Mask = $bsl.Mask
  7389. $scan.Literals = $bsl.Literals
  7390. }
  7391. $script:moduleScan = $scan
  7392. return $scan
  7393. }
  7394. # Где имя элемента/команды передают строкой: Найти("X"), ПолеКомпоновкиДанных("X"), ПутьКДанным = "X",
  7395. # УстановитьСвойствоЭлементаФормы(Элементы, "X", …); реквизита — ещё РеквизитФормыВЗначение("X") и
  7396. # ЗначениеВРеквизитФормы(…, "X").
  7397. $script:itemLiteralContext = '((?<!\w)(Найти|Find|ПолеКомпоновкиДанных|DataCompositionField)\s*\(\s*|(?<!\w)(ПутьКДанным|DataPath)\s*=\s*|(?<!\w)(Элементы|Items)\s*,\s*)$'
  7398. $script:attrLiteralContext = '((?<!\w)(ПолеКомпоновкиДанных|DataCompositionField|РеквизитФормыВЗначение|FormAttributeToValue)\s*\(\s*|(?<!\w)(ЗначениеВРеквизитФормы|ValueToFormAttribute)\s*\(.*,\s*|(?<!\w)(ПутьКДанным|DataPath)\s*=\s*)$'
  7399. # Номера строк модуля, где есть ссылка на имя. Kind: element | command | attribute.
  7400. function Find-ModuleRefs([string]$name, [string]$kind) {
  7401. $scan = Get-ModuleScan
  7402. $hits = New-Object System.Collections.Generic.SortedSet[int]
  7403. if (-not $scan.Exists) { return @() }
  7404. $n = [regex]::Escape($name)
  7405. $opt = [System.Text.RegularExpressions.RegexOptions]::IgnoreCase
  7406. if ($kind -eq 'attribute') { $mm = Get-ModuleMethods; $locals = (Find-ModuleDecl $name).Locals }
  7407. for ($i = 0; $i -lt $scan.Code.Count; $i++) {
  7408. $code = $scan.Code[$i]
  7409. if ($kind -eq 'element') {
  7410. if ([regex]::IsMatch($code, "(?<!\w)(Элементы|Items|ПодчиненныеЭлементы|ChildItems)\s*\.\s*$n(?!\w)", $opt)) { [void]$hits.Add($i + 1) }
  7411. } elseif ($kind -eq 'command') {
  7412. if ([regex]::IsMatch($code, "(?<!\w)(Команды|Commands)\s*\.\s*$n(?!\w)", $opt)) { [void]$hits.Add($i + 1) }
  7413. } elseif ($kind -eq 'parameter') {
  7414. if ([regex]::IsMatch($code, "(?<!\w)(Параметры|Parameters)\s*\.\s*$n(?!\w)", $opt)) { [void]$hits.Add($i + 1) }
  7415. } else {
  7416. # Реквизит формы: имя целым словом не после точки; после точки — только ЭтаФорма./ЭтотОбъект.
  7417. # В методе без контекста реквизитов формы нет; где имя объявлено локально, голое имя — локальное
  7418. if ($code.IndexOf($name, [System.StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
  7419. $meth = Get-MethodAt $mm ($i + 1)
  7420. if ($null -ne $meth -and $meth.noCtx) { continue }
  7421. $isLocal = $null -ne $meth -and $locals.ContainsKey($meth.name)
  7422. foreach ($m in [regex]::Matches($code, "(?<!\w)$n(?!\w)", $opt)) {
  7423. $before = $code.Substring(0, $m.Index)
  7424. if ($before -match '\.\s*$') {
  7425. if ([regex]::IsMatch($before, '(?<![\w.])(ЭтаФорма|ЭтотОбъект|ThisForm|ThisObject)\s*\.\s*$', $opt)) { [void]$hits.Add($i + 1) }
  7426. } elseif (-not $isLocal) {
  7427. [void]$hits.Add($i + 1)
  7428. }
  7429. }
  7430. }
  7431. }
  7432. # Строкой имя передают только в узком наборе вызовов (по корпусу) — остальные литералы
  7433. # (параметры запроса, ключи структур) с именем совпадают случайно и ссылкой не считаются.
  7434. $ctxPat = if ($kind -eq 'attribute') { $script:attrLiteralContext } else { $script:itemLiteralContext }
  7435. foreach ($lit in $scan.Literals) {
  7436. $t = $lit.Text
  7437. $match = ($t -eq $name -or ($kind -eq 'attribute' -and $t.StartsWith("$name.", [System.StringComparison]::OrdinalIgnoreCase)))
  7438. if ($match -and [regex]::IsMatch($lit.Prefix, $ctxPat, $opt)) { [void]$hits.Add($lit.Line) }
  7439. }
  7440. return @($hits)
  7441. }
  7442. function Format-ModuleRefs([int[]]$lines) {
  7443. $scan = Get-ModuleScan
  7444. $out = @()
  7445. foreach ($l in ($lines | Select-Object -First 5)) { $out += " Module.bsl:${l}: $($scan.Lines[$l - 1].Trim())" }
  7446. if ($lines.Count -gt 5) { $out += " … и ещё $($lines.Count - 5)" }
  7447. return ($out -join "`n")
  7448. }
  7449. # Обработчики удаляемого, которые есть процедурами в модуле, — в отчёт: мёртвый код, решает автор.
  7450. function Add-LeftHandlers([string[]]$handlers) {
  7451. $scan = Get-ModuleScan
  7452. if (-not $scan.Exists) { return }
  7453. foreach ($h in $handlers) {
  7454. if (-not $h -or $script:leftHandlers -contains $h) { continue }
  7455. $pat = "(?im)^\s*((Асинх|Async)\s+)?(Процедура|Функция|Procedure|Function)\s+$([regex]::Escape($h))\s*\("
  7456. if ([regex]::IsMatch($scan.Raw, $pat)) { $script:leftHandlers += $h }
  7457. }
  7458. }
  7459. function Test-Borrowed([string]$name, [string]$kind) {
  7460. if (-not $script:isExtension) { return $false }
  7461. $bf = $root.SelectSingleNode("f:BaseForm", $nsMgr)
  7462. $xp = switch ($kind) {
  7463. 'element' { ".//*[@name]" }
  7464. 'command' { "f:Commands/f:Command" }
  7465. 'attribute' { "f:Attributes/f:Attribute" }
  7466. 'parameter' { "f:Parameters/f:Parameter" }
  7467. }
  7468. foreach ($n in $bf.SelectNodes($xp, $nsMgr)) {
  7469. if ($n.NamespaceURI -eq $formNs -and $n.GetAttribute("name") -eq $name) {
  7470. if ($kind -ne 'element' -or $n.ParentNode.LocalName -eq 'ChildItems') { return $true }
  7471. }
  7472. }
  7473. return $false
  7474. }
  7475. # Ближайший именованный элемент формы, которому принадлежит узел.
  7476. function Get-OwnerElement($node) {
  7477. $cur = $node
  7478. while ($null -ne $cur -and $cur.NodeType -eq 'Element') {
  7479. if ($cur.NamespaceURI -eq $formNs -and $cur.HasAttribute("name") -and ($cur.ParentNode.LocalName -eq 'ChildItems' -or $script:companionTags -contains $cur.LocalName)) { return $cur }
  7480. $cur = $cur.ParentNode
  7481. }
  7482. return $null
  7483. }
  7484. function Get-ElementScopes {
  7485. $scopes = @()
  7486. if ($null -ne $script:rootCI) { $scopes += $script:rootCI }
  7487. $acbNode = $root.SelectSingleNode("f:AutoCommandBar", $nsMgr)
  7488. if ($null -ne $acbNode) { $scopes += $acbNode }
  7489. return $scopes
  7490. }
  7491. function Get-NamedInSubtree($node) {
  7492. $names = @($node.GetAttribute("name"))
  7493. foreach ($d in $node.SelectNodes(".//*[@name]")) {
  7494. if ($d.NamespaceURI -eq $formNs -and ($d.ParentNode.LocalName -eq 'ChildItems' -or $script:companionTags -contains $d.LocalName)) { $names += $d.GetAttribute("name") }
  7495. }
  7496. return $names
  7497. }
  7498. # Общий удалитель элементов: каскад зависимых кнопок и дополнений поиска, отказ при ссылках из
  7499. # модуля и из привязанных полей, чистка условного оформления. $roots — узлы, $reasons — подпись.
  7500. function Remove-FormElements($roots, [string]$ctx, [string]$reason) {
  7501. # Вложенные в другие удаляемые — поглощаются
  7502. $set = New-Object System.Collections.ArrayList
  7503. foreach ($r in $roots) {
  7504. $inside = $false
  7505. foreach ($o in $roots) { if (-not (Same $o $r) -and (Test-IsInside $r $o)) { $inside = $true; break } }
  7506. if (-not $inside) { [void]$set.Add($r) }
  7507. }
  7508. $items = New-Object System.Collections.ArrayList # @{ Node; Reason }
  7509. foreach ($r in $set) { [void]$items.Add(@{ Node = $r; Reason = $reason }) }
  7510. foreach ($r in $set) {
  7511. foreach ($nm in (Get-NamedInSubtree $r)) {
  7512. if (Test-Borrowed $nm 'element') { Fail "${ctx}: '$nm' — заимствованный элемент, платформа не даёт удалять его в расширении; чтобы скрыть — {""set"": ""$nm"", ""visible"": false}" }
  7513. }
  7514. }
  7515. # Каскад: кнопки, дополнения поиска; отказ: прочие привязки Items.X…
  7516. $changed = $true
  7517. while ($changed) {
  7518. $changed = $false
  7519. $removedNames = @{}
  7520. foreach ($it in $items) { foreach ($nm in (Get-NamedInSubtree $it.Node)) { $removedNames[$nm] = $nm } }
  7521. $blockers = @()
  7522. foreach ($s in (Get-ElementScopes)) {
  7523. foreach ($t in $s.SelectNodes(".//*")) {
  7524. $ln = $t.LocalName
  7525. if (-not ($ln -eq 'CommandName' -or $ln -eq 'CommandSource' -or $ln.EndsWith('DataPath') -or ($ln -eq 'Item' -and $t.ParentNode.LocalName -eq 'AdditionSource'))) { continue }
  7526. $txt = $t.InnerText.Trim()
  7527. $target = $null
  7528. if ($txt -match '^Form\.Item\.([^.]+)\.') { $target = $Matches[1] }
  7529. elseif ($ln -eq 'CommandSource' -and $txt -match '^Item\.([^.]+)$') { $target = $Matches[1] }
  7530. elseif ($txt -match '^Items\.([^.]+)\.') { $target = $Matches[1] }
  7531. elseif ($ln -eq 'Item') { $target = $txt }
  7532. if (-not $target -or -not $removedNames.ContainsKey($target)) { continue }
  7533. $owner = Get-OwnerElement $t
  7534. if ($null -eq $owner) { continue }
  7535. $inRemoved = $false
  7536. foreach ($it in $items) { if (Test-IsInside $owner $it.Node) { $inRemoved = $true; break } }
  7537. if ($inRemoved) { continue }
  7538. $ol = $owner.LocalName
  7539. if ($ol -in @('Button','ButtonGroup','Popup','CommandBar','SearchStringAddition','ViewStatusAddition','SearchControlAddition')) {
  7540. [void]$items.Add(@{ Node = $owner; Reason = "зависел от удалённого $($removedNames[$target])" })
  7541. $changed = $true
  7542. break
  7543. }
  7544. $blockers += "$($owner.GetAttribute('name')) ($ol, $ln = $txt)"
  7545. }
  7546. if ($changed) { break }
  7547. }
  7548. }
  7549. if ($blockers.Count -gt 0) {
  7550. Fail "${ctx}: на удаляемое ссылаются элементы, которые остаются: $(($blockers | Select-Object -Unique) -join '; ') — удали их в том же remove или перепривяжи"
  7551. }
  7552. # Заимствованное и ссылки из модуля — по всем удаляемым именам
  7553. $allNames = @()
  7554. foreach ($it in $items) { $allNames += Get-NamedInSubtree $it.Node }
  7555. $allNames = @($allNames | Select-Object -Unique)
  7556. foreach ($nm in $allNames) {
  7557. if (Test-Borrowed $nm 'element') { Fail "${ctx}: '$nm' — заимствованный элемент, платформа не даёт удалять его в расширении; чтобы скрыть — {""set"": ""$nm"", ""visible"": false}" }
  7558. }
  7559. foreach ($nm in $allNames) {
  7560. $refs = Find-ModuleRefs $nm 'element'
  7561. if ($refs.Count -gt 0) { Fail "${ctx}: на элемент '$nm' ссылается модуль формы — сначала убери обращения из кода:`n$(Format-ModuleRefs $refs)" }
  7562. }
  7563. # Командный интерфейс формы: пункт с параметром из текущей строки удаляемого — каскадом
  7564. $cif = $root.SelectSingleNode("f:CommandInterface", $nsMgr)
  7565. if ($null -ne $cif) {
  7566. $lowerNames = @{}; foreach ($nm in $allNames) { $lowerNames[$nm.ToLower()] = $true }
  7567. foreach ($a in @($cif.SelectNodes(".//f:Item/f:Attribute", $nsMgr))) {
  7568. if ($a.InnerText.Trim() -match '^~?Items\.([^.]+)(\.|$)' -and $lowerNames.ContainsKey($Matches[1].ToLower())) {
  7569. $item = $a.ParentNode
  7570. $parent = $item.ParentNode
  7571. Remove-NodeWithWs $item
  7572. while (-not (Same $parent $root) -and $null -eq (Get-FirstElementChild $parent)) {
  7573. $up = $parent.ParentNode
  7574. Remove-NodeWithWs $parent
  7575. $parent = $up
  7576. }
  7577. $script:removeLog += " - командный интерфейс: пункт с параметром $($a.InnerText.Trim())"
  7578. }
  7579. }
  7580. }
  7581. # Обработчики событий удаляемого
  7582. $handlers = @()
  7583. foreach ($it in $items) {
  7584. foreach ($ev in $it.Node.SelectNodes(".//f:Event", $nsMgr)) { $handlers += $ev.InnerText.Trim() }
  7585. }
  7586. Add-LeftHandlers $handlers
  7587. # Условное оформление: поле удаляемого элемента — из списка оформляемых; пустой список
  7588. # означал бы «вся форма», поэтому такое правило уходит целиком.
  7589. $ca = $root.SelectSingleNode("f:Attributes/f:ConditionalAppearance", $nsMgr)
  7590. if ($null -ne $ca) {
  7591. $lower = @{}; foreach ($nm in $allNames) { $lower[$nm.ToLower()] = $true }
  7592. foreach ($rule in @($ca.SelectNodes("dcsset:item", $nsMgr))) {
  7593. $sel = $rule.SelectSingleNode("dcsset:selection", $nsMgr)
  7594. if ($null -eq $sel) { continue }
  7595. $hit = $false
  7596. foreach ($si in @($sel.SelectNodes("dcsset:item", $nsMgr))) {
  7597. $f = $si.SelectSingleNode("dcsset:field", $nsMgr)
  7598. if ($null -ne $f -and $lower.ContainsKey($f.InnerText.Trim().ToLower())) {
  7599. $script:removeLog += " - условное оформление: поле $($f.InnerText.Trim()) убрано из правила"
  7600. Remove-NodeWithWs $si
  7601. $hit = $true
  7602. }
  7603. }
  7604. if ($hit -and $null -eq (Get-FirstElementChild $sel)) {
  7605. Remove-NodeWithWs $rule
  7606. $script:removeLog += " - условное оформление: правило без оформляемых полей удалено"
  7607. }
  7608. }
  7609. if ($null -eq (Get-FirstElementChild $ca)) { Remove-NodeWithWs $ca }
  7610. }
  7611. foreach ($it in $items) {
  7612. $node = $it.Node
  7613. $name = $node.GetAttribute("name")
  7614. # вложенные элементы для отчёта — без служебных узлов
  7615. $shown = @()
  7616. foreach ($d in $node.SelectNodes(".//*[@name]")) {
  7617. if ($d.NamespaceURI -eq $formNs -and $d.ParentNode.LocalName -eq 'ChildItems') { $shown += $d.GetAttribute("name") }
  7618. }
  7619. $tail = ""
  7620. if ($shown.Count -gt 0) {
  7621. $list = ($shown | Select-Object -First 10) -join ', '
  7622. if ($shown.Count -gt 10) { $list += ", … и ещё $($shown.Count - 10)" }
  7623. $tail = " (+ $list)"
  7624. }
  7625. $why = if ($it.Reason) { " — $($it.Reason)" } else { "" }
  7626. $ci = $node.ParentNode
  7627. $holder = $ci.ParentNode
  7628. Remove-NodeWithWs $node
  7629. Remove-IfEmptyChildItems $ci
  7630. # Опустевшая командная панель или меню — пустым тегом, как пишет платформа
  7631. if ($null -ne $holder -and $script:companionTags -contains $holder.LocalName -and $null -eq (Get-FirstElementChild $holder)) {
  7632. while ($holder.HasChildNodes) { $holder.RemoveChild($holder.FirstChild) | Out-Null }
  7633. $holder.IsEmpty = $true
  7634. }
  7635. $script:removeLog += " - $name [$($node.LocalName)]$tail$why"
  7636. $script:removedCount++
  7637. }
  7638. }
  7639. function Invoke-Remove($op, [int]$idx) {
  7640. $ctx = "elements[$idx] remove"
  7641. Assert-OpKeys $op @('remove') $ctx
  7642. $names = @(@($op.remove) | ForEach-Object { "$_" } | Where-Object { $_ })
  7643. if ($names.Count -eq 0) { Fail "${ctx}: укажи имя элемента или список имён" }
  7644. $nodes = @()
  7645. $seen = @{}
  7646. foreach ($n in $names) {
  7647. if ($seen.ContainsKey($n)) { Fail "${ctx}: '$n' указан дважды" }
  7648. $seen[$n] = $true
  7649. $node = Find-FormElement $n
  7650. if ($null -eq $node) { Fail "${ctx}: элемент '$n' не найден в форме" }
  7651. if ($node.ParentNode.LocalName -ne 'ChildItems' -or $script:companionTags -contains $node.LocalName) {
  7652. Fail "${ctx}: '$n' — служебный узел ($($node.LocalName)) своего элемента, удаляется только вместе с ним"
  7653. }
  7654. $nodes += $node
  7655. }
  7656. Remove-FormElements $nodes $ctx ""
  7657. }
  7658. function Remove-FormCommand($op, [int]$idx) {
  7659. $ctx = "commands[$idx] remove"
  7660. Assert-OpKeys $op @('remove') $ctx
  7661. $name = "$($op.remove)"
  7662. $sec = $root.SelectSingleNode("f:Commands", $nsMgr)
  7663. $cmd = $null
  7664. if ($null -ne $sec) { foreach ($c in $sec.SelectNodes("f:Command", $nsMgr)) { if ($c.GetAttribute("name") -eq $name) { $cmd = $c; break } } }
  7665. if ($null -eq $cmd) { Fail "${ctx}: команда '$name' не найдена в форме" }
  7666. $name = $cmd.GetAttribute("name")
  7667. if (Test-Borrowed $name 'command') { Fail "${ctx}: '$name' — заимствованная команда, платформа не даёт удалять её в расширении" }
  7668. $refs = Find-ModuleRefs $name 'command'
  7669. if ($refs.Count -gt 0) { Fail "${ctx}: на команду '$name' ссылается модуль формы — сначала убери обращения из кода:`n$(Format-ModuleRefs $refs)" }
  7670. # Кнопки команды — через общий удалитель (их имена тоже проверяются по модулю)
  7671. $buttons = @()
  7672. foreach ($s in (Get-ElementScopes)) {
  7673. foreach ($cn in $s.SelectNodes(".//f:CommandName", $nsMgr)) {
  7674. if ($cn.InnerText.Trim() -eq "Form.Command.$name") {
  7675. $b = Get-OwnerElement $cn
  7676. if ($null -ne $b) { $buttons += $b }
  7677. }
  7678. }
  7679. }
  7680. if ($buttons.Count -gt 0) { Remove-FormElements $buttons $ctx "кнопка удалённой команды $name" }
  7681. # Пункты командного интерфейса формы
  7682. $ci = $root.SelectSingleNode("f:CommandInterface", $nsMgr)
  7683. if ($null -ne $ci) {
  7684. foreach ($c in @($ci.SelectNodes(".//f:Item/f:Command", $nsMgr))) {
  7685. if ($c.InnerText.Trim() -ne "Form.Command.$name") { continue }
  7686. $item = $c.ParentNode
  7687. $parent = $item.ParentNode
  7688. Remove-NodeWithWs $item
  7689. while (-not (Same $parent $root) -and $null -eq (Get-FirstElementChild $parent)) {
  7690. $up = $parent.ParentNode
  7691. Remove-NodeWithWs $parent
  7692. $parent = $up
  7693. }
  7694. $script:removeLog += " - командный интерфейс: пункт команды $name"
  7695. }
  7696. }
  7697. Add-LeftHandlers @($cmd.SelectNodes("f:Action", $nsMgr) | ForEach-Object { $_.InnerText.Trim() })
  7698. Remove-NodeWithWs $cmd
  7699. if ($null -eq (Get-FirstElementChild $sec)) { Remove-NodeWithWs $sec }
  7700. $script:removeLog += " - команда $name"
  7701. $script:removedCount++
  7702. }
  7703. function Remove-FormAttribute($op, [int]$idx) {
  7704. $ctx = "attributes[$idx] remove"
  7705. Assert-OpKeys $op @('remove') $ctx
  7706. $name = "$($op.remove)"
  7707. $sec = $root.SelectSingleNode("f:Attributes", $nsMgr)
  7708. $attr = $null
  7709. if ($null -ne $sec) { foreach ($a in $sec.SelectNodes("f:Attribute", $nsMgr)) { if ($a.GetAttribute("name") -eq $name) { $attr = $a; break } } }
  7710. if ($null -eq $attr) { Fail "${ctx}: реквизит '$name' не найден в форме" }
  7711. $name = $attr.GetAttribute("name")
  7712. $main = $attr.SelectSingleNode("f:MainAttribute", $nsMgr)
  7713. if ($null -ne $main -and $main.InnerText.Trim() -eq 'true') { Fail "${ctx}: '$name' — основной реквизит формы, он не удаляется" }
  7714. if (Test-Borrowed $name 'attribute') { Fail "${ctx}: '$name' — заимствованный реквизит, платформа не даёт удалять его в расширении" }
  7715. $refs = Find-ModuleRefs $name 'attribute'
  7716. if ($refs.Count -gt 0) { Fail "${ctx}: к реквизиту '$name' обращается модуль формы — сначала убери обращения из кода:`n$(Format-ModuleRefs $refs)" }
  7717. # Привязки в форме: пути данных элементов и поля условного оформления
  7718. $users = @()
  7719. $isPath = { param($t) $t -eq $name -or $t.StartsWith("$name.", [System.StringComparison]::OrdinalIgnoreCase) }
  7720. foreach ($s in (Get-ElementScopes)) {
  7721. foreach ($t in $s.SelectNodes(".//*")) {
  7722. if (-not $t.LocalName.EndsWith('DataPath')) { continue }
  7723. if (& $isPath $t.InnerText.Trim()) {
  7724. $o = Get-OwnerElement $t
  7725. if ($null -ne $o) { $users += "$($o.GetAttribute('name')) ($($t.LocalName))" }
  7726. }
  7727. }
  7728. }
  7729. $ca = $root.SelectSingleNode("f:Attributes/f:ConditionalAppearance", $nsMgr)
  7730. if ($null -ne $ca) {
  7731. foreach ($t in $ca.SelectNodes(".//dcsset:left | .//dcsset:right", $nsMgr)) {
  7732. $xt = $t.GetAttribute("type", "http://www.w3.org/2001/XMLSchema-instance")
  7733. if ($xt.EndsWith(':Field') -and (& $isPath $t.InnerText.Trim())) { $users += "условное оформление (отбор по $($t.InnerText.Trim()))" }
  7734. }
  7735. }
  7736. $cif = $root.SelectSingleNode("f:CommandInterface", $nsMgr)
  7737. if ($null -ne $cif) {
  7738. foreach ($a in $cif.SelectNodes(".//f:Item/f:Attribute", $nsMgr)) {
  7739. $at = $a.InnerText.Trim().TrimStart('~')
  7740. if (& $isPath $at) { $users += "командный интерфейс (параметр $($a.InnerText.Trim()))" }
  7741. }
  7742. }
  7743. if ($users.Count -gt 0) {
  7744. Fail "${ctx}: к реквизиту '$name' привязаны: $(($users | Select-Object -Unique) -join '; ') — удали или перепривяжи их раньше (elements выполняются до attributes)"
  7745. }
  7746. Remove-NodeWithWs $attr
  7747. if ($null -eq (Get-FirstElementChild $sec)) {
  7748. while ($sec.HasChildNodes) { $sec.RemoveChild($sec.FirstChild) | Out-Null }
  7749. $sec.IsEmpty = $true
  7750. }
  7751. $script:removeLog += " - реквизит $name"
  7752. $script:removedCount++
  7753. }
  7754. # === 9e. Секции формы ===
  7755. # Узел-секция корня формы; нет — создаётся на своём месте (порядок корня — по корпусу).
  7756. function Get-OrCreateRootSection([string]$tag) {
  7757. $sec = $root.SelectSingleNode("f:$tag", $nsMgr)
  7758. if ($null -ne $sec) { return $sec }
  7759. $sec = $xmlDoc.CreateElement($tag, $formNs)
  7760. Insert-RootChild $sec
  7761. return $sec
  7762. }
  7763. function Insert-RootChild($node) {
  7764. $rank = Get-FormRootRank $node.LocalName
  7765. $ref = $null
  7766. foreach ($c in $root.ChildNodes) {
  7767. if ($c.NodeType -ne 'Element') { continue }
  7768. if ((Get-FormRootRank $c.LocalName) -gt $rank) { $ref = $c; break }
  7769. }
  7770. Insert-NodeAt $root $node $ref (Get-ChildIndent $root)
  7771. }
  7772. # Вывод эмиттера form-compile во фрагмент: блок пишет через X; результат — узлы верхнего уровня.
  7773. function Invoke-SectionEmit([scriptblock]$emit, [string]$rootType = '', [bool]$normalize = $false) {
  7774. $saveId = $script:nextElemId
  7775. $script:xml = New-Object System.Text.StringBuilder 2048
  7776. X "<_F $allNsDecl>"
  7777. . $emit
  7778. X "</_F>"
  7779. $script:nextElemId = $saveId
  7780. # Перечисления — к виду платформы, как в form-compile: у тегов прямо под корнем фрагмента — по $rootType
  7781. # (свойства формы); $normalize — у вложенных узлов по их типу (добавляемые реквизиты и команды)
  7782. $text = $script:xml.ToString()
  7783. if ($rootType -or $normalize) { $text = Normalize-EnumTags $text $rootType }
  7784. return @(Import-ElementNodes (Parse-Fragment $text))
  7785. }
  7786. # Свойство формы: значение — как в form-compile; null — убрать.
  7787. function Set-FormProperty([string]$key, $value) {
  7788. 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])) {
  7789. Fail "properties.${key}: значение — строка, число или true/false"
  7790. }
  7791. $probe = New-Object PSObject
  7792. $probe | Add-Member -NotePropertyName $key -NotePropertyValue $(if ($null -eq $value -or "$value" -eq '') { 'x' } else { $value })
  7793. $node = @(Invoke-SectionEmit { Emit-Properties -props $probe -indent "`t" } $(if ($null -eq $value -or "$value" -eq '') { '' } else { 'Form' }))[0]
  7794. $tag = $node.LocalName
  7795. $existing = $root.SelectSingleNode("f:$tag", $nsMgr)
  7796. if ($null -eq $value -or "$value" -eq '') {
  7797. if ($null -ne $existing) { Remove-NodeWithWs $existing; $script:formLog += " * $tag убрано"; $script:formChanged++ }
  7798. return
  7799. }
  7800. if ($null -ne $existing) { $root.ReplaceChild($node, $existing) | Out-Null } else { Insert-RootChild $node }
  7801. $script:formLog += " * ${tag}=$($node.InnerText)"
  7802. $script:formChanged++
  7803. }
  7804. # Снять привязки события у формы или элемента: callType пуст — все (в расширении у события их бывает
  7805. # несколько), иначе — только эту. Пустой <Events> убирается. Возвращает снятые узлы.
  7806. function Remove-EventBindings($owner, [string]$evName, [string]$callType) {
  7807. $sec = $owner.SelectSingleNode("f:Events", $nsMgr)
  7808. $hits = @()
  7809. if ($null -ne $sec) {
  7810. foreach ($e in @($sec.SelectNodes("f:Event", $nsMgr))) {
  7811. if ($e.GetAttribute('name') -eq $evName -and (-not $callType -or $e.GetAttribute('callType') -eq $callType)) { $hits += $e }
  7812. }
  7813. }
  7814. foreach ($e in $hits) { Remove-NodeWithWs $e }
  7815. if ($hits.Count -gt 0 -and $null -eq (Get-FirstElementChild $sec)) { Remove-NodeWithWs $sec }
  7816. return ,$hits
  7817. }
  7818. # Обработчики, отвязанные снятием или заменой. Проверяются в конце запуска (Resolve-UnboundHandlers):
  7819. # правка могла привязать то же имя к другому событию.
  7820. $script:unboundHandlers = @()
  7821. function Add-UnboundHandlers([string[]]$handlers) {
  7822. foreach ($h in $handlers) { if ($h) { $script:unboundHandlers += $h } }
  7823. }
  7824. # Отвязанные, которые форма больше не вызывает, — в «Handlers left in module». Копия исходной формы
  7825. # в <BaseForm> расширения не в счёт: её привязки — не привязки расширения.
  7826. function Resolve-UnboundHandlers {
  7827. if ($script:unboundHandlers.Count -eq 0) { return }
  7828. $bound = @{}
  7829. foreach ($e in $xmlDoc.SelectNodes("//f:Event[not(ancestor::f:BaseForm)]|//f:Action[not(ancestor::f:BaseForm)]", $nsMgr)) { $bound[$e.InnerText.Trim().ToLower()] = $true }
  7830. $left = @($script:unboundHandlers | Where-Object { -not $bound.ContainsKey($_.ToLower()) })
  7831. if ($left.Count -gt 0) { Add-LeftHandlers $left }
  7832. }
  7833. # События формы — как events элемента: объект { Событие: обработчик | { handler, callType } | [ … ] } вешает
  7834. # или заменяет, null — снимает; список [ Событие | { event, callType } ] — имена по конвенции.
  7835. function Add-FormEventsDsl($events) {
  7836. Update-FormOwner
  7837. $adds = @()
  7838. if ($events -is [array]) {
  7839. foreach ($v in $events) {
  7840. $isObj = $v -is [System.Management.Automation.PSCustomObject]
  7841. $n = Resolve-EventName 'Form' $(if ($isObj) { "$($v.event)" } else { "$v" }) 'Form events'
  7842. $h = if ($isObj) { "$($v.handler)" } else { '' }
  7843. $ct = if ($isObj) { Normalize-CallType "$($v.callType)" 'Form' $n } else { '' }
  7844. if (-not $ct -and $script:isExtension) { $ct = 'Before' }
  7845. if (-not $h) {
  7846. # Имя по конвенции типовых (ПриСозданииНаСервере); у события вне каталога его нет
  7847. if (-not (Get-EventEntry 'Form' $n)) { Fail "events: у события формы $n укажите имя обработчика — имени по конвенции для него нет" }
  7848. $h = Get-HandlerName -elementName '' -eventName $n -xmlTag 'Form' -callType $ct
  7849. }
  7850. $adds += [pscustomobject]@{ name = $n; handler = $h; callType = $ct }
  7851. }
  7852. } elseif ($events -is [System.Management.Automation.PSCustomObject]) {
  7853. foreach ($p in $events.PSObject.Properties) {
  7854. $n = Resolve-EventName 'Form' $p.Name 'Form events'
  7855. if (@($p.Value).Count -eq 0) { Fail "events: событие формы $n — пустой список; чтобы снять обработчик, укажите null" }
  7856. foreach ($v in @($p.Value)) {
  7857. $isObj = $v -is [System.Management.Automation.PSCustomObject]
  7858. $h = if ($isObj) { "$($v.handler)" } else { "$v" }
  7859. $ct = if ($isObj) { Normalize-CallType "$($v.callType)" 'Form' $n } else { '' }
  7860. if (-not $h) {
  7861. # null — снять: без callType — все привязки события, с callType — только эту
  7862. $ctStr = if ($ct) { "[$ct]" } else { "" }
  7863. $hits = Remove-EventBindings $root $n $ct
  7864. if ($hits.Count -eq 0) { Fail "events: событие формы $n$ctStr не обрабатывается — снимать нечего" }
  7865. foreach ($e in $hits) {
  7866. $ec = $e.GetAttribute('callType'); $ecStr = if ($ec) { "[$ec]" } else { "" }
  7867. $script:formLog += " - event $n$ecStr -> $($e.InnerText)"
  7868. $script:formChanged++
  7869. }
  7870. Add-UnboundHandlers @($hits | ForEach-Object { $_.InnerText })
  7871. continue
  7872. }
  7873. if (-not $ct -and $script:isExtension) { $ct = 'Before' }
  7874. $adds += [pscustomobject]@{ name = $n; handler = $h; callType = $ct }
  7875. }
  7876. }
  7877. } else { Fail "events — объект { Событие: обработчик } или список событий" }
  7878. $sec = $null
  7879. foreach ($a in $adds) {
  7880. Test-EventPairs -pairs @([pscustomobject]@{ name = $a.name }) -xmlTag 'Form' -elementName ''
  7881. $n = $a.name; $h = $a.handler; $ct = $a.callType
  7882. $ctStr = if ($ct) { "[$ct]" } else { "" }
  7883. Register-Handler $h 'form' 'Form' $n
  7884. if ($null -eq $sec) { $sec = $root.SelectSingleNode("f:Events", $nsMgr) }
  7885. if ($null -ne $sec) {
  7886. $dup = $null
  7887. foreach ($e in $sec.SelectNodes("f:Event", $nsMgr)) {
  7888. if ($e.GetAttribute('name') -eq $n -and $e.GetAttribute('callType') -eq $ct) { $dup = $e; break }
  7889. }
  7890. if ($null -ne $dup) {
  7891. $old = $dup.InnerText
  7892. if ($old -eq $h) { $script:formLog += " = event $n$ctStr -> $h already bound"; continue }
  7893. # Другое имя — замена: у события один обработчик (на вид вызова)
  7894. $dup.InnerText = $h
  7895. Add-UnboundHandlers @($old)
  7896. $script:formLog += " ~ event $n${ctStr}: $old -> $h"
  7897. $script:formChanged++
  7898. continue
  7899. }
  7900. }
  7901. if ($null -eq $sec) { $sec = Get-OrCreateRootSection 'Events' }
  7902. $ev = $xmlDoc.CreateElement("Event", $formNs)
  7903. $ev.SetAttribute('name', $n)
  7904. if ($ct) { $ev.SetAttribute('callType', $ct) }
  7905. $ev.InnerText = $h
  7906. Insert-NodeAt $sec $ev (Get-EventInsertRef $sec 'Form' $n $ct) (Get-ChildIndent $sec)
  7907. $script:formLog += " + event $n$ctStr -> $h"
  7908. $script:formChanged++
  7909. }
  7910. }
  7911. # Исключённые команды: список имён — исключить; { remove: [...] } — вернуть.
  7912. function Update-ExcludedCommands($spec) {
  7913. if ($spec -is [System.Management.Automation.PSCustomObject]) {
  7914. Assert-OpKeys $spec @('remove') "excludedCommands"
  7915. $sec = $root.SelectSingleNode("f:CommandSet", $nsMgr)
  7916. foreach ($n in @(@($spec.remove) | ForEach-Object { "$_" })) {
  7917. $hit = $null
  7918. if ($null -ne $sec) { foreach ($e in $sec.SelectNodes("f:ExcludedCommand", $nsMgr)) { if ($e.InnerText.Trim() -eq $n) { $hit = $e; break } } }
  7919. if ($null -eq $hit) { Fail "excludedCommands: команда '$n' не исключена в форме" }
  7920. Remove-NodeWithWs $hit
  7921. $script:formLog += " - исключение команды $n"
  7922. $script:formChanged++
  7923. }
  7924. if ($null -ne $sec -and $null -eq (Get-FirstElementChild $sec)) { Remove-NodeWithWs $sec }
  7925. return
  7926. }
  7927. $sec = $null
  7928. foreach ($n in @(@($spec) | ForEach-Object { "$_" } | Where-Object { $_ })) {
  7929. if ($null -eq $sec) { $sec = Get-OrCreateRootSection 'CommandSet' }
  7930. $dup = $false
  7931. foreach ($e in $sec.SelectNodes("f:ExcludedCommand", $nsMgr)) { if ($e.InnerText.Trim() -eq $n) { $dup = $true; break } }
  7932. if ($dup) { $script:formLog += " = команда $n уже исключена"; continue }
  7933. $e = $xmlDoc.CreateElement("ExcludedCommand", $formNs)
  7934. $e.InnerText = $n
  7935. Insert-NodeAt $sec $e $null (Get-ChildIndent $sec)
  7936. $script:formLog += " + исключена команда $n"
  7937. $script:formChanged++
  7938. }
  7939. }
  7940. # Параметры формы — по порядку: определения — как в form-compile; { remove: имя | [...] } — удалить;
  7941. # { set: имя, … } — изменить.
  7942. function Update-FormParameters($list) {
  7943. $i = 0
  7944. foreach ($p in @($list)) {
  7945. if ($null -ne $p.PSObject.Properties['remove']) {
  7946. Assert-OpKeys $p @('remove') "parameters[$i] remove"
  7947. foreach ($n in @(@($p.remove) | ForEach-Object { "$_" })) {
  7948. $sec = $root.SelectSingleNode("f:Parameters", $nsMgr)
  7949. $hit = $null
  7950. if ($null -ne $sec) { foreach ($e in $sec.SelectNodes("f:Parameter", $nsMgr)) { if ($e.GetAttribute('name') -eq $n) { $hit = $e; break } } }
  7951. if ($null -eq $hit) { Fail "parameters[$i] remove: параметр '$n' не найден в форме" }
  7952. $refs = Find-ModuleRefs $n 'parameter'
  7953. if ($refs.Count -gt 0) { Fail "parameters[$i] remove: к параметру '$n' обращается модуль формы — сначала убери обращения из кода:`n$(Format-ModuleRefs $refs)" }
  7954. Remove-NodeWithWs $hit
  7955. if ($null -eq (Get-FirstElementChild $sec)) { Remove-NodeWithWs $sec }
  7956. $script:formLog += " - параметр $n"
  7957. $script:formChanged++
  7958. }
  7959. } elseif ($null -ne $p.PSObject.Properties['set']) {
  7960. Invoke-ParamSet $p $i
  7961. } elseif ($null -ne $p.PSObject.Properties['rename']) {
  7962. Invoke-ParamRename $p $i
  7963. } else {
  7964. Assert-OpKeys $p $script:paramKeys "parameters[$i] '$($p.name)'"
  7965. $sec = Get-OrCreateRootSection 'Parameters'
  7966. foreach ($e in $sec.SelectNodes("f:Parameter", $nsMgr)) {
  7967. if ($e.GetAttribute('name') -eq "$($p.name)") { Fail "parameters: параметр '$($p.name)' уже есть в форме; изменить: { `"set`": `"$($p.name)`", … }" }
  7968. }
  7969. $wrap = @(Invoke-SectionEmit { Emit-Parameters -params @($p) -indent "`t" })[0]
  7970. foreach ($node in @($wrap.SelectNodes("f:Parameter", $nsMgr))) {
  7971. $wrap.RemoveChild($node) | Out-Null
  7972. Insert-NodeAt $sec $node $null (Get-ChildIndent $sec)
  7973. $script:formLog += " + параметр $($node.GetAttribute('name'))"
  7974. $script:formChanged++
  7975. }
  7976. }
  7977. $i++
  7978. }
  7979. }
  7980. # Условное оформление: правила — как в form-compile; добавляются в конец оформления формы.
  7981. function Add-FormConditionalAppearance($items) {
  7982. $items = @($items)
  7983. if ($items.Count -eq 0) { return }
  7984. $attrs = Get-OrCreateRootSection 'Attributes'
  7985. if ($attrs.IsEmpty) { $attrs.IsEmpty = $false }
  7986. $ca = $attrs.SelectSingleNode("f:ConditionalAppearance", $nsMgr)
  7987. $wrap = @(Invoke-SectionEmit { Emit-ConditionalAppearance -items $items -indent "`t`t" -wrapTag 'ConditionalAppearance' })[0]
  7988. if ($null -eq $ca) {
  7989. Insert-NodeAt $attrs $wrap $null (Get-ChildIndent $attrs)
  7990. $n = @($wrap.ChildNodes | Where-Object { $_.NodeType -eq 'Element' }).Count
  7991. } else {
  7992. $n = 0
  7993. foreach ($r in @($wrap.ChildNodes | Where-Object { $_.NodeType -eq 'Element' })) {
  7994. $wrap.RemoveChild($r) | Out-Null
  7995. Insert-NodeAt $ca $r $null (Get-ChildIndent $ca)
  7996. $n++
  7997. }
  7998. }
  7999. $script:formLog += " + условное оформление: правил $n"
  8000. $script:formChanged += $n
  8001. }
  8002. # Командный интерфейс: пункты панелей — как в form-compile; добавляются в конец своей панели.
  8003. function Add-FormCommandInterface($ci) {
  8004. $wrap = @(Invoke-SectionEmit { Emit-CommandInterface -ci $ci -indent "`t" })
  8005. if ($wrap.Count -eq 0) { return }
  8006. $wrap = $wrap[0]
  8007. $sec = $root.SelectSingleNode("f:CommandInterface", $nsMgr)
  8008. if ($null -eq $sec) {
  8009. Insert-RootChild $wrap
  8010. foreach ($pn in @($wrap.ChildNodes | Where-Object { $_.NodeType -eq 'Element' })) {
  8011. $script:formLog += " + командный интерфейс, $($pn.LocalName): пунктов $(@($pn.SelectNodes('f:Item', $nsMgr)).Count)"
  8012. $script:formChanged++
  8013. }
  8014. return
  8015. }
  8016. foreach ($pn in @($wrap.ChildNodes | Where-Object { $_.NodeType -eq 'Element' })) {
  8017. $target = $sec.SelectSingleNode("f:$($pn.LocalName)", $nsMgr)
  8018. if ($null -eq $target) {
  8019. $wrap.RemoveChild($pn) | Out-Null
  8020. # Как в выгрузке: панель навигации раньше командной панели
  8021. $ref = if ($pn.LocalName -eq 'NavigationPanel') { $sec.SelectSingleNode("f:CommandBar", $nsMgr) } else { $null }
  8022. Insert-NodeAt $sec $pn $ref (Get-ChildIndent $sec)
  8023. $cnt = @($pn.SelectNodes('f:Item', $nsMgr)).Count
  8024. } else {
  8025. $cnt = 0
  8026. foreach ($it in @($pn.SelectNodes("f:Item", $nsMgr))) {
  8027. $pn.RemoveChild($it) | Out-Null
  8028. Insert-NodeAt $target $it $null (Get-ChildIndent $target)
  8029. $cnt++
  8030. }
  8031. }
  8032. $script:formLog += " + командный интерфейс, $($pn.LocalName): пунктов $cnt"
  8033. $script:formChanged++
  8034. }
  8035. }
  8036. # Обработчики, которые были в форме до правки: callType по умолчанию ставится только новым
  8037. $script:preexistingHandlers = New-Object 'System.Collections.Generic.HashSet[System.Xml.XmlNode]'
  8038. foreach ($n in $root.SelectNodes("//f:Event | //f:Action", $nsMgr)) { [void]$script:preexistingHandlers.Add($n) }
  8039. # === 9f. Реквизиты, команды, параметры: изменение (set), колонки по пути ===
  8040. # Ключи записей — те, что читают эмиттеры form-compile, с их синонимами. Эмиттер незнакомый ключ
  8041. # молча пропустил бы — поэтому он ошибка.
  8042. $script:attrKeys = @('name','title','type','valueType','typeDescription','описаниеТипов','типЗначений','planner','chart','main','view','edit','savedData','save','fillCheck','fillChecking','useAlways','functionalOptions','columns','additionalColumns','settings')
  8043. $script:colKeys = @('name','title','type','fillCheck','fillChecking','functionalOptions','view','edit','useAlways')
  8044. $script:cmdKeys = @('name','title','tooltip','use','shortcut','picture','loadTransparent','action','actions','callType','functionalOptions','representation','modifiesSavedData','currentRowUse','table','associatedTableElementId','используемаяТаблица')
  8045. $script:paramKeys = @('name','type','key')
  8046. # Тег, который пишет ключ. Ключи одного тега меняются одной пробой (action + callType, picture + loadTransparent).
  8047. $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' }
  8048. $script:colKeyTags = @{ title='Title'; type='Type'; fillCheck='FillCheck'; fillChecking='FillCheck'; functionalOptions='FunctionalOptions'; view='View'; edit='Edit' }
  8049. $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' }
  8050. $script:paramKeyTags = @{ type='Type'; key='KeyParameter' }
  8051. # Ключи настроек динамического списка — теги, которые они пишут; отбор, параметры данных, сортировка и
  8052. # оформление — части пользовательских настроек (ListSettings), меняются по отдельности
  8053. $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') }
  8054. $script:dlListParts = @{ filter = 'filter'; dataParameters = 'dataParameters'; order = 'order'; conditionalAppearance = 'conditionalAppearance' }
  8055. # Порядок детей — как пишут эмиттеры (он же платформенный). Settings динамического списка — после Columns.
  8056. $script:sectionChildOrder = @{
  8057. Attribute = @('Title','Type','Settings','MainAttribute','View','Edit','SavedData','Save','FillCheck','UseAlways','FunctionalOptions','Columns','Settings#DynamicList')
  8058. Column = @('Title','Type','FillCheck','FunctionalOptions','View','Edit')
  8059. Command = @('Title','ToolTip','Use','Shortcut','Picture','Action','FunctionalOptions','Representation','ModifiesSavedData','CurrentRowUse','AssociatedTableElementId')
  8060. Parameter = @('Type','KeyParameter')
  8061. # Настройки динамического списка — порядок корпуса (ERP, БП, УТ); KeyField и MainTable вместе не встречаются — как в эмиттере
  8062. ListSettings = @('filter','dataParameters','order','conditionalAppearance','item','itemsViewMode','itemsUserSettingID','itemsUserSettingPresentation')
  8063. Settings = @('AutoFillAvailableFields','ManualQuery','DynamicDataRead','QueryText','Field','CalculatedField','Parameter','KeyType','KeyField','MainTable','AutoSaveUserSettings','GetInvisibleFieldPresentations','ListSettings')
  8064. }
  8065. function Get-SectionChildRank([string]$parentTag, $child) {
  8066. $ln = $child.LocalName
  8067. if ($ln -eq 'Settings' -and $child.GetAttribute('type', 'http://www.w3.org/2001/XMLSchema-instance') -eq 'DynamicList') { $ln = 'Settings#DynamicList' }
  8068. return [array]::IndexOf($script:sectionChildOrder[$parentTag], $ln)
  8069. }
  8070. function Insert-SectionChild($parent, $child, [string]$indent = $null) {
  8071. if (-not $indent) { $indent = Get-ChildIndent $parent }
  8072. $rank = Get-SectionChildRank $parent.LocalName $child
  8073. $ref = $null
  8074. foreach ($c in $parent.ChildNodes) {
  8075. if ($c.NodeType -ne 'Element') { continue }
  8076. if ((Get-SectionChildRank $parent.LocalName $c) -gt $rank) { $ref = $c; break }
  8077. }
  8078. Insert-NodeAt $parent $child $ref $indent
  8079. }
  8080. function New-DslSpec($h) { return (ConvertFrom-JsonInput ([pscustomobject]$h | ConvertTo-Json -Depth 100 -Compress) 'DSL spec') }
  8081. # Узел секции по имени (имена в 1С регистронезависимы)
  8082. function Find-SectionItem([string]$section, [string]$tag, [string]$name) {
  8083. foreach ($n in $root.SelectNodes("f:$section/f:$tag", $nsMgr)) { if ($n.GetAttribute('name') -eq $name) { return $n } }
  8084. return $null
  8085. }
  8086. function Test-MainAttribute($node) {
  8087. $m = $node.SelectSingleNode("f:MainAttribute", $nsMgr)
  8088. return ($null -ne $m -and $m.InnerText.Trim() -eq 'true')
  8089. }
  8090. # Вид реквизита: таблица (свои колонки), динамический список или прочее
  8091. function Get-AttrKind($node) {
  8092. $ts = @($node.SelectNodes("f:Type/v8:Type", $nsMgr) | ForEach-Object { $_.InnerText.Trim() })
  8093. if ($ts.Count -eq 1 -and @('v8:ValueTable','v8:ValueTree') -contains $ts[0]) { return 'table' }
  8094. if ($ts.Count -eq 1 -and $ts[0] -eq 'cfg:DynamicList') { return 'dynlist' }
  8095. return 'scalar'
  8096. }
  8097. # Тип для вывода — в записи DSL: string(150), decimal(15,2), CatalogRef.X, A | B
  8098. function Format-TypeNode($t) {
  8099. if ($null -eq $t -or $null -eq $t.SelectSingleNode("v8:Type | v8:TypeSet | v8:TypeId", $nsMgr)) { return '(no type)' }
  8100. $parts = @()
  8101. foreach ($ty in $t.SelectNodes("v8:Type | v8:TypeSet | v8:TypeId", $nsMgr)) {
  8102. $v = $ty.InnerText.Trim() -replace '^(cfg|v8|xs|d\d+p\d+):', ''
  8103. if ($v -eq 'string') {
  8104. $l = $t.SelectSingleNode("v8:StringQualifiers/v8:Length", $nsMgr)
  8105. if ($null -ne $l -and $l.InnerText.Trim() -ne '0') { $v = "string($($l.InnerText.Trim()))" }
  8106. } elseif ($v -eq 'decimal') {
  8107. $d = $t.SelectSingleNode("v8:NumberQualifiers/v8:Digits", $nsMgr); $f = $t.SelectSingleNode("v8:NumberQualifiers/v8:FractionDigits", $nsMgr)
  8108. if ($null -ne $d) { $v = "decimal($($d.InnerText.Trim()),$(if ($null -ne $f) { $f.InnerText.Trim() } else { '0' }))" }
  8109. } elseif ($v -eq 'dateTime') {
  8110. $df = $t.SelectSingleNode("v8:DateQualifiers/v8:DateFractions", $nsMgr)
  8111. if ($null -ne $df) { $v = @{ Date = 'date'; Time = 'time'; DateTime = 'dateTime' }[$df.InnerText.Trim()] }
  8112. }
  8113. $parts += $v
  8114. }
  8115. return ($parts -join ' | ')
  8116. }
  8117. # Пробы эмиттеров form-compile: узел, каким его пишет создание формы, — с отступами места назначения
  8118. function Get-AttrProbe($spec, [string]$attrIndent) {
  8119. $ind = if ($attrIndent.Length -gt 0) { $attrIndent.Substring(1) } else { '' }
  8120. $wrap = @(Invoke-SectionEmit { Emit-Attributes -attrs @($spec) -indent $ind } '' $true)[0]
  8121. return $wrap.SelectSingleNode("f:Attribute", $nsMgr)
  8122. }
  8123. function Get-ColumnProbe($spec, [string]$attrName) {
  8124. $a = Get-AttrProbe (New-DslSpec ([ordered]@{ name = $attrName; title = ''; type = 'ValueTable'; columns = @($spec) })) "`t`t"
  8125. return $a.SelectSingleNode("f:Columns/f:Column", $nsMgr)
  8126. }
  8127. function Get-CommandProbe($spec) {
  8128. $wrap = @(Invoke-SectionEmit { Emit-Commands -cmds @($spec) -indent "`t" } '' $true)[0]
  8129. return $wrap.SelectSingleNode("f:Command", $nsMgr)
  8130. }
  8131. function Get-ParameterProbe($spec) {
  8132. $wrap = @(Invoke-SectionEmit { Emit-Parameters -params @($spec) -indent "`t" })[0]
  8133. return $wrap.SelectSingleNode("f:Parameter", $nsMgr)
  8134. }
  8135. # Теги ключа: у узла снимаются, из пробы встают на своё место (в пробе нет — так и остаётся: false, null)
  8136. function Set-SectionTags($target, $probe, [string[]]$tags) {
  8137. # Отступ детей — до снятия тегов: без детей у узла остаётся только закрывающий перевод строки
  8138. $ci = Get-ChildIndent $target
  8139. foreach ($t in $tags) { foreach ($x in @($target.SelectNodes("f:$t", $nsMgr))) { Remove-NodeWithWs $x } }
  8140. if ($null -eq $probe) { return }
  8141. foreach ($t in $tags) {
  8142. foreach ($pn in @($probe.SelectNodes("f:$t", $nsMgr))) {
  8143. $old = Get-NodeIndent $pn
  8144. $probe.RemoveChild($pn) | Out-Null
  8145. Insert-SectionChild $target $pn $ci
  8146. Set-SubtreeIndent $pn $old $ci
  8147. }
  8148. }
  8149. }
  8150. function Format-SetValue($v) {
  8151. if ($null -eq $v) { return 'null' }
  8152. if ($v -is [bool]) { return "$v".ToLower() }
  8153. if ($v -is [string] -or $v -is [int] -or $v -is [long] -or $v -is [double]) { return "$v" }
  8154. return ($v | ConvertTo-Json -Depth 20 -Compress)
  8155. }
  8156. # Общий ход set: ключи — по тегам; на каждый тег одна проба со всеми его ключами. $probeOf — проба по
  8157. # ключам тега, $x — что ей нужно знать об узле (имя, отступ)
  8158. function Set-SectionNode($node, $props, $keyTags, [scriptblock]$probeOf, $x, [string]$label, [string]$c) {
  8159. $byTag = [ordered]@{}
  8160. foreach ($p in $props) {
  8161. $tag = $keyTags[$p.Name]
  8162. if (-not $byTag.Contains($tag)) { $byTag[$tag] = @() }
  8163. $byTag[$tag] += $p
  8164. }
  8165. foreach ($tag in $byTag.Keys) {
  8166. $ps = @($byTag[$tag])
  8167. $given = @($ps | Where-Object { $null -ne $_.Value })
  8168. $probe = $null
  8169. if ($given.Count -gt 0) {
  8170. $h = [ordered]@{}
  8171. foreach ($p in $given) { $h[$p.Name] = $p.Value }
  8172. $probe = & $probeOf $h $x
  8173. } elseif ($tag -eq 'Title' -and $x.AutoTitle) {
  8174. # умолчание заголовка — как при добавлении: из имени
  8175. $probe = & $probeOf ([ordered]@{ '#auto' = $true }) $x
  8176. }
  8177. $beforeType = if ($tag -eq 'Type') { Format-TypeNode ($node.SelectSingleNode("f:Type", $nsMgr)) } else { $null }
  8178. Set-SectionTags $node $probe @($tag)
  8179. if ($tag -eq 'Type') {
  8180. $script:changeLog += " ~ ${label}: type $beforeType → $(Format-TypeNode ($node.SelectSingleNode("f:Type", $nsMgr)))"
  8181. } else {
  8182. $shown = ($ps | ForEach-Object { if ($null -eq $_.Value) { "$($_.Name) сброшено" } else { "$($_.Name)=$(Format-SetValue $_.Value)" } }) -join ', '
  8183. $script:changeLog += " ~ ${label}: $shown"
  8184. }
  8185. $script:sectionChanged++
  8186. }
  8187. }
  8188. function Assert-SetKeys($props, $keyTags, [string]$c, [string]$renameHint) {
  8189. foreach ($p in $props) {
  8190. if ($p.Name -eq 'name') { Fail "${c}: имя через set не меняется — переименование: $renameHint" }
  8191. if (-not $keyTags.ContainsKey($p.Name)) {
  8192. Fail "${c}: неизвестный ключ '$($p.Name)'; допустимы: $((@($keyTags.Keys) | Sort-Object -Unique) -join ', ')"
  8193. }
  8194. }
  8195. }
  8196. # Колонка по пути: Таблица.Колонка — своя колонка реквизита-таблицы; Объект.ТЧ.Колонка — доп. колонка
  8197. # табличной части (группа AdditionalColumns table="Объект.ТЧ")
  8198. function Resolve-ColumnPath([string]$path, [string]$c) {
  8199. $segs = @($path -split '\.')
  8200. if ($segs.Count -lt 2 -or @($segs | Where-Object { -not $_ }).Count -gt 0) { Fail "${c}: путь колонки — Таблица.Колонка или Объект.ТабличнаяЧасть.Колонка" }
  8201. $attr = Find-SectionItem 'Attributes' 'Attribute' $segs[0]
  8202. if ($null -eq $attr) { Fail "${c}: реквизит '$($segs[0])' не найден в форме" }
  8203. $colName = $segs[$segs.Count - 1]
  8204. $cols = $attr.SelectSingleNode("f:Columns", $nsMgr)
  8205. $kind = Get-AttrKind $attr
  8206. if ($kind -eq 'dynlist') { Fail "${c}: у динамического списка колонок нет — поля задаёт запрос (set + settings)" }
  8207. if ($segs.Count -eq 2) {
  8208. if ($kind -ne 'table') { Fail "${c}: у '$($segs[0])' нет своих колонок; доп. колонка табличной части — путь $($segs[0]).ТабличнаяЧасть.Колонка" }
  8209. $container = $cols
  8210. $table = $null
  8211. } else {
  8212. $table = ($segs[0..($segs.Count - 2)]) -join '.'
  8213. $container = $null
  8214. if ($null -ne $cols) { foreach ($g in $cols.SelectNodes("f:AdditionalColumns", $nsMgr)) { if ($g.GetAttribute('table') -eq $table) { $container = $g; break } } }
  8215. }
  8216. $col = $null
  8217. if ($null -ne $container) { foreach ($x in $container.SelectNodes("f:Column", $nsMgr)) { if ($x.GetAttribute('name') -eq $colName) { $col = $x; break } } }
  8218. return @{ Attr = $attr; Container = $container; Table = $table; Name = $colName; Column = $col; Columns = $cols; Segs = $segs; Kind = $kind }
  8219. }
  8220. # Табличные части объекта формы — из его описания рядом (<Объект>.xml над Forms); нет описания — $null
  8221. function Get-ObjectTabularSections {
  8222. $d = [System.IO.Path]::GetDirectoryName($resolvedFormPath)
  8223. for ($k = 0; $k -lt 3; $k++) { $d = [System.IO.Path]::GetDirectoryName($d); if (-not $d) { return $null } }
  8224. $xml = "$d.xml"
  8225. if (-not (Test-Path -LiteralPath $xml)) { return $null }
  8226. $t = [System.IO.File]::ReadAllText($xml)
  8227. # пустой список — тоже ответ («частей нет»), не $null: запятая не даёт PS развернуть его в ничто
  8228. return ,@([regex]::Matches($t, '<TabularSection uuid="[^"]*">[\s\S]*?<Properties>\s*<Name>([^<]+)</Name>') | ForEach-Object { $_.Groups[1].Value })
  8229. }
  8230. # Новая группа доп. колонок: путь таблицы — от колонки-таблицы реквизита или табличной части объекта.
  8231. # Что можно проверить по форме и описанию объекта — проверяется; остальное проверит платформа при загрузке.
  8232. function Assert-AdditionalTable($r, [string]$c) {
  8233. $segs = $r.Segs
  8234. $an = $r.Attr.GetAttribute('name')
  8235. if ($r.Kind -eq 'table') {
  8236. # Каждый уровень пути — колонка-таблица предыдущего (в корпусе только ValueTable/ValueTree)
  8237. $level = $r.Columns
  8238. for ($k = 1; $k -le $segs.Count - 2; $k++) {
  8239. $prefix = ($segs[0..($k - 1)]) -join '.'
  8240. if ($k -gt 1) {
  8241. $level = $null
  8242. foreach ($g in $r.Columns.SelectNodes("f:AdditionalColumns", $nsMgr)) { if ($g.GetAttribute('table') -eq $prefix) { $level = $g; break } }
  8243. if ($null -eq $level) { Fail "${c}: вложенной таблицы '$prefix' в форме нет — сначала добавь её колонки" }
  8244. }
  8245. $owner = $null
  8246. if ($null -ne $level) { foreach ($x in $level.SelectNodes("f:Column", $nsMgr)) { if ($x.GetAttribute('name') -eq $segs[$k]) { $owner = $x; break } } }
  8247. if ($null -eq $owner) { Fail "${c}: у '$prefix' нет колонки '$($segs[$k])' — путь вложенной таблицы идёт от колонки реквизита" }
  8248. $ot = @($owner.SelectNodes("f:Type/v8:Type", $nsMgr) | ForEach-Object { $_.InnerText.Trim() })
  8249. if ($ot.Count -ne 1 -or @('v8:ValueTable','v8:ValueTree') -notcontains $ot[0]) { Fail "${c}: колонка '$prefix.$($segs[$k])' — не таблица значений, вложенных колонок у неё нет" }
  8250. }
  8251. return
  8252. }
  8253. if ($segs.Count -eq 3 -and (Test-MainAttribute $r.Attr) -and -not $script:isExtension) {
  8254. $ts = Get-ObjectTabularSections
  8255. if ($null -ne $ts) {
  8256. if ($ts -notcontains $segs[1]) { Fail "${c}: у объекта нет табличной части '$($segs[1])'$(if ($ts.Count) { "; есть: $($ts -join ', ')" })" }
  8257. return
  8258. }
  8259. }
  8260. $script:warnLog += "[WARN] new additional columns of '$($r.Table)' — the table path is not checked here; the platform rejects a wrong one at load"
  8261. }
  8262. function Invoke-AttrSet($op, [int]$idx) {
  8263. $ctx = "attributes[$idx] set"
  8264. $targets = @(@($op.set) | ForEach-Object { "$_" } | Where-Object { $_ })
  8265. if ($targets.Count -eq 0) { Fail "${ctx}: укажи имя реквизита (колонку — путём Таблица.Колонка) или список имён" }
  8266. $props = @($op.PSObject.Properties | Where-Object { $_.Name -ne 'set' })
  8267. if ($props.Count -eq 0) { Fail "${ctx}: не указано, что менять" }
  8268. foreach ($t in $targets) {
  8269. $c = "$ctx '$t'"
  8270. if ($t.Contains('.')) {
  8271. $r = Resolve-ColumnPath $t $c
  8272. if ($null -eq $r.Column) { Fail "${c}: колонка не найдена" }
  8273. if (Test-Borrowed $r.Attr.GetAttribute('name') 'attribute') { Fail "${c}: колонка заимствованного реквизита — её свойства задаёт исходная форма" }
  8274. Assert-SetKeys $props $script:colKeyTags $c "{ `"rename`": `"$t`", `"to`": `"НовоеИмя`" }"
  8275. foreach ($p in $props) { if ($p.Name -eq 'type' -and ($null -eq $p.Value -or "$($p.Value)" -eq '')) { Fail "${c}: тип обязателен — укажи новый" } }
  8276. 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
  8277. continue
  8278. }
  8279. $node = Find-SectionItem 'Attributes' 'Attribute' $t
  8280. if ($null -eq $node) { Fail "${c}: реквизит не найден в форме" }
  8281. $name = $node.GetAttribute('name')
  8282. if (Test-Borrowed $name 'attribute') { Fail "${c}: заимствованный реквизит — его свойства задаёт исходная форма" }
  8283. foreach ($p in $props) {
  8284. if (@('columns','additionalColumns') -contains $p.Name) { Fail "${c}: колонки задаются путём: { `"name`": `"$name.Колонка`", … } — добавить, { `"set`": `"$name.Колонка`", … } — изменить, { `"remove`": `"$name.Колонка`" } — удалить" }
  8285. if ($p.Name -eq 'main') { Fail "${c}: основной реквизит через set не назначается" }
  8286. }
  8287. Assert-SetKeys $props $script:attrKeyTags $c "{ `"rename`": `"$name`", `"to`": `"НовоеИмя`" }"
  8288. $kind = Get-AttrKind $node
  8289. $isMain = Test-MainAttribute $node
  8290. $settingsOp = @($props | Where-Object { $_.Name -eq 'settings' })
  8291. $rest = @($props | Where-Object { $_.Name -ne 'settings' })
  8292. foreach ($p in $rest) {
  8293. $tag = $script:attrKeyTags[$p.Name]
  8294. if ($p.Name -eq 'type') {
  8295. if ($null -eq $p.Value -or "$($p.Value)" -eq '') { Fail "${c}: тип обязателен — укажи новый" }
  8296. if ($isMain) { Fail "${c}: тип основного реквизита не меняется — он задаёт, что редактирует форма" }
  8297. }
  8298. if ($tag -eq 'Settings' -and $kind -eq 'dynlist') { Fail "${c}: '$($p.Name)' к динамическому списку не применимо — его настройки меняет settings" }
  8299. }
  8300. $ind = Get-NodeIndent $node
  8301. if ($rest.Count -gt 0) {
  8302. $typeOp = @($rest | Where-Object { $_.Name -eq 'type' })
  8303. if ($typeOp.Count -gt 0) {
  8304. $pt = Get-AttrProbe (New-DslSpec ([ordered]@{ name = $name; title = ''; type = $typeOp[0].Value })) $ind
  8305. $nk = Get-AttrKind $pt
  8306. if ($nk -ne $kind) {
  8307. $what = @{ table = 'таблица значений/дерево'; dynlist = 'динамический список'; scalar = 'значение' }
  8308. Fail "${c}: тип меняет вид реквизита ($($what[$kind]) → $($what[$nk])) — колонки, настройки и привязанные элементы не переносятся; такой реквизит удаляют и добавляют заново"
  8309. }
  8310. }
  8311. 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
  8312. }
  8313. if ($settingsOp.Count -gt 0) { Set-DynListSettings $node $settingsOp[0].Value $ind $c }
  8314. }
  8315. }
  8316. # Настройки динамического списка: перевыпускаются только переданные части (запрос, основная таблица,
  8317. # поля…); остальное — в том числе пользовательские настройки списка — остаётся
  8318. function Set-DynListSettings($node, $v, [string]$ind, [string]$c) {
  8319. $name = $node.GetAttribute('name')
  8320. if ((Get-AttrKind $node) -ne 'dynlist') { Fail "${c}: settings — настройки динамического списка, а '$name' не динамический список" }
  8321. if (-not ($v -is [System.Management.Automation.PSCustomObject]) -or @($v.PSObject.Properties).Count -eq 0) { Fail "${c}: settings — объект с меняемыми настройками, напр. { `"query`": `"…`" }" }
  8322. $keys = @($v.PSObject.Properties | ForEach-Object { $_.Name })
  8323. foreach ($k in $keys) {
  8324. 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 ', ')" }
  8325. }
  8326. $parts = @($keys | Where-Object { $script:dlListParts.ContainsKey($_) })
  8327. if ($parts.Count -gt 0 -and $keys -contains 'listSettings') { Fail "${c}: settings — listSettings целиком или $($parts -join ', ') по частям, не вместе" }
  8328. $target = $null
  8329. foreach ($s in $node.SelectNodes("f:Settings", $nsMgr)) { if ($s.GetAttribute('type', 'http://www.w3.org/2001/XMLSchema-instance') -eq 'DynamicList') { $target = $s; break } }
  8330. if ($null -eq $target) { Fail "${c}: у '$name' нет настроек динамического списка" }
  8331. $with = (Get-AttrProbe (New-DslSpec ([ordered]@{ name = $name; title = ''; settings = $v })) $ind).SelectSingleNode("f:Settings", $nsMgr)
  8332. $without = (Get-AttrProbe (New-DslSpec ([ordered]@{ name = $name; title = ''; settings = [pscustomobject]@{ _ = $null } })) $ind).SelectSingleNode("f:Settings", $nsMgr)
  8333. # Теги — по ключам (значение, равное умолчанию, тоже записывается) и всё, что проба меняет помимо
  8334. # них; пользовательские настройки списка — только переданными частями
  8335. $d = Get-ProbeDiff $without $with
  8336. $tags = @()
  8337. foreach ($k in $keys) { if ($script:dlKeyTags.ContainsKey($k)) { $tags += $script:dlKeyTags[$k] } }
  8338. foreach ($t in $d.Tags) { if ($t -ne 'ListSettings' -or $keys -contains 'listSettings') { $tags += $t } }
  8339. $tags = @($tags | Select-Object -Unique)
  8340. $labels = @($tags)
  8341. if ($tags.Count -gt 0) { Set-SectionTags $target $with $tags }
  8342. if ($parts.Count -gt 0) {
  8343. $tls = $target.SelectSingleNode("f:ListSettings", $nsMgr)
  8344. $pls = $with.SelectSingleNode("f:ListSettings", $nsMgr)
  8345. if ($null -eq $tls -or $null -eq (Get-FirstElementChild $tls)) {
  8346. Set-SectionTags $target $with @('ListSettings')
  8347. $labels += 'ListSettings'
  8348. } else {
  8349. $ci = Get-ChildIndent $tls
  8350. foreach ($k in $parts) {
  8351. $ln = $script:dlListParts[$k]
  8352. foreach ($x in @($tls.SelectNodes("dcsset:$ln", $nsMgr))) { Remove-NodeWithWs $x }
  8353. foreach ($pn in @($pls.SelectNodes("dcsset:$ln", $nsMgr))) {
  8354. $old = Get-NodeIndent $pn
  8355. $pls.RemoveChild($pn) | Out-Null
  8356. Insert-SectionChild $tls $pn $ci
  8357. Set-SubtreeIndent $pn $old $ci
  8358. }
  8359. $labels += "ListSettings/$ln"
.claude/skills/help-add/scripts/add-help.ps1 · Bundled script · 352 lines
  1. # help-add v1.26 — Add built-in help to 1C object (+write_xml_file/write_utf8_bom: общий эталон записи)
  2. # Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
  3. param(
  4. [Parameter(Mandatory)]
  5. [string]$ObjectName,
  6. [string]$Lang = "ru",
  7. [string]$SrcDir = "src"
  8. )
  9. $ErrorActionPreference = "Stop"
  10. [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
  11. [Console]::InputEncoding = [System.Text.Encoding]::UTF8
  12. # --- Support guard (Ext/ParentConfigurations.bin) ---
  13. # See docs/1c-support-state-spec.md. Blocks edits of vendor objects "на замке" /
  14. # read-only configs unless allowed. Trigger = bin present; reaction from
  15. # .v8-project.json editingAllowedCheck (deny|warn|off, default deny). Never
  16. # throws — guard errors degrade to allow.
  17. function Get-RootUuid([string]$xmlPath) {
  18. if (-not (Test-Path $xmlPath)) { return $null }
  19. try {
  20. [xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
  21. $el = $mx.DocumentElement.FirstChild
  22. while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
  23. if ($el) { $u = $el.GetAttribute("uuid"); if ($u) { return $u } }
  24. } catch {}
  25. return $null
  26. }
  27. function Test-ExternalObjectRoot([string]$xmlPath) {
  28. if (-not (Test-Path $xmlPath)) { return $false }
  29. try {
  30. [xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
  31. $el = $mx.DocumentElement.FirstChild
  32. while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
  33. if ($el) { return @('ExternalDataProcessor','ExternalReport') -contains $el.LocalName }
  34. } catch {}
  35. return $false
  36. }
  37. function Find-V8Project([string]$startDir) {
  38. $d = $startDir
  39. for ($i = 0; $i -lt 20 -and $d; $i++) {
  40. $pj = Join-Path $d ".v8-project.json"
  41. if (Test-Path $pj) { return $pj }
  42. $parent = [System.IO.Path]::GetDirectoryName($d)
  43. if ($parent -eq $d) { break }
  44. $d = $parent
  45. }
  46. return $null
  47. }
  48. function Get-EditMode([string]$cfgDir) {
  49. try {
  50. $pj = Find-V8Project (Get-Location).ProviderPath
  51. if (-not $pj) { $pj = Find-V8Project ([System.IO.Path]::GetFullPath($cfgDir)) }
  52. if (-not $pj) { return 'deny' }
  53. # UTF-8 явно: PS 5.1 читает файл без BOM как ANSI, и configSrc с кириллицей не совпал бы
  54. $proj = Get-Content -Raw -Encoding UTF8 $pj | ConvertFrom-Json
  55. # configSrc — от каталога .v8-project.json, а не от рабочего каталога: иначе из подкаталога
  56. # проекта база не сопоставляется и берётся правило проекта.
  57. $projDir = [System.IO.Path]::GetDirectoryName($pj)
  58. $cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
  59. if ($proj.databases) {
  60. foreach ($db in $proj.databases) {
  61. if ($db.configSrc) {
  62. $src = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($projDir, $db.configSrc)).TrimEnd('\', '/')
  63. if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
  64. if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
  65. }
  66. }
  67. }
  68. }
  69. if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
  70. return 'deny'
  71. } catch { return 'deny' }
  72. }
  73. function Assert-EditAllowed([string]$targetPath, [string]$require) {
  74. try {
  75. $rp = $targetPath
  76. try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).ProviderPath } catch {}
  77. # Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
  78. if (Test-ExternalObjectRoot $rp) { return }
  79. $elemUuid = Get-RootUuid $rp
  80. $cfgDir = $null; $binPath = $null
  81. $d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
  82. for ($i = 0; $i -lt 12 -and $d; $i++) {
  83. if (Test-ExternalObjectRoot "$d.xml") { return }
  84. if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
  85. if (-not $cfgDir) {
  86. $cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
  87. if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
  88. }
  89. if ($elemUuid -and $cfgDir) { break }
  90. $parent = [System.IO.Path]::GetDirectoryName($d)
  91. if ($parent -eq $d) { break }
  92. $d = $parent
  93. }
  94. # New object (no element file): fall back to config root uuid.
  95. if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
  96. if (-not $binPath -or -not (Test-Path $binPath)) { return }
  97. $bytes = [System.IO.File]::ReadAllBytes($binPath)
  98. if ($bytes.Length -le 32) { return }
  99. $start = 0
  100. if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
  101. $text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
  102. $hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
  103. if (-not $hm.Success) { return }
  104. $G = [int]$hm.Groups[1].Value
  105. $K = [int]$hm.Groups[2].Value
  106. if ($K -eq 0) { return }
  107. $best = $null
  108. if ($elemUuid) {
  109. $u = [regex]::Escape($elemUuid.ToLower())
  110. foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
  111. $f1 = [int]$m.Groups[1].Value
  112. if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
  113. }
  114. }
  115. $blocked = $false; $code = ""; $reason = ""
  116. if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
  117. elseif ($require -eq 'removed') {
  118. if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
  119. }
  120. else {
  121. if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
  122. }
  123. if (-not $blocked) { return }
  124. $mode = Get-EditMode $cfgDir
  125. if ($mode -eq 'off') { return }
  126. # Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
  127. # latter throws and would be swallowed by this function's own catch.
  128. if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
  129. $head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
  130. $cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
  131. $offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
  132. if ($code -eq "capability-off") {
  133. $state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
  134. $fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
  135. } elseif ($code -eq "not-removed") {
  136. $state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
  137. $fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
  138. } else {
  139. $state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
  140. $fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
  141. }
  142. [Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
  143. exit 1
  144. } catch { return }
  145. }
  146. # --- Detect format version ---
  147. function Detect-FormatVersion([string]$dir) {
  148. $d = $dir
  149. while ($d) {
  150. # Автономная внешняя обработка/отчёт: своего Configuration.xml у неё нет, версию несёт
  151. # корень самой обработки. Без этого форма и макет внутри обработки 2.21 писались бы 2.17.
  152. $extPath = "$d.xml"
  153. if (Test-Path $extPath) {
  154. $extText = [System.IO.File]::ReadAllText($extPath, [System.Text.Encoding]::UTF8)
  155. $extHead = $extText.Substring(0, [Math]::Min(2000, $extText.Length))
  156. if ($extHead -match '<(ExternalDataProcessor|ExternalReport)[ >]' -and $extHead -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
  157. }
  158. $cfgPath = Join-Path $d "Configuration.xml"
  159. if (Test-Path $cfgPath) {
  160. $cfgText = [System.IO.File]::ReadAllText($cfgPath, [System.Text.Encoding]::UTF8)
  161. # Длину среза берём по СТРОКЕ, а не по размеру файла: размер в БАЙТАХ, Substring считает
  162. # СИМВОЛЫ, и на кириллице байт больше — короткий Configuration.xml ронял навык исключением.
  163. $head = $cfgText.Substring(0, [Math]::Min(2000, $cfgText.Length))
  164. if ($head -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
  165. }
  166. $parent = Split-Path $d -Parent
  167. if ($parent -eq $d) { break }
  168. $d = $parent
  169. }
  170. return "2.17"
  171. }
  172. # --- Проверки ---
  173. $objectDir = Join-Path $SrcDir $ObjectName
  174. $extDir = Join-Path $objectDir "Ext"
  175. if (-not (Test-Path $extDir)) {
  176. Write-Error "Каталог объекта не найден: $extDir. Проверьте путь ObjectName (например Catalogs/МойСправочник)."
  177. exit 1
  178. }
  179. # Справка — тело объекта, а тело и дескриптор платформа загружает только в одной версии формата.
  180. # Поэтому версию берём прежде всего из дескриптора <объект>.xml (объект может быть старше выгрузки после
  181. # мержа веток), и только без него — подъёмом от каталога объекта. Не от SrcDir: у внешней обработки
  182. # корень <Имя>.xml лежит В SrcDir, подъём его не видел, и справка обработки 2.20 писалась 2.17.
  183. $formatVersion = $null
  184. # Resolve-Path сохраняет завершающий разделитель («Обр/» → «…\Обр\»): без обрезки искался бы «…\Обр\.xml».
  185. $objectFull = (Resolve-Path $objectDir).ProviderPath.TrimEnd('\', '/')
  186. $ownerXml = "$objectFull.xml"
  187. if (Test-Path $ownerXml) {
  188. $ownerHead = [System.IO.File]::ReadAllText($ownerXml, [System.Text.Encoding]::UTF8)
  189. $ownerHead = $ownerHead.Substring(0, [Math]::Min(2000, $ownerHead.Length))
  190. if ($ownerHead -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { $formatVersion = $Matches[1] }
  191. }
  192. if (-not $formatVersion) { $formatVersion = Detect-FormatVersion $objectFull }
  193. # Код языка идёт и в текст XML, и в имя файла страницы, поэтому проверяем его до записи:
  194. # пустое значение дало бы файл «.html» и пустой <Page></Page>, разделитель пути — запись мимо
  195. # каталога страниц, а зарезервированное имя устройства (nul, con, prn, aux, com1…, lpt1…) на
  196. # Windows уводит запись в само устройство. Все отказы платформы были бы тихими.
  197. #
  198. # Якоря `\A…\z`, а не `^…$`: последние в обоих языках допускают перевод строки в конце.
  199. #
  200. # Копия этой функции есть в template-add (навыки автономны, формат «дескриптор + страница»
  201. # у них общий). Держать копии одинаковыми — сознательно; за дрейфом следит check-inline-drift.
  202. function Test-LangCode([string]$code) {
  203. if ($code -notmatch '\A[A-Za-z0-9_-]+\z') { return $false }
  204. if ($code -match '\A(?i)(con|prn|aux|nul|com[1-9]|lpt[1-9])\z') { return $false }
  205. return $true
  206. }
  207. if (-not (Test-LangCode $Lang)) {
  208. Write-Error "Недопустимый код языка: '$Lang'`nОжидается код вида ru, en (буквы, цифры, дефис, подчёркивание; имена устройств Windows недопустимы)"
  209. exit 1
  210. }
  211. $helpXmlPath = Join-Path $extDir "Help.xml"
  212. if (Test-Path $helpXmlPath) {
  213. Write-Error "Справка уже существует: $helpXmlPath"
  214. exit 1
  215. }
  216. Assert-EditAllowed $objectDir 'editable'
  217. # --- Кодировка ---
  218. $encBom = New-Object System.Text.UTF8Encoding($true)
  219. # --- 1. Help.xml ---
  220. $helpXml = @"
  221. <?xml version="1.0" encoding="UTF-8"?>
  222. <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">
  223. <Page>$Lang</Page>
  224. </Help>
  225. "@
  226. # XML в каноне выгрузки Конфигуратора: CRLF в разделителях, без перевода в конце.
  227. #
  228. # Копия этой функции есть в каждом навыке-эмиттере (навыки автономны). Держать
  229. # копии одинаковыми — сознательно: разошедшиеся копии сводят на нет весь смысл.
  230. #
  231. # HTML-страница сюда НЕ идёт — платформа хранит её с LF.
  232. function Write-XmlFile([string]$path, [string]$text, $encoding) {
  233. $t = ($text -replace "`r`n", "`n") -replace "`n", "`r`n"
  234. [System.IO.File]::WriteAllText($path, $t.TrimEnd("`r", "`n"), $encoding)
  235. }
  236. Write-XmlFile $helpXmlPath $helpXml $encBom
  237. # --- 2. Help/<lang>.html ---
  238. $helpDir = Join-Path $extDir "Help"
  239. New-Item -ItemType Directory -Path $helpDir -Force | Out-Null
  240. $helpHtmlPath = Join-Path $helpDir "$Lang.html"
  241. $helpHtml = @"
  242. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  243. <html>
  244. <head>
  245. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
  246. <link rel="stylesheet" type="text/css" href="v8help://service_book/service_style"></link>
  247. </head>
  248. <body>
  249. <h1>$ObjectName</h1>
  250. <p>Описание.</p>
  251. </body>
  252. </html>
  253. "@
  254. # Файл страницы НЕ перезаписываем: отказ выше смотрит только на Help.xml, а страница может
  255. # пережить его (удалённый дескриптор, частичная выгрузка, справка, сделанная руками) — и тогда
  256. # безусловная запись молча стирала бы текст справки с кодом 0.
  257. if (Test-Path $helpHtmlPath) {
  258. Write-Host "[WARN] Страница $Lang.html уже лежала на диске — содержимое сохранено, создан только дескриптор."
  259. } else {
  260. [System.IO.File]::WriteAllText($helpHtmlPath, $helpHtml, $encBom)
  261. }
  262. # --- 3. Проверка IncludeHelpInContents в метаданных форм ---
  263. $formsDir = Join-Path $objectDir "Forms"
  264. if (Test-Path $formsDir) {
  265. $formMetaFiles = Get-ChildItem -Path $formsDir -Filter "*.xml" -File
  266. foreach ($formMeta in $formMetaFiles) {
  267. $xmlDoc = New-Object System.Xml.XmlDocument
  268. $xmlDoc.PreserveWhitespace = $true
  269. $xmlDoc.Load($formMeta.FullName)
  270. $nsMgr = New-Object System.Xml.XmlNamespaceManager($xmlDoc.NameTable)
  271. $nsMgr.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
  272. $includeHelp = $xmlDoc.SelectSingleNode("//md:IncludeHelpInContents", $nsMgr)
  273. if (-not $includeHelp) {
  274. # Добавить после <FormType>
  275. $formType = $xmlDoc.SelectSingleNode("//md:FormType", $nsMgr)
  276. if ($formType) {
  277. $newElem = $xmlDoc.CreateElement("IncludeHelpInContents", "http://v8.1c.ru/8.3/MDClasses")
  278. $newElem.InnerText = "false"
  279. $parent = $formType.ParentNode
  280. $nextSibling = $formType.NextSibling
  281. # Вставить перенос + табуляцию + элемент
  282. $ws = $xmlDoc.CreateWhitespace("`n`t`t`t")
  283. if ($nextSibling) {
  284. $parent.InsertBefore($ws, $nextSibling) | Out-Null
  285. $parent.InsertBefore($newElem, $ws) | Out-Null
  286. } else {
  287. $parent.AppendChild($ws) | Out-Null
  288. $parent.AppendChild($newElem) | Out-Null
  289. }
  290. $settings = New-Object System.Xml.XmlWriterSettings
  291. $settings.Encoding = $encBom
  292. $settings.Indent = $false
  293. $settings.NewLineHandling = [System.Xml.NewLineHandling]::None
  294. # Через MemoryStream, а не прямо в файл: нужен шаг пост-обработки строки.
  295. $memStream = New-Object System.IO.MemoryStream
  296. $writer = [System.Xml.XmlWriter]::Create($memStream, $settings)
  297. $xmlDoc.Save($writer)
  298. $writer.Flush(); $writer.Close()
  299. $xmlText = [System.Text.Encoding]::UTF8.GetString($memStream.ToArray())
  300. $memStream.Close()
  301. if ($xmlText.Length -gt 0 -and $xmlText[0] -eq [char]0xFEFF) { $xmlText = $xmlText.Substring(1) }
  302. $xmlText = $xmlText.Replace('encoding="utf-8"', 'encoding="UTF-8"')
  303. # Пустой элемент: XmlWriter отдаёт `<a />`, Конфигуратор пишет `<a/>`. Внутри
  304. # CDATA/комментария ` />` может быть содержимым (там `>` не экранируется),
  305. # поэтому они идут первыми ветками альтернации и возвращаются как есть.
  306. $xmlText = [regex]::Replace($xmlText, '(?s)<!\[CDATA\[.*?\]\]>|<!--.*?-->|(?<=\S) />', { param($m) if ($m.Value -eq ' />') { '/>' } else { $m.Value } })
  307. # Целевой перевод строки: стиль файла-назначения — правка наследует его (#44/#46/#47),
  308. # новый файл получает канон выгрузки CRLF. Зеркало _detect_xml_style в py-порту.
  309. $targetEol = if ((Test-Path -LiteralPath $formMeta.FullName) -and ([System.IO.File]::ReadAllText($formMeta.FullName) -notmatch "`r`n")) { "`n" } else { "`r`n" }
  310. $xmlText = ($xmlText -replace "`r`n", "`n") -replace "`n", $targetEol
  311. [System.IO.File]::WriteAllText($formMeta.FullName, $xmlText, $encBom)
  312. Write-Host " IncludeHelpInContents добавлен: $($formMeta.Name)"
  313. }
  314. }
  315. }
  316. }
  317. Write-Host "[OK] Создана справка: $ObjectName"
  318. Write-Host " Метаданные: $helpXmlPath"
  319. Write-Host " Страница: $helpHtmlPath"

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.