Compare commits
No commits in common. "master" and "v1.6" have entirely different histories.
@ -1,8 +1,6 @@
|
|||||||
# -*- mode: python ; coding: utf-8 -*-
|
# -*- mode: python ; coding: utf-8 -*-
|
||||||
|
|
||||||
import os
|
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
@ -12,15 +10,15 @@ spec_dir = Path(SPECPATH)
|
|||||||
|
|
||||||
def git_build_ref():
|
def git_build_ref():
|
||||||
try:
|
try:
|
||||||
dirty = subprocess.check_output(
|
dirty = subprocess.run(
|
||||||
['git', 'status', '--porcelain', '--untracked-files=normal'],
|
['git', 'diff-index', '--quiet', 'HEAD', '--'],
|
||||||
cwd=spec_dir,
|
cwd=spec_dir,
|
||||||
stderr=subprocess.DEVNULL,
|
stderr=subprocess.DEVNULL,
|
||||||
text=True,
|
stdout=subprocess.DEVNULL,
|
||||||
)
|
).returncode != 0
|
||||||
if dirty.strip():
|
if dirty:
|
||||||
return datetime.now().strftime('%H%M%S-%d%m%Y')
|
return datetime.now().strftime('%H%M%S-%d%m%Y')
|
||||||
except (OSError, subprocess.CalledProcessError):
|
except OSError:
|
||||||
return datetime.now().strftime('%H%M%S-%d%m%Y')
|
return datetime.now().strftime('%H%M%S-%d%m%Y')
|
||||||
try:
|
try:
|
||||||
tag = subprocess.check_output(
|
tag = subprocess.check_output(
|
||||||
@ -47,67 +45,26 @@ def git_build_ref():
|
|||||||
return 'untagged'
|
return 'untagged'
|
||||||
|
|
||||||
|
|
||||||
def _build_library_roots():
|
|
||||||
windows_root = Path(os.environ.get('SystemRoot', r'C:\Windows')).resolve()
|
|
||||||
return tuple(dict.fromkeys(
|
|
||||||
path.resolve() for path in (
|
|
||||||
Path(sys.executable).parent,
|
|
||||||
Path(sys.prefix),
|
|
||||||
Path(sys.base_prefix),
|
|
||||||
Path(sys.base_prefix) / 'DLLs',
|
|
||||||
windows_root / 'System32',
|
|
||||||
windows_root,
|
|
||||||
) if path.is_dir()
|
|
||||||
))
|
|
||||||
|
|
||||||
|
|
||||||
def _set_isolated_build_path(roots):
|
|
||||||
# Analysis searches PATH for DLLs. Unrelated tools may provide incompatible
|
|
||||||
# copies of the Windows runtime or ICU libraries there.
|
|
||||||
os.environ['PATH'] = os.pathsep.join(str(root) for root in roots)
|
|
||||||
|
|
||||||
|
|
||||||
def _check_binary_sources(binaries, roots):
|
|
||||||
foreign = [
|
|
||||||
(name, source)
|
|
||||||
for name, source, kind in binaries
|
|
||||||
if kind == 'BINARY'
|
|
||||||
and not any(Path(source).resolve().is_relative_to(root) for root in roots)
|
|
||||||
]
|
|
||||||
if foreign:
|
|
||||||
details = '\n'.join(f'{name}: {source}' for name, source in foreign[:10])
|
|
||||||
raise RuntimeError(f'Build contains DLLs outside Python and Windows:\n{details}')
|
|
||||||
|
|
||||||
|
|
||||||
app_name = f'LEDMapper-{git_build_ref()}'
|
app_name = f'LEDMapper-{git_build_ref()}'
|
||||||
library_roots = _build_library_roots()
|
|
||||||
_set_isolated_build_path(library_roots)
|
|
||||||
build_version_path = spec_dir.parent / 'build' / 'ledmapper-build-version.txt'
|
|
||||||
build_version_path.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
build_version_path.write_text(app_name.removeprefix('LEDMapper-'), encoding='utf-8')
|
|
||||||
|
|
||||||
|
|
||||||
a = Analysis(
|
a = Analysis(
|
||||||
[str(spec_dir / 'main.py')],
|
[str(spec_dir / 'main.py')],
|
||||||
pathex=[str(spec_dir), str(spec_dir.parent)],
|
pathex=[str(spec_dir), str(spec_dir.parent)],
|
||||||
binaries=[],
|
binaries=[],
|
||||||
datas=[(str(spec_dir / 'assets'), 'assets'), (str(build_version_path), '.')],
|
datas=[(str(spec_dir / 'assets'), 'assets')],
|
||||||
hiddenimports=[
|
hiddenimports=[
|
||||||
'canvas',
|
'canvas',
|
||||||
'background_image_loader',
|
|
||||||
'background_dialog',
|
'background_dialog',
|
||||||
'icons',
|
'icons',
|
||||||
'localization',
|
'localization',
|
||||||
'main_window',
|
'main_window',
|
||||||
'mapping_renderer',
|
|
||||||
'models',
|
'models',
|
||||||
'panel_mapping_generator',
|
'panel_mapping_generator',
|
||||||
'settings',
|
'settings',
|
||||||
'settings_dialog',
|
'settings_dialog',
|
||||||
'theme',
|
'theme',
|
||||||
'unfolding',
|
'unfolding',
|
||||||
'update_service',
|
|
||||||
'version',
|
|
||||||
],
|
],
|
||||||
hookspath=[],
|
hookspath=[],
|
||||||
hooksconfig={},
|
hooksconfig={},
|
||||||
@ -116,7 +73,6 @@ a = Analysis(
|
|||||||
noarchive=False,
|
noarchive=False,
|
||||||
optimize=0,
|
optimize=0,
|
||||||
)
|
)
|
||||||
_check_binary_sources(a.binaries, library_roots)
|
|
||||||
pyz = PYZ(a.pure)
|
pyz = PYZ(a.pure)
|
||||||
|
|
||||||
exe = EXE(
|
exe = EXE(
|
||||||
|
|||||||
53
README.md
53
README.md
@ -10,24 +10,19 @@ LED Mapper — настольное приложение на Python и PySide6
|
|||||||
- Отображение схемы в реальных координатах.
|
- Отображение схемы в реальных координатах.
|
||||||
- Выделение точек мышью и работа через таблицу выбранных LED.
|
- Выделение точек мышью и работа через таблицу выбранных LED.
|
||||||
- До 4 физических линий светодиодных лент.
|
- До 4 физических линий светодиодных лент.
|
||||||
- Нумерация линий и блоков с `0`.
|
|
||||||
- Блоки внутри линий, включая пустые блоки.
|
- Блоки внутри линий, включая пустые блоки.
|
||||||
- Индексация LED отдельно для каждой линии, начиная с `0`.
|
- Индексация LED отдельно для каждой линии, начиная с `0`.
|
||||||
- Индексация внутри каждого блока.
|
- Индексация внутри каждого блока.
|
||||||
- Добавление блоков вручную, из выделения, автоблоками и кистью.
|
- Добавление блоков вручную, из выделения, автоблоками и кистью.
|
||||||
- Продолжение существующего блока кистью от последней точки блока.
|
- Продолжение существующего блока кистью от последней точки блока.
|
||||||
- Предпросмотр зоны действия кисти и точек, которые будут добавлены.
|
- Предпросмотр зоны действия кисти и точек, которые будут добавлены.
|
||||||
- Сетка с настраиваемым шагом (по умолчанию 34 мм) во всех режимах редактирования и генерации.
|
- Сетка 34 мм.
|
||||||
- Настраиваемые абсолютные размеры LED-точек и текста их индексов: визуальный размер не меняется при приближении.
|
- Undo/redo для операций разметки.
|
||||||
- Свободные многострочные текстовые комментарии на схеме.
|
|
||||||
- Undo/redo для операций разметки и комментариев.
|
|
||||||
- Удаление назначений через `Del` и контекстные меню.
|
- Удаление назначений через `Del` и контекстные меню.
|
||||||
- Пакетное удаление выбранных блоков через дерево одной операцией с единым Undo.
|
|
||||||
- Сворачивание боковой панели.
|
- Сворачивание боковой панели.
|
||||||
- Сортировка таблицы выбранных точек по столбцам.
|
- Сортировка таблицы выбранных точек по столбцам.
|
||||||
- Генерация `vm_map.h`, `ordered_circles.json`, `validation_report.txt` и README для результата.
|
- Генерация `vm_map.h`, `virtual_matrix_legacy.ino.txt`, `ordered_circles.json`, `validation_report.txt` и README для результата.
|
||||||
- Сборка самостоятельного Windows EXE через PyInstaller.
|
- Сборка самостоятельного Windows EXE через PyInstaller.
|
||||||
- Проверка и установка Windows-обновлений из релизов Gitea.
|
|
||||||
|
|
||||||
## Структура приложения
|
## Структура приложения
|
||||||
|
|
||||||
@ -37,8 +32,6 @@ main_window.py Главное окно, меню, действия,
|
|||||||
canvas.py Холст схемы, выделение, кисть, сетка и связи
|
canvas.py Холст схемы, выделение, кисть, сетка и связи
|
||||||
models.py Модель карты, линий, блоков и алгоритмы маршрутов
|
models.py Модель карты, линий, блоков и алгоритмы маршрутов
|
||||||
panel_mapping_generator.py Генерация файлов маппинга
|
panel_mapping_generator.py Генерация файлов маппинга
|
||||||
update_service.py Проверка релизов и безопасная установка Windows EXE
|
|
||||||
version.py Базовая версия приложения при запуске из исходников
|
|
||||||
icons.py Встроенные lucide-иконки
|
icons.py Встроенные lucide-иконки
|
||||||
unfolding.py Описание развертки линий и блоков
|
unfolding.py Описание развертки линий и блоков
|
||||||
qa_smoke.py Smoke-тесты приложения
|
qa_smoke.py Smoke-тесты приложения
|
||||||
@ -90,28 +83,8 @@ python -m venv .venv
|
|||||||
6. Проверьте счетчики в верхней части боковой панели: количество линий, блоков и назначенных LED.
|
6. Проверьте счетчики в верхней части боковой панели: количество линий, блоков и назначенных LED.
|
||||||
7. Сгенерируйте скрипт через `Файл -> Сгенерировать скрипт`.
|
7. Сгенерируйте скрипт через `Файл -> Сгенерировать скрипт`.
|
||||||
|
|
||||||
Шаг сетки, диаметр точек и размер текста индексов меняются в `Файл -> Параметры -> Внешний вид`. Для каждого значения рядом есть кнопка `Сбросить`. Размер текста индексов обновляется на схеме сразу во время настройки; при отмене возвращается прежнее значение. Шаг сетки сохраняется в JSON текущей схемы, а диаметр точек и размер текста индексов — в пользовательских параметрах приложения. Визуальные размеры точек и подписей не меняются при приближении схемы. Изменение шага не перемещает уже существующие LED автоматически.
|
|
||||||
|
|
||||||
Чтобы удалить несколько блоков, выделите их в дереве с `Ctrl` или `Shift`, затем нажмите `Ctrl+Del` или выберите удаление в контекстном меню. Приложение показывает одно подтверждение и создаёт одну операцию Undo.
|
|
||||||
|
|
||||||
В режиме редактирования выбранные светодиоды можно скопировать через `Ctrl+C` и вставить через `Ctrl+V`. Вставленные LED остаются свободными, сохраняют взаимное расположение и пользовательские поля исходных точек. Первая копия смещается на один шаг сетки вправо и вниз, а следующие вставки образуют каскад. Вся группа вставляется одной операцией Undo и сразу становится текущим выделением.
|
|
||||||
|
|
||||||
В собранном Windows EXE приложение проверяет наличие нового стабильного релиза после запуска. В меню `Справка` можно запустить проверку вручную и, если новая версия найдена, выбрать `Установить обновление`. Загружается только артефакт вида `LEDMapper-vX.Y.Z.exe` из репозитория `Robotail/LED-mapper` на `git.robotail.pro`. После проверки размера и формата EXE приложение предлагает сохранить изменённую схему, закрывается, а отдельный процесс заменяет EXE по прежнему пути и запускает новую версию — существующие ярлыки продолжают работать. Версия релизной сборки хранится внутри EXE, поэтому переименование файла не вызывает повторную установку того же обновления. При неудачном запуске старая версия восстанавливается; причина записывается рядом с EXE в `update-error.log`. Для обновления нужны доступ к серверу релизов и право записи в каталог приложения. Из исходников можно проверить наличие версии, но автоустановка недоступна.
|
|
||||||
|
|
||||||
Перед загрузкой проверяются права записи в каталог приложения. Перенаправления на страницу входа, другой сайт или неожиданный путь того же сервера отклоняются; объявленный сервером размер файла должен совпадать с размером артефакта в данных релиза.
|
|
||||||
|
|
||||||
Если не назначен ни один светодиод, генерация не запускается. Если назначены не все светодиоды, приложение показывает предупреждение и предлагает либо сгенерировать неполный маппинг, либо продолжить редактирование.
|
Если не назначен ни один светодиод, генерация не запускается. Если назначены не все светодиоды, приложение показывает предупреждение и предлагает либо сгенерировать неполный маппинг, либо продолжить редактирование.
|
||||||
|
|
||||||
## Текстовые комментарии на схеме
|
|
||||||
|
|
||||||
Чтобы разместить заметку, нажмите правой кнопкой мыши в нужном месте схемы и выберите `Добавить комментарий…`. Команда `Инструменты -> Добавить комментарий…` создаёт заметку в центре видимой области. Введите многострочный текст и подтвердите ввод.
|
|
||||||
|
|
||||||
Комментарий можно свободно перетаскивать левой кнопкой мыши в любом режиме. Двойной щелчок открывает редактирование текста; в контекстном меню комментария доступны изменение и удаление. Размер текста остаётся читаемым при изменении масштаба. Команда `Показать всё` учитывает комментарии, в том числе за пределами LED-схемы.
|
|
||||||
|
|
||||||
Добавление, изменение, перемещение и удаление поддерживают Undo/Redo. Отмена диалога и пустой текст не изменяют схему. Комментарии сохраняются в JSON в списке `comments`: `id`, `text`, `x`, `y`; координаты используют единицы схемы. Старые JSON без этого списка открываются без комментариев. Можно сохранить схему, содержащую только комментарии.
|
|
||||||
|
|
||||||
Комментарии не привязаны к линиям, блокам или LED и не влияют на физические адреса в `VM_MAPPINGS`. Экспорт изображения маппинга через меню `Файл` по-прежнему показывает LED и легенду; текстовые комментарии сохраняются в JSON и отображаются в редакторе.
|
|
||||||
|
|
||||||
## Горячие клавиши
|
## Горячие клавиши
|
||||||
|
|
||||||
| Действие | Клавиши |
|
| Действие | Клавиши |
|
||||||
@ -122,14 +95,11 @@ python -m venv .venv
|
|||||||
| Сгенерировать скрипт | `Ctrl+G` |
|
| Сгенерировать скрипт | `Ctrl+G` |
|
||||||
| Отменить | `Ctrl+Z` |
|
| Отменить | `Ctrl+Z` |
|
||||||
| Повторить | `Ctrl+Y` |
|
| Повторить | `Ctrl+Y` |
|
||||||
| Копировать выбранные LED | `Ctrl+C` |
|
|
||||||
| Вставить скопированные LED | `Ctrl+V` |
|
|
||||||
| Удалить фиксацию | `Del` |
|
| Удалить фиксацию | `Del` |
|
||||||
| Удалить выбранные точки или блоки | `Ctrl+Del` |
|
|
||||||
| Удалить все | `Ctrl+Shift+Del` |
|
| Удалить все | `Ctrl+Shift+Del` |
|
||||||
| Очистить выбор | `Esc` |
|
| Очистить выбор | `Esc` |
|
||||||
| Показать всю схему | `Ctrl+0` |
|
| Показать всю схему | `Ctrl+0` |
|
||||||
| Сетка | `G` |
|
| Сетка 34 мм | `G` |
|
||||||
| Стрелки направления | `Ctrl+Shift+A` |
|
| Стрелки направления | `Ctrl+Shift+A` |
|
||||||
| Скрыть/показать боковую панель | `F9` |
|
| Скрыть/показать боковую панель | `F9` |
|
||||||
| Новая линия | `Ctrl+L` |
|
| Новая линия | `Ctrl+L` |
|
||||||
@ -141,19 +111,14 @@ python -m venv .venv
|
|||||||
Генератор создает:
|
Генератор создает:
|
||||||
|
|
||||||
- `vm_map.h` — основной header для прошивки.
|
- `vm_map.h` — основной header для прошивки.
|
||||||
|
- `virtual_matrix_legacy.ino.txt` — читаемая legacy-версия с `setLEDs(...)`.
|
||||||
- `ordered_circles.json` — нормализованные точки и координаты виртуальной матрицы.
|
- `ordered_circles.json` — нормализованные точки и координаты виртуальной матрицы.
|
||||||
- `validation_report.txt` — отчет о проверках маршрутов и ячеек.
|
- `validation_report.txt` — отчет о проверках маршрутов и ячеек.
|
||||||
- `README.md` — краткое описание результата генерации.
|
- `README.md` — краткое описание результата генерации.
|
||||||
|
|
||||||
Устаревший `virtual_matrix_legacy.ino.txt` больше не создаётся. Если файл с этим точным именем остался в выходной папке от прежней версии, следующая успешная генерация удалит его. Другие `.ino`-файлы не затрагиваются.
|
|
||||||
|
|
||||||
JSON схемы хранит `coordinate_unit`, `grid_step_mm` и `index_base: 0`. При первом открытии старого файла без единицы координат приложение определяет её один раз и затем сохраняет явно. Старые схемы с 1-based ID линий и блоков при загрузке переводятся на 0-based; сохранение записывает маркер `index_base: 0`, чтобы повторная загрузка не сдвигала ID. Сохранение выполняется через временный файл и атомарную замену, поэтому исходный JSON не повреждается при ошибке записи.
|
|
||||||
|
|
||||||
Если у схемы есть подложка, при сохранении исходное изображение встраивается в секцию `background.embedded_image` внутри JSON вместе с именем, MIME-типом и контрольной суммой. Диалог выбора показывает все форматы, которые доступны в поставляемой версии Qt (включая PNG, JPEG/JFIF, BMP, GIF, WebP, TIFF и SVG), распознаёт содержимое независимо от регистра и расширения файла и учитывает EXIF-ориентацию. Большие изображения безопасно уменьшаются для отображения. Если изображение повреждено или его декодер недоступен, приложение показывает причину и сохраняет прежнюю подложку. После сохранения схема не зависит от внешнего файла, а размеры и параметры подложки сохраняются при редактировании и переносе JSON. Для уже встроенного и не заменённого изображения диалог `Подложка` показывает в поле пути значение `Встроенная`. Чтобы заменить его, нажмите `Выбрать` и укажите новый файл; новое изображение будет встроено при следующем сохранении схемы.
|
|
||||||
|
|
||||||
В `vm_map.h` используются физические адреса из GUI:
|
В `vm_map.h` используются физические адреса из GUI:
|
||||||
|
|
||||||
- `strip = line_id`
|
- `strip = line_id - 1`
|
||||||
- `led_id = line_index`
|
- `led_id = line_index`
|
||||||
|
|
||||||
Неназначенные точки не попадают в рабочий `VM_MAPPINGS`, но исходные точки могут оставаться в служебных метаданных.
|
Неназначенные точки не попадают в рабочий `VM_MAPPINGS`, но исходные точки могут оставаться в служебных метаданных.
|
||||||
@ -197,12 +162,10 @@ JSON схемы хранит `coordinate_unit`, `grid_step_mm` и `index_base: 0
|
|||||||
.\.venv\Scripts\python.exe -m PyInstaller --noconfirm --clean app\LEDMapper.spec
|
.\.venv\Scripts\python.exe -m PyInstaller --noconfirm --clean app\LEDMapper.spec
|
||||||
```
|
```
|
||||||
|
|
||||||
Сборочный `spec` ограничивает поиск DLL каталогами Python, виртуального окружения и Windows. Это защищает EXE от несовместимых системных библиотек сторонних программ, добавленных в `PATH`. После сборки проверяйте готовый файл командой `dist\LEDMapper-vX.Y.Z.exe --verify-bundle`: успешная проверка завершается с кодом `0` без открытия окна приложения.
|
Готовый файл появится здесь:
|
||||||
|
|
||||||
В чистой сборке из релизного тега файл будет называться:
|
|
||||||
|
|
||||||
```text
|
```text
|
||||||
dist/LEDMapper-vX.Y.Z.exe
|
dist/LEDMapper.exe
|
||||||
```
|
```
|
||||||
|
|
||||||
`build/` и `dist/` не коммитятся, потому что это воспроизводимые артефакты сборки.
|
`build/` и `dist/` не коммитятся, потому что это воспроизводимые артефакты сборки.
|
||||||
|
|||||||
@ -1,3 +1 @@
|
|||||||
"""LED Mapper Editor application package."""
|
"""LED Mapper Editor application package."""
|
||||||
|
|
||||||
from .version import __version__
|
|
||||||
|
|||||||
@ -16,31 +16,21 @@ from PySide6.QtWidgets import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from .background_image_loader import supported_image_filter
|
|
||||||
from .localization import localize_dialog_buttons
|
from .localization import localize_dialog_buttons
|
||||||
from .models import BackgroundImage
|
from .models import BackgroundImage
|
||||||
except ImportError:
|
except ImportError:
|
||||||
from background_image_loader import supported_image_filter
|
|
||||||
from localization import localize_dialog_buttons
|
from localization import localize_dialog_buttons
|
||||||
from models import BackgroundImage
|
from models import BackgroundImage
|
||||||
|
|
||||||
|
|
||||||
class BackgroundDialog(QDialog):
|
class BackgroundDialog(QDialog):
|
||||||
EMBEDDED_PATH_LABEL = "Встроенная"
|
|
||||||
|
|
||||||
def __init__(self, background: BackgroundImage, parent=None) -> None: # noqa: ANN001
|
def __init__(self, background: BackgroundImage, parent=None) -> None: # noqa: ANN001
|
||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
self.setWindowTitle("Подложка")
|
self.setWindowTitle("Подложка")
|
||||||
self.setMinimumWidth(460)
|
self.setMinimumWidth(460)
|
||||||
|
|
||||||
self._source_background = background
|
self.path = QLineEdit(background.path)
|
||||||
self._keep_embedded_image = background.has_embedded_image()
|
self.path.setPlaceholderText("PNG или JPEG")
|
||||||
self.path = QLineEdit(self.EMBEDDED_PATH_LABEL if self._keep_embedded_image else background.path)
|
|
||||||
self.path.setPlaceholderText("Файл изображения")
|
|
||||||
self.path.setReadOnly(self._keep_embedded_image)
|
|
||||||
if self._keep_embedded_image:
|
|
||||||
source_name = background.embedded_image_name or "изображение"
|
|
||||||
self.path.setToolTip(f"{source_name} встроено в JSON схемы")
|
|
||||||
browse = QPushButton("Выбрать")
|
browse = QPushButton("Выбрать")
|
||||||
browse.clicked.connect(self._browse)
|
browse.clicked.connect(self._browse)
|
||||||
path_row = QWidget()
|
path_row = QWidget()
|
||||||
@ -79,19 +69,14 @@ class BackgroundDialog(QDialog):
|
|||||||
form.addRow(buttons)
|
form.addRow(buttons)
|
||||||
|
|
||||||
def background(self) -> BackgroundImage:
|
def background(self) -> BackgroundImage:
|
||||||
embedded = self._source_background if self._keep_embedded_image else BackgroundImage()
|
|
||||||
return BackgroundImage(
|
return BackgroundImage(
|
||||||
path="" if self._keep_embedded_image else self.path.text().strip(),
|
path=self.path.text().strip(),
|
||||||
offset_x=self.offset_x.value(),
|
offset_x=self.offset_x.value(),
|
||||||
offset_y=self.offset_y.value(),
|
offset_y=self.offset_y.value(),
|
||||||
scale_x_percent=self.scale_x.value(),
|
scale_x_percent=self.scale_x.value(),
|
||||||
scale_y_percent=self.scale_y.value(),
|
scale_y_percent=self.scale_y.value(),
|
||||||
opacity_percent=self.opacity.value(),
|
opacity_percent=self.opacity.value(),
|
||||||
visible=self.visible.isChecked(),
|
visible=self.visible.isChecked(),
|
||||||
embedded_image_base64=embedded.embedded_image_base64,
|
|
||||||
embedded_image_mime_type=embedded.embedded_image_mime_type,
|
|
||||||
embedded_image_name=embedded.embedded_image_name,
|
|
||||||
embedded_image_sha256=embedded.embedded_image_sha256,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def _reset_scale(self) -> None:
|
def _reset_scale(self) -> None:
|
||||||
@ -99,22 +84,16 @@ class BackgroundDialog(QDialog):
|
|||||||
self.scale_y.setValue(100.0)
|
self.scale_y.setValue(100.0)
|
||||||
|
|
||||||
def _browse(self) -> None:
|
def _browse(self) -> None:
|
||||||
start = "" if self._keep_embedded_image else self.path.text().strip()
|
start = self.path.text().strip()
|
||||||
start_path = Path(start).parent if start else Path.home()
|
start_path = Path(start).parent if start else Path.home()
|
||||||
selected, _ = QFileDialog.getOpenFileName(
|
selected, _ = QFileDialog.getOpenFileName(
|
||||||
self,
|
self,
|
||||||
"Выбрать подложку",
|
"Выбрать подложку",
|
||||||
str(start_path),
|
str(start_path),
|
||||||
supported_image_filter(),
|
"Изображения (*.png *.jpg *.jpeg);;Все файлы (*.*)",
|
||||||
)
|
)
|
||||||
if selected:
|
if selected:
|
||||||
self._set_external_path(selected)
|
self.path.setText(selected)
|
||||||
|
|
||||||
def _set_external_path(self, path: str) -> None:
|
|
||||||
self._keep_embedded_image = False
|
|
||||||
self.path.setReadOnly(False)
|
|
||||||
self.path.setToolTip("")
|
|
||||||
self.path.setText(path)
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _spin(minimum: float, maximum: float, value: float, suffix: str) -> QDoubleSpinBox:
|
def _spin(minimum: float, maximum: float, value: float, suffix: str) -> QDoubleSpinBox:
|
||||||
|
|||||||
@ -1,147 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from dataclasses import dataclass
|
|
||||||
import math
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from PySide6.QtCore import QByteArray, QBuffer, QIODevice, QSize, Qt
|
|
||||||
from PySide6.QtGui import QImage, QImageIOHandler, QImageReader
|
|
||||||
|
|
||||||
try:
|
|
||||||
from .models import BackgroundImage
|
|
||||||
except ImportError:
|
|
||||||
from models import BackgroundImage
|
|
||||||
|
|
||||||
|
|
||||||
MAX_BACKGROUND_IMAGE_SIDE = 8192
|
|
||||||
MAX_BACKGROUND_IMAGE_PIXELS = 32_000_000
|
|
||||||
MAX_UNSCALED_SOURCE_PIXELS = 100_000_000
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class BackgroundImageLoadResult:
|
|
||||||
image: QImage
|
|
||||||
error: str = ""
|
|
||||||
|
|
||||||
@property
|
|
||||||
def loaded(self) -> bool:
|
|
||||||
return not self.image.isNull()
|
|
||||||
|
|
||||||
|
|
||||||
def supported_image_filter() -> str:
|
|
||||||
formats = sorted(
|
|
||||||
{
|
|
||||||
bytes(image_format).decode("ascii", errors="ignore").lower()
|
|
||||||
for image_format in QImageReader.supportedImageFormats()
|
|
||||||
if image_format
|
|
||||||
}
|
|
||||||
)
|
|
||||||
wildcards: list[str] = []
|
|
||||||
for image_format in formats:
|
|
||||||
if not image_format or image_format == "pdf":
|
|
||||||
continue
|
|
||||||
wildcards.extend((f"*.{image_format}", f"*.{image_format.upper()}"))
|
|
||||||
patterns = " ".join(dict.fromkeys(wildcards))
|
|
||||||
return f"Изображения ({patterns});;Все файлы (*.*)"
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_background_path(background: BackgroundImage, document_path: Path | None = None) -> Path:
|
|
||||||
path = Path(background.path)
|
|
||||||
if not path.is_absolute() and document_path is not None:
|
|
||||||
path = document_path.parent / path
|
|
||||||
return path
|
|
||||||
|
|
||||||
|
|
||||||
def background_cache_key(background: BackgroundImage, document_path: Path | None = None) -> tuple[object, ...]:
|
|
||||||
if background.has_embedded_image():
|
|
||||||
image_bytes = background.embedded_image_bytes()
|
|
||||||
return ("embedded", background.embedded_image_sha256 or hash(image_bytes), len(image_bytes))
|
|
||||||
path = resolve_background_path(background, document_path)
|
|
||||||
try:
|
|
||||||
stat = path.stat()
|
|
||||||
except OSError:
|
|
||||||
return ("file", str(path), None, None)
|
|
||||||
return ("file", str(path), stat.st_mtime_ns, stat.st_size)
|
|
||||||
|
|
||||||
|
|
||||||
def _bounded_image_size(size: QSize, max_side: int) -> QSize:
|
|
||||||
if not size.isValid() or max_side <= 0:
|
|
||||||
return size
|
|
||||||
side_factor = min(1.0, max_side / max(size.width(), size.height()))
|
|
||||||
pixel_factor = min(1.0, math.sqrt(MAX_BACKGROUND_IMAGE_PIXELS / (size.width() * size.height())))
|
|
||||||
factor = min(side_factor, pixel_factor)
|
|
||||||
if factor >= 1.0:
|
|
||||||
return size
|
|
||||||
return QSize(max(1, math.floor(size.width() * factor)), max(1, math.floor(size.height() * factor)))
|
|
||||||
|
|
||||||
|
|
||||||
def load_background_image(
|
|
||||||
background: BackgroundImage,
|
|
||||||
document_path: Path | None = None,
|
|
||||||
*,
|
|
||||||
max_side: int = MAX_BACKGROUND_IMAGE_SIDE,
|
|
||||||
) -> BackgroundImageLoadResult:
|
|
||||||
buffer: QBuffer | None = None
|
|
||||||
if background.has_embedded_image():
|
|
||||||
image_bytes = background.embedded_image_bytes()
|
|
||||||
if not image_bytes:
|
|
||||||
return BackgroundImageLoadResult(QImage(), "Встроенные данные изображения повреждены или пусты.")
|
|
||||||
buffer = QBuffer()
|
|
||||||
buffer.setData(QByteArray(image_bytes))
|
|
||||||
if not buffer.open(QIODevice.OpenModeFlag.ReadOnly):
|
|
||||||
return BackgroundImageLoadResult(QImage(), "Не удалось открыть встроенные данные изображения.")
|
|
||||||
reader = QImageReader(buffer)
|
|
||||||
source_name = background.embedded_image_name or "встроенное изображение"
|
|
||||||
else:
|
|
||||||
path = resolve_background_path(background, document_path)
|
|
||||||
if not path.is_file():
|
|
||||||
return BackgroundImageLoadResult(QImage(), f"Файл не найден: {path}")
|
|
||||||
reader = QImageReader(str(path))
|
|
||||||
source_name = path.name
|
|
||||||
|
|
||||||
previous_allocation_limit: int | None = None
|
|
||||||
try:
|
|
||||||
reader.setAutoTransform(True)
|
|
||||||
reader.setDecideFormatFromContent(True)
|
|
||||||
size = reader.size()
|
|
||||||
bounded_size = _bounded_image_size(size, max_side)
|
|
||||||
if bounded_size != size:
|
|
||||||
if not reader.supportsOption(QImageIOHandler.ImageOption.ScaledSize):
|
|
||||||
source_pixels = size.width() * size.height()
|
|
||||||
if source_pixels > MAX_UNSCALED_SOURCE_PIXELS:
|
|
||||||
return BackgroundImageLoadResult(
|
|
||||||
QImage(),
|
|
||||||
f"Изображение «{source_name}» слишком большое для безопасного декодирования "
|
|
||||||
f"({size.width()}×{size.height()} пикселей).",
|
|
||||||
)
|
|
||||||
current_allocation_limit = QImageReader.allocationLimit()
|
|
||||||
required_megabytes = math.ceil(source_pixels * 8 / (1024 * 1024)) + 16
|
|
||||||
if current_allocation_limit > 0 and required_megabytes > current_allocation_limit:
|
|
||||||
previous_allocation_limit = current_allocation_limit
|
|
||||||
QImageReader.setAllocationLimit(required_megabytes)
|
|
||||||
reader.setScaledSize(bounded_size)
|
|
||||||
image = reader.read()
|
|
||||||
if image.isNull():
|
|
||||||
details = reader.errorString().strip()
|
|
||||||
message = f"Не удалось декодировать «{source_name}»"
|
|
||||||
if details:
|
|
||||||
message += f": {details}"
|
|
||||||
return BackgroundImageLoadResult(QImage(), message + ".")
|
|
||||||
|
|
||||||
bounded_size = _bounded_image_size(image.size(), max_side)
|
|
||||||
if bounded_size != image.size():
|
|
||||||
image = image.scaled(
|
|
||||||
bounded_size,
|
|
||||||
Qt.AspectRatioMode.KeepAspectRatio,
|
|
||||||
Qt.TransformationMode.SmoothTransformation,
|
|
||||||
)
|
|
||||||
if image.format() not in (QImage.Format.Format_ARGB32, QImage.Format.Format_ARGB32_Premultiplied):
|
|
||||||
image = image.convertToFormat(QImage.Format.Format_ARGB32_Premultiplied)
|
|
||||||
if image.isNull():
|
|
||||||
return BackgroundImageLoadResult(QImage(), f"Не удалось преобразовать «{source_name}» для отображения.")
|
|
||||||
return BackgroundImageLoadResult(image)
|
|
||||||
finally:
|
|
||||||
if previous_allocation_limit is not None:
|
|
||||||
QImageReader.setAllocationLimit(previous_allocation_limit)
|
|
||||||
if buffer is not None:
|
|
||||||
buffer.close()
|
|
||||||
@ -1,13 +0,0 @@
|
|||||||
# Свободные текстовые комментарии — план
|
|
||||||
|
|
||||||
Цель: свободные многострочные заметки на схеме, согласованные пользователем 05.11.2026.
|
|
||||||
|
|
||||||
Архитектура: отдельная коллекция `comments` документа с устойчивым ID, текстом и координатами в единицах документа. Холст отвечает за отображение и жесты, главное окно — за диалог и историю. Существующие файлы без comments загружаются с пустой коллекцией; неизвестные поля сохраняются. Физический маппинг не изменяется.
|
|
||||||
|
|
||||||
Варианты: привязка к LED/линиям отклонена пользователем; выбрано свободное расположение. Техническое решение: встроить объекты в существующий QGraphicsView и deepcopy-историю без новых зависимостей.
|
|
||||||
|
|
||||||
- [x] Модель: тест round-trip Unicode, отрицательных/дробных координат, неизвестных полей и старого JSON; добавить TextComment и CRUD.
|
|
||||||
- [x] Интерфейс: контекстное меню добавления/изменения/удаления, двойной щелчок, перетаскивание. Проверить Undo/Redo, отмену/пустой текст, пустую схему, масштаб и единицы m/mm.
|
|
||||||
- [x] Документация и проверка: README, полный smoke-набор, py_compile, интерактивные события Qt и рендер холста. Сохранить фактические результаты в AgentMemory.
|
|
||||||
|
|
||||||
Ограничения: использовать .venv; сохранить существующие пользовательские изменения; не создавать коммиты и релизы. Обнаружена грязная рабочая копия с HEAD 3699586 — это отличается от исторической записи памяти о релизе v3.4.0; version.py содержит 3.4.0. Работа ведётся поверх текущих файлов без отката.
|
|
||||||
11
icons.py
11
icons.py
@ -10,8 +10,6 @@ LUCIDE_PATHS = {
|
|||||||
"arrow-right": '<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>',
|
"arrow-right": '<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>',
|
||||||
"brush": '<path d="m9.06 11.9 8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08"/><path d="M7.07 14.94c-1.66 0-3 1.35-3 3.01 0 1.1-.89 2-2 2 1.4 1.4 3.67 1.4 5.07 0l2.94-2.94a2.93 2.93 0 0 0-4.14-4.14z"/>',
|
"brush": '<path d="m9.06 11.9 8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08"/><path d="M7.07 14.94c-1.66 0-3 1.35-3 3.01 0 1.1-.89 2-2 2 1.4 1.4 3.67 1.4 5.07 0l2.94-2.94a2.93 2.93 0 0 0-4.14-4.14z"/>',
|
||||||
"chevron-right": '<path d="m9 18 6-6-6-6"/>',
|
"chevron-right": '<path d="m9 18 6-6-6-6"/>',
|
||||||
"clipboard-paste": '<rect width="8" height="4" x="8" y="2" rx="1"/><path d="M16 4h2a2 2 0 0 1 2 2v5M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6"/><path d="m16 19 3-3-3-3"/><path d="M19 16h-7"/>',
|
|
||||||
"copy": '<rect width="14" height="14" x="8" y="8" rx="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
|
|
||||||
"eraser": '<path d="m7 21-4.3-4.3c-.9-.9-.9-2.4 0-3.3L14 2l8 8-11 11Z"/><path d="M22 21H7"/><path d="m5 11 8 8"/>',
|
"eraser": '<path d="m7 21-4.3-4.3c-.9-.9-.9-2.4 0-3.3L14 2l8 8-11 11Z"/><path d="M22 21H7"/><path d="m5 11 8 8"/>',
|
||||||
"eye": '<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>',
|
"eye": '<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>',
|
||||||
"file-plus": '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z"/><path d="M14 2v6h6"/><path d="M12 18v-6"/><path d="M9 15h6"/>',
|
"file-plus": '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z"/><path d="M14 2v6h6"/><path d="M12 18v-6"/><path d="M9 15h6"/>',
|
||||||
@ -25,21 +23,12 @@ LUCIDE_PATHS = {
|
|||||||
"paintbrush": '<path d="m14.62 17.9-1.48 1.48a2.12 2.12 0 1 1-3-3l1.48-1.48"/><path d="m16.1 16.42 5.15-5.15a4.95 4.95 0 0 0-7-7L9.1 9.42"/><path d="m7.5 11 5.5 5.5"/><path d="m9 9-6 6v4h4l6-6"/>',
|
"paintbrush": '<path d="m14.62 17.9-1.48 1.48a2.12 2.12 0 1 1-3-3l1.48-1.48"/><path d="m16.1 16.42 5.15-5.15a4.95 4.95 0 0 0-7-7L9.1 9.42"/><path d="m7.5 11 5.5 5.5"/><path d="m9 9-6 6v4h4l6-6"/>',
|
||||||
"plus": '<path d="M5 12h14"/><path d="M12 5v14"/>',
|
"plus": '<path d="M5 12h14"/><path d="M12 5v14"/>',
|
||||||
"redo-2": '<path d="m15 14 5-5-5-5"/><path d="M20 9H9.5A5.5 5.5 0 0 0 4 14.5 5.5 5.5 0 0 0 9.5 20H13"/>',
|
"redo-2": '<path d="m15 14 5-5-5-5"/><path d="M20 9H9.5A5.5 5.5 0 0 0 4 14.5 5.5 5.5 0 0 0 9.5 20H13"/>',
|
||||||
"rotate-ccw": '<path d="M3 12a9 9 0 1 0 2.64-6.36L3 8"/><path d="M3 3v5h5"/>',
|
|
||||||
"rotate-cw": '<path d="M21 12a9 9 0 1 1-2.64-6.36L21 8"/><path d="M21 3v5h-5"/>',
|
"rotate-cw": '<path d="M21 12a9 9 0 1 1-2.64-6.36L21 8"/><path d="M21 3v5h-5"/>',
|
||||||
"save": '<path d="M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"/><path d="M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"/><path d="M7 3v4a1 1 0 0 0 1 1h7"/>',
|
"save": '<path d="M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"/><path d="M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"/><path d="M7 3v4a1 1 0 0 0 1 1h7"/>',
|
||||||
"save-all": '<path d="M10 2v3a1 1 0 0 0 1 1h5"/><path d="M18 18v-6a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1v6"/><path d="M18 22H6a2 2 0 0 1-2-2V6"/><path d="M8 2h8l4 4v12a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2"/>',
|
"save-all": '<path d="M10 2v3a1 1 0 0 0 1 1h5"/><path d="M18 18v-6a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1v6"/><path d="M18 22H6a2 2 0 0 1-2-2V6"/><path d="M8 2h8l4 4v12a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2"/>',
|
||||||
"settings": '<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.09a2 2 0 0 1-1-1.74v-.51a2 2 0 0 1 1-1.72l.15-.1a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>',
|
"settings": '<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.09a2 2 0 0 1-1-1.74v-.51a2 2 0 0 1 1-1.72l.15-.1a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>',
|
||||||
"trash-2": '<path d="M3 6h18"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/>',
|
"trash-2": '<path d="M3 6h18"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/>',
|
||||||
"undo-2": '<path d="M9 14 4 9l5-5"/><path d="M4 9h10.5A5.5 5.5 0 0 1 20 14.5 5.5 5.5 0 0 1 14.5 20H11"/>',
|
"undo-2": '<path d="M9 14 4 9l5-5"/><path d="M4 9h10.5A5.5 5.5 0 0 1 20 14.5 5.5 5.5 0 0 1 14.5 20H11"/>',
|
||||||
"pencil": '<path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/>',
|
|
||||||
"mouse-pointer": '<path d="m3 3 7.07 16.97 2.51-7.39 7.39-2.51L3 3z"/><path d="m13 13 6 6"/>',
|
|
||||||
"move": '<path d="m5 9-3 3 3 3M9 5l3-3 3 3M15 19l-3 3-3-3M19 9l3 3-3 3M2 12h20M12 2v20"/>',
|
|
||||||
"plus-circle": '<circle cx="12" cy="12" r="10"/><path d="M8 12h8M12 8v8"/>',
|
|
||||||
"align-horizontal": '<line x1="2" x2="22" y1="12" y2="12"/><rect width="4" height="6" x="5" y="9" rx="1"/><rect width="4" height="6" x="15" y="9" rx="1"/>',
|
|
||||||
"align-vertical": '<line x1="12" x2="12" y1="2" y2="22"/><rect width="6" height="4" x="9" y="5" rx="1"/><rect width="6" height="4" x="9" y="15" rx="1"/>',
|
|
||||||
"grid-horizontal": '<rect width="18" height="18" x="3" y="3" rx="2"/><path d="M9 3v18M15 3v18"/>',
|
|
||||||
"grid-vertical": '<rect width="18" height="18" x="3" y="3" rx="2"/><path d="M3 9h18M3 15h18"/>',
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
7
main.py
7
main.py
@ -3,7 +3,6 @@ from __future__ import annotations
|
|||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from PySide6.QtCore import QTimer
|
|
||||||
from PySide6.QtWidgets import QApplication
|
from PySide6.QtWidgets import QApplication
|
||||||
|
|
||||||
APP_DIR = Path(__file__).resolve().parent
|
APP_DIR = Path(__file__).resolve().parent
|
||||||
@ -15,20 +14,15 @@ try:
|
|||||||
from .main_window import MainWindow
|
from .main_window import MainWindow
|
||||||
from .settings import AppSettings
|
from .settings import AppSettings
|
||||||
from .theme import apply_app_theme, effective_theme
|
from .theme import apply_app_theme, effective_theme
|
||||||
from .update_service import signal_update_ready
|
|
||||||
except ImportError:
|
except ImportError:
|
||||||
from icons import lucide_icon
|
from icons import lucide_icon
|
||||||
from main_window import MainWindow
|
from main_window import MainWindow
|
||||||
from settings import AppSettings
|
from settings import AppSettings
|
||||||
from theme import apply_app_theme, effective_theme
|
from theme import apply_app_theme, effective_theme
|
||||||
from update_service import signal_update_ready
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
app = QApplication(sys.argv)
|
app = QApplication(sys.argv)
|
||||||
if "--verify-bundle" in sys.argv:
|
|
||||||
app.processEvents()
|
|
||||||
return 0
|
|
||||||
settings = AppSettings.load()
|
settings = AppSettings.load()
|
||||||
apply_app_theme(settings.theme)
|
apply_app_theme(settings.theme)
|
||||||
icon_color = "#111827" if effective_theme(settings.theme) == "light" else "#e5e7eb"
|
icon_color = "#111827" if effective_theme(settings.theme) == "light" else "#e5e7eb"
|
||||||
@ -37,7 +31,6 @@ def main() -> int:
|
|||||||
window = MainWindow()
|
window = MainWindow()
|
||||||
window.setWindowIcon(app_icon)
|
window.setWindowIcon(app_icon)
|
||||||
window.show()
|
window.show()
|
||||||
QTimer.singleShot(500, signal_update_ready)
|
|
||||||
return app.exec()
|
return app.exec()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
1311
main_window.py
1311
main_window.py
File diff suppressed because it is too large
Load Diff
@ -1,503 +0,0 @@
|
|||||||
"""Standalone high-quality mapping image renderer.
|
|
||||||
|
|
||||||
Draws the LED mapping directly from MappingDocument data, completely
|
|
||||||
independent of the Qt scene/canvas so no UI labels or zoom state leak in.
|
|
||||||
|
|
||||||
Layout
|
|
||||||
------
|
|
||||||
* Top part : LED mapping (square canvas)
|
|
||||||
* Bottom part: colour legend arranged left-to-right for lines,
|
|
||||||
with blocks listed top-to-bottom inside each column.
|
|
||||||
|
|
||||||
Connections
|
|
||||||
-----------
|
|
||||||
* Inner connections (within a block): solid line, full opacity.
|
|
||||||
* Bridge connections (between consecutive blocks of the same line): dashed
|
|
||||||
line, slightly thinner, same colour.
|
|
||||||
* Overlapping segments are deflected with a quadratic Bezier (same
|
|
||||||
algorithm as the Qt canvas).
|
|
||||||
* Mid-segment arrow heads indicate direction.
|
|
||||||
|
|
||||||
Badges
|
|
||||||
------
|
|
||||||
* Start badge (green, above dot) : first LED of a block.
|
|
||||||
* End badge (red, below dot) : last LED of a block.
|
|
||||||
* Single badge (blue, above dot) : block with exactly one LED.
|
|
||||||
* An anti-overlap pass shifts badges that would otherwise overlap.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import math
|
|
||||||
from pathlib import Path
|
|
||||||
from typing import TYPE_CHECKING
|
|
||||||
|
|
||||||
from PySide6.QtCore import QPointF, QRectF, Qt
|
|
||||||
from PySide6.QtGui import (
|
|
||||||
QBrush,
|
|
||||||
QColor,
|
|
||||||
QFont,
|
|
||||||
QFontMetricsF,
|
|
||||||
QImage,
|
|
||||||
QPainter,
|
|
||||||
QPainterPath,
|
|
||||||
QPen,
|
|
||||||
)
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
try:
|
|
||||||
from models import MappingDocument
|
|
||||||
except ImportError:
|
|
||||||
from .models import MappingDocument # type: ignore[no-redef]
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Layout constants
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
MAPPING_MAX = 4000 # longest side of mapping area (pixels)
|
|
||||||
LEGEND_HEIGHT = 480 # legend strip at the bottom
|
|
||||||
PADDING_FRAC = 0.04 # % padding inside mapping area
|
|
||||||
|
|
||||||
# Legend layout
|
|
||||||
LEGEND_H_PAD = 60 # horizontal padding of legend area
|
|
||||||
LEGEND_V_PAD = 28 # vertical padding of legend area
|
|
||||||
LEGEND_COL_GAP = 24 # gap between line columns
|
|
||||||
LEGEND_SWATCH_W = 22
|
|
||||||
LEGEND_SWATCH_H = 22
|
|
||||||
LEGEND_LINE_ROW = 38 # height of each line header row
|
|
||||||
LEGEND_BLOCK_ROW = 26 # height of each block row
|
|
||||||
|
|
||||||
# Colours
|
|
||||||
DARK_BG = "#0f172a"
|
|
||||||
DARK_LEGEND_BG = "#111827"
|
|
||||||
DIVIDER = "#1e3a5f"
|
|
||||||
DARK_TITLE = "#f8fafc"
|
|
||||||
DARK_LINE_TEXT = "#f1f5f9"
|
|
||||||
DARK_BLOCK_TEXT = "#94a3b8"
|
|
||||||
UNASSIGNED = "#3b4f6b"
|
|
||||||
BADGE_START = "#10b981"
|
|
||||||
BADGE_END = "#ef4444"
|
|
||||||
BADGE_SINGLE = "#3b82f6"
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Internal helpers
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _overlap_control_point(
|
|
||||||
start: QPointF,
|
|
||||||
end: QPointF,
|
|
||||||
segments: list[tuple[QPointF, QPointF]],
|
|
||||||
base_scale: float = 1.0,
|
|
||||||
) -> QPointF | None:
|
|
||||||
"""Return a quadratic Bezier control point if *start-end* overlaps an
|
|
||||||
existing segment, otherwise None (straight line)."""
|
|
||||||
dx = end.x() - start.x()
|
|
||||||
dy = end.y() - start.y()
|
|
||||||
length = math.hypot(dx, dy)
|
|
||||||
if length < 0.001:
|
|
||||||
return None
|
|
||||||
|
|
||||||
unit_ax = dx / length
|
|
||||||
unit_ay = dy / length
|
|
||||||
|
|
||||||
previous_count = 0
|
|
||||||
for prev_s, prev_e in segments:
|
|
||||||
# Parallel check
|
|
||||||
pdx = prev_e.x() - prev_s.x()
|
|
||||||
pdy = prev_e.y() - prev_s.y()
|
|
||||||
plen = math.hypot(pdx, pdy)
|
|
||||||
if plen < 0.001:
|
|
||||||
continue
|
|
||||||
unit_bx = pdx / plen
|
|
||||||
unit_by = pdy / plen
|
|
||||||
if abs(unit_ax * unit_bx + unit_ay * unit_by) < 0.985:
|
|
||||||
continue
|
|
||||||
# Perpendicular distance
|
|
||||||
d0 = abs((prev_s.x() - start.x()) * unit_ay - (prev_s.y() - start.y()) * unit_ax)
|
|
||||||
d1 = abs((prev_e.x() - start.x()) * unit_ay - (prev_e.y() - start.y()) * unit_ax)
|
|
||||||
if max(d0, d1) > 5.0 * base_scale:
|
|
||||||
continue
|
|
||||||
# Overlap projection
|
|
||||||
b0 = (prev_s.x() - start.x()) * unit_ax + (prev_s.y() - start.y()) * unit_ay
|
|
||||||
b1 = (prev_e.x() - start.x()) * unit_ax + (prev_e.y() - start.y()) * unit_ay
|
|
||||||
ov_s = max(0.0, min(b0, b1))
|
|
||||||
ov_e = min(length, max(b0, b1))
|
|
||||||
if (ov_e - ov_s) >= min(10.0 * base_scale, min(length, plen) * 0.35):
|
|
||||||
previous_count += 1
|
|
||||||
|
|
||||||
segments.append((QPointF(start), QPointF(end)))
|
|
||||||
if previous_count == 0:
|
|
||||||
return None
|
|
||||||
|
|
||||||
bend = min(16.0 * base_scale, max(7.0 * base_scale, length * 0.24))
|
|
||||||
side = 1.0 if previous_count % 2 == 1 else -1.0
|
|
||||||
layer = 1.0 + (previous_count - 1) // 2
|
|
||||||
offset = side * bend * layer
|
|
||||||
perp_x = -dy / length
|
|
||||||
perp_y = dx / length
|
|
||||||
mid_x = (start.x() + end.x()) / 2
|
|
||||||
mid_y = (start.y() + end.y()) / 2
|
|
||||||
return QPointF(mid_x + perp_x * offset, mid_y + perp_y * offset)
|
|
||||||
|
|
||||||
|
|
||||||
def _append_connection(
|
|
||||||
path: QPainterPath,
|
|
||||||
start: QPointF,
|
|
||||||
end: QPointF,
|
|
||||||
segments: list[tuple[QPointF, QPointF]],
|
|
||||||
base_scale: float = 1.0,
|
|
||||||
) -> QPointF | None:
|
|
||||||
path.moveTo(start)
|
|
||||||
control = _overlap_control_point(start, end, segments, base_scale)
|
|
||||||
if control is None:
|
|
||||||
path.lineTo(end)
|
|
||||||
else:
|
|
||||||
path.quadTo(control, end)
|
|
||||||
return control
|
|
||||||
|
|
||||||
|
|
||||||
def _append_arrow(
|
|
||||||
path: QPainterPath,
|
|
||||||
start: QPointF,
|
|
||||||
end: QPointF,
|
|
||||||
control: QPointF | None,
|
|
||||||
base_scale: float = 1.0,
|
|
||||||
) -> None:
|
|
||||||
dx = end.x() - start.x()
|
|
||||||
dy = end.y() - start.y()
|
|
||||||
length = math.hypot(dx, dy)
|
|
||||||
if length < 8.0 * base_scale:
|
|
||||||
return
|
|
||||||
t = 0.55
|
|
||||||
if control is None:
|
|
||||||
unit_x = dx / length
|
|
||||||
unit_y = dy / length
|
|
||||||
mid_x = start.x() + dx * t
|
|
||||||
mid_y = start.y() + dy * t
|
|
||||||
else:
|
|
||||||
inv_t = 1.0 - t
|
|
||||||
mid_x = inv_t*inv_t*start.x() + 2*inv_t*t*control.x() + t*t*end.x()
|
|
||||||
mid_y = inv_t*inv_t*start.y() + 2*inv_t*t*control.y() + t*t*end.y()
|
|
||||||
tan_x = 2*inv_t*(control.x()-start.x()) + 2*t*(end.x()-control.x())
|
|
||||||
tan_y = 2*inv_t*(control.y()-start.y()) + 2*t*(end.y()-control.y())
|
|
||||||
tl = math.hypot(tan_x, tan_y)
|
|
||||||
if tl < 0.001:
|
|
||||||
return
|
|
||||||
unit_x = tan_x / tl
|
|
||||||
unit_y = tan_y / tl
|
|
||||||
alen = min(7.0 * base_scale, length * 0.28)
|
|
||||||
awid = alen * 0.55
|
|
||||||
base_x = mid_x - unit_x * alen
|
|
||||||
base_y = mid_y - unit_y * alen
|
|
||||||
perp_x = -unit_y
|
|
||||||
perp_y = unit_x
|
|
||||||
path.moveTo(QPointF(base_x + perp_x*awid, base_y + perp_y*awid))
|
|
||||||
path.lineTo(QPointF(mid_x, mid_y))
|
|
||||||
path.lineTo(QPointF(base_x - perp_x*awid, base_y - perp_y*awid))
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Public API
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def render_mapping_image(doc: "MappingDocument", file_path: str | Path, theme: str = "dark") -> bool:
|
|
||||||
"""Render *doc* to *file_path* (PNG or JPEG). Returns True on success."""
|
|
||||||
if not doc.points:
|
|
||||||
return False
|
|
||||||
|
|
||||||
is_dark = theme == "dark"
|
|
||||||
bg_color = QColor(DARK_BG if is_dark else "#ffffff")
|
|
||||||
legend_bg_color = QColor(DARK_LEGEND_BG if is_dark else "#f8fafc")
|
|
||||||
divider_color = QColor(DIVIDER if is_dark else "#e2e8f0")
|
|
||||||
line_text_color = QColor(DARK_LINE_TEXT if is_dark else "#0f172a")
|
|
||||||
block_text_color = QColor(DARK_BLOCK_TEXT if is_dark else "#475569")
|
|
||||||
unassigned_color = QColor(UNASSIGNED if is_dark else "#cbd5e1")
|
|
||||||
|
|
||||||
# Scale factor based on resolution
|
|
||||||
base_scale = MAPPING_MAX / 2200.0
|
|
||||||
|
|
||||||
# ── 1. World bounds ─────────────────────────────────────────────────────
|
|
||||||
xs = [p.x for p in doc.points]
|
|
||||||
ys = [p.y for p in doc.points]
|
|
||||||
min_x, max_x = min(xs), max(xs)
|
|
||||||
min_y, max_y = min(ys), max(ys)
|
|
||||||
world_w = max(max_x - min_x, 1.0)
|
|
||||||
world_h = max(max_y - min_y, 1.0)
|
|
||||||
pad_x = world_w * PADDING_FRAC
|
|
||||||
pad_y = world_h * PADDING_FRAC
|
|
||||||
draw_x0 = min_x - pad_x
|
|
||||||
draw_y0 = min_y - pad_y
|
|
||||||
draw_w = world_w + 2 * pad_x
|
|
||||||
draw_h = world_h + 2 * pad_y
|
|
||||||
|
|
||||||
# Compute actual pixel map dimensions (preserve aspect ratio)
|
|
||||||
aspect = draw_w / draw_h
|
|
||||||
if aspect >= 1.0:
|
|
||||||
map_px_w = MAPPING_MAX
|
|
||||||
map_px_h = max(200, round(MAPPING_MAX / aspect))
|
|
||||||
else:
|
|
||||||
map_px_h = MAPPING_MAX
|
|
||||||
map_px_w = max(200, round(MAPPING_MAX * aspect))
|
|
||||||
|
|
||||||
scale = map_px_w / draw_w # == map_px_h / draw_h
|
|
||||||
|
|
||||||
def to_px(x: float, y: float) -> QPointF:
|
|
||||||
px = (x - draw_x0) * scale
|
|
||||||
py = ((max_y + pad_y) - y) * scale # flip y
|
|
||||||
return QPointF(px, py)
|
|
||||||
|
|
||||||
dot_r = max(5.0 * base_scale, min(14.0 * base_scale, scale * 1.6))
|
|
||||||
|
|
||||||
# ── 2. Lookups ───────────────────────────────────────────────────────────
|
|
||||||
point_by_uid: dict[int, object] = {p.uid: p for p in doc.points}
|
|
||||||
point_line: dict[int, object] = {}
|
|
||||||
badge_info: dict[int, tuple[str, str]] = {} # uid → (text, badge_type)
|
|
||||||
|
|
||||||
for line in doc.lines:
|
|
||||||
cur = 0
|
|
||||||
for block in line.blocks:
|
|
||||||
n = len(block.point_ids)
|
|
||||||
if n == 0:
|
|
||||||
continue
|
|
||||||
s_uid = block.point_ids[0]
|
|
||||||
e_uid = block.point_ids[-1]
|
|
||||||
for uid in block.point_ids:
|
|
||||||
point_line[uid] = line
|
|
||||||
if n == 1:
|
|
||||||
badge_info[s_uid] = (f"#{cur}", "single")
|
|
||||||
else:
|
|
||||||
badge_info[s_uid] = (f"#{cur}", "start")
|
|
||||||
badge_info[e_uid] = (f"#{cur + n - 1}", "end")
|
|
||||||
cur += n
|
|
||||||
|
|
||||||
# 3. Pre-compute legend height so image is created at the right size
|
|
||||||
legend_line_row = LEGEND_LINE_ROW * base_scale
|
|
||||||
legend_block_row = LEGEND_BLOCK_ROW * base_scale
|
|
||||||
legend_v_pad = LEGEND_V_PAD * base_scale
|
|
||||||
legend_h_pad = LEGEND_H_PAD * base_scale
|
|
||||||
legend_col_gap = LEGEND_COL_GAP * base_scale
|
|
||||||
legend_swatch_w = LEGEND_SWATCH_W * base_scale
|
|
||||||
legend_swatch_h = LEGEND_SWATCH_H * base_scale
|
|
||||||
|
|
||||||
max_col_h_pre = max(
|
|
||||||
(legend_line_row + len(ln.blocks) * legend_block_row for ln in doc.lines),
|
|
||||||
default=0,
|
|
||||||
)
|
|
||||||
legend_height_pre = legend_v_pad * 2 + max(max_col_h_pre, 60.0 * base_scale)
|
|
||||||
|
|
||||||
img_w = map_px_w
|
|
||||||
img_h = map_px_h + round(legend_height_pre)
|
|
||||||
image = QImage(img_w, img_h, QImage.Format.Format_ARGB32)
|
|
||||||
image.fill(bg_color)
|
|
||||||
|
|
||||||
painter = QPainter(image)
|
|
||||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
|
||||||
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing)
|
|
||||||
|
|
||||||
# ── 4. Connections ───────────────────────────────────────────────────────
|
|
||||||
segments: list[tuple[QPointF, QPointF]] = []
|
|
||||||
line_w_inner = max(1.2 * base_scale, dot_r * 0.30)
|
|
||||||
line_w_bridge = max(1.0 * base_scale, dot_r * 0.20)
|
|
||||||
line_w_arrow = max(1.0 * base_scale, dot_r * 0.22)
|
|
||||||
|
|
||||||
for line in doc.lines:
|
|
||||||
lc = QColor(line.color)
|
|
||||||
|
|
||||||
# Inner paths
|
|
||||||
inner_path = QPainterPath()
|
|
||||||
arrow_path = QPainterPath()
|
|
||||||
for block in line.blocks:
|
|
||||||
pts = [point_by_uid.get(uid) for uid in block.point_ids]
|
|
||||||
pts = [p for p in pts if p is not None]
|
|
||||||
for a, b in zip(pts, pts[1:]):
|
|
||||||
s = to_px(a.x, a.y) # type: ignore[union-attr]
|
|
||||||
e = to_px(b.x, b.y) # type: ignore[union-attr]
|
|
||||||
ctrl = _append_connection(inner_path, s, e, segments, base_scale)
|
|
||||||
_append_arrow(arrow_path, s, e, ctrl, base_scale)
|
|
||||||
|
|
||||||
c_inner = QColor(lc)
|
|
||||||
c_inner.setAlphaF(0.85)
|
|
||||||
pen = QPen(c_inner, line_w_inner)
|
|
||||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
|
||||||
painter.setPen(pen)
|
|
||||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
|
||||||
painter.drawPath(inner_path)
|
|
||||||
|
|
||||||
c_arrow = QColor(lc)
|
|
||||||
c_arrow.setAlphaF(0.95)
|
|
||||||
pen_a = QPen(c_arrow, line_w_arrow)
|
|
||||||
pen_a.setCapStyle(Qt.PenCapStyle.RoundCap)
|
|
||||||
pen_a.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
|
|
||||||
painter.setPen(pen_a)
|
|
||||||
painter.drawPath(arrow_path)
|
|
||||||
|
|
||||||
# Bridge paths (between blocks)
|
|
||||||
bridge_path = QPainterPath()
|
|
||||||
b_arrow_path = QPainterPath()
|
|
||||||
prev_end_pt = None
|
|
||||||
for block in line.blocks:
|
|
||||||
if not block.point_ids:
|
|
||||||
continue
|
|
||||||
first_pt = point_by_uid.get(block.point_ids[0])
|
|
||||||
last_pt = point_by_uid.get(block.point_ids[-1])
|
|
||||||
if first_pt is not None and prev_end_pt is not None:
|
|
||||||
s = to_px(prev_end_pt.x, prev_end_pt.y) # type: ignore[union-attr]
|
|
||||||
e = to_px(first_pt.x, first_pt.y) # type: ignore[union-attr]
|
|
||||||
ctrl = _append_connection(bridge_path, s, e, segments, base_scale)
|
|
||||||
_append_arrow(b_arrow_path, s, e, ctrl, base_scale)
|
|
||||||
if last_pt is not None:
|
|
||||||
prev_end_pt = last_pt
|
|
||||||
|
|
||||||
c_bridge = QColor(lc)
|
|
||||||
c_bridge.setAlphaF(0.5)
|
|
||||||
pen_b = QPen(c_bridge, line_w_bridge)
|
|
||||||
pen_b.setCapStyle(Qt.PenCapStyle.RoundCap)
|
|
||||||
pen_b.setStyle(Qt.PenStyle.DashLine)
|
|
||||||
painter.setPen(pen_b)
|
|
||||||
painter.drawPath(bridge_path)
|
|
||||||
|
|
||||||
c_ba = QColor(lc)
|
|
||||||
c_ba.setAlphaF(0.75)
|
|
||||||
pen_ba = QPen(c_ba, line_w_arrow)
|
|
||||||
pen_ba.setCapStyle(Qt.PenCapStyle.RoundCap)
|
|
||||||
pen_ba.setStyle(Qt.PenStyle.SolidLine)
|
|
||||||
painter.setPen(pen_ba)
|
|
||||||
painter.drawPath(b_arrow_path)
|
|
||||||
|
|
||||||
# ── 5. LED dots ──────────────────────────────────────────────────────────
|
|
||||||
for point in doc.points:
|
|
||||||
px = to_px(point.x, point.y)
|
|
||||||
line = point_line.get(point.uid)
|
|
||||||
color = QColor(line.color if line else unassigned_color)
|
|
||||||
painter.setPen(QPen(color.darker(160), max(1.0, dot_r * 0.10)))
|
|
||||||
painter.setBrush(QBrush(color))
|
|
||||||
painter.drawEllipse(px, dot_r, dot_r)
|
|
||||||
|
|
||||||
# ── 6. Badges (anti-overlap) ─────────────────────────────────────────────
|
|
||||||
badge_font = QFont("Segoe UI", max(7, int(dot_r * 0.82)))
|
|
||||||
badge_font.setBold(True)
|
|
||||||
painter.setFont(badge_font)
|
|
||||||
fm = QFontMetricsF(badge_font)
|
|
||||||
|
|
||||||
# First pass: compute proposed rect for each badge
|
|
||||||
badge_rects: list[tuple[str, str, QRectF, QColor]] = [] # (text, badge_type, rect, bg)
|
|
||||||
|
|
||||||
def proposed_rect(uid: int, text: str, btype: str) -> tuple[QRectF, QColor]:
|
|
||||||
p = point_by_uid.get(uid)
|
|
||||||
if p is None:
|
|
||||||
return QRectF(), QColor()
|
|
||||||
px = to_px(p.x, p.y) # type: ignore[union-attr]
|
|
||||||
tw = fm.horizontalAdvance(text)
|
|
||||||
th = fm.height()
|
|
||||||
bx = px.x() - tw / 2 - 5 * base_scale
|
|
||||||
bw = tw + 10 * base_scale
|
|
||||||
bh = th + 4 * base_scale
|
|
||||||
if btype in ("start", "single"):
|
|
||||||
by = px.y() - dot_r - bh - 4 * base_scale
|
|
||||||
bg = QColor(BADGE_START if btype == "start" else BADGE_SINGLE)
|
|
||||||
else:
|
|
||||||
by = px.y() + dot_r + 4 * base_scale
|
|
||||||
bg = QColor(BADGE_END)
|
|
||||||
return QRectF(bx, by, bw, bh), bg
|
|
||||||
|
|
||||||
# Collect all badges
|
|
||||||
raw_badges: list[tuple[int, str, str]] = []
|
|
||||||
for uid, (text, btype) in badge_info.items():
|
|
||||||
raw_badges.append((uid, text, btype))
|
|
||||||
|
|
||||||
# Build placed rects with nudge to avoid overlap
|
|
||||||
placed: list[QRectF] = []
|
|
||||||
NUDGE_STEP = fm.height() + 6 * base_scale
|
|
||||||
# Maximum y for badge bottom must stay within mapping area
|
|
||||||
badge_max_y = map_px_h - 4 * base_scale
|
|
||||||
|
|
||||||
for uid, text, btype in raw_badges:
|
|
||||||
rect, bg = proposed_rect(uid, text, btype)
|
|
||||||
if rect.isEmpty():
|
|
||||||
continue
|
|
||||||
# Try shifting vertically until no overlap
|
|
||||||
direction = -1 if btype in ("start", "single") else 1
|
|
||||||
for _ in range(12):
|
|
||||||
overlaps = any(rect.intersects(pr) for pr in placed)
|
|
||||||
if not overlaps:
|
|
||||||
break
|
|
||||||
rect = rect.translated(0, direction * NUDGE_STEP)
|
|
||||||
# Clamp: don't let badge go outside mapping area vertically
|
|
||||||
if rect.bottom() > badge_max_y:
|
|
||||||
rect = rect.translated(0, badge_max_y - rect.bottom())
|
|
||||||
if rect.top() < 0:
|
|
||||||
rect = rect.translated(0, -rect.top())
|
|
||||||
placed.append(rect)
|
|
||||||
badge_rects.append((text, btype, rect, bg))
|
|
||||||
|
|
||||||
# Second pass: draw
|
|
||||||
for text, btype, rect, bg in badge_rects:
|
|
||||||
painter.setPen(Qt.PenStyle.NoPen)
|
|
||||||
painter.setBrush(QBrush(bg))
|
|
||||||
painter.drawRoundedRect(rect, 3 * base_scale, 3 * base_scale)
|
|
||||||
painter.setPen(QColor(Qt.GlobalColor.white))
|
|
||||||
painter.drawText(rect, Qt.AlignmentFlag.AlignCenter, text)
|
|
||||||
|
|
||||||
# ── 7. Legend strip ───────────────────────────────────────────────────────
|
|
||||||
title_font = QFont("Segoe UI", int(16 * base_scale))
|
|
||||||
title_font.setBold(True)
|
|
||||||
block_font = QFont("Segoe UI", int(13 * base_scale))
|
|
||||||
|
|
||||||
legend_y0 = map_px_h
|
|
||||||
legend_h = round(legend_height_pre)
|
|
||||||
|
|
||||||
painter.setPen(Qt.PenStyle.NoPen)
|
|
||||||
painter.setBrush(QBrush(legend_bg_color))
|
|
||||||
painter.drawRect(0, legend_y0, img_w, legend_h)
|
|
||||||
|
|
||||||
# divider
|
|
||||||
painter.setPen(QPen(divider_color, int(2 * base_scale)))
|
|
||||||
painter.drawLine(0, legend_y0, img_w, legend_y0)
|
|
||||||
|
|
||||||
if doc.lines:
|
|
||||||
n_lines = len(doc.lines)
|
|
||||||
avail_w = img_w - 2 * legend_h_pad
|
|
||||||
col_w = (avail_w - legend_col_gap * (n_lines - 1)) / n_lines
|
|
||||||
|
|
||||||
for i, line in enumerate(doc.lines):
|
|
||||||
cx = float(legend_h_pad) + i * (col_w + legend_col_gap)
|
|
||||||
cy = float(legend_y0 + legend_v_pad)
|
|
||||||
|
|
||||||
# Colour swatch + line name
|
|
||||||
painter.setPen(Qt.PenStyle.NoPen)
|
|
||||||
painter.setBrush(QBrush(QColor(line.color)))
|
|
||||||
painter.drawRoundedRect(
|
|
||||||
QRectF(cx, cy + 4 * base_scale, legend_swatch_w, legend_swatch_h), 3 * base_scale, 3 * base_scale
|
|
||||||
)
|
|
||||||
painter.setFont(title_font)
|
|
||||||
painter.setPen(line_text_color)
|
|
||||||
painter.drawText(
|
|
||||||
QRectF(cx + legend_swatch_w + 10 * base_scale, cy, col_w - legend_swatch_w - 10 * base_scale, legend_line_row),
|
|
||||||
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
|
|
||||||
line.name,
|
|
||||||
)
|
|
||||||
cy += legend_line_row
|
|
||||||
|
|
||||||
# Blocks (top-to-bottom within column)
|
|
||||||
cur = 0
|
|
||||||
painter.setFont(block_font)
|
|
||||||
for block in line.blocks:
|
|
||||||
n = len(block.point_ids)
|
|
||||||
rng = f"{cur}-{cur + n - 1}" if n else "пусто"
|
|
||||||
cur += n
|
|
||||||
|
|
||||||
# Thin colour bar on the left
|
|
||||||
painter.setPen(Qt.PenStyle.NoPen)
|
|
||||||
painter.setBrush(QBrush(QColor(line.color)))
|
|
||||||
painter.drawRect(QRectF(cx + 4 * base_scale, cy + 4 * base_scale, 3 * base_scale, legend_block_row - 8 * base_scale))
|
|
||||||
|
|
||||||
painter.setPen(block_text_color)
|
|
||||||
painter.drawText(
|
|
||||||
QRectF(cx + 16 * base_scale, cy, col_w - 16 * base_scale, legend_block_row),
|
|
||||||
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
|
|
||||||
f"{block.name}: {rng}",
|
|
||||||
)
|
|
||||||
cy += legend_block_row
|
|
||||||
|
|
||||||
painter.end()
|
|
||||||
return image.save(str(file_path))
|
|
||||||
601
models.py
601
models.py
@ -1,18 +1,9 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import base64
|
|
||||||
import binascii
|
|
||||||
import hashlib
|
|
||||||
import json
|
import json
|
||||||
import math
|
import math
|
||||||
import mimetypes
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import tempfile
|
|
||||||
import uuid
|
|
||||||
from collections import deque
|
from collections import deque
|
||||||
from copy import deepcopy
|
from dataclasses import dataclass, field
|
||||||
from dataclasses import dataclass, field, replace
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@ -22,16 +13,12 @@ except ImportError: # pragma: no cover - supports package imports in tests/tool
|
|||||||
from .unfolding import MAX_LINES, UnfoldingDescription, UnfoldingLineSummary, clockwise_sort, order_points_clockwise
|
from .unfolding import MAX_LINES, UnfoldingDescription, UnfoldingLineSummary, clockwise_sort, order_points_clockwise
|
||||||
|
|
||||||
MIN_NEIGHBOR_DISTANCE_MM = 34.0
|
MIN_NEIGHBOR_DISTANCE_MM = 34.0
|
||||||
DEFAULT_GRID_STEP_MM = MIN_NEIGHBOR_DISTANCE_MM
|
|
||||||
MAX_NEIGHBOR_TOLERANCE_MM = 2.0
|
MAX_NEIGHBOR_TOLERANCE_MM = 2.0
|
||||||
METER_LIKE_MAX_SPAN = 10.0
|
METER_LIKE_MAX_SPAN = 10.0
|
||||||
_DOCUMENT_KNOWN_FIELDS = {
|
_DOCUMENT_KNOWN_FIELDS = {
|
||||||
"background",
|
"background",
|
||||||
"comments",
|
|
||||||
"circles",
|
"circles",
|
||||||
"coordinate_unit",
|
"coordinate_unit",
|
||||||
"grid_step_mm",
|
|
||||||
"index_base",
|
|
||||||
"leds",
|
"leds",
|
||||||
"lines",
|
"lines",
|
||||||
"unit",
|
"unit",
|
||||||
@ -53,120 +40,6 @@ _LED_POINT_KNOWN_FIELDS = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class NominalGridDistance(float):
|
|
||||||
"""Grid spacing carrying a tolerance expressed in the same coordinate unit."""
|
|
||||||
|
|
||||||
def __new__(cls, value: float, tolerance: float): # noqa: ANN204
|
|
||||||
instance = super().__new__(cls, value)
|
|
||||||
instance.tolerance = tolerance
|
|
||||||
return instance
|
|
||||||
|
|
||||||
|
|
||||||
def load_json_document(path: str | Path) -> dict[str, Any]:
|
|
||||||
path = Path(path)
|
|
||||||
if path.exists():
|
|
||||||
try:
|
|
||||||
if path.stat().st_size == 0:
|
|
||||||
path.write_text('{"circles": []}', encoding="utf-8")
|
|
||||||
else:
|
|
||||||
content = path.read_bytes()
|
|
||||||
if not content.strip():
|
|
||||||
path.write_text('{"circles": []}', encoding="utf-8")
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
text, was_converted = _read_text_as_utf8(path)
|
|
||||||
if was_converted:
|
|
||||||
path.write_text(text, encoding="utf-8")
|
|
||||||
data = _loads_lenient_json(text)
|
|
||||||
if isinstance(data, list):
|
|
||||||
return {"circles": data}
|
|
||||||
if isinstance(data, dict):
|
|
||||||
return data
|
|
||||||
raise ValueError("JSON must contain an object or an array of LED points.")
|
|
||||||
|
|
||||||
|
|
||||||
def _read_text_as_utf8(path: Path) -> tuple[str, bool]:
|
|
||||||
raw = path.read_bytes()
|
|
||||||
try:
|
|
||||||
text = raw.decode("utf-8-sig")
|
|
||||||
if _looks_like_json_text(text):
|
|
||||||
return text, False
|
|
||||||
except UnicodeDecodeError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
for encoding in ("utf-16", "utf-16-le", "utf-16-be", "cp1251", "cp1252"):
|
|
||||||
try:
|
|
||||||
text = raw.decode(encoding)
|
|
||||||
except UnicodeDecodeError:
|
|
||||||
continue
|
|
||||||
if _looks_like_json_text(text):
|
|
||||||
return text.lstrip("\ufeff"), True
|
|
||||||
return raw.decode("utf-8", errors="replace"), True
|
|
||||||
|
|
||||||
|
|
||||||
def _looks_like_json_text(text: str) -> bool:
|
|
||||||
if "\x00" in text[:64]:
|
|
||||||
return False
|
|
||||||
stripped = text.lstrip("\ufeff \t\r\n")
|
|
||||||
return stripped.startswith("{") or stripped.startswith("[")
|
|
||||||
|
|
||||||
|
|
||||||
def _loads_lenient_json(text: str) -> Any:
|
|
||||||
try:
|
|
||||||
return json.loads(text)
|
|
||||||
except json.JSONDecodeError as original_error:
|
|
||||||
fixed_text = _sanitize_raw_json_text(text)
|
|
||||||
if fixed_text == text:
|
|
||||||
raise original_error
|
|
||||||
try:
|
|
||||||
return json.loads(fixed_text)
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
raise original_error
|
|
||||||
|
|
||||||
|
|
||||||
def _sanitize_raw_json_text(text: str) -> str:
|
|
||||||
result: list[str] = []
|
|
||||||
in_string = False
|
|
||||||
escaped = False
|
|
||||||
length = len(text)
|
|
||||||
index = 0
|
|
||||||
while index < length:
|
|
||||||
char = text[index]
|
|
||||||
if in_string:
|
|
||||||
result.append(char)
|
|
||||||
if escaped:
|
|
||||||
escaped = False
|
|
||||||
elif char == "\\":
|
|
||||||
escaped = True
|
|
||||||
elif char == '"':
|
|
||||||
in_string = False
|
|
||||||
index += 1
|
|
||||||
continue
|
|
||||||
|
|
||||||
if char == '"':
|
|
||||||
in_string = True
|
|
||||||
result.append(char)
|
|
||||||
elif char == "," and _next_non_space(text, index + 1) in {"}", "]"}:
|
|
||||||
pass
|
|
||||||
elif char == "." and result and result[-1].isdigit() and not _next_char_is_digit(text, index + 1):
|
|
||||||
result.append(".0")
|
|
||||||
else:
|
|
||||||
result.append(char)
|
|
||||||
index += 1
|
|
||||||
return "".join(result)
|
|
||||||
|
|
||||||
|
|
||||||
def _next_non_space(text: str, start: int) -> str | None:
|
|
||||||
for index in range(start, len(text)):
|
|
||||||
if not text[index].isspace():
|
|
||||||
return text[index]
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _next_char_is_digit(text: str, start: int) -> bool:
|
|
||||||
return start < len(text) and text[start].isdigit()
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class LedPoint:
|
class LedPoint:
|
||||||
uid: int
|
uid: int
|
||||||
@ -208,33 +81,11 @@ class BackgroundImage:
|
|||||||
scale_y_percent: float = 100.0
|
scale_y_percent: float = 100.0
|
||||||
opacity_percent: float = 100.0
|
opacity_percent: float = 100.0
|
||||||
visible: bool = True
|
visible: bool = True
|
||||||
embedded_image_base64: str = ""
|
|
||||||
embedded_image_mime_type: str = ""
|
|
||||||
embedded_image_name: str = ""
|
|
||||||
embedded_image_sha256: str = ""
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_payload(cls, payload) -> "BackgroundImage": # noqa: ANN001
|
def from_payload(cls, payload) -> "BackgroundImage": # noqa: ANN001
|
||||||
if not isinstance(payload, dict):
|
if not isinstance(payload, dict):
|
||||||
return cls()
|
return cls()
|
||||||
embedded = payload.get("embedded_image")
|
|
||||||
embedded_data = ""
|
|
||||||
embedded_mime_type = ""
|
|
||||||
embedded_name = ""
|
|
||||||
embedded_sha256 = ""
|
|
||||||
if isinstance(embedded, dict):
|
|
||||||
candidate_data = str(embedded.get("data") or "")
|
|
||||||
try:
|
|
||||||
decoded = base64.b64decode(candidate_data, validate=True) if candidate_data else b""
|
|
||||||
except (binascii.Error, ValueError, TypeError):
|
|
||||||
decoded = b""
|
|
||||||
candidate_sha256 = str(embedded.get("sha256") or "").strip().lower()
|
|
||||||
actual_sha256 = hashlib.sha256(decoded).hexdigest() if decoded else ""
|
|
||||||
if decoded and (not candidate_sha256 or candidate_sha256 == actual_sha256):
|
|
||||||
embedded_data = candidate_data
|
|
||||||
embedded_mime_type = str(embedded.get("mime_type") or "application/octet-stream")
|
|
||||||
embedded_name = Path(str(embedded.get("name") or "background")).name
|
|
||||||
embedded_sha256 = actual_sha256
|
|
||||||
scale = _optional_float(payload.get("scale_percent"))
|
scale = _optional_float(payload.get("scale_percent"))
|
||||||
scale_x = _optional_float(payload.get("scale_x_percent"))
|
scale_x = _optional_float(payload.get("scale_x_percent"))
|
||||||
scale_y = _optional_float(payload.get("scale_y_percent"))
|
scale_y = _optional_float(payload.get("scale_y_percent"))
|
||||||
@ -253,14 +104,10 @@ class BackgroundImage:
|
|||||||
scale_y_percent=max(1.0, float(scale_y)),
|
scale_y_percent=max(1.0, float(scale_y)),
|
||||||
opacity_percent=min(100.0, max(0.0, 100.0 if opacity is None else float(opacity))),
|
opacity_percent=min(100.0, max(0.0, 100.0 if opacity is None else float(opacity))),
|
||||||
visible=bool(payload.get("visible", True)),
|
visible=bool(payload.get("visible", True)),
|
||||||
embedded_image_base64=embedded_data,
|
|
||||||
embedded_image_mime_type=embedded_mime_type,
|
|
||||||
embedded_image_name=embedded_name,
|
|
||||||
embedded_image_sha256=embedded_sha256,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def to_payload(self) -> dict[str, Any]:
|
def to_payload(self) -> dict[str, bool | float | str]:
|
||||||
payload: dict[str, Any] = {
|
return {
|
||||||
"path": self.path,
|
"path": self.path,
|
||||||
"offset_x": self.offset_x,
|
"offset_x": self.offset_x,
|
||||||
"offset_y": self.offset_y,
|
"offset_y": self.offset_y,
|
||||||
@ -269,80 +116,9 @@ class BackgroundImage:
|
|||||||
"opacity_percent": self.opacity_percent,
|
"opacity_percent": self.opacity_percent,
|
||||||
"visible": self.visible,
|
"visible": self.visible,
|
||||||
}
|
}
|
||||||
if self.has_embedded_image():
|
|
||||||
payload["embedded_image"] = {
|
|
||||||
"encoding": "base64",
|
|
||||||
"mime_type": self.embedded_image_mime_type or "application/octet-stream",
|
|
||||||
"name": self.embedded_image_name or "background",
|
|
||||||
"sha256": self.embedded_image_sha256 or hashlib.sha256(self.embedded_image_bytes()).hexdigest(),
|
|
||||||
"data": self.embedded_image_base64,
|
|
||||||
}
|
|
||||||
return payload
|
|
||||||
|
|
||||||
def is_enabled(self) -> bool:
|
def is_enabled(self) -> bool:
|
||||||
return bool(self.path) or self.has_embedded_image()
|
return bool(self.path)
|
||||||
|
|
||||||
def has_embedded_image(self) -> bool:
|
|
||||||
return bool(self.embedded_image_base64)
|
|
||||||
|
|
||||||
def embedded_image_bytes(self) -> bytes:
|
|
||||||
if not self.embedded_image_base64:
|
|
||||||
return b""
|
|
||||||
try:
|
|
||||||
return base64.b64decode(self.embedded_image_base64, validate=True)
|
|
||||||
except (binascii.Error, ValueError, TypeError):
|
|
||||||
return b""
|
|
||||||
|
|
||||||
def with_embedded_image(self, base_dir: Path | None = None) -> "BackgroundImage":
|
|
||||||
if self.has_embedded_image() or not self.path:
|
|
||||||
return self
|
|
||||||
image_path = Path(self.path)
|
|
||||||
if not image_path.is_absolute() and base_dir is not None:
|
|
||||||
image_path = base_dir / image_path
|
|
||||||
image_bytes = image_path.read_bytes()
|
|
||||||
if not image_bytes:
|
|
||||||
raise ValueError("Файл подложки пуст и не может быть встроен в схему.")
|
|
||||||
mime_type = mimetypes.guess_type(image_path.name)[0] or "application/octet-stream"
|
|
||||||
return replace(
|
|
||||||
self,
|
|
||||||
path="",
|
|
||||||
embedded_image_base64=base64.b64encode(image_bytes).decode("ascii"),
|
|
||||||
embedded_image_mime_type=mime_type,
|
|
||||||
embedded_image_name=image_path.name,
|
|
||||||
embedded_image_sha256=hashlib.sha256(image_bytes).hexdigest(),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class TextComment:
|
|
||||||
id: str
|
|
||||||
text: str
|
|
||||||
x: float
|
|
||||||
y: float
|
|
||||||
extra_payload: dict[str, Any] = field(default_factory=dict)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def from_payload(cls, payload: dict[str, Any]) -> "TextComment":
|
|
||||||
text, x, y = cls.validate(payload.get("text", ""), payload.get("x", 0), payload.get("y", 0))
|
|
||||||
return cls(
|
|
||||||
id=str(payload.get("id") or uuid.uuid4().hex), text=text, x=x, y=y,
|
|
||||||
extra_payload={key: deepcopy(value) for key, value in payload.items()
|
|
||||||
if key not in {"id", "text", "x", "y"}},
|
|
||||||
)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def validate(text: str, x: float, y: float) -> tuple[str, float, float]:
|
|
||||||
if not isinstance(text, str) or not text.strip():
|
|
||||||
raise ValueError("Введите текст комментария.")
|
|
||||||
x, y = float(x), float(y)
|
|
||||||
if not math.isfinite(x) or not math.isfinite(y):
|
|
||||||
raise ValueError("Координаты комментария должны быть конечными числами.")
|
|
||||||
return text, x, y
|
|
||||||
|
|
||||||
def to_payload(self) -> dict[str, Any]:
|
|
||||||
text, x, y = self.validate(self.text, self.x, self.y)
|
|
||||||
return {**deepcopy(self.extra_payload), "id": self.id, "text": text, "x": x, "y": y}
|
|
||||||
|
|
||||||
|
|
||||||
class MappingDocument:
|
class MappingDocument:
|
||||||
@ -351,40 +127,35 @@ class MappingDocument:
|
|||||||
self.collection_name = "circles"
|
self.collection_name = "circles"
|
||||||
self.points: list[LedPoint] = []
|
self.points: list[LedPoint] = []
|
||||||
self.lines: list[LedLine] = []
|
self.lines: list[LedLine] = []
|
||||||
self.comments: list[TextComment] = []
|
|
||||||
self.background = BackgroundImage()
|
self.background = BackgroundImage()
|
||||||
self.unfolding = UnfoldingDescription()
|
self.unfolding = UnfoldingDescription()
|
||||||
self.coordinate_unit = "mm"
|
self.coordinate_unit = "auto"
|
||||||
self.grid_step_mm = DEFAULT_GRID_STEP_MM
|
|
||||||
self.extra_payload: dict[str, Any] = {}
|
self.extra_payload: dict[str, Any] = {}
|
||||||
self._next_line_id = 0
|
self._next_line_id = 1
|
||||||
self._next_block_id = 0
|
self._next_block_id = 1
|
||||||
|
|
||||||
def clear(self) -> None:
|
def clear(self) -> None:
|
||||||
self.path = None
|
self.path = None
|
||||||
self.collection_name = "circles"
|
self.collection_name = "circles"
|
||||||
self.points.clear()
|
self.points.clear()
|
||||||
self.lines.clear()
|
self.lines.clear()
|
||||||
self.comments.clear()
|
|
||||||
self.background = BackgroundImage()
|
self.background = BackgroundImage()
|
||||||
self.unfolding = UnfoldingDescription()
|
self.unfolding = UnfoldingDescription()
|
||||||
self.coordinate_unit = "mm"
|
self.coordinate_unit = "auto"
|
||||||
self.grid_step_mm = DEFAULT_GRID_STEP_MM
|
|
||||||
self.extra_payload.clear()
|
self.extra_payload.clear()
|
||||||
self._next_line_id = 0
|
self._next_line_id = 1
|
||||||
self._next_block_id = 0
|
self._next_block_id = 1
|
||||||
|
|
||||||
def load(self, path: str | Path) -> None:
|
def load(self, path: str | Path) -> None:
|
||||||
self.clear()
|
self.clear()
|
||||||
self.path = Path(path)
|
self.path = Path(path)
|
||||||
data = load_json_document(self.path)
|
data = json.loads(self.path.read_text(encoding="utf-8-sig"))
|
||||||
self.extra_payload = {
|
self.extra_payload = {
|
||||||
key: value
|
key: value
|
||||||
for key, value in data.items()
|
for key, value in data.items()
|
||||||
if key not in _DOCUMENT_KNOWN_FIELDS
|
if key not in _DOCUMENT_KNOWN_FIELDS
|
||||||
}
|
}
|
||||||
self.coordinate_unit = str(data.get("coordinate_unit", data.get("unit", "auto"))).strip().lower()
|
self.coordinate_unit = str(data.get("coordinate_unit", data.get("unit", "auto")))
|
||||||
self.grid_step_mm = _positive_finite_float(data.get("grid_step_mm"), DEFAULT_GRID_STEP_MM)
|
|
||||||
points_data = data.get("leds")
|
points_data = data.get("leds")
|
||||||
self.collection_name = "leds"
|
self.collection_name = "leds"
|
||||||
if not isinstance(points_data, list):
|
if not isinstance(points_data, list):
|
||||||
@ -420,22 +191,7 @@ class MappingDocument:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
self._canonicalize_coordinate_unit()
|
|
||||||
comments_data = data.get("comments", [])
|
|
||||||
if not isinstance(comments_data, list):
|
|
||||||
raise ValueError("Поле comments должно содержать список комментариев.")
|
|
||||||
seen_comment_ids: set[str] = set()
|
|
||||||
for payload in comments_data:
|
|
||||||
if not isinstance(payload, dict):
|
|
||||||
raise ValueError("Комментарий должен быть объектом JSON.")
|
|
||||||
comment = TextComment.from_payload(payload)
|
|
||||||
if comment.id in seen_comment_ids:
|
|
||||||
comment.id = uuid.uuid4().hex
|
|
||||||
seen_comment_ids.add(comment.id)
|
|
||||||
self.comments.append(comment)
|
|
||||||
|
|
||||||
self._load_lines(data)
|
self._load_lines(data)
|
||||||
self._migrate_legacy_index_base(data)
|
|
||||||
self.background = BackgroundImage.from_payload(data.get("background"))
|
self.background = BackgroundImage.from_payload(data.get("background"))
|
||||||
self.unfolding = UnfoldingDescription.from_payload(data.get("unfolding"))
|
self.unfolding = UnfoldingDescription.from_payload(data.get("unfolding"))
|
||||||
self.unfolding.max_lines = MAX_LINES
|
self.unfolding.max_lines = MAX_LINES
|
||||||
@ -474,41 +230,6 @@ class MappingDocument:
|
|||||||
self.lines.append(line)
|
self.lines.append(line)
|
||||||
self._next_line_id = max(self._next_line_id, line_id + 1)
|
self._next_line_id = max(self._next_line_id, line_id + 1)
|
||||||
|
|
||||||
def _migrate_legacy_index_base(self, data: dict[str, Any]) -> None:
|
|
||||||
"""Однократно переводит старые 1-based ID, сохраняя физические адреса лент."""
|
|
||||||
marker = data.get("index_base")
|
|
||||||
if marker == 0:
|
|
||||||
return
|
|
||||||
if marker not in (None, 1):
|
|
||||||
raise ValueError("Unsupported mapping index_base; expected 0 or 1.")
|
|
||||||
identifiers = [line.id for line in self.lines]
|
|
||||||
identifiers.extend(point.line_id for point in self.points if point.line_id is not None)
|
|
||||||
if marker is None and (not identifiers or min(identifiers) == 0):
|
|
||||||
return
|
|
||||||
if identifiers and min(identifiers) < 1:
|
|
||||||
return
|
|
||||||
for line in self.lines:
|
|
||||||
old_id = line.id
|
|
||||||
line.id -= 1
|
|
||||||
if re.fullmatch(r"(?:Линия|Line)\s+\d+", line.name):
|
|
||||||
line.name = f"Линия {line.id}"
|
|
||||||
if line.color == default_color(old_id):
|
|
||||||
line.color = default_color(line.id)
|
|
||||||
for block in line.blocks:
|
|
||||||
block.id -= 1
|
|
||||||
if re.fullmatch(r"(?:Блок|Block)\s+\d+", block.name):
|
|
||||||
block.name = f"Блок {block.id}"
|
|
||||||
for point in self.points:
|
|
||||||
if point.line_id is not None:
|
|
||||||
point.line_id -= 1
|
|
||||||
if point.block_id is not None:
|
|
||||||
point.block_id -= 1
|
|
||||||
self._next_line_id = max((line.id for line in self.lines), default=-1) + 1
|
|
||||||
self._next_block_id = max(
|
|
||||||
(block.id for line in self.lines for block in line.blocks),
|
|
||||||
default=-1,
|
|
||||||
) + 1
|
|
||||||
|
|
||||||
def _rebuild_lines_from_points(self) -> None:
|
def _rebuild_lines_from_points(self) -> None:
|
||||||
for line_id in sorted({point.line_id for point in self.points if point.line_id is not None}):
|
for line_id in sorted({point.line_id for point in self.points if point.line_id is not None}):
|
||||||
line = LedLine(int(line_id), f"Line {line_id}", default_color(int(line_id)))
|
line = LedLine(int(line_id), f"Line {line_id}", default_color(int(line_id)))
|
||||||
@ -530,7 +251,7 @@ class MappingDocument:
|
|||||||
if point.line_id == line_id
|
if point.line_id == line_id
|
||||||
]
|
]
|
||||||
if ids:
|
if ids:
|
||||||
line.blocks.append(LedBlock(self._next_block_id, f"Блок {self._next_block_id}", ids))
|
line.blocks.append(LedBlock(self._next_block_id, "Block 1", ids))
|
||||||
self._next_block_id += 1
|
self._next_block_id += 1
|
||||||
for block_id in block_ids:
|
for block_id in block_ids:
|
||||||
ids = [
|
ids = [
|
||||||
@ -552,34 +273,9 @@ class MappingDocument:
|
|||||||
def save(self, path: str | Path) -> None:
|
def save(self, path: str | Path) -> None:
|
||||||
path = Path(path)
|
path = Path(path)
|
||||||
self.reindex_all()
|
self.reindex_all()
|
||||||
source_base_dir = self.path.parent if self.path is not None else path.parent
|
payload = self.to_payload()
|
||||||
background_for_save = self.background.with_embedded_image(source_base_dir)
|
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||||
payload = self.to_payload(background=background_for_save)
|
|
||||||
serialized = json.dumps(payload, ensure_ascii=False, indent=2, allow_nan=False)
|
|
||||||
if json.loads(serialized) != payload:
|
|
||||||
raise ValueError("Не удалось без потерь сериализовать схему.")
|
|
||||||
temporary_path: Path | None = None
|
|
||||||
try:
|
|
||||||
with tempfile.NamedTemporaryFile(
|
|
||||||
mode="w",
|
|
||||||
encoding="utf-8",
|
|
||||||
newline="\n",
|
|
||||||
dir=path.parent,
|
|
||||||
prefix=f".{path.name}.",
|
|
||||||
suffix=".tmp",
|
|
||||||
delete=False,
|
|
||||||
) as temporary_file:
|
|
||||||
temporary_file.write(serialized)
|
|
||||||
temporary_file.write("\n")
|
|
||||||
temporary_file.flush()
|
|
||||||
os.fsync(temporary_file.fileno())
|
|
||||||
temporary_path = Path(temporary_file.name)
|
|
||||||
os.replace(temporary_path, path)
|
|
||||||
finally:
|
|
||||||
if temporary_path is not None and temporary_path.exists():
|
|
||||||
temporary_path.unlink()
|
|
||||||
self.path = path
|
self.path = path
|
||||||
self.background = background_for_save
|
|
||||||
|
|
||||||
def to_payload(
|
def to_payload(
|
||||||
self,
|
self,
|
||||||
@ -587,7 +283,6 @@ class MappingDocument:
|
|||||||
point_payloads: list[dict[str, Any]] | None = None,
|
point_payloads: list[dict[str, Any]] | None = None,
|
||||||
lines_payload: list[dict[str, Any]] | None = None,
|
lines_payload: list[dict[str, Any]] | None = None,
|
||||||
collection_name: str | None = None,
|
collection_name: str | None = None,
|
||||||
background: BackgroundImage | None = None,
|
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
payload = dict(self.extra_payload)
|
payload = dict(self.extra_payload)
|
||||||
payload[collection_name or self.collection_name] = (
|
payload[collection_name or self.collection_name] = (
|
||||||
@ -597,11 +292,8 @@ class MappingDocument:
|
|||||||
)
|
)
|
||||||
payload["unfolding"] = self.describe_unfolding().to_payload()
|
payload["unfolding"] = self.describe_unfolding().to_payload()
|
||||||
payload["coordinate_unit"] = self._coordinate_unit_for_save()
|
payload["coordinate_unit"] = self._coordinate_unit_for_save()
|
||||||
payload["grid_step_mm"] = self.grid_step_mm
|
payload["background"] = self.background.to_payload()
|
||||||
payload["index_base"] = 0
|
|
||||||
payload["background"] = (self.background if background is None else background).to_payload()
|
|
||||||
payload["lines"] = self.lines_to_payload() if lines_payload is None else lines_payload
|
payload["lines"] = self.lines_to_payload() if lines_payload is None else lines_payload
|
||||||
payload["comments"] = [comment.to_payload() for comment in self.comments]
|
|
||||||
return payload
|
return payload
|
||||||
|
|
||||||
def point_to_payload(self, point: LedPoint, *, id_value: int | None = None) -> dict[str, Any]:
|
def point_to_payload(self, point: LedPoint, *, id_value: int | None = None) -> dict[str, Any]:
|
||||||
@ -645,32 +337,6 @@ class MappingDocument:
|
|||||||
for line in self.lines
|
for line in self.lines
|
||||||
]
|
]
|
||||||
|
|
||||||
def add_comment(self, text: str, x: float, y: float) -> TextComment:
|
|
||||||
text, x, y = TextComment.validate(text, x, y)
|
|
||||||
comment = TextComment(uuid.uuid4().hex, text, x, y)
|
|
||||||
self.comments.append(comment)
|
|
||||||
return comment
|
|
||||||
|
|
||||||
def get_comment(self, comment_id: str) -> TextComment:
|
|
||||||
for comment in self.comments:
|
|
||||||
if comment.id == comment_id:
|
|
||||||
return comment
|
|
||||||
raise KeyError(comment_id)
|
|
||||||
|
|
||||||
def update_comment(
|
|
||||||
self, comment_id: str, *, text: str | None = None,
|
|
||||||
x: float | None = None, y: float | None = None,
|
|
||||||
) -> None:
|
|
||||||
comment = self.get_comment(comment_id)
|
|
||||||
values = TextComment.validate(
|
|
||||||
comment.text if text is None else text,
|
|
||||||
comment.x if x is None else x, comment.y if y is None else y,
|
|
||||||
)
|
|
||||||
comment.text, comment.x, comment.y = values
|
|
||||||
|
|
||||||
def remove_comment(self, comment_id: str) -> None:
|
|
||||||
self.comments.remove(self.get_comment(comment_id))
|
|
||||||
|
|
||||||
def add_line(self) -> LedLine:
|
def add_line(self) -> LedLine:
|
||||||
line_limit = self._line_limit()
|
line_limit = self._line_limit()
|
||||||
if len(self.lines) >= line_limit:
|
if len(self.lines) >= line_limit:
|
||||||
@ -697,37 +363,6 @@ class MappingDocument:
|
|||||||
self.points.append(point)
|
self.points.append(point)
|
||||||
return point
|
return point
|
||||||
|
|
||||||
def add_point_copies(
|
|
||||||
self,
|
|
||||||
templates: list[LedPoint],
|
|
||||||
*,
|
|
||||||
offset_x: float,
|
|
||||||
offset_y: float,
|
|
||||||
) -> list[LedPoint]:
|
|
||||||
if not templates:
|
|
||||||
return []
|
|
||||||
next_source_id = max((point.source_id for point in self.points), default=-1) + 1
|
|
||||||
copies: list[LedPoint] = []
|
|
||||||
for template in list(templates):
|
|
||||||
x = float(template.x) + float(offset_x)
|
|
||||||
y = float(template.y) + float(offset_y)
|
|
||||||
row, col = self._grid_cell_for_coordinate(x, y)
|
|
||||||
point = LedPoint(
|
|
||||||
uid=len(self.points),
|
|
||||||
source_id=next_source_id,
|
|
||||||
x=x,
|
|
||||||
y=y,
|
|
||||||
row=row,
|
|
||||||
col=col,
|
|
||||||
coordinate_unit=self._coordinate_unit_for_save(),
|
|
||||||
manual=True,
|
|
||||||
extra_payload=deepcopy(template.extra_payload),
|
|
||||||
)
|
|
||||||
self.points.append(point)
|
|
||||||
copies.append(point)
|
|
||||||
next_source_id += 1
|
|
||||||
return copies
|
|
||||||
|
|
||||||
def update_point_position(self, point_id: int, x: float | None = None, y: float | None = None) -> None:
|
def update_point_position(self, point_id: int, x: float | None = None, y: float | None = None) -> None:
|
||||||
point = self.get_point(point_id)
|
point = self.get_point(point_id)
|
||||||
if x is not None:
|
if x is not None:
|
||||||
@ -768,7 +403,7 @@ class MappingDocument:
|
|||||||
point_id for point_id in point_ids if 0 <= point_id < len(self.points)
|
point_id for point_id in point_ids if 0 <= point_id < len(self.points)
|
||||||
])
|
])
|
||||||
self._detach_points_from_blocks(clean_point_ids)
|
self._detach_points_from_blocks(clean_point_ids)
|
||||||
block = LedBlock(len(line.blocks), f"Блок {len(line.blocks)}", clean_point_ids)
|
block = LedBlock(len(line.blocks) + 1, f"Блок {len(line.blocks) + 1}", clean_point_ids)
|
||||||
insert_index = len(line.blocks)
|
insert_index = len(line.blocks)
|
||||||
if after_block_id is not None:
|
if after_block_id is not None:
|
||||||
for index, existing_block in enumerate(line.blocks):
|
for index, existing_block in enumerate(line.blocks):
|
||||||
@ -862,36 +497,18 @@ class MappingDocument:
|
|||||||
return removed
|
return removed
|
||||||
|
|
||||||
def remove_block(self, line_id: int, block_id: int) -> int:
|
def remove_block(self, line_id: int, block_id: int) -> int:
|
||||||
return self.remove_blocks([(line_id, block_id)])
|
line = self.get_line(line_id)
|
||||||
|
|
||||||
def remove_blocks(self, block_keys: list[tuple[int, int]]) -> int:
|
|
||||||
target_keys = set(block_keys)
|
|
||||||
if not target_keys:
|
|
||||||
return 0
|
|
||||||
|
|
||||||
existing_keys = {
|
|
||||||
(line.id, block.id)
|
|
||||||
for line in self.lines
|
|
||||||
for block in line.blocks
|
|
||||||
}
|
|
||||||
missing_keys = target_keys - existing_keys
|
|
||||||
if missing_keys:
|
|
||||||
raise KeyError(f"Unknown block keys: {sorted(missing_keys)}")
|
|
||||||
|
|
||||||
removed_ids: list[int] = []
|
removed_ids: list[int] = []
|
||||||
for line in self.lines:
|
kept_blocks: list[LedBlock] = []
|
||||||
kept_blocks: list[LedBlock] = []
|
for block in line.blocks:
|
||||||
for block in line.blocks:
|
if block.id == block_id:
|
||||||
if (line.id, block.id) in target_keys:
|
removed_ids.extend(block.point_ids)
|
||||||
removed_ids.extend(block.point_ids)
|
else:
|
||||||
else:
|
kept_blocks.append(block)
|
||||||
kept_blocks.append(block)
|
line.blocks = kept_blocks
|
||||||
line.blocks = kept_blocks
|
self._clear_points(removed_ids)
|
||||||
|
|
||||||
unique_removed_ids = unique_in_order(removed_ids)
|
|
||||||
self._clear_points(unique_removed_ids)
|
|
||||||
self.reindex_all()
|
self.reindex_all()
|
||||||
return len(unique_removed_ids)
|
return len(removed_ids)
|
||||||
|
|
||||||
def remove_line(self, line_id: int) -> int:
|
def remove_line(self, line_id: int) -> int:
|
||||||
removed_ids: list[int] = []
|
removed_ids: list[int] = []
|
||||||
@ -912,26 +529,25 @@ class MappingDocument:
|
|||||||
assigned = sum(1 for point in self.points if point.line_id is not None or point.block_id is not None)
|
assigned = sum(1 for point in self.points if point.line_id is not None or point.block_id is not None)
|
||||||
self.lines.clear()
|
self.lines.clear()
|
||||||
self._clear_points([point.uid for point in self.points])
|
self._clear_points([point.uid for point in self.points])
|
||||||
self._next_line_id = 0
|
self._next_line_id = 1
|
||||||
self._next_block_id = 0
|
self._next_block_id = 1
|
||||||
return assigned
|
return assigned
|
||||||
|
|
||||||
def renumber_lines(self) -> None:
|
def renumber_lines(self) -> None:
|
||||||
self.order_lines_clockwise()
|
self.order_lines_clockwise()
|
||||||
id_map: dict[int, int] = {}
|
id_map: dict[int, int] = {}
|
||||||
for new_id, line in enumerate(self.lines):
|
for new_id, line in enumerate(self.lines, start=1):
|
||||||
old_id = line.id
|
old_id = line.id
|
||||||
id_map[old_id] = new_id
|
id_map[old_id] = new_id
|
||||||
line.id = new_id
|
line.id = new_id
|
||||||
if not line.name or re.match(r"^(Линия|Line)\s+\d+$", line.name):
|
line.name = f"Линия {new_id}"
|
||||||
line.name = f"Линия {new_id}"
|
|
||||||
line.color = default_color(new_id)
|
line.color = default_color(new_id)
|
||||||
|
|
||||||
for point in self.points:
|
for point in self.points:
|
||||||
if point.line_id in id_map:
|
if point.line_id in id_map:
|
||||||
point.line_id = id_map[point.line_id]
|
point.line_id = id_map[point.line_id]
|
||||||
|
|
||||||
self._next_line_id = len(self.lines)
|
self._next_line_id = len(self.lines) + 1
|
||||||
|
|
||||||
def _validate_line_limit(self) -> None:
|
def _validate_line_limit(self) -> None:
|
||||||
line_limit = self._line_limit()
|
line_limit = self._line_limit()
|
||||||
@ -946,23 +562,7 @@ class MappingDocument:
|
|||||||
return "m"
|
return "m"
|
||||||
if self.coordinate_unit in {"mm", "millimeter", "millimeters"}:
|
if self.coordinate_unit in {"mm", "millimeter", "millimeters"}:
|
||||||
return "mm"
|
return "mm"
|
||||||
self._canonicalize_coordinate_unit()
|
return "m" if coordinate_display_scale(self.points) == 1000.0 else "mm"
|
||||||
return self.coordinate_unit
|
|
||||||
|
|
||||||
def _canonicalize_coordinate_unit(self) -> None:
|
|
||||||
if self.coordinate_unit in {"m", "meter", "meters"}:
|
|
||||||
unit = "m"
|
|
||||||
elif self.coordinate_unit in {"mm", "millimeter", "millimeters"}:
|
|
||||||
unit = "mm"
|
|
||||||
else:
|
|
||||||
unit = "m" if self.points and coordinate_display_scale(self.points) == 1000.0 else "mm"
|
|
||||||
self.coordinate_unit = unit
|
|
||||||
for point in self.points:
|
|
||||||
point.coordinate_unit = unit
|
|
||||||
|
|
||||||
def grid_step_in_document_units(self) -> float:
|
|
||||||
scale = 1000.0 if self._coordinate_unit_for_save() == "m" else 1.0
|
|
||||||
return NominalGridDistance(self.grid_step_mm / scale, MAX_NEIGHBOR_TOLERANCE_MM / scale)
|
|
||||||
|
|
||||||
def _grid_cell_for_coordinate(self, x: float, y: float, *, exclude_uid: int | None = None) -> tuple[int, int]:
|
def _grid_cell_for_coordinate(self, x: float, y: float, *, exclude_uid: int | None = None) -> tuple[int, int]:
|
||||||
anchors = [point for point in self.points if point.uid != exclude_uid and not point.manual]
|
anchors = [point for point in self.points if point.uid != exclude_uid and not point.manual]
|
||||||
@ -970,7 +570,8 @@ class MappingDocument:
|
|||||||
anchors = [point for point in self.points if point.uid != exclude_uid]
|
anchors = [point for point in self.points if point.uid != exclude_uid]
|
||||||
if not anchors:
|
if not anchors:
|
||||||
return 0, 0
|
return 0, 0
|
||||||
step = self.grid_step_in_document_units()
|
scale = coordinate_display_scale(anchors)
|
||||||
|
step = MIN_NEIGHBOR_DISTANCE_MM / scale
|
||||||
row_axis, row_sign, col_axis, col_sign = infer_grid_coordinate_axes(anchors)
|
row_axis, row_sign, col_axis, col_sign = infer_grid_coordinate_axes(anchors)
|
||||||
source_row_value = x if row_axis == "x" else y
|
source_row_value = x if row_axis == "x" else y
|
||||||
source_col_value = x if col_axis == "x" else y
|
source_col_value = x if col_axis == "x" else y
|
||||||
@ -990,14 +591,7 @@ class MappingDocument:
|
|||||||
if reorder_leds:
|
if reorder_leds:
|
||||||
for block in line.blocks:
|
for block in line.blocks:
|
||||||
start_point_id = block.point_ids[0] if block.point_ids else None
|
start_point_id = block.point_ids[0] if block.point_ids else None
|
||||||
ordered_ids = [
|
ordered_ids = [point.uid for point in order_points_like_grid_svg(self._points_for_block(block), start_point_id)]
|
||||||
point.uid
|
|
||||||
for point in order_points_like_grid_svg(
|
|
||||||
self._points_for_block(block),
|
|
||||||
start_point_id,
|
|
||||||
min_neighbor_distance=self.grid_step_in_document_units(),
|
|
||||||
)
|
|
||||||
]
|
|
||||||
if start_point_id is not None:
|
if start_point_id is not None:
|
||||||
ordered_ids = rotate_ids_to_start(ordered_ids, start_point_id)
|
ordered_ids = rotate_ids_to_start(ordered_ids, start_point_id)
|
||||||
block.point_ids = ordered_ids
|
block.point_ids = ordered_ids
|
||||||
@ -1098,7 +692,7 @@ class MappingDocument:
|
|||||||
start_id = start_ids[0] if start_ids else point_ids[0]
|
start_id = start_ids[0] if start_ids else point_ids[0]
|
||||||
groups = self.route_groups_from_points(point_ids, start_id)
|
groups = self.route_groups_from_points(point_ids, start_id)
|
||||||
line.blocks.clear()
|
line.blocks.clear()
|
||||||
for block_number, group in enumerate(groups):
|
for block_number, group in enumerate(groups, start=1):
|
||||||
line.blocks.append(LedBlock(block_number, f"Блок {block_number}", group))
|
line.blocks.append(LedBlock(block_number, f"Блок {block_number}", group))
|
||||||
self.reindex_all()
|
self.reindex_all()
|
||||||
return len(groups)
|
return len(groups)
|
||||||
@ -1110,7 +704,7 @@ class MappingDocument:
|
|||||||
self._detach_points_from_blocks([point_id for group in groups for point_id in group])
|
self._detach_points_from_blocks([point_id for group in groups for point_id in group])
|
||||||
line = self.get_line(line_id)
|
line = self.get_line(line_id)
|
||||||
for group_ids in groups:
|
for group_ids in groups:
|
||||||
block_number = len(line.blocks)
|
block_number = len(line.blocks) + 1
|
||||||
block = LedBlock(block_number, f"Блок {block_number}", unique_in_order(group_ids))
|
block = LedBlock(block_number, f"Блок {block_number}", unique_in_order(group_ids))
|
||||||
line.blocks.append(block)
|
line.blocks.append(block)
|
||||||
self.order_blocks_clockwise(line_id, reorder_leds=False)
|
self.order_blocks_clockwise(line_id, reorder_leds=False)
|
||||||
@ -1124,11 +718,7 @@ class MappingDocument:
|
|||||||
]
|
]
|
||||||
return [
|
return [
|
||||||
[point.uid for point in route]
|
[point.uid for point in route]
|
||||||
for route in trace_route_paths_like_grid_svg(
|
for route in trace_route_paths_like_grid_svg(points, start_point_id)
|
||||||
points,
|
|
||||||
start_point_id,
|
|
||||||
min_neighbor_distance=self.grid_step_in_document_units(),
|
|
||||||
)
|
|
||||||
]
|
]
|
||||||
|
|
||||||
def add_clockwise_block_from_seed(self, line_id: int, start_point_id: int) -> LedBlock:
|
def add_clockwise_block_from_seed(self, line_id: int, start_point_id: int) -> LedBlock:
|
||||||
@ -1137,12 +727,6 @@ class MappingDocument:
|
|||||||
group_ids = self.clockwise_block_from_seed_preview(start_point_id)
|
group_ids = self.clockwise_block_from_seed_preview(start_point_id)
|
||||||
return self.add_clockwise_block_from_group(line_id, start_point_id, group_ids)
|
return self.add_clockwise_block_from_group(line_id, start_point_id, group_ids)
|
||||||
|
|
||||||
def add_counterclockwise_block_from_seed(self, line_id: int, start_point_id: int) -> LedBlock:
|
|
||||||
if not 0 <= start_point_id < len(self.points):
|
|
||||||
raise ValueError(f"Unknown LED point id: {start_point_id}")
|
|
||||||
group_ids = self.counterclockwise_block_from_seed_preview(start_point_id)
|
|
||||||
return self.add_clockwise_block_from_group(line_id, start_point_id, group_ids)
|
|
||||||
|
|
||||||
def add_clockwise_block_from_group(self, line_id: int, start_point_id: int, group_ids: list[int]) -> LedBlock:
|
def add_clockwise_block_from_group(self, line_id: int, start_point_id: int, group_ids: list[int]) -> LedBlock:
|
||||||
if not 0 <= start_point_id < len(self.points):
|
if not 0 <= start_point_id < len(self.points):
|
||||||
raise ValueError(f"Unknown LED point id: {start_point_id}")
|
raise ValueError(f"Unknown LED point id: {start_point_id}")
|
||||||
@ -1152,12 +736,6 @@ class MappingDocument:
|
|||||||
return block
|
return block
|
||||||
|
|
||||||
def clockwise_block_from_seed_preview(self, start_point_id: int) -> list[int]:
|
def clockwise_block_from_seed_preview(self, start_point_id: int) -> list[int]:
|
||||||
return self.route_block_from_seed_preview(start_point_id, direction="clockwise")
|
|
||||||
|
|
||||||
def counterclockwise_block_from_seed_preview(self, start_point_id: int) -> list[int]:
|
|
||||||
return self.route_block_from_seed_preview(start_point_id, direction="counterclockwise")
|
|
||||||
|
|
||||||
def route_block_from_seed_preview(self, start_point_id: int, *, direction: str = "clockwise") -> list[int]:
|
|
||||||
if not 0 <= start_point_id < len(self.points):
|
if not 0 <= start_point_id < len(self.points):
|
||||||
return []
|
return []
|
||||||
candidate_points = [
|
candidate_points = [
|
||||||
@ -1165,7 +743,7 @@ class MappingDocument:
|
|||||||
for point in self.points
|
for point in self.points
|
||||||
if point.uid == start_point_id or (point.line_id is None and point.block_id is None)
|
if point.uid == start_point_id or (point.line_id is None and point.block_id is None)
|
||||||
]
|
]
|
||||||
threshold = self.grid_step_in_document_units()
|
threshold = min_neighbor_distance_for_points(candidate_points)
|
||||||
adjacency = build_route_adjacency(candidate_points, threshold)
|
adjacency = build_route_adjacency(candidate_points, threshold)
|
||||||
route = trace_single_route_like_grid_svg(
|
route = trace_single_route_like_grid_svg(
|
||||||
candidate_points,
|
candidate_points,
|
||||||
@ -1173,12 +751,11 @@ class MappingDocument:
|
|||||||
adjacency=adjacency,
|
adjacency=adjacency,
|
||||||
allowed_ids={point.uid for point in candidate_points},
|
allowed_ids={point.uid for point in candidate_points},
|
||||||
min_neighbor_distance=threshold,
|
min_neighbor_distance=threshold,
|
||||||
direction=direction,
|
|
||||||
)
|
)
|
||||||
if not route:
|
if not route:
|
||||||
return [start_point_id]
|
return [start_point_id]
|
||||||
return rotate_ids_to_start(
|
return rotate_ids_to_start(
|
||||||
[point.uid for point in normalize_route_direction(route, threshold, direction=direction)],
|
[point.uid for point in normalize_route_clockwise(route, threshold)],
|
||||||
start_point_id,
|
start_point_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -1190,10 +767,7 @@ class MappingDocument:
|
|||||||
]
|
]
|
||||||
return [
|
return [
|
||||||
[point.uid for point in route]
|
[point.uid for point in route]
|
||||||
for route in trace_route_paths_like_grid_svg(
|
for route in trace_route_paths_like_grid_svg(points)
|
||||||
points,
|
|
||||||
min_neighbor_distance=self.grid_step_in_document_units(),
|
|
||||||
)
|
|
||||||
]
|
]
|
||||||
|
|
||||||
def reindex_all(self) -> None:
|
def reindex_all(self) -> None:
|
||||||
@ -1220,10 +794,9 @@ class MappingDocument:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def renumber_blocks(line: LedLine) -> None:
|
def renumber_blocks(line: LedLine) -> None:
|
||||||
for block_number, block in enumerate(line.blocks):
|
for block_number, block in enumerate(line.blocks, start=1):
|
||||||
block.id = block_number
|
block.id = block_number
|
||||||
if not block.name or re.match(r"^(Блок|Block)\s+\d+$", block.name):
|
block.name = f"Блок {block_number}"
|
||||||
block.name = f"Блок {block_number}"
|
|
||||||
|
|
||||||
|
|
||||||
def sorted_unique(values: list[int]) -> list[int]:
|
def sorted_unique(values: list[int]) -> list[int]:
|
||||||
@ -1249,23 +822,11 @@ def rotate_ids_to_start(values: list[int], start_value: int) -> list[int]:
|
|||||||
|
|
||||||
|
|
||||||
def normalize_route_clockwise(route: list[LedPoint], min_neighbor_distance: float) -> list[LedPoint]:
|
def normalize_route_clockwise(route: list[LedPoint], min_neighbor_distance: float) -> list[LedPoint]:
|
||||||
return normalize_route_direction(route, min_neighbor_distance, direction="clockwise")
|
|
||||||
|
|
||||||
|
|
||||||
def normalize_route_direction(
|
|
||||||
route: list[LedPoint],
|
|
||||||
min_neighbor_distance: float,
|
|
||||||
*,
|
|
||||||
direction: str = "clockwise",
|
|
||||||
) -> list[LedPoint]:
|
|
||||||
if len(route) < 3:
|
if len(route) < 3:
|
||||||
return route[:]
|
return route[:]
|
||||||
if not is_valid_route_neighbor(route[-1], route[0], min_neighbor_distance):
|
if not is_valid_route_neighbor(route[-1], route[0], min_neighbor_distance):
|
||||||
return route[:]
|
return route[:]
|
||||||
signed_area = route_signed_area(route)
|
return list(reversed(route)) if route_signed_area(route) > 0 else route[:]
|
||||||
if direction == "counterclockwise":
|
|
||||||
return list(reversed(route)) if signed_area < 0 else route[:]
|
|
||||||
return list(reversed(route)) if signed_area > 0 else route[:]
|
|
||||||
|
|
||||||
|
|
||||||
def route_signed_area(route: list[LedPoint]) -> float:
|
def route_signed_area(route: list[LedPoint]) -> float:
|
||||||
@ -1286,13 +847,6 @@ def _optional_float(value: Any) -> float | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _positive_finite_float(value: Any, fallback: float) -> float:
|
|
||||||
parsed = _optional_float(value)
|
|
||||||
if parsed is None or not math.isfinite(parsed) or parsed <= 0.0:
|
|
||||||
return fallback
|
|
||||||
return min(1000.0, max(1.0, parsed))
|
|
||||||
|
|
||||||
|
|
||||||
def infer_grid_coordinate_axes(points: list[LedPoint]) -> tuple[str, int, str, int]:
|
def infer_grid_coordinate_axes(points: list[LedPoint]) -> tuple[str, int, str, int]:
|
||||||
row_x = _axis_correlation(points, "row", "x")
|
row_x = _axis_correlation(points, "row", "x")
|
||||||
row_y = _axis_correlation(points, "row", "y")
|
row_y = _axis_correlation(points, "row", "y")
|
||||||
@ -1329,7 +883,7 @@ def _correlation_sign(value: float) -> int:
|
|||||||
|
|
||||||
def default_color(line_id: int) -> str:
|
def default_color(line_id: int) -> str:
|
||||||
colors = ["#e11d48", "#2563eb", "#16a34a", "#f59e0b", "#7c3aed", "#0891b2"]
|
colors = ["#e11d48", "#2563eb", "#16a34a", "#f59e0b", "#7c3aed", "#0891b2"]
|
||||||
return colors[line_id % len(colors)]
|
return colors[(line_id - 1) % len(colors)]
|
||||||
|
|
||||||
|
|
||||||
def distance(a: LedPoint, b: LedPoint) -> float:
|
def distance(a: LedPoint, b: LedPoint) -> float:
|
||||||
@ -1393,10 +947,7 @@ def contour_groups_like_grid_svg(points: list[LedPoint]) -> list[list[LedPoint]]
|
|||||||
return sorted(groups, key=lambda group: min(point_sort_key_for_model(point) for point in group))
|
return sorted(groups, key=lambda group: min(point_sort_key_for_model(point) for point in group))
|
||||||
|
|
||||||
|
|
||||||
def route_groups_like_grid_svg(
|
def route_groups_like_grid_svg(points: list[LedPoint]) -> list[list[LedPoint]]:
|
||||||
points: list[LedPoint],
|
|
||||||
min_neighbor_distance: float | None = None,
|
|
||||||
) -> list[list[LedPoint]]:
|
|
||||||
points_by_cell: dict[tuple[int, int], list[LedPoint]] = {}
|
points_by_cell: dict[tuple[int, int], list[LedPoint]] = {}
|
||||||
for point in points:
|
for point in points:
|
||||||
points_by_cell.setdefault((point.row, point.col), []).append(point)
|
points_by_cell.setdefault((point.row, point.col), []).append(point)
|
||||||
@ -1405,7 +956,7 @@ def route_groups_like_grid_svg(
|
|||||||
seen: set[tuple[int, int]] = set()
|
seen: set[tuple[int, int]] = set()
|
||||||
groups: list[list[LedPoint]] = []
|
groups: list[list[LedPoint]] = []
|
||||||
neighbors = ((1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, 1), (-1, -1), (1, -1))
|
neighbors = ((1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, 1), (-1, -1), (1, -1))
|
||||||
threshold = min_neighbor_distance or min_neighbor_distance_for_points(points)
|
threshold = min_neighbor_distance_for_points(points)
|
||||||
|
|
||||||
for start_cell in sorted(cells):
|
for start_cell in sorted(cells):
|
||||||
if start_cell in seen:
|
if start_cell in seen:
|
||||||
@ -1459,15 +1010,10 @@ def order_group_nearest(points: list[LedPoint]) -> list[LedPoint]:
|
|||||||
return ordered
|
return ordered
|
||||||
|
|
||||||
|
|
||||||
def order_points_like_grid_svg(
|
def order_points_like_grid_svg(points: list[LedPoint], start_point_id: int | None = None) -> list[LedPoint]:
|
||||||
points: list[LedPoint],
|
|
||||||
start_point_id: int | None = None,
|
|
||||||
*,
|
|
||||||
min_neighbor_distance: float | None = None,
|
|
||||||
) -> list[LedPoint]:
|
|
||||||
if len(points) <= 1:
|
if len(points) <= 1:
|
||||||
return points[:]
|
return points[:]
|
||||||
min_neighbor_distance = min_neighbor_distance or min_neighbor_distance_for_points(points)
|
min_neighbor_distance = min_neighbor_distance_for_points(points)
|
||||||
remaining = points[:]
|
remaining = points[:]
|
||||||
if start_point_id is None:
|
if start_point_id is None:
|
||||||
start_point = min(remaining, key=point_sort_key_for_model)
|
start_point = min(remaining, key=point_sort_key_for_model)
|
||||||
@ -1507,14 +1053,12 @@ def order_points_like_grid_svg(
|
|||||||
def trace_route_paths_like_grid_svg(
|
def trace_route_paths_like_grid_svg(
|
||||||
points: list[LedPoint],
|
points: list[LedPoint],
|
||||||
start_point_id: int | None = None,
|
start_point_id: int | None = None,
|
||||||
*,
|
|
||||||
min_neighbor_distance: float | None = None,
|
|
||||||
) -> list[list[LedPoint]]:
|
) -> list[list[LedPoint]]:
|
||||||
remaining = points[:]
|
remaining = points[:]
|
||||||
remaining_ids = {point.uid for point in remaining}
|
remaining_ids = {point.uid for point in remaining}
|
||||||
routes: list[list[LedPoint]] = []
|
routes: list[list[LedPoint]] = []
|
||||||
preferred_start_id = start_point_id
|
preferred_start_id = start_point_id
|
||||||
min_neighbor_distance = min_neighbor_distance or min_neighbor_distance_for_points(points)
|
min_neighbor_distance = min_neighbor_distance_for_points(points)
|
||||||
while remaining:
|
while remaining:
|
||||||
if preferred_start_id is not None:
|
if preferred_start_id is not None:
|
||||||
start_point = next((point for point in remaining if point.uid == preferred_start_id), None)
|
start_point = next((point for point in remaining if point.uid == preferred_start_id), None)
|
||||||
@ -1546,7 +1090,6 @@ def trace_single_route_like_grid_svg(
|
|||||||
adjacency: dict[int, list[LedPoint]] | None = None,
|
adjacency: dict[int, list[LedPoint]] | None = None,
|
||||||
allowed_ids: set[int] | None = None,
|
allowed_ids: set[int] | None = None,
|
||||||
min_neighbor_distance: float | None = None,
|
min_neighbor_distance: float | None = None,
|
||||||
direction: str = "clockwise",
|
|
||||||
) -> list[LedPoint]:
|
) -> list[LedPoint]:
|
||||||
if not points:
|
if not points:
|
||||||
return []
|
return []
|
||||||
@ -1578,7 +1121,7 @@ def trace_single_route_like_grid_svg(
|
|||||||
)
|
)
|
||||||
if not neighbors:
|
if not neighbors:
|
||||||
break
|
break
|
||||||
next_point = choose_next_route_point(route, neighbors, min_neighbor_distance, direction=direction)
|
next_point = choose_next_route_point(route, neighbors, min_neighbor_distance)
|
||||||
route.append(next_point)
|
route.append(next_point)
|
||||||
remaining.remove(next_point)
|
remaining.remove(next_point)
|
||||||
remaining_ids.remove(next_point.uid)
|
remaining_ids.remove(next_point.uid)
|
||||||
@ -1613,11 +1156,9 @@ def choose_next_route_point(
|
|||||||
route: list[LedPoint],
|
route: list[LedPoint],
|
||||||
neighbors: list[LedPoint],
|
neighbors: list[LedPoint],
|
||||||
min_neighbor_distance: float,
|
min_neighbor_distance: float,
|
||||||
*,
|
|
||||||
direction: str = "clockwise",
|
|
||||||
) -> LedPoint:
|
) -> LedPoint:
|
||||||
if len(route) < 2:
|
if len(route) < 2:
|
||||||
return min(neighbors, key=lambda point: route_path_preference(route, point, min_neighbor_distance, direction=direction))
|
return min(neighbors, key=lambda point: route_path_preference(route, point, min_neighbor_distance))
|
||||||
|
|
||||||
neighbors = nearest_neighbor_band(route[-1], neighbors, min_neighbor_distance)
|
neighbors = nearest_neighbor_band(route[-1], neighbors, min_neighbor_distance)
|
||||||
previous = route[-2]
|
previous = route[-2]
|
||||||
@ -1628,10 +1169,7 @@ def choose_next_route_point(
|
|||||||
if same_direction_vector(previous, current, point)
|
if same_direction_vector(previous, current, point)
|
||||||
]
|
]
|
||||||
if same_vector_direction:
|
if same_vector_direction:
|
||||||
return min(
|
return min(same_vector_direction, key=lambda point: route_path_preference(route, point, min_neighbor_distance))
|
||||||
same_vector_direction,
|
|
||||||
key=lambda point: route_path_preference(route, point, min_neighbor_distance, direction=direction),
|
|
||||||
)
|
|
||||||
|
|
||||||
forward_direction = [
|
forward_direction = [
|
||||||
point
|
point
|
||||||
@ -1639,12 +1177,9 @@ def choose_next_route_point(
|
|||||||
if forward_direction_vector(previous, current, point)
|
if forward_direction_vector(previous, current, point)
|
||||||
]
|
]
|
||||||
if forward_direction:
|
if forward_direction:
|
||||||
return min(
|
return min(forward_direction, key=lambda point: route_path_preference(route, point, min_neighbor_distance))
|
||||||
forward_direction,
|
|
||||||
key=lambda point: route_path_preference(route, point, min_neighbor_distance, direction=direction),
|
|
||||||
)
|
|
||||||
|
|
||||||
return min(neighbors, key=lambda point: route_path_preference(route, point, min_neighbor_distance, direction=direction))
|
return min(neighbors, key=lambda point: route_path_preference(route, point, min_neighbor_distance))
|
||||||
|
|
||||||
|
|
||||||
def nearest_neighbor_band(
|
def nearest_neighbor_band(
|
||||||
@ -1908,8 +1443,6 @@ def route_path_preference(
|
|||||||
route: list[LedPoint],
|
route: list[LedPoint],
|
||||||
candidate: LedPoint,
|
candidate: LedPoint,
|
||||||
min_distance: float,
|
min_distance: float,
|
||||||
*,
|
|
||||||
direction: str = "clockwise",
|
|
||||||
) -> tuple[int, float, int, int, float, tuple[int, int, float, float, int]]:
|
) -> tuple[int, float, int, int, float, tuple[int, int, float, float, int]]:
|
||||||
current = route[-1]
|
current = route[-1]
|
||||||
if len(route) < 2:
|
if len(route) < 2:
|
||||||
@ -1924,7 +1457,7 @@ def route_path_preference(
|
|||||||
)
|
)
|
||||||
|
|
||||||
previous = route[-2]
|
previous = route[-2]
|
||||||
turn_class, turn_rank = route_turn_preference(previous, current, candidate, direction=direction)
|
turn_class, turn_rank = route_clockwise_turn_preference(previous, current, candidate)
|
||||||
return (
|
return (
|
||||||
turn_class,
|
turn_class,
|
||||||
turn_rank,
|
turn_rank,
|
||||||
@ -1937,16 +1470,6 @@ def route_path_preference(
|
|||||||
|
|
||||||
|
|
||||||
def route_clockwise_turn_preference(previous: LedPoint, current: LedPoint, candidate: LedPoint) -> tuple[int, float]:
|
def route_clockwise_turn_preference(previous: LedPoint, current: LedPoint, candidate: LedPoint) -> tuple[int, float]:
|
||||||
return route_turn_preference(previous, current, candidate, direction="clockwise")
|
|
||||||
|
|
||||||
|
|
||||||
def route_turn_preference(
|
|
||||||
previous: LedPoint,
|
|
||||||
current: LedPoint,
|
|
||||||
candidate: LedPoint,
|
|
||||||
*,
|
|
||||||
direction: str = "clockwise",
|
|
||||||
) -> tuple[int, float]:
|
|
||||||
incoming_x = current.x - previous.x
|
incoming_x = current.x - previous.x
|
||||||
incoming_y = current.y - previous.y
|
incoming_y = current.y - previous.y
|
||||||
outgoing_x = candidate.x - current.x
|
outgoing_x = candidate.x - current.x
|
||||||
@ -1958,10 +1481,6 @@ def route_turn_preference(
|
|||||||
return 0, 0.0
|
return 0, 0.0
|
||||||
if angle < math.radians(35):
|
if angle < math.radians(35):
|
||||||
return 0, angle
|
return 0, angle
|
||||||
if direction == "counterclockwise":
|
|
||||||
if cross > epsilon:
|
|
||||||
return 1, -angle
|
|
||||||
return 2, angle
|
|
||||||
if cross < -epsilon:
|
if cross < -epsilon:
|
||||||
return 1, -angle
|
return 1, -angle
|
||||||
return 2, angle
|
return 2, angle
|
||||||
@ -2018,15 +1537,11 @@ def max_neighbor_distance(nominal_distance: float) -> float:
|
|||||||
|
|
||||||
|
|
||||||
def neighbor_tolerance(nominal_distance: float) -> float:
|
def neighbor_tolerance(nominal_distance: float) -> float:
|
||||||
explicit_tolerance = getattr(nominal_distance, "tolerance", None)
|
|
||||||
if explicit_tolerance is not None:
|
|
||||||
return float(explicit_tolerance)
|
|
||||||
return MAX_NEIGHBOR_TOLERANCE_MM / (MIN_NEIGHBOR_DISTANCE_MM / nominal_distance)
|
return MAX_NEIGHBOR_TOLERANCE_MM / (MIN_NEIGHBOR_DISTANCE_MM / nominal_distance)
|
||||||
|
|
||||||
|
|
||||||
def min_neighbor_distance_for_points(points: list[LedPoint]) -> float:
|
def min_neighbor_distance_for_points(points: list[LedPoint]) -> float:
|
||||||
scale = coordinate_display_scale(points)
|
return MIN_NEIGHBOR_DISTANCE_MM / coordinate_display_scale(points)
|
||||||
return NominalGridDistance(MIN_NEIGHBOR_DISTANCE_MM / scale, MAX_NEIGHBOR_TOLERANCE_MM / scale)
|
|
||||||
|
|
||||||
|
|
||||||
def coordinate_display_scale(points: list[LedPoint]) -> float:
|
def coordinate_display_scale(points: list[LedPoint]) -> float:
|
||||||
|
|||||||
@ -11,20 +11,20 @@ from typing import Iterable
|
|||||||
try:
|
try:
|
||||||
from .models import (
|
from .models import (
|
||||||
LedPoint,
|
LedPoint,
|
||||||
MAX_NEIGHBOR_TOLERANCE_MM,
|
|
||||||
MappingDocument,
|
MappingDocument,
|
||||||
contour_groups_like_grid_svg as route_groups_like_grid_svg,
|
contour_groups_like_grid_svg as route_groups_like_grid_svg,
|
||||||
coordinate_display_scale,
|
coordinate_display_scale,
|
||||||
|
min_neighbor_distance_for_points,
|
||||||
normalize_route_clockwise,
|
normalize_route_clockwise,
|
||||||
order_points_like_grid_svg,
|
order_points_like_grid_svg,
|
||||||
)
|
)
|
||||||
except ImportError:
|
except ImportError:
|
||||||
from models import (
|
from models import (
|
||||||
LedPoint,
|
LedPoint,
|
||||||
MAX_NEIGHBOR_TOLERANCE_MM,
|
|
||||||
MappingDocument,
|
MappingDocument,
|
||||||
contour_groups_like_grid_svg as route_groups_like_grid_svg,
|
contour_groups_like_grid_svg as route_groups_like_grid_svg,
|
||||||
coordinate_display_scale,
|
coordinate_display_scale,
|
||||||
|
min_neighbor_distance_for_points,
|
||||||
normalize_route_clockwise,
|
normalize_route_clockwise,
|
||||||
order_points_like_grid_svg,
|
order_points_like_grid_svg,
|
||||||
)
|
)
|
||||||
@ -36,7 +36,6 @@ MAX_LEDS_PER_CELL = 3
|
|||||||
NUM_STRIPS = 4
|
NUM_STRIPS = 4
|
||||||
EMPTY_STRIP = "0xFF"
|
EMPTY_STRIP = "0xFF"
|
||||||
EMPTY_LED = "0xFFFF"
|
EMPTY_LED = "0xFFFF"
|
||||||
OBSOLETE_LEGACY_FILENAME = "virtual_matrix_legacy.ino.txt"
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@ -70,72 +69,7 @@ class BuildResult:
|
|||||||
unassigned_count: int
|
unassigned_count: int
|
||||||
|
|
||||||
|
|
||||||
def remove_obsolete_legacy_output(output_dir: Path) -> None:
|
def generate_panel_mapping_from_document(document: MappingDocument, output_dir: str | Path) -> BuildResult:
|
||||||
"""Удалить только legacy-файл, созданный прежними версиями генератора."""
|
|
||||||
legacy_path = output_dir / OBSOLETE_LEGACY_FILENAME
|
|
||||||
if legacy_path.is_file() or legacy_path.is_symlink():
|
|
||||||
legacy_path.unlink()
|
|
||||||
|
|
||||||
|
|
||||||
def cpp_float_literal(value: float) -> str:
|
|
||||||
text = format(float(value), ".9g")
|
|
||||||
if "." not in text and "e" not in text.lower():
|
|
||||||
text += ".0"
|
|
||||||
return f"{text}f"
|
|
||||||
|
|
||||||
|
|
||||||
def sanitize_cpp_identifier(name: str) -> str:
|
|
||||||
# Transliteration dictionary for Russian Cyrillic
|
|
||||||
cyrillic_translit = {
|
|
||||||
'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'е': 'e', 'ё': 'yo',
|
|
||||||
'ж': 'zh', 'з': 'z', 'и': 'i', 'й': 'y', 'к': 'k', 'л': 'l', 'м': 'm',
|
|
||||||
'н': 'n', 'о': 'o', 'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u',
|
|
||||||
'ф': 'f', 'х': 'kh', 'ц': 'ts', 'ч': 'ch', 'ш': 'sh', 'щ': 'shch',
|
|
||||||
'ы': 'y', 'э': 'e', 'ю': 'yu', 'я': 'ya',
|
|
||||||
'А': 'A', 'Б': 'B', 'В': 'V', 'Г': 'G', 'Д': 'D', 'Е': 'E', 'Ё': 'Yo',
|
|
||||||
'Ж': 'Zh', 'З': 'Z', 'И': 'I', 'Й': 'Y', 'К': 'K', 'Л': 'L', 'М': 'M',
|
|
||||||
'Н': 'N', 'О': 'O', 'П': 'P', 'Р': 'R', 'С': 'S', 'Т': 'T', 'У': 'U',
|
|
||||||
'Ф': 'F', 'Х': 'Kh', 'Ц': 'Ts', 'Ч': 'Ch', 'Ш': 'Sh', 'Щ': 'Shch',
|
|
||||||
'Ы': 'Y', 'Э': 'E', 'Ю': 'Yu', 'Я': 'Ya',
|
|
||||||
'ь': '', 'Ь': '', 'ъ': '', 'Ъ': ''
|
|
||||||
}
|
|
||||||
|
|
||||||
# Transliterate Cyrillic to Latin
|
|
||||||
transliterated = "".join(cyrillic_translit.get(c, c) for c in name)
|
|
||||||
|
|
||||||
# Replace non-alphanumeric chars with underscore
|
|
||||||
sanitized = ""
|
|
||||||
for c in transliterated:
|
|
||||||
if c.isalnum() or c == '_':
|
|
||||||
sanitized += c
|
|
||||||
else:
|
|
||||||
sanitized += '_'
|
|
||||||
|
|
||||||
# Remove multiple consecutive underscores
|
|
||||||
while "__" in sanitized:
|
|
||||||
sanitized = sanitized.replace("__", "_")
|
|
||||||
|
|
||||||
# Strip leading/trailing underscores
|
|
||||||
sanitized = sanitized.strip("_")
|
|
||||||
|
|
||||||
# Prepend underscore if starts with a digit
|
|
||||||
if sanitized and sanitized[0].isdigit():
|
|
||||||
sanitized = "_" + sanitized
|
|
||||||
|
|
||||||
# If empty, return a default prefix
|
|
||||||
if not sanitized:
|
|
||||||
sanitized = "BLOCK"
|
|
||||||
|
|
||||||
return sanitized
|
|
||||||
|
|
||||||
|
|
||||||
def generate_panel_mapping_from_document(
|
|
||||||
document: MappingDocument,
|
|
||||||
output_dir: str | Path,
|
|
||||||
*,
|
|
||||||
generate_grid: bool = True,
|
|
||||||
generate_blocks: bool = False,
|
|
||||||
) -> BuildResult:
|
|
||||||
if not document.points:
|
if not document.points:
|
||||||
raise ValueError("Нет точек для генерации скрипта.")
|
raise ValueError("Нет точек для генерации скрипта.")
|
||||||
|
|
||||||
@ -148,26 +82,20 @@ def generate_panel_mapping_from_document(
|
|||||||
raise ValueError("Нет назначенных LED: перед генерацией распределите точки по линиям.")
|
raise ValueError("Нет назначенных LED: перед генерацией распределите точки по линиям.")
|
||||||
cells = build_cells(mapping_points)
|
cells = build_cells(mapping_points)
|
||||||
block_count = sum(len(line.blocks) for line in document.lines)
|
block_count = sum(len(line.blocks) for line in document.lines)
|
||||||
|
|
||||||
generated_files = {
|
generated_files = {
|
||||||
"vm_map": output_dir / "vm_map.h",
|
"vm_map": output_dir / "vm_map.h",
|
||||||
|
"legacy_ino": output_dir / "virtual_matrix_legacy.ino.txt",
|
||||||
"ordered_json": output_dir / "ordered_circles.json",
|
"ordered_json": output_dir / "ordered_circles.json",
|
||||||
"validation_report": output_dir / "validation_report.txt",
|
"validation_report": output_dir / "validation_report.txt",
|
||||||
"readme": output_dir / "README.md",
|
"readme": output_dir / "README.md",
|
||||||
}
|
}
|
||||||
|
|
||||||
write_vm_map_header(
|
write_vm_map_header(generated_files["vm_map"], points, mapping_points, cells, block_count)
|
||||||
generated_files["vm_map"],
|
write_legacy_ino(generated_files["legacy_ino"], mapping_points, cells)
|
||||||
points,
|
|
||||||
mapping_points,
|
|
||||||
cells,
|
|
||||||
document,
|
|
||||||
generate_grid=generate_grid,
|
|
||||||
generate_blocks=generate_blocks,
|
|
||||||
)
|
|
||||||
write_ordered_json(generated_files["ordered_json"], points, document)
|
write_ordered_json(generated_files["ordered_json"], points, document)
|
||||||
write_validation_report(generated_files["validation_report"], points, document.grid_step_mm)
|
write_validation_report(generated_files["validation_report"], points)
|
||||||
write_readme(generated_files["readme"])
|
write_readme(generated_files["readme"])
|
||||||
remove_obsolete_legacy_output(output_dir)
|
|
||||||
|
|
||||||
vm_rows, vm_cols, grid_rows, grid_cols = get_dimensions(points)
|
vm_rows, vm_cols, grid_rows, grid_cols = get_dimensions(points)
|
||||||
return BuildResult(
|
return BuildResult(
|
||||||
@ -188,14 +116,10 @@ def generate_panel_mapping_from_document(
|
|||||||
def normalize_document_points(document: MappingDocument) -> list[PanelLedPoint]:
|
def normalize_document_points(document: MappingDocument) -> list[PanelLedPoint]:
|
||||||
scale = _coordinate_scale_to_mm(document)
|
scale = _coordinate_scale_to_mm(document)
|
||||||
route_groups = route_groups_like_grid_svg(document.points)
|
route_groups = route_groups_like_grid_svg(document.points)
|
||||||
min_neighbor_distance = document.grid_step_in_document_units()
|
|
||||||
ordered: list[tuple[LedPoint, int]] = []
|
ordered: list[tuple[LedPoint, int]] = []
|
||||||
for route_group_index, route_group in enumerate(route_groups, start=1):
|
for route_group_index, route_group in enumerate(route_groups, start=1):
|
||||||
route = order_points_like_grid_svg(
|
route = order_points_like_grid_svg(route_group)
|
||||||
route_group,
|
route = normalize_route_clockwise(route, min_neighbor_distance_for_points(route))
|
||||||
min_neighbor_distance=min_neighbor_distance,
|
|
||||||
)
|
|
||||||
route = normalize_route_clockwise(route, min_neighbor_distance)
|
|
||||||
ordered.extend((point, route_group_index) for point in route)
|
ordered.extend((point, route_group_index) for point in route)
|
||||||
|
|
||||||
min_row = min(point.row for point, _group in ordered)
|
min_row = min(point.row for point, _group in ordered)
|
||||||
@ -205,7 +129,7 @@ def normalize_document_points(document: MappingDocument) -> list[PanelLedPoint]:
|
|||||||
generated_id=index,
|
generated_id=index,
|
||||||
source_id=point.source_id,
|
source_id=point.source_id,
|
||||||
input_index=point.uid,
|
input_index=point.uid,
|
||||||
strip=point.line_id,
|
strip=(point.line_id - 1) if point.line_id is not None else None,
|
||||||
led_id=point.line_index,
|
led_id=point.line_index,
|
||||||
x_mm=point.x * scale,
|
x_mm=point.x * scale,
|
||||||
y_mm=point.y * scale,
|
y_mm=point.y * scale,
|
||||||
@ -256,35 +180,12 @@ def write_vm_map_header(
|
|||||||
all_points: list[PanelLedPoint],
|
all_points: list[PanelLedPoint],
|
||||||
mapping_points: list[PanelLedPoint],
|
mapping_points: list[PanelLedPoint],
|
||||||
cells: dict[tuple[int, int], list[PanelLedPoint]],
|
cells: dict[tuple[int, int], list[PanelLedPoint]],
|
||||||
document: MappingDocument,
|
block_count: int,
|
||||||
generate_grid: bool = True,
|
|
||||||
generate_blocks: bool = False,
|
|
||||||
) -> None:
|
) -> None:
|
||||||
vm_rows, vm_cols, grid_rows, grid_cols = get_dimensions(all_points)
|
vm_rows, vm_cols, grid_rows, grid_cols = get_dimensions(all_points)
|
||||||
min_row, max_row, min_col, max_col = get_source_bounds(all_points)
|
min_row, max_row, min_col, max_col = get_source_bounds(all_points)
|
||||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
# Collect blocks info
|
|
||||||
all_blocks = []
|
|
||||||
for line in document.lines:
|
|
||||||
all_blocks.extend(line.blocks)
|
|
||||||
block_count = len(all_blocks)
|
|
||||||
|
|
||||||
point_by_input_index = {p.input_index: p for p in all_points}
|
|
||||||
flat_block_leds = []
|
|
||||||
block_ranges = []
|
|
||||||
for block in all_blocks:
|
|
||||||
block_points = []
|
|
||||||
for point_uid in block.point_ids:
|
|
||||||
p = point_by_input_index.get(point_uid)
|
|
||||||
if p is not None and p.strip is not None and p.led_id is not None:
|
|
||||||
block_points.append(p)
|
|
||||||
|
|
||||||
offset = len(flat_block_leds)
|
|
||||||
count = len(block_points)
|
|
||||||
flat_block_leds.extend(block_points)
|
|
||||||
block_ranges.append((offset, count, block.name))
|
|
||||||
|
|
||||||
with path.open("w", encoding="utf-8", newline="\n") as file:
|
with path.open("w", encoding="utf-8", newline="\n") as file:
|
||||||
file.write("#pragma once\n")
|
file.write("#pragma once\n")
|
||||||
file.write("// Auto-generated by LED Mapper GUI\n")
|
file.write("// Auto-generated by LED Mapper GUI\n")
|
||||||
@ -292,192 +193,194 @@ def write_vm_map_header(
|
|||||||
file.write("// Virtual matrix mapping plus physical LED grid-cell metadata.\n\n")
|
file.write("// Virtual matrix mapping plus physical LED grid-cell metadata.\n\n")
|
||||||
file.write("#include <stdint.h>\n")
|
file.write("#include <stdint.h>\n")
|
||||||
file.write("#include <Arduino.h>\n\n")
|
file.write("#include <Arduino.h>\n\n")
|
||||||
|
file.write(f"#define VM_ROWS {vm_rows}\n")
|
||||||
|
file.write(f"#define VM_COLS {vm_cols}\n")
|
||||||
|
file.write("#define VM_CELLS (VM_ROWS * VM_COLS)\n")
|
||||||
|
file.write(f"#define VM_MAX_IDS_PER_CELL {MAX_LEDS_PER_CELL}\n")
|
||||||
file.write(f"#define VM_NUM_STRIPS {NUM_STRIPS}\n")
|
file.write(f"#define VM_NUM_STRIPS {NUM_STRIPS}\n")
|
||||||
file.write(f"#define LED_COUNT {len(mapping_points)}\n")
|
file.write(f"#define LED_COUNT {len(mapping_points)}\n")
|
||||||
file.write(f"#define SOURCE_POINT_COUNT {len(all_points)}\n")
|
file.write(f"#define SOURCE_POINT_COUNT {len(all_points)}\n")
|
||||||
|
file.write(f"#define GRID_ROWS {grid_rows}\n")
|
||||||
|
file.write(f"#define GRID_COLS {grid_cols}\n")
|
||||||
|
file.write(f"#define GRID_ROW_MIN {min_row}\n")
|
||||||
|
file.write(f"#define GRID_ROW_MAX {max_row}\n")
|
||||||
|
file.write(f"#define GRID_COL_MIN {min_col}\n")
|
||||||
|
file.write(f"#define GRID_COL_MAX {max_col}\n")
|
||||||
|
file.write(f"#define GRID_CELL_SIZE_MM {CELL_SIZE_MM:.1f}f\n")
|
||||||
file.write(f"#define LED_BLOCK_COUNT {block_count}\n\n")
|
file.write(f"#define LED_BLOCK_COUNT {block_count}\n\n")
|
||||||
|
file.write("// Source grid -> virtual matrix orientation used by this file.\n")
|
||||||
if generate_grid:
|
file.write("// VM row is the source column flipped from right to left.\n")
|
||||||
file.write(f"#define VM_ROWS {vm_rows}\n")
|
file.write("// VM column is the source row shifted to zero-based coordinates.\n")
|
||||||
file.write(f"#define VM_COLS {vm_cols}\n")
|
file.write("#define VM_ROW_FROM_GRID_COL(col) (GRID_COL_MAX - (col))\n")
|
||||||
file.write("#define VM_CELLS (VM_ROWS * VM_COLS)\n")
|
file.write("#define VM_COL_FROM_GRID_ROW(row) ((row) - GRID_ROW_MIN)\n")
|
||||||
file.write(f"#define VM_MAX_IDS_PER_CELL {MAX_LEDS_PER_CELL}\n")
|
file.write("#define VM_GRID_ROW_FROM_VM_COL(col) ((col) + GRID_ROW_MIN)\n")
|
||||||
file.write(f"#define GRID_ROWS {grid_rows}\n")
|
file.write("#define VM_GRID_COL_FROM_VM_ROW(row) (GRID_COL_MAX - (row))\n\n")
|
||||||
file.write(f"#define GRID_COLS {grid_cols}\n")
|
|
||||||
file.write(f"#define GRID_ROW_MIN {min_row}\n")
|
|
||||||
file.write(f"#define GRID_ROW_MAX {max_row}\n")
|
|
||||||
file.write(f"#define GRID_COL_MIN {min_col}\n")
|
|
||||||
file.write(f"#define GRID_COL_MAX {max_col}\n")
|
|
||||||
file.write(f"#define GRID_CELL_SIZE_MM {cpp_float_literal(document.grid_step_mm)}\n\n")
|
|
||||||
file.write("// Source grid -> virtual matrix orientation used by this file.\n")
|
|
||||||
file.write("// VM row is the source column flipped from right to left.\n")
|
|
||||||
file.write("// VM column is the source row shifted to zero-based coordinates.\n")
|
|
||||||
file.write("#define VM_ROW_FROM_GRID_COL(col) (GRID_COL_MAX - (col))\n")
|
|
||||||
file.write("#define VM_COL_FROM_GRID_ROW(row) ((row) - GRID_ROW_MIN)\n")
|
|
||||||
file.write("#define VM_GRID_ROW_FROM_VM_COL(col) ((col) + GRID_ROW_MIN)\n")
|
|
||||||
file.write("#define VM_GRID_COL_FROM_VM_ROW(row) (GRID_COL_MAX - (row))\n\n")
|
|
||||||
|
|
||||||
file.write("struct LEDMap {\n")
|
file.write("struct LEDMap {\n")
|
||||||
file.write(" uint8_t strip;\n")
|
file.write(" uint8_t strip;\n")
|
||||||
file.write(" uint16_t led_id;\n")
|
file.write(" uint16_t led_id;\n")
|
||||||
file.write("};\n\n")
|
file.write("};\n\n")
|
||||||
|
file.write("struct GridCellRef {\n")
|
||||||
|
file.write(" uint8_t row;\n")
|
||||||
|
file.write(" uint8_t col;\n")
|
||||||
|
file.write("};\n\n")
|
||||||
|
|
||||||
if generate_grid:
|
file.write("// Number of LEDs in each virtual cell VM[row][col].\n")
|
||||||
file.write("struct GridCellRef {\n")
|
file.write("const uint8_t PROGMEM VM_LED_COUNT[VM_ROWS][VM_COLS] = {\n")
|
||||||
file.write(" uint8_t row;\n")
|
for row in range(vm_rows):
|
||||||
file.write(" uint8_t col;\n")
|
counts = [len(cells.get((row, col), [])) for col in range(vm_cols)]
|
||||||
file.write("};\n\n")
|
suffix = "," if row < vm_rows - 1 else ""
|
||||||
|
file.write(f" {format_int_row(counts)}{suffix}\n")
|
||||||
|
file.write("};\n\n")
|
||||||
|
|
||||||
file.write("// Number of LEDs in each virtual cell VM[row][col].\n")
|
file.write("// LED mappings for all virtual cells. Empty slots use {0xFF, 0xFFFF}.\n")
|
||||||
file.write("const uint8_t PROGMEM VM_LED_COUNT[VM_ROWS][VM_COLS] = {\n")
|
file.write("const LEDMap PROGMEM VM_MAPPINGS[VM_ROWS][VM_COLS][3] = {\n")
|
||||||
for row in range(vm_rows):
|
for row in range(vm_rows):
|
||||||
counts = [len(cells.get((row, col), [])) for col in range(vm_cols)]
|
file.write(" {\n")
|
||||||
suffix = "," if row < vm_rows - 1 else ""
|
for col in range(vm_cols):
|
||||||
file.write(f" {format_int_row(counts)}{suffix}\n")
|
cell_points = cells.get((row, col), [])
|
||||||
file.write("};\n\n")
|
entries = []
|
||||||
|
for slot in range(MAX_LEDS_PER_CELL):
|
||||||
|
if slot < len(cell_points):
|
||||||
|
point = cell_points[slot]
|
||||||
|
entries.append(f"{{{point.strip}, {point.led_id}}}")
|
||||||
|
else:
|
||||||
|
entries.append(f"{{{EMPTY_STRIP}, {EMPTY_LED}}}")
|
||||||
|
suffix = "," if col < vm_cols - 1 else ""
|
||||||
|
file.write(f" {{ {', '.join(entries)} }}{suffix}\n")
|
||||||
|
suffix = "," if row < vm_rows - 1 else ""
|
||||||
|
file.write(f" }}{suffix}\n")
|
||||||
|
file.write("};\n\n")
|
||||||
|
|
||||||
file.write("// LED mappings for all virtual cells. Empty slots use {0xFF, 0xFFFF}.\n")
|
file.write("// Original 1-based grid cell for each source point id.\n")
|
||||||
file.write("const LEDMap PROGMEM VM_MAPPINGS[VM_ROWS][VM_COLS][3] = {\n")
|
file.write("const GridCellRef PROGMEM LED_GRID_CELL_1BASED[SOURCE_POINT_COUNT] = {\n")
|
||||||
for row in range(vm_rows):
|
for index, point in enumerate(all_points):
|
||||||
file.write(" {\n")
|
suffix = "," if index < len(all_points) - 1 else ""
|
||||||
for col in range(vm_cols):
|
file.write(f" {{{point.row}, {point.col}}}{suffix} // id {point.generated_id}\n")
|
||||||
cell_points = cells.get((row, col), [])
|
file.write("};\n\n")
|
||||||
entries = []
|
|
||||||
for slot in range(MAX_LEDS_PER_CELL):
|
|
||||||
if slot < len(cell_points):
|
|
||||||
point = cell_points[slot]
|
|
||||||
entries.append(f"{{{point.strip}, {point.led_id}}}")
|
|
||||||
else:
|
|
||||||
entries.append(f"{{{EMPTY_STRIP}, {EMPTY_LED}}}")
|
|
||||||
suffix = "," if col < vm_cols - 1 else ""
|
|
||||||
file.write(f" {{ {', '.join(entries)} }}{suffix}\n")
|
|
||||||
suffix = "," if row < vm_rows - 1 else ""
|
|
||||||
file.write(f" }}{suffix}\n")
|
|
||||||
file.write("};\n\n")
|
|
||||||
|
|
||||||
file.write("// Original 1-based grid cell for each source point id.\n")
|
file.write("// Zero-based virtual matrix cell for each source point id.\n")
|
||||||
file.write("const GridCellRef PROGMEM LED_GRID_CELL_1BASED[SOURCE_POINT_COUNT] = {\n")
|
file.write("const GridCellRef PROGMEM LED_GRID_CELL_ZERO_BASED[SOURCE_POINT_COUNT] = {\n")
|
||||||
for index, point in enumerate(all_points):
|
for index, point in enumerate(all_points):
|
||||||
suffix = "," if index < len(all_points) - 1 else ""
|
suffix = "," if index < len(all_points) - 1 else ""
|
||||||
file.write(f" {{{point.row}, {point.col}}}{suffix} // id {point.generated_id}\n")
|
file.write(f" {{{point.matrix_row}, {point.matrix_col}}}{suffix} // id {point.generated_id}\n")
|
||||||
file.write("};\n\n")
|
file.write("};\n\n")
|
||||||
|
|
||||||
file.write("// Zero-based virtual matrix cell for each source point id.\n")
|
file.write("// Source ids from the input JSON, indexed by source point id.\n")
|
||||||
file.write("const GridCellRef PROGMEM LED_GRID_CELL_ZERO_BASED[SOURCE_POINT_COUNT] = {\n")
|
file.write("const uint16_t PROGMEM LED_SOURCE_ID[SOURCE_POINT_COUNT] = {\n")
|
||||||
for index, point in enumerate(all_points):
|
for start in range(0, len(all_points), 16):
|
||||||
suffix = "," if index < len(all_points) - 1 else ""
|
values = [point.source_id for point in all_points[start : start + 16]]
|
||||||
file.write(f" {{{point.matrix_row}, {point.matrix_col}}}{suffix} // id {point.generated_id}\n")
|
suffix = "," if start + 16 < len(all_points) else ""
|
||||||
file.write("};\n\n")
|
file.write(f" {', '.join(str(value) for value in values)}{suffix}\n")
|
||||||
|
file.write("};\n\n")
|
||||||
|
|
||||||
file.write("// Source ids from the input JSON, indexed by source point id.\n")
|
|
||||||
file.write("const uint16_t PROGMEM LED_SOURCE_ID[SOURCE_POINT_COUNT] = {\n")
|
|
||||||
for start in range(0, len(all_points), 16):
|
|
||||||
values = [point.source_id for point in all_points[start : start + 16]]
|
|
||||||
suffix = "," if start + 16 < len(all_points) else ""
|
|
||||||
file.write(f" {', '.join(str(value) for value in values)}{suffix}\n")
|
|
||||||
file.write("};\n\n")
|
|
||||||
|
|
||||||
if generate_blocks:
|
def write_legacy_ino(
|
||||||
# Generate compile-time block macros/constants
|
path: Path,
|
||||||
file.write("// Compile-time block indices\n")
|
points: list[PanelLedPoint],
|
||||||
for index, (offset, count, name) in enumerate(block_ranges):
|
cells: dict[tuple[int, int], list[PanelLedPoint]],
|
||||||
identifier = sanitize_cpp_identifier(name)
|
) -> None:
|
||||||
file.write(f"#define BLOCK_{identifier} {index}\n")
|
vm_rows, vm_cols, _grid_rows, _grid_cols = get_dimensions(points)
|
||||||
file.write("\n")
|
with path.open("w", encoding="utf-8", newline="\n") as file:
|
||||||
|
file.write("// ============================================================================\n")
|
||||||
file.write(f"#define TOTAL_BLOCK_LEDS {len(flat_block_leds)}\n\n")
|
file.write("// ARCHIVE COPY - VIRTUAL MATRIX GENERATED BY LED Mapper GUI\n")
|
||||||
file.write("struct BlockRange {\n")
|
file.write("// Saved as .ino.txt so Arduino IDE will not compile it automatically.\n")
|
||||||
file.write(" uint16_t offset;\n")
|
file.write("// ============================================================================\n\n")
|
||||||
file.write(" uint16_t count;\n")
|
file.write("#include <initializer_list>\n\n")
|
||||||
file.write("};\n\n")
|
file.write("#ifndef ARDUINO\n#include <Arduino.h>\n#endif\n\n")
|
||||||
|
file.write("#include <Adafruit_NeoPixel.h>\n")
|
||||||
file.write("// Flat list of all LEDs in blocks, ordered by block, and within block\n")
|
file.write("#ifndef NUM_STRIPS\n")
|
||||||
file.write("const LEDMap PROGMEM BLOCK_LEDS[TOTAL_BLOCK_LEDS] = {\n")
|
file.write(f"#define NUM_STRIPS {NUM_STRIPS}\n")
|
||||||
for index, point in enumerate(flat_block_leds):
|
file.write("#endif\n")
|
||||||
suffix = "," if index < len(flat_block_leds) - 1 else ""
|
file.write("extern Adafruit_NeoPixel hwStrips[NUM_STRIPS];\n\n")
|
||||||
file.write(f" {{{point.strip}, {point.led_id}}}{suffix} // block point\n")
|
file.write("#ifndef VM_MAX_PHYS_LEDS\n")
|
||||||
file.write("};\n\n")
|
file.write(f"#define VM_MAX_PHYS_LEDS {max(point.led_id for point in points if point.led_id is not None) + 1}\n")
|
||||||
|
file.write("#endif\n")
|
||||||
file.write("// Start offset and length for each block\n")
|
file.write("#ifndef VM_MAX_IDS_PER_CELL\n")
|
||||||
file.write("const BlockRange PROGMEM BLOCK_RANGES[LED_BLOCK_COUNT] = {\n")
|
file.write(f"#define VM_MAX_IDS_PER_CELL {MAX_LEDS_PER_CELL}\n")
|
||||||
for index, (offset, count, name) in enumerate(block_ranges):
|
file.write("#endif\n")
|
||||||
suffix = "," if index < len(block_ranges) - 1 else ""
|
file.write("#ifndef MATRIX_ROWS\n")
|
||||||
file.write(f" {{{offset}, {count}}}{suffix} // {name}\n")
|
file.write(f"#define MATRIX_ROWS {vm_rows}\n")
|
||||||
file.write("};\n\n")
|
file.write("#endif\n")
|
||||||
|
file.write("#ifndef MATRIX_COLS\n")
|
||||||
# String names array in PROGMEM
|
file.write(f"#define MATRIX_COLS {vm_cols}\n")
|
||||||
file.write("// Original string names of blocks in flash memory\n")
|
file.write("#endif\n\n")
|
||||||
for index, (offset, count, name) in enumerate(block_ranges):
|
file.write("struct VMPhys { uint16_t idx; uint8_t strip; };\n\n")
|
||||||
escaped_name = name.replace('"', '\\"')
|
file.write("static uint8_t vmCount[MATRIX_ROWS][MATRIX_COLS];\n")
|
||||||
file.write(f"const char BLOCK_NAME_{index}[] PROGMEM = \"{escaped_name}\";\n")
|
file.write("static VMPhys vmCell[MATRIX_ROWS][MATRIX_COLS][VM_MAX_IDS_PER_CELL];\n")
|
||||||
file.write("\n")
|
file.write("static int16_t vmRow[NUM_STRIPS][VM_MAX_PHYS_LEDS];\n")
|
||||||
|
file.write("static int16_t vmCol[NUM_STRIPS][VM_MAX_PHYS_LEDS];\n")
|
||||||
file.write("const char* const BLOCK_NAMES[LED_BLOCK_COUNT] PROGMEM = {\n")
|
file.write("static uint8_t vmUsed[NUM_STRIPS][VM_MAX_PHYS_LEDS];\n")
|
||||||
for index in range(len(block_ranges)):
|
file.write("static uint16_t vmMaxId[NUM_STRIPS];\n\n")
|
||||||
suffix = "," if index < len(block_ranges) - 1 else ""
|
file.write("void clearVirtualMatrix();\n")
|
||||||
file.write(f" BLOCK_NAME_{index}{suffix}\n")
|
file.write("void setLEDs(uint16_t row, uint16_t col, uint8_t strip1based, std::initializer_list<uint16_t> ids);\n")
|
||||||
file.write("};\n\n")
|
file.write("void vmSetByPhys(uint8_t strip, uint16_t led, uint32_t color);\n")
|
||||||
|
file.write("void initVirtualMatrix();\n\n")
|
||||||
# Inline helpers for blocks
|
file.write("void clearVirtualMatrix() {\n")
|
||||||
file.write("// Control block LEDs by count inside a block\n")
|
file.write(" for (int r = 0; r < MATRIX_ROWS; ++r)\n")
|
||||||
file.write("inline void setBlockLEDsCount(uint16_t blockIdx, uint16_t count, uint32_t color) {\n")
|
file.write(" for (int c = 0; c < MATRIX_COLS; ++c) vmCount[r][c] = 0;\n")
|
||||||
file.write(" if (blockIdx >= LED_BLOCK_COUNT) return;\n")
|
file.write(" for (int s = 0; s < NUM_STRIPS; ++s) {\n")
|
||||||
file.write(" uint16_t offset = pgm_read_word(&BLOCK_RANGES[blockIdx].offset);\n")
|
file.write(" vmMaxId[s] = 0;\n")
|
||||||
file.write(" uint16_t total_count = pgm_read_word(&BLOCK_RANGES[blockIdx].count);\n")
|
file.write(" for (int i = 0; i < VM_MAX_PHYS_LEDS; ++i) {\n")
|
||||||
file.write(" if (count > total_count) count = total_count;\n")
|
file.write(" vmRow[s][i] = -1;\n")
|
||||||
file.write(f" extern Adafruit_NeoPixel hwStrips[VM_NUM_STRIPS];\n")
|
file.write(" vmCol[s][i] = -1;\n")
|
||||||
file.write(" for (uint16_t i = 0; i < count; i++) {\n")
|
file.write(" vmUsed[s][i] = 0;\n")
|
||||||
file.write(" uint8_t strip = pgm_read_byte(&BLOCK_LEDS[offset + i].strip);\n")
|
file.write(" }\n")
|
||||||
file.write(" uint16_t led_id = pgm_read_word(&BLOCK_LEDS[offset + i].led_id);\n")
|
file.write(" }\n")
|
||||||
file.write(" if (strip < VM_NUM_STRIPS) {\n")
|
file.write("}\n\n")
|
||||||
file.write(" hwStrips[strip].setPixelColor(led_id, color);\n")
|
file.write("void setLEDs(uint16_t row, uint16_t col, uint8_t strip1based, std::initializer_list<uint16_t> ids) {\n")
|
||||||
file.write(" }\n")
|
file.write(" if (row >= MATRIX_ROWS || col >= MATRIX_COLS) return;\n")
|
||||||
file.write(" }\n")
|
file.write(" uint8_t strip = (strip1based == 0) ? 0 : (uint8_t)(strip1based - 1);\n")
|
||||||
file.write("}\n\n")
|
file.write(" if (strip >= NUM_STRIPS) return;\n")
|
||||||
|
file.write(" for (uint16_t id : ids) {\n")
|
||||||
file.write("// Control single block LED by 0-based index inside a block\n")
|
file.write(" if (id >= VM_MAX_PHYS_LEDS) continue;\n")
|
||||||
file.write("inline void setBlockLED(uint16_t blockIdx, uint16_t ledIdxInBlock, uint32_t color) {\n")
|
file.write(" uint8_t &count = vmCount[row][col];\n")
|
||||||
file.write(" if (blockIdx >= LED_BLOCK_COUNT) return;\n")
|
file.write(" if (count < VM_MAX_IDS_PER_CELL) {\n")
|
||||||
file.write(" uint16_t offset = pgm_read_word(&BLOCK_RANGES[blockIdx].offset);\n")
|
file.write(" vmCell[row][col][count].idx = id;\n")
|
||||||
file.write(" uint16_t count = pgm_read_word(&BLOCK_RANGES[blockIdx].count);\n")
|
file.write(" vmCell[row][col][count].strip = strip;\n")
|
||||||
file.write(" if (ledIdxInBlock >= count) return;\n")
|
file.write(" ++count;\n")
|
||||||
file.write(" uint8_t strip = pgm_read_byte(&BLOCK_LEDS[offset + ledIdxInBlock].strip);\n")
|
file.write(" }\n")
|
||||||
file.write(" uint16_t led_id = pgm_read_word(&BLOCK_LEDS[offset + ledIdxInBlock].led_id);\n")
|
file.write(" vmRow[strip][id] = (int16_t)row;\n")
|
||||||
file.write(f" extern Adafruit_NeoPixel hwStrips[VM_NUM_STRIPS];\n")
|
file.write(" vmCol[strip][id] = (int16_t)col;\n")
|
||||||
file.write(" if (strip < VM_NUM_STRIPS) {\n")
|
file.write(" vmUsed[strip][id] = 1;\n")
|
||||||
file.write(" hwStrips[strip].setPixelColor(led_id, color);\n")
|
file.write(" if (id > vmMaxId[strip]) vmMaxId[strip] = id;\n")
|
||||||
file.write(" }\n")
|
file.write(" }\n")
|
||||||
file.write("}\n\n")
|
file.write("}\n\n")
|
||||||
|
file.write("void vmSetByPhys(uint8_t strip, uint16_t led, uint32_t color) {\n")
|
||||||
# Add getBlockIndexByName
|
file.write(" if (strip >= NUM_STRIPS || led >= VM_MAX_PHYS_LEDS) return;\n")
|
||||||
file.write("// Find block index by its string name (case-sensitive, original name)\n")
|
file.write(" int16_t row = vmRow[strip][led];\n")
|
||||||
file.write("inline int16_t getBlockIndexByName(const char* name) {\n")
|
file.write(" int16_t col = vmCol[strip][led];\n")
|
||||||
file.write(" for (uint16_t i = 0; i < LED_BLOCK_COUNT; i++) {\n")
|
file.write(" if (row < 0 || col < 0) {\n")
|
||||||
file.write(" const char* blockNamePtr = (const char*)pgm_read_word(&BLOCK_NAMES[i]);\n")
|
file.write(" if (led < hwStrips[strip].numPixels()) hwStrips[strip].setPixelColor(led, color);\n")
|
||||||
file.write(" if (strcmp_P(name, blockNamePtr) == 0) {\n")
|
file.write(" return;\n")
|
||||||
file.write(" return (int16_t)i;\n")
|
file.write(" }\n")
|
||||||
file.write(" }\n")
|
file.write(" uint8_t count = vmCount[row][col];\n")
|
||||||
file.write(" }\n")
|
file.write(" for (uint8_t i = 0; i < count; ++i) {\n")
|
||||||
file.write(" return -1;\n")
|
file.write(" const VMPhys &phys = vmCell[row][col][i];\n")
|
||||||
file.write("}\n\n")
|
file.write(" if (phys.strip < NUM_STRIPS && phys.idx < hwStrips[phys.strip].numPixels()) {\n")
|
||||||
|
file.write(" hwStrips[phys.strip].setPixelColor(phys.idx, color);\n")
|
||||||
# Add string-based control overloads
|
file.write(" }\n")
|
||||||
file.write("// Control block LEDs by string name and count\n")
|
file.write(" }\n")
|
||||||
file.write("inline void setBlockLEDsCount(const char* name, uint16_t count, uint32_t color) {\n")
|
file.write("}\n\n")
|
||||||
file.write(" int16_t idx = getBlockIndexByName(name);\n")
|
file.write("void initVirtualMatrix() {\n")
|
||||||
file.write(" if (idx >= 0) {\n")
|
file.write(" clearVirtualMatrix();\n")
|
||||||
file.write(" setBlockLEDsCount((uint16_t)idx, count, color);\n")
|
last_row = None
|
||||||
file.write(" }\n")
|
for row in range(vm_rows):
|
||||||
file.write("}\n\n")
|
row_cells = [(col, cells[(row, col)]) for col in range(vm_cols) if (row, col) in cells]
|
||||||
|
if not row_cells:
|
||||||
file.write("// Control single block LED by block string name and 0-based index\n")
|
continue
|
||||||
file.write("inline void setBlockLED(const char* name, uint16_t ledIdxInBlock, uint32_t color) {\n")
|
if last_row != row:
|
||||||
file.write(" int16_t idx = getBlockIndexByName(name);\n")
|
file.write(f"\n // Row {row}\n")
|
||||||
file.write(" if (idx >= 0) {\n")
|
last_row = row
|
||||||
file.write(" setBlockLED((uint16_t)idx, ledIdxInBlock, color);\n")
|
for col, cell_points in row_cells:
|
||||||
file.write(" }\n")
|
by_strip: dict[int, list[int]] = defaultdict(list)
|
||||||
file.write("}\n")
|
for point in cell_points:
|
||||||
|
if point.strip is not None and point.led_id is not None:
|
||||||
|
by_strip[point.strip + 1].append(point.led_id)
|
||||||
|
for strip1based, led_ids_list in sorted(by_strip.items()):
|
||||||
|
led_ids = ", ".join(str(led_id) for led_id in led_ids_list)
|
||||||
|
file.write(f" setLEDs({row}, {col:2d}, {strip1based}, {{ {led_ids} }});\n")
|
||||||
|
file.write("}\n")
|
||||||
|
|
||||||
|
|
||||||
def write_ordered_json(path: Path, points: list[PanelLedPoint], document: MappingDocument) -> None:
|
def write_ordered_json(path: Path, points: list[PanelLedPoint], document: MappingDocument) -> None:
|
||||||
@ -512,18 +415,14 @@ def write_ordered_json(path: Path, points: list[PanelLedPoint], document: Mappin
|
|||||||
{
|
{
|
||||||
"source": str(document.path) if document.path is not None else "LED Mapper GUI",
|
"source": str(document.path) if document.path is not None else "LED Mapper GUI",
|
||||||
"unit": OUTPUT_UNIT,
|
"unit": OUTPUT_UNIT,
|
||||||
"coordinate_unit": OUTPUT_UNIT,
|
"cell_size_mm": CELL_SIZE_MM,
|
||||||
"cell_size_mm": document.grid_step_mm,
|
|
||||||
"ordered_id_mode": "generated_uid",
|
"ordered_id_mode": "generated_uid",
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
def collect_validation(
|
def collect_validation(points: list[PanelLedPoint]) -> list[str]:
|
||||||
points: list[PanelLedPoint],
|
|
||||||
cell_size_mm: float = CELL_SIZE_MM,
|
|
||||||
) -> list[str]:
|
|
||||||
lines = []
|
lines = []
|
||||||
distance_violations = []
|
distance_violations = []
|
||||||
cell_violations = []
|
cell_violations = []
|
||||||
@ -531,9 +430,7 @@ def collect_validation(
|
|||||||
if current.route_group != next_point.route_group:
|
if current.route_group != next_point.route_group:
|
||||||
continue
|
continue
|
||||||
gap = math.hypot(current.x_mm - next_point.x_mm, current.y_mm - next_point.y_mm)
|
gap = math.hypot(current.x_mm - next_point.x_mm, current.y_mm - next_point.y_mm)
|
||||||
diagonal = abs(current.row - next_point.row) == 1 and abs(current.col - next_point.col) == 1
|
if gap > CELL_SIZE_MM + 1e-6:
|
||||||
distance_limit = cell_size_mm * (math.sqrt(2.0) if diagonal else 1.0) + MAX_NEIGHBOR_TOLERANCE_MM
|
|
||||||
if gap > distance_limit + 1e-6:
|
|
||||||
distance_violations.append((current, next_point, gap))
|
distance_violations.append((current, next_point, gap))
|
||||||
if abs(current.row - next_point.row) > 1 or abs(current.col - next_point.col) > 1:
|
if abs(current.row - next_point.row) > 1 or abs(current.col - next_point.col) > 1:
|
||||||
cell_violations.append((current, next_point))
|
cell_violations.append((current, next_point))
|
||||||
@ -543,7 +440,7 @@ def collect_validation(
|
|||||||
lines.append(f"LED count: {len(points)}")
|
lines.append(f"LED count: {len(points)}")
|
||||||
lines.append(f"Generated ids contiguous: {not duplicate_ids}")
|
lines.append(f"Generated ids contiguous: {not duplicate_ids}")
|
||||||
lines.append(f"Max LEDs per cell: {max_per_cell}")
|
lines.append(f"Max LEDs per cell: {max_per_cell}")
|
||||||
lines.append(f"Same-route distance violations beyond grid step + tolerance: {len(distance_violations)}")
|
lines.append(f"Same-route distance violations > {CELL_SIZE_MM:g} mm: {len(distance_violations)}")
|
||||||
lines.append(f"Same-route 8-neighbor cell violations: {len(cell_violations)}")
|
lines.append(f"Same-route 8-neighbor cell violations: {len(cell_violations)}")
|
||||||
if max_per_cell > MAX_LEDS_PER_CELL:
|
if max_per_cell > MAX_LEDS_PER_CELL:
|
||||||
lines.append(f"ERROR: max LEDs per cell exceeds {MAX_LEDS_PER_CELL}")
|
lines.append(f"ERROR: max LEDs per cell exceeds {MAX_LEDS_PER_CELL}")
|
||||||
@ -560,15 +457,11 @@ def collect_validation(
|
|||||||
return lines
|
return lines
|
||||||
|
|
||||||
|
|
||||||
def write_validation_report(
|
def write_validation_report(path: Path, points: list[PanelLedPoint]) -> None:
|
||||||
path: Path,
|
|
||||||
points: list[PanelLedPoint],
|
|
||||||
cell_size_mm: float = CELL_SIZE_MM,
|
|
||||||
) -> None:
|
|
||||||
lines = [
|
lines = [
|
||||||
"Panel mapping validation",
|
"Panel mapping validation",
|
||||||
"========================",
|
"========================",
|
||||||
*collect_validation(points, cell_size_mm),
|
*collect_validation(points),
|
||||||
"",
|
"",
|
||||||
]
|
]
|
||||||
path.write_text("\n".join(lines), encoding="utf-8")
|
path.write_text("\n".join(lines), encoding="utf-8")
|
||||||
@ -578,17 +471,13 @@ def write_readme(path: Path) -> None:
|
|||||||
path.write_text(
|
path.write_text(
|
||||||
"\n".join(
|
"\n".join(
|
||||||
[
|
[
|
||||||
"# Результат генерации Panel Mapping",
|
"# Panel Mapping Build",
|
||||||
"",
|
"",
|
||||||
"LED Mapper создал следующие файлы:",
|
"This folder contains files generated by the LED Mapper GUI:",
|
||||||
"- `vm_map.h` — маппинг виртуальной матрицы в формате PROGMEM.",
|
"- `vm_map.h` contains the PROGMEM virtual matrix mapping.",
|
||||||
"- `ordered_circles.json` — нормализованные LED и координаты матрицы.",
|
"- `virtual_matrix_legacy.ino.txt` keeps the readable `setLEDs(...)` mapping.",
|
||||||
"- `validation_report.txt` — результаты проверки маршрутов и ячеек.",
|
"- `ordered_circles.json` stores generated ids plus source row/col data.",
|
||||||
"- `README.md` — описание набора файлов.",
|
"- `validation_report.txt` records sequence and cell checks.",
|
||||||
"",
|
|
||||||
"Физический адрес ленты в `vm_map.h`: `strip = line_id`; нумерация начинается с `0`.",
|
|
||||||
"",
|
|
||||||
"Устаревший `virtual_matrix_legacy.ino.txt` больше не создаётся.",
|
|
||||||
"",
|
"",
|
||||||
]
|
]
|
||||||
),
|
),
|
||||||
|
|||||||
2155
qa_smoke.py
2155
qa_smoke.py
File diff suppressed because it is too large
Load Diff
54
settings.py
54
settings.py
@ -1,7 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import math
|
|
||||||
from dataclasses import asdict, dataclass
|
from dataclasses import asdict, dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@ -10,7 +9,6 @@ from PySide6.QtGui import QKeySequence
|
|||||||
|
|
||||||
|
|
||||||
SHORTCUT_DEFINITIONS: list[tuple[str, str, str]] = [
|
SHORTCUT_DEFINITIONS: list[tuple[str, str, str]] = [
|
||||||
("new", "Создать", "Ctrl+N"),
|
|
||||||
("open", "Открыть", "Ctrl+O"),
|
("open", "Открыть", "Ctrl+O"),
|
||||||
("save", "Сохранить", "Ctrl+S"),
|
("save", "Сохранить", "Ctrl+S"),
|
||||||
("save_as", "Сохранить как", "Ctrl+Shift+S"),
|
("save_as", "Сохранить как", "Ctrl+Shift+S"),
|
||||||
@ -18,14 +16,12 @@ SHORTCUT_DEFINITIONS: list[tuple[str, str, str]] = [
|
|||||||
("settings", "Параметры", "Ctrl+,"),
|
("settings", "Параметры", "Ctrl+,"),
|
||||||
("undo", "Отменить", "Ctrl+Z"),
|
("undo", "Отменить", "Ctrl+Z"),
|
||||||
("redo", "Повторить", "Ctrl+Y"),
|
("redo", "Повторить", "Ctrl+Y"),
|
||||||
("copy_leds", "Копировать светодиоды", "Ctrl+C"),
|
|
||||||
("paste_leds", "Вставить светодиоды", "Ctrl+V"),
|
|
||||||
("delete", "Удалить фиксацию", "Del"),
|
("delete", "Удалить фиксацию", "Del"),
|
||||||
("delete_points", "Удалить точки", "Ctrl+Del"),
|
("delete_points", "Удалить точки", "Ctrl+Del"),
|
||||||
("clear_all", "Удалить все", "Shift+Del"),
|
("clear_all", "Удалить все", "Ctrl+Shift+Del"),
|
||||||
("clear_selection", "Очистить выбор", "Esc"),
|
("clear_selection", "Очистить выбор", "Esc"),
|
||||||
("fit_view", "Показать всё", "Ctrl+0"),
|
("fit_view", "Показать всё", "Ctrl+0"),
|
||||||
("grid", "Сетка", "G"),
|
("grid", "Сетка 34 мм", "G"),
|
||||||
("direction_arrows", "Стрелки направления", "Ctrl+Shift+A"),
|
("direction_arrows", "Стрелки направления", "Ctrl+Shift+A"),
|
||||||
("led_ids", "Отображать id светодиодов", "I"),
|
("led_ids", "Отображать id светодиодов", "I"),
|
||||||
("background", "Подложка", "Ctrl+B"),
|
("background", "Подложка", "Ctrl+B"),
|
||||||
@ -39,22 +35,11 @@ SHORTCUT_DEFINITIONS: list[tuple[str, str, str]] = [
|
|||||||
("add_block", "Блок из выбора", "Ctrl+Shift+L"),
|
("add_block", "Блок из выбора", "Ctrl+Shift+L"),
|
||||||
("auto_blocks", "Автоблоки", "Ctrl+Shift+B"),
|
("auto_blocks", "Автоблоки", "Ctrl+Shift+B"),
|
||||||
("clockwise", "По часовой", "Ctrl+Alt+R"),
|
("clockwise", "По часовой", "Ctrl+Alt+R"),
|
||||||
("counterclockwise", "Против часовой", "Ctrl+Alt+Shift+R"),
|
|
||||||
("rebuild_route", "Пересобрать", "Ctrl+Shift+R"),
|
("rebuild_route", "Пересобрать", "Ctrl+Shift+R"),
|
||||||
("brush", "Кисть", "B"),
|
("brush", "Кисть", "B"),
|
||||||
]
|
]
|
||||||
DEFAULT_SHORTCUTS = {key: shortcut for key, _title, shortcut in SHORTCUT_DEFINITIONS}
|
DEFAULT_SHORTCUTS = {key: shortcut for key, _title, shortcut in SHORTCUT_DEFINITIONS}
|
||||||
SETTINGS_VERSION = 4
|
SETTINGS_VERSION = 2
|
||||||
SHORTCUT_DEFAULTS_MIGRATION_VERSION = 2
|
|
||||||
DEFAULT_GRID_STEP_MM = 34.0
|
|
||||||
MIN_GRID_STEP_MM = 1.0
|
|
||||||
MAX_GRID_STEP_MM = 1000.0
|
|
||||||
DEFAULT_LED_POINT_DIAMETER_PX = 9
|
|
||||||
MIN_LED_POINT_DIAMETER_PX = 1
|
|
||||||
MAX_LED_POINT_DIAMETER_PX = 64
|
|
||||||
DEFAULT_LED_INDEX_FONT_SIZE_PX = 12
|
|
||||||
MIN_LED_INDEX_FONT_SIZE_PX = 6
|
|
||||||
MAX_LED_INDEX_FONT_SIZE_PX = 64
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@ -64,9 +49,6 @@ class AppSettings:
|
|||||||
show_grid_by_default: bool = False
|
show_grid_by_default: bool = False
|
||||||
show_direction_arrows_by_default: bool = True
|
show_direction_arrows_by_default: bool = True
|
||||||
show_led_ids_by_default: bool = True
|
show_led_ids_by_default: bool = True
|
||||||
grid_step_mm: float = DEFAULT_GRID_STEP_MM
|
|
||||||
led_point_diameter_px: int = DEFAULT_LED_POINT_DIAMETER_PX
|
|
||||||
led_index_font_size_px: int = DEFAULT_LED_INDEX_FONT_SIZE_PX
|
|
||||||
zoom_focus_pull: int = 35
|
zoom_focus_pull: int = 35
|
||||||
pan_mode: str = "middle_space"
|
pan_mode: str = "middle_space"
|
||||||
instant_space_pan: bool = False
|
instant_space_pan: bool = False
|
||||||
@ -91,24 +73,6 @@ class AppSettings:
|
|||||||
if hasattr(settings, key):
|
if hasattr(settings, key):
|
||||||
setattr(settings, key, value)
|
setattr(settings, key, value)
|
||||||
settings.version = SETTINGS_VERSION
|
settings.version = SETTINGS_VERSION
|
||||||
settings.grid_step_mm = clamp_float(
|
|
||||||
settings.grid_step_mm,
|
|
||||||
MIN_GRID_STEP_MM,
|
|
||||||
MAX_GRID_STEP_MM,
|
|
||||||
DEFAULT_GRID_STEP_MM,
|
|
||||||
)
|
|
||||||
settings.led_point_diameter_px = clamp_int(
|
|
||||||
settings.led_point_diameter_px,
|
|
||||||
MIN_LED_POINT_DIAMETER_PX,
|
|
||||||
MAX_LED_POINT_DIAMETER_PX,
|
|
||||||
DEFAULT_LED_POINT_DIAMETER_PX,
|
|
||||||
)
|
|
||||||
settings.led_index_font_size_px = clamp_int(
|
|
||||||
settings.led_index_font_size_px,
|
|
||||||
MIN_LED_INDEX_FONT_SIZE_PX,
|
|
||||||
MAX_LED_INDEX_FONT_SIZE_PX,
|
|
||||||
DEFAULT_LED_INDEX_FONT_SIZE_PX,
|
|
||||||
)
|
|
||||||
settings.zoom_focus_pull = clamp_int(settings.zoom_focus_pull, 0, 100, cls.zoom_focus_pull)
|
settings.zoom_focus_pull = clamp_int(settings.zoom_focus_pull, 0, 100, cls.zoom_focus_pull)
|
||||||
settings.brush_radius = clamp_int(settings.brush_radius, 4, 80, cls.brush_radius)
|
settings.brush_radius = clamp_int(settings.brush_radius, 4, 80, cls.brush_radius)
|
||||||
if settings.theme not in {"system", "light", "dark"}:
|
if settings.theme not in {"system", "light", "dark"}:
|
||||||
@ -124,7 +88,7 @@ class AppSettings:
|
|||||||
settings.sidebar_inner_sizes = normalize_splitter_sizes(settings.sidebar_inner_sizes, [360, 420])
|
settings.sidebar_inner_sizes = normalize_splitter_sizes(settings.sidebar_inner_sizes, [360, 420])
|
||||||
settings.shortcuts = normalize_shortcuts(
|
settings.shortcuts = normalize_shortcuts(
|
||||||
settings.shortcuts,
|
settings.shortcuts,
|
||||||
fill_new_defaults=saved_version < SHORTCUT_DEFAULTS_MIGRATION_VERSION,
|
fill_new_defaults=saved_version < SETTINGS_VERSION,
|
||||||
)
|
)
|
||||||
return settings
|
return settings
|
||||||
|
|
||||||
@ -154,16 +118,6 @@ def clamp_int(value, minimum: int, maximum: int, fallback: int) -> int: # noqa:
|
|||||||
return max(minimum, min(maximum, number))
|
return max(minimum, min(maximum, number))
|
||||||
|
|
||||||
|
|
||||||
def clamp_float(value, minimum: float, maximum: float, fallback: float) -> float: # noqa: ANN001
|
|
||||||
try:
|
|
||||||
number = float(value)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return fallback
|
|
||||||
if not math.isfinite(number):
|
|
||||||
return fallback
|
|
||||||
return max(minimum, min(maximum, number))
|
|
||||||
|
|
||||||
|
|
||||||
def normalize_splitter_sizes(value, fallback: list[int]) -> list[int]: # noqa: ANN001
|
def normalize_splitter_sizes(value, fallback: list[int]) -> list[int]: # noqa: ANN001
|
||||||
if not isinstance(value, list) or len(value) != len(fallback):
|
if not isinstance(value, list) or len(value) != len(fallback):
|
||||||
return fallback[:]
|
return fallback[:]
|
||||||
|
|||||||
@ -1,6 +1,5 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import replace
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from PySide6.QtGui import QKeySequence
|
from PySide6.QtGui import QKeySequence
|
||||||
@ -11,7 +10,6 @@ from PySide6.QtWidgets import (
|
|||||||
QComboBox,
|
QComboBox,
|
||||||
QDialog,
|
QDialog,
|
||||||
QDialogButtonBox,
|
QDialogButtonBox,
|
||||||
QDoubleSpinBox,
|
|
||||||
QFileDialog,
|
QFileDialog,
|
||||||
QFormLayout,
|
QFormLayout,
|
||||||
QHBoxLayout,
|
QHBoxLayout,
|
||||||
@ -28,38 +26,10 @@ from PySide6.QtWidgets import (
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
from .localization import localize_dialog_buttons, show_warning
|
from .localization import localize_dialog_buttons, show_warning
|
||||||
from .settings import (
|
from .settings import DEFAULT_SHORTCUTS, SHORTCUT_DEFINITIONS, AppSettings
|
||||||
DEFAULT_GRID_STEP_MM,
|
|
||||||
DEFAULT_LED_INDEX_FONT_SIZE_PX,
|
|
||||||
DEFAULT_LED_POINT_DIAMETER_PX,
|
|
||||||
DEFAULT_SHORTCUTS,
|
|
||||||
MAX_GRID_STEP_MM,
|
|
||||||
MAX_LED_INDEX_FONT_SIZE_PX,
|
|
||||||
MAX_LED_POINT_DIAMETER_PX,
|
|
||||||
MIN_GRID_STEP_MM,
|
|
||||||
MIN_LED_INDEX_FONT_SIZE_PX,
|
|
||||||
MIN_LED_POINT_DIAMETER_PX,
|
|
||||||
SETTINGS_VERSION,
|
|
||||||
SHORTCUT_DEFINITIONS,
|
|
||||||
AppSettings,
|
|
||||||
)
|
|
||||||
except ImportError:
|
except ImportError:
|
||||||
from localization import localize_dialog_buttons, show_warning
|
from localization import localize_dialog_buttons, show_warning
|
||||||
from settings import (
|
from settings import DEFAULT_SHORTCUTS, SHORTCUT_DEFINITIONS, AppSettings
|
||||||
DEFAULT_GRID_STEP_MM,
|
|
||||||
DEFAULT_LED_INDEX_FONT_SIZE_PX,
|
|
||||||
DEFAULT_LED_POINT_DIAMETER_PX,
|
|
||||||
DEFAULT_SHORTCUTS,
|
|
||||||
MAX_GRID_STEP_MM,
|
|
||||||
MAX_LED_INDEX_FONT_SIZE_PX,
|
|
||||||
MAX_LED_POINT_DIAMETER_PX,
|
|
||||||
MIN_GRID_STEP_MM,
|
|
||||||
MIN_LED_INDEX_FONT_SIZE_PX,
|
|
||||||
MIN_LED_POINT_DIAMETER_PX,
|
|
||||||
SETTINGS_VERSION,
|
|
||||||
SHORTCUT_DEFINITIONS,
|
|
||||||
AppSettings,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class SettingsDialog(QDialog):
|
class SettingsDialog(QDialog):
|
||||||
@ -74,44 +44,12 @@ class SettingsDialog(QDialog):
|
|||||||
self.theme.addItem("Светлая", "light")
|
self.theme.addItem("Светлая", "light")
|
||||||
self.theme.addItem("Темная", "dark")
|
self.theme.addItem("Темная", "dark")
|
||||||
self.theme.setCurrentIndex(max(0, self.theme.findData(settings.theme)))
|
self.theme.setCurrentIndex(max(0, self.theme.findData(settings.theme)))
|
||||||
self.show_grid = QCheckBox("Показывать сетку при запуске")
|
self.show_grid = QCheckBox("Показывать сетку 34 мм при запуске")
|
||||||
self.show_grid.setChecked(settings.show_grid_by_default)
|
self.show_grid.setChecked(settings.show_grid_by_default)
|
||||||
self.show_arrows = QCheckBox("Показывать стрелки направления при запуске")
|
self.show_arrows = QCheckBox("Показывать стрелки направления при запуске")
|
||||||
self.show_arrows.setChecked(settings.show_direction_arrows_by_default)
|
self.show_arrows.setChecked(settings.show_direction_arrows_by_default)
|
||||||
self.show_led_ids = QCheckBox("Показывать id светодиодов при выборе")
|
self.show_led_ids = QCheckBox("Показывать id светодиодов при выборе")
|
||||||
self.show_led_ids.setChecked(settings.show_led_ids_by_default)
|
self.show_led_ids.setChecked(settings.show_led_ids_by_default)
|
||||||
self.grid_step = QDoubleSpinBox()
|
|
||||||
self.grid_step.setRange(MIN_GRID_STEP_MM, MAX_GRID_STEP_MM)
|
|
||||||
self.grid_step.setDecimals(2)
|
|
||||||
self.grid_step.setSingleStep(1.0)
|
|
||||||
self.grid_step.setSuffix(" мм")
|
|
||||||
self.grid_step.setValue(settings.grid_step_mm)
|
|
||||||
self.grid_step_reset = QPushButton("Сбросить")
|
|
||||||
self.grid_step_reset.clicked.connect(
|
|
||||||
lambda: self.grid_step.setValue(DEFAULT_GRID_STEP_MM)
|
|
||||||
)
|
|
||||||
self.led_point_diameter = QSpinBox()
|
|
||||||
self.led_point_diameter.setRange(
|
|
||||||
MIN_LED_POINT_DIAMETER_PX,
|
|
||||||
MAX_LED_POINT_DIAMETER_PX,
|
|
||||||
)
|
|
||||||
self.led_point_diameter.setSuffix(" px")
|
|
||||||
self.led_point_diameter.setValue(settings.led_point_diameter_px)
|
|
||||||
self.led_point_diameter_reset = QPushButton("Сбросить")
|
|
||||||
self.led_point_diameter_reset.clicked.connect(
|
|
||||||
lambda: self.led_point_diameter.setValue(DEFAULT_LED_POINT_DIAMETER_PX)
|
|
||||||
)
|
|
||||||
self.led_index_font_size = QSpinBox()
|
|
||||||
self.led_index_font_size.setRange(
|
|
||||||
MIN_LED_INDEX_FONT_SIZE_PX,
|
|
||||||
MAX_LED_INDEX_FONT_SIZE_PX,
|
|
||||||
)
|
|
||||||
self.led_index_font_size.setSuffix(" px")
|
|
||||||
self.led_index_font_size.setValue(settings.led_index_font_size_px)
|
|
||||||
self.led_index_font_size_reset = QPushButton("Сбросить")
|
|
||||||
self.led_index_font_size_reset.clicked.connect(
|
|
||||||
lambda: self.led_index_font_size.setValue(DEFAULT_LED_INDEX_FONT_SIZE_PX)
|
|
||||||
)
|
|
||||||
self.zoom_pull = QSpinBox()
|
self.zoom_pull = QSpinBox()
|
||||||
self.zoom_pull.setRange(0, 100)
|
self.zoom_pull.setRange(0, 100)
|
||||||
self.zoom_pull.setSuffix(" %")
|
self.zoom_pull.setSuffix(" %")
|
||||||
@ -167,16 +105,11 @@ class SettingsDialog(QDialog):
|
|||||||
self.section_stack.addWidget(widget)
|
self.section_stack.addWidget(widget)
|
||||||
|
|
||||||
def settings(self) -> AppSettings:
|
def settings(self) -> AppSettings:
|
||||||
return replace(
|
return AppSettings(
|
||||||
self._settings,
|
|
||||||
version=SETTINGS_VERSION,
|
|
||||||
theme=str(self.theme.currentData()),
|
theme=str(self.theme.currentData()),
|
||||||
show_grid_by_default=self.show_grid.isChecked(),
|
show_grid_by_default=self.show_grid.isChecked(),
|
||||||
show_direction_arrows_by_default=self.show_arrows.isChecked(),
|
show_direction_arrows_by_default=self.show_arrows.isChecked(),
|
||||||
show_led_ids_by_default=self.show_led_ids.isChecked(),
|
show_led_ids_by_default=self.show_led_ids.isChecked(),
|
||||||
grid_step_mm=self.grid_step.value(),
|
|
||||||
led_point_diameter_px=self.led_point_diameter.value(),
|
|
||||||
led_index_font_size_px=self.led_index_font_size.value(),
|
|
||||||
zoom_focus_pull=self.zoom_pull.value(),
|
zoom_focus_pull=self.zoom_pull.value(),
|
||||||
pan_mode=str(self.pan_mode.currentData()),
|
pan_mode=str(self.pan_mode.currentData()),
|
||||||
instant_space_pan=self.instant_space_pan.isChecked(),
|
instant_space_pan=self.instant_space_pan.isChecked(),
|
||||||
@ -193,28 +126,10 @@ class SettingsDialog(QDialog):
|
|||||||
layout.addRow(self.show_grid)
|
layout.addRow(self.show_grid)
|
||||||
layout.addRow(self.show_arrows)
|
layout.addRow(self.show_arrows)
|
||||||
layout.addRow(self.show_led_ids)
|
layout.addRow(self.show_led_ids)
|
||||||
layout.addRow("Шаг сетки", self._setting_with_reset(self.grid_step, self.grid_step_reset))
|
|
||||||
layout.addRow(
|
|
||||||
"Диаметр LED-точек",
|
|
||||||
self._setting_with_reset(self.led_point_diameter, self.led_point_diameter_reset),
|
|
||||||
)
|
|
||||||
layout.addRow(
|
|
||||||
"Размер текста индексов LED",
|
|
||||||
self._setting_with_reset(self.led_index_font_size, self.led_index_font_size_reset),
|
|
||||||
)
|
|
||||||
layout.addRow("Притяжение зума к курсору", self.zoom_pull)
|
layout.addRow("Притяжение зума к курсору", self.zoom_pull)
|
||||||
layout.addRow(QLabel("0% оставляет центр спокойнее, 100% сильнее тянет схему к курсору."))
|
layout.addRow(QLabel("0% оставляет центр спокойнее, 100% сильнее тянет схему к курсору."))
|
||||||
return page
|
return page
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _setting_with_reset(editor: QWidget, reset: QPushButton) -> QWidget:
|
|
||||||
row = QWidget()
|
|
||||||
row_layout = QHBoxLayout(row)
|
|
||||||
row_layout.setContentsMargins(0, 0, 0, 0)
|
|
||||||
row_layout.addWidget(editor, 1)
|
|
||||||
row_layout.addWidget(reset)
|
|
||||||
return row
|
|
||||||
|
|
||||||
def _build_behavior_tab(self) -> QWidget:
|
def _build_behavior_tab(self) -> QWidget:
|
||||||
page = QWidget()
|
page = QWidget()
|
||||||
layout = QFormLayout(page)
|
layout = QFormLayout(page)
|
||||||
|
|||||||
@ -1,348 +0,0 @@
|
|||||||
"""Безопасная проверка и установка Windows-релизов LED Mapper."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import platform
|
|
||||||
import re
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
import uuid
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from pathlib import Path
|
|
||||||
from typing import BinaryIO, Callable
|
|
||||||
from urllib.parse import urlparse
|
|
||||||
from urllib.request import Request, urlopen
|
|
||||||
|
|
||||||
try:
|
|
||||||
from .version import __version__
|
|
||||||
except ImportError:
|
|
||||||
from version import __version__
|
|
||||||
|
|
||||||
RELEASE_API_URL = "https://git.robotail.pro/api/v1/repos/Robotail/LED-mapper/releases/latest"
|
|
||||||
RELEASE_PAGE_URL = "https://git.robotail.pro/Robotail/LED-mapper/releases"
|
|
||||||
RELEASE_HOST = "git.robotail.pro"
|
|
||||||
READY_ENV = "LEDMAPPER_UPDATE_READY_FILE"
|
|
||||||
MAX_METADATA_BYTES = 1024 * 1024
|
|
||||||
MAX_DOWNLOAD_BYTES = 200 * 1024 * 1024
|
|
||||||
CHUNK_BYTES = 1024 * 1024
|
|
||||||
VERSION_RE = re.compile(r"v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)\Z")
|
|
||||||
EXECUTABLE_RE = re.compile(r"LEDMapper-(v\d+\.\d+\.\d+)\.exe\Z", re.IGNORECASE)
|
|
||||||
|
|
||||||
|
|
||||||
class UpdateError(RuntimeError):
|
|
||||||
"""Проверка, загрузка или установка обновления не выполнена."""
|
|
||||||
|
|
||||||
|
|
||||||
class UpdateCancelled(UpdateError):
|
|
||||||
"""Загрузка отменена пользователем."""
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class UpdateInfo:
|
|
||||||
tag: str
|
|
||||||
version: str
|
|
||||||
asset_name: str
|
|
||||||
download_url: str
|
|
||||||
size: int
|
|
||||||
|
|
||||||
|
|
||||||
def parse_version(value: str) -> tuple[int, int, int]:
|
|
||||||
match = VERSION_RE.fullmatch(value.strip())
|
|
||||||
if match is None:
|
|
||||||
raise UpdateError("Версия релиза должна иметь формат vX.Y.Z")
|
|
||||||
return tuple(int(part) for part in match.groups())
|
|
||||||
|
|
||||||
|
|
||||||
def current_version() -> str:
|
|
||||||
if getattr(sys, "frozen", False):
|
|
||||||
bundle_dir = getattr(sys, "_MEIPASS", None)
|
|
||||||
if bundle_dir is not None:
|
|
||||||
try:
|
|
||||||
bundled_version = (Path(bundle_dir) / "ledmapper-build-version.txt").read_text(encoding="utf-8").strip()
|
|
||||||
if VERSION_RE.fullmatch(bundled_version):
|
|
||||||
return bundled_version
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
match = EXECUTABLE_RE.fullmatch(Path(sys.executable).name)
|
|
||||||
if match is not None:
|
|
||||||
return match.group(1)
|
|
||||||
return __version__
|
|
||||||
|
|
||||||
|
|
||||||
def _trusted_url(value: str) -> bool:
|
|
||||||
parsed = urlparse(value)
|
|
||||||
return (
|
|
||||||
parsed.scheme == "https"
|
|
||||||
and parsed.hostname == RELEASE_HOST
|
|
||||||
and parsed.port in (None, 443)
|
|
||||||
and not parsed.username
|
|
||||||
and not parsed.password
|
|
||||||
and not parsed.fragment
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def check_for_update(
|
|
||||||
installed_version: str,
|
|
||||||
*,
|
|
||||||
opener: Callable[..., BinaryIO] | None = None,
|
|
||||||
timeout: float = 10.0,
|
|
||||||
) -> UpdateInfo | None:
|
|
||||||
"""Возвращает только новый релиз с ровно одним подходящим Windows EXE."""
|
|
||||||
installed = parse_version(installed_version)
|
|
||||||
if platform.system() != "Windows":
|
|
||||||
raise UpdateError("Автообновление доступно только в Windows")
|
|
||||||
request = Request(
|
|
||||||
RELEASE_API_URL,
|
|
||||||
headers={"Accept": "application/json", "User-Agent": "LEDMapper-Updater"},
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
with (opener or urlopen)(request, timeout=timeout) as response:
|
|
||||||
if not _trusted_url(response.geturl()):
|
|
||||||
raise UpdateError("Сервер релизов перенаправил запрос на другой сайт")
|
|
||||||
payload = response.read(MAX_METADATA_BYTES + 1)
|
|
||||||
if len(payload) > MAX_METADATA_BYTES:
|
|
||||||
raise UpdateError("Ответ сервера релизов слишком велик")
|
|
||||||
release = json.loads(payload)
|
|
||||||
except UpdateError:
|
|
||||||
raise
|
|
||||||
except (OSError, ValueError, TypeError) as exc:
|
|
||||||
raise UpdateError(f"Не удалось проверить обновления: {exc}") from exc
|
|
||||||
if not isinstance(release, dict) or release.get("draft") or release.get("prerelease"):
|
|
||||||
raise UpdateError("Сервер не вернул опубликованный стабильный релиз")
|
|
||||||
tag = release.get("tag_name")
|
|
||||||
if not isinstance(tag, str) or not tag.startswith("v"):
|
|
||||||
raise UpdateError("У релиза отсутствует корректный тег")
|
|
||||||
remote = parse_version(tag)
|
|
||||||
if remote <= installed:
|
|
||||||
return None
|
|
||||||
expected_name = f"LEDMapper-{tag}.exe"
|
|
||||||
assets = release.get("assets")
|
|
||||||
if not isinstance(assets, list):
|
|
||||||
raise UpdateError("У релиза отсутствует список артефактов")
|
|
||||||
matching = [asset for asset in assets if isinstance(asset, dict) and asset.get("name") == expected_name]
|
|
||||||
if len(matching) != 1:
|
|
||||||
raise UpdateError(f"Не найден Windows-артефакт {expected_name}")
|
|
||||||
asset = matching[0]
|
|
||||||
download_url = asset.get("browser_download_url")
|
|
||||||
expected_path = f"/Robotail/LED-mapper/releases/download/{tag}/{expected_name}"
|
|
||||||
if not isinstance(download_url, str) or not _trusted_url(download_url) or urlparse(download_url).path != expected_path:
|
|
||||||
raise UpdateError("Релиз содержит неожиданный адрес артефакта")
|
|
||||||
size = asset.get("size")
|
|
||||||
if isinstance(size, bool) or not isinstance(size, int) or not 0 < size <= MAX_DOWNLOAD_BYTES:
|
|
||||||
raise UpdateError("Релиз содержит недопустимый размер артефакта")
|
|
||||||
return UpdateInfo(tag, tag.removeprefix("v"), expected_name, download_url, size)
|
|
||||||
|
|
||||||
|
|
||||||
def _check_executable(path: Path) -> None:
|
|
||||||
with path.open("rb") as source:
|
|
||||||
header = source.read(64)
|
|
||||||
if len(header) < 64 or header[:2] != b"MZ":
|
|
||||||
raise UpdateError("Скачанный файл не является Windows EXE")
|
|
||||||
pe_offset = int.from_bytes(header[0x3C:0x40], "little")
|
|
||||||
if not 64 <= pe_offset <= 1024 * 1024:
|
|
||||||
raise UpdateError("Некорректный заголовок Windows EXE")
|
|
||||||
source.seek(pe_offset)
|
|
||||||
if source.read(4) != b"PE\x00\x00":
|
|
||||||
raise UpdateError("Некорректный заголовок Windows EXE")
|
|
||||||
if source.read(2) != b"\x64\x86":
|
|
||||||
raise UpdateError("Обновление не предназначено для Windows x64")
|
|
||||||
|
|
||||||
|
|
||||||
def download_update(
|
|
||||||
info: UpdateInfo,
|
|
||||||
directory: Path,
|
|
||||||
*,
|
|
||||||
opener: Callable[..., BinaryIO] | None = None,
|
|
||||||
progress: Callable[[int], None] | None = None,
|
|
||||||
cancelled: Callable[[], bool] | None = None,
|
|
||||||
timeout: float = 30.0,
|
|
||||||
) -> Path:
|
|
||||||
"""Скачивает артефакт в отдельный временный файл и проверяет размер/PE."""
|
|
||||||
target_dir = directory.resolve()
|
|
||||||
if not target_dir.is_dir():
|
|
||||||
raise UpdateError("Каталог приложения не найден")
|
|
||||||
if not os.access(target_dir, os.W_OK):
|
|
||||||
raise UpdateError("Нет прав на запись в каталог приложения")
|
|
||||||
if not _trusted_url(info.download_url) or urlparse(info.download_url).path != (
|
|
||||||
f"/Robotail/LED-mapper/releases/download/{info.tag}/{info.asset_name}"
|
|
||||||
):
|
|
||||||
raise UpdateError("Недопустимый адрес загрузки обновления")
|
|
||||||
expected_path = f"/Robotail/LED-mapper/releases/download/{info.tag}/{info.asset_name}"
|
|
||||||
path: Path | None = None
|
|
||||||
received = 0
|
|
||||||
request = Request(info.download_url, headers={"User-Agent": "LEDMapper-Updater"})
|
|
||||||
try:
|
|
||||||
with (opener or urlopen)(request, timeout=timeout) as response:
|
|
||||||
if not _trusted_url(response.geturl()):
|
|
||||||
raise UpdateError("Загрузка перенаправлена на другой сайт")
|
|
||||||
final_path = urlparse(response.geturl()).path
|
|
||||||
if final_path == "/user/login":
|
|
||||||
raise UpdateError("Release-артефакты недоступны без авторизации")
|
|
||||||
if final_path != expected_path:
|
|
||||||
raise UpdateError("Загрузка перенаправлена на неожиданный адрес")
|
|
||||||
content_length = getattr(response, "headers", {}).get("Content-Length")
|
|
||||||
if content_length is not None:
|
|
||||||
try:
|
|
||||||
declared_size = int(content_length)
|
|
||||||
except (TypeError, ValueError) as exc:
|
|
||||||
raise UpdateError("Сервер вернул некорректный размер обновления") from exc
|
|
||||||
if declared_size != info.size:
|
|
||||||
raise UpdateError("Размер обновления не совпадает с данными релиза")
|
|
||||||
with tempfile.NamedTemporaryFile(
|
|
||||||
mode="wb", dir=target_dir, prefix=".ledmapper-update-", suffix=".download", delete=False
|
|
||||||
) as output:
|
|
||||||
path = Path(output.name)
|
|
||||||
while True:
|
|
||||||
if cancelled is not None and cancelled():
|
|
||||||
raise UpdateCancelled("Загрузка обновления отменена")
|
|
||||||
chunk = response.read(CHUNK_BYTES)
|
|
||||||
if not chunk:
|
|
||||||
break
|
|
||||||
received += len(chunk)
|
|
||||||
if received > MAX_DOWNLOAD_BYTES or received > info.size:
|
|
||||||
raise UpdateError("Артефакт превышает объявленный размер")
|
|
||||||
output.write(chunk)
|
|
||||||
if progress is not None:
|
|
||||||
progress(min(received * 100 // info.size, 100))
|
|
||||||
output.flush()
|
|
||||||
os.fsync(output.fileno())
|
|
||||||
if received != info.size:
|
|
||||||
raise UpdateError("Артефакт скачан не полностью")
|
|
||||||
_check_executable(path)
|
|
||||||
if progress is not None:
|
|
||||||
progress(100)
|
|
||||||
return path
|
|
||||||
except (UpdateError, OSError) as exc:
|
|
||||||
if path is not None:
|
|
||||||
path.unlink(missing_ok=True)
|
|
||||||
if isinstance(exc, UpdateError):
|
|
||||||
raise
|
|
||||||
raise UpdateError(f"Не удалось скачать обновление: {exc}") from exc
|
|
||||||
|
|
||||||
|
|
||||||
def current_executable() -> Path:
|
|
||||||
if not getattr(sys, "frozen", False):
|
|
||||||
raise UpdateError("Установка обновления доступна только в собранном EXE")
|
|
||||||
return Path(sys.executable).resolve()
|
|
||||||
|
|
||||||
|
|
||||||
def signal_update_ready() -> None:
|
|
||||||
marker = os.environ.pop(READY_ENV, None)
|
|
||||||
if marker is None:
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
path = Path(marker).resolve()
|
|
||||||
if path.parent != current_executable().parent or not path.name.startswith(".ledmapper-ready-"):
|
|
||||||
return
|
|
||||||
path.write_text(str(os.getpid()), encoding="ascii")
|
|
||||||
except (OSError, UpdateError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def _write_windows_updater(path: Path) -> None:
|
|
||||||
script = r'''param(
|
|
||||||
[int]$ApplicationProcessId,
|
|
||||||
[string]$Source,
|
|
||||||
[string]$OldTarget,
|
|
||||||
[string]$NewTarget,
|
|
||||||
[string]$Backup,
|
|
||||||
[string]$ReadyFile
|
|
||||||
)
|
|
||||||
$ErrorActionPreference = "Stop"
|
|
||||||
$applicationDirectory = Split-Path -Parent $OldTarget
|
|
||||||
$errorLog = Join-Path $applicationDirectory "update-error.log"
|
|
||||||
$restarted = $null
|
|
||||||
$oldMoved = $false
|
|
||||||
$newMoved = $false
|
|
||||||
try {
|
|
||||||
Wait-Process -Id $ApplicationProcessId -ErrorAction SilentlyContinue
|
|
||||||
# Родительский процесс PyInstaller может ещё удерживать EXE при очистке.
|
|
||||||
$moveDeadline = (Get-Date).AddSeconds(30)
|
|
||||||
while (-not $oldMoved) {
|
|
||||||
try {
|
|
||||||
Move-Item -LiteralPath $OldTarget -Destination $Backup -ErrorAction Stop
|
|
||||||
$oldMoved = $true
|
|
||||||
} catch {
|
|
||||||
if ((Get-Date) -ge $moveDeadline) { throw }
|
|
||||||
Start-Sleep -Milliseconds 250
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (Test-Path -LiteralPath $NewTarget) { throw "Целевой EXE уже существует" }
|
|
||||||
Move-Item -LiteralPath $Source -Destination $NewTarget -ErrorAction Stop
|
|
||||||
$newMoved = $true
|
|
||||||
$env:LEDMAPPER_UPDATE_READY_FILE = $ReadyFile
|
|
||||||
$env:PYINSTALLER_RESET_ENVIRONMENT = "1"
|
|
||||||
$restarted = Start-Process -FilePath $NewTarget -WorkingDirectory $applicationDirectory -PassThru
|
|
||||||
$deadline = (Get-Date).AddSeconds(60)
|
|
||||||
while (-not (Test-Path -LiteralPath $ReadyFile -PathType Leaf)) {
|
|
||||||
if ($restarted.HasExited) { throw "Новая версия завершилась до открытия окна" }
|
|
||||||
if ((Get-Date) -ge $deadline) { throw "Новая версия не подтвердила запуск" }
|
|
||||||
Start-Sleep -Milliseconds 250
|
|
||||||
}
|
|
||||||
if ($restarted.HasExited) { throw "Новая версия завершилась сразу после запуска" }
|
|
||||||
Remove-Item -LiteralPath $ReadyFile -Force -ErrorAction SilentlyContinue
|
|
||||||
Remove-Item -LiteralPath $Backup -Force -ErrorAction SilentlyContinue
|
|
||||||
Remove-Item -LiteralPath $MyInvocation.MyCommand.Path -Force -ErrorAction SilentlyContinue
|
|
||||||
} catch {
|
|
||||||
$failure = $_.ToString()
|
|
||||||
if ($restarted -and -not $restarted.HasExited) {
|
|
||||||
& taskkill.exe /PID $restarted.Id /T /F *> $null
|
|
||||||
}
|
|
||||||
if ($newMoved -and (Test-Path -LiteralPath $NewTarget)) {
|
|
||||||
Remove-Item -LiteralPath $NewTarget -Force -ErrorAction SilentlyContinue
|
|
||||||
}
|
|
||||||
if ($oldMoved -and (Test-Path -LiteralPath $Backup)) {
|
|
||||||
Move-Item -LiteralPath $Backup -Destination $OldTarget -Force -ErrorAction SilentlyContinue
|
|
||||||
}
|
|
||||||
Remove-Item -LiteralPath $ReadyFile -Force -ErrorAction SilentlyContinue
|
|
||||||
$failure | Out-File -LiteralPath $errorLog -Encoding utf8
|
|
||||||
Remove-Item -LiteralPath $MyInvocation.MyCommand.Path -Force -ErrorAction SilentlyContinue
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
'''
|
|
||||||
path.write_text(script, encoding="utf-8-sig", newline="\r\n")
|
|
||||||
|
|
||||||
|
|
||||||
def launch_update(downloaded: Path, info: UpdateInfo, *, process_id: int | None = None) -> None:
|
|
||||||
"""Запускает отдельный helper; замену EXE он делает после выхода приложения."""
|
|
||||||
old_target = current_executable()
|
|
||||||
source = downloaded.resolve()
|
|
||||||
if platform.system() != "Windows":
|
|
||||||
raise UpdateError("Установка обновления доступна только в Windows")
|
|
||||||
if not os.access(old_target.parent, os.W_OK):
|
|
||||||
raise UpdateError("Нет прав на замену приложения")
|
|
||||||
if source.parent != old_target.parent or not source.is_file() or not source.name.startswith(".ledmapper-update-"):
|
|
||||||
raise UpdateError("Скачанный файл должен находиться рядом с приложением")
|
|
||||||
if not EXECUTABLE_RE.fullmatch(info.asset_name):
|
|
||||||
raise UpdateError("Недопустимое имя Windows-артефакта")
|
|
||||||
new_target = old_target
|
|
||||||
if source.stat().st_size != info.size:
|
|
||||||
raise UpdateError("Размер скачанного артефакта изменился")
|
|
||||||
_check_executable(source)
|
|
||||||
token = uuid.uuid4().hex
|
|
||||||
script_path = old_target.parent / f".ledmapper-updater-{token}.ps1"
|
|
||||||
backup_path = old_target.parent / f".ledmapper-backup-{token}.exe"
|
|
||||||
ready_path = old_target.parent / f".ledmapper-ready-{token}"
|
|
||||||
try:
|
|
||||||
_write_windows_updater(script_path)
|
|
||||||
creation_flags = (
|
|
||||||
getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
|
|
||||||
| getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
|
||||||
)
|
|
||||||
subprocess.Popen(
|
|
||||||
[
|
|
||||||
"powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File",
|
|
||||||
str(script_path), str(process_id or os.getpid()), str(source), str(old_target),
|
|
||||||
str(new_target), str(backup_path), str(ready_path),
|
|
||||||
],
|
|
||||||
close_fds=True,
|
|
||||||
creationflags=creation_flags,
|
|
||||||
)
|
|
||||||
except (OSError, UpdateError) as exc:
|
|
||||||
script_path.unlink(missing_ok=True)
|
|
||||||
if isinstance(exc, UpdateError):
|
|
||||||
raise
|
|
||||||
raise UpdateError(f"Не удалось запустить установщик: {exc}") from exc
|
|
||||||
@ -1,3 +0,0 @@
|
|||||||
"""Текущая версия приложения; обновляется при публикации релиза."""
|
|
||||||
|
|
||||||
__version__ = "3.5.0"
|
|
||||||
Loading…
x
Reference in New Issue
Block a user